mirror of
https://github.com/ent/ent.git
synced 2026-05-24 09:31:56 +03:00
ent/doc: fix getting started example and add link to Github
Reviewed By: alexsn Differential Revision: D17734937 fbshipit-source-id: abced88c23b7385d371361c5069292de5c1c5b1e
This commit is contained in:
committed by
Facebook Github Bot
parent
86c14d7a3c
commit
6d159024e7
9
examples/start/README.md
Normal file
9
examples/start/README.md
Normal file
@@ -0,0 +1,9 @@
|
||||
# Getting Started Example
|
||||
|
||||
The example from the getting-started page in https://entgo.io.
|
||||
|
||||
### Generate Assets
|
||||
|
||||
```console
|
||||
go generate ./...
|
||||
```
|
||||
102
examples/start/ent/car.go
Normal file
102
examples/start/ent/car.go
Normal file
@@ -0,0 +1,102 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/facebookincubator/ent/dialect/sql"
|
||||
)
|
||||
|
||||
// Car is the model entity for the Car schema.
|
||||
type Car struct {
|
||||
config `json:"-"`
|
||||
// ID of the ent.
|
||||
ID int `json:"id,omitempty"`
|
||||
// Model holds the value of the "model" field.
|
||||
Model string `json:"model,omitempty"`
|
||||
// RegisteredAt holds the value of the "registered_at" field.
|
||||
RegisteredAt time.Time `json:"registered_at,omitempty"`
|
||||
}
|
||||
|
||||
// FromRows scans the sql response data into Car.
|
||||
func (c *Car) FromRows(rows *sql.Rows) error {
|
||||
var vc struct {
|
||||
ID int
|
||||
Model sql.NullString
|
||||
RegisteredAt sql.NullTime
|
||||
}
|
||||
// the order here should be the same as in the `car.Columns`.
|
||||
if err := rows.Scan(
|
||||
&vc.ID,
|
||||
&vc.Model,
|
||||
&vc.RegisteredAt,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
c.ID = vc.ID
|
||||
c.Model = vc.Model.String
|
||||
c.RegisteredAt = vc.RegisteredAt.Time
|
||||
return nil
|
||||
}
|
||||
|
||||
// QueryOwner queries the owner edge of the Car.
|
||||
func (c *Car) QueryOwner() *UserQuery {
|
||||
return (&CarClient{c.config}).QueryOwner(c)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this Car.
|
||||
// Note that, you need to call Car.Unwrap() before calling this method, if this Car
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (c *Car) Update() *CarUpdateOne {
|
||||
return (&CarClient{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 *Car) Unwrap() *Car {
|
||||
tx, ok := c.config.driver.(*txDriver)
|
||||
if !ok {
|
||||
panic("ent: Car is not a transactional entity")
|
||||
}
|
||||
c.config.driver = tx.drv
|
||||
return c
|
||||
}
|
||||
|
||||
// String implements the fmt.Stringer.
|
||||
func (c *Car) String() string {
|
||||
buf := bytes.NewBuffer(nil)
|
||||
buf.WriteString("Car(")
|
||||
buf.WriteString(fmt.Sprintf("id=%v", c.ID))
|
||||
buf.WriteString(fmt.Sprintf(", model=%v", c.Model))
|
||||
buf.WriteString(fmt.Sprintf(", registered_at=%v", c.RegisteredAt))
|
||||
buf.WriteString(")")
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// Cars is a parsable slice of Car.
|
||||
type Cars []*Car
|
||||
|
||||
// FromRows scans the sql response data into Cars.
|
||||
func (c *Cars) FromRows(rows *sql.Rows) error {
|
||||
for rows.Next() {
|
||||
vc := &Car{}
|
||||
if err := vc.FromRows(rows); err != nil {
|
||||
return err
|
||||
}
|
||||
*c = append(*c, vc)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c Cars) config(cfg config) {
|
||||
for i := range c {
|
||||
c[i].config = cfg
|
||||
}
|
||||
}
|
||||
35
examples/start/ent/car/car.go
Normal file
35
examples/start/ent/car/car.go
Normal file
@@ -0,0 +1,35 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package car
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the car type in the database.
|
||||
Label = "car"
|
||||
// FieldID holds the string denoting the id field in the database.
|
||||
FieldID = "id"
|
||||
// FieldModel holds the string denoting the model vertex property in the database.
|
||||
FieldModel = "model"
|
||||
// FieldRegisteredAt holds the string denoting the registered_at vertex property in the database.
|
||||
FieldRegisteredAt = "registered_at"
|
||||
|
||||
// Table holds the table name of the car in the database.
|
||||
Table = "cars"
|
||||
// OwnerTable is the table the holds the owner relation/edge.
|
||||
OwnerTable = "cars"
|
||||
// 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 car fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldModel,
|
||||
FieldRegisteredAt,
|
||||
}
|
||||
420
examples/start/ent/car/where.go
Normal file
420
examples/start/ent/car/where.go
Normal file
@@ -0,0 +1,420 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package car
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/facebookincubator/ent/dialect/sql"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/predicate"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their identifier.
|
||||
func ID(id int) predicate.Car {
|
||||
return predicate.Car(
|
||||
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.Car {
|
||||
return predicate.Car(
|
||||
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.Car {
|
||||
return predicate.Car(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldID), id))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...int) predicate.Car {
|
||||
return predicate.Car(
|
||||
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.Car {
|
||||
return predicate.Car(
|
||||
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...))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id int) predicate.Car {
|
||||
return predicate.Car(
|
||||
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.Car {
|
||||
return predicate.Car(
|
||||
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.Car {
|
||||
return predicate.Car(
|
||||
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.Car {
|
||||
return predicate.Car(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldID), id))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// Model applies equality check predicate on the "model" field. It's identical to ModelEQ.
|
||||
func Model(v string) predicate.Car {
|
||||
return predicate.Car(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldModel), v))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// RegisteredAt applies equality check predicate on the "registered_at" field. It's identical to RegisteredAtEQ.
|
||||
func RegisteredAt(v time.Time) predicate.Car {
|
||||
return predicate.Car(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldRegisteredAt), v))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// ModelEQ applies the EQ predicate on the "model" field.
|
||||
func ModelEQ(v string) predicate.Car {
|
||||
return predicate.Car(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldModel), v))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// ModelNEQ applies the NEQ predicate on the "model" field.
|
||||
func ModelNEQ(v string) predicate.Car {
|
||||
return predicate.Car(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldModel), v))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// ModelIn applies the In predicate on the "model" field.
|
||||
func ModelIn(vs ...string) predicate.Car {
|
||||
v := make([]interface{}, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Car(
|
||||
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(FieldModel), v...))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// ModelNotIn applies the NotIn predicate on the "model" field.
|
||||
func ModelNotIn(vs ...string) predicate.Car {
|
||||
v := make([]interface{}, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Car(
|
||||
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(FieldModel), v...))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// ModelGT applies the GT predicate on the "model" field.
|
||||
func ModelGT(v string) predicate.Car {
|
||||
return predicate.Car(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldModel), v))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// ModelGTE applies the GTE predicate on the "model" field.
|
||||
func ModelGTE(v string) predicate.Car {
|
||||
return predicate.Car(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldModel), v))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// ModelLT applies the LT predicate on the "model" field.
|
||||
func ModelLT(v string) predicate.Car {
|
||||
return predicate.Car(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldModel), v))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// ModelLTE applies the LTE predicate on the "model" field.
|
||||
func ModelLTE(v string) predicate.Car {
|
||||
return predicate.Car(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldModel), v))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// ModelContains applies the Contains predicate on the "model" field.
|
||||
func ModelContains(v string) predicate.Car {
|
||||
return predicate.Car(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.Contains(s.C(FieldModel), v))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// ModelHasPrefix applies the HasPrefix predicate on the "model" field.
|
||||
func ModelHasPrefix(v string) predicate.Car {
|
||||
return predicate.Car(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.HasPrefix(s.C(FieldModel), v))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// ModelHasSuffix applies the HasSuffix predicate on the "model" field.
|
||||
func ModelHasSuffix(v string) predicate.Car {
|
||||
return predicate.Car(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.HasSuffix(s.C(FieldModel), v))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// ModelEqualFold applies the EqualFold predicate on the "model" field.
|
||||
func ModelEqualFold(v string) predicate.Car {
|
||||
return predicate.Car(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.EqualFold(s.C(FieldModel), v))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// ModelContainsFold applies the ContainsFold predicate on the "model" field.
|
||||
func ModelContainsFold(v string) predicate.Car {
|
||||
return predicate.Car(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.ContainsFold(s.C(FieldModel), v))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// RegisteredAtEQ applies the EQ predicate on the "registered_at" field.
|
||||
func RegisteredAtEQ(v time.Time) predicate.Car {
|
||||
return predicate.Car(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldRegisteredAt), v))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// RegisteredAtNEQ applies the NEQ predicate on the "registered_at" field.
|
||||
func RegisteredAtNEQ(v time.Time) predicate.Car {
|
||||
return predicate.Car(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldRegisteredAt), v))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// RegisteredAtIn applies the In predicate on the "registered_at" field.
|
||||
func RegisteredAtIn(vs ...time.Time) predicate.Car {
|
||||
v := make([]interface{}, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Car(
|
||||
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(FieldRegisteredAt), v...))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// RegisteredAtNotIn applies the NotIn predicate on the "registered_at" field.
|
||||
func RegisteredAtNotIn(vs ...time.Time) predicate.Car {
|
||||
v := make([]interface{}, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Car(
|
||||
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(FieldRegisteredAt), v...))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// RegisteredAtGT applies the GT predicate on the "registered_at" field.
|
||||
func RegisteredAtGT(v time.Time) predicate.Car {
|
||||
return predicate.Car(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldRegisteredAt), v))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// RegisteredAtGTE applies the GTE predicate on the "registered_at" field.
|
||||
func RegisteredAtGTE(v time.Time) predicate.Car {
|
||||
return predicate.Car(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldRegisteredAt), v))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// RegisteredAtLT applies the LT predicate on the "registered_at" field.
|
||||
func RegisteredAtLT(v time.Time) predicate.Car {
|
||||
return predicate.Car(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldRegisteredAt), v))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// RegisteredAtLTE applies the LTE predicate on the "registered_at" field.
|
||||
func RegisteredAtLTE(v time.Time) predicate.Car {
|
||||
return predicate.Car(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldRegisteredAt), v))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// HasOwner applies the HasEdge predicate on the "owner" edge.
|
||||
func HasOwner() predicate.Car {
|
||||
return predicate.Car(
|
||||
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.Car {
|
||||
return predicate.Car(
|
||||
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.Car) predicate.Car {
|
||||
return predicate.Car(
|
||||
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.Car) predicate.Car {
|
||||
return predicate.Car(
|
||||
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.Car) predicate.Car {
|
||||
return predicate.Car(
|
||||
func(s *sql.Selector) {
|
||||
p(s.Not())
|
||||
},
|
||||
)
|
||||
}
|
||||
125
examples/start/ent/car_create.go
Normal file
125
examples/start/ent/car_create.go
Normal file
@@ -0,0 +1,125 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/facebookincubator/ent/dialect/sql"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/car"
|
||||
)
|
||||
|
||||
// CarCreate is the builder for creating a Car entity.
|
||||
type CarCreate struct {
|
||||
config
|
||||
model *string
|
||||
registered_at *time.Time
|
||||
owner map[int]struct{}
|
||||
}
|
||||
|
||||
// SetModel sets the model field.
|
||||
func (cc *CarCreate) SetModel(s string) *CarCreate {
|
||||
cc.model = &s
|
||||
return cc
|
||||
}
|
||||
|
||||
// SetRegisteredAt sets the registered_at field.
|
||||
func (cc *CarCreate) SetRegisteredAt(t time.Time) *CarCreate {
|
||||
cc.registered_at = &t
|
||||
return cc
|
||||
}
|
||||
|
||||
// SetOwnerID sets the owner edge to User by id.
|
||||
func (cc *CarCreate) SetOwnerID(id int) *CarCreate {
|
||||
if cc.owner == nil {
|
||||
cc.owner = make(map[int]struct{})
|
||||
}
|
||||
cc.owner[id] = struct{}{}
|
||||
return cc
|
||||
}
|
||||
|
||||
// SetNillableOwnerID sets the owner edge to User by id if the given value is not nil.
|
||||
func (cc *CarCreate) SetNillableOwnerID(id *int) *CarCreate {
|
||||
if id != nil {
|
||||
cc = cc.SetOwnerID(*id)
|
||||
}
|
||||
return cc
|
||||
}
|
||||
|
||||
// SetOwner sets the owner edge to User.
|
||||
func (cc *CarCreate) SetOwner(u *User) *CarCreate {
|
||||
return cc.SetOwnerID(u.ID)
|
||||
}
|
||||
|
||||
// Save creates the Car in the database.
|
||||
func (cc *CarCreate) Save(ctx context.Context) (*Car, error) {
|
||||
if cc.model == nil {
|
||||
return nil, errors.New("ent: missing required field \"model\"")
|
||||
}
|
||||
if cc.registered_at == nil {
|
||||
return nil, errors.New("ent: missing required field \"registered_at\"")
|
||||
}
|
||||
if len(cc.owner) > 1 {
|
||||
return nil, errors.New("ent: multiple assignments on a unique edge \"owner\"")
|
||||
}
|
||||
return cc.sqlSave(ctx)
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
func (cc *CarCreate) SaveX(ctx context.Context) *Car {
|
||||
v, err := cc.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func (cc *CarCreate) sqlSave(ctx context.Context) (*Car, error) {
|
||||
var (
|
||||
res sql.Result
|
||||
c = &Car{config: cc.config}
|
||||
)
|
||||
tx, err := cc.driver.Tx(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
builder := sql.Insert(car.Table).Default(cc.driver.Dialect())
|
||||
if value := cc.model; value != nil {
|
||||
builder.Set(car.FieldModel, *value)
|
||||
c.Model = *value
|
||||
}
|
||||
if value := cc.registered_at; value != nil {
|
||||
builder.Set(car.FieldRegisteredAt, *value)
|
||||
c.RegisteredAt = *value
|
||||
}
|
||||
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 {
|
||||
for eid := range cc.owner {
|
||||
query, args := sql.Update(car.OwnerTable).
|
||||
Set(car.OwnerColumn, eid).
|
||||
Where(sql.EQ(car.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 c, nil
|
||||
}
|
||||
81
examples/start/ent/car_delete.go
Normal file
81
examples/start/ent/car_delete.go
Normal file
@@ -0,0 +1,81 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/facebookincubator/ent/dialect/sql"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/car"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/predicate"
|
||||
)
|
||||
|
||||
// CarDelete is the builder for deleting a Car entity.
|
||||
type CarDelete struct {
|
||||
config
|
||||
predicates []predicate.Car
|
||||
}
|
||||
|
||||
// Where adds a new predicate to the delete builder.
|
||||
func (cd *CarDelete) Where(ps ...predicate.Car) *CarDelete {
|
||||
cd.predicates = append(cd.predicates, ps...)
|
||||
return cd
|
||||
}
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (cd *CarDelete) Exec(ctx context.Context) (int, error) {
|
||||
return cd.sqlExec(ctx)
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (cd *CarDelete) ExecX(ctx context.Context) int {
|
||||
n, err := cd.Exec(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (cd *CarDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
var res sql.Result
|
||||
selector := sql.Select().From(sql.Table(car.Table))
|
||||
for _, p := range cd.predicates {
|
||||
p(selector)
|
||||
}
|
||||
query, args := sql.Delete(car.Table).FromSelect(selector).Query()
|
||||
if err := cd.driver.Exec(ctx, query, args, &res); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
affected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return int(affected), nil
|
||||
}
|
||||
|
||||
// CarDeleteOne is the builder for deleting a single Car entity.
|
||||
type CarDeleteOne struct {
|
||||
cd *CarDelete
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (cdo *CarDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := cdo.cd.Exec(ctx)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case n == 0:
|
||||
return &ErrNotFound{car.Label}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (cdo *CarDeleteOne) ExecX(ctx context.Context) {
|
||||
cdo.cd.ExecX(ctx)
|
||||
}
|
||||
610
examples/start/ent/car_query.go
Normal file
610
examples/start/ent/car_query.go
Normal file
@@ -0,0 +1,610 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"github.com/facebookincubator/ent/dialect/sql"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/car"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/predicate"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/user"
|
||||
)
|
||||
|
||||
// CarQuery is the builder for querying Car entities.
|
||||
type CarQuery struct {
|
||||
config
|
||||
limit *int
|
||||
offset *int
|
||||
order []Order
|
||||
unique []string
|
||||
predicates []predicate.Car
|
||||
// intermediate queries.
|
||||
sql *sql.Selector
|
||||
}
|
||||
|
||||
// Where adds a new predicate for the builder.
|
||||
func (cq *CarQuery) Where(ps ...predicate.Car) *CarQuery {
|
||||
cq.predicates = append(cq.predicates, ps...)
|
||||
return cq
|
||||
}
|
||||
|
||||
// Limit adds a limit step to the query.
|
||||
func (cq *CarQuery) Limit(limit int) *CarQuery {
|
||||
cq.limit = &limit
|
||||
return cq
|
||||
}
|
||||
|
||||
// Offset adds an offset step to the query.
|
||||
func (cq *CarQuery) Offset(offset int) *CarQuery {
|
||||
cq.offset = &offset
|
||||
return cq
|
||||
}
|
||||
|
||||
// Order adds an order step to the query.
|
||||
func (cq *CarQuery) Order(o ...Order) *CarQuery {
|
||||
cq.order = append(cq.order, o...)
|
||||
return cq
|
||||
}
|
||||
|
||||
// QueryOwner chains the current query on the owner edge.
|
||||
func (cq *CarQuery) QueryOwner() *UserQuery {
|
||||
query := &UserQuery{config: cq.config}
|
||||
t1 := sql.Table(user.Table)
|
||||
t2 := cq.sqlQuery()
|
||||
t2.Select(t2.C(car.OwnerColumn))
|
||||
query.sql = sql.Select(t1.Columns(user.Columns...)...).
|
||||
From(t1).
|
||||
Join(t2).
|
||||
On(t1.C(user.FieldID), t2.C(car.OwnerColumn))
|
||||
return query
|
||||
}
|
||||
|
||||
// First returns the first Car entity in the query. Returns *ErrNotFound when no car was found.
|
||||
func (cq *CarQuery) First(ctx context.Context) (*Car, error) {
|
||||
cs, err := cq.Limit(1).All(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(cs) == 0 {
|
||||
return nil, &ErrNotFound{car.Label}
|
||||
}
|
||||
return cs[0], nil
|
||||
}
|
||||
|
||||
// FirstX is like First, but panics if an error occurs.
|
||||
func (cq *CarQuery) FirstX(ctx context.Context) *Car {
|
||||
c, err := cq.First(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// FirstID returns the first Car id in the query. Returns *ErrNotFound when no id was found.
|
||||
func (cq *CarQuery) 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{car.Label}
|
||||
return
|
||||
}
|
||||
return ids[0], nil
|
||||
}
|
||||
|
||||
// FirstXID is like FirstID, but panics if an error occurs.
|
||||
func (cq *CarQuery) FirstXID(ctx context.Context) int {
|
||||
id, err := cq.FirstID(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Only returns the only Car entity in the query, returns an error if not exactly one entity was returned.
|
||||
func (cq *CarQuery) Only(ctx context.Context) (*Car, 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{car.Label}
|
||||
default:
|
||||
return nil, &ErrNotSingular{car.Label}
|
||||
}
|
||||
}
|
||||
|
||||
// OnlyX is like Only, but panics if an error occurs.
|
||||
func (cq *CarQuery) OnlyX(ctx context.Context) *Car {
|
||||
c, err := cq.Only(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// OnlyID returns the only Car id in the query, returns an error if not exactly one id was returned.
|
||||
func (cq *CarQuery) 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{car.Label}
|
||||
default:
|
||||
err = &ErrNotSingular{car.Label}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// OnlyXID is like OnlyID, but panics if an error occurs.
|
||||
func (cq *CarQuery) 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 Cars.
|
||||
func (cq *CarQuery) All(ctx context.Context) ([]*Car, error) {
|
||||
return cq.sqlAll(ctx)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
func (cq *CarQuery) AllX(ctx context.Context) []*Car {
|
||||
cs, err := cq.All(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return cs
|
||||
}
|
||||
|
||||
// IDs executes the query and returns a list of Car ids.
|
||||
func (cq *CarQuery) IDs(ctx context.Context) ([]int, error) {
|
||||
return cq.sqlIDs(ctx)
|
||||
}
|
||||
|
||||
// IDsX is like IDs, but panics if an error occurs.
|
||||
func (cq *CarQuery) 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 *CarQuery) Count(ctx context.Context) (int, error) {
|
||||
return cq.sqlCount(ctx)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
func (cq *CarQuery) 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 *CarQuery) Exist(ctx context.Context) (bool, error) {
|
||||
return cq.sqlExist(ctx)
|
||||
}
|
||||
|
||||
// ExistX is like Exist, but panics if an error occurs.
|
||||
func (cq *CarQuery) 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 *CarQuery) Clone() *CarQuery {
|
||||
return &CarQuery{
|
||||
config: cq.config,
|
||||
limit: cq.limit,
|
||||
offset: cq.offset,
|
||||
order: append([]Order{}, cq.order...),
|
||||
unique: append([]string{}, cq.unique...),
|
||||
predicates: append([]predicate.Car{}, 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 {
|
||||
// Model string `json:"model,omitempty"`
|
||||
// Count int `json:"count,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.Car.Query().
|
||||
// GroupBy(car.FieldModel).
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
//
|
||||
func (cq *CarQuery) GroupBy(field string, fields ...string) *CarGroupBy {
|
||||
group := &CarGroupBy{config: cq.config}
|
||||
group.fields = append([]string{field}, fields...)
|
||||
group.sql = cq.sqlQuery()
|
||||
return group
|
||||
}
|
||||
|
||||
// Select one or more fields from the given query.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// var v []struct {
|
||||
// Model string `json:"model,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.Car.Query().
|
||||
// Select(car.FieldModel).
|
||||
// Scan(ctx, &v)
|
||||
//
|
||||
func (cq *CarQuery) Select(field string, fields ...string) *CarSelect {
|
||||
selector := &CarSelect{config: cq.config}
|
||||
selector.fields = append([]string{field}, fields...)
|
||||
selector.sql = cq.sqlQuery()
|
||||
return selector
|
||||
}
|
||||
|
||||
func (cq *CarQuery) sqlAll(ctx context.Context) ([]*Car, 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 Cars
|
||||
if err := cs.FromRows(rows); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cs.config(cq.config)
|
||||
return cs, nil
|
||||
}
|
||||
|
||||
func (cq *CarQuery) sqlCount(ctx context.Context) (int, error) {
|
||||
rows := &sql.Rows{}
|
||||
selector := cq.sqlQuery()
|
||||
unique := []string{car.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 *CarQuery) 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 *CarQuery) 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 *CarQuery) sqlQuery() *sql.Selector {
|
||||
t1 := sql.Table(car.Table)
|
||||
selector := sql.Select(t1.Columns(car.Columns...)...).From(t1)
|
||||
if cq.sql != nil {
|
||||
selector = cq.sql
|
||||
selector.Select(selector.Columns(car.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
|
||||
}
|
||||
|
||||
// CarGroupBy is the builder for group-by Car entities.
|
||||
type CarGroupBy struct {
|
||||
config
|
||||
fields []string
|
||||
fns []Aggregate
|
||||
// intermediate queries.
|
||||
sql *sql.Selector
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the group-by query.
|
||||
func (cgb *CarGroupBy) Aggregate(fns ...Aggregate) *CarGroupBy {
|
||||
cgb.fns = append(cgb.fns, fns...)
|
||||
return cgb
|
||||
}
|
||||
|
||||
// Scan applies the group-by query and scan the result into the given value.
|
||||
func (cgb *CarGroupBy) Scan(ctx context.Context, v interface{}) error {
|
||||
return cgb.sqlScan(ctx, v)
|
||||
}
|
||||
|
||||
// ScanX is like Scan, but panics if an error occurs.
|
||||
func (cgb *CarGroupBy) 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 *CarGroupBy) Strings(ctx context.Context) ([]string, error) {
|
||||
if len(cgb.fields) > 1 {
|
||||
return nil, errors.New("ent: CarGroupBy.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 *CarGroupBy) 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 *CarGroupBy) Ints(ctx context.Context) ([]int, error) {
|
||||
if len(cgb.fields) > 1 {
|
||||
return nil, errors.New("ent: CarGroupBy.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 *CarGroupBy) 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 *CarGroupBy) Float64s(ctx context.Context) ([]float64, error) {
|
||||
if len(cgb.fields) > 1 {
|
||||
return nil, errors.New("ent: CarGroupBy.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 *CarGroupBy) 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 *CarGroupBy) Bools(ctx context.Context) ([]bool, error) {
|
||||
if len(cgb.fields) > 1 {
|
||||
return nil, errors.New("ent: CarGroupBy.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 *CarGroupBy) BoolsX(ctx context.Context) []bool {
|
||||
v, err := cgb.Bools(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func (cgb *CarGroupBy) 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 *CarGroupBy) 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...)
|
||||
}
|
||||
|
||||
// CarSelect is the builder for select fields of Car entities.
|
||||
type CarSelect struct {
|
||||
config
|
||||
fields []string
|
||||
// intermediate queries.
|
||||
sql *sql.Selector
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scan the result into the given value.
|
||||
func (cs *CarSelect) Scan(ctx context.Context, v interface{}) error {
|
||||
return cs.sqlScan(ctx, v)
|
||||
}
|
||||
|
||||
// ScanX is like Scan, but panics if an error occurs.
|
||||
func (cs *CarSelect) ScanX(ctx context.Context, v interface{}) {
|
||||
if err := cs.Scan(ctx, v); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Strings returns list of strings from selector. It is only allowed when selecting one field.
|
||||
func (cs *CarSelect) Strings(ctx context.Context) ([]string, error) {
|
||||
if len(cs.fields) > 1 {
|
||||
return nil, errors.New("ent: CarSelect.Strings is not achievable when selecting more than 1 field")
|
||||
}
|
||||
var v []string
|
||||
if err := cs.Scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// StringsX is like Strings, but panics if an error occurs.
|
||||
func (cs *CarSelect) StringsX(ctx context.Context) []string {
|
||||
v, err := cs.Strings(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Ints returns list of ints from selector. It is only allowed when selecting one field.
|
||||
func (cs *CarSelect) Ints(ctx context.Context) ([]int, error) {
|
||||
if len(cs.fields) > 1 {
|
||||
return nil, errors.New("ent: CarSelect.Ints is not achievable when selecting more than 1 field")
|
||||
}
|
||||
var v []int
|
||||
if err := cs.Scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// IntsX is like Ints, but panics if an error occurs.
|
||||
func (cs *CarSelect) IntsX(ctx context.Context) []int {
|
||||
v, err := cs.Ints(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Float64s returns list of float64s from selector. It is only allowed when selecting one field.
|
||||
func (cs *CarSelect) Float64s(ctx context.Context) ([]float64, error) {
|
||||
if len(cs.fields) > 1 {
|
||||
return nil, errors.New("ent: CarSelect.Float64s is not achievable when selecting more than 1 field")
|
||||
}
|
||||
var v []float64
|
||||
if err := cs.Scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// Float64sX is like Float64s, but panics if an error occurs.
|
||||
func (cs *CarSelect) Float64sX(ctx context.Context) []float64 {
|
||||
v, err := cs.Float64s(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Bools returns list of bools from selector. It is only allowed when selecting one field.
|
||||
func (cs *CarSelect) Bools(ctx context.Context) ([]bool, error) {
|
||||
if len(cs.fields) > 1 {
|
||||
return nil, errors.New("ent: CarSelect.Bools is not achievable when selecting more than 1 field")
|
||||
}
|
||||
var v []bool
|
||||
if err := cs.Scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// BoolsX is like Bools, but panics if an error occurs.
|
||||
func (cs *CarSelect) BoolsX(ctx context.Context) []bool {
|
||||
v, err := cs.Bools(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func (cs *CarSelect) sqlScan(ctx context.Context, v interface{}) error {
|
||||
rows := &sql.Rows{}
|
||||
query, args := cs.sqlQuery().Query()
|
||||
if err := cs.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
|
||||
func (cs *CarSelect) sqlQuery() sql.Querier {
|
||||
view := "car_view"
|
||||
return sql.Select(cs.fields...).From(cs.sql.As(view))
|
||||
}
|
||||
328
examples/start/ent/car_update.go
Normal file
328
examples/start/ent/car_update.go
Normal file
@@ -0,0 +1,328 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/facebookincubator/ent/dialect/sql"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/car"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/predicate"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/user"
|
||||
)
|
||||
|
||||
// CarUpdate is the builder for updating Car entities.
|
||||
type CarUpdate struct {
|
||||
config
|
||||
model *string
|
||||
registered_at *time.Time
|
||||
owner map[int]struct{}
|
||||
clearedOwner bool
|
||||
predicates []predicate.Car
|
||||
}
|
||||
|
||||
// Where adds a new predicate for the builder.
|
||||
func (cu *CarUpdate) Where(ps ...predicate.Car) *CarUpdate {
|
||||
cu.predicates = append(cu.predicates, ps...)
|
||||
return cu
|
||||
}
|
||||
|
||||
// SetModel sets the model field.
|
||||
func (cu *CarUpdate) SetModel(s string) *CarUpdate {
|
||||
cu.model = &s
|
||||
return cu
|
||||
}
|
||||
|
||||
// SetRegisteredAt sets the registered_at field.
|
||||
func (cu *CarUpdate) SetRegisteredAt(t time.Time) *CarUpdate {
|
||||
cu.registered_at = &t
|
||||
return cu
|
||||
}
|
||||
|
||||
// SetOwnerID sets the owner edge to User by id.
|
||||
func (cu *CarUpdate) SetOwnerID(id int) *CarUpdate {
|
||||
if cu.owner == nil {
|
||||
cu.owner = make(map[int]struct{})
|
||||
}
|
||||
cu.owner[id] = struct{}{}
|
||||
return cu
|
||||
}
|
||||
|
||||
// SetNillableOwnerID sets the owner edge to User by id if the given value is not nil.
|
||||
func (cu *CarUpdate) SetNillableOwnerID(id *int) *CarUpdate {
|
||||
if id != nil {
|
||||
cu = cu.SetOwnerID(*id)
|
||||
}
|
||||
return cu
|
||||
}
|
||||
|
||||
// SetOwner sets the owner edge to User.
|
||||
func (cu *CarUpdate) SetOwner(u *User) *CarUpdate {
|
||||
return cu.SetOwnerID(u.ID)
|
||||
}
|
||||
|
||||
// ClearOwner clears the owner edge to User.
|
||||
func (cu *CarUpdate) ClearOwner() *CarUpdate {
|
||||
cu.clearedOwner = true
|
||||
return cu
|
||||
}
|
||||
|
||||
// Save executes the query and returns the number of rows/vertices matched by this operation.
|
||||
func (cu *CarUpdate) Save(ctx context.Context) (int, error) {
|
||||
if len(cu.owner) > 1 {
|
||||
return 0, errors.New("ent: multiple assignments on a unique edge \"owner\"")
|
||||
}
|
||||
return cu.sqlSave(ctx)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (cu *CarUpdate) SaveX(ctx context.Context) int {
|
||||
affected, err := cu.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return affected
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (cu *CarUpdate) Exec(ctx context.Context) error {
|
||||
_, err := cu.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (cu *CarUpdate) ExecX(ctx context.Context) {
|
||||
if err := cu.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (cu *CarUpdate) sqlSave(ctx context.Context) (n int, err error) {
|
||||
selector := sql.Select(car.FieldID).From(sql.Table(car.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 (
|
||||
res sql.Result
|
||||
builder = sql.Update(car.Table).Where(sql.InInts(car.FieldID, ids...))
|
||||
)
|
||||
if value := cu.model; value != nil {
|
||||
builder.Set(car.FieldModel, *value)
|
||||
}
|
||||
if value := cu.registered_at; value != nil {
|
||||
builder.Set(car.FieldRegisteredAt, *value)
|
||||
}
|
||||
if !builder.Empty() {
|
||||
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(car.OwnerTable).
|
||||
SetNull(car.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 eid := range cu.owner {
|
||||
query, args := sql.Update(car.OwnerTable).
|
||||
Set(car.OwnerColumn, eid).
|
||||
Where(sql.InInts(car.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
|
||||
}
|
||||
|
||||
// CarUpdateOne is the builder for updating a single Car entity.
|
||||
type CarUpdateOne struct {
|
||||
config
|
||||
id int
|
||||
model *string
|
||||
registered_at *time.Time
|
||||
owner map[int]struct{}
|
||||
clearedOwner bool
|
||||
}
|
||||
|
||||
// SetModel sets the model field.
|
||||
func (cuo *CarUpdateOne) SetModel(s string) *CarUpdateOne {
|
||||
cuo.model = &s
|
||||
return cuo
|
||||
}
|
||||
|
||||
// SetRegisteredAt sets the registered_at field.
|
||||
func (cuo *CarUpdateOne) SetRegisteredAt(t time.Time) *CarUpdateOne {
|
||||
cuo.registered_at = &t
|
||||
return cuo
|
||||
}
|
||||
|
||||
// SetOwnerID sets the owner edge to User by id.
|
||||
func (cuo *CarUpdateOne) SetOwnerID(id int) *CarUpdateOne {
|
||||
if cuo.owner == nil {
|
||||
cuo.owner = make(map[int]struct{})
|
||||
}
|
||||
cuo.owner[id] = struct{}{}
|
||||
return cuo
|
||||
}
|
||||
|
||||
// SetNillableOwnerID sets the owner edge to User by id if the given value is not nil.
|
||||
func (cuo *CarUpdateOne) SetNillableOwnerID(id *int) *CarUpdateOne {
|
||||
if id != nil {
|
||||
cuo = cuo.SetOwnerID(*id)
|
||||
}
|
||||
return cuo
|
||||
}
|
||||
|
||||
// SetOwner sets the owner edge to User.
|
||||
func (cuo *CarUpdateOne) SetOwner(u *User) *CarUpdateOne {
|
||||
return cuo.SetOwnerID(u.ID)
|
||||
}
|
||||
|
||||
// ClearOwner clears the owner edge to User.
|
||||
func (cuo *CarUpdateOne) ClearOwner() *CarUpdateOne {
|
||||
cuo.clearedOwner = true
|
||||
return cuo
|
||||
}
|
||||
|
||||
// Save executes the query and returns the updated entity.
|
||||
func (cuo *CarUpdateOne) Save(ctx context.Context) (*Car, error) {
|
||||
if len(cuo.owner) > 1 {
|
||||
return nil, errors.New("ent: multiple assignments on a unique edge \"owner\"")
|
||||
}
|
||||
return cuo.sqlSave(ctx)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (cuo *CarUpdateOne) SaveX(ctx context.Context) *Car {
|
||||
c, err := cuo.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// Exec executes the query on the entity.
|
||||
func (cuo *CarUpdateOne) Exec(ctx context.Context) error {
|
||||
_, err := cuo.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (cuo *CarUpdateOne) ExecX(ctx context.Context) {
|
||||
if err := cuo.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (cuo *CarUpdateOne) sqlSave(ctx context.Context) (c *Car, err error) {
|
||||
selector := sql.Select(car.Columns...).From(sql.Table(car.Table))
|
||||
car.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 = &Car{config: cuo.config}
|
||||
if err := c.FromRows(rows); err != nil {
|
||||
return nil, fmt.Errorf("ent: failed scanning row into Car: %v", err)
|
||||
}
|
||||
id = c.ID
|
||||
ids = append(ids, id)
|
||||
}
|
||||
switch n := len(ids); {
|
||||
case n == 0:
|
||||
return nil, fmt.Errorf("ent: Car not found with id: %v", cuo.id)
|
||||
case n > 1:
|
||||
return nil, fmt.Errorf("ent: more than one Car with the same id: %v", cuo.id)
|
||||
}
|
||||
|
||||
tx, err := cuo.driver.Tx(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var (
|
||||
res sql.Result
|
||||
builder = sql.Update(car.Table).Where(sql.InInts(car.FieldID, ids...))
|
||||
)
|
||||
if value := cuo.model; value != nil {
|
||||
builder.Set(car.FieldModel, *value)
|
||||
c.Model = *value
|
||||
}
|
||||
if value := cuo.registered_at; value != nil {
|
||||
builder.Set(car.FieldRegisteredAt, *value)
|
||||
c.RegisteredAt = *value
|
||||
}
|
||||
if !builder.Empty() {
|
||||
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(car.OwnerTable).
|
||||
SetNull(car.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 eid := range cuo.owner {
|
||||
query, args := sql.Update(car.OwnerTable).
|
||||
Set(car.OwnerColumn, eid).
|
||||
Where(sql.InInts(car.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 c, nil
|
||||
}
|
||||
364
examples/start/ent/client.go
Normal file
364
examples/start/ent/client.go
Normal file
@@ -0,0 +1,364 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/facebookincubator/ent/examples/start/ent/migrate"
|
||||
|
||||
"github.com/facebookincubator/ent/examples/start/ent/car"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/group"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/user"
|
||||
|
||||
"github.com/facebookincubator/ent/dialect"
|
||||
"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
|
||||
// Car is the client for interacting with the Car builders.
|
||||
Car *CarClient
|
||||
// Group is the client for interacting with the Group builders.
|
||||
Group *GroupClient
|
||||
// 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),
|
||||
Car: NewCarClient(c),
|
||||
Group: NewGroupClient(c),
|
||||
User: NewUserClient(c),
|
||||
}
|
||||
}
|
||||
|
||||
// Open opens a connection to the database specified by the driver name and a
|
||||
// driver-specific data source name, and returns a new client attached to it.
|
||||
// Optional parameters can be added for configuring the client.
|
||||
func Open(driverName, dataSourceName string, options ...Option) (*Client, error) {
|
||||
switch driverName {
|
||||
case dialect.MySQL, dialect.SQLite:
|
||||
drv, err := sql.Open(driverName, dataSourceName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewClient(append(options, Driver(drv))...), nil
|
||||
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported driver: %q", driverName)
|
||||
}
|
||||
}
|
||||
|
||||
// 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, debug: c.debug}
|
||||
return &Tx{
|
||||
config: cfg,
|
||||
Car: NewCarClient(cfg),
|
||||
Group: NewGroupClient(cfg),
|
||||
User: NewUserClient(cfg),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
|
||||
//
|
||||
// client.Debug().
|
||||
// Car.
|
||||
// Query().
|
||||
// Count(ctx)
|
||||
//
|
||||
func (c *Client) Debug() *Client {
|
||||
if c.debug {
|
||||
return c
|
||||
}
|
||||
cfg := config{driver: dialect.Debug(c.driver, c.log), log: c.log, debug: true}
|
||||
return &Client{
|
||||
config: cfg,
|
||||
Schema: migrate.NewSchema(cfg.driver),
|
||||
Car: NewCarClient(cfg),
|
||||
Group: NewGroupClient(cfg),
|
||||
User: NewUserClient(cfg),
|
||||
}
|
||||
}
|
||||
|
||||
// Close closes the database connection and prevents new queries from starting.
|
||||
func (c *Client) Close() error {
|
||||
return c.driver.Close()
|
||||
}
|
||||
|
||||
// CarClient is a client for the Car schema.
|
||||
type CarClient struct {
|
||||
config
|
||||
}
|
||||
|
||||
// NewCarClient returns a client for the Car from the given config.
|
||||
func NewCarClient(c config) *CarClient {
|
||||
return &CarClient{config: c}
|
||||
}
|
||||
|
||||
// Create returns a create builder for Car.
|
||||
func (c *CarClient) Create() *CarCreate {
|
||||
return &CarCreate{config: c.config}
|
||||
}
|
||||
|
||||
// Update returns an update builder for Car.
|
||||
func (c *CarClient) Update() *CarUpdate {
|
||||
return &CarUpdate{config: c.config}
|
||||
}
|
||||
|
||||
// UpdateOne returns an update builder for the given entity.
|
||||
func (c *CarClient) UpdateOne(ca *Car) *CarUpdateOne {
|
||||
return c.UpdateOneID(ca.ID)
|
||||
}
|
||||
|
||||
// UpdateOneID returns an update builder for the given id.
|
||||
func (c *CarClient) UpdateOneID(id int) *CarUpdateOne {
|
||||
return &CarUpdateOne{config: c.config, id: id}
|
||||
}
|
||||
|
||||
// Delete returns a delete builder for Car.
|
||||
func (c *CarClient) Delete() *CarDelete {
|
||||
return &CarDelete{config: c.config}
|
||||
}
|
||||
|
||||
// DeleteOne returns a delete builder for the given entity.
|
||||
func (c *CarClient) DeleteOne(ca *Car) *CarDeleteOne {
|
||||
return c.DeleteOneID(ca.ID)
|
||||
}
|
||||
|
||||
// DeleteOneID returns a delete builder for the given id.
|
||||
func (c *CarClient) DeleteOneID(id int) *CarDeleteOne {
|
||||
return &CarDeleteOne{c.Delete().Where(car.ID(id))}
|
||||
}
|
||||
|
||||
// Create returns a query builder for Car.
|
||||
func (c *CarClient) Query() *CarQuery {
|
||||
return &CarQuery{config: c.config}
|
||||
}
|
||||
|
||||
// Get returns a Car entity by its id.
|
||||
func (c *CarClient) Get(ctx context.Context, id int) (*Car, error) {
|
||||
return c.Query().Where(car.ID(id)).Only(ctx)
|
||||
}
|
||||
|
||||
// GetX is like Get, but panics if an error occurs.
|
||||
func (c *CarClient) GetX(ctx context.Context, id int) *Car {
|
||||
ca, err := c.Get(ctx, id)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return ca
|
||||
}
|
||||
|
||||
// QueryOwner queries the owner edge of a Car.
|
||||
func (c *CarClient) QueryOwner(ca *Car) *UserQuery {
|
||||
query := &UserQuery{config: c.config}
|
||||
id := ca.ID
|
||||
t1 := sql.Table(user.Table)
|
||||
t2 := sql.Select(car.OwnerColumn).
|
||||
From(sql.Table(car.OwnerTable)).
|
||||
Where(sql.EQ(car.FieldID, id))
|
||||
query.sql = sql.Select().From(t1).Join(t2).On(t1.C(user.FieldID), t2.C(car.OwnerColumn))
|
||||
|
||||
return query
|
||||
}
|
||||
|
||||
// GroupClient is a client for the Group schema.
|
||||
type GroupClient struct {
|
||||
config
|
||||
}
|
||||
|
||||
// NewGroupClient returns a client for the Group from the given config.
|
||||
func NewGroupClient(c config) *GroupClient {
|
||||
return &GroupClient{config: c}
|
||||
}
|
||||
|
||||
// Create returns a create builder for Group.
|
||||
func (c *GroupClient) Create() *GroupCreate {
|
||||
return &GroupCreate{config: c.config}
|
||||
}
|
||||
|
||||
// Update returns an update builder for Group.
|
||||
func (c *GroupClient) Update() *GroupUpdate {
|
||||
return &GroupUpdate{config: c.config}
|
||||
}
|
||||
|
||||
// UpdateOne returns an update builder for the given entity.
|
||||
func (c *GroupClient) UpdateOne(gr *Group) *GroupUpdateOne {
|
||||
return c.UpdateOneID(gr.ID)
|
||||
}
|
||||
|
||||
// UpdateOneID returns an update builder for the given id.
|
||||
func (c *GroupClient) UpdateOneID(id int) *GroupUpdateOne {
|
||||
return &GroupUpdateOne{config: c.config, id: id}
|
||||
}
|
||||
|
||||
// Delete returns a delete builder for Group.
|
||||
func (c *GroupClient) Delete() *GroupDelete {
|
||||
return &GroupDelete{config: c.config}
|
||||
}
|
||||
|
||||
// DeleteOne returns a delete builder for the given entity.
|
||||
func (c *GroupClient) DeleteOne(gr *Group) *GroupDeleteOne {
|
||||
return c.DeleteOneID(gr.ID)
|
||||
}
|
||||
|
||||
// DeleteOneID returns a delete builder for the given id.
|
||||
func (c *GroupClient) DeleteOneID(id int) *GroupDeleteOne {
|
||||
return &GroupDeleteOne{c.Delete().Where(group.ID(id))}
|
||||
}
|
||||
|
||||
// Create returns a query builder for Group.
|
||||
func (c *GroupClient) Query() *GroupQuery {
|
||||
return &GroupQuery{config: c.config}
|
||||
}
|
||||
|
||||
// Get returns a Group entity by its id.
|
||||
func (c *GroupClient) Get(ctx context.Context, id int) (*Group, error) {
|
||||
return c.Query().Where(group.ID(id)).Only(ctx)
|
||||
}
|
||||
|
||||
// GetX is like Get, but panics if an error occurs.
|
||||
func (c *GroupClient) GetX(ctx context.Context, id int) *Group {
|
||||
gr, err := c.Get(ctx, id)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return gr
|
||||
}
|
||||
|
||||
// QueryUsers queries the users edge of a Group.
|
||||
func (c *GroupClient) QueryUsers(gr *Group) *UserQuery {
|
||||
query := &UserQuery{config: c.config}
|
||||
id := gr.ID
|
||||
t1 := sql.Table(user.Table)
|
||||
t2 := sql.Table(group.Table)
|
||||
t3 := sql.Table(group.UsersTable)
|
||||
t4 := sql.Select(t3.C(group.UsersPrimaryKey[1])).
|
||||
From(t3).
|
||||
Join(t2).
|
||||
On(t3.C(group.UsersPrimaryKey[0]), t2.C(group.FieldID)).
|
||||
Where(sql.EQ(t2.C(group.FieldID), id))
|
||||
query.sql = sql.Select().
|
||||
From(t1).
|
||||
Join(t4).
|
||||
On(t1.C(user.FieldID), t4.C(group.UsersPrimaryKey[1]))
|
||||
|
||||
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}
|
||||
}
|
||||
|
||||
// Get returns a User entity by its id.
|
||||
func (c *UserClient) Get(ctx context.Context, id int) (*User, error) {
|
||||
return c.Query().Where(user.ID(id)).Only(ctx)
|
||||
}
|
||||
|
||||
// GetX is like Get, but panics if an error occurs.
|
||||
func (c *UserClient) GetX(ctx context.Context, id int) *User {
|
||||
u, err := c.Get(ctx, id)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
// QueryCars queries the cars edge of a User.
|
||||
func (c *UserClient) QueryCars(u *User) *CarQuery {
|
||||
query := &CarQuery{config: c.config}
|
||||
id := u.ID
|
||||
query.sql = sql.Select().From(sql.Table(car.Table)).
|
||||
Where(sql.EQ(user.CarsColumn, id))
|
||||
|
||||
return query
|
||||
}
|
||||
|
||||
// QueryGroups queries the groups edge of a User.
|
||||
func (c *UserClient) QueryGroups(u *User) *GroupQuery {
|
||||
query := &GroupQuery{config: c.config}
|
||||
id := u.ID
|
||||
t1 := sql.Table(group.Table)
|
||||
t2 := sql.Table(user.Table)
|
||||
t3 := sql.Table(user.GroupsTable)
|
||||
t4 := sql.Select(t3.C(user.GroupsPrimaryKey[0])).
|
||||
From(t3).
|
||||
Join(t2).
|
||||
On(t3.C(user.GroupsPrimaryKey[1]), t2.C(user.FieldID)).
|
||||
Where(sql.EQ(t2.C(user.FieldID), id))
|
||||
query.sql = sql.Select().
|
||||
From(t1).
|
||||
Join(t4).
|
||||
On(t1.C(group.FieldID), t4.C(user.GroupsPrimaryKey[0]))
|
||||
|
||||
return query
|
||||
}
|
||||
55
examples/start/ent/config.go
Normal file
55
examples/start/ent/config.go
Normal file
@@ -0,0 +1,55 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// 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 used for executing database requests.
|
||||
driver dialect.Driver
|
||||
// debug enable a debug logging.
|
||||
debug bool
|
||||
// log used for logging on debug 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.debug {
|
||||
c.driver = dialect.Debug(c.driver, c.log)
|
||||
}
|
||||
}
|
||||
|
||||
// Debug enables debug logging on the ent.Driver.
|
||||
func Debug() Option {
|
||||
return func(c *config) {
|
||||
c.debug = true
|
||||
}
|
||||
}
|
||||
|
||||
// Log sets the logging function for debug mode.
|
||||
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
|
||||
}
|
||||
}
|
||||
24
examples/start/ent/context.go
Normal file
24
examples/start/ent/context.go
Normal file
@@ -0,0 +1,24 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// 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)
|
||||
}
|
||||
196
examples/start/ent/ent.go
Normal file
196
examples/start/ent/ent.go
Normal file
@@ -0,0 +1,196 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// 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
|
||||
}
|
||||
120
examples/start/ent/example_test.go
Normal file
120
examples/start/ent/example_test.go
Normal file
@@ -0,0 +1,120 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// 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 ExampleCar() {
|
||||
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 car's edges.
|
||||
|
||||
// create car vertex with its edges.
|
||||
c := client.Car.
|
||||
Create().
|
||||
SetModel("string").
|
||||
SetRegisteredAt(time.Now()).
|
||||
SaveX(ctx)
|
||||
log.Println("car created:", c)
|
||||
|
||||
// query edges.
|
||||
|
||||
// Output:
|
||||
}
|
||||
func ExampleGroup() {
|
||||
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 group's edges.
|
||||
u0 := client.User.
|
||||
Create().
|
||||
SetAge(1).
|
||||
SetName("string").
|
||||
SaveX(ctx)
|
||||
log.Println("user created:", u0)
|
||||
|
||||
// create group vertex with its edges.
|
||||
gr := client.Group.
|
||||
Create().
|
||||
SetName("string").
|
||||
AddUsers(u0).
|
||||
SaveX(ctx)
|
||||
log.Println("group created:", gr)
|
||||
|
||||
// query edges.
|
||||
u0, err = gr.QueryUsers().First(ctx)
|
||||
if err != nil {
|
||||
log.Fatalf("failed querying users: %v", err)
|
||||
}
|
||||
log.Println("users found:", u0)
|
||||
|
||||
// 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.Car.
|
||||
Create().
|
||||
SetModel("string").
|
||||
SetRegisteredAt(time.Now()).
|
||||
SaveX(ctx)
|
||||
log.Println("car created:", c0)
|
||||
|
||||
// create user vertex with its edges.
|
||||
u := client.User.
|
||||
Create().
|
||||
SetAge(1).
|
||||
SetName("string").
|
||||
AddCars(c0).
|
||||
SaveX(ctx)
|
||||
log.Println("user created:", u)
|
||||
|
||||
// query edges.
|
||||
c0, err = u.QueryCars().First(ctx)
|
||||
if err != nil {
|
||||
log.Fatalf("failed querying cars: %v", err)
|
||||
}
|
||||
log.Println("cars found:", c0)
|
||||
|
||||
// Output:
|
||||
}
|
||||
7
examples/start/ent/generate.go
Normal file
7
examples/start/ent/generate.go
Normal file
@@ -0,0 +1,7 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
package ent
|
||||
|
||||
//go:generate go run ../../../entc/cmd/entc/entc.go generate --header "Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n// This source code is licensed under the Apache 2.0 license found\n// in the LICENSE file in the root directory of this source tree.\n\n// Code generated (@generated) by entc, DO NOT EDIT." ./schema
|
||||
95
examples/start/ent/group.go
Normal file
95
examples/start/ent/group.go
Normal file
@@ -0,0 +1,95 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
|
||||
"github.com/facebookincubator/ent/dialect/sql"
|
||||
)
|
||||
|
||||
// Group is the model entity for the Group schema.
|
||||
type Group struct {
|
||||
config `json:"-"`
|
||||
// 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 Group.
|
||||
func (gr *Group) FromRows(rows *sql.Rows) error {
|
||||
var vgr struct {
|
||||
ID int
|
||||
Name sql.NullString
|
||||
}
|
||||
// the order here should be the same as in the `group.Columns`.
|
||||
if err := rows.Scan(
|
||||
&vgr.ID,
|
||||
&vgr.Name,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
gr.ID = vgr.ID
|
||||
gr.Name = vgr.Name.String
|
||||
return nil
|
||||
}
|
||||
|
||||
// QueryUsers queries the users edge of the Group.
|
||||
func (gr *Group) QueryUsers() *UserQuery {
|
||||
return (&GroupClient{gr.config}).QueryUsers(gr)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this Group.
|
||||
// Note that, you need to call Group.Unwrap() before calling this method, if this Group
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (gr *Group) Update() *GroupUpdateOne {
|
||||
return (&GroupClient{gr.config}).UpdateOne(gr)
|
||||
}
|
||||
|
||||
// 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 (gr *Group) Unwrap() *Group {
|
||||
tx, ok := gr.config.driver.(*txDriver)
|
||||
if !ok {
|
||||
panic("ent: Group is not a transactional entity")
|
||||
}
|
||||
gr.config.driver = tx.drv
|
||||
return gr
|
||||
}
|
||||
|
||||
// String implements the fmt.Stringer.
|
||||
func (gr *Group) String() string {
|
||||
buf := bytes.NewBuffer(nil)
|
||||
buf.WriteString("Group(")
|
||||
buf.WriteString(fmt.Sprintf("id=%v", gr.ID))
|
||||
buf.WriteString(fmt.Sprintf(", name=%v", gr.Name))
|
||||
buf.WriteString(")")
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// Groups is a parsable slice of Group.
|
||||
type Groups []*Group
|
||||
|
||||
// FromRows scans the sql response data into Groups.
|
||||
func (gr *Groups) FromRows(rows *sql.Rows) error {
|
||||
for rows.Next() {
|
||||
vgr := &Group{}
|
||||
if err := vgr.FromRows(rows); err != nil {
|
||||
return err
|
||||
}
|
||||
*gr = append(*gr, vgr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (gr Groups) config(cfg config) {
|
||||
for i := range gr {
|
||||
gr[i].config = cfg
|
||||
}
|
||||
}
|
||||
49
examples/start/ent/group/group.go
Normal file
49
examples/start/ent/group/group.go
Normal file
@@ -0,0 +1,49 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package group
|
||||
|
||||
import (
|
||||
"github.com/facebookincubator/ent/examples/start/ent/schema"
|
||||
)
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the group type in the database.
|
||||
Label = "group"
|
||||
// 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 group in the database.
|
||||
Table = "groups"
|
||||
// UsersTable is the table the holds the users relation/edge. The primary key declared below.
|
||||
UsersTable = "group_users"
|
||||
// UsersInverseTable is the table name for the User entity.
|
||||
// It exists in this package in order to avoid circular dependency with the "user" package.
|
||||
UsersInverseTable = "users"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns are group fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldName,
|
||||
}
|
||||
|
||||
var (
|
||||
// UsersPrimaryKey and UsersColumn2 are the table columns denoting the
|
||||
// primary key for the users relation (M2M).
|
||||
UsersPrimaryKey = []string{"group_id", "user_id"}
|
||||
)
|
||||
|
||||
var (
|
||||
fields = schema.Group{}.Fields()
|
||||
|
||||
// descName is the schema descriptor for name field.
|
||||
descName = fields[0].Descriptor()
|
||||
// NameValidator is a validator for the "name" field. It is called by the builders before save.
|
||||
NameValidator = descName.Validators[0].(func(string) error)
|
||||
)
|
||||
329
examples/start/ent/group/where.go
Normal file
329
examples/start/ent/group/where.go
Normal file
@@ -0,0 +1,329 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package group
|
||||
|
||||
import (
|
||||
"github.com/facebookincubator/ent/dialect/sql"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/predicate"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their identifier.
|
||||
func ID(id int) predicate.Group {
|
||||
return predicate.Group(
|
||||
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.Group {
|
||||
return predicate.Group(
|
||||
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.Group {
|
||||
return predicate.Group(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldID), id))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...int) predicate.Group {
|
||||
return predicate.Group(
|
||||
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.Group {
|
||||
return predicate.Group(
|
||||
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...))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id int) predicate.Group {
|
||||
return predicate.Group(
|
||||
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.Group {
|
||||
return predicate.Group(
|
||||
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.Group {
|
||||
return predicate.Group(
|
||||
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.Group {
|
||||
return predicate.Group(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldID), id))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
|
||||
func Name(v string) predicate.Group {
|
||||
return predicate.Group(
|
||||
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.Group {
|
||||
return predicate.Group(
|
||||
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.Group {
|
||||
return predicate.Group(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldName), v))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// NameIn applies the In predicate on the "name" field.
|
||||
func NameIn(vs ...string) predicate.Group {
|
||||
v := make([]interface{}, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Group(
|
||||
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.Group {
|
||||
v := make([]interface{}, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Group(
|
||||
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...))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// NameGT applies the GT predicate on the "name" field.
|
||||
func NameGT(v string) predicate.Group {
|
||||
return predicate.Group(
|
||||
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.Group {
|
||||
return predicate.Group(
|
||||
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.Group {
|
||||
return predicate.Group(
|
||||
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.Group {
|
||||
return predicate.Group(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldName), v))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// NameContains applies the Contains predicate on the "name" field.
|
||||
func NameContains(v string) predicate.Group {
|
||||
return predicate.Group(
|
||||
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.Group {
|
||||
return predicate.Group(
|
||||
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.Group {
|
||||
return predicate.Group(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.HasSuffix(s.C(FieldName), v))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// NameEqualFold applies the EqualFold predicate on the "name" field.
|
||||
func NameEqualFold(v string) predicate.Group {
|
||||
return predicate.Group(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.EqualFold(s.C(FieldName), v))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// NameContainsFold applies the ContainsFold predicate on the "name" field.
|
||||
func NameContainsFold(v string) predicate.Group {
|
||||
return predicate.Group(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.ContainsFold(s.C(FieldName), v))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// HasUsers applies the HasEdge predicate on the "users" edge.
|
||||
func HasUsers() predicate.Group {
|
||||
return predicate.Group(
|
||||
func(s *sql.Selector) {
|
||||
t1 := s.Table()
|
||||
s.Where(
|
||||
sql.In(
|
||||
t1.C(FieldID),
|
||||
sql.Select(UsersPrimaryKey[0]).From(sql.Table(UsersTable)),
|
||||
),
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// HasUsersWith applies the HasEdge predicate on the "users" edge with a given conditions (other predicates).
|
||||
func HasUsersWith(preds ...predicate.User) predicate.Group {
|
||||
return predicate.Group(
|
||||
func(s *sql.Selector) {
|
||||
t1 := s.Table()
|
||||
t2 := sql.Table(UsersInverseTable)
|
||||
t3 := sql.Table(UsersTable)
|
||||
t4 := sql.Select(t3.C(UsersPrimaryKey[0])).
|
||||
From(t3).
|
||||
Join(t2).
|
||||
On(t3.C(UsersPrimaryKey[1]), t2.C(FieldID))
|
||||
t5 := sql.Select().From(t2)
|
||||
for _, p := range preds {
|
||||
p(t5)
|
||||
}
|
||||
t4.FromSelect(t5)
|
||||
s.Where(sql.In(t1.C(FieldID), t4))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// And groups list of predicates with the AND operator between them.
|
||||
func And(predicates ...predicate.Group) predicate.Group {
|
||||
return predicate.Group(
|
||||
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.Group) predicate.Group {
|
||||
return predicate.Group(
|
||||
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.Group) predicate.Group {
|
||||
return predicate.Group(
|
||||
func(s *sql.Selector) {
|
||||
p(s.Not())
|
||||
},
|
||||
)
|
||||
}
|
||||
110
examples/start/ent/group_create.go
Normal file
110
examples/start/ent/group_create.go
Normal file
@@ -0,0 +1,110 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/facebookincubator/ent/dialect/sql"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/group"
|
||||
)
|
||||
|
||||
// GroupCreate is the builder for creating a Group entity.
|
||||
type GroupCreate struct {
|
||||
config
|
||||
name *string
|
||||
users map[int]struct{}
|
||||
}
|
||||
|
||||
// SetName sets the name field.
|
||||
func (gc *GroupCreate) SetName(s string) *GroupCreate {
|
||||
gc.name = &s
|
||||
return gc
|
||||
}
|
||||
|
||||
// AddUserIDs adds the users edge to User by ids.
|
||||
func (gc *GroupCreate) AddUserIDs(ids ...int) *GroupCreate {
|
||||
if gc.users == nil {
|
||||
gc.users = make(map[int]struct{})
|
||||
}
|
||||
for i := range ids {
|
||||
gc.users[ids[i]] = struct{}{}
|
||||
}
|
||||
return gc
|
||||
}
|
||||
|
||||
// AddUsers adds the users edges to User.
|
||||
func (gc *GroupCreate) AddUsers(u ...*User) *GroupCreate {
|
||||
ids := make([]int, len(u))
|
||||
for i := range u {
|
||||
ids[i] = u[i].ID
|
||||
}
|
||||
return gc.AddUserIDs(ids...)
|
||||
}
|
||||
|
||||
// Save creates the Group in the database.
|
||||
func (gc *GroupCreate) Save(ctx context.Context) (*Group, error) {
|
||||
if gc.name == nil {
|
||||
return nil, errors.New("ent: missing required field \"name\"")
|
||||
}
|
||||
if err := group.NameValidator(*gc.name); err != nil {
|
||||
return nil, fmt.Errorf("ent: validator failed for field \"name\": %v", err)
|
||||
}
|
||||
return gc.sqlSave(ctx)
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
func (gc *GroupCreate) SaveX(ctx context.Context) *Group {
|
||||
v, err := gc.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func (gc *GroupCreate) sqlSave(ctx context.Context) (*Group, error) {
|
||||
var (
|
||||
res sql.Result
|
||||
gr = &Group{config: gc.config}
|
||||
)
|
||||
tx, err := gc.driver.Tx(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
builder := sql.Insert(group.Table).Default(gc.driver.Dialect())
|
||||
if value := gc.name; value != nil {
|
||||
builder.Set(group.FieldName, *value)
|
||||
gr.Name = *value
|
||||
}
|
||||
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)
|
||||
}
|
||||
gr.ID = int(id)
|
||||
if len(gc.users) > 0 {
|
||||
for eid := range gc.users {
|
||||
|
||||
query, args := sql.Insert(group.UsersTable).
|
||||
Columns(group.UsersPrimaryKey[0], group.UsersPrimaryKey[1]).
|
||||
Values(id, eid).
|
||||
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 gr, nil
|
||||
}
|
||||
81
examples/start/ent/group_delete.go
Normal file
81
examples/start/ent/group_delete.go
Normal file
@@ -0,0 +1,81 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/facebookincubator/ent/dialect/sql"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/group"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/predicate"
|
||||
)
|
||||
|
||||
// GroupDelete is the builder for deleting a Group entity.
|
||||
type GroupDelete struct {
|
||||
config
|
||||
predicates []predicate.Group
|
||||
}
|
||||
|
||||
// Where adds a new predicate to the delete builder.
|
||||
func (gd *GroupDelete) Where(ps ...predicate.Group) *GroupDelete {
|
||||
gd.predicates = append(gd.predicates, ps...)
|
||||
return gd
|
||||
}
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (gd *GroupDelete) Exec(ctx context.Context) (int, error) {
|
||||
return gd.sqlExec(ctx)
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (gd *GroupDelete) ExecX(ctx context.Context) int {
|
||||
n, err := gd.Exec(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (gd *GroupDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
var res sql.Result
|
||||
selector := sql.Select().From(sql.Table(group.Table))
|
||||
for _, p := range gd.predicates {
|
||||
p(selector)
|
||||
}
|
||||
query, args := sql.Delete(group.Table).FromSelect(selector).Query()
|
||||
if err := gd.driver.Exec(ctx, query, args, &res); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
affected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return int(affected), nil
|
||||
}
|
||||
|
||||
// GroupDeleteOne is the builder for deleting a single Group entity.
|
||||
type GroupDeleteOne struct {
|
||||
gd *GroupDelete
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (gdo *GroupDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := gdo.gd.Exec(ctx)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case n == 0:
|
||||
return &ErrNotFound{group.Label}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (gdo *GroupDeleteOne) ExecX(ctx context.Context) {
|
||||
gdo.gd.ExecX(ctx)
|
||||
}
|
||||
615
examples/start/ent/group_query.go
Normal file
615
examples/start/ent/group_query.go
Normal file
@@ -0,0 +1,615 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"github.com/facebookincubator/ent/dialect/sql"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/group"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/predicate"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/user"
|
||||
)
|
||||
|
||||
// GroupQuery is the builder for querying Group entities.
|
||||
type GroupQuery struct {
|
||||
config
|
||||
limit *int
|
||||
offset *int
|
||||
order []Order
|
||||
unique []string
|
||||
predicates []predicate.Group
|
||||
// intermediate queries.
|
||||
sql *sql.Selector
|
||||
}
|
||||
|
||||
// Where adds a new predicate for the builder.
|
||||
func (gq *GroupQuery) Where(ps ...predicate.Group) *GroupQuery {
|
||||
gq.predicates = append(gq.predicates, ps...)
|
||||
return gq
|
||||
}
|
||||
|
||||
// Limit adds a limit step to the query.
|
||||
func (gq *GroupQuery) Limit(limit int) *GroupQuery {
|
||||
gq.limit = &limit
|
||||
return gq
|
||||
}
|
||||
|
||||
// Offset adds an offset step to the query.
|
||||
func (gq *GroupQuery) Offset(offset int) *GroupQuery {
|
||||
gq.offset = &offset
|
||||
return gq
|
||||
}
|
||||
|
||||
// Order adds an order step to the query.
|
||||
func (gq *GroupQuery) Order(o ...Order) *GroupQuery {
|
||||
gq.order = append(gq.order, o...)
|
||||
return gq
|
||||
}
|
||||
|
||||
// QueryUsers chains the current query on the users edge.
|
||||
func (gq *GroupQuery) QueryUsers() *UserQuery {
|
||||
query := &UserQuery{config: gq.config}
|
||||
t1 := sql.Table(user.Table)
|
||||
t2 := gq.sqlQuery()
|
||||
t2.Select(t2.C(group.FieldID))
|
||||
t3 := sql.Table(group.UsersTable)
|
||||
t4 := sql.Select(t3.C(group.UsersPrimaryKey[1])).
|
||||
From(t3).
|
||||
Join(t2).
|
||||
On(t3.C(group.UsersPrimaryKey[0]), t2.C(group.FieldID))
|
||||
query.sql = sql.Select().
|
||||
From(t1).
|
||||
Join(t4).
|
||||
On(t1.C(user.FieldID), t4.C(group.UsersPrimaryKey[1]))
|
||||
return query
|
||||
}
|
||||
|
||||
// First returns the first Group entity in the query. Returns *ErrNotFound when no group was found.
|
||||
func (gq *GroupQuery) First(ctx context.Context) (*Group, error) {
|
||||
grs, err := gq.Limit(1).All(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(grs) == 0 {
|
||||
return nil, &ErrNotFound{group.Label}
|
||||
}
|
||||
return grs[0], nil
|
||||
}
|
||||
|
||||
// FirstX is like First, but panics if an error occurs.
|
||||
func (gq *GroupQuery) FirstX(ctx context.Context) *Group {
|
||||
gr, err := gq.First(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return gr
|
||||
}
|
||||
|
||||
// FirstID returns the first Group id in the query. Returns *ErrNotFound when no id was found.
|
||||
func (gq *GroupQuery) FirstID(ctx context.Context) (id int, err error) {
|
||||
var ids []int
|
||||
if ids, err = gq.Limit(1).IDs(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
err = &ErrNotFound{group.Label}
|
||||
return
|
||||
}
|
||||
return ids[0], nil
|
||||
}
|
||||
|
||||
// FirstXID is like FirstID, but panics if an error occurs.
|
||||
func (gq *GroupQuery) FirstXID(ctx context.Context) int {
|
||||
id, err := gq.FirstID(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Only returns the only Group entity in the query, returns an error if not exactly one entity was returned.
|
||||
func (gq *GroupQuery) Only(ctx context.Context) (*Group, error) {
|
||||
grs, err := gq.Limit(2).All(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch len(grs) {
|
||||
case 1:
|
||||
return grs[0], nil
|
||||
case 0:
|
||||
return nil, &ErrNotFound{group.Label}
|
||||
default:
|
||||
return nil, &ErrNotSingular{group.Label}
|
||||
}
|
||||
}
|
||||
|
||||
// OnlyX is like Only, but panics if an error occurs.
|
||||
func (gq *GroupQuery) OnlyX(ctx context.Context) *Group {
|
||||
gr, err := gq.Only(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return gr
|
||||
}
|
||||
|
||||
// OnlyID returns the only Group id in the query, returns an error if not exactly one id was returned.
|
||||
func (gq *GroupQuery) OnlyID(ctx context.Context) (id int, err error) {
|
||||
var ids []int
|
||||
if ids, err = gq.Limit(2).IDs(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(ids) {
|
||||
case 1:
|
||||
id = ids[0]
|
||||
case 0:
|
||||
err = &ErrNotFound{group.Label}
|
||||
default:
|
||||
err = &ErrNotSingular{group.Label}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// OnlyXID is like OnlyID, but panics if an error occurs.
|
||||
func (gq *GroupQuery) OnlyXID(ctx context.Context) int {
|
||||
id, err := gq.OnlyID(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// All executes the query and returns a list of Groups.
|
||||
func (gq *GroupQuery) All(ctx context.Context) ([]*Group, error) {
|
||||
return gq.sqlAll(ctx)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
func (gq *GroupQuery) AllX(ctx context.Context) []*Group {
|
||||
grs, err := gq.All(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return grs
|
||||
}
|
||||
|
||||
// IDs executes the query and returns a list of Group ids.
|
||||
func (gq *GroupQuery) IDs(ctx context.Context) ([]int, error) {
|
||||
return gq.sqlIDs(ctx)
|
||||
}
|
||||
|
||||
// IDsX is like IDs, but panics if an error occurs.
|
||||
func (gq *GroupQuery) IDsX(ctx context.Context) []int {
|
||||
ids, err := gq.IDs(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// Count returns the count of the given query.
|
||||
func (gq *GroupQuery) Count(ctx context.Context) (int, error) {
|
||||
return gq.sqlCount(ctx)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
func (gq *GroupQuery) CountX(ctx context.Context) int {
|
||||
count, err := gq.Count(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// Exist returns true if the query has elements in the graph.
|
||||
func (gq *GroupQuery) Exist(ctx context.Context) (bool, error) {
|
||||
return gq.sqlExist(ctx)
|
||||
}
|
||||
|
||||
// ExistX is like Exist, but panics if an error occurs.
|
||||
func (gq *GroupQuery) ExistX(ctx context.Context) bool {
|
||||
exist, err := gq.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 (gq *GroupQuery) Clone() *GroupQuery {
|
||||
return &GroupQuery{
|
||||
config: gq.config,
|
||||
limit: gq.limit,
|
||||
offset: gq.offset,
|
||||
order: append([]Order{}, gq.order...),
|
||||
unique: append([]string{}, gq.unique...),
|
||||
predicates: append([]predicate.Group{}, gq.predicates...),
|
||||
// clone intermediate queries.
|
||||
sql: gq.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.Group.Query().
|
||||
// GroupBy(group.FieldName).
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
//
|
||||
func (gq *GroupQuery) GroupBy(field string, fields ...string) *GroupGroupBy {
|
||||
group := &GroupGroupBy{config: gq.config}
|
||||
group.fields = append([]string{field}, fields...)
|
||||
group.sql = gq.sqlQuery()
|
||||
return group
|
||||
}
|
||||
|
||||
// Select one or more fields from the given query.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// var v []struct {
|
||||
// Name string `json:"name,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.Group.Query().
|
||||
// Select(group.FieldName).
|
||||
// Scan(ctx, &v)
|
||||
//
|
||||
func (gq *GroupQuery) Select(field string, fields ...string) *GroupSelect {
|
||||
selector := &GroupSelect{config: gq.config}
|
||||
selector.fields = append([]string{field}, fields...)
|
||||
selector.sql = gq.sqlQuery()
|
||||
return selector
|
||||
}
|
||||
|
||||
func (gq *GroupQuery) sqlAll(ctx context.Context) ([]*Group, error) {
|
||||
rows := &sql.Rows{}
|
||||
selector := gq.sqlQuery()
|
||||
if unique := gq.unique; len(unique) == 0 {
|
||||
selector.Distinct()
|
||||
}
|
||||
query, args := selector.Query()
|
||||
if err := gq.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var grs Groups
|
||||
if err := grs.FromRows(rows); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
grs.config(gq.config)
|
||||
return grs, nil
|
||||
}
|
||||
|
||||
func (gq *GroupQuery) sqlCount(ctx context.Context) (int, error) {
|
||||
rows := &sql.Rows{}
|
||||
selector := gq.sqlQuery()
|
||||
unique := []string{group.FieldID}
|
||||
if len(gq.unique) > 0 {
|
||||
unique = gq.unique
|
||||
}
|
||||
selector.Count(sql.Distinct(selector.Columns(unique...)...))
|
||||
query, args := selector.Query()
|
||||
if err := gq.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 (gq *GroupQuery) sqlExist(ctx context.Context) (bool, error) {
|
||||
n, err := gq.sqlCount(ctx)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("ent: check existence: %v", err)
|
||||
}
|
||||
return n > 0, nil
|
||||
}
|
||||
|
||||
func (gq *GroupQuery) sqlIDs(ctx context.Context) ([]int, error) {
|
||||
vs, err := gq.sqlAll(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var ids []int
|
||||
for _, v := range vs {
|
||||
ids = append(ids, v.ID)
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
func (gq *GroupQuery) sqlQuery() *sql.Selector {
|
||||
t1 := sql.Table(group.Table)
|
||||
selector := sql.Select(t1.Columns(group.Columns...)...).From(t1)
|
||||
if gq.sql != nil {
|
||||
selector = gq.sql
|
||||
selector.Select(selector.Columns(group.Columns...)...)
|
||||
}
|
||||
for _, p := range gq.predicates {
|
||||
p(selector)
|
||||
}
|
||||
for _, p := range gq.order {
|
||||
p(selector)
|
||||
}
|
||||
if offset := gq.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 := gq.limit; limit != nil {
|
||||
selector.Limit(*limit)
|
||||
}
|
||||
return selector
|
||||
}
|
||||
|
||||
// GroupGroupBy is the builder for group-by Group entities.
|
||||
type GroupGroupBy struct {
|
||||
config
|
||||
fields []string
|
||||
fns []Aggregate
|
||||
// intermediate queries.
|
||||
sql *sql.Selector
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the group-by query.
|
||||
func (ggb *GroupGroupBy) Aggregate(fns ...Aggregate) *GroupGroupBy {
|
||||
ggb.fns = append(ggb.fns, fns...)
|
||||
return ggb
|
||||
}
|
||||
|
||||
// Scan applies the group-by query and scan the result into the given value.
|
||||
func (ggb *GroupGroupBy) Scan(ctx context.Context, v interface{}) error {
|
||||
return ggb.sqlScan(ctx, v)
|
||||
}
|
||||
|
||||
// ScanX is like Scan, but panics if an error occurs.
|
||||
func (ggb *GroupGroupBy) ScanX(ctx context.Context, v interface{}) {
|
||||
if err := ggb.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 (ggb *GroupGroupBy) Strings(ctx context.Context) ([]string, error) {
|
||||
if len(ggb.fields) > 1 {
|
||||
return nil, errors.New("ent: GroupGroupBy.Strings is not achievable when grouping more than 1 field")
|
||||
}
|
||||
var v []string
|
||||
if err := ggb.Scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// StringsX is like Strings, but panics if an error occurs.
|
||||
func (ggb *GroupGroupBy) StringsX(ctx context.Context) []string {
|
||||
v, err := ggb.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 (ggb *GroupGroupBy) Ints(ctx context.Context) ([]int, error) {
|
||||
if len(ggb.fields) > 1 {
|
||||
return nil, errors.New("ent: GroupGroupBy.Ints is not achievable when grouping more than 1 field")
|
||||
}
|
||||
var v []int
|
||||
if err := ggb.Scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// IntsX is like Ints, but panics if an error occurs.
|
||||
func (ggb *GroupGroupBy) IntsX(ctx context.Context) []int {
|
||||
v, err := ggb.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 (ggb *GroupGroupBy) Float64s(ctx context.Context) ([]float64, error) {
|
||||
if len(ggb.fields) > 1 {
|
||||
return nil, errors.New("ent: GroupGroupBy.Float64s is not achievable when grouping more than 1 field")
|
||||
}
|
||||
var v []float64
|
||||
if err := ggb.Scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// Float64sX is like Float64s, but panics if an error occurs.
|
||||
func (ggb *GroupGroupBy) Float64sX(ctx context.Context) []float64 {
|
||||
v, err := ggb.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 (ggb *GroupGroupBy) Bools(ctx context.Context) ([]bool, error) {
|
||||
if len(ggb.fields) > 1 {
|
||||
return nil, errors.New("ent: GroupGroupBy.Bools is not achievable when grouping more than 1 field")
|
||||
}
|
||||
var v []bool
|
||||
if err := ggb.Scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// BoolsX is like Bools, but panics if an error occurs.
|
||||
func (ggb *GroupGroupBy) BoolsX(ctx context.Context) []bool {
|
||||
v, err := ggb.Bools(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func (ggb *GroupGroupBy) sqlScan(ctx context.Context, v interface{}) error {
|
||||
rows := &sql.Rows{}
|
||||
query, args := ggb.sqlQuery().Query()
|
||||
if err := ggb.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
|
||||
func (ggb *GroupGroupBy) sqlQuery() *sql.Selector {
|
||||
selector := ggb.sql
|
||||
columns := make([]string, 0, len(ggb.fields)+len(ggb.fns))
|
||||
columns = append(columns, ggb.fields...)
|
||||
for _, fn := range ggb.fns {
|
||||
columns = append(columns, fn.SQL(selector))
|
||||
}
|
||||
return selector.Select(columns...).GroupBy(ggb.fields...)
|
||||
}
|
||||
|
||||
// GroupSelect is the builder for select fields of Group entities.
|
||||
type GroupSelect struct {
|
||||
config
|
||||
fields []string
|
||||
// intermediate queries.
|
||||
sql *sql.Selector
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scan the result into the given value.
|
||||
func (gs *GroupSelect) Scan(ctx context.Context, v interface{}) error {
|
||||
return gs.sqlScan(ctx, v)
|
||||
}
|
||||
|
||||
// ScanX is like Scan, but panics if an error occurs.
|
||||
func (gs *GroupSelect) ScanX(ctx context.Context, v interface{}) {
|
||||
if err := gs.Scan(ctx, v); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Strings returns list of strings from selector. It is only allowed when selecting one field.
|
||||
func (gs *GroupSelect) Strings(ctx context.Context) ([]string, error) {
|
||||
if len(gs.fields) > 1 {
|
||||
return nil, errors.New("ent: GroupSelect.Strings is not achievable when selecting more than 1 field")
|
||||
}
|
||||
var v []string
|
||||
if err := gs.Scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// StringsX is like Strings, but panics if an error occurs.
|
||||
func (gs *GroupSelect) StringsX(ctx context.Context) []string {
|
||||
v, err := gs.Strings(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Ints returns list of ints from selector. It is only allowed when selecting one field.
|
||||
func (gs *GroupSelect) Ints(ctx context.Context) ([]int, error) {
|
||||
if len(gs.fields) > 1 {
|
||||
return nil, errors.New("ent: GroupSelect.Ints is not achievable when selecting more than 1 field")
|
||||
}
|
||||
var v []int
|
||||
if err := gs.Scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// IntsX is like Ints, but panics if an error occurs.
|
||||
func (gs *GroupSelect) IntsX(ctx context.Context) []int {
|
||||
v, err := gs.Ints(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Float64s returns list of float64s from selector. It is only allowed when selecting one field.
|
||||
func (gs *GroupSelect) Float64s(ctx context.Context) ([]float64, error) {
|
||||
if len(gs.fields) > 1 {
|
||||
return nil, errors.New("ent: GroupSelect.Float64s is not achievable when selecting more than 1 field")
|
||||
}
|
||||
var v []float64
|
||||
if err := gs.Scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// Float64sX is like Float64s, but panics if an error occurs.
|
||||
func (gs *GroupSelect) Float64sX(ctx context.Context) []float64 {
|
||||
v, err := gs.Float64s(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Bools returns list of bools from selector. It is only allowed when selecting one field.
|
||||
func (gs *GroupSelect) Bools(ctx context.Context) ([]bool, error) {
|
||||
if len(gs.fields) > 1 {
|
||||
return nil, errors.New("ent: GroupSelect.Bools is not achievable when selecting more than 1 field")
|
||||
}
|
||||
var v []bool
|
||||
if err := gs.Scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// BoolsX is like Bools, but panics if an error occurs.
|
||||
func (gs *GroupSelect) BoolsX(ctx context.Context) []bool {
|
||||
v, err := gs.Bools(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func (gs *GroupSelect) sqlScan(ctx context.Context, v interface{}) error {
|
||||
rows := &sql.Rows{}
|
||||
query, args := gs.sqlQuery().Query()
|
||||
if err := gs.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
|
||||
func (gs *GroupSelect) sqlQuery() sql.Querier {
|
||||
view := "group_view"
|
||||
return sql.Select(gs.fields...).From(gs.sql.As(view))
|
||||
}
|
||||
352
examples/start/ent/group_update.go
Normal file
352
examples/start/ent/group_update.go
Normal file
@@ -0,0 +1,352 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/facebookincubator/ent/dialect/sql"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/group"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/predicate"
|
||||
)
|
||||
|
||||
// GroupUpdate is the builder for updating Group entities.
|
||||
type GroupUpdate struct {
|
||||
config
|
||||
name *string
|
||||
users map[int]struct{}
|
||||
removedUsers map[int]struct{}
|
||||
predicates []predicate.Group
|
||||
}
|
||||
|
||||
// Where adds a new predicate for the builder.
|
||||
func (gu *GroupUpdate) Where(ps ...predicate.Group) *GroupUpdate {
|
||||
gu.predicates = append(gu.predicates, ps...)
|
||||
return gu
|
||||
}
|
||||
|
||||
// SetName sets the name field.
|
||||
func (gu *GroupUpdate) SetName(s string) *GroupUpdate {
|
||||
gu.name = &s
|
||||
return gu
|
||||
}
|
||||
|
||||
// AddUserIDs adds the users edge to User by ids.
|
||||
func (gu *GroupUpdate) AddUserIDs(ids ...int) *GroupUpdate {
|
||||
if gu.users == nil {
|
||||
gu.users = make(map[int]struct{})
|
||||
}
|
||||
for i := range ids {
|
||||
gu.users[ids[i]] = struct{}{}
|
||||
}
|
||||
return gu
|
||||
}
|
||||
|
||||
// AddUsers adds the users edges to User.
|
||||
func (gu *GroupUpdate) AddUsers(u ...*User) *GroupUpdate {
|
||||
ids := make([]int, len(u))
|
||||
for i := range u {
|
||||
ids[i] = u[i].ID
|
||||
}
|
||||
return gu.AddUserIDs(ids...)
|
||||
}
|
||||
|
||||
// RemoveUserIDs removes the users edge to User by ids.
|
||||
func (gu *GroupUpdate) RemoveUserIDs(ids ...int) *GroupUpdate {
|
||||
if gu.removedUsers == nil {
|
||||
gu.removedUsers = make(map[int]struct{})
|
||||
}
|
||||
for i := range ids {
|
||||
gu.removedUsers[ids[i]] = struct{}{}
|
||||
}
|
||||
return gu
|
||||
}
|
||||
|
||||
// RemoveUsers removes users edges to User.
|
||||
func (gu *GroupUpdate) RemoveUsers(u ...*User) *GroupUpdate {
|
||||
ids := make([]int, len(u))
|
||||
for i := range u {
|
||||
ids[i] = u[i].ID
|
||||
}
|
||||
return gu.RemoveUserIDs(ids...)
|
||||
}
|
||||
|
||||
// Save executes the query and returns the number of rows/vertices matched by this operation.
|
||||
func (gu *GroupUpdate) Save(ctx context.Context) (int, error) {
|
||||
if gu.name != nil {
|
||||
if err := group.NameValidator(*gu.name); err != nil {
|
||||
return 0, fmt.Errorf("ent: validator failed for field \"name\": %v", err)
|
||||
}
|
||||
}
|
||||
return gu.sqlSave(ctx)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (gu *GroupUpdate) SaveX(ctx context.Context) int {
|
||||
affected, err := gu.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return affected
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (gu *GroupUpdate) Exec(ctx context.Context) error {
|
||||
_, err := gu.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (gu *GroupUpdate) ExecX(ctx context.Context) {
|
||||
if err := gu.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (gu *GroupUpdate) sqlSave(ctx context.Context) (n int, err error) {
|
||||
selector := sql.Select(group.FieldID).From(sql.Table(group.Table))
|
||||
for _, p := range gu.predicates {
|
||||
p(selector)
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err = gu.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 := gu.driver.Tx(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var (
|
||||
res sql.Result
|
||||
builder = sql.Update(group.Table).Where(sql.InInts(group.FieldID, ids...))
|
||||
)
|
||||
if value := gu.name; value != nil {
|
||||
builder.Set(group.FieldName, *value)
|
||||
}
|
||||
if !builder.Empty() {
|
||||
query, args := builder.Query()
|
||||
if err := tx.Exec(ctx, query, args, &res); err != nil {
|
||||
return 0, rollback(tx, err)
|
||||
}
|
||||
}
|
||||
if len(gu.removedUsers) > 0 {
|
||||
eids := make([]int, len(gu.removedUsers))
|
||||
for eid := range gu.removedUsers {
|
||||
eids = append(eids, eid)
|
||||
}
|
||||
query, args := sql.Delete(group.UsersTable).
|
||||
Where(sql.InInts(group.UsersPrimaryKey[0], ids...)).
|
||||
Where(sql.InInts(group.UsersPrimaryKey[1], eids...)).
|
||||
Query()
|
||||
if err := tx.Exec(ctx, query, args, &res); err != nil {
|
||||
return 0, rollback(tx, err)
|
||||
}
|
||||
}
|
||||
if len(gu.users) > 0 {
|
||||
values := make([][]int, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
for eid := range gu.users {
|
||||
values = append(values, []int{id, eid})
|
||||
}
|
||||
}
|
||||
builder := sql.Insert(group.UsersTable).
|
||||
Columns(group.UsersPrimaryKey[0], group.UsersPrimaryKey[1])
|
||||
for _, v := range values {
|
||||
builder.Values(v[0], v[1])
|
||||
}
|
||||
query, args := builder.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
|
||||
}
|
||||
|
||||
// GroupUpdateOne is the builder for updating a single Group entity.
|
||||
type GroupUpdateOne struct {
|
||||
config
|
||||
id int
|
||||
name *string
|
||||
users map[int]struct{}
|
||||
removedUsers map[int]struct{}
|
||||
}
|
||||
|
||||
// SetName sets the name field.
|
||||
func (guo *GroupUpdateOne) SetName(s string) *GroupUpdateOne {
|
||||
guo.name = &s
|
||||
return guo
|
||||
}
|
||||
|
||||
// AddUserIDs adds the users edge to User by ids.
|
||||
func (guo *GroupUpdateOne) AddUserIDs(ids ...int) *GroupUpdateOne {
|
||||
if guo.users == nil {
|
||||
guo.users = make(map[int]struct{})
|
||||
}
|
||||
for i := range ids {
|
||||
guo.users[ids[i]] = struct{}{}
|
||||
}
|
||||
return guo
|
||||
}
|
||||
|
||||
// AddUsers adds the users edges to User.
|
||||
func (guo *GroupUpdateOne) AddUsers(u ...*User) *GroupUpdateOne {
|
||||
ids := make([]int, len(u))
|
||||
for i := range u {
|
||||
ids[i] = u[i].ID
|
||||
}
|
||||
return guo.AddUserIDs(ids...)
|
||||
}
|
||||
|
||||
// RemoveUserIDs removes the users edge to User by ids.
|
||||
func (guo *GroupUpdateOne) RemoveUserIDs(ids ...int) *GroupUpdateOne {
|
||||
if guo.removedUsers == nil {
|
||||
guo.removedUsers = make(map[int]struct{})
|
||||
}
|
||||
for i := range ids {
|
||||
guo.removedUsers[ids[i]] = struct{}{}
|
||||
}
|
||||
return guo
|
||||
}
|
||||
|
||||
// RemoveUsers removes users edges to User.
|
||||
func (guo *GroupUpdateOne) RemoveUsers(u ...*User) *GroupUpdateOne {
|
||||
ids := make([]int, len(u))
|
||||
for i := range u {
|
||||
ids[i] = u[i].ID
|
||||
}
|
||||
return guo.RemoveUserIDs(ids...)
|
||||
}
|
||||
|
||||
// Save executes the query and returns the updated entity.
|
||||
func (guo *GroupUpdateOne) Save(ctx context.Context) (*Group, error) {
|
||||
if guo.name != nil {
|
||||
if err := group.NameValidator(*guo.name); err != nil {
|
||||
return nil, fmt.Errorf("ent: validator failed for field \"name\": %v", err)
|
||||
}
|
||||
}
|
||||
return guo.sqlSave(ctx)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (guo *GroupUpdateOne) SaveX(ctx context.Context) *Group {
|
||||
gr, err := guo.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return gr
|
||||
}
|
||||
|
||||
// Exec executes the query on the entity.
|
||||
func (guo *GroupUpdateOne) Exec(ctx context.Context) error {
|
||||
_, err := guo.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (guo *GroupUpdateOne) ExecX(ctx context.Context) {
|
||||
if err := guo.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (guo *GroupUpdateOne) sqlSave(ctx context.Context) (gr *Group, err error) {
|
||||
selector := sql.Select(group.Columns...).From(sql.Table(group.Table))
|
||||
group.ID(guo.id)(selector)
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err = guo.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var ids []int
|
||||
for rows.Next() {
|
||||
var id int
|
||||
gr = &Group{config: guo.config}
|
||||
if err := gr.FromRows(rows); err != nil {
|
||||
return nil, fmt.Errorf("ent: failed scanning row into Group: %v", err)
|
||||
}
|
||||
id = gr.ID
|
||||
ids = append(ids, id)
|
||||
}
|
||||
switch n := len(ids); {
|
||||
case n == 0:
|
||||
return nil, fmt.Errorf("ent: Group not found with id: %v", guo.id)
|
||||
case n > 1:
|
||||
return nil, fmt.Errorf("ent: more than one Group with the same id: %v", guo.id)
|
||||
}
|
||||
|
||||
tx, err := guo.driver.Tx(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var (
|
||||
res sql.Result
|
||||
builder = sql.Update(group.Table).Where(sql.InInts(group.FieldID, ids...))
|
||||
)
|
||||
if value := guo.name; value != nil {
|
||||
builder.Set(group.FieldName, *value)
|
||||
gr.Name = *value
|
||||
}
|
||||
if !builder.Empty() {
|
||||
query, args := builder.Query()
|
||||
if err := tx.Exec(ctx, query, args, &res); err != nil {
|
||||
return nil, rollback(tx, err)
|
||||
}
|
||||
}
|
||||
if len(guo.removedUsers) > 0 {
|
||||
eids := make([]int, len(guo.removedUsers))
|
||||
for eid := range guo.removedUsers {
|
||||
eids = append(eids, eid)
|
||||
}
|
||||
query, args := sql.Delete(group.UsersTable).
|
||||
Where(sql.InInts(group.UsersPrimaryKey[0], ids...)).
|
||||
Where(sql.InInts(group.UsersPrimaryKey[1], eids...)).
|
||||
Query()
|
||||
if err := tx.Exec(ctx, query, args, &res); err != nil {
|
||||
return nil, rollback(tx, err)
|
||||
}
|
||||
}
|
||||
if len(guo.users) > 0 {
|
||||
values := make([][]int, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
for eid := range guo.users {
|
||||
values = append(values, []int{id, eid})
|
||||
}
|
||||
}
|
||||
builder := sql.Insert(group.UsersTable).
|
||||
Columns(group.UsersPrimaryKey[0], group.UsersPrimaryKey[1])
|
||||
for _, v := range values {
|
||||
builder.Values(v[0], v[1])
|
||||
}
|
||||
query, args := builder.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 gr, nil
|
||||
}
|
||||
71
examples/start/ent/migrate/migrate.go
Normal file
71
examples/start/ent/migrate/migrate.go
Normal file
@@ -0,0 +1,71 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package migrate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"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...)
|
||||
}
|
||||
|
||||
// WriteTo writes the schema changes to w instead of running them against the database.
|
||||
//
|
||||
// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil {
|
||||
// log.Fatal(err)
|
||||
// }
|
||||
//
|
||||
func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error {
|
||||
drv := &schema.WriteDriver{
|
||||
Writer: w,
|
||||
Driver: s.drv,
|
||||
}
|
||||
migrate, err := schema.NewMigrate(drv, opts...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ent/migrate: %v", err)
|
||||
}
|
||||
return migrate.Create(ctx, Tables...)
|
||||
}
|
||||
104
examples/start/ent/migrate/schema.go
Normal file
104
examples/start/ent/migrate/schema.go
Normal file
@@ -0,0 +1,104 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package migrate
|
||||
|
||||
import (
|
||||
"github.com/facebookincubator/ent/examples/start/ent/user"
|
||||
|
||||
"github.com/facebookincubator/ent/dialect/sql/schema"
|
||||
"github.com/facebookincubator/ent/schema/field"
|
||||
)
|
||||
|
||||
var (
|
||||
// CarsColumns holds the columns for the "cars" table.
|
||||
CarsColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeInt, Increment: true},
|
||||
{Name: "model", Type: field.TypeString},
|
||||
{Name: "registered_at", Type: field.TypeTime},
|
||||
{Name: "owner_id", Type: field.TypeInt, Nullable: true},
|
||||
}
|
||||
// CarsTable holds the schema information for the "cars" table.
|
||||
CarsTable = &schema.Table{
|
||||
Name: "cars",
|
||||
Columns: CarsColumns,
|
||||
PrimaryKey: []*schema.Column{CarsColumns[0]},
|
||||
ForeignKeys: []*schema.ForeignKey{
|
||||
{
|
||||
Symbol: "cars_users_cars",
|
||||
Columns: []*schema.Column{CarsColumns[3]},
|
||||
|
||||
RefColumns: []*schema.Column{UsersColumns[0]},
|
||||
OnDelete: schema.SetNull,
|
||||
},
|
||||
},
|
||||
}
|
||||
// GroupsColumns holds the columns for the "groups" table.
|
||||
GroupsColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeInt, Increment: true},
|
||||
{Name: "name", Type: field.TypeString},
|
||||
}
|
||||
// GroupsTable holds the schema information for the "groups" table.
|
||||
GroupsTable = &schema.Table{
|
||||
Name: "groups",
|
||||
Columns: GroupsColumns,
|
||||
PrimaryKey: []*schema.Column{GroupsColumns[0]},
|
||||
ForeignKeys: []*schema.ForeignKey{},
|
||||
}
|
||||
// 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, Default: user.DefaultName},
|
||||
}
|
||||
// UsersTable holds the schema information for the "users" table.
|
||||
UsersTable = &schema.Table{
|
||||
Name: "users",
|
||||
Columns: UsersColumns,
|
||||
PrimaryKey: []*schema.Column{UsersColumns[0]},
|
||||
ForeignKeys: []*schema.ForeignKey{},
|
||||
}
|
||||
// GroupUsersColumns holds the columns for the "group_users" table.
|
||||
GroupUsersColumns = []*schema.Column{
|
||||
{Name: "group_id", Type: field.TypeInt},
|
||||
{Name: "user_id", Type: field.TypeInt},
|
||||
}
|
||||
// GroupUsersTable holds the schema information for the "group_users" table.
|
||||
GroupUsersTable = &schema.Table{
|
||||
Name: "group_users",
|
||||
Columns: GroupUsersColumns,
|
||||
PrimaryKey: []*schema.Column{GroupUsersColumns[0], GroupUsersColumns[1]},
|
||||
ForeignKeys: []*schema.ForeignKey{
|
||||
{
|
||||
Symbol: "group_users_group_id",
|
||||
Columns: []*schema.Column{GroupUsersColumns[0]},
|
||||
|
||||
RefColumns: []*schema.Column{GroupsColumns[0]},
|
||||
OnDelete: schema.Cascade,
|
||||
},
|
||||
{
|
||||
Symbol: "group_users_user_id",
|
||||
Columns: []*schema.Column{GroupUsersColumns[1]},
|
||||
|
||||
RefColumns: []*schema.Column{UsersColumns[0]},
|
||||
OnDelete: schema.Cascade,
|
||||
},
|
||||
},
|
||||
}
|
||||
// Tables holds all the tables in the schema.
|
||||
Tables = []*schema.Table{
|
||||
CarsTable,
|
||||
GroupsTable,
|
||||
UsersTable,
|
||||
GroupUsersTable,
|
||||
}
|
||||
)
|
||||
|
||||
func init() {
|
||||
CarsTable.ForeignKeys[0].RefTable = UsersTable
|
||||
GroupUsersTable.ForeignKeys[0].RefTable = GroupsTable
|
||||
GroupUsersTable.ForeignKeys[1].RefTable = UsersTable
|
||||
}
|
||||
20
examples/start/ent/predicate/predicate.go
Normal file
20
examples/start/ent/predicate/predicate.go
Normal file
@@ -0,0 +1,20 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package predicate
|
||||
|
||||
import (
|
||||
"github.com/facebookincubator/ent/dialect/sql"
|
||||
)
|
||||
|
||||
// Car is the predicate function for car builders.
|
||||
type Car func(*sql.Selector)
|
||||
|
||||
// Group is the predicate function for group builders.
|
||||
type Group func(*sql.Selector)
|
||||
|
||||
// User is the predicate function for user builders.
|
||||
type User func(*sql.Selector)
|
||||
34
examples/start/ent/schema/car.go
Normal file
34
examples/start/ent/schema/car.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package schema
|
||||
|
||||
import (
|
||||
"github.com/facebookincubator/ent"
|
||||
"github.com/facebookincubator/ent/schema/edge"
|
||||
"github.com/facebookincubator/ent/schema/field"
|
||||
)
|
||||
|
||||
// Car holds the schema definition for the Car entity.
|
||||
type Car struct {
|
||||
ent.Schema
|
||||
}
|
||||
|
||||
// Fields of the Car.
|
||||
func (Car) Fields() []ent.Field {
|
||||
return []ent.Field{
|
||||
field.String("model"),
|
||||
field.Time("registered_at"),
|
||||
}
|
||||
}
|
||||
|
||||
// Edges of the Car.
|
||||
func (Car) Edges() []ent.Edge {
|
||||
return []ent.Edge{
|
||||
// create an inverse-edge called "owner" of type `User`
|
||||
// and reference it to the "cars" edge (in User schema)
|
||||
// explicitly using the `Ref` method.
|
||||
edge.From("owner", User.Type).
|
||||
Ref("cars").
|
||||
// setting the edge to unique, ensure
|
||||
// that a car can have only one owner.
|
||||
Unique(),
|
||||
}
|
||||
}
|
||||
31
examples/start/ent/schema/group.go
Normal file
31
examples/start/ent/schema/group.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package schema
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
|
||||
"github.com/facebookincubator/ent"
|
||||
"github.com/facebookincubator/ent/schema/edge"
|
||||
"github.com/facebookincubator/ent/schema/field"
|
||||
)
|
||||
|
||||
// Group holds the schema definition for the Group entity.
|
||||
type Group struct {
|
||||
ent.Schema
|
||||
}
|
||||
|
||||
// Fields of the Group.
|
||||
// Fields of the Group.
|
||||
func (Group) Fields() []ent.Field {
|
||||
return []ent.Field{
|
||||
field.String("name").
|
||||
// regexp validation for group name.
|
||||
Match(regexp.MustCompile("[a-zA-Z_]+$")),
|
||||
}
|
||||
}
|
||||
|
||||
// Edges of the Group.
|
||||
func (Group) Edges() []ent.Edge {
|
||||
return []ent.Edge{
|
||||
edge.To("users", User.Type),
|
||||
}
|
||||
}
|
||||
34
examples/start/ent/schema/user.go
Normal file
34
examples/start/ent/schema/user.go
Normal file
@@ -0,0 +1,34 @@
|
||||
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").
|
||||
Positive(),
|
||||
field.String("name").
|
||||
Default("unknown"),
|
||||
}
|
||||
}
|
||||
|
||||
// Edges of the User.
|
||||
func (User) Edges() []ent.Edge {
|
||||
return []ent.Edge{
|
||||
edge.To("cars", Car.Type),
|
||||
// create an inverse-edge called "groups" of type `Group`
|
||||
// and reference it to the "users" edge (in Group schema)
|
||||
// explicitly using the `Ref` method.
|
||||
edge.From("groups", Group.Type).
|
||||
Ref("users"),
|
||||
}
|
||||
}
|
||||
103
examples/start/ent/tx.go
Normal file
103
examples/start/ent/tx.go
Normal file
@@ -0,0 +1,103 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/facebookincubator/ent/dialect"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/migrate"
|
||||
)
|
||||
|
||||
// Tx is a transactional client that is created by calling Client.Tx().
|
||||
type Tx struct {
|
||||
config
|
||||
// Car is the client for interacting with the Car builders.
|
||||
Car *CarClient
|
||||
// Group is the client for interacting with the Group builders.
|
||||
Group *GroupClient
|
||||
// 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),
|
||||
Car: NewCarClient(tx.config),
|
||||
Group: NewGroupClient(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: Car.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)
|
||||
106
examples/start/ent/user.go
Normal file
106
examples/start/ent/user.go
Normal file
@@ -0,0 +1,106 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// 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 `json:"-"`
|
||||
// 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
|
||||
}
|
||||
|
||||
// QueryCars queries the cars edge of the User.
|
||||
func (u *User) QueryCars() *CarQuery {
|
||||
return (&UserClient{u.config}).QueryCars(u)
|
||||
}
|
||||
|
||||
// QueryGroups queries the groups edge of the User.
|
||||
func (u *User) QueryGroups() *GroupQuery {
|
||||
return (&UserClient{u.config}).QueryGroups(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
|
||||
}
|
||||
}
|
||||
64
examples/start/ent/user/user.go
Normal file
64
examples/start/ent/user/user.go
Normal file
@@ -0,0 +1,64 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package user
|
||||
|
||||
import (
|
||||
"github.com/facebookincubator/ent/examples/start/ent/schema"
|
||||
)
|
||||
|
||||
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"
|
||||
// CarsTable is the table the holds the cars relation/edge.
|
||||
CarsTable = "cars"
|
||||
// CarsInverseTable is the table name for the Car entity.
|
||||
// It exists in this package in order to avoid circular dependency with the "car" package.
|
||||
CarsInverseTable = "cars"
|
||||
// CarsColumn is the table column denoting the cars relation/edge.
|
||||
CarsColumn = "owner_id"
|
||||
// GroupsTable is the table the holds the groups relation/edge. The primary key declared below.
|
||||
GroupsTable = "group_users"
|
||||
// GroupsInverseTable is the table name for the Group entity.
|
||||
// It exists in this package in order to avoid circular dependency with the "group" package.
|
||||
GroupsInverseTable = "groups"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns are user fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldAge,
|
||||
FieldName,
|
||||
}
|
||||
|
||||
var (
|
||||
// GroupsPrimaryKey and GroupsColumn2 are the table columns denoting the
|
||||
// primary key for the groups relation (M2M).
|
||||
GroupsPrimaryKey = []string{"group_id", "user_id"}
|
||||
)
|
||||
|
||||
var (
|
||||
fields = schema.User{}.Fields()
|
||||
|
||||
// descAge is the schema descriptor for age field.
|
||||
descAge = fields[0].Descriptor()
|
||||
// AgeValidator is a validator for the "age" field. It is called by the builders before save.
|
||||
AgeValidator = descAge.Validators[0].(func(int) error)
|
||||
|
||||
// descName is the schema descriptor for name field.
|
||||
descName = fields[1].Descriptor()
|
||||
// DefaultName holds the default value on creation for the name field.
|
||||
DefaultName = descName.Default.(string)
|
||||
)
|
||||
461
examples/start/ent/user/where.go
Normal file
461
examples/start/ent/user/where.go
Normal file
@@ -0,0 +1,461 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package user
|
||||
|
||||
import (
|
||||
"github.com/facebookincubator/ent/dialect/sql"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/predicate"
|
||||
)
|
||||
|
||||
// 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))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// 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...))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// 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))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// 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))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// 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...))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// 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))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// 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))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// 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...))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// 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))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// 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))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// NameEqualFold applies the EqualFold predicate on the "name" field.
|
||||
func NameEqualFold(v string) predicate.User {
|
||||
return predicate.User(
|
||||
func(s *sql.Selector) {
|
||||
s.Where(sql.EqualFold(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))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// HasCars applies the HasEdge predicate on the "cars" edge.
|
||||
func HasCars() predicate.User {
|
||||
return predicate.User(
|
||||
func(s *sql.Selector) {
|
||||
t1 := s.Table()
|
||||
s.Where(
|
||||
sql.In(
|
||||
t1.C(FieldID),
|
||||
sql.Select(CarsColumn).
|
||||
From(sql.Table(CarsTable)).
|
||||
Where(sql.NotNull(CarsColumn)),
|
||||
),
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// HasCarsWith applies the HasEdge predicate on the "cars" edge with a given conditions (other predicates).
|
||||
func HasCarsWith(preds ...predicate.Car) predicate.User {
|
||||
return predicate.User(
|
||||
func(s *sql.Selector) {
|
||||
t1 := s.Table()
|
||||
t2 := sql.Select(CarsColumn).From(sql.Table(CarsTable))
|
||||
for _, p := range preds {
|
||||
p(t2)
|
||||
}
|
||||
s.Where(sql.In(t1.C(FieldID), t2))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// HasGroups applies the HasEdge predicate on the "groups" edge.
|
||||
func HasGroups() predicate.User {
|
||||
return predicate.User(
|
||||
func(s *sql.Selector) {
|
||||
t1 := s.Table()
|
||||
s.Where(
|
||||
sql.In(
|
||||
t1.C(FieldID),
|
||||
sql.Select(GroupsPrimaryKey[1]).From(sql.Table(GroupsTable)),
|
||||
),
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// HasGroupsWith applies the HasEdge predicate on the "groups" edge with a given conditions (other predicates).
|
||||
func HasGroupsWith(preds ...predicate.Group) predicate.User {
|
||||
return predicate.User(
|
||||
func(s *sql.Selector) {
|
||||
t1 := s.Table()
|
||||
t2 := sql.Table(GroupsInverseTable)
|
||||
t3 := sql.Table(GroupsTable)
|
||||
t4 := sql.Select(t3.C(GroupsPrimaryKey[1])).
|
||||
From(t3).
|
||||
Join(t2).
|
||||
On(t3.C(GroupsPrimaryKey[0]), t2.C(FieldID))
|
||||
t5 := sql.Select().From(t2)
|
||||
for _, p := range preds {
|
||||
p(t5)
|
||||
}
|
||||
t4.FromSelect(t5)
|
||||
s.Where(sql.In(t1.C(FieldID), t4))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// 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())
|
||||
},
|
||||
)
|
||||
}
|
||||
175
examples/start/ent/user_create.go
Normal file
175
examples/start/ent/user_create.go
Normal file
@@ -0,0 +1,175 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/facebookincubator/ent/dialect/sql"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/car"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/user"
|
||||
)
|
||||
|
||||
// UserCreate is the builder for creating a User entity.
|
||||
type UserCreate struct {
|
||||
config
|
||||
age *int
|
||||
name *string
|
||||
cars map[int]struct{}
|
||||
groups 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
|
||||
}
|
||||
|
||||
// SetNillableName sets the name field if the given value is not nil.
|
||||
func (uc *UserCreate) SetNillableName(s *string) *UserCreate {
|
||||
if s != nil {
|
||||
uc.SetName(*s)
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// AddCarIDs adds the cars edge to Car by ids.
|
||||
func (uc *UserCreate) AddCarIDs(ids ...int) *UserCreate {
|
||||
if uc.cars == nil {
|
||||
uc.cars = make(map[int]struct{})
|
||||
}
|
||||
for i := range ids {
|
||||
uc.cars[ids[i]] = struct{}{}
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// AddCars adds the cars edges to Car.
|
||||
func (uc *UserCreate) AddCars(c ...*Car) *UserCreate {
|
||||
ids := make([]int, len(c))
|
||||
for i := range c {
|
||||
ids[i] = c[i].ID
|
||||
}
|
||||
return uc.AddCarIDs(ids...)
|
||||
}
|
||||
|
||||
// AddGroupIDs adds the groups edge to Group by ids.
|
||||
func (uc *UserCreate) AddGroupIDs(ids ...int) *UserCreate {
|
||||
if uc.groups == nil {
|
||||
uc.groups = make(map[int]struct{})
|
||||
}
|
||||
for i := range ids {
|
||||
uc.groups[ids[i]] = struct{}{}
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// AddGroups adds the groups edges to Group.
|
||||
func (uc *UserCreate) AddGroups(g ...*Group) *UserCreate {
|
||||
ids := make([]int, len(g))
|
||||
for i := range g {
|
||||
ids[i] = g[i].ID
|
||||
}
|
||||
return uc.AddGroupIDs(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 err := user.AgeValidator(*uc.age); err != nil {
|
||||
return nil, fmt.Errorf("ent: validator failed for field \"age\": %v", err)
|
||||
}
|
||||
if uc.name == nil {
|
||||
v := user.DefaultName
|
||||
uc.name = &v
|
||||
}
|
||||
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 value := uc.age; value != nil {
|
||||
builder.Set(user.FieldAge, *value)
|
||||
u.Age = *value
|
||||
}
|
||||
if value := uc.name; value != nil {
|
||||
builder.Set(user.FieldName, *value)
|
||||
u.Name = *value
|
||||
}
|
||||
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.cars) > 0 {
|
||||
p := sql.P()
|
||||
for eid := range uc.cars {
|
||||
p.Or().EQ(car.FieldID, eid)
|
||||
}
|
||||
query, args := sql.Update(user.CarsTable).
|
||||
Set(user.CarsColumn, id).
|
||||
Where(sql.And(p, sql.IsNull(user.CarsColumn))).
|
||||
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.cars) {
|
||||
return nil, rollback(tx, &ErrConstraintFailed{msg: fmt.Sprintf("one of \"cars\" %v already connected to a different \"User\"", keys(uc.cars))})
|
||||
}
|
||||
}
|
||||
if len(uc.groups) > 0 {
|
||||
for eid := range uc.groups {
|
||||
|
||||
query, args := sql.Insert(user.GroupsTable).
|
||||
Columns(user.GroupsPrimaryKey[1], user.GroupsPrimaryKey[0]).
|
||||
Values(id, eid).
|
||||
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 u, nil
|
||||
}
|
||||
81
examples/start/ent/user_delete.go
Normal file
81
examples/start/ent/user_delete.go
Normal file
@@ -0,0 +1,81 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/facebookincubator/ent/dialect/sql"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/predicate"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/user"
|
||||
)
|
||||
|
||||
// UserDelete is the builder for deleting a User entity.
|
||||
type UserDelete struct {
|
||||
config
|
||||
predicates []predicate.User
|
||||
}
|
||||
|
||||
// Where adds a new predicate to the delete builder.
|
||||
func (ud *UserDelete) Where(ps ...predicate.User) *UserDelete {
|
||||
ud.predicates = append(ud.predicates, ps...)
|
||||
return ud
|
||||
}
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (ud *UserDelete) Exec(ctx context.Context) (int, error) {
|
||||
return ud.sqlExec(ctx)
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (ud *UserDelete) ExecX(ctx context.Context) int {
|
||||
n, err := ud.Exec(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (ud *UserDelete) sqlExec(ctx context.Context) (int, 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()
|
||||
if err := ud.driver.Exec(ctx, query, args, &res); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
affected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return int(affected), nil
|
||||
}
|
||||
|
||||
// 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 {
|
||||
n, err := udo.ud.Exec(ctx)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case n == 0:
|
||||
return &ErrNotFound{user.Label}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (udo *UserDeleteOne) ExecX(ctx context.Context) {
|
||||
udo.ud.ExecX(ctx)
|
||||
}
|
||||
629
examples/start/ent/user_query.go
Normal file
629
examples/start/ent/user_query.go
Normal file
@@ -0,0 +1,629 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"github.com/facebookincubator/ent/dialect/sql"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/car"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/group"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/predicate"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/user"
|
||||
)
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// QueryCars chains the current query on the cars edge.
|
||||
func (uq *UserQuery) QueryCars() *CarQuery {
|
||||
query := &CarQuery{config: uq.config}
|
||||
t1 := sql.Table(car.Table)
|
||||
t2 := uq.sqlQuery()
|
||||
t2.Select(t2.C(user.FieldID))
|
||||
query.sql = sql.Select().
|
||||
From(t1).
|
||||
Join(t2).
|
||||
On(t1.C(user.CarsColumn), t2.C(user.FieldID))
|
||||
return query
|
||||
}
|
||||
|
||||
// QueryGroups chains the current query on the groups edge.
|
||||
func (uq *UserQuery) QueryGroups() *GroupQuery {
|
||||
query := &GroupQuery{config: uq.config}
|
||||
t1 := sql.Table(group.Table)
|
||||
t2 := uq.sqlQuery()
|
||||
t2.Select(t2.C(user.FieldID))
|
||||
t3 := sql.Table(user.GroupsTable)
|
||||
t4 := sql.Select(t3.C(user.GroupsPrimaryKey[0])).
|
||||
From(t3).
|
||||
Join(t2).
|
||||
On(t3.C(user.GroupsPrimaryKey[1]), t2.C(user.FieldID))
|
||||
query.sql = sql.Select().
|
||||
From(t1).
|
||||
Join(t4).
|
||||
On(t1.C(group.FieldID), t4.C(user.GroupsPrimaryKey[0]))
|
||||
return query
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// Select one or more fields from the given query.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// var v []struct {
|
||||
// Age int `json:"age,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.User.Query().
|
||||
// Select(user.FieldAge).
|
||||
// Scan(ctx, &v)
|
||||
//
|
||||
func (uq *UserQuery) Select(field string, fields ...string) *UserSelect {
|
||||
selector := &UserSelect{config: uq.config}
|
||||
selector.fields = append([]string{field}, fields...)
|
||||
selector.sql = uq.sqlQuery()
|
||||
return selector
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// UserGroupBy 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...)
|
||||
}
|
||||
|
||||
// UserSelect is the builder for select fields of User entities.
|
||||
type UserSelect struct {
|
||||
config
|
||||
fields []string
|
||||
// intermediate queries.
|
||||
sql *sql.Selector
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scan the result into the given value.
|
||||
func (us *UserSelect) Scan(ctx context.Context, v interface{}) error {
|
||||
return us.sqlScan(ctx, v)
|
||||
}
|
||||
|
||||
// ScanX is like Scan, but panics if an error occurs.
|
||||
func (us *UserSelect) ScanX(ctx context.Context, v interface{}) {
|
||||
if err := us.Scan(ctx, v); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Strings returns list of strings from selector. It is only allowed when selecting one field.
|
||||
func (us *UserSelect) Strings(ctx context.Context) ([]string, error) {
|
||||
if len(us.fields) > 1 {
|
||||
return nil, errors.New("ent: UserSelect.Strings is not achievable when selecting more than 1 field")
|
||||
}
|
||||
var v []string
|
||||
if err := us.Scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// StringsX is like Strings, but panics if an error occurs.
|
||||
func (us *UserSelect) StringsX(ctx context.Context) []string {
|
||||
v, err := us.Strings(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Ints returns list of ints from selector. It is only allowed when selecting one field.
|
||||
func (us *UserSelect) Ints(ctx context.Context) ([]int, error) {
|
||||
if len(us.fields) > 1 {
|
||||
return nil, errors.New("ent: UserSelect.Ints is not achievable when selecting more than 1 field")
|
||||
}
|
||||
var v []int
|
||||
if err := us.Scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// IntsX is like Ints, but panics if an error occurs.
|
||||
func (us *UserSelect) IntsX(ctx context.Context) []int {
|
||||
v, err := us.Ints(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Float64s returns list of float64s from selector. It is only allowed when selecting one field.
|
||||
func (us *UserSelect) Float64s(ctx context.Context) ([]float64, error) {
|
||||
if len(us.fields) > 1 {
|
||||
return nil, errors.New("ent: UserSelect.Float64s is not achievable when selecting more than 1 field")
|
||||
}
|
||||
var v []float64
|
||||
if err := us.Scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// Float64sX is like Float64s, but panics if an error occurs.
|
||||
func (us *UserSelect) Float64sX(ctx context.Context) []float64 {
|
||||
v, err := us.Float64s(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Bools returns list of bools from selector. It is only allowed when selecting one field.
|
||||
func (us *UserSelect) Bools(ctx context.Context) ([]bool, error) {
|
||||
if len(us.fields) > 1 {
|
||||
return nil, errors.New("ent: UserSelect.Bools is not achievable when selecting more than 1 field")
|
||||
}
|
||||
var v []bool
|
||||
if err := us.Scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// BoolsX is like Bools, but panics if an error occurs.
|
||||
func (us *UserSelect) BoolsX(ctx context.Context) []bool {
|
||||
v, err := us.Bools(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func (us *UserSelect) sqlScan(ctx context.Context, v interface{}) error {
|
||||
rows := &sql.Rows{}
|
||||
query, args := us.sqlQuery().Query()
|
||||
if err := us.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
|
||||
func (us *UserSelect) sqlQuery() sql.Querier {
|
||||
view := "user_view"
|
||||
return sql.Select(us.fields...).From(us.sql.As(view))
|
||||
}
|
||||
577
examples/start/ent/user_update.go
Normal file
577
examples/start/ent/user_update.go
Normal file
@@ -0,0 +1,577 @@
|
||||
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated (@generated) by entc, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/facebookincubator/ent/dialect/sql"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/car"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/predicate"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/user"
|
||||
)
|
||||
|
||||
// UserUpdate is the builder for updating User entities.
|
||||
type UserUpdate struct {
|
||||
config
|
||||
age *int
|
||||
addage *int
|
||||
name *string
|
||||
cars map[int]struct{}
|
||||
groups map[int]struct{}
|
||||
removedCars map[int]struct{}
|
||||
removedGroups 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
|
||||
uu.addage = nil
|
||||
return uu
|
||||
}
|
||||
|
||||
// AddAge adds i to age.
|
||||
func (uu *UserUpdate) AddAge(i int) *UserUpdate {
|
||||
if uu.addage == nil {
|
||||
uu.addage = &i
|
||||
} else {
|
||||
*uu.addage += i
|
||||
}
|
||||
return uu
|
||||
}
|
||||
|
||||
// SetName sets the name field.
|
||||
func (uu *UserUpdate) SetName(s string) *UserUpdate {
|
||||
uu.name = &s
|
||||
return uu
|
||||
}
|
||||
|
||||
// SetNillableName sets the name field if the given value is not nil.
|
||||
func (uu *UserUpdate) SetNillableName(s *string) *UserUpdate {
|
||||
if s != nil {
|
||||
uu.SetName(*s)
|
||||
}
|
||||
return uu
|
||||
}
|
||||
|
||||
// AddCarIDs adds the cars edge to Car by ids.
|
||||
func (uu *UserUpdate) AddCarIDs(ids ...int) *UserUpdate {
|
||||
if uu.cars == nil {
|
||||
uu.cars = make(map[int]struct{})
|
||||
}
|
||||
for i := range ids {
|
||||
uu.cars[ids[i]] = struct{}{}
|
||||
}
|
||||
return uu
|
||||
}
|
||||
|
||||
// AddCars adds the cars edges to Car.
|
||||
func (uu *UserUpdate) AddCars(c ...*Car) *UserUpdate {
|
||||
ids := make([]int, len(c))
|
||||
for i := range c {
|
||||
ids[i] = c[i].ID
|
||||
}
|
||||
return uu.AddCarIDs(ids...)
|
||||
}
|
||||
|
||||
// AddGroupIDs adds the groups edge to Group by ids.
|
||||
func (uu *UserUpdate) AddGroupIDs(ids ...int) *UserUpdate {
|
||||
if uu.groups == nil {
|
||||
uu.groups = make(map[int]struct{})
|
||||
}
|
||||
for i := range ids {
|
||||
uu.groups[ids[i]] = struct{}{}
|
||||
}
|
||||
return uu
|
||||
}
|
||||
|
||||
// AddGroups adds the groups edges to Group.
|
||||
func (uu *UserUpdate) AddGroups(g ...*Group) *UserUpdate {
|
||||
ids := make([]int, len(g))
|
||||
for i := range g {
|
||||
ids[i] = g[i].ID
|
||||
}
|
||||
return uu.AddGroupIDs(ids...)
|
||||
}
|
||||
|
||||
// RemoveCarIDs removes the cars edge to Car by ids.
|
||||
func (uu *UserUpdate) RemoveCarIDs(ids ...int) *UserUpdate {
|
||||
if uu.removedCars == nil {
|
||||
uu.removedCars = make(map[int]struct{})
|
||||
}
|
||||
for i := range ids {
|
||||
uu.removedCars[ids[i]] = struct{}{}
|
||||
}
|
||||
return uu
|
||||
}
|
||||
|
||||
// RemoveCars removes cars edges to Car.
|
||||
func (uu *UserUpdate) RemoveCars(c ...*Car) *UserUpdate {
|
||||
ids := make([]int, len(c))
|
||||
for i := range c {
|
||||
ids[i] = c[i].ID
|
||||
}
|
||||
return uu.RemoveCarIDs(ids...)
|
||||
}
|
||||
|
||||
// RemoveGroupIDs removes the groups edge to Group by ids.
|
||||
func (uu *UserUpdate) RemoveGroupIDs(ids ...int) *UserUpdate {
|
||||
if uu.removedGroups == nil {
|
||||
uu.removedGroups = make(map[int]struct{})
|
||||
}
|
||||
for i := range ids {
|
||||
uu.removedGroups[ids[i]] = struct{}{}
|
||||
}
|
||||
return uu
|
||||
}
|
||||
|
||||
// RemoveGroups removes groups edges to Group.
|
||||
func (uu *UserUpdate) RemoveGroups(g ...*Group) *UserUpdate {
|
||||
ids := make([]int, len(g))
|
||||
for i := range g {
|
||||
ids[i] = g[i].ID
|
||||
}
|
||||
return uu.RemoveGroupIDs(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) {
|
||||
if uu.age != nil {
|
||||
if err := user.AgeValidator(*uu.age); err != nil {
|
||||
return 0, fmt.Errorf("ent: validator failed for field \"age\": %v", err)
|
||||
}
|
||||
}
|
||||
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 (
|
||||
res sql.Result
|
||||
builder = sql.Update(user.Table).Where(sql.InInts(user.FieldID, ids...))
|
||||
)
|
||||
if value := uu.age; value != nil {
|
||||
builder.Set(user.FieldAge, *value)
|
||||
}
|
||||
if value := uu.addage; value != nil {
|
||||
builder.Add(user.FieldAge, *value)
|
||||
}
|
||||
if value := uu.name; value != nil {
|
||||
builder.Set(user.FieldName, *value)
|
||||
}
|
||||
if !builder.Empty() {
|
||||
query, args := builder.Query()
|
||||
if err := tx.Exec(ctx, query, args, &res); err != nil {
|
||||
return 0, rollback(tx, err)
|
||||
}
|
||||
}
|
||||
if len(uu.removedCars) > 0 {
|
||||
eids := make([]int, len(uu.removedCars))
|
||||
for eid := range uu.removedCars {
|
||||
eids = append(eids, eid)
|
||||
}
|
||||
query, args := sql.Update(user.CarsTable).
|
||||
SetNull(user.CarsColumn).
|
||||
Where(sql.InInts(user.CarsColumn, ids...)).
|
||||
Where(sql.InInts(car.FieldID, eids...)).
|
||||
Query()
|
||||
if err := tx.Exec(ctx, query, args, &res); err != nil {
|
||||
return 0, rollback(tx, err)
|
||||
}
|
||||
}
|
||||
if len(uu.cars) > 0 {
|
||||
for _, id := range ids {
|
||||
p := sql.P()
|
||||
for eid := range uu.cars {
|
||||
p.Or().EQ(car.FieldID, eid)
|
||||
}
|
||||
query, args := sql.Update(user.CarsTable).
|
||||
Set(user.CarsColumn, id).
|
||||
Where(sql.And(p, sql.IsNull(user.CarsColumn))).
|
||||
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.cars) {
|
||||
return 0, rollback(tx, &ErrConstraintFailed{msg: fmt.Sprintf("one of \"cars\" %v already connected to a different \"User\"", keys(uu.cars))})
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(uu.removedGroups) > 0 {
|
||||
eids := make([]int, len(uu.removedGroups))
|
||||
for eid := range uu.removedGroups {
|
||||
eids = append(eids, eid)
|
||||
}
|
||||
query, args := sql.Delete(user.GroupsTable).
|
||||
Where(sql.InInts(user.GroupsPrimaryKey[1], ids...)).
|
||||
Where(sql.InInts(user.GroupsPrimaryKey[0], eids...)).
|
||||
Query()
|
||||
if err := tx.Exec(ctx, query, args, &res); err != nil {
|
||||
return 0, rollback(tx, err)
|
||||
}
|
||||
}
|
||||
if len(uu.groups) > 0 {
|
||||
values := make([][]int, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
for eid := range uu.groups {
|
||||
values = append(values, []int{id, eid})
|
||||
}
|
||||
}
|
||||
builder := sql.Insert(user.GroupsTable).
|
||||
Columns(user.GroupsPrimaryKey[1], user.GroupsPrimaryKey[0])
|
||||
for _, v := range values {
|
||||
builder.Values(v[0], v[1])
|
||||
}
|
||||
query, args := builder.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
|
||||
}
|
||||
|
||||
// UserUpdateOne is the builder for updating a single User entity.
|
||||
type UserUpdateOne struct {
|
||||
config
|
||||
id int
|
||||
age *int
|
||||
addage *int
|
||||
name *string
|
||||
cars map[int]struct{}
|
||||
groups map[int]struct{}
|
||||
removedCars map[int]struct{}
|
||||
removedGroups map[int]struct{}
|
||||
}
|
||||
|
||||
// SetAge sets the age field.
|
||||
func (uuo *UserUpdateOne) SetAge(i int) *UserUpdateOne {
|
||||
uuo.age = &i
|
||||
uuo.addage = nil
|
||||
return uuo
|
||||
}
|
||||
|
||||
// AddAge adds i to age.
|
||||
func (uuo *UserUpdateOne) AddAge(i int) *UserUpdateOne {
|
||||
if uuo.addage == nil {
|
||||
uuo.addage = &i
|
||||
} else {
|
||||
*uuo.addage += i
|
||||
}
|
||||
return uuo
|
||||
}
|
||||
|
||||
// SetName sets the name field.
|
||||
func (uuo *UserUpdateOne) SetName(s string) *UserUpdateOne {
|
||||
uuo.name = &s
|
||||
return uuo
|
||||
}
|
||||
|
||||
// SetNillableName sets the name field if the given value is not nil.
|
||||
func (uuo *UserUpdateOne) SetNillableName(s *string) *UserUpdateOne {
|
||||
if s != nil {
|
||||
uuo.SetName(*s)
|
||||
}
|
||||
return uuo
|
||||
}
|
||||
|
||||
// AddCarIDs adds the cars edge to Car by ids.
|
||||
func (uuo *UserUpdateOne) AddCarIDs(ids ...int) *UserUpdateOne {
|
||||
if uuo.cars == nil {
|
||||
uuo.cars = make(map[int]struct{})
|
||||
}
|
||||
for i := range ids {
|
||||
uuo.cars[ids[i]] = struct{}{}
|
||||
}
|
||||
return uuo
|
||||
}
|
||||
|
||||
// AddCars adds the cars edges to Car.
|
||||
func (uuo *UserUpdateOne) AddCars(c ...*Car) *UserUpdateOne {
|
||||
ids := make([]int, len(c))
|
||||
for i := range c {
|
||||
ids[i] = c[i].ID
|
||||
}
|
||||
return uuo.AddCarIDs(ids...)
|
||||
}
|
||||
|
||||
// AddGroupIDs adds the groups edge to Group by ids.
|
||||
func (uuo *UserUpdateOne) AddGroupIDs(ids ...int) *UserUpdateOne {
|
||||
if uuo.groups == nil {
|
||||
uuo.groups = make(map[int]struct{})
|
||||
}
|
||||
for i := range ids {
|
||||
uuo.groups[ids[i]] = struct{}{}
|
||||
}
|
||||
return uuo
|
||||
}
|
||||
|
||||
// AddGroups adds the groups edges to Group.
|
||||
func (uuo *UserUpdateOne) AddGroups(g ...*Group) *UserUpdateOne {
|
||||
ids := make([]int, len(g))
|
||||
for i := range g {
|
||||
ids[i] = g[i].ID
|
||||
}
|
||||
return uuo.AddGroupIDs(ids...)
|
||||
}
|
||||
|
||||
// RemoveCarIDs removes the cars edge to Car by ids.
|
||||
func (uuo *UserUpdateOne) RemoveCarIDs(ids ...int) *UserUpdateOne {
|
||||
if uuo.removedCars == nil {
|
||||
uuo.removedCars = make(map[int]struct{})
|
||||
}
|
||||
for i := range ids {
|
||||
uuo.removedCars[ids[i]] = struct{}{}
|
||||
}
|
||||
return uuo
|
||||
}
|
||||
|
||||
// RemoveCars removes cars edges to Car.
|
||||
func (uuo *UserUpdateOne) RemoveCars(c ...*Car) *UserUpdateOne {
|
||||
ids := make([]int, len(c))
|
||||
for i := range c {
|
||||
ids[i] = c[i].ID
|
||||
}
|
||||
return uuo.RemoveCarIDs(ids...)
|
||||
}
|
||||
|
||||
// RemoveGroupIDs removes the groups edge to Group by ids.
|
||||
func (uuo *UserUpdateOne) RemoveGroupIDs(ids ...int) *UserUpdateOne {
|
||||
if uuo.removedGroups == nil {
|
||||
uuo.removedGroups = make(map[int]struct{})
|
||||
}
|
||||
for i := range ids {
|
||||
uuo.removedGroups[ids[i]] = struct{}{}
|
||||
}
|
||||
return uuo
|
||||
}
|
||||
|
||||
// RemoveGroups removes groups edges to Group.
|
||||
func (uuo *UserUpdateOne) RemoveGroups(g ...*Group) *UserUpdateOne {
|
||||
ids := make([]int, len(g))
|
||||
for i := range g {
|
||||
ids[i] = g[i].ID
|
||||
}
|
||||
return uuo.RemoveGroupIDs(ids...)
|
||||
}
|
||||
|
||||
// Save executes the query and returns the updated entity.
|
||||
func (uuo *UserUpdateOne) Save(ctx context.Context) (*User, error) {
|
||||
if uuo.age != nil {
|
||||
if err := user.AgeValidator(*uuo.age); err != nil {
|
||||
return nil, fmt.Errorf("ent: validator failed for field \"age\": %v", err)
|
||||
}
|
||||
}
|
||||
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 (
|
||||
res sql.Result
|
||||
builder = sql.Update(user.Table).Where(sql.InInts(user.FieldID, ids...))
|
||||
)
|
||||
if value := uuo.age; value != nil {
|
||||
builder.Set(user.FieldAge, *value)
|
||||
u.Age = *value
|
||||
}
|
||||
if value := uuo.addage; value != nil {
|
||||
builder.Add(user.FieldAge, *value)
|
||||
u.Age += *value
|
||||
}
|
||||
if value := uuo.name; value != nil {
|
||||
builder.Set(user.FieldName, *value)
|
||||
u.Name = *value
|
||||
}
|
||||
if !builder.Empty() {
|
||||
query, args := builder.Query()
|
||||
if err := tx.Exec(ctx, query, args, &res); err != nil {
|
||||
return nil, rollback(tx, err)
|
||||
}
|
||||
}
|
||||
if len(uuo.removedCars) > 0 {
|
||||
eids := make([]int, len(uuo.removedCars))
|
||||
for eid := range uuo.removedCars {
|
||||
eids = append(eids, eid)
|
||||
}
|
||||
query, args := sql.Update(user.CarsTable).
|
||||
SetNull(user.CarsColumn).
|
||||
Where(sql.InInts(user.CarsColumn, ids...)).
|
||||
Where(sql.InInts(car.FieldID, eids...)).
|
||||
Query()
|
||||
if err := tx.Exec(ctx, query, args, &res); err != nil {
|
||||
return nil, rollback(tx, err)
|
||||
}
|
||||
}
|
||||
if len(uuo.cars) > 0 {
|
||||
for _, id := range ids {
|
||||
p := sql.P()
|
||||
for eid := range uuo.cars {
|
||||
p.Or().EQ(car.FieldID, eid)
|
||||
}
|
||||
query, args := sql.Update(user.CarsTable).
|
||||
Set(user.CarsColumn, id).
|
||||
Where(sql.And(p, sql.IsNull(user.CarsColumn))).
|
||||
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.cars) {
|
||||
return nil, rollback(tx, &ErrConstraintFailed{msg: fmt.Sprintf("one of \"cars\" %v already connected to a different \"User\"", keys(uuo.cars))})
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(uuo.removedGroups) > 0 {
|
||||
eids := make([]int, len(uuo.removedGroups))
|
||||
for eid := range uuo.removedGroups {
|
||||
eids = append(eids, eid)
|
||||
}
|
||||
query, args := sql.Delete(user.GroupsTable).
|
||||
Where(sql.InInts(user.GroupsPrimaryKey[1], ids...)).
|
||||
Where(sql.InInts(user.GroupsPrimaryKey[0], eids...)).
|
||||
Query()
|
||||
if err := tx.Exec(ctx, query, args, &res); err != nil {
|
||||
return nil, rollback(tx, err)
|
||||
}
|
||||
}
|
||||
if len(uuo.groups) > 0 {
|
||||
values := make([][]int, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
for eid := range uuo.groups {
|
||||
values = append(values, []int{id, eid})
|
||||
}
|
||||
}
|
||||
builder := sql.Insert(user.GroupsTable).
|
||||
Columns(user.GroupsPrimaryKey[1], user.GroupsPrimaryKey[0])
|
||||
for _, v := range values {
|
||||
builder.Values(v[0], v[1])
|
||||
}
|
||||
query, args := builder.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 u, nil
|
||||
}
|
||||
279
examples/start/start.go
Normal file
279
examples/start/start.go
Normal file
@@ -0,0 +1,279 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/facebookincubator/ent/examples/start/ent"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/car"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/group"
|
||||
"github.com/facebookincubator/ent/examples/start/ent/user"
|
||||
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
)
|
||||
|
||||
func main() {
|
||||
client, err := ent.Open("sqlite3", "file:ent?mode=memory&cache=shared&_fk=1")
|
||||
if err != nil {
|
||||
log.Fatalf("failed opening connection to sqlite: %v", err)
|
||||
}
|
||||
defer client.Close()
|
||||
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 = CreateUser(ctx, client); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if _, err = QueryUser(ctx, client); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
a8m, err := CreateCars(ctx, client)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if err := QueryCars(ctx, a8m); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if err := QueryCarUsers(ctx, a8m); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if err := CreateGraph(ctx, client); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if err := QueryGithub(ctx, client); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if err := QueryArielCars(ctx, client); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if err := QueryGroupWithUsers(ctx, client); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func CreateUser(ctx context.Context, client *ent.Client) (*ent.User, error) {
|
||||
u, err := client.User.
|
||||
Create().
|
||||
SetAge(30).
|
||||
SetName("a8m").
|
||||
Save(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed creating user: %v", err)
|
||||
}
|
||||
log.Println("user was created: ", u)
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func QueryUser(ctx context.Context, client *ent.Client) (*ent.User, error) {
|
||||
u, err := client.User.
|
||||
Query().
|
||||
Where(user.NameEQ("a8m")).
|
||||
// `Only` fails if no user found,
|
||||
// or more than 1 user returned.
|
||||
Only(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed querying user: %v", err)
|
||||
}
|
||||
log.Println("user returned: ", u)
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func CreateCars(ctx context.Context, client *ent.Client) (*ent.User, error) {
|
||||
// creating new car with model "Tesla".
|
||||
tesla, err := client.Car.
|
||||
Create().
|
||||
SetModel("Tesla").
|
||||
SetRegisteredAt(time.Now()).
|
||||
Save(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed creating car: %v", err)
|
||||
}
|
||||
|
||||
// creating new car with model "Ford".
|
||||
ford, err := client.Car.
|
||||
Create().
|
||||
SetModel("Ford").
|
||||
SetRegisteredAt(time.Now()).
|
||||
Save(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed creating car: %v", err)
|
||||
}
|
||||
log.Println("car was created: ", ford)
|
||||
|
||||
// create a new user, and add it the 2 cars.
|
||||
a8m, err := client.User.
|
||||
Create().
|
||||
SetAge(30).
|
||||
SetName("a8m").
|
||||
AddCars(tesla, ford).
|
||||
Save(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed creating user: %v", err)
|
||||
}
|
||||
log.Println("user was created: ", a8m)
|
||||
return a8m, nil
|
||||
}
|
||||
|
||||
func QueryCars(ctx context.Context, a8m *ent.User) error {
|
||||
cars, err := a8m.QueryCars().All(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed querying user cars: %v", err)
|
||||
}
|
||||
log.Println("returned cars:", cars)
|
||||
|
||||
// what about filtering specific cars.
|
||||
ford, err := a8m.QueryCars().
|
||||
Where(car.ModelEQ("Ford")).
|
||||
Only(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed querying user cars: %v", err)
|
||||
}
|
||||
log.Println(ford)
|
||||
return nil
|
||||
}
|
||||
|
||||
func QueryCarUsers(ctx context.Context, a8m *ent.User) error {
|
||||
cars, err := a8m.QueryCars().All(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed querying user cars: %v", err)
|
||||
}
|
||||
|
||||
// query the inverse edge.
|
||||
for _, ca := range cars {
|
||||
owner, err := ca.QueryOwner().Only(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed querying car %q owner: %v", ca.Model, err)
|
||||
}
|
||||
log.Printf("car %q owner: %q\n", ca.Model, owner.Name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func CreateGraph(ctx context.Context, client *ent.Client) error {
|
||||
// first, create the users.
|
||||
a8m, err := client.User.
|
||||
Create().
|
||||
SetAge(30).
|
||||
SetName("Ariel").
|
||||
Save(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
neta, err := client.User.
|
||||
Create().
|
||||
SetAge(28).
|
||||
SetName("Neta").
|
||||
Save(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// then, create the cars, and attach them to the users in the creation.
|
||||
_, err = client.Car.
|
||||
Create().
|
||||
SetModel("Tesla").
|
||||
SetRegisteredAt(time.Now()). // ignore the time in the graph.
|
||||
SetOwner(a8m). // attach this graph to Ariel.
|
||||
Save(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = client.Car.
|
||||
Create().
|
||||
SetModel("Mazda").
|
||||
SetRegisteredAt(time.Now()). // ignore the time in the graph.
|
||||
SetOwner(a8m). // attach this graph to Ariel.
|
||||
Save(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = client.Car.
|
||||
Create().
|
||||
SetModel("Ford").
|
||||
SetRegisteredAt(time.Now()). // ignore the time in the graph.
|
||||
SetOwner(neta). // attach this graph to Neta.
|
||||
Save(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// create the groups, and add their users in the creation.
|
||||
_, err = client.Group.
|
||||
Create().
|
||||
SetName("GitLab").
|
||||
AddUsers(neta, a8m).
|
||||
Save(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = client.Group.
|
||||
Create().
|
||||
SetName("GitHub").
|
||||
AddUsers(a8m).
|
||||
Save(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Println("The graph was created successfully")
|
||||
return nil
|
||||
}
|
||||
|
||||
func QueryGithub(ctx context.Context, client *ent.Client) error {
|
||||
cars, err := client.Group.
|
||||
Query().
|
||||
Where(group.Name("GitHub")). // (Group(Name=GitHub),)
|
||||
QueryUsers(). // (User(Name=Ariel, Age=30),)
|
||||
QueryCars(). // (Car(Model=Tesla, RegisteredAt=<Time>), Car(Model=Mazda, RegisteredAt=<Time>),)
|
||||
All(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed getting cars: %v", err)
|
||||
}
|
||||
log.Println("cars returned:", cars)
|
||||
// Output: (Car(Model=Tesla, RegisteredAt=<Time>), Car(Model=Mazda, RegisteredAt=<Time>),)
|
||||
return nil
|
||||
}
|
||||
|
||||
func QueryArielCars(ctx context.Context, client *ent.Client) error {
|
||||
// Get "Ariel" from previous steps.
|
||||
a8m := client.User.
|
||||
Query().
|
||||
Where(
|
||||
user.HasCars(),
|
||||
user.Name("Ariel"),
|
||||
).
|
||||
OnlyX(ctx)
|
||||
cars, err := a8m. // Get the groups, that a8m is connected to:
|
||||
QueryGroups(). // (Group(Name=GitHub), Group(Name=GitLab),)
|
||||
QueryUsers(). // (User(Name=Ariel, Age=30), User(Name=Neta, Age=28),)
|
||||
QueryCars(). //
|
||||
Where( //
|
||||
car.Not( // Get Neta and Ariel cars, but filter out
|
||||
car.ModelEQ("Mazda"), // those who named "Mazda"
|
||||
), //
|
||||
). //
|
||||
All(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed getting cars: %v", err)
|
||||
}
|
||||
log.Println("cars returned:", cars)
|
||||
return nil
|
||||
}
|
||||
|
||||
func QueryGroupWithUsers(ctx context.Context, client *ent.Client) error {
|
||||
groups, err := client.Group.
|
||||
Query().
|
||||
Where(group.HasUsers()).
|
||||
All(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed getting groups: %v", err)
|
||||
}
|
||||
log.Println("groups returned:", groups)
|
||||
// Output: (Group(Name=GitHub), Group(Name=GitLab),)
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user