ent/doc: add edge example for o2o 2 types

Reviewed By: alexsn

Differential Revision: D17045287

fbshipit-source-id: e62bce8c1935b844aa26712bb9dc574b525a275c
This commit is contained in:
Ariel Mashraki
2019-08-25 02:42:12 -07:00
committed by Facebook Github Bot
parent aaafde973b
commit 01c59f104c
29 changed files with 4060 additions and 7 deletions

View File

@@ -0,0 +1,10 @@
# User-Card O2O Relation Example
An example for a O2O relation between a User and Card.
In the example, a User can have only one card, and a card must have exactly one owner (required edge).
### Generate Assets
```console
go generate ./...
```

View File

@@ -0,0 +1,98 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"bytes"
"fmt"
"time"
"github.com/facebookincubator/ent/dialect/sql"
)
// Card is the model entity for the Card schema.
type Card struct {
config
// ID of the ent.
ID int `json:"id,omitempty"`
// Expired holds the value of the "expired" field.
Expired time.Time `json:"expired,omitempty"`
// Number holds the value of the "number" field.
Number string `json:"number,omitempty"`
}
// FromRows scans the sql response data into Card.
func (c *Card) FromRows(rows *sql.Rows) error {
var vc struct {
ID int
Expired sql.NullTime
Number sql.NullString
}
// the order here should be the same as in the `card.Columns`.
if err := rows.Scan(
&vc.ID,
&vc.Expired,
&vc.Number,
); err != nil {
return err
}
c.ID = vc.ID
c.Expired = vc.Expired.Time
c.Number = vc.Number.String
return nil
}
// QueryOwner queries the owner edge of the Card.
func (c *Card) QueryOwner() *UserQuery {
return (&CardClient{c.config}).QueryOwner(c)
}
// Update returns a builder for updating this Card.
// Note that, you need to call Card.Unwrap() before calling this method, if this Card
// was returned from a transaction, and the transaction was committed or rolled back.
func (c *Card) Update() *CardUpdateOne {
return (&CardClient{c.config}).UpdateOne(c)
}
// Unwrap unwraps the entity that was returned from a transaction after it was closed,
// so that all next queries will be executed through the driver which created the transaction.
func (c *Card) Unwrap() *Card {
tx, ok := c.config.driver.(*txDriver)
if !ok {
panic("ent: Card is not a transactional entity")
}
c.config.driver = tx.drv
return c
}
// String implements the fmt.Stringer.
func (c *Card) String() string {
buf := bytes.NewBuffer(nil)
buf.WriteString("Card(")
buf.WriteString(fmt.Sprintf("id=%v", c.ID))
buf.WriteString(fmt.Sprintf(", expired=%v", c.Expired))
buf.WriteString(fmt.Sprintf(", number=%v", c.Number))
buf.WriteString(")")
return buf.String()
}
// Cards is a parsable slice of Card.
type Cards []*Card
// FromRows scans the sql response data into Cards.
func (c *Cards) FromRows(rows *sql.Rows) error {
for rows.Next() {
vc := &Card{}
if err := vc.FromRows(rows); err != nil {
return err
}
*c = append(*c, vc)
}
return nil
}
func (c Cards) config(cfg config) {
for i := range c {
c[i].config = cfg
}
}

View File

@@ -0,0 +1,31 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package card
const (
// Label holds the string label denoting the card type in the database.
Label = "card"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldExpired holds the string denoting the expired vertex property in the database.
FieldExpired = "expired"
// FieldNumber holds the string denoting the number vertex property in the database.
FieldNumber = "number"
// Table holds the table name of the card in the database.
Table = "cards"
// OwnerTable is the table the holds the owner relation/edge.
OwnerTable = "cards"
// OwnerInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
OwnerInverseTable = "users"
// OwnerColumn is the table column denoting the owner relation/edge.
OwnerColumn = "owner_id"
)
// Columns holds all SQL columns are card fields.
var Columns = []string{
FieldID,
FieldExpired,
FieldNumber,
}

View File

@@ -0,0 +1,408 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package card
import (
"time"
"github.com/facebookincubator/ent/examples/o2o2types/ent/predicate"
"github.com/facebookincubator/ent/dialect/sql"
)
// ID filters vertices based on their identifier.
func ID(id int) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
},
)
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
},
)
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldID), id))
},
)
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldID), id))
},
)
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldID), id))
},
)
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldID), id))
},
)
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldID), id))
},
)
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.In(s.C(FieldID), v...))
},
)
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.NotIn(s.C(FieldID), v...))
},
)
}
// Expired applies equality check predicate on the "expired" field. It's identical to ExpiredEQ.
func Expired(v time.Time) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldExpired), v))
},
)
}
// Number applies equality check predicate on the "number" field. It's identical to NumberEQ.
func Number(v string) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldNumber), v))
},
)
}
// ExpiredEQ applies the EQ predicate on the "expired" field.
func ExpiredEQ(v time.Time) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldExpired), v))
},
)
}
// ExpiredNEQ applies the NEQ predicate on the "expired" field.
func ExpiredNEQ(v time.Time) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldExpired), v))
},
)
}
// ExpiredGT applies the GT predicate on the "expired" field.
func ExpiredGT(v time.Time) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldExpired), v))
},
)
}
// ExpiredGTE applies the GTE predicate on the "expired" field.
func ExpiredGTE(v time.Time) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldExpired), v))
},
)
}
// ExpiredLT applies the LT predicate on the "expired" field.
func ExpiredLT(v time.Time) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldExpired), v))
},
)
}
// ExpiredLTE applies the LTE predicate on the "expired" field.
func ExpiredLTE(v time.Time) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldExpired), v))
},
)
}
// ExpiredIn applies the In predicate on the "expired" field.
func ExpiredIn(vs ...time.Time) predicate.Card {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Card(
func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(vs) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldExpired), v...))
},
)
}
// ExpiredNotIn applies the NotIn predicate on the "expired" field.
func ExpiredNotIn(vs ...time.Time) predicate.Card {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Card(
func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(vs) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldExpired), v...))
},
)
}
// NumberEQ applies the EQ predicate on the "number" field.
func NumberEQ(v string) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldNumber), v))
},
)
}
// NumberNEQ applies the NEQ predicate on the "number" field.
func NumberNEQ(v string) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldNumber), v))
},
)
}
// NumberGT applies the GT predicate on the "number" field.
func NumberGT(v string) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldNumber), v))
},
)
}
// NumberGTE applies the GTE predicate on the "number" field.
func NumberGTE(v string) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldNumber), v))
},
)
}
// NumberLT applies the LT predicate on the "number" field.
func NumberLT(v string) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldNumber), v))
},
)
}
// NumberLTE applies the LTE predicate on the "number" field.
func NumberLTE(v string) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldNumber), v))
},
)
}
// NumberIn applies the In predicate on the "number" field.
func NumberIn(vs ...string) predicate.Card {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Card(
func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(vs) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldNumber), v...))
},
)
}
// NumberNotIn applies the NotIn predicate on the "number" field.
func NumberNotIn(vs ...string) predicate.Card {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Card(
func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(vs) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldNumber), v...))
},
)
}
// NumberContains applies the Contains predicate on the "number" field.
func NumberContains(v string) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldNumber), v))
},
)
}
// NumberHasPrefix applies the HasPrefix predicate on the "number" field.
func NumberHasPrefix(v string) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldNumber), v))
},
)
}
// NumberHasSuffix applies the HasSuffix predicate on the "number" field.
func NumberHasSuffix(v string) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldNumber), v))
},
)
}
// NumberContainsFold applies the ContainsFold predicate on the "number" field.
func NumberContainsFold(v string) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldNumber), v))
},
)
}
// HasOwner applies the HasEdge predicate on the "owner" edge.
func HasOwner() predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
t1 := s.Table()
s.Where(sql.NotNull(t1.C(OwnerColumn)))
},
)
}
// HasOwnerWith applies the HasEdge predicate on the "owner" edge with a given conditions (other predicates).
func HasOwnerWith(preds ...predicate.User) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
t1 := s.Table()
t2 := sql.Select(FieldID).From(sql.Table(OwnerInverseTable))
for _, p := range preds {
p(t2)
}
s.Where(sql.In(t1.C(OwnerColumn), t2))
},
)
}
// And groups list of predicates with the AND operator between them.
func And(predicates ...predicate.Card) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
for _, p := range predicates {
p(s)
}
},
)
}
// Or groups list of predicates with the OR operator between them.
func Or(predicates ...predicate.Card) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
for i, p := range predicates {
if i > 0 {
s.Or()
}
p(s)
}
},
)
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Card) predicate.Card {
return predicate.Card(
func(s *sql.Selector) {
p(s.Not())
},
)
}

View File

@@ -0,0 +1,124 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"github.com/facebookincubator/ent/examples/o2o2types/ent/card"
"github.com/facebookincubator/ent/dialect/sql"
)
// CardCreate is the builder for creating a Card entity.
type CardCreate struct {
config
expired *time.Time
number *string
owner map[int]struct{}
}
// SetExpired sets the expired field.
func (cc *CardCreate) SetExpired(t time.Time) *CardCreate {
cc.expired = &t
return cc
}
// SetNumber sets the number field.
func (cc *CardCreate) SetNumber(s string) *CardCreate {
cc.number = &s
return cc
}
// SetOwnerID sets the owner edge to User by id.
func (cc *CardCreate) SetOwnerID(id int) *CardCreate {
if cc.owner == nil {
cc.owner = make(map[int]struct{})
}
cc.owner[id] = struct{}{}
return cc
}
// SetOwner sets the owner edge to User.
func (cc *CardCreate) SetOwner(u *User) *CardCreate {
return cc.SetOwnerID(u.ID)
}
// Save creates the Card in the database.
func (cc *CardCreate) Save(ctx context.Context) (*Card, error) {
if cc.expired == nil {
return nil, errors.New("ent: missing required field \"expired\"")
}
if cc.number == nil {
return nil, errors.New("ent: missing required field \"number\"")
}
if len(cc.owner) > 1 {
return nil, errors.New("ent: multiple assignments on a unique edge \"owner\"")
}
if cc.owner == nil {
return nil, errors.New("ent: missing required edge \"owner\"")
}
return cc.sqlSave(ctx)
}
// SaveX calls Save and panics if Save returns an error.
func (cc *CardCreate) SaveX(ctx context.Context) *Card {
v, err := cc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
func (cc *CardCreate) sqlSave(ctx context.Context) (*Card, error) {
var (
res sql.Result
c = &Card{config: cc.config}
)
tx, err := cc.driver.Tx(ctx)
if err != nil {
return nil, err
}
builder := sql.Insert(card.Table).Default(cc.driver.Dialect())
if cc.expired != nil {
builder.Set(card.FieldExpired, *cc.expired)
c.Expired = *cc.expired
}
if cc.number != nil {
builder.Set(card.FieldNumber, *cc.number)
c.Number = *cc.number
}
query, args := builder.Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return nil, rollback(tx, err)
}
id, err := res.LastInsertId()
if err != nil {
return nil, rollback(tx, err)
}
c.ID = int(id)
if len(cc.owner) > 0 {
eid := keys(cc.owner)[0]
query, args := sql.Update(card.OwnerTable).
Set(card.OwnerColumn, eid).
Where(sql.EQ(card.FieldID, id).And().IsNull(card.OwnerColumn)).
Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return nil, rollback(tx, err)
}
affected, err := res.RowsAffected()
if err != nil {
return nil, rollback(tx, err)
}
if int(affected) < len(cc.owner) {
return nil, rollback(tx, &ErrConstraintFailed{msg: fmt.Sprintf("one of \"owner\" %v already connected to a different \"Card\"", keys(cc.owner))})
}
}
if err := tx.Commit(); err != nil {
return nil, err
}
return c, nil
}

