diff --git a/entc/integration/privacy/ent/client.go b/entc/integration/privacy/ent/client.go index e96b6b603..ef61c8382 100644 --- a/entc/integration/privacy/ent/client.go +++ b/entc/integration/privacy/ent/client.go @@ -13,6 +13,7 @@ import ( "github.com/facebookincubator/ent/entc/integration/privacy/ent/migrate" + "github.com/facebookincubator/ent/entc/integration/privacy/ent/galaxy" "github.com/facebookincubator/ent/entc/integration/privacy/ent/planet" "github.com/facebookincubator/ent/dialect" @@ -25,6 +26,8 @@ type Client struct { config // Schema is the client for creating, migrating and dropping schema. Schema *migrate.Schema + // Galaxy is the client for interacting with the Galaxy builders. + Galaxy *GalaxyClient // Planet is the client for interacting with the Planet builders. Planet *PlanetClient } @@ -40,6 +43,7 @@ func NewClient(opts ...Option) *Client { func (c *Client) init() { c.Schema = migrate.NewSchema(c.driver) + c.Galaxy = NewGalaxyClient(c.config) c.Planet = NewPlanetClient(c.config) } @@ -71,6 +75,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { cfg := config{driver: tx, log: c.log, debug: c.debug, hooks: c.hooks} return &Tx{ config: cfg, + Galaxy: NewGalaxyClient(cfg), Planet: NewPlanetClient(cfg), }, nil } @@ -78,7 +83,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { // Debug returns a new debug-client. It's used to get verbose logging on specific operations. // // client.Debug(). -// Planet. +// Galaxy. // Query(). // Count(ctx) // @@ -100,9 +105,110 @@ func (c *Client) Close() error { // Use adds the mutation hooks to all the entity clients. // In order to add hooks to a specific client, call: `client.Node.Use(...)`. func (c *Client) Use(hooks ...Hook) { + c.Galaxy.Use(hooks...) c.Planet.Use(hooks...) } +// GalaxyClient is a client for the Galaxy schema. +type GalaxyClient struct { + config +} + +// NewGalaxyClient returns a client for the Galaxy from the given config. +func NewGalaxyClient(c config) *GalaxyClient { + return &GalaxyClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `galaxy.Hooks(f(g(h())))`. +func (c *GalaxyClient) Use(hooks ...Hook) { + c.hooks.Galaxy = append(c.hooks.Galaxy, hooks...) +} + +// Create returns a create builder for Galaxy. +func (c *GalaxyClient) Create() *GalaxyCreate { + mutation := newGalaxyMutation(c.config, OpCreate) + return &GalaxyCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Update returns an update builder for Galaxy. +func (c *GalaxyClient) Update() *GalaxyUpdate { + mutation := newGalaxyMutation(c.config, OpUpdate) + return &GalaxyUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *GalaxyClient) UpdateOne(ga *Galaxy) *GalaxyUpdateOne { + return c.UpdateOneID(ga.ID) +} + +// UpdateOneID returns an update builder for the given id. +func (c *GalaxyClient) UpdateOneID(id int) *GalaxyUpdateOne { + mutation := newGalaxyMutation(c.config, OpUpdateOne) + mutation.id = &id + return &GalaxyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Galaxy. +func (c *GalaxyClient) Delete() *GalaxyDelete { + mutation := newGalaxyMutation(c.config, OpDelete) + return &GalaxyDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *GalaxyClient) DeleteOne(ga *Galaxy) *GalaxyDeleteOne { + return c.DeleteOneID(ga.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *GalaxyClient) DeleteOneID(id int) *GalaxyDeleteOne { + builder := c.Delete().Where(galaxy.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &GalaxyDeleteOne{builder} +} + +// Create returns a query builder for Galaxy. +func (c *GalaxyClient) Query() *GalaxyQuery { + return &GalaxyQuery{config: c.config} +} + +// Get returns a Galaxy entity by its id. +func (c *GalaxyClient) Get(ctx context.Context, id int) (*Galaxy, error) { + return c.Query().Where(galaxy.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *GalaxyClient) GetX(ctx context.Context, id int) *Galaxy { + ga, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return ga +} + +// QueryPlanets queries the planets edge of a Galaxy. +func (c *GalaxyClient) QueryPlanets(ga *Galaxy) *PlanetQuery { + query := &PlanetQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := ga.ID + step := sqlgraph.NewStep( + sqlgraph.From(galaxy.Table, galaxy.FieldID, id), + sqlgraph.To(planet.Table, planet.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, galaxy.PlanetsTable, galaxy.PlanetsColumn), + ) + fromV = sqlgraph.Neighbors(ga.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *GalaxyClient) Hooks() []Hook { + hooks := c.hooks.Galaxy + return append(hooks[:len(hooks):len(hooks)], galaxy.Hooks[:]...) +} + // PlanetClient is a client for the Planet schema. type PlanetClient struct { config diff --git a/entc/integration/privacy/ent/config.go b/entc/integration/privacy/ent/config.go index 6608d2c6c..78c0c9ccb 100644 --- a/entc/integration/privacy/ent/config.go +++ b/entc/integration/privacy/ent/config.go @@ -28,6 +28,7 @@ type config struct { // hooks per client, for fast access. type hooks struct { + Galaxy []ent.Hook Planet []ent.Hook } diff --git a/entc/integration/privacy/ent/galaxy.go b/entc/integration/privacy/ent/galaxy.go new file mode 100644 index 000000000..cd366a989 --- /dev/null +++ b/entc/integration/privacy/ent/galaxy.go @@ -0,0 +1,126 @@ +// 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 by entc, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "github.com/facebookincubator/ent/dialect/sql" + "github.com/facebookincubator/ent/entc/integration/privacy/ent/galaxy" +) + +// Galaxy is the model entity for the Galaxy schema. +type Galaxy 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"` + // Type holds the value of the "type" field. + Type galaxy.Type `json:"type,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the GalaxyQuery when eager-loading is set. + Edges GalaxyEdges `json:"edges"` +} + +// GalaxyEdges holds the relations/edges for other nodes in the graph. +type GalaxyEdges struct { + // Planets holds the value of the planets edge. + Planets []*Planet + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// PlanetsOrErr returns the Planets value or an error if the edge +// was not loaded in eager-loading. +func (e GalaxyEdges) PlanetsOrErr() ([]*Planet, error) { + if e.loadedTypes[0] { + return e.Planets, nil + } + return nil, &NotLoadedError{edge: "planets"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Galaxy) scanValues() []interface{} { + return []interface{}{ + &sql.NullInt64{}, // id + &sql.NullString{}, // name + &sql.NullString{}, // type + } +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Galaxy fields. +func (ga *Galaxy) assignValues(values ...interface{}) error { + if m, n := len(values), len(galaxy.Columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + value, ok := values[0].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + ga.ID = int(value.Int64) + values = values[1:] + if value, ok := values[0].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[0]) + } else if value.Valid { + ga.Name = value.String + } + if value, ok := values[1].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field type", values[1]) + } else if value.Valid { + ga.Type = galaxy.Type(value.String) + } + return nil +} + +// QueryPlanets queries the planets edge of the Galaxy. +func (ga *Galaxy) QueryPlanets() *PlanetQuery { + return (&GalaxyClient{config: ga.config}).QueryPlanets(ga) +} + +// Update returns a builder for updating this Galaxy. +// Note that, you need to call Galaxy.Unwrap() before calling this method, if this Galaxy +// was returned from a transaction, and the transaction was committed or rolled back. +func (ga *Galaxy) Update() *GalaxyUpdateOne { + return (&GalaxyClient{config: ga.config}).UpdateOne(ga) +} + +// 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 (ga *Galaxy) Unwrap() *Galaxy { + tx, ok := ga.config.driver.(*txDriver) + if !ok { + panic("ent: Galaxy is not a transactional entity") + } + ga.config.driver = tx.drv + return ga +} + +// String implements the fmt.Stringer. +func (ga *Galaxy) String() string { + var builder strings.Builder + builder.WriteString("Galaxy(") + builder.WriteString(fmt.Sprintf("id=%v", ga.ID)) + builder.WriteString(", name=") + builder.WriteString(ga.Name) + builder.WriteString(", type=") + builder.WriteString(fmt.Sprintf("%v", ga.Type)) + builder.WriteByte(')') + return builder.String() +} + +// Galaxies is a parsable slice of Galaxy. +type Galaxies []*Galaxy + +func (ga Galaxies) config(cfg config) { + for _i := range ga { + ga[_i].config = cfg + } +} diff --git a/entc/integration/privacy/ent/galaxy/galaxy.go b/entc/integration/privacy/ent/galaxy/galaxy.go new file mode 100644 index 000000000..042975542 --- /dev/null +++ b/entc/integration/privacy/ent/galaxy/galaxy.go @@ -0,0 +1,80 @@ +// 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 by entc, DO NOT EDIT. + +package galaxy + +import ( + "fmt" + + "github.com/facebookincubator/ent" +) + +const ( + // Label holds the string label denoting the galaxy type in the database. + Label = "galaxy" + // 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" // FieldType holds the string denoting the type vertex property in the database. + FieldType = "type" + + // EdgePlanets holds the string denoting the planets edge name in mutations. + EdgePlanets = "planets" + + // Table holds the table name of the galaxy in the database. + Table = "galaxies" + // PlanetsTable is the table the holds the planets relation/edge. + PlanetsTable = "planets" + // PlanetsInverseTable is the table name for the Planet entity. + // It exists in this package in order to avoid circular dependency with the "planet" package. + PlanetsInverseTable = "planets" + // PlanetsColumn is the table column denoting the planets relation/edge. + PlanetsColumn = "galaxy_planets" +) + +// Columns holds all SQL columns for galaxy fields. +var Columns = []string{ + FieldID, + FieldName, + FieldType, +} + +// Note that the variables below are initialized by the runtime +// package on the initialization of the application. Therefore, +// it should be imported in the main as follows: +// +// import _ "github.com/facebookincubator/ent/entc/integration/privacy/ent/runtime" +// +var ( + Hooks [1]ent.Hook + Policy ent.Policy + // NameValidator is a validator for the "name" field. It is called by the builders before save. + NameValidator func(string) error +) + +// Type defines the type for the type enum field. +type Type string + +// Type values. +const ( + TypeSpiral Type = "spiral" + TypeBarredSpiral Type = "barred_spiral" + TypeElliptical Type = "elliptical" + TypeIrregular Type = "irregular" +) + +func (s Type) String() string { + return string(s) +} + +// TypeValidator is a validator for the "_type" field enum values. It is called by the builders before save. +func TypeValidator(_type Type) error { + switch _type { + case TypeSpiral, TypeBarredSpiral, TypeElliptical, TypeIrregular: + return nil + default: + return fmt.Errorf("galaxy: invalid enum value for type field: %q", _type) + } +} diff --git a/entc/integration/privacy/ent/galaxy/where.go b/entc/integration/privacy/ent/galaxy/where.go new file mode 100644 index 000000000..96ecd4738 --- /dev/null +++ b/entc/integration/privacy/ent/galaxy/where.go @@ -0,0 +1,322 @@ +// 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 by entc, DO NOT EDIT. + +package galaxy + +import ( + "github.com/facebookincubator/ent/dialect/sql" + "github.com/facebookincubator/ent/dialect/sql/sqlgraph" + "github.com/facebookincubator/ent/entc/integration/privacy/ent/predicate" +) + +// ID filters vertices based on their identifier. +func ID(id int) predicate.Galaxy { + return predicate.Galaxy(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.Galaxy { + return predicate.Galaxy(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.Galaxy { + return predicate.Galaxy(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.Galaxy { + return predicate.Galaxy(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.Galaxy { + return predicate.Galaxy(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.Galaxy { + return predicate.Galaxy(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.Galaxy { + return predicate.Galaxy(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.Galaxy { + return predicate.Galaxy(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.Galaxy { + return predicate.Galaxy(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.Galaxy { + return predicate.Galaxy(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.Galaxy { + return predicate.Galaxy(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.Galaxy { + return predicate.Galaxy(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.Galaxy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Galaxy(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.Galaxy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Galaxy(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.Galaxy { + return predicate.Galaxy(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.Galaxy { + return predicate.Galaxy(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.Galaxy { + return predicate.Galaxy(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.Galaxy { + return predicate.Galaxy(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.Galaxy { + return predicate.Galaxy(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.Galaxy { + return predicate.Galaxy(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.Galaxy { + return predicate.Galaxy(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.Galaxy { + return predicate.Galaxy(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.Galaxy { + return predicate.Galaxy(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldName), v)) + }) +} + +// TypeEQ applies the EQ predicate on the "type" field. +func TypeEQ(v Type) predicate.Galaxy { + return predicate.Galaxy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldType), v)) + }) +} + +// TypeNEQ applies the NEQ predicate on the "type" field. +func TypeNEQ(v Type) predicate.Galaxy { + return predicate.Galaxy(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldType), v)) + }) +} + +// TypeIn applies the In predicate on the "type" field. +func TypeIn(vs ...Type) predicate.Galaxy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Galaxy(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(FieldType), v...)) + }) +} + +// TypeNotIn applies the NotIn predicate on the "type" field. +func TypeNotIn(vs ...Type) predicate.Galaxy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Galaxy(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(FieldType), v...)) + }) +} + +// HasPlanets applies the HasEdge predicate on the "planets" edge. +func HasPlanets() predicate.Galaxy { + return predicate.Galaxy(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(PlanetsTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, PlanetsTable, PlanetsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasPlanetsWith applies the HasEdge predicate on the "planets" edge with a given conditions (other predicates). +func HasPlanetsWith(preds ...predicate.Planet) predicate.Galaxy { + return predicate.Galaxy(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(PlanetsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, PlanetsTable, PlanetsColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups list of predicates with the AND operator between them. +func And(predicates ...predicate.Galaxy) predicate.Galaxy { + return predicate.Galaxy(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for _, p := range predicates { + p(s1) + } + s.Where(s1.P()) + }) +} + +// Or groups list of predicates with the OR operator between them. +func Or(predicates ...predicate.Galaxy) predicate.Galaxy { + return predicate.Galaxy(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for i, p := range predicates { + if i > 0 { + s1.Or() + } + p(s1) + } + s.Where(s1.P()) + }) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Galaxy) predicate.Galaxy { + return predicate.Galaxy(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/entc/integration/privacy/ent/galaxy_create.go b/entc/integration/privacy/ent/galaxy_create.go new file mode 100644 index 000000000..8246a93a4 --- /dev/null +++ b/entc/integration/privacy/ent/galaxy_create.go @@ -0,0 +1,162 @@ +// 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 by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "github.com/facebookincubator/ent/dialect/sql/sqlgraph" + "github.com/facebookincubator/ent/entc/integration/privacy/ent/galaxy" + "github.com/facebookincubator/ent/entc/integration/privacy/ent/planet" + "github.com/facebookincubator/ent/schema/field" +) + +// GalaxyCreate is the builder for creating a Galaxy entity. +type GalaxyCreate struct { + config + mutation *GalaxyMutation + hooks []Hook +} + +// SetName sets the name field. +func (gc *GalaxyCreate) SetName(s string) *GalaxyCreate { + gc.mutation.SetName(s) + return gc +} + +// SetType sets the type field. +func (gc *GalaxyCreate) SetType(ga galaxy.Type) *GalaxyCreate { + gc.mutation.SetType(ga) + return gc +} + +// AddPlanetIDs adds the planets edge to Planet by ids. +func (gc *GalaxyCreate) AddPlanetIDs(ids ...int) *GalaxyCreate { + gc.mutation.AddPlanetIDs(ids...) + return gc +} + +// AddPlanets adds the planets edges to Planet. +func (gc *GalaxyCreate) AddPlanets(p ...*Planet) *GalaxyCreate { + ids := make([]int, len(p)) + for i := range p { + ids[i] = p[i].ID + } + return gc.AddPlanetIDs(ids...) +} + +// Save creates the Galaxy in the database. +func (gc *GalaxyCreate) Save(ctx context.Context) (*Galaxy, error) { + if _, ok := gc.mutation.Name(); !ok { + return nil, errors.New("ent: missing required field \"name\"") + } + if v, ok := gc.mutation.Name(); ok { + if err := galaxy.NameValidator(v); err != nil { + return nil, fmt.Errorf("ent: validator failed for field \"name\": %v", err) + } + } + if _, ok := gc.mutation.GetType(); !ok { + return nil, errors.New("ent: missing required field \"type\"") + } + if v, ok := gc.mutation.GetType(); ok { + if err := galaxy.TypeValidator(v); err != nil { + return nil, fmt.Errorf("ent: validator failed for field \"type\": %v", err) + } + } + var ( + err error + node *Galaxy + ) + if len(gc.hooks) == 0 { + node, err = gc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*GalaxyMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + gc.mutation = mutation + node, err = gc.sqlSave(ctx) + return node, err + }) + for i := len(gc.hooks) - 1; i >= 0; i-- { + mut = gc.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, gc.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (gc *GalaxyCreate) SaveX(ctx context.Context) *Galaxy { + v, err := gc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +func (gc *GalaxyCreate) sqlSave(ctx context.Context) (*Galaxy, error) { + var ( + ga = &Galaxy{config: gc.config} + _spec = &sqlgraph.CreateSpec{ + Table: galaxy.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: galaxy.FieldID, + }, + } + ) + if value, ok := gc.mutation.Name(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: galaxy.FieldName, + }) + ga.Name = value + } + if value, ok := gc.mutation.GetType(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeEnum, + Value: value, + Column: galaxy.FieldType, + }) + ga.Type = value + } + if nodes := gc.mutation.PlanetsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: galaxy.PlanetsTable, + Columns: []string{galaxy.PlanetsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: planet.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if err := sqlgraph.CreateNode(ctx, gc.driver, _spec); err != nil { + if cerr, ok := isSQLConstraintError(err); ok { + err = cerr + } + return nil, err + } + id := _spec.ID.Value.(int64) + ga.ID = int(id) + return ga, nil +} diff --git a/entc/integration/privacy/ent/galaxy_delete.go b/entc/integration/privacy/ent/galaxy_delete.go new file mode 100644 index 000000000..914cf916f --- /dev/null +++ b/entc/integration/privacy/ent/galaxy_delete.go @@ -0,0 +1,112 @@ +// 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 by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + + "github.com/facebookincubator/ent/dialect/sql" + "github.com/facebookincubator/ent/dialect/sql/sqlgraph" + "github.com/facebookincubator/ent/entc/integration/privacy/ent/galaxy" + "github.com/facebookincubator/ent/entc/integration/privacy/ent/predicate" + "github.com/facebookincubator/ent/schema/field" +) + +// GalaxyDelete is the builder for deleting a Galaxy entity. +type GalaxyDelete struct { + config + hooks []Hook + mutation *GalaxyMutation + predicates []predicate.Galaxy +} + +// Where adds a new predicate to the delete builder. +func (gd *GalaxyDelete) Where(ps ...predicate.Galaxy) *GalaxyDelete { + gd.predicates = append(gd.predicates, ps...) + return gd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (gd *GalaxyDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(gd.hooks) == 0 { + affected, err = gd.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*GalaxyMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + gd.mutation = mutation + affected, err = gd.sqlExec(ctx) + return affected, err + }) + for i := len(gd.hooks) - 1; i >= 0; i-- { + mut = gd.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, gd.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (gd *GalaxyDelete) ExecX(ctx context.Context) int { + n, err := gd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (gd *GalaxyDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: galaxy.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: galaxy.FieldID, + }, + }, + } + if ps := gd.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, gd.driver, _spec) +} + +// GalaxyDeleteOne is the builder for deleting a single Galaxy entity. +type GalaxyDeleteOne struct { + gd *GalaxyDelete +} + +// Exec executes the deletion query. +func (gdo *GalaxyDeleteOne) Exec(ctx context.Context) error { + n, err := gdo.gd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{galaxy.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (gdo *GalaxyDeleteOne) ExecX(ctx context.Context) { + gdo.gd.ExecX(ctx) +} diff --git a/entc/integration/privacy/ent/galaxy_query.go b/entc/integration/privacy/ent/galaxy_query.go new file mode 100644 index 000000000..8c133951d --- /dev/null +++ b/entc/integration/privacy/ent/galaxy_query.go @@ -0,0 +1,731 @@ +// 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 by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "database/sql/driver" + "errors" + "fmt" + "math" + + "github.com/facebookincubator/ent/dialect/sql" + "github.com/facebookincubator/ent/dialect/sql/sqlgraph" + "github.com/facebookincubator/ent/entc/integration/privacy/ent/galaxy" + "github.com/facebookincubator/ent/entc/integration/privacy/ent/planet" + "github.com/facebookincubator/ent/entc/integration/privacy/ent/predicate" + "github.com/facebookincubator/ent/schema/field" +) + +// GalaxyQuery is the builder for querying Galaxy entities. +type GalaxyQuery struct { + config + limit *int + offset *int + order []Order + unique []string + predicates []predicate.Galaxy + // eager-loading edges. + withPlanets *PlanetQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the builder. +func (gq *GalaxyQuery) Where(ps ...predicate.Galaxy) *GalaxyQuery { + gq.predicates = append(gq.predicates, ps...) + return gq +} + +// Limit adds a limit step to the query. +func (gq *GalaxyQuery) Limit(limit int) *GalaxyQuery { + gq.limit = &limit + return gq +} + +// Offset adds an offset step to the query. +func (gq *GalaxyQuery) Offset(offset int) *GalaxyQuery { + gq.offset = &offset + return gq +} + +// Order adds an order step to the query. +func (gq *GalaxyQuery) Order(o ...Order) *GalaxyQuery { + gq.order = append(gq.order, o...) + return gq +} + +// QueryPlanets chains the current query on the planets edge. +func (gq *GalaxyQuery) QueryPlanets() *PlanetQuery { + query := &PlanetQuery{config: gq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := gq.prepareQuery(ctx); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(galaxy.Table, galaxy.FieldID, gq.sqlQuery()), + sqlgraph.To(planet.Table, planet.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, galaxy.PlanetsTable, galaxy.PlanetsColumn), + ) + fromU = sqlgraph.SetNeighbors(gq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Galaxy entity in the query. Returns *NotFoundError when no galaxy was found. +func (gq *GalaxyQuery) First(ctx context.Context) (*Galaxy, error) { + gas, err := gq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(gas) == 0 { + return nil, &NotFoundError{galaxy.Label} + } + return gas[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (gq *GalaxyQuery) FirstX(ctx context.Context) *Galaxy { + ga, err := gq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return ga +} + +// FirstID returns the first Galaxy id in the query. Returns *NotFoundError when no id was found. +func (gq *GalaxyQuery) 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 = &NotFoundError{galaxy.Label} + return + } + return ids[0], nil +} + +// FirstXID is like FirstID, but panics if an error occurs. +func (gq *GalaxyQuery) FirstXID(ctx context.Context) int { + id, err := gq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns the only Galaxy entity in the query, returns an error if not exactly one entity was returned. +func (gq *GalaxyQuery) Only(ctx context.Context) (*Galaxy, error) { + gas, err := gq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(gas) { + case 1: + return gas[0], nil + case 0: + return nil, &NotFoundError{galaxy.Label} + default: + return nil, &NotSingularError{galaxy.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (gq *GalaxyQuery) OnlyX(ctx context.Context) *Galaxy { + ga, err := gq.Only(ctx) + if err != nil { + panic(err) + } + return ga +} + +// OnlyID returns the only Galaxy id in the query, returns an error if not exactly one id was returned. +func (gq *GalaxyQuery) 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 = &NotFoundError{galaxy.Label} + default: + err = &NotSingularError{galaxy.Label} + } + return +} + +// OnlyXID is like OnlyID, but panics if an error occurs. +func (gq *GalaxyQuery) 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 Galaxies. +func (gq *GalaxyQuery) All(ctx context.Context) ([]*Galaxy, error) { + if err := gq.prepareQuery(ctx); err != nil { + return nil, err + } + return gq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (gq *GalaxyQuery) AllX(ctx context.Context) []*Galaxy { + gas, err := gq.All(ctx) + if err != nil { + panic(err) + } + return gas +} + +// IDs executes the query and returns a list of Galaxy ids. +func (gq *GalaxyQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := gq.Select(galaxy.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (gq *GalaxyQuery) 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 *GalaxyQuery) Count(ctx context.Context) (int, error) { + if err := gq.prepareQuery(ctx); err != nil { + return 0, err + } + return gq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (gq *GalaxyQuery) 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 *GalaxyQuery) Exist(ctx context.Context) (bool, error) { + if err := gq.prepareQuery(ctx); err != nil { + return false, err + } + return gq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (gq *GalaxyQuery) 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 *GalaxyQuery) Clone() *GalaxyQuery { + return &GalaxyQuery{ + config: gq.config, + limit: gq.limit, + offset: gq.offset, + order: append([]Order{}, gq.order...), + unique: append([]string{}, gq.unique...), + predicates: append([]predicate.Galaxy{}, gq.predicates...), + // clone intermediate query. + sql: gq.sql.Clone(), + path: gq.path, + } +} + +// WithPlanets tells the query-builder to eager-loads the nodes that are connected to +// the "planets" edge. The optional arguments used to configure the query builder of the edge. +func (gq *GalaxyQuery) WithPlanets(opts ...func(*PlanetQuery)) *GalaxyQuery { + query := &PlanetQuery{config: gq.config} + for _, opt := range opts { + opt(query) + } + gq.withPlanets = query + return gq +} + +// 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.Galaxy.Query(). +// GroupBy(galaxy.FieldName). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +// +func (gq *GalaxyQuery) GroupBy(field string, fields ...string) *GalaxyGroupBy { + group := &GalaxyGroupBy{config: gq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := gq.prepareQuery(ctx); err != nil { + return nil, err + } + return gq.sqlQuery(), nil + } + return group +} + +// Select one or more fields from the given query. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// } +// +// client.Galaxy.Query(). +// Select(galaxy.FieldName). +// Scan(ctx, &v) +// +func (gq *GalaxyQuery) Select(field string, fields ...string) *GalaxySelect { + selector := &GalaxySelect{config: gq.config} + selector.fields = append([]string{field}, fields...) + selector.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := gq.prepareQuery(ctx); err != nil { + return nil, err + } + return gq.sqlQuery(), nil + } + return selector +} + +func (gq *GalaxyQuery) prepareQuery(ctx context.Context) error { + if gq.path != nil { + prev, err := gq.path(ctx) + if err != nil { + return err + } + gq.sql = prev + } + if err := galaxy.Policy.EvalQuery(ctx, gq); err != nil { + return err + } + return nil +} + +func (gq *GalaxyQuery) sqlAll(ctx context.Context) ([]*Galaxy, error) { + var ( + nodes = []*Galaxy{} + _spec = gq.querySpec() + loadedTypes = [1]bool{ + gq.withPlanets != nil, + } + ) + _spec.ScanValues = func() []interface{} { + node := &Galaxy{config: gq.config} + nodes = append(nodes, node) + values := node.scanValues() + return values + } + _spec.Assign = func(values ...interface{}) error { + if len(nodes) == 0 { + return fmt.Errorf("ent: Assign called without calling ScanValues") + } + node := nodes[len(nodes)-1] + node.Edges.loadedTypes = loadedTypes + return node.assignValues(values...) + } + if err := sqlgraph.QueryNodes(ctx, gq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + + if query := gq.withPlanets; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*Galaxy) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + } + query.withFKs = true + query.Where(predicate.Planet(func(s *sql.Selector) { + s.Where(sql.InValues(galaxy.PlanetsColumn, fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + fk := n.galaxy_planets + if fk == nil { + return nil, fmt.Errorf(`foreign-key "galaxy_planets" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "galaxy_planets" returned %v for node %v`, *fk, n.ID) + } + node.Edges.Planets = append(node.Edges.Planets, n) + } + } + + return nodes, nil +} + +func (gq *GalaxyQuery) sqlCount(ctx context.Context) (int, error) { + _spec := gq.querySpec() + return sqlgraph.CountNodes(ctx, gq.driver, _spec) +} + +func (gq *GalaxyQuery) 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 *GalaxyQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: galaxy.Table, + Columns: galaxy.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: galaxy.FieldID, + }, + }, + From: gq.sql, + Unique: true, + } + if ps := gq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := gq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := gq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := gq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (gq *GalaxyQuery) sqlQuery() *sql.Selector { + builder := sql.Dialect(gq.driver.Dialect()) + t1 := builder.Table(galaxy.Table) + selector := builder.Select(t1.Columns(galaxy.Columns...)...).From(t1) + if gq.sql != nil { + selector = gq.sql + selector.Select(selector.Columns(galaxy.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.MaxInt32) + } + if limit := gq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// GalaxyGroupBy is the builder for group-by Galaxy entities. +type GalaxyGroupBy struct { + config + fields []string + fns []Aggregate + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (ggb *GalaxyGroupBy) Aggregate(fns ...Aggregate) *GalaxyGroupBy { + ggb.fns = append(ggb.fns, fns...) + return ggb +} + +// Scan applies the group-by query and scan the result into the given value. +func (ggb *GalaxyGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := ggb.path(ctx) + if err != nil { + return err + } + ggb.sql = query + return ggb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (ggb *GalaxyGroupBy) 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 *GalaxyGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(ggb.fields) > 1 { + return nil, errors.New("ent: GalaxyGroupBy.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 *GalaxyGroupBy) 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 *GalaxyGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(ggb.fields) > 1 { + return nil, errors.New("ent: GalaxyGroupBy.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 *GalaxyGroupBy) 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 *GalaxyGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(ggb.fields) > 1 { + return nil, errors.New("ent: GalaxyGroupBy.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 *GalaxyGroupBy) 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 *GalaxyGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(ggb.fields) > 1 { + return nil, errors.New("ent: GalaxyGroupBy.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 *GalaxyGroupBy) BoolsX(ctx context.Context) []bool { + v, err := ggb.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +func (ggb *GalaxyGroupBy) 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 *GalaxyGroupBy) 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(selector)) + } + return selector.Select(columns...).GroupBy(ggb.fields...) +} + +// GalaxySelect is the builder for select fields of Galaxy entities. +type GalaxySelect struct { + config + fields []string + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Scan applies the selector query and scan the result into the given value. +func (gs *GalaxySelect) Scan(ctx context.Context, v interface{}) error { + query, err := gs.path(ctx) + if err != nil { + return err + } + gs.sql = query + return gs.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (gs *GalaxySelect) 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 *GalaxySelect) Strings(ctx context.Context) ([]string, error) { + if len(gs.fields) > 1 { + return nil, errors.New("ent: GalaxySelect.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 *GalaxySelect) 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 *GalaxySelect) Ints(ctx context.Context) ([]int, error) { + if len(gs.fields) > 1 { + return nil, errors.New("ent: GalaxySelect.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 *GalaxySelect) 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 *GalaxySelect) Float64s(ctx context.Context) ([]float64, error) { + if len(gs.fields) > 1 { + return nil, errors.New("ent: GalaxySelect.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 *GalaxySelect) 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 *GalaxySelect) Bools(ctx context.Context) ([]bool, error) { + if len(gs.fields) > 1 { + return nil, errors.New("ent: GalaxySelect.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 *GalaxySelect) BoolsX(ctx context.Context) []bool { + v, err := gs.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +func (gs *GalaxySelect) 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 *GalaxySelect) sqlQuery() sql.Querier { + selector := gs.sql + selector.Select(selector.Columns(gs.fields...)...) + return selector +} diff --git a/entc/integration/privacy/ent/galaxy_update.go b/entc/integration/privacy/ent/galaxy_update.go new file mode 100644 index 000000000..23d94333f --- /dev/null +++ b/entc/integration/privacy/ent/galaxy_update.go @@ -0,0 +1,409 @@ +// 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 by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + + "github.com/facebookincubator/ent/dialect/sql" + "github.com/facebookincubator/ent/dialect/sql/sqlgraph" + "github.com/facebookincubator/ent/entc/integration/privacy/ent/galaxy" + "github.com/facebookincubator/ent/entc/integration/privacy/ent/planet" + "github.com/facebookincubator/ent/entc/integration/privacy/ent/predicate" + "github.com/facebookincubator/ent/schema/field" +) + +// GalaxyUpdate is the builder for updating Galaxy entities. +type GalaxyUpdate struct { + config + hooks []Hook + mutation *GalaxyMutation + predicates []predicate.Galaxy +} + +// Where adds a new predicate for the builder. +func (gu *GalaxyUpdate) Where(ps ...predicate.Galaxy) *GalaxyUpdate { + gu.predicates = append(gu.predicates, ps...) + return gu +} + +// SetName sets the name field. +func (gu *GalaxyUpdate) SetName(s string) *GalaxyUpdate { + gu.mutation.SetName(s) + return gu +} + +// SetType sets the type field. +func (gu *GalaxyUpdate) SetType(ga galaxy.Type) *GalaxyUpdate { + gu.mutation.SetType(ga) + return gu +} + +// AddPlanetIDs adds the planets edge to Planet by ids. +func (gu *GalaxyUpdate) AddPlanetIDs(ids ...int) *GalaxyUpdate { + gu.mutation.AddPlanetIDs(ids...) + return gu +} + +// AddPlanets adds the planets edges to Planet. +func (gu *GalaxyUpdate) AddPlanets(p ...*Planet) *GalaxyUpdate { + ids := make([]int, len(p)) + for i := range p { + ids[i] = p[i].ID + } + return gu.AddPlanetIDs(ids...) +} + +// RemovePlanetIDs removes the planets edge to Planet by ids. +func (gu *GalaxyUpdate) RemovePlanetIDs(ids ...int) *GalaxyUpdate { + gu.mutation.RemovePlanetIDs(ids...) + return gu +} + +// RemovePlanets removes planets edges to Planet. +func (gu *GalaxyUpdate) RemovePlanets(p ...*Planet) *GalaxyUpdate { + ids := make([]int, len(p)) + for i := range p { + ids[i] = p[i].ID + } + return gu.RemovePlanetIDs(ids...) +} + +// Save executes the query and returns the number of rows/vertices matched by this operation. +func (gu *GalaxyUpdate) Save(ctx context.Context) (int, error) { + if v, ok := gu.mutation.Name(); ok { + if err := galaxy.NameValidator(v); err != nil { + return 0, fmt.Errorf("ent: validator failed for field \"name\": %v", err) + } + } + if v, ok := gu.mutation.GetType(); ok { + if err := galaxy.TypeValidator(v); err != nil { + return 0, fmt.Errorf("ent: validator failed for field \"type\": %v", err) + } + } + + var ( + err error + affected int + ) + if len(gu.hooks) == 0 { + affected, err = gu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*GalaxyMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + gu.mutation = mutation + affected, err = gu.sqlSave(ctx) + return affected, err + }) + for i := len(gu.hooks) - 1; i >= 0; i-- { + mut = gu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, gu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (gu *GalaxyUpdate) SaveX(ctx context.Context) int { + affected, err := gu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (gu *GalaxyUpdate) Exec(ctx context.Context) error { + _, err := gu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (gu *GalaxyUpdate) ExecX(ctx context.Context) { + if err := gu.Exec(ctx); err != nil { + panic(err) + } +} + +func (gu *GalaxyUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: galaxy.Table, + Columns: galaxy.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: galaxy.FieldID, + }, + }, + } + if ps := gu.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := gu.mutation.Name(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: galaxy.FieldName, + }) + } + if value, ok := gu.mutation.GetType(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeEnum, + Value: value, + Column: galaxy.FieldType, + }) + } + if nodes := gu.mutation.RemovedPlanetsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: galaxy.PlanetsTable, + Columns: []string{galaxy.PlanetsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: planet.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := gu.mutation.PlanetsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: galaxy.PlanetsTable, + Columns: []string{galaxy.PlanetsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: planet.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if n, err = sqlgraph.UpdateNodes(ctx, gu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{galaxy.Label} + } else if cerr, ok := isSQLConstraintError(err); ok { + err = cerr + } + return 0, err + } + return n, nil +} + +// GalaxyUpdateOne is the builder for updating a single Galaxy entity. +type GalaxyUpdateOne struct { + config + hooks []Hook + mutation *GalaxyMutation +} + +// SetName sets the name field. +func (guo *GalaxyUpdateOne) SetName(s string) *GalaxyUpdateOne { + guo.mutation.SetName(s) + return guo +} + +// SetType sets the type field. +func (guo *GalaxyUpdateOne) SetType(ga galaxy.Type) *GalaxyUpdateOne { + guo.mutation.SetType(ga) + return guo +} + +// AddPlanetIDs adds the planets edge to Planet by ids. +func (guo *GalaxyUpdateOne) AddPlanetIDs(ids ...int) *GalaxyUpdateOne { + guo.mutation.AddPlanetIDs(ids...) + return guo +} + +// AddPlanets adds the planets edges to Planet. +func (guo *GalaxyUpdateOne) AddPlanets(p ...*Planet) *GalaxyUpdateOne { + ids := make([]int, len(p)) + for i := range p { + ids[i] = p[i].ID + } + return guo.AddPlanetIDs(ids...) +} + +// RemovePlanetIDs removes the planets edge to Planet by ids. +func (guo *GalaxyUpdateOne) RemovePlanetIDs(ids ...int) *GalaxyUpdateOne { + guo.mutation.RemovePlanetIDs(ids...) + return guo +} + +// RemovePlanets removes planets edges to Planet. +func (guo *GalaxyUpdateOne) RemovePlanets(p ...*Planet) *GalaxyUpdateOne { + ids := make([]int, len(p)) + for i := range p { + ids[i] = p[i].ID + } + return guo.RemovePlanetIDs(ids...) +} + +// Save executes the query and returns the updated entity. +func (guo *GalaxyUpdateOne) Save(ctx context.Context) (*Galaxy, error) { + if v, ok := guo.mutation.Name(); ok { + if err := galaxy.NameValidator(v); err != nil { + return nil, fmt.Errorf("ent: validator failed for field \"name\": %v", err) + } + } + if v, ok := guo.mutation.GetType(); ok { + if err := galaxy.TypeValidator(v); err != nil { + return nil, fmt.Errorf("ent: validator failed for field \"type\": %v", err) + } + } + + var ( + err error + node *Galaxy + ) + if len(guo.hooks) == 0 { + node, err = guo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*GalaxyMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + guo.mutation = mutation + node, err = guo.sqlSave(ctx) + return node, err + }) + for i := len(guo.hooks) - 1; i >= 0; i-- { + mut = guo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, guo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (guo *GalaxyUpdateOne) SaveX(ctx context.Context) *Galaxy { + ga, err := guo.Save(ctx) + if err != nil { + panic(err) + } + return ga +} + +// Exec executes the query on the entity. +func (guo *GalaxyUpdateOne) Exec(ctx context.Context) error { + _, err := guo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (guo *GalaxyUpdateOne) ExecX(ctx context.Context) { + if err := guo.Exec(ctx); err != nil { + panic(err) + } +} + +func (guo *GalaxyUpdateOne) sqlSave(ctx context.Context) (ga *Galaxy, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: galaxy.Table, + Columns: galaxy.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: galaxy.FieldID, + }, + }, + } + id, ok := guo.mutation.ID() + if !ok { + return nil, fmt.Errorf("missing Galaxy.ID for update") + } + _spec.Node.ID.Value = id + if value, ok := guo.mutation.Name(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: galaxy.FieldName, + }) + } + if value, ok := guo.mutation.GetType(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeEnum, + Value: value, + Column: galaxy.FieldType, + }) + } + if nodes := guo.mutation.RemovedPlanetsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: galaxy.PlanetsTable, + Columns: []string{galaxy.PlanetsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: planet.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := guo.mutation.PlanetsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: galaxy.PlanetsTable, + Columns: []string{galaxy.PlanetsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: planet.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + ga = &Galaxy{config: guo.config} + _spec.Assign = ga.assignValues + _spec.ScanValues = ga.scanValues() + if err = sqlgraph.UpdateNode(ctx, guo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{galaxy.Label} + } else if cerr, ok := isSQLConstraintError(err); ok { + err = cerr + } + return nil, err + } + return ga, nil +} diff --git a/entc/integration/privacy/ent/hook/hook.go b/entc/integration/privacy/ent/hook/hook.go index 40669371b..f43075a2e 100644 --- a/entc/integration/privacy/ent/hook/hook.go +++ b/entc/integration/privacy/ent/hook/hook.go @@ -13,6 +13,19 @@ import ( "github.com/facebookincubator/ent/entc/integration/privacy/ent" ) +// The GalaxyFunc type is an adapter to allow the use of ordinary +// function as Galaxy mutator. +type GalaxyFunc func(context.Context, *ent.GalaxyMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f GalaxyFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + mv, ok := m.(*ent.GalaxyMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GalaxyMutation", m) + } + return f(ctx, mv) +} + // The PlanetFunc type is an adapter to allow the use of ordinary // function as Planet mutator. type PlanetFunc func(context.Context, *ent.PlanetMutation) (ent.Value, error) diff --git a/entc/integration/privacy/ent/migrate/schema.go b/entc/integration/privacy/ent/migrate/schema.go index 3b67a85e4..266d2db88 100644 --- a/entc/integration/privacy/ent/migrate/schema.go +++ b/entc/integration/privacy/ent/migrate/schema.go @@ -12,18 +12,40 @@ import ( ) var ( + // GalaxiesColumns holds the columns for the "galaxies" table. + GalaxiesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "name", Type: field.TypeString, Unique: true}, + {Name: "type", Type: field.TypeEnum, Enums: []string{"spiral", "barred_spiral", "elliptical", "irregular"}}, + } + // GalaxiesTable holds the schema information for the "galaxies" table. + GalaxiesTable = &schema.Table{ + Name: "galaxies", + Columns: GalaxiesColumns, + PrimaryKey: []*schema.Column{GalaxiesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{}, + } // PlanetsColumns holds the columns for the "planets" table. PlanetsColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, {Name: "name", Type: field.TypeString, Unique: true}, {Name: "age", Type: field.TypeUint, Nullable: true}, + {Name: "galaxy_planets", Type: field.TypeInt, Nullable: true}, } // PlanetsTable holds the schema information for the "planets" table. PlanetsTable = &schema.Table{ - Name: "planets", - Columns: PlanetsColumns, - PrimaryKey: []*schema.Column{PlanetsColumns[0]}, - ForeignKeys: []*schema.ForeignKey{}, + Name: "planets", + Columns: PlanetsColumns, + PrimaryKey: []*schema.Column{PlanetsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "planets_galaxies_planets", + Columns: []*schema.Column{PlanetsColumns[3]}, + + RefColumns: []*schema.Column{GalaxiesColumns[0]}, + OnDelete: schema.SetNull, + }, + }, } // PlanetNeighborsColumns holds the columns for the "planet_neighbors" table. PlanetNeighborsColumns = []*schema.Column{ @@ -54,12 +76,14 @@ var ( } // Tables holds all the tables in the schema. Tables = []*schema.Table{ + GalaxiesTable, PlanetsTable, PlanetNeighborsTable, } ) func init() { + PlanetsTable.ForeignKeys[0].RefTable = GalaxiesTable PlanetNeighborsTable.ForeignKeys[0].RefTable = PlanetsTable PlanetNeighborsTable.ForeignKeys[1].RefTable = PlanetsTable } diff --git a/entc/integration/privacy/ent/mutation.go b/entc/integration/privacy/ent/mutation.go index 0ed86c4ac..851fe822a 100644 --- a/entc/integration/privacy/ent/mutation.go +++ b/entc/integration/privacy/ent/mutation.go @@ -9,6 +9,7 @@ package ent import ( "fmt" + "github.com/facebookincubator/ent/entc/integration/privacy/ent/galaxy" "github.com/facebookincubator/ent/entc/integration/privacy/ent/planet" "github.com/facebookincubator/ent" @@ -23,9 +24,343 @@ const ( OpUpdateOne = ent.OpUpdateOne // Node types. + TypeGalaxy = "Galaxy" TypePlanet = "Planet" ) +// GalaxyMutation represents an operation that mutate the Galaxies +// nodes in the graph. +type GalaxyMutation struct { + config + op Op + typ string + id *int + name *string + _type *galaxy.Type + clearedFields map[string]struct{} + planets map[int]struct{} + removedplanets map[int]struct{} +} + +var _ ent.Mutation = (*GalaxyMutation)(nil) + +// newGalaxyMutation creates new mutation for $n.Name. +func newGalaxyMutation(c config, op Op) *GalaxyMutation { + return &GalaxyMutation{ + config: c, + op: op, + typ: TypeGalaxy, + clearedFields: make(map[string]struct{}), + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m GalaxyMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m GalaxyMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, fmt.Errorf("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// ID returns the id value in the mutation. Note that, the id +// is available only if it was provided to the builder. +func (m *GalaxyMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// SetName sets the name field. +func (m *GalaxyMutation) SetName(s string) { + m.name = &s +} + +// Name returns the name value in the mutation. +func (m *GalaxyMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// ResetName reset all changes of the name field. +func (m *GalaxyMutation) ResetName() { + m.name = nil +} + +// SetType sets the type field. +func (m *GalaxyMutation) SetType(ga galaxy.Type) { + m._type = &ga +} + +// GetType returns the type value in the mutation. +func (m *GalaxyMutation) GetType() (r galaxy.Type, exists bool) { + v := m._type + if v == nil { + return + } + return *v, true +} + +// ResetType reset all changes of the type field. +func (m *GalaxyMutation) ResetType() { + m._type = nil +} + +// AddPlanetIDs adds the planets edge to Planet by ids. +func (m *GalaxyMutation) AddPlanetIDs(ids ...int) { + if m.planets == nil { + m.planets = make(map[int]struct{}) + } + for i := range ids { + m.planets[ids[i]] = struct{}{} + } +} + +// RemovePlanetIDs removes the planets edge to Planet by ids. +func (m *GalaxyMutation) RemovePlanetIDs(ids ...int) { + if m.removedplanets == nil { + m.removedplanets = make(map[int]struct{}) + } + for i := range ids { + m.removedplanets[ids[i]] = struct{}{} + } +} + +// RemovedPlanets returns the removed ids of planets. +func (m *GalaxyMutation) RemovedPlanetsIDs() (ids []int) { + for id := range m.removedplanets { + ids = append(ids, id) + } + return +} + +// PlanetsIDs returns the planets ids in the mutation. +func (m *GalaxyMutation) PlanetsIDs() (ids []int) { + for id := range m.planets { + ids = append(ids, id) + } + return +} + +// ResetPlanets reset all changes of the planets edge. +func (m *GalaxyMutation) ResetPlanets() { + m.planets = nil + m.removedplanets = nil +} + +// Op returns the operation name. +func (m *GalaxyMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (Galaxy). +func (m *GalaxyMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during +// this mutation. Note that, in order to get all numeric +// fields that were in/decremented, call AddedFields(). +func (m *GalaxyMutation) Fields() []string { + fields := make([]string, 0, 2) + if m.name != nil { + fields = append(fields, galaxy.FieldName) + } + if m._type != nil { + fields = append(fields, galaxy.FieldType) + } + return fields +} + +// Field returns the value of a field with the given name. +// The second boolean value indicates that this field was +// not set, or was not define in the schema. +func (m *GalaxyMutation) Field(name string) (ent.Value, bool) { + switch name { + case galaxy.FieldName: + return m.Name() + case galaxy.FieldType: + return m.GetType() + } + return nil, false +} + +// SetField sets the value for the given name. It returns an +// error if the field is not defined in the schema, or if the +// type mismatch the field type. +func (m *GalaxyMutation) SetField(name string, value ent.Value) error { + switch name { + case galaxy.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case galaxy.FieldType: + v, ok := value.(galaxy.Type) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetType(v) + return nil + } + return fmt.Errorf("unknown Galaxy field %s", name) +} + +// AddedFields returns all numeric fields that were incremented +// or decremented during this mutation. +func (m *GalaxyMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was in/decremented +// from a field with the given name. The second value indicates +// that this field was not set, or was not define in the schema. +func (m *GalaxyMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value for the given name. It returns an +// error if the field is not defined in the schema, or if the +// type mismatch the field type. +func (m *GalaxyMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Galaxy numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared +// during this mutation. +func (m *GalaxyMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicates if this field was +// cleared in this mutation. +func (m *GalaxyMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value for the given name. It returns an +// error if the field is not defined in the schema. +func (m *GalaxyMutation) ClearField(name string) error { + return fmt.Errorf("unknown Galaxy nullable field %s", name) +} + +// ResetField resets all changes in the mutation regarding the +// given field name. It returns an error if the field is not +// defined in the schema. +func (m *GalaxyMutation) ResetField(name string) error { + switch name { + case galaxy.FieldName: + m.ResetName() + return nil + case galaxy.FieldType: + m.ResetType() + return nil + } + return fmt.Errorf("unknown Galaxy field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this +// mutation. +func (m *GalaxyMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.planets != nil { + edges = append(edges, galaxy.EdgePlanets) + } + return edges +} + +// AddedIDs returns all ids (to other nodes) that were added for +// the given edge name. +func (m *GalaxyMutation) AddedIDs(name string) []ent.Value { + switch name { + case galaxy.EdgePlanets: + ids := make([]ent.Value, 0, len(m.planets)) + for id := range m.planets { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this +// mutation. +func (m *GalaxyMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + if m.removedplanets != nil { + edges = append(edges, galaxy.EdgePlanets) + } + return edges +} + +// RemovedIDs returns all ids (to other nodes) that were removed for +// the given edge name. +func (m *GalaxyMutation) RemovedIDs(name string) []ent.Value { + switch name { + case galaxy.EdgePlanets: + ids := make([]ent.Value, 0, len(m.removedplanets)) + for id := range m.removedplanets { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this +// mutation. +func (m *GalaxyMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + return edges +} + +// EdgeCleared returns a boolean indicates if this edge was +// cleared in this mutation. +func (m *GalaxyMutation) EdgeCleared(name string) bool { + switch name { + } + return false +} + +// ClearEdge clears the value for the given name. It returns an +// error if the edge name is not defined in the schema. +func (m *GalaxyMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown Galaxy unique edge %s", name) +} + +// ResetEdge resets all changes in the mutation regarding the +// given edge name. It returns an error if the edge is not +// defined in the schema. +func (m *GalaxyMutation) ResetEdge(name string) error { + switch name { + case galaxy.EdgePlanets: + m.ResetPlanets() + return nil + } + return fmt.Errorf("unknown Galaxy edge %s", name) +} + // PlanetMutation represents an operation that mutate the Planets // nodes in the graph. type PlanetMutation struct { diff --git a/entc/integration/privacy/ent/planet.go b/entc/integration/privacy/ent/planet.go index 95d0ee00d..480fdb407 100644 --- a/entc/integration/privacy/ent/planet.go +++ b/entc/integration/privacy/ent/planet.go @@ -25,7 +25,8 @@ type Planet struct { Age uint `json:"age,omitempty"` // Edges holds the relations/edges for other nodes in the graph. // The values are being populated by the PlanetQuery when eager-loading is set. - Edges PlanetEdges `json:"edges"` + Edges PlanetEdges `json:"edges"` + galaxy_planets *int } // PlanetEdges holds the relations/edges for other nodes in the graph. @@ -55,6 +56,13 @@ func (*Planet) scanValues() []interface{} { } } +// fkValues returns the types for scanning foreign-keys values from sql.Rows. +func (*Planet) fkValues() []interface{} { + return []interface{}{ + &sql.NullInt64{}, // galaxy_planets + } +} + // assignValues assigns the values that were returned from sql.Rows (after scanning) // to the Planet fields. func (pl *Planet) assignValues(values ...interface{}) error { @@ -77,6 +85,15 @@ func (pl *Planet) assignValues(values ...interface{}) error { } else if value.Valid { pl.Age = uint(value.Int64) } + values = values[2:] + if len(values) == len(planet.ForeignKeys) { + if value, ok := values[0].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field galaxy_planets", value) + } else if value.Valid { + pl.galaxy_planets = new(int) + *pl.galaxy_planets = int(value.Int64) + } + } return nil } diff --git a/entc/integration/privacy/ent/planet/planet.go b/entc/integration/privacy/ent/planet/planet.go index 8064fba26..2a2955ba2 100644 --- a/entc/integration/privacy/ent/planet/planet.go +++ b/entc/integration/privacy/ent/planet/planet.go @@ -34,6 +34,11 @@ var Columns = []string{ FieldAge, } +// ForeignKeys holds the SQL foreign-keys that are owned by the Planet type. +var ForeignKeys = []string{ + "galaxy_planets", +} + var ( // NeighborsPrimaryKey and NeighborsColumn2 are the table columns denoting the // primary key for the neighbors relation (M2M). diff --git a/entc/integration/privacy/ent/planet_query.go b/entc/integration/privacy/ent/planet_query.go index 5787cc0fa..25e44ba8d 100644 --- a/entc/integration/privacy/ent/planet_query.go +++ b/entc/integration/privacy/ent/planet_query.go @@ -30,6 +30,7 @@ type PlanetQuery struct { predicates []predicate.Planet // eager-loading edges. withNeighbors *PlanetQuery + withFKs bool // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -335,15 +336,22 @@ func (pq *PlanetQuery) prepareQuery(ctx context.Context) error { func (pq *PlanetQuery) sqlAll(ctx context.Context) ([]*Planet, error) { var ( nodes = []*Planet{} + withFKs = pq.withFKs _spec = pq.querySpec() loadedTypes = [1]bool{ pq.withNeighbors != nil, } ) + if withFKs { + _spec.Node.Columns = append(_spec.Node.Columns, planet.ForeignKeys...) + } _spec.ScanValues = func() []interface{} { node := &Planet{config: pq.config} nodes = append(nodes, node) values := node.scanValues() + if withFKs { + values = append(values, node.fkValues()...) + } return values } _spec.Assign = func(values ...interface{}) error { diff --git a/entc/integration/privacy/ent/predicate/predicate.go b/entc/integration/privacy/ent/predicate/predicate.go index ed57b7031..dbf8435c3 100644 --- a/entc/integration/privacy/ent/predicate/predicate.go +++ b/entc/integration/privacy/ent/predicate/predicate.go @@ -10,5 +10,8 @@ import ( "github.com/facebookincubator/ent/dialect/sql" ) +// Galaxy is the predicate function for galaxy builders. +type Galaxy func(*sql.Selector) + // Planet is the predicate function for planet builders. type Planet func(*sql.Selector) diff --git a/entc/integration/privacy/ent/privacy/privacy.go b/entc/integration/privacy/ent/privacy/privacy.go index d0ac3d88b..d7ad9407a 100644 --- a/entc/integration/privacy/ent/privacy/privacy.go +++ b/entc/integration/privacy/ent/privacy/privacy.go @@ -148,6 +148,30 @@ type fixedDecisionRule struct{ err error } func (f fixedDecisionRule) EvalQuery(context.Context, ent.Query) error { return f.err } func (f fixedDecisionRule) EvalMutation(context.Context, ent.Mutation) error { return f.err } +// The GalaxyQueryRuleFunc type is an adapter to allow the use of ordinary +// functions as a query rule. +type GalaxyQueryRuleFunc func(context.Context, *ent.GalaxyQuery) error + +// EvalQuery return f(ctx, q). +func (f GalaxyQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error { + if q, ok := q.(*ent.GalaxyQuery); ok { + return f(ctx, q) + } + return Denyf("ent/privacy: unexpected query type %T, expect *ent.GalaxyQuery", q) +} + +// The GalaxyMutationRuleFunc type is an adapter to allow the use of ordinary +// functions as a mutation rule. +type GalaxyMutationRuleFunc func(context.Context, *ent.GalaxyMutation) error + +// EvalMutation calls f(ctx, m). +func (f GalaxyMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error { + if m, ok := m.(*ent.GalaxyMutation); ok { + return f(ctx, m) + } + return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.GalaxyMutation", m) +} + // The PlanetQueryRuleFunc type is an adapter to allow the use of ordinary // functions as a query rule. type PlanetQueryRuleFunc func(context.Context, *ent.PlanetQuery) error diff --git a/entc/integration/privacy/ent/runtime/runtime.go b/entc/integration/privacy/ent/runtime/runtime.go index a80124848..5890d2f70 100644 --- a/entc/integration/privacy/ent/runtime/runtime.go +++ b/entc/integration/privacy/ent/runtime/runtime.go @@ -9,6 +9,7 @@ package runtime import ( "context" + "github.com/facebookincubator/ent/entc/integration/privacy/ent/galaxy" "github.com/facebookincubator/ent/entc/integration/privacy/ent/planet" "github.com/facebookincubator/ent/entc/integration/privacy/ent/schema" @@ -19,6 +20,21 @@ import ( // code (default values, validators or hooks) and stitches it // to their package variables. func init() { + galaxy.Policy = schema.Galaxy{}.Policy() + galaxy.Hooks[0] = func(next ent.Mutator) ent.Mutator { + return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if err := galaxy.Policy.EvalMutation(ctx, m); err != nil { + return nil, err + } + return next.Mutate(ctx, m) + }) + } + galaxyFields := schema.Galaxy{}.Fields() + _ = galaxyFields + // galaxyDescName is the schema descriptor for name field. + galaxyDescName := galaxyFields[0].Descriptor() + // galaxy.NameValidator is a validator for the "name" field. It is called by the builders before save. + galaxy.NameValidator = galaxyDescName.Validators[0].(func(string) error) planet.Policy = schema.Planet{}.Policy() planet.Hooks[0] = func(next ent.Mutator) ent.Mutator { return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) { diff --git a/entc/integration/privacy/ent/schema/galaxy.go b/entc/integration/privacy/ent/schema/galaxy.go new file mode 100644 index 000000000..cf2f3edb8 --- /dev/null +++ b/entc/integration/privacy/ent/schema/galaxy.go @@ -0,0 +1,47 @@ +// 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. + +package schema + +import ( + "github.com/facebookincubator/ent/entc/integration/privacy/ent/privacy" + + "github.com/facebookincubator/ent/entc/integration/privacy/rule" + + "github.com/facebookincubator/ent" + "github.com/facebookincubator/ent/schema/edge" + "github.com/facebookincubator/ent/schema/field" +) + +// Galaxy defines the schema of a galaxy. +type Galaxy struct { + ent.Schema +} + +// Fields of the galaxy. +func (Galaxy) Fields() []ent.Field { + return []ent.Field{ + field.String("name"). + NotEmpty(). + Unique(), + field.Enum("type"). + Values("spiral", "barred_spiral", "elliptical", "irregular"), + } +} + +// Edges of the galaxy. +func (Galaxy) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("planets", Planet.Type), + } +} + +func (Galaxy) Policy() ent.Policy { + return privacy.Policy{ + Query: privacy.QueryPolicy{ + rule.FilterIrregularGalaxyRule(), + privacy.AlwaysAllowRule(), + }, + } +} diff --git a/entc/integration/privacy/ent/schema/planet.go b/entc/integration/privacy/ent/schema/planet.go index 8b5f22de0..967690f75 100644 --- a/entc/integration/privacy/ent/schema/planet.go +++ b/entc/integration/privacy/ent/schema/planet.go @@ -1,3 +1,7 @@ +// 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. + package schema import ( @@ -8,7 +12,7 @@ import ( "github.com/facebookincubator/ent/schema/field" ) -// Planet defines the schema of a rule. +// Planet defines the schema of a planet. type Planet struct { ent.Schema } diff --git a/entc/integration/privacy/ent/tx.go b/entc/integration/privacy/ent/tx.go index ade96ebba..d0c39e7ce 100644 --- a/entc/integration/privacy/ent/tx.go +++ b/entc/integration/privacy/ent/tx.go @@ -15,6 +15,8 @@ import ( // Tx is a transactional client that is created by calling Client.Tx(). type Tx struct { config + // Galaxy is the client for interacting with the Galaxy builders. + Galaxy *GalaxyClient // Planet is the client for interacting with the Planet builders. Planet *PlanetClient } @@ -37,6 +39,7 @@ func (tx *Tx) Client() *Client { } func (tx *Tx) init() { + tx.Galaxy = NewGalaxyClient(tx.config) tx.Planet = NewPlanetClient(tx.config) } @@ -47,7 +50,7 @@ func (tx *Tx) init() { // 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: Planet.QueryXXX(), the query will be executed +// applies a query, for example: Galaxy.QueryXXX(), the query will be executed // through the driver which created this transaction. // // Note that txDriver is not goroutine safe. diff --git a/entc/integration/privacy/privacy_test.go b/entc/integration/privacy/privacy_test.go index 58bd7b4cc..4f181dba4 100644 --- a/entc/integration/privacy/privacy_test.go +++ b/entc/integration/privacy/privacy_test.go @@ -6,10 +6,12 @@ import ( "testing" "github.com/facebookincubator/ent/entc/integration/privacy/ent" + "github.com/facebookincubator/ent/entc/integration/privacy/ent/galaxy" "github.com/facebookincubator/ent/entc/integration/privacy/ent/planet" "github.com/facebookincubator/ent/entc/integration/privacy/ent/privacy" _ "github.com/facebookincubator/ent/entc/integration/privacy/ent/runtime" "github.com/facebookincubator/ent/entc/integration/privacy/rule" + _ "github.com/mattn/go-sqlite3" "github.com/stretchr/testify/require" ) @@ -44,4 +46,9 @@ func TestPrivacyRules(t *testing.T) { mars.Update().SetAge(6_000_000_000).ExecX(ctx) count = client.Planet.Query().CountX(ctx) require.Equal(t, 2, count) + + client.Galaxy.Create().SetName("Milky Way").SetType(galaxy.TypeBarredSpiral).AddPlanets(earth, mars).SaveX(ctx) + client.Galaxy.Create().SetName("IC 3583").SetType(galaxy.TypeIrregular).SaveX(ctx) + count = client.Galaxy.Query().CountX(ctx) + require.Equal(t, 1, count) } diff --git a/entc/integration/privacy/rule/rule.go b/entc/integration/privacy/rule/rule.go index 3c10f5801..c0a822980 100644 --- a/entc/integration/privacy/rule/rule.go +++ b/entc/integration/privacy/rule/rule.go @@ -5,6 +5,7 @@ import ( "sync" "github.com/facebookincubator/ent/entc/integration/privacy/ent" + "github.com/facebookincubator/ent/entc/integration/privacy/ent/galaxy" "github.com/facebookincubator/ent/entc/integration/privacy/ent/hook" "github.com/facebookincubator/ent/entc/integration/privacy/ent/planet" "github.com/facebookincubator/ent/entc/integration/privacy/ent/privacy" @@ -47,6 +48,14 @@ func FilterZeroAgePlanetRule() privacy.QueryRule { }) } +// FilterIrregularGalaxyRule is a query rule that filters out irregular galaxies. +func FilterIrregularGalaxyRule() privacy.QueryRule { + return privacy.GalaxyQueryRuleFunc(func(ctx context.Context, q *ent.GalaxyQuery) error { + q.Where(galaxy.TypeNEQ(galaxy.TypeIrregular)) + return privacy.Skip + }) +} + var logger = struct { logf func(string, ...interface{}) sync.RWMutex