diff --git a/UPSTREAM.md b/UPSTREAM.md index 67e1b21728..92f7f0f71b 100644 --- a/UPSTREAM.md +++ b/UPSTREAM.md @@ -180,6 +180,7 @@ touches the same area may be assuming the behaviour we replaced. | **Create read-back** | `sqlgraph.CreateSpec` carries `Returning`, `ScanValues` and `Assign`, and a create reads back the row it stored: by the INSERT, with `RETURNING`, where the dialect has it, and by a query after it on MySQL or with a conflict clause. `sql/returning` gives a create builder `Stored`, which asks for it, in a `CreateBulk` as well: a batch reads every row back, matched to its node by the Id the caller gave, or by its place when the database made the Ids up. Upstream's INSERT answers with the Id and nothing else. | #9, #11 | | **Mutation expressions** | A generated mutation assigns a field a SQL expression (`SetFieldExpr`, `FieldExpr`, `ExprFields`; `SetField` hands one over), which an update writes and `Fields`/`Field` report to hooks. A validated, immutable, id or edge field refuses one, as does a create. `sqlgraph` writes a `sql.Querier` in a `FieldSpec` as SQL, even for a JSON column, which upstream would encode. Upstream's only route for an expression is `Modify`, which the mutation never sees. | #1 | | **Set after clear** | A mutation's `SetX` drops a previous clear of an optional field, so `ClearX().SetX(v)` writes `v` once. Upstream emits `x = NULL, x = ?`, which PostgreSQL refuses. The same fix was offered upstream; drop this row once upstream has it. | #13 | +| **A field named after a mutation method** | A field's `Clear` and `Cleared` are renamed when every mutation has a method of that name, as its `Add`, `Set` and the rest already were -- `ClearFieldField` and `FieldFieldCleared` for a field named `field` -- and everything that calls a field's method calls it by the namer: the dispatchers that take a field by its name (`AddedField`, `AddField`, `ClearField`), the update builders, and an update's check of a required edge (`EdgeEdgeCleared`). `mutMethods` lists every method a generated mutation has beside `ent.Mutation`'s, which upstream's list does not; one of them, `Ids`, is upstream's `IDs`, which a field named `ids` meets only here. Upstream has the rest of this bug; drop the row once it has the fix. | #21 | | **Time: zone** | Every `time.Time` is UTC at both edges. `bindArgs` moves an argument to UTC; `Rows.Scan` moves a scanned value to UTC; `field.Time`'s `Default`/`UpdateDefault` answer in UTC. | `7d10ad284`, `c6003ab94`, `1d1a9d88b` | | **Time: precision** | Time columns keep six fractional-second digits by default; `field.Time().Precision(n)` says otherwise. | `cede1c296` | | **Time: MySql column** | A time field is a `datetime`, not a `timestamp` -- no session `time_zone` conversion, no 2038. | `5d232985b` | diff --git a/entc/gen/mutnames_test.go b/entc/gen/mutnames_test.go new file mode 100644 index 0000000000..2f159fa6e7 --- /dev/null +++ b/entc/gen/mutnames_test.go @@ -0,0 +1,146 @@ +// Copyright 2026 Seunghyun Hwang. 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 gen + +import ( + "go/ast" + "go/parser" + "go/token" + "path/filepath" + "strings" + "testing" + "unicode" + + "github.com/protobuf-orm/ent/entc/load" + "github.com/protobuf-orm/ent/schema/field" + "github.com/stretchr/testify/require" +) + +// fieldMethods are the names of a field's own mutation methods. +var fieldMethods = map[string]func(Field) string{ + "MutationGet": Field.MutationGet, + "MutationGetOld": Field.MutationGetOld, + "MutationSet": Field.MutationSet, + "MutationReset": Field.MutationReset, + "MutationClear": Field.MutationClear, + "MutationCleared": Field.MutationCleared, + "MutationAdd": Field.MutationAdd, + "MutationAdded": Field.MutationAdded, + "MutationAppend": Field.MutationAppend, + "MutationAppended": Field.MutationAppended, +} + +// TestField_MutationNames names a field after each method every mutation has, +// and after what is left of one once a field method's prefix or suffix is +// taken off it -- `field` for AddField, `edge` for EdgeCleared -- and requires +// that none of that field's own methods is one of them. +// +// One that is would be declared twice, or would be shadowed by the ent +// package's mutation, and the client would not compile: the field method and +// the generic one taking a field by its name are different functions of the +// same name. Two namers did not ask (Clear, Cleared), and the dispatchers +// that call a field's method by name called the generic one instead. +func TestField_MutationNames(t *testing.T) { + typ := &Type{Id: &Field{Name: "id", Type: &field.TypeInfo{Type: field.TypeInt}}} + typ.Id.typ = typ + + affixes := [][2]string{ + {"", ""}, {"Old", ""}, {"Set", ""}, {"Reset", ""}, {"Clear", ""}, {"", "Cleared"}, + {"Add", ""}, {"Added", ""}, {"Append", ""}, {"Appended", ""}, + } + tried := map[string]bool{} + for m := range mutMethods { + for _, a := range affixes { + rest, ok := strings.CutPrefix(m, a[0]) + if !ok { + continue + } + if rest, ok = strings.CutSuffix(rest, a[1]); !ok || rest == "" || !unicode.IsUpper(rune(rest[0])) { + continue + } + name := snakeWords(rest) + if pascal(name) != rest || tried[name] { + continue + } + tried[name] = true + + f := Field{Name: name, typ: typ, Type: &field.TypeInfo{Type: field.TypeInt}} + for namer, method := range fieldMethods { + got := method(f) + require.False(t, mutMethods[got], "%s of a field named %q is %s, which every mutation has", namer, name, got) + } + } + } + for _, name := range []string{"field", "fields", "edge", "ids", "where", "op", "type"} { + require.True(t, tried[name], "%q was not tried", name) + } +} + +// snakeWords is a name whose words are the PascalCase words of s, which is +// pascal undone: WhereP is where_p. +func snakeWords(s string) string { + var b strings.Builder + for i, r := range s { + if i > 0 && unicode.IsUpper(r) { + b.WriteByte('_') + } + b.WriteRune(unicode.ToLower(r)) + } + return b.String() +} + +// TestMutationMethods generates a type with nothing of its own and requires +// that every exported method its mutations have, in the type's package and in +// the ent package, is one the field namers keep clear of. +// +// mutMethods is ent.Mutation's methods and a list of the others, and the list +// is the part that can go stale: it missed Ids, which a field named `ids` +// shadowed, since this fork spells upstream's IDs as a word. +func TestMutationMethods(t *testing.T) { + target := filepath.Join(t.TempDir(), "ent") + graph, err := NewGraph(&Config{ + Package: "entc/gen", + Target: target, + Storage: drivers[0], + IdType: &field.TypeInfo{Type: field.TypeInt}, + }, &load.Schema{Name: "T1"}) + require.NoError(t, err) + require.NoError(t, graph.Gen()) + + methods := map[string]bool{} + for path, receiver := range map[string]string{ + filepath.Join(target, "t1", "mutation.go"): "Mutation", + filepath.Join(target, "mutation.go"): "T1Mutation", + } { + f, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.SkipObjectResolution) + require.NoError(t, err) + for _, d := range f.Decls { + fn, ok := d.(*ast.FuncDecl) + if !ok || fn.Recv == nil || !fn.Name.IsExported() || named(fn.Recv.List[0].Type) != receiver { + continue + } + methods[fn.Name.Name] = true + } + } + require.Contains(t, methods, "Ids", "the generated mutation was not read") + for m := range methods { + // The id's own getter, which no other field can be named after. + if m == "Id" { + continue + } + require.True(t, mutMethods[m], "every mutation has %s, and a field may be given a method of that name", m) + } +} + +// named is the name of a receiver's type, through its pointer. +func named(e ast.Expr) string { + if s, ok := e.(*ast.StarExpr); ok { + e = s.X + } + if id, ok := e.(*ast.Ident); ok { + return id.Name + } + return "" +} diff --git a/entc/gen/template/builder/setter.tmpl b/entc/gen/template/builder/setter.tmpl index d3fd4a582c..170525671d 100644 --- a/entc/gen/template/builder/setter.tmpl +++ b/entc/gen/template/builder/setter.tmpl @@ -68,7 +68,7 @@ in the LICENSE file in the root directory of this source tree. {{ $func := print "Clear" $f.StructField }} // {{ $func }} clears the value of the "{{ $f.Name }}" field. func ({{ $receiver }} *{{ $builder }}) {{ $func }}() *{{ $builder }} { - {{ $receiver }}.mutation.{{ $func }}() + {{ $receiver }}.mutation.{{ $f.MutationClear }}() return {{ $receiver }} } {{ end }} diff --git a/entc/gen/template/builder/update.tmpl b/entc/gen/template/builder/update.tmpl index 16e8c9ce5d..525c6e66f3 100644 --- a/entc/gen/template/builder/update.tmpl +++ b/entc/gen/template/builder/update.tmpl @@ -233,7 +233,7 @@ func ({{ $receiver }} *{{ $onebuilder }}) ExecX(ctx context.Context) { func ({{ $receiver }} *{{ $builder }}) defaults() {{ if $runtimeRequired }}error{{ end }}{ {{- range $f := $.Fields }} {{- if $f.UpdateDefault }} - if _, ok := {{ $mutation }}.{{ $f.MutationGet }}(); !ok {{ if $f.Optional }} && !{{ $mutation }}.{{ $f.StructField }}Cleared() {{ end }} { + if _, ok := {{ $mutation }}.{{ $f.MutationGet }}(); !ok {{ if $f.Optional }} && !{{ $mutation }}.{{ $f.MutationCleared }}() {{ end }} { {{- /* An expression is what the field was set to, and setting the default would replace it. */}} {{- if $f.SupportsMutationExpr }} if _, ok := {{ $mutation }}.FieldExpr({{ $.Package }}.{{ $f.Constant }}); !ok { @@ -272,7 +272,7 @@ func ({{ $receiver }} *{{ $onebuilder }}) ExecX(ctx context.Context) { {{- end }} {{- range $e := $.Edges }} {{- if and $e.Unique (not $e.Optional) }} - if {{ $mutation }}.{{ $e.StructField }}Cleared() && len({{ $mutation }}.{{ $e.StructField }}Ids()) > 0 { + if {{ $mutation }}.{{ $e.MutationCleared }}() && len({{ $mutation }}.{{ $e.StructField }}Ids()) > 0 { return errors.New(`{{ $pkg }}: clearing a required unique edge "{{ $.Name }}.{{ $e.Name }}"`) } {{- end }} diff --git a/entc/gen/template/dialect/sql/update.tmpl b/entc/gen/template/dialect/sql/update.tmpl index f6c95686e5..98c4d59397 100644 --- a/entc/gen/template/dialect/sql/update.tmpl +++ b/entc/gen/template/dialect/sql/update.tmpl @@ -144,7 +144,7 @@ func ({{ $receiver }} *{{ $builder }}) sqlSave(ctx context.Context) (_node {{ if {{- end }} {{- end }} {{- if $f.Optional }} - if {{ $mutation }}.{{ $f.StructField }}Cleared() { + if {{ $mutation }}.{{ $f.MutationCleared }}() { _spec.ClearField({{ $.Package }}.{{ $f.Constant }}, field.{{ $f.Type.ConstName }}) } {{- end }} diff --git a/entc/gen/template/mutation.tmpl b/entc/gen/template/mutation.tmpl index dec5a866d0..e82603df58 100644 --- a/entc/gen/template/mutation.tmpl +++ b/entc/gen/template/mutation.tmpl @@ -479,7 +479,7 @@ func (m *Mutation) AddedField(name string) (ent.Value, bool) { {{- range $f := $.Fields }} {{- if $f.SupportsMutationAdd }} case {{ $f.Constant }}: - return m.Added{{ $f.StructField }}() + return m.{{ $f.MutationAdded }}() {{- end }} {{- end }} } @@ -501,7 +501,7 @@ func (m *Mutation) AddField(name string, value ent.Value) error { if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.Add{{ $f.StructField }}(v) + m.{{ $f.MutationAdd }}(v) return nil {{- end }} {{- end }} @@ -543,7 +543,7 @@ func (m *Mutation) ClearField(name string) error { {{- range $f := $.Fields }} {{- if $f.Optional }} case {{ $f.Constant }}: - m.Clear{{ $f.StructField }}() + m.{{ $f.MutationClear }}() return nil {{- end }} {{- end }} diff --git a/entc/gen/type.go b/entc/gen/type.go index ada2909652..ada90acac5 100644 --- a/entc/gen/type.go +++ b/entc/gen/type.go @@ -1175,9 +1175,18 @@ func (f Field) EntSql() *entsql.Annotation { return sqlAnnotate(f.Annotations) } -// mutMethods returns the method names of mutation interface. +// mutMethods holds the method names of the mutation interface, and of the +// methods every generated mutation has beside them. A field's own method of +// one of these names would be declared twice, or shadowed by the ent +// package's mutation, which embeds the entity package's. Ids is one: upstream +// spells it IDs, and spelled by this fork's rule it is also the getter of a +// field named "ids". var mutMethods = func() map[string]bool { - names := map[string]bool{"Client": true, "Tx": true, "Where": true, "SetOp": true} + names := map[string]bool{ + "Client": true, "Tx": true, "Ids": true, + "Where": true, "WhereP": true, "Predicates": true, "SetOp": true, + "SetFieldExpr": true, "FieldExpr": true, "ExprFields": true, + } t := reflect.TypeOf(new(ent.Mutation)).Elem() for i := 0; i < t.NumMethod(); i++ { names[t.Method(i).Name] = true @@ -1228,14 +1237,26 @@ func (f Field) MutationSet() string { } // MutationClear returns the method name for clearing the field value. +// The default name is "Clear". If the method conflicts with +// the mutation methods, suffix the method with "Field". func (f Field) MutationClear() string { - return "Clear" + f.StructField() + name := "Clear" + f.StructField() + if mutMethods[name] { + name += "Field" + } + return name } // MutationCleared returns the method name for indicating if the field -// was cleared in the mutation. +// was cleared in the mutation. The default name is "Cleared". +// If the method conflicts with the mutation methods, add "Field" after +// the field name, as an edge's adds "Edge". func (f Field) MutationCleared() string { - return f.StructField() + "Cleared" + name := f.StructField() + "Cleared" + if mutMethods[name] { + return f.StructField() + "FieldCleared" + } + return name } // MutationAdd returns the method name for adding a value to the field. diff --git a/entc/integration/fieldnames/ent/client.go b/entc/integration/fieldnames/ent/client.go new file mode 100644 index 0000000000..f79b564712 --- /dev/null +++ b/entc/integration/fieldnames/ent/client.go @@ -0,0 +1,550 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "log" + "reflect" + + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/migrate" + + "github.com/protobuf-orm/ent" + "github.com/protobuf-orm/ent/dialect" + "github.com/protobuf-orm/ent/dialect/sql" + "github.com/protobuf-orm/ent/dialect/sql/sqlgraph" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/item" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/owner" +) + +// 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 + // Item is the client for interacting with the Item builders. + Item *ItemClient + // Owner is the client for interacting with the Owner builders. + Owner *OwnerClient +} + +// NewClient creates a new client configured with the given options. +func NewClient(opts ...Option) *Client { + client := &Client{config: newConfig(opts...)} + client.init() + return client +} + +func (c *Client) init() { + c.Schema = migrate.NewSchema(c.driver) + c.Item = NewItemClient(c.config) + c.Owner = NewOwnerClient(c.config) +} + +type ( + // config is the configuration for the client and its builder. + 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(...any) + // hooks to execute on mutations. + hooks *hooks + // interceptors to execute on queries. + inters *inters + } + // Option function to configure the client. + Option func(*config) +) + +// newConfig creates a new config for the client. +func newConfig(opts ...Option) config { + cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}} + cfg.options(opts...) + return cfg +} + +// 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(...any)) 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 + } +} + +// 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) + } +} + +// ErrTxStarted is returned when trying to start a new transaction from a transactional client. +var ErrTxStarted = errors.New("ent: cannot start a transaction within a transaction") + +// 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, ErrTxStarted + } + 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, + Item: NewItemClient(cfg), + Owner: NewOwnerClient(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, errors.New("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{ + ctx: ctx, + config: cfg, + Item: NewItemClient(cfg), + Owner: NewOwnerClient(cfg), + }, nil +} + +// Debug returns a new debug-client. It's used to get verbose logging on specific operations. +// +// client.Debug(). +// Item. +// 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() +} + +// Dialect is the name of the Sql this client speaks. +// +// Code that writes SQL of its own has to know which SQL it may write, and the +// connection is what settles that. Asking the client keeps the answer from +// being a second claim that can disagree with the one made when it was opened. +func (c *Client) Dialect() string { + return c.driver.Dialect() +} + +// Driver is what this client runs its queries through. +// +// It is what a transaction is begun on when several clients are to share one, +// and what is handed back to [Client.WithDriver] afterwards. +func (c *Client) Driver() dialect.Driver { + return c.driver +} + +// WithDriver returns a client that runs through drv and is this one in every +// other way. +// +// The hooks, the interceptors and the debug setting come along, which is the +// point: a fresh client built from the driver reaches the same database and +// quietly drops all three. It is what [Client.Tx] does to bind a client to a +// transaction, spelled for a driver that came from elsewhere. +func (c *Client) WithDriver(drv dialect.Driver) *Client { + cfg := c.config + cfg.driver = drv + client := &Client{config: cfg} + client.init() + return client +} + +// InTx reports whether this client is already bound to a transaction, which is +// the one [Client.Tx] refuses to nest. +// +// It is the question Tx asks itself, so a caller can ask it first rather than +// starting a transaction to find out. +// +// Any transaction, not only one this package began: a stack sharing one begun +// with [dialect.BeginTx] is inside it as much as a client handed out by +// [Client.Tx] is, and a caller deciding whether to start one has the same +// answer either way. +func (c *Client) InTx() bool { + return dialect.InTx(c.driver) +} + +// 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.Item.Use(hooks...) + c.Owner.Use(hooks...) +} + +// Intercept adds the query interceptors to all the entity clients. +// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. +func (c *Client) Intercept(interceptors ...Interceptor) { + c.Item.Intercept(interceptors...) + c.Owner.Intercept(interceptors...) +} + +// Mutate implements the ent.Mutator interface. +func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { + switch m := m.(type) { + case *ItemMutation: + return c.Item.mutate(ctx, m) + case *OwnerMutation: + return c.Owner.mutate(ctx, m) + default: + return nil, fmt.Errorf("ent: unknown mutation type %T", m) + } +} + +// ItemClient is a client for the Item schema. +type ItemClient struct { + config +} + +// NewItemClient returns a client for the Item from the given config. +func NewItemClient(c config) *ItemClient { + return &ItemClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `item.Hooks(f(g(h())))`. +func (c *ItemClient) Use(hooks ...Hook) { + c.hooks.Item = append(c.hooks.Item, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `item.Intercept(f(g(h())))`. +func (c *ItemClient) Intercept(interceptors ...Interceptor) { + c.inters.Item = append(c.inters.Item, interceptors...) +} + +// Create returns a builder for creating a Item entity. +func (c *ItemClient) Create() *ItemCreate { + mutation := newItemMutation(c.config, OpCreate) + return &ItemCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Item entities. +func (c *ItemClient) CreateBulk(builders ...*ItemCreate) *ItemCreateBulk { + return &ItemCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *ItemClient) MapCreateBulk(slice any, setFunc func(*ItemCreate, int)) *ItemCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ItemCreateBulk{err: fmt.Errorf("calling to ItemClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ItemCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ItemCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Item. +func (c *ItemClient) Update() *ItemUpdate { + mutation := newItemMutation(c.config, OpUpdate) + return &ItemUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ItemClient) UpdateOne(_m *Item) *ItemUpdateOne { + mutation := newItemMutation(c.config, OpUpdateOne, withItem(_m)) + return &ItemUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneId returns an update builder for the given id. +func (c *ItemClient) UpdateOneId(id int) *ItemUpdateOne { + mutation := newItemMutation(c.config, OpUpdateOne, withItemId(id)) + return &ItemUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Item. +func (c *ItemClient) Delete() *ItemDelete { + mutation := newItemMutation(c.config, OpDelete) + return &ItemDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ItemClient) DeleteOne(_m *Item) *ItemDeleteOne { + return c.DeleteOneId(_m.Id) +} + +// DeleteOneId returns a builder for deleting the given entity by its id. +func (c *ItemClient) DeleteOneId(id int) *ItemDeleteOne { + builder := c.Delete().Where(item.Id(id)) + builder.mutation.id = &id + builder.mutation.SetOp(OpDeleteOne) + return &ItemDeleteOne{builder} +} + +// Query returns a query builder for Item. +func (c *ItemClient) Query() *ItemQuery { + return &ItemQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeItem}, + inters: c.Interceptors(), + } +} + +// Get returns a Item entity by its id. +func (c *ItemClient) Get(ctx context.Context, id int) (*Item, error) { + return c.Query().Where(item.Id(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ItemClient) GetX(ctx context.Context, id int) *Item { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *ItemClient) Hooks() []Hook { + return c.hooks.Item +} + +// Interceptors returns the client interceptors. +func (c *ItemClient) Interceptors() []Interceptor { + return c.inters.Item +} + +func (c *ItemClient) mutate(ctx context.Context, m *ItemMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ItemCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ItemUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ItemUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ItemDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Item mutation op: %q", m.Op()) + } +} + +// OwnerClient is a client for the Owner schema. +type OwnerClient struct { + config +} + +// NewOwnerClient returns a client for the Owner from the given config. +func NewOwnerClient(c config) *OwnerClient { + return &OwnerClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `owner.Hooks(f(g(h())))`. +func (c *OwnerClient) Use(hooks ...Hook) { + c.hooks.Owner = append(c.hooks.Owner, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `owner.Intercept(f(g(h())))`. +func (c *OwnerClient) Intercept(interceptors ...Interceptor) { + c.inters.Owner = append(c.inters.Owner, interceptors...) +} + +// Create returns a builder for creating a Owner entity. +func (c *OwnerClient) Create() *OwnerCreate { + mutation := newOwnerMutation(c.config, OpCreate) + return &OwnerCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Owner entities. +func (c *OwnerClient) CreateBulk(builders ...*OwnerCreate) *OwnerCreateBulk { + return &OwnerCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *OwnerClient) MapCreateBulk(slice any, setFunc func(*OwnerCreate, int)) *OwnerCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &OwnerCreateBulk{err: fmt.Errorf("calling to OwnerClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*OwnerCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &OwnerCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Owner. +func (c *OwnerClient) Update() *OwnerUpdate { + mutation := newOwnerMutation(c.config, OpUpdate) + return &OwnerUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *OwnerClient) UpdateOne(_m *Owner) *OwnerUpdateOne { + mutation := newOwnerMutation(c.config, OpUpdateOne, withOwner(_m)) + return &OwnerUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneId returns an update builder for the given id. +func (c *OwnerClient) UpdateOneId(id int) *OwnerUpdateOne { + mutation := newOwnerMutation(c.config, OpUpdateOne, withOwnerId(id)) + return &OwnerUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Owner. +func (c *OwnerClient) Delete() *OwnerDelete { + mutation := newOwnerMutation(c.config, OpDelete) + return &OwnerDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *OwnerClient) DeleteOne(_m *Owner) *OwnerDeleteOne { + return c.DeleteOneId(_m.Id) +} + +// DeleteOneId returns a builder for deleting the given entity by its id. +func (c *OwnerClient) DeleteOneId(id int) *OwnerDeleteOne { + builder := c.Delete().Where(owner.Id(id)) + builder.mutation.id = &id + builder.mutation.SetOp(OpDeleteOne) + return &OwnerDeleteOne{builder} +} + +// Query returns a query builder for Owner. +func (c *OwnerClient) Query() *OwnerQuery { + return &OwnerQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeOwner}, + inters: c.Interceptors(), + } +} + +// Get returns a Owner entity by its id. +func (c *OwnerClient) Get(ctx context.Context, id int) (*Owner, error) { + return c.Query().Where(owner.Id(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *OwnerClient) GetX(ctx context.Context, id int) *Owner { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryEdge queries the edge edge of a Owner. +func (c *OwnerClient) QueryEdge(_m *Owner) *ItemQuery { + query := (&ItemClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.Id + step := sqlgraph.NewStep( + sqlgraph.From(owner.Table, owner.FieldId, id), + sqlgraph.To(item.Table, item.FieldId), + sqlgraph.Edge(sqlgraph.M2O, false, owner.EdgeTable, owner.EdgeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *OwnerClient) Hooks() []Hook { + return c.hooks.Owner +} + +// Interceptors returns the client interceptors. +func (c *OwnerClient) Interceptors() []Interceptor { + return c.inters.Owner +} + +func (c *OwnerClient) mutate(ctx context.Context, m *OwnerMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&OwnerCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&OwnerUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&OwnerUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&OwnerDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Owner mutation op: %q", m.Op()) + } +} + +// hooks and interceptors per client, for fast access. +type ( + hooks struct { + Item, Owner []ent.Hook + } + inters struct { + Item, Owner []ent.Interceptor + } +) diff --git a/entc/integration/fieldnames/ent/ent.go b/entc/integration/fieldnames/ent/ent.go new file mode 100644 index 0000000000..a451c7f40e --- /dev/null +++ b/entc/integration/fieldnames/ent/ent.go @@ -0,0 +1,614 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "reflect" + "sync" + + "github.com/protobuf-orm/ent" + "github.com/protobuf-orm/ent/dialect/sql" + "github.com/protobuf-orm/ent/dialect/sql/sqlgraph" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/item" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/owner" +) + +// ent aliases to avoid import conflicts in user's code. +type ( + Op = ent.Op + Hook = ent.Hook + Value = ent.Value + Query = ent.Query + QueryContext = ent.QueryContext + Querier = ent.Querier + QuerierFunc = ent.QuerierFunc + Interceptor = ent.Interceptor + InterceptFunc = ent.InterceptFunc + Traverser = ent.Traverser + TraverseFunc = ent.TraverseFunc + Policy = ent.Policy + Mutator = ent.Mutator + Mutation = ent.Mutation + MutateFunc = ent.MutateFunc +) + +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) +} + +// OrderFunc applies an ordering on the sql selector. +// Deprecated: Use Asc/Desc functions or the package builders instead. +type OrderFunc func(*sql.Selector) + +var ( + initCheck sync.Once + columnCheck sql.ColumnCheck +) + +// checkColumn checks if the column exists in the given table. +func checkColumn(t, c string) error { + initCheck.Do(func() { + columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ + item.Table: item.ValidColumn, + owner.Table: owner.ValidColumn, + }) + }) + return columnCheck(t, c) +} + +// Asc applies the given fields in ASC order. +func Asc(fields ...string) func(*sql.Selector) { + return func(s *sql.Selector) { + for _, f := range fields { + if err := checkColumn(s.TableName(), 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) func(*sql.Selector) { + return func(s *sql.Selector) { + for _, f := range fields { + if err := checkColumn(s.TableName(), 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 { + if err := checkColumn(s.TableName(), 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 { + if err := checkColumn(s.TableName(), 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 { + if err := checkColumn(s.TableName(), 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 { + if err := checkColumn(s.TableName(), 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 or edge 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) +} + +// selector embedded by the different Select/GroupBy builders. +type selector struct { + label string + flds *[]string + fns []AggregateFunc + scan func(context.Context, any) error +} + +// ScanX is like Scan, but panics if an error occurs. +func (s *selector) ScanX(ctx context.Context, v any) { + if err := s.scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (s *selector) Strings(ctx context.Context) ([]string, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (s *selector) StringsX(ctx context.Context) []string { + v, err := s.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 (s *selector) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = s.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (s *selector) StringX(ctx context.Context) string { + v, err := s.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 (s *selector) Ints(ctx context.Context) ([]int, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (s *selector) IntsX(ctx context.Context) []int { + v, err := s.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 (s *selector) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = s.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (s *selector) IntX(ctx context.Context) int { + v, err := s.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 (s *selector) Float64s(ctx context.Context) ([]float64, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (s *selector) Float64sX(ctx context.Context) []float64 { + v, err := s.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 (s *selector) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = s.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (s *selector) Float64X(ctx context.Context) float64 { + v, err := s.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 (s *selector) Bools(ctx context.Context) ([]bool, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (s *selector) BoolsX(ctx context.Context) []bool { + v, err := s.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 (s *selector) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = s.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (s *selector) BoolX(ctx context.Context) bool { + v, err := s.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +// withHooks invokes the builder operation with the given hooks, if any. +func withHooks[V Value, M any, PM interface { + *M + Mutation +}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) { + if len(hooks) == 0 { + return exec(ctx) + } + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutationT, ok := any(m).(PM) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + // Set the mutation to the builder. + *mutation = *mutationT + return exec(ctx) + }) + for i := len(hooks) - 1; i >= 0; i-- { + if hooks[i] == nil { + return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = hooks[i](mut) + } + v, err := mut.Mutate(ctx, mutation) + if err != nil { + return value, err + } + nv, ok := v.(V) + if !ok { + return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation) + } + return nv, nil +} + +// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist. +func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context { + if ent.QueryFromContext(ctx) == nil { + qc.Op = op + ctx = ent.NewQueryContext(ctx, qc) + } + return ctx +} + +func querierAll[V Value, Q interface { + sqlAll(context.Context, ...queryHook) (V, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlAll(ctx) + }) +} + +func querierCount[Q interface { + sqlCount(context.Context) (int, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlCount(ctx) + }) +} + +func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) { + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + rv, err := qr.Query(ctx, q) + if err != nil { + return v, err + } + vt, ok := rv.(V) + if !ok { + return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v) + } + return vt, nil +} + +func scanWithInterceptors[Q1 ent.Query, Q2 interface { + sqlScan(context.Context, Q1, any) error +}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error { + rv := reflect.ValueOf(v) + var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q1) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + if err := selectOrGroup.sqlScan(ctx, query, v); err != nil { + return nil, err + } + if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() { + return rv.Elem().Interface(), nil + } + return v, nil + }) + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + vv, err := qr.Query(ctx, rootQuery) + if err != nil { + return err + } + switch rv2 := reflect.ValueOf(vv); { + case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer: + case rv.Type() == rv2.Type(): + rv.Elem().Set(rv2.Elem()) + case rv.Elem().Type() == rv2.Type(): + rv.Elem().Set(rv2) + } + return nil +} + +// queryHook describes an internal hook for the different sqlAll methods. +type queryHook func(context.Context, *sqlgraph.QuerySpec) diff --git a/entc/integration/fieldnames/ent/entql.go b/entc/integration/fieldnames/ent/entql.go new file mode 100644 index 0000000000..3514ebcd60 --- /dev/null +++ b/entc/integration/fieldnames/ent/entql.go @@ -0,0 +1,210 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package ent + +import ( + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/item" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/owner" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/predicate" + + "github.com/protobuf-orm/ent/dialect/sql" + "github.com/protobuf-orm/ent/dialect/sql/sqlgraph" + "github.com/protobuf-orm/ent/entql" + "github.com/protobuf-orm/ent/schema/field" +) + +// schemaGraph holds a representation of ent/schema at runtime. +var schemaGraph = func() *sqlgraph.Schema { + graph := &sqlgraph.Schema{Nodes: make([]*sqlgraph.Node, 2)} + graph.Nodes[0] = &sqlgraph.Node{ + NodeSpec: sqlgraph.NodeSpec{ + Table: item.Table, + Columns: item.Columns, + Id: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: item.FieldId, + }, + }, + Type: "Item", + Fields: map[string]*sqlgraph.FieldSpec{ + item.FieldField: {Type: field.TypeInt, Column: item.FieldField}, + item.FieldFields: {Type: field.TypeInt, Column: item.FieldFields}, + item.FieldEdge: {Type: field.TypeInt, Column: item.FieldEdge}, + item.FieldIds: {Type: field.TypeInt, Column: item.FieldIds}, + item.FieldWhere: {Type: field.TypeInt, Column: item.FieldWhere}, + item.FieldOp: {Type: field.TypeInt, Column: item.FieldOp}, + item.FieldType: {Type: field.TypeInt, Column: item.FieldType}, + }, + } + graph.Nodes[1] = &sqlgraph.Node{ + NodeSpec: sqlgraph.NodeSpec{ + Table: owner.Table, + Columns: owner.Columns, + Id: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: owner.FieldId, + }, + }, + Type: "Owner", + Fields: map[string]*sqlgraph.FieldSpec{ + owner.FieldField: {Type: field.TypeInt, Column: owner.FieldField}, + }, + } + graph.MustAddE( + "edge", + &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: owner.EdgeTable, + Columns: []string{owner.EdgeColumn}, + Bidi: false, + }, + "Owner", + "Item", + ) + return graph +}() + +// predicateAdder wraps the addPredicate method. +// All update, update-one and query builders implement this interface. +type predicateAdder interface { + addPredicate(func(s *sql.Selector)) +} + +// addPredicate implements the predicateAdder interface. +func (_q *ItemQuery) addPredicate(pred func(s *sql.Selector)) { + _q.predicates = append(_q.predicates, pred) +} + +// Filter returns a Filter implementation to apply filters on the ItemQuery builder. +func (_q *ItemQuery) Filter() *ItemFilter { + return &ItemFilter{config: _q.config, predicateAdder: _q} +} + +// addPredicate implements the predicateAdder interface. +func (m *ItemMutation) addPredicate(pred func(s *sql.Selector)) { + m.Where(pred) +} + +// Filter returns an entql.Where implementation to apply filters on the ItemMutation builder. +func (m *ItemMutation) Filter() *ItemFilter { + return &ItemFilter{config: m.config, predicateAdder: m} +} + +// ItemFilter provides a generic filtering capability at runtime for ItemQuery. +type ItemFilter struct { + predicateAdder + config +} + +// Where applies the entql predicate on the query filter. +func (f *ItemFilter) Where(p entql.P) { + f.addPredicate(func(s *sql.Selector) { + if err := schemaGraph.EvalP(schemaGraph.Nodes[0].Type, p, s); err != nil { + s.AddError(err) + } + }) +} + +// WhereId applies the entql int predicate on the id field. +func (f *ItemFilter) WhereId(p entql.IntP) { + f.Where(p.Field(item.FieldId)) +} + +// WhereField applies the entql int predicate on the field field. +func (f *ItemFilter) WhereField(p entql.IntP) { + f.Where(p.Field(item.FieldField)) +} + +// WhereFields applies the entql int predicate on the fields field. +func (f *ItemFilter) WhereFields(p entql.IntP) { + f.Where(p.Field(item.FieldFields)) +} + +// WhereEdge applies the entql int predicate on the edge field. +func (f *ItemFilter) WhereEdge(p entql.IntP) { + f.Where(p.Field(item.FieldEdge)) +} + +// WhereIds applies the entql int predicate on the ids field. +func (f *ItemFilter) WhereIds(p entql.IntP) { + f.Where(p.Field(item.FieldIds)) +} + +// WhereWhere applies the entql int predicate on the where field. +func (f *ItemFilter) WhereWhere(p entql.IntP) { + f.Where(p.Field(item.FieldWhere)) +} + +// WhereOp applies the entql int predicate on the op field. +func (f *ItemFilter) WhereOp(p entql.IntP) { + f.Where(p.Field(item.FieldOp)) +} + +// WhereType applies the entql int predicate on the type field. +func (f *ItemFilter) WhereType(p entql.IntP) { + f.Where(p.Field(item.FieldType)) +} + +// addPredicate implements the predicateAdder interface. +func (_q *OwnerQuery) addPredicate(pred func(s *sql.Selector)) { + _q.predicates = append(_q.predicates, pred) +} + +// Filter returns a Filter implementation to apply filters on the OwnerQuery builder. +func (_q *OwnerQuery) Filter() *OwnerFilter { + return &OwnerFilter{config: _q.config, predicateAdder: _q} +} + +// addPredicate implements the predicateAdder interface. +func (m *OwnerMutation) addPredicate(pred func(s *sql.Selector)) { + m.Where(pred) +} + +// Filter returns an entql.Where implementation to apply filters on the OwnerMutation builder. +func (m *OwnerMutation) Filter() *OwnerFilter { + return &OwnerFilter{config: m.config, predicateAdder: m} +} + +// OwnerFilter provides a generic filtering capability at runtime for OwnerQuery. +type OwnerFilter struct { + predicateAdder + config +} + +// Where applies the entql predicate on the query filter. +func (f *OwnerFilter) Where(p entql.P) { + f.addPredicate(func(s *sql.Selector) { + if err := schemaGraph.EvalP(schemaGraph.Nodes[1].Type, p, s); err != nil { + s.AddError(err) + } + }) +} + +// WhereId applies the entql int predicate on the id field. +func (f *OwnerFilter) WhereId(p entql.IntP) { + f.Where(p.Field(owner.FieldId)) +} + +// WhereField applies the entql int predicate on the field field. +func (f *OwnerFilter) WhereField(p entql.IntP) { + f.Where(p.Field(owner.FieldField)) +} + +// WhereHasEdge applies a predicate to check if query has an edge edge. +func (f *OwnerFilter) WhereHasEdge() { + f.Where(entql.HasEdge("edge")) +} + +// WhereHasEdgeWith applies a predicate to check if query has an edge edge with a given conditions (other predicates). +func (f *OwnerFilter) WhereHasEdgeWith(preds ...predicate.Item) { + f.Where(entql.HasEdgeWith("edge", sqlgraph.WrapFunc(func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }))) +} diff --git a/entc/integration/fieldnames/ent/enttest/enttest.go b/entc/integration/fieldnames/ent/enttest/enttest.go new file mode 100644 index 0000000000..ebcc9cd61b --- /dev/null +++ b/entc/integration/fieldnames/ent/enttest/enttest.go @@ -0,0 +1,88 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package enttest + +import ( + "context" + + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent" + // required by schema hooks. + _ "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/runtime" + + "github.com/protobuf-orm/ent/dialect/sql/schema" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/migrate" +) + +type ( + // TestingT is the interface that is shared between + // testing.T and testing.B and used by enttest. + TestingT interface { + FailNow() + Error(...any) + } + + // 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() + } + migrateSchema(t, c, o) + 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...) + migrateSchema(t, c, o) + return c +} +func migrateSchema(t TestingT, c *ent.Client, o *options) { + tables, err := schema.CopyTables(migrate.Tables) + if err != nil { + t.Error(err) + t.FailNow() + } + if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil { + t.Error(err) + t.FailNow() + } +} diff --git a/entc/integration/fieldnames/ent/generate.go b/entc/integration/fieldnames/ent/generate.go new file mode 100644 index 0000000000..9d802184e1 --- /dev/null +++ b/entc/integration/fieldnames/ent/generate.go @@ -0,0 +1,7 @@ +// Copyright 2026 Seunghyun Hwang. 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 github.com/protobuf-orm/ent/cmd/ent generate --feature entql,privacy,intercept,sql/upsert,sql/modifier,sql/returning --header "// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT." ./schema diff --git a/entc/integration/fieldnames/ent/hook/hook.go b/entc/integration/fieldnames/ent/hook/hook.go new file mode 100644 index 0000000000..f13977427b --- /dev/null +++ b/entc/integration/fieldnames/ent/hook/hook.go @@ -0,0 +1,215 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package hook + +import ( + "context" + "fmt" + + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent" +) + +// The ItemFunc type is an adapter to allow the use of ordinary +// function as Item mutator. +type ItemFunc func(context.Context, *ent.ItemMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f ItemFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.ItemMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ItemMutation", m) +} + +// The OwnerFunc type is an adapter to allow the use of ordinary +// function as Owner mutator. +type OwnerFunc func(context.Context, *ent.OwnerMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f OwnerFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.OwnerMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.OwnerMutation", m) +} + +// 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/entc/integration/fieldnames/ent/intercept/intercept.go b/entc/integration/fieldnames/ent/intercept/intercept.go new file mode 100644 index 0000000000..75d1ef53b4 --- /dev/null +++ b/entc/integration/fieldnames/ent/intercept/intercept.go @@ -0,0 +1,183 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package intercept + +import ( + "context" + "fmt" + + "github.com/protobuf-orm/ent/dialect/sql" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/item" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/owner" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/predicate" +) + +// The Query interface represents an operation that queries a graph. +// By using this interface, users can write generic code that manipulates +// query builders of different types. +type Query interface { + // Type returns the string representation of the query type. + Type() string + // Limit the number of records to be returned by this query. + Limit(int) + // Offset to start from. + Offset(int) + // Unique configures the query builder to filter duplicate records. + Unique(bool) + // Order specifies how the records should be ordered. + Order(...func(*sql.Selector)) + // WhereP appends storage-level predicates to the query builder. Using this method, users + // can use type-assertion to append predicates that do not depend on any generated package. + WhereP(...func(*sql.Selector)) +} + +// The Func type is an adapter that allows ordinary functions to be used as interceptors. +// Unlike traversal functions, interceptors are skipped during graph traversals. Note that the +// implementation of Func is different from the one defined in github.com/protobuf-orm/ent.InterceptFunc. +type Func func(context.Context, Query) error + +// Intercept calls f(ctx, q) and then applied the next Querier. +func (f Func) Intercept(next ent.Querier) ent.Querier { + return ent.QuerierFunc(func(ctx context.Context, q ent.Query) (ent.Value, error) { + query, err := NewQuery(q) + if err != nil { + return nil, err + } + if err := f(ctx, query); err != nil { + return nil, err + } + return next.Query(ctx, q) + }) +} + +// The TraverseFunc type is an adapter to allow the use of ordinary function as Traverser. +// If f is a function with the appropriate signature, TraverseFunc(f) is a Traverser that calls f. +type TraverseFunc func(context.Context, Query) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseFunc) Intercept(next ent.Querier) ent.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseFunc) Traverse(ctx context.Context, q ent.Query) error { + query, err := NewQuery(q) + if err != nil { + return err + } + return f(ctx, query) +} + +// The ItemFunc type is an adapter to allow the use of ordinary function as a Querier. +type ItemFunc func(context.Context, *ent.ItemQuery) (ent.Value, error) + +// Query calls f(ctx, q). +func (f ItemFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) { + if q, ok := q.(*ent.ItemQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *ent.ItemQuery", q) +} + +// The TraverseItem type is an adapter to allow the use of ordinary function as Traverser. +type TraverseItem func(context.Context, *ent.ItemQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseItem) Intercept(next ent.Querier) ent.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseItem) Traverse(ctx context.Context, q ent.Query) error { + if q, ok := q.(*ent.ItemQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *ent.ItemQuery", q) +} + +// The OwnerFunc type is an adapter to allow the use of ordinary function as a Querier. +type OwnerFunc func(context.Context, *ent.OwnerQuery) (ent.Value, error) + +// Query calls f(ctx, q). +func (f OwnerFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) { + if q, ok := q.(*ent.OwnerQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *ent.OwnerQuery", q) +} + +// The TraverseOwner type is an adapter to allow the use of ordinary function as Traverser. +type TraverseOwner func(context.Context, *ent.OwnerQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseOwner) Intercept(next ent.Querier) ent.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseOwner) Traverse(ctx context.Context, q ent.Query) error { + if q, ok := q.(*ent.OwnerQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *ent.OwnerQuery", q) +} + +// NewQuery returns the generic Query interface for the given typed query. +func NewQuery(q ent.Query) (Query, error) { + switch q := q.(type) { + case *ent.ItemQuery: + return &query[*ent.ItemQuery, predicate.Item, item.OrderOption]{typ: ent.TypeItem, tq: q}, nil + case *ent.OwnerQuery: + return &query[*ent.OwnerQuery, predicate.Owner, owner.OrderOption]{typ: ent.TypeOwner, tq: q}, nil + default: + return nil, fmt.Errorf("unknown query type %T", q) + } +} + +type query[T any, P ~func(*sql.Selector), R ~func(*sql.Selector)] struct { + typ string + tq interface { + Limit(int) T + Offset(int) T + Unique(bool) T + Order(...R) T + Where(...P) T + } +} + +func (q query[T, P, R]) Type() string { + return q.typ +} + +func (q query[T, P, R]) Limit(limit int) { + q.tq.Limit(limit) +} + +func (q query[T, P, R]) Offset(offset int) { + q.tq.Offset(offset) +} + +func (q query[T, P, R]) Unique(unique bool) { + q.tq.Unique(unique) +} + +func (q query[T, P, R]) Order(orders ...func(*sql.Selector)) { + rs := make([]R, len(orders)) + for i := range orders { + rs[i] = orders[i] + } + q.tq.Order(rs...) +} + +func (q query[T, P, R]) WhereP(ps ...func(*sql.Selector)) { + p := make([]P, len(ps)) + for i := range ps { + p[i] = ps[i] + } + q.tq.Where(p...) +} diff --git a/entc/integration/fieldnames/ent/item.go b/entc/integration/fieldnames/ent/item.go new file mode 100644 index 0000000000..b441e3349b --- /dev/null +++ b/entc/integration/fieldnames/ent/item.go @@ -0,0 +1,192 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "github.com/protobuf-orm/ent" + "github.com/protobuf-orm/ent/dialect/sql" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/item" +) + +// Item is the model entity for the Item schema. +type Item struct { + config `json:"-"` + // Id of the ent. + Id int `json:"id,omitempty"` + // Field holds the value of the "field" field. + Field *int `json:"field,omitempty"` + // Fields holds the value of the "fields" field. + Fields *int `json:"fields,omitempty"` + // Edge holds the value of the "edge" field. + Edge *int `json:"edge,omitempty"` + // Ids holds the value of the "ids" field. + Ids *int `json:"ids,omitempty"` + // Where holds the value of the "where" field. + Where *int `json:"where,omitempty"` + // Op holds the value of the "op" field. + Op *int `json:"op,omitempty"` + // Type holds the value of the "type" field. + Type *int `json:"type,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Item) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case item.FieldId, item.FieldField, item.FieldFields, item.FieldEdge, item.FieldIds, item.FieldWhere, item.FieldOp, item.FieldType: + values[i] = new(sql.NullInt64) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Item fields. +func (_m *Item) assignValues(columns []string, values []any) 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 item.FieldId: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.Id = int(value.Int64) + case item.FieldField: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field field", values[i]) + } else if value.Valid { + _m.Field = new(int) + *_m.Field = int(value.Int64) + } + case item.FieldFields: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field fields", values[i]) + } else if value.Valid { + _m.Fields = new(int) + *_m.Fields = int(value.Int64) + } + case item.FieldEdge: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field edge", values[i]) + } else if value.Valid { + _m.Edge = new(int) + *_m.Edge = int(value.Int64) + } + case item.FieldIds: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field ids", values[i]) + } else if value.Valid { + _m.Ids = new(int) + *_m.Ids = int(value.Int64) + } + case item.FieldWhere: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field where", values[i]) + } else if value.Valid { + _m.Where = new(int) + *_m.Where = int(value.Int64) + } + case item.FieldOp: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field op", values[i]) + } else if value.Valid { + _m.Op = new(int) + *_m.Op = int(value.Int64) + } + case item.FieldType: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field type", values[i]) + } else if value.Valid { + _m.Type = new(int) + *_m.Type = int(value.Int64) + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Item. +// This includes values selected through modifiers, order, etc. +func (_m *Item) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this Item. +// Note that you need to call Item.Unwrap() before calling this method if this Item +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Item) Update() *ItemUpdateOne { + return NewItemClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Item 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 (_m *Item) Unwrap() *Item { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: Item is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Item) String() string { + var builder strings.Builder + builder.WriteString("Item(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.Id)) + if v := _m.Field; v != nil { + builder.WriteString("field=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.Fields; v != nil { + builder.WriteString("fields=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.Edge; v != nil { + builder.WriteString("edge=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.Ids; v != nil { + builder.WriteString("ids=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.Where; v != nil { + builder.WriteString("where=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.Op; v != nil { + builder.WriteString("op=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.Type; v != nil { + builder.WriteString("type=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteByte(')') + return builder.String() +} + +// ItemList is a parsable slice of Item. +type ItemList []*Item diff --git a/entc/integration/fieldnames/ent/item/item.go b/entc/integration/fieldnames/ent/item/item.go new file mode 100644 index 0000000000..a9a61da082 --- /dev/null +++ b/entc/integration/fieldnames/ent/item/item.go @@ -0,0 +1,99 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package item + +import ( + "github.com/protobuf-orm/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the item type in the database. + Label = "item" + // FieldId holds the string denoting the id field in the database. + FieldId = "id" + // FieldField holds the string denoting the field field in the database. + FieldField = "field" + // FieldFields holds the string denoting the fields field in the database. + FieldFields = "fields" + // FieldEdge holds the string denoting the edge field in the database. + FieldEdge = "edge" + // FieldIds holds the string denoting the ids field in the database. + FieldIds = "ids" + // FieldWhere holds the string denoting the where field in the database. + FieldWhere = "where" + // FieldOp holds the string denoting the op field in the database. + FieldOp = "op" + // FieldType holds the string denoting the type field in the database. + FieldType = "type" + // Table holds the table name of the item in the database. + Table = "item" +) + +// Columns holds all SQL columns for item fields. +var Columns = []string{ + FieldId, + FieldField, + FieldFields, + FieldEdge, + FieldIds, + FieldWhere, + FieldOp, + FieldType, +} + +// 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 +} + +// OrderOption defines the ordering options for the Item queries. +type OrderOption func(*sql.Selector) + +// ById orders the results by the id field. +func ById(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldId, opts...).ToFunc() +} + +// ByField orders the results by the field field. +func ByField(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldField, opts...).ToFunc() +} + +// ByFields orders the results by the fields field. +func ByFields(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFields, opts...).ToFunc() +} + +// ByEdge orders the results by the edge field. +func ByEdge(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldEdge, opts...).ToFunc() +} + +// ByIds orders the results by the ids field. +func ByIds(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIds, opts...).ToFunc() +} + +// ByWhere orders the results by the where field. +func ByWhere(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldWhere, opts...).ToFunc() +} + +// ByOp orders the results by the op field. +func ByOp(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldOp, opts...).ToFunc() +} + +// ByType orders the results by the type field. +func ByType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldType, opts...).ToFunc() +} diff --git a/entc/integration/fieldnames/ent/item/mutation.go b/entc/integration/fieldnames/ent/item/mutation.go new file mode 100644 index 0000000000..5dd5445765 --- /dev/null +++ b/entc/integration/fieldnames/ent/item/mutation.go @@ -0,0 +1,956 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package item + +import ( + "context" + "fmt" + + "github.com/protobuf-orm/ent" + "github.com/protobuf-orm/ent/dialect/sql" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/predicate" +) + +// Mutation represents an operation that mutates the Item nodes in the graph. +type Mutation struct { + op ent.Op + typ string + field *int + addfield *int + fields *int + addfields *int + edge *int + addedge *int + ids *int + addids *int + where *int + addwhere *int + _op *int + add_op *int + _type *int + add_type *int + clearedFields map[string]struct{} + exprs map[string]sql.Querier + predicates []predicate.Item +} + +// NewMutation creates a new Mutation for the Item entity. +func NewMutation(op ent.Op) *Mutation { + return &Mutation{ + op: op, + typ: "Item", + clearedFields: make(map[string]struct{}), + } +} + +// Predicates returns the list of predicates set on the mutation. +func (m *Mutation) Predicates() []predicate.Item { + return m.predicates +} + +// SetFieldField sets the "field" field. +func (m *Mutation) SetFieldField(i int) { + m.field = &i + m.addfield = nil + delete(m.clearedFields, FieldField) + delete(m.exprs, FieldField) +} + +// GetField returns the value of the "field" field in the mutation. +func (m *Mutation) GetField() (r int, exists bool) { + v := m.field + if v == nil { + return + } + return *v, true +} + +// AddFieldField adds i to the "field" field. +func (m *Mutation) AddFieldField(i int) { + if m.addfield != nil { + *m.addfield += i + } else { + m.addfield = &i + } +} + +// AddedFieldField returns the value that was added to the "field" field in this mutation. +func (m *Mutation) AddedFieldField() (r int, exists bool) { + v := m.addfield + if v == nil { + return + } + return *v, true +} + +// ClearFieldField clears the value of the "field" field. +func (m *Mutation) ClearFieldField() { + m.field = nil + m.addfield = nil + delete(m.exprs, FieldField) + m.clearedFields[FieldField] = struct{}{} +} + +// FieldFieldCleared returns if the "field" field was cleared in this mutation. +func (m *Mutation) FieldFieldCleared() bool { + _, ok := m.clearedFields[FieldField] + return ok +} + +// ResetFieldField resets all changes to the "field" field. +func (m *Mutation) ResetFieldField() { + m.field = nil + m.addfield = nil + delete(m.clearedFields, FieldField) + delete(m.exprs, FieldField) +} + +// SetFields sets the "fields" field. +func (m *Mutation) SetFields(i int) { + m.fields = &i + m.addfields = nil + delete(m.clearedFields, FieldFields) + delete(m.exprs, FieldFields) +} + +// GetFields returns the value of the "fields" field in the mutation. +func (m *Mutation) GetFields() (r int, exists bool) { + v := m.fields + if v == nil { + return + } + return *v, true +} + +// AddFields adds i to the "fields" field. +func (m *Mutation) AddFields(i int) { + if m.addfields != nil { + *m.addfields += i + } else { + m.addfields = &i + } +} + +// AddedFieldsField returns the value that was added to the "fields" field in this mutation. +func (m *Mutation) AddedFieldsField() (r int, exists bool) { + v := m.addfields + if v == nil { + return + } + return *v, true +} + +// ClearFields clears the value of the "fields" field. +func (m *Mutation) ClearFields() { + m.fields = nil + m.addfields = nil + delete(m.exprs, FieldFields) + m.clearedFields[FieldFields] = struct{}{} +} + +// FieldsCleared returns if the "fields" field was cleared in this mutation. +func (m *Mutation) FieldsCleared() bool { + _, ok := m.clearedFields[FieldFields] + return ok +} + +// ResetFields resets all changes to the "fields" field. +func (m *Mutation) ResetFields() { + m.fields = nil + m.addfields = nil + delete(m.clearedFields, FieldFields) + delete(m.exprs, FieldFields) +} + +// SetEdge sets the "edge" field. +func (m *Mutation) SetEdge(i int) { + m.edge = &i + m.addedge = nil + delete(m.clearedFields, FieldEdge) + delete(m.exprs, FieldEdge) +} + +// Edge returns the value of the "edge" field in the mutation. +func (m *Mutation) Edge() (r int, exists bool) { + v := m.edge + if v == nil { + return + } + return *v, true +} + +// AddEdge adds i to the "edge" field. +func (m *Mutation) AddEdge(i int) { + if m.addedge != nil { + *m.addedge += i + } else { + m.addedge = &i + } +} + +// AddedEdge returns the value that was added to the "edge" field in this mutation. +func (m *Mutation) AddedEdge() (r int, exists bool) { + v := m.addedge + if v == nil { + return + } + return *v, true +} + +// ClearEdgeField clears the value of the "edge" field. +func (m *Mutation) ClearEdgeField() { + m.edge = nil + m.addedge = nil + delete(m.exprs, FieldEdge) + m.clearedFields[FieldEdge] = struct{}{} +} + +// EdgeFieldCleared returns if the "edge" field was cleared in this mutation. +func (m *Mutation) EdgeFieldCleared() bool { + _, ok := m.clearedFields[FieldEdge] + return ok +} + +// ResetEdgeField resets all changes to the "edge" field. +func (m *Mutation) ResetEdgeField() { + m.edge = nil + m.addedge = nil + delete(m.clearedFields, FieldEdge) + delete(m.exprs, FieldEdge) +} + +// SetIds sets the "ids" field. +func (m *Mutation) SetIds(i int) { + m.ids = &i + m.addids = nil + delete(m.clearedFields, FieldIds) + delete(m.exprs, FieldIds) +} + +// GetIds returns the value of the "ids" field in the mutation. +func (m *Mutation) GetIds() (r int, exists bool) { + v := m.ids + if v == nil { + return + } + return *v, true +} + +// AddIds adds i to the "ids" field. +func (m *Mutation) AddIds(i int) { + if m.addids != nil { + *m.addids += i + } else { + m.addids = &i + } +} + +// AddedIdsField returns the value that was added to the "ids" field in this mutation. +func (m *Mutation) AddedIdsField() (r int, exists bool) { + v := m.addids + if v == nil { + return + } + return *v, true +} + +// ClearIds clears the value of the "ids" field. +func (m *Mutation) ClearIds() { + m.ids = nil + m.addids = nil + delete(m.exprs, FieldIds) + m.clearedFields[FieldIds] = struct{}{} +} + +// IdsCleared returns if the "ids" field was cleared in this mutation. +func (m *Mutation) IdsCleared() bool { + _, ok := m.clearedFields[FieldIds] + return ok +} + +// ResetIds resets all changes to the "ids" field. +func (m *Mutation) ResetIds() { + m.ids = nil + m.addids = nil + delete(m.clearedFields, FieldIds) + delete(m.exprs, FieldIds) +} + +// SetWhere sets the "where" field. +func (m *Mutation) SetWhere(i int) { + m.where = &i + m.addwhere = nil + delete(m.clearedFields, FieldWhere) + delete(m.exprs, FieldWhere) +} + +// GetWhere returns the value of the "where" field in the mutation. +func (m *Mutation) GetWhere() (r int, exists bool) { + v := m.where + if v == nil { + return + } + return *v, true +} + +// AddWhere adds i to the "where" field. +func (m *Mutation) AddWhere(i int) { + if m.addwhere != nil { + *m.addwhere += i + } else { + m.addwhere = &i + } +} + +// AddedWhere returns the value that was added to the "where" field in this mutation. +func (m *Mutation) AddedWhere() (r int, exists bool) { + v := m.addwhere + if v == nil { + return + } + return *v, true +} + +// ClearWhere clears the value of the "where" field. +func (m *Mutation) ClearWhere() { + m.where = nil + m.addwhere = nil + delete(m.exprs, FieldWhere) + m.clearedFields[FieldWhere] = struct{}{} +} + +// WhereCleared returns if the "where" field was cleared in this mutation. +func (m *Mutation) WhereCleared() bool { + _, ok := m.clearedFields[FieldWhere] + return ok +} + +// ResetWhere resets all changes to the "where" field. +func (m *Mutation) ResetWhere() { + m.where = nil + m.addwhere = nil + delete(m.clearedFields, FieldWhere) + delete(m.exprs, FieldWhere) +} + +// SetOpField sets the "op" field. +func (m *Mutation) SetOpField(i int) { + m._op = &i + m.add_op = nil + delete(m.clearedFields, FieldOp) + delete(m.exprs, FieldOp) +} + +// GetOp returns the value of the "op" field in the mutation. +func (m *Mutation) GetOp() (r int, exists bool) { + v := m._op + if v == nil { + return + } + return *v, true +} + +// AddOp adds i to the "op" field. +func (m *Mutation) AddOp(i int) { + if m.add_op != nil { + *m.add_op += i + } else { + m.add_op = &i + } +} + +// AddedOp returns the value that was added to the "op" field in this mutation. +func (m *Mutation) AddedOp() (r int, exists bool) { + v := m.add_op + if v == nil { + return + } + return *v, true +} + +// ClearOp clears the value of the "op" field. +func (m *Mutation) ClearOp() { + m._op = nil + m.add_op = nil + delete(m.exprs, FieldOp) + m.clearedFields[FieldOp] = struct{}{} +} + +// OpCleared returns if the "op" field was cleared in this mutation. +func (m *Mutation) OpCleared() bool { + _, ok := m.clearedFields[FieldOp] + return ok +} + +// ResetOp resets all changes to the "op" field. +func (m *Mutation) ResetOp() { + m._op = nil + m.add_op = nil + delete(m.clearedFields, FieldOp) + delete(m.exprs, FieldOp) +} + +// SetType sets the "type" field. +func (m *Mutation) SetType(i int) { + m._type = &i + m.add_type = nil + delete(m.clearedFields, FieldType) + delete(m.exprs, FieldType) +} + +// GetType returns the value of the "type" field in the mutation. +func (m *Mutation) GetType() (r int, exists bool) { + v := m._type + if v == nil { + return + } + return *v, true +} + +// AddType adds i to the "type" field. +func (m *Mutation) AddType(i int) { + if m.add_type != nil { + *m.add_type += i + } else { + m.add_type = &i + } +} + +// AddedType returns the value that was added to the "type" field in this mutation. +func (m *Mutation) AddedType() (r int, exists bool) { + v := m.add_type + if v == nil { + return + } + return *v, true +} + +// ClearType clears the value of the "type" field. +func (m *Mutation) ClearType() { + m._type = nil + m.add_type = nil + delete(m.exprs, FieldType) + m.clearedFields[FieldType] = struct{}{} +} + +// TypeCleared returns if the "type" field was cleared in this mutation. +func (m *Mutation) TypeCleared() bool { + _, ok := m.clearedFields[FieldType] + return ok +} + +// ResetType resets all changes to the "type" field. +func (m *Mutation) ResetType() { + m._type = nil + m.add_type = nil + delete(m.clearedFields, FieldType) + delete(m.exprs, FieldType) +} + +// Where appends a list predicates to the Mutation builder. +func (m *Mutation) Where(ps ...predicate.Item) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the Mutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *Mutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Item, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *Mutation) Op() ent.Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *Mutation) SetOp(op ent.Op) { + m.op = op +} + +// Type returns the node type of this mutation (Item). +func (m *Mutation) 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 *Mutation) Fields() []string { + fields := make([]string, 0, 7) + if m.field != nil || m.exprs[FieldField] != nil { + fields = append(fields, FieldField) + } + if m.fields != nil || m.exprs[FieldFields] != nil { + fields = append(fields, FieldFields) + } + if m.edge != nil || m.exprs[FieldEdge] != nil { + fields = append(fields, FieldEdge) + } + if m.ids != nil || m.exprs[FieldIds] != nil { + fields = append(fields, FieldIds) + } + if m.where != nil || m.exprs[FieldWhere] != nil { + fields = append(fields, FieldWhere) + } + if m._op != nil || m.exprs[FieldOp] != nil { + fields = append(fields, FieldOp) + } + if m._type != nil || m.exprs[FieldType] != nil { + fields = append(fields, FieldType) + } + 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. +// +// A field assigned an expression with SetFieldExpr returns that expression, a +// sql.Querier, since the value it stands for is the database's to compute. +func (m *Mutation) Field(name string) (ent.Value, bool) { + if e, ok := m.exprs[name]; ok { + return e, true + } + switch name { + case FieldField: + return m.GetField() + case FieldFields: + return m.GetFields() + case FieldEdge: + return m.Edge() + case FieldIds: + return m.GetIds() + case FieldWhere: + return m.GetWhere() + case FieldOp: + return m.GetOp() + case FieldType: + return m.GetType() + } + 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 *Mutation) OldField(ctx context.Context, name string) (ent.Value, error) { + return nil, fmt.Errorf("unknown Item 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. +// +// A sql.Querier that is not of the field's type is handed to SetFieldExpr, so +// that what Field returns for a field can be set back on it. +func (m *Mutation) SetField(name string, value ent.Value) error { + switch name { + case FieldField: + v, ok := value.(int) + if !ok { + if e, ok := value.(sql.Querier); ok { + return m.SetFieldExpr(name, e) + } + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFieldField(v) + return nil + case FieldFields: + v, ok := value.(int) + if !ok { + if e, ok := value.(sql.Querier); ok { + return m.SetFieldExpr(name, e) + } + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFields(v) + return nil + case FieldEdge: + v, ok := value.(int) + if !ok { + if e, ok := value.(sql.Querier); ok { + return m.SetFieldExpr(name, e) + } + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEdge(v) + return nil + case FieldIds: + v, ok := value.(int) + if !ok { + if e, ok := value.(sql.Querier); ok { + return m.SetFieldExpr(name, e) + } + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIds(v) + return nil + case FieldWhere: + v, ok := value.(int) + if !ok { + if e, ok := value.(sql.Querier); ok { + return m.SetFieldExpr(name, e) + } + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetWhere(v) + return nil + case FieldOp: + v, ok := value.(int) + if !ok { + if e, ok := value.(sql.Querier); ok { + return m.SetFieldExpr(name, e) + } + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOpField(v) + return nil + case FieldType: + v, ok := value.(int) + if !ok { + if e, ok := value.(sql.Querier); ok { + return m.SetFieldExpr(name, e) + } + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetType(v) + return nil + } + return fmt.Errorf("unknown Item field %s", name) +} + +// SetFieldExpr assigns the field with the given name a SQL expression, which +// the database evaluates as the UPDATE writes the row. It replaces any value +// the field was set, added, appended or cleared with, as setting it again +// would, and so the column is assigned once. +// +// The field is listed by Fields and Field returns the expression, so a hook +// sees it as it sees any other. What it does not have is a value: a field +// with a validator is refused, since there is nothing for the validator to +// check, and so is one that only a create could write. A create refuses a +// mutation holding an expression at all. +func (m *Mutation) SetFieldExpr(name string, expr sql.Querier) error { + if expr == nil { + return fmt.Errorf("no expression for field %s", name) + } + if m.op.Is(ent.OpCreate) { + return fmt.Errorf("field %s cannot be assigned an expression: a create writes values, and an expression is written only by an update", name) + } + switch name { + case FieldField: + m.ResetFieldField() + case FieldFields: + m.ResetFields() + case FieldEdge: + m.ResetEdgeField() + case FieldIds: + m.ResetIds() + case FieldWhere: + m.ResetWhere() + case FieldOp: + m.ResetOp() + case FieldType: + m.ResetType() + default: + return fmt.Errorf("unknown Item field %s", name) + } + if m.exprs == nil { + m.exprs = make(map[string]sql.Querier) + } + m.exprs[name] = expr + return nil +} + +// FieldExpr returns the expression the field with the given name was assigned +// by SetFieldExpr. The second return value reports whether it was. +func (m *Mutation) FieldExpr(name string) (sql.Querier, bool) { + e, ok := m.exprs[name] + return e, ok +} + +// ExprFields returns the fields that were assigned an expression by +// SetFieldExpr. +func (m *Mutation) ExprFields() []string { + var fields []string + if _, ok := m.exprs[FieldField]; ok { + fields = append(fields, FieldField) + } + if _, ok := m.exprs[FieldFields]; ok { + fields = append(fields, FieldFields) + } + if _, ok := m.exprs[FieldEdge]; ok { + fields = append(fields, FieldEdge) + } + if _, ok := m.exprs[FieldIds]; ok { + fields = append(fields, FieldIds) + } + if _, ok := m.exprs[FieldWhere]; ok { + fields = append(fields, FieldWhere) + } + if _, ok := m.exprs[FieldOp]; ok { + fields = append(fields, FieldOp) + } + if _, ok := m.exprs[FieldType]; ok { + fields = append(fields, FieldType) + } + return fields +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *Mutation) AddedFields() []string { + var fields []string + if m.addfield != nil { + fields = append(fields, FieldField) + } + if m.addfields != nil { + fields = append(fields, FieldFields) + } + if m.addedge != nil { + fields = append(fields, FieldEdge) + } + if m.addids != nil { + fields = append(fields, FieldIds) + } + if m.addwhere != nil { + fields = append(fields, FieldWhere) + } + if m.add_op != nil { + fields = append(fields, FieldOp) + } + if m.add_type != nil { + fields = append(fields, FieldType) + } + 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 *Mutation) AddedField(name string) (ent.Value, bool) { + switch name { + case FieldField: + return m.AddedFieldField() + case FieldFields: + return m.AddedFieldsField() + case FieldEdge: + return m.AddedEdge() + case FieldIds: + return m.AddedIdsField() + case FieldWhere: + return m.AddedWhere() + case FieldOp: + return m.AddedOp() + case FieldType: + return m.AddedType() + } + 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 *Mutation) AddField(name string, value ent.Value) error { + switch name { + case FieldField: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddFieldField(v) + return nil + case FieldFields: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddFields(v) + return nil + case FieldEdge: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddEdge(v) + return nil + case FieldIds: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddIds(v) + return nil + case FieldWhere: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddWhere(v) + return nil + case FieldOp: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddOp(v) + return nil + case FieldType: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddType(v) + return nil + } + return fmt.Errorf("unknown Item numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *Mutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(FieldField) { + fields = append(fields, FieldField) + } + if m.FieldCleared(FieldFields) { + fields = append(fields, FieldFields) + } + if m.FieldCleared(FieldEdge) { + fields = append(fields, FieldEdge) + } + if m.FieldCleared(FieldIds) { + fields = append(fields, FieldIds) + } + if m.FieldCleared(FieldWhere) { + fields = append(fields, FieldWhere) + } + if m.FieldCleared(FieldOp) { + fields = append(fields, FieldOp) + } + if m.FieldCleared(FieldType) { + fields = append(fields, FieldType) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *Mutation) 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 *Mutation) ClearField(name string) error { + switch name { + case FieldField: + m.ClearFieldField() + return nil + case FieldFields: + m.ClearFields() + return nil + case FieldEdge: + m.ClearEdgeField() + return nil + case FieldIds: + m.ClearIds() + return nil + case FieldWhere: + m.ClearWhere() + return nil + case FieldOp: + m.ClearOp() + return nil + case FieldType: + m.ClearType() + return nil + } + return fmt.Errorf("unknown Item 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 *Mutation) ResetField(name string) error { + switch name { + case FieldField: + m.ResetFieldField() + return nil + case FieldFields: + m.ResetFields() + return nil + case FieldEdge: + m.ResetEdgeField() + return nil + case FieldIds: + m.ResetIds() + return nil + case FieldWhere: + m.ResetWhere() + return nil + case FieldOp: + m.ResetOp() + return nil + case FieldType: + m.ResetType() + return nil + } + return fmt.Errorf("unknown Item field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *Mutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIds returns all Ids (to other nodes) that were added for the given edge +// name in this mutation. +func (m *Mutation) AddedIds(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *Mutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIds returns all Ids (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *Mutation) RemovedIds(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *Mutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *Mutation) EdgeCleared(name string) bool { + 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 *Mutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Item 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 *Mutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Item edge %s", name) +} diff --git a/entc/integration/fieldnames/ent/item/where.go b/entc/integration/fieldnames/ent/item/where.go new file mode 100644 index 0000000000..a99120b9c7 --- /dev/null +++ b/entc/integration/fieldnames/ent/item/where.go @@ -0,0 +1,457 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package item + +import ( + "github.com/protobuf-orm/ent/dialect/sql" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/predicate" +) + +// Id filters vertices based on their Id field. +func Id(id int) predicate.Item { + return predicate.Item(sql.FieldEQ(FieldId, id)) +} + +// IdEQ applies the EQ predicate on the Id field. +func IdEQ(id int) predicate.Item { + return predicate.Item(sql.FieldEQ(FieldId, id)) +} + +// IdNEQ applies the NEQ predicate on the Id field. +func IdNEQ(id int) predicate.Item { + return predicate.Item(sql.FieldNEQ(FieldId, id)) +} + +// IdIn applies the In predicate on the Id field. +func IdIn(ids ...int) predicate.Item { + return predicate.Item(sql.FieldIn(FieldId, ids...)) +} + +// IdNotIn applies the NotIn predicate on the Id field. +func IdNotIn(ids ...int) predicate.Item { + return predicate.Item(sql.FieldNotIn(FieldId, ids...)) +} + +// IdGT applies the GT predicate on the Id field. +func IdGT(id int) predicate.Item { + return predicate.Item(sql.FieldGT(FieldId, id)) +} + +// IdGTE applies the GTE predicate on the Id field. +func IdGTE(id int) predicate.Item { + return predicate.Item(sql.FieldGTE(FieldId, id)) +} + +// IdLT applies the LT predicate on the Id field. +func IdLT(id int) predicate.Item { + return predicate.Item(sql.FieldLT(FieldId, id)) +} + +// IdLTE applies the LTE predicate on the Id field. +func IdLTE(id int) predicate.Item { + return predicate.Item(sql.FieldLTE(FieldId, id)) +} + +// Field applies equality check predicate on the "field" field. It's identical to FieldEQ. +func Field(v int) predicate.Item { + return predicate.Item(sql.FieldEQ(FieldField, v)) +} + +// Fields applies equality check predicate on the "fields" field. It's identical to FieldsEQ. +func Fields(v int) predicate.Item { + return predicate.Item(sql.FieldEQ(FieldFields, v)) +} + +// Edge applies equality check predicate on the "edge" field. It's identical to EdgeEQ. +func Edge(v int) predicate.Item { + return predicate.Item(sql.FieldEQ(FieldEdge, v)) +} + +// Ids applies equality check predicate on the "ids" field. It's identical to IdsEQ. +func Ids(v int) predicate.Item { + return predicate.Item(sql.FieldEQ(FieldIds, v)) +} + +// Where applies equality check predicate on the "where" field. It's identical to WhereEQ. +func Where(v int) predicate.Item { + return predicate.Item(sql.FieldEQ(FieldWhere, v)) +} + +// Op applies equality check predicate on the "op" field. It's identical to OpEQ. +func Op(v int) predicate.Item { + return predicate.Item(sql.FieldEQ(FieldOp, v)) +} + +// Type applies equality check predicate on the "type" field. It's identical to TypeEQ. +func Type(v int) predicate.Item { + return predicate.Item(sql.FieldEQ(FieldType, v)) +} + +// FieldEQ applies the EQ predicate on the "field" field. +func FieldEQ(v int) predicate.Item { + return predicate.Item(sql.FieldEQ(FieldField, v)) +} + +// FieldNEQ applies the NEQ predicate on the "field" field. +func FieldNEQ(v int) predicate.Item { + return predicate.Item(sql.FieldNEQ(FieldField, v)) +} + +// FieldIn applies the In predicate on the "field" field. +func FieldIn(vs ...int) predicate.Item { + return predicate.Item(sql.FieldIn(FieldField, vs...)) +} + +// FieldNotIn applies the NotIn predicate on the "field" field. +func FieldNotIn(vs ...int) predicate.Item { + return predicate.Item(sql.FieldNotIn(FieldField, vs...)) +} + +// FieldGT applies the GT predicate on the "field" field. +func FieldGT(v int) predicate.Item { + return predicate.Item(sql.FieldGT(FieldField, v)) +} + +// FieldGTE applies the GTE predicate on the "field" field. +func FieldGTE(v int) predicate.Item { + return predicate.Item(sql.FieldGTE(FieldField, v)) +} + +// FieldLT applies the LT predicate on the "field" field. +func FieldLT(v int) predicate.Item { + return predicate.Item(sql.FieldLT(FieldField, v)) +} + +// FieldLTE applies the LTE predicate on the "field" field. +func FieldLTE(v int) predicate.Item { + return predicate.Item(sql.FieldLTE(FieldField, v)) +} + +// FieldIsNil applies the IsNil predicate on the "field" field. +func FieldIsNil() predicate.Item { + return predicate.Item(sql.FieldIsNull(FieldField)) +} + +// FieldNotNil applies the NotNil predicate on the "field" field. +func FieldNotNil() predicate.Item { + return predicate.Item(sql.FieldNotNull(FieldField)) +} + +// FieldsEQ applies the EQ predicate on the "fields" field. +func FieldsEQ(v int) predicate.Item { + return predicate.Item(sql.FieldEQ(FieldFields, v)) +} + +// FieldsNEQ applies the NEQ predicate on the "fields" field. +func FieldsNEQ(v int) predicate.Item { + return predicate.Item(sql.FieldNEQ(FieldFields, v)) +} + +// FieldsIn applies the In predicate on the "fields" field. +func FieldsIn(vs ...int) predicate.Item { + return predicate.Item(sql.FieldIn(FieldFields, vs...)) +} + +// FieldsNotIn applies the NotIn predicate on the "fields" field. +func FieldsNotIn(vs ...int) predicate.Item { + return predicate.Item(sql.FieldNotIn(FieldFields, vs...)) +} + +// FieldsGT applies the GT predicate on the "fields" field. +func FieldsGT(v int) predicate.Item { + return predicate.Item(sql.FieldGT(FieldFields, v)) +} + +// FieldsGTE applies the GTE predicate on the "fields" field. +func FieldsGTE(v int) predicate.Item { + return predicate.Item(sql.FieldGTE(FieldFields, v)) +} + +// FieldsLT applies the LT predicate on the "fields" field. +func FieldsLT(v int) predicate.Item { + return predicate.Item(sql.FieldLT(FieldFields, v)) +} + +// FieldsLTE applies the LTE predicate on the "fields" field. +func FieldsLTE(v int) predicate.Item { + return predicate.Item(sql.FieldLTE(FieldFields, v)) +} + +// FieldsIsNil applies the IsNil predicate on the "fields" field. +func FieldsIsNil() predicate.Item { + return predicate.Item(sql.FieldIsNull(FieldFields)) +} + +// FieldsNotNil applies the NotNil predicate on the "fields" field. +func FieldsNotNil() predicate.Item { + return predicate.Item(sql.FieldNotNull(FieldFields)) +} + +// EdgeEQ applies the EQ predicate on the "edge" field. +func EdgeEQ(v int) predicate.Item { + return predicate.Item(sql.FieldEQ(FieldEdge, v)) +} + +// EdgeNEQ applies the NEQ predicate on the "edge" field. +func EdgeNEQ(v int) predicate.Item { + return predicate.Item(sql.FieldNEQ(FieldEdge, v)) +} + +// EdgeIn applies the In predicate on the "edge" field. +func EdgeIn(vs ...int) predicate.Item { + return predicate.Item(sql.FieldIn(FieldEdge, vs...)) +} + +// EdgeNotIn applies the NotIn predicate on the "edge" field. +func EdgeNotIn(vs ...int) predicate.Item { + return predicate.Item(sql.FieldNotIn(FieldEdge, vs...)) +} + +// EdgeGT applies the GT predicate on the "edge" field. +func EdgeGT(v int) predicate.Item { + return predicate.Item(sql.FieldGT(FieldEdge, v)) +} + +// EdgeGTE applies the GTE predicate on the "edge" field. +func EdgeGTE(v int) predicate.Item { + return predicate.Item(sql.FieldGTE(FieldEdge, v)) +} + +// EdgeLT applies the LT predicate on the "edge" field. +func EdgeLT(v int) predicate.Item { + return predicate.Item(sql.FieldLT(FieldEdge, v)) +} + +// EdgeLTE applies the LTE predicate on the "edge" field. +func EdgeLTE(v int) predicate.Item { + return predicate.Item(sql.FieldLTE(FieldEdge, v)) +} + +// EdgeIsNil applies the IsNil predicate on the "edge" field. +func EdgeIsNil() predicate.Item { + return predicate.Item(sql.FieldIsNull(FieldEdge)) +} + +// EdgeNotNil applies the NotNil predicate on the "edge" field. +func EdgeNotNil() predicate.Item { + return predicate.Item(sql.FieldNotNull(FieldEdge)) +} + +// IdsEQ applies the EQ predicate on the "ids" field. +func IdsEQ(v int) predicate.Item { + return predicate.Item(sql.FieldEQ(FieldIds, v)) +} + +// IdsNEQ applies the NEQ predicate on the "ids" field. +func IdsNEQ(v int) predicate.Item { + return predicate.Item(sql.FieldNEQ(FieldIds, v)) +} + +// IdsIn applies the In predicate on the "ids" field. +func IdsIn(vs ...int) predicate.Item { + return predicate.Item(sql.FieldIn(FieldIds, vs...)) +} + +// IdsNotIn applies the NotIn predicate on the "ids" field. +func IdsNotIn(vs ...int) predicate.Item { + return predicate.Item(sql.FieldNotIn(FieldIds, vs...)) +} + +// IdsGT applies the GT predicate on the "ids" field. +func IdsGT(v int) predicate.Item { + return predicate.Item(sql.FieldGT(FieldIds, v)) +} + +// IdsGTE applies the GTE predicate on the "ids" field. +func IdsGTE(v int) predicate.Item { + return predicate.Item(sql.FieldGTE(FieldIds, v)) +} + +// IdsLT applies the LT predicate on the "ids" field. +func IdsLT(v int) predicate.Item { + return predicate.Item(sql.FieldLT(FieldIds, v)) +} + +// IdsLTE applies the LTE predicate on the "ids" field. +func IdsLTE(v int) predicate.Item { + return predicate.Item(sql.FieldLTE(FieldIds, v)) +} + +// IdsIsNil applies the IsNil predicate on the "ids" field. +func IdsIsNil() predicate.Item { + return predicate.Item(sql.FieldIsNull(FieldIds)) +} + +// IdsNotNil applies the NotNil predicate on the "ids" field. +func IdsNotNil() predicate.Item { + return predicate.Item(sql.FieldNotNull(FieldIds)) +} + +// WhereEQ applies the EQ predicate on the "where" field. +func WhereEQ(v int) predicate.Item { + return predicate.Item(sql.FieldEQ(FieldWhere, v)) +} + +// WhereNEQ applies the NEQ predicate on the "where" field. +func WhereNEQ(v int) predicate.Item { + return predicate.Item(sql.FieldNEQ(FieldWhere, v)) +} + +// WhereIn applies the In predicate on the "where" field. +func WhereIn(vs ...int) predicate.Item { + return predicate.Item(sql.FieldIn(FieldWhere, vs...)) +} + +// WhereNotIn applies the NotIn predicate on the "where" field. +func WhereNotIn(vs ...int) predicate.Item { + return predicate.Item(sql.FieldNotIn(FieldWhere, vs...)) +} + +// WhereGT applies the GT predicate on the "where" field. +func WhereGT(v int) predicate.Item { + return predicate.Item(sql.FieldGT(FieldWhere, v)) +} + +// WhereGTE applies the GTE predicate on the "where" field. +func WhereGTE(v int) predicate.Item { + return predicate.Item(sql.FieldGTE(FieldWhere, v)) +} + +// WhereLT applies the LT predicate on the "where" field. +func WhereLT(v int) predicate.Item { + return predicate.Item(sql.FieldLT(FieldWhere, v)) +} + +// WhereLTE applies the LTE predicate on the "where" field. +func WhereLTE(v int) predicate.Item { + return predicate.Item(sql.FieldLTE(FieldWhere, v)) +} + +// WhereIsNil applies the IsNil predicate on the "where" field. +func WhereIsNil() predicate.Item { + return predicate.Item(sql.FieldIsNull(FieldWhere)) +} + +// WhereNotNil applies the NotNil predicate on the "where" field. +func WhereNotNil() predicate.Item { + return predicate.Item(sql.FieldNotNull(FieldWhere)) +} + +// OpEQ applies the EQ predicate on the "op" field. +func OpEQ(v int) predicate.Item { + return predicate.Item(sql.FieldEQ(FieldOp, v)) +} + +// OpNEQ applies the NEQ predicate on the "op" field. +func OpNEQ(v int) predicate.Item { + return predicate.Item(sql.FieldNEQ(FieldOp, v)) +} + +// OpIn applies the In predicate on the "op" field. +func OpIn(vs ...int) predicate.Item { + return predicate.Item(sql.FieldIn(FieldOp, vs...)) +} + +// OpNotIn applies the NotIn predicate on the "op" field. +func OpNotIn(vs ...int) predicate.Item { + return predicate.Item(sql.FieldNotIn(FieldOp, vs...)) +} + +// OpGT applies the GT predicate on the "op" field. +func OpGT(v int) predicate.Item { + return predicate.Item(sql.FieldGT(FieldOp, v)) +} + +// OpGTE applies the GTE predicate on the "op" field. +func OpGTE(v int) predicate.Item { + return predicate.Item(sql.FieldGTE(FieldOp, v)) +} + +// OpLT applies the LT predicate on the "op" field. +func OpLT(v int) predicate.Item { + return predicate.Item(sql.FieldLT(FieldOp, v)) +} + +// OpLTE applies the LTE predicate on the "op" field. +func OpLTE(v int) predicate.Item { + return predicate.Item(sql.FieldLTE(FieldOp, v)) +} + +// OpIsNil applies the IsNil predicate on the "op" field. +func OpIsNil() predicate.Item { + return predicate.Item(sql.FieldIsNull(FieldOp)) +} + +// OpNotNil applies the NotNil predicate on the "op" field. +func OpNotNil() predicate.Item { + return predicate.Item(sql.FieldNotNull(FieldOp)) +} + +// TypeEQ applies the EQ predicate on the "type" field. +func TypeEQ(v int) predicate.Item { + return predicate.Item(sql.FieldEQ(FieldType, v)) +} + +// TypeNEQ applies the NEQ predicate on the "type" field. +func TypeNEQ(v int) predicate.Item { + return predicate.Item(sql.FieldNEQ(FieldType, v)) +} + +// TypeIn applies the In predicate on the "type" field. +func TypeIn(vs ...int) predicate.Item { + return predicate.Item(sql.FieldIn(FieldType, vs...)) +} + +// TypeNotIn applies the NotIn predicate on the "type" field. +func TypeNotIn(vs ...int) predicate.Item { + return predicate.Item(sql.FieldNotIn(FieldType, vs...)) +} + +// TypeGT applies the GT predicate on the "type" field. +func TypeGT(v int) predicate.Item { + return predicate.Item(sql.FieldGT(FieldType, v)) +} + +// TypeGTE applies the GTE predicate on the "type" field. +func TypeGTE(v int) predicate.Item { + return predicate.Item(sql.FieldGTE(FieldType, v)) +} + +// TypeLT applies the LT predicate on the "type" field. +func TypeLT(v int) predicate.Item { + return predicate.Item(sql.FieldLT(FieldType, v)) +} + +// TypeLTE applies the LTE predicate on the "type" field. +func TypeLTE(v int) predicate.Item { + return predicate.Item(sql.FieldLTE(FieldType, v)) +} + +// TypeIsNil applies the IsNil predicate on the "type" field. +func TypeIsNil() predicate.Item { + return predicate.Item(sql.FieldIsNull(FieldType)) +} + +// TypeNotNil applies the NotNil predicate on the "type" field. +func TypeNotNil() predicate.Item { + return predicate.Item(sql.FieldNotNull(FieldType)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Item) predicate.Item { + return predicate.Item(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Item) predicate.Item { + return predicate.Item(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Item) predicate.Item { + return predicate.Item(sql.NotPredicates(p)) +} diff --git a/entc/integration/fieldnames/ent/item_create.go b/entc/integration/fieldnames/ent/item_create.go new file mode 100644 index 0000000000..f6a74499ff --- /dev/null +++ b/entc/integration/fieldnames/ent/item_create.go @@ -0,0 +1,1133 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "github.com/protobuf-orm/ent/dialect/sql" + "github.com/protobuf-orm/ent/dialect/sql/sqlgraph" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/item" + "github.com/protobuf-orm/ent/schema/field" +) + +// ItemCreate is the builder for creating a Item entity. +type ItemCreate struct { + config + mutation *ItemMutation + hooks []Hook + stored **Item + conflict []sql.ConflictOption +} + +// SetField sets the "field" field. +func (_c *ItemCreate) SetField(v int) *ItemCreate { + _c.mutation.SetFieldField(v) + return _c +} + +// SetNillableField sets the "field" field if the given value is not nil. +func (_c *ItemCreate) SetNillableField(v *int) *ItemCreate { + if v != nil { + _c.SetField(*v) + } + return _c +} + +// SetFields sets the "fields" field. +func (_c *ItemCreate) SetFields(v int) *ItemCreate { + _c.mutation.SetFields(v) + return _c +} + +// SetNillableFields sets the "fields" field if the given value is not nil. +func (_c *ItemCreate) SetNillableFields(v *int) *ItemCreate { + if v != nil { + _c.SetFields(*v) + } + return _c +} + +// SetEdge sets the "edge" field. +func (_c *ItemCreate) SetEdge(v int) *ItemCreate { + _c.mutation.SetEdge(v) + return _c +} + +// SetNillableEdge sets the "edge" field if the given value is not nil. +func (_c *ItemCreate) SetNillableEdge(v *int) *ItemCreate { + if v != nil { + _c.SetEdge(*v) + } + return _c +} + +// SetIds sets the "ids" field. +func (_c *ItemCreate) SetIds(v int) *ItemCreate { + _c.mutation.SetIds(v) + return _c +} + +// SetNillableIds sets the "ids" field if the given value is not nil. +func (_c *ItemCreate) SetNillableIds(v *int) *ItemCreate { + if v != nil { + _c.SetIds(*v) + } + return _c +} + +// SetWhere sets the "where" field. +func (_c *ItemCreate) SetWhere(v int) *ItemCreate { + _c.mutation.SetWhere(v) + return _c +} + +// SetNillableWhere sets the "where" field if the given value is not nil. +func (_c *ItemCreate) SetNillableWhere(v *int) *ItemCreate { + if v != nil { + _c.SetWhere(*v) + } + return _c +} + +// SetOp sets the "op" field. +func (_c *ItemCreate) SetOp(v int) *ItemCreate { + _c.mutation.SetOpField(v) + return _c +} + +// SetNillableOp sets the "op" field if the given value is not nil. +func (_c *ItemCreate) SetNillableOp(v *int) *ItemCreate { + if v != nil { + _c.SetOp(*v) + } + return _c +} + +// SetType sets the "type" field. +func (_c *ItemCreate) SetType(v int) *ItemCreate { + _c.mutation.SetType(v) + return _c +} + +// SetNillableType sets the "type" field if the given value is not nil. +func (_c *ItemCreate) SetNillableType(v *int) *ItemCreate { + if v != nil { + _c.SetType(*v) + } + return _c +} + +// Mutation returns the ItemMutation object of the builder. +func (_c *ItemCreate) Mutation() *ItemMutation { + return _c.mutation +} + +// Save creates the Item in the database. +func (_c *ItemCreate) Save(ctx context.Context) (*Item, error) { + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ItemCreate) SaveX(ctx context.Context) *Item { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ItemCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ItemCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ItemCreate) check() error { + if fs := _c.mutation.ExprFields(); len(fs) > 0 { + return &ValidationError{Name: fs[0], err: fmt.Errorf(`ent: field "Item.%s" was assigned an expression, which only an update writes`, fs[0])} + } + return nil +} + +func (_c *ItemCreate) sqlSave(ctx context.Context) (*Item, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + id := _spec.Id.Value.(int64) + _node.Id = int(id) + _c.mutation.id = &_node.Id + _c.mutation.done = true + return _node, nil +} + +func (_c *ItemCreate) createSpec() (*Item, *sqlgraph.CreateSpec) { + var ( + _node = &Item{config: _c.config} + _spec = sqlgraph.NewCreateSpec(item.Table, sqlgraph.NewFieldSpec(item.FieldId, field.TypeInt)) + ) + if _c.stored != nil { + _stored := &Item{config: _c.config} + _spec.Returning = item.Columns + _spec.ScanValues = _stored.scanValues + _spec.Assign = func(columns []string, values []any) error { + if err := _stored.assignValues(columns, values); err != nil { + return err + } + *_c.stored = _stored + return nil + } + } + _spec.OnConflict = _c.conflict + if value, ok := _c.mutation.GetField(); ok { + _spec.SetField(item.FieldField, field.TypeInt, value) + _node.Field = &value + } + if value, ok := _c.mutation.GetFields(); ok { + _spec.SetField(item.FieldFields, field.TypeInt, value) + _node.Fields = &value + } + if value, ok := _c.mutation.Edge(); ok { + _spec.SetField(item.FieldEdge, field.TypeInt, value) + _node.Edge = &value + } + if value, ok := _c.mutation.GetIds(); ok { + _spec.SetField(item.FieldIds, field.TypeInt, value) + _node.Ids = &value + } + if value, ok := _c.mutation.GetWhere(); ok { + _spec.SetField(item.FieldWhere, field.TypeInt, value) + _node.Where = &value + } + if value, ok := _c.mutation.GetOp(); ok { + _spec.SetField(item.FieldOp, field.TypeInt, value) + _node.Op = &value + } + if value, ok := _c.mutation.GetType(); ok { + _spec.SetField(item.FieldType, field.TypeInt, value) + _node.Type = &value + } + return _node, _spec +} + +// Stored has Save read the Item back, into `v`, as the database stored +// it: at the precision of its columns, with the defaults the database filled +// in and what a trigger before the write made of it. Save itself answers with +// the Item as this builder had it. +// +// The INSERT reads it, with RETURNING, where the dialect has it, so that the +// row and the reading of it are one statement. MySQL has none, and an INSERT +// with a conflict clause may have written nothing, so for those it is a query +// by the Id just after the INSERT. Either way it is read on the driver the +// INSERT ran on, so inside a transaction it is that transaction's row. Its +// edges are not loaded. +// +// In a CreateBulk, the Stored of each builder is honoured and the batch's one +// INSERT reads all of their rows back: each is matched to its builder by the +// Id the builder was given, or by its place when the database made the Ids up. +// A column some builders of a batch set and others do not is NULL for the +// others, as it is in any batch; the database's default is for a column no +// builder sets. +// +// `v` is written only by a Save that wrote the row: one that failed, or that a +// hook answered without writing, leaves it as it was. +func (_c *ItemCreate) Stored(v **Item) *ItemCreate { + _c.stored = v + return _c +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.Item.Create(). +// SetField(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.ItemUpsert) { +// SetField(v+v). +// }). +// Exec(ctx) +func (_c *ItemCreate) OnConflict(opts ...sql.ConflictOption) *ItemUpsertOne { + _c.conflict = opts + return &ItemUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Item.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ItemCreate) OnConflictColumns(columns ...string) *ItemUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ItemUpsertOne{ + create: _c, + } +} + +type ( + // ItemUpsertOne is the builder for "upsert"-ing + // one Item node. + ItemUpsertOne struct { + create *ItemCreate + } + + // ItemUpsert is the "OnConflict" setter. + ItemUpsert struct { + *sql.UpdateSet + } +) + +// SetField sets the "field" field. +func (u *ItemUpsert) SetField(v int) *ItemUpsert { + u.Set(item.FieldField, v) + return u +} + +// UpdateField sets the "field" field to the value that was provided on create. +func (u *ItemUpsert) UpdateField() *ItemUpsert { + u.SetExcluded(item.FieldField) + return u +} + +// AddField adds v to the "field" field. +func (u *ItemUpsert) AddField(v int) *ItemUpsert { + u.Add(item.FieldField, v) + return u +} + +// ClearField clears the value of the "field" field. +func (u *ItemUpsert) ClearField() *ItemUpsert { + u.SetNull(item.FieldField) + return u +} + +// SetFields sets the "fields" field. +func (u *ItemUpsert) SetFields(v int) *ItemUpsert { + u.Set(item.FieldFields, v) + return u +} + +// UpdateFields sets the "fields" field to the value that was provided on create. +func (u *ItemUpsert) UpdateFields() *ItemUpsert { + u.SetExcluded(item.FieldFields) + return u +} + +// AddFields adds v to the "fields" field. +func (u *ItemUpsert) AddFields(v int) *ItemUpsert { + u.Add(item.FieldFields, v) + return u +} + +// ClearFields clears the value of the "fields" field. +func (u *ItemUpsert) ClearFields() *ItemUpsert { + u.SetNull(item.FieldFields) + return u +} + +// SetEdge sets the "edge" field. +func (u *ItemUpsert) SetEdge(v int) *ItemUpsert { + u.Set(item.FieldEdge, v) + return u +} + +// UpdateEdge sets the "edge" field to the value that was provided on create. +func (u *ItemUpsert) UpdateEdge() *ItemUpsert { + u.SetExcluded(item.FieldEdge) + return u +} + +// AddEdge adds v to the "edge" field. +func (u *ItemUpsert) AddEdge(v int) *ItemUpsert { + u.Add(item.FieldEdge, v) + return u +} + +// ClearEdge clears the value of the "edge" field. +func (u *ItemUpsert) ClearEdge() *ItemUpsert { + u.SetNull(item.FieldEdge) + return u +} + +// SetIds sets the "ids" field. +func (u *ItemUpsert) SetIds(v int) *ItemUpsert { + u.Set(item.FieldIds, v) + return u +} + +// UpdateIds sets the "ids" field to the value that was provided on create. +func (u *ItemUpsert) UpdateIds() *ItemUpsert { + u.SetExcluded(item.FieldIds) + return u +} + +// AddIds adds v to the "ids" field. +func (u *ItemUpsert) AddIds(v int) *ItemUpsert { + u.Add(item.FieldIds, v) + return u +} + +// ClearIds clears the value of the "ids" field. +func (u *ItemUpsert) ClearIds() *ItemUpsert { + u.SetNull(item.FieldIds) + return u +} + +// SetWhere sets the "where" field. +func (u *ItemUpsert) SetWhere(v int) *ItemUpsert { + u.Set(item.FieldWhere, v) + return u +} + +// UpdateWhere sets the "where" field to the value that was provided on create. +func (u *ItemUpsert) UpdateWhere() *ItemUpsert { + u.SetExcluded(item.FieldWhere) + return u +} + +// AddWhere adds v to the "where" field. +func (u *ItemUpsert) AddWhere(v int) *ItemUpsert { + u.Add(item.FieldWhere, v) + return u +} + +// ClearWhere clears the value of the "where" field. +func (u *ItemUpsert) ClearWhere() *ItemUpsert { + u.SetNull(item.FieldWhere) + return u +} + +// SetOp sets the "op" field. +func (u *ItemUpsert) SetOp(v int) *ItemUpsert { + u.Set(item.FieldOp, v) + return u +} + +// UpdateOp sets the "op" field to the value that was provided on create. +func (u *ItemUpsert) UpdateOp() *ItemUpsert { + u.SetExcluded(item.FieldOp) + return u +} + +// AddOp adds v to the "op" field. +func (u *ItemUpsert) AddOp(v int) *ItemUpsert { + u.Add(item.FieldOp, v) + return u +} + +// ClearOp clears the value of the "op" field. +func (u *ItemUpsert) ClearOp() *ItemUpsert { + u.SetNull(item.FieldOp) + return u +} + +// SetType sets the "type" field. +func (u *ItemUpsert) SetType(v int) *ItemUpsert { + u.Set(item.FieldType, v) + return u +} + +// UpdateType sets the "type" field to the value that was provided on create. +func (u *ItemUpsert) UpdateType() *ItemUpsert { + u.SetExcluded(item.FieldType) + return u +} + +// AddType adds v to the "type" field. +func (u *ItemUpsert) AddType(v int) *ItemUpsert { + u.Add(item.FieldType, v) + return u +} + +// ClearType clears the value of the "type" field. +func (u *ItemUpsert) ClearType() *ItemUpsert { + u.SetNull(item.FieldType) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create. +// Using this option is equivalent to using: +// +// client.Item.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +func (u *ItemUpsertOne) UpdateNewValues() *ItemUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Item.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ItemUpsertOne) Ignore() *ItemUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSql. +func (u *ItemUpsertOne) DoNothing() *ItemUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ItemCreate.OnConflict +// documentation for more info. +func (u *ItemUpsertOne) Update(set func(*ItemUpsert)) *ItemUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ItemUpsert{UpdateSet: update}) + })) + return u +} + +// SetField sets the "field" field. +func (u *ItemUpsertOne) SetField(v int) *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.SetField(v) + }) +} + +// AddField adds v to the "field" field. +func (u *ItemUpsertOne) AddField(v int) *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.AddField(v) + }) +} + +// UpdateField sets the "field" field to the value that was provided on create. +func (u *ItemUpsertOne) UpdateField() *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.UpdateField() + }) +} + +// ClearField clears the value of the "field" field. +func (u *ItemUpsertOne) ClearField() *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.ClearField() + }) +} + +// SetFields sets the "fields" field. +func (u *ItemUpsertOne) SetFields(v int) *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.SetFields(v) + }) +} + +// AddFields adds v to the "fields" field. +func (u *ItemUpsertOne) AddFields(v int) *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.AddFields(v) + }) +} + +// UpdateFields sets the "fields" field to the value that was provided on create. +func (u *ItemUpsertOne) UpdateFields() *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.UpdateFields() + }) +} + +// ClearFields clears the value of the "fields" field. +func (u *ItemUpsertOne) ClearFields() *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.ClearFields() + }) +} + +// SetEdge sets the "edge" field. +func (u *ItemUpsertOne) SetEdge(v int) *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.SetEdge(v) + }) +} + +// AddEdge adds v to the "edge" field. +func (u *ItemUpsertOne) AddEdge(v int) *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.AddEdge(v) + }) +} + +// UpdateEdge sets the "edge" field to the value that was provided on create. +func (u *ItemUpsertOne) UpdateEdge() *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.UpdateEdge() + }) +} + +// ClearEdge clears the value of the "edge" field. +func (u *ItemUpsertOne) ClearEdge() *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.ClearEdge() + }) +} + +// SetIds sets the "ids" field. +func (u *ItemUpsertOne) SetIds(v int) *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.SetIds(v) + }) +} + +// AddIds adds v to the "ids" field. +func (u *ItemUpsertOne) AddIds(v int) *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.AddIds(v) + }) +} + +// UpdateIds sets the "ids" field to the value that was provided on create. +func (u *ItemUpsertOne) UpdateIds() *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.UpdateIds() + }) +} + +// ClearIds clears the value of the "ids" field. +func (u *ItemUpsertOne) ClearIds() *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.ClearIds() + }) +} + +// SetWhere sets the "where" field. +func (u *ItemUpsertOne) SetWhere(v int) *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.SetWhere(v) + }) +} + +// AddWhere adds v to the "where" field. +func (u *ItemUpsertOne) AddWhere(v int) *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.AddWhere(v) + }) +} + +// UpdateWhere sets the "where" field to the value that was provided on create. +func (u *ItemUpsertOne) UpdateWhere() *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.UpdateWhere() + }) +} + +// ClearWhere clears the value of the "where" field. +func (u *ItemUpsertOne) ClearWhere() *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.ClearWhere() + }) +} + +// SetOp sets the "op" field. +func (u *ItemUpsertOne) SetOp(v int) *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.SetOp(v) + }) +} + +// AddOp adds v to the "op" field. +func (u *ItemUpsertOne) AddOp(v int) *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.AddOp(v) + }) +} + +// UpdateOp sets the "op" field to the value that was provided on create. +func (u *ItemUpsertOne) UpdateOp() *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.UpdateOp() + }) +} + +// ClearOp clears the value of the "op" field. +func (u *ItemUpsertOne) ClearOp() *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.ClearOp() + }) +} + +// SetType sets the "type" field. +func (u *ItemUpsertOne) SetType(v int) *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.SetType(v) + }) +} + +// AddType adds v to the "type" field. +func (u *ItemUpsertOne) AddType(v int) *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.AddType(v) + }) +} + +// UpdateType sets the "type" field to the value that was provided on create. +func (u *ItemUpsertOne) UpdateType() *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.UpdateType() + }) +} + +// ClearType clears the value of the "type" field. +func (u *ItemUpsertOne) ClearType() *ItemUpsertOne { + return u.Update(func(s *ItemUpsert) { + s.ClearType() + }) +} + +// Exec executes the query. +func (u *ItemUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for ItemCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ItemUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated Id. +func (u *ItemUpsertOne) Id(ctx context.Context) (id int, err error) { + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.Id, nil +} + +// IdX is like Id, but panics if an error occurs. +func (u *ItemUpsertOne) IdX(ctx context.Context) int { + id, err := u.Id(ctx) + if err != nil { + panic(err) + } + return id +} + +// ItemCreateBulk is the builder for creating many Item entities in bulk. +type ItemCreateBulk struct { + config + err error + builders []*ItemCreate + conflict []sql.ConflictOption +} + +// Save creates the Item entities in the database. +func (_c *ItemCreateBulk) Save(ctx context.Context) ([]*Item, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Item, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*ItemMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].Id + if specs[i].Id.Value != nil { + id := specs[i].Id.Value.(int64) + nodes[i].Id = int(id) + } + mutation.done = true + 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, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *ItemCreateBulk) SaveX(ctx context.Context) []*Item { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ItemCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ItemCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.Item.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.ItemUpsert) { +// SetField(v+v). +// }). +// Exec(ctx) +func (_c *ItemCreateBulk) OnConflict(opts ...sql.ConflictOption) *ItemUpsertBulk { + _c.conflict = opts + return &ItemUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Item.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ItemCreateBulk) OnConflictColumns(columns ...string) *ItemUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ItemUpsertBulk{ + create: _c, + } +} + +// ItemUpsertBulk is the builder for "upsert"-ing +// a bulk of Item nodes. +type ItemUpsertBulk struct { + create *ItemCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.Item.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +func (u *ItemUpsertBulk) UpdateNewValues() *ItemUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Item.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ItemUpsertBulk) Ignore() *ItemUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSql. +func (u *ItemUpsertBulk) DoNothing() *ItemUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ItemCreateBulk.OnConflict +// documentation for more info. +func (u *ItemUpsertBulk) Update(set func(*ItemUpsert)) *ItemUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ItemUpsert{UpdateSet: update}) + })) + return u +} + +// SetField sets the "field" field. +func (u *ItemUpsertBulk) SetField(v int) *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.SetField(v) + }) +} + +// AddField adds v to the "field" field. +func (u *ItemUpsertBulk) AddField(v int) *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.AddField(v) + }) +} + +// UpdateField sets the "field" field to the value that was provided on create. +func (u *ItemUpsertBulk) UpdateField() *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.UpdateField() + }) +} + +// ClearField clears the value of the "field" field. +func (u *ItemUpsertBulk) ClearField() *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.ClearField() + }) +} + +// SetFields sets the "fields" field. +func (u *ItemUpsertBulk) SetFields(v int) *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.SetFields(v) + }) +} + +// AddFields adds v to the "fields" field. +func (u *ItemUpsertBulk) AddFields(v int) *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.AddFields(v) + }) +} + +// UpdateFields sets the "fields" field to the value that was provided on create. +func (u *ItemUpsertBulk) UpdateFields() *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.UpdateFields() + }) +} + +// ClearFields clears the value of the "fields" field. +func (u *ItemUpsertBulk) ClearFields() *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.ClearFields() + }) +} + +// SetEdge sets the "edge" field. +func (u *ItemUpsertBulk) SetEdge(v int) *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.SetEdge(v) + }) +} + +// AddEdge adds v to the "edge" field. +func (u *ItemUpsertBulk) AddEdge(v int) *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.AddEdge(v) + }) +} + +// UpdateEdge sets the "edge" field to the value that was provided on create. +func (u *ItemUpsertBulk) UpdateEdge() *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.UpdateEdge() + }) +} + +// ClearEdge clears the value of the "edge" field. +func (u *ItemUpsertBulk) ClearEdge() *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.ClearEdge() + }) +} + +// SetIds sets the "ids" field. +func (u *ItemUpsertBulk) SetIds(v int) *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.SetIds(v) + }) +} + +// AddIds adds v to the "ids" field. +func (u *ItemUpsertBulk) AddIds(v int) *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.AddIds(v) + }) +} + +// UpdateIds sets the "ids" field to the value that was provided on create. +func (u *ItemUpsertBulk) UpdateIds() *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.UpdateIds() + }) +} + +// ClearIds clears the value of the "ids" field. +func (u *ItemUpsertBulk) ClearIds() *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.ClearIds() + }) +} + +// SetWhere sets the "where" field. +func (u *ItemUpsertBulk) SetWhere(v int) *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.SetWhere(v) + }) +} + +// AddWhere adds v to the "where" field. +func (u *ItemUpsertBulk) AddWhere(v int) *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.AddWhere(v) + }) +} + +// UpdateWhere sets the "where" field to the value that was provided on create. +func (u *ItemUpsertBulk) UpdateWhere() *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.UpdateWhere() + }) +} + +// ClearWhere clears the value of the "where" field. +func (u *ItemUpsertBulk) ClearWhere() *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.ClearWhere() + }) +} + +// SetOp sets the "op" field. +func (u *ItemUpsertBulk) SetOp(v int) *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.SetOp(v) + }) +} + +// AddOp adds v to the "op" field. +func (u *ItemUpsertBulk) AddOp(v int) *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.AddOp(v) + }) +} + +// UpdateOp sets the "op" field to the value that was provided on create. +func (u *ItemUpsertBulk) UpdateOp() *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.UpdateOp() + }) +} + +// ClearOp clears the value of the "op" field. +func (u *ItemUpsertBulk) ClearOp() *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.ClearOp() + }) +} + +// SetType sets the "type" field. +func (u *ItemUpsertBulk) SetType(v int) *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.SetType(v) + }) +} + +// AddType adds v to the "type" field. +func (u *ItemUpsertBulk) AddType(v int) *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.AddType(v) + }) +} + +// UpdateType sets the "type" field to the value that was provided on create. +func (u *ItemUpsertBulk) UpdateType() *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.UpdateType() + }) +} + +// ClearType clears the value of the "type" field. +func (u *ItemUpsertBulk) ClearType() *ItemUpsertBulk { + return u.Update(func(s *ItemUpsert) { + s.ClearType() + }) +} + +// Exec executes the query. +func (u *ItemUpsertBulk) Exec(ctx context.Context) error { + if u.create.err != nil { + return u.create.err + } + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the ItemCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for ItemCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ItemUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/fieldnames/ent/item_delete.go b/entc/integration/fieldnames/ent/item_delete.go new file mode 100644 index 0000000000..69231227f4 --- /dev/null +++ b/entc/integration/fieldnames/ent/item_delete.go @@ -0,0 +1,92 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "github.com/protobuf-orm/ent/dialect/sql" + "github.com/protobuf-orm/ent/dialect/sql/sqlgraph" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/item" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/predicate" + "github.com/protobuf-orm/ent/schema/field" +) + +// ItemDelete is the builder for deleting a Item entity. +type ItemDelete struct { + config + hooks []Hook + mutation *ItemMutation +} + +// Where appends a list predicates to the ItemDelete builder. +func (_d *ItemDelete) Where(ps ...predicate.Item) *ItemDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ItemDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ItemDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ItemDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(item.Table, sqlgraph.NewFieldSpec(item.FieldId, field.TypeInt)) + if ps := _d.mutation.Predicates(); len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// ItemDeleteOne is the builder for deleting a single Item entity. +type ItemDeleteOne struct { + _d *ItemDelete +} + +// Where appends a list predicates to the ItemDelete builder. +func (_d *ItemDeleteOne) Where(ps ...predicate.Item) *ItemDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ItemDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{item.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ItemDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/fieldnames/ent/item_query.go b/entc/integration/fieldnames/ent/item_query.go new file mode 100644 index 0000000000..cfef140b8d --- /dev/null +++ b/entc/integration/fieldnames/ent/item_query.go @@ -0,0 +1,554 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "github.com/protobuf-orm/ent" + "github.com/protobuf-orm/ent/dialect/sql" + "github.com/protobuf-orm/ent/dialect/sql/sqlgraph" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/item" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/predicate" + "github.com/protobuf-orm/ent/schema/field" +) + +// ItemQuery is the builder for querying Item entities. +type ItemQuery struct { + config + ctx *QueryContext + order []item.OrderOption + inters []Interceptor + predicates []predicate.Item + modifiers []func(*sql.Selector) + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the ItemQuery builder. +func (_q *ItemQuery) Where(ps ...predicate.Item) *ItemQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ItemQuery) Limit(limit int) *ItemQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ItemQuery) Offset(offset int) *ItemQuery { + _q.ctx.Offset = &offset + return _q +} + +// 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 (_q *ItemQuery) Unique(unique bool) *ItemQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ItemQuery) Order(o ...item.OrderOption) *ItemQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first Item entity from the query. +// Returns a *NotFoundError when no Item was found. +func (_q *ItemQuery) First(ctx context.Context) (*Item, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{item.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ItemQuery) FirstX(ctx context.Context) *Item { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstId returns the first Item Id from the query. +// Returns a *NotFoundError when no Item Id was found. +func (_q *ItemQuery) FirstId(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(1).Ids(setContextOp(ctx, _q.ctx, ent.OpQueryFirstId)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{item.Label} + return + } + return ids[0], nil +} + +// FirstIdX is like FirstId, but panics if an error occurs. +func (_q *ItemQuery) FirstIdX(ctx context.Context) int { + id, err := _q.FirstId(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Item entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Item entity is found. +// Returns a *NotFoundError when no Item entities are found. +func (_q *ItemQuery) Only(ctx context.Context) (*Item, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{item.Label} + default: + return nil, &NotSingularError{item.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ItemQuery) OnlyX(ctx context.Context) *Item { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyId is like Only, but returns the only Item Id in the query. +// Returns a *NotSingularError when more than one Item Id is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ItemQuery) OnlyId(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(2).Ids(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyId)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{item.Label} + default: + err = &NotSingularError{item.Label} + } + return +} + +// OnlyIdX is like OnlyId, but panics if an error occurs. +func (_q *ItemQuery) OnlyIdX(ctx context.Context) int { + id, err := _q.OnlyId(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Item entities. +func (_q *ItemQuery) All(ctx context.Context) ([]*Item, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Item, *ItemQuery]() + return withInterceptors[[]*Item](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ItemQuery) AllX(ctx context.Context) []*Item { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// Ids executes the query and returns a list of Item Ids. +func (_q *ItemQuery) Ids(ctx context.Context) (ids []int, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIds) + if err = _q.Select(item.FieldId).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IdsX is like Ids, but panics if an error occurs. +func (_q *ItemQuery) IdsX(ctx context.Context) []int { + ids, err := _q.Ids(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *ItemQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*ItemQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ItemQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *ItemQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstId(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *ItemQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ItemQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *ItemQuery) Clone() *ItemQuery { + if _q == nil { + return nil + } + return &ItemQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]item.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Item{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + modifiers: append([]func(*sql.Selector){}, _q.modifiers...), + } +} + +// 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 { +// Field int `json:"field,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Item.Query(). +// GroupBy(item.FieldField). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *ItemQuery) GroupBy(field string, fields ...string) *ItemGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ItemGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = item.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// 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 { +// Field int `json:"field,omitempty"` +// } +// +// client.Item.Query(). +// Select(item.FieldField). +// Scan(ctx, &v) +func (_q *ItemQuery) Select(fields ...string) *ItemSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ItemSelect{ItemQuery: _q} + sbuild.label = item.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ItemSelect configured with the given aggregations. +func (_q *ItemQuery) Aggregate(fns ...AggregateFunc) *ItemSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ItemQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !item.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *ItemQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Item, error) { + var ( + nodes = []*Item{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Item).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Item{config: _q.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (_q *ItemQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *ItemQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(item.Table, item.Columns, sqlgraph.NewFieldSpec(item.FieldId, field.TypeInt)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, item.FieldId) + for i := range fields { + if fields[i] != item.FieldId { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *ItemQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(item.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = item.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.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 := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_q *ItemQuery) Modify(modifiers ...func(s *sql.Selector)) *ItemSelect { + _q.modifiers = append(_q.modifiers, modifiers...) + return _q.Select() +} + +// ItemGroupBy is the group-by builder for Item entities. +type ItemGroupBy struct { + selector + build *ItemQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ItemGroupBy) Aggregate(fns ...AggregateFunc) *ItemGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ItemGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ItemQuery, *ItemGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ItemGroupBy) sqlScan(ctx context.Context, root *ItemQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// ItemSelect is the builder for selecting fields of Item entities. +type ItemSelect struct { + *ItemQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ItemSelect) Aggregate(fns ...AggregateFunc) *ItemSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ItemSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ItemQuery, *ItemSelect](ctx, _s.ItemQuery, _s, _s.inters, v) +} + +func (_s *ItemSelect) sqlScan(ctx context.Context, root *ItemQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_s *ItemSelect) Modify(modifiers ...func(s *sql.Selector)) *ItemSelect { + _s.modifiers = append(_s.modifiers, modifiers...) + return _s +} diff --git a/entc/integration/fieldnames/ent/item_update.go b/entc/integration/fieldnames/ent/item_update.go new file mode 100644 index 0000000000..c8c4742b29 --- /dev/null +++ b/entc/integration/fieldnames/ent/item_update.go @@ -0,0 +1,741 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "github.com/protobuf-orm/ent/dialect/sql" + "github.com/protobuf-orm/ent/dialect/sql/sqlgraph" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/item" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/predicate" + "github.com/protobuf-orm/ent/schema/field" +) + +// ItemUpdate is the builder for updating Item entities. +type ItemUpdate struct { + config + hooks []Hook + mutation *ItemMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the ItemUpdate builder. +func (_u *ItemUpdate) Where(ps ...predicate.Item) *ItemUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetField sets the "field" field. +func (_u *ItemUpdate) SetField(v int) *ItemUpdate { + _u.mutation.ResetFieldField() + _u.mutation.SetFieldField(v) + return _u +} + +// SetNillableField sets the "field" field if the given value is not nil. +func (_u *ItemUpdate) SetNillableField(v *int) *ItemUpdate { + if v != nil { + _u.SetField(*v) + } + return _u +} + +// AddFieldField adds value to the "field" field. +func (_u *ItemUpdate) AddFieldField(v int) *ItemUpdate { + _u.mutation.AddFieldField(v) + return _u +} + +// ClearField clears the value of the "field" field. +func (_u *ItemUpdate) ClearField() *ItemUpdate { + _u.mutation.ClearFieldField() + return _u +} + +// SetFields sets the "fields" field. +func (_u *ItemUpdate) SetFields(v int) *ItemUpdate { + _u.mutation.ResetFields() + _u.mutation.SetFields(v) + return _u +} + +// SetNillableFields sets the "fields" field if the given value is not nil. +func (_u *ItemUpdate) SetNillableFields(v *int) *ItemUpdate { + if v != nil { + _u.SetFields(*v) + } + return _u +} + +// AddFields adds value to the "fields" field. +func (_u *ItemUpdate) AddFields(v int) *ItemUpdate { + _u.mutation.AddFields(v) + return _u +} + +// ClearFields clears the value of the "fields" field. +func (_u *ItemUpdate) ClearFields() *ItemUpdate { + _u.mutation.ClearFields() + return _u +} + +// SetEdge sets the "edge" field. +func (_u *ItemUpdate) SetEdge(v int) *ItemUpdate { + _u.mutation.ResetEdgeField() + _u.mutation.SetEdge(v) + return _u +} + +// SetNillableEdge sets the "edge" field if the given value is not nil. +func (_u *ItemUpdate) SetNillableEdge(v *int) *ItemUpdate { + if v != nil { + _u.SetEdge(*v) + } + return _u +} + +// AddEdge adds value to the "edge" field. +func (_u *ItemUpdate) AddEdge(v int) *ItemUpdate { + _u.mutation.AddEdge(v) + return _u +} + +// ClearEdge clears the value of the "edge" field. +func (_u *ItemUpdate) ClearEdge() *ItemUpdate { + _u.mutation.ClearEdgeField() + return _u +} + +// SetIds sets the "ids" field. +func (_u *ItemUpdate) SetIds(v int) *ItemUpdate { + _u.mutation.ResetIds() + _u.mutation.SetIds(v) + return _u +} + +// SetNillableIds sets the "ids" field if the given value is not nil. +func (_u *ItemUpdate) SetNillableIds(v *int) *ItemUpdate { + if v != nil { + _u.SetIds(*v) + } + return _u +} + +// AddIds adds value to the "ids" field. +func (_u *ItemUpdate) AddIds(v int) *ItemUpdate { + _u.mutation.AddIds(v) + return _u +} + +// ClearIds clears the value of the "ids" field. +func (_u *ItemUpdate) ClearIds() *ItemUpdate { + _u.mutation.ClearIds() + return _u +} + +// SetWhere sets the "where" field. +func (_u *ItemUpdate) SetWhere(v int) *ItemUpdate { + _u.mutation.ResetWhere() + _u.mutation.SetWhere(v) + return _u +} + +// SetNillableWhere sets the "where" field if the given value is not nil. +func (_u *ItemUpdate) SetNillableWhere(v *int) *ItemUpdate { + if v != nil { + _u.SetWhere(*v) + } + return _u +} + +// AddWhere adds value to the "where" field. +func (_u *ItemUpdate) AddWhere(v int) *ItemUpdate { + _u.mutation.AddWhere(v) + return _u +} + +// ClearWhere clears the value of the "where" field. +func (_u *ItemUpdate) ClearWhere() *ItemUpdate { + _u.mutation.ClearWhere() + return _u +} + +// SetOp sets the "op" field. +func (_u *ItemUpdate) SetOp(v int) *ItemUpdate { + _u.mutation.ResetOp() + _u.mutation.SetOpField(v) + return _u +} + +// SetNillableOp sets the "op" field if the given value is not nil. +func (_u *ItemUpdate) SetNillableOp(v *int) *ItemUpdate { + if v != nil { + _u.SetOp(*v) + } + return _u +} + +// AddOp adds value to the "op" field. +func (_u *ItemUpdate) AddOp(v int) *ItemUpdate { + _u.mutation.AddOp(v) + return _u +} + +// ClearOp clears the value of the "op" field. +func (_u *ItemUpdate) ClearOp() *ItemUpdate { + _u.mutation.ClearOp() + return _u +} + +// SetType sets the "type" field. +func (_u *ItemUpdate) SetType(v int) *ItemUpdate { + _u.mutation.ResetType() + _u.mutation.SetType(v) + return _u +} + +// SetNillableType sets the "type" field if the given value is not nil. +func (_u *ItemUpdate) SetNillableType(v *int) *ItemUpdate { + if v != nil { + _u.SetType(*v) + } + return _u +} + +// AddType adds value to the "type" field. +func (_u *ItemUpdate) AddType(v int) *ItemUpdate { + _u.mutation.AddType(v) + return _u +} + +// ClearType clears the value of the "type" field. +func (_u *ItemUpdate) ClearType() *ItemUpdate { + _u.mutation.ClearType() + return _u +} + +// Mutation returns the ItemMutation object of the builder. +func (_u *ItemUpdate) Mutation() *ItemMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ItemUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ItemUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ItemUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ItemUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *ItemUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *ItemUpdate { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *ItemUpdate) sqlSave(ctx context.Context) (_node int, err error) { + _spec := sqlgraph.NewUpdateSpec(item.Table, item.Columns, sqlgraph.NewFieldSpec(item.FieldId, field.TypeInt)) + if ps := _u.mutation.Predicates(); len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.GetField(); ok { + _spec.SetField(item.FieldField, field.TypeInt, value) + } + if e, ok := _u.mutation.FieldExpr(item.FieldField); ok { + _spec.SetField(item.FieldField, field.TypeInt, e) + } + if value, ok := _u.mutation.AddedFieldField(); ok { + _spec.AddField(item.FieldField, field.TypeInt, value) + } + if _u.mutation.FieldFieldCleared() { + _spec.ClearField(item.FieldField, field.TypeInt) + } + if value, ok := _u.mutation.GetFields(); ok { + _spec.SetField(item.FieldFields, field.TypeInt, value) + } + if e, ok := _u.mutation.FieldExpr(item.FieldFields); ok { + _spec.SetField(item.FieldFields, field.TypeInt, e) + } + if value, ok := _u.mutation.AddedFieldsField(); ok { + _spec.AddField(item.FieldFields, field.TypeInt, value) + } + if _u.mutation.FieldsCleared() { + _spec.ClearField(item.FieldFields, field.TypeInt) + } + if value, ok := _u.mutation.Edge(); ok { + _spec.SetField(item.FieldEdge, field.TypeInt, value) + } + if e, ok := _u.mutation.FieldExpr(item.FieldEdge); ok { + _spec.SetField(item.FieldEdge, field.TypeInt, e) + } + if value, ok := _u.mutation.AddedEdge(); ok { + _spec.AddField(item.FieldEdge, field.TypeInt, value) + } + if _u.mutation.EdgeFieldCleared() { + _spec.ClearField(item.FieldEdge, field.TypeInt) + } + if value, ok := _u.mutation.GetIds(); ok { + _spec.SetField(item.FieldIds, field.TypeInt, value) + } + if e, ok := _u.mutation.FieldExpr(item.FieldIds); ok { + _spec.SetField(item.FieldIds, field.TypeInt, e) + } + if value, ok := _u.mutation.AddedIdsField(); ok { + _spec.AddField(item.FieldIds, field.TypeInt, value) + } + if _u.mutation.IdsCleared() { + _spec.ClearField(item.FieldIds, field.TypeInt) + } + if value, ok := _u.mutation.GetWhere(); ok { + _spec.SetField(item.FieldWhere, field.TypeInt, value) + } + if e, ok := _u.mutation.FieldExpr(item.FieldWhere); ok { + _spec.SetField(item.FieldWhere, field.TypeInt, e) + } + if value, ok := _u.mutation.AddedWhere(); ok { + _spec.AddField(item.FieldWhere, field.TypeInt, value) + } + if _u.mutation.WhereCleared() { + _spec.ClearField(item.FieldWhere, field.TypeInt) + } + if value, ok := _u.mutation.GetOp(); ok { + _spec.SetField(item.FieldOp, field.TypeInt, value) + } + if e, ok := _u.mutation.FieldExpr(item.FieldOp); ok { + _spec.SetField(item.FieldOp, field.TypeInt, e) + } + if value, ok := _u.mutation.AddedOp(); ok { + _spec.AddField(item.FieldOp, field.TypeInt, value) + } + if _u.mutation.OpCleared() { + _spec.ClearField(item.FieldOp, field.TypeInt) + } + if value, ok := _u.mutation.GetType(); ok { + _spec.SetField(item.FieldType, field.TypeInt, value) + } + if e, ok := _u.mutation.FieldExpr(item.FieldType); ok { + _spec.SetField(item.FieldType, field.TypeInt, e) + } + if value, ok := _u.mutation.AddedType(); ok { + _spec.AddField(item.FieldType, field.TypeInt, value) + } + if _u.mutation.TypeCleared() { + _spec.ClearField(item.FieldType, field.TypeInt) + } + _spec.AddModifiers(_u.modifiers...) + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{item.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ItemUpdateOne is the builder for updating a single Item entity. +type ItemUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ItemMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetField sets the "field" field. +func (_u *ItemUpdateOne) SetField(v int) *ItemUpdateOne { + _u.mutation.ResetFieldField() + _u.mutation.SetFieldField(v) + return _u +} + +// SetNillableField sets the "field" field if the given value is not nil. +func (_u *ItemUpdateOne) SetNillableField(v *int) *ItemUpdateOne { + if v != nil { + _u.SetField(*v) + } + return _u +} + +// AddFieldField adds value to the "field" field. +func (_u *ItemUpdateOne) AddFieldField(v int) *ItemUpdateOne { + _u.mutation.AddFieldField(v) + return _u +} + +// ClearField clears the value of the "field" field. +func (_u *ItemUpdateOne) ClearField() *ItemUpdateOne { + _u.mutation.ClearFieldField() + return _u +} + +// SetFields sets the "fields" field. +func (_u *ItemUpdateOne) SetFields(v int) *ItemUpdateOne { + _u.mutation.ResetFields() + _u.mutation.SetFields(v) + return _u +} + +// SetNillableFields sets the "fields" field if the given value is not nil. +func (_u *ItemUpdateOne) SetNillableFields(v *int) *ItemUpdateOne { + if v != nil { + _u.SetFields(*v) + } + return _u +} + +// AddFields adds value to the "fields" field. +func (_u *ItemUpdateOne) AddFields(v int) *ItemUpdateOne { + _u.mutation.AddFields(v) + return _u +} + +// ClearFields clears the value of the "fields" field. +func (_u *ItemUpdateOne) ClearFields() *ItemUpdateOne { + _u.mutation.ClearFields() + return _u +} + +// SetEdge sets the "edge" field. +func (_u *ItemUpdateOne) SetEdge(v int) *ItemUpdateOne { + _u.mutation.ResetEdgeField() + _u.mutation.SetEdge(v) + return _u +} + +// SetNillableEdge sets the "edge" field if the given value is not nil. +func (_u *ItemUpdateOne) SetNillableEdge(v *int) *ItemUpdateOne { + if v != nil { + _u.SetEdge(*v) + } + return _u +} + +// AddEdge adds value to the "edge" field. +func (_u *ItemUpdateOne) AddEdge(v int) *ItemUpdateOne { + _u.mutation.AddEdge(v) + return _u +} + +// ClearEdge clears the value of the "edge" field. +func (_u *ItemUpdateOne) ClearEdge() *ItemUpdateOne { + _u.mutation.ClearEdgeField() + return _u +} + +// SetIds sets the "ids" field. +func (_u *ItemUpdateOne) SetIds(v int) *ItemUpdateOne { + _u.mutation.ResetIds() + _u.mutation.SetIds(v) + return _u +} + +// SetNillableIds sets the "ids" field if the given value is not nil. +func (_u *ItemUpdateOne) SetNillableIds(v *int) *ItemUpdateOne { + if v != nil { + _u.SetIds(*v) + } + return _u +} + +// AddIds adds value to the "ids" field. +func (_u *ItemUpdateOne) AddIds(v int) *ItemUpdateOne { + _u.mutation.AddIds(v) + return _u +} + +// ClearIds clears the value of the "ids" field. +func (_u *ItemUpdateOne) ClearIds() *ItemUpdateOne { + _u.mutation.ClearIds() + return _u +} + +// SetWhere sets the "where" field. +func (_u *ItemUpdateOne) SetWhere(v int) *ItemUpdateOne { + _u.mutation.ResetWhere() + _u.mutation.SetWhere(v) + return _u +} + +// SetNillableWhere sets the "where" field if the given value is not nil. +func (_u *ItemUpdateOne) SetNillableWhere(v *int) *ItemUpdateOne { + if v != nil { + _u.SetWhere(*v) + } + return _u +} + +// AddWhere adds value to the "where" field. +func (_u *ItemUpdateOne) AddWhere(v int) *ItemUpdateOne { + _u.mutation.AddWhere(v) + return _u +} + +// ClearWhere clears the value of the "where" field. +func (_u *ItemUpdateOne) ClearWhere() *ItemUpdateOne { + _u.mutation.ClearWhere() + return _u +} + +// SetOp sets the "op" field. +func (_u *ItemUpdateOne) SetOp(v int) *ItemUpdateOne { + _u.mutation.ResetOp() + _u.mutation.SetOpField(v) + return _u +} + +// SetNillableOp sets the "op" field if the given value is not nil. +func (_u *ItemUpdateOne) SetNillableOp(v *int) *ItemUpdateOne { + if v != nil { + _u.SetOp(*v) + } + return _u +} + +// AddOp adds value to the "op" field. +func (_u *ItemUpdateOne) AddOp(v int) *ItemUpdateOne { + _u.mutation.AddOp(v) + return _u +} + +// ClearOp clears the value of the "op" field. +func (_u *ItemUpdateOne) ClearOp() *ItemUpdateOne { + _u.mutation.ClearOp() + return _u +} + +// SetType sets the "type" field. +func (_u *ItemUpdateOne) SetType(v int) *ItemUpdateOne { + _u.mutation.ResetType() + _u.mutation.SetType(v) + return _u +} + +// SetNillableType sets the "type" field if the given value is not nil. +func (_u *ItemUpdateOne) SetNillableType(v *int) *ItemUpdateOne { + if v != nil { + _u.SetType(*v) + } + return _u +} + +// AddType adds value to the "type" field. +func (_u *ItemUpdateOne) AddType(v int) *ItemUpdateOne { + _u.mutation.AddType(v) + return _u +} + +// ClearType clears the value of the "type" field. +func (_u *ItemUpdateOne) ClearType() *ItemUpdateOne { + _u.mutation.ClearType() + return _u +} + +// Mutation returns the ItemMutation object of the builder. +func (_u *ItemUpdateOne) Mutation() *ItemMutation { + return _u.mutation +} + +// Where appends a list predicates to the ItemUpdate builder. +func (_u *ItemUpdateOne) Where(ps ...predicate.Item) *ItemUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *ItemUpdateOne) Select(field string, fields ...string) *ItemUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Item entity. +func (_u *ItemUpdateOne) Save(ctx context.Context) (*Item, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ItemUpdateOne) SaveX(ctx context.Context) *Item { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ItemUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ItemUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *ItemUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *ItemUpdateOne { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *ItemUpdateOne) sqlSave(ctx context.Context) (_node *Item, err error) { + _spec := sqlgraph.NewUpdateSpec(item.Table, item.Columns, sqlgraph.NewFieldSpec(item.FieldId, field.TypeInt)) + id, ok := _u.mutation.Id() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Item.id" for update`)} + } + _spec.Node.Id.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, item.FieldId) + for _, f := range fields { + if !item.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != item.FieldId { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.Predicates(); len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.GetField(); ok { + _spec.SetField(item.FieldField, field.TypeInt, value) + } + if e, ok := _u.mutation.FieldExpr(item.FieldField); ok { + _spec.SetField(item.FieldField, field.TypeInt, e) + } + if value, ok := _u.mutation.AddedFieldField(); ok { + _spec.AddField(item.FieldField, field.TypeInt, value) + } + if _u.mutation.FieldFieldCleared() { + _spec.ClearField(item.FieldField, field.TypeInt) + } + if value, ok := _u.mutation.GetFields(); ok { + _spec.SetField(item.FieldFields, field.TypeInt, value) + } + if e, ok := _u.mutation.FieldExpr(item.FieldFields); ok { + _spec.SetField(item.FieldFields, field.TypeInt, e) + } + if value, ok := _u.mutation.AddedFieldsField(); ok { + _spec.AddField(item.FieldFields, field.TypeInt, value) + } + if _u.mutation.FieldsCleared() { + _spec.ClearField(item.FieldFields, field.TypeInt) + } + if value, ok := _u.mutation.Edge(); ok { + _spec.SetField(item.FieldEdge, field.TypeInt, value) + } + if e, ok := _u.mutation.FieldExpr(item.FieldEdge); ok { + _spec.SetField(item.FieldEdge, field.TypeInt, e) + } + if value, ok := _u.mutation.AddedEdge(); ok { + _spec.AddField(item.FieldEdge, field.TypeInt, value) + } + if _u.mutation.EdgeFieldCleared() { + _spec.ClearField(item.FieldEdge, field.TypeInt) + } + if value, ok := _u.mutation.GetIds(); ok { + _spec.SetField(item.FieldIds, field.TypeInt, value) + } + if e, ok := _u.mutation.FieldExpr(item.FieldIds); ok { + _spec.SetField(item.FieldIds, field.TypeInt, e) + } + if value, ok := _u.mutation.AddedIdsField(); ok { + _spec.AddField(item.FieldIds, field.TypeInt, value) + } + if _u.mutation.IdsCleared() { + _spec.ClearField(item.FieldIds, field.TypeInt) + } + if value, ok := _u.mutation.GetWhere(); ok { + _spec.SetField(item.FieldWhere, field.TypeInt, value) + } + if e, ok := _u.mutation.FieldExpr(item.FieldWhere); ok { + _spec.SetField(item.FieldWhere, field.TypeInt, e) + } + if value, ok := _u.mutation.AddedWhere(); ok { + _spec.AddField(item.FieldWhere, field.TypeInt, value) + } + if _u.mutation.WhereCleared() { + _spec.ClearField(item.FieldWhere, field.TypeInt) + } + if value, ok := _u.mutation.GetOp(); ok { + _spec.SetField(item.FieldOp, field.TypeInt, value) + } + if e, ok := _u.mutation.FieldExpr(item.FieldOp); ok { + _spec.SetField(item.FieldOp, field.TypeInt, e) + } + if value, ok := _u.mutation.AddedOp(); ok { + _spec.AddField(item.FieldOp, field.TypeInt, value) + } + if _u.mutation.OpCleared() { + _spec.ClearField(item.FieldOp, field.TypeInt) + } + if value, ok := _u.mutation.GetType(); ok { + _spec.SetField(item.FieldType, field.TypeInt, value) + } + if e, ok := _u.mutation.FieldExpr(item.FieldType); ok { + _spec.SetField(item.FieldType, field.TypeInt, e) + } + if value, ok := _u.mutation.AddedType(); ok { + _spec.AddField(item.FieldType, field.TypeInt, value) + } + if _u.mutation.TypeCleared() { + _spec.ClearField(item.FieldType, field.TypeInt) + } + _spec.AddModifiers(_u.modifiers...) + _node = &Item{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{item.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/entc/integration/fieldnames/ent/migrate/migrate.go b/entc/integration/fieldnames/ent/migrate/migrate.go new file mode 100644 index 0000000000..3d50c01753 --- /dev/null +++ b/entc/integration/fieldnames/ent/migrate/migrate.go @@ -0,0 +1,68 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package migrate + +import ( + "context" + "fmt" + "io" + + "github.com/protobuf-orm/ent/dialect" + "github.com/protobuf-orm/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 + // 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 +} + +// 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 { + return Create(ctx, s, Tables, opts...) +} + +// Create creates all table resources using the given schema driver. +func Create(ctx context.Context, s *Schema, tables []*schema.Table, 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 { + return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...) +} diff --git a/entc/integration/fieldnames/ent/migrate/schema.go b/entc/integration/fieldnames/ent/migrate/schema.go new file mode 100644 index 0000000000..9dfbd45ffe --- /dev/null +++ b/entc/integration/fieldnames/ent/migrate/schema.go @@ -0,0 +1,61 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package migrate + +import ( + "github.com/protobuf-orm/ent/dialect/sql/schema" + "github.com/protobuf-orm/ent/schema/field" +) + +var ( + // ItemColumns holds the columns for the "item" table. + ItemColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "field", Type: field.TypeInt, Nullable: true}, + {Name: "fields", Type: field.TypeInt, Nullable: true}, + {Name: "edge", Type: field.TypeInt, Nullable: true}, + {Name: "ids", Type: field.TypeInt, Nullable: true}, + {Name: "where", Type: field.TypeInt, Nullable: true}, + {Name: "op", Type: field.TypeInt, Nullable: true}, + {Name: "type", Type: field.TypeInt, Nullable: true}, + } + // ItemTable holds the schema information for the "item" table. + ItemTable = &schema.Table{ + Name: "item", + Columns: ItemColumns, + PrimaryKey: []*schema.Column{ItemColumns[0]}, + } + // OwnerColumns holds the columns for the "owner" table. + OwnerColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "field", Type: field.TypeInt, Nullable: true}, + {Name: "owner_edge", Type: field.TypeInt}, + } + // OwnerTable holds the schema information for the "owner" table. + OwnerTable = &schema.Table{ + Name: "owner", + Columns: OwnerColumns, + PrimaryKey: []*schema.Column{OwnerColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "owner_item_edge", + Columns: []*schema.Column{OwnerColumns[2]}, + RefColumns: []*schema.Column{ItemColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + } + // Tables holds all the tables in the schema. + Tables = []*schema.Table{ + ItemTable, + OwnerTable, + } +) + +func init() { + OwnerTable.ForeignKeys[0].RefTable = ItemTable +} diff --git a/entc/integration/fieldnames/ent/mutation.go b/entc/integration/fieldnames/ent/mutation.go new file mode 100644 index 0000000000..87735b9d17 --- /dev/null +++ b/entc/integration/fieldnames/ent/mutation.go @@ -0,0 +1,411 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "sync" + + "github.com/protobuf-orm/ent" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/item" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/owner" +) + +const ( + // Operation types. + OpCreate = ent.OpCreate + OpDelete = ent.OpDelete + OpDeleteOne = ent.OpDeleteOne + OpUpdate = ent.OpUpdate + OpUpdateOne = ent.OpUpdateOne + + // Node types. + TypeItem = "Item" + TypeOwner = "Owner" +) + +// ItemMutation represents an operation that mutates the Item nodes in the graph. +type ItemMutation struct { + item.Mutation + config + id *int + done bool + oldValue func(context.Context) (*Item, error) +} + +var _ ent.Mutation = (*ItemMutation)(nil) + +// itemOption allows management of the mutation configuration using functional options. +type itemOption func(*ItemMutation) + +// newItemMutation creates new mutation for the Item entity. +func newItemMutation(c config, op Op, opts ...itemOption) *ItemMutation { + m := &ItemMutation{ + Mutation: *item.NewMutation(op), + config: c, + } + for _, opt := range opts { + opt(m) + } + return m +} + +// Id returns the Id value in the mutation. Note that the Id is only available +// if it was provided to the builder or after it was returned from the database. +func (m *ItemMutation) Id() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// withItemId sets the Id field of the mutation. +func withItemId(id int) itemOption { + return func(m *ItemMutation) { + var ( + err error + once sync.Once + value *Item + ) + m.oldValue = func(ctx context.Context) (*Item, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Item.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withItem sets the old Item of the mutation. +func withItem(node *Item) itemOption { + return func(m *ItemMutation) { + m.oldValue = func(context.Context) (*Item, 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 ItemMutation) 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 ItemMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// Ids queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *ItemMutation) Ids(ctx context.Context) ([]int, error) { + switch { + case m.Op().Is(OpUpdateOne | OpDeleteOne): + id, exists := m.Id() + if exists { + return []int{id}, nil + } + fallthrough + case m.Op().Is(OpUpdate | OpDelete): + return m.Client().Item.Query().Where(m.Predicates()...).Ids(ctx) + default: + return nil, fmt.Errorf("Ids is not allowed on %s operations", m.Op()) + } +} + +// GetOldField returns the old "field" field's value of the Item entity. +// If the Item 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 *ItemMutation) GetOldField(ctx context.Context) (v *int, err error) { + if !m.Op().Is(OpUpdateOne) { + return v, errors.New("GetOldField is only allowed on UpdateOne operations") + } + if _, exists := m.Id(); !exists || m.oldValue == nil { + return v, errors.New("GetOldField requires an Id field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for GetOldField: %w", err) + } + return oldValue.Field, nil +} + +// OldFields returns the old "fields" field's value of the Item entity. +// If the Item 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 *ItemMutation) OldFields(ctx context.Context) (v *int, err error) { + if !m.Op().Is(OpUpdateOne) { + return v, errors.New("OldFields is only allowed on UpdateOne operations") + } + if _, exists := m.Id(); !exists || m.oldValue == nil { + return v, errors.New("OldFields requires an Id field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFields: %w", err) + } + return oldValue.Fields, nil +} + +// OldEdge returns the old "edge" field's value of the Item entity. +// If the Item 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 *ItemMutation) OldEdge(ctx context.Context) (v *int, err error) { + if !m.Op().Is(OpUpdateOne) { + return v, errors.New("OldEdge is only allowed on UpdateOne operations") + } + if _, exists := m.Id(); !exists || m.oldValue == nil { + return v, errors.New("OldEdge requires an Id field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEdge: %w", err) + } + return oldValue.Edge, nil +} + +// OldIds returns the old "ids" field's value of the Item entity. +// If the Item 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 *ItemMutation) OldIds(ctx context.Context) (v *int, err error) { + if !m.Op().Is(OpUpdateOne) { + return v, errors.New("OldIds is only allowed on UpdateOne operations") + } + if _, exists := m.Id(); !exists || m.oldValue == nil { + return v, errors.New("OldIds requires an Id field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIds: %w", err) + } + return oldValue.Ids, nil +} + +// OldWhere returns the old "where" field's value of the Item entity. +// If the Item 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 *ItemMutation) OldWhere(ctx context.Context) (v *int, err error) { + if !m.Op().Is(OpUpdateOne) { + return v, errors.New("OldWhere is only allowed on UpdateOne operations") + } + if _, exists := m.Id(); !exists || m.oldValue == nil { + return v, errors.New("OldWhere requires an Id field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldWhere: %w", err) + } + return oldValue.Where, nil +} + +// OldOp returns the old "op" field's value of the Item entity. +// If the Item 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 *ItemMutation) OldOp(ctx context.Context) (v *int, err error) { + if !m.Op().Is(OpUpdateOne) { + return v, errors.New("OldOp is only allowed on UpdateOne operations") + } + if _, exists := m.Id(); !exists || m.oldValue == nil { + return v, errors.New("OldOp requires an Id field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOp: %w", err) + } + return oldValue.Op, nil +} + +// OldType returns the old "type" field's value of the Item entity. +// If the Item 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 *ItemMutation) OldType(ctx context.Context) (v *int, err error) { + if !m.Op().Is(OpUpdateOne) { + return v, errors.New("OldType is only allowed on UpdateOne operations") + } + if _, exists := m.Id(); !exists || m.oldValue == nil { + return v, errors.New("OldType requires an Id field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldType: %w", err) + } + return oldValue.Type, nil +} + +// 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 *ItemMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case item.FieldField: + return m.GetOldField(ctx) + case item.FieldFields: + return m.OldFields(ctx) + case item.FieldEdge: + return m.OldEdge(ctx) + case item.FieldIds: + return m.OldIds(ctx) + case item.FieldWhere: + return m.OldWhere(ctx) + case item.FieldOp: + return m.OldOp(ctx) + case item.FieldType: + return m.OldType(ctx) + } + return nil, fmt.Errorf("unknown Item field %s", name) +} + +// OwnerMutation represents an operation that mutates the Owner nodes in the graph. +type OwnerMutation struct { + owner.Mutation + config + id *int + done bool + oldValue func(context.Context) (*Owner, error) +} + +var _ ent.Mutation = (*OwnerMutation)(nil) + +// ownerOption allows management of the mutation configuration using functional options. +type ownerOption func(*OwnerMutation) + +// newOwnerMutation creates new mutation for the Owner entity. +func newOwnerMutation(c config, op Op, opts ...ownerOption) *OwnerMutation { + m := &OwnerMutation{ + Mutation: *owner.NewMutation(op), + config: c, + } + for _, opt := range opts { + opt(m) + } + return m +} + +// Id returns the Id value in the mutation. Note that the Id is only available +// if it was provided to the builder or after it was returned from the database. +func (m *OwnerMutation) Id() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// withOwnerId sets the Id field of the mutation. +func withOwnerId(id int) ownerOption { + return func(m *OwnerMutation) { + var ( + err error + once sync.Once + value *Owner + ) + m.oldValue = func(ctx context.Context) (*Owner, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Owner.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withOwner sets the old Owner of the mutation. +func withOwner(node *Owner) ownerOption { + return func(m *OwnerMutation) { + m.oldValue = func(context.Context) (*Owner, 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 OwnerMutation) 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 OwnerMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// Ids queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *OwnerMutation) Ids(ctx context.Context) ([]int, error) { + switch { + case m.Op().Is(OpUpdateOne | OpDeleteOne): + id, exists := m.Id() + if exists { + return []int{id}, nil + } + fallthrough + case m.Op().Is(OpUpdate | OpDelete): + return m.Client().Owner.Query().Where(m.Predicates()...).Ids(ctx) + default: + return nil, fmt.Errorf("Ids is not allowed on %s operations", m.Op()) + } +} + +// GetOldField returns the old "field" field's value of the Owner entity. +// If the Owner 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 *OwnerMutation) GetOldField(ctx context.Context) (v *int, err error) { + if !m.Op().Is(OpUpdateOne) { + return v, errors.New("GetOldField is only allowed on UpdateOne operations") + } + if _, exists := m.Id(); !exists || m.oldValue == nil { + return v, errors.New("GetOldField requires an Id field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for GetOldField: %w", err) + } + return oldValue.Field, nil +} + +// 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 *OwnerMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case owner.FieldField: + return m.GetOldField(ctx) + } + return nil, fmt.Errorf("unknown Owner field %s", name) +} diff --git a/entc/integration/fieldnames/ent/owner.go b/entc/integration/fieldnames/ent/owner.go new file mode 100644 index 0000000000..3e0a9e115b --- /dev/null +++ b/entc/integration/fieldnames/ent/owner.go @@ -0,0 +1,147 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "github.com/protobuf-orm/ent" + "github.com/protobuf-orm/ent/dialect/sql" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/item" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/owner" +) + +// Owner is the model entity for the Owner schema. +type Owner struct { + config `json:"-"` + // Id of the ent. + Id int `json:"id,omitempty"` + // Field holds the value of the "field" field. + Field *int `json:"field,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the OwnerQuery when eager-loading is set. + Edges OwnerEdges `json:"edges"` + owner_edge *int + selectValues sql.SelectValues +} + +// OwnerEdges holds the relations/edges for other nodes in the graph. +type OwnerEdges struct { + // Edge holds the value of the edge edge. + Edge *Item `json:"edge,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// EdgeOrErr returns the Edge value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e OwnerEdges) EdgeOrErr() (*Item, error) { + if e.Edge != nil { + return e.Edge, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: item.Label} + } + return nil, &NotLoadedError{edge: "edge"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Owner) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case owner.FieldId, owner.FieldField: + values[i] = new(sql.NullInt64) + case owner.ForeignKeys[0]: // owner_edge + values[i] = new(sql.NullInt64) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Owner fields. +func (_m *Owner) assignValues(columns []string, values []any) 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 owner.FieldId: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.Id = int(value.Int64) + case owner.FieldField: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field field", values[i]) + } else if value.Valid { + _m.Field = new(int) + *_m.Field = int(value.Int64) + } + case owner.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field owner_edge", value) + } else if value.Valid { + _m.owner_edge = new(int) + *_m.owner_edge = int(value.Int64) + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Owner. +// This includes values selected through modifiers, order, etc. +func (_m *Owner) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryEdge queries the "edge" edge of the Owner entity. +func (_m *Owner) QueryEdge() *ItemQuery { + return NewOwnerClient(_m.config).QueryEdge(_m) +} + +// Update returns a builder for updating this Owner. +// Note that you need to call Owner.Unwrap() before calling this method if this Owner +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Owner) Update() *OwnerUpdateOne { + return NewOwnerClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Owner 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 (_m *Owner) Unwrap() *Owner { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: Owner is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Owner) String() string { + var builder strings.Builder + builder.WriteString("Owner(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.Id)) + if v := _m.Field; v != nil { + builder.WriteString("field=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteByte(')') + return builder.String() +} + +// OwnerList is a parsable slice of Owner. +type OwnerList []*Owner diff --git a/entc/integration/fieldnames/ent/owner/mutation.go b/entc/integration/fieldnames/ent/owner/mutation.go new file mode 100644 index 0000000000..d7919e2ee3 --- /dev/null +++ b/entc/integration/fieldnames/ent/owner/mutation.go @@ -0,0 +1,423 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package owner + +import ( + "context" + "fmt" + + "github.com/protobuf-orm/ent" + "github.com/protobuf-orm/ent/dialect/sql" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/predicate" +) + +// Mutation represents an operation that mutates the Owner nodes in the graph. +type Mutation struct { + op ent.Op + typ string + field *int + addfield *int + clearedFields map[string]struct{} + exprs map[string]sql.Querier + edge *int + clearededge bool + predicates []predicate.Owner +} + +// NewMutation creates a new Mutation for the Owner entity. +func NewMutation(op ent.Op) *Mutation { + return &Mutation{ + op: op, + typ: "Owner", + clearedFields: make(map[string]struct{}), + } +} + +// Predicates returns the list of predicates set on the mutation. +func (m *Mutation) Predicates() []predicate.Owner { + return m.predicates +} + +// SetFieldField sets the "field" field. +func (m *Mutation) SetFieldField(i int) { + m.field = &i + m.addfield = nil + delete(m.clearedFields, FieldField) + delete(m.exprs, FieldField) +} + +// GetField returns the value of the "field" field in the mutation. +func (m *Mutation) GetField() (r int, exists bool) { + v := m.field + if v == nil { + return + } + return *v, true +} + +// AddFieldField adds i to the "field" field. +func (m *Mutation) AddFieldField(i int) { + if m.addfield != nil { + *m.addfield += i + } else { + m.addfield = &i + } +} + +// AddedFieldField returns the value that was added to the "field" field in this mutation. +func (m *Mutation) AddedFieldField() (r int, exists bool) { + v := m.addfield + if v == nil { + return + } + return *v, true +} + +// ClearFieldField clears the value of the "field" field. +func (m *Mutation) ClearFieldField() { + m.field = nil + m.addfield = nil + delete(m.exprs, FieldField) + m.clearedFields[FieldField] = struct{}{} +} + +// FieldFieldCleared returns if the "field" field was cleared in this mutation. +func (m *Mutation) FieldFieldCleared() bool { + _, ok := m.clearedFields[FieldField] + return ok +} + +// ResetFieldField resets all changes to the "field" field. +func (m *Mutation) ResetFieldField() { + m.field = nil + m.addfield = nil + delete(m.clearedFields, FieldField) + delete(m.exprs, FieldField) +} + +// SetEdgeId sets the "edge" edge to the Item entity by id. +func (m *Mutation) SetEdgeId(id int) { + m.edge = &id +} + +// ClearEdgeEdge clears the "edge" edge to the Item entity. +func (m *Mutation) ClearEdgeEdge() { + m.clearededge = true +} + +// EdgeEdgeCleared reports if the "edge" edge to the Item entity was cleared. +func (m *Mutation) EdgeEdgeCleared() bool { + return m.clearededge +} + +// EdgeId returns the "edge" edge Id in the mutation. +func (m *Mutation) EdgeId() (id int, exists bool) { + if m.edge != nil { + return *m.edge, true + } + return +} + +// EdgeIds returns the "edge" edge Ids in the mutation. +// Note that Ids always returns len(Ids) <= 1 for unique edges, and you should use +// EdgeId instead. It exists only for internal usage by the builders. +func (m *Mutation) EdgeIds() (ids []int) { + if id := m.edge; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetEdgeEdge resets all changes to the "edge" edge. +func (m *Mutation) ResetEdgeEdge() { + m.edge = nil + m.clearededge = false +} + +// Where appends a list predicates to the Mutation builder. +func (m *Mutation) Where(ps ...predicate.Owner) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the Mutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *Mutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Owner, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *Mutation) Op() ent.Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *Mutation) SetOp(op ent.Op) { + m.op = op +} + +// Type returns the node type of this mutation (Owner). +func (m *Mutation) 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 *Mutation) Fields() []string { + fields := make([]string, 0, 1) + if m.field != nil || m.exprs[FieldField] != nil { + fields = append(fields, FieldField) + } + 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. +// +// A field assigned an expression with SetFieldExpr returns that expression, a +// sql.Querier, since the value it stands for is the database's to compute. +func (m *Mutation) Field(name string) (ent.Value, bool) { + if e, ok := m.exprs[name]; ok { + return e, true + } + switch name { + case FieldField: + return m.GetField() + } + 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 *Mutation) OldField(ctx context.Context, name string) (ent.Value, error) { + return nil, fmt.Errorf("unknown Owner 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. +// +// A sql.Querier that is not of the field's type is handed to SetFieldExpr, so +// that what Field returns for a field can be set back on it. +func (m *Mutation) SetField(name string, value ent.Value) error { + switch name { + case FieldField: + v, ok := value.(int) + if !ok { + if e, ok := value.(sql.Querier); ok { + return m.SetFieldExpr(name, e) + } + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFieldField(v) + return nil + } + return fmt.Errorf("unknown Owner field %s", name) +} + +// SetFieldExpr assigns the field with the given name a SQL expression, which +// the database evaluates as the UPDATE writes the row. It replaces any value +// the field was set, added, appended or cleared with, as setting it again +// would, and so the column is assigned once. +// +// The field is listed by Fields and Field returns the expression, so a hook +// sees it as it sees any other. What it does not have is a value: a field +// with a validator is refused, since there is nothing for the validator to +// check, and so is one that only a create could write. A create refuses a +// mutation holding an expression at all. +func (m *Mutation) SetFieldExpr(name string, expr sql.Querier) error { + if expr == nil { + return fmt.Errorf("no expression for field %s", name) + } + if m.op.Is(ent.OpCreate) { + return fmt.Errorf("field %s cannot be assigned an expression: a create writes values, and an expression is written only by an update", name) + } + switch name { + case FieldField: + m.ResetFieldField() + default: + return fmt.Errorf("unknown Owner field %s", name) + } + if m.exprs == nil { + m.exprs = make(map[string]sql.Querier) + } + m.exprs[name] = expr + return nil +} + +// FieldExpr returns the expression the field with the given name was assigned +// by SetFieldExpr. The second return value reports whether it was. +func (m *Mutation) FieldExpr(name string) (sql.Querier, bool) { + e, ok := m.exprs[name] + return e, ok +} + +// ExprFields returns the fields that were assigned an expression by +// SetFieldExpr. +func (m *Mutation) ExprFields() []string { + var fields []string + if _, ok := m.exprs[FieldField]; ok { + fields = append(fields, FieldField) + } + return fields +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *Mutation) AddedFields() []string { + var fields []string + if m.addfield != nil { + fields = append(fields, FieldField) + } + 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 *Mutation) AddedField(name string) (ent.Value, bool) { + switch name { + case FieldField: + return m.AddedFieldField() + } + 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 *Mutation) AddField(name string, value ent.Value) error { + switch name { + case FieldField: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddFieldField(v) + return nil + } + return fmt.Errorf("unknown Owner numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *Mutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(FieldField) { + fields = append(fields, FieldField) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *Mutation) 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 *Mutation) ClearField(name string) error { + switch name { + case FieldField: + m.ClearFieldField() + return nil + } + return fmt.Errorf("unknown Owner 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 *Mutation) ResetField(name string) error { + switch name { + case FieldField: + m.ResetFieldField() + return nil + } + return fmt.Errorf("unknown Owner field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *Mutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.edge != nil { + edges = append(edges, EdgeEdge) + } + return edges +} + +// AddedIds returns all Ids (to other nodes) that were added for the given edge +// name in this mutation. +func (m *Mutation) AddedIds(name string) []ent.Value { + switch name { + case EdgeEdge: + if id := m.edge; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *Mutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + return edges +} + +// RemovedIds returns all Ids (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *Mutation) RemovedIds(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *Mutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearededge { + edges = append(edges, EdgeEdge) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *Mutation) EdgeCleared(name string) bool { + switch name { + case EdgeEdge: + return m.clearededge + } + 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 *Mutation) ClearEdge(name string) error { + switch name { + case EdgeEdge: + m.ClearEdgeEdge() + return nil + } + return fmt.Errorf("unknown Owner 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 *Mutation) ResetEdge(name string) error { + switch name { + case EdgeEdge: + m.ResetEdgeEdge() + return nil + } + return fmt.Errorf("unknown Owner edge %s", name) +} diff --git a/entc/integration/fieldnames/ent/owner/owner.go b/entc/integration/fieldnames/ent/owner/owner.go new file mode 100644 index 0000000000..3bc90d8ea4 --- /dev/null +++ b/entc/integration/fieldnames/ent/owner/owner.go @@ -0,0 +1,91 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package owner + +import ( + "github.com/protobuf-orm/ent/dialect/sql" + "github.com/protobuf-orm/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the owner type in the database. + Label = "owner" + // FieldId holds the string denoting the id field in the database. + FieldId = "id" + // FieldField holds the string denoting the field field in the database. + FieldField = "field" + // EdgeEdge holds the string denoting the edge edge name in mutations. + EdgeEdge = "edge" + // Table holds the table name of the owner in the database. + Table = "owner" + // EdgeTable is the table that holds the edge relation/edge. + EdgeTable = "owner" + // EdgeInverseTable is the table name for the Item entity. + // It exists in this package in order to avoid circular dependency with the "item" package. + EdgeInverseTable = "item" + // EdgeColumn is the table column denoting the edge relation/edge. + EdgeColumn = "owner_edge" +) + +// Columns holds all SQL columns for owner fields. +var Columns = []string{ + FieldId, + FieldField, +} + +// ForeignKeys holds the SQL foreign-keys that are owned by the "owner" +// table and are not defined as standalone fields in the schema. +var ForeignKeys = []string{ + "owner_edge", +} + +// 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 + } + } + for i := range ForeignKeys { + if column == ForeignKeys[i] { + return true + } + } + return false +} + +var ( + // UpdateDefaultField holds the default value on update for the "field" field. + UpdateDefaultField func() int +) + +// OrderOption defines the ordering options for the Owner queries. +type OrderOption func(*sql.Selector) + +// ById orders the results by the id field. +func ById(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldId, opts...).ToFunc() +} + +// ByField orders the results by the field field. +func ByField(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldField, opts...).ToFunc() +} + +// ByEdgeField orders the results by edge field. +func ByEdgeField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newEdgeStep(), sql.OrderByField(field, opts...)) + } +} +func newEdgeStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldId), + sqlgraph.To(EdgeInverseTable, FieldId), + sqlgraph.Edge(sqlgraph.M2O, false, EdgeTable, EdgeColumn), + ) +} diff --git a/entc/integration/fieldnames/ent/owner/where.go b/entc/integration/fieldnames/ent/owner/where.go new file mode 100644 index 0000000000..7bfa3b52b7 --- /dev/null +++ b/entc/integration/fieldnames/ent/owner/where.go @@ -0,0 +1,151 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package owner + +import ( + "github.com/protobuf-orm/ent/dialect/sql" + "github.com/protobuf-orm/ent/dialect/sql/sqlgraph" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/predicate" +) + +// Id filters vertices based on their Id field. +func Id(id int) predicate.Owner { + return predicate.Owner(sql.FieldEQ(FieldId, id)) +} + +// IdEQ applies the EQ predicate on the Id field. +func IdEQ(id int) predicate.Owner { + return predicate.Owner(sql.FieldEQ(FieldId, id)) +} + +// IdNEQ applies the NEQ predicate on the Id field. +func IdNEQ(id int) predicate.Owner { + return predicate.Owner(sql.FieldNEQ(FieldId, id)) +} + +// IdIn applies the In predicate on the Id field. +func IdIn(ids ...int) predicate.Owner { + return predicate.Owner(sql.FieldIn(FieldId, ids...)) +} + +// IdNotIn applies the NotIn predicate on the Id field. +func IdNotIn(ids ...int) predicate.Owner { + return predicate.Owner(sql.FieldNotIn(FieldId, ids...)) +} + +// IdGT applies the GT predicate on the Id field. +func IdGT(id int) predicate.Owner { + return predicate.Owner(sql.FieldGT(FieldId, id)) +} + +// IdGTE applies the GTE predicate on the Id field. +func IdGTE(id int) predicate.Owner { + return predicate.Owner(sql.FieldGTE(FieldId, id)) +} + +// IdLT applies the LT predicate on the Id field. +func IdLT(id int) predicate.Owner { + return predicate.Owner(sql.FieldLT(FieldId, id)) +} + +// IdLTE applies the LTE predicate on the Id field. +func IdLTE(id int) predicate.Owner { + return predicate.Owner(sql.FieldLTE(FieldId, id)) +} + +// Field applies equality check predicate on the "field" field. It's identical to FieldEQ. +func Field(v int) predicate.Owner { + return predicate.Owner(sql.FieldEQ(FieldField, v)) +} + +// FieldEQ applies the EQ predicate on the "field" field. +func FieldEQ(v int) predicate.Owner { + return predicate.Owner(sql.FieldEQ(FieldField, v)) +} + +// FieldNEQ applies the NEQ predicate on the "field" field. +func FieldNEQ(v int) predicate.Owner { + return predicate.Owner(sql.FieldNEQ(FieldField, v)) +} + +// FieldIn applies the In predicate on the "field" field. +func FieldIn(vs ...int) predicate.Owner { + return predicate.Owner(sql.FieldIn(FieldField, vs...)) +} + +// FieldNotIn applies the NotIn predicate on the "field" field. +func FieldNotIn(vs ...int) predicate.Owner { + return predicate.Owner(sql.FieldNotIn(FieldField, vs...)) +} + +// FieldGT applies the GT predicate on the "field" field. +func FieldGT(v int) predicate.Owner { + return predicate.Owner(sql.FieldGT(FieldField, v)) +} + +// FieldGTE applies the GTE predicate on the "field" field. +func FieldGTE(v int) predicate.Owner { + return predicate.Owner(sql.FieldGTE(FieldField, v)) +} + +// FieldLT applies the LT predicate on the "field" field. +func FieldLT(v int) predicate.Owner { + return predicate.Owner(sql.FieldLT(FieldField, v)) +} + +// FieldLTE applies the LTE predicate on the "field" field. +func FieldLTE(v int) predicate.Owner { + return predicate.Owner(sql.FieldLTE(FieldField, v)) +} + +// FieldIsNil applies the IsNil predicate on the "field" field. +func FieldIsNil() predicate.Owner { + return predicate.Owner(sql.FieldIsNull(FieldField)) +} + +// FieldNotNil applies the NotNil predicate on the "field" field. +func FieldNotNil() predicate.Owner { + return predicate.Owner(sql.FieldNotNull(FieldField)) +} + +// HasEdge applies the HasEdge predicate on the "edge" edge. +func HasEdge() predicate.Owner { + return predicate.Owner(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldId), + sqlgraph.Edge(sqlgraph.M2O, false, EdgeTable, EdgeColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasEdgeWith applies the HasEdge predicate on the "edge" edge with a given conditions (other predicates). +func HasEdgeWith(preds ...predicate.Item) predicate.Owner { + return predicate.Owner(func(s *sql.Selector) { + step := newEdgeStep() + 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.Owner) predicate.Owner { + return predicate.Owner(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Owner) predicate.Owner { + return predicate.Owner(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Owner) predicate.Owner { + return predicate.Owner(sql.NotPredicates(p)) +} diff --git a/entc/integration/fieldnames/ent/owner_create.go b/entc/integration/fieldnames/ent/owner_create.go new file mode 100644 index 0000000000..07247897b8 --- /dev/null +++ b/entc/integration/fieldnames/ent/owner_create.go @@ -0,0 +1,577 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "github.com/protobuf-orm/ent/dialect/sql" + "github.com/protobuf-orm/ent/dialect/sql/sqlgraph" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/item" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/owner" + "github.com/protobuf-orm/ent/schema/field" +) + +// OwnerCreate is the builder for creating a Owner entity. +type OwnerCreate struct { + config + mutation *OwnerMutation + hooks []Hook + stored **Owner + conflict []sql.ConflictOption +} + +// SetField sets the "field" field. +func (_c *OwnerCreate) SetField(v int) *OwnerCreate { + _c.mutation.SetFieldField(v) + return _c +} + +// SetNillableField sets the "field" field if the given value is not nil. +func (_c *OwnerCreate) SetNillableField(v *int) *OwnerCreate { + if v != nil { + _c.SetField(*v) + } + return _c +} + +// SetEdgeId sets the "edge" edge to the Item entity by Id. +func (_c *OwnerCreate) SetEdgeId(id int) *OwnerCreate { + _c.mutation.SetEdgeId(id) + return _c +} + +// SetEdge sets the "edge" edge to the Item entity. +func (_c *OwnerCreate) SetEdge(v *Item) *OwnerCreate { + return _c.SetEdgeId(v.Id) +} + +// Mutation returns the OwnerMutation object of the builder. +func (_c *OwnerCreate) Mutation() *OwnerMutation { + return _c.mutation +} + +// Save creates the Owner in the database. +func (_c *OwnerCreate) Save(ctx context.Context) (*Owner, error) { + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *OwnerCreate) SaveX(ctx context.Context) *Owner { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *OwnerCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *OwnerCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *OwnerCreate) check() error { + if fs := _c.mutation.ExprFields(); len(fs) > 0 { + return &ValidationError{Name: fs[0], err: fmt.Errorf(`ent: field "Owner.%s" was assigned an expression, which only an update writes`, fs[0])} + } + if len(_c.mutation.EdgeIds()) == 0 { + return &ValidationError{Name: "edge", err: errors.New(`ent: missing required edge "Owner.edge"`)} + } + return nil +} + +func (_c *OwnerCreate) sqlSave(ctx context.Context) (*Owner, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + id := _spec.Id.Value.(int64) + _node.Id = int(id) + _c.mutation.id = &_node.Id + _c.mutation.done = true + return _node, nil +} + +func (_c *OwnerCreate) createSpec() (*Owner, *sqlgraph.CreateSpec) { + var ( + _node = &Owner{config: _c.config} + _spec = sqlgraph.NewCreateSpec(owner.Table, sqlgraph.NewFieldSpec(owner.FieldId, field.TypeInt)) + ) + if _c.stored != nil { + _stored := &Owner{config: _c.config} + _spec.Returning = append(append([]string{}, owner.Columns...), owner.ForeignKeys...) + _spec.ScanValues = _stored.scanValues + _spec.Assign = func(columns []string, values []any) error { + if err := _stored.assignValues(columns, values); err != nil { + return err + } + *_c.stored = _stored + return nil + } + } + _spec.OnConflict = _c.conflict + if value, ok := _c.mutation.GetField(); ok { + _spec.SetField(owner.FieldField, field.TypeInt, value) + _node.Field = &value + } + if nodes := _c.mutation.EdgeIds(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: owner.EdgeTable, + Columns: []string{owner.EdgeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IdSpec: sqlgraph.NewFieldSpec(item.FieldId, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.owner_edge = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// Stored has Save read the Owner back, into `v`, as the database stored +// it: at the precision of its columns, with the defaults the database filled +// in and what a trigger before the write made of it. Save itself answers with +// the Owner as this builder had it. +// +// The INSERT reads it, with RETURNING, where the dialect has it, so that the +// row and the reading of it are one statement. MySQL has none, and an INSERT +// with a conflict clause may have written nothing, so for those it is a query +// by the Id just after the INSERT. Either way it is read on the driver the +// INSERT ran on, so inside a transaction it is that transaction's row. Its +// edges are not loaded. +// +// In a CreateBulk, the Stored of each builder is honoured and the batch's one +// INSERT reads all of their rows back: each is matched to its builder by the +// Id the builder was given, or by its place when the database made the Ids up. +// A column some builders of a batch set and others do not is NULL for the +// others, as it is in any batch; the database's default is for a column no +// builder sets. +// +// `v` is written only by a Save that wrote the row: one that failed, or that a +// hook answered without writing, leaves it as it was. +func (_c *OwnerCreate) Stored(v **Owner) *OwnerCreate { + _c.stored = v + return _c +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.Owner.Create(). +// SetField(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.OwnerUpsert) { +// SetField(v+v). +// }). +// Exec(ctx) +func (_c *OwnerCreate) OnConflict(opts ...sql.ConflictOption) *OwnerUpsertOne { + _c.conflict = opts + return &OwnerUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Owner.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *OwnerCreate) OnConflictColumns(columns ...string) *OwnerUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &OwnerUpsertOne{ + create: _c, + } +} + +type ( + // OwnerUpsertOne is the builder for "upsert"-ing + // one Owner node. + OwnerUpsertOne struct { + create *OwnerCreate + } + + // OwnerUpsert is the "OnConflict" setter. + OwnerUpsert struct { + *sql.UpdateSet + } +) + +// SetField sets the "field" field. +func (u *OwnerUpsert) SetField(v int) *OwnerUpsert { + u.Set(owner.FieldField, v) + return u +} + +// UpdateField sets the "field" field to the value that was provided on create. +func (u *OwnerUpsert) UpdateField() *OwnerUpsert { + u.SetExcluded(owner.FieldField) + return u +} + +// AddField adds v to the "field" field. +func (u *OwnerUpsert) AddField(v int) *OwnerUpsert { + u.Add(owner.FieldField, v) + return u +} + +// ClearField clears the value of the "field" field. +func (u *OwnerUpsert) ClearField() *OwnerUpsert { + u.SetNull(owner.FieldField) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create. +// Using this option is equivalent to using: +// +// client.Owner.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +func (u *OwnerUpsertOne) UpdateNewValues() *OwnerUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Owner.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *OwnerUpsertOne) Ignore() *OwnerUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSql. +func (u *OwnerUpsertOne) DoNothing() *OwnerUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the OwnerCreate.OnConflict +// documentation for more info. +func (u *OwnerUpsertOne) Update(set func(*OwnerUpsert)) *OwnerUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&OwnerUpsert{UpdateSet: update}) + })) + return u +} + +// SetField sets the "field" field. +func (u *OwnerUpsertOne) SetField(v int) *OwnerUpsertOne { + return u.Update(func(s *OwnerUpsert) { + s.SetField(v) + }) +} + +// AddField adds v to the "field" field. +func (u *OwnerUpsertOne) AddField(v int) *OwnerUpsertOne { + return u.Update(func(s *OwnerUpsert) { + s.AddField(v) + }) +} + +// UpdateField sets the "field" field to the value that was provided on create. +func (u *OwnerUpsertOne) UpdateField() *OwnerUpsertOne { + return u.Update(func(s *OwnerUpsert) { + s.UpdateField() + }) +} + +// ClearField clears the value of the "field" field. +func (u *OwnerUpsertOne) ClearField() *OwnerUpsertOne { + return u.Update(func(s *OwnerUpsert) { + s.ClearField() + }) +} + +// Exec executes the query. +func (u *OwnerUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for OwnerCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *OwnerUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated Id. +func (u *OwnerUpsertOne) Id(ctx context.Context) (id int, err error) { + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.Id, nil +} + +// IdX is like Id, but panics if an error occurs. +func (u *OwnerUpsertOne) IdX(ctx context.Context) int { + id, err := u.Id(ctx) + if err != nil { + panic(err) + } + return id +} + +// OwnerCreateBulk is the builder for creating many Owner entities in bulk. +type OwnerCreateBulk struct { + config + err error + builders []*OwnerCreate + conflict []sql.ConflictOption +} + +// Save creates the Owner entities in the database. +func (_c *OwnerCreateBulk) Save(ctx context.Context) ([]*Owner, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Owner, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*OwnerMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].Id + if specs[i].Id.Value != nil { + id := specs[i].Id.Value.(int64) + nodes[i].Id = int(id) + } + mutation.done = true + 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, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *OwnerCreateBulk) SaveX(ctx context.Context) []*Owner { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *OwnerCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *OwnerCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.Owner.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.OwnerUpsert) { +// SetField(v+v). +// }). +// Exec(ctx) +func (_c *OwnerCreateBulk) OnConflict(opts ...sql.ConflictOption) *OwnerUpsertBulk { + _c.conflict = opts + return &OwnerUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Owner.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *OwnerCreateBulk) OnConflictColumns(columns ...string) *OwnerUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &OwnerUpsertBulk{ + create: _c, + } +} + +// OwnerUpsertBulk is the builder for "upsert"-ing +// a bulk of Owner nodes. +type OwnerUpsertBulk struct { + create *OwnerCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.Owner.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +func (u *OwnerUpsertBulk) UpdateNewValues() *OwnerUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Owner.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *OwnerUpsertBulk) Ignore() *OwnerUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSql. +func (u *OwnerUpsertBulk) DoNothing() *OwnerUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the OwnerCreateBulk.OnConflict +// documentation for more info. +func (u *OwnerUpsertBulk) Update(set func(*OwnerUpsert)) *OwnerUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&OwnerUpsert{UpdateSet: update}) + })) + return u +} + +// SetField sets the "field" field. +func (u *OwnerUpsertBulk) SetField(v int) *OwnerUpsertBulk { + return u.Update(func(s *OwnerUpsert) { + s.SetField(v) + }) +} + +// AddField adds v to the "field" field. +func (u *OwnerUpsertBulk) AddField(v int) *OwnerUpsertBulk { + return u.Update(func(s *OwnerUpsert) { + s.AddField(v) + }) +} + +// UpdateField sets the "field" field to the value that was provided on create. +func (u *OwnerUpsertBulk) UpdateField() *OwnerUpsertBulk { + return u.Update(func(s *OwnerUpsert) { + s.UpdateField() + }) +} + +// ClearField clears the value of the "field" field. +func (u *OwnerUpsertBulk) ClearField() *OwnerUpsertBulk { + return u.Update(func(s *OwnerUpsert) { + s.ClearField() + }) +} + +// Exec executes the query. +func (u *OwnerUpsertBulk) Exec(ctx context.Context) error { + if u.create.err != nil { + return u.create.err + } + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the OwnerCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for OwnerCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *OwnerUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/fieldnames/ent/owner_delete.go b/entc/integration/fieldnames/ent/owner_delete.go new file mode 100644 index 0000000000..f6ca409630 --- /dev/null +++ b/entc/integration/fieldnames/ent/owner_delete.go @@ -0,0 +1,92 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "github.com/protobuf-orm/ent/dialect/sql" + "github.com/protobuf-orm/ent/dialect/sql/sqlgraph" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/owner" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/predicate" + "github.com/protobuf-orm/ent/schema/field" +) + +// OwnerDelete is the builder for deleting a Owner entity. +type OwnerDelete struct { + config + hooks []Hook + mutation *OwnerMutation +} + +// Where appends a list predicates to the OwnerDelete builder. +func (_d *OwnerDelete) Where(ps ...predicate.Owner) *OwnerDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *OwnerDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *OwnerDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *OwnerDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(owner.Table, sqlgraph.NewFieldSpec(owner.FieldId, field.TypeInt)) + if ps := _d.mutation.Predicates(); len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// OwnerDeleteOne is the builder for deleting a single Owner entity. +type OwnerDeleteOne struct { + _d *OwnerDelete +} + +// Where appends a list predicates to the OwnerDelete builder. +func (_d *OwnerDeleteOne) Where(ps ...predicate.Owner) *OwnerDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *OwnerDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{owner.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *OwnerDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/fieldnames/ent/owner_query.go b/entc/integration/fieldnames/ent/owner_query.go new file mode 100644 index 0000000000..0f2e5c70be --- /dev/null +++ b/entc/integration/fieldnames/ent/owner_query.go @@ -0,0 +1,641 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "github.com/protobuf-orm/ent" + "github.com/protobuf-orm/ent/dialect/sql" + "github.com/protobuf-orm/ent/dialect/sql/sqlgraph" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/item" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/owner" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/predicate" + "github.com/protobuf-orm/ent/schema/field" +) + +// OwnerQuery is the builder for querying Owner entities. +type OwnerQuery struct { + config + ctx *QueryContext + order []owner.OrderOption + inters []Interceptor + predicates []predicate.Owner + withEdge *ItemQuery + withFKs bool + modifiers []func(*sql.Selector) + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the OwnerQuery builder. +func (_q *OwnerQuery) Where(ps ...predicate.Owner) *OwnerQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *OwnerQuery) Limit(limit int) *OwnerQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *OwnerQuery) Offset(offset int) *OwnerQuery { + _q.ctx.Offset = &offset + return _q +} + +// 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 (_q *OwnerQuery) Unique(unique bool) *OwnerQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *OwnerQuery) Order(o ...owner.OrderOption) *OwnerQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryEdge chains the current query on the "edge" edge. +func (_q *OwnerQuery) QueryEdge() *ItemQuery { + query := (&ItemClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(owner.Table, owner.FieldId, selector), + sqlgraph.To(item.Table, item.FieldId), + sqlgraph.Edge(sqlgraph.M2O, false, owner.EdgeTable, owner.EdgeColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Owner entity from the query. +// Returns a *NotFoundError when no Owner was found. +func (_q *OwnerQuery) First(ctx context.Context) (*Owner, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{owner.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *OwnerQuery) FirstX(ctx context.Context) *Owner { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstId returns the first Owner Id from the query. +// Returns a *NotFoundError when no Owner Id was found. +func (_q *OwnerQuery) FirstId(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(1).Ids(setContextOp(ctx, _q.ctx, ent.OpQueryFirstId)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{owner.Label} + return + } + return ids[0], nil +} + +// FirstIdX is like FirstId, but panics if an error occurs. +func (_q *OwnerQuery) FirstIdX(ctx context.Context) int { + id, err := _q.FirstId(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Owner entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Owner entity is found. +// Returns a *NotFoundError when no Owner entities are found. +func (_q *OwnerQuery) Only(ctx context.Context) (*Owner, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{owner.Label} + default: + return nil, &NotSingularError{owner.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *OwnerQuery) OnlyX(ctx context.Context) *Owner { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyId is like Only, but returns the only Owner Id in the query. +// Returns a *NotSingularError when more than one Owner Id is found. +// Returns a *NotFoundError when no entities are found. +func (_q *OwnerQuery) OnlyId(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(2).Ids(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyId)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{owner.Label} + default: + err = &NotSingularError{owner.Label} + } + return +} + +// OnlyIdX is like OnlyId, but panics if an error occurs. +func (_q *OwnerQuery) OnlyIdX(ctx context.Context) int { + id, err := _q.OnlyId(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Owner entities. +func (_q *OwnerQuery) All(ctx context.Context) ([]*Owner, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Owner, *OwnerQuery]() + return withInterceptors[[]*Owner](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *OwnerQuery) AllX(ctx context.Context) []*Owner { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// Ids executes the query and returns a list of Owner Ids. +func (_q *OwnerQuery) Ids(ctx context.Context) (ids []int, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIds) + if err = _q.Select(owner.FieldId).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IdsX is like Ids, but panics if an error occurs. +func (_q *OwnerQuery) IdsX(ctx context.Context) []int { + ids, err := _q.Ids(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *OwnerQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*OwnerQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *OwnerQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *OwnerQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstId(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *OwnerQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the OwnerQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *OwnerQuery) Clone() *OwnerQuery { + if _q == nil { + return nil + } + return &OwnerQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]owner.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Owner{}, _q.predicates...), + withEdge: _q.withEdge.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + modifiers: append([]func(*sql.Selector){}, _q.modifiers...), + } +} + +// WithEdge tells the query-builder to eager-load the nodes that are connected to +// the "edge" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *OwnerQuery) WithEdge(opts ...func(*ItemQuery)) *OwnerQuery { + query := (&ItemClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withEdge = query + return _q +} + +// 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 { +// Field int `json:"field,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Owner.Query(). +// GroupBy(owner.FieldField). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *OwnerQuery) GroupBy(field string, fields ...string) *OwnerGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &OwnerGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = owner.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// 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 { +// Field int `json:"field,omitempty"` +// } +// +// client.Owner.Query(). +// Select(owner.FieldField). +// Scan(ctx, &v) +func (_q *OwnerQuery) Select(fields ...string) *OwnerSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &OwnerSelect{OwnerQuery: _q} + sbuild.label = owner.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a OwnerSelect configured with the given aggregations. +func (_q *OwnerQuery) Aggregate(fns ...AggregateFunc) *OwnerSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *OwnerQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !owner.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *OwnerQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Owner, error) { + var ( + nodes = []*Owner{} + withFKs = _q.withFKs + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withEdge != nil, + } + ) + if _q.withEdge != nil { + withFKs = true + } + if withFKs { + _spec.Node.Columns = append(_spec.Node.Columns, owner.ForeignKeys...) + } + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Owner).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Owner{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withEdge; query != nil { + if err := _q.loadEdge(ctx, query, nodes, nil, + func(n *Owner, e *Item) { n.Edges.Edge = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *OwnerQuery) loadEdge(ctx context.Context, query *ItemQuery, nodes []*Owner, init func(*Owner), assign func(*Owner, *Item)) error { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*Owner) + for i := range nodes { + if nodes[i].owner_edge == nil { + continue + } + fk := *nodes[i].owner_edge + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(item.IdIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.Id] + if !ok { + return fmt.Errorf(`unexpected foreign-key "owner_edge" returned %v`, n.Id) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *OwnerQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *OwnerQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(owner.Table, owner.Columns, sqlgraph.NewFieldSpec(owner.FieldId, field.TypeInt)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, owner.FieldId) + for i := range fields { + if fields[i] != owner.FieldId { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *OwnerQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(owner.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = owner.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.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 := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_q *OwnerQuery) Modify(modifiers ...func(s *sql.Selector)) *OwnerSelect { + _q.modifiers = append(_q.modifiers, modifiers...) + return _q.Select() +} + +// OwnerGroupBy is the group-by builder for Owner entities. +type OwnerGroupBy struct { + selector + build *OwnerQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *OwnerGroupBy) Aggregate(fns ...AggregateFunc) *OwnerGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *OwnerGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*OwnerQuery, *OwnerGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *OwnerGroupBy) sqlScan(ctx context.Context, root *OwnerQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// OwnerSelect is the builder for selecting fields of Owner entities. +type OwnerSelect struct { + *OwnerQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *OwnerSelect) Aggregate(fns ...AggregateFunc) *OwnerSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *OwnerSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*OwnerQuery, *OwnerSelect](ctx, _s.OwnerQuery, _s, _s.inters, v) +} + +func (_s *OwnerSelect) sqlScan(ctx context.Context, root *OwnerQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_s *OwnerSelect) Modify(modifiers ...func(s *sql.Selector)) *OwnerSelect { + _s.modifiers = append(_s.modifiers, modifiers...) + return _s +} diff --git a/entc/integration/fieldnames/ent/owner_update.go b/entc/integration/fieldnames/ent/owner_update.go new file mode 100644 index 0000000000..a4988707d8 --- /dev/null +++ b/entc/integration/fieldnames/ent/owner_update.go @@ -0,0 +1,394 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "github.com/protobuf-orm/ent/dialect/sql" + "github.com/protobuf-orm/ent/dialect/sql/sqlgraph" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/item" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/owner" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/predicate" + "github.com/protobuf-orm/ent/schema/field" +) + +// OwnerUpdate is the builder for updating Owner entities. +type OwnerUpdate struct { + config + hooks []Hook + mutation *OwnerMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the OwnerUpdate builder. +func (_u *OwnerUpdate) Where(ps ...predicate.Owner) *OwnerUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetField sets the "field" field. +func (_u *OwnerUpdate) SetField(v int) *OwnerUpdate { + _u.mutation.ResetFieldField() + _u.mutation.SetFieldField(v) + return _u +} + +// AddFieldField adds value to the "field" field. +func (_u *OwnerUpdate) AddFieldField(v int) *OwnerUpdate { + _u.mutation.AddFieldField(v) + return _u +} + +// ClearField clears the value of the "field" field. +func (_u *OwnerUpdate) ClearField() *OwnerUpdate { + _u.mutation.ClearFieldField() + return _u +} + +// SetEdgeId sets the "edge" edge to the Item entity by Id. +func (_u *OwnerUpdate) SetEdgeId(id int) *OwnerUpdate { + _u.mutation.SetEdgeId(id) + return _u +} + +// SetEdge sets the "edge" edge to the Item entity. +func (_u *OwnerUpdate) SetEdge(v *Item) *OwnerUpdate { + return _u.SetEdgeId(v.Id) +} + +// Mutation returns the OwnerMutation object of the builder. +func (_u *OwnerUpdate) Mutation() *OwnerMutation { + return _u.mutation +} + +// ClearEdgeEdge clears the "edge" edge to the Item entity. +func (_u *OwnerUpdate) ClearEdgeEdge() *OwnerUpdate { + _u.mutation.ClearEdgeEdge() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *OwnerUpdate) Save(ctx context.Context) (int, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *OwnerUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *OwnerUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *OwnerUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *OwnerUpdate) defaults() { + if _, ok := _u.mutation.GetField(); !ok && !_u.mutation.FieldFieldCleared() { + if _, ok := _u.mutation.FieldExpr(owner.FieldField); !ok { + v := owner.UpdateDefaultField() + _u.mutation.SetFieldField(v) + } + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *OwnerUpdate) check() error { + if _u.mutation.EdgeEdgeCleared() && len(_u.mutation.EdgeIds()) > 0 { + return errors.New(`ent: clearing a required unique edge "Owner.edge"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *OwnerUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *OwnerUpdate { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *OwnerUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(owner.Table, owner.Columns, sqlgraph.NewFieldSpec(owner.FieldId, field.TypeInt)) + if ps := _u.mutation.Predicates(); len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.GetField(); ok { + _spec.SetField(owner.FieldField, field.TypeInt, value) + } + if e, ok := _u.mutation.FieldExpr(owner.FieldField); ok { + _spec.SetField(owner.FieldField, field.TypeInt, e) + } + if value, ok := _u.mutation.AddedFieldField(); ok { + _spec.AddField(owner.FieldField, field.TypeInt, value) + } + if _u.mutation.FieldFieldCleared() { + _spec.ClearField(owner.FieldField, field.TypeInt) + } + if _u.mutation.EdgeEdgeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: owner.EdgeTable, + Columns: []string{owner.EdgeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IdSpec: sqlgraph.NewFieldSpec(item.FieldId, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.EdgeIds(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: owner.EdgeTable, + Columns: []string{owner.EdgeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IdSpec: sqlgraph.NewFieldSpec(item.FieldId, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{owner.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// OwnerUpdateOne is the builder for updating a single Owner entity. +type OwnerUpdateOne struct { + config + fields []string + hooks []Hook + mutation *OwnerMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetField sets the "field" field. +func (_u *OwnerUpdateOne) SetField(v int) *OwnerUpdateOne { + _u.mutation.ResetFieldField() + _u.mutation.SetFieldField(v) + return _u +} + +// AddFieldField adds value to the "field" field. +func (_u *OwnerUpdateOne) AddFieldField(v int) *OwnerUpdateOne { + _u.mutation.AddFieldField(v) + return _u +} + +// ClearField clears the value of the "field" field. +func (_u *OwnerUpdateOne) ClearField() *OwnerUpdateOne { + _u.mutation.ClearFieldField() + return _u +} + +// SetEdgeId sets the "edge" edge to the Item entity by Id. +func (_u *OwnerUpdateOne) SetEdgeId(id int) *OwnerUpdateOne { + _u.mutation.SetEdgeId(id) + return _u +} + +// SetEdge sets the "edge" edge to the Item entity. +func (_u *OwnerUpdateOne) SetEdge(v *Item) *OwnerUpdateOne { + return _u.SetEdgeId(v.Id) +} + +// Mutation returns the OwnerMutation object of the builder. +func (_u *OwnerUpdateOne) Mutation() *OwnerMutation { + return _u.mutation +} + +// ClearEdgeEdge clears the "edge" edge to the Item entity. +func (_u *OwnerUpdateOne) ClearEdgeEdge() *OwnerUpdateOne { + _u.mutation.ClearEdgeEdge() + return _u +} + +// Where appends a list predicates to the OwnerUpdate builder. +func (_u *OwnerUpdateOne) Where(ps ...predicate.Owner) *OwnerUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *OwnerUpdateOne) Select(field string, fields ...string) *OwnerUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Owner entity. +func (_u *OwnerUpdateOne) Save(ctx context.Context) (*Owner, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *OwnerUpdateOne) SaveX(ctx context.Context) *Owner { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *OwnerUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *OwnerUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *OwnerUpdateOne) defaults() { + if _, ok := _u.mutation.GetField(); !ok && !_u.mutation.FieldFieldCleared() { + if _, ok := _u.mutation.FieldExpr(owner.FieldField); !ok { + v := owner.UpdateDefaultField() + _u.mutation.SetFieldField(v) + } + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *OwnerUpdateOne) check() error { + if _u.mutation.EdgeEdgeCleared() && len(_u.mutation.EdgeIds()) > 0 { + return errors.New(`ent: clearing a required unique edge "Owner.edge"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *OwnerUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *OwnerUpdateOne { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *OwnerUpdateOne) sqlSave(ctx context.Context) (_node *Owner, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(owner.Table, owner.Columns, sqlgraph.NewFieldSpec(owner.FieldId, field.TypeInt)) + id, ok := _u.mutation.Id() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Owner.id" for update`)} + } + _spec.Node.Id.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, owner.FieldId) + for _, f := range fields { + if !owner.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != owner.FieldId { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.Predicates(); len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.GetField(); ok { + _spec.SetField(owner.FieldField, field.TypeInt, value) + } + if e, ok := _u.mutation.FieldExpr(owner.FieldField); ok { + _spec.SetField(owner.FieldField, field.TypeInt, e) + } + if value, ok := _u.mutation.AddedFieldField(); ok { + _spec.AddField(owner.FieldField, field.TypeInt, value) + } + if _u.mutation.FieldFieldCleared() { + _spec.ClearField(owner.FieldField, field.TypeInt) + } + if _u.mutation.EdgeEdgeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: owner.EdgeTable, + Columns: []string{owner.EdgeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IdSpec: sqlgraph.NewFieldSpec(item.FieldId, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.EdgeIds(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: owner.EdgeTable, + Columns: []string{owner.EdgeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IdSpec: sqlgraph.NewFieldSpec(item.FieldId, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + _node = &Owner{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{owner.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/entc/integration/fieldnames/ent/predicate/predicate.go b/entc/integration/fieldnames/ent/predicate/predicate.go new file mode 100644 index 0000000000..3316a101de --- /dev/null +++ b/entc/integration/fieldnames/ent/predicate/predicate.go @@ -0,0 +1,17 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package predicate + +import ( + "github.com/protobuf-orm/ent/dialect/sql" +) + +// Item is the predicate function for item builders. +type Item func(*sql.Selector) + +// Owner is the predicate function for owner builders. +type Owner func(*sql.Selector) diff --git a/entc/integration/fieldnames/ent/privacy/privacy.go b/entc/integration/fieldnames/ent/privacy/privacy.go new file mode 100644 index 0000000000..e06970295e --- /dev/null +++ b/entc/integration/fieldnames/ent/privacy/privacy.go @@ -0,0 +1,219 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package privacy + +import ( + "context" + + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent" + + "github.com/protobuf-orm/ent/entql" + "github.com/protobuf-orm/ent/privacy" +) + +var ( + // Allow may be returned by rules to indicate that the policy + // evaluation should terminate with allow decision. + Allow = privacy.Allow + + // Deny may be returned by rules to indicate that the policy + // evaluation should terminate with deny decision. + Deny = privacy.Deny + + // Skip may be returned by rules to indicate that the policy + // evaluation should continue to the next rule. + Skip = privacy.Skip +) + +// Allowf returns a formatted wrapped Allow decision. +func Allowf(format string, a ...any) error { + return privacy.Allowf(format, a...) +} + +// Denyf returns a formatted wrapped Deny decision. +func Denyf(format string, a ...any) error { + return privacy.Denyf(format, a...) +} + +// Skipf returns a formatted wrapped Skip decision. +func Skipf(format string, a ...any) error { + return privacy.Skipf(format, a...) +} + +// DecisionContext creates a new context from the given parent context with +// a policy decision attach to it. +func DecisionContext(parent context.Context, decision error) context.Context { + return privacy.DecisionContext(parent, decision) +} + +// DecisionFromContext retrieves the policy decision from the context. +func DecisionFromContext(ctx context.Context) (error, bool) { + return privacy.DecisionFromContext(ctx) +} + +type ( + // Policy groups query and mutation policies. + Policy = privacy.Policy + + // QueryRule defines the interface deciding whether a + // query is allowed and optionally modify it. + QueryRule = privacy.QueryRule + // QueryPolicy combines multiple query rules into a single policy. + QueryPolicy = privacy.QueryPolicy + + // MutationRule defines the interface which decides whether a + // mutation is allowed and optionally modifies it. + MutationRule = privacy.MutationRule + // MutationPolicy combines multiple mutation rules into a single policy. + MutationPolicy = privacy.MutationPolicy + // MutationRuleFunc type is an adapter which allows the use of + // ordinary functions as mutation rules. + MutationRuleFunc = privacy.MutationRuleFunc + + // QueryMutationRule is an interface which groups query and mutation rules. + QueryMutationRule = privacy.QueryMutationRule +) + +// QueryRuleFunc type is an adapter to allow the use of +// ordinary functions as query rules. +type QueryRuleFunc func(context.Context, ent.Query) error + +// Eval returns f(ctx, q). +func (f QueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error { + return f(ctx, q) +} + +// AlwaysAllowRule returns a rule that returns an allow decision. +func AlwaysAllowRule() QueryMutationRule { + return privacy.AlwaysAllowRule() +} + +// AlwaysDenyRule returns a rule that returns a deny decision. +func AlwaysDenyRule() QueryMutationRule { + return privacy.AlwaysDenyRule() +} + +// ContextQueryMutationRule creates a query/mutation rule from a context eval func. +func ContextQueryMutationRule(eval func(context.Context) error) QueryMutationRule { + return privacy.ContextQueryMutationRule(eval) +} + +// OnMutationOperation evaluates the given rule only on a given mutation operation. +func OnMutationOperation(rule MutationRule, op ent.Op) MutationRule { + return privacy.OnMutationOperation(rule, op) +} + +// DenyMutationOperationRule returns a rule denying specified mutation operation. +func DenyMutationOperationRule(op ent.Op) MutationRule { + rule := MutationRuleFunc(func(_ context.Context, m ent.Mutation) error { + return Denyf("ent/privacy: operation %s is not allowed", m.Op()) + }) + return OnMutationOperation(rule, op) +} + +// The ItemQueryRuleFunc type is an adapter to allow the use of ordinary +// functions as a query rule. +type ItemQueryRuleFunc func(context.Context, *ent.ItemQuery) error + +// EvalQuery return f(ctx, q). +func (f ItemQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error { + if q, ok := q.(*ent.ItemQuery); ok { + return f(ctx, q) + } + return Denyf("ent/privacy: unexpected query type %T, expect *ent.ItemQuery", q) +} + +// The ItemMutationRuleFunc type is an adapter to allow the use of ordinary +// functions as a mutation rule. +type ItemMutationRuleFunc func(context.Context, *ent.ItemMutation) error + +// EvalMutation calls f(ctx, m). +func (f ItemMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error { + if m, ok := m.(*ent.ItemMutation); ok { + return f(ctx, m) + } + return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.ItemMutation", m) +} + +// The OwnerQueryRuleFunc type is an adapter to allow the use of ordinary +// functions as a query rule. +type OwnerQueryRuleFunc func(context.Context, *ent.OwnerQuery) error + +// EvalQuery return f(ctx, q). +func (f OwnerQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error { + if q, ok := q.(*ent.OwnerQuery); ok { + return f(ctx, q) + } + return Denyf("ent/privacy: unexpected query type %T, expect *ent.OwnerQuery", q) +} + +// The OwnerMutationRuleFunc type is an adapter to allow the use of ordinary +// functions as a mutation rule. +type OwnerMutationRuleFunc func(context.Context, *ent.OwnerMutation) error + +// EvalMutation calls f(ctx, m). +func (f OwnerMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error { + if m, ok := m.(*ent.OwnerMutation); ok { + return f(ctx, m) + } + return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.OwnerMutation", m) +} + +type ( + // Filter is the interface that wraps the Where function + // for filtering nodes in queries and mutations. + Filter interface { + // Where applies a filter on the executed query/mutation. + Where(entql.P) + } + + // The FilterFunc type is an adapter that allows the use of ordinary + // functions as filters for query and mutation types. + FilterFunc func(context.Context, Filter) error +) + +// EvalQuery calls f(ctx, q) if the query implements the Filter interface, otherwise it is denied. +func (f FilterFunc) EvalQuery(ctx context.Context, q ent.Query) error { + fr, err := queryFilter(q) + if err != nil { + return err + } + return f(ctx, fr) +} + +// EvalMutation calls f(ctx, q) if the mutation implements the Filter interface, otherwise it is denied. +func (f FilterFunc) EvalMutation(ctx context.Context, m ent.Mutation) error { + fr, err := mutationFilter(m) + if err != nil { + return err + } + return f(ctx, fr) +} + +var _ QueryMutationRule = FilterFunc(nil) + +func queryFilter(q ent.Query) (Filter, error) { + switch q := q.(type) { + case *ent.ItemQuery: + return q.Filter(), nil + case *ent.OwnerQuery: + return q.Filter(), nil + default: + return nil, Denyf("ent/privacy: unexpected query type %T for query filter", q) + } +} + +func mutationFilter(m ent.Mutation) (Filter, error) { + switch m := m.(type) { + case *ent.ItemMutation: + return m.Filter(), nil + case *ent.OwnerMutation: + return m.Filter(), nil + default: + return nil, Denyf("ent/privacy: unexpected mutation type %T for mutation filter", m) + } +} diff --git a/entc/integration/fieldnames/ent/runtime.go b/entc/integration/fieldnames/ent/runtime.go new file mode 100644 index 0000000000..e4e2fc920f --- /dev/null +++ b/entc/integration/fieldnames/ent/runtime.go @@ -0,0 +1,24 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package ent + +import ( + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/owner" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/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() { + ownerFields := schema.Owner{}.Fields() + _ = ownerFields + // ownerDescField is the schema descriptor for field field. + ownerDescField := ownerFields[0].Descriptor() + // owner.UpdateDefaultField holds the default value on update for the field field. + owner.UpdateDefaultField = ownerDescField.UpdateDefault.(func() int) +} diff --git a/entc/integration/fieldnames/ent/runtime/runtime.go b/entc/integration/fieldnames/ent/runtime/runtime.go new file mode 100644 index 0000000000..a848332c87 --- /dev/null +++ b/entc/integration/fieldnames/ent/runtime/runtime.go @@ -0,0 +1,13 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package runtime + +// The schema-stitching logic is generated in github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/runtime.go + +const ( + Version = "v0.14.6" // Version of ent codegen. +) diff --git a/entc/integration/fieldnames/ent/schema/item.go b/entc/integration/fieldnames/ent/schema/item.go new file mode 100644 index 0000000000..ff692e94e0 --- /dev/null +++ b/entc/integration/fieldnames/ent/schema/item.go @@ -0,0 +1,37 @@ +// Copyright 2026 Seunghyun Hwang. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +package schema + +import ( + "github.com/protobuf-orm/ent" + "github.com/protobuf-orm/ent/schema/field" +) + +// Item has a field for each name whose own mutation methods would be methods +// every mutation already has: `field` is AddField, AddedField, ClearField, +// FieldCleared, ResetField, SetField and OldField of ent.Mutation; `fields` +// is AddedFields; `edge` ClearEdge, EdgeCleared and ResetEdge; `ids` AddedIds, +// and Ids of the ent package's mutation; and `where`, `op` and `type` are +// methods themselves. +// +// Each is numeric and optional, which gives it every method a field has: Add +// and Added for a number, Clear and Cleared for a column that may be NULL. And +// nillable, so that a row read back says whether it was cleared. +type Item struct { + ent.Schema +} + +// Fields of the Item. +func (Item) Fields() []ent.Field { + return []ent.Field{ + field.Int("field").Optional().Nillable(), + field.Int("fields").Optional().Nillable(), + field.Int("edge").Optional().Nillable(), + field.Int("ids").Optional().Nillable(), + field.Int("where").Optional().Nillable(), + field.Int("op").Optional().Nillable(), + field.Int("type").Optional().Nillable(), + } +} diff --git a/entc/integration/fieldnames/ent/schema/owner.go b/entc/integration/fieldnames/ent/schema/owner.go new file mode 100644 index 0000000000..d7fc2b3591 --- /dev/null +++ b/entc/integration/fieldnames/ent/schema/owner.go @@ -0,0 +1,33 @@ +// Copyright 2026 Seunghyun Hwang. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +package schema + +import ( + "github.com/protobuf-orm/ent" + "github.com/protobuf-orm/ent/schema/edge" + "github.com/protobuf-orm/ent/schema/field" +) + +// Owner has the two things an update builder asks the mutation about by name: +// whether a field with an update default was cleared, which for `field` is +// FieldCleared, and whether a required unique edge was, which for `edge` is +// EdgeCleared. +type Owner struct { + ent.Schema +} + +// Fields of the Owner. +func (Owner) Fields() []ent.Field { + return []ent.Field{ + field.Int("field").Optional().Nillable().UpdateDefault(func() int { return 1 }), + } +} + +// Edges of the Owner. +func (Owner) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("edge", Item.Type).Unique().Required(), + } +} diff --git a/entc/integration/fieldnames/ent/tx.go b/entc/integration/fieldnames/ent/tx.go new file mode 100644 index 0000000000..f188ea4e23 --- /dev/null +++ b/entc/integration/fieldnames/ent/tx.go @@ -0,0 +1,221 @@ +// Copyright 2026 Seunghyun Hwang. 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 ent, DO NOT EDIT. + +package ent + +import ( + "context" + "sync" + + "github.com/protobuf-orm/ent/dialect" +) + +// Tx is a transactional client that is created by calling Client.Tx(). +type Tx struct { + config + // Item is the client for interacting with the Item builders. + Item *ItemClient + // Owner is the client for interacting with the Owner builders. + Owner *OwnerClient + + // lazily loaded. + client *Client + clientOnce sync.Once + // 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 Commit 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(ctx 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() + }) + txDriver.mu.Lock() + hooks := append([]CommitHook(nil), txDriver.onCommit...) + txDriver.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) { + txDriver := tx.config.driver.(*txDriver) + txDriver.mu.Lock() + txDriver.onCommit = append(txDriver.onCommit, f) + txDriver.mu.Unlock() +} + +type ( + // Rollbacker is the interface that wraps the Rollback 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(ctx 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() + }) + txDriver.mu.Lock() + hooks := append([]RollbackHook(nil), txDriver.onRollback...) + txDriver.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) { + txDriver := tx.config.driver.(*txDriver) + txDriver.mu.Lock() + txDriver.onRollback = append(txDriver.onRollback, f) + txDriver.mu.Unlock() +} + +// 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.Item = NewItemClient(tx.config) + tx.Owner = NewOwnerClient(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: Item.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 + // completion hooks. + mu sync.Mutex + onCommit []CommitHook + onRollback []RollbackHook +} + +// 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 +} + +// InTx says this driver is a transaction, which is what [dialect.InTx] asks a +// driver through however many wrappers. +func (*txDriver) InTx() bool { return true } + +// 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 any) error { + return tx.tx.Exec(ctx, query, args, v) +} + +// Query calls tx.Query. +func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error { + return tx.tx.Query(ctx, query, args, v) +} + +var _ dialect.Driver = (*txDriver)(nil) diff --git a/entc/integration/fieldnames/fieldnames_test.go b/entc/integration/fieldnames/fieldnames_test.go new file mode 100644 index 0000000000..5f6274847f --- /dev/null +++ b/entc/integration/fieldnames/fieldnames_test.go @@ -0,0 +1,207 @@ +// Copyright 2026 Seunghyun Hwang. 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 fieldnames holds a schema whose fields are named after the methods +// every mutation has, and what each engine says of the client it generates: +// that it compiles, which it did not, and that the mutation's methods that +// take a field by its name -- the ones a hook or a privacy rule calls -- reach +// that field's own, whatever they had to be renamed to. +package fieldnames + +import ( + "context" + "fmt" + "testing" + + "github.com/protobuf-orm/ent/dialect" + "github.com/protobuf-orm/ent/dialect/sql" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent" + "github.com/protobuf-orm/ent/entc/integration/fieldnames/ent/item" + + _ "github.com/go-sql-driver/mysql" + _ "github.com/lib/pq" + _ "github.com/ncruces/go-sqlite3/driver" + "github.com/stretchr/testify/require" +) + +func TestSQLite(t *testing.T) { + drv, err := sql.Open(dialect.SQLite, "file:"+t.TempDir()+"/db.sqlite?_pragma=foreign_keys(1)") + require.NoError(t, err) + defer drv.Close() + named(t, drv) +} + +func TestMySql(t *testing.T) { + for version, port := range map[string]int{"8": 3308, "84": 3309} { + t.Run(version, func(t *testing.T) { onMySql(t, port) }) + } +} + +func TestMaria(t *testing.T) { + for version, port := range map[string]int{"1011": 4309, "114": 4310} { + t.Run(version, func(t *testing.T) { onMySql(t, port) }) + } +} + +func onMySql(t *testing.T, port int) { + ctx := context.Background() + root, err := sql.Open(dialect.MySql, fmt.Sprintf("root:pass@tcp(localhost:%d)/", port)) + require.NoError(t, err) + defer root.Close() + require.NoError(t, root.Exec(ctx, "DROP DATABASE IF EXISTS fieldnames", []any{}, nil)) + require.NoError(t, root.Exec(ctx, "CREATE DATABASE fieldnames", []any{}, nil)) + defer root.Exec(ctx, "DROP DATABASE IF EXISTS fieldnames", []any{}, nil) + + drv, err := sql.Open(dialect.MySql, fmt.Sprintf("root:pass@tcp(localhost:%d)/fieldnames", port)) + require.NoError(t, err) + defer drv.Close() + named(t, drv) +} + +func TestPostgres(t *testing.T) { + for version, port := range map[string]int{"14": 5434, "17": 5437} { + t.Run(version, func(t *testing.T) { + ctx := context.Background() + dsn := fmt.Sprintf("host=localhost port=%d user=postgres password=pass sslmode=disable", port) + root, err := sql.Open(dialect.Postgres, dsn) + require.NoError(t, err) + defer root.Close() + require.NoError(t, root.Exec(ctx, "DROP DATABASE IF EXISTS fieldnames", []any{}, nil)) + require.NoError(t, root.Exec(ctx, "CREATE DATABASE fieldnames", []any{}, nil)) + defer root.Exec(ctx, "DROP DATABASE IF EXISTS fieldnames", []any{}, nil) + + drv, err := sql.Open(dialect.Postgres, dsn+" dbname=fieldnames") + require.NoError(t, err) + defer drv.Close() + named(t, drv) + }) + } +} + +// names are the Item's fields, in the order [values] reads them. +var names = []string{ + item.FieldField, item.FieldFields, item.FieldEdge, item.FieldIds, + item.FieldWhere, item.FieldOp, item.FieldType, +} + +func values(it *ent.Item) []*int { + return []*int{it.Field, it.Fields, it.Edge, it.Ids, it.Where, it.Op, it.Type} +} + +// holds is whether every field of the row is n, and nothing when n is nil. +func holds(t *testing.T, n *int, it *ent.Item) { + t.Helper() + for i, v := range values(it) { + require.Equal(t, n, v, names[i]) + } +} + +// named is the same things on every engine. +func named(t *testing.T, drv *sql.Driver) { + ctx := context.Background() + client := ent.NewClient(ent.Driver(drv)) + require.NoError(t, client.Schema.Create(ctx)) + + // create writes n to every field of a new row. + create := func(n int) *ent.Item { + return client.Item.Create(). + SetField(n).SetFields(n).SetEdge(n).SetIds(n).SetWhere(n).SetOp(n).SetType(n). + SaveX(ctx) + } + of := func(n int) *int { return &n } + + t.Run("a field is written, read, and filtered and ordered by", func(t *testing.T) { + a, b := create(1), create(2) + holds(t, of(2), b) + + got := client.Item.Query(). + Where(item.Field(2), item.Fields(2), item.Edge(2), item.Ids(2), item.Where(2), item.Op(2), item.Type(2)). + OnlyX(ctx) + require.Equal(t, b.Id, got.Id) + holds(t, of(2), got) + + for i, by := range []func(...sql.OrderTermOption) item.OrderOption{ + item.ByField, item.ByFields, item.ByEdge, item.ByIds, item.ByWhere, item.ByOp, item.ByType, + } { + ids := client.Item.Query().Where(item.IdIn(a.Id, b.Id)).Order(by(sql.OrderDesc())).IdsX(ctx) + require.Equal(t, []int{b.Id, a.Id}, ids, names[i]) + } + }) + + t.Run("an update adds to a field and clears it", func(t *testing.T) { + it := create(1) + holds(t, of(3), client.Item.UpdateOne(it). + AddFieldField(2).AddFields(2).AddEdge(2).AddIds(2).AddWhere(2).AddOp(2).AddType(2). + SaveX(ctx)) + holds(t, of(3), client.Item.GetX(ctx, it.Id)) + + n := client.Item.Update().Where(item.Id(it.Id)). + ClearField().ClearFields().ClearEdge().ClearIds().ClearWhere().ClearOp().ClearType(). + SaveX(ctx) + require.Equal(t, 1, n) + holds(t, nil, client.Item.Query().Where(item.Id(it.Id), item.FieldIsNil(), item.TypeIsNil()).OnlyX(ctx)) + }) + + t.Run("a hook reaches each field by its name", func(t *testing.T) { + // What the mutation answers, by name, after the hook did op to each: + // what was added, if anything was, and whether it was cleared. + type answer struct { + added any + cleared bool + } + var ( + op func(m ent.Mutation, name string) error + answers map[string]answer + ) + hooked := ent.NewClient(ent.Driver(drv)) + hooked.Item.Use(func(next ent.Mutator) ent.Mutator { + return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) { + answers = map[string]answer{} + for _, name := range names { + if err := op(m, name); err != nil { + return nil, err + } + added, ok := m.AddedField(name) + if !ok { + added = nil + } + answers[name] = answer{added, m.FieldCleared(name)} + } + return next.Mutate(ctx, m) + }) + }) + + it := create(1) + op = func(m ent.Mutation, name string) error { return m.AddField(name, 2) } + holds(t, of(3), hooked.Item.UpdateOne(it).SaveX(ctx)) + for _, name := range names { + require.Equal(t, answer{added: 2}, answers[name], name) + } + + op = func(m ent.Mutation, name string) error { return m.ClearField(name) } + holds(t, nil, hooked.Item.UpdateOne(it).SaveX(ctx)) + for _, name := range names { + require.Equal(t, answer{cleared: true}, answers[name], name) + } + + op = func(m ent.Mutation, name string) error { return m.SetField(name, 5) } + holds(t, of(5), hooked.Item.UpdateOne(it).SaveX(ctx)) + }) + + t.Run("an update asks whether what it fills or needs was cleared", func(t *testing.T) { + it := create(1) + o := client.Owner.Create().SetEdge(it).SaveX(ctx) + require.Nil(t, o.Field) + + // The update default fills `field`, unless the update clears it. + require.Equal(t, of(1), client.Owner.UpdateOne(o).SaveX(ctx).Field) + require.Nil(t, client.Owner.UpdateOne(o).ClearField().SaveX(ctx).Field) + + // The edge is required: an update may move it, and refuses to clear it. + moved := create(2) + require.Equal(t, moved.Id, client.Owner.UpdateOne(o).SetEdge(moved).SaveX(ctx).QueryEdge().OnlyIdX(ctx)) + _, err := client.Owner.UpdateOne(o).ClearEdgeEdge().SetEdge(it).Save(ctx) + require.ErrorContains(t, err, `clearing a required unique edge "Owner.edge"`) + }) +}