ent/doc: o2m two types example

Reviewed By: idoshveki

Differential Revision: D17050002

fbshipit-source-id: 183c41bfb8cffb463a80a80590a01aba176e3b2a
This commit is contained in:
Ariel Mashraki
2019-08-26 02:43:17 -07:00
committed by Facebook Github Bot
parent e2b81d2ebc
commit 551236f06d
29 changed files with 3938 additions and 3 deletions

View File

@@ -0,0 +1,12 @@
# User-Pets O2M Relation
An example for a O2M (one-to-many) relation between a user and its pets.
Each user **has many** pets, and a pet **has one** owner. If a user A adds
a pet B using the pets edge, B can get its owner using the owner edge.
### Generate Assets
```console
go generate ./...
```

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/o2m2types/ent/migrate"
"github.com/facebookincubator/ent/examples/o2m2types/ent/pet"
"github.com/facebookincubator/ent/examples/o2m2types/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
// Pet is the client for interacting with the Pet builders.
Pet *PetClient
// 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),
Pet: NewPetClient(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,
Pet: NewPetClient(cfg),
User: NewUserClient(cfg),
}, nil
}
// PetClient is a client for the Pet schema.
type PetClient struct {
config
}
// NewPetClient returns a client for the Pet from the given config.
func NewPetClient(c config) *PetClient {
return &PetClient{config: c}
}
// Create returns a create builder for Pet.
func (c *PetClient) Create() *PetCreate {
return &PetCreate{config: c.config}
}
// Update returns an update builder for Pet.
func (c *PetClient) Update() *PetUpdate {
return &PetUpdate{config: c.config}
}
// UpdateOne returns an update builder for the given entity.
func (c *PetClient) UpdateOne(pe *Pet) *PetUpdateOne {
return c.UpdateOneID(pe.ID)
}
// UpdateOneID returns an update builder for the given id.
func (c *PetClient) UpdateOneID(id int) *PetUpdateOne {
return &PetUpdateOne{config: c.config, id: id}
}
// Delete returns a delete builder for Pet.
func (c *PetClient) Delete() *PetDelete {
return &PetDelete{config: c.config}
}
// DeleteOne returns a delete builder for the given entity.
func (c *PetClient) DeleteOne(pe *Pet) *PetDeleteOne {
return c.DeleteOneID(pe.ID)
}
// DeleteOneID returns a delete builder for the given id.
func (c *PetClient) DeleteOneID(id int) *PetDeleteOne {
return &PetDeleteOne{c.Delete().Where(pet.ID(id))}
}
// Create returns a query builder for Pet.
func (c *PetClient) Query() *PetQuery {
return &PetQuery{config: c.config}
}
// QueryOwner queries the owner edge of a Pet.
func (c *PetClient) QueryOwner(pe *Pet) *UserQuery {
query := &UserQuery{config: c.config}
id := pe.ID
t1 := sql.Table(user.Table)
t2 := sql.Select(pet.OwnerColumn).
From(sql.Table(pet.OwnerTable)).
Where(sql.EQ(pet.FieldID, id))
query.sql = sql.Select().From(t1).Join(t2).On(t1.C(user.FieldID), t2.C(pet.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}
}
// QueryPets queries the pets edge of a User.
func (c *UserClient) QueryPets(u *User) *PetQuery {
query := &PetQuery{config: c.config}
id := u.ID
query.sql = sql.Select().From(sql.Table(pet.Table)).
Where(sql.EQ(user.PetsColumn, 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,77 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"log"
"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 ExamplePet() {
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 pet's edges.
// create pet vertex with its edges.
pe := client.Pet.
Create().
SetName("string").
SaveX(ctx)
log.Println("pet created:", pe)
// 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.
pe0 := client.Pet.
Create().
SetName("string").
SaveX(ctx)
log.Println("pet created:", pe0)
// create user vertex with its edges.
u := client.User.
Create().
SetAge(1).
SetName("string").
AddPets(pe0).
SaveX(ctx)
log.Println("user created:", u)
// query edges.
pe0, err = u.QueryPets().First(ctx)
if err != nil {
log.Fatalf("failed querying pets: %v", err)
}
log.Println("pets found:", pe0)
// 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,54 @@
// 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 (
// PetsColumns holds the columns for the "pets" table.
PetsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "name", Type: field.TypeString},
{Name: "owner_id", Type: field.TypeInt, Nullable: true},
}
// PetsTable holds the schema information for the "pets" table.
PetsTable = &schema.Table{
Name: "pets",
Columns: PetsColumns,
PrimaryKey: []*schema.Column{PetsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "pets_users_pets",
Columns: []*schema.Column{PetsColumns[2]},
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{
PetsTable,
UsersTable,
}
)
func init() {
PetsTable.ForeignKeys[0].RefTable = UsersTable
}

View File

@@ -0,0 +1,91 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"bytes"
"fmt"
"github.com/facebookincubator/ent/dialect/sql"
)
// Pet is the model entity for the Pet schema.
type Pet struct {
config
// ID of the ent.
ID int `json:"id,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
}
// FromRows scans the sql response data into Pet.
func (pe *Pet) FromRows(rows *sql.Rows) error {
var vpe struct {
ID int
Name sql.NullString
}
// the order here should be the same as in the `pet.Columns`.
if err := rows.Scan(
&vpe.ID,
&vpe.Name,
); err != nil {
return err
}
pe.ID = vpe.ID
pe.Name = vpe.Name.String
return nil
}
// QueryOwner queries the owner edge of the Pet.
func (pe *Pet) QueryOwner() *UserQuery {
return (&PetClient{pe.config}).QueryOwner(pe)
}
// Update returns a builder for updating this Pet.
// Note that, you need to call Pet.Unwrap() before calling this method, if this Pet
// was returned from a transaction, and the transaction was committed or rolled back.
func (pe *Pet) Update() *PetUpdateOne {
return (&PetClient{pe.config}).UpdateOne(pe)
}
// 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 (pe *Pet) Unwrap() *Pet {
tx, ok := pe.config.driver.(*txDriver)
if !ok {
panic("ent: Pet is not a transactional entity")
}
pe.config.driver = tx.drv
return pe
}
// String implements the fmt.Stringer.
func (pe *Pet) String() string {
buf := bytes.NewBuffer(nil)
buf.WriteString("Pet(")
buf.WriteString(fmt.Sprintf("id=%v", pe.ID))
buf.WriteString(fmt.Sprintf(", name=%v", pe.Name))
buf.WriteString(")")
return buf.String()
}
// Pets is a parsable slice of Pet.
type Pets []*Pet
// FromRows scans the sql response data into Pets.
func (pe *Pets) FromRows(rows *sql.Rows) error {
for rows.Next() {
vpe := &Pet{}
if err := vpe.FromRows(rows); err != nil {
return err
}
*pe = append(*pe, vpe)
}
return nil
}
func (pe Pets) config(cfg config) {
for i := range pe {
pe[i].config = cfg
}
}

View File

@@ -0,0 +1,28 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package pet
const (
// Label holds the string label denoting the pet type in the database.
Label = "pet"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldName holds the string denoting the name vertex property in the database.
FieldName = "name"
// Table holds the table name of the pet in the database.
Table = "pets"
// OwnerTable is the table the holds the owner relation/edge.
OwnerTable = "pets"
// 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 pet fields.
var Columns = []string{
FieldID,
FieldName,
}

View File

@@ -0,0 +1,305 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package pet
import (
"github.com/facebookincubator/ent/examples/o2m2types/ent/predicate"
"github.com/facebookincubator/ent/dialect/sql"
)
// ID filters vertices based on their identifier.
func ID(id int) predicate.Pet {
return predicate.Pet(
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.Pet {
return predicate.Pet(
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.Pet {
return predicate.Pet(
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.Pet {
return predicate.Pet(
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.Pet {
return predicate.Pet(
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.Pet {
return predicate.Pet(
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.Pet {
return predicate.Pet(
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.Pet {
return predicate.Pet(
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.Pet {
return predicate.Pet(
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...))
},
)
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Pet {
return predicate.Pet(
func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldName), v))
},
)
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Pet {
return predicate.Pet(
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.Pet {
return predicate.Pet(
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.Pet {
return predicate.Pet(
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.Pet {
return predicate.Pet(
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.Pet {
return predicate.Pet(
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.Pet {
return predicate.Pet(
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.Pet {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Pet(
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.Pet {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Pet(
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.Pet {
return predicate.Pet(
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.Pet {
return predicate.Pet(
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.Pet {
return predicate.Pet(
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.Pet {
return predicate.Pet(
func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldName), v))
},
)
}
// HasOwner applies the HasEdge predicate on the "owner" edge.
func HasOwner() predicate.Pet {
return predicate.Pet(
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.Pet {
return predicate.Pet(
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.Pet) predicate.Pet {
return predicate.Pet(
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.Pet) predicate.Pet {
return predicate.Pet(
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.Pet) predicate.Pet {
return predicate.Pet(
func(s *sql.Selector) {
p(s.Not())
},
)
}

View File

@@ -0,0 +1,107 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"errors"
"github.com/facebookincubator/ent/examples/o2m2types/ent/pet"
"github.com/facebookincubator/ent/dialect/sql"
)
// PetCreate is the builder for creating a Pet entity.
type PetCreate struct {
config
name *string
owner map[int]struct{}
}
// SetName sets the name field.
func (pc *PetCreate) SetName(s string) *PetCreate {
pc.name = &s
return pc
}
// SetOwnerID sets the owner edge to User by id.
func (pc *PetCreate) SetOwnerID(id int) *PetCreate {
if pc.owner == nil {
pc.owner = make(map[int]struct{})
}
pc.owner[id] = struct{}{}
return pc
}
// SetNillableOwnerID sets the owner edge to User by id if the given value is not nil.
func (pc *PetCreate) SetNillableOwnerID(id *int) *PetCreate {
if id != nil {
pc = pc.SetOwnerID(*id)
}
return pc
}
// SetOwner sets the owner edge to User.
func (pc *PetCreate) SetOwner(u *User) *PetCreate {
return pc.SetOwnerID(u.ID)
}
// Save creates the Pet in the database.
func (pc *PetCreate) Save(ctx context.Context) (*Pet, error) {
if pc.name == nil {
return nil, errors.New("ent: missing required field \"name\"")
}
if len(pc.owner) > 1 {
return nil, errors.New("ent: multiple assignments on a unique edge \"owner\"")
}
return pc.sqlSave(ctx)
}
// SaveX calls Save and panics if Save returns an error.
func (pc *PetCreate) SaveX(ctx context.Context) *Pet {
v, err := pc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
func (pc *PetCreate) sqlSave(ctx context.Context) (*Pet, error) {
var (
res sql.Result
pe = &Pet{config: pc.config}
)
tx, err := pc.driver.Tx(ctx)
if err != nil {
return nil, err
}
builder := sql.Insert(pet.Table).Default(pc.driver.Dialect())
if pc.name != nil {
builder.Set(pet.FieldName, *pc.name)
pe.Name = *pc.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)
}
pe.ID = int(id)
if len(pc.owner) > 0 {
for eid := range pc.owner {
query, args := sql.Update(pet.OwnerTable).
Set(pet.OwnerColumn, eid).
Where(sql.EQ(pet.FieldID, id)).
Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return nil, rollback(tx, err)
}
}
}
if err := tx.Commit(); err != nil {
return nil, err
}
return pe, nil
}

View File

@@ -0,0 +1,61 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"github.com/facebookincubator/ent/examples/o2m2types/ent/pet"
"github.com/facebookincubator/ent/examples/o2m2types/ent/predicate"
"github.com/facebookincubator/ent/dialect/sql"
)
// PetDelete is the builder for deleting a Pet entity.
type PetDelete struct {
config
predicates []predicate.Pet
}
// Where adds a new predicate for the builder.
func (pd *PetDelete) Where(ps ...predicate.Pet) *PetDelete {
pd.predicates = append(pd.predicates, ps...)
return pd
}
// Exec executes the deletion query.
func (pd *PetDelete) Exec(ctx context.Context) error {
return pd.sqlExec(ctx)
}
// ExecX is like Exec, but panics if an error occurs.
func (pd *PetDelete) ExecX(ctx context.Context) {
if err := pd.Exec(ctx); err != nil {
panic(err)
}
}
func (pd *PetDelete) sqlExec(ctx context.Context) error {
var res sql.Result
selector := sql.Select().From(sql.Table(pet.Table))
for _, p := range pd.predicates {
p(selector)
}
query, args := sql.Delete(pet.Table).FromSelect(selector).Query()
return pd.driver.Exec(ctx, query, args, &res)
}
// PetDeleteOne is the builder for deleting a single Pet entity.
type PetDeleteOne struct {
pd *PetDelete
}
// Exec executes the deletion query.
func (pdo *PetDeleteOne) Exec(ctx context.Context) error {
return pdo.pd.Exec(ctx)
}
// ExecX is like Exec, but panics if an error occurs.
func (pdo *PetDeleteOne) ExecX(ctx context.Context) {
pdo.pd.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/o2m2types/ent/pet"
"github.com/facebookincubator/ent/examples/o2m2types/ent/predicate"
"github.com/facebookincubator/ent/examples/o2m2types/ent/user"
"github.com/facebookincubator/ent/dialect/sql"
)
// PetQuery is the builder for querying Pet entities.
type PetQuery struct {
config
limit *int
offset *int
order []Order
unique []string
predicates []predicate.Pet
// intermediate queries.
sql *sql.Selector
}
// Where adds a new predicate for the builder.
func (pq *PetQuery) Where(ps ...predicate.Pet) *PetQuery {
pq.predicates = append(pq.predicates, ps...)
return pq
}
// Limit adds a limit step to the query.
func (pq *PetQuery) Limit(limit int) *PetQuery {
pq.limit = &limit
return pq
}
// Offset adds an offset step to the query.
func (pq *PetQuery) Offset(offset int) *PetQuery {
pq.offset = &offset
return pq
}
// Order adds an order step to the query.
func (pq *PetQuery) Order(o ...Order) *PetQuery {
pq.order = append(pq.order, o...)
return pq
}
// QueryOwner chains the current query on the owner edge.
func (pq *PetQuery) QueryOwner() *UserQuery {
query := &UserQuery{config: pq.config}
t1 := sql.Table(user.Table)
t2 := pq.sqlQuery()
t2.Select(t2.C(pet.OwnerColumn))
query.sql = sql.Select(t1.Columns(user.Columns...)...).
From(t1).
Join(t2).
On(t1.C(user.FieldID), t2.C(pet.OwnerColumn))
return query
}
// Get returns a Pet entity by its id.
func (pq *PetQuery) Get(ctx context.Context, id int) (*Pet, error) {
return pq.Where(pet.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (pq *PetQuery) GetX(ctx context.Context, id int) *Pet {
pe, err := pq.Get(ctx, id)
if err != nil {
panic(err)
}
return pe
}
// First returns the first Pet entity in the query. Returns *ErrNotFound when no pet was found.
func (pq *PetQuery) First(ctx context.Context) (*Pet, error) {
pes, err := pq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(pes) == 0 {
return nil, &ErrNotFound{pet.Label}
}
return pes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (pq *PetQuery) FirstX(ctx context.Context) *Pet {
pe, err := pq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return pe
}
// FirstID returns the first Pet id in the query. Returns *ErrNotFound when no id was found.
func (pq *PetQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = pq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &ErrNotFound{pet.Label}
return
}
return ids[0], nil
}
// FirstXID is like FirstID, but panics if an error occurs.
func (pq *PetQuery) FirstXID(ctx context.Context) int {
id, err := pq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns the only Pet entity in the query, returns an error if not exactly one entity was returned.
func (pq *PetQuery) Only(ctx context.Context) (*Pet, error) {
pes, err := pq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(pes) {
case 1:
return pes[0], nil
case 0:
return nil, &ErrNotFound{pet.Label}
default:
return nil, &ErrNotSingular{pet.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (pq *PetQuery) OnlyX(ctx context.Context) *Pet {
pe, err := pq.Only(ctx)
if err != nil {
panic(err)
}
return pe
}
// OnlyID returns the only Pet id in the query, returns an error if not exactly one id was returned.
func (pq *PetQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = pq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &ErrNotFound{pet.Label}
default:
err = &ErrNotSingular{pet.Label}
}
return
}
// OnlyXID is like OnlyID, but panics if an error occurs.
func (pq *PetQuery) OnlyXID(ctx context.Context) int {
id, err := pq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Pets.
func (pq *PetQuery) All(ctx context.Context) ([]*Pet, error) {
return pq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (pq *PetQuery) AllX(ctx context.Context) []*Pet {
pes, err := pq.All(ctx)
if err != nil {
panic(err)
}
return pes
}
// IDs executes the query and returns a list of Pet ids.
func (pq *PetQuery) IDs(ctx context.Context) ([]int, error) {
return pq.sqlIDs(ctx)
}
// IDsX is like IDs, but panics if an error occurs.
func (pq *PetQuery) IDsX(ctx context.Context) []int {
ids, err := pq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (pq *PetQuery) Count(ctx context.Context) (int, error) {
return pq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (pq *PetQuery) CountX(ctx context.Context) int {
count, err := pq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (pq *PetQuery) Exist(ctx context.Context) (bool, error) {
return pq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (pq *PetQuery) ExistX(ctx context.Context) bool {
exist, err := pq.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 (pq *PetQuery) Clone() *PetQuery {
return &PetQuery{
config: pq.config,
limit: pq.limit,
offset: pq.offset,
order: append([]Order{}, pq.order...),
unique: append([]string{}, pq.unique...),
predicates: append([]predicate.Pet{}, pq.predicates...),
// clone intermediate queries.
sql: pq.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 {
// Name string `json:"name,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Pet.Query().
// GroupBy(pet.FieldName).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
//
func (pq *PetQuery) GroupBy(field string, fields ...string) *PetGroupBy {
group := &PetGroupBy{config: pq.config}
group.fields = append([]string{field}, fields...)
group.sql = pq.sqlQuery()
return group
}
func (pq *PetQuery) sqlAll(ctx context.Context) ([]*Pet, error) {
rows := &sql.Rows{}
selector := pq.sqlQuery()
if unique := pq.unique; len(unique) == 0 {
selector.Distinct()
}
query, args := selector.Query()
if err := pq.driver.Query(ctx, query, args, rows); err != nil {
return nil, err
}
defer rows.Close()
var pes Pets
if err := pes.FromRows(rows); err != nil {
return nil, err
}
pes.config(pq.config)
return pes, nil
}
func (pq *PetQuery) sqlCount(ctx context.Context) (int, error) {
rows := &sql.Rows{}
selector := pq.sqlQuery()
unique := []string{pet.FieldID}
if len(pq.unique) > 0 {
unique = pq.unique
}
selector.Count(sql.Distinct(selector.Columns(unique...)...))
query, args := selector.Query()
if err := pq.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 (pq *PetQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := pq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("ent: check existence: %v", err)
}
return n > 0, nil
}
func (pq *PetQuery) sqlIDs(ctx context.Context) ([]int, error) {
vs, err := pq.sqlAll(ctx)
if err != nil {
return nil, err
}
var ids []int
for _, v := range vs {
ids = append(ids, v.ID)
}
return ids, nil
}
func (pq *PetQuery) sqlQuery() *sql.Selector {
t1 := sql.Table(pet.Table)
selector := sql.Select(t1.Columns(pet.Columns...)...).From(t1)
if pq.sql != nil {
selector = pq.sql
selector.Select(selector.Columns(pet.Columns...)...)
}
for _, p := range pq.predicates {
p(selector)
}
for _, p := range pq.order {
p(selector)
}
if offset := pq.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 := pq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// PetQuery is the builder for group-by Pet entities.
type PetGroupBy struct {
config
fields []string
fns []Aggregate
// intermediate queries.
sql *sql.Selector
}
// Aggregate adds the given aggregation functions to the group-by query.
func (pgb *PetGroupBy) Aggregate(fns ...Aggregate) *PetGroupBy {
pgb.fns = append(pgb.fns, fns...)
return pgb
}
// Scan applies the group-by query and scan the result into the given value.
func (pgb *PetGroupBy) Scan(ctx context.Context, v interface{}) error {
return pgb.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (pgb *PetGroupBy) ScanX(ctx context.Context, v interface{}) {
if err := pgb.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 (pgb *PetGroupBy) Strings(ctx context.Context) ([]string, error) {
if len(pgb.fields) > 1 {
return nil, errors.New("ent: PetGroupBy.Strings is not achievable when grouping more than 1 field")
}
var v []string
if err := pgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (pgb *PetGroupBy) StringsX(ctx context.Context) []string {
v, err := pgb.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 (pgb *PetGroupBy) Ints(ctx context.Context) ([]int, error) {
if len(pgb.fields) > 1 {
return nil, errors.New("ent: PetGroupBy.Ints is not achievable when grouping more than 1 field")
}
var v []int
if err := pgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (pgb *PetGroupBy) IntsX(ctx context.Context) []int {
v, err := pgb.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 (pgb *PetGroupBy) Float64s(ctx context.Context) ([]float64, error) {
if len(pgb.fields) > 1 {
return nil, errors.New("ent: PetGroupBy.Float64s is not achievable when grouping more than 1 field")
}
var v []float64
if err := pgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (pgb *PetGroupBy) Float64sX(ctx context.Context) []float64 {
v, err := pgb.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 (pgb *PetGroupBy) Bools(ctx context.Context) ([]bool, error) {
if len(pgb.fields) > 1 {
return nil, errors.New("ent: PetGroupBy.Bools is not achievable when grouping more than 1 field")
}
var v []bool
if err := pgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (pgb *PetGroupBy) BoolsX(ctx context.Context) []bool {
v, err := pgb.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
func (pgb *PetGroupBy) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{}
query, args := pgb.sqlQuery().Query()
if err := pgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (pgb *PetGroupBy) sqlQuery() *sql.Selector {
selector := pgb.sql
columns := make([]string, 0, len(pgb.fields)+len(pgb.fns))
columns = append(columns, pgb.fields...)
for _, fn := range pgb.fns {
columns = append(columns, fn.SQL(selector))
}
return selector.Select(columns...).GroupBy(pgb.fields...)
}

View File

@@ -0,0 +1,307 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"github.com/facebookincubator/ent/examples/o2m2types/ent/pet"
"github.com/facebookincubator/ent/examples/o2m2types/ent/predicate"
"github.com/facebookincubator/ent/examples/o2m2types/ent/user"
"github.com/facebookincubator/ent/dialect/sql"
)
// PetUpdate is the builder for updating Pet entities.
type PetUpdate struct {
config
name *string
owner map[int]struct{}
clearedOwner bool
predicates []predicate.Pet
}
// Where adds a new predicate for the builder.
func (pu *PetUpdate) Where(ps ...predicate.Pet) *PetUpdate {
pu.predicates = append(pu.predicates, ps...)
return pu
}
// SetName sets the name field.
func (pu *PetUpdate) SetName(s string) *PetUpdate {
pu.name = &s
return pu
}
// SetOwnerID sets the owner edge to User by id.
func (pu *PetUpdate) SetOwnerID(id int) *PetUpdate {
if pu.owner == nil {
pu.owner = make(map[int]struct{})
}
pu.owner[id] = struct{}{}
return pu
}
// SetNillableOwnerID sets the owner edge to User by id if the given value is not nil.
func (pu *PetUpdate) SetNillableOwnerID(id *int) *PetUpdate {
if id != nil {
pu = pu.SetOwnerID(*id)
}
return pu
}
// SetOwner sets the owner edge to User.
func (pu *PetUpdate) SetOwner(u *User) *PetUpdate {
return pu.SetOwnerID(u.ID)
}
// ClearOwner clears the owner edge to User.
func (pu *PetUpdate) ClearOwner() *PetUpdate {
pu.clearedOwner = true
return pu
}
// Save executes the query and returns the number of rows/vertices matched by this operation.
func (pu *PetUpdate) Save(ctx context.Context) (int, error) {
if len(pu.owner) > 1 {
return 0, errors.New("ent: multiple assignments on a unique edge \"owner\"")
}
return pu.sqlSave(ctx)
}
// SaveX is like Save, but panics if an error occurs.
func (pu *PetUpdate) SaveX(ctx context.Context) int {
affected, err := pu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (pu *PetUpdate) Exec(ctx context.Context) error {
_, err := pu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (pu *PetUpdate) ExecX(ctx context.Context) {
if err := pu.Exec(ctx); err != nil {
panic(err)
}
}
func (pu *PetUpdate) sqlSave(ctx context.Context) (n int, err error) {
selector := sql.Select(pet.FieldID).From(sql.Table(pet.Table))
for _, p := range pu.predicates {
p(selector)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err = pu.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 := pu.driver.Tx(ctx)
if err != nil {
return 0, err
}
var (
update bool
res sql.Result
builder = sql.Update(pet.Table).Where(sql.InInts(pet.FieldID, ids...))
)
if pu.name != nil {
update = true
builder.Set(pet.FieldName, *pu.name)
}
if update {
query, args := builder.Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return 0, rollback(tx, err)
}
}
if pu.clearedOwner {
query, args := sql.Update(pet.OwnerTable).
SetNull(pet.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(pu.owner) > 0 {
for eid := range pu.owner {
query, args := sql.Update(pet.OwnerTable).
Set(pet.OwnerColumn, eid).
Where(sql.InInts(pet.FieldID, ids...)).
Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return 0, rollback(tx, err)
}
}
}
if err = tx.Commit(); err != nil {
return 0, err
}
return len(ids), nil
}
// PetUpdateOne is the builder for updating a single Pet entity.
type PetUpdateOne struct {
config
id int
name *string
owner map[int]struct{}
clearedOwner bool
}
// SetName sets the name field.
func (puo *PetUpdateOne) SetName(s string) *PetUpdateOne {
puo.name = &s
return puo
}
// SetOwnerID sets the owner edge to User by id.
func (puo *PetUpdateOne) SetOwnerID(id int) *PetUpdateOne {
if puo.owner == nil {
puo.owner = make(map[int]struct{})
}
puo.owner[id] = struct{}{}
return puo
}
// SetNillableOwnerID sets the owner edge to User by id if the given value is not nil.
func (puo *PetUpdateOne) SetNillableOwnerID(id *int) *PetUpdateOne {
if id != nil {
puo = puo.SetOwnerID(*id)
}
return puo
}
// SetOwner sets the owner edge to User.
func (puo *PetUpdateOne) SetOwner(u *User) *PetUpdateOne {
return puo.SetOwnerID(u.ID)
}
// ClearOwner clears the owner edge to User.
func (puo *PetUpdateOne) ClearOwner() *PetUpdateOne {
puo.clearedOwner = true
return puo
}
// Save executes the query and returns the updated entity.
func (puo *PetUpdateOne) Save(ctx context.Context) (*Pet, error) {
if len(puo.owner) > 1 {
return nil, errors.New("ent: multiple assignments on a unique edge \"owner\"")
}
return puo.sqlSave(ctx)
}
// SaveX is like Save, but panics if an error occurs.
func (puo *PetUpdateOne) SaveX(ctx context.Context) *Pet {
pe, err := puo.Save(ctx)
if err != nil {
panic(err)
}
return pe
}
// Exec executes the query on the entity.
func (puo *PetUpdateOne) Exec(ctx context.Context) error {
_, err := puo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (puo *PetUpdateOne) ExecX(ctx context.Context) {
if err := puo.Exec(ctx); err != nil {
panic(err)
}
}
func (puo *PetUpdateOne) sqlSave(ctx context.Context) (pe *Pet, err error) {
selector := sql.Select(pet.Columns...).From(sql.Table(pet.Table))
pet.ID(puo.id)(selector)
rows := &sql.Rows{}
query, args := selector.Query()
if err = puo.driver.Query(ctx, query, args, rows); err != nil {
return nil, err
}
defer rows.Close()
var ids []int
for rows.Next() {
var id int
pe = &Pet{config: puo.config}
if err := pe.FromRows(rows); err != nil {
return nil, fmt.Errorf("ent: failed scanning row into Pet: %v", err)
}
id = pe.ID
ids = append(ids, id)
}
switch n := len(ids); {
case n == 0:
return nil, fmt.Errorf("ent: Pet not found with id: %v", puo.id)
case n > 1:
return nil, fmt.Errorf("ent: more than one Pet with the same id: %v", puo.id)
}
tx, err := puo.driver.Tx(ctx)
if err != nil {
return nil, err
}
var (
update bool
res sql.Result
builder = sql.Update(pet.Table).Where(sql.InInts(pet.FieldID, ids...))
)
if puo.name != nil {
update = true
builder.Set(pet.FieldName, *puo.name)
pe.Name = *puo.name
}
if update {
query, args := builder.Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return nil, rollback(tx, err)
}
}
if puo.clearedOwner {
query, args := sql.Update(pet.OwnerTable).
SetNull(pet.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(puo.owner) > 0 {
for eid := range puo.owner {
query, args := sql.Update(pet.OwnerTable).
Set(pet.OwnerColumn, eid).
Where(sql.InInts(pet.FieldID, ids...)).
Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return nil, rollback(tx, err)
}
}
}
if err = tx.Commit(); err != nil {
return nil, err
}
return pe, nil
}

View File

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

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"
)
// Pet holds the schema definition for the Pet entity.
type Pet struct {
ent.Schema
}
// Fields of the Pet.
func (Pet) Fields() []ent.Field {
return []ent.Field{
field.String("name"),
}
}
// Edges of the Pet.
func (Pet) Edges() []ent.Edge {
return []ent.Edge{
edge.From("owner", User.Type).
Ref("pets").
Unique(),
}
}

View File

@@ -0,0 +1,27 @@
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("pets", Pet.Type),
}
}

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/o2m2types/ent/migrate"
)
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
// Pet is the client for interacting with the Pet builders.
Pet *PetClient
// 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),
Pet: NewPetClient(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: Pet.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
}
// QueryPets queries the pets edge of the User.
func (u *User) QueryPets() *PetQuery {
return (&UserClient{u.config}).QueryPets(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"
// PetsTable is the table the holds the pets relation/edge.
PetsTable = "pets"
// PetsInverseTable is the table name for the Pet entity.
// It exists in this package in order to avoid circular dependency with the "pet" package.
PetsInverseTable = "pets"
// PetsColumn is the table column denoting the pets relation/edge.
PetsColumn = "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/o2m2types/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))
},
)
}
// HasPets applies the HasEdge predicate on the "pets" edge.
func HasPets() predicate.User {
return predicate.User(
func(s *sql.Selector) {
t1 := s.Table()
s.Where(
sql.In(
t1.C(FieldID),
sql.Select(PetsColumn).
From(sql.Table(PetsTable)).
Where(sql.NotNull(PetsColumn)),
),
)
},
)
}
// HasPetsWith applies the HasEdge predicate on the "pets" edge with a given conditions (other predicates).
func HasPetsWith(preds ...predicate.Pet) predicate.User {
return predicate.User(
func(s *sql.Selector) {
t1 := s.Table()
t2 := sql.Select(PetsColumn).From(sql.Table(PetsTable))
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,127 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"github.com/facebookincubator/ent/examples/o2m2types/ent/pet"
"github.com/facebookincubator/ent/examples/o2m2types/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
pets 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
}
// AddPetIDs adds the pets edge to Pet by ids.
func (uc *UserCreate) AddPetIDs(ids ...int) *UserCreate {
if uc.pets == nil {
uc.pets = make(map[int]struct{})
}
for i := range ids {
uc.pets[ids[i]] = struct{}{}
}
return uc
}
// AddPets adds the pets edges to Pet.
func (uc *UserCreate) AddPets(p ...*Pet) *UserCreate {
ids := make([]int, len(p))
for i := range p {
ids[i] = p[i].ID
}
return uc.AddPetIDs(ids...)
}
// 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\"")
}
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.pets) > 0 {
p := sql.P()
for eid := range uc.pets {
p.Or().EQ(pet.FieldID, eid)
}
query, args := sql.Update(user.PetsTable).
Set(user.PetsColumn, id).
Where(sql.And(p, sql.IsNull(user.PetsColumn))).
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.pets) {
return nil, rollback(tx, &ErrConstraintFailed{msg: fmt.Sprintf("one of \"pets\" %v already connected to a different \"User\"", keys(uc.pets))})
}
}
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/o2m2types/ent/predicate"
"github.com/facebookincubator/ent/examples/o2m2types/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/o2m2types/ent/pet"
"github.com/facebookincubator/ent/examples/o2m2types/ent/predicate"
"github.com/facebookincubator/ent/examples/o2m2types/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
}
// QueryPets chains the current query on the pets edge.
func (uq *UserQuery) QueryPets() *PetQuery {
query := &PetQuery{config: uq.config}
t1 := sql.Table(pet.Table)
t2 := uq.sqlQuery()
t2.Select(t2.C(user.FieldID))
query.sql = sql.Select().
From(t1).
Join(t2).
On(t1.C(user.PetsColumn), 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,379 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"github.com/facebookincubator/ent/examples/o2m2types/ent/pet"
"github.com/facebookincubator/ent/examples/o2m2types/ent/predicate"
"github.com/facebookincubator/ent/examples/o2m2types/ent/user"
"github.com/facebookincubator/ent/dialect/sql"
)
// UserUpdate is the builder for updating User entities.
type UserUpdate struct {
config
age *int
name *string
pets map[int]struct{}
removedPets map[int]struct{}
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
}
// AddPetIDs adds the pets edge to Pet by ids.
func (uu *UserUpdate) AddPetIDs(ids ...int) *UserUpdate {
if uu.pets == nil {
uu.pets = make(map[int]struct{})
}
for i := range ids {
uu.pets[ids[i]] = struct{}{}
}
return uu
}
// AddPets adds the pets edges to Pet.
func (uu *UserUpdate) AddPets(p ...*Pet) *UserUpdate {
ids := make([]int, len(p))
for i := range p {
ids[i] = p[i].ID
}
return uu.AddPetIDs(ids...)
}
// RemovePetIDs removes the pets edge to Pet by ids.
func (uu *UserUpdate) RemovePetIDs(ids ...int) *UserUpdate {
if uu.removedPets == nil {
uu.removedPets = make(map[int]struct{})
}
for i := range ids {
uu.removedPets[ids[i]] = struct{}{}
}
return uu
}
// RemovePets removes pets edges to Pet.
func (uu *UserUpdate) RemovePets(p ...*Pet) *UserUpdate {
ids := make([]int, len(p))
for i := range p {
ids[i] = p[i].ID
}
return uu.RemovePetIDs(ids...)
}
// Save executes the query and returns the number of rows/vertices matched by this operation.
func (uu *UserUpdate) Save(ctx context.Context) (int, error) {
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 len(uu.removedPets) > 0 {
eids := make([]int, len(uu.removedPets))
for eid := range uu.removedPets {
eids = append(eids, eid)
}
query, args := sql.Update(user.PetsTable).
SetNull(user.PetsColumn).
Where(sql.InInts(user.PetsColumn, ids...)).
Where(sql.InInts(pet.FieldID, eids...)).
Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return 0, rollback(tx, err)
}
}
if len(uu.pets) > 0 {
for _, id := range ids {
p := sql.P()
for eid := range uu.pets {
p.Or().EQ(pet.FieldID, eid)
}
query, args := sql.Update(user.PetsTable).
Set(user.PetsColumn, id).
Where(sql.And(p, sql.IsNull(user.PetsColumn))).
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.pets) {
return 0, rollback(tx, &ErrConstraintFailed{msg: fmt.Sprintf("one of \"pets\" %v already connected to a different \"User\"", keys(uu.pets))})
}
}
}
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
pets map[int]struct{}
removedPets map[int]struct{}
}
// 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
}
// AddPetIDs adds the pets edge to Pet by ids.
func (uuo *UserUpdateOne) AddPetIDs(ids ...int) *UserUpdateOne {
if uuo.pets == nil {
uuo.pets = make(map[int]struct{})
}
for i := range ids {
uuo.pets[ids[i]] = struct{}{}
}
return uuo
}
// AddPets adds the pets edges to Pet.
func (uuo *UserUpdateOne) AddPets(p ...*Pet) *UserUpdateOne {
ids := make([]int, len(p))
for i := range p {
ids[i] = p[i].ID
}
return uuo.AddPetIDs(ids...)
}
// RemovePetIDs removes the pets edge to Pet by ids.
func (uuo *UserUpdateOne) RemovePetIDs(ids ...int) *UserUpdateOne {
if uuo.removedPets == nil {
uuo.removedPets = make(map[int]struct{})
}
for i := range ids {
uuo.removedPets[ids[i]] = struct{}{}
}
return uuo
}
// RemovePets removes pets edges to Pet.
func (uuo *UserUpdateOne) RemovePets(p ...*Pet) *UserUpdateOne {
ids := make([]int, len(p))
for i := range p {
ids[i] = p[i].ID
}
return uuo.RemovePetIDs(ids...)
}
// Save executes the query and returns the updated entity.
func (uuo *UserUpdateOne) Save(ctx context.Context) (*User, error) {
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 len(uuo.removedPets) > 0 {
eids := make([]int, len(uuo.removedPets))
for eid := range uuo.removedPets {
eids = append(eids, eid)
}
query, args := sql.Update(user.PetsTable).
SetNull(user.PetsColumn).
Where(sql.InInts(user.PetsColumn, ids...)).
Where(sql.InInts(pet.FieldID, eids...)).
Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return nil, rollback(tx, err)
}
}
if len(uuo.pets) > 0 {
for _, id := range ids {
p := sql.P()
for eid := range uuo.pets {
p.Or().EQ(pet.FieldID, eid)
}
query, args := sql.Update(user.PetsTable).
Set(user.PetsColumn, id).
Where(sql.And(p, sql.IsNull(user.PetsColumn))).
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.pets) {
return nil, rollback(tx, &ErrConstraintFailed{msg: fmt.Sprintf("one of \"pets\" %v already connected to a different \"User\"", keys(uuo.pets))})
}
}
}
if err = tx.Commit(); err != nil {
return nil, err
}
return u, nil
}

View File

@@ -0,0 +1,73 @@
package main
import (
"context"
"fmt"
"log"
"github.com/facebookincubator/ent/examples/o2m2types/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 {
// Create the 2 pets.
pedro, err := client.Pet.
Create().
SetName("pedro").
Save(ctx)
if err != nil {
return fmt.Errorf("creating pet: %v", err)
}
lola, err := client.Pet.
Create().
SetName("lola").
Save(ctx)
if err != nil {
return fmt.Errorf("creating pet: %v", err)
}
// Create the user, and add its pets on the creation.
a8m, err := client.User.
Create().
SetAge(30).
SetName("a8m").
AddPets(pedro, lola).
Save(ctx)
if err != nil {
return fmt.Errorf("creating user: %v", err)
}
fmt.Println("User created:", a8m)
// Output: User(id=1, age=30, name=a8m)
// Query the owner. Unlike `Only`, `OnlyX` panics if an error occurs.
owner := pedro.QueryOwner().OnlyX(ctx)
fmt.Println(owner.Name)
// Output: a8m
// Traverse the sub-graph. Unlike `Count`, `CountX` panics if an error occurs.
count := pedro.
QueryOwner(). // a8m
QueryPets(). // pedro, lola
CountX(ctx) // count
fmt.Println(count)
// Output: 2
return nil
}