View File

@@ -0,0 +1,61 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"github.com/facebookincubator/ent/examples/o2o2types/ent/card"
"github.com/facebookincubator/ent/examples/o2o2types/ent/predicate"
"github.com/facebookincubator/ent/dialect/sql"
)
// CardDelete is the builder for deleting a Card entity.
type CardDelete struct {
config
predicates []predicate.Card
}
// Where adds a new predicate for the builder.
func (cd *CardDelete) Where(ps ...predicate.Card) *CardDelete {
cd.predicates = append(cd.predicates, ps...)
return cd
}
// Exec executes the deletion query.
func (cd *CardDelete) Exec(ctx context.Context) error {
return cd.sqlExec(ctx)
}
// ExecX is like Exec, but panics if an error occurs.
func (cd *CardDelete) ExecX(ctx context.Context) {
if err := cd.Exec(ctx); err != nil {
panic(err)
}
}
func (cd *CardDelete) sqlExec(ctx context.Context) error {
var res sql.Result
selector := sql.Select().From(sql.Table(card.Table))
for _, p := range cd.predicates {
p(selector)
}
query, args := sql.Delete(card.Table).FromSelect(selector).Query()
return cd.driver.Exec(ctx, query, args, &res)
}
// CardDeleteOne is the builder for deleting a single Card entity.
type CardDeleteOne struct {
cd *CardDelete
}
// Exec executes the deletion query.
func (cdo *CardDeleteOne) Exec(ctx context.Context) error {
return cdo.cd.Exec(ctx)
}
// ExecX is like Exec, but panics if an error occurs.
func (cdo *CardDeleteOne) ExecX(ctx context.Context) {
cdo.cd.ExecX(ctx)
}

View File

