From 961dc08d148d3f00f8e1794830a86c253548c5d0 Mon Sep 17 00:00:00 2001 From: Ariel Mashraki <7413593+a8m@users.noreply.github.com> Date: Tue, 25 May 2021 20:45:37 +0300 Subject: [PATCH] examples/fs: add example for recursive traversals (#1599) --- dialect/sql/builder.go | 6 + examples/fs/ent/client.go | 249 ++++++ examples/fs/ent/config.go | 63 ++ examples/fs/ent/context.go | 37 + examples/fs/ent/ent.go | 283 +++++++ examples/fs/ent/enttest/enttest.go | 82 ++ examples/fs/ent/file.go | 172 ++++ examples/fs/ent/file/file.go | 57 ++ examples/fs/ent/file/where.go | 392 +++++++++ examples/fs/ent/file_create.go | 296 +++++++ examples/fs/ent/file_delete.go | 112 +++ examples/fs/ent/file_query.go | 1050 ++++++++++++++++++++++++ examples/fs/ent/file_update.go | 618 ++++++++++++++ examples/fs/ent/generate.go | 7 + examples/fs/ent/hook/hook.go | 208 +++++ examples/fs/ent/migrate/migrate.go | 76 ++ examples/fs/ent/migrate/schema.go | 44 + examples/fs/ent/mutation.go | 587 +++++++++++++ examples/fs/ent/predicate/predicate.go | 14 + examples/fs/ent/runtime.go | 24 + examples/fs/ent/runtime/runtime.go | 13 + examples/fs/ent/schema/file.go | 37 + examples/fs/ent/tx.go | 214 +++++ examples/fs/example_test.go | 91 ++ 24 files changed, 4732 insertions(+) create mode 100644 examples/fs/ent/client.go create mode 100644 examples/fs/ent/config.go create mode 100644 examples/fs/ent/context.go create mode 100644 examples/fs/ent/ent.go create mode 100644 examples/fs/ent/enttest/enttest.go create mode 100644 examples/fs/ent/file.go create mode 100644 examples/fs/ent/file/file.go create mode 100644 examples/fs/ent/file/where.go create mode 100644 examples/fs/ent/file_create.go create mode 100644 examples/fs/ent/file_delete.go create mode 100644 examples/fs/ent/file_query.go create mode 100644 examples/fs/ent/file_update.go create mode 100644 examples/fs/ent/generate.go create mode 100644 examples/fs/ent/hook/hook.go create mode 100644 examples/fs/ent/migrate/migrate.go create mode 100644 examples/fs/ent/migrate/schema.go create mode 100644 examples/fs/ent/mutation.go create mode 100644 examples/fs/ent/predicate/predicate.go create mode 100644 examples/fs/ent/runtime.go create mode 100644 examples/fs/ent/runtime/runtime.go create mode 100644 examples/fs/ent/schema/file.go create mode 100644 examples/fs/ent/tx.go create mode 100644 examples/fs/example_test.go diff --git a/dialect/sql/builder.go b/dialect/sql/builder.go index 198c1f20e..150245d0c 100644 --- a/dialect/sql/builder.go +++ b/dialect/sql/builder.go @@ -2110,6 +2110,9 @@ func (s *Selector) Query() (string, []interface{}) { }) b.WriteString(" AS ") b.Ident(t.as) + case *WithBuilder: + t.SetDialect(s.dialect) + b.Ident(t.name) } for _, join := range s.joins { b.WriteString(" " + join.kind + " ") @@ -2124,6 +2127,9 @@ func (s *Selector) Query() (string, []interface{}) { }) b.WriteString(" AS ") b.Ident(view.as) + case *WithBuilder: + view.SetDialect(s.dialect) + b.Ident(view.name) } if join.on != nil { b.WriteString(" ON ") diff --git a/examples/fs/ent/client.go b/examples/fs/ent/client.go new file mode 100644 index 000000000..d6d78e7d1 --- /dev/null +++ b/examples/fs/ent/client.go @@ -0,0 +1,249 @@ +// 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. + +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "log" + + "entgo.io/ent/examples/fs/ent/migrate" + + "entgo.io/ent/examples/fs/ent/file" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// 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 + // File is the client for interacting with the File builders. + File *FileClient +} + +// NewClient creates a new client configured with the given options. +func NewClient(opts ...Option) *Client { + cfg := config{log: log.Println, hooks: &hooks{}} + cfg.options(opts...) + client := &Client{config: cfg} + client.init() + return client +} + +func (c *Client) init() { + c.Schema = migrate.NewSchema(c.driver) + c.File = NewFileClient(c.config) +} + +// Open opens a database/sql.DB specified by the driver name and +// the 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.Postgres, 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. The provided context +// is used until the transaction is committed or rolled back. +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: %w", err) + } + cfg := c.config + cfg.driver = tx + return &Tx{ + ctx: ctx, + config: cfg, + File: NewFileClient(cfg), + }, nil +} + +// BeginTx returns a transactional client with specified options. +func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, fmt.Errorf("ent: cannot start a transaction within a transaction") + } + tx, err := c.driver.(interface { + BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error) + }).BeginTx(ctx, opts) + if err != nil { + return nil, fmt.Errorf("ent: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = &txDriver{tx: tx, drv: c.driver} + return &Tx{ + config: cfg, + File: NewFileClient(cfg), + }, nil +} + +// Debug returns a new debug-client. It's used to get verbose logging on specific operations. +// +// client.Debug(). +// File. +// Query(). +// Count(ctx) +// +func (c *Client) Debug() *Client { + if c.debug { + return c + } + cfg := c.config + cfg.driver = dialect.Debug(c.driver, c.log) + client := &Client{config: cfg} + client.init() + return client +} + +// Close closes the database connection and prevents new queries from starting. +func (c *Client) Close() error { + return c.driver.Close() +} + +// 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.File.Use(hooks...) +} + +// FileClient is a client for the File schema. +type FileClient struct { + config +} + +// NewFileClient returns a client for the File from the given config. +func NewFileClient(c config) *FileClient { + return &FileClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `file.Hooks(f(g(h())))`. +func (c *FileClient) Use(hooks ...Hook) { + c.hooks.File = append(c.hooks.File, hooks...) +} + +// Create returns a create builder for File. +func (c *FileClient) Create() *FileCreate { + mutation := newFileMutation(c.config, OpCreate) + return &FileCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of File entities. +func (c *FileClient) CreateBulk(builders ...*FileCreate) *FileCreateBulk { + return &FileCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for File. +func (c *FileClient) Update() *FileUpdate { + mutation := newFileMutation(c.config, OpUpdate) + return &FileUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *FileClient) UpdateOne(f *File) *FileUpdateOne { + mutation := newFileMutation(c.config, OpUpdateOne, withFile(f)) + return &FileUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *FileClient) UpdateOneID(id int) *FileUpdateOne { + mutation := newFileMutation(c.config, OpUpdateOne, withFileID(id)) + return &FileUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for File. +func (c *FileClient) Delete() *FileDelete { + mutation := newFileMutation(c.config, OpDelete) + return &FileDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *FileClient) DeleteOne(f *File) *FileDeleteOne { + return c.DeleteOneID(f.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *FileClient) DeleteOneID(id int) *FileDeleteOne { + builder := c.Delete().Where(file.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &FileDeleteOne{builder} +} + +// Query returns a query builder for File. +func (c *FileClient) Query() *FileQuery { + return &FileQuery{ + config: c.config, + } +} + +// Get returns a File entity by its id. +func (c *FileClient) Get(ctx context.Context, id int) (*File, error) { + return c.Query().Where(file.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *FileClient) GetX(ctx context.Context, id int) *File { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryParent queries the parent edge of a File. +func (c *FileClient) QueryParent(f *File) *FileQuery { + query := &FileQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := f.ID + step := sqlgraph.NewStep( + sqlgraph.From(file.Table, file.FieldID, id), + sqlgraph.To(file.Table, file.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, file.ParentTable, file.ParentColumn), + ) + fromV = sqlgraph.Neighbors(f.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChildren queries the children edge of a File. +func (c *FileClient) QueryChildren(f *File) *FileQuery { + query := &FileQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := f.ID + step := sqlgraph.NewStep( + sqlgraph.From(file.Table, file.FieldID, id), + sqlgraph.To(file.Table, file.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, file.ChildrenTable, file.ChildrenColumn), + ) + fromV = sqlgraph.Neighbors(f.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *FileClient) Hooks() []Hook { + return c.hooks.File +} diff --git a/examples/fs/ent/config.go b/examples/fs/ent/config.go new file mode 100644 index 000000000..22aba8840 --- /dev/null +++ b/examples/fs/ent/config.go @@ -0,0 +1,63 @@ +// 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. + +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "entgo.io/ent" + "entgo.io/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{}) + // hooks to execute on mutations. + hooks *hooks +} + +// hooks per client, for fast access. +type hooks struct { + File []ent.Hook +} + +// 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 + } +} diff --git a/examples/fs/ent/context.go b/examples/fs/ent/context.go new file mode 100644 index 000000000..7c21e0dbd --- /dev/null +++ b/examples/fs/ent/context.go @@ -0,0 +1,37 @@ +// 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. + +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" +) + +type clientCtxKey struct{} + +// FromContext returns a Client stored inside a context, or nil if there isn't one. +func FromContext(ctx context.Context) *Client { + c, _ := ctx.Value(clientCtxKey{}).(*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, clientCtxKey{}, c) +} + +type txCtxKey struct{} + +// TxFromContext returns a Tx stored inside a context, or nil if there isn't one. +func TxFromContext(ctx context.Context) *Tx { + tx, _ := ctx.Value(txCtxKey{}).(*Tx) + return tx +} + +// NewTxContext returns a new context with the given Tx attached. +func NewTxContext(parent context.Context, tx *Tx) context.Context { + return context.WithValue(parent, txCtxKey{}, tx) +} diff --git a/examples/fs/ent/ent.go b/examples/fs/ent/ent.go new file mode 100644 index 000000000..27ae4194e --- /dev/null +++ b/examples/fs/ent/ent.go @@ -0,0 +1,283 @@ +// 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. + +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "errors" + "fmt" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/fs/ent/file" +) + +// ent aliases to avoid import conflicts in user's code. +type ( + Op = ent.Op + Hook = ent.Hook + Value = ent.Value + Query = ent.Query + Policy = ent.Policy + Mutator = ent.Mutator + Mutation = ent.Mutation + MutateFunc = ent.MutateFunc +) + +// OrderFunc applies an ordering on the sql selector. +type OrderFunc func(*sql.Selector) + +// columnChecker returns a function indicates if the column exists in the given column. +func columnChecker(table string) func(string) error { + checks := map[string]func(string) bool{ + file.Table: file.ValidColumn, + } + check, ok := checks[table] + if !ok { + return func(string) error { + return fmt.Errorf("unknown table %q", table) + } + } + return func(column string) error { + if !check(column) { + return fmt.Errorf("unknown column %q for table %q", column, table) + } + return nil + } +} + +// Asc applies the given fields in ASC order. +func Asc(fields ...string) OrderFunc { + return func(s *sql.Selector) { + check := columnChecker(s.TableName()) + for _, f := range fields { + if err := check(f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)}) + } + s.OrderBy(sql.Asc(s.C(f))) + } + } +} + +// Desc applies the given fields in DESC order. +func Desc(fields ...string) OrderFunc { + return func(s *sql.Selector) { + check := columnChecker(s.TableName()) + for _, f := range fields { + if err := check(f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)}) + } + s.OrderBy(sql.Desc(s.C(f))) + } + } +} + +// AggregateFunc applies an aggregation step on the group-by traversal/selector. +type AggregateFunc 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 AggregateFunc, end string) AggregateFunc { + return func(s *sql.Selector) string { + return sql.As(fn(s), end) + } +} + +// Count applies the "count" aggregation function on each group. +func Count() AggregateFunc { + return 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) AggregateFunc { + return func(s *sql.Selector) string { + check := columnChecker(s.TableName()) + if err := check(field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) + return "" + } + return sql.Max(s.C(field)) + } +} + +// Mean applies the "mean" aggregation function on the given field of each group. +func Mean(field string) AggregateFunc { + return func(s *sql.Selector) string { + check := columnChecker(s.TableName()) + if err := check(field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) + return "" + } + return sql.Avg(s.C(field)) + } +} + +// Min applies the "min" aggregation function on the given field of each group. +func Min(field string) AggregateFunc { + return func(s *sql.Selector) string { + check := columnChecker(s.TableName()) + if err := check(field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) + return "" + } + return sql.Min(s.C(field)) + } +} + +// Sum applies the "sum" aggregation function on the given field of each group. +func Sum(field string) AggregateFunc { + return func(s *sql.Selector) string { + check := columnChecker(s.TableName()) + if err := check(field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) + return "" + } + return sql.Sum(s.C(field)) + } +} + +// ValidationError returns when validating a field fails. +type ValidationError struct { + Name string // Field or edge name. + err error +} + +// Error implements the error interface. +func (e *ValidationError) Error() string { + return e.err.Error() +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ValidationError) Unwrap() error { + return e.err +} + +// IsValidationError returns a boolean indicating whether the error is a validation error. +func IsValidationError(err error) bool { + if err == nil { + return false + } + var e *ValidationError + return errors.As(err, &e) +} + +// NotFoundError returns when trying to fetch a specific entity and it was not found in the database. +type NotFoundError struct { + label string +} + +// Error implements the error interface. +func (e *NotFoundError) Error() string { + return "ent: " + e.label + " not found" +} + +// IsNotFound returns a boolean indicating whether the error is a not found error. +func IsNotFound(err error) bool { + if err == nil { + return false + } + var e *NotFoundError + return errors.As(err, &e) +} + +// MaskNotFound masks not found error. +func MaskNotFound(err error) error { + if IsNotFound(err) { + return nil + } + return err +} + +// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database. +type NotSingularError struct { + label string +} + +// Error implements the error interface. +func (e *NotSingularError) Error() string { + return "ent: " + e.label + " not singular" +} + +// IsNotSingular returns a boolean indicating whether the error is a not singular error. +func IsNotSingular(err error) bool { + if err == nil { + return false + } + var e *NotSingularError + return errors.As(err, &e) +} + +// NotLoadedError returns when trying to get a node that was not loaded by the query. +type NotLoadedError struct { + edge string +} + +// Error implements the error interface. +func (e *NotLoadedError) Error() string { + return "ent: " + e.edge + " edge was not loaded" +} + +// IsNotLoaded returns a boolean indicating whether the error is a not loaded error. +func IsNotLoaded(err error) bool { + if err == nil { + return false + } + var e *NotLoadedError + return errors.As(err, &e) +} + +// ConstraintError 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 ConstraintError struct { + msg string + wrap error +} + +// Error implements the error interface. +func (e ConstraintError) Error() string { + return "ent: constraint failed: " + e.msg +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ConstraintError) Unwrap() error { + return e.wrap +} + +// IsConstraintError returns a boolean indicating whether the error is a constraint failure. +func IsConstraintError(err error) bool { + if err == nil { + return false + } + var e *ConstraintError + return errors.As(err, &e) +} + +func isSQLConstraintError(err error) (*ConstraintError, bool) { + if sqlgraph.IsConstraintError(err) { + return &ConstraintError{err.Error(), err}, true + } + return nil, false +} + +// rollback calls tx.Rollback and wraps the given error with the rollback error if present. +func rollback(tx dialect.Tx, err error) error { + if rerr := tx.Rollback(); rerr != nil { + err = fmt.Errorf("%w: %v", err, rerr) + } + if err, ok := isSQLConstraintError(err); ok { + return err + } + return err +} diff --git a/examples/fs/ent/enttest/enttest.go b/examples/fs/ent/enttest/enttest.go new file mode 100644 index 000000000..7a776d0d6 --- /dev/null +++ b/examples/fs/ent/enttest/enttest.go @@ -0,0 +1,82 @@ +// 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. + +// Code generated by entc, DO NOT EDIT. + +package enttest + +import ( + "context" + + "entgo.io/ent/examples/fs/ent" + // required by schema hooks. + _ "entgo.io/ent/examples/fs/ent/runtime" + + "entgo.io/ent/dialect/sql/schema" +) + +type ( + // TestingT is the interface that is shared between + // testing.T and testing.B and used by enttest. + TestingT interface { + FailNow() + Error(...interface{}) + } + + // Option configures client creation. + Option func(*options) + + options struct { + opts []ent.Option + migrateOpts []schema.MigrateOption + } +) + +// WithOptions forwards options to client creation. +func WithOptions(opts ...ent.Option) Option { + return func(o *options) { + o.opts = append(o.opts, opts...) + } +} + +// WithMigrateOptions forwards options to auto migration. +func WithMigrateOptions(opts ...schema.MigrateOption) Option { + return func(o *options) { + o.migrateOpts = append(o.migrateOpts, opts...) + } +} + +func newOptions(opts []Option) *options { + o := &options{} + for _, opt := range opts { + opt(o) + } + return o +} + +// Open calls ent.Open and auto-run migration. +func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Client { + o := newOptions(opts) + c, err := ent.Open(driverName, dataSourceName, o.opts...) + if err != nil { + t.Error(err) + t.FailNow() + } + if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil { + t.Error(err) + t.FailNow() + } + return c +} + +// NewClient calls ent.NewClient and auto-run migration. +func NewClient(t TestingT, opts ...Option) *ent.Client { + o := newOptions(opts) + c := ent.NewClient(o.opts...) + if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil { + t.Error(err) + t.FailNow() + } + return c +} diff --git a/examples/fs/ent/file.go b/examples/fs/ent/file.go new file mode 100644 index 000000000..a2d79d9e8 --- /dev/null +++ b/examples/fs/ent/file.go @@ -0,0 +1,172 @@ +// 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. + +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/examples/fs/ent/file" +) + +// File is the model entity for the File schema. +type File 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"` + // Deleted holds the value of the "deleted" field. + Deleted bool `json:"deleted,omitempty"` + // ParentID holds the value of the "parent_id" field. + ParentID int `json:"parent_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the FileQuery when eager-loading is set. + Edges FileEdges `json:"edges"` +} + +// FileEdges holds the relations/edges for other nodes in the graph. +type FileEdges struct { + // Parent holds the value of the parent edge. + Parent *File `json:"parent,omitempty"` + // Children holds the value of the children edge. + Children []*File `json:"children,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// ParentOrErr returns the Parent value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e FileEdges) ParentOrErr() (*File, error) { + if e.loadedTypes[0] { + if e.Parent == nil { + // The edge parent was loaded in eager-loading, + // but was not found. + return nil, &NotFoundError{label: file.Label} + } + return e.Parent, nil + } + return nil, &NotLoadedError{edge: "parent"} +} + +// ChildrenOrErr returns the Children value or an error if the edge +// was not loaded in eager-loading. +func (e FileEdges) ChildrenOrErr() ([]*File, error) { + if e.loadedTypes[1] { + return e.Children, nil + } + return nil, &NotLoadedError{edge: "children"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*File) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case file.FieldDeleted: + values[i] = new(sql.NullBool) + case file.FieldID, file.FieldParentID: + values[i] = new(sql.NullInt64) + case file.FieldName: + values[i] = new(sql.NullString) + default: + return nil, fmt.Errorf("unexpected column %q for type File", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the File fields. +func (f *File) assignValues(columns []string, values []interface{}) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case file.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + f.ID = int(value.Int64) + case file.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + f.Name = value.String + } + case file.FieldDeleted: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field deleted", values[i]) + } else if value.Valid { + f.Deleted = value.Bool + } + case file.FieldParentID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field parent_id", values[i]) + } else if value.Valid { + f.ParentID = int(value.Int64) + } + } + } + return nil +} + +// QueryParent queries the "parent" edge of the File entity. +func (f *File) QueryParent() *FileQuery { + return (&FileClient{config: f.config}).QueryParent(f) +} + +// QueryChildren queries the "children" edge of the File entity. +func (f *File) QueryChildren() *FileQuery { + return (&FileClient{config: f.config}).QueryChildren(f) +} + +// Update returns a builder for updating this File. +// Note that you need to call File.Unwrap() before calling this method if this File +// was returned from a transaction, and the transaction was committed or rolled back. +func (f *File) Update() *FileUpdateOne { + return (&FileClient{config: f.config}).UpdateOne(f) +} + +// Unwrap unwraps the File entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (f *File) Unwrap() *File { + tx, ok := f.config.driver.(*txDriver) + if !ok { + panic("ent: File is not a transactional entity") + } + f.config.driver = tx.drv + return f +} + +// String implements the fmt.Stringer. +func (f *File) String() string { + var builder strings.Builder + builder.WriteString("File(") + builder.WriteString(fmt.Sprintf("id=%v", f.ID)) + builder.WriteString(", name=") + builder.WriteString(f.Name) + builder.WriteString(", deleted=") + builder.WriteString(fmt.Sprintf("%v", f.Deleted)) + builder.WriteString(", parent_id=") + builder.WriteString(fmt.Sprintf("%v", f.ParentID)) + builder.WriteByte(')') + return builder.String() +} + +// Files is a parsable slice of File. +type Files []*File + +func (f Files) config(cfg config) { + for _i := range f { + f[_i].config = cfg + } +} diff --git a/examples/fs/ent/file/file.go b/examples/fs/ent/file/file.go new file mode 100644 index 000000000..8e6c0dad1 --- /dev/null +++ b/examples/fs/ent/file/file.go @@ -0,0 +1,57 @@ +// 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. + +// Code generated by entc, DO NOT EDIT. + +package file + +const ( + // Label holds the string label denoting the file type in the database. + Label = "file" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldDeleted holds the string denoting the deleted field in the database. + FieldDeleted = "deleted" + // FieldParentID holds the string denoting the parent_id field in the database. + FieldParentID = "parent_id" + // EdgeParent holds the string denoting the parent edge name in mutations. + EdgeParent = "parent" + // EdgeChildren holds the string denoting the children edge name in mutations. + EdgeChildren = "children" + // Table holds the table name of the file in the database. + Table = "files" + // ParentTable is the table the holds the parent relation/edge. + ParentTable = "files" + // ParentColumn is the table column denoting the parent relation/edge. + ParentColumn = "parent_id" + // ChildrenTable is the table the holds the children relation/edge. + ChildrenTable = "files" + // ChildrenColumn is the table column denoting the children relation/edge. + ChildrenColumn = "parent_id" +) + +// Columns holds all SQL columns for file fields. +var Columns = []string{ + FieldID, + FieldName, + FieldDeleted, + FieldParentID, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultDeleted holds the default value on creation for the "deleted" field. + DefaultDeleted bool +) diff --git a/examples/fs/ent/file/where.go b/examples/fs/ent/file/where.go new file mode 100644 index 000000000..4dd661894 --- /dev/null +++ b/examples/fs/ent/file/where.go @@ -0,0 +1,392 @@ +// 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. + +// Code generated by entc, DO NOT EDIT. + +package file + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/fs/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.File { + return predicate.File(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.File { + return predicate.File(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.File { + return predicate.File(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.File { + return predicate.File(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.File { + return predicate.File(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.File { + return predicate.File(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.File { + return predicate.File(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.File { + return predicate.File(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.File { + return predicate.File(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.File { + return predicate.File(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldName), v)) + }) +} + +// Deleted applies equality check predicate on the "deleted" field. It's identical to DeletedEQ. +func Deleted(v bool) predicate.File { + return predicate.File(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDeleted), v)) + }) +} + +// ParentID applies equality check predicate on the "parent_id" field. It's identical to ParentIDEQ. +func ParentID(v int) predicate.File { + return predicate.File(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldParentID), v)) + }) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.File { + return predicate.File(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.File { + return predicate.File(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.File { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.File(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(v) == 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.File { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.File(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(v) == 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.File { + return predicate.File(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.File { + return predicate.File(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.File { + return predicate.File(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.File { + return predicate.File(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.File { + return predicate.File(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.File { + return predicate.File(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.File { + return predicate.File(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.File { + return predicate.File(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.File { + return predicate.File(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldName), v)) + }) +} + +// DeletedEQ applies the EQ predicate on the "deleted" field. +func DeletedEQ(v bool) predicate.File { + return predicate.File(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDeleted), v)) + }) +} + +// DeletedNEQ applies the NEQ predicate on the "deleted" field. +func DeletedNEQ(v bool) predicate.File { + return predicate.File(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldDeleted), v)) + }) +} + +// ParentIDEQ applies the EQ predicate on the "parent_id" field. +func ParentIDEQ(v int) predicate.File { + return predicate.File(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldParentID), v)) + }) +} + +// ParentIDNEQ applies the NEQ predicate on the "parent_id" field. +func ParentIDNEQ(v int) predicate.File { + return predicate.File(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldParentID), v)) + }) +} + +// ParentIDIn applies the In predicate on the "parent_id" field. +func ParentIDIn(vs ...int) predicate.File { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.File(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(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldParentID), v...)) + }) +} + +// ParentIDNotIn applies the NotIn predicate on the "parent_id" field. +func ParentIDNotIn(vs ...int) predicate.File { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.File(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(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldParentID), v...)) + }) +} + +// ParentIDIsNil applies the IsNil predicate on the "parent_id" field. +func ParentIDIsNil() predicate.File { + return predicate.File(func(s *sql.Selector) { + s.Where(sql.IsNull(s.C(FieldParentID))) + }) +} + +// ParentIDNotNil applies the NotNil predicate on the "parent_id" field. +func ParentIDNotNil() predicate.File { + return predicate.File(func(s *sql.Selector) { + s.Where(sql.NotNull(s.C(FieldParentID))) + }) +} + +// HasParent applies the HasEdge predicate on the "parent" edge. +func HasParent() predicate.File { + return predicate.File(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ParentTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ParentTable, ParentColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasParentWith applies the HasEdge predicate on the "parent" edge with a given conditions (other predicates). +func HasParentWith(preds ...predicate.File) predicate.File { + return predicate.File(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ParentTable, ParentColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasChildren applies the HasEdge predicate on the "children" edge. +func HasChildren() predicate.File { + return predicate.File(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ChildrenTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ChildrenTable, ChildrenColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasChildrenWith applies the HasEdge predicate on the "children" edge with a given conditions (other predicates). +func HasChildrenWith(preds ...predicate.File) predicate.File { + return predicate.File(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ChildrenTable, ChildrenColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.File) predicate.File { + return predicate.File(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for _, p := range predicates { + p(s1) + } + s.Where(s1.P()) + }) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.File) predicate.File { + return predicate.File(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.File) predicate.File { + return predicate.File(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/examples/fs/ent/file_create.go b/examples/fs/ent/file_create.go new file mode 100644 index 000000000..fa31623d4 --- /dev/null +++ b/examples/fs/ent/file_create.go @@ -0,0 +1,296 @@ +// 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. + +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/fs/ent/file" + "entgo.io/ent/schema/field" +) + +// FileCreate is the builder for creating a File entity. +type FileCreate struct { + config + mutation *FileMutation + hooks []Hook +} + +// SetName sets the "name" field. +func (fc *FileCreate) SetName(s string) *FileCreate { + fc.mutation.SetName(s) + return fc +} + +// SetDeleted sets the "deleted" field. +func (fc *FileCreate) SetDeleted(b bool) *FileCreate { + fc.mutation.SetDeleted(b) + return fc +} + +// SetNillableDeleted sets the "deleted" field if the given value is not nil. +func (fc *FileCreate) SetNillableDeleted(b *bool) *FileCreate { + if b != nil { + fc.SetDeleted(*b) + } + return fc +} + +// SetParentID sets the "parent_id" field. +func (fc *FileCreate) SetParentID(i int) *FileCreate { + fc.mutation.SetParentID(i) + return fc +} + +// SetNillableParentID sets the "parent_id" field if the given value is not nil. +func (fc *FileCreate) SetNillableParentID(i *int) *FileCreate { + if i != nil { + fc.SetParentID(*i) + } + return fc +} + +// SetParent sets the "parent" edge to the File entity. +func (fc *FileCreate) SetParent(f *File) *FileCreate { + return fc.SetParentID(f.ID) +} + +// AddChildIDs adds the "children" edge to the File entity by IDs. +func (fc *FileCreate) AddChildIDs(ids ...int) *FileCreate { + fc.mutation.AddChildIDs(ids...) + return fc +} + +// AddChildren adds the "children" edges to the File entity. +func (fc *FileCreate) AddChildren(f ...*File) *FileCreate { + ids := make([]int, len(f)) + for i := range f { + ids[i] = f[i].ID + } + return fc.AddChildIDs(ids...) +} + +// Mutation returns the FileMutation object of the builder. +func (fc *FileCreate) Mutation() *FileMutation { + return fc.mutation +} + +// Save creates the File in the database. +func (fc *FileCreate) Save(ctx context.Context) (*File, error) { + var ( + err error + node *File + ) + fc.defaults() + if len(fc.hooks) == 0 { + if err = fc.check(); err != nil { + return nil, err + } + node, err = fc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*FileMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = fc.check(); err != nil { + return nil, err + } + fc.mutation = mutation + node, err = fc.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(fc.hooks) - 1; i >= 0; i-- { + mut = fc.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, fc.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (fc *FileCreate) SaveX(ctx context.Context) *File { + v, err := fc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// defaults sets the default values of the builder before save. +func (fc *FileCreate) defaults() { + if _, ok := fc.mutation.Deleted(); !ok { + v := file.DefaultDeleted + fc.mutation.SetDeleted(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (fc *FileCreate) check() error { + if _, ok := fc.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New("ent: missing required field \"name\"")} + } + if _, ok := fc.mutation.Deleted(); !ok { + return &ValidationError{Name: "deleted", err: errors.New("ent: missing required field \"deleted\"")} + } + return nil +} + +func (fc *FileCreate) sqlSave(ctx context.Context) (*File, error) { + _node, _spec := fc.createSpec() + if err := sqlgraph.CreateNode(ctx, fc.driver, _spec); err != nil { + if cerr, ok := isSQLConstraintError(err); ok { + err = cerr + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (fc *FileCreate) createSpec() (*File, *sqlgraph.CreateSpec) { + var ( + _node = &File{config: fc.config} + _spec = &sqlgraph.CreateSpec{ + Table: file.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: file.FieldID, + }, + } + ) + if value, ok := fc.mutation.Name(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: file.FieldName, + }) + _node.Name = value + } + if value, ok := fc.mutation.Deleted(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeBool, + Value: value, + Column: file.FieldDeleted, + }) + _node.Deleted = value + } + if nodes := fc.mutation.ParentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: file.ParentTable, + Columns: []string{file.ParentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: file.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.ParentID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := fc.mutation.ChildrenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: file.ChildrenTable, + Columns: []string{file.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: file.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// FileCreateBulk is the builder for creating many File entities in bulk. +type FileCreateBulk struct { + config + builders []*FileCreate +} + +// Save creates the File entities in the database. +func (fcb *FileCreateBulk) Save(ctx context.Context) ([]*File, error) { + specs := make([]*sqlgraph.CreateSpec, len(fcb.builders)) + nodes := make([]*File, len(fcb.builders)) + mutators := make([]Mutator, len(fcb.builders)) + for i := range fcb.builders { + func(i int, root context.Context) { + builder := fcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*FileMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + nodes[i], specs[i] = builder.createSpec() + var err error + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, fcb.builders[i+1].mutation) + } else { + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, fcb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil { + if cerr, ok := isSQLConstraintError(err); ok { + err = cerr + } + } + } + mutation.done = true + if err != nil { + return nil, err + } + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, fcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (fcb *FileCreateBulk) SaveX(ctx context.Context) []*File { + v, err := fcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} diff --git a/examples/fs/ent/file_delete.go b/examples/fs/ent/file_delete.go new file mode 100644 index 000000000..f18856afc --- /dev/null +++ b/examples/fs/ent/file_delete.go @@ -0,0 +1,112 @@ +// 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. + +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/fs/ent/file" + "entgo.io/ent/examples/fs/ent/predicate" + "entgo.io/ent/schema/field" +) + +// FileDelete is the builder for deleting a File entity. +type FileDelete struct { + config + hooks []Hook + mutation *FileMutation +} + +// Where adds a new predicate to the FileDelete builder. +func (fd *FileDelete) Where(ps ...predicate.File) *FileDelete { + fd.mutation.predicates = append(fd.mutation.predicates, ps...) + return fd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (fd *FileDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(fd.hooks) == 0 { + affected, err = fd.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*FileMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + fd.mutation = mutation + affected, err = fd.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(fd.hooks) - 1; i >= 0; i-- { + mut = fd.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, fd.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (fd *FileDelete) ExecX(ctx context.Context) int { + n, err := fd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (fd *FileDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: file.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: file.FieldID, + }, + }, + } + if ps := fd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, fd.driver, _spec) +} + +// FileDeleteOne is the builder for deleting a single File entity. +type FileDeleteOne struct { + fd *FileDelete +} + +// Exec executes the deletion query. +func (fdo *FileDeleteOne) Exec(ctx context.Context) error { + n, err := fdo.fd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{file.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (fdo *FileDeleteOne) ExecX(ctx context.Context) { + fdo.fd.ExecX(ctx) +} diff --git a/examples/fs/ent/file_query.go b/examples/fs/ent/file_query.go new file mode 100644 index 000000000..0824e3d3e --- /dev/null +++ b/examples/fs/ent/file_query.go @@ -0,0 +1,1050 @@ +// 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. + +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "database/sql/driver" + "errors" + "fmt" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/fs/ent/file" + "entgo.io/ent/examples/fs/ent/predicate" + "entgo.io/ent/schema/field" +) + +// FileQuery is the builder for querying File entities. +type FileQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.File + // eager-loading edges. + withParent *FileQuery + withChildren *FileQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the FileQuery builder. +func (fq *FileQuery) Where(ps ...predicate.File) *FileQuery { + fq.predicates = append(fq.predicates, ps...) + return fq +} + +// Limit adds a limit step to the query. +func (fq *FileQuery) Limit(limit int) *FileQuery { + fq.limit = &limit + return fq +} + +// Offset adds an offset step to the query. +func (fq *FileQuery) Offset(offset int) *FileQuery { + fq.offset = &offset + return fq +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (fq *FileQuery) Unique(unique bool) *FileQuery { + fq.unique = &unique + return fq +} + +// Order adds an order step to the query. +func (fq *FileQuery) Order(o ...OrderFunc) *FileQuery { + fq.order = append(fq.order, o...) + return fq +} + +// QueryParent chains the current query on the "parent" edge. +func (fq *FileQuery) QueryParent() *FileQuery { + query := &FileQuery{config: fq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := fq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := fq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(file.Table, file.FieldID, selector), + sqlgraph.To(file.Table, file.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, file.ParentTable, file.ParentColumn), + ) + fromU = sqlgraph.SetNeighbors(fq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryChildren chains the current query on the "children" edge. +func (fq *FileQuery) QueryChildren() *FileQuery { + query := &FileQuery{config: fq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := fq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := fq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(file.Table, file.FieldID, selector), + sqlgraph.To(file.Table, file.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, file.ChildrenTable, file.ChildrenColumn), + ) + fromU = sqlgraph.SetNeighbors(fq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first File entity from the query. +// Returns a *NotFoundError when no File was found. +func (fq *FileQuery) First(ctx context.Context) (*File, error) { + nodes, err := fq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{file.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (fq *FileQuery) FirstX(ctx context.Context) *File { + node, err := fq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first File ID from the query. +// Returns a *NotFoundError when no File ID was found. +func (fq *FileQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = fq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{file.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (fq *FileQuery) FirstIDX(ctx context.Context) int { + id, err := fq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single File entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when exactly one File entity is not found. +// Returns a *NotFoundError when no File entities are found. +func (fq *FileQuery) Only(ctx context.Context) (*File, error) { + nodes, err := fq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{file.Label} + default: + return nil, &NotSingularError{file.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (fq *FileQuery) OnlyX(ctx context.Context) *File { + node, err := fq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only File ID in the query. +// Returns a *NotSingularError when exactly one File ID is not found. +// Returns a *NotFoundError when no entities are found. +func (fq *FileQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = fq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{file.Label} + default: + err = &NotSingularError{file.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (fq *FileQuery) OnlyIDX(ctx context.Context) int { + id, err := fq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Files. +func (fq *FileQuery) All(ctx context.Context) ([]*File, error) { + if err := fq.prepareQuery(ctx); err != nil { + return nil, err + } + return fq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (fq *FileQuery) AllX(ctx context.Context) []*File { + nodes, err := fq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of File IDs. +func (fq *FileQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := fq.Select(file.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (fq *FileQuery) IDsX(ctx context.Context) []int { + ids, err := fq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (fq *FileQuery) Count(ctx context.Context) (int, error) { + if err := fq.prepareQuery(ctx); err != nil { + return 0, err + } + return fq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (fq *FileQuery) CountX(ctx context.Context) int { + count, err := fq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (fq *FileQuery) Exist(ctx context.Context) (bool, error) { + if err := fq.prepareQuery(ctx); err != nil { + return false, err + } + return fq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (fq *FileQuery) ExistX(ctx context.Context) bool { + exist, err := fq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the FileQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (fq *FileQuery) Clone() *FileQuery { + if fq == nil { + return nil + } + return &FileQuery{ + config: fq.config, + limit: fq.limit, + offset: fq.offset, + order: append([]OrderFunc{}, fq.order...), + predicates: append([]predicate.File{}, fq.predicates...), + withParent: fq.withParent.Clone(), + withChildren: fq.withChildren.Clone(), + // clone intermediate query. + sql: fq.sql.Clone(), + path: fq.path, + } +} + +// WithParent tells the query-builder to eager-load the nodes that are connected to +// the "parent" edge. The optional arguments are used to configure the query builder of the edge. +func (fq *FileQuery) WithParent(opts ...func(*FileQuery)) *FileQuery { + query := &FileQuery{config: fq.config} + for _, opt := range opts { + opt(query) + } + fq.withParent = query + return fq +} + +// WithChildren tells the query-builder to eager-load the nodes that are connected to +// the "children" edge. The optional arguments are used to configure the query builder of the edge. +func (fq *FileQuery) WithChildren(opts ...func(*FileQuery)) *FileQuery { + query := &FileQuery{config: fq.config} + for _, opt := range opts { + opt(query) + } + fq.withChildren = query + return fq +} + +// GroupBy is 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.File.Query(). +// GroupBy(file.FieldName). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +// +func (fq *FileQuery) GroupBy(field string, fields ...string) *FileGroupBy { + group := &FileGroupBy{config: fq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := fq.prepareQuery(ctx); err != nil { + return nil, err + } + return fq.sqlQuery(ctx), nil + } + return group +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// } +// +// client.File.Query(). +// Select(file.FieldName). +// Scan(ctx, &v) +// +func (fq *FileQuery) Select(field string, fields ...string) *FileSelect { + fq.fields = append([]string{field}, fields...) + return &FileSelect{FileQuery: fq} +} + +func (fq *FileQuery) prepareQuery(ctx context.Context) error { + for _, f := range fq.fields { + if !file.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if fq.path != nil { + prev, err := fq.path(ctx) + if err != nil { + return err + } + fq.sql = prev + } + return nil +} + +func (fq *FileQuery) sqlAll(ctx context.Context) ([]*File, error) { + var ( + nodes = []*File{} + _spec = fq.querySpec() + loadedTypes = [2]bool{ + fq.withParent != nil, + fq.withChildren != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + node := &File{config: fq.config} + nodes = append(nodes, node) + return node.scanValues(columns) + } + _spec.Assign = func(columns []string, 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(columns, values) + } + if err := sqlgraph.QueryNodes(ctx, fq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + + if query := fq.withParent; query != nil { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*File) + for i := range nodes { + fk := nodes[i].ParentID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + query.Where(file.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "parent_id" returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.Parent = n + } + } + } + + if query := fq.withChildren; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*File) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + nodes[i].Edges.Children = []*File{} + } + query.Where(predicate.File(func(s *sql.Selector) { + s.Where(sql.InValues(file.ChildrenColumn, fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + fk := n.ParentID + node, ok := nodeids[fk] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "parent_id" returned %v for node %v`, fk, n.ID) + } + node.Edges.Children = append(node.Edges.Children, n) + } + } + + return nodes, nil +} + +func (fq *FileQuery) sqlCount(ctx context.Context) (int, error) { + _spec := fq.querySpec() + return sqlgraph.CountNodes(ctx, fq.driver, _spec) +} + +func (fq *FileQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := fq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("ent: check existence: %w", err) + } + return n > 0, nil +} + +func (fq *FileQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: file.Table, + Columns: file.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: file.FieldID, + }, + }, + From: fq.sql, + Unique: true, + } + if unique := fq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := fq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, file.FieldID) + for i := range fields { + if fields[i] != file.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := fq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := fq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := fq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := fq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (fq *FileQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(fq.driver.Dialect()) + t1 := builder.Table(file.Table) + selector := builder.Select(t1.Columns(file.Columns...)...).From(t1) + if fq.sql != nil { + selector = fq.sql + selector.Select(selector.Columns(file.Columns...)...) + } + for _, p := range fq.predicates { + p(selector) + } + for _, p := range fq.order { + p(selector) + } + if offset := fq.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 := fq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// FileGroupBy is the group-by builder for File entities. +type FileGroupBy struct { + config + fields []string + fns []AggregateFunc + // 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 (fgb *FileGroupBy) Aggregate(fns ...AggregateFunc) *FileGroupBy { + fgb.fns = append(fgb.fns, fns...) + return fgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (fgb *FileGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := fgb.path(ctx) + if err != nil { + return err + } + fgb.sql = query + return fgb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (fgb *FileGroupBy) ScanX(ctx context.Context, v interface{}) { + if err := fgb.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from group-by. +// It is only allowed when executing a group-by query with one field. +func (fgb *FileGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(fgb.fields) > 1 { + return nil, errors.New("ent: FileGroupBy.Strings is not achievable when grouping more than 1 field") + } + var v []string + if err := fgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (fgb *FileGroupBy) StringsX(ctx context.Context) []string { + v, err := fgb.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (fgb *FileGroupBy) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = fgb.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{file.Label} + default: + err = fmt.Errorf("ent: FileGroupBy.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (fgb *FileGroupBy) StringX(ctx context.Context) string { + v, err := fgb.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from group-by. +// It is only allowed when executing a group-by query with one field. +func (fgb *FileGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(fgb.fields) > 1 { + return nil, errors.New("ent: FileGroupBy.Ints is not achievable when grouping more than 1 field") + } + var v []int + if err := fgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (fgb *FileGroupBy) IntsX(ctx context.Context) []int { + v, err := fgb.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (fgb *FileGroupBy) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = fgb.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{file.Label} + default: + err = fmt.Errorf("ent: FileGroupBy.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (fgb *FileGroupBy) IntX(ctx context.Context) int { + v, err := fgb.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from group-by. +// It is only allowed when executing a group-by query with one field. +func (fgb *FileGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(fgb.fields) > 1 { + return nil, errors.New("ent: FileGroupBy.Float64s is not achievable when grouping more than 1 field") + } + var v []float64 + if err := fgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (fgb *FileGroupBy) Float64sX(ctx context.Context) []float64 { + v, err := fgb.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (fgb *FileGroupBy) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = fgb.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{file.Label} + default: + err = fmt.Errorf("ent: FileGroupBy.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (fgb *FileGroupBy) Float64X(ctx context.Context) float64 { + v, err := fgb.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from group-by. +// It is only allowed when executing a group-by query with one field. +func (fgb *FileGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(fgb.fields) > 1 { + return nil, errors.New("ent: FileGroupBy.Bools is not achievable when grouping more than 1 field") + } + var v []bool + if err := fgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (fgb *FileGroupBy) BoolsX(ctx context.Context) []bool { + v, err := fgb.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (fgb *FileGroupBy) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = fgb.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{file.Label} + default: + err = fmt.Errorf("ent: FileGroupBy.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (fgb *FileGroupBy) BoolX(ctx context.Context) bool { + v, err := fgb.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (fgb *FileGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range fgb.fields { + if !file.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := fgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := fgb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (fgb *FileGroupBy) sqlQuery() *sql.Selector { + selector := fgb.sql.Select() + aggregation := make([]string, 0, len(fgb.fns)) + for _, fn := range fgb.fns { + aggregation = append(aggregation, fn(selector)) + } + // If no columns were selected in a custom aggregation function, the default + // selection is the fields used for "group-by", and the aggregation functions. + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(fgb.fields)+len(fgb.fns)) + for _, f := range fgb.fields { + columns = append(columns, selector.C(f)) + } + for _, c := range aggregation { + columns = append(columns, c) + } + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(fgb.fields...)...) +} + +// FileSelect is the builder for selecting fields of File entities. +type FileSelect struct { + *FileQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (fs *FileSelect) Scan(ctx context.Context, v interface{}) error { + if err := fs.prepareQuery(ctx); err != nil { + return err + } + fs.sql = fs.FileQuery.sqlQuery(ctx) + return fs.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (fs *FileSelect) ScanX(ctx context.Context, v interface{}) { + if err := fs.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (fs *FileSelect) Strings(ctx context.Context) ([]string, error) { + if len(fs.fields) > 1 { + return nil, errors.New("ent: FileSelect.Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := fs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (fs *FileSelect) StringsX(ctx context.Context) []string { + v, err := fs.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (fs *FileSelect) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = fs.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{file.Label} + default: + err = fmt.Errorf("ent: FileSelect.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (fs *FileSelect) StringX(ctx context.Context) string { + v, err := fs.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (fs *FileSelect) Ints(ctx context.Context) ([]int, error) { + if len(fs.fields) > 1 { + return nil, errors.New("ent: FileSelect.Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := fs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (fs *FileSelect) IntsX(ctx context.Context) []int { + v, err := fs.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (fs *FileSelect) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = fs.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{file.Label} + default: + err = fmt.Errorf("ent: FileSelect.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (fs *FileSelect) IntX(ctx context.Context) int { + v, err := fs.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (fs *FileSelect) Float64s(ctx context.Context) ([]float64, error) { + if len(fs.fields) > 1 { + return nil, errors.New("ent: FileSelect.Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := fs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (fs *FileSelect) Float64sX(ctx context.Context) []float64 { + v, err := fs.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (fs *FileSelect) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = fs.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{file.Label} + default: + err = fmt.Errorf("ent: FileSelect.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (fs *FileSelect) Float64X(ctx context.Context) float64 { + v, err := fs.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (fs *FileSelect) Bools(ctx context.Context) ([]bool, error) { + if len(fs.fields) > 1 { + return nil, errors.New("ent: FileSelect.Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := fs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (fs *FileSelect) BoolsX(ctx context.Context) []bool { + v, err := fs.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (fs *FileSelect) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = fs.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{file.Label} + default: + err = fmt.Errorf("ent: FileSelect.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (fs *FileSelect) BoolX(ctx context.Context) bool { + v, err := fs.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (fs *FileSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := fs.sqlQuery().Query() + if err := fs.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (fs *FileSelect) sqlQuery() sql.Querier { + selector := fs.sql + selector.Select(selector.Columns(fs.fields...)...) + return selector +} diff --git a/examples/fs/ent/file_update.go b/examples/fs/ent/file_update.go new file mode 100644 index 000000000..57fd1fea1 --- /dev/null +++ b/examples/fs/ent/file_update.go @@ -0,0 +1,618 @@ +// 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. + +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/fs/ent/file" + "entgo.io/ent/examples/fs/ent/predicate" + "entgo.io/ent/schema/field" +) + +// FileUpdate is the builder for updating File entities. +type FileUpdate struct { + config + hooks []Hook + mutation *FileMutation +} + +// Where adds a new predicate for the FileUpdate builder. +func (fu *FileUpdate) Where(ps ...predicate.File) *FileUpdate { + fu.mutation.predicates = append(fu.mutation.predicates, ps...) + return fu +} + +// SetName sets the "name" field. +func (fu *FileUpdate) SetName(s string) *FileUpdate { + fu.mutation.SetName(s) + return fu +} + +// SetDeleted sets the "deleted" field. +func (fu *FileUpdate) SetDeleted(b bool) *FileUpdate { + fu.mutation.SetDeleted(b) + return fu +} + +// SetNillableDeleted sets the "deleted" field if the given value is not nil. +func (fu *FileUpdate) SetNillableDeleted(b *bool) *FileUpdate { + if b != nil { + fu.SetDeleted(*b) + } + return fu +} + +// SetParentID sets the "parent_id" field. +func (fu *FileUpdate) SetParentID(i int) *FileUpdate { + fu.mutation.ResetParentID() + fu.mutation.SetParentID(i) + return fu +} + +// SetNillableParentID sets the "parent_id" field if the given value is not nil. +func (fu *FileUpdate) SetNillableParentID(i *int) *FileUpdate { + if i != nil { + fu.SetParentID(*i) + } + return fu +} + +// ClearParentID clears the value of the "parent_id" field. +func (fu *FileUpdate) ClearParentID() *FileUpdate { + fu.mutation.ClearParentID() + return fu +} + +// SetParent sets the "parent" edge to the File entity. +func (fu *FileUpdate) SetParent(f *File) *FileUpdate { + return fu.SetParentID(f.ID) +} + +// AddChildIDs adds the "children" edge to the File entity by IDs. +func (fu *FileUpdate) AddChildIDs(ids ...int) *FileUpdate { + fu.mutation.AddChildIDs(ids...) + return fu +} + +// AddChildren adds the "children" edges to the File entity. +func (fu *FileUpdate) AddChildren(f ...*File) *FileUpdate { + ids := make([]int, len(f)) + for i := range f { + ids[i] = f[i].ID + } + return fu.AddChildIDs(ids...) +} + +// Mutation returns the FileMutation object of the builder. +func (fu *FileUpdate) Mutation() *FileMutation { + return fu.mutation +} + +// ClearParent clears the "parent" edge to the File entity. +func (fu *FileUpdate) ClearParent() *FileUpdate { + fu.mutation.ClearParent() + return fu +} + +// ClearChildren clears all "children" edges to the File entity. +func (fu *FileUpdate) ClearChildren() *FileUpdate { + fu.mutation.ClearChildren() + return fu +} + +// RemoveChildIDs removes the "children" edge to File entities by IDs. +func (fu *FileUpdate) RemoveChildIDs(ids ...int) *FileUpdate { + fu.mutation.RemoveChildIDs(ids...) + return fu +} + +// RemoveChildren removes "children" edges to File entities. +func (fu *FileUpdate) RemoveChildren(f ...*File) *FileUpdate { + ids := make([]int, len(f)) + for i := range f { + ids[i] = f[i].ID + } + return fu.RemoveChildIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (fu *FileUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(fu.hooks) == 0 { + affected, err = fu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*FileMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + fu.mutation = mutation + affected, err = fu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(fu.hooks) - 1; i >= 0; i-- { + mut = fu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, fu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (fu *FileUpdate) SaveX(ctx context.Context) int { + affected, err := fu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (fu *FileUpdate) Exec(ctx context.Context) error { + _, err := fu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (fu *FileUpdate) ExecX(ctx context.Context) { + if err := fu.Exec(ctx); err != nil { + panic(err) + } +} + +func (fu *FileUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: file.Table, + Columns: file.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: file.FieldID, + }, + }, + } + if ps := fu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := fu.mutation.Name(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: file.FieldName, + }) + } + if value, ok := fu.mutation.Deleted(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeBool, + Value: value, + Column: file.FieldDeleted, + }) + } + if fu.mutation.ParentCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: file.ParentTable, + Columns: []string{file.ParentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: file.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := fu.mutation.ParentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: file.ParentTable, + Columns: []string{file.ParentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: file.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if fu.mutation.ChildrenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: file.ChildrenTable, + Columns: []string{file.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: file.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := fu.mutation.RemovedChildrenIDs(); len(nodes) > 0 && !fu.mutation.ChildrenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: file.ChildrenTable, + Columns: []string{file.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: file.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := fu.mutation.ChildrenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: file.ChildrenTable, + Columns: []string{file.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: file.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, fu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{file.Label} + } else if cerr, ok := isSQLConstraintError(err); ok { + err = cerr + } + return 0, err + } + return n, nil +} + +// FileUpdateOne is the builder for updating a single File entity. +type FileUpdateOne struct { + config + fields []string + hooks []Hook + mutation *FileMutation +} + +// SetName sets the "name" field. +func (fuo *FileUpdateOne) SetName(s string) *FileUpdateOne { + fuo.mutation.SetName(s) + return fuo +} + +// SetDeleted sets the "deleted" field. +func (fuo *FileUpdateOne) SetDeleted(b bool) *FileUpdateOne { + fuo.mutation.SetDeleted(b) + return fuo +} + +// SetNillableDeleted sets the "deleted" field if the given value is not nil. +func (fuo *FileUpdateOne) SetNillableDeleted(b *bool) *FileUpdateOne { + if b != nil { + fuo.SetDeleted(*b) + } + return fuo +} + +// SetParentID sets the "parent_id" field. +func (fuo *FileUpdateOne) SetParentID(i int) *FileUpdateOne { + fuo.mutation.ResetParentID() + fuo.mutation.SetParentID(i) + return fuo +} + +// SetNillableParentID sets the "parent_id" field if the given value is not nil. +func (fuo *FileUpdateOne) SetNillableParentID(i *int) *FileUpdateOne { + if i != nil { + fuo.SetParentID(*i) + } + return fuo +} + +// ClearParentID clears the value of the "parent_id" field. +func (fuo *FileUpdateOne) ClearParentID() *FileUpdateOne { + fuo.mutation.ClearParentID() + return fuo +} + +// SetParent sets the "parent" edge to the File entity. +func (fuo *FileUpdateOne) SetParent(f *File) *FileUpdateOne { + return fuo.SetParentID(f.ID) +} + +// AddChildIDs adds the "children" edge to the File entity by IDs. +func (fuo *FileUpdateOne) AddChildIDs(ids ...int) *FileUpdateOne { + fuo.mutation.AddChildIDs(ids...) + return fuo +} + +// AddChildren adds the "children" edges to the File entity. +func (fuo *FileUpdateOne) AddChildren(f ...*File) *FileUpdateOne { + ids := make([]int, len(f)) + for i := range f { + ids[i] = f[i].ID + } + return fuo.AddChildIDs(ids...) +} + +// Mutation returns the FileMutation object of the builder. +func (fuo *FileUpdateOne) Mutation() *FileMutation { + return fuo.mutation +} + +// ClearParent clears the "parent" edge to the File entity. +func (fuo *FileUpdateOne) ClearParent() *FileUpdateOne { + fuo.mutation.ClearParent() + return fuo +} + +// ClearChildren clears all "children" edges to the File entity. +func (fuo *FileUpdateOne) ClearChildren() *FileUpdateOne { + fuo.mutation.ClearChildren() + return fuo +} + +// RemoveChildIDs removes the "children" edge to File entities by IDs. +func (fuo *FileUpdateOne) RemoveChildIDs(ids ...int) *FileUpdateOne { + fuo.mutation.RemoveChildIDs(ids...) + return fuo +} + +// RemoveChildren removes "children" edges to File entities. +func (fuo *FileUpdateOne) RemoveChildren(f ...*File) *FileUpdateOne { + ids := make([]int, len(f)) + for i := range f { + ids[i] = f[i].ID + } + return fuo.RemoveChildIDs(ids...) +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (fuo *FileUpdateOne) Select(field string, fields ...string) *FileUpdateOne { + fuo.fields = append([]string{field}, fields...) + return fuo +} + +// Save executes the query and returns the updated File entity. +func (fuo *FileUpdateOne) Save(ctx context.Context) (*File, error) { + var ( + err error + node *File + ) + if len(fuo.hooks) == 0 { + node, err = fuo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*FileMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + fuo.mutation = mutation + node, err = fuo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(fuo.hooks) - 1; i >= 0; i-- { + mut = fuo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, fuo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (fuo *FileUpdateOne) SaveX(ctx context.Context) *File { + node, err := fuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (fuo *FileUpdateOne) Exec(ctx context.Context) error { + _, err := fuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (fuo *FileUpdateOne) ExecX(ctx context.Context) { + if err := fuo.Exec(ctx); err != nil { + panic(err) + } +} + +func (fuo *FileUpdateOne) sqlSave(ctx context.Context) (_node *File, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: file.Table, + Columns: file.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: file.FieldID, + }, + }, + } + id, ok := fuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing File.ID for update")} + } + _spec.Node.ID.Value = id + if fields := fuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, file.FieldID) + for _, f := range fields { + if !file.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != file.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := fuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := fuo.mutation.Name(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: file.FieldName, + }) + } + if value, ok := fuo.mutation.Deleted(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeBool, + Value: value, + Column: file.FieldDeleted, + }) + } + if fuo.mutation.ParentCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: file.ParentTable, + Columns: []string{file.ParentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: file.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := fuo.mutation.ParentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: file.ParentTable, + Columns: []string{file.ParentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: file.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if fuo.mutation.ChildrenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: file.ChildrenTable, + Columns: []string{file.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: file.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := fuo.mutation.RemovedChildrenIDs(); len(nodes) > 0 && !fuo.mutation.ChildrenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: file.ChildrenTable, + Columns: []string{file.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: file.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := fuo.mutation.ChildrenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: file.ChildrenTable, + Columns: []string{file.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: file.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &File{config: fuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, fuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{file.Label} + } else if cerr, ok := isSQLConstraintError(err); ok { + err = cerr + } + return nil, err + } + return _node, nil +} diff --git a/examples/fs/ent/generate.go b/examples/fs/ent/generate.go new file mode 100644 index 000000000..fac82d5d2 --- /dev/null +++ b/examples/fs/ent/generate.go @@ -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 -mod=mod entgo.io/ent/cmd/ent generate --header "// Copyright 2019-present Facebook Inc. 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 by entc, DO NOT EDIT." ./schema diff --git a/examples/fs/ent/hook/hook.go b/examples/fs/ent/hook/hook.go new file mode 100644 index 000000000..f7e9a08be --- /dev/null +++ b/examples/fs/ent/hook/hook.go @@ -0,0 +1,208 @@ +// 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. + +// Code generated by entc, DO NOT EDIT. + +package hook + +import ( + "context" + "fmt" + + "entgo.io/ent/examples/fs/ent" +) + +// The FileFunc type is an adapter to allow the use of ordinary +// function as File mutator. +type FileFunc func(context.Context, *ent.FileMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f FileFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + mv, ok := m.(*ent.FileMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.FileMutation", m) + } + return f(ctx, mv) +} + +// Condition is a hook condition function. +type Condition func(context.Context, ent.Mutation) bool + +// And groups conditions with the AND operator. +func And(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m ent.Mutation) bool { + if !first(ctx, m) || !second(ctx, m) { + return false + } + for _, cond := range rest { + if !cond(ctx, m) { + return false + } + } + return true + } +} + +// Or groups conditions with the OR operator. +func Or(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m ent.Mutation) bool { + if first(ctx, m) || second(ctx, m) { + return true + } + for _, cond := range rest { + if cond(ctx, m) { + return true + } + } + return false + } +} + +// Not negates a given condition. +func Not(cond Condition) Condition { + return func(ctx context.Context, m ent.Mutation) bool { + return !cond(ctx, m) + } +} + +// HasOp is a condition testing mutation operation. +func HasOp(op ent.Op) Condition { + return func(_ context.Context, m ent.Mutation) bool { + return m.Op().Is(op) + } +} + +// HasAddedFields is a condition validating `.AddedField` on fields. +func HasAddedFields(field string, fields ...string) Condition { + return func(_ context.Context, m ent.Mutation) bool { + if _, exists := m.AddedField(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.AddedField(field); !exists { + return false + } + } + return true + } +} + +// HasClearedFields is a condition validating `.FieldCleared` on fields. +func HasClearedFields(field string, fields ...string) Condition { + return func(_ context.Context, m ent.Mutation) bool { + if exists := m.FieldCleared(field); !exists { + return false + } + for _, field := range fields { + if exists := m.FieldCleared(field); !exists { + return false + } + } + return true + } +} + +// HasFields is a condition validating `.Field` on fields. +func HasFields(field string, fields ...string) Condition { + return func(_ context.Context, m ent.Mutation) bool { + if _, exists := m.Field(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.Field(field); !exists { + return false + } + } + return true + } +} + +// If executes the given hook under condition. +// +// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) +// +func If(hk ent.Hook, cond Condition) ent.Hook { + return func(next ent.Mutator) ent.Mutator { + return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if cond(ctx, m) { + return hk(next).Mutate(ctx, m) + } + return next.Mutate(ctx, m) + }) + } +} + +// On executes the given hook only for the given operation. +// +// hook.On(Log, ent.Delete|ent.Create) +// +func On(hk ent.Hook, op ent.Op) ent.Hook { + return If(hk, HasOp(op)) +} + +// Unless skips the given hook only for the given operation. +// +// hook.Unless(Log, ent.Update|ent.UpdateOne) +// +func Unless(hk ent.Hook, op ent.Op) ent.Hook { + return If(hk, Not(HasOp(op))) +} + +// FixedError is a hook returning a fixed error. +func FixedError(err error) ent.Hook { + return func(ent.Mutator) ent.Mutator { + return ent.MutateFunc(func(context.Context, ent.Mutation) (ent.Value, error) { + return nil, err + }) + } +} + +// Reject returns a hook that rejects all operations that match op. +// +// func (T) Hooks() []ent.Hook { +// return []ent.Hook{ +// Reject(ent.Delete|ent.Update), +// } +// } +// +func Reject(op ent.Op) ent.Hook { + hk := FixedError(fmt.Errorf("%s operation is not allowed", op)) + return On(hk, op) +} + +// Chain acts as a list of hooks and is effectively immutable. +// Once created, it will always hold the same set of hooks in the same order. +type Chain struct { + hooks []ent.Hook +} + +// NewChain creates a new chain of hooks. +func NewChain(hooks ...ent.Hook) Chain { + return Chain{append([]ent.Hook(nil), hooks...)} +} + +// Hook chains the list of hooks and returns the final hook. +func (c Chain) Hook() ent.Hook { + return func(mutator ent.Mutator) ent.Mutator { + for i := len(c.hooks) - 1; i >= 0; i-- { + mutator = c.hooks[i](mutator) + } + return mutator + } +} + +// Append extends a chain, adding the specified hook +// as the last ones in the mutation flow. +func (c Chain) Append(hooks ...ent.Hook) Chain { + newHooks := make([]ent.Hook, 0, len(c.hooks)+len(hooks)) + newHooks = append(newHooks, c.hooks...) + newHooks = append(newHooks, hooks...) + return Chain{newHooks} +} + +// Extend extends a chain, adding the specified chain +// as the last ones in the mutation flow. +func (c Chain) Extend(chain Chain) Chain { + return c.Append(chain.hooks...) +} diff --git a/examples/fs/ent/migrate/migrate.go b/examples/fs/ent/migrate/migrate.go new file mode 100644 index 000000000..61ffeff08 --- /dev/null +++ b/examples/fs/ent/migrate/migrate.go @@ -0,0 +1,76 @@ +// 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. + +// Code generated by entc, DO NOT EDIT. + +package migrate + +import ( + "context" + "fmt" + "io" + + "entgo.io/ent/dialect" + "entgo.io/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 + // WithFixture sets the foreign-key renaming option to the migration when upgrading + // ent from v0.1.0 (issue-#285). Defaults to false. + WithFixture = schema.WithFixture + // WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true. + WithForeignKeys = schema.WithForeignKeys +) + +// 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: %w", 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: %w", err) + } + return migrate.Create(ctx, Tables...) +} diff --git a/examples/fs/ent/migrate/schema.go b/examples/fs/ent/migrate/schema.go new file mode 100644 index 000000000..a46b6ce7f --- /dev/null +++ b/examples/fs/ent/migrate/schema.go @@ -0,0 +1,44 @@ +// 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. + +// Code generated by entc, DO NOT EDIT. + +package migrate + +import ( + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/schema/field" +) + +var ( + // FilesColumns holds the columns for the "files" table. + FilesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "name", Type: field.TypeString}, + {Name: "deleted", Type: field.TypeBool, Default: false}, + {Name: "parent_id", Type: field.TypeInt, Nullable: true}, + } + // FilesTable holds the schema information for the "files" table. + FilesTable = &schema.Table{ + Name: "files", + Columns: FilesColumns, + PrimaryKey: []*schema.Column{FilesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "files_files_children", + Columns: []*schema.Column{FilesColumns[3]}, + RefColumns: []*schema.Column{FilesColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + } + // Tables holds all the tables in the schema. + Tables = []*schema.Table{ + FilesTable, + } +) + +func init() { + FilesTable.ForeignKeys[0].RefTable = FilesTable +} diff --git a/examples/fs/ent/mutation.go b/examples/fs/ent/mutation.go new file mode 100644 index 000000000..5529003de --- /dev/null +++ b/examples/fs/ent/mutation.go @@ -0,0 +1,587 @@ +// 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. + +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "sync" + + "entgo.io/ent/examples/fs/ent/file" + "entgo.io/ent/examples/fs/ent/predicate" + + "entgo.io/ent" +) + +const ( + // Operation types. + OpCreate = ent.OpCreate + OpDelete = ent.OpDelete + OpDeleteOne = ent.OpDeleteOne + OpUpdate = ent.OpUpdate + OpUpdateOne = ent.OpUpdateOne + + // Node types. + TypeFile = "File" +) + +// FileMutation represents an operation that mutates the File nodes in the graph. +type FileMutation struct { + config + op Op + typ string + id *int + name *string + deleted *bool + clearedFields map[string]struct{} + parent *int + clearedparent bool + children map[int]struct{} + removedchildren map[int]struct{} + clearedchildren bool + done bool + oldValue func(context.Context) (*File, error) + predicates []predicate.File +} + +var _ ent.Mutation = (*FileMutation)(nil) + +// fileOption allows management of the mutation configuration using functional options. +type fileOption func(*FileMutation) + +// newFileMutation creates new mutation for the File entity. +func newFileMutation(c config, op Op, opts ...fileOption) *FileMutation { + m := &FileMutation{ + config: c, + op: op, + typ: TypeFile, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withFileID sets the ID field of the mutation. +func withFileID(id int) fileOption { + return func(m *FileMutation) { + var ( + err error + once sync.Once + value *File + ) + m.oldValue = func(ctx context.Context) (*File, error) { + once.Do(func() { + if m.done { + err = fmt.Errorf("querying old values post mutation is not allowed") + } else { + value, err = m.Client().File.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withFile sets the old File of the mutation. +func withFile(node *File) fileOption { + return func(m *FileMutation) { + m.oldValue = func(context.Context) (*File, error) { + return node, nil + } + m.id = &node.ID + } +} + +// 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 FileMutation) 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 FileMutation) 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 only available if it was provided to the builder. +func (m *FileMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// SetName sets the "name" field. +func (m *FileMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *FileMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the File entity. +// If the File object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *FileMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *FileMutation) ResetName() { + m.name = nil +} + +// SetDeleted sets the "deleted" field. +func (m *FileMutation) SetDeleted(b bool) { + m.deleted = &b +} + +// Deleted returns the value of the "deleted" field in the mutation. +func (m *FileMutation) Deleted() (r bool, exists bool) { + v := m.deleted + if v == nil { + return + } + return *v, true +} + +// OldDeleted returns the old "deleted" field's value of the File entity. +// If the File object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *FileMutation) OldDeleted(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldDeleted is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldDeleted requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeleted: %w", err) + } + return oldValue.Deleted, nil +} + +// ResetDeleted resets all changes to the "deleted" field. +func (m *FileMutation) ResetDeleted() { + m.deleted = nil +} + +// SetParentID sets the "parent_id" field. +func (m *FileMutation) SetParentID(i int) { + m.parent = &i +} + +// ParentID returns the value of the "parent_id" field in the mutation. +func (m *FileMutation) ParentID() (r int, exists bool) { + v := m.parent + if v == nil { + return + } + return *v, true +} + +// OldParentID returns the old "parent_id" field's value of the File entity. +// If the File object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *FileMutation) OldParentID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldParentID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldParentID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldParentID: %w", err) + } + return oldValue.ParentID, nil +} + +// ClearParentID clears the value of the "parent_id" field. +func (m *FileMutation) ClearParentID() { + m.parent = nil + m.clearedFields[file.FieldParentID] = struct{}{} +} + +// ParentIDCleared returns if the "parent_id" field was cleared in this mutation. +func (m *FileMutation) ParentIDCleared() bool { + _, ok := m.clearedFields[file.FieldParentID] + return ok +} + +// ResetParentID resets all changes to the "parent_id" field. +func (m *FileMutation) ResetParentID() { + m.parent = nil + delete(m.clearedFields, file.FieldParentID) +} + +// ClearParent clears the "parent" edge to the File entity. +func (m *FileMutation) ClearParent() { + m.clearedparent = true +} + +// ParentCleared reports if the "parent" edge to the File entity was cleared. +func (m *FileMutation) ParentCleared() bool { + return m.ParentIDCleared() || m.clearedparent +} + +// ParentIDs returns the "parent" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ParentID instead. It exists only for internal usage by the builders. +func (m *FileMutation) ParentIDs() (ids []int) { + if id := m.parent; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetParent resets all changes to the "parent" edge. +func (m *FileMutation) ResetParent() { + m.parent = nil + m.clearedparent = false +} + +// AddChildIDs adds the "children" edge to the File entity by ids. +func (m *FileMutation) AddChildIDs(ids ...int) { + if m.children == nil { + m.children = make(map[int]struct{}) + } + for i := range ids { + m.children[ids[i]] = struct{}{} + } +} + +// ClearChildren clears the "children" edge to the File entity. +func (m *FileMutation) ClearChildren() { + m.clearedchildren = true +} + +// ChildrenCleared reports if the "children" edge to the File entity was cleared. +func (m *FileMutation) ChildrenCleared() bool { + return m.clearedchildren +} + +// RemoveChildIDs removes the "children" edge to the File entity by IDs. +func (m *FileMutation) RemoveChildIDs(ids ...int) { + if m.removedchildren == nil { + m.removedchildren = make(map[int]struct{}) + } + for i := range ids { + m.removedchildren[ids[i]] = struct{}{} + } +} + +// RemovedChildren returns the removed IDs of the "children" edge to the File entity. +func (m *FileMutation) RemovedChildrenIDs() (ids []int) { + for id := range m.removedchildren { + ids = append(ids, id) + } + return +} + +// ChildrenIDs returns the "children" edge IDs in the mutation. +func (m *FileMutation) ChildrenIDs() (ids []int) { + for id := range m.children { + ids = append(ids, id) + } + return +} + +// ResetChildren resets all changes to the "children" edge. +func (m *FileMutation) ResetChildren() { + m.children = nil + m.clearedchildren = false + m.removedchildren = nil +} + +// Op returns the operation name. +func (m *FileMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (File). +func (m *FileMutation) 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 incremented/decremented, call +// AddedFields(). +func (m *FileMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.name != nil { + fields = append(fields, file.FieldName) + } + if m.deleted != nil { + fields = append(fields, file.FieldDeleted) + } + if m.parent != nil { + fields = append(fields, file.FieldParentID) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *FileMutation) Field(name string) (ent.Value, bool) { + switch name { + case file.FieldName: + return m.Name() + case file.FieldDeleted: + return m.Deleted() + case file.FieldParentID: + return m.ParentID() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *FileMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case file.FieldName: + return m.OldName(ctx) + case file.FieldDeleted: + return m.OldDeleted(ctx) + case file.FieldParentID: + return m.OldParentID(ctx) + } + return nil, fmt.Errorf("unknown File field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *FileMutation) SetField(name string, value ent.Value) error { + switch name { + case file.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case file.FieldDeleted: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeleted(v) + return nil + case file.FieldParentID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetParentID(v) + return nil + } + return fmt.Errorf("unknown File field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *FileMutation) AddedFields() []string { + var fields []string + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *FileMutation) AddedField(name string) (ent.Value, bool) { + switch name { + } + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *FileMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown File numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *FileMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(file.FieldParentID) { + fields = append(fields, file.FieldParentID) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *FileMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *FileMutation) ClearField(name string) error { + switch name { + case file.FieldParentID: + m.ClearParentID() + return nil + } + return fmt.Errorf("unknown File nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *FileMutation) ResetField(name string) error { + switch name { + case file.FieldName: + m.ResetName() + return nil + case file.FieldDeleted: + m.ResetDeleted() + return nil + case file.FieldParentID: + m.ResetParentID() + return nil + } + return fmt.Errorf("unknown File field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *FileMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.parent != nil { + edges = append(edges, file.EdgeParent) + } + if m.children != nil { + edges = append(edges, file.EdgeChildren) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *FileMutation) AddedIDs(name string) []ent.Value { + switch name { + case file.EdgeParent: + if id := m.parent; id != nil { + return []ent.Value{*id} + } + case file.EdgeChildren: + ids := make([]ent.Value, 0, len(m.children)) + for id := range m.children { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *FileMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removedchildren != nil { + edges = append(edges, file.EdgeChildren) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *FileMutation) RemovedIDs(name string) []ent.Value { + switch name { + case file.EdgeChildren: + ids := make([]ent.Value, 0, len(m.removedchildren)) + for id := range m.removedchildren { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *FileMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedparent { + edges = append(edges, file.EdgeParent) + } + if m.clearedchildren { + edges = append(edges, file.EdgeChildren) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *FileMutation) EdgeCleared(name string) bool { + switch name { + case file.EdgeParent: + return m.clearedparent + case file.EdgeChildren: + return m.clearedchildren + } + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *FileMutation) ClearEdge(name string) error { + switch name { + case file.EdgeParent: + m.ClearParent() + return nil + } + return fmt.Errorf("unknown File unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *FileMutation) ResetEdge(name string) error { + switch name { + case file.EdgeParent: + m.ResetParent() + return nil + case file.EdgeChildren: + m.ResetChildren() + return nil + } + return fmt.Errorf("unknown File edge %s", name) +} diff --git a/examples/fs/ent/predicate/predicate.go b/examples/fs/ent/predicate/predicate.go new file mode 100644 index 000000000..6b7448bba --- /dev/null +++ b/examples/fs/ent/predicate/predicate.go @@ -0,0 +1,14 @@ +// 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. + +// Code generated by entc, DO NOT EDIT. + +package predicate + +import ( + "entgo.io/ent/dialect/sql" +) + +// File is the predicate function for file builders. +type File func(*sql.Selector) diff --git a/examples/fs/ent/runtime.go b/examples/fs/ent/runtime.go new file mode 100644 index 000000000..a62a48777 --- /dev/null +++ b/examples/fs/ent/runtime.go @@ -0,0 +1,24 @@ +// 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. + +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "entgo.io/ent/examples/fs/ent/file" + "entgo.io/ent/examples/fs/ent/schema" +) + +// The init function reads all schema descriptors with runtime code +// (default values, validators, hooks and policies) and stitches it +// to their package variables. +func init() { + fileFields := schema.File{}.Fields() + _ = fileFields + // fileDescDeleted is the schema descriptor for deleted field. + fileDescDeleted := fileFields[1].Descriptor() + // file.DefaultDeleted holds the default value on creation for the deleted field. + file.DefaultDeleted = fileDescDeleted.Default.(bool) +} diff --git a/examples/fs/ent/runtime/runtime.go b/examples/fs/ent/runtime/runtime.go new file mode 100644 index 000000000..27d09c7c7 --- /dev/null +++ b/examples/fs/ent/runtime/runtime.go @@ -0,0 +1,13 @@ +// 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. + +// Code generated by entc, DO NOT EDIT. + +package runtime + +// The schema-stitching logic is generated in entgo.io/ent/examples/fs/ent/runtime.go + +const ( + Version = "(devel)" // Version of ent codegen. +) diff --git a/examples/fs/ent/schema/file.go b/examples/fs/ent/schema/file.go new file mode 100644 index 000000000..3b54fddd3 --- /dev/null +++ b/examples/fs/ent/schema/file.go @@ -0,0 +1,37 @@ +// 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 schema + +import ( + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +// File holds the schema definition for the File entity. +type File struct { + ent.Schema +} + +// Fields of the File. +func (File) Fields() []ent.Field { + return []ent.Field{ + field.String("name"), + field.Bool("deleted"). + Default(false), + field.Int("parent_id"). + Optional(), + } +} + +// Edges of the File. +func (File) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("children", File.Type). + From("parent"). + Unique(). + Field("parent_id"), + } +} diff --git a/examples/fs/ent/tx.go b/examples/fs/ent/tx.go new file mode 100644 index 000000000..b652116ba --- /dev/null +++ b/examples/fs/ent/tx.go @@ -0,0 +1,214 @@ +// 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. + +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "sync" + + "entgo.io/ent/dialect" +) + +// Tx is a transactional client that is created by calling Client.Tx(). +type Tx struct { + config + // File is the client for interacting with the File builders. + File *FileClient + + // lazily loaded. + client *Client + clientOnce sync.Once + + // completion callbacks. + mu sync.Mutex + onCommit []CommitHook + onRollback []RollbackHook + + // ctx lives for the life of the transaction. It is + // the same context used by the underlying connection. + ctx context.Context +} + +type ( + // Committer is the interface that wraps the Committer method. + Committer interface { + Commit(context.Context, *Tx) error + } + + // The CommitFunc type is an adapter to allow the use of ordinary + // function as a Committer. If f is a function with the appropriate + // signature, CommitFunc(f) is a Committer that calls f. + CommitFunc func(context.Context, *Tx) error + + // CommitHook defines the "commit middleware". A function that gets a Committer + // and returns a Committer. For example: + // + // hook := func(next ent.Committer) ent.Committer { + // return ent.CommitFunc(func(context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Commit(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + CommitHook func(Committer) Committer +) + +// Commit calls f(ctx, m). +func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Commit commits the transaction. +func (tx *Tx) Commit() error { + txDriver := tx.config.driver.(*txDriver) + var fn Committer = CommitFunc(func(context.Context, *Tx) error { + return txDriver.tx.Commit() + }) + tx.mu.Lock() + hooks := append([]CommitHook(nil), tx.onCommit...) + tx.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Commit(tx.ctx, tx) +} + +// OnCommit adds a hook to call on commit. +func (tx *Tx) OnCommit(f CommitHook) { + tx.mu.Lock() + defer tx.mu.Unlock() + tx.onCommit = append(tx.onCommit, f) +} + +type ( + // Rollbacker is the interface that wraps the Rollbacker method. + Rollbacker interface { + Rollback(context.Context, *Tx) error + } + + // The RollbackFunc type is an adapter to allow the use of ordinary + // function as a Rollbacker. If f is a function with the appropriate + // signature, RollbackFunc(f) is a Rollbacker that calls f. + RollbackFunc func(context.Context, *Tx) error + + // RollbackHook defines the "rollback middleware". A function that gets a Rollbacker + // and returns a Rollbacker. For example: + // + // hook := func(next ent.Rollbacker) ent.Rollbacker { + // return ent.RollbackFunc(func(context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Rollback(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + RollbackHook func(Rollbacker) Rollbacker +) + +// Rollback calls f(ctx, m). +func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Rollback rollbacks the transaction. +func (tx *Tx) Rollback() error { + txDriver := tx.config.driver.(*txDriver) + var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error { + return txDriver.tx.Rollback() + }) + tx.mu.Lock() + hooks := append([]RollbackHook(nil), tx.onRollback...) + tx.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Rollback(tx.ctx, tx) +} + +// OnRollback adds a hook to call on rollback. +func (tx *Tx) OnRollback(f RollbackHook) { + tx.mu.Lock() + defer tx.mu.Unlock() + tx.onRollback = append(tx.onRollback, f) +} + +// Client returns a Client that binds to current transaction. +func (tx *Tx) Client() *Client { + tx.clientOnce.Do(func() { + tx.client = &Client{config: tx.config} + tx.client.init() + }) + return tx.client +} + +func (tx *Tx) init() { + tx.File = NewFileClient(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: File.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) diff --git a/examples/fs/example_test.go b/examples/fs/example_test.go new file mode 100644 index 000000000..9660b3d83 --- /dev/null +++ b/examples/fs/example_test.go @@ -0,0 +1,91 @@ +// 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" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/examples/fs/ent" + "entgo.io/ent/examples/fs/ent/file" + + _ "github.com/mattn/go-sqlite3" +) + +func Example_RecursiveTraversal() { + 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) + } + + // Add multiple files in the following ree structure: + // + // a/ + // ├─ b/ + // │ ├─ ba + // │ ├─ bb + // │ └─ bc (deleted) + // ├─ c/ (deleted) + // │ ├─ ca + // │ └─ cb + // └─ d (deleted) + // + a := client.File.Create().SetName("a").SaveX(ctx) + b := client.File.Create().SetName("b").SetParent(a).SaveX(ctx) + client.File.Create().SetName("ba").SetParent(b).SaveX(ctx) + client.File.Create().SetName("bb").SetParent(b).SaveX(ctx) + client.File.Create().SetName("bc").SetParent(b).SetDeleted(true).SaveX(ctx) + c := client.File.Create().SetName("c").SetParent(a).SetDeleted(true).SaveX(ctx) + client.File.Create().SetName("ca").SetParent(c).SaveX(ctx) + client.File.Create().SetName("cb").SetParent(c).SaveX(ctx) + client.File.Create().SetName("d").SetParent(a).SetDeleted(true).SaveX(ctx) + + // Query undeleted files: + // + // a/ + // └─ b/ + // ├─ ba + // └─ bb + // + names := client.File.Query(). + Where(func(s *sql.Selector) { + t1, t2 := sql.Table(file.Table), sql.Table(file.Table) + with := sql.WithRecursive("undeleted", file.FieldID, file.FieldParentID) + with.As( + sql.Select(t1.Columns(file.FieldID, file.FieldParentID)...). + From(t1). + Where( + sql.And( + sql.IsNull(t1.C(file.FieldParentID)), + sql.EQ(t1.C(file.FieldDeleted), false), + ), + ). + UnionAll( + sql.Select(t2.Columns(file.FieldID, file.FieldParentID)...). + From(t2). + Join(with). + On(t2.C(file.FieldParentID), with.C(file.FieldID)). + Where( + sql.EQ(t1.C(file.FieldDeleted), false), + ), + ), + ) + s.Prefix(with).Join(with).On(s.C(file.FieldID), with.C(file.FieldID)) + }). + Select(file.FieldName). + StringsX(ctx) + fmt.Printf("%q\n", names) + + // Output: + // ["a" "b" "ba" "bb"] +}