@@ -0,0 +1,483 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"math"
"github.com/facebookincubator/ent/examples/o2o2types/ent/card"
"github.com/facebookincubator/ent/examples/o2o2types/ent/predicate"
"github.com/facebookincubator/ent/examples/o2o2types/ent/user"
"github.com/facebookincubator/ent/dialect/sql"
)
// CardQuery is the builder for querying Card entities.
type CardQuery struct {
config
limit *int
offset *int
order []Order
unique []string
predicates []predicate.Card
// intermediate queries.
sql *sql.Selector
}
// Where adds a new predicate for the builder.
func (cq *CardQuery) Where(ps ...predicate.Card) *CardQuery {
cq.predicates = append(cq.predicates, ps...)
return cq
}
// Limit adds a limit step to the query.
func (cq *CardQuery) Limit(limit int) *CardQuery {
cq.limit = &limit
return cq
}
// Offset adds an offset step to the query.
func (cq *CardQuery) Offset(offset int) *CardQuery {
cq.offset = &offset
return cq
}
// Order adds an order step to the query.
func (cq *CardQuery) Order(o ...Order) *CardQuery {
cq.order = append(cq.order, o...)
return cq
}
// QueryOwner chains the current query on the owner edge.
func (cq *CardQuery) QueryOwner() *UserQuery {
query := &UserQuery{config: cq.config}
t1 := sql.Table(user.Table)
t2 := cq.sqlQuery()
t2.Select(t2.C(card.OwnerColumn))
query.sql = sql.Select(t1.Columns(user.Columns...)...).
From(t1).
Join(t2).
On(t1.C(user.FieldID), t2.C(card.OwnerColumn))
return query
}
// Get returns a Card entity by its id.
func (cq *CardQuery) Get(ctx context.Context, id int) (*Card, error) {
return cq.Where(card.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (cq *CardQuery) GetX(ctx context.Context, id int) *Card {
c, err := cq.Get(ctx, id)
if err != nil {
panic(err)
}
return c
}
// First returns the first Card entity in the query. Returns *ErrNotFound when no card was found.
func (cq *CardQuery) First(ctx context.Context) (*Card, error) {
cs, err := cq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(cs) == 0 {
return nil, &ErrNotFound{card.Label}
}
return cs[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (cq *CardQuery) FirstX(ctx context.Context) *Card {
c, err := cq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return c
}
// FirstID returns the first Card id in the query. Returns *ErrNotFound when no id was found.
func (cq *CardQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = cq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &ErrNotFound{card.Label}
return
}
return ids[0], nil
}
// FirstXID is like FirstID, but panics if an error occurs.
func (cq *CardQuery) FirstXID(ctx context.Context) int {
id, err := cq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns the only Card entity in the query, returns an error if not exactly one entity was returned.
func (cq *CardQuery) Only(ctx context.Context) (*Card, error) {
cs, err := cq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(cs) {
case 1:
return cs[0], nil
case 0:
return nil, &ErrNotFound{card.Label}
default:
return nil, &ErrNotSingular{card.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (cq *CardQuery) OnlyX(ctx context.Context) *Card {
c, err := cq.Only(ctx)
if err != nil {
panic(err)
}
return c
}
// OnlyID returns the only Card id in the query, returns an error if not exactly one id was returned.
func (cq *CardQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = cq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &ErrNotFound{card.Label}
default:
err = &ErrNotSingular{card.Label}
}
return
}
// OnlyXID is like OnlyID, but panics if an error occurs.
func (cq *CardQuery) OnlyXID(ctx context.Context) int {
id, err := cq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Cards.
func (cq *CardQuery) All(ctx context.Context) ([]*Card, error) {
return cq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (cq *CardQuery) AllX(ctx context.Context) []*Card {
cs, err := cq.All(ctx)
if err != nil {
panic(err)
}
return cs
}
// IDs executes the query and returns a list of Card ids.
func (cq *CardQuery) IDs(ctx context.Context) ([]int, error) {
return cq.sqlIDs(ctx)
}
// IDsX is like IDs, but panics if an error occurs.
func (cq *CardQuery) IDsX(ctx context.Context) []int {
ids, err := cq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (cq *CardQuery) Count(ctx context.Context) (int, error) {
return cq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (cq *CardQuery) CountX(ctx context.Context) int {
count, err := cq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (cq *CardQuery) Exist(ctx context.Context) (bool, error) {
return cq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (cq *CardQuery) ExistX(ctx context.Context) bool {
exist, err := cq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the query builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (cq *CardQuery) Clone() *CardQuery {
return &CardQuery{
config: cq.config,
limit: cq.limit,
offset: cq.offset,
order: append([]Order{}, cq.order...),
unique: append([]string{}, cq.unique...),
predicates: append([]predicate.Card{}, cq.predicates...),
// clone intermediate queries.
sql: cq.sql.Clone(),
}
}
// GroupBy used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// Expired time.Time `json:"expired,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Card.Query().
// GroupBy(card.FieldExpired).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
//
func (cq *CardQuery) GroupBy(field string, fields ...string) *CardGroupBy {
group := &CardGroupBy{config: cq.config}
group.fields = append([]string{field}, fields...)
group.sql = cq.sqlQuery()
return group
}
func (cq *CardQuery) sqlAll(ctx context.Context) ([]*Card, error) {
rows := &sql.Rows{}
selector := cq.sqlQuery()
if unique := cq.unique; len(unique) == 0 {
selector.Distinct()
}
query, args := selector.Query()
if err := cq.driver.Query(ctx, query, args, rows); err != nil {
return nil, err
}
defer rows.Close()
var cs Cards
if err := cs.FromRows(rows); err != nil {
return nil, err
}
cs.config(cq.config)
return cs, nil
}
func (cq *CardQuery) sqlCount(ctx context.Context) (int, error) {
rows := &sql.Rows{}
selector := cq.sqlQuery()
unique := []string{card.FieldID}
if len(cq.unique) > 0 {
unique = cq.unique
}
selector.Count(sql.Distinct(selector.Columns(unique...)...))
query, args := selector.Query()
if err := cq.driver.Query(ctx, query, args, rows); err != nil {
return 0, err
}
defer rows.Close()
if !rows.Next() {
return 0, errors.New("ent: no rows found")
}
var n int
if err := rows.Scan(&n); err != nil {
return 0, fmt.Errorf("ent: failed reading count: %v", err)
}
return n, nil
}
func (cq *CardQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := cq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("ent: check existence: %v", err)
}
return n > 0, nil
}
func (cq *CardQuery) sqlIDs(ctx context.Context) ([]int, error) {
vs, err := cq.sqlAll(ctx)
if err != nil {
return nil, err
}
var ids []int
for _, v := range vs {
ids = append(ids, v.ID)
}
return ids, nil
}
func (cq *CardQuery) sqlQuery() *sql.Selector {
t1 := sql.Table(card.Table)
selector := sql.Select(t1.Columns(card.Columns...)...).From(t1)
if cq.sql != nil {
selector = cq.sql
selector.Select(selector.Columns(card.Columns...)...)
}
for _, p := range cq.predicates {
p(selector)
}
for _, p := range cq.order {
p(selector)
}
if offset := cq.offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt64)
}
if limit := cq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// CardQuery is the builder for group-by Card entities.
type CardGroupBy struct {
config
fields []string
fns []Aggregate
// intermediate queries.
sql *sql.Selector
}
// Aggregate adds the given aggregation functions to the group-by query.
func (cgb *CardGroupBy) Aggregate(fns ...Aggregate) *CardGroupBy {
cgb.fns = append(cgb.fns, fns...)
return cgb
}
// Scan applies the group-by query and scan the result into the given value.
func (cgb *CardGroupBy) Scan(ctx context.Context, v interface{}) error {
return cgb.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (cgb *CardGroupBy) ScanX(ctx context.Context, v interface{}) {
if err := cgb.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from group-by. It is only allowed when querying group-by with one field.
func (cgb *CardGroupBy) Strings(ctx context.Context) ([]string, error) {
if len(cgb.fields) > 1 {
return nil, errors.New("ent: CardGroupBy.Strings is not achievable when grouping more than 1 field")
}
var v []string
if err := cgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (cgb *CardGroupBy) StringsX(ctx context.Context) []string {
v, err := cgb.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from group-by. It is only allowed when querying group-by with one field.
func (cgb *CardGroupBy) Ints(ctx context.Context) ([]int, error) {
if len(cgb.fields) > 1 {
return nil, errors.New("ent: CardGroupBy.Ints is not achievable when grouping more than 1 field")
}
var v []int
if err := cgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (cgb *CardGroupBy) IntsX(ctx context.Context) []int {
v, err := cgb.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from group-by. It is only allowed when querying group-by with one field.
func (cgb *CardGroupBy) Float64s(ctx context.Context) ([]float64, error) {
if len(cgb.fields) > 1 {
return nil, errors.New("ent: CardGroupBy.Float64s is not achievable when grouping more than 1 field")
}
var v []float64
if err := cgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (cgb *CardGroupBy) Float64sX(ctx context.Context) []float64 {
v, err := cgb.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from group-by. It is only allowed when querying group-by with one field.
func (cgb *CardGroupBy) Bools(ctx context.Context) ([]bool, error) {
if len(cgb.fields) > 1 {
return nil, errors.New("ent: CardGroupBy.Bools is not achievable when grouping more than 1 field")
}
var v []bool
if err := cgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (cgb *CardGroupBy) BoolsX(ctx context.Context) []bool {
v, err := cgb.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
func (cgb *CardGroupBy) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{}
query, args := cgb.sqlQuery().Query()
if err := cgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (cgb *CardGroupBy) sqlQuery() *sql.Selector {
selector := cgb.sql
columns := make([]string, 0, len(cgb.fields)+len(cgb.fns))
columns = append(columns, cgb.fields...)
for _, fn := range cgb.fns {
columns = append(columns, fn.SQL(selector))
}
return selector.Select(columns...).GroupBy(cgb.fields...)
}

View File

@@ -0,0 +1,337 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"github.com/facebookincubator/ent/examples/o2o2types/ent/card"
"github.com/facebookincubator/ent/examples/o2o2types/ent/predicate"
"github.com/facebookincubator/ent/examples/o2o2types/ent/user"
"github.com/facebookincubator/ent/dialect/sql"
)
// CardUpdate is the builder for updating Card entities.
type CardUpdate struct {
config
expired *time.Time
number *string
owner map[int]struct{}
clearedOwner bool
predicates []predicate.Card
}
// Where adds a new predicate for the builder.
func (cu *CardUpdate) Where(ps ...predicate.Card) *CardUpdate {
cu.predicates = append(cu.predicates, ps...)
return cu
}
// SetExpired sets the expired field.
func (cu *CardUpdate) SetExpired(t time.Time) *CardUpdate {
cu.expired = &t
return cu
}
// SetNumber sets the number field.
func (cu *CardUpdate) SetNumber(s string) *CardUpdate {
cu.number = &s
return cu
}
// SetOwnerID sets the owner edge to User by id.
func (cu *CardUpdate) SetOwnerID(id int) *CardUpdate {
if cu.owner == nil {
cu.owner = make(map[int]struct{})
}
cu.owner[id] = struct{}{}
return cu
}
// SetOwner sets the owner edge to User.
func (cu *CardUpdate) SetOwner(u *User) *CardUpdate {
return cu.SetOwnerID(u.ID)
}
// ClearOwner clears the owner edge to User.
func (cu *CardUpdate) ClearOwner() *CardUpdate {
cu.clearedOwner = true
return cu
}
// Save executes the query and returns the number of rows/vertices matched by this operation.
func (cu *CardUpdate) Save(ctx context.Context) (int, error) {
if len(cu.owner) > 1 {
return 0, errors.New("ent: multiple assignments on a unique edge \"owner\"")
}
if cu.clearedOwner && cu.owner == nil {
return 0, errors.New("ent: clearing a unique edge \"owner\"")
}
return cu.sqlSave(ctx)
}
// SaveX is like Save, but panics if an error occurs.
func (cu *CardUpdate) SaveX(ctx context.Context) int {
affected, err := cu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (cu *CardUpdate) Exec(ctx context.Context) error {
_, err := cu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (cu *CardUpdate) ExecX(ctx context.Context) {
if err := cu.Exec(ctx); err != nil {
panic(err)
}
}
func (cu *CardUpdate) sqlSave(ctx context.Context) (n int, err error) {
selector := sql.Select(card.FieldID).From(sql.Table(card.Table))
for _, p := range cu.predicates {
p(selector)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err = cu.driver.Query(ctx, query, args, rows); err != nil {
return 0, err
}
defer rows.Close()
var ids []int
for rows.Next() {
var id int
if err := rows.Scan(&id); err != nil {
return 0, fmt.Errorf("ent: failed reading id: %v", err)
}
ids = append(ids, id)
}
if len(ids) == 0 {
return 0, nil
}
tx, err := cu.driver.Tx(ctx)
if err != nil {
return 0, err
}
var (
update bool
res sql.Result
builder = sql.Update(card.Table).Where(sql.InInts(card.FieldID, ids...))
)
if cu.expired != nil {
update = true
builder.Set(card.FieldExpired, *cu.expired)
}
if cu.number != nil {
update = true
builder.Set(card.FieldNumber, *cu.number)
}
if update {
query, args := builder.Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return 0, rollback(tx, err)
}
}
if cu.clearedOwner {
query, args := sql.Update(card.OwnerTable).
SetNull(card.OwnerColumn).
Where(sql.InInts(user.FieldID, ids...)).
Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return 0, rollback(tx, err)
}
}
if len(cu.owner) > 0 {
for _, id := range ids {
eid := keys(cu.owner)[0]
query, args := sql.Update(card.OwnerTable).
Set(card.OwnerColumn, eid).
Where(sql.EQ(card.FieldID, id).And().IsNull(card.OwnerColumn)).
Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return 0, rollback(tx, err)
}
affected, err := res.RowsAffected()
if err != nil {
return 0, rollback(tx, err)
}
if int(affected) < len(cu.owner) {
return 0, rollback(tx, &ErrConstraintFailed{msg: fmt.Sprintf("one of \"owner\" %v already connected to a different \"Card\"", keys(cu.owner))})
}
}
}
if err = tx.Commit(); err != nil {
return 0, err
}
return len(ids), nil
}
// CardUpdateOne is the builder for updating a single Card entity.
type CardUpdateOne struct {
config
id int
expired *time.Time
number *string
owner map[int]struct{}
clearedOwner bool
}
// SetExpired sets the expired field.
func (cuo *CardUpdateOne) SetExpired(t time.Time) *CardUpdateOne {
cuo.expired = &t
return cuo
}
// SetNumber sets the number field.
func (cuo *CardUpdateOne) SetNumber(s string) *CardUpdateOne {
cuo.number = &s
return cuo
}
// SetOwnerID sets the owner edge to User by id.
func (cuo *CardUpdateOne) SetOwnerID(id int) *CardUpdateOne {
if cuo.owner == nil {
cuo.owner = make(map[int]struct{})
}
cuo.owner[id] = struct{}{}
return cuo
}
// SetOwner sets the owner edge to User.
func (cuo *CardUpdateOne) SetOwner(u *User) *CardUpdateOne {
return cuo.SetOwnerID(u.ID)
}
// ClearOwner clears the owner edge to User.
func (cuo *CardUpdateOne) ClearOwner() *CardUpdateOne {
cuo.clearedOwner = true
return cuo
}
// Save executes the query and returns the updated entity.
func (cuo *CardUpdateOne) Save(ctx context.Context) (*Card, error) {
if len(cuo.owner) > 1 {
return nil, errors.New("ent: multiple assignments on a unique edge \"owner\"")
}
if cuo.clearedOwner && cuo.owner == nil {
return nil, errors.New("ent: clearing a unique edge \"owner\"")
}
return cuo.sqlSave(ctx)
}
// SaveX is like Save, but panics if an error occurs.
func (cuo *CardUpdateOne) SaveX(ctx context.Context) *Card {
c, err := cuo.Save(ctx)
if err != nil {
panic(err)
}
return c
}
// Exec executes the query on the entity.
func (cuo *CardUpdateOne) Exec(ctx context.Context) error {
_, err := cuo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (cuo *CardUpdateOne) ExecX(ctx context.Context) {
if err := cuo.Exec(ctx); err != nil {
panic(err)
}
}
func (cuo *CardUpdateOne) sqlSave(ctx context.Context) (c *Card, err error) {
selector := sql.Select(card.Columns...).From(sql.Table(card.Table))
card.ID(cuo.id)(selector)
rows := &sql.Rows{}
query, args := selector.Query()
if err = cuo.driver.Query(ctx, query, args, rows); err != nil {
return nil, err
}
defer rows.Close()
var ids []int
for rows.Next() {
var id int
c = &Card{config: cuo.config}
if err := c.FromRows(rows); err != nil {
return nil, fmt.Errorf("ent: failed scanning row into Card: %v", err)
}
id = c.ID
ids = append(ids, id)
}
switch n := len(ids); {
case n == 0:
return nil, fmt.Errorf("ent: Card not found with id: %v", cuo.id)
case n > 1:
return nil, fmt.Errorf("ent: more than one Card with the same id: %v", cuo.id)
}
tx, err := cuo.driver.Tx(ctx)
if err != nil {
return nil, err
}
var (
update bool
res sql.Result
builder = sql.Update(card.Table).Where(sql.InInts(card.FieldID, ids...))
)
if cuo.expired != nil {
update = true
builder.Set(card.FieldExpired, *cuo.expired)
c.Expired = *cuo.expired
}
if cuo.number != nil {
update = true
builder.Set(card.FieldNumber, *cuo.number)
c.Number = *cuo.number
}
if update {
query, args := builder.Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return nil, rollback(tx, err)
}
}
if cuo.clearedOwner {
query, args := sql.Update(card.OwnerTable).
SetNull(card.OwnerColumn).
Where(sql.InInts(user.FieldID, ids...)).
Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return nil, rollback(tx, err)
}
}
if len(cuo.owner) > 0 {
for _, id := range ids {
eid := keys(cuo.owner)[0]
query, args := sql.Update(card.OwnerTable).
Set(card.OwnerColumn, eid).
Where(sql.EQ(card.FieldID, id).And().IsNull(card.OwnerColumn)).
Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return nil, rollback(tx, err)
}
affected, err := res.RowsAffected()
if err != nil {
return nil, rollback(tx, err)
}
if int(affected) < len(cuo.owner) {
return nil, rollback(tx, &ErrConstraintFailed{msg: fmt.Sprintf("one of \"owner\" %v already connected to a different \"Card\"", keys(cuo.owner))})
}
}
}
if err = tx.Commit(); err != nil {
return nil, err
}
return c, nil
}

View File

@@ -0,0 +1,179 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"log"
"github.com/facebookincubator/ent/examples/o2o2types/ent/migrate"
"github.com/facebookincubator/ent/examples/o2o2types/ent/card"
"github.com/facebookincubator/ent/examples/o2o2types/ent/user"
"github.com/facebookincubator/ent/dialect/sql"
)
// Client is the client that holds all ent builders.
type Client struct {
config
// Schema is the client for creating, migrating and dropping schema.
Schema *migrate.Schema
// Card is the client for interacting with the Card builders.
Card *CardClient
// User is the client for interacting with the User builders.
User *UserClient
}
// NewClient creates a new client configured with the given options.
func NewClient(opts ...Option) *Client {
c := config{log: log.Println}
c.options(opts...)
return &Client{
config: c,
Schema: migrate.NewSchema(c.driver),
Card: NewCardClient(c),
User: NewUserClient(c),
}
}
// Tx returns a new transactional client.
func (c *Client) Tx(ctx context.Context) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, fmt.Errorf("ent: cannot start a transaction within a transaction")
}
tx, err := newTx(ctx, c.driver)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %v", err)
}
cfg := config{driver: tx, log: c.log, verbose: c.verbose}
return &Tx{
config: cfg,
Card: NewCardClient(cfg),
User: NewUserClient(cfg),
}, nil
}
// CardClient is a client for the Card schema.
type CardClient struct {
config
}
// NewCardClient returns a client for the Card from the given config.
func NewCardClient(c config) *CardClient {
return &CardClient{config: c}
}
// Create returns a create builder for Card.
func (c *CardClient) Create() *CardCreate {
return &CardCreate{config: c.config}
}
// Update returns an update builder for Card.
func (c *CardClient) Update() *CardUpdate {
return &CardUpdate{config: c.config}
}
// UpdateOne returns an update builder for the given entity.
func (c *CardClient) UpdateOne(ca *Card) *CardUpdateOne {
return c.UpdateOneID(ca.ID)
}
// UpdateOneID returns an update builder for the given id.
func (c *CardClient) UpdateOneID(id int) *CardUpdateOne {
return &CardUpdateOne{config: c.config, id: id}
}
// Delete returns a delete builder for Card.
func (c *CardClient) Delete() *CardDelete {
return &CardDelete{config: c.config}
}
// DeleteOne returns a delete builder for the given entity.
func (c *CardClient) DeleteOne(ca *Card) *CardDeleteOne {
return c.DeleteOneID(ca.ID)
}
// DeleteOneID returns a delete builder for the given id.
func (c *CardClient) DeleteOneID(id int) *CardDeleteOne {
return &CardDeleteOne{c.Delete().Where(card.ID(id))}
}
// Create returns a query builder for Card.
func (c *CardClient) Query() *CardQuery {
return &CardQuery{config: c.config}
}
// QueryOwner queries the owner edge of a Card.
func (c *CardClient) QueryOwner(ca *Card) *UserQuery {
query := &UserQuery{config: c.config}
id := ca.ID
t1 := sql.Table(user.Table)
t2 := sql.Select(card.OwnerColumn).
From(sql.Table(card.OwnerTable)).
Where(sql.EQ(card.FieldID, id))
query.sql = sql.Select().From(t1).Join(t2).On(t1.C(user.FieldID), t2.C(card.OwnerColumn))
return query
}
// UserClient is a client for the User schema.
type UserClient struct {
config
}
// NewUserClient returns a client for the User from the given config.
func NewUserClient(c config) *UserClient {
return &UserClient{config: c}
}
// Create returns a create builder for User.
func (c *UserClient) Create() *UserCreate {
return &UserCreate{config: c.config}
}
// Update returns an update builder for User.
func (c *UserClient) Update() *UserUpdate {
return &UserUpdate{config: c.config}
}
// UpdateOne returns an update builder for the given entity.
func (c *UserClient) UpdateOne(u *User) *UserUpdateOne {
return c.UpdateOneID(u.ID)
}
// UpdateOneID returns an update builder for the given id.
func (c *UserClient) UpdateOneID(id int) *UserUpdateOne {
return &UserUpdateOne{config: c.config, id: id}
}
// Delete returns a delete builder for User.
func (c *UserClient) Delete() *UserDelete {
return &UserDelete{config: c.config}
}
// DeleteOne returns a delete builder for the given entity.
func (c *UserClient) DeleteOne(u *User) *UserDeleteOne {
return c.DeleteOneID(u.ID)
}
// DeleteOneID returns a delete builder for the given id.
func (c *UserClient) DeleteOneID(id int) *UserDeleteOne {
return &UserDeleteOne{c.Delete().Where(user.ID(id))}
}
// Create returns a query builder for User.
func (c *UserClient) Query() *UserQuery {
return &UserQuery{config: c.config}
}
// QueryCard queries the card edge of a User.
func (c *UserClient) QueryCard(u *User) *CardQuery {
query := &CardQuery{config: c.config}
id := u.ID
query.sql = sql.Select().From(sql.Table(card.Table)).
Where(sql.EQ(user.CardColumn, id))
return query
}

View File

@@ -0,0 +1,51 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"github.com/facebookincubator/ent/dialect"
)
// Option function to configure the client.
type Option func(*config)
// Config is the configuration for the client and its builder.
type config struct {
// driver is the driver used for execute database requests.
driver dialect.Driver
// verbose enable a verbosity logging.
verbose bool
// log used for logging on verbose mode.
log func(...interface{})
}
// Options applies the options on the config object.
func (c *config) options(opts ...Option) {
for _, opt := range opts {
opt(c)
}
if c.verbose {
c.driver = dialect.Debug(c.driver, c.log)
}
}
// Verbose sets the client logging to verbose.
func Verbose() Option {
return func(c *config) {
c.verbose = true
}
}
// Log sets the client logging to verbose.
func Log(fn func(...interface{})) Option {
return func(c *config) {
c.log = fn
}
}
// Driver configures the client driver.
func Driver(driver dialect.Driver) Option {
return func(c *config) {
c.driver = driver
}
}

View File

@@ -0,0 +1,20 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
)
type contextKey struct{}
// FromContext returns the Client stored in a context, or nil if there isn't one.
func FromContext(ctx context.Context) *Client {
c, _ := ctx.Value(contextKey{}).(*Client)
return c
}
// NewContext returns a new context with the given Client attached.
func NewContext(parent context.Context, c *Client) context.Context {
return context.WithValue(parent, contextKey{}, c)
}

View File

@@ -0,0 +1,192 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"github.com/facebookincubator/ent/dialect"
"github.com/facebookincubator/ent/dialect/sql"
)
// Order applies an ordering on either graph traversal or sql selector.
type Order func(*sql.Selector)
// Asc applies the given fields in ASC order.
func Asc(fields ...string) Order {
return Order(
func(s *sql.Selector) {
for _, f := range fields {
s.OrderBy(sql.Asc(f))
}
},
)
}
// Desc applies the given fields in DESC order.
func Desc(fields ...string) Order {
return Order(
func(s *sql.Selector) {
for _, f := range fields {
s.OrderBy(sql.Desc(f))
}
},
)
}
// Aggregate applies an aggregation step on the group-by traversal/selector.
type Aggregate struct {
// SQL the column wrapped with the aggregation function.
SQL func(*sql.Selector) string
}
// As is a pseudo aggregation function for renaming another other functions with custom names. For example:
//
// GroupBy(field1, field2).
// Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")).
// Scan(ctx, &v)
//
func As(fn Aggregate, end string) Aggregate {
return Aggregate{
SQL: func(s *sql.Selector) string {
return sql.As(fn.SQL(s), end)
},
}
}
// Count applies the "count" aggregation function on each group.
func Count() Aggregate {
return Aggregate{
SQL: func(s *sql.Selector) string {
return sql.Count("*")
},
}
}
// Max applies the "max" aggregation function on the given field of each group.
func Max(field string) Aggregate {
return Aggregate{
SQL: func(s *sql.Selector) string {
return sql.Max(s.C(field))
},
}
}
// Mean applies the "mean" aggregation function on the given field of each group.
func Mean(field string) Aggregate {
return Aggregate{
SQL: func(s *sql.Selector) string {
return sql.Avg(s.C(field))
},
}
}
// Min applies the "min" aggregation function on the given field of each group.
func Min(field string) Aggregate {
return Aggregate{
SQL: func(s *sql.Selector) string {
return sql.Min(s.C(field))
},
}
}
// Sum applies the "sum" aggregation function on the given field of each group.
func Sum(field string) Aggregate {
return Aggregate{
SQL: func(s *sql.Selector) string {
return sql.Sum(s.C(field))
},
}
}
// ErrNotFound returns when trying to fetch a specific entity and it was not found in the database.
type ErrNotFound struct {
label string
}
// Error implements the error interface.
func (e *ErrNotFound) Error() string {
return fmt.Sprintf("ent: %s not found", e.label)
}
// IsNotFound returns a boolean indicating whether the error is a not found error.
func IsNotFound(err error) bool {
_, ok := err.(*ErrNotFound)
return ok
}
// MaskNotFound masks nor found error.
func MaskNotFound(err error) error {
if IsNotFound(err) {
return nil
}
return err
}
// ErrNotSingular returns when trying to fetch a singular entity and more then one was found in the database.
type ErrNotSingular struct {
label string
}
// Error implements the error interface.
func (e *ErrNotSingular) Error() string {
return fmt.Sprintf("ent: %s not singular", e.label)
}
// IsNotSingular returns a boolean indicating whether the error is a not singular error.
func IsNotSingular(err error) bool {
_, ok := err.(*ErrNotSingular)
return ok
}
// ErrConstraintFailed returns when trying to create/update one or more entities and
// one or more of their constraints failed. For example, violation of edge or field uniqueness.
type ErrConstraintFailed struct {
msg string
wrap error
}
// Error implements the error interface.
func (e ErrConstraintFailed) Error() string {
return fmt.Sprintf("ent: unique constraint failed: %s", e.msg)
}
// Unwrap implements the errors.Wrapper interface.
func (e *ErrConstraintFailed) Unwrap() error {
return e.wrap
}
// IsConstraintFailure returns a boolean indicating whether the error is a constraint failure.
func IsConstraintFailure(err error) bool {
_, ok := err.(*ErrConstraintFailed)
return ok
}
func isSQLConstraintError(err error) (*ErrConstraintFailed, bool) {
// Error number 1062 is ER_DUP_ENTRY in mysql, and "UNIQUE constraint failed" is SQLite prefix.
if msg := err.Error(); strings.HasPrefix(msg, "Error 1062") || strings.HasPrefix(msg, "UNIQUE constraint failed") {
return &ErrConstraintFailed{msg, err}, true
}
return nil, false
}
// rollback calls to tx.Rollback and wraps the given error with the rollback error if occurred.
func rollback(tx dialect.Tx, err error) error {
if rerr := tx.Rollback(); rerr != nil {
err = fmt.Errorf("%s: %v", err.Error(), rerr)
}
if err, ok := isSQLConstraintError(err); ok {
return err
}
return err
}
// keys returns the keys/ids from the edge map.
func keys(m map[int]struct{}) []int {
s := make([]int, 0, len(m))
for id, _ := range m {
s = append(s, id)
}
return s
}

View File

@@ -0,0 +1,80 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"log"
"time"
"github.com/facebookincubator/ent/dialect/sql"
)
// dsn for the database. In order to run the tests locally, run the following command:
//
// ENT_INTEGRATION_ENDPOINT="root:pass@tcp(localhost:3306)/test?parseTime=True" go test -v
//
var dsn string
func ExampleCard() {
if dsn == "" {
return
}
ctx := context.Background()
drv, err := sql.Open("mysql", dsn)
if err != nil {
log.Fatalf("failed creating database client: %v", err)
}
defer drv.Close()
client := NewClient(Driver(drv))
// creating vertices for the card's edges.
// create card vertex with its edges.
c := client.Card.
Create().
SetExpired(time.Now()).
SetNumber("string").
SaveX(ctx)
log.Println("card created:", c)
// query edges.
// Output:
}
func ExampleUser() {
if dsn == "" {
return
}
ctx := context.Background()
drv, err := sql.Open("mysql", dsn)
if err != nil {
log.Fatalf("failed creating database client: %v", err)
}
defer drv.Close()
client := NewClient(Driver(drv))
// creating vertices for the user's edges.
c0 := client.Card.
Create().
SetExpired(time.Now()).
SetNumber("string").
SaveX(ctx)
log.Println("card created:", c0)
// create user vertex with its edges.
u := client.User.
Create().
SetAge(1).
SetName("string").
SetCard(c0).
SaveX(ctx)
log.Println("user created:", u)
// query edges.
c0, err = u.QueryCard().First(ctx)
if err != nil {
log.Fatalf("failed querying card: %v", err)
}
log.Println("card found:", c0)
// Output:
}

View File

@@ -0,0 +1,3 @@
package ent
//go:generate go run ../../../entc/cmd/entc/entc.go generate --header "Code generated (@generated) by entc, DO NOT EDIT." ./schema

View File

@@ -0,0 +1,48 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package migrate
import (
"context"
"fmt"
"github.com/facebookincubator/ent/dialect"
"github.com/facebookincubator/ent/dialect/sql/schema"
)
var (
// WithGlobalUniqueID sets the universal ids options to the migration.
// If this option is enabled, ent migration will allocate a 1<<32 range
// for the ids of each entity (table).
// Note that this option cannot be applied on tables that already exist.
WithGlobalUniqueID = schema.WithGlobalUniqueID
// WithDropColumn sets the drop column option to the migration.
// If this option is enabled, ent migration will drop old columns
// that were used for both fields and edges. This defaults to false.
WithDropColumn = schema.WithDropColumn
// WithDropIndex sets the drop index option to the migration.
// If this option is enabled, ent migration will drop old indexes
// that were defined in the schema. This defaults to false.
// Note that unique constraints are defined using `UNIQUE INDEX`,
// and therefore, it's recommended to enable this option to get more
// flexibility in the schema changes.
WithDropIndex = schema.WithDropIndex
)
// Schema is the API for creating, migrating and dropping a schema.
type Schema struct {
drv dialect.Driver
universalID bool
}
// NewSchema creates a new schema client.
func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} }
// Create creates all schema resources.
func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error {
migrate, err := schema.NewMigrate(s.drv, opts...)
if err != nil {
return fmt.Errorf("ent/migrate: %v", err)
}
return migrate.Create(ctx, Tables...)
}

View File

@@ -0,0 +1,55 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package migrate
import (
"github.com/facebookincubator/ent/dialect/sql/schema"
"github.com/facebookincubator/ent/schema/field"
)
var (
// CardsColumns holds the columns for the "cards" table.
CardsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "expired", Type: field.TypeTime},
{Name: "number", Type: field.TypeString},
{Name: "owner_id", Type: field.TypeInt, Unique: true, Nullable: true},
}
// CardsTable holds the schema information for the "cards" table.
CardsTable = &schema.Table{
Name: "cards",
Columns: CardsColumns,
PrimaryKey: []*schema.Column{CardsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "cards_users_card",
Columns: []*schema.Column{CardsColumns[3]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.SetNull,
},
},
}
// UsersColumns holds the columns for the "users" table.
UsersColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "age", Type: field.TypeInt},
{Name: "name", Type: field.TypeString},
}
// UsersTable holds the schema information for the "users" table.
UsersTable = &schema.Table{
Name: "users",
Columns: UsersColumns,
PrimaryKey: []*schema.Column{UsersColumns[0]},
ForeignKeys: []*schema.ForeignKey{},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
CardsTable,
UsersTable,
}
)
func init() {
CardsTable.ForeignKeys[0].RefTable = UsersTable
}

View File

@@ -0,0 +1,13 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package predicate
import (
"github.com/facebookincubator/ent/dialect/sql"
)
// Card is the predicate function for card builders.
type Card func(*sql.Selector)
// User is the predicate function for user builders.
type User func(*sql.Selector)

View File

@@ -0,0 +1,33 @@
package schema
import (
"github.com/facebookincubator/ent"
"github.com/facebookincubator/ent/schema/edge"
"github.com/facebookincubator/ent/schema/field"
)
// Card holds the schema definition for the Card entity.
type Card struct {
ent.Schema
}
// Fields of the Card.
func (Card) Fields() []ent.Field {
return []ent.Field{
field.Time("expired"),
field.String("number"),
}
}
// Edges of the Card.
func (Card) Edges() []ent.Edge {
return []ent.Edge{
edge.From("owner", User.Type).
Ref("card").
Unique().
// We add the "Required" method to the builder
// to make this edge required on entity creation.
// i.e. Card cannot be created without its owner.
Required(),
}
}

View File

@@ -0,0 +1,28 @@
package schema
import (
"github.com/facebookincubator/ent"
"github.com/facebookincubator/ent/schema/edge"
"github.com/facebookincubator/ent/schema/field"
)
// User holds the schema definition for the User entity.
type User struct {
ent.Schema
}
// Fields of the User.
func (User) Fields() []ent.Field {
return []ent.Field{
field.Int("age"),
field.String("name"),
}
}
// Edges of the User.
func (User) Edges() []ent.Edge {
return []ent.Edge{
edge.To("card", Card.Type).
Unique(),
}
}

View File

@@ -0,0 +1,96 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"github.com/facebookincubator/ent/dialect"
"github.com/facebookincubator/ent/examples/o2o2types/ent/migrate"
)
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
// Card is the client for interacting with the Card builders.
Card *CardClient
// User is the client for interacting with the User builders.
User *UserClient
}
// Commit commits the transaction.
func (tx *Tx) Commit() error {
return tx.config.driver.(*txDriver).tx.Commit()
}
// Rollback rollbacks the transaction.
func (tx *Tx) Rollback() error {
return tx.config.driver.(*txDriver).tx.Rollback()
}
// Client returns a Client that binds to current transaction.
func (tx *Tx) Client() *Client {
return &Client{
config: tx.config,
Schema: migrate.NewSchema(tx.driver),
Card: NewCardClient(tx.config),
User: NewUserClient(tx.config),
}
}
// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation.
// The idea is to support transactions without adding any extra code to the builders.
// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance.
// Commit and Rollback are nop for the internal builders and the user must call one
// of them in order to commit or rollback the transaction.
//
// If a closed transaction is embedded in one of the generated entities, and the entity
// applies a query, for example: Card.QueryXXX(), the query will be executed
// through the driver which created this transaction.
//
// Note that txDriver is not goroutine safe.
type txDriver struct {
// the driver we started the transaction from.
drv dialect.Driver
// tx is the underlying transaction.
tx dialect.Tx
}
// newTx creates a new transactional driver.
func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) {
tx, err := drv.Tx(ctx)
if err != nil {
return nil, err
}
return &txDriver{tx: tx, drv: drv}, nil
}
// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls
// from the internal builders. Should be called only by the internal builders.
func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil }
// Dialect returns the dialect of the driver we started the transaction from.
func (tx *txDriver) Dialect() string { return tx.drv.Dialect() }
// Close is a nop close.
func (*txDriver) Close() error { return nil }
// Commit is a nop commit for the internal builders.
// User must call `Tx.Commit` in order to commit the transaction.
func (*txDriver) Commit() error { return nil }
// Rollback is a nop rollback for the internal builders.
// User must call `Tx.Rollback` in order to rollback the transaction.
func (*txDriver) Rollback() error { return nil }
// Exec calls tx.Exec.
func (tx *txDriver) Exec(ctx context.Context, query string, args, v interface{}) error {
return tx.tx.Exec(ctx, query, args, v)
}
// Query calls tx.Query.
func (tx *txDriver) Query(ctx context.Context, query string, args, v interface{}) error {
return tx.tx.Query(ctx, query, args, v)
}
var _ dialect.Driver = (*txDriver)(nil)

View File

@@ -0,0 +1,97 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"bytes"
"fmt"
"github.com/facebookincubator/ent/dialect/sql"
)
// User is the model entity for the User schema.
type User struct {
config
// ID of the ent.
ID int `json:"id,omitempty"`
// Age holds the value of the "age" field.
Age int `json:"age,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
}
// FromRows scans the sql response data into User.
func (u *User) FromRows(rows *sql.Rows) error {
var vu struct {
ID int
Age sql.NullInt64
Name sql.NullString
}
// the order here should be the same as in the `user.Columns`.
if err := rows.Scan(
&vu.ID,
&vu.Age,
&vu.Name,
); err != nil {
return err
}
u.ID = vu.ID
u.Age = int(vu.Age.Int64)
u.Name = vu.Name.String
return nil
}
// QueryCard queries the card edge of the User.
func (u *User) QueryCard() *CardQuery {
return (&UserClient{u.config}).QueryCard(u)
}
// Update returns a builder for updating this User.
// Note that, you need to call User.Unwrap() before calling this method, if this User
// was returned from a transaction, and the transaction was committed or rolled back.
func (u *User) Update() *UserUpdateOne {
return (&UserClient{u.config}).UpdateOne(u)
}
// Unwrap unwraps the entity that was returned from a transaction after it was closed,
// so that all next queries will be executed through the driver which created the transaction.
func (u *User) Unwrap() *User {
tx, ok := u.config.driver.(*txDriver)
if !ok {
panic("ent: User is not a transactional entity")
}
u.config.driver = tx.drv
return u
}
// String implements the fmt.Stringer.
func (u *User) String() string {
buf := bytes.NewBuffer(nil)
buf.WriteString("User(")
buf.WriteString(fmt.Sprintf("id=%v", u.ID))
buf.WriteString(fmt.Sprintf(", age=%v", u.Age))
buf.WriteString(fmt.Sprintf(", name=%v", u.Name))
buf.WriteString(")")
return buf.String()
}
// Users is a parsable slice of User.
type Users []*User
// FromRows scans the sql response data into Users.
func (u *Users) FromRows(rows *sql.Rows) error {
for rows.Next() {
vu := &User{}
if err := vu.FromRows(rows); err != nil {
return err
}
*u = append(*u, vu)
}
return nil
}
func (u Users) config(cfg config) {
for i := range u {
u[i].config = cfg
}
}

View File

@@ -0,0 +1,31 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package user
const (
// Label holds the string label denoting the user type in the database.
Label = "user"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldAge holds the string denoting the age vertex property in the database.
FieldAge = "age"
// FieldName holds the string denoting the name vertex property in the database.
FieldName = "name"
// Table holds the table name of the user in the database.
Table = "users"
// CardTable is the table the holds the card relation/edge.
CardTable = "cards"
// CardInverseTable is the table name for the Card entity.
// It exists in this package in order to avoid circular dependency with the "card" package.
CardInverseTable = "cards"
// CardColumn is the table column denoting the card relation/edge.
CardColumn = "owner_id"
)
// Columns holds all SQL columns are user fields.
var Columns = []string{
FieldID,
FieldAge,
FieldName,
}

View File

@@ -0,0 +1,413 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package user
import (
"github.com/facebookincubator/ent/examples/o2o2types/ent/predicate"
"github.com/facebookincubator/ent/dialect/sql"
)
// ID filters vertices based on their identifier.
func ID(id int) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
},
)
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
},
)
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldID), id))
},
)
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldID), id))
},
)
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldID), id))
},
)
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldID), id))
},
)
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldID), id))
},
)
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.User {
return predicate.User(
func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.In(s.C(FieldID), v...))
},
)
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.User {
return predicate.User(
func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.NotIn(s.C(FieldID), v...))
},
)
}
// Age applies equality check predicate on the "age" field. It's identical to AgeEQ.
func Age(v int) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldAge), v))
},
)
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldName), v))
},
)
}
// AgeEQ applies the EQ predicate on the "age" field.
func AgeEQ(v int) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldAge), v))
},
)
}
// AgeNEQ applies the NEQ predicate on the "age" field.
func AgeNEQ(v int) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldAge), v))
},
)
}
// AgeGT applies the GT predicate on the "age" field.
func AgeGT(v int) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldAge), v))
},
)
}
// AgeGTE applies the GTE predicate on the "age" field.
func AgeGTE(v int) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldAge), v))
},
)
}
// AgeLT applies the LT predicate on the "age" field.
func AgeLT(v int) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldAge), v))
},
)
}
// AgeLTE applies the LTE predicate on the "age" field.
func AgeLTE(v int) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldAge), v))
},
)
}
// AgeIn applies the In predicate on the "age" field.
func AgeIn(vs ...int) predicate.User {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.User(
func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(vs) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldAge), v...))
},
)
}
// AgeNotIn applies the NotIn predicate on the "age" field.
func AgeNotIn(vs ...int) predicate.User {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.User(
func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(vs) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldAge), v...))
},
)
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldName), v))
},
)
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldName), v))
},
)
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldName), v))
},
)
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldName), v))
},
)
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldName), v))
},
)
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldName), v))
},
)
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.User {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.User(
func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(vs) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldName), v...))
},
)
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.User {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.User(
func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(vs) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldName), v...))
},
)
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldName), v))
},
)
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldName), v))
},
)
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldName), v))
},
)
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldName), v))
},
)
}
// HasCard applies the HasEdge predicate on the "card" edge.
func HasCard() predicate.User {
return predicate.User(
func(s *sql.Selector) {
t1 := s.Table()
s.Where(
sql.In(
t1.C(FieldID),
sql.Select(CardColumn).
From(sql.Table(CardTable)).
Where(sql.NotNull(CardColumn)),
),
)
},
)
}
// HasCardWith applies the HasEdge predicate on the "card" edge with a given conditions (other predicates).
func HasCardWith(preds ...predicate.Card) predicate.User {
return predicate.User(
func(s *sql.Selector) {
t1 := s.Table()
t2 := sql.Select(CardColumn).From(sql.Table(CardTable))
for _, p := range preds {
p(t2)
}
s.Where(sql.In(t1.C(FieldID), t2))
},
)
}
// And groups list of predicates with the AND operator between them.
func And(predicates ...predicate.User) predicate.User {
return predicate.User(
func(s *sql.Selector) {
for _, p := range predicates {
p(s)
}
},
)
}
// Or groups list of predicates with the OR operator between them.
func Or(predicates ...predicate.User) predicate.User {
return predicate.User(
func(s *sql.Selector) {
for i, p := range predicates {
if i > 0 {
s.Or()
}
p(s)
}
},
)
}
// Not applies the not operator on the given predicate.
func Not(p predicate.User) predicate.User {
return predicate.User(
func(s *sql.Selector) {
p(s.Not())
},
)
}

View File

@@ -0,0 +1,129 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"github.com/facebookincubator/ent/examples/o2o2types/ent/card"
"github.com/facebookincubator/ent/examples/o2o2types/ent/user"
"github.com/facebookincubator/ent/dialect/sql"
)
// UserCreate is the builder for creating a User entity.
type UserCreate struct {
config
age *int
name *string
card map[int]struct{}
}
// SetAge sets the age field.
func (uc *UserCreate) SetAge(i int) *UserCreate {
uc.age = &i
return uc
}
// SetName sets the name field.
func (uc *UserCreate) SetName(s string) *UserCreate {
uc.name = &s
return uc
}
// SetCardID sets the card edge to Card by id.
func (uc *UserCreate) SetCardID(id int) *UserCreate {
if uc.card == nil {
uc.card = make(map[int]struct{})
}
uc.card[id] = struct{}{}
return uc
}
// SetNillableCardID sets the card edge to Card by id if the given value is not nil.
func (uc *UserCreate) SetNillableCardID(id *int) *UserCreate {
if id != nil {
uc = uc.SetCardID(*id)
}
return uc
}
// SetCard sets the card edge to Card.
func (uc *UserCreate) SetCard(c *Card) *UserCreate {
return uc.SetCardID(c.ID)
}
// Save creates the User in the database.
func (uc *UserCreate) Save(ctx context.Context) (*User, error) {
if uc.age == nil {
return nil, errors.New("ent: missing required field \"age\"")
}
if uc.name == nil {
return nil, errors.New("ent: missing required field \"name\"")
}
if len(uc.card) > 1 {
return nil, errors.New("ent: multiple assignments on a unique edge \"card\"")
}
return uc.sqlSave(ctx)
}
// SaveX calls Save and panics if Save returns an error.
func (uc *UserCreate) SaveX(ctx context.Context) *User {
v, err := uc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
func (uc *UserCreate) sqlSave(ctx context.Context) (*User, error) {
var (
res sql.Result
u = &User{config: uc.config}
)
tx, err := uc.driver.Tx(ctx)
if err != nil {
return nil, err
}
builder := sql.Insert(user.Table).Default(uc.driver.Dialect())
if uc.age != nil {
builder.Set(user.FieldAge, *uc.age)
u.Age = *uc.age
}
if uc.name != nil {
builder.Set(user.FieldName, *uc.name)
u.Name = *uc.name
}
query, args := builder.Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return nil, rollback(tx, err)
}
id, err := res.LastInsertId()
if err != nil {
return nil, rollback(tx, err)
}
u.ID = int(id)
if len(uc.card) > 0 {
eid := keys(uc.card)[0]
query, args := sql.Update(user.CardTable).
Set(user.CardColumn, id).
Where(sql.EQ(card.FieldID, eid).And().IsNull(user.CardColumn)).
Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return nil, rollback(tx, err)
}
affected, err := res.RowsAffected()
if err != nil {
return nil, rollback(tx, err)
}
if int(affected) < len(uc.card) {
return nil, rollback(tx, &ErrConstraintFailed{msg: fmt.Sprintf("one of \"card\" %v already connected to a different \"User\"", keys(uc.card))})
}
}
if err := tx.Commit(); err != nil {
return nil, err
}
return u, nil
}

View File

@@ -0,0 +1,61 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"github.com/facebookincubator/ent/examples/o2o2types/ent/predicate"
"github.com/facebookincubator/ent/examples/o2o2types/ent/user"
"github.com/facebookincubator/ent/dialect/sql"
)
// UserDelete is the builder for deleting a User entity.
type UserDelete struct {
config
predicates []predicate.User
}
// Where adds a new predicate for the builder.
func (ud *UserDelete) Where(ps ...predicate.User) *UserDelete {
ud.predicates = append(ud.predicates, ps...)
return ud
}
// Exec executes the deletion query.
func (ud *UserDelete) Exec(ctx context.Context) error {
return ud.sqlExec(ctx)
}
// ExecX is like Exec, but panics if an error occurs.
func (ud *UserDelete) ExecX(ctx context.Context) {
if err := ud.Exec(ctx); err != nil {
panic(err)
}
}
func (ud *UserDelete) sqlExec(ctx context.Context) error {
var res sql.Result
selector := sql.Select().From(sql.Table(user.Table))
for _, p := range ud.predicates {
p(selector)
}
query, args := sql.Delete(user.Table).FromSelect(selector).Query()
return ud.driver.Exec(ctx, query, args, &res)
}
// UserDeleteOne is the builder for deleting a single User entity.
type UserDeleteOne struct {
ud *UserDelete
}
// Exec executes the deletion query.
func (udo *UserDeleteOne) Exec(ctx context.Context) error {
return udo.ud.Exec(ctx)
}
// ExecX is like Exec, but panics if an error occurs.
func (udo *UserDeleteOne) ExecX(ctx context.Context) {
udo.ud.ExecX(ctx)
}

View File

@@ -0,0 +1,483 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"math"
"github.com/facebookincubator/ent/examples/o2o2types/ent/card"
"github.com/facebookincubator/ent/examples/o2o2types/ent/predicate"
"github.com/facebookincubator/ent/examples/o2o2types/ent/user"
"github.com/facebookincubator/ent/dialect/sql"
)
// UserQuery is the builder for querying User entities.
type UserQuery struct {
config
limit *int
offset *int
order []Order
unique []string
predicates []predicate.User
// intermediate queries.
sql *sql.Selector
}
// Where adds a new predicate for the builder.
func (uq *UserQuery) Where(ps ...predicate.User) *UserQuery {
uq.predicates = append(uq.predicates, ps...)
return uq
}
// Limit adds a limit step to the query.
func (uq *UserQuery) Limit(limit int) *UserQuery {
uq.limit = &limit
return uq
}
// Offset adds an offset step to the query.
func (uq *UserQuery) Offset(offset int) *UserQuery {
uq.offset = &offset
return uq
}
// Order adds an order step to the query.
func (uq *UserQuery) Order(o ...Order) *UserQuery {
uq.order = append(uq.order, o...)
return uq
}
// QueryCard chains the current query on the card edge.
func (uq *UserQuery) QueryCard() *CardQuery {
query := &CardQuery{config: uq.config}
t1 := sql.Table(card.Table)
t2 := uq.sqlQuery()
t2.Select(t2.C(user.FieldID))
query.sql = sql.Select().
From(t1).
Join(t2).
On(t1.C(user.CardColumn), t2.C(user.FieldID))
return query
}
// Get returns a User entity by its id.
func (uq *UserQuery) Get(ctx context.Context, id int) (*User, error) {
return uq.Where(user.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (uq *UserQuery) GetX(ctx context.Context, id int) *User {
u, err := uq.Get(ctx, id)
if err != nil {
panic(err)
}
return u
}
// First returns the first User entity in the query. Returns *ErrNotFound when no user was found.
func (uq *UserQuery) First(ctx context.Context) (*User, error) {
us, err := uq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(us) == 0 {
return nil, &ErrNotFound{user.Label}
}
return us[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (uq *UserQuery) FirstX(ctx context.Context) *User {
u, err := uq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return u
}
// FirstID returns the first User id in the query. Returns *ErrNotFound when no id was found.
func (uq *UserQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = uq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &ErrNotFound{user.Label}
return
}
return ids[0], nil
}
// FirstXID is like FirstID, but panics if an error occurs.
func (uq *UserQuery) FirstXID(ctx context.Context) int {
id, err := uq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns the only User entity in the query, returns an error if not exactly one entity was returned.
func (uq *UserQuery) Only(ctx context.Context) (*User, error) {
us, err := uq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(us) {
case 1:
return us[0], nil
case 0:
return nil, &ErrNotFound{user.Label}
default:
return nil, &ErrNotSingular{user.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (uq *UserQuery) OnlyX(ctx context.Context) *User {
u, err := uq.Only(ctx)
if err != nil {
panic(err)
}
return u
}
// OnlyID returns the only User id in the query, returns an error if not exactly one id was returned.
func (uq *UserQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = uq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &ErrNotFound{user.Label}
default:
err = &ErrNotSingular{user.Label}
}
return
}
// OnlyXID is like OnlyID, but panics if an error occurs.
func (uq *UserQuery) OnlyXID(ctx context.Context) int {
id, err := uq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Users.
func (uq *UserQuery) All(ctx context.Context) ([]*User, error) {
return uq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (uq *UserQuery) AllX(ctx context.Context) []*User {
us, err := uq.All(ctx)
if err != nil {
panic(err)
}
return us
}
// IDs executes the query and returns a list of User ids.
func (uq *UserQuery) IDs(ctx context.Context) ([]int, error) {
return uq.sqlIDs(ctx)
}
// IDsX is like IDs, but panics if an error occurs.
func (uq *UserQuery) IDsX(ctx context.Context) []int {
ids, err := uq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (uq *UserQuery) Count(ctx context.Context) (int, error) {
return uq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (uq *UserQuery) CountX(ctx context.Context) int {
count, err := uq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (uq *UserQuery) Exist(ctx context.Context) (bool, error) {
return uq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (uq *UserQuery) ExistX(ctx context.Context) bool {
exist, err := uq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the query builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (uq *UserQuery) Clone() *UserQuery {
return &UserQuery{
config: uq.config,
limit: uq.limit,
offset: uq.offset,
order: append([]Order{}, uq.order...),
unique: append([]string{}, uq.unique...),
predicates: append([]predicate.User{}, uq.predicates...),
// clone intermediate queries.
sql: uq.sql.Clone(),
}
}
// GroupBy used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// Age int `json:"age,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.User.Query().
// GroupBy(user.FieldAge).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
//
func (uq *UserQuery) GroupBy(field string, fields ...string) *UserGroupBy {
group := &UserGroupBy{config: uq.config}
group.fields = append([]string{field}, fields...)
group.sql = uq.sqlQuery()
return group
}
func (uq *UserQuery) sqlAll(ctx context.Context) ([]*User, error) {
rows := &sql.Rows{}
selector := uq.sqlQuery()
if unique := uq.unique; len(unique) == 0 {
selector.Distinct()
}
query, args := selector.Query()
if err := uq.driver.Query(ctx, query, args, rows); err != nil {
return nil, err
}
defer rows.Close()
var us Users
if err := us.FromRows(rows); err != nil {
return nil, err
}
us.config(uq.config)
return us, nil
}
func (uq *UserQuery) sqlCount(ctx context.Context) (int, error) {
rows := &sql.Rows{}
selector := uq.sqlQuery()
unique := []string{user.FieldID}
if len(uq.unique) > 0 {
unique = uq.unique
}
selector.Count(sql.Distinct(selector.Columns(unique...)...))
query, args := selector.Query()
if err := uq.driver.Query(ctx, query, args, rows); err != nil {
return 0, err
}
defer rows.Close()
if !rows.Next() {
return 0, errors.New("ent: no rows found")
}
var n int
if err := rows.Scan(&n); err != nil {
return 0, fmt.Errorf("ent: failed reading count: %v", err)
}
return n, nil
}
func (uq *UserQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := uq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("ent: check existence: %v", err)
}
return n > 0, nil
}
func (uq *UserQuery) sqlIDs(ctx context.Context) ([]int, error) {
vs, err := uq.sqlAll(ctx)
if err != nil {
return nil, err
}
var ids []int
for _, v := range vs {
ids = append(ids, v.ID)
}
return ids, nil
}
func (uq *UserQuery) sqlQuery() *sql.Selector {
t1 := sql.Table(user.Table)
selector := sql.Select(t1.Columns(user.Columns...)...).From(t1)
if uq.sql != nil {
selector = uq.sql
selector.Select(selector.Columns(user.Columns...)...)
}
for _, p := range uq.predicates {
p(selector)
}
for _, p := range uq.order {
p(selector)
}
if offset := uq.offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt64)
}
if limit := uq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// UserQuery is the builder for group-by User entities.
type UserGroupBy struct {
config
fields []string
fns []Aggregate
// intermediate queries.
sql *sql.Selector
}
// Aggregate adds the given aggregation functions to the group-by query.
func (ugb *UserGroupBy) Aggregate(fns ...Aggregate) *UserGroupBy {
ugb.fns = append(ugb.fns, fns...)
return ugb
}
// Scan applies the group-by query and scan the result into the given value.
func (ugb *UserGroupBy) Scan(ctx context.Context, v interface{}) error {
return ugb.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (ugb *UserGroupBy) ScanX(ctx context.Context, v interface{}) {
if err := ugb.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from group-by. It is only allowed when querying group-by with one field.
func (ugb *UserGroupBy) Strings(ctx context.Context) ([]string, error) {
if len(ugb.fields) > 1 {
return nil, errors.New("ent: UserGroupBy.Strings is not achievable when grouping more than 1 field")
}
var v []string
if err := ugb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (ugb *UserGroupBy) StringsX(ctx context.Context) []string {
v, err := ugb.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from group-by. It is only allowed when querying group-by with one field.
func (ugb *UserGroupBy) Ints(ctx context.Context) ([]int, error) {
if len(ugb.fields) > 1 {
return nil, errors.New("ent: UserGroupBy.Ints is not achievable when grouping more than 1 field")
}
var v []int
if err := ugb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (ugb *UserGroupBy) IntsX(ctx context.Context) []int {
v, err := ugb.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from group-by. It is only allowed when querying group-by with one field.
func (ugb *UserGroupBy) Float64s(ctx context.Context) ([]float64, error) {
if len(ugb.fields) > 1 {
return nil, errors.New("ent: UserGroupBy.Float64s is not achievable when grouping more than 1 field")
}
var v []float64
if err := ugb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (ugb *UserGroupBy) Float64sX(ctx context.Context) []float64 {
v, err := ugb.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from group-by. It is only allowed when querying group-by with one field.
func (ugb *UserGroupBy) Bools(ctx context.Context) ([]bool, error) {
if len(ugb.fields) > 1 {
return nil, errors.New("ent: UserGroupBy.Bools is not achievable when grouping more than 1 field")
}
var v []bool
if err := ugb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (ugb *UserGroupBy) BoolsX(ctx context.Context) []bool {
v, err := ugb.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
func (ugb *UserGroupBy) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{}
query, args := ugb.sqlQuery().Query()
if err := ugb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (ugb *UserGroupBy) sqlQuery() *sql.Selector {
selector := ugb.sql
columns := make([]string, 0, len(ugb.fields)+len(ugb.fns))
columns = append(columns, ugb.fields...)
for _, fn := range ugb.fns {
columns = append(columns, fn.SQL(selector))
}
return selector.Select(columns...).GroupBy(ugb.fields...)
}

View File

@@ -0,0 +1,346 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"github.com/facebookincubator/ent/examples/o2o2types/ent/card"
"github.com/facebookincubator/ent/examples/o2o2types/ent/predicate"
"github.com/facebookincubator/ent/examples/o2o2types/ent/user"
"github.com/facebookincubator/ent/dialect/sql"
)
// UserUpdate is the builder for updating User entities.
type UserUpdate struct {
config
age *int
name *string
card map[int]struct{}
clearedCard bool
predicates []predicate.User
}
// Where adds a new predicate for the builder.
func (uu *UserUpdate) Where(ps ...predicate.User) *UserUpdate {
uu.predicates = append(uu.predicates, ps...)
return uu
}
// SetAge sets the age field.
func (uu *UserUpdate) SetAge(i int) *UserUpdate {
uu.age = &i
return uu
}
// SetName sets the name field.
func (uu *UserUpdate) SetName(s string) *UserUpdate {
uu.name = &s
return uu
}
// SetCardID sets the card edge to Card by id.
func (uu *UserUpdate) SetCardID(id int) *UserUpdate {
if uu.card == nil {
uu.card = make(map[int]struct{})
}
uu.card[id] = struct{}{}
return uu
}
// SetNillableCardID sets the card edge to Card by id if the given value is not nil.
func (uu *UserUpdate) SetNillableCardID(id *int) *UserUpdate {
if id != nil {
uu = uu.SetCardID(*id)
}
return uu
}
// SetCard sets the card edge to Card.
func (uu *UserUpdate) SetCard(c *Card) *UserUpdate {
return uu.SetCardID(c.ID)
}
// ClearCard clears the card edge to Card.
func (uu *UserUpdate) ClearCard() *UserUpdate {
uu.clearedCard = true
return uu
}
// Save executes the query and returns the number of rows/vertices matched by this operation.
func (uu *UserUpdate) Save(ctx context.Context) (int, error) {
if len(uu.card) > 1 {
return 0, errors.New("ent: multiple assignments on a unique edge \"card\"")
}
return uu.sqlSave(ctx)
}
// SaveX is like Save, but panics if an error occurs.
func (uu *UserUpdate) SaveX(ctx context.Context) int {
affected, err := uu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (uu *UserUpdate) Exec(ctx context.Context) error {
_, err := uu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (uu *UserUpdate) ExecX(ctx context.Context) {
if err := uu.Exec(ctx); err != nil {
panic(err)
}
}
func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) {
selector := sql.Select(user.FieldID).From(sql.Table(user.Table))
for _, p := range uu.predicates {
p(selector)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err = uu.driver.Query(ctx, query, args, rows); err != nil {
return 0, err
}
defer rows.Close()
var ids []int
for rows.Next() {
var id int
if err := rows.Scan(&id); err != nil {
return 0, fmt.Errorf("ent: failed reading id: %v", err)
}
ids = append(ids, id)
}
if len(ids) == 0 {
return 0, nil
}
tx, err := uu.driver.Tx(ctx)
if err != nil {
return 0, err
}
var (
update bool
res sql.Result
builder = sql.Update(user.Table).Where(sql.InInts(user.FieldID, ids...))
)
if uu.age != nil {
update = true
builder.Set(user.FieldAge, *uu.age)
}
if uu.name != nil {
update = true
builder.Set(user.FieldName, *uu.name)
}
if update {
query, args := builder.Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return 0, rollback(tx, err)
}
}
if uu.clearedCard {
query, args := sql.Update(user.CardTable).
SetNull(user.CardColumn).
Where(sql.InInts(card.FieldID, ids...)).
Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return 0, rollback(tx, err)
}
}
if len(uu.card) > 0 {
for _, id := range ids {
eid := keys(uu.card)[0]
query, args := sql.Update(user.CardTable).
Set(user.CardColumn, id).
Where(sql.EQ(card.FieldID, eid).And().IsNull(user.CardColumn)).
Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return 0, rollback(tx, err)
}
affected, err := res.RowsAffected()
if err != nil {
return 0, rollback(tx, err)
}
if int(affected) < len(uu.card) {
return 0, rollback(tx, &ErrConstraintFailed{msg: fmt.Sprintf("one of \"card\" %v already connected to a different \"User\"", keys(uu.card))})
}
}
}
if err = tx.Commit(); err != nil {
return 0, err
}
return len(ids), nil
}
// UserUpdateOne is the builder for updating a single User entity.
type UserUpdateOne struct {
config
id int
age *int
name *string
card map[int]struct{}
clearedCard bool
}
// SetAge sets the age field.
func (uuo *UserUpdateOne) SetAge(i int) *UserUpdateOne {
uuo.age = &i
return uuo
}
// SetName sets the name field.
func (uuo *UserUpdateOne) SetName(s string) *UserUpdateOne {
uuo.name = &s
return uuo
}
// SetCardID sets the card edge to Card by id.
func (uuo *UserUpdateOne) SetCardID(id int) *UserUpdateOne {
if uuo.card == nil {
uuo.card = make(map[int]struct{})
}
uuo.card[id] = struct{}{}
return uuo
}
// SetNillableCardID sets the card edge to Card by id if the given value is not nil.
func (uuo *UserUpdateOne) SetNillableCardID(id *int) *UserUpdateOne {
if id != nil {
uuo = uuo.SetCardID(*id)
}
return uuo
}
// SetCard sets the card edge to Card.
func (uuo *UserUpdateOne) SetCard(c *Card) *UserUpdateOne {
return uuo.SetCardID(c.ID)
}
// ClearCard clears the card edge to Card.
func (uuo *UserUpdateOne) ClearCard() *UserUpdateOne {
uuo.clearedCard = true
return uuo
}
// Save executes the query and returns the updated entity.
func (uuo *UserUpdateOne) Save(ctx context.Context) (*User, error) {
if len(uuo.card) > 1 {
return nil, errors.New("ent: multiple assignments on a unique edge \"card\"")
}
return uuo.sqlSave(ctx)
}
// SaveX is like Save, but panics if an error occurs.
func (uuo *UserUpdateOne) SaveX(ctx context.Context) *User {
u, err := uuo.Save(ctx)
if err != nil {
panic(err)
}
return u
}
// Exec executes the query on the entity.
func (uuo *UserUpdateOne) Exec(ctx context.Context) error {
_, err := uuo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (uuo *UserUpdateOne) ExecX(ctx context.Context) {
if err := uuo.Exec(ctx); err != nil {
panic(err)
}
}
func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (u *User, err error) {
selector := sql.Select(user.Columns...).From(sql.Table(user.Table))
user.ID(uuo.id)(selector)
rows := &sql.Rows{}
query, args := selector.Query()
if err = uuo.driver.Query(ctx, query, args, rows); err != nil {
return nil, err
}
defer rows.Close()
var ids []int
for rows.Next() {
var id int
u = &User{config: uuo.config}
if err := u.FromRows(rows); err != nil {
return nil, fmt.Errorf("ent: failed scanning row into User: %v", err)
}
id = u.ID
ids = append(ids, id)
}
switch n := len(ids); {
case n == 0:
return nil, fmt.Errorf("ent: User not found with id: %v", uuo.id)
case n > 1:
return nil, fmt.Errorf("ent: more than one User with the same id: %v", uuo.id)
}
tx, err := uuo.driver.Tx(ctx)
if err != nil {
return nil, err
}
var (
update bool
res sql.Result
builder = sql.Update(user.Table).Where(sql.InInts(user.FieldID, ids...))
)
if uuo.age != nil {
update = true
builder.Set(user.FieldAge, *uuo.age)
u.Age = *uuo.age
}
if uuo.name != nil {
update = true
builder.Set(user.FieldName, *uuo.name)
u.Name = *uuo.name
}
if update {
query, args := builder.Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return nil, rollback(tx, err)
}
}
if uuo.clearedCard {
query, args := sql.Update(user.CardTable).
SetNull(user.CardColumn).
Where(sql.InInts(card.FieldID, ids...)).
Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return nil, rollback(tx, err)
}
}
if len(uuo.card) > 0 {
for _, id := range ids {
eid := keys(uuo.card)[0]
query, args := sql.Update(user.CardTable).
Set(user.CardColumn, id).
Where(sql.EQ(card.FieldID, eid).And().IsNull(user.CardColumn)).
Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return nil, rollback(tx, err)
}
affected, err := res.RowsAffected()
if err != nil {
return nil, rollback(tx, err)
}
if int(affected) < len(uuo.card) {
return nil, rollback(tx, &ErrConstraintFailed{msg: fmt.Sprintf("one of \"card\" %v already connected to a different \"User\"", keys(uuo.card))})
}
}
}
if err = tx.Commit(); err != nil {
return nil, err
}
return u, nil
}

View File

@@ -0,0 +1,67 @@
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/facebookincubator/ent/examples/o2o2types/ent"
"github.com/facebookincubator/ent/dialect/sql"
_ "github.com/mattn/go-sqlite3"
)
func main() {
db, err := sql.Open("sqlite3", "file:o2o2types?mode=memory&cache=shared&_fk=1")
if err != nil {
log.Fatalf("failed opening connection to sqlite: %v", err)
}
defer db.Close()
client := ent.NewClient(ent.Driver(db))
ctx := context.Background()
// run the auto migration tool.
if err := client.Schema.Create(ctx); err != nil {
log.Fatalf("failed creating schema resources: %v", err)
}
if err := Do(ctx, client); err != nil {
log.Fatal(err)
}
}
func Do(ctx context.Context, client *ent.Client) error {
a8m, err := client.User.
Create().
SetAge(30).
SetName("Mashraki").
Save(ctx)
if err != nil {
return fmt.Errorf("creating user: %v", err)
}
log.Println("user:", a8m)
card1, err := client.Card.
Create().
SetOwner(a8m).
SetNumber("1020").
SetExpired(time.Now().Add(time.Minute)).
Save(ctx)
if err != nil {
return fmt.Errorf("creating card: %v", err)
}
log.Println("card:", card1)
// Only returns the card of the user,
// and expects that there's only one.
card2, err := a8m.QueryCard().Only(ctx)
if err != nil {
return fmt.Errorf("querying card: %v", err)
}
log.Println("card:", card2)
// The Card entity is able to query its owner using
// its back-reference.
owner, err := card2.QueryOwner().Only(ctx)
if err != nil {
return fmt.Errorf("querying owner: %v", err)
}
log.Println("owner:", owner)
return nil
}