From 3221e28996256fc93b9bf9fdb3a0cd616b6d91b9 Mon Sep 17 00:00:00 2001 From: danilov6083 Date: Thu, 15 Jan 2026 21:16:42 +0300 Subject: [PATCH 01/13] dialect: added support for ydb retries --- dialect/sql/sqlgraph/graph.go | 163 +++++++++++++++++++++++++--------- dialect/sql/sqlgraph/retry.go | 57 ++++++++++++ dialect/ydb/driver.go | 17 +++- dialect/ydb/retry.go | 113 +++++++++++++++++++++++ entc/gen/storage.go | 2 +- 5 files changed, 308 insertions(+), 44 deletions(-) create mode 100644 dialect/sql/sqlgraph/retry.go create mode 100644 dialect/ydb/retry.go diff --git a/dialect/sql/sqlgraph/graph.go b/dialect/sql/sqlgraph/graph.go index c41c6b9ca0..9788bcd608 100644 --- a/dialect/sql/sqlgraph/graph.go +++ b/dialect/sql/sqlgraph/graph.go @@ -711,6 +711,8 @@ type ( // } // OnConflict []sql.ConflictOption + + RetryConfig RetryConfig } // BatchCreateSpec holds the information for creating @@ -728,6 +730,8 @@ type ( // } // OnConflict []sql.ConflictOption + + RetryConfig RetryConfig } ) @@ -748,16 +752,28 @@ func (u *CreateSpec) SetField(column string, t field.Type, value driver.Value) { // CreateNode applies the CreateSpec on the graph. The operation creates a new // record in the database, and connects it to other nodes specified in spec.Edges. func CreateNode(ctx context.Context, drv dialect.Driver, spec *CreateSpec) error { - gr := graph{tx: drv, builder: sql.Dialect(drv.Dialect())} - cr := &creator{CreateSpec: spec, graph: gr} - return cr.node(ctx, drv) + op := func(ctx context.Context, d dialect.Driver) error { + gr := graph{tx: d, builder: sql.Dialect(drv.Dialect())} + cr := &creator{CreateSpec: spec, graph: gr} + return cr.node(ctx, d) + } + if retry := getRetryExecutor(drv); retry != nil { + return retry.DoTx(ctx, op, spec.RetryConfig.Options...) + } + return op(ctx, drv) } // BatchCreate applies the BatchCreateSpec on the graph. func BatchCreate(ctx context.Context, drv dialect.Driver, spec *BatchCreateSpec) error { - gr := graph{tx: drv, builder: sql.Dialect(drv.Dialect())} - cr := &batchCreator{BatchCreateSpec: spec, graph: gr} - return cr.nodes(ctx, drv) + op := func(ctx context.Context, d dialect.Driver) error { + gr := graph{tx: d, builder: sql.Dialect(drv.Dialect())} + cr := &batchCreator{BatchCreateSpec: spec, graph: gr} + return cr.nodes(ctx, d) + } + if retry := getRetryExecutor(drv); retry != nil { + return retry.DoTx(ctx, op, spec.RetryConfig.Options...) + } + return op(ctx, drv) } type ( @@ -785,6 +801,8 @@ type ( ScanValues func(columns []string) ([]any, error) Assign func(columns []string, values []any) error + + RetryConfig RetryConfig } ) @@ -840,23 +858,47 @@ func (u *UpdateSpec) ClearField(column string, t field.Type) { // UpdateNode applies the UpdateSpec on one node in the graph. func UpdateNode(ctx context.Context, drv dialect.Driver, spec *UpdateSpec) error { - tx, err := drv.Tx(ctx) - if err != nil { - return err + op := func(ctx context.Context, d dialect.Driver) error { + tx, err := d.Tx(ctx) + if err != nil { + return err + } + gr := graph{tx: tx, builder: sql.Dialect(drv.Dialect())} + cr := &updater{UpdateSpec: spec, graph: gr} + if err := cr.node(ctx, tx); err != nil { + return rollback(tx, err) + } + return tx.Commit() } - gr := graph{tx: tx, builder: sql.Dialect(drv.Dialect())} - cr := &updater{UpdateSpec: spec, graph: gr} - if err := cr.node(ctx, tx); err != nil { - return rollback(tx, err) + if retry := getRetryExecutor(drv); retry != nil { + return retry.DoTx(ctx, op, spec.RetryConfig.Options...) } - return tx.Commit() + return op(ctx, drv) } // UpdateNodes applies the UpdateSpec on a set of nodes in the graph. func UpdateNodes(ctx context.Context, drv dialect.Driver, spec *UpdateSpec) (int, error) { - gr := graph{tx: drv, builder: sql.Dialect(drv.Dialect())} - cr := &updater{UpdateSpec: spec, graph: gr} - return cr.nodes(ctx, drv) + var affected int + op := func(ctx context.Context, d dialect.Driver) error { + gr := graph{tx: d, builder: sql.Dialect(drv.Dialect())} + cr := &updater{UpdateSpec: spec, graph: gr} + n, err := cr.nodes(ctx, d) + if err != nil { + return err + } + affected = n + return nil + } + if retry := getRetryExecutor(drv); retry != nil { + if err := retry.DoTx(ctx, op, spec.RetryConfig.Options...); err != nil { + return 0, err + } + return affected, nil + } + if err := op(ctx, drv); err != nil { + return 0, err + } + return affected, nil } // NotFoundError returns when trying to update an @@ -873,8 +915,9 @@ func (e *NotFoundError) Error() string { // DeleteSpec holds the information for delete one // or more nodes in the graph. type DeleteSpec struct { - Node *NodeSpec - Predicate func(*sql.Selector) + Node *NodeSpec + Predicate func(*sql.Selector) + RetryConfig RetryConfig } // NewDeleteSpec creates a new node deletion spec. @@ -884,25 +927,39 @@ func NewDeleteSpec(table string, id *FieldSpec) *DeleteSpec { // DeleteNodes applies the DeleteSpec on the graph. func DeleteNodes(ctx context.Context, drv dialect.Driver, spec *DeleteSpec) (int, error) { - var ( - res sql.Result - builder = sql.Dialect(drv.Dialect()) - ) - selector := builder.Select(). - From(builder.Table(spec.Node.Table).Schema(spec.Node.Schema)). - WithContext(ctx) - if pred := spec.Predicate; pred != nil { - pred(selector) + var affected int + op := func(ctx context.Context, d dialect.Driver) error { + var ( + res sql.Result + builder = sql.Dialect(drv.Dialect()) + ) + selector := builder.Select(). + From(builder.Table(spec.Node.Table).Schema(spec.Node.Schema)). + WithContext(ctx) + if pred := spec.Predicate; pred != nil { + pred(selector) + } + query, args := builder.Delete(spec.Node.Table).Schema(spec.Node.Schema).FromSelect(selector).Query() + if err := d.Exec(ctx, query, args, &res); err != nil { + return err + } + n, err := res.RowsAffected() + if err != nil { + return err + } + affected = int(n) + return nil } - query, args := builder.Delete(spec.Node.Table).Schema(spec.Node.Schema).FromSelect(selector).Query() - if err := drv.Exec(ctx, query, args, &res); err != nil { - return 0, err + if retry := getRetryExecutor(drv); retry != nil { + if err := retry.DoTx(ctx, op, spec.RetryConfig.Options...); err != nil { + return 0, err + } + return affected, nil } - affected, err := res.RowsAffected() - if err != nil { + if err := op(ctx, drv); err != nil { return 0, err } - return int(affected), nil + return affected, nil } // QuerySpec holds the information for querying @@ -920,6 +977,8 @@ type QuerySpec struct { ScanValues func(columns []string) ([]any, error) Assign func(columns []string, values []any) error + + RetryConfig RetryConfig } // NewQuerySpec creates a new node query spec. @@ -935,16 +994,40 @@ func NewQuerySpec(table string, columns []string, id *FieldSpec) *QuerySpec { // QueryNodes queries the nodes in the graph query and scans them to the given values. func QueryNodes(ctx context.Context, drv dialect.Driver, spec *QuerySpec) error { - builder := sql.Dialect(drv.Dialect()) - qr := &query{graph: graph{builder: builder}, QuerySpec: spec} - return qr.nodes(ctx, drv) + op := func(ctx context.Context, d dialect.Driver) error { + builder := sql.Dialect(drv.Dialect()) + qr := &query{graph: graph{builder: builder}, QuerySpec: spec} + return qr.nodes(ctx, d) + } + if retry := getRetryExecutor(drv); retry != nil { + return retry.Do(ctx, op, spec.RetryConfig.Options...) + } + return op(ctx, drv) } // CountNodes counts the nodes in the given graph query. func CountNodes(ctx context.Context, drv dialect.Driver, spec *QuerySpec) (int, error) { - builder := sql.Dialect(drv.Dialect()) - qr := &query{graph: graph{builder: builder}, QuerySpec: spec} - return qr.count(ctx, drv) + var count int + op := func(ctx context.Context, d dialect.Driver) error { + builder := sql.Dialect(drv.Dialect()) + qr := &query{graph: graph{builder: builder}, QuerySpec: spec} + n, err := qr.count(ctx, d) + if err != nil { + return err + } + count = n + return nil + } + if retry := getRetryExecutor(drv); retry != nil { + if err := retry.Do(ctx, op, spec.RetryConfig.Options...); err != nil { + return 0, err + } + return count, nil + } + if err := op(ctx, drv); err != nil { + return 0, err + } + return count, nil } // EdgeQuerySpec holds the information for querying diff --git a/dialect/sql/sqlgraph/retry.go b/dialect/sql/sqlgraph/retry.go new file mode 100644 index 0000000000..449e4dffbd --- /dev/null +++ b/dialect/sql/sqlgraph/retry.go @@ -0,0 +1,57 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +package sqlgraph + +import ( + "context" + + "entgo.io/ent/dialect" +) + +// RetryExecutor is an interface for database operations with automatic retries. +type RetryExecutor interface { + // Do executes the given function within a retry loop without a transaction. + // The function receives a dialect.Driver that wraps the connection. + // opts are driver-specific retry options (e.g., ydb retry.Option). + Do( + ctx context.Context, + fn func(ctx context.Context, drv dialect.Driver) error, + opts ...any, + ) error + + // DoTx executes the given function within a retry loop with a transaction. + // The function receives a dialect.Driver that wraps the database/sql.Tx transaction. + // opts are driver-specific retry options (e.g., ydb retry.Option). + DoTx( + ctx context.Context, + fn func(ctx context.Context, drv dialect.Driver) error, + opts ...any, + ) error +} + +// RetryExecutorGetter is an optional interface that drivers can implement to provide +// a RetryExecutor for automatic retry handling. +// If a driver implements this interface, +// sqlgraph operations will use the RetryExecutor for database operations. +type RetryExecutorGetter interface { + // RetryExecutor returns the RetryExecutor for this driver. + // If nil is returned, no retry handling will be applied. + RetryExecutor() RetryExecutor +} + +// getRetryExecutor returns the RetryExecutor for the given driver if available. +func getRetryExecutor(drv dialect.Driver) RetryExecutor { + if reg, ok := drv.(RetryExecutorGetter); ok { + return reg.RetryExecutor() + } + return nil +} + +// RetryConfig holds retry configuration for sqlgraph operations. +// This is used to pass retry options to the RetryExecutor. +type RetryConfig struct { + // Options are driver-specific retry options. + Options []any +} diff --git a/dialect/ydb/driver.go b/dialect/ydb/driver.go index 14c7e38418..390d74eccd 100644 --- a/dialect/ydb/driver.go +++ b/dialect/ydb/driver.go @@ -10,6 +10,7 @@ import ( "entgo.io/ent/dialect" entSql "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" ydb "github.com/ydb-platform/ydb-go-sdk/v3" ) @@ -17,9 +18,12 @@ import ( type YDBDriver struct { *entSql.Driver - nativeDriver *ydb.Driver + nativeDriver *ydb.Driver + retryExecutor *RetryExecutor } +var _ sqlgraph.RetryExecutorGetter = (*YDBDriver)(nil) + func Open(ctx context.Context, dsn string) (*YDBDriver, error) { nativeDriver, err := ydb.Open(ctx, dsn) if err != nil { @@ -38,11 +42,18 @@ func Open(ctx context.Context, dsn string) (*YDBDriver, error) { dbSQLDriver := sql.OpenDB(conn) return &YDBDriver{ - Driver: entSql.OpenDB(dialect.YDB, dbSQLDriver), - nativeDriver: nativeDriver, + Driver: entSql.OpenDB(dialect.YDB, dbSQLDriver), + nativeDriver: nativeDriver, + retryExecutor: NewRetryExecutor(dbSQLDriver), }, nil } func (y *YDBDriver) NativeDriver() *ydb.Driver { return y.nativeDriver } + +// RetryExecutor returns the RetryExecutor for this driver. +// This allows sqlgraph to automatically wrap operations with YDB retry logic. +func (y *YDBDriver) RetryExecutor() sqlgraph.RetryExecutor { + return y.retryExecutor +} diff --git a/dialect/ydb/retry.go b/dialect/ydb/retry.go new file mode 100644 index 0000000000..efe1a67f94 --- /dev/null +++ b/dialect/ydb/retry.go @@ -0,0 +1,113 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +package ydb + +import ( + "context" + "database/sql" + + "entgo.io/ent/dialect" + entSql "entgo.io/ent/dialect/sql" + "github.com/ydb-platform/ydb-go-sdk/v3/retry" +) + +// RetryExecutor implements sqlgraph.RetryExecutor for YDB +type RetryExecutor struct { + db *sql.DB +} + +// NewRetryExecutor creates a new RetryExecutor with the given database connection +func NewRetryExecutor(db *sql.DB) *RetryExecutor { + return &RetryExecutor{db: db} +} + +// DoTx executes the operation within a transaction with retry support. +// It uses ydb-go-sdk's retry.DoTx which handles YDB-specific retryable errors. +// Options should be created using retry.WithIdempotent(), retry.WithLabel(), etc. +func (r *RetryExecutor) DoTx( + ctx context.Context, + fn func(ctx context.Context, drv dialect.Driver) error, + opts ...any, +) error { + retryOpts := make([]retry.Option, 0, len(opts)) + for _, opt := range opts { + if ro, ok := opt.(retry.Option); ok { + retryOpts = append(retryOpts, ro) + } + } + + return retry.DoTx( + ctx, + r.db, + func(ctx context.Context, tx *sql.Tx) error { + return fn(ctx, NewTxRetryDriver(tx)) + }, + retry.WithDoTxRetryOptions(retryOpts...), + ) +} + +// Do executes a read-only operation with retry support. +// It uses ydb-go-sdk's retry.Do which handles YDB-specific retryable errors. +// Options should be created using retry.WithIdempotent(), retry.WithLabel(), etc. +func (r *RetryExecutor) Do( + ctx context.Context, + fn func(ctx context.Context, drv dialect.Driver) error, + opts ...any, +) error { + retryOpts := make([]retry.Option, 0, len(opts)) + for _, opt := range opts { + if ro, ok := opt.(retry.Option); ok { + retryOpts = append(retryOpts, ro) + } + } + + return retry.Do( + ctx, + r.db, + func(ctx context.Context, conn *sql.Conn) error { + return fn(ctx, NewRetryDriver(conn)) + }, + retry.WithDoRetryOptions(retryOpts...), + ) +} + +// RetryDriver is designed for use only in sqlgraph, +// specifically - in retry.DoTx callbacks +type RetryDriver struct { + entSql.Conn +} + +var _ dialect.Driver = (*RetryDriver)(nil) + +// NewTxRetryDriver creates a new RetryDriver from a transaction. +func NewTxRetryDriver(tx *sql.Tx) *RetryDriver { + return &RetryDriver{ + Conn: entSql.Conn{ExecQuerier: tx}, + } +} + +// NewRetryDriver creates a new RetryDriver from a database connection. +func NewRetryDriver(conn *sql.Conn) *RetryDriver { + return &RetryDriver{ + Conn: entSql.Conn{ExecQuerier: conn}, + } +} + +// sqlgraph creates nested transactions in several methods. +// But YDB doesnt support nested transactions. +// Therefore, this methods returns no-op tx +func (d *RetryDriver) Tx(ctx context.Context) (dialect.Tx, error) { + return dialect.NopTx(d), nil +} + +// Close is a no-op for TxDriver since retry.DoTx manages the transaction lifecycle. +func (d *RetryDriver) Close() error { + return nil +} + +// Dialect returns the YDB dialect name. +func (d *RetryDriver) Dialect() string { + return dialect.YDB +} diff --git a/entc/gen/storage.go b/entc/gen/storage.go index 9a01d683a9..bbf89356ad 100644 --- a/entc/gen/storage.go +++ b/entc/gen/storage.go @@ -54,7 +54,7 @@ var drivers = []*Storage{ Name: "sql", IdentName: "SQL", Builder: reflect.TypeOf(&sql.Selector{}), - Dialects: []string{"dialect.SQLite", "dialect.MySQL", "dialect.Postgres"}, + Dialects: []string{"dialect.SQLite", "dialect.MySQL", "dialect.Postgres", "dialect.YDB"}, Imports: []string{ "database/sql/driver", "entgo.io/ent/dialect/sql", From ed40b066e31afc640e72eebee6c185e412234b97 Mon Sep 17 00:00:00 2001 From: danilov6083 Date: Thu, 15 Jan 2026 22:22:11 +0300 Subject: [PATCH 02/13] entc/gen/template/dialect/sql/feature: added WithRetryOptions template --- entc/gen/feature.go | 10 ++ entc/gen/template/builder/delete.tmpl | 5 + entc/gen/template/dialect/sql/delete.tmpl | 16 ++ .../dialect/sql/feature/retryoptions.tmpl | 155 ++++++++++++++++++ 4 files changed, 186 insertions(+) create mode 100644 entc/gen/template/dialect/sql/feature/retryoptions.tmpl diff --git a/entc/gen/feature.go b/entc/gen/feature.go index 1b0c37e4f9..344142a7a5 100644 --- a/entc/gen/feature.go +++ b/entc/gen/feature.go @@ -159,6 +159,15 @@ var ( }, } + // FeatureRetryOptions provides a feature-flag for adding retry options to query/mutation builders. + // This is primarily useful for databases like YDB that require explicit retry handling. + FeatureRetryOptions = Feature{ + Name: "sql/retryoptions", + Stage: Experimental, + Default: false, + Description: "Adds WithRetryOptions methods to builders for databases that require explicit retry handling (e.g., YDB)", + } + // AllFeatures holds a list of all feature-flags. AllFeatures = []Feature{ FeaturePrivacy, @@ -174,6 +183,7 @@ var ( FeatureUpsert, FeatureVersionedMigration, FeatureGlobalID, + FeatureRetryOptions, } // allFeatures includes all public and private features. allFeatures = append(AllFeatures, featureMultiSchema) diff --git a/entc/gen/template/builder/delete.tmpl b/entc/gen/template/builder/delete.tmpl index 513f2b502b..c1ad612fef 100644 --- a/entc/gen/template/builder/delete.tmpl +++ b/entc/gen/template/builder/delete.tmpl @@ -26,6 +26,11 @@ type {{ $builder }} struct { config hooks []Hook mutation *{{ $.MutationName }} + {{- /* Additional fields to add to the builder. */}} + {{- $tmpl := printf "dialect/%s/delete/fields" $.Storage }} + {{- if hasTemplate $tmpl }} + {{- xtemplate $tmpl . }} + {{- end }} } // Where appends a list predicates to the {{ $builder }} builder. diff --git a/entc/gen/template/dialect/sql/delete.tmpl b/entc/gen/template/dialect/sql/delete.tmpl index 9e007d256f..be9db4511d 100644 --- a/entc/gen/template/dialect/sql/delete.tmpl +++ b/entc/gen/template/dialect/sql/delete.tmpl @@ -34,4 +34,20 @@ func ({{ $receiver}} *{{ $builder }}) sqlExec(ctx context.Context) (int, error) return affected, err } +{{- /* Allow adding methods to the delete builder by ent extensions or user templates.*/}} +{{- with $tmpls := matchTemplate "dialect/sql/delete/additional/*" }} + {{- range $tmpl := $tmpls }} + {{- xtemplate $tmpl $ }} + {{- end }} +{{- end }} + {{ end }} + +{{/* Additional fields for the delete builder. */}} +{{ define "dialect/sql/delete/fields" }} + {{- with $tmpls := matchTemplate "dialect/sql/delete/fields/additional/*" }} + {{- range $tmpl := $tmpls }} + {{- xtemplate $tmpl $ }} + {{- end }} + {{- end }} +{{- end }} diff --git a/entc/gen/template/dialect/sql/feature/retryoptions.tmpl b/entc/gen/template/dialect/sql/feature/retryoptions.tmpl new file mode 100644 index 0000000000..fa066279da --- /dev/null +++ b/entc/gen/template/dialect/sql/feature/retryoptions.tmpl @@ -0,0 +1,155 @@ +{{/* +Copyright 2019-present Facebook Inc. All rights reserved. +This source code is licensed under the Apache 2.0 license found +in the LICENSE file in the root directory of this source tree. +*/}} + +{{/* gotype: entgo.io/ent/entc/gen.Type */}} + +{{/* Templates used by the "sql/retryoptions" feature-flag to add retry options to query/mutation builders. + This is primarily useful for databases like YDB that require explicit retry handling. */}} + +{{/* Additional fields for the create builder. */}} +{{ define "dialect/sql/create/fields/additional/retryoptions" -}} + {{- if $.FeatureEnabled "sql/retryoptions" }} + retryConfig sqlgraph.RetryConfig + {{- end }} +{{- end }} + +{{/* Additional fields for the create_bulk builder. */}} +{{ define "dialect/sql/create_bulk/fields/additional/retryoptions" -}} + {{- if $.FeatureEnabled "sql/retryoptions" }} + retryConfig sqlgraph.RetryConfig + {{- end }} +{{- end }} + +{{/* Additional fields for the update builder. */}} +{{ define "dialect/sql/update/fields/additional/retryoptions" -}} + {{- if $.FeatureEnabled "sql/retryoptions" }} + retryConfig sqlgraph.RetryConfig + {{- end }} +{{- end }} + +{{/* Additional fields for the query builder. */}} +{{ define "dialect/sql/query/fields/additional/retryoptions" -}} + {{- if $.FeatureEnabled "sql/retryoptions" }} + retryConfig sqlgraph.RetryConfig + {{- end }} +{{- end }} + +{{/* Additional fields for the delete builder. */}} +{{ define "dialect/sql/delete/fields/additional/retryoptions" -}} + {{- if $.FeatureEnabled "sql/retryoptions" }} + retryConfig sqlgraph.RetryConfig + {{- end }} +{{- end }} + +{{/* WithRetryOptions method for create builder. */}} +{{ define "dialect/sql/create/additional/retryoptions" }} +{{- if $.FeatureEnabled "sql/retryoptions" }} +{{ $builder := pascal $.Scope.Builder }} +{{ $receiver := $.Scope.Receiver }} + +// WithRetryOptions sets the retry options for the create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func ({{ $receiver }} *{{ $builder }}) WithRetryOptions(opts ...any) *{{ $builder }} { + {{ $receiver }}.retryConfig.Options = opts + return {{ $receiver }} +} +{{- end }} +{{- end }} + +{{/* WithRetryOptions method for create_bulk builder. */}} +{{ define "dialect/sql/create_bulk/additional/retryoptions" }} +{{- if $.FeatureEnabled "sql/retryoptions" }} +{{ $builder := pascal $.Scope.Builder }} +{{ $receiver := $.Scope.Receiver }} + +// WithRetryOptions sets the retry options for the bulk create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func ({{ $receiver }} *{{ $builder }}) WithRetryOptions(opts ...any) *{{ $builder }} { + {{ $receiver }}.retryConfig.Options = opts + return {{ $receiver }} +} +{{- end }} +{{- end }} + +{{/* WithRetryOptions method for update builder. */}} +{{ define "dialect/sql/update/additional/retryoptions" }} +{{- if $.FeatureEnabled "sql/retryoptions" }} +{{ $builder := pascal $.Scope.Builder }} +{{ $receiver := $.Scope.Receiver }} + +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func ({{ $receiver }} *{{ $builder }}) WithRetryOptions(opts ...any) *{{ $builder }} { + {{ $receiver }}.retryConfig.Options = opts + return {{ $receiver }} +} +{{- end }} +{{- end }} + +{{/* WithRetryOptions method for query builder. */}} +{{ define "dialect/sql/query/additional/retryoptions" }} +{{- if $.FeatureEnabled "sql/retryoptions" }} +{{ $builder := pascal $.Scope.Builder }} +{{ $receiver := $.Scope.Receiver }} + +// WithRetryOptions sets the retry options for the query operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func ({{ $receiver }} *{{ $builder }}) WithRetryOptions(opts ...any) *{{ $builder }} { + {{ $receiver }}.retryConfig.Options = opts + return {{ $receiver }} +} +{{- end }} +{{- end }} + +{{/* WithRetryOptions method for delete builder. */}} +{{ define "dialect/sql/delete/additional/retryoptions" }} +{{- if $.FeatureEnabled "sql/retryoptions" }} +{{ $builder := pascal $.Scope.Builder }} +{{ $receiver := $.Scope.Receiver }} + +// WithRetryOptions sets the retry options for the delete operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func ({{ $receiver }} *{{ $builder }}) WithRetryOptions(opts ...any) *{{ $builder }} { + {{ $receiver }}.retryConfig.Options = opts + return {{ $receiver }} +} +{{- end }} +{{- end }} + +{{/* Pass retry options to CreateSpec. */}} +{{ define "dialect/sql/create/spec/retryoptions" -}} + {{- if $.FeatureEnabled "sql/retryoptions" }} + _spec.RetryConfig = {{ $.Scope.Receiver }}.retryConfig + {{- end }} +{{- end }} + +{{/* Pass retry options to BatchCreateSpec. */}} +{{ define "dialect/sql/create_bulk/spec/retryoptions" -}} + {{- if $.FeatureEnabled "sql/retryoptions" }} + spec.RetryConfig = {{ $.Scope.Receiver }}.retryConfig + {{- end }} +{{- end }} + +{{/* Pass retry options to UpdateSpec. */}} +{{ define "dialect/sql/update/spec/retryoptions" -}} + {{- if $.FeatureEnabled "sql/retryoptions" }} + _spec.RetryConfig = {{ $.Scope.Receiver }}.retryConfig + {{- end }} +{{- end }} + +{{/* Pass retry options to QuerySpec. */}} +{{ define "dialect/sql/query/spec/retryoptions" -}} + {{- if $.FeatureEnabled "sql/retryoptions" }} + _spec.RetryConfig = {{ $.Scope.Receiver }}.retryConfig + {{- end }} +{{- end }} + +{{/* Pass retry options to DeleteSpec. */}} +{{ define "dialect/sql/delete/spec/retryoptions" -}} + {{- if $.FeatureEnabled "sql/retryoptions" }} + _spec.RetryConfig = {{ $.Scope.Receiver }}.retryConfig + {{- end }} +{{- end }} From 0cd4d75ad3cc051728cdc16d8d0a347e34374d0e Mon Sep 17 00:00:00 2001 From: danilov6083 Date: Sun, 1 Feb 2026 21:43:08 +0300 Subject: [PATCH 03/13] dialect/sql/schema: fixed several schema create bugs --- dialect/sql/schema/atlas.go | 81 +++++++++++++++++++++++++++---------- dialect/sql/schema/ydb.go | 26 ++++++++---- entc/gen/storage.go | 1 + entc/integration/go.mod | 2 +- entc/integration/go.sum | 4 +- examples/go.mod | 2 +- examples/go.sum | 4 +- go.mod | 2 +- go.sum | 4 +- 9 files changed, 89 insertions(+), 37 deletions(-) diff --git a/dialect/sql/schema/atlas.go b/dialect/sql/schema/atlas.go index af72e56b83..8a738ff676 100644 --- a/dialect/sql/schema/atlas.go +++ b/dialect/sql/schema/atlas.go @@ -24,6 +24,7 @@ import ( "entgo.io/ent/dialect" entsql "entgo.io/ent/dialect/sql" "entgo.io/ent/schema/field" + "github.com/ydb-platform/ydb-go-sdk/v3" ) // Atlas atlas migration engine. @@ -626,35 +627,73 @@ func (a *Atlas) create(ctx context.Context, tables ...*Table) (err error) { if len(plan.Changes) == 0 { return nil } - // Open a transaction for backwards compatibility, - // even if the migration is not transactional. - tx, err := a.sqlDialect.Tx(ctx) - if err != nil { - return err - } - a.atDriver, err = a.sqlDialect.atOpen(tx) - if err != nil { - return err - } - // Apply plan (changes). - var applier Applier = ApplyFunc(func(ctx context.Context, tx dialect.ExecQuerier, plan *migrate.Plan) error { - for _, c := range plan.Changes { - if err := tx.Exec(ctx, c.Cmd, c.Args, nil); err != nil { - if c.Comment != "" { - err = fmt.Errorf("%s: %w", c.Comment, err) + + // YDB requires DDL operations to be executed outside of transactions. + if a.sqlDialect.Dialect() == dialect.YDB { + applier := ApplyFunc(func(ctx context.Context, conn dialect.ExecQuerier, plan *migrate.Plan) error { + for _, change := range plan.Changes { + err := conn.Exec( + ydb.WithQueryMode(ctx, ydb.SchemeQueryMode), + change.Cmd, + change.Args, + nil, + ) + if err != nil { + return wrapChangeError(change, err) } - return err } + return nil + }) + if err := a.applyWithHooks(ctx, a.sqlDialect, plan, applier); err != nil { + return fmt.Errorf("sql/schema: %w", err) } return nil - }) + } else { + // Open a transaction for backwards compatibility, + // even if the migration is not transactional. + tx, err := a.sqlDialect.Tx(ctx) + if err != nil { + return err + } + a.atDriver, err = a.sqlDialect.atOpen(tx) + if err != nil { + return err + } + applier := ApplyFunc(func(ctx context.Context, conn dialect.ExecQuerier, plan *migrate.Plan) error { + for _, change := range plan.Changes { + if err := conn.Exec(ctx, change.Cmd, change.Args, nil); err != nil { + return wrapChangeError(change, err) + } + } + return nil + }) + if err := a.applyWithHooks(ctx, tx, plan, applier); err != nil { + return errors.Join(fmt.Errorf("sql/schema: %w", err), tx.Rollback()) + } + return tx.Commit() + } +} + +// applyWithHooks wraps the given applier with the configured apply hooks and executes it. +func (a *Atlas) applyWithHooks( + ctx context.Context, + conn dialect.ExecQuerier, + plan *migrate.Plan, + base Applier, +) error { + applier := base for i := len(a.applyHook) - 1; i >= 0; i-- { applier = a.applyHook[i](applier) } - if err = applier.Apply(ctx, tx, plan); err != nil { - return errors.Join(fmt.Errorf("sql/schema: %w", err), tx.Rollback()) + return applier.Apply(ctx, conn, plan) +} + +// wrapChangeError wraps an error with the change comment if present. +func wrapChangeError(c *migrate.Change, err error) error { + if c.Comment != "" { + return fmt.Errorf("%s: %w", c.Comment, err) } - return tx.Commit() + return err } // For BC reason, we omit the schema qualifier from the migration plan. diff --git a/dialect/sql/schema/ydb.go b/dialect/sql/schema/ydb.go index 94b1a0a064..cc64216537 100644 --- a/dialect/sql/schema/ydb.go +++ b/dialect/sql/schema/ydb.go @@ -6,14 +6,13 @@ package schema import ( "context" - "database/sql" "errors" "fmt" "strings" "entgo.io/ent/dialect" entsql "entgo.io/ent/dialect/sql" - entdriver "entgo.io/ent/dialect/ydb" + entdrv "entgo.io/ent/dialect/ydb" "entgo.io/ent/schema/field" "ariga.io/atlas/sql/migrate" @@ -34,8 +33,8 @@ func (d *YDB) init(ctx context.Context) error { return nil // already initialized. } - rows := &sql.Rows{} - if err := d.Driver.Query(ctx, "SELECT version()", nil, rows); err != nil { + rows := &entsql.Rows{} + if err := d.Driver.Query(ctx, "SELECT version()", []any{}, rows); err != nil { return fmt.Errorf("ydb: failed to query version: %w", err) } defer rows.Close() @@ -69,9 +68,22 @@ func (d *YDB) tableExist(ctx context.Context, conn dialect.ExecQuerier, name str // atOpen returns a custom Atlas migrate.Driver for YDB. func (d *YDB) atOpen(conn dialect.ExecQuerier) (migrate.Driver, error) { - ydbDriver, ok := conn.(*entdriver.YDBDriver) - if !ok { - return nil, fmt.Errorf("expected dialect/ydb.YDBDriver, but got %T", conn) + var ydbDriver *entdrv.YDBDriver + + switch drv := conn.(type) { + case *entdrv.YDBDriver: + ydbDriver = drv + case *YDB: + if ydb, ok := drv.Driver.(*entdrv.YDBDriver); ok { + ydbDriver = ydb + } + } + if ydbDriver == nil { + if ydb, ok := d.Driver.(*entdrv.YDBDriver); ok { + ydbDriver = ydb + } else { + return nil, fmt.Errorf("expected dialect/ydb.YDBDriver, but got %T", conn) + } } return atlas.Open( diff --git a/entc/gen/storage.go b/entc/gen/storage.go index bbf89356ad..6fcde470fa 100644 --- a/entc/gen/storage.go +++ b/entc/gen/storage.go @@ -60,6 +60,7 @@ var drivers = []*Storage{ "entgo.io/ent/dialect/sql", "entgo.io/ent/dialect/sql/sqlgraph", "entgo.io/ent/dialect/sql/sqljson", + "entgo.io/ent/dialect/ydb", "entgo.io/ent/schema/field", }, SchemaMode: Unique | Indexes | Cascade | Migrate, diff --git a/entc/integration/go.mod b/entc/integration/go.mod index 1e73a8cb46..30553da709 100644 --- a/entc/integration/go.mod +++ b/entc/integration/go.mod @@ -37,7 +37,7 @@ require ( github.com/rogpeppe/go-internal v1.11.0 // indirect github.com/stretchr/objx v0.5.2 // indirect github.com/ydb-platform/ydb-go-genproto v0.0.0-20251222105147-0bf751469a4a // indirect - github.com/ydb-platform/ydb-go-sdk/v3 v3.125.0 // indirect + github.com/ydb-platform/ydb-go-sdk/v3 v3.125.4 // indirect github.com/zclconf/go-cty v1.14.4 // indirect github.com/zclconf/go-cty-yaml v1.1.0 // indirect golang.org/x/mod v0.30.0 // indirect diff --git a/entc/integration/go.sum b/entc/integration/go.sum index 7a58fa2697..980501e17b 100644 --- a/entc/integration/go.sum +++ b/entc/integration/go.sum @@ -123,8 +123,8 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/ydb-platform/ydb-go-genproto v0.0.0-20251222105147-0bf751469a4a h1:nRqONRrMFulP2bTWM2RRnPM1VDhWuBZg4ULXkG4xXdk= github.com/ydb-platform/ydb-go-genproto v0.0.0-20251222105147-0bf751469a4a/go.mod h1:Er+FePu1dNUieD+XTMDduGpQuCPssK5Q4BjF+IIXJ3I= -github.com/ydb-platform/ydb-go-sdk/v3 v3.125.0 h1:KPnGV2diuX1A4/1zXLO1UWHJokWC8yICzEfjdkSUWKo= -github.com/ydb-platform/ydb-go-sdk/v3 v3.125.0/go.mod h1:/LjMxb/rXmoGAAnImoqAFIlhO5ampHacbvDetQitCk4= +github.com/ydb-platform/ydb-go-sdk/v3 v3.125.4 h1:GAC7qeNgsibEJkUVzV4z06aBnHR4jqfXsFiQtrY40gI= +github.com/ydb-platform/ydb-go-sdk/v3 v3.125.4/go.mod h1:stS1mQYjbJvwwYaYzKyFY9eMiuVXWWXQA6T+SpOLg9c= github.com/zclconf/go-cty v1.14.4 h1:uXXczd9QDGsgu0i/QFR/hzI5NYCHLf6NQw/atrbnhq8= github.com/zclconf/go-cty v1.14.4/go.mod h1:VvMs5i0vgZdhYawQNq5kePSpLAoz8u1xvZgrPIxfnZE= github.com/zclconf/go-cty-yaml v1.1.0 h1:nP+jp0qPHv2IhUVqmQSzjvqAWcObN0KBkUl2rWBdig0= diff --git a/examples/go.mod b/examples/go.mod index 74e79123fb..e04845acd3 100644 --- a/examples/go.mod +++ b/examples/go.mod @@ -32,7 +32,7 @@ require ( github.com/mitchellh/go-wordwrap v1.0.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/ydb-platform/ydb-go-genproto v0.0.0-20251222105147-0bf751469a4a // indirect - github.com/ydb-platform/ydb-go-sdk/v3 v3.125.0 // indirect + github.com/ydb-platform/ydb-go-sdk/v3 v3.125.4 // indirect github.com/zclconf/go-cty v1.14.4 // indirect github.com/zclconf/go-cty-yaml v1.1.0 // indirect go.opencensus.io v0.24.0 // indirect diff --git a/examples/go.sum b/examples/go.sum index df815aaa94..57411018ba 100644 --- a/examples/go.sum +++ b/examples/go.sum @@ -1699,8 +1699,8 @@ github.com/xlab/treeprint v1.1.0/go.mod h1:gj5Gd3gPdKtR1ikdDK6fnFLdmIS0X30kTTuNd github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= github.com/ydb-platform/ydb-go-genproto v0.0.0-20251222105147-0bf751469a4a h1:nRqONRrMFulP2bTWM2RRnPM1VDhWuBZg4ULXkG4xXdk= github.com/ydb-platform/ydb-go-genproto v0.0.0-20251222105147-0bf751469a4a/go.mod h1:Er+FePu1dNUieD+XTMDduGpQuCPssK5Q4BjF+IIXJ3I= -github.com/ydb-platform/ydb-go-sdk/v3 v3.125.0 h1:KPnGV2diuX1A4/1zXLO1UWHJokWC8yICzEfjdkSUWKo= -github.com/ydb-platform/ydb-go-sdk/v3 v3.125.0/go.mod h1:/LjMxb/rXmoGAAnImoqAFIlhO5ampHacbvDetQitCk4= +github.com/ydb-platform/ydb-go-sdk/v3 v3.125.4 h1:GAC7qeNgsibEJkUVzV4z06aBnHR4jqfXsFiQtrY40gI= +github.com/ydb-platform/ydb-go-sdk/v3 v3.125.4/go.mod h1:stS1mQYjbJvwwYaYzKyFY9eMiuVXWWXQA6T+SpOLg9c= github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= diff --git a/go.mod b/go.mod index 9513cbfb74..e0ffb11189 100644 --- a/go.mod +++ b/go.mod @@ -18,7 +18,7 @@ require ( github.com/olekukonko/tablewriter v1.0.8 github.com/spf13/cobra v1.7.0 github.com/stretchr/testify v1.11.1 - github.com/ydb-platform/ydb-go-sdk/v3 v3.125.0 + github.com/ydb-platform/ydb-go-sdk/v3 v3.125.4 go.opencensus.io v0.24.0 golang.org/x/sync v0.19.0 golang.org/x/tools v0.39.0 diff --git a/go.sum b/go.sum index b5b7a0e5a1..2d89673ef4 100644 --- a/go.sum +++ b/go.sum @@ -158,8 +158,8 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/ydb-platform/ydb-go-genproto v0.0.0-20251222105147-0bf751469a4a h1:nRqONRrMFulP2bTWM2RRnPM1VDhWuBZg4ULXkG4xXdk= github.com/ydb-platform/ydb-go-genproto v0.0.0-20251222105147-0bf751469a4a/go.mod h1:Er+FePu1dNUieD+XTMDduGpQuCPssK5Q4BjF+IIXJ3I= -github.com/ydb-platform/ydb-go-sdk/v3 v3.125.0 h1:KPnGV2diuX1A4/1zXLO1UWHJokWC8yICzEfjdkSUWKo= -github.com/ydb-platform/ydb-go-sdk/v3 v3.125.0/go.mod h1:/LjMxb/rXmoGAAnImoqAFIlhO5ampHacbvDetQitCk4= +github.com/ydb-platform/ydb-go-sdk/v3 v3.125.4 h1:GAC7qeNgsibEJkUVzV4z06aBnHR4jqfXsFiQtrY40gI= +github.com/ydb-platform/ydb-go-sdk/v3 v3.125.4/go.mod h1:stS1mQYjbJvwwYaYzKyFY9eMiuVXWWXQA6T+SpOLg9c= github.com/zclconf/go-cty v1.14.4 h1:uXXczd9QDGsgu0i/QFR/hzI5NYCHLf6NQw/atrbnhq8= github.com/zclconf/go-cty v1.14.4/go.mod h1:VvMs5i0vgZdhYawQNq5kePSpLAoz8u1xvZgrPIxfnZE= github.com/zclconf/go-cty-yaml v1.1.0 h1:nP+jp0qPHv2IhUVqmQSzjvqAWcObN0KBkUl2rWBdig0= From 60c5f1c3391bad1d92a5975dd96e24ca07edc165 Mon Sep 17 00:00:00 2001 From: danilov6083 Date: Fri, 16 Jan 2026 14:35:25 +0300 Subject: [PATCH 04/13] dialect/sql/sqlgraph: fixed using correlated subqueries --- dialect/sql/sqlgraph/graph.go | 66 +++++++++++++++++++++++------------ 1 file changed, 44 insertions(+), 22 deletions(-) diff --git a/dialect/sql/sqlgraph/graph.go b/dialect/sql/sqlgraph/graph.go index 9788bcd608..78523e699d 100644 --- a/dialect/sql/sqlgraph/graph.go +++ b/dialect/sql/sqlgraph/graph.go @@ -297,6 +297,7 @@ func HasNeighborsWith(q *sql.Selector, s *Step, pred func(*sql.Selector)) { pred(matches) join.FromSelect(matches) q.Where(sql.In(q.C(s.From.Column), join)) + case s.FromEdgeOwner(): to := builder.Table(s.To.Table).Schema(s.To.Schema) // Avoid ambiguity in case both source @@ -312,17 +313,28 @@ func HasNeighborsWith(q *sql.Selector, s *Step, pred func(*sql.Selector)) { to.As(fmt.Sprintf("%s_edge_%d", s.To.Table, i)) } } - matches := builder.Select(to.C(s.To.Column)). - From(to) - matches.WithContext(q.Context()) - matches.Where( - sql.ColumnsEQ( - q.C(s.Edge.Columns[0]), - to.C(s.To.Column), - ), - ) - pred(matches) - q.Where(sql.Exists(matches)) + + // YDB doesn't support correlated EXISTS subqueries. + // Use IN subquery instead for YDB dialect. + if q.Dialect() == dialect.YDB { + matches := builder.Select(to.C(s.To.Column)).From(to) + matches.WithContext(q.Context()) + pred(matches) + q.Where(sql.In(q.C(s.Edge.Columns[0]), matches)) + } else { + matches := builder.Select(to.C(s.To.Column)). + From(to) + matches.WithContext(q.Context()) + matches.Where( + sql.ColumnsEQ( + q.C(s.Edge.Columns[0]), + to.C(s.To.Column), + ), + ) + pred(matches) + q.Where(sql.Exists(matches)) + } + case s.ToEdgeOwner(): to := builder.Table(s.Edge.Table).Schema(s.Edge.Schema) // Avoid ambiguity in case both source @@ -338,17 +350,27 @@ func HasNeighborsWith(q *sql.Selector, s *Step, pred func(*sql.Selector)) { to.As(fmt.Sprintf("%s_edge_%d", s.Edge.Table, i)) } } - matches := builder.Select(to.C(s.Edge.Columns[0])). - From(to) - matches.WithContext(q.Context()) - matches.Where( - sql.ColumnsEQ( - q.C(s.From.Column), - to.C(s.Edge.Columns[0]), - ), - ) - pred(matches) - q.Where(sql.Exists(matches)) + + // YDB doesn't support correlated EXISTS subqueries. + // Use IN subquery instead for YDB dialect. + if q.Dialect() == dialect.YDB { + matches := builder.Select(to.C(s.Edge.Columns[0])).From(to) + matches.WithContext(q.Context()) + pred(matches) + q.Where(sql.In(q.C(s.From.Column), matches)) + } else { + matches := builder.Select(to.C(s.Edge.Columns[0])). + From(to) + matches.WithContext(q.Context()) + matches.Where( + sql.ColumnsEQ( + q.C(s.From.Column), + to.C(s.Edge.Columns[0]), + ), + ) + pred(matches) + q.Where(sql.Exists(matches)) + } } } From 07acbb4a6ee24a1c7efc85e473044970360567d4 Mon Sep 17 00:00:00 2001 From: danilov6083 Date: Fri, 16 Jan 2026 14:36:50 +0300 Subject: [PATCH 05/13] entc/gen: fixed open template --- entc/gen/template/dialect/sql/open.tmpl | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/entc/gen/template/dialect/sql/open.tmpl b/entc/gen/template/dialect/sql/open.tmpl index d64b2417be..9be135d5b2 100644 --- a/entc/gen/template/dialect/sql/open.tmpl +++ b/entc/gen/template/dialect/sql/open.tmpl @@ -7,7 +7,15 @@ in the LICENSE file in the root directory of this source tree. {{/* gotype: entgo.io/ent/entc/gen.Graph */}} {{ define "dialect/sql/client/open" }} - drv, err := sql.Open(driverName, dataSourceName) + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } From f948f3c897f7ddb34797329ae342b62c79cbfefc Mon Sep 17 00:00:00 2001 From: danilov6083 Date: Fri, 16 Jan 2026 15:10:07 +0300 Subject: [PATCH 06/13] dialect: removed query mode and enabled query service for database/sql driver --- dialect/sql/schema/atlas.go | 3 +-- dialect/ydb/driver.go | 1 + 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dialect/sql/schema/atlas.go b/dialect/sql/schema/atlas.go index 8a738ff676..d0ce2ff502 100644 --- a/dialect/sql/schema/atlas.go +++ b/dialect/sql/schema/atlas.go @@ -24,7 +24,6 @@ import ( "entgo.io/ent/dialect" entsql "entgo.io/ent/dialect/sql" "entgo.io/ent/schema/field" - "github.com/ydb-platform/ydb-go-sdk/v3" ) // Atlas atlas migration engine. @@ -633,7 +632,7 @@ func (a *Atlas) create(ctx context.Context, tables ...*Table) (err error) { applier := ApplyFunc(func(ctx context.Context, conn dialect.ExecQuerier, plan *migrate.Plan) error { for _, change := range plan.Changes { err := conn.Exec( - ydb.WithQueryMode(ctx, ydb.SchemeQueryMode), + ctx, change.Cmd, change.Args, nil, diff --git a/dialect/ydb/driver.go b/dialect/ydb/driver.go index 390d74eccd..1a8a6f12df 100644 --- a/dialect/ydb/driver.go +++ b/dialect/ydb/driver.go @@ -34,6 +34,7 @@ func Open(ctx context.Context, dsn string) (*YDBDriver, error) { nativeDriver, ydb.WithAutoDeclare(), ydb.WithTablePathPrefix(nativeDriver.Name()), + ydb.WithQueryService(true), ) if err != nil { return nil, err From 30809ff96302d9660dfa1ce149dac2cb4338bd23 Mon Sep 17 00:00:00 2001 From: danilov6083 Date: Fri, 16 Jan 2026 15:57:53 +0300 Subject: [PATCH 07/13] dialect/sql/sqlgraph: fixed clauses not supported by ydb --- dialect/sql/sqlgraph/graph.go | 79 ++++++++++++++++++++++++++--------- 1 file changed, 60 insertions(+), 19 deletions(-) diff --git a/dialect/sql/sqlgraph/graph.go b/dialect/sql/sqlgraph/graph.go index 78523e699d..ca049cce04 100644 --- a/dialect/sql/sqlgraph/graph.go +++ b/dialect/sql/sqlgraph/graph.go @@ -261,18 +261,30 @@ func HasNeighbors(q *sql.Selector, s *Step) { if s.From.Table == s.Edge.Table { to.As(fmt.Sprintf("%s_edge", s.Edge.Table)) } - q.Where( - sql.Exists( - builder.Select(to.C(s.Edge.Columns[0])). - From(to). - Where( - sql.ColumnsEQ( - q.C(s.From.Column), - to.C(s.Edge.Columns[0]), + + // YDB doesn't support correlated EXISTS subqueries. + // Use IN subquery instead for YDB dialect. + if q.Dialect() == dialect.YDB { + q.Where( + sql.In( + q.C(s.From.Column), + builder.Select(to.C(s.Edge.Columns[0])).From(to), + ), + ) + } else { + q.Where( + sql.Exists( + builder.Select(to.C(s.Edge.Columns[0])). + From(to). + Where( + sql.ColumnsEQ( + q.C(s.From.Column), + to.C(s.Edge.Columns[0]), + ), ), - ), - ), - ) + ), + ) + } } } @@ -1481,18 +1493,45 @@ func (u *updater) scan(rows *sql.Rows) error { } func (u *updater) ensureExists(ctx context.Context) error { - exists := u.builder.Select().From(u.builder.Table(u.Node.Table).Schema(u.Node.Schema)).Where(sql.EQ(u.Node.ID.Column, u.Node.ID.Value)) - u.Predicate(exists) - query, args := u.builder.SelectExpr(sql.Exists(exists)).Query() + selector := u.builder. + Select(). + From(u.builder.Table(u.Node.Table).Schema(u.Node.Schema)). + Where(sql.EQ(u.Node.ID.Column, u.Node.ID.Value)) + u.Predicate(selector) + + var query string + var args []any + + // YDB doesn't fully support EXISTS in all contexts. + // Use COUNT(*) > 0 approach instead for better compatibility. + if selector.Dialect() == dialect.YDB { + selector.Count("*") + query, args = selector.Query() + } else { + query, args = u.builder.SelectExpr(sql.Exists(selector)).Query() + } + rows := &sql.Rows{} if err := u.tx.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() - found, err := sql.ScanBool(rows) - if err != nil { - return err + + var found bool + if selector.Dialect() == dialect.YDB { + count, err := sql.ScanInt(rows) + if err != nil { + return err + } + found = count > 0 + } else { + var err error + found, err = sql.ScanBool(rows) + if err != nil { + return err + } } + if !found { return &NotFoundError{table: u.Node.Table, id: u.Node.ID.Value} } @@ -1833,7 +1872,8 @@ func (g *graph) addM2MEdges(ctx context.Context, ids []driver.Value, edges EdgeS } // Ignore conflicts only if edges do not contain extra fields, because these fields // can hold different values on different insertions (e.g. time.Now() or uuid.New()). - if len(edges[0].Target.Fields) == 0 { + // YDB doesn't support ON CONFLICT clause, so skip it for YDB dialect. + if len(edges[0].Target.Fields) == 0 && insert.Dialect() != dialect.YDB { insert.OnConflict(sql.DoNothing()) } query, args := insert.Query() @@ -1868,7 +1908,8 @@ func (g *graph) batchAddM2M(ctx context.Context, spec *BatchCreateSpec) error { } // Ignore conflicts only if edges do not contain extra fields, because these fields // can hold different values on different insertions (e.g. time.Now() or uuid.New()). - if len(edge.Target.Fields) == 0 { + // YDB doesn't support ON CONFLICT clause, so skip it for YDB dialect. + if len(edge.Target.Fields) == 0 && insert.Dialect() != dialect.YDB { insert.OnConflict(sql.DoNothing()) } } From 08f4f5fe46be09f30a593ad33c41c4c344352544 Mon Sep 17 00:00:00 2001 From: danilov6083 Date: Fri, 16 Jan 2026 16:02:16 +0300 Subject: [PATCH 08/13] ent/examples: added basic ydb example --- examples/go.mod | 2 +- examples/ydb/README.md | 59 + examples/ydb/ent/client.go | 704 +++++++++ examples/ydb/ent/ent.go | 616 ++++++++ examples/ydb/ent/entc.go | 31 + examples/ydb/ent/enttest/enttest.go | 88 ++ examples/ydb/ent/episode.go | 161 +++ examples/ydb/ent/episode/episode.go | 96 ++ examples/ydb/ent/episode/where.go | 238 ++++ examples/ydb/ent/episode_create.go | 271 ++++ examples/ydb/ent/episode_delete.go | 101 ++ examples/ydb/ent/episode_query.go | 620 ++++++++ examples/ydb/ent/episode_update.go | 407 ++++++ examples/ydb/ent/generate.go | 7 + examples/ydb/ent/hook/hook.go | 227 +++ examples/ydb/ent/migrate/migrate.go | 68 + examples/ydb/ent/migrate/schema.go | 92 ++ examples/ydb/ent/mutation.go | 1724 +++++++++++++++++++++++ examples/ydb/ent/predicate/predicate.go | 20 + examples/ydb/ent/runtime.go | 38 + examples/ydb/ent/runtime/runtime.go | 13 + examples/ydb/ent/schema/episode.go | 47 + examples/ydb/ent/schema/season.go | 49 + examples/ydb/ent/schema/series.go | 44 + examples/ydb/ent/season.go | 188 +++ examples/ydb/ent/season/season.go | 134 ++ examples/ydb/ent/season/where.go | 306 ++++ examples/ydb/ent/season_create.go | 316 +++++ examples/ydb/ent/season_delete.go | 101 ++ examples/ydb/ent/season_query.go | 695 +++++++++ examples/ydb/ent/season_update.go | 604 ++++++++ examples/ydb/ent/series.go | 158 +++ examples/ydb/ent/series/series.go | 103 ++ examples/ydb/ent/series/where.go | 293 ++++ examples/ydb/ent/series_create.go | 286 ++++ examples/ydb/ent/series_delete.go | 101 ++ examples/ydb/ent/series_query.go | 620 ++++++++ examples/ydb/ent/series_update.go | 507 +++++++ examples/ydb/ent/tx.go | 220 +++ examples/ydb/example.go | 194 +++ 40 files changed, 10548 insertions(+), 1 deletion(-) create mode 100644 examples/ydb/README.md create mode 100644 examples/ydb/ent/client.go create mode 100644 examples/ydb/ent/ent.go create mode 100644 examples/ydb/ent/entc.go create mode 100644 examples/ydb/ent/enttest/enttest.go create mode 100644 examples/ydb/ent/episode.go create mode 100644 examples/ydb/ent/episode/episode.go create mode 100644 examples/ydb/ent/episode/where.go create mode 100644 examples/ydb/ent/episode_create.go create mode 100644 examples/ydb/ent/episode_delete.go create mode 100644 examples/ydb/ent/episode_query.go create mode 100644 examples/ydb/ent/episode_update.go create mode 100644 examples/ydb/ent/generate.go create mode 100644 examples/ydb/ent/hook/hook.go create mode 100644 examples/ydb/ent/migrate/migrate.go create mode 100644 examples/ydb/ent/migrate/schema.go create mode 100644 examples/ydb/ent/mutation.go create mode 100644 examples/ydb/ent/predicate/predicate.go create mode 100644 examples/ydb/ent/runtime.go create mode 100644 examples/ydb/ent/runtime/runtime.go create mode 100644 examples/ydb/ent/schema/episode.go create mode 100644 examples/ydb/ent/schema/season.go create mode 100644 examples/ydb/ent/schema/series.go create mode 100644 examples/ydb/ent/season.go create mode 100644 examples/ydb/ent/season/season.go create mode 100644 examples/ydb/ent/season/where.go create mode 100644 examples/ydb/ent/season_create.go create mode 100644 examples/ydb/ent/season_delete.go create mode 100644 examples/ydb/ent/season_query.go create mode 100644 examples/ydb/ent/season_update.go create mode 100644 examples/ydb/ent/series.go create mode 100644 examples/ydb/ent/series/series.go create mode 100644 examples/ydb/ent/series/where.go create mode 100644 examples/ydb/ent/series_create.go create mode 100644 examples/ydb/ent/series_delete.go create mode 100644 examples/ydb/ent/series_query.go create mode 100644 examples/ydb/ent/series_update.go create mode 100644 examples/ydb/ent/tx.go create mode 100644 examples/ydb/example.go diff --git a/examples/go.mod b/examples/go.mod index e04845acd3..e4854a48d5 100644 --- a/examples/go.mod +++ b/examples/go.mod @@ -14,6 +14,7 @@ require ( github.com/lib/pq v1.10.7 github.com/mattn/go-sqlite3 v1.14.28 github.com/stretchr/testify v1.11.1 + github.com/ydb-platform/ydb-go-sdk/v3 v3.125.4 gocloud.dev v0.28.0 ) @@ -32,7 +33,6 @@ require ( github.com/mitchellh/go-wordwrap v1.0.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/ydb-platform/ydb-go-genproto v0.0.0-20251222105147-0bf751469a4a // indirect - github.com/ydb-platform/ydb-go-sdk/v3 v3.125.4 // indirect github.com/zclconf/go-cty v1.14.4 // indirect github.com/zclconf/go-cty-yaml v1.1.0 // indirect go.opencensus.io v0.24.0 // indirect diff --git a/examples/ydb/README.md b/examples/ydb/README.md new file mode 100644 index 0000000000..81a1dee2b8 --- /dev/null +++ b/examples/ydb/README.md @@ -0,0 +1,59 @@ +# YDB Example + +This example demonstrates how to use ent with [YDB](https://ydb.tech/) database. + +## Prerequisites + +- Running YDB instance (local or remote) +- Go 1.22+ + +## Running YDB Locally + +You can run YDB locally using Docker: + +```bash +docker run -d --rm --name ydb-local \ + -p 2135:2135 -p 2136:2136 -p 8765:8765 \ + -e GRPC_TLS_PORT=2135 \ + -e GRPC_PORT=2136 \ + -e MON_PORT=8765 \ + -e YDB_USE_IN_MEMORY_PDISKS=true \ + cr.yandex/yc/yandex-docker-local-ydb:latest +``` + +## Key Features Demonstrated + +1. **YDB Driver** - Using the ent YDB driver with ydb-go-sdk +2. **Automatic Retries** - Using `WithRetryOptions()` for YDB-specific retry handling +3. **Schema Creation** - Creating tables in YDB using ent migrations +4. **CRUD Operations** - Create, Read, Update, Delete operations with YDB + +## Schema + +This example uses a simple TV series database with three entities: + +- **Series** - TV series (title, info, release date) +- **Season** - Seasons of a series (title, first/last aired dates) +- **Episode** - Episodes in a season (title, air date, duration) + +## Retry Handling + +YDB requires special retry handling for transient errors. The ent YDB driver +automatically handles retries using ydb-go-sdk's retry package. You can +customize retry behavior using `WithRetryOptions()`: + +```go +// Create with custom retry options +_, err := client.Series.Create(). + SetTitle("The Expanse"). + SetInfo("Humanity has colonized the solar system"). + SetReleaseDate(time.Date(2015, 12, 14, 0, 0, 0, 0, time.UTC)). + WithRetryOptions(retry.WithIdempotent(true)). + Save(ctx) + +// Query with retry options +series, err := client.Series.Query(). + Where(series.TitleContains("Expanse")). + WithRetryOptions(retry.WithIdempotent(true)). + All(ctx) +``` diff --git a/examples/ydb/ent/client.go b/examples/ydb/ent/client.go new file mode 100644 index 0000000000..d378e901b7 --- /dev/null +++ b/examples/ydb/ent/client.go @@ -0,0 +1,704 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "log" + "reflect" + + "entgo.io/ent" + "entgo.io/ent/examples/ydb/ent/migrate" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" + "entgo.io/ent/examples/ydb/ent/episode" + "entgo.io/ent/examples/ydb/ent/season" + "entgo.io/ent/examples/ydb/ent/series" +) + +// 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 + // Episode is the client for interacting with the Episode builders. + Episode *EpisodeClient + // Season is the client for interacting with the Season builders. + Season *SeasonClient + // Series is the client for interacting with the Series builders. + Series *SeriesClient +} + +// 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.Episode = NewEpisodeClient(c.config) + c.Season = NewSeasonClient(c.config) + c.Series = NewSeriesClient(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, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + 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, + Episode: NewEpisodeClient(cfg), + Season: NewSeasonClient(cfg), + Series: NewSeriesClient(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, + Episode: NewEpisodeClient(cfg), + Season: NewSeasonClient(cfg), + Series: NewSeriesClient(cfg), + }, nil +} + +// Debug returns a new debug-client. It's used to get verbose logging on specific operations. +// +// client.Debug(). +// Episode. +// Query(). +// Count(ctx) +func (c *Client) Debug() *Client { + if c.debug { + return c + } + cfg := c.config + cfg.driver = dialect.Debug(c.driver, c.log) + client := &Client{config: cfg} + client.init() + return client +} + +// Close closes the database connection and prevents new queries from starting. +func (c *Client) Close() error { + return c.driver.Close() +} + +// Use adds the mutation hooks to all the entity clients. +// In order to add hooks to a specific client, call: `client.Node.Use(...)`. +func (c *Client) Use(hooks ...Hook) { + c.Episode.Use(hooks...) + c.Season.Use(hooks...) + c.Series.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.Episode.Intercept(interceptors...) + c.Season.Intercept(interceptors...) + c.Series.Intercept(interceptors...) +} + +// Mutate implements the ent.Mutator interface. +func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { + switch m := m.(type) { + case *EpisodeMutation: + return c.Episode.mutate(ctx, m) + case *SeasonMutation: + return c.Season.mutate(ctx, m) + case *SeriesMutation: + return c.Series.mutate(ctx, m) + default: + return nil, fmt.Errorf("ent: unknown mutation type %T", m) + } +} + +// EpisodeClient is a client for the Episode schema. +type EpisodeClient struct { + config +} + +// NewEpisodeClient returns a client for the Episode from the given config. +func NewEpisodeClient(c config) *EpisodeClient { + return &EpisodeClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `episode.Hooks(f(g(h())))`. +func (c *EpisodeClient) Use(hooks ...Hook) { + c.hooks.Episode = append(c.hooks.Episode, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `episode.Intercept(f(g(h())))`. +func (c *EpisodeClient) Intercept(interceptors ...Interceptor) { + c.inters.Episode = append(c.inters.Episode, interceptors...) +} + +// Create returns a builder for creating a Episode entity. +func (c *EpisodeClient) Create() *EpisodeCreate { + mutation := newEpisodeMutation(c.config, OpCreate) + return &EpisodeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Episode entities. +func (c *EpisodeClient) CreateBulk(builders ...*EpisodeCreate) *EpisodeCreateBulk { + return &EpisodeCreateBulk{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 *EpisodeClient) MapCreateBulk(slice any, setFunc func(*EpisodeCreate, int)) *EpisodeCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &EpisodeCreateBulk{err: fmt.Errorf("calling to EpisodeClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*EpisodeCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &EpisodeCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Episode. +func (c *EpisodeClient) Update() *EpisodeUpdate { + mutation := newEpisodeMutation(c.config, OpUpdate) + return &EpisodeUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *EpisodeClient) UpdateOne(_m *Episode) *EpisodeUpdateOne { + mutation := newEpisodeMutation(c.config, OpUpdateOne, withEpisode(_m)) + return &EpisodeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *EpisodeClient) UpdateOneID(id int64) *EpisodeUpdateOne { + mutation := newEpisodeMutation(c.config, OpUpdateOne, withEpisodeID(id)) + return &EpisodeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Episode. +func (c *EpisodeClient) Delete() *EpisodeDelete { + mutation := newEpisodeMutation(c.config, OpDelete) + return &EpisodeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *EpisodeClient) DeleteOne(_m *Episode) *EpisodeDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *EpisodeClient) DeleteOneID(id int64) *EpisodeDeleteOne { + builder := c.Delete().Where(episode.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &EpisodeDeleteOne{builder} +} + +// Query returns a query builder for Episode. +func (c *EpisodeClient) Query() *EpisodeQuery { + return &EpisodeQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeEpisode}, + inters: c.Interceptors(), + } +} + +// Get returns a Episode entity by its id. +func (c *EpisodeClient) Get(ctx context.Context, id int64) (*Episode, error) { + return c.Query().Where(episode.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *EpisodeClient) GetX(ctx context.Context, id int64) *Episode { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QuerySeason queries the season edge of a Episode. +func (c *EpisodeClient) QuerySeason(_m *Episode) *SeasonQuery { + query := (&SeasonClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(episode.Table, episode.FieldID, id), + sqlgraph.To(season.Table, season.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, episode.SeasonTable, episode.SeasonColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *EpisodeClient) Hooks() []Hook { + return c.hooks.Episode +} + +// Interceptors returns the client interceptors. +func (c *EpisodeClient) Interceptors() []Interceptor { + return c.inters.Episode +} + +func (c *EpisodeClient) mutate(ctx context.Context, m *EpisodeMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&EpisodeCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&EpisodeUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&EpisodeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&EpisodeDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Episode mutation op: %q", m.Op()) + } +} + +// SeasonClient is a client for the Season schema. +type SeasonClient struct { + config +} + +// NewSeasonClient returns a client for the Season from the given config. +func NewSeasonClient(c config) *SeasonClient { + return &SeasonClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `season.Hooks(f(g(h())))`. +func (c *SeasonClient) Use(hooks ...Hook) { + c.hooks.Season = append(c.hooks.Season, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `season.Intercept(f(g(h())))`. +func (c *SeasonClient) Intercept(interceptors ...Interceptor) { + c.inters.Season = append(c.inters.Season, interceptors...) +} + +// Create returns a builder for creating a Season entity. +func (c *SeasonClient) Create() *SeasonCreate { + mutation := newSeasonMutation(c.config, OpCreate) + return &SeasonCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Season entities. +func (c *SeasonClient) CreateBulk(builders ...*SeasonCreate) *SeasonCreateBulk { + return &SeasonCreateBulk{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 *SeasonClient) MapCreateBulk(slice any, setFunc func(*SeasonCreate, int)) *SeasonCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &SeasonCreateBulk{err: fmt.Errorf("calling to SeasonClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*SeasonCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &SeasonCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Season. +func (c *SeasonClient) Update() *SeasonUpdate { + mutation := newSeasonMutation(c.config, OpUpdate) + return &SeasonUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *SeasonClient) UpdateOne(_m *Season) *SeasonUpdateOne { + mutation := newSeasonMutation(c.config, OpUpdateOne, withSeason(_m)) + return &SeasonUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *SeasonClient) UpdateOneID(id int64) *SeasonUpdateOne { + mutation := newSeasonMutation(c.config, OpUpdateOne, withSeasonID(id)) + return &SeasonUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Season. +func (c *SeasonClient) Delete() *SeasonDelete { + mutation := newSeasonMutation(c.config, OpDelete) + return &SeasonDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *SeasonClient) DeleteOne(_m *Season) *SeasonDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *SeasonClient) DeleteOneID(id int64) *SeasonDeleteOne { + builder := c.Delete().Where(season.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &SeasonDeleteOne{builder} +} + +// Query returns a query builder for Season. +func (c *SeasonClient) Query() *SeasonQuery { + return &SeasonQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeSeason}, + inters: c.Interceptors(), + } +} + +// Get returns a Season entity by its id. +func (c *SeasonClient) Get(ctx context.Context, id int64) (*Season, error) { + return c.Query().Where(season.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *SeasonClient) GetX(ctx context.Context, id int64) *Season { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QuerySeries queries the series edge of a Season. +func (c *SeasonClient) QuerySeries(_m *Season) *SeriesQuery { + query := (&SeriesClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(season.Table, season.FieldID, id), + sqlgraph.To(series.Table, series.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, season.SeriesTable, season.SeriesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryEpisodes queries the episodes edge of a Season. +func (c *SeasonClient) QueryEpisodes(_m *Season) *EpisodeQuery { + query := (&EpisodeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(season.Table, season.FieldID, id), + sqlgraph.To(episode.Table, episode.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, season.EpisodesTable, season.EpisodesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *SeasonClient) Hooks() []Hook { + return c.hooks.Season +} + +// Interceptors returns the client interceptors. +func (c *SeasonClient) Interceptors() []Interceptor { + return c.inters.Season +} + +func (c *SeasonClient) mutate(ctx context.Context, m *SeasonMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&SeasonCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&SeasonUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&SeasonUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&SeasonDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Season mutation op: %q", m.Op()) + } +} + +// SeriesClient is a client for the Series schema. +type SeriesClient struct { + config +} + +// NewSeriesClient returns a client for the Series from the given config. +func NewSeriesClient(c config) *SeriesClient { + return &SeriesClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `series.Hooks(f(g(h())))`. +func (c *SeriesClient) Use(hooks ...Hook) { + c.hooks.Series = append(c.hooks.Series, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `series.Intercept(f(g(h())))`. +func (c *SeriesClient) Intercept(interceptors ...Interceptor) { + c.inters.Series = append(c.inters.Series, interceptors...) +} + +// Create returns a builder for creating a Series entity. +func (c *SeriesClient) Create() *SeriesCreate { + mutation := newSeriesMutation(c.config, OpCreate) + return &SeriesCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Series entities. +func (c *SeriesClient) CreateBulk(builders ...*SeriesCreate) *SeriesCreateBulk { + return &SeriesCreateBulk{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 *SeriesClient) MapCreateBulk(slice any, setFunc func(*SeriesCreate, int)) *SeriesCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &SeriesCreateBulk{err: fmt.Errorf("calling to SeriesClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*SeriesCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &SeriesCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Series. +func (c *SeriesClient) Update() *SeriesUpdate { + mutation := newSeriesMutation(c.config, OpUpdate) + return &SeriesUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *SeriesClient) UpdateOne(_m *Series) *SeriesUpdateOne { + mutation := newSeriesMutation(c.config, OpUpdateOne, withSeries(_m)) + return &SeriesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *SeriesClient) UpdateOneID(id int64) *SeriesUpdateOne { + mutation := newSeriesMutation(c.config, OpUpdateOne, withSeriesID(id)) + return &SeriesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Series. +func (c *SeriesClient) Delete() *SeriesDelete { + mutation := newSeriesMutation(c.config, OpDelete) + return &SeriesDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *SeriesClient) DeleteOne(_m *Series) *SeriesDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *SeriesClient) DeleteOneID(id int64) *SeriesDeleteOne { + builder := c.Delete().Where(series.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &SeriesDeleteOne{builder} +} + +// Query returns a query builder for Series. +func (c *SeriesClient) Query() *SeriesQuery { + return &SeriesQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeSeries}, + inters: c.Interceptors(), + } +} + +// Get returns a Series entity by its id. +func (c *SeriesClient) Get(ctx context.Context, id int64) (*Series, error) { + return c.Query().Where(series.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *SeriesClient) GetX(ctx context.Context, id int64) *Series { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QuerySeasons queries the seasons edge of a Series. +func (c *SeriesClient) QuerySeasons(_m *Series) *SeasonQuery { + query := (&SeasonClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(series.Table, series.FieldID, id), + sqlgraph.To(season.Table, season.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, series.SeasonsTable, series.SeasonsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *SeriesClient) Hooks() []Hook { + return c.hooks.Series +} + +// Interceptors returns the client interceptors. +func (c *SeriesClient) Interceptors() []Interceptor { + return c.inters.Series +} + +func (c *SeriesClient) mutate(ctx context.Context, m *SeriesMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&SeriesCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&SeriesUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&SeriesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&SeriesDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Series mutation op: %q", m.Op()) + } +} + +// hooks and interceptors per client, for fast access. +type ( + hooks struct { + Episode, Season, Series []ent.Hook + } + inters struct { + Episode, Season, Series []ent.Interceptor + } +) diff --git a/examples/ydb/ent/ent.go b/examples/ydb/ent/ent.go new file mode 100644 index 0000000000..26efa85eae --- /dev/null +++ b/examples/ydb/ent/ent.go @@ -0,0 +1,616 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "reflect" + "sync" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/ydb/ent/episode" + "entgo.io/ent/examples/ydb/ent/season" + "entgo.io/ent/examples/ydb/ent/series" +) + +// 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{ + episode.Table: episode.ValidColumn, + season.Table: season.ValidColumn, + series.Table: series.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/examples/ydb/ent/entc.go b/examples/ydb/ent/entc.go new file mode 100644 index 0000000000..7ce29fc20e --- /dev/null +++ b/examples/ydb/ent/entc.go @@ -0,0 +1,31 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +//go:build ignore +// +build ignore + +package main + +import ( + "log" + + "entgo.io/ent/entc" + "entgo.io/ent/entc/gen" +) + +func main() { + err := entc.Generate("./schema", &gen.Config{ + Header: `// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT.`, + Features: []gen.Feature{ + gen.FeatureRetryOptions, + }, + }) + if err != nil { + log.Fatalf("running ent codegen: %v", err) + } +} diff --git a/examples/ydb/ent/enttest/enttest.go b/examples/ydb/ent/enttest/enttest.go new file mode 100644 index 0000000000..070a75c5b9 --- /dev/null +++ b/examples/ydb/ent/enttest/enttest.go @@ -0,0 +1,88 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package enttest + +import ( + "context" + + "entgo.io/ent/examples/ydb/ent" + // required by schema hooks. + _ "entgo.io/ent/examples/ydb/ent/runtime" + + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/examples/ydb/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/examples/ydb/ent/episode.go b/examples/ydb/ent/episode.go new file mode 100644 index 0000000000..dd6ec3dbdd --- /dev/null +++ b/examples/ydb/ent/episode.go @@ -0,0 +1,161 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/examples/ydb/ent/episode" + "entgo.io/ent/examples/ydb/ent/season" +) + +// Episode is the model entity for the Episode schema. +type Episode struct { + config `json:"-"` + // ID of the ent. + ID int64 `json:"id,omitempty"` + // SeasonID holds the value of the "season_id" field. + SeasonID int64 `json:"season_id,omitempty"` + // Title holds the value of the "title" field. + Title string `json:"title,omitempty"` + // AirDate holds the value of the "air_date" field. + AirDate time.Time `json:"air_date,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the EpisodeQuery when eager-loading is set. + Edges EpisodeEdges `json:"edges"` + selectValues sql.SelectValues +} + +// EpisodeEdges holds the relations/edges for other nodes in the graph. +type EpisodeEdges struct { + // Season holds the value of the season edge. + Season *Season `json:"season,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// SeasonOrErr returns the Season value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e EpisodeEdges) SeasonOrErr() (*Season, error) { + if e.Season != nil { + return e.Season, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: season.Label} + } + return nil, &NotLoadedError{edge: "season"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Episode) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case episode.FieldID, episode.FieldSeasonID: + values[i] = new(sql.NullInt64) + case episode.FieldTitle: + values[i] = new(sql.NullString) + case episode.FieldAirDate: + values[i] = new(sql.NullTime) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Episode fields. +func (_m *Episode) 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 episode.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int64(value.Int64) + case episode.FieldSeasonID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field season_id", values[i]) + } else if value.Valid { + _m.SeasonID = value.Int64 + } + case episode.FieldTitle: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field title", values[i]) + } else if value.Valid { + _m.Title = value.String + } + case episode.FieldAirDate: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field air_date", values[i]) + } else if value.Valid { + _m.AirDate = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Episode. +// This includes values selected through modifiers, order, etc. +func (_m *Episode) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QuerySeason queries the "season" edge of the Episode entity. +func (_m *Episode) QuerySeason() *SeasonQuery { + return NewEpisodeClient(_m.config).QuerySeason(_m) +} + +// Update returns a builder for updating this Episode. +// Note that you need to call Episode.Unwrap() before calling this method if this Episode +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Episode) Update() *EpisodeUpdateOne { + return NewEpisodeClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Episode 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 *Episode) Unwrap() *Episode { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: Episode is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Episode) String() string { + var builder strings.Builder + builder.WriteString("Episode(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("season_id=") + builder.WriteString(fmt.Sprintf("%v", _m.SeasonID)) + builder.WriteString(", ") + builder.WriteString("title=") + builder.WriteString(_m.Title) + builder.WriteString(", ") + builder.WriteString("air_date=") + builder.WriteString(_m.AirDate.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// Episodes is a parsable slice of Episode. +type Episodes []*Episode diff --git a/examples/ydb/ent/episode/episode.go b/examples/ydb/ent/episode/episode.go new file mode 100644 index 0000000000..be6e97858d --- /dev/null +++ b/examples/ydb/ent/episode/episode.go @@ -0,0 +1,96 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package episode + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the episode type in the database. + Label = "episode" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldSeasonID holds the string denoting the season_id field in the database. + FieldSeasonID = "season_id" + // FieldTitle holds the string denoting the title field in the database. + FieldTitle = "title" + // FieldAirDate holds the string denoting the air_date field in the database. + FieldAirDate = "air_date" + // EdgeSeason holds the string denoting the season edge name in mutations. + EdgeSeason = "season" + // Table holds the table name of the episode in the database. + Table = "episodes" + // SeasonTable is the table that holds the season relation/edge. + SeasonTable = "episodes" + // SeasonInverseTable is the table name for the Season entity. + // It exists in this package in order to avoid circular dependency with the "season" package. + SeasonInverseTable = "seasons" + // SeasonColumn is the table column denoting the season relation/edge. + SeasonColumn = "season_id" +) + +// Columns holds all SQL columns for episode fields. +var Columns = []string{ + FieldID, + FieldSeasonID, + FieldTitle, + FieldAirDate, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // TitleValidator is a validator for the "title" field. It is called by the builders before save. + TitleValidator func(string) error +) + +// OrderOption defines the ordering options for the Episode 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() +} + +// BySeasonID orders the results by the season_id field. +func BySeasonID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSeasonID, opts...).ToFunc() +} + +// ByTitle orders the results by the title field. +func ByTitle(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTitle, opts...).ToFunc() +} + +// ByAirDate orders the results by the air_date field. +func ByAirDate(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAirDate, opts...).ToFunc() +} + +// BySeasonField orders the results by season field. +func BySeasonField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSeasonStep(), sql.OrderByField(field, opts...)) + } +} +func newSeasonStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SeasonInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SeasonTable, SeasonColumn), + ) +} diff --git a/examples/ydb/ent/episode/where.go b/examples/ydb/ent/episode/where.go new file mode 100644 index 0000000000..2d93abb53e --- /dev/null +++ b/examples/ydb/ent/episode/where.go @@ -0,0 +1,238 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package episode + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/ydb/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int64) predicate.Episode { + return predicate.Episode(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int64) predicate.Episode { + return predicate.Episode(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int64) predicate.Episode { + return predicate.Episode(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int64) predicate.Episode { + return predicate.Episode(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int64) predicate.Episode { + return predicate.Episode(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int64) predicate.Episode { + return predicate.Episode(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int64) predicate.Episode { + return predicate.Episode(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int64) predicate.Episode { + return predicate.Episode(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int64) predicate.Episode { + return predicate.Episode(sql.FieldLTE(FieldID, id)) +} + +// SeasonID applies equality check predicate on the "season_id" field. It's identical to SeasonIDEQ. +func SeasonID(v int64) predicate.Episode { + return predicate.Episode(sql.FieldEQ(FieldSeasonID, v)) +} + +// Title applies equality check predicate on the "title" field. It's identical to TitleEQ. +func Title(v string) predicate.Episode { + return predicate.Episode(sql.FieldEQ(FieldTitle, v)) +} + +// AirDate applies equality check predicate on the "air_date" field. It's identical to AirDateEQ. +func AirDate(v time.Time) predicate.Episode { + return predicate.Episode(sql.FieldEQ(FieldAirDate, v)) +} + +// SeasonIDEQ applies the EQ predicate on the "season_id" field. +func SeasonIDEQ(v int64) predicate.Episode { + return predicate.Episode(sql.FieldEQ(FieldSeasonID, v)) +} + +// SeasonIDNEQ applies the NEQ predicate on the "season_id" field. +func SeasonIDNEQ(v int64) predicate.Episode { + return predicate.Episode(sql.FieldNEQ(FieldSeasonID, v)) +} + +// SeasonIDIn applies the In predicate on the "season_id" field. +func SeasonIDIn(vs ...int64) predicate.Episode { + return predicate.Episode(sql.FieldIn(FieldSeasonID, vs...)) +} + +// SeasonIDNotIn applies the NotIn predicate on the "season_id" field. +func SeasonIDNotIn(vs ...int64) predicate.Episode { + return predicate.Episode(sql.FieldNotIn(FieldSeasonID, vs...)) +} + +// TitleEQ applies the EQ predicate on the "title" field. +func TitleEQ(v string) predicate.Episode { + return predicate.Episode(sql.FieldEQ(FieldTitle, v)) +} + +// TitleNEQ applies the NEQ predicate on the "title" field. +func TitleNEQ(v string) predicate.Episode { + return predicate.Episode(sql.FieldNEQ(FieldTitle, v)) +} + +// TitleIn applies the In predicate on the "title" field. +func TitleIn(vs ...string) predicate.Episode { + return predicate.Episode(sql.FieldIn(FieldTitle, vs...)) +} + +// TitleNotIn applies the NotIn predicate on the "title" field. +func TitleNotIn(vs ...string) predicate.Episode { + return predicate.Episode(sql.FieldNotIn(FieldTitle, vs...)) +} + +// TitleGT applies the GT predicate on the "title" field. +func TitleGT(v string) predicate.Episode { + return predicate.Episode(sql.FieldGT(FieldTitle, v)) +} + +// TitleGTE applies the GTE predicate on the "title" field. +func TitleGTE(v string) predicate.Episode { + return predicate.Episode(sql.FieldGTE(FieldTitle, v)) +} + +// TitleLT applies the LT predicate on the "title" field. +func TitleLT(v string) predicate.Episode { + return predicate.Episode(sql.FieldLT(FieldTitle, v)) +} + +// TitleLTE applies the LTE predicate on the "title" field. +func TitleLTE(v string) predicate.Episode { + return predicate.Episode(sql.FieldLTE(FieldTitle, v)) +} + +// TitleContains applies the Contains predicate on the "title" field. +func TitleContains(v string) predicate.Episode { + return predicate.Episode(sql.FieldContains(FieldTitle, v)) +} + +// TitleHasPrefix applies the HasPrefix predicate on the "title" field. +func TitleHasPrefix(v string) predicate.Episode { + return predicate.Episode(sql.FieldHasPrefix(FieldTitle, v)) +} + +// TitleHasSuffix applies the HasSuffix predicate on the "title" field. +func TitleHasSuffix(v string) predicate.Episode { + return predicate.Episode(sql.FieldHasSuffix(FieldTitle, v)) +} + +// TitleEqualFold applies the EqualFold predicate on the "title" field. +func TitleEqualFold(v string) predicate.Episode { + return predicate.Episode(sql.FieldEqualFold(FieldTitle, v)) +} + +// TitleContainsFold applies the ContainsFold predicate on the "title" field. +func TitleContainsFold(v string) predicate.Episode { + return predicate.Episode(sql.FieldContainsFold(FieldTitle, v)) +} + +// AirDateEQ applies the EQ predicate on the "air_date" field. +func AirDateEQ(v time.Time) predicate.Episode { + return predicate.Episode(sql.FieldEQ(FieldAirDate, v)) +} + +// AirDateNEQ applies the NEQ predicate on the "air_date" field. +func AirDateNEQ(v time.Time) predicate.Episode { + return predicate.Episode(sql.FieldNEQ(FieldAirDate, v)) +} + +// AirDateIn applies the In predicate on the "air_date" field. +func AirDateIn(vs ...time.Time) predicate.Episode { + return predicate.Episode(sql.FieldIn(FieldAirDate, vs...)) +} + +// AirDateNotIn applies the NotIn predicate on the "air_date" field. +func AirDateNotIn(vs ...time.Time) predicate.Episode { + return predicate.Episode(sql.FieldNotIn(FieldAirDate, vs...)) +} + +// AirDateGT applies the GT predicate on the "air_date" field. +func AirDateGT(v time.Time) predicate.Episode { + return predicate.Episode(sql.FieldGT(FieldAirDate, v)) +} + +// AirDateGTE applies the GTE predicate on the "air_date" field. +func AirDateGTE(v time.Time) predicate.Episode { + return predicate.Episode(sql.FieldGTE(FieldAirDate, v)) +} + +// AirDateLT applies the LT predicate on the "air_date" field. +func AirDateLT(v time.Time) predicate.Episode { + return predicate.Episode(sql.FieldLT(FieldAirDate, v)) +} + +// AirDateLTE applies the LTE predicate on the "air_date" field. +func AirDateLTE(v time.Time) predicate.Episode { + return predicate.Episode(sql.FieldLTE(FieldAirDate, v)) +} + +// HasSeason applies the HasEdge predicate on the "season" edge. +func HasSeason() predicate.Episode { + return predicate.Episode(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SeasonTable, SeasonColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSeasonWith applies the HasEdge predicate on the "season" edge with a given conditions (other predicates). +func HasSeasonWith(preds ...predicate.Season) predicate.Episode { + return predicate.Episode(func(s *sql.Selector) { + step := newSeasonStep() + 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.Episode) predicate.Episode { + return predicate.Episode(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Episode) predicate.Episode { + return predicate.Episode(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Episode) predicate.Episode { + return predicate.Episode(sql.NotPredicates(p)) +} diff --git a/examples/ydb/ent/episode_create.go b/examples/ydb/ent/episode_create.go new file mode 100644 index 0000000000..0cb9c190c2 --- /dev/null +++ b/examples/ydb/ent/episode_create.go @@ -0,0 +1,271 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/ydb/ent/episode" + "entgo.io/ent/examples/ydb/ent/season" + "entgo.io/ent/schema/field" +) + +// EpisodeCreate is the builder for creating a Episode entity. +type EpisodeCreate struct { + config + mutation *EpisodeMutation + hooks []Hook + retryConfig sqlgraph.RetryConfig +} + +// SetSeasonID sets the "season_id" field. +func (_c *EpisodeCreate) SetSeasonID(v int64) *EpisodeCreate { + _c.mutation.SetSeasonID(v) + return _c +} + +// SetTitle sets the "title" field. +func (_c *EpisodeCreate) SetTitle(v string) *EpisodeCreate { + _c.mutation.SetTitle(v) + return _c +} + +// SetAirDate sets the "air_date" field. +func (_c *EpisodeCreate) SetAirDate(v time.Time) *EpisodeCreate { + _c.mutation.SetAirDate(v) + return _c +} + +// SetID sets the "id" field. +func (_c *EpisodeCreate) SetID(v int64) *EpisodeCreate { + _c.mutation.SetID(v) + return _c +} + +// SetSeason sets the "season" edge to the Season entity. +func (_c *EpisodeCreate) SetSeason(v *Season) *EpisodeCreate { + return _c.SetSeasonID(v.ID) +} + +// Mutation returns the EpisodeMutation object of the builder. +func (_c *EpisodeCreate) Mutation() *EpisodeMutation { + return _c.mutation +} + +// Save creates the Episode in the database. +func (_c *EpisodeCreate) Save(ctx context.Context) (*Episode, error) { + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *EpisodeCreate) SaveX(ctx context.Context) *Episode { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *EpisodeCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *EpisodeCreate) 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 *EpisodeCreate) check() error { + if _, ok := _c.mutation.SeasonID(); !ok { + return &ValidationError{Name: "season_id", err: errors.New(`ent: missing required field "Episode.season_id"`)} + } + if _, ok := _c.mutation.Title(); !ok { + return &ValidationError{Name: "title", err: errors.New(`ent: missing required field "Episode.title"`)} + } + if v, ok := _c.mutation.Title(); ok { + if err := episode.TitleValidator(v); err != nil { + return &ValidationError{Name: "title", err: fmt.Errorf(`ent: validator failed for field "Episode.title": %w`, err)} + } + } + if _, ok := _c.mutation.AirDate(); !ok { + return &ValidationError{Name: "air_date", err: errors.New(`ent: missing required field "Episode.air_date"`)} + } + if len(_c.mutation.SeasonIDs()) == 0 { + return &ValidationError{Name: "season", err: errors.New(`ent: missing required edge "Episode.season"`)} + } + return nil +} + +func (_c *EpisodeCreate) sqlSave(ctx context.Context) (*Episode, 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 + } + if _spec.ID.Value != _node.ID { + id := _spec.ID.Value.(int64) + _node.ID = int64(id) + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *EpisodeCreate) createSpec() (*Episode, *sqlgraph.CreateSpec) { + var ( + _node = &Episode{config: _c.config} + _spec = sqlgraph.NewCreateSpec(episode.Table, sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt64)) + ) + _spec.RetryConfig = _c.retryConfig + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.Title(); ok { + _spec.SetField(episode.FieldTitle, field.TypeString, value) + _node.Title = value + } + if value, ok := _c.mutation.AirDate(); ok { + _spec.SetField(episode.FieldAirDate, field.TypeTime, value) + _node.AirDate = value + } + if nodes := _c.mutation.SeasonIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: episode.SeasonTable, + Columns: []string{episode.SeasonColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(season.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.SeasonID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// WithRetryOptions sets the retry options for the create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *EpisodeCreate) WithRetryOptions(opts ...any) *EpisodeCreate { + _c.retryConfig.Options = opts + return _c +} + +// EpisodeCreateBulk is the builder for creating many Episode entities in bulk. +type EpisodeCreateBulk struct { + config + err error + builders []*EpisodeCreate + retryConfig sqlgraph.RetryConfig +} + +// Save creates the Episode entities in the database. +func (_c *EpisodeCreateBulk) Save(ctx context.Context) ([]*Episode, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Episode, 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.(*EpisodeMutation) + 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.RetryConfig = _c.retryConfig + // 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 && nodes[i].ID == 0 { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int64(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 *EpisodeCreateBulk) SaveX(ctx context.Context) []*Episode { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *EpisodeCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *EpisodeCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// WithRetryOptions sets the retry options for the bulk create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *EpisodeCreateBulk) WithRetryOptions(opts ...any) *EpisodeCreateBulk { + _c.retryConfig.Options = opts + return _c +} diff --git a/examples/ydb/ent/episode_delete.go b/examples/ydb/ent/episode_delete.go new file mode 100644 index 0000000000..2720770e34 --- /dev/null +++ b/examples/ydb/ent/episode_delete.go @@ -0,0 +1,101 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/ydb/ent/episode" + "entgo.io/ent/examples/ydb/ent/predicate" + "entgo.io/ent/schema/field" +) + +// EpisodeDelete is the builder for deleting a Episode entity. +type EpisodeDelete struct { + config + hooks []Hook + mutation *EpisodeMutation + retryConfig sqlgraph.RetryConfig +} + +// Where appends a list predicates to the EpisodeDelete builder. +func (_d *EpisodeDelete) Where(ps ...predicate.Episode) *EpisodeDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *EpisodeDelete) 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 *EpisodeDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *EpisodeDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(episode.Table, sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt64)) + _spec.RetryConfig = _d.retryConfig + 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 +} + +// WithRetryOptions sets the retry options for the delete operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_d *EpisodeDelete) WithRetryOptions(opts ...any) *EpisodeDelete { + _d.retryConfig.Options = opts + return _d +} + +// EpisodeDeleteOne is the builder for deleting a single Episode entity. +type EpisodeDeleteOne struct { + _d *EpisodeDelete +} + +// Where appends a list predicates to the EpisodeDelete builder. +func (_d *EpisodeDeleteOne) Where(ps ...predicate.Episode) *EpisodeDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *EpisodeDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{episode.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *EpisodeDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/examples/ydb/ent/episode_query.go b/examples/ydb/ent/episode_query.go new file mode 100644 index 0000000000..7c7a3d5830 --- /dev/null +++ b/examples/ydb/ent/episode_query.go @@ -0,0 +1,620 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/ydb/ent/episode" + "entgo.io/ent/examples/ydb/ent/predicate" + "entgo.io/ent/examples/ydb/ent/season" + "entgo.io/ent/schema/field" +) + +// EpisodeQuery is the builder for querying Episode entities. +type EpisodeQuery struct { + config + ctx *QueryContext + order []episode.OrderOption + inters []Interceptor + predicates []predicate.Episode + withSeason *SeasonQuery + retryConfig sqlgraph.RetryConfig + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the EpisodeQuery builder. +func (_q *EpisodeQuery) Where(ps ...predicate.Episode) *EpisodeQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *EpisodeQuery) Limit(limit int) *EpisodeQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *EpisodeQuery) Offset(offset int) *EpisodeQuery { + _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 *EpisodeQuery) Unique(unique bool) *EpisodeQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *EpisodeQuery) Order(o ...episode.OrderOption) *EpisodeQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QuerySeason chains the current query on the "season" edge. +func (_q *EpisodeQuery) QuerySeason() *SeasonQuery { + query := (&SeasonClient{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(episode.Table, episode.FieldID, selector), + sqlgraph.To(season.Table, season.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, episode.SeasonTable, episode.SeasonColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Episode entity from the query. +// Returns a *NotFoundError when no Episode was found. +func (_q *EpisodeQuery) First(ctx context.Context) (*Episode, 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{episode.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *EpisodeQuery) FirstX(ctx context.Context) *Episode { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Episode ID from the query. +// Returns a *NotFoundError when no Episode ID was found. +func (_q *EpisodeQuery) FirstID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{episode.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *EpisodeQuery) FirstIDX(ctx context.Context) int64 { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Episode entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Episode entity is found. +// Returns a *NotFoundError when no Episode entities are found. +func (_q *EpisodeQuery) Only(ctx context.Context) (*Episode, 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{episode.Label} + default: + return nil, &NotSingularError{episode.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *EpisodeQuery) OnlyX(ctx context.Context) *Episode { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Episode ID in the query. +// Returns a *NotSingularError when more than one Episode ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *EpisodeQuery) OnlyID(ctx context.Context) (id int64, err error) { + var ids []int64 + 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{episode.Label} + default: + err = &NotSingularError{episode.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *EpisodeQuery) OnlyIDX(ctx context.Context) int64 { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Episodes. +func (_q *EpisodeQuery) All(ctx context.Context) ([]*Episode, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Episode, *EpisodeQuery]() + return withInterceptors[[]*Episode](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *EpisodeQuery) AllX(ctx context.Context) []*Episode { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Episode IDs. +func (_q *EpisodeQuery) IDs(ctx context.Context) (ids []int64, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(episode.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *EpisodeQuery) IDsX(ctx context.Context) []int64 { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *EpisodeQuery) 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[*EpisodeQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *EpisodeQuery) 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 *EpisodeQuery) 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 *EpisodeQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the EpisodeQuery 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 *EpisodeQuery) Clone() *EpisodeQuery { + if _q == nil { + return nil + } + return &EpisodeQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]episode.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Episode{}, _q.predicates...), + withSeason: _q.withSeason.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithSeason tells the query-builder to eager-load the nodes that are connected to +// the "season" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *EpisodeQuery) WithSeason(opts ...func(*SeasonQuery)) *EpisodeQuery { + query := (&SeasonClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSeason = 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 { +// SeasonID int64 `json:"season_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Episode.Query(). +// GroupBy(episode.FieldSeasonID). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *EpisodeQuery) GroupBy(field string, fields ...string) *EpisodeGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &EpisodeGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = episode.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 { +// SeasonID int64 `json:"season_id,omitempty"` +// } +// +// client.Episode.Query(). +// Select(episode.FieldSeasonID). +// Scan(ctx, &v) +func (_q *EpisodeQuery) Select(fields ...string) *EpisodeSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &EpisodeSelect{EpisodeQuery: _q} + sbuild.label = episode.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a EpisodeSelect configured with the given aggregations. +func (_q *EpisodeQuery) Aggregate(fns ...AggregateFunc) *EpisodeSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *EpisodeQuery) 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 !episode.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 *EpisodeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Episode, error) { + var ( + nodes = []*Episode{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withSeason != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Episode).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Episode{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + _spec.RetryConfig = _q.retryConfig + 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.withSeason; query != nil { + if err := _q.loadSeason(ctx, query, nodes, nil, + func(n *Episode, e *Season) { n.Edges.Season = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *EpisodeQuery) loadSeason(ctx context.Context, query *SeasonQuery, nodes []*Episode, init func(*Episode), assign func(*Episode, *Season)) error { + ids := make([]int64, 0, len(nodes)) + nodeids := make(map[int64][]*Episode) + for i := range nodes { + fk := nodes[i].SeasonID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(season.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 "season_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *EpisodeQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.RetryConfig = _q.retryConfig + _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 *EpisodeQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(episode.Table, episode.Columns, sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt64)) + _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, episode.FieldID) + for i := range fields { + if fields[i] != episode.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withSeason != nil { + _spec.Node.AddColumnOnce(episode.FieldSeasonID) + } + } + 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 *EpisodeQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(episode.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = episode.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 _, 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 +} + +// WithRetryOptions sets the retry options for the query operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_q *EpisodeQuery) WithRetryOptions(opts ...any) *EpisodeQuery { + _q.retryConfig.Options = opts + return _q +} + +// EpisodeGroupBy is the group-by builder for Episode entities. +type EpisodeGroupBy struct { + selector + build *EpisodeQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *EpisodeGroupBy) Aggregate(fns ...AggregateFunc) *EpisodeGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *EpisodeGroupBy) 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[*EpisodeQuery, *EpisodeGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *EpisodeGroupBy) sqlScan(ctx context.Context, root *EpisodeQuery, 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) +} + +// EpisodeSelect is the builder for selecting fields of Episode entities. +type EpisodeSelect struct { + *EpisodeQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *EpisodeSelect) Aggregate(fns ...AggregateFunc) *EpisodeSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *EpisodeSelect) 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[*EpisodeQuery, *EpisodeSelect](ctx, _s.EpisodeQuery, _s, _s.inters, v) +} + +func (_s *EpisodeSelect) sqlScan(ctx context.Context, root *EpisodeQuery, 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) +} diff --git a/examples/ydb/ent/episode_update.go b/examples/ydb/ent/episode_update.go new file mode 100644 index 0000000000..16cd9f1359 --- /dev/null +++ b/examples/ydb/ent/episode_update.go @@ -0,0 +1,407 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/ydb/ent/episode" + "entgo.io/ent/examples/ydb/ent/predicate" + "entgo.io/ent/examples/ydb/ent/season" + "entgo.io/ent/schema/field" +) + +// EpisodeUpdate is the builder for updating Episode entities. +type EpisodeUpdate struct { + config + hooks []Hook + mutation *EpisodeMutation + retryConfig sqlgraph.RetryConfig +} + +// Where appends a list predicates to the EpisodeUpdate builder. +func (_u *EpisodeUpdate) Where(ps ...predicate.Episode) *EpisodeUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetSeasonID sets the "season_id" field. +func (_u *EpisodeUpdate) SetSeasonID(v int64) *EpisodeUpdate { + _u.mutation.SetSeasonID(v) + return _u +} + +// SetNillableSeasonID sets the "season_id" field if the given value is not nil. +func (_u *EpisodeUpdate) SetNillableSeasonID(v *int64) *EpisodeUpdate { + if v != nil { + _u.SetSeasonID(*v) + } + return _u +} + +// SetTitle sets the "title" field. +func (_u *EpisodeUpdate) SetTitle(v string) *EpisodeUpdate { + _u.mutation.SetTitle(v) + return _u +} + +// SetNillableTitle sets the "title" field if the given value is not nil. +func (_u *EpisodeUpdate) SetNillableTitle(v *string) *EpisodeUpdate { + if v != nil { + _u.SetTitle(*v) + } + return _u +} + +// SetAirDate sets the "air_date" field. +func (_u *EpisodeUpdate) SetAirDate(v time.Time) *EpisodeUpdate { + _u.mutation.SetAirDate(v) + return _u +} + +// SetNillableAirDate sets the "air_date" field if the given value is not nil. +func (_u *EpisodeUpdate) SetNillableAirDate(v *time.Time) *EpisodeUpdate { + if v != nil { + _u.SetAirDate(*v) + } + return _u +} + +// SetSeason sets the "season" edge to the Season entity. +func (_u *EpisodeUpdate) SetSeason(v *Season) *EpisodeUpdate { + return _u.SetSeasonID(v.ID) +} + +// Mutation returns the EpisodeMutation object of the builder. +func (_u *EpisodeUpdate) Mutation() *EpisodeMutation { + return _u.mutation +} + +// ClearSeason clears the "season" edge to the Season entity. +func (_u *EpisodeUpdate) ClearSeason() *EpisodeUpdate { + _u.mutation.ClearSeason() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *EpisodeUpdate) 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 *EpisodeUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *EpisodeUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *EpisodeUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *EpisodeUpdate) check() error { + if v, ok := _u.mutation.Title(); ok { + if err := episode.TitleValidator(v); err != nil { + return &ValidationError{Name: "title", err: fmt.Errorf(`ent: validator failed for field "Episode.title": %w`, err)} + } + } + if _u.mutation.SeasonCleared() && len(_u.mutation.SeasonIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "Episode.season"`) + } + return nil +} + +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *EpisodeUpdate) WithRetryOptions(opts ...any) *EpisodeUpdate { + _u.retryConfig.Options = opts + return _u +} + +func (_u *EpisodeUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(episode.Table, episode.Columns, sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt64)) + 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.Title(); ok { + _spec.SetField(episode.FieldTitle, field.TypeString, value) + } + if value, ok := _u.mutation.AirDate(); ok { + _spec.SetField(episode.FieldAirDate, field.TypeTime, value) + } + if _u.mutation.SeasonCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: episode.SeasonTable, + Columns: []string{episode.SeasonColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(season.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.SeasonIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: episode.SeasonTable, + Columns: []string{episode.SeasonColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(season.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.RetryConfig = _u.retryConfig + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{episode.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// EpisodeUpdateOne is the builder for updating a single Episode entity. +type EpisodeUpdateOne struct { + config + fields []string + hooks []Hook + mutation *EpisodeMutation + retryConfig sqlgraph.RetryConfig +} + +// SetSeasonID sets the "season_id" field. +func (_u *EpisodeUpdateOne) SetSeasonID(v int64) *EpisodeUpdateOne { + _u.mutation.SetSeasonID(v) + return _u +} + +// SetNillableSeasonID sets the "season_id" field if the given value is not nil. +func (_u *EpisodeUpdateOne) SetNillableSeasonID(v *int64) *EpisodeUpdateOne { + if v != nil { + _u.SetSeasonID(*v) + } + return _u +} + +// SetTitle sets the "title" field. +func (_u *EpisodeUpdateOne) SetTitle(v string) *EpisodeUpdateOne { + _u.mutation.SetTitle(v) + return _u +} + +// SetNillableTitle sets the "title" field if the given value is not nil. +func (_u *EpisodeUpdateOne) SetNillableTitle(v *string) *EpisodeUpdateOne { + if v != nil { + _u.SetTitle(*v) + } + return _u +} + +// SetAirDate sets the "air_date" field. +func (_u *EpisodeUpdateOne) SetAirDate(v time.Time) *EpisodeUpdateOne { + _u.mutation.SetAirDate(v) + return _u +} + +// SetNillableAirDate sets the "air_date" field if the given value is not nil. +func (_u *EpisodeUpdateOne) SetNillableAirDate(v *time.Time) *EpisodeUpdateOne { + if v != nil { + _u.SetAirDate(*v) + } + return _u +} + +// SetSeason sets the "season" edge to the Season entity. +func (_u *EpisodeUpdateOne) SetSeason(v *Season) *EpisodeUpdateOne { + return _u.SetSeasonID(v.ID) +} + +// Mutation returns the EpisodeMutation object of the builder. +func (_u *EpisodeUpdateOne) Mutation() *EpisodeMutation { + return _u.mutation +} + +// ClearSeason clears the "season" edge to the Season entity. +func (_u *EpisodeUpdateOne) ClearSeason() *EpisodeUpdateOne { + _u.mutation.ClearSeason() + return _u +} + +// Where appends a list predicates to the EpisodeUpdate builder. +func (_u *EpisodeUpdateOne) Where(ps ...predicate.Episode) *EpisodeUpdateOne { + _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 *EpisodeUpdateOne) Select(field string, fields ...string) *EpisodeUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Episode entity. +func (_u *EpisodeUpdateOne) Save(ctx context.Context) (*Episode, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *EpisodeUpdateOne) SaveX(ctx context.Context) *Episode { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *EpisodeUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *EpisodeUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *EpisodeUpdateOne) check() error { + if v, ok := _u.mutation.Title(); ok { + if err := episode.TitleValidator(v); err != nil { + return &ValidationError{Name: "title", err: fmt.Errorf(`ent: validator failed for field "Episode.title": %w`, err)} + } + } + if _u.mutation.SeasonCleared() && len(_u.mutation.SeasonIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "Episode.season"`) + } + return nil +} + +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *EpisodeUpdateOne) WithRetryOptions(opts ...any) *EpisodeUpdateOne { + _u.retryConfig.Options = opts + return _u +} + +func (_u *EpisodeUpdateOne) sqlSave(ctx context.Context) (_node *Episode, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(episode.Table, episode.Columns, sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt64)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Episode.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, episode.FieldID) + for _, f := range fields { + if !episode.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != episode.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.Title(); ok { + _spec.SetField(episode.FieldTitle, field.TypeString, value) + } + if value, ok := _u.mutation.AirDate(); ok { + _spec.SetField(episode.FieldAirDate, field.TypeTime, value) + } + if _u.mutation.SeasonCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: episode.SeasonTable, + Columns: []string{episode.SeasonColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(season.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.SeasonIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: episode.SeasonTable, + Columns: []string{episode.SeasonColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(season.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.RetryConfig = _u.retryConfig + _node = &Episode{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{episode.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/examples/ydb/ent/generate.go b/examples/ydb/ent/generate.go new file mode 100644 index 0000000000..14d86db5b5 --- /dev/null +++ b/examples/ydb/ent/generate.go @@ -0,0 +1,7 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +package ent + +//go:generate go run entc.go diff --git a/examples/ydb/ent/hook/hook.go b/examples/ydb/ent/hook/hook.go new file mode 100644 index 0000000000..f833b57ead --- /dev/null +++ b/examples/ydb/ent/hook/hook.go @@ -0,0 +1,227 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package hook + +import ( + "context" + "fmt" + + "entgo.io/ent/examples/ydb/ent" +) + +// The EpisodeFunc type is an adapter to allow the use of ordinary +// function as Episode mutator. +type EpisodeFunc func(context.Context, *ent.EpisodeMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f EpisodeFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.EpisodeMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.EpisodeMutation", m) +} + +// The SeasonFunc type is an adapter to allow the use of ordinary +// function as Season mutator. +type SeasonFunc func(context.Context, *ent.SeasonMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f SeasonFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.SeasonMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.SeasonMutation", m) +} + +// The SeriesFunc type is an adapter to allow the use of ordinary +// function as Series mutator. +type SeriesFunc func(context.Context, *ent.SeriesMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f SeriesFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.SeriesMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.SeriesMutation", 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/examples/ydb/ent/migrate/migrate.go b/examples/ydb/ent/migrate/migrate.go new file mode 100644 index 0000000000..0a632cc3d3 --- /dev/null +++ b/examples/ydb/ent/migrate/migrate.go @@ -0,0 +1,68 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "context" + "fmt" + "io" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql/schema" +) + +var ( + // WithGlobalUniqueID sets the universal ids options to the migration. + // If this option is enabled, ent migration will allocate a 1<<32 range + // for the ids of each entity (table). + // Note that this option cannot be applied on tables that already exist. + WithGlobalUniqueID = schema.WithGlobalUniqueID + // WithDropColumn sets the drop column option to the migration. + // If this option is enabled, ent migration will drop old columns + // that were used for both fields and edges. This defaults to false. + WithDropColumn = schema.WithDropColumn + // WithDropIndex sets the drop index option to the migration. + // If this option is enabled, ent migration will drop old indexes + // that were defined in the schema. This defaults to false. + // Note that unique constraints are defined using `UNIQUE INDEX`, + // and therefore, it's recommended to enable this option to get more + // flexibility in the schema changes. + WithDropIndex = schema.WithDropIndex + // 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/examples/ydb/ent/migrate/schema.go b/examples/ydb/ent/migrate/schema.go new file mode 100644 index 0000000000..fa2f7af054 --- /dev/null +++ b/examples/ydb/ent/migrate/schema.go @@ -0,0 +1,92 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/schema/field" +) + +var ( + // EpisodesColumns holds the columns for the "episodes" table. + EpisodesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt64, Increment: true}, + {Name: "title", Type: field.TypeString}, + {Name: "air_date", Type: field.TypeTime}, + {Name: "season_id", Type: field.TypeInt64}, + } + // EpisodesTable holds the schema information for the "episodes" table. + EpisodesTable = &schema.Table{ + Name: "episodes", + Columns: EpisodesColumns, + PrimaryKey: []*schema.Column{EpisodesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "episodes_seasons_episodes", + Columns: []*schema.Column{EpisodesColumns[3]}, + RefColumns: []*schema.Column{SeasonsColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + } + // SeasonsColumns holds the columns for the "seasons" table. + SeasonsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt64, Increment: true}, + {Name: "title", Type: field.TypeString}, + {Name: "first_aired", Type: field.TypeTime}, + {Name: "last_aired", Type: field.TypeTime}, + {Name: "series_id", Type: field.TypeInt64}, + } + // SeasonsTable holds the schema information for the "seasons" table. + SeasonsTable = &schema.Table{ + Name: "seasons", + Columns: SeasonsColumns, + PrimaryKey: []*schema.Column{SeasonsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "seasons_series_seasons", + Columns: []*schema.Column{SeasonsColumns[4]}, + RefColumns: []*schema.Column{SeriesColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + } + // SeriesColumns holds the columns for the "series" table. + SeriesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt64, Increment: true}, + {Name: "title", Type: field.TypeString}, + {Name: "info", Type: field.TypeString, Nullable: true, Size: 2147483647}, + {Name: "release_date", Type: field.TypeTime}, + } + // SeriesTable holds the schema information for the "series" table. + SeriesTable = &schema.Table{ + Name: "series", + Columns: SeriesColumns, + PrimaryKey: []*schema.Column{SeriesColumns[0]}, + } + // Tables holds all the tables in the schema. + Tables = []*schema.Table{ + EpisodesTable, + SeasonsTable, + SeriesTable, + } +) + +func init() { + EpisodesTable.ForeignKeys[0].RefTable = SeasonsTable + EpisodesTable.Annotation = &entsql.Annotation{ + Table: "episodes", + } + SeasonsTable.ForeignKeys[0].RefTable = SeriesTable + SeasonsTable.Annotation = &entsql.Annotation{ + Table: "seasons", + } + SeriesTable.Annotation = &entsql.Annotation{ + Table: "series", + } +} diff --git a/examples/ydb/ent/mutation.go b/examples/ydb/ent/mutation.go new file mode 100644 index 0000000000..8ad18be334 --- /dev/null +++ b/examples/ydb/ent/mutation.go @@ -0,0 +1,1724 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "sync" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/examples/ydb/ent/episode" + "entgo.io/ent/examples/ydb/ent/predicate" + "entgo.io/ent/examples/ydb/ent/season" + "entgo.io/ent/examples/ydb/ent/series" +) + +const ( + // Operation types. + OpCreate = ent.OpCreate + OpDelete = ent.OpDelete + OpDeleteOne = ent.OpDeleteOne + OpUpdate = ent.OpUpdate + OpUpdateOne = ent.OpUpdateOne + + // Node types. + TypeEpisode = "Episode" + TypeSeason = "Season" + TypeSeries = "Series" +) + +// EpisodeMutation represents an operation that mutates the Episode nodes in the graph. +type EpisodeMutation struct { + config + op Op + typ string + id *int64 + title *string + air_date *time.Time + clearedFields map[string]struct{} + season *int64 + clearedseason bool + done bool + oldValue func(context.Context) (*Episode, error) + predicates []predicate.Episode +} + +var _ ent.Mutation = (*EpisodeMutation)(nil) + +// episodeOption allows management of the mutation configuration using functional options. +type episodeOption func(*EpisodeMutation) + +// newEpisodeMutation creates new mutation for the Episode entity. +func newEpisodeMutation(c config, op Op, opts ...episodeOption) *EpisodeMutation { + m := &EpisodeMutation{ + config: c, + op: op, + typ: TypeEpisode, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withEpisodeID sets the ID field of the mutation. +func withEpisodeID(id int64) episodeOption { + return func(m *EpisodeMutation) { + var ( + err error + once sync.Once + value *Episode + ) + m.oldValue = func(ctx context.Context) (*Episode, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Episode.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withEpisode sets the old Episode of the mutation. +func withEpisode(node *Episode) episodeOption { + return func(m *EpisodeMutation) { + m.oldValue = func(context.Context) (*Episode, 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 EpisodeMutation) 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 EpisodeMutation) 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 +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of Episode entities. +func (m *EpisodeMutation) SetID(id int64) { + m.id = &id +} + +// 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 *EpisodeMutation) ID() (id int64, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// 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 *EpisodeMutation) IDs(ctx context.Context) ([]int64, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int64{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Episode.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetSeasonID sets the "season_id" field. +func (m *EpisodeMutation) SetSeasonID(i int64) { + m.season = &i +} + +// SeasonID returns the value of the "season_id" field in the mutation. +func (m *EpisodeMutation) SeasonID() (r int64, exists bool) { + v := m.season + if v == nil { + return + } + return *v, true +} + +// OldSeasonID returns the old "season_id" field's value of the Episode entity. +// If the Episode 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 *EpisodeMutation) OldSeasonID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSeasonID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSeasonID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSeasonID: %w", err) + } + return oldValue.SeasonID, nil +} + +// ResetSeasonID resets all changes to the "season_id" field. +func (m *EpisodeMutation) ResetSeasonID() { + m.season = nil +} + +// SetTitle sets the "title" field. +func (m *EpisodeMutation) SetTitle(s string) { + m.title = &s +} + +// Title returns the value of the "title" field in the mutation. +func (m *EpisodeMutation) Title() (r string, exists bool) { + v := m.title + if v == nil { + return + } + return *v, true +} + +// OldTitle returns the old "title" field's value of the Episode entity. +// If the Episode 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 *EpisodeMutation) OldTitle(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTitle is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTitle requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTitle: %w", err) + } + return oldValue.Title, nil +} + +// ResetTitle resets all changes to the "title" field. +func (m *EpisodeMutation) ResetTitle() { + m.title = nil +} + +// SetAirDate sets the "air_date" field. +func (m *EpisodeMutation) SetAirDate(t time.Time) { + m.air_date = &t +} + +// AirDate returns the value of the "air_date" field in the mutation. +func (m *EpisodeMutation) AirDate() (r time.Time, exists bool) { + v := m.air_date + if v == nil { + return + } + return *v, true +} + +// OldAirDate returns the old "air_date" field's value of the Episode entity. +// If the Episode 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 *EpisodeMutation) OldAirDate(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAirDate is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAirDate requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAirDate: %w", err) + } + return oldValue.AirDate, nil +} + +// ResetAirDate resets all changes to the "air_date" field. +func (m *EpisodeMutation) ResetAirDate() { + m.air_date = nil +} + +// ClearSeason clears the "season" edge to the Season entity. +func (m *EpisodeMutation) ClearSeason() { + m.clearedseason = true + m.clearedFields[episode.FieldSeasonID] = struct{}{} +} + +// SeasonCleared reports if the "season" edge to the Season entity was cleared. +func (m *EpisodeMutation) SeasonCleared() bool { + return m.clearedseason +} + +// SeasonIDs returns the "season" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SeasonID instead. It exists only for internal usage by the builders. +func (m *EpisodeMutation) SeasonIDs() (ids []int64) { + if id := m.season; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSeason resets all changes to the "season" edge. +func (m *EpisodeMutation) ResetSeason() { + m.season = nil + m.clearedseason = false +} + +// Where appends a list predicates to the EpisodeMutation builder. +func (m *EpisodeMutation) Where(ps ...predicate.Episode) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the EpisodeMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *EpisodeMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Episode, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *EpisodeMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *EpisodeMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Episode). +func (m *EpisodeMutation) 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 *EpisodeMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.season != nil { + fields = append(fields, episode.FieldSeasonID) + } + if m.title != nil { + fields = append(fields, episode.FieldTitle) + } + if m.air_date != nil { + fields = append(fields, episode.FieldAirDate) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *EpisodeMutation) Field(name string) (ent.Value, bool) { + switch name { + case episode.FieldSeasonID: + return m.SeasonID() + case episode.FieldTitle: + return m.Title() + case episode.FieldAirDate: + return m.AirDate() + } + 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 *EpisodeMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case episode.FieldSeasonID: + return m.OldSeasonID(ctx) + case episode.FieldTitle: + return m.OldTitle(ctx) + case episode.FieldAirDate: + return m.OldAirDate(ctx) + } + return nil, fmt.Errorf("unknown Episode field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *EpisodeMutation) SetField(name string, value ent.Value) error { + switch name { + case episode.FieldSeasonID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSeasonID(v) + return nil + case episode.FieldTitle: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTitle(v) + return nil + case episode.FieldAirDate: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAirDate(v) + return nil + } + return fmt.Errorf("unknown Episode field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *EpisodeMutation) AddedFields() []string { + var fields []string + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *EpisodeMutation) AddedField(name string) (ent.Value, bool) { + switch name { + } + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *EpisodeMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Episode numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *EpisodeMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *EpisodeMutation) 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 *EpisodeMutation) ClearField(name string) error { + return fmt.Errorf("unknown Episode 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 *EpisodeMutation) ResetField(name string) error { + switch name { + case episode.FieldSeasonID: + m.ResetSeasonID() + return nil + case episode.FieldTitle: + m.ResetTitle() + return nil + case episode.FieldAirDate: + m.ResetAirDate() + return nil + } + return fmt.Errorf("unknown Episode field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *EpisodeMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.season != nil { + edges = append(edges, episode.EdgeSeason) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *EpisodeMutation) AddedIDs(name string) []ent.Value { + switch name { + case episode.EdgeSeason: + if id := m.season; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *EpisodeMutation) 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 *EpisodeMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *EpisodeMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedseason { + edges = append(edges, episode.EdgeSeason) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *EpisodeMutation) EdgeCleared(name string) bool { + switch name { + case episode.EdgeSeason: + return m.clearedseason + } + 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 *EpisodeMutation) ClearEdge(name string) error { + switch name { + case episode.EdgeSeason: + m.ClearSeason() + return nil + } + return fmt.Errorf("unknown Episode 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 *EpisodeMutation) ResetEdge(name string) error { + switch name { + case episode.EdgeSeason: + m.ResetSeason() + return nil + } + return fmt.Errorf("unknown Episode edge %s", name) +} + +// SeasonMutation represents an operation that mutates the Season nodes in the graph. +type SeasonMutation struct { + config + op Op + typ string + id *int64 + title *string + first_aired *time.Time + last_aired *time.Time + clearedFields map[string]struct{} + series *int64 + clearedseries bool + episodes map[int64]struct{} + removedepisodes map[int64]struct{} + clearedepisodes bool + done bool + oldValue func(context.Context) (*Season, error) + predicates []predicate.Season +} + +var _ ent.Mutation = (*SeasonMutation)(nil) + +// seasonOption allows management of the mutation configuration using functional options. +type seasonOption func(*SeasonMutation) + +// newSeasonMutation creates new mutation for the Season entity. +func newSeasonMutation(c config, op Op, opts ...seasonOption) *SeasonMutation { + m := &SeasonMutation{ + config: c, + op: op, + typ: TypeSeason, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withSeasonID sets the ID field of the mutation. +func withSeasonID(id int64) seasonOption { + return func(m *SeasonMutation) { + var ( + err error + once sync.Once + value *Season + ) + m.oldValue = func(ctx context.Context) (*Season, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Season.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withSeason sets the old Season of the mutation. +func withSeason(node *Season) seasonOption { + return func(m *SeasonMutation) { + m.oldValue = func(context.Context) (*Season, 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 SeasonMutation) 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 SeasonMutation) 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 +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of Season entities. +func (m *SeasonMutation) SetID(id int64) { + m.id = &id +} + +// 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 *SeasonMutation) ID() (id int64, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// 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 *SeasonMutation) IDs(ctx context.Context) ([]int64, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int64{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Season.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetSeriesID sets the "series_id" field. +func (m *SeasonMutation) SetSeriesID(i int64) { + m.series = &i +} + +// SeriesID returns the value of the "series_id" field in the mutation. +func (m *SeasonMutation) SeriesID() (r int64, exists bool) { + v := m.series + if v == nil { + return + } + return *v, true +} + +// OldSeriesID returns the old "series_id" field's value of the Season entity. +// If the Season 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 *SeasonMutation) OldSeriesID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSeriesID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSeriesID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSeriesID: %w", err) + } + return oldValue.SeriesID, nil +} + +// ResetSeriesID resets all changes to the "series_id" field. +func (m *SeasonMutation) ResetSeriesID() { + m.series = nil +} + +// SetTitle sets the "title" field. +func (m *SeasonMutation) SetTitle(s string) { + m.title = &s +} + +// Title returns the value of the "title" field in the mutation. +func (m *SeasonMutation) Title() (r string, exists bool) { + v := m.title + if v == nil { + return + } + return *v, true +} + +// OldTitle returns the old "title" field's value of the Season entity. +// If the Season 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 *SeasonMutation) OldTitle(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTitle is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTitle requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTitle: %w", err) + } + return oldValue.Title, nil +} + +// ResetTitle resets all changes to the "title" field. +func (m *SeasonMutation) ResetTitle() { + m.title = nil +} + +// SetFirstAired sets the "first_aired" field. +func (m *SeasonMutation) SetFirstAired(t time.Time) { + m.first_aired = &t +} + +// FirstAired returns the value of the "first_aired" field in the mutation. +func (m *SeasonMutation) FirstAired() (r time.Time, exists bool) { + v := m.first_aired + if v == nil { + return + } + return *v, true +} + +// OldFirstAired returns the old "first_aired" field's value of the Season entity. +// If the Season 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 *SeasonMutation) OldFirstAired(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFirstAired is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFirstAired requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFirstAired: %w", err) + } + return oldValue.FirstAired, nil +} + +// ResetFirstAired resets all changes to the "first_aired" field. +func (m *SeasonMutation) ResetFirstAired() { + m.first_aired = nil +} + +// SetLastAired sets the "last_aired" field. +func (m *SeasonMutation) SetLastAired(t time.Time) { + m.last_aired = &t +} + +// LastAired returns the value of the "last_aired" field in the mutation. +func (m *SeasonMutation) LastAired() (r time.Time, exists bool) { + v := m.last_aired + if v == nil { + return + } + return *v, true +} + +// OldLastAired returns the old "last_aired" field's value of the Season entity. +// If the Season 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 *SeasonMutation) OldLastAired(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLastAired is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLastAired requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLastAired: %w", err) + } + return oldValue.LastAired, nil +} + +// ResetLastAired resets all changes to the "last_aired" field. +func (m *SeasonMutation) ResetLastAired() { + m.last_aired = nil +} + +// ClearSeries clears the "series" edge to the Series entity. +func (m *SeasonMutation) ClearSeries() { + m.clearedseries = true + m.clearedFields[season.FieldSeriesID] = struct{}{} +} + +// SeriesCleared reports if the "series" edge to the Series entity was cleared. +func (m *SeasonMutation) SeriesCleared() bool { + return m.clearedseries +} + +// SeriesIDs returns the "series" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SeriesID instead. It exists only for internal usage by the builders. +func (m *SeasonMutation) SeriesIDs() (ids []int64) { + if id := m.series; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSeries resets all changes to the "series" edge. +func (m *SeasonMutation) ResetSeries() { + m.series = nil + m.clearedseries = false +} + +// AddEpisodeIDs adds the "episodes" edge to the Episode entity by ids. +func (m *SeasonMutation) AddEpisodeIDs(ids ...int64) { + if m.episodes == nil { + m.episodes = make(map[int64]struct{}) + } + for i := range ids { + m.episodes[ids[i]] = struct{}{} + } +} + +// ClearEpisodes clears the "episodes" edge to the Episode entity. +func (m *SeasonMutation) ClearEpisodes() { + m.clearedepisodes = true +} + +// EpisodesCleared reports if the "episodes" edge to the Episode entity was cleared. +func (m *SeasonMutation) EpisodesCleared() bool { + return m.clearedepisodes +} + +// RemoveEpisodeIDs removes the "episodes" edge to the Episode entity by IDs. +func (m *SeasonMutation) RemoveEpisodeIDs(ids ...int64) { + if m.removedepisodes == nil { + m.removedepisodes = make(map[int64]struct{}) + } + for i := range ids { + delete(m.episodes, ids[i]) + m.removedepisodes[ids[i]] = struct{}{} + } +} + +// RemovedEpisodes returns the removed IDs of the "episodes" edge to the Episode entity. +func (m *SeasonMutation) RemovedEpisodesIDs() (ids []int64) { + for id := range m.removedepisodes { + ids = append(ids, id) + } + return +} + +// EpisodesIDs returns the "episodes" edge IDs in the mutation. +func (m *SeasonMutation) EpisodesIDs() (ids []int64) { + for id := range m.episodes { + ids = append(ids, id) + } + return +} + +// ResetEpisodes resets all changes to the "episodes" edge. +func (m *SeasonMutation) ResetEpisodes() { + m.episodes = nil + m.clearedepisodes = false + m.removedepisodes = nil +} + +// Where appends a list predicates to the SeasonMutation builder. +func (m *SeasonMutation) Where(ps ...predicate.Season) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the SeasonMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *SeasonMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Season, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *SeasonMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *SeasonMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Season). +func (m *SeasonMutation) 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 *SeasonMutation) Fields() []string { + fields := make([]string, 0, 4) + if m.series != nil { + fields = append(fields, season.FieldSeriesID) + } + if m.title != nil { + fields = append(fields, season.FieldTitle) + } + if m.first_aired != nil { + fields = append(fields, season.FieldFirstAired) + } + if m.last_aired != nil { + fields = append(fields, season.FieldLastAired) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *SeasonMutation) Field(name string) (ent.Value, bool) { + switch name { + case season.FieldSeriesID: + return m.SeriesID() + case season.FieldTitle: + return m.Title() + case season.FieldFirstAired: + return m.FirstAired() + case season.FieldLastAired: + return m.LastAired() + } + 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 *SeasonMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case season.FieldSeriesID: + return m.OldSeriesID(ctx) + case season.FieldTitle: + return m.OldTitle(ctx) + case season.FieldFirstAired: + return m.OldFirstAired(ctx) + case season.FieldLastAired: + return m.OldLastAired(ctx) + } + return nil, fmt.Errorf("unknown Season field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *SeasonMutation) SetField(name string, value ent.Value) error { + switch name { + case season.FieldSeriesID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSeriesID(v) + return nil + case season.FieldTitle: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTitle(v) + return nil + case season.FieldFirstAired: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFirstAired(v) + return nil + case season.FieldLastAired: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLastAired(v) + return nil + } + return fmt.Errorf("unknown Season field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *SeasonMutation) AddedFields() []string { + var fields []string + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *SeasonMutation) AddedField(name string) (ent.Value, bool) { + switch name { + } + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *SeasonMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Season numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *SeasonMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *SeasonMutation) 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 *SeasonMutation) ClearField(name string) error { + return fmt.Errorf("unknown Season 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 *SeasonMutation) ResetField(name string) error { + switch name { + case season.FieldSeriesID: + m.ResetSeriesID() + return nil + case season.FieldTitle: + m.ResetTitle() + return nil + case season.FieldFirstAired: + m.ResetFirstAired() + return nil + case season.FieldLastAired: + m.ResetLastAired() + return nil + } + return fmt.Errorf("unknown Season field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *SeasonMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.series != nil { + edges = append(edges, season.EdgeSeries) + } + if m.episodes != nil { + edges = append(edges, season.EdgeEpisodes) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *SeasonMutation) AddedIDs(name string) []ent.Value { + switch name { + case season.EdgeSeries: + if id := m.series; id != nil { + return []ent.Value{*id} + } + case season.EdgeEpisodes: + ids := make([]ent.Value, 0, len(m.episodes)) + for id := range m.episodes { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *SeasonMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removedepisodes != nil { + edges = append(edges, season.EdgeEpisodes) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *SeasonMutation) RemovedIDs(name string) []ent.Value { + switch name { + case season.EdgeEpisodes: + ids := make([]ent.Value, 0, len(m.removedepisodes)) + for id := range m.removedepisodes { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *SeasonMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedseries { + edges = append(edges, season.EdgeSeries) + } + if m.clearedepisodes { + edges = append(edges, season.EdgeEpisodes) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *SeasonMutation) EdgeCleared(name string) bool { + switch name { + case season.EdgeSeries: + return m.clearedseries + case season.EdgeEpisodes: + return m.clearedepisodes + } + 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 *SeasonMutation) ClearEdge(name string) error { + switch name { + case season.EdgeSeries: + m.ClearSeries() + return nil + } + return fmt.Errorf("unknown Season 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 *SeasonMutation) ResetEdge(name string) error { + switch name { + case season.EdgeSeries: + m.ResetSeries() + return nil + case season.EdgeEpisodes: + m.ResetEpisodes() + return nil + } + return fmt.Errorf("unknown Season edge %s", name) +} + +// SeriesMutation represents an operation that mutates the Series nodes in the graph. +type SeriesMutation struct { + config + op Op + typ string + id *int64 + title *string + info *string + release_date *time.Time + clearedFields map[string]struct{} + seasons map[int64]struct{} + removedseasons map[int64]struct{} + clearedseasons bool + done bool + oldValue func(context.Context) (*Series, error) + predicates []predicate.Series +} + +var _ ent.Mutation = (*SeriesMutation)(nil) + +// seriesOption allows management of the mutation configuration using functional options. +type seriesOption func(*SeriesMutation) + +// newSeriesMutation creates new mutation for the Series entity. +func newSeriesMutation(c config, op Op, opts ...seriesOption) *SeriesMutation { + m := &SeriesMutation{ + config: c, + op: op, + typ: TypeSeries, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withSeriesID sets the ID field of the mutation. +func withSeriesID(id int64) seriesOption { + return func(m *SeriesMutation) { + var ( + err error + once sync.Once + value *Series + ) + m.oldValue = func(ctx context.Context) (*Series, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Series.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withSeries sets the old Series of the mutation. +func withSeries(node *Series) seriesOption { + return func(m *SeriesMutation) { + m.oldValue = func(context.Context) (*Series, 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 SeriesMutation) 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 SeriesMutation) 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 +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of Series entities. +func (m *SeriesMutation) SetID(id int64) { + m.id = &id +} + +// 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 *SeriesMutation) ID() (id int64, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// 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 *SeriesMutation) IDs(ctx context.Context) ([]int64, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int64{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Series.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetTitle sets the "title" field. +func (m *SeriesMutation) SetTitle(s string) { + m.title = &s +} + +// Title returns the value of the "title" field in the mutation. +func (m *SeriesMutation) Title() (r string, exists bool) { + v := m.title + if v == nil { + return + } + return *v, true +} + +// OldTitle returns the old "title" field's value of the Series entity. +// If the Series 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 *SeriesMutation) OldTitle(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTitle is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTitle requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTitle: %w", err) + } + return oldValue.Title, nil +} + +// ResetTitle resets all changes to the "title" field. +func (m *SeriesMutation) ResetTitle() { + m.title = nil +} + +// SetInfo sets the "info" field. +func (m *SeriesMutation) SetInfo(s string) { + m.info = &s +} + +// Info returns the value of the "info" field in the mutation. +func (m *SeriesMutation) Info() (r string, exists bool) { + v := m.info + if v == nil { + return + } + return *v, true +} + +// OldInfo returns the old "info" field's value of the Series entity. +// If the Series 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 *SeriesMutation) OldInfo(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInfo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInfo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInfo: %w", err) + } + return oldValue.Info, nil +} + +// ClearInfo clears the value of the "info" field. +func (m *SeriesMutation) ClearInfo() { + m.info = nil + m.clearedFields[series.FieldInfo] = struct{}{} +} + +// InfoCleared returns if the "info" field was cleared in this mutation. +func (m *SeriesMutation) InfoCleared() bool { + _, ok := m.clearedFields[series.FieldInfo] + return ok +} + +// ResetInfo resets all changes to the "info" field. +func (m *SeriesMutation) ResetInfo() { + m.info = nil + delete(m.clearedFields, series.FieldInfo) +} + +// SetReleaseDate sets the "release_date" field. +func (m *SeriesMutation) SetReleaseDate(t time.Time) { + m.release_date = &t +} + +// ReleaseDate returns the value of the "release_date" field in the mutation. +func (m *SeriesMutation) ReleaseDate() (r time.Time, exists bool) { + v := m.release_date + if v == nil { + return + } + return *v, true +} + +// OldReleaseDate returns the old "release_date" field's value of the Series entity. +// If the Series 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 *SeriesMutation) OldReleaseDate(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldReleaseDate is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldReleaseDate requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldReleaseDate: %w", err) + } + return oldValue.ReleaseDate, nil +} + +// ResetReleaseDate resets all changes to the "release_date" field. +func (m *SeriesMutation) ResetReleaseDate() { + m.release_date = nil +} + +// AddSeasonIDs adds the "seasons" edge to the Season entity by ids. +func (m *SeriesMutation) AddSeasonIDs(ids ...int64) { + if m.seasons == nil { + m.seasons = make(map[int64]struct{}) + } + for i := range ids { + m.seasons[ids[i]] = struct{}{} + } +} + +// ClearSeasons clears the "seasons" edge to the Season entity. +func (m *SeriesMutation) ClearSeasons() { + m.clearedseasons = true +} + +// SeasonsCleared reports if the "seasons" edge to the Season entity was cleared. +func (m *SeriesMutation) SeasonsCleared() bool { + return m.clearedseasons +} + +// RemoveSeasonIDs removes the "seasons" edge to the Season entity by IDs. +func (m *SeriesMutation) RemoveSeasonIDs(ids ...int64) { + if m.removedseasons == nil { + m.removedseasons = make(map[int64]struct{}) + } + for i := range ids { + delete(m.seasons, ids[i]) + m.removedseasons[ids[i]] = struct{}{} + } +} + +// RemovedSeasons returns the removed IDs of the "seasons" edge to the Season entity. +func (m *SeriesMutation) RemovedSeasonsIDs() (ids []int64) { + for id := range m.removedseasons { + ids = append(ids, id) + } + return +} + +// SeasonsIDs returns the "seasons" edge IDs in the mutation. +func (m *SeriesMutation) SeasonsIDs() (ids []int64) { + for id := range m.seasons { + ids = append(ids, id) + } + return +} + +// ResetSeasons resets all changes to the "seasons" edge. +func (m *SeriesMutation) ResetSeasons() { + m.seasons = nil + m.clearedseasons = false + m.removedseasons = nil +} + +// Where appends a list predicates to the SeriesMutation builder. +func (m *SeriesMutation) Where(ps ...predicate.Series) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the SeriesMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *SeriesMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Series, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *SeriesMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *SeriesMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Series). +func (m *SeriesMutation) 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 *SeriesMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.title != nil { + fields = append(fields, series.FieldTitle) + } + if m.info != nil { + fields = append(fields, series.FieldInfo) + } + if m.release_date != nil { + fields = append(fields, series.FieldReleaseDate) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *SeriesMutation) Field(name string) (ent.Value, bool) { + switch name { + case series.FieldTitle: + return m.Title() + case series.FieldInfo: + return m.Info() + case series.FieldReleaseDate: + return m.ReleaseDate() + } + 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 *SeriesMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case series.FieldTitle: + return m.OldTitle(ctx) + case series.FieldInfo: + return m.OldInfo(ctx) + case series.FieldReleaseDate: + return m.OldReleaseDate(ctx) + } + return nil, fmt.Errorf("unknown Series field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *SeriesMutation) SetField(name string, value ent.Value) error { + switch name { + case series.FieldTitle: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTitle(v) + return nil + case series.FieldInfo: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInfo(v) + return nil + case series.FieldReleaseDate: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetReleaseDate(v) + return nil + } + return fmt.Errorf("unknown Series field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *SeriesMutation) AddedFields() []string { + return nil +} + +// 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 *SeriesMutation) AddedField(name string) (ent.Value, bool) { + 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 *SeriesMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Series numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *SeriesMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(series.FieldInfo) { + fields = append(fields, series.FieldInfo) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *SeriesMutation) 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 *SeriesMutation) ClearField(name string) error { + switch name { + case series.FieldInfo: + m.ClearInfo() + return nil + } + return fmt.Errorf("unknown Series 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 *SeriesMutation) ResetField(name string) error { + switch name { + case series.FieldTitle: + m.ResetTitle() + return nil + case series.FieldInfo: + m.ResetInfo() + return nil + case series.FieldReleaseDate: + m.ResetReleaseDate() + return nil + } + return fmt.Errorf("unknown Series field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *SeriesMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.seasons != nil { + edges = append(edges, series.EdgeSeasons) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *SeriesMutation) AddedIDs(name string) []ent.Value { + switch name { + case series.EdgeSeasons: + ids := make([]ent.Value, 0, len(m.seasons)) + for id := range m.seasons { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *SeriesMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + if m.removedseasons != nil { + edges = append(edges, series.EdgeSeasons) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *SeriesMutation) RemovedIDs(name string) []ent.Value { + switch name { + case series.EdgeSeasons: + ids := make([]ent.Value, 0, len(m.removedseasons)) + for id := range m.removedseasons { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *SeriesMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedseasons { + edges = append(edges, series.EdgeSeasons) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *SeriesMutation) EdgeCleared(name string) bool { + switch name { + case series.EdgeSeasons: + return m.clearedseasons + } + 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 *SeriesMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown Series 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 *SeriesMutation) ResetEdge(name string) error { + switch name { + case series.EdgeSeasons: + m.ResetSeasons() + return nil + } + return fmt.Errorf("unknown Series edge %s", name) +} diff --git a/examples/ydb/ent/predicate/predicate.go b/examples/ydb/ent/predicate/predicate.go new file mode 100644 index 0000000000..dc4baef3df --- /dev/null +++ b/examples/ydb/ent/predicate/predicate.go @@ -0,0 +1,20 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package predicate + +import ( + "entgo.io/ent/dialect/sql" +) + +// Episode is the predicate function for episode builders. +type Episode func(*sql.Selector) + +// Season is the predicate function for season builders. +type Season func(*sql.Selector) + +// Series is the predicate function for series builders. +type Series func(*sql.Selector) diff --git a/examples/ydb/ent/runtime.go b/examples/ydb/ent/runtime.go new file mode 100644 index 0000000000..d986e8a6e2 --- /dev/null +++ b/examples/ydb/ent/runtime.go @@ -0,0 +1,38 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "entgo.io/ent/examples/ydb/ent/episode" + "entgo.io/ent/examples/ydb/ent/schema" + "entgo.io/ent/examples/ydb/ent/season" + "entgo.io/ent/examples/ydb/ent/series" +) + +// 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() { + episodeFields := schema.Episode{}.Fields() + _ = episodeFields + // episodeDescTitle is the schema descriptor for title field. + episodeDescTitle := episodeFields[2].Descriptor() + // episode.TitleValidator is a validator for the "title" field. It is called by the builders before save. + episode.TitleValidator = episodeDescTitle.Validators[0].(func(string) error) + seasonFields := schema.Season{}.Fields() + _ = seasonFields + // seasonDescTitle is the schema descriptor for title field. + seasonDescTitle := seasonFields[2].Descriptor() + // season.TitleValidator is a validator for the "title" field. It is called by the builders before save. + season.TitleValidator = seasonDescTitle.Validators[0].(func(string) error) + seriesFields := schema.Series{}.Fields() + _ = seriesFields + // seriesDescTitle is the schema descriptor for title field. + seriesDescTitle := seriesFields[1].Descriptor() + // series.TitleValidator is a validator for the "title" field. It is called by the builders before save. + series.TitleValidator = seriesDescTitle.Validators[0].(func(string) error) +} diff --git a/examples/ydb/ent/runtime/runtime.go b/examples/ydb/ent/runtime/runtime.go new file mode 100644 index 0000000000..c51f42a630 --- /dev/null +++ b/examples/ydb/ent/runtime/runtime.go @@ -0,0 +1,13 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package runtime + +// The schema-stitching logic is generated in entgo.io/ent/examples/ydb/ent/runtime.go + +const ( + Version = "v0.0.0-00010101000000-000000000000" // Version of ent codegen. +) diff --git a/examples/ydb/ent/schema/episode.go b/examples/ydb/ent/schema/episode.go new file mode 100644 index 0000000000..e7a7ad4fac --- /dev/null +++ b/examples/ydb/ent/schema/episode.go @@ -0,0 +1,47 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +// Episode holds the schema definition for the Episode entity. +type Episode struct { + ent.Schema +} + +// Annotations of the Episode. +func (Episode) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Annotation{Table: "episodes"}, + } +} + +// Fields of the Episode. +func (Episode) Fields() []ent.Field { + return []ent.Field{ + field.Int64("id"), + field.Int64("season_id"), + field.String("title"). + NotEmpty(), + field.Time("air_date"), + } +} + +// Edges of the Episode. +func (Episode) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("season", Season.Type). + Ref("episodes"). + Unique(). + Required(). + Field("season_id"), + } +} diff --git a/examples/ydb/ent/schema/season.go b/examples/ydb/ent/schema/season.go new file mode 100644 index 0000000000..3093dc144b --- /dev/null +++ b/examples/ydb/ent/schema/season.go @@ -0,0 +1,49 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +// Season holds the schema definition for the Season entity. +type Season struct { + ent.Schema +} + +// Annotations of the Season. +func (Season) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Annotation{Table: "seasons"}, + } +} + +// Fields of the Season. +func (Season) Fields() []ent.Field { + return []ent.Field{ + field.Int64("id"), + field.Int64("series_id"), + field.String("title"). + NotEmpty(), + field.Time("first_aired"), + field.Time("last_aired"), + } +} + +// Edges of the Season. +func (Season) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("series", Series.Type). + Ref("seasons"). + Unique(). + Required(). + Field("series_id"), + edge.To("episodes", Episode.Type), + } +} diff --git a/examples/ydb/ent/schema/series.go b/examples/ydb/ent/schema/series.go new file mode 100644 index 0000000000..b50678bd43 --- /dev/null +++ b/examples/ydb/ent/schema/series.go @@ -0,0 +1,44 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +// Series holds the schema definition for the Series entity. +type Series struct { + ent.Schema +} + +// Annotations of the Series. +func (Series) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Annotation{Table: "series"}, + } +} + +// Fields of the Series. +func (Series) Fields() []ent.Field { + return []ent.Field{ + field.Int64("id"), + field.String("title"). + NotEmpty(), + field.Text("info"). + Optional(), + field.Time("release_date"), + } +} + +// Edges of the Series. +func (Series) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("seasons", Season.Type), + } +} diff --git a/examples/ydb/ent/season.go b/examples/ydb/ent/season.go new file mode 100644 index 0000000000..eb808605fc --- /dev/null +++ b/examples/ydb/ent/season.go @@ -0,0 +1,188 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/examples/ydb/ent/season" + "entgo.io/ent/examples/ydb/ent/series" +) + +// Season is the model entity for the Season schema. +type Season struct { + config `json:"-"` + // ID of the ent. + ID int64 `json:"id,omitempty"` + // SeriesID holds the value of the "series_id" field. + SeriesID int64 `json:"series_id,omitempty"` + // Title holds the value of the "title" field. + Title string `json:"title,omitempty"` + // FirstAired holds the value of the "first_aired" field. + FirstAired time.Time `json:"first_aired,omitempty"` + // LastAired holds the value of the "last_aired" field. + LastAired time.Time `json:"last_aired,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the SeasonQuery when eager-loading is set. + Edges SeasonEdges `json:"edges"` + selectValues sql.SelectValues +} + +// SeasonEdges holds the relations/edges for other nodes in the graph. +type SeasonEdges struct { + // Series holds the value of the series edge. + Series *Series `json:"series,omitempty"` + // Episodes holds the value of the episodes edge. + Episodes []*Episode `json:"episodes,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// SeriesOrErr returns the Series value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e SeasonEdges) SeriesOrErr() (*Series, error) { + if e.Series != nil { + return e.Series, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: series.Label} + } + return nil, &NotLoadedError{edge: "series"} +} + +// EpisodesOrErr returns the Episodes value or an error if the edge +// was not loaded in eager-loading. +func (e SeasonEdges) EpisodesOrErr() ([]*Episode, error) { + if e.loadedTypes[1] { + return e.Episodes, nil + } + return nil, &NotLoadedError{edge: "episodes"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Season) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case season.FieldID, season.FieldSeriesID: + values[i] = new(sql.NullInt64) + case season.FieldTitle: + values[i] = new(sql.NullString) + case season.FieldFirstAired, season.FieldLastAired: + values[i] = new(sql.NullTime) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Season fields. +func (_m *Season) 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 season.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int64(value.Int64) + case season.FieldSeriesID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field series_id", values[i]) + } else if value.Valid { + _m.SeriesID = value.Int64 + } + case season.FieldTitle: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field title", values[i]) + } else if value.Valid { + _m.Title = value.String + } + case season.FieldFirstAired: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field first_aired", values[i]) + } else if value.Valid { + _m.FirstAired = value.Time + } + case season.FieldLastAired: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field last_aired", values[i]) + } else if value.Valid { + _m.LastAired = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Season. +// This includes values selected through modifiers, order, etc. +func (_m *Season) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QuerySeries queries the "series" edge of the Season entity. +func (_m *Season) QuerySeries() *SeriesQuery { + return NewSeasonClient(_m.config).QuerySeries(_m) +} + +// QueryEpisodes queries the "episodes" edge of the Season entity. +func (_m *Season) QueryEpisodes() *EpisodeQuery { + return NewSeasonClient(_m.config).QueryEpisodes(_m) +} + +// Update returns a builder for updating this Season. +// Note that you need to call Season.Unwrap() before calling this method if this Season +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Season) Update() *SeasonUpdateOne { + return NewSeasonClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Season 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 *Season) Unwrap() *Season { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: Season is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Season) String() string { + var builder strings.Builder + builder.WriteString("Season(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("series_id=") + builder.WriteString(fmt.Sprintf("%v", _m.SeriesID)) + builder.WriteString(", ") + builder.WriteString("title=") + builder.WriteString(_m.Title) + builder.WriteString(", ") + builder.WriteString("first_aired=") + builder.WriteString(_m.FirstAired.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("last_aired=") + builder.WriteString(_m.LastAired.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// Seasons is a parsable slice of Season. +type Seasons []*Season diff --git a/examples/ydb/ent/season/season.go b/examples/ydb/ent/season/season.go new file mode 100644 index 0000000000..c1919974ba --- /dev/null +++ b/examples/ydb/ent/season/season.go @@ -0,0 +1,134 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package season + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the season type in the database. + Label = "season" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldSeriesID holds the string denoting the series_id field in the database. + FieldSeriesID = "series_id" + // FieldTitle holds the string denoting the title field in the database. + FieldTitle = "title" + // FieldFirstAired holds the string denoting the first_aired field in the database. + FieldFirstAired = "first_aired" + // FieldLastAired holds the string denoting the last_aired field in the database. + FieldLastAired = "last_aired" + // EdgeSeries holds the string denoting the series edge name in mutations. + EdgeSeries = "series" + // EdgeEpisodes holds the string denoting the episodes edge name in mutations. + EdgeEpisodes = "episodes" + // Table holds the table name of the season in the database. + Table = "seasons" + // SeriesTable is the table that holds the series relation/edge. + SeriesTable = "seasons" + // SeriesInverseTable is the table name for the Series entity. + // It exists in this package in order to avoid circular dependency with the "series" package. + SeriesInverseTable = "series" + // SeriesColumn is the table column denoting the series relation/edge. + SeriesColumn = "series_id" + // EpisodesTable is the table that holds the episodes relation/edge. + EpisodesTable = "episodes" + // EpisodesInverseTable is the table name for the Episode entity. + // It exists in this package in order to avoid circular dependency with the "episode" package. + EpisodesInverseTable = "episodes" + // EpisodesColumn is the table column denoting the episodes relation/edge. + EpisodesColumn = "season_id" +) + +// Columns holds all SQL columns for season fields. +var Columns = []string{ + FieldID, + FieldSeriesID, + FieldTitle, + FieldFirstAired, + FieldLastAired, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // TitleValidator is a validator for the "title" field. It is called by the builders before save. + TitleValidator func(string) error +) + +// OrderOption defines the ordering options for the Season 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() +} + +// BySeriesID orders the results by the series_id field. +func BySeriesID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSeriesID, opts...).ToFunc() +} + +// ByTitle orders the results by the title field. +func ByTitle(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTitle, opts...).ToFunc() +} + +// ByFirstAired orders the results by the first_aired field. +func ByFirstAired(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFirstAired, opts...).ToFunc() +} + +// ByLastAired orders the results by the last_aired field. +func ByLastAired(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLastAired, opts...).ToFunc() +} + +// BySeriesField orders the results by series field. +func BySeriesField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSeriesStep(), sql.OrderByField(field, opts...)) + } +} + +// ByEpisodesCount orders the results by episodes count. +func ByEpisodesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newEpisodesStep(), opts...) + } +} + +// ByEpisodes orders the results by episodes terms. +func ByEpisodes(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newEpisodesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newSeriesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SeriesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SeriesTable, SeriesColumn), + ) +} +func newEpisodesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(EpisodesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, EpisodesTable, EpisodesColumn), + ) +} diff --git a/examples/ydb/ent/season/where.go b/examples/ydb/ent/season/where.go new file mode 100644 index 0000000000..801bf07703 --- /dev/null +++ b/examples/ydb/ent/season/where.go @@ -0,0 +1,306 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package season + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/ydb/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int64) predicate.Season { + return predicate.Season(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int64) predicate.Season { + return predicate.Season(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int64) predicate.Season { + return predicate.Season(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int64) predicate.Season { + return predicate.Season(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int64) predicate.Season { + return predicate.Season(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int64) predicate.Season { + return predicate.Season(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int64) predicate.Season { + return predicate.Season(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int64) predicate.Season { + return predicate.Season(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int64) predicate.Season { + return predicate.Season(sql.FieldLTE(FieldID, id)) +} + +// SeriesID applies equality check predicate on the "series_id" field. It's identical to SeriesIDEQ. +func SeriesID(v int64) predicate.Season { + return predicate.Season(sql.FieldEQ(FieldSeriesID, v)) +} + +// Title applies equality check predicate on the "title" field. It's identical to TitleEQ. +func Title(v string) predicate.Season { + return predicate.Season(sql.FieldEQ(FieldTitle, v)) +} + +// FirstAired applies equality check predicate on the "first_aired" field. It's identical to FirstAiredEQ. +func FirstAired(v time.Time) predicate.Season { + return predicate.Season(sql.FieldEQ(FieldFirstAired, v)) +} + +// LastAired applies equality check predicate on the "last_aired" field. It's identical to LastAiredEQ. +func LastAired(v time.Time) predicate.Season { + return predicate.Season(sql.FieldEQ(FieldLastAired, v)) +} + +// SeriesIDEQ applies the EQ predicate on the "series_id" field. +func SeriesIDEQ(v int64) predicate.Season { + return predicate.Season(sql.FieldEQ(FieldSeriesID, v)) +} + +// SeriesIDNEQ applies the NEQ predicate on the "series_id" field. +func SeriesIDNEQ(v int64) predicate.Season { + return predicate.Season(sql.FieldNEQ(FieldSeriesID, v)) +} + +// SeriesIDIn applies the In predicate on the "series_id" field. +func SeriesIDIn(vs ...int64) predicate.Season { + return predicate.Season(sql.FieldIn(FieldSeriesID, vs...)) +} + +// SeriesIDNotIn applies the NotIn predicate on the "series_id" field. +func SeriesIDNotIn(vs ...int64) predicate.Season { + return predicate.Season(sql.FieldNotIn(FieldSeriesID, vs...)) +} + +// TitleEQ applies the EQ predicate on the "title" field. +func TitleEQ(v string) predicate.Season { + return predicate.Season(sql.FieldEQ(FieldTitle, v)) +} + +// TitleNEQ applies the NEQ predicate on the "title" field. +func TitleNEQ(v string) predicate.Season { + return predicate.Season(sql.FieldNEQ(FieldTitle, v)) +} + +// TitleIn applies the In predicate on the "title" field. +func TitleIn(vs ...string) predicate.Season { + return predicate.Season(sql.FieldIn(FieldTitle, vs...)) +} + +// TitleNotIn applies the NotIn predicate on the "title" field. +func TitleNotIn(vs ...string) predicate.Season { + return predicate.Season(sql.FieldNotIn(FieldTitle, vs...)) +} + +// TitleGT applies the GT predicate on the "title" field. +func TitleGT(v string) predicate.Season { + return predicate.Season(sql.FieldGT(FieldTitle, v)) +} + +// TitleGTE applies the GTE predicate on the "title" field. +func TitleGTE(v string) predicate.Season { + return predicate.Season(sql.FieldGTE(FieldTitle, v)) +} + +// TitleLT applies the LT predicate on the "title" field. +func TitleLT(v string) predicate.Season { + return predicate.Season(sql.FieldLT(FieldTitle, v)) +} + +// TitleLTE applies the LTE predicate on the "title" field. +func TitleLTE(v string) predicate.Season { + return predicate.Season(sql.FieldLTE(FieldTitle, v)) +} + +// TitleContains applies the Contains predicate on the "title" field. +func TitleContains(v string) predicate.Season { + return predicate.Season(sql.FieldContains(FieldTitle, v)) +} + +// TitleHasPrefix applies the HasPrefix predicate on the "title" field. +func TitleHasPrefix(v string) predicate.Season { + return predicate.Season(sql.FieldHasPrefix(FieldTitle, v)) +} + +// TitleHasSuffix applies the HasSuffix predicate on the "title" field. +func TitleHasSuffix(v string) predicate.Season { + return predicate.Season(sql.FieldHasSuffix(FieldTitle, v)) +} + +// TitleEqualFold applies the EqualFold predicate on the "title" field. +func TitleEqualFold(v string) predicate.Season { + return predicate.Season(sql.FieldEqualFold(FieldTitle, v)) +} + +// TitleContainsFold applies the ContainsFold predicate on the "title" field. +func TitleContainsFold(v string) predicate.Season { + return predicate.Season(sql.FieldContainsFold(FieldTitle, v)) +} + +// FirstAiredEQ applies the EQ predicate on the "first_aired" field. +func FirstAiredEQ(v time.Time) predicate.Season { + return predicate.Season(sql.FieldEQ(FieldFirstAired, v)) +} + +// FirstAiredNEQ applies the NEQ predicate on the "first_aired" field. +func FirstAiredNEQ(v time.Time) predicate.Season { + return predicate.Season(sql.FieldNEQ(FieldFirstAired, v)) +} + +// FirstAiredIn applies the In predicate on the "first_aired" field. +func FirstAiredIn(vs ...time.Time) predicate.Season { + return predicate.Season(sql.FieldIn(FieldFirstAired, vs...)) +} + +// FirstAiredNotIn applies the NotIn predicate on the "first_aired" field. +func FirstAiredNotIn(vs ...time.Time) predicate.Season { + return predicate.Season(sql.FieldNotIn(FieldFirstAired, vs...)) +} + +// FirstAiredGT applies the GT predicate on the "first_aired" field. +func FirstAiredGT(v time.Time) predicate.Season { + return predicate.Season(sql.FieldGT(FieldFirstAired, v)) +} + +// FirstAiredGTE applies the GTE predicate on the "first_aired" field. +func FirstAiredGTE(v time.Time) predicate.Season { + return predicate.Season(sql.FieldGTE(FieldFirstAired, v)) +} + +// FirstAiredLT applies the LT predicate on the "first_aired" field. +func FirstAiredLT(v time.Time) predicate.Season { + return predicate.Season(sql.FieldLT(FieldFirstAired, v)) +} + +// FirstAiredLTE applies the LTE predicate on the "first_aired" field. +func FirstAiredLTE(v time.Time) predicate.Season { + return predicate.Season(sql.FieldLTE(FieldFirstAired, v)) +} + +// LastAiredEQ applies the EQ predicate on the "last_aired" field. +func LastAiredEQ(v time.Time) predicate.Season { + return predicate.Season(sql.FieldEQ(FieldLastAired, v)) +} + +// LastAiredNEQ applies the NEQ predicate on the "last_aired" field. +func LastAiredNEQ(v time.Time) predicate.Season { + return predicate.Season(sql.FieldNEQ(FieldLastAired, v)) +} + +// LastAiredIn applies the In predicate on the "last_aired" field. +func LastAiredIn(vs ...time.Time) predicate.Season { + return predicate.Season(sql.FieldIn(FieldLastAired, vs...)) +} + +// LastAiredNotIn applies the NotIn predicate on the "last_aired" field. +func LastAiredNotIn(vs ...time.Time) predicate.Season { + return predicate.Season(sql.FieldNotIn(FieldLastAired, vs...)) +} + +// LastAiredGT applies the GT predicate on the "last_aired" field. +func LastAiredGT(v time.Time) predicate.Season { + return predicate.Season(sql.FieldGT(FieldLastAired, v)) +} + +// LastAiredGTE applies the GTE predicate on the "last_aired" field. +func LastAiredGTE(v time.Time) predicate.Season { + return predicate.Season(sql.FieldGTE(FieldLastAired, v)) +} + +// LastAiredLT applies the LT predicate on the "last_aired" field. +func LastAiredLT(v time.Time) predicate.Season { + return predicate.Season(sql.FieldLT(FieldLastAired, v)) +} + +// LastAiredLTE applies the LTE predicate on the "last_aired" field. +func LastAiredLTE(v time.Time) predicate.Season { + return predicate.Season(sql.FieldLTE(FieldLastAired, v)) +} + +// HasSeries applies the HasEdge predicate on the "series" edge. +func HasSeries() predicate.Season { + return predicate.Season(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SeriesTable, SeriesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSeriesWith applies the HasEdge predicate on the "series" edge with a given conditions (other predicates). +func HasSeriesWith(preds ...predicate.Series) predicate.Season { + return predicate.Season(func(s *sql.Selector) { + step := newSeriesStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasEpisodes applies the HasEdge predicate on the "episodes" edge. +func HasEpisodes() predicate.Season { + return predicate.Season(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, EpisodesTable, EpisodesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasEpisodesWith applies the HasEdge predicate on the "episodes" edge with a given conditions (other predicates). +func HasEpisodesWith(preds ...predicate.Episode) predicate.Season { + return predicate.Season(func(s *sql.Selector) { + step := newEpisodesStep() + 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.Season) predicate.Season { + return predicate.Season(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Season) predicate.Season { + return predicate.Season(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Season) predicate.Season { + return predicate.Season(sql.NotPredicates(p)) +} diff --git a/examples/ydb/ent/season_create.go b/examples/ydb/ent/season_create.go new file mode 100644 index 0000000000..bb49606788 --- /dev/null +++ b/examples/ydb/ent/season_create.go @@ -0,0 +1,316 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/ydb/ent/episode" + "entgo.io/ent/examples/ydb/ent/season" + "entgo.io/ent/examples/ydb/ent/series" + "entgo.io/ent/schema/field" +) + +// SeasonCreate is the builder for creating a Season entity. +type SeasonCreate struct { + config + mutation *SeasonMutation + hooks []Hook + retryConfig sqlgraph.RetryConfig +} + +// SetSeriesID sets the "series_id" field. +func (_c *SeasonCreate) SetSeriesID(v int64) *SeasonCreate { + _c.mutation.SetSeriesID(v) + return _c +} + +// SetTitle sets the "title" field. +func (_c *SeasonCreate) SetTitle(v string) *SeasonCreate { + _c.mutation.SetTitle(v) + return _c +} + +// SetFirstAired sets the "first_aired" field. +func (_c *SeasonCreate) SetFirstAired(v time.Time) *SeasonCreate { + _c.mutation.SetFirstAired(v) + return _c +} + +// SetLastAired sets the "last_aired" field. +func (_c *SeasonCreate) SetLastAired(v time.Time) *SeasonCreate { + _c.mutation.SetLastAired(v) + return _c +} + +// SetID sets the "id" field. +func (_c *SeasonCreate) SetID(v int64) *SeasonCreate { + _c.mutation.SetID(v) + return _c +} + +// SetSeries sets the "series" edge to the Series entity. +func (_c *SeasonCreate) SetSeries(v *Series) *SeasonCreate { + return _c.SetSeriesID(v.ID) +} + +// AddEpisodeIDs adds the "episodes" edge to the Episode entity by IDs. +func (_c *SeasonCreate) AddEpisodeIDs(ids ...int64) *SeasonCreate { + _c.mutation.AddEpisodeIDs(ids...) + return _c +} + +// AddEpisodes adds the "episodes" edges to the Episode entity. +func (_c *SeasonCreate) AddEpisodes(v ...*Episode) *SeasonCreate { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddEpisodeIDs(ids...) +} + +// Mutation returns the SeasonMutation object of the builder. +func (_c *SeasonCreate) Mutation() *SeasonMutation { + return _c.mutation +} + +// Save creates the Season in the database. +func (_c *SeasonCreate) Save(ctx context.Context) (*Season, error) { + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *SeasonCreate) SaveX(ctx context.Context) *Season { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *SeasonCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *SeasonCreate) 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 *SeasonCreate) check() error { + if _, ok := _c.mutation.SeriesID(); !ok { + return &ValidationError{Name: "series_id", err: errors.New(`ent: missing required field "Season.series_id"`)} + } + if _, ok := _c.mutation.Title(); !ok { + return &ValidationError{Name: "title", err: errors.New(`ent: missing required field "Season.title"`)} + } + if v, ok := _c.mutation.Title(); ok { + if err := season.TitleValidator(v); err != nil { + return &ValidationError{Name: "title", err: fmt.Errorf(`ent: validator failed for field "Season.title": %w`, err)} + } + } + if _, ok := _c.mutation.FirstAired(); !ok { + return &ValidationError{Name: "first_aired", err: errors.New(`ent: missing required field "Season.first_aired"`)} + } + if _, ok := _c.mutation.LastAired(); !ok { + return &ValidationError{Name: "last_aired", err: errors.New(`ent: missing required field "Season.last_aired"`)} + } + if len(_c.mutation.SeriesIDs()) == 0 { + return &ValidationError{Name: "series", err: errors.New(`ent: missing required edge "Season.series"`)} + } + return nil +} + +func (_c *SeasonCreate) sqlSave(ctx context.Context) (*Season, 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 + } + if _spec.ID.Value != _node.ID { + id := _spec.ID.Value.(int64) + _node.ID = int64(id) + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *SeasonCreate) createSpec() (*Season, *sqlgraph.CreateSpec) { + var ( + _node = &Season{config: _c.config} + _spec = sqlgraph.NewCreateSpec(season.Table, sqlgraph.NewFieldSpec(season.FieldID, field.TypeInt64)) + ) + _spec.RetryConfig = _c.retryConfig + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.Title(); ok { + _spec.SetField(season.FieldTitle, field.TypeString, value) + _node.Title = value + } + if value, ok := _c.mutation.FirstAired(); ok { + _spec.SetField(season.FieldFirstAired, field.TypeTime, value) + _node.FirstAired = value + } + if value, ok := _c.mutation.LastAired(); ok { + _spec.SetField(season.FieldLastAired, field.TypeTime, value) + _node.LastAired = value + } + if nodes := _c.mutation.SeriesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: season.SeriesTable, + Columns: []string{season.SeriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(series.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.SeriesID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.EpisodesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: season.EpisodesTable, + Columns: []string{season.EpisodesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// WithRetryOptions sets the retry options for the create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *SeasonCreate) WithRetryOptions(opts ...any) *SeasonCreate { + _c.retryConfig.Options = opts + return _c +} + +// SeasonCreateBulk is the builder for creating many Season entities in bulk. +type SeasonCreateBulk struct { + config + err error + builders []*SeasonCreate + retryConfig sqlgraph.RetryConfig +} + +// Save creates the Season entities in the database. +func (_c *SeasonCreateBulk) Save(ctx context.Context) ([]*Season, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Season, 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.(*SeasonMutation) + 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.RetryConfig = _c.retryConfig + // 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 && nodes[i].ID == 0 { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int64(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 *SeasonCreateBulk) SaveX(ctx context.Context) []*Season { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *SeasonCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *SeasonCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// WithRetryOptions sets the retry options for the bulk create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *SeasonCreateBulk) WithRetryOptions(opts ...any) *SeasonCreateBulk { + _c.retryConfig.Options = opts + return _c +} diff --git a/examples/ydb/ent/season_delete.go b/examples/ydb/ent/season_delete.go new file mode 100644 index 0000000000..89a1d5ee9c --- /dev/null +++ b/examples/ydb/ent/season_delete.go @@ -0,0 +1,101 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/ydb/ent/predicate" + "entgo.io/ent/examples/ydb/ent/season" + "entgo.io/ent/schema/field" +) + +// SeasonDelete is the builder for deleting a Season entity. +type SeasonDelete struct { + config + hooks []Hook + mutation *SeasonMutation + retryConfig sqlgraph.RetryConfig +} + +// Where appends a list predicates to the SeasonDelete builder. +func (_d *SeasonDelete) Where(ps ...predicate.Season) *SeasonDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *SeasonDelete) 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 *SeasonDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *SeasonDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(season.Table, sqlgraph.NewFieldSpec(season.FieldID, field.TypeInt64)) + _spec.RetryConfig = _d.retryConfig + 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 +} + +// WithRetryOptions sets the retry options for the delete operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_d *SeasonDelete) WithRetryOptions(opts ...any) *SeasonDelete { + _d.retryConfig.Options = opts + return _d +} + +// SeasonDeleteOne is the builder for deleting a single Season entity. +type SeasonDeleteOne struct { + _d *SeasonDelete +} + +// Where appends a list predicates to the SeasonDelete builder. +func (_d *SeasonDeleteOne) Where(ps ...predicate.Season) *SeasonDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *SeasonDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{season.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *SeasonDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/examples/ydb/ent/season_query.go b/examples/ydb/ent/season_query.go new file mode 100644 index 0000000000..34a45ed74b --- /dev/null +++ b/examples/ydb/ent/season_query.go @@ -0,0 +1,695 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/ydb/ent/episode" + "entgo.io/ent/examples/ydb/ent/predicate" + "entgo.io/ent/examples/ydb/ent/season" + "entgo.io/ent/examples/ydb/ent/series" + "entgo.io/ent/schema/field" +) + +// SeasonQuery is the builder for querying Season entities. +type SeasonQuery struct { + config + ctx *QueryContext + order []season.OrderOption + inters []Interceptor + predicates []predicate.Season + withSeries *SeriesQuery + withEpisodes *EpisodeQuery + retryConfig sqlgraph.RetryConfig + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the SeasonQuery builder. +func (_q *SeasonQuery) Where(ps ...predicate.Season) *SeasonQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *SeasonQuery) Limit(limit int) *SeasonQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *SeasonQuery) Offset(offset int) *SeasonQuery { + _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 *SeasonQuery) Unique(unique bool) *SeasonQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *SeasonQuery) Order(o ...season.OrderOption) *SeasonQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QuerySeries chains the current query on the "series" edge. +func (_q *SeasonQuery) QuerySeries() *SeriesQuery { + query := (&SeriesClient{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(season.Table, season.FieldID, selector), + sqlgraph.To(series.Table, series.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, season.SeriesTable, season.SeriesColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryEpisodes chains the current query on the "episodes" edge. +func (_q *SeasonQuery) QueryEpisodes() *EpisodeQuery { + query := (&EpisodeClient{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(season.Table, season.FieldID, selector), + sqlgraph.To(episode.Table, episode.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, season.EpisodesTable, season.EpisodesColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Season entity from the query. +// Returns a *NotFoundError when no Season was found. +func (_q *SeasonQuery) First(ctx context.Context) (*Season, 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{season.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *SeasonQuery) FirstX(ctx context.Context) *Season { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Season ID from the query. +// Returns a *NotFoundError when no Season ID was found. +func (_q *SeasonQuery) FirstID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{season.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *SeasonQuery) FirstIDX(ctx context.Context) int64 { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Season entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Season entity is found. +// Returns a *NotFoundError when no Season entities are found. +func (_q *SeasonQuery) Only(ctx context.Context) (*Season, 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{season.Label} + default: + return nil, &NotSingularError{season.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *SeasonQuery) OnlyX(ctx context.Context) *Season { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Season ID in the query. +// Returns a *NotSingularError when more than one Season ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *SeasonQuery) OnlyID(ctx context.Context) (id int64, err error) { + var ids []int64 + 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{season.Label} + default: + err = &NotSingularError{season.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *SeasonQuery) OnlyIDX(ctx context.Context) int64 { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Seasons. +func (_q *SeasonQuery) All(ctx context.Context) ([]*Season, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Season, *SeasonQuery]() + return withInterceptors[[]*Season](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *SeasonQuery) AllX(ctx context.Context) []*Season { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Season IDs. +func (_q *SeasonQuery) IDs(ctx context.Context) (ids []int64, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(season.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *SeasonQuery) IDsX(ctx context.Context) []int64 { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *SeasonQuery) 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[*SeasonQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *SeasonQuery) 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 *SeasonQuery) 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 *SeasonQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the SeasonQuery 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 *SeasonQuery) Clone() *SeasonQuery { + if _q == nil { + return nil + } + return &SeasonQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]season.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Season{}, _q.predicates...), + withSeries: _q.withSeries.Clone(), + withEpisodes: _q.withEpisodes.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithSeries tells the query-builder to eager-load the nodes that are connected to +// the "series" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *SeasonQuery) WithSeries(opts ...func(*SeriesQuery)) *SeasonQuery { + query := (&SeriesClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSeries = query + return _q +} + +// WithEpisodes tells the query-builder to eager-load the nodes that are connected to +// the "episodes" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *SeasonQuery) WithEpisodes(opts ...func(*EpisodeQuery)) *SeasonQuery { + query := (&EpisodeClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withEpisodes = 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 { +// SeriesID int64 `json:"series_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Season.Query(). +// GroupBy(season.FieldSeriesID). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *SeasonQuery) GroupBy(field string, fields ...string) *SeasonGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &SeasonGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = season.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 { +// SeriesID int64 `json:"series_id,omitempty"` +// } +// +// client.Season.Query(). +// Select(season.FieldSeriesID). +// Scan(ctx, &v) +func (_q *SeasonQuery) Select(fields ...string) *SeasonSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &SeasonSelect{SeasonQuery: _q} + sbuild.label = season.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a SeasonSelect configured with the given aggregations. +func (_q *SeasonQuery) Aggregate(fns ...AggregateFunc) *SeasonSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *SeasonQuery) 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 !season.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 *SeasonQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Season, error) { + var ( + nodes = []*Season{} + _spec = _q.querySpec() + loadedTypes = [2]bool{ + _q.withSeries != nil, + _q.withEpisodes != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Season).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Season{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + _spec.RetryConfig = _q.retryConfig + 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.withSeries; query != nil { + if err := _q.loadSeries(ctx, query, nodes, nil, + func(n *Season, e *Series) { n.Edges.Series = e }); err != nil { + return nil, err + } + } + if query := _q.withEpisodes; query != nil { + if err := _q.loadEpisodes(ctx, query, nodes, + func(n *Season) { n.Edges.Episodes = []*Episode{} }, + func(n *Season, e *Episode) { n.Edges.Episodes = append(n.Edges.Episodes, e) }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *SeasonQuery) loadSeries(ctx context.Context, query *SeriesQuery, nodes []*Season, init func(*Season), assign func(*Season, *Series)) error { + ids := make([]int64, 0, len(nodes)) + nodeids := make(map[int64][]*Season) + for i := range nodes { + fk := nodes[i].SeriesID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(series.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 "series_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *SeasonQuery) loadEpisodes(ctx context.Context, query *EpisodeQuery, nodes []*Season, init func(*Season), assign func(*Season, *Episode)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int64]*Season) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(episode.FieldSeasonID) + } + query.Where(predicate.Episode(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(season.EpisodesColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.SeasonID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "season_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *SeasonQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.RetryConfig = _q.retryConfig + _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 *SeasonQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(season.Table, season.Columns, sqlgraph.NewFieldSpec(season.FieldID, field.TypeInt64)) + _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, season.FieldID) + for i := range fields { + if fields[i] != season.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withSeries != nil { + _spec.Node.AddColumnOnce(season.FieldSeriesID) + } + } + 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 *SeasonQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(season.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = season.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 _, 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 +} + +// WithRetryOptions sets the retry options for the query operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_q *SeasonQuery) WithRetryOptions(opts ...any) *SeasonQuery { + _q.retryConfig.Options = opts + return _q +} + +// SeasonGroupBy is the group-by builder for Season entities. +type SeasonGroupBy struct { + selector + build *SeasonQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *SeasonGroupBy) Aggregate(fns ...AggregateFunc) *SeasonGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *SeasonGroupBy) 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[*SeasonQuery, *SeasonGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *SeasonGroupBy) sqlScan(ctx context.Context, root *SeasonQuery, 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) +} + +// SeasonSelect is the builder for selecting fields of Season entities. +type SeasonSelect struct { + *SeasonQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *SeasonSelect) Aggregate(fns ...AggregateFunc) *SeasonSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *SeasonSelect) 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[*SeasonQuery, *SeasonSelect](ctx, _s.SeasonQuery, _s, _s.inters, v) +} + +func (_s *SeasonSelect) sqlScan(ctx context.Context, root *SeasonQuery, 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) +} diff --git a/examples/ydb/ent/season_update.go b/examples/ydb/ent/season_update.go new file mode 100644 index 0000000000..b9f44283dd --- /dev/null +++ b/examples/ydb/ent/season_update.go @@ -0,0 +1,604 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/ydb/ent/episode" + "entgo.io/ent/examples/ydb/ent/predicate" + "entgo.io/ent/examples/ydb/ent/season" + "entgo.io/ent/examples/ydb/ent/series" + "entgo.io/ent/schema/field" +) + +// SeasonUpdate is the builder for updating Season entities. +type SeasonUpdate struct { + config + hooks []Hook + mutation *SeasonMutation + retryConfig sqlgraph.RetryConfig +} + +// Where appends a list predicates to the SeasonUpdate builder. +func (_u *SeasonUpdate) Where(ps ...predicate.Season) *SeasonUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetSeriesID sets the "series_id" field. +func (_u *SeasonUpdate) SetSeriesID(v int64) *SeasonUpdate { + _u.mutation.SetSeriesID(v) + return _u +} + +// SetNillableSeriesID sets the "series_id" field if the given value is not nil. +func (_u *SeasonUpdate) SetNillableSeriesID(v *int64) *SeasonUpdate { + if v != nil { + _u.SetSeriesID(*v) + } + return _u +} + +// SetTitle sets the "title" field. +func (_u *SeasonUpdate) SetTitle(v string) *SeasonUpdate { + _u.mutation.SetTitle(v) + return _u +} + +// SetNillableTitle sets the "title" field if the given value is not nil. +func (_u *SeasonUpdate) SetNillableTitle(v *string) *SeasonUpdate { + if v != nil { + _u.SetTitle(*v) + } + return _u +} + +// SetFirstAired sets the "first_aired" field. +func (_u *SeasonUpdate) SetFirstAired(v time.Time) *SeasonUpdate { + _u.mutation.SetFirstAired(v) + return _u +} + +// SetNillableFirstAired sets the "first_aired" field if the given value is not nil. +func (_u *SeasonUpdate) SetNillableFirstAired(v *time.Time) *SeasonUpdate { + if v != nil { + _u.SetFirstAired(*v) + } + return _u +} + +// SetLastAired sets the "last_aired" field. +func (_u *SeasonUpdate) SetLastAired(v time.Time) *SeasonUpdate { + _u.mutation.SetLastAired(v) + return _u +} + +// SetNillableLastAired sets the "last_aired" field if the given value is not nil. +func (_u *SeasonUpdate) SetNillableLastAired(v *time.Time) *SeasonUpdate { + if v != nil { + _u.SetLastAired(*v) + } + return _u +} + +// SetSeries sets the "series" edge to the Series entity. +func (_u *SeasonUpdate) SetSeries(v *Series) *SeasonUpdate { + return _u.SetSeriesID(v.ID) +} + +// AddEpisodeIDs adds the "episodes" edge to the Episode entity by IDs. +func (_u *SeasonUpdate) AddEpisodeIDs(ids ...int64) *SeasonUpdate { + _u.mutation.AddEpisodeIDs(ids...) + return _u +} + +// AddEpisodes adds the "episodes" edges to the Episode entity. +func (_u *SeasonUpdate) AddEpisodes(v ...*Episode) *SeasonUpdate { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddEpisodeIDs(ids...) +} + +// Mutation returns the SeasonMutation object of the builder. +func (_u *SeasonUpdate) Mutation() *SeasonMutation { + return _u.mutation +} + +// ClearSeries clears the "series" edge to the Series entity. +func (_u *SeasonUpdate) ClearSeries() *SeasonUpdate { + _u.mutation.ClearSeries() + return _u +} + +// ClearEpisodes clears all "episodes" edges to the Episode entity. +func (_u *SeasonUpdate) ClearEpisodes() *SeasonUpdate { + _u.mutation.ClearEpisodes() + return _u +} + +// RemoveEpisodeIDs removes the "episodes" edge to Episode entities by IDs. +func (_u *SeasonUpdate) RemoveEpisodeIDs(ids ...int64) *SeasonUpdate { + _u.mutation.RemoveEpisodeIDs(ids...) + return _u +} + +// RemoveEpisodes removes "episodes" edges to Episode entities. +func (_u *SeasonUpdate) RemoveEpisodes(v ...*Episode) *SeasonUpdate { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveEpisodeIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *SeasonUpdate) 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 *SeasonUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *SeasonUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *SeasonUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *SeasonUpdate) check() error { + if v, ok := _u.mutation.Title(); ok { + if err := season.TitleValidator(v); err != nil { + return &ValidationError{Name: "title", err: fmt.Errorf(`ent: validator failed for field "Season.title": %w`, err)} + } + } + if _u.mutation.SeriesCleared() && len(_u.mutation.SeriesIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "Season.series"`) + } + return nil +} + +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *SeasonUpdate) WithRetryOptions(opts ...any) *SeasonUpdate { + _u.retryConfig.Options = opts + return _u +} + +func (_u *SeasonUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(season.Table, season.Columns, sqlgraph.NewFieldSpec(season.FieldID, field.TypeInt64)) + 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.Title(); ok { + _spec.SetField(season.FieldTitle, field.TypeString, value) + } + if value, ok := _u.mutation.FirstAired(); ok { + _spec.SetField(season.FieldFirstAired, field.TypeTime, value) + } + if value, ok := _u.mutation.LastAired(); ok { + _spec.SetField(season.FieldLastAired, field.TypeTime, value) + } + if _u.mutation.SeriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: season.SeriesTable, + Columns: []string{season.SeriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(series.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.SeriesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: season.SeriesTable, + Columns: []string{season.SeriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(series.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.EpisodesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: season.EpisodesTable, + Columns: []string{season.EpisodesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedEpisodesIDs(); len(nodes) > 0 && !_u.mutation.EpisodesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: season.EpisodesTable, + Columns: []string{season.EpisodesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.EpisodesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: season.EpisodesTable, + Columns: []string{season.EpisodesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.RetryConfig = _u.retryConfig + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{season.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// SeasonUpdateOne is the builder for updating a single Season entity. +type SeasonUpdateOne struct { + config + fields []string + hooks []Hook + mutation *SeasonMutation + retryConfig sqlgraph.RetryConfig +} + +// SetSeriesID sets the "series_id" field. +func (_u *SeasonUpdateOne) SetSeriesID(v int64) *SeasonUpdateOne { + _u.mutation.SetSeriesID(v) + return _u +} + +// SetNillableSeriesID sets the "series_id" field if the given value is not nil. +func (_u *SeasonUpdateOne) SetNillableSeriesID(v *int64) *SeasonUpdateOne { + if v != nil { + _u.SetSeriesID(*v) + } + return _u +} + +// SetTitle sets the "title" field. +func (_u *SeasonUpdateOne) SetTitle(v string) *SeasonUpdateOne { + _u.mutation.SetTitle(v) + return _u +} + +// SetNillableTitle sets the "title" field if the given value is not nil. +func (_u *SeasonUpdateOne) SetNillableTitle(v *string) *SeasonUpdateOne { + if v != nil { + _u.SetTitle(*v) + } + return _u +} + +// SetFirstAired sets the "first_aired" field. +func (_u *SeasonUpdateOne) SetFirstAired(v time.Time) *SeasonUpdateOne { + _u.mutation.SetFirstAired(v) + return _u +} + +// SetNillableFirstAired sets the "first_aired" field if the given value is not nil. +func (_u *SeasonUpdateOne) SetNillableFirstAired(v *time.Time) *SeasonUpdateOne { + if v != nil { + _u.SetFirstAired(*v) + } + return _u +} + +// SetLastAired sets the "last_aired" field. +func (_u *SeasonUpdateOne) SetLastAired(v time.Time) *SeasonUpdateOne { + _u.mutation.SetLastAired(v) + return _u +} + +// SetNillableLastAired sets the "last_aired" field if the given value is not nil. +func (_u *SeasonUpdateOne) SetNillableLastAired(v *time.Time) *SeasonUpdateOne { + if v != nil { + _u.SetLastAired(*v) + } + return _u +} + +// SetSeries sets the "series" edge to the Series entity. +func (_u *SeasonUpdateOne) SetSeries(v *Series) *SeasonUpdateOne { + return _u.SetSeriesID(v.ID) +} + +// AddEpisodeIDs adds the "episodes" edge to the Episode entity by IDs. +func (_u *SeasonUpdateOne) AddEpisodeIDs(ids ...int64) *SeasonUpdateOne { + _u.mutation.AddEpisodeIDs(ids...) + return _u +} + +// AddEpisodes adds the "episodes" edges to the Episode entity. +func (_u *SeasonUpdateOne) AddEpisodes(v ...*Episode) *SeasonUpdateOne { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddEpisodeIDs(ids...) +} + +// Mutation returns the SeasonMutation object of the builder. +func (_u *SeasonUpdateOne) Mutation() *SeasonMutation { + return _u.mutation +} + +// ClearSeries clears the "series" edge to the Series entity. +func (_u *SeasonUpdateOne) ClearSeries() *SeasonUpdateOne { + _u.mutation.ClearSeries() + return _u +} + +// ClearEpisodes clears all "episodes" edges to the Episode entity. +func (_u *SeasonUpdateOne) ClearEpisodes() *SeasonUpdateOne { + _u.mutation.ClearEpisodes() + return _u +} + +// RemoveEpisodeIDs removes the "episodes" edge to Episode entities by IDs. +func (_u *SeasonUpdateOne) RemoveEpisodeIDs(ids ...int64) *SeasonUpdateOne { + _u.mutation.RemoveEpisodeIDs(ids...) + return _u +} + +// RemoveEpisodes removes "episodes" edges to Episode entities. +func (_u *SeasonUpdateOne) RemoveEpisodes(v ...*Episode) *SeasonUpdateOne { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveEpisodeIDs(ids...) +} + +// Where appends a list predicates to the SeasonUpdate builder. +func (_u *SeasonUpdateOne) Where(ps ...predicate.Season) *SeasonUpdateOne { + _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 *SeasonUpdateOne) Select(field string, fields ...string) *SeasonUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Season entity. +func (_u *SeasonUpdateOne) Save(ctx context.Context) (*Season, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *SeasonUpdateOne) SaveX(ctx context.Context) *Season { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *SeasonUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *SeasonUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *SeasonUpdateOne) check() error { + if v, ok := _u.mutation.Title(); ok { + if err := season.TitleValidator(v); err != nil { + return &ValidationError{Name: "title", err: fmt.Errorf(`ent: validator failed for field "Season.title": %w`, err)} + } + } + if _u.mutation.SeriesCleared() && len(_u.mutation.SeriesIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "Season.series"`) + } + return nil +} + +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *SeasonUpdateOne) WithRetryOptions(opts ...any) *SeasonUpdateOne { + _u.retryConfig.Options = opts + return _u +} + +func (_u *SeasonUpdateOne) sqlSave(ctx context.Context) (_node *Season, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(season.Table, season.Columns, sqlgraph.NewFieldSpec(season.FieldID, field.TypeInt64)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Season.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, season.FieldID) + for _, f := range fields { + if !season.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != season.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.Title(); ok { + _spec.SetField(season.FieldTitle, field.TypeString, value) + } + if value, ok := _u.mutation.FirstAired(); ok { + _spec.SetField(season.FieldFirstAired, field.TypeTime, value) + } + if value, ok := _u.mutation.LastAired(); ok { + _spec.SetField(season.FieldLastAired, field.TypeTime, value) + } + if _u.mutation.SeriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: season.SeriesTable, + Columns: []string{season.SeriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(series.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.SeriesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: season.SeriesTable, + Columns: []string{season.SeriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(series.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.EpisodesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: season.EpisodesTable, + Columns: []string{season.EpisodesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedEpisodesIDs(); len(nodes) > 0 && !_u.mutation.EpisodesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: season.EpisodesTable, + Columns: []string{season.EpisodesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.EpisodesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: season.EpisodesTable, + Columns: []string{season.EpisodesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(episode.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.RetryConfig = _u.retryConfig + _node = &Season{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{season.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/examples/ydb/ent/series.go b/examples/ydb/ent/series.go new file mode 100644 index 0000000000..2b137d6066 --- /dev/null +++ b/examples/ydb/ent/series.go @@ -0,0 +1,158 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/examples/ydb/ent/series" +) + +// Series is the model entity for the Series schema. +type Series struct { + config `json:"-"` + // ID of the ent. + ID int64 `json:"id,omitempty"` + // Title holds the value of the "title" field. + Title string `json:"title,omitempty"` + // Info holds the value of the "info" field. + Info string `json:"info,omitempty"` + // ReleaseDate holds the value of the "release_date" field. + ReleaseDate time.Time `json:"release_date,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the SeriesQuery when eager-loading is set. + Edges SeriesEdges `json:"edges"` + selectValues sql.SelectValues +} + +// SeriesEdges holds the relations/edges for other nodes in the graph. +type SeriesEdges struct { + // Seasons holds the value of the seasons edge. + Seasons []*Season `json:"seasons,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// SeasonsOrErr returns the Seasons value or an error if the edge +// was not loaded in eager-loading. +func (e SeriesEdges) SeasonsOrErr() ([]*Season, error) { + if e.loadedTypes[0] { + return e.Seasons, nil + } + return nil, &NotLoadedError{edge: "seasons"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Series) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case series.FieldID: + values[i] = new(sql.NullInt64) + case series.FieldTitle, series.FieldInfo: + values[i] = new(sql.NullString) + case series.FieldReleaseDate: + values[i] = new(sql.NullTime) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Series fields. +func (_m *Series) 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 series.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int64(value.Int64) + case series.FieldTitle: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field title", values[i]) + } else if value.Valid { + _m.Title = value.String + } + case series.FieldInfo: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field info", values[i]) + } else if value.Valid { + _m.Info = value.String + } + case series.FieldReleaseDate: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field release_date", values[i]) + } else if value.Valid { + _m.ReleaseDate = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Series. +// This includes values selected through modifiers, order, etc. +func (_m *Series) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QuerySeasons queries the "seasons" edge of the Series entity. +func (_m *Series) QuerySeasons() *SeasonQuery { + return NewSeriesClient(_m.config).QuerySeasons(_m) +} + +// Update returns a builder for updating this Series. +// Note that you need to call Series.Unwrap() before calling this method if this Series +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Series) Update() *SeriesUpdateOne { + return NewSeriesClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Series 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 *Series) Unwrap() *Series { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: Series is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Series) String() string { + var builder strings.Builder + builder.WriteString("Series(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("title=") + builder.WriteString(_m.Title) + builder.WriteString(", ") + builder.WriteString("info=") + builder.WriteString(_m.Info) + builder.WriteString(", ") + builder.WriteString("release_date=") + builder.WriteString(_m.ReleaseDate.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// SeriesSlice is a parsable slice of Series. +type SeriesSlice []*Series diff --git a/examples/ydb/ent/series/series.go b/examples/ydb/ent/series/series.go new file mode 100644 index 0000000000..1e21b94896 --- /dev/null +++ b/examples/ydb/ent/series/series.go @@ -0,0 +1,103 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package series + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the series type in the database. + Label = "series" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldTitle holds the string denoting the title field in the database. + FieldTitle = "title" + // FieldInfo holds the string denoting the info field in the database. + FieldInfo = "info" + // FieldReleaseDate holds the string denoting the release_date field in the database. + FieldReleaseDate = "release_date" + // EdgeSeasons holds the string denoting the seasons edge name in mutations. + EdgeSeasons = "seasons" + // Table holds the table name of the series in the database. + Table = "series" + // SeasonsTable is the table that holds the seasons relation/edge. + SeasonsTable = "seasons" + // SeasonsInverseTable is the table name for the Season entity. + // It exists in this package in order to avoid circular dependency with the "season" package. + SeasonsInverseTable = "seasons" + // SeasonsColumn is the table column denoting the seasons relation/edge. + SeasonsColumn = "series_id" +) + +// Columns holds all SQL columns for series fields. +var Columns = []string{ + FieldID, + FieldTitle, + FieldInfo, + FieldReleaseDate, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // TitleValidator is a validator for the "title" field. It is called by the builders before save. + TitleValidator func(string) error +) + +// OrderOption defines the ordering options for the Series 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() +} + +// ByTitle orders the results by the title field. +func ByTitle(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTitle, opts...).ToFunc() +} + +// ByInfo orders the results by the info field. +func ByInfo(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInfo, opts...).ToFunc() +} + +// ByReleaseDate orders the results by the release_date field. +func ByReleaseDate(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldReleaseDate, opts...).ToFunc() +} + +// BySeasonsCount orders the results by seasons count. +func BySeasonsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newSeasonsStep(), opts...) + } +} + +// BySeasons orders the results by seasons terms. +func BySeasons(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSeasonsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newSeasonsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SeasonsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SeasonsTable, SeasonsColumn), + ) +} diff --git a/examples/ydb/ent/series/where.go b/examples/ydb/ent/series/where.go new file mode 100644 index 0000000000..d308a6c8a3 --- /dev/null +++ b/examples/ydb/ent/series/where.go @@ -0,0 +1,293 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package series + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/ydb/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int64) predicate.Series { + return predicate.Series(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int64) predicate.Series { + return predicate.Series(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int64) predicate.Series { + return predicate.Series(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int64) predicate.Series { + return predicate.Series(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int64) predicate.Series { + return predicate.Series(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int64) predicate.Series { + return predicate.Series(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int64) predicate.Series { + return predicate.Series(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int64) predicate.Series { + return predicate.Series(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int64) predicate.Series { + return predicate.Series(sql.FieldLTE(FieldID, id)) +} + +// Title applies equality check predicate on the "title" field. It's identical to TitleEQ. +func Title(v string) predicate.Series { + return predicate.Series(sql.FieldEQ(FieldTitle, v)) +} + +// Info applies equality check predicate on the "info" field. It's identical to InfoEQ. +func Info(v string) predicate.Series { + return predicate.Series(sql.FieldEQ(FieldInfo, v)) +} + +// ReleaseDate applies equality check predicate on the "release_date" field. It's identical to ReleaseDateEQ. +func ReleaseDate(v time.Time) predicate.Series { + return predicate.Series(sql.FieldEQ(FieldReleaseDate, v)) +} + +// TitleEQ applies the EQ predicate on the "title" field. +func TitleEQ(v string) predicate.Series { + return predicate.Series(sql.FieldEQ(FieldTitle, v)) +} + +// TitleNEQ applies the NEQ predicate on the "title" field. +func TitleNEQ(v string) predicate.Series { + return predicate.Series(sql.FieldNEQ(FieldTitle, v)) +} + +// TitleIn applies the In predicate on the "title" field. +func TitleIn(vs ...string) predicate.Series { + return predicate.Series(sql.FieldIn(FieldTitle, vs...)) +} + +// TitleNotIn applies the NotIn predicate on the "title" field. +func TitleNotIn(vs ...string) predicate.Series { + return predicate.Series(sql.FieldNotIn(FieldTitle, vs...)) +} + +// TitleGT applies the GT predicate on the "title" field. +func TitleGT(v string) predicate.Series { + return predicate.Series(sql.FieldGT(FieldTitle, v)) +} + +// TitleGTE applies the GTE predicate on the "title" field. +func TitleGTE(v string) predicate.Series { + return predicate.Series(sql.FieldGTE(FieldTitle, v)) +} + +// TitleLT applies the LT predicate on the "title" field. +func TitleLT(v string) predicate.Series { + return predicate.Series(sql.FieldLT(FieldTitle, v)) +} + +// TitleLTE applies the LTE predicate on the "title" field. +func TitleLTE(v string) predicate.Series { + return predicate.Series(sql.FieldLTE(FieldTitle, v)) +} + +// TitleContains applies the Contains predicate on the "title" field. +func TitleContains(v string) predicate.Series { + return predicate.Series(sql.FieldContains(FieldTitle, v)) +} + +// TitleHasPrefix applies the HasPrefix predicate on the "title" field. +func TitleHasPrefix(v string) predicate.Series { + return predicate.Series(sql.FieldHasPrefix(FieldTitle, v)) +} + +// TitleHasSuffix applies the HasSuffix predicate on the "title" field. +func TitleHasSuffix(v string) predicate.Series { + return predicate.Series(sql.FieldHasSuffix(FieldTitle, v)) +} + +// TitleEqualFold applies the EqualFold predicate on the "title" field. +func TitleEqualFold(v string) predicate.Series { + return predicate.Series(sql.FieldEqualFold(FieldTitle, v)) +} + +// TitleContainsFold applies the ContainsFold predicate on the "title" field. +func TitleContainsFold(v string) predicate.Series { + return predicate.Series(sql.FieldContainsFold(FieldTitle, v)) +} + +// InfoEQ applies the EQ predicate on the "info" field. +func InfoEQ(v string) predicate.Series { + return predicate.Series(sql.FieldEQ(FieldInfo, v)) +} + +// InfoNEQ applies the NEQ predicate on the "info" field. +func InfoNEQ(v string) predicate.Series { + return predicate.Series(sql.FieldNEQ(FieldInfo, v)) +} + +// InfoIn applies the In predicate on the "info" field. +func InfoIn(vs ...string) predicate.Series { + return predicate.Series(sql.FieldIn(FieldInfo, vs...)) +} + +// InfoNotIn applies the NotIn predicate on the "info" field. +func InfoNotIn(vs ...string) predicate.Series { + return predicate.Series(sql.FieldNotIn(FieldInfo, vs...)) +} + +// InfoGT applies the GT predicate on the "info" field. +func InfoGT(v string) predicate.Series { + return predicate.Series(sql.FieldGT(FieldInfo, v)) +} + +// InfoGTE applies the GTE predicate on the "info" field. +func InfoGTE(v string) predicate.Series { + return predicate.Series(sql.FieldGTE(FieldInfo, v)) +} + +// InfoLT applies the LT predicate on the "info" field. +func InfoLT(v string) predicate.Series { + return predicate.Series(sql.FieldLT(FieldInfo, v)) +} + +// InfoLTE applies the LTE predicate on the "info" field. +func InfoLTE(v string) predicate.Series { + return predicate.Series(sql.FieldLTE(FieldInfo, v)) +} + +// InfoContains applies the Contains predicate on the "info" field. +func InfoContains(v string) predicate.Series { + return predicate.Series(sql.FieldContains(FieldInfo, v)) +} + +// InfoHasPrefix applies the HasPrefix predicate on the "info" field. +func InfoHasPrefix(v string) predicate.Series { + return predicate.Series(sql.FieldHasPrefix(FieldInfo, v)) +} + +// InfoHasSuffix applies the HasSuffix predicate on the "info" field. +func InfoHasSuffix(v string) predicate.Series { + return predicate.Series(sql.FieldHasSuffix(FieldInfo, v)) +} + +// InfoIsNil applies the IsNil predicate on the "info" field. +func InfoIsNil() predicate.Series { + return predicate.Series(sql.FieldIsNull(FieldInfo)) +} + +// InfoNotNil applies the NotNil predicate on the "info" field. +func InfoNotNil() predicate.Series { + return predicate.Series(sql.FieldNotNull(FieldInfo)) +} + +// InfoEqualFold applies the EqualFold predicate on the "info" field. +func InfoEqualFold(v string) predicate.Series { + return predicate.Series(sql.FieldEqualFold(FieldInfo, v)) +} + +// InfoContainsFold applies the ContainsFold predicate on the "info" field. +func InfoContainsFold(v string) predicate.Series { + return predicate.Series(sql.FieldContainsFold(FieldInfo, v)) +} + +// ReleaseDateEQ applies the EQ predicate on the "release_date" field. +func ReleaseDateEQ(v time.Time) predicate.Series { + return predicate.Series(sql.FieldEQ(FieldReleaseDate, v)) +} + +// ReleaseDateNEQ applies the NEQ predicate on the "release_date" field. +func ReleaseDateNEQ(v time.Time) predicate.Series { + return predicate.Series(sql.FieldNEQ(FieldReleaseDate, v)) +} + +// ReleaseDateIn applies the In predicate on the "release_date" field. +func ReleaseDateIn(vs ...time.Time) predicate.Series { + return predicate.Series(sql.FieldIn(FieldReleaseDate, vs...)) +} + +// ReleaseDateNotIn applies the NotIn predicate on the "release_date" field. +func ReleaseDateNotIn(vs ...time.Time) predicate.Series { + return predicate.Series(sql.FieldNotIn(FieldReleaseDate, vs...)) +} + +// ReleaseDateGT applies the GT predicate on the "release_date" field. +func ReleaseDateGT(v time.Time) predicate.Series { + return predicate.Series(sql.FieldGT(FieldReleaseDate, v)) +} + +// ReleaseDateGTE applies the GTE predicate on the "release_date" field. +func ReleaseDateGTE(v time.Time) predicate.Series { + return predicate.Series(sql.FieldGTE(FieldReleaseDate, v)) +} + +// ReleaseDateLT applies the LT predicate on the "release_date" field. +func ReleaseDateLT(v time.Time) predicate.Series { + return predicate.Series(sql.FieldLT(FieldReleaseDate, v)) +} + +// ReleaseDateLTE applies the LTE predicate on the "release_date" field. +func ReleaseDateLTE(v time.Time) predicate.Series { + return predicate.Series(sql.FieldLTE(FieldReleaseDate, v)) +} + +// HasSeasons applies the HasEdge predicate on the "seasons" edge. +func HasSeasons() predicate.Series { + return predicate.Series(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SeasonsTable, SeasonsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSeasonsWith applies the HasEdge predicate on the "seasons" edge with a given conditions (other predicates). +func HasSeasonsWith(preds ...predicate.Season) predicate.Series { + return predicate.Series(func(s *sql.Selector) { + step := newSeasonsStep() + 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.Series) predicate.Series { + return predicate.Series(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Series) predicate.Series { + return predicate.Series(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Series) predicate.Series { + return predicate.Series(sql.NotPredicates(p)) +} diff --git a/examples/ydb/ent/series_create.go b/examples/ydb/ent/series_create.go new file mode 100644 index 0000000000..6d4352e662 --- /dev/null +++ b/examples/ydb/ent/series_create.go @@ -0,0 +1,286 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/ydb/ent/season" + "entgo.io/ent/examples/ydb/ent/series" + "entgo.io/ent/schema/field" +) + +// SeriesCreate is the builder for creating a Series entity. +type SeriesCreate struct { + config + mutation *SeriesMutation + hooks []Hook + retryConfig sqlgraph.RetryConfig +} + +// SetTitle sets the "title" field. +func (_c *SeriesCreate) SetTitle(v string) *SeriesCreate { + _c.mutation.SetTitle(v) + return _c +} + +// SetInfo sets the "info" field. +func (_c *SeriesCreate) SetInfo(v string) *SeriesCreate { + _c.mutation.SetInfo(v) + return _c +} + +// SetNillableInfo sets the "info" field if the given value is not nil. +func (_c *SeriesCreate) SetNillableInfo(v *string) *SeriesCreate { + if v != nil { + _c.SetInfo(*v) + } + return _c +} + +// SetReleaseDate sets the "release_date" field. +func (_c *SeriesCreate) SetReleaseDate(v time.Time) *SeriesCreate { + _c.mutation.SetReleaseDate(v) + return _c +} + +// SetID sets the "id" field. +func (_c *SeriesCreate) SetID(v int64) *SeriesCreate { + _c.mutation.SetID(v) + return _c +} + +// AddSeasonIDs adds the "seasons" edge to the Season entity by IDs. +func (_c *SeriesCreate) AddSeasonIDs(ids ...int64) *SeriesCreate { + _c.mutation.AddSeasonIDs(ids...) + return _c +} + +// AddSeasons adds the "seasons" edges to the Season entity. +func (_c *SeriesCreate) AddSeasons(v ...*Season) *SeriesCreate { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddSeasonIDs(ids...) +} + +// Mutation returns the SeriesMutation object of the builder. +func (_c *SeriesCreate) Mutation() *SeriesMutation { + return _c.mutation +} + +// Save creates the Series in the database. +func (_c *SeriesCreate) Save(ctx context.Context) (*Series, error) { + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *SeriesCreate) SaveX(ctx context.Context) *Series { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *SeriesCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *SeriesCreate) 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 *SeriesCreate) check() error { + if _, ok := _c.mutation.Title(); !ok { + return &ValidationError{Name: "title", err: errors.New(`ent: missing required field "Series.title"`)} + } + if v, ok := _c.mutation.Title(); ok { + if err := series.TitleValidator(v); err != nil { + return &ValidationError{Name: "title", err: fmt.Errorf(`ent: validator failed for field "Series.title": %w`, err)} + } + } + if _, ok := _c.mutation.ReleaseDate(); !ok { + return &ValidationError{Name: "release_date", err: errors.New(`ent: missing required field "Series.release_date"`)} + } + return nil +} + +func (_c *SeriesCreate) sqlSave(ctx context.Context) (*Series, 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 + } + if _spec.ID.Value != _node.ID { + id := _spec.ID.Value.(int64) + _node.ID = int64(id) + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *SeriesCreate) createSpec() (*Series, *sqlgraph.CreateSpec) { + var ( + _node = &Series{config: _c.config} + _spec = sqlgraph.NewCreateSpec(series.Table, sqlgraph.NewFieldSpec(series.FieldID, field.TypeInt64)) + ) + _spec.RetryConfig = _c.retryConfig + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.Title(); ok { + _spec.SetField(series.FieldTitle, field.TypeString, value) + _node.Title = value + } + if value, ok := _c.mutation.Info(); ok { + _spec.SetField(series.FieldInfo, field.TypeString, value) + _node.Info = value + } + if value, ok := _c.mutation.ReleaseDate(); ok { + _spec.SetField(series.FieldReleaseDate, field.TypeTime, value) + _node.ReleaseDate = value + } + if nodes := _c.mutation.SeasonsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: series.SeasonsTable, + Columns: []string{series.SeasonsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(season.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// WithRetryOptions sets the retry options for the create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *SeriesCreate) WithRetryOptions(opts ...any) *SeriesCreate { + _c.retryConfig.Options = opts + return _c +} + +// SeriesCreateBulk is the builder for creating many Series entities in bulk. +type SeriesCreateBulk struct { + config + err error + builders []*SeriesCreate + retryConfig sqlgraph.RetryConfig +} + +// Save creates the Series entities in the database. +func (_c *SeriesCreateBulk) Save(ctx context.Context) ([]*Series, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Series, 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.(*SeriesMutation) + 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.RetryConfig = _c.retryConfig + // 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 && nodes[i].ID == 0 { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int64(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 *SeriesCreateBulk) SaveX(ctx context.Context) []*Series { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *SeriesCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *SeriesCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// WithRetryOptions sets the retry options for the bulk create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *SeriesCreateBulk) WithRetryOptions(opts ...any) *SeriesCreateBulk { + _c.retryConfig.Options = opts + return _c +} diff --git a/examples/ydb/ent/series_delete.go b/examples/ydb/ent/series_delete.go new file mode 100644 index 0000000000..a66adf80f7 --- /dev/null +++ b/examples/ydb/ent/series_delete.go @@ -0,0 +1,101 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/ydb/ent/predicate" + "entgo.io/ent/examples/ydb/ent/series" + "entgo.io/ent/schema/field" +) + +// SeriesDelete is the builder for deleting a Series entity. +type SeriesDelete struct { + config + hooks []Hook + mutation *SeriesMutation + retryConfig sqlgraph.RetryConfig +} + +// Where appends a list predicates to the SeriesDelete builder. +func (_d *SeriesDelete) Where(ps ...predicate.Series) *SeriesDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *SeriesDelete) 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 *SeriesDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *SeriesDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(series.Table, sqlgraph.NewFieldSpec(series.FieldID, field.TypeInt64)) + _spec.RetryConfig = _d.retryConfig + 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 +} + +// WithRetryOptions sets the retry options for the delete operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_d *SeriesDelete) WithRetryOptions(opts ...any) *SeriesDelete { + _d.retryConfig.Options = opts + return _d +} + +// SeriesDeleteOne is the builder for deleting a single Series entity. +type SeriesDeleteOne struct { + _d *SeriesDelete +} + +// Where appends a list predicates to the SeriesDelete builder. +func (_d *SeriesDeleteOne) Where(ps ...predicate.Series) *SeriesDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *SeriesDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{series.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *SeriesDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/examples/ydb/ent/series_query.go b/examples/ydb/ent/series_query.go new file mode 100644 index 0000000000..c3c484ba5b --- /dev/null +++ b/examples/ydb/ent/series_query.go @@ -0,0 +1,620 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/ydb/ent/predicate" + "entgo.io/ent/examples/ydb/ent/season" + "entgo.io/ent/examples/ydb/ent/series" + "entgo.io/ent/schema/field" +) + +// SeriesQuery is the builder for querying Series entities. +type SeriesQuery struct { + config + ctx *QueryContext + order []series.OrderOption + inters []Interceptor + predicates []predicate.Series + withSeasons *SeasonQuery + retryConfig sqlgraph.RetryConfig + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the SeriesQuery builder. +func (_q *SeriesQuery) Where(ps ...predicate.Series) *SeriesQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *SeriesQuery) Limit(limit int) *SeriesQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *SeriesQuery) Offset(offset int) *SeriesQuery { + _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 *SeriesQuery) Unique(unique bool) *SeriesQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *SeriesQuery) Order(o ...series.OrderOption) *SeriesQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QuerySeasons chains the current query on the "seasons" edge. +func (_q *SeriesQuery) QuerySeasons() *SeasonQuery { + query := (&SeasonClient{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(series.Table, series.FieldID, selector), + sqlgraph.To(season.Table, season.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, series.SeasonsTable, series.SeasonsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Series entity from the query. +// Returns a *NotFoundError when no Series was found. +func (_q *SeriesQuery) First(ctx context.Context) (*Series, 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{series.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *SeriesQuery) FirstX(ctx context.Context) *Series { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Series ID from the query. +// Returns a *NotFoundError when no Series ID was found. +func (_q *SeriesQuery) FirstID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{series.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *SeriesQuery) FirstIDX(ctx context.Context) int64 { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Series entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Series entity is found. +// Returns a *NotFoundError when no Series entities are found. +func (_q *SeriesQuery) Only(ctx context.Context) (*Series, 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{series.Label} + default: + return nil, &NotSingularError{series.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *SeriesQuery) OnlyX(ctx context.Context) *Series { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Series ID in the query. +// Returns a *NotSingularError when more than one Series ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *SeriesQuery) OnlyID(ctx context.Context) (id int64, err error) { + var ids []int64 + 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{series.Label} + default: + err = &NotSingularError{series.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *SeriesQuery) OnlyIDX(ctx context.Context) int64 { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of SeriesSlice. +func (_q *SeriesQuery) All(ctx context.Context) ([]*Series, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Series, *SeriesQuery]() + return withInterceptors[[]*Series](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *SeriesQuery) AllX(ctx context.Context) []*Series { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Series IDs. +func (_q *SeriesQuery) IDs(ctx context.Context) (ids []int64, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(series.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *SeriesQuery) IDsX(ctx context.Context) []int64 { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *SeriesQuery) 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[*SeriesQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *SeriesQuery) 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 *SeriesQuery) 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 *SeriesQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the SeriesQuery 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 *SeriesQuery) Clone() *SeriesQuery { + if _q == nil { + return nil + } + return &SeriesQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]series.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Series{}, _q.predicates...), + withSeasons: _q.withSeasons.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithSeasons tells the query-builder to eager-load the nodes that are connected to +// the "seasons" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *SeriesQuery) WithSeasons(opts ...func(*SeasonQuery)) *SeriesQuery { + query := (&SeasonClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSeasons = 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 { +// Title string `json:"title,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Series.Query(). +// GroupBy(series.FieldTitle). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *SeriesQuery) GroupBy(field string, fields ...string) *SeriesGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &SeriesGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = series.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 { +// Title string `json:"title,omitempty"` +// } +// +// client.Series.Query(). +// Select(series.FieldTitle). +// Scan(ctx, &v) +func (_q *SeriesQuery) Select(fields ...string) *SeriesSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &SeriesSelect{SeriesQuery: _q} + sbuild.label = series.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a SeriesSelect configured with the given aggregations. +func (_q *SeriesQuery) Aggregate(fns ...AggregateFunc) *SeriesSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *SeriesQuery) 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 !series.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 *SeriesQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Series, error) { + var ( + nodes = []*Series{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withSeasons != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Series).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Series{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + _spec.RetryConfig = _q.retryConfig + 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.withSeasons; query != nil { + if err := _q.loadSeasons(ctx, query, nodes, + func(n *Series) { n.Edges.Seasons = []*Season{} }, + func(n *Series, e *Season) { n.Edges.Seasons = append(n.Edges.Seasons, e) }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *SeriesQuery) loadSeasons(ctx context.Context, query *SeasonQuery, nodes []*Series, init func(*Series), assign func(*Series, *Season)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int64]*Series) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(season.FieldSeriesID) + } + query.Where(predicate.Season(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(series.SeasonsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.SeriesID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "series_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *SeriesQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.RetryConfig = _q.retryConfig + _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 *SeriesQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(series.Table, series.Columns, sqlgraph.NewFieldSpec(series.FieldID, field.TypeInt64)) + _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, series.FieldID) + for i := range fields { + if fields[i] != series.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 *SeriesQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(series.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = series.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 _, 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 +} + +// WithRetryOptions sets the retry options for the query operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_q *SeriesQuery) WithRetryOptions(opts ...any) *SeriesQuery { + _q.retryConfig.Options = opts + return _q +} + +// SeriesGroupBy is the group-by builder for Series entities. +type SeriesGroupBy struct { + selector + build *SeriesQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *SeriesGroupBy) Aggregate(fns ...AggregateFunc) *SeriesGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *SeriesGroupBy) 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[*SeriesQuery, *SeriesGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *SeriesGroupBy) sqlScan(ctx context.Context, root *SeriesQuery, 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) +} + +// SeriesSelect is the builder for selecting fields of Series entities. +type SeriesSelect struct { + *SeriesQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *SeriesSelect) Aggregate(fns ...AggregateFunc) *SeriesSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *SeriesSelect) 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[*SeriesQuery, *SeriesSelect](ctx, _s.SeriesQuery, _s, _s.inters, v) +} + +func (_s *SeriesSelect) sqlScan(ctx context.Context, root *SeriesQuery, 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) +} diff --git a/examples/ydb/ent/series_update.go b/examples/ydb/ent/series_update.go new file mode 100644 index 0000000000..9c53f19fc0 --- /dev/null +++ b/examples/ydb/ent/series_update.go @@ -0,0 +1,507 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/ydb/ent/predicate" + "entgo.io/ent/examples/ydb/ent/season" + "entgo.io/ent/examples/ydb/ent/series" + "entgo.io/ent/schema/field" +) + +// SeriesUpdate is the builder for updating Series entities. +type SeriesUpdate struct { + config + hooks []Hook + mutation *SeriesMutation + retryConfig sqlgraph.RetryConfig +} + +// Where appends a list predicates to the SeriesUpdate builder. +func (_u *SeriesUpdate) Where(ps ...predicate.Series) *SeriesUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetTitle sets the "title" field. +func (_u *SeriesUpdate) SetTitle(v string) *SeriesUpdate { + _u.mutation.SetTitle(v) + return _u +} + +// SetNillableTitle sets the "title" field if the given value is not nil. +func (_u *SeriesUpdate) SetNillableTitle(v *string) *SeriesUpdate { + if v != nil { + _u.SetTitle(*v) + } + return _u +} + +// SetInfo sets the "info" field. +func (_u *SeriesUpdate) SetInfo(v string) *SeriesUpdate { + _u.mutation.SetInfo(v) + return _u +} + +// SetNillableInfo sets the "info" field if the given value is not nil. +func (_u *SeriesUpdate) SetNillableInfo(v *string) *SeriesUpdate { + if v != nil { + _u.SetInfo(*v) + } + return _u +} + +// ClearInfo clears the value of the "info" field. +func (_u *SeriesUpdate) ClearInfo() *SeriesUpdate { + _u.mutation.ClearInfo() + return _u +} + +// SetReleaseDate sets the "release_date" field. +func (_u *SeriesUpdate) SetReleaseDate(v time.Time) *SeriesUpdate { + _u.mutation.SetReleaseDate(v) + return _u +} + +// SetNillableReleaseDate sets the "release_date" field if the given value is not nil. +func (_u *SeriesUpdate) SetNillableReleaseDate(v *time.Time) *SeriesUpdate { + if v != nil { + _u.SetReleaseDate(*v) + } + return _u +} + +// AddSeasonIDs adds the "seasons" edge to the Season entity by IDs. +func (_u *SeriesUpdate) AddSeasonIDs(ids ...int64) *SeriesUpdate { + _u.mutation.AddSeasonIDs(ids...) + return _u +} + +// AddSeasons adds the "seasons" edges to the Season entity. +func (_u *SeriesUpdate) AddSeasons(v ...*Season) *SeriesUpdate { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddSeasonIDs(ids...) +} + +// Mutation returns the SeriesMutation object of the builder. +func (_u *SeriesUpdate) Mutation() *SeriesMutation { + return _u.mutation +} + +// ClearSeasons clears all "seasons" edges to the Season entity. +func (_u *SeriesUpdate) ClearSeasons() *SeriesUpdate { + _u.mutation.ClearSeasons() + return _u +} + +// RemoveSeasonIDs removes the "seasons" edge to Season entities by IDs. +func (_u *SeriesUpdate) RemoveSeasonIDs(ids ...int64) *SeriesUpdate { + _u.mutation.RemoveSeasonIDs(ids...) + return _u +} + +// RemoveSeasons removes "seasons" edges to Season entities. +func (_u *SeriesUpdate) RemoveSeasons(v ...*Season) *SeriesUpdate { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveSeasonIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *SeriesUpdate) 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 *SeriesUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *SeriesUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *SeriesUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *SeriesUpdate) check() error { + if v, ok := _u.mutation.Title(); ok { + if err := series.TitleValidator(v); err != nil { + return &ValidationError{Name: "title", err: fmt.Errorf(`ent: validator failed for field "Series.title": %w`, err)} + } + } + return nil +} + +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *SeriesUpdate) WithRetryOptions(opts ...any) *SeriesUpdate { + _u.retryConfig.Options = opts + return _u +} + +func (_u *SeriesUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(series.Table, series.Columns, sqlgraph.NewFieldSpec(series.FieldID, field.TypeInt64)) + 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.Title(); ok { + _spec.SetField(series.FieldTitle, field.TypeString, value) + } + if value, ok := _u.mutation.Info(); ok { + _spec.SetField(series.FieldInfo, field.TypeString, value) + } + if _u.mutation.InfoCleared() { + _spec.ClearField(series.FieldInfo, field.TypeString) + } + if value, ok := _u.mutation.ReleaseDate(); ok { + _spec.SetField(series.FieldReleaseDate, field.TypeTime, value) + } + if _u.mutation.SeasonsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: series.SeasonsTable, + Columns: []string{series.SeasonsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(season.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedSeasonsIDs(); len(nodes) > 0 && !_u.mutation.SeasonsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: series.SeasonsTable, + Columns: []string{series.SeasonsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(season.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.SeasonsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: series.SeasonsTable, + Columns: []string{series.SeasonsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(season.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.RetryConfig = _u.retryConfig + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{series.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// SeriesUpdateOne is the builder for updating a single Series entity. +type SeriesUpdateOne struct { + config + fields []string + hooks []Hook + mutation *SeriesMutation + retryConfig sqlgraph.RetryConfig +} + +// SetTitle sets the "title" field. +func (_u *SeriesUpdateOne) SetTitle(v string) *SeriesUpdateOne { + _u.mutation.SetTitle(v) + return _u +} + +// SetNillableTitle sets the "title" field if the given value is not nil. +func (_u *SeriesUpdateOne) SetNillableTitle(v *string) *SeriesUpdateOne { + if v != nil { + _u.SetTitle(*v) + } + return _u +} + +// SetInfo sets the "info" field. +func (_u *SeriesUpdateOne) SetInfo(v string) *SeriesUpdateOne { + _u.mutation.SetInfo(v) + return _u +} + +// SetNillableInfo sets the "info" field if the given value is not nil. +func (_u *SeriesUpdateOne) SetNillableInfo(v *string) *SeriesUpdateOne { + if v != nil { + _u.SetInfo(*v) + } + return _u +} + +// ClearInfo clears the value of the "info" field. +func (_u *SeriesUpdateOne) ClearInfo() *SeriesUpdateOne { + _u.mutation.ClearInfo() + return _u +} + +// SetReleaseDate sets the "release_date" field. +func (_u *SeriesUpdateOne) SetReleaseDate(v time.Time) *SeriesUpdateOne { + _u.mutation.SetReleaseDate(v) + return _u +} + +// SetNillableReleaseDate sets the "release_date" field if the given value is not nil. +func (_u *SeriesUpdateOne) SetNillableReleaseDate(v *time.Time) *SeriesUpdateOne { + if v != nil { + _u.SetReleaseDate(*v) + } + return _u +} + +// AddSeasonIDs adds the "seasons" edge to the Season entity by IDs. +func (_u *SeriesUpdateOne) AddSeasonIDs(ids ...int64) *SeriesUpdateOne { + _u.mutation.AddSeasonIDs(ids...) + return _u +} + +// AddSeasons adds the "seasons" edges to the Season entity. +func (_u *SeriesUpdateOne) AddSeasons(v ...*Season) *SeriesUpdateOne { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddSeasonIDs(ids...) +} + +// Mutation returns the SeriesMutation object of the builder. +func (_u *SeriesUpdateOne) Mutation() *SeriesMutation { + return _u.mutation +} + +// ClearSeasons clears all "seasons" edges to the Season entity. +func (_u *SeriesUpdateOne) ClearSeasons() *SeriesUpdateOne { + _u.mutation.ClearSeasons() + return _u +} + +// RemoveSeasonIDs removes the "seasons" edge to Season entities by IDs. +func (_u *SeriesUpdateOne) RemoveSeasonIDs(ids ...int64) *SeriesUpdateOne { + _u.mutation.RemoveSeasonIDs(ids...) + return _u +} + +// RemoveSeasons removes "seasons" edges to Season entities. +func (_u *SeriesUpdateOne) RemoveSeasons(v ...*Season) *SeriesUpdateOne { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveSeasonIDs(ids...) +} + +// Where appends a list predicates to the SeriesUpdate builder. +func (_u *SeriesUpdateOne) Where(ps ...predicate.Series) *SeriesUpdateOne { + _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 *SeriesUpdateOne) Select(field string, fields ...string) *SeriesUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Series entity. +func (_u *SeriesUpdateOne) Save(ctx context.Context) (*Series, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *SeriesUpdateOne) SaveX(ctx context.Context) *Series { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *SeriesUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *SeriesUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *SeriesUpdateOne) check() error { + if v, ok := _u.mutation.Title(); ok { + if err := series.TitleValidator(v); err != nil { + return &ValidationError{Name: "title", err: fmt.Errorf(`ent: validator failed for field "Series.title": %w`, err)} + } + } + return nil +} + +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *SeriesUpdateOne) WithRetryOptions(opts ...any) *SeriesUpdateOne { + _u.retryConfig.Options = opts + return _u +} + +func (_u *SeriesUpdateOne) sqlSave(ctx context.Context) (_node *Series, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(series.Table, series.Columns, sqlgraph.NewFieldSpec(series.FieldID, field.TypeInt64)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Series.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, series.FieldID) + for _, f := range fields { + if !series.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != series.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.Title(); ok { + _spec.SetField(series.FieldTitle, field.TypeString, value) + } + if value, ok := _u.mutation.Info(); ok { + _spec.SetField(series.FieldInfo, field.TypeString, value) + } + if _u.mutation.InfoCleared() { + _spec.ClearField(series.FieldInfo, field.TypeString) + } + if value, ok := _u.mutation.ReleaseDate(); ok { + _spec.SetField(series.FieldReleaseDate, field.TypeTime, value) + } + if _u.mutation.SeasonsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: series.SeasonsTable, + Columns: []string{series.SeasonsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(season.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedSeasonsIDs(); len(nodes) > 0 && !_u.mutation.SeasonsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: series.SeasonsTable, + Columns: []string{series.SeasonsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(season.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.SeasonsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: series.SeasonsTable, + Columns: []string{series.SeasonsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(season.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.RetryConfig = _u.retryConfig + _node = &Series{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{series.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/examples/ydb/ent/tx.go b/examples/ydb/ent/tx.go new file mode 100644 index 0000000000..12c3ea1cbb --- /dev/null +++ b/examples/ydb/ent/tx.go @@ -0,0 +1,220 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "sync" + + "entgo.io/ent/dialect" +) + +// Tx is a transactional client that is created by calling Client.Tx(). +type Tx struct { + config + // Episode is the client for interacting with the Episode builders. + Episode *EpisodeClient + // Season is the client for interacting with the Season builders. + Season *SeasonClient + // Series is the client for interacting with the Series builders. + Series *SeriesClient + + // 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.Episode = NewEpisodeClient(tx.config) + tx.Season = NewSeasonClient(tx.config) + tx.Series = NewSeriesClient(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: Episode.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 +} + +// 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/examples/ydb/example.go b/examples/ydb/example.go new file mode 100644 index 0000000000..797b9cf311 --- /dev/null +++ b/examples/ydb/example.go @@ -0,0 +1,194 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +package main + +import ( + "context" + "fmt" + "log" + "time" + + "ariga.io/atlas/sql/migrate" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/examples/ydb/ent" + "entgo.io/ent/examples/ydb/ent/episode" + "entgo.io/ent/examples/ydb/ent/season" + "entgo.io/ent/examples/ydb/ent/series" + + "github.com/ydb-platform/ydb-go-sdk/v3/retry" +) + +func main() { + // Open connection to YDB + client, err := ent.Open("ydb", "grpc://localhost:2136/local") + if err != nil { + log.Fatalf("failed opening connection to ydb: %v", err) + } + defer client.Close() + + ctx := context.Background() + + // Run the auto migration tool to create tables with debug logging + err = client.Schema.Create( + ctx, + schema.WithDropColumn(true), + schema.WithDropIndex(true), + schema.WithApplyHook(func(next schema.Applier) schema.Applier { + return schema.ApplyFunc(func(ctx context.Context, conn dialect.ExecQuerier, plan *migrate.Plan) error { + log.Println("=== DDL Commands ===") + for i, c := range plan.Changes { + log.Printf("DDL[%d] Comment: %s", i, c.Comment) + log.Printf("DDL[%d] Cmd: %s", i, c.Cmd) + log.Printf("DDL[%d] Args: %v", i, c.Args) + } + return next.Apply(ctx, conn, plan) + }) + }), + ) + if err != nil { + log.Fatalf("failed creating schema resources: %v", err) + } + + // Clear existing data before running example + log.Println("Clearing existing data...") + if _, err := client.Episode.Delete().Exec(ctx); err != nil { + log.Printf("Warning: failed to clear episodes: %v", err) + } + if _, err := client.Season.Delete().Exec(ctx); err != nil { + log.Printf("Warning: failed to clear seasons: %v", err) + } + if _, err := client.Series.Delete().Exec(ctx); err != nil { + log.Printf("Warning: failed to clear series: %v", err) + } + log.Println("Data cleared") + + // Run the example + if err := Example(ctx, client); err != nil { + log.Fatal(err) + } +} + +// Example demonstrates CRUD operations with YDB and ent. +func Example(ctx context.Context, client *ent.Client) error { + // Create a new series with retry options + theExpanse, err := client.Series.Create(). + SetTitle("The Expanse"). + SetInfo("Humanity has colonized the solar system - Mars, the Moon, the Asteroid Belt and beyond"). + SetReleaseDate(time.Date(2015, 12, 14, 0, 0, 0, 0, time.UTC)). + WithRetryOptions(retry.WithIdempotent(true)). + Save(ctx) + if err != nil { + return fmt.Errorf("failed creating series: %w", err) + } + log.Printf("Created series: %v", theExpanse) + + // Create seasons for the series + season1, err := client.Season.Create(). + SetTitle("Season 1"). + SetFirstAired(time.Date(2015, 12, 14, 0, 0, 0, 0, time.UTC)). + SetLastAired(time.Date(2016, 2, 2, 0, 0, 0, 0, time.UTC)). + SetSeries(theExpanse). + WithRetryOptions(retry.WithIdempotent(true)). + Save(ctx) + if err != nil { + return fmt.Errorf("failed creating season: %w", err) + } + log.Printf("Created season: %v", season1) + + // Create episodes + ep1, err := client.Episode.Create(). + SetTitle("Dulcinea"). + SetAirDate(time.Date(2015, 12, 14, 0, 0, 0, 0, time.UTC)). + SetSeason(season1). + WithRetryOptions(retry.WithIdempotent(true)). + Save(ctx) + if err != nil { + return fmt.Errorf("failed creating episode: %w", err) + } + log.Printf("Created episode: %v", ep1) + + ep2, err := client.Episode.Create(). + SetTitle("The Big Empty"). + SetAirDate(time.Date(2015, 12, 15, 0, 0, 0, 0, time.UTC)). + SetSeason(season1). + WithRetryOptions(retry.WithIdempotent(true)). + Save(ctx) + if err != nil { + return fmt.Errorf("failed creating episode: %w", err) + } + log.Printf("Created episode: %v", ep2) + + // Query series with retry options + allSeries, err := client.Series.Query(). + WithRetryOptions(retry.WithIdempotent(true)). + All(ctx) + if err != nil { + return fmt.Errorf("failed querying series: %w", err) + } + log.Printf("All series: %v", allSeries) + + // Query with filtering + expSeries, err := client.Series.Query(). + Where(series.TitleContains("Expanse")). + WithRetryOptions(retry.WithIdempotent(true)). + Only(ctx) + if err != nil { + return fmt.Errorf("failed querying series by title: %w", err) + } + log.Printf("Found series: %v", expSeries) + + // Query seasons for a series using edge traversal + seasons, err := expSeries.QuerySeasons(). + WithRetryOptions(retry.WithIdempotent(true)). + All(ctx) + if err != nil { + return fmt.Errorf("failed querying seasons: %w", err) + } + log.Printf("Seasons of %s: %v", expSeries.Title, seasons) + + // Query episodes for a season + episodes, err := client.Episode.Query(). + Where(episode.HasSeasonWith(season.TitleEQ("Season 1"))). + WithRetryOptions(retry.WithIdempotent(true)). + All(ctx) + if err != nil { + return fmt.Errorf("failed querying episodes: %w", err) + } + log.Printf("Episodes in Season 1: %v", episodes) + + // Update series info + _, err = client.Series.Update(). + Where(series.IDEQ(theExpanse.ID)). + SetInfo("Humanity has colonized the solar system - a sci-fi masterpiece based on the novels by James S.A. Corey"). + WithRetryOptions(retry.WithIdempotent(true)). + Save(ctx) + if err != nil { + return fmt.Errorf("failed updating series: %w", err) + } + log.Printf("Updated series info") + + // Delete episode + _, err = client.Episode.Delete(). + Where(episode.TitleEQ("The Big Empty")). + WithRetryOptions(retry.WithIdempotent(true)). + Exec(ctx) + if err != nil { + return fmt.Errorf("failed deleting episode: %w", err) + } + log.Printf("Deleted episode") + + // Verify deletion + remaining, err := client.Episode.Query(). + Where(episode.HasSeasonWith(season.TitleEQ("Season 1"))). + WithRetryOptions(retry.WithIdempotent(true)). + All(ctx) + if err != nil { + return fmt.Errorf("failed querying remaining episodes: %w", err) + } + log.Printf("Remaining episodes: %v", remaining) + + return nil +} From 400c5c3a3147928b372c149bf3dfb7e1595f5a93 Mon Sep 17 00:00:00 2001 From: danilov6083 Date: Fri, 16 Jan 2026 16:07:56 +0300 Subject: [PATCH 09/13] entc/integration: regenerated all integration code --- entc/integration/cascadelete/ent/client.go | 13 ++++++-- entc/integration/config/ent/client.go | 13 ++++++-- entc/integration/customid/ent/client.go | 13 ++++++-- entc/integration/edgefield/ent/client.go | 13 ++++++-- entc/integration/edgeschema/ent/client.go | 13 ++++++-- entc/integration/ent/api_create.go | 30 +++++++++++++---- entc/integration/ent/api_delete.go | 13 ++++++-- entc/integration/ent/api_query.go | 20 +++++++++--- entc/integration/ent/api_update.go | 32 +++++++++++++++---- entc/integration/ent/builder_create.go | 30 +++++++++++++---- entc/integration/ent/builder_delete.go | 13 ++++++-- entc/integration/ent/builder_query.go | 20 +++++++++--- entc/integration/ent/builder_update.go | 32 +++++++++++++++---- entc/integration/ent/card_create.go | 30 +++++++++++++---- entc/integration/ent/card_delete.go | 13 ++++++-- entc/integration/ent/card_query.go | 10 ++++++ entc/integration/ent/card_update.go | 32 +++++++++++++++---- entc/integration/ent/client.go | 13 ++++++-- entc/integration/ent/comment_create.go | 30 +++++++++++++---- entc/integration/ent/comment_delete.go | 13 ++++++-- entc/integration/ent/comment_query.go | 20 +++++++++--- entc/integration/ent/comment_update.go | 32 +++++++++++++++---- entc/integration/ent/exvaluescan_create.go | 30 +++++++++++++---- entc/integration/ent/exvaluescan_delete.go | 13 ++++++-- entc/integration/ent/exvaluescan_query.go | 20 +++++++++--- entc/integration/ent/exvaluescan_update.go | 32 +++++++++++++++---- entc/integration/ent/fieldtype_create.go | 30 +++++++++++++---- entc/integration/ent/fieldtype_delete.go | 13 ++++++-- entc/integration/ent/fieldtype_query.go | 22 +++++++++---- entc/integration/ent/fieldtype_update.go | 32 +++++++++++++++---- entc/integration/ent/file_create.go | 30 +++++++++++++---- entc/integration/ent/file_delete.go | 13 ++++++-- entc/integration/ent/file_query.go | 10 ++++++ entc/integration/ent/file_update.go | 32 +++++++++++++++---- entc/integration/ent/filetype_create.go | 30 +++++++++++++---- entc/integration/ent/filetype_delete.go | 13 ++++++-- entc/integration/ent/filetype_query.go | 10 ++++++ entc/integration/ent/filetype_update.go | 32 +++++++++++++++---- entc/integration/ent/generate.go | 2 +- entc/integration/ent/goods_create.go | 30 +++++++++++++---- entc/integration/ent/goods_delete.go | 13 ++++++-- entc/integration/ent/goods_query.go | 20 +++++++++--- entc/integration/ent/goods_update.go | 32 +++++++++++++++---- entc/integration/ent/group_create.go | 30 +++++++++++++---- entc/integration/ent/group_delete.go | 13 ++++++-- entc/integration/ent/group_query.go | 10 ++++++ entc/integration/ent/group_update.go | 32 +++++++++++++++---- entc/integration/ent/groupinfo_create.go | 30 +++++++++++++---- entc/integration/ent/groupinfo_delete.go | 13 ++++++-- entc/integration/ent/groupinfo_query.go | 10 ++++++ entc/integration/ent/groupinfo_update.go | 32 +++++++++++++++---- entc/integration/ent/item_create.go | 30 +++++++++++++---- entc/integration/ent/item_delete.go | 13 ++++++-- entc/integration/ent/item_query.go | 20 +++++++++--- entc/integration/ent/item_update.go | 32 +++++++++++++++---- entc/integration/ent/license_create.go | 30 +++++++++++++---- entc/integration/ent/license_delete.go | 13 ++++++-- entc/integration/ent/license_query.go | 20 +++++++++--- entc/integration/ent/license_update.go | 32 +++++++++++++++---- entc/integration/ent/node_create.go | 30 +++++++++++++---- entc/integration/ent/node_delete.go | 13 ++++++-- entc/integration/ent/node_query.go | 26 ++++++++++----- entc/integration/ent/node_update.go | 32 +++++++++++++++---- entc/integration/ent/pc_create.go | 30 +++++++++++++---- entc/integration/ent/pc_delete.go | 13 ++++++-- entc/integration/ent/pc_query.go | 20 +++++++++--- entc/integration/ent/pc_update.go | 32 +++++++++++++++---- entc/integration/ent/pet_create.go | 30 +++++++++++++---- entc/integration/ent/pet_delete.go | 13 ++++++-- entc/integration/ent/pet_query.go | 26 ++++++++++----- entc/integration/ent/pet_update.go | 32 +++++++++++++++---- entc/integration/ent/spec_create.go | 30 +++++++++++++---- entc/integration/ent/spec_delete.go | 13 ++++++-- entc/integration/ent/spec_query.go | 10 ++++++ entc/integration/ent/spec_update.go | 32 +++++++++++++++---- entc/integration/ent/task_create.go | 30 +++++++++++++---- entc/integration/ent/task_delete.go | 13 ++++++-- entc/integration/ent/task_query.go | 20 +++++++++--- entc/integration/ent/task_update.go | 32 +++++++++++++++---- entc/integration/ent/user_create.go | 30 +++++++++++++---- entc/integration/ent/user_delete.go | 13 ++++++-- entc/integration/ent/user_query.go | 10 ++++++ entc/integration/ent/user_update.go | 32 +++++++++++++++---- entc/integration/go.sum | 22 +++++++++++++ entc/integration/hooks/ent/client.go | 13 ++++++-- entc/integration/idtype/ent/client.go | 13 ++++++-- entc/integration/json/ent/client.go | 13 ++++++-- entc/integration/migrate/entv1/client.go | 13 ++++++-- entc/integration/migrate/entv2/blog_create.go | 2 +- entc/integration/migrate/entv2/client.go | 13 ++++++-- entc/integration/migrate/versioned/client.go | 13 ++++++-- entc/integration/multischema/ent/client.go | 13 ++++++-- .../multischema/versioned/client.go | 13 ++++++-- entc/integration/privacy/ent/client.go | 13 ++++++-- entc/integration/template/ent/client.go | 13 ++++++-- 95 files changed, 1597 insertions(+), 386 deletions(-) diff --git a/entc/integration/cascadelete/ent/client.go b/entc/integration/cascadelete/ent/client.go index 1d4ef1f1e7..554ee80e20 100644 --- a/entc/integration/cascadelete/ent/client.go +++ b/entc/integration/cascadelete/ent/client.go @@ -19,6 +19,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/entc/integration/cascadelete/ent/comment" "entgo.io/ent/entc/integration/cascadelete/ent/post" "entgo.io/ent/entc/integration/cascadelete/ent/user" @@ -112,8 +113,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/entc/integration/config/ent/client.go b/entc/integration/config/ent/client.go index 53fdadb55a..1b9dee98cb 100644 --- a/entc/integration/config/ent/client.go +++ b/entc/integration/config/ent/client.go @@ -18,6 +18,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/entc/integration/config/ent/user" ) @@ -103,8 +104,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/entc/integration/customid/ent/client.go b/entc/integration/customid/ent/client.go index af08dc9747..85427b4f00 100644 --- a/entc/integration/customid/ent/client.go +++ b/entc/integration/customid/ent/client.go @@ -23,6 +23,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/entc/integration/customid/ent/account" "entgo.io/ent/entc/integration/customid/ent/blob" "entgo.io/ent/entc/integration/customid/ent/bloblink" @@ -172,8 +173,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/entc/integration/edgefield/ent/client.go b/entc/integration/edgefield/ent/client.go index ca24675669..eaf9bcb348 100644 --- a/entc/integration/edgefield/ent/client.go +++ b/entc/integration/edgefield/ent/client.go @@ -20,6 +20,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/entc/integration/edgefield/ent/car" "entgo.io/ent/entc/integration/edgefield/ent/card" "entgo.io/ent/entc/integration/edgefield/ent/info" @@ -137,8 +138,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/entc/integration/edgeschema/ent/client.go b/entc/integration/edgeschema/ent/client.go index 0d084d1535..3a8ad32449 100644 --- a/entc/integration/edgeschema/ent/client.go +++ b/entc/integration/edgeschema/ent/client.go @@ -20,6 +20,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/entc/integration/edgeschema/ent/attachedfile" "entgo.io/ent/entc/integration/edgeschema/ent/file" "entgo.io/ent/entc/integration/edgeschema/ent/friendship" @@ -169,8 +170,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/entc/integration/ent/api_create.go b/entc/integration/ent/api_create.go index ec60346db8..11995cb813 100644 --- a/entc/integration/ent/api_create.go +++ b/entc/integration/ent/api_create.go @@ -20,9 +20,10 @@ import ( // APICreate is the builder for creating a Api entity. type APICreate struct { config - mutation *APIMutation - hooks []Hook - conflict []sql.ConflictOption + mutation *APIMutation + hooks []Hook + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // Mutation returns the APIMutation object of the builder. @@ -85,10 +86,18 @@ func (_c *APICreate) createSpec() (*Api, *sqlgraph.CreateSpec) { _node = &Api{config: _c.config} _spec = sqlgraph.NewCreateSpec(api.Table, sqlgraph.NewFieldSpec(api.FieldID, field.TypeInt)) ) + _spec.RetryConfig = _c.retryConfig _spec.OnConflict = _c.conflict return _node, _spec } +// WithRetryOptions sets the retry options for the create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *APICreate) WithRetryOptions(opts ...any) *APICreate { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // @@ -208,9 +217,10 @@ func (u *ApiUpsertOne) IDX(ctx context.Context) int { // APICreateBulk is the builder for creating many Api entities in bulk. type APICreateBulk struct { config - err error - builders []*APICreate - conflict []sql.ConflictOption + err error + builders []*APICreate + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // Save creates the Api entities in the database. @@ -239,6 +249,7 @@ func (_c *APICreateBulk) Save(ctx context.Context) ([]*Api, error) { _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.RetryConfig = _c.retryConfig 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 { @@ -294,6 +305,13 @@ func (_c *APICreateBulk) ExecX(ctx context.Context) { } } +// WithRetryOptions sets the retry options for the bulk create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *APICreateBulk) WithRetryOptions(opts ...any) *APICreateBulk { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // diff --git a/entc/integration/ent/api_delete.go b/entc/integration/ent/api_delete.go index fcbbdb3bc1..ea896eca93 100644 --- a/entc/integration/ent/api_delete.go +++ b/entc/integration/ent/api_delete.go @@ -19,8 +19,9 @@ import ( // APIDelete is the builder for deleting a Api entity. type APIDelete struct { config - hooks []Hook - mutation *APIMutation + hooks []Hook + mutation *APIMutation + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the APIDelete builder. @@ -45,6 +46,7 @@ func (_d *APIDelete) ExecX(ctx context.Context) int { func (_d *APIDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(api.Table, sqlgraph.NewFieldSpec(api.FieldID, field.TypeInt)) + _spec.RetryConfig = _d.retryConfig if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { @@ -60,6 +62,13 @@ func (_d *APIDelete) sqlExec(ctx context.Context) (int, error) { return affected, err } +// WithRetryOptions sets the retry options for the delete operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_d *APIDelete) WithRetryOptions(opts ...any) *APIDelete { + _d.retryConfig.Options = opts + return _d +} + // APIDeleteOne is the builder for deleting a single Api entity. type APIDeleteOne struct { _d *APIDelete diff --git a/entc/integration/ent/api_query.go b/entc/integration/ent/api_query.go index 78aa8e9aa1..256d3f8281 100644 --- a/entc/integration/ent/api_query.go +++ b/entc/integration/ent/api_query.go @@ -23,11 +23,12 @@ import ( // APIQuery is the builder for querying Api entities. type APIQuery struct { config - ctx *QueryContext - order []api.OrderOption - inters []Interceptor - predicates []predicate.Api - modifiers []func(*sql.Selector) + ctx *QueryContext + order []api.OrderOption + inters []Interceptor + predicates []predicate.Api + modifiers []func(*sql.Selector) + retryConfig sqlgraph.RetryConfig // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -331,6 +332,7 @@ func (_q *APIQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Api, err if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig for i := range hooks { hooks[i](ctx, _spec) } @@ -348,6 +350,7 @@ func (_q *APIQuery) sqlCount(ctx context.Context) (int, error) { if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig _spec.Node.Columns = _q.ctx.Fields if len(_q.ctx.Fields) > 0 { _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique @@ -462,6 +465,13 @@ func (_q *APIQuery) Modify(modifiers ...func(s *sql.Selector)) *APISelect { return _q.Select() } +// WithRetryOptions sets the retry options for the query operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_q *APIQuery) WithRetryOptions(opts ...any) *APIQuery { + _q.retryConfig.Options = opts + return _q +} + // APIGroupBy is the group-by builder for Api entities. type APIGroupBy struct { selector diff --git a/entc/integration/ent/api_update.go b/entc/integration/ent/api_update.go index fd9d0a456e..ad788a6f45 100644 --- a/entc/integration/ent/api_update.go +++ b/entc/integration/ent/api_update.go @@ -21,9 +21,10 @@ import ( // APIUpdate is the builder for updating Api entities. type APIUpdate struct { config - hooks []Hook - mutation *APIMutation - modifiers []func(*sql.UpdateBuilder) + hooks []Hook + mutation *APIMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the APIUpdate builder. @@ -70,6 +71,13 @@ func (_u *APIUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *APIUpdate return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *APIUpdate) WithRetryOptions(opts ...any) *APIUpdate { + _u.retryConfig.Options = opts + return _u +} + func (_u *APIUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec := sqlgraph.NewUpdateSpec(api.Table, api.Columns, sqlgraph.NewFieldSpec(api.FieldID, field.TypeInt)) if ps := _u.mutation.predicates; len(ps) > 0 { @@ -80,6 +88,7 @@ func (_u *APIUpdate) sqlSave(ctx context.Context) (_node int, err error) { } } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{api.Label} @@ -95,10 +104,11 @@ func (_u *APIUpdate) sqlSave(ctx context.Context) (_node int, err error) { // APIUpdateOne is the builder for updating a single Api entity. type APIUpdateOne struct { config - fields []string - hooks []Hook - mutation *APIMutation - modifiers []func(*sql.UpdateBuilder) + fields []string + hooks []Hook + mutation *APIMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // Mutation returns the APIMutation object of the builder. @@ -152,6 +162,13 @@ func (_u *APIUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *APIUpda return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *APIUpdateOne) WithRetryOptions(opts ...any) *APIUpdateOne { + _u.retryConfig.Options = opts + return _u +} + func (_u *APIUpdateOne) sqlSave(ctx context.Context) (_node *Api, err error) { _spec := sqlgraph.NewUpdateSpec(api.Table, api.Columns, sqlgraph.NewFieldSpec(api.FieldID, field.TypeInt)) id, ok := _u.mutation.ID() @@ -179,6 +196,7 @@ func (_u *APIUpdateOne) sqlSave(ctx context.Context) (_node *Api, err error) { } } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig _node = &Api{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/entc/integration/ent/builder_create.go b/entc/integration/ent/builder_create.go index bc698496b2..ce42a6c5c8 100644 --- a/entc/integration/ent/builder_create.go +++ b/entc/integration/ent/builder_create.go @@ -20,9 +20,10 @@ import ( // BuilderCreate is the builder for creating a Builder entity. type BuilderCreate struct { config - mutation *BuilderMutation - hooks []Hook - conflict []sql.ConflictOption + mutation *BuilderMutation + hooks []Hook + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // Mutation returns the BuilderMutation object of the builder. @@ -85,10 +86,18 @@ func (_c *BuilderCreate) createSpec() (*Builder, *sqlgraph.CreateSpec) { _node = &Builder{config: _c.config} _spec = sqlgraph.NewCreateSpec(builder.Table, sqlgraph.NewFieldSpec(builder.FieldID, field.TypeInt)) ) + _spec.RetryConfig = _c.retryConfig _spec.OnConflict = _c.conflict return _node, _spec } +// WithRetryOptions sets the retry options for the create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *BuilderCreate) WithRetryOptions(opts ...any) *BuilderCreate { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // @@ -208,9 +217,10 @@ func (u *BuilderUpsertOne) IDX(ctx context.Context) int { // BuilderCreateBulk is the builder for creating many Builder entities in bulk. type BuilderCreateBulk struct { config - err error - builders []*BuilderCreate - conflict []sql.ConflictOption + err error + builders []*BuilderCreate + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // Save creates the Builder entities in the database. @@ -239,6 +249,7 @@ func (_c *BuilderCreateBulk) Save(ctx context.Context) ([]*Builder, error) { _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.RetryConfig = _c.retryConfig 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 { @@ -294,6 +305,13 @@ func (_c *BuilderCreateBulk) ExecX(ctx context.Context) { } } +// WithRetryOptions sets the retry options for the bulk create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *BuilderCreateBulk) WithRetryOptions(opts ...any) *BuilderCreateBulk { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // diff --git a/entc/integration/ent/builder_delete.go b/entc/integration/ent/builder_delete.go index 530a021b40..e2df610c9b 100644 --- a/entc/integration/ent/builder_delete.go +++ b/entc/integration/ent/builder_delete.go @@ -19,8 +19,9 @@ import ( // BuilderDelete is the builder for deleting a Builder entity. type BuilderDelete struct { config - hooks []Hook - mutation *BuilderMutation + hooks []Hook + mutation *BuilderMutation + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the BuilderDelete builder. @@ -45,6 +46,7 @@ func (_d *BuilderDelete) ExecX(ctx context.Context) int { func (_d *BuilderDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(builder.Table, sqlgraph.NewFieldSpec(builder.FieldID, field.TypeInt)) + _spec.RetryConfig = _d.retryConfig if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { @@ -60,6 +62,13 @@ func (_d *BuilderDelete) sqlExec(ctx context.Context) (int, error) { return affected, err } +// WithRetryOptions sets the retry options for the delete operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_d *BuilderDelete) WithRetryOptions(opts ...any) *BuilderDelete { + _d.retryConfig.Options = opts + return _d +} + // BuilderDeleteOne is the builder for deleting a single Builder entity. type BuilderDeleteOne struct { _d *BuilderDelete diff --git a/entc/integration/ent/builder_query.go b/entc/integration/ent/builder_query.go index e797623818..111b69a9d8 100644 --- a/entc/integration/ent/builder_query.go +++ b/entc/integration/ent/builder_query.go @@ -23,11 +23,12 @@ import ( // BuilderQuery is the builder for querying Builder entities. type BuilderQuery struct { config - ctx *QueryContext - order []builder.OrderOption - inters []Interceptor - predicates []predicate.Builder - modifiers []func(*sql.Selector) + ctx *QueryContext + order []builder.OrderOption + inters []Interceptor + predicates []predicate.Builder + modifiers []func(*sql.Selector) + retryConfig sqlgraph.RetryConfig // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -331,6 +332,7 @@ func (_q *BuilderQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Buil if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig for i := range hooks { hooks[i](ctx, _spec) } @@ -348,6 +350,7 @@ func (_q *BuilderQuery) sqlCount(ctx context.Context) (int, error) { if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig _spec.Node.Columns = _q.ctx.Fields if len(_q.ctx.Fields) > 0 { _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique @@ -462,6 +465,13 @@ func (_q *BuilderQuery) Modify(modifiers ...func(s *sql.Selector)) *BuilderSelec return _q.Select() } +// WithRetryOptions sets the retry options for the query operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_q *BuilderQuery) WithRetryOptions(opts ...any) *BuilderQuery { + _q.retryConfig.Options = opts + return _q +} + // BuilderGroupBy is the group-by builder for Builder entities. type BuilderGroupBy struct { selector diff --git a/entc/integration/ent/builder_update.go b/entc/integration/ent/builder_update.go index 179c6d84b8..b543367ef3 100644 --- a/entc/integration/ent/builder_update.go +++ b/entc/integration/ent/builder_update.go @@ -21,9 +21,10 @@ import ( // BuilderUpdate is the builder for updating Builder entities. type BuilderUpdate struct { config - hooks []Hook - mutation *BuilderMutation - modifiers []func(*sql.UpdateBuilder) + hooks []Hook + mutation *BuilderMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the BuilderUpdate builder. @@ -70,6 +71,13 @@ func (_u *BuilderUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *Builde return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *BuilderUpdate) WithRetryOptions(opts ...any) *BuilderUpdate { + _u.retryConfig.Options = opts + return _u +} + func (_u *BuilderUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec := sqlgraph.NewUpdateSpec(builder.Table, builder.Columns, sqlgraph.NewFieldSpec(builder.FieldID, field.TypeInt)) if ps := _u.mutation.predicates; len(ps) > 0 { @@ -80,6 +88,7 @@ func (_u *BuilderUpdate) sqlSave(ctx context.Context) (_node int, err error) { } } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{builder.Label} @@ -95,10 +104,11 @@ func (_u *BuilderUpdate) sqlSave(ctx context.Context) (_node int, err error) { // BuilderUpdateOne is the builder for updating a single Builder entity. type BuilderUpdateOne struct { config - fields []string - hooks []Hook - mutation *BuilderMutation - modifiers []func(*sql.UpdateBuilder) + fields []string + hooks []Hook + mutation *BuilderMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // Mutation returns the BuilderMutation object of the builder. @@ -152,6 +162,13 @@ func (_u *BuilderUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *Bui return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *BuilderUpdateOne) WithRetryOptions(opts ...any) *BuilderUpdateOne { + _u.retryConfig.Options = opts + return _u +} + func (_u *BuilderUpdateOne) sqlSave(ctx context.Context) (_node *Builder, err error) { _spec := sqlgraph.NewUpdateSpec(builder.Table, builder.Columns, sqlgraph.NewFieldSpec(builder.FieldID, field.TypeInt)) id, ok := _u.mutation.ID() @@ -179,6 +196,7 @@ func (_u *BuilderUpdateOne) sqlSave(ctx context.Context) (_node *Builder, err er } } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig _node = &Builder{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/entc/integration/ent/card_create.go b/entc/integration/ent/card_create.go index 793ccc994c..eb559b8334 100644 --- a/entc/integration/ent/card_create.go +++ b/entc/integration/ent/card_create.go @@ -23,9 +23,10 @@ import ( // CardCreate is the builder for creating a Card entity. type CardCreate struct { config - mutation *CardMutation - hooks []Hook - conflict []sql.ConflictOption + mutation *CardMutation + hooks []Hook + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // SetCreateTime sets the "create_time" field. @@ -223,6 +224,7 @@ func (_c *CardCreate) createSpec() (*Card, *sqlgraph.CreateSpec) { _node = &Card{config: _c.config} _spec = sqlgraph.NewCreateSpec(card.Table, sqlgraph.NewFieldSpec(card.FieldID, field.TypeInt)) ) + _spec.RetryConfig = _c.retryConfig _spec.OnConflict = _c.conflict if value, ok := _c.mutation.CreateTime(); ok { _spec.SetField(card.FieldCreateTime, field.TypeTime, value) @@ -280,6 +282,13 @@ func (_c *CardCreate) createSpec() (*Card, *sqlgraph.CreateSpec) { return _node, _spec } +// WithRetryOptions sets the retry options for the create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *CardCreate) WithRetryOptions(opts ...any) *CardCreate { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // @@ -517,9 +526,10 @@ func (u *CardUpsertOne) IDX(ctx context.Context) int { // CardCreateBulk is the builder for creating many Card entities in bulk. type CardCreateBulk struct { config - err error - builders []*CardCreate - conflict []sql.ConflictOption + err error + builders []*CardCreate + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // Save creates the Card entities in the database. @@ -549,6 +559,7 @@ func (_c *CardCreateBulk) Save(ctx context.Context) ([]*Card, error) { _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.RetryConfig = _c.retryConfig 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 { @@ -604,6 +615,13 @@ func (_c *CardCreateBulk) ExecX(ctx context.Context) { } } +// WithRetryOptions sets the retry options for the bulk create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *CardCreateBulk) WithRetryOptions(opts ...any) *CardCreateBulk { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // diff --git a/entc/integration/ent/card_delete.go b/entc/integration/ent/card_delete.go index d177539bb0..d6479ec76d 100644 --- a/entc/integration/ent/card_delete.go +++ b/entc/integration/ent/card_delete.go @@ -19,8 +19,9 @@ import ( // CardDelete is the builder for deleting a Card entity. type CardDelete struct { config - hooks []Hook - mutation *CardMutation + hooks []Hook + mutation *CardMutation + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the CardDelete builder. @@ -45,6 +46,7 @@ func (_d *CardDelete) ExecX(ctx context.Context) int { func (_d *CardDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(card.Table, sqlgraph.NewFieldSpec(card.FieldID, field.TypeInt)) + _spec.RetryConfig = _d.retryConfig if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { @@ -60,6 +62,13 @@ func (_d *CardDelete) sqlExec(ctx context.Context) (int, error) { return affected, err } +// WithRetryOptions sets the retry options for the delete operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_d *CardDelete) WithRetryOptions(opts ...any) *CardDelete { + _d.retryConfig.Options = opts + return _d +} + // CardDeleteOne is the builder for deleting a single Card entity. type CardDeleteOne struct { _d *CardDelete diff --git a/entc/integration/ent/card_query.go b/entc/integration/ent/card_query.go index 9b8f319b1d..b15621ff4b 100644 --- a/entc/integration/ent/card_query.go +++ b/entc/integration/ent/card_query.go @@ -35,6 +35,7 @@ type CardQuery struct { withFKs bool modifiers []func(*sql.Selector) withNamedSpec map[string]*SpecQuery + retryConfig sqlgraph.RetryConfig // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -440,6 +441,7 @@ func (_q *CardQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Card, e if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig for i := range hooks { hooks[i](ctx, _spec) } @@ -576,6 +578,7 @@ func (_q *CardQuery) sqlCount(ctx context.Context) (int, error) { if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig _spec.Node.Columns = _q.ctx.Fields if len(_q.ctx.Fields) > 0 { _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique @@ -704,6 +707,13 @@ func (_q *CardQuery) WithNamedSpec(name string, opts ...func(*SpecQuery)) *CardQ return _q } +// WithRetryOptions sets the retry options for the query operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_q *CardQuery) WithRetryOptions(opts ...any) *CardQuery { + _q.retryConfig.Options = opts + return _q +} + // CardGroupBy is the group-by builder for Card entities. type CardGroupBy struct { selector diff --git a/entc/integration/ent/card_update.go b/entc/integration/ent/card_update.go index 3eeffb0202..679c383abf 100644 --- a/entc/integration/ent/card_update.go +++ b/entc/integration/ent/card_update.go @@ -24,9 +24,10 @@ import ( // CardUpdate is the builder for updating Card entities. type CardUpdate struct { config - hooks []Hook - mutation *CardMutation - modifiers []func(*sql.UpdateBuilder) + hooks []Hook + mutation *CardMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the CardUpdate builder. @@ -200,6 +201,13 @@ func (_u *CardUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *CardUpdat return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *CardUpdate) WithRetryOptions(opts ...any) *CardUpdate { + _u.retryConfig.Options = opts + return _u +} + func (_u *CardUpdate) sqlSave(ctx context.Context) (_node int, err error) { if err := _u.check(); err != nil { return _node, err @@ -302,6 +310,7 @@ func (_u *CardUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec.Edges.Add = append(_spec.Edges.Add, edge) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{card.Label} @@ -317,10 +326,11 @@ func (_u *CardUpdate) sqlSave(ctx context.Context) (_node int, err error) { // CardUpdateOne is the builder for updating a single Card entity. type CardUpdateOne struct { config - fields []string - hooks []Hook - mutation *CardMutation - modifiers []func(*sql.UpdateBuilder) + fields []string + hooks []Hook + mutation *CardMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // SetUpdateTime sets the "update_time" field. @@ -501,6 +511,13 @@ func (_u *CardUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *CardUp return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *CardUpdateOne) WithRetryOptions(opts ...any) *CardUpdateOne { + _u.retryConfig.Options = opts + return _u +} + func (_u *CardUpdateOne) sqlSave(ctx context.Context) (_node *Card, err error) { if err := _u.check(); err != nil { return _node, err @@ -620,6 +637,7 @@ func (_u *CardUpdateOne) sqlSave(ctx context.Context) (_node *Card, err error) { _spec.Edges.Add = append(_spec.Edges.Add, edge) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig _node = &Card{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/entc/integration/ent/client.go b/entc/integration/ent/client.go index c848a9fe37..199db87d67 100644 --- a/entc/integration/ent/client.go +++ b/entc/integration/ent/client.go @@ -19,6 +19,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/entc/integration/ent/api" "entgo.io/ent/entc/integration/ent/builder" "entgo.io/ent/entc/integration/ent/card" @@ -179,8 +180,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/entc/integration/ent/comment_create.go b/entc/integration/ent/comment_create.go index 3d30fb8ed8..d06f067950 100644 --- a/entc/integration/ent/comment_create.go +++ b/entc/integration/ent/comment_create.go @@ -21,9 +21,10 @@ import ( // CommentCreate is the builder for creating a Comment entity. type CommentCreate struct { config - mutation *CommentMutation - hooks []Hook - conflict []sql.ConflictOption + mutation *CommentMutation + hooks []Hook + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // SetUniqueInt sets the "unique_int" field. @@ -160,6 +161,7 @@ func (_c *CommentCreate) createSpec() (*Comment, *sqlgraph.CreateSpec) { _node = &Comment{config: _c.config} _spec = sqlgraph.NewCreateSpec(comment.Table, sqlgraph.NewFieldSpec(comment.FieldID, field.TypeInt)) ) + _spec.RetryConfig = _c.retryConfig _spec.OnConflict = _c.conflict if value, ok := _c.mutation.UniqueInt(); ok { _spec.SetField(comment.FieldUniqueInt, field.TypeInt, value) @@ -188,6 +190,13 @@ func (_c *CommentCreate) createSpec() (*Comment, *sqlgraph.CreateSpec) { return _node, _spec } +// WithRetryOptions sets the retry options for the create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *CommentCreate) WithRetryOptions(opts ...any) *CommentCreate { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // @@ -560,9 +569,10 @@ func (u *CommentUpsertOne) IDX(ctx context.Context) int { // CommentCreateBulk is the builder for creating many Comment entities in bulk. type CommentCreateBulk struct { config - err error - builders []*CommentCreate - conflict []sql.ConflictOption + err error + builders []*CommentCreate + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // Save creates the Comment entities in the database. @@ -591,6 +601,7 @@ func (_c *CommentCreateBulk) Save(ctx context.Context) ([]*Comment, error) { _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.RetryConfig = _c.retryConfig 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 { @@ -646,6 +657,13 @@ func (_c *CommentCreateBulk) ExecX(ctx context.Context) { } } +// WithRetryOptions sets the retry options for the bulk create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *CommentCreateBulk) WithRetryOptions(opts ...any) *CommentCreateBulk { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // diff --git a/entc/integration/ent/comment_delete.go b/entc/integration/ent/comment_delete.go index 5e6d04f522..f4f2270eb2 100644 --- a/entc/integration/ent/comment_delete.go +++ b/entc/integration/ent/comment_delete.go @@ -19,8 +19,9 @@ import ( // CommentDelete is the builder for deleting a Comment entity. type CommentDelete struct { config - hooks []Hook - mutation *CommentMutation + hooks []Hook + mutation *CommentMutation + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the CommentDelete builder. @@ -45,6 +46,7 @@ func (_d *CommentDelete) ExecX(ctx context.Context) int { func (_d *CommentDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(comment.Table, sqlgraph.NewFieldSpec(comment.FieldID, field.TypeInt)) + _spec.RetryConfig = _d.retryConfig if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { @@ -60,6 +62,13 @@ func (_d *CommentDelete) sqlExec(ctx context.Context) (int, error) { return affected, err } +// WithRetryOptions sets the retry options for the delete operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_d *CommentDelete) WithRetryOptions(opts ...any) *CommentDelete { + _d.retryConfig.Options = opts + return _d +} + // CommentDeleteOne is the builder for deleting a single Comment entity. type CommentDeleteOne struct { _d *CommentDelete diff --git a/entc/integration/ent/comment_query.go b/entc/integration/ent/comment_query.go index a8e5165de9..166542f3a2 100644 --- a/entc/integration/ent/comment_query.go +++ b/entc/integration/ent/comment_query.go @@ -23,11 +23,12 @@ import ( // CommentQuery is the builder for querying Comment entities. type CommentQuery struct { config - ctx *QueryContext - order []comment.OrderOption - inters []Interceptor - predicates []predicate.Comment - modifiers []func(*sql.Selector) + ctx *QueryContext + order []comment.OrderOption + inters []Interceptor + predicates []predicate.Comment + modifiers []func(*sql.Selector) + retryConfig sqlgraph.RetryConfig // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -353,6 +354,7 @@ func (_q *CommentQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Comm if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig for i := range hooks { hooks[i](ctx, _spec) } @@ -370,6 +372,7 @@ func (_q *CommentQuery) sqlCount(ctx context.Context) (int, error) { if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig _spec.Node.Columns = _q.ctx.Fields if len(_q.ctx.Fields) > 0 { _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique @@ -484,6 +487,13 @@ func (_q *CommentQuery) Modify(modifiers ...func(s *sql.Selector)) *CommentSelec return _q.Select() } +// WithRetryOptions sets the retry options for the query operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_q *CommentQuery) WithRetryOptions(opts ...any) *CommentQuery { + _q.retryConfig.Options = opts + return _q +} + // CommentGroupBy is the group-by builder for Comment entities. type CommentGroupBy struct { selector diff --git a/entc/integration/ent/comment_update.go b/entc/integration/ent/comment_update.go index 5a07e393a1..acc785dedc 100644 --- a/entc/integration/ent/comment_update.go +++ b/entc/integration/ent/comment_update.go @@ -22,9 +22,10 @@ import ( // CommentUpdate is the builder for updating Comment entities. type CommentUpdate struct { config - hooks []Hook - mutation *CommentMutation - modifiers []func(*sql.UpdateBuilder) + hooks []Hook + mutation *CommentMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the CommentUpdate builder. @@ -200,6 +201,13 @@ func (_u *CommentUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *Commen return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *CommentUpdate) WithRetryOptions(opts ...any) *CommentUpdate { + _u.retryConfig.Options = opts + return _u +} + func (_u *CommentUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec := sqlgraph.NewUpdateSpec(comment.Table, comment.Columns, sqlgraph.NewFieldSpec(comment.FieldID, field.TypeInt)) if ps := _u.mutation.predicates; len(ps) > 0 { @@ -249,6 +257,7 @@ func (_u *CommentUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec.ClearField(comment.FieldClient, field.TypeString) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{comment.Label} @@ -264,10 +273,11 @@ func (_u *CommentUpdate) sqlSave(ctx context.Context) (_node int, err error) { // CommentUpdateOne is the builder for updating a single Comment entity. type CommentUpdateOne struct { config - fields []string - hooks []Hook - mutation *CommentMutation - modifiers []func(*sql.UpdateBuilder) + fields []string + hooks []Hook + mutation *CommentMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // SetUniqueInt sets the "unique_int" field. @@ -450,6 +460,13 @@ func (_u *CommentUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *Com return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *CommentUpdateOne) WithRetryOptions(opts ...any) *CommentUpdateOne { + _u.retryConfig.Options = opts + return _u +} + func (_u *CommentUpdateOne) sqlSave(ctx context.Context) (_node *Comment, err error) { _spec := sqlgraph.NewUpdateSpec(comment.Table, comment.Columns, sqlgraph.NewFieldSpec(comment.FieldID, field.TypeInt)) id, ok := _u.mutation.ID() @@ -516,6 +533,7 @@ func (_u *CommentUpdateOne) sqlSave(ctx context.Context) (_node *Comment, err er _spec.ClearField(comment.FieldClient, field.TypeString) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig _node = &Comment{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/entc/integration/ent/exvaluescan_create.go b/entc/integration/ent/exvaluescan_create.go index 55fb92073f..f3137aa574 100644 --- a/entc/integration/ent/exvaluescan_create.go +++ b/entc/integration/ent/exvaluescan_create.go @@ -22,9 +22,10 @@ import ( // ExValueScanCreate is the builder for creating a ExValueScan entity. type ExValueScanCreate struct { config - mutation *ExValueScanMutation - hooks []Hook - conflict []sql.ConflictOption + mutation *ExValueScanMutation + hooks []Hook + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // SetBinary sets the "binary" field. @@ -161,6 +162,7 @@ func (_c *ExValueScanCreate) createSpec() (*ExValueScan, *sqlgraph.CreateSpec, e _node = &ExValueScan{config: _c.config} _spec = sqlgraph.NewCreateSpec(exvaluescan.Table, sqlgraph.NewFieldSpec(exvaluescan.FieldID, field.TypeInt)) ) + _spec.RetryConfig = _c.retryConfig _spec.OnConflict = _c.conflict if value, ok := _c.mutation.Binary(); ok { vv, err := exvaluescan.ValueScanner.Binary.Value(value) @@ -229,6 +231,13 @@ func (_c *ExValueScanCreate) createSpec() (*ExValueScan, *sqlgraph.CreateSpec, e return _node, _spec, nil } +// WithRetryOptions sets the retry options for the create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *ExValueScanCreate) WithRetryOptions(opts ...any) *ExValueScanCreate { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // @@ -601,9 +610,10 @@ func (u *ExValueScanUpsertOne) IDX(ctx context.Context) int { // ExValueScanCreateBulk is the builder for creating many ExValueScan entities in bulk. type ExValueScanCreateBulk struct { config - err error - builders []*ExValueScanCreate - conflict []sql.ConflictOption + err error + builders []*ExValueScanCreate + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // Save creates the ExValueScan entities in the database. @@ -635,6 +645,7 @@ func (_c *ExValueScanCreateBulk) Save(ctx context.Context) ([]*ExValueScan, erro _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.RetryConfig = _c.retryConfig 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 { @@ -690,6 +701,13 @@ func (_c *ExValueScanCreateBulk) ExecX(ctx context.Context) { } } +// WithRetryOptions sets the retry options for the bulk create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *ExValueScanCreateBulk) WithRetryOptions(opts ...any) *ExValueScanCreateBulk { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // diff --git a/entc/integration/ent/exvaluescan_delete.go b/entc/integration/ent/exvaluescan_delete.go index 3b9b8eb5e8..3a6556e16e 100644 --- a/entc/integration/ent/exvaluescan_delete.go +++ b/entc/integration/ent/exvaluescan_delete.go @@ -19,8 +19,9 @@ import ( // ExValueScanDelete is the builder for deleting a ExValueScan entity. type ExValueScanDelete struct { config - hooks []Hook - mutation *ExValueScanMutation + hooks []Hook + mutation *ExValueScanMutation + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the ExValueScanDelete builder. @@ -45,6 +46,7 @@ func (_d *ExValueScanDelete) ExecX(ctx context.Context) int { func (_d *ExValueScanDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(exvaluescan.Table, sqlgraph.NewFieldSpec(exvaluescan.FieldID, field.TypeInt)) + _spec.RetryConfig = _d.retryConfig if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { @@ -60,6 +62,13 @@ func (_d *ExValueScanDelete) sqlExec(ctx context.Context) (int, error) { return affected, err } +// WithRetryOptions sets the retry options for the delete operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_d *ExValueScanDelete) WithRetryOptions(opts ...any) *ExValueScanDelete { + _d.retryConfig.Options = opts + return _d +} + // ExValueScanDeleteOne is the builder for deleting a single ExValueScan entity. type ExValueScanDeleteOne struct { _d *ExValueScanDelete diff --git a/entc/integration/ent/exvaluescan_query.go b/entc/integration/ent/exvaluescan_query.go index 76d343604d..65590152e2 100644 --- a/entc/integration/ent/exvaluescan_query.go +++ b/entc/integration/ent/exvaluescan_query.go @@ -23,11 +23,12 @@ import ( // ExValueScanQuery is the builder for querying ExValueScan entities. type ExValueScanQuery struct { config - ctx *QueryContext - order []exvaluescan.OrderOption - inters []Interceptor - predicates []predicate.ExValueScan - modifiers []func(*sql.Selector) + ctx *QueryContext + order []exvaluescan.OrderOption + inters []Interceptor + predicates []predicate.ExValueScan + modifiers []func(*sql.Selector) + retryConfig sqlgraph.RetryConfig // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -353,6 +354,7 @@ func (_q *ExValueScanQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]* if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig for i := range hooks { hooks[i](ctx, _spec) } @@ -370,6 +372,7 @@ func (_q *ExValueScanQuery) sqlCount(ctx context.Context) (int, error) { if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig _spec.Node.Columns = _q.ctx.Fields if len(_q.ctx.Fields) > 0 { _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique @@ -484,6 +487,13 @@ func (_q *ExValueScanQuery) Modify(modifiers ...func(s *sql.Selector)) *ExValueS return _q.Select() } +// WithRetryOptions sets the retry options for the query operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_q *ExValueScanQuery) WithRetryOptions(opts ...any) *ExValueScanQuery { + _q.retryConfig.Options = opts + return _q +} + // ExValueScanGroupBy is the group-by builder for ExValueScan entities. type ExValueScanGroupBy struct { selector diff --git a/entc/integration/ent/exvaluescan_update.go b/entc/integration/ent/exvaluescan_update.go index 389c051db1..4e61748b2f 100644 --- a/entc/integration/ent/exvaluescan_update.go +++ b/entc/integration/ent/exvaluescan_update.go @@ -23,9 +23,10 @@ import ( // ExValueScanUpdate is the builder for updating ExValueScan entities. type ExValueScanUpdate struct { config - hooks []Hook - mutation *ExValueScanMutation - modifiers []func(*sql.UpdateBuilder) + hooks []Hook + mutation *ExValueScanMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the ExValueScanUpdate builder. @@ -162,6 +163,13 @@ func (_u *ExValueScanUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *Ex return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *ExValueScanUpdate) WithRetryOptions(opts ...any) *ExValueScanUpdate { + _u.retryConfig.Options = opts + return _u +} + func (_u *ExValueScanUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec := sqlgraph.NewUpdateSpec(exvaluescan.Table, exvaluescan.Columns, sqlgraph.NewFieldSpec(exvaluescan.FieldID, field.TypeInt)) if ps := _u.mutation.predicates; len(ps) > 0 { @@ -237,6 +245,7 @@ func (_u *ExValueScanUpdate) sqlSave(ctx context.Context) (_node int, err error) _spec.ClearField(exvaluescan.FieldCustomOptional, field.TypeString) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{exvaluescan.Label} @@ -252,10 +261,11 @@ func (_u *ExValueScanUpdate) sqlSave(ctx context.Context) (_node int, err error) // ExValueScanUpdateOne is the builder for updating a single ExValueScan entity. type ExValueScanUpdateOne struct { config - fields []string - hooks []Hook - mutation *ExValueScanMutation - modifiers []func(*sql.UpdateBuilder) + fields []string + hooks []Hook + mutation *ExValueScanMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // SetBinary sets the "binary" field. @@ -399,6 +409,13 @@ func (_u *ExValueScanUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *ExValueScanUpdateOne) WithRetryOptions(opts ...any) *ExValueScanUpdateOne { + _u.retryConfig.Options = opts + return _u +} + func (_u *ExValueScanUpdateOne) sqlSave(ctx context.Context) (_node *ExValueScan, err error) { _spec := sqlgraph.NewUpdateSpec(exvaluescan.Table, exvaluescan.Columns, sqlgraph.NewFieldSpec(exvaluescan.FieldID, field.TypeInt)) id, ok := _u.mutation.ID() @@ -491,6 +508,7 @@ func (_u *ExValueScanUpdateOne) sqlSave(ctx context.Context) (_node *ExValueScan _spec.ClearField(exvaluescan.FieldCustomOptional, field.TypeString) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig _node = &ExValueScan{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/entc/integration/ent/fieldtype_create.go b/entc/integration/ent/fieldtype_create.go index 5b4f8776e9..dcba23b626 100644 --- a/entc/integration/ent/fieldtype_create.go +++ b/entc/integration/ent/fieldtype_create.go @@ -26,9 +26,10 @@ import ( // FieldTypeCreate is the builder for creating a FieldType entity. type FieldTypeCreate struct { config - mutation *FieldTypeMutation - hooks []Hook - conflict []sql.ConflictOption + mutation *FieldTypeMutation + hooks []Hook + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // SetInt sets the "int" field. @@ -973,6 +974,7 @@ func (_c *FieldTypeCreate) createSpec() (*FieldType, *sqlgraph.CreateSpec) { _node = &FieldType{config: _c.config} _spec = sqlgraph.NewCreateSpec(fieldtype.Table, sqlgraph.NewFieldSpec(fieldtype.FieldID, field.TypeInt)) ) + _spec.RetryConfig = _c.retryConfig _spec.OnConflict = _c.conflict if value, ok := _c.mutation.Int(); ok { _spec.SetField(fieldtype.FieldInt, field.TypeInt, value) @@ -1237,6 +1239,13 @@ func (_c *FieldTypeCreate) createSpec() (*FieldType, *sqlgraph.CreateSpec) { return _node, _spec } +// WithRetryOptions sets the retry options for the create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *FieldTypeCreate) WithRetryOptions(opts ...any) *FieldTypeCreate { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // @@ -4170,9 +4179,10 @@ func (u *FieldTypeUpsertOne) IDX(ctx context.Context) int { // FieldTypeCreateBulk is the builder for creating many FieldType entities in bulk. type FieldTypeCreateBulk struct { config - err error - builders []*FieldTypeCreate - conflict []sql.ConflictOption + err error + builders []*FieldTypeCreate + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // Save creates the FieldType entities in the database. @@ -4202,6 +4212,7 @@ func (_c *FieldTypeCreateBulk) Save(ctx context.Context) ([]*FieldType, error) { _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.RetryConfig = _c.retryConfig 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 { @@ -4257,6 +4268,13 @@ func (_c *FieldTypeCreateBulk) ExecX(ctx context.Context) { } } +// WithRetryOptions sets the retry options for the bulk create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *FieldTypeCreateBulk) WithRetryOptions(opts ...any) *FieldTypeCreateBulk { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // diff --git a/entc/integration/ent/fieldtype_delete.go b/entc/integration/ent/fieldtype_delete.go index 28e4ccbcd9..0dd3867853 100644 --- a/entc/integration/ent/fieldtype_delete.go +++ b/entc/integration/ent/fieldtype_delete.go @@ -19,8 +19,9 @@ import ( // FieldTypeDelete is the builder for deleting a FieldType entity. type FieldTypeDelete struct { config - hooks []Hook - mutation *FieldTypeMutation + hooks []Hook + mutation *FieldTypeMutation + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the FieldTypeDelete builder. @@ -45,6 +46,7 @@ func (_d *FieldTypeDelete) ExecX(ctx context.Context) int { func (_d *FieldTypeDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(fieldtype.Table, sqlgraph.NewFieldSpec(fieldtype.FieldID, field.TypeInt)) + _spec.RetryConfig = _d.retryConfig if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { @@ -60,6 +62,13 @@ func (_d *FieldTypeDelete) sqlExec(ctx context.Context) (int, error) { return affected, err } +// WithRetryOptions sets the retry options for the delete operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_d *FieldTypeDelete) WithRetryOptions(opts ...any) *FieldTypeDelete { + _d.retryConfig.Options = opts + return _d +} + // FieldTypeDeleteOne is the builder for deleting a single FieldType entity. type FieldTypeDeleteOne struct { _d *FieldTypeDelete diff --git a/entc/integration/ent/fieldtype_query.go b/entc/integration/ent/fieldtype_query.go index 639514fac4..ac8b169052 100644 --- a/entc/integration/ent/fieldtype_query.go +++ b/entc/integration/ent/fieldtype_query.go @@ -23,12 +23,13 @@ import ( // FieldTypeQuery is the builder for querying FieldType entities. type FieldTypeQuery struct { config - ctx *QueryContext - order []fieldtype.OrderOption - inters []Interceptor - predicates []predicate.FieldType - withFKs bool - modifiers []func(*sql.Selector) + ctx *QueryContext + order []fieldtype.OrderOption + inters []Interceptor + predicates []predicate.FieldType + withFKs bool + modifiers []func(*sql.Selector) + retryConfig sqlgraph.RetryConfig // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -358,6 +359,7 @@ func (_q *FieldTypeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Fi if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig for i := range hooks { hooks[i](ctx, _spec) } @@ -375,6 +377,7 @@ func (_q *FieldTypeQuery) sqlCount(ctx context.Context) (int, error) { if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig _spec.Node.Columns = _q.ctx.Fields if len(_q.ctx.Fields) > 0 { _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique @@ -489,6 +492,13 @@ func (_q *FieldTypeQuery) Modify(modifiers ...func(s *sql.Selector)) *FieldTypeS return _q.Select() } +// WithRetryOptions sets the retry options for the query operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_q *FieldTypeQuery) WithRetryOptions(opts ...any) *FieldTypeQuery { + _q.retryConfig.Options = opts + return _q +} + // FieldTypeGroupBy is the group-by builder for FieldType entities. type FieldTypeGroupBy struct { selector diff --git a/entc/integration/ent/fieldtype_update.go b/entc/integration/ent/fieldtype_update.go index eda886c8e1..81890a7dd9 100644 --- a/entc/integration/ent/fieldtype_update.go +++ b/entc/integration/ent/fieldtype_update.go @@ -28,9 +28,10 @@ import ( // FieldTypeUpdate is the builder for updating FieldType entities. type FieldTypeUpdate struct { config - hooks []Hook - mutation *FieldTypeMutation - modifiers []func(*sql.UpdateBuilder) + hooks []Hook + mutation *FieldTypeMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the FieldTypeUpdate builder. @@ -1447,6 +1448,13 @@ func (_u *FieldTypeUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *Fiel return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *FieldTypeUpdate) WithRetryOptions(opts ...any) *FieldTypeUpdate { + _u.retryConfig.Options = opts + return _u +} + func (_u *FieldTypeUpdate) sqlSave(ctx context.Context) (_node int, err error) { if err := _u.check(); err != nil { return _node, err @@ -1918,6 +1926,7 @@ func (_u *FieldTypeUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec.ClearField(fieldtype.FieldPasswordOther, field.TypeOther) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{fieldtype.Label} @@ -1933,10 +1942,11 @@ func (_u *FieldTypeUpdate) sqlSave(ctx context.Context) (_node int, err error) { // FieldTypeUpdateOne is the builder for updating a single FieldType entity. type FieldTypeUpdateOne struct { config - fields []string - hooks []Hook - mutation *FieldTypeMutation - modifiers []func(*sql.UpdateBuilder) + fields []string + hooks []Hook + mutation *FieldTypeMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // SetInt sets the "int" field. @@ -3360,6 +3370,13 @@ func (_u *FieldTypeUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *F return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *FieldTypeUpdateOne) WithRetryOptions(opts ...any) *FieldTypeUpdateOne { + _u.retryConfig.Options = opts + return _u +} + func (_u *FieldTypeUpdateOne) sqlSave(ctx context.Context) (_node *FieldType, err error) { if err := _u.check(); err != nil { return _node, err @@ -3848,6 +3865,7 @@ func (_u *FieldTypeUpdateOne) sqlSave(ctx context.Context) (_node *FieldType, er _spec.ClearField(fieldtype.FieldPasswordOther, field.TypeOther) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig _node = &FieldType{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/entc/integration/ent/file_create.go b/entc/integration/ent/file_create.go index 6130182028..6b7c44fcc8 100644 --- a/entc/integration/ent/file_create.go +++ b/entc/integration/ent/file_create.go @@ -24,9 +24,10 @@ import ( // FileCreate is the builder for creating a File entity. type FileCreate struct { config - mutation *FileMutation - hooks []Hook - conflict []sql.ConflictOption + mutation *FileMutation + hooks []Hook + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // SetSetID sets the "set_id" field. @@ -271,6 +272,7 @@ func (_c *FileCreate) createSpec() (*File, *sqlgraph.CreateSpec) { _node = &File{config: _c.config} _spec = sqlgraph.NewCreateSpec(file.Table, sqlgraph.NewFieldSpec(file.FieldID, field.TypeInt)) ) + _spec.RetryConfig = _c.retryConfig _spec.OnConflict = _c.conflict if value, ok := _c.mutation.SetID(); ok { _spec.SetField(file.FieldSetID, field.TypeInt, value) @@ -357,6 +359,13 @@ func (_c *FileCreate) createSpec() (*File, *sqlgraph.CreateSpec) { return _node, _spec } +// WithRetryOptions sets the retry options for the create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *FileCreate) WithRetryOptions(opts ...any) *FileCreate { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // @@ -807,9 +816,10 @@ func (u *FileUpsertOne) IDX(ctx context.Context) int { // FileCreateBulk is the builder for creating many File entities in bulk. type FileCreateBulk struct { config - err error - builders []*FileCreate - conflict []sql.ConflictOption + err error + builders []*FileCreate + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // Save creates the File entities in the database. @@ -839,6 +849,7 @@ func (_c *FileCreateBulk) Save(ctx context.Context) ([]*File, error) { _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.RetryConfig = _c.retryConfig 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 { @@ -894,6 +905,13 @@ func (_c *FileCreateBulk) ExecX(ctx context.Context) { } } +// WithRetryOptions sets the retry options for the bulk create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *FileCreateBulk) WithRetryOptions(opts ...any) *FileCreateBulk { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // diff --git a/entc/integration/ent/file_delete.go b/entc/integration/ent/file_delete.go index c6a5d4f570..7af494bf69 100644 --- a/entc/integration/ent/file_delete.go +++ b/entc/integration/ent/file_delete.go @@ -19,8 +19,9 @@ import ( // FileDelete is the builder for deleting a File entity. type FileDelete struct { config - hooks []Hook - mutation *FileMutation + hooks []Hook + mutation *FileMutation + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the FileDelete builder. @@ -45,6 +46,7 @@ func (_d *FileDelete) ExecX(ctx context.Context) int { func (_d *FileDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(file.Table, sqlgraph.NewFieldSpec(file.FieldID, field.TypeInt)) + _spec.RetryConfig = _d.retryConfig if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { @@ -60,6 +62,13 @@ func (_d *FileDelete) sqlExec(ctx context.Context) (int, error) { return affected, err } +// WithRetryOptions sets the retry options for the delete operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_d *FileDelete) WithRetryOptions(opts ...any) *FileDelete { + _d.retryConfig.Options = opts + return _d +} + // FileDeleteOne is the builder for deleting a single File entity. type FileDeleteOne struct { _d *FileDelete diff --git a/entc/integration/ent/file_query.go b/entc/integration/ent/file_query.go index e5769c49b8..ac61788e95 100644 --- a/entc/integration/ent/file_query.go +++ b/entc/integration/ent/file_query.go @@ -37,6 +37,7 @@ type FileQuery struct { withFKs bool modifiers []func(*sql.Selector) withNamedField map[string]*FieldTypeQuery + retryConfig sqlgraph.RetryConfig // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -477,6 +478,7 @@ func (_q *FileQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*File, e if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig for i := range hooks { hooks[i](ctx, _spec) } @@ -616,6 +618,7 @@ func (_q *FileQuery) sqlCount(ctx context.Context) (int, error) { if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig _spec.Node.Columns = _q.ctx.Fields if len(_q.ctx.Fields) > 0 { _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique @@ -744,6 +747,13 @@ func (_q *FileQuery) WithNamedField(name string, opts ...func(*FieldTypeQuery)) return _q } +// WithRetryOptions sets the retry options for the query operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_q *FileQuery) WithRetryOptions(opts ...any) *FileQuery { + _q.retryConfig.Options = opts + return _q +} + // FileGroupBy is the group-by builder for File entities. type FileGroupBy struct { selector diff --git a/entc/integration/ent/file_update.go b/entc/integration/ent/file_update.go index 2b1e5eb831..da45d1c6b5 100644 --- a/entc/integration/ent/file_update.go +++ b/entc/integration/ent/file_update.go @@ -25,9 +25,10 @@ import ( // FileUpdate is the builder for updating File entities. type FileUpdate struct { config - hooks []Hook - mutation *FileMutation - modifiers []func(*sql.UpdateBuilder) + hooks []Hook + mutation *FileMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the FileUpdate builder. @@ -344,6 +345,13 @@ func (_u *FileUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *FileUpdat return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *FileUpdate) WithRetryOptions(opts ...any) *FileUpdate { + _u.retryConfig.Options = opts + return _u +} + func (_u *FileUpdate) sqlSave(ctx context.Context) (_node int, err error) { if err := _u.check(); err != nil { return _node, err @@ -511,6 +519,7 @@ func (_u *FileUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec.Edges.Add = append(_spec.Edges.Add, edge) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{file.Label} @@ -526,10 +535,11 @@ func (_u *FileUpdate) sqlSave(ctx context.Context) (_node int, err error) { // FileUpdateOne is the builder for updating a single File entity. type FileUpdateOne struct { config - fields []string - hooks []Hook - mutation *FileMutation - modifiers []func(*sql.UpdateBuilder) + fields []string + hooks []Hook + mutation *FileMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // SetSetID sets the "set_id" field. @@ -853,6 +863,13 @@ func (_u *FileUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *FileUp return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *FileUpdateOne) WithRetryOptions(opts ...any) *FileUpdateOne { + _u.retryConfig.Options = opts + return _u +} + func (_u *FileUpdateOne) sqlSave(ctx context.Context) (_node *File, err error) { if err := _u.check(); err != nil { return _node, err @@ -1037,6 +1054,7 @@ func (_u *FileUpdateOne) sqlSave(ctx context.Context) (_node *File, err error) { _spec.Edges.Add = append(_spec.Edges.Add, edge) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig _node = &File{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/entc/integration/ent/filetype_create.go b/entc/integration/ent/filetype_create.go index 8b7923bc37..04bc53ab60 100644 --- a/entc/integration/ent/filetype_create.go +++ b/entc/integration/ent/filetype_create.go @@ -21,9 +21,10 @@ import ( // FileTypeCreate is the builder for creating a FileType entity. type FileTypeCreate struct { config - mutation *FileTypeMutation - hooks []Hook - conflict []sql.ConflictOption + mutation *FileTypeMutation + hooks []Hook + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // SetName sets the "name" field. @@ -167,6 +168,7 @@ func (_c *FileTypeCreate) createSpec() (*FileType, *sqlgraph.CreateSpec) { _node = &FileType{config: _c.config} _spec = sqlgraph.NewCreateSpec(filetype.Table, sqlgraph.NewFieldSpec(filetype.FieldID, field.TypeInt)) ) + _spec.RetryConfig = _c.retryConfig _spec.OnConflict = _c.conflict if value, ok := _c.mutation.Name(); ok { _spec.SetField(filetype.FieldName, field.TypeString, value) @@ -199,6 +201,13 @@ func (_c *FileTypeCreate) createSpec() (*FileType, *sqlgraph.CreateSpec) { return _node, _spec } +// WithRetryOptions sets the retry options for the create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *FileTypeCreate) WithRetryOptions(opts ...any) *FileTypeCreate { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // @@ -402,9 +411,10 @@ func (u *FileTypeUpsertOne) IDX(ctx context.Context) int { // FileTypeCreateBulk is the builder for creating many FileType entities in bulk. type FileTypeCreateBulk struct { config - err error - builders []*FileTypeCreate - conflict []sql.ConflictOption + err error + builders []*FileTypeCreate + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // Save creates the FileType entities in the database. @@ -434,6 +444,7 @@ func (_c *FileTypeCreateBulk) Save(ctx context.Context) ([]*FileType, error) { _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.RetryConfig = _c.retryConfig 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 { @@ -489,6 +500,13 @@ func (_c *FileTypeCreateBulk) ExecX(ctx context.Context) { } } +// WithRetryOptions sets the retry options for the bulk create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *FileTypeCreateBulk) WithRetryOptions(opts ...any) *FileTypeCreateBulk { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // diff --git a/entc/integration/ent/filetype_delete.go b/entc/integration/ent/filetype_delete.go index cdc590de47..a95d2f4df1 100644 --- a/entc/integration/ent/filetype_delete.go +++ b/entc/integration/ent/filetype_delete.go @@ -19,8 +19,9 @@ import ( // FileTypeDelete is the builder for deleting a FileType entity. type FileTypeDelete struct { config - hooks []Hook - mutation *FileTypeMutation + hooks []Hook + mutation *FileTypeMutation + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the FileTypeDelete builder. @@ -45,6 +46,7 @@ func (_d *FileTypeDelete) ExecX(ctx context.Context) int { func (_d *FileTypeDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(filetype.Table, sqlgraph.NewFieldSpec(filetype.FieldID, field.TypeInt)) + _spec.RetryConfig = _d.retryConfig if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { @@ -60,6 +62,13 @@ func (_d *FileTypeDelete) sqlExec(ctx context.Context) (int, error) { return affected, err } +// WithRetryOptions sets the retry options for the delete operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_d *FileTypeDelete) WithRetryOptions(opts ...any) *FileTypeDelete { + _d.retryConfig.Options = opts + return _d +} + // FileTypeDeleteOne is the builder for deleting a single FileType entity. type FileTypeDeleteOne struct { _d *FileTypeDelete diff --git a/entc/integration/ent/filetype_query.go b/entc/integration/ent/filetype_query.go index f03514db3b..3823927bd2 100644 --- a/entc/integration/ent/filetype_query.go +++ b/entc/integration/ent/filetype_query.go @@ -32,6 +32,7 @@ type FileTypeQuery struct { withFiles *FileQuery modifiers []func(*sql.Selector) withNamedFiles map[string]*FileQuery + retryConfig sqlgraph.RetryConfig // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -395,6 +396,7 @@ func (_q *FileTypeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Fil if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig for i := range hooks { hooks[i](ctx, _spec) } @@ -468,6 +470,7 @@ func (_q *FileTypeQuery) sqlCount(ctx context.Context) (int, error) { if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig _spec.Node.Columns = _q.ctx.Fields if len(_q.ctx.Fields) > 0 { _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique @@ -596,6 +599,13 @@ func (_q *FileTypeQuery) WithNamedFiles(name string, opts ...func(*FileQuery)) * return _q } +// WithRetryOptions sets the retry options for the query operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_q *FileTypeQuery) WithRetryOptions(opts ...any) *FileTypeQuery { + _q.retryConfig.Options = opts + return _q +} + // FileTypeGroupBy is the group-by builder for FileType entities. type FileTypeGroupBy struct { selector diff --git a/entc/integration/ent/filetype_update.go b/entc/integration/ent/filetype_update.go index ef57d68545..10cf3c1996 100644 --- a/entc/integration/ent/filetype_update.go +++ b/entc/integration/ent/filetype_update.go @@ -22,9 +22,10 @@ import ( // FileTypeUpdate is the builder for updating FileType entities. type FileTypeUpdate struct { config - hooks []Hook - mutation *FileTypeMutation - modifiers []func(*sql.UpdateBuilder) + hooks []Hook + mutation *FileTypeMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the FileTypeUpdate builder. @@ -164,6 +165,13 @@ func (_u *FileTypeUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *FileT return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *FileTypeUpdate) WithRetryOptions(opts ...any) *FileTypeUpdate { + _u.retryConfig.Options = opts + return _u +} + func (_u *FileTypeUpdate) sqlSave(ctx context.Context) (_node int, err error) { if err := _u.check(); err != nil { return _node, err @@ -231,6 +239,7 @@ func (_u *FileTypeUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec.Edges.Add = append(_spec.Edges.Add, edge) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{filetype.Label} @@ -246,10 +255,11 @@ func (_u *FileTypeUpdate) sqlSave(ctx context.Context) (_node int, err error) { // FileTypeUpdateOne is the builder for updating a single FileType entity. type FileTypeUpdateOne struct { config - fields []string - hooks []Hook - mutation *FileTypeMutation - modifiers []func(*sql.UpdateBuilder) + fields []string + hooks []Hook + mutation *FileTypeMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // SetName sets the "name" field. @@ -396,6 +406,13 @@ func (_u *FileTypeUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *Fi return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *FileTypeUpdateOne) WithRetryOptions(opts ...any) *FileTypeUpdateOne { + _u.retryConfig.Options = opts + return _u +} + func (_u *FileTypeUpdateOne) sqlSave(ctx context.Context) (_node *FileType, err error) { if err := _u.check(); err != nil { return _node, err @@ -480,6 +497,7 @@ func (_u *FileTypeUpdateOne) sqlSave(ctx context.Context) (_node *FileType, err _spec.Edges.Add = append(_spec.Edges.Add, edge) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig _node = &FileType{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/entc/integration/ent/generate.go b/entc/integration/ent/generate.go index 98a2607f37..6f7e2ee331 100644 --- a/entc/integration/ent/generate.go +++ b/entc/integration/ent/generate.go @@ -4,4 +4,4 @@ package ent -//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate --feature entql,sql/modifier,sql/lock,sql/upsert,sql/execquery,namedges,bidiedges,sql/globalid --template ./template --header "// Copyright 2019-present Facebook Inc. All rights reserved.\n// This source code is licensed under the Apache 2.0 license found\n// in the LICENSE file in the root directory of this source tree.\n\n// Code generated by ent, DO NOT EDIT." ./schema +//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate --feature entql,sql/modifier,sql/lock,sql/upsert,sql/execquery,namedges,bidiedges,sql/globalid,sql/retryoptions --template ./template --header "// Copyright 2019-present Facebook Inc. All rights reserved.\n// This source code is licensed under the Apache 2.0 license found\n// in the LICENSE file in the root directory of this source tree.\n\n// Code generated by ent, DO NOT EDIT." ./schema diff --git a/entc/integration/ent/goods_create.go b/entc/integration/ent/goods_create.go index 5c13ecad9c..ce57d59b77 100644 --- a/entc/integration/ent/goods_create.go +++ b/entc/integration/ent/goods_create.go @@ -20,9 +20,10 @@ import ( // GoodsCreate is the builder for creating a Goods entity. type GoodsCreate struct { config - mutation *GoodsMutation - hooks []Hook - conflict []sql.ConflictOption + mutation *GoodsMutation + hooks []Hook + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // Mutation returns the GoodsMutation object of the builder. @@ -85,10 +86,18 @@ func (_c *GoodsCreate) createSpec() (*Goods, *sqlgraph.CreateSpec) { _node = &Goods{config: _c.config} _spec = sqlgraph.NewCreateSpec(goods.Table, sqlgraph.NewFieldSpec(goods.FieldID, field.TypeInt)) ) + _spec.RetryConfig = _c.retryConfig _spec.OnConflict = _c.conflict return _node, _spec } +// WithRetryOptions sets the retry options for the create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *GoodsCreate) WithRetryOptions(opts ...any) *GoodsCreate { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // @@ -208,9 +217,10 @@ func (u *GoodsUpsertOne) IDX(ctx context.Context) int { // GoodsCreateBulk is the builder for creating many Goods entities in bulk. type GoodsCreateBulk struct { config - err error - builders []*GoodsCreate - conflict []sql.ConflictOption + err error + builders []*GoodsCreate + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // Save creates the Goods entities in the database. @@ -239,6 +249,7 @@ func (_c *GoodsCreateBulk) Save(ctx context.Context) ([]*Goods, error) { _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.RetryConfig = _c.retryConfig 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 { @@ -294,6 +305,13 @@ func (_c *GoodsCreateBulk) ExecX(ctx context.Context) { } } +// WithRetryOptions sets the retry options for the bulk create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *GoodsCreateBulk) WithRetryOptions(opts ...any) *GoodsCreateBulk { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // diff --git a/entc/integration/ent/goods_delete.go b/entc/integration/ent/goods_delete.go index cc05623319..f9e49134df 100644 --- a/entc/integration/ent/goods_delete.go +++ b/entc/integration/ent/goods_delete.go @@ -19,8 +19,9 @@ import ( // GoodsDelete is the builder for deleting a Goods entity. type GoodsDelete struct { config - hooks []Hook - mutation *GoodsMutation + hooks []Hook + mutation *GoodsMutation + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the GoodsDelete builder. @@ -45,6 +46,7 @@ func (_d *GoodsDelete) ExecX(ctx context.Context) int { func (_d *GoodsDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(goods.Table, sqlgraph.NewFieldSpec(goods.FieldID, field.TypeInt)) + _spec.RetryConfig = _d.retryConfig if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { @@ -60,6 +62,13 @@ func (_d *GoodsDelete) sqlExec(ctx context.Context) (int, error) { return affected, err } +// WithRetryOptions sets the retry options for the delete operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_d *GoodsDelete) WithRetryOptions(opts ...any) *GoodsDelete { + _d.retryConfig.Options = opts + return _d +} + // GoodsDeleteOne is the builder for deleting a single Goods entity. type GoodsDeleteOne struct { _d *GoodsDelete diff --git a/entc/integration/ent/goods_query.go b/entc/integration/ent/goods_query.go index 87a19f788a..c28b06688d 100644 --- a/entc/integration/ent/goods_query.go +++ b/entc/integration/ent/goods_query.go @@ -23,11 +23,12 @@ import ( // GoodsQuery is the builder for querying Goods entities. type GoodsQuery struct { config - ctx *QueryContext - order []goods.OrderOption - inters []Interceptor - predicates []predicate.Goods - modifiers []func(*sql.Selector) + ctx *QueryContext + order []goods.OrderOption + inters []Interceptor + predicates []predicate.Goods + modifiers []func(*sql.Selector) + retryConfig sqlgraph.RetryConfig // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -331,6 +332,7 @@ func (_q *GoodsQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Goods, if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig for i := range hooks { hooks[i](ctx, _spec) } @@ -348,6 +350,7 @@ func (_q *GoodsQuery) sqlCount(ctx context.Context) (int, error) { if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig _spec.Node.Columns = _q.ctx.Fields if len(_q.ctx.Fields) > 0 { _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique @@ -462,6 +465,13 @@ func (_q *GoodsQuery) Modify(modifiers ...func(s *sql.Selector)) *GoodsSelect { return _q.Select() } +// WithRetryOptions sets the retry options for the query operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_q *GoodsQuery) WithRetryOptions(opts ...any) *GoodsQuery { + _q.retryConfig.Options = opts + return _q +} + // GoodsGroupBy is the group-by builder for Goods entities. type GoodsGroupBy struct { selector diff --git a/entc/integration/ent/goods_update.go b/entc/integration/ent/goods_update.go index e0105fddd3..37732b6254 100644 --- a/entc/integration/ent/goods_update.go +++ b/entc/integration/ent/goods_update.go @@ -21,9 +21,10 @@ import ( // GoodsUpdate is the builder for updating Goods entities. type GoodsUpdate struct { config - hooks []Hook - mutation *GoodsMutation - modifiers []func(*sql.UpdateBuilder) + hooks []Hook + mutation *GoodsMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the GoodsUpdate builder. @@ -70,6 +71,13 @@ func (_u *GoodsUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *GoodsUpd return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *GoodsUpdate) WithRetryOptions(opts ...any) *GoodsUpdate { + _u.retryConfig.Options = opts + return _u +} + func (_u *GoodsUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec := sqlgraph.NewUpdateSpec(goods.Table, goods.Columns, sqlgraph.NewFieldSpec(goods.FieldID, field.TypeInt)) if ps := _u.mutation.predicates; len(ps) > 0 { @@ -80,6 +88,7 @@ func (_u *GoodsUpdate) sqlSave(ctx context.Context) (_node int, err error) { } } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{goods.Label} @@ -95,10 +104,11 @@ func (_u *GoodsUpdate) sqlSave(ctx context.Context) (_node int, err error) { // GoodsUpdateOne is the builder for updating a single Goods entity. type GoodsUpdateOne struct { config - fields []string - hooks []Hook - mutation *GoodsMutation - modifiers []func(*sql.UpdateBuilder) + fields []string + hooks []Hook + mutation *GoodsMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // Mutation returns the GoodsMutation object of the builder. @@ -152,6 +162,13 @@ func (_u *GoodsUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *Goods return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *GoodsUpdateOne) WithRetryOptions(opts ...any) *GoodsUpdateOne { + _u.retryConfig.Options = opts + return _u +} + func (_u *GoodsUpdateOne) sqlSave(ctx context.Context) (_node *Goods, err error) { _spec := sqlgraph.NewUpdateSpec(goods.Table, goods.Columns, sqlgraph.NewFieldSpec(goods.FieldID, field.TypeInt)) id, ok := _u.mutation.ID() @@ -179,6 +196,7 @@ func (_u *GoodsUpdateOne) sqlSave(ctx context.Context) (_node *Goods, err error) } } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig _node = &Goods{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/entc/integration/ent/group_create.go b/entc/integration/ent/group_create.go index 5b5506a68c..8d2be28c49 100644 --- a/entc/integration/ent/group_create.go +++ b/entc/integration/ent/group_create.go @@ -24,9 +24,10 @@ import ( // GroupCreate is the builder for creating a Group entity. type GroupCreate struct { config - mutation *GroupMutation - hooks []Hook - conflict []sql.ConflictOption + mutation *GroupMutation + hooks []Hook + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // SetActive sets the "active" field. @@ -239,6 +240,7 @@ func (_c *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) { _node = &Group{config: _c.config} _spec = sqlgraph.NewCreateSpec(group.Table, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt)) ) + _spec.RetryConfig = _c.retryConfig _spec.OnConflict = _c.conflict if value, ok := _c.mutation.Active(); ok { _spec.SetField(group.FieldActive, field.TypeBool, value) @@ -328,6 +330,13 @@ func (_c *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) { return _node, _spec } +// WithRetryOptions sets the retry options for the create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *GroupCreate) WithRetryOptions(opts ...any) *GroupCreate { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // @@ -622,9 +631,10 @@ func (u *GroupUpsertOne) IDX(ctx context.Context) int { // GroupCreateBulk is the builder for creating many Group entities in bulk. type GroupCreateBulk struct { config - err error - builders []*GroupCreate - conflict []sql.ConflictOption + err error + builders []*GroupCreate + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // Save creates the Group entities in the database. @@ -654,6 +664,7 @@ func (_c *GroupCreateBulk) Save(ctx context.Context) ([]*Group, error) { _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.RetryConfig = _c.retryConfig 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 { @@ -709,6 +720,13 @@ func (_c *GroupCreateBulk) ExecX(ctx context.Context) { } } +// WithRetryOptions sets the retry options for the bulk create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *GroupCreateBulk) WithRetryOptions(opts ...any) *GroupCreateBulk { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // diff --git a/entc/integration/ent/group_delete.go b/entc/integration/ent/group_delete.go index c1555ee064..353ed4e359 100644 --- a/entc/integration/ent/group_delete.go +++ b/entc/integration/ent/group_delete.go @@ -19,8 +19,9 @@ import ( // GroupDelete is the builder for deleting a Group entity. type GroupDelete struct { config - hooks []Hook - mutation *GroupMutation + hooks []Hook + mutation *GroupMutation + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the GroupDelete builder. @@ -45,6 +46,7 @@ func (_d *GroupDelete) ExecX(ctx context.Context) int { func (_d *GroupDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(group.Table, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt)) + _spec.RetryConfig = _d.retryConfig if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { @@ -60,6 +62,13 @@ func (_d *GroupDelete) sqlExec(ctx context.Context) (int, error) { return affected, err } +// WithRetryOptions sets the retry options for the delete operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_d *GroupDelete) WithRetryOptions(opts ...any) *GroupDelete { + _d.retryConfig.Options = opts + return _d +} + // GroupDeleteOne is the builder for deleting a single Group entity. type GroupDeleteOne struct { _d *GroupDelete diff --git a/entc/integration/ent/group_query.go b/entc/integration/ent/group_query.go index 295755d48a..99c333cd9c 100644 --- a/entc/integration/ent/group_query.go +++ b/entc/integration/ent/group_query.go @@ -40,6 +40,7 @@ type GroupQuery struct { withNamedFiles map[string]*FileQuery withNamedBlocked map[string]*UserQuery withNamedUsers map[string]*UserQuery + retryConfig sqlgraph.RetryConfig // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -515,6 +516,7 @@ func (_q *GroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Group, if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig for i := range hooks { hooks[i](ctx, _spec) } @@ -736,6 +738,7 @@ func (_q *GroupQuery) sqlCount(ctx context.Context) (int, error) { if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig _spec.Node.Columns = _q.ctx.Fields if len(_q.ctx.Fields) > 0 { _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique @@ -892,6 +895,13 @@ func (_q *GroupQuery) WithNamedUsers(name string, opts ...func(*UserQuery)) *Gro return _q } +// WithRetryOptions sets the retry options for the query operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_q *GroupQuery) WithRetryOptions(opts ...any) *GroupQuery { + _q.retryConfig.Options = opts + return _q +} + // GroupGroupBy is the group-by builder for Group entities. type GroupGroupBy struct { selector diff --git a/entc/integration/ent/group_update.go b/entc/integration/ent/group_update.go index f3c19a8321..1fb546a0c2 100644 --- a/entc/integration/ent/group_update.go +++ b/entc/integration/ent/group_update.go @@ -25,9 +25,10 @@ import ( // GroupUpdate is the builder for updating Group entities. type GroupUpdate struct { config - hooks []Hook - mutation *GroupMutation - modifiers []func(*sql.UpdateBuilder) + hooks []Hook + mutation *GroupMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the GroupUpdate builder. @@ -311,6 +312,13 @@ func (_u *GroupUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *GroupUpd return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *GroupUpdate) WithRetryOptions(opts ...any) *GroupUpdate { + _u.retryConfig.Options = opts + return _u +} + func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) { if err := _u.check(); err != nil { return _node, err @@ -512,6 +520,7 @@ func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec.Edges.Add = append(_spec.Edges.Add, edge) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{group.Label} @@ -527,10 +536,11 @@ func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) { // GroupUpdateOne is the builder for updating a single Group entity. type GroupUpdateOne struct { config - fields []string - hooks []Hook - mutation *GroupMutation - modifiers []func(*sql.UpdateBuilder) + fields []string + hooks []Hook + mutation *GroupMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // SetActive sets the "active" field. @@ -821,6 +831,13 @@ func (_u *GroupUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *Group return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *GroupUpdateOne) WithRetryOptions(opts ...any) *GroupUpdateOne { + _u.retryConfig.Options = opts + return _u +} + func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error) { if err := _u.check(); err != nil { return _node, err @@ -1039,6 +1056,7 @@ func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error) _spec.Edges.Add = append(_spec.Edges.Add, edge) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig _node = &Group{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/entc/integration/ent/groupinfo_create.go b/entc/integration/ent/groupinfo_create.go index ede6d1706a..8162668e19 100644 --- a/entc/integration/ent/groupinfo_create.go +++ b/entc/integration/ent/groupinfo_create.go @@ -21,9 +21,10 @@ import ( // GroupInfoCreate is the builder for creating a GroupInfo entity. type GroupInfoCreate struct { config - mutation *GroupInfoMutation - hooks []Hook - conflict []sql.ConflictOption + mutation *GroupInfoMutation + hooks []Hook + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // SetDesc sets the "desc" field. @@ -136,6 +137,7 @@ func (_c *GroupInfoCreate) createSpec() (*GroupInfo, *sqlgraph.CreateSpec) { _node = &GroupInfo{config: _c.config} _spec = sqlgraph.NewCreateSpec(groupinfo.Table, sqlgraph.NewFieldSpec(groupinfo.FieldID, field.TypeInt)) ) + _spec.RetryConfig = _c.retryConfig _spec.OnConflict = _c.conflict if value, ok := _c.mutation.Desc(); ok { _spec.SetField(groupinfo.FieldDesc, field.TypeString, value) @@ -164,6 +166,13 @@ func (_c *GroupInfoCreate) createSpec() (*GroupInfo, *sqlgraph.CreateSpec) { return _node, _spec } +// WithRetryOptions sets the retry options for the create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *GroupInfoCreate) WithRetryOptions(opts ...any) *GroupInfoCreate { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // @@ -354,9 +363,10 @@ func (u *GroupInfoUpsertOne) IDX(ctx context.Context) int { // GroupInfoCreateBulk is the builder for creating many GroupInfo entities in bulk. type GroupInfoCreateBulk struct { config - err error - builders []*GroupInfoCreate - conflict []sql.ConflictOption + err error + builders []*GroupInfoCreate + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // Save creates the GroupInfo entities in the database. @@ -386,6 +396,7 @@ func (_c *GroupInfoCreateBulk) Save(ctx context.Context) ([]*GroupInfo, error) { _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.RetryConfig = _c.retryConfig 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 { @@ -441,6 +452,13 @@ func (_c *GroupInfoCreateBulk) ExecX(ctx context.Context) { } } +// WithRetryOptions sets the retry options for the bulk create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *GroupInfoCreateBulk) WithRetryOptions(opts ...any) *GroupInfoCreateBulk { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // diff --git a/entc/integration/ent/groupinfo_delete.go b/entc/integration/ent/groupinfo_delete.go index ee218c89ad..9be9235d12 100644 --- a/entc/integration/ent/groupinfo_delete.go +++ b/entc/integration/ent/groupinfo_delete.go @@ -19,8 +19,9 @@ import ( // GroupInfoDelete is the builder for deleting a GroupInfo entity. type GroupInfoDelete struct { config - hooks []Hook - mutation *GroupInfoMutation + hooks []Hook + mutation *GroupInfoMutation + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the GroupInfoDelete builder. @@ -45,6 +46,7 @@ func (_d *GroupInfoDelete) ExecX(ctx context.Context) int { func (_d *GroupInfoDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(groupinfo.Table, sqlgraph.NewFieldSpec(groupinfo.FieldID, field.TypeInt)) + _spec.RetryConfig = _d.retryConfig if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { @@ -60,6 +62,13 @@ func (_d *GroupInfoDelete) sqlExec(ctx context.Context) (int, error) { return affected, err } +// WithRetryOptions sets the retry options for the delete operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_d *GroupInfoDelete) WithRetryOptions(opts ...any) *GroupInfoDelete { + _d.retryConfig.Options = opts + return _d +} + // GroupInfoDeleteOne is the builder for deleting a single GroupInfo entity. type GroupInfoDeleteOne struct { _d *GroupInfoDelete diff --git a/entc/integration/ent/groupinfo_query.go b/entc/integration/ent/groupinfo_query.go index 67c4fc0ffa..16bc6bc9b3 100644 --- a/entc/integration/ent/groupinfo_query.go +++ b/entc/integration/ent/groupinfo_query.go @@ -32,6 +32,7 @@ type GroupInfoQuery struct { withGroups *GroupQuery modifiers []func(*sql.Selector) withNamedGroups map[string]*GroupQuery + retryConfig sqlgraph.RetryConfig // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -395,6 +396,7 @@ func (_q *GroupInfoQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Gr if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig for i := range hooks { hooks[i](ctx, _spec) } @@ -468,6 +470,7 @@ func (_q *GroupInfoQuery) sqlCount(ctx context.Context) (int, error) { if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig _spec.Node.Columns = _q.ctx.Fields if len(_q.ctx.Fields) > 0 { _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique @@ -596,6 +599,13 @@ func (_q *GroupInfoQuery) WithNamedGroups(name string, opts ...func(*GroupQuery) return _q } +// WithRetryOptions sets the retry options for the query operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_q *GroupInfoQuery) WithRetryOptions(opts ...any) *GroupInfoQuery { + _q.retryConfig.Options = opts + return _q +} + // GroupInfoGroupBy is the group-by builder for GroupInfo entities. type GroupInfoGroupBy struct { selector diff --git a/entc/integration/ent/groupinfo_update.go b/entc/integration/ent/groupinfo_update.go index 261d0e00ee..d464deded5 100644 --- a/entc/integration/ent/groupinfo_update.go +++ b/entc/integration/ent/groupinfo_update.go @@ -22,9 +22,10 @@ import ( // GroupInfoUpdate is the builder for updating GroupInfo entities. type GroupInfoUpdate struct { config - hooks []Hook - mutation *GroupInfoMutation - modifiers []func(*sql.UpdateBuilder) + hooks []Hook + mutation *GroupInfoMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the GroupInfoUpdate builder. @@ -142,6 +143,13 @@ func (_u *GroupInfoUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *Grou return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *GroupInfoUpdate) WithRetryOptions(opts ...any) *GroupInfoUpdate { + _u.retryConfig.Options = opts + return _u +} + func (_u *GroupInfoUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec := sqlgraph.NewUpdateSpec(groupinfo.Table, groupinfo.Columns, sqlgraph.NewFieldSpec(groupinfo.FieldID, field.TypeInt)) if ps := _u.mutation.predicates; len(ps) > 0 { @@ -206,6 +214,7 @@ func (_u *GroupInfoUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec.Edges.Add = append(_spec.Edges.Add, edge) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{groupinfo.Label} @@ -221,10 +230,11 @@ func (_u *GroupInfoUpdate) sqlSave(ctx context.Context) (_node int, err error) { // GroupInfoUpdateOne is the builder for updating a single GroupInfo entity. type GroupInfoUpdateOne struct { config - fields []string - hooks []Hook - mutation *GroupInfoMutation - modifiers []func(*sql.UpdateBuilder) + fields []string + hooks []Hook + mutation *GroupInfoMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // SetDesc sets the "desc" field. @@ -349,6 +359,13 @@ func (_u *GroupInfoUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *G return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *GroupInfoUpdateOne) WithRetryOptions(opts ...any) *GroupInfoUpdateOne { + _u.retryConfig.Options = opts + return _u +} + func (_u *GroupInfoUpdateOne) sqlSave(ctx context.Context) (_node *GroupInfo, err error) { _spec := sqlgraph.NewUpdateSpec(groupinfo.Table, groupinfo.Columns, sqlgraph.NewFieldSpec(groupinfo.FieldID, field.TypeInt)) id, ok := _u.mutation.ID() @@ -430,6 +447,7 @@ func (_u *GroupInfoUpdateOne) sqlSave(ctx context.Context) (_node *GroupInfo, er _spec.Edges.Add = append(_spec.Edges.Add, edge) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig _node = &GroupInfo{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/entc/integration/ent/item_create.go b/entc/integration/ent/item_create.go index 07ab7e886f..b5a7dcd441 100644 --- a/entc/integration/ent/item_create.go +++ b/entc/integration/ent/item_create.go @@ -21,9 +21,10 @@ import ( // ItemCreate is the builder for creating a Item entity. type ItemCreate struct { config - mutation *ItemMutation - hooks []Hook - conflict []sql.ConflictOption + mutation *ItemMutation + hooks []Hook + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // SetText sets the "text" field. @@ -138,6 +139,7 @@ func (_c *ItemCreate) createSpec() (*Item, *sqlgraph.CreateSpec) { _node = &Item{config: _c.config} _spec = sqlgraph.NewCreateSpec(item.Table, sqlgraph.NewFieldSpec(item.FieldID, field.TypeString)) ) + _spec.RetryConfig = _c.retryConfig _spec.OnConflict = _c.conflict if id, ok := _c.mutation.ID(); ok { _node.ID = id @@ -150,6 +152,13 @@ func (_c *ItemCreate) createSpec() (*Item, *sqlgraph.CreateSpec) { return _node, _spec } +// WithRetryOptions sets the retry options for the create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *ItemCreate) WithRetryOptions(opts ...any) *ItemCreate { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // @@ -327,9 +336,10 @@ func (u *ItemUpsertOne) IDX(ctx context.Context) string { // ItemCreateBulk is the builder for creating many Item entities in bulk. type ItemCreateBulk struct { config - err error - builders []*ItemCreate - conflict []sql.ConflictOption + err error + builders []*ItemCreate + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // Save creates the Item entities in the database. @@ -359,6 +369,7 @@ func (_c *ItemCreateBulk) Save(ctx context.Context) ([]*Item, error) { _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.RetryConfig = _c.retryConfig 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 { @@ -410,6 +421,13 @@ func (_c *ItemCreateBulk) ExecX(ctx context.Context) { } } +// WithRetryOptions sets the retry options for the bulk create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *ItemCreateBulk) WithRetryOptions(opts ...any) *ItemCreateBulk { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // diff --git a/entc/integration/ent/item_delete.go b/entc/integration/ent/item_delete.go index a0107e3de6..2fc36cc402 100644 --- a/entc/integration/ent/item_delete.go +++ b/entc/integration/ent/item_delete.go @@ -19,8 +19,9 @@ import ( // ItemDelete is the builder for deleting a Item entity. type ItemDelete struct { config - hooks []Hook - mutation *ItemMutation + hooks []Hook + mutation *ItemMutation + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the ItemDelete builder. @@ -45,6 +46,7 @@ func (_d *ItemDelete) ExecX(ctx context.Context) int { func (_d *ItemDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(item.Table, sqlgraph.NewFieldSpec(item.FieldID, field.TypeString)) + _spec.RetryConfig = _d.retryConfig if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { @@ -60,6 +62,13 @@ func (_d *ItemDelete) sqlExec(ctx context.Context) (int, error) { return affected, err } +// WithRetryOptions sets the retry options for the delete operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_d *ItemDelete) WithRetryOptions(opts ...any) *ItemDelete { + _d.retryConfig.Options = opts + return _d +} + // ItemDeleteOne is the builder for deleting a single Item entity. type ItemDeleteOne struct { _d *ItemDelete diff --git a/entc/integration/ent/item_query.go b/entc/integration/ent/item_query.go index 03672184f8..55761a6193 100644 --- a/entc/integration/ent/item_query.go +++ b/entc/integration/ent/item_query.go @@ -23,11 +23,12 @@ import ( // 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) + ctx *QueryContext + order []item.OrderOption + inters []Interceptor + predicates []predicate.Item + modifiers []func(*sql.Selector) + retryConfig sqlgraph.RetryConfig // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -353,6 +354,7 @@ func (_q *ItemQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Item, e if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig for i := range hooks { hooks[i](ctx, _spec) } @@ -370,6 +372,7 @@ func (_q *ItemQuery) sqlCount(ctx context.Context) (int, error) { if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig _spec.Node.Columns = _q.ctx.Fields if len(_q.ctx.Fields) > 0 { _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique @@ -484,6 +487,13 @@ func (_q *ItemQuery) Modify(modifiers ...func(s *sql.Selector)) *ItemSelect { return _q.Select() } +// WithRetryOptions sets the retry options for the query operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_q *ItemQuery) WithRetryOptions(opts ...any) *ItemQuery { + _q.retryConfig.Options = opts + return _q +} + // ItemGroupBy is the group-by builder for Item entities. type ItemGroupBy struct { selector diff --git a/entc/integration/ent/item_update.go b/entc/integration/ent/item_update.go index dd09136087..80c3fcafb0 100644 --- a/entc/integration/ent/item_update.go +++ b/entc/integration/ent/item_update.go @@ -21,9 +21,10 @@ import ( // ItemUpdate is the builder for updating Item entities. type ItemUpdate struct { config - hooks []Hook - mutation *ItemMutation - modifiers []func(*sql.UpdateBuilder) + hooks []Hook + mutation *ItemMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the ItemUpdate builder. @@ -100,6 +101,13 @@ func (_u *ItemUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *ItemUpdat return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *ItemUpdate) WithRetryOptions(opts ...any) *ItemUpdate { + _u.retryConfig.Options = opts + return _u +} + func (_u *ItemUpdate) sqlSave(ctx context.Context) (_node int, err error) { if err := _u.check(); err != nil { return _node, err @@ -119,6 +127,7 @@ func (_u *ItemUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec.ClearField(item.FieldText, field.TypeString) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{item.Label} @@ -134,10 +143,11 @@ func (_u *ItemUpdate) sqlSave(ctx context.Context) (_node int, err error) { // ItemUpdateOne is the builder for updating a single Item entity. type ItemUpdateOne struct { config - fields []string - hooks []Hook - mutation *ItemMutation - modifiers []func(*sql.UpdateBuilder) + fields []string + hooks []Hook + mutation *ItemMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // SetText sets the "text" field. @@ -221,6 +231,13 @@ func (_u *ItemUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *ItemUp return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *ItemUpdateOne) WithRetryOptions(opts ...any) *ItemUpdateOne { + _u.retryConfig.Options = opts + return _u +} + func (_u *ItemUpdateOne) sqlSave(ctx context.Context) (_node *Item, err error) { if err := _u.check(); err != nil { return _node, err @@ -257,6 +274,7 @@ func (_u *ItemUpdateOne) sqlSave(ctx context.Context) (_node *Item, err error) { _spec.ClearField(item.FieldText, field.TypeString) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig _node = &Item{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/entc/integration/ent/license_create.go b/entc/integration/ent/license_create.go index be85871465..82a8a5f50b 100644 --- a/entc/integration/ent/license_create.go +++ b/entc/integration/ent/license_create.go @@ -21,9 +21,10 @@ import ( // LicenseCreate is the builder for creating a License entity. type LicenseCreate struct { config - mutation *LicenseMutation - hooks []Hook - conflict []sql.ConflictOption + mutation *LicenseMutation + hooks []Hook + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // SetCreateTime sets the "create_time" field. @@ -141,6 +142,7 @@ func (_c *LicenseCreate) createSpec() (*License, *sqlgraph.CreateSpec) { _node = &License{config: _c.config} _spec = sqlgraph.NewCreateSpec(license.Table, sqlgraph.NewFieldSpec(license.FieldID, field.TypeInt)) ) + _spec.RetryConfig = _c.retryConfig _spec.OnConflict = _c.conflict if id, ok := _c.mutation.ID(); ok { _node.ID = id @@ -157,6 +159,13 @@ func (_c *LicenseCreate) createSpec() (*License, *sqlgraph.CreateSpec) { return _node, _spec } +// WithRetryOptions sets the retry options for the create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *LicenseCreate) WithRetryOptions(opts ...any) *LicenseCreate { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // @@ -319,9 +328,10 @@ func (u *LicenseUpsertOne) IDX(ctx context.Context) int { // LicenseCreateBulk is the builder for creating many License entities in bulk. type LicenseCreateBulk struct { config - err error - builders []*LicenseCreate - conflict []sql.ConflictOption + err error + builders []*LicenseCreate + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // Save creates the License entities in the database. @@ -351,6 +361,7 @@ func (_c *LicenseCreateBulk) Save(ctx context.Context) ([]*License, error) { _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.RetryConfig = _c.retryConfig 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 { @@ -406,6 +417,13 @@ func (_c *LicenseCreateBulk) ExecX(ctx context.Context) { } } +// WithRetryOptions sets the retry options for the bulk create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *LicenseCreateBulk) WithRetryOptions(opts ...any) *LicenseCreateBulk { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // diff --git a/entc/integration/ent/license_delete.go b/entc/integration/ent/license_delete.go index 9e35225d09..deb737343e 100644 --- a/entc/integration/ent/license_delete.go +++ b/entc/integration/ent/license_delete.go @@ -19,8 +19,9 @@ import ( // LicenseDelete is the builder for deleting a License entity. type LicenseDelete struct { config - hooks []Hook - mutation *LicenseMutation + hooks []Hook + mutation *LicenseMutation + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the LicenseDelete builder. @@ -45,6 +46,7 @@ func (_d *LicenseDelete) ExecX(ctx context.Context) int { func (_d *LicenseDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(license.Table, sqlgraph.NewFieldSpec(license.FieldID, field.TypeInt)) + _spec.RetryConfig = _d.retryConfig if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { @@ -60,6 +62,13 @@ func (_d *LicenseDelete) sqlExec(ctx context.Context) (int, error) { return affected, err } +// WithRetryOptions sets the retry options for the delete operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_d *LicenseDelete) WithRetryOptions(opts ...any) *LicenseDelete { + _d.retryConfig.Options = opts + return _d +} + // LicenseDeleteOne is the builder for deleting a single License entity. type LicenseDeleteOne struct { _d *LicenseDelete diff --git a/entc/integration/ent/license_query.go b/entc/integration/ent/license_query.go index 60c538a432..b6488048e7 100644 --- a/entc/integration/ent/license_query.go +++ b/entc/integration/ent/license_query.go @@ -23,11 +23,12 @@ import ( // LicenseQuery is the builder for querying License entities. type LicenseQuery struct { config - ctx *QueryContext - order []license.OrderOption - inters []Interceptor - predicates []predicate.License - modifiers []func(*sql.Selector) + ctx *QueryContext + order []license.OrderOption + inters []Interceptor + predicates []predicate.License + modifiers []func(*sql.Selector) + retryConfig sqlgraph.RetryConfig // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -353,6 +354,7 @@ func (_q *LicenseQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Lice if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig for i := range hooks { hooks[i](ctx, _spec) } @@ -370,6 +372,7 @@ func (_q *LicenseQuery) sqlCount(ctx context.Context) (int, error) { if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig _spec.Node.Columns = _q.ctx.Fields if len(_q.ctx.Fields) > 0 { _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique @@ -484,6 +487,13 @@ func (_q *LicenseQuery) Modify(modifiers ...func(s *sql.Selector)) *LicenseSelec return _q.Select() } +// WithRetryOptions sets the retry options for the query operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_q *LicenseQuery) WithRetryOptions(opts ...any) *LicenseQuery { + _q.retryConfig.Options = opts + return _q +} + // LicenseGroupBy is the group-by builder for License entities. type LicenseGroupBy struct { selector diff --git a/entc/integration/ent/license_update.go b/entc/integration/ent/license_update.go index a945974280..85551abd7b 100644 --- a/entc/integration/ent/license_update.go +++ b/entc/integration/ent/license_update.go @@ -22,9 +22,10 @@ import ( // LicenseUpdate is the builder for updating License entities. type LicenseUpdate struct { config - hooks []Hook - mutation *LicenseMutation - modifiers []func(*sql.UpdateBuilder) + hooks []Hook + mutation *LicenseMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the LicenseUpdate builder. @@ -86,6 +87,13 @@ func (_u *LicenseUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *Licens return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *LicenseUpdate) WithRetryOptions(opts ...any) *LicenseUpdate { + _u.retryConfig.Options = opts + return _u +} + func (_u *LicenseUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec := sqlgraph.NewUpdateSpec(license.Table, license.Columns, sqlgraph.NewFieldSpec(license.FieldID, field.TypeInt)) if ps := _u.mutation.predicates; len(ps) > 0 { @@ -99,6 +107,7 @@ func (_u *LicenseUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec.SetField(license.FieldUpdateTime, field.TypeTime, value) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{license.Label} @@ -114,10 +123,11 @@ func (_u *LicenseUpdate) sqlSave(ctx context.Context) (_node int, err error) { // LicenseUpdateOne is the builder for updating a single License entity. type LicenseUpdateOne struct { config - fields []string - hooks []Hook - mutation *LicenseMutation - modifiers []func(*sql.UpdateBuilder) + fields []string + hooks []Hook + mutation *LicenseMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // SetUpdateTime sets the "update_time" field. @@ -186,6 +196,13 @@ func (_u *LicenseUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *Lic return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *LicenseUpdateOne) WithRetryOptions(opts ...any) *LicenseUpdateOne { + _u.retryConfig.Options = opts + return _u +} + func (_u *LicenseUpdateOne) sqlSave(ctx context.Context) (_node *License, err error) { _spec := sqlgraph.NewUpdateSpec(license.Table, license.Columns, sqlgraph.NewFieldSpec(license.FieldID, field.TypeInt)) id, ok := _u.mutation.ID() @@ -216,6 +233,7 @@ func (_u *LicenseUpdateOne) sqlSave(ctx context.Context) (_node *License, err er _spec.SetField(license.FieldUpdateTime, field.TypeTime, value) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig _node = &License{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/entc/integration/ent/node_create.go b/entc/integration/ent/node_create.go index e1e912644f..cd1d4f23b4 100644 --- a/entc/integration/ent/node_create.go +++ b/entc/integration/ent/node_create.go @@ -21,9 +21,10 @@ import ( // NodeCreate is the builder for creating a Node entity. type NodeCreate struct { config - mutation *NodeMutation - hooks []Hook - conflict []sql.ConflictOption + mutation *NodeMutation + hooks []Hook + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // SetValue sets the "value" field. @@ -152,6 +153,7 @@ func (_c *NodeCreate) createSpec() (*Node, *sqlgraph.CreateSpec) { _node = &Node{config: _c.config} _spec = sqlgraph.NewCreateSpec(node.Table, sqlgraph.NewFieldSpec(node.FieldID, field.TypeInt)) ) + _spec.RetryConfig = _c.retryConfig _spec.OnConflict = _c.conflict if value, ok := _c.mutation.Value(); ok { _spec.SetField(node.FieldValue, field.TypeInt, value) @@ -197,6 +199,13 @@ func (_c *NodeCreate) createSpec() (*Node, *sqlgraph.CreateSpec) { return _node, _spec } +// WithRetryOptions sets the retry options for the create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *NodeCreate) WithRetryOptions(opts ...any) *NodeCreate { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // @@ -413,9 +422,10 @@ func (u *NodeUpsertOne) IDX(ctx context.Context) int { // NodeCreateBulk is the builder for creating many Node entities in bulk. type NodeCreateBulk struct { config - err error - builders []*NodeCreate - conflict []sql.ConflictOption + err error + builders []*NodeCreate + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // Save creates the Node entities in the database. @@ -444,6 +454,7 @@ func (_c *NodeCreateBulk) Save(ctx context.Context) ([]*Node, error) { _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.RetryConfig = _c.retryConfig 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 { @@ -499,6 +510,13 @@ func (_c *NodeCreateBulk) ExecX(ctx context.Context) { } } +// WithRetryOptions sets the retry options for the bulk create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *NodeCreateBulk) WithRetryOptions(opts ...any) *NodeCreateBulk { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // diff --git a/entc/integration/ent/node_delete.go b/entc/integration/ent/node_delete.go index e456e5620a..dee9b0ba35 100644 --- a/entc/integration/ent/node_delete.go +++ b/entc/integration/ent/node_delete.go @@ -19,8 +19,9 @@ import ( // NodeDelete is the builder for deleting a Node entity. type NodeDelete struct { config - hooks []Hook - mutation *NodeMutation + hooks []Hook + mutation *NodeMutation + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the NodeDelete builder. @@ -45,6 +46,7 @@ func (_d *NodeDelete) ExecX(ctx context.Context) int { func (_d *NodeDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(node.Table, sqlgraph.NewFieldSpec(node.FieldID, field.TypeInt)) + _spec.RetryConfig = _d.retryConfig if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { @@ -60,6 +62,13 @@ func (_d *NodeDelete) sqlExec(ctx context.Context) (int, error) { return affected, err } +// WithRetryOptions sets the retry options for the delete operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_d *NodeDelete) WithRetryOptions(opts ...any) *NodeDelete { + _d.retryConfig.Options = opts + return _d +} + // NodeDeleteOne is the builder for deleting a single Node entity. type NodeDeleteOne struct { _d *NodeDelete diff --git a/entc/integration/ent/node_query.go b/entc/integration/ent/node_query.go index 19b6f8922d..c39f0b82a2 100644 --- a/entc/integration/ent/node_query.go +++ b/entc/integration/ent/node_query.go @@ -24,14 +24,15 @@ import ( // NodeQuery is the builder for querying Node entities. type NodeQuery struct { config - ctx *QueryContext - order []node.OrderOption - inters []Interceptor - predicates []predicate.Node - withPrev *NodeQuery - withNext *NodeQuery - withFKs bool - modifiers []func(*sql.Selector) + ctx *QueryContext + order []node.OrderOption + inters []Interceptor + predicates []predicate.Node + withPrev *NodeQuery + withNext *NodeQuery + withFKs bool + modifiers []func(*sql.Selector) + retryConfig sqlgraph.RetryConfig // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -437,6 +438,7 @@ func (_q *NodeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Node, e if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig for i := range hooks { hooks[i](ctx, _spec) } @@ -537,6 +539,7 @@ func (_q *NodeQuery) sqlCount(ctx context.Context) (int, error) { if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig _spec.Node.Columns = _q.ctx.Fields if len(_q.ctx.Fields) > 0 { _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique @@ -651,6 +654,13 @@ func (_q *NodeQuery) Modify(modifiers ...func(s *sql.Selector)) *NodeSelect { return _q.Select() } +// WithRetryOptions sets the retry options for the query operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_q *NodeQuery) WithRetryOptions(opts ...any) *NodeQuery { + _q.retryConfig.Options = opts + return _q +} + // NodeGroupBy is the group-by builder for Node entities. type NodeGroupBy struct { selector diff --git a/entc/integration/ent/node_update.go b/entc/integration/ent/node_update.go index 6611f936ea..0f22c31517 100644 --- a/entc/integration/ent/node_update.go +++ b/entc/integration/ent/node_update.go @@ -22,9 +22,10 @@ import ( // NodeUpdate is the builder for updating Node entities. type NodeUpdate struct { config - hooks []Hook - mutation *NodeMutation - modifiers []func(*sql.UpdateBuilder) + hooks []Hook + mutation *NodeMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the NodeUpdate builder. @@ -169,6 +170,13 @@ func (_u *NodeUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *NodeUpdat return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *NodeUpdate) WithRetryOptions(opts ...any) *NodeUpdate { + _u.retryConfig.Options = opts + return _u +} + func (_u *NodeUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec := sqlgraph.NewUpdateSpec(node.Table, node.Columns, sqlgraph.NewFieldSpec(node.FieldID, field.TypeInt)) if ps := _u.mutation.predicates; len(ps) > 0 { @@ -252,6 +260,7 @@ func (_u *NodeUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec.Edges.Add = append(_spec.Edges.Add, edge) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{node.Label} @@ -267,10 +276,11 @@ func (_u *NodeUpdate) sqlSave(ctx context.Context) (_node int, err error) { // NodeUpdateOne is the builder for updating a single Node entity. type NodeUpdateOne struct { config - fields []string - hooks []Hook - mutation *NodeMutation - modifiers []func(*sql.UpdateBuilder) + fields []string + hooks []Hook + mutation *NodeMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // SetValue sets the "value" field. @@ -422,6 +432,13 @@ func (_u *NodeUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *NodeUp return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *NodeUpdateOne) WithRetryOptions(opts ...any) *NodeUpdateOne { + _u.retryConfig.Options = opts + return _u +} + func (_u *NodeUpdateOne) sqlSave(ctx context.Context) (_node *Node, err error) { _spec := sqlgraph.NewUpdateSpec(node.Table, node.Columns, sqlgraph.NewFieldSpec(node.FieldID, field.TypeInt)) id, ok := _u.mutation.ID() @@ -522,6 +539,7 @@ func (_u *NodeUpdateOne) sqlSave(ctx context.Context) (_node *Node, err error) { _spec.Edges.Add = append(_spec.Edges.Add, edge) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig _node = &Node{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/entc/integration/ent/pc_create.go b/entc/integration/ent/pc_create.go index dcf1a5cdbd..6285b1e040 100644 --- a/entc/integration/ent/pc_create.go +++ b/entc/integration/ent/pc_create.go @@ -20,9 +20,10 @@ import ( // PCCreate is the builder for creating a PC entity. type PCCreate struct { config - mutation *PCMutation - hooks []Hook - conflict []sql.ConflictOption + mutation *PCMutation + hooks []Hook + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // Mutation returns the PCMutation object of the builder. @@ -85,10 +86,18 @@ func (_c *PCCreate) createSpec() (*PC, *sqlgraph.CreateSpec) { _node = &PC{config: _c.config} _spec = sqlgraph.NewCreateSpec(pc.Table, sqlgraph.NewFieldSpec(pc.FieldID, field.TypeInt)) ) + _spec.RetryConfig = _c.retryConfig _spec.OnConflict = _c.conflict return _node, _spec } +// WithRetryOptions sets the retry options for the create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *PCCreate) WithRetryOptions(opts ...any) *PCCreate { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // @@ -208,9 +217,10 @@ func (u *PCUpsertOne) IDX(ctx context.Context) int { // PCCreateBulk is the builder for creating many PC entities in bulk. type PCCreateBulk struct { config - err error - builders []*PCCreate - conflict []sql.ConflictOption + err error + builders []*PCCreate + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // Save creates the PC entities in the database. @@ -239,6 +249,7 @@ func (_c *PCCreateBulk) Save(ctx context.Context) ([]*PC, error) { _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.RetryConfig = _c.retryConfig 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 { @@ -294,6 +305,13 @@ func (_c *PCCreateBulk) ExecX(ctx context.Context) { } } +// WithRetryOptions sets the retry options for the bulk create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *PCCreateBulk) WithRetryOptions(opts ...any) *PCCreateBulk { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // diff --git a/entc/integration/ent/pc_delete.go b/entc/integration/ent/pc_delete.go index 48f2e3932a..6b90014579 100644 --- a/entc/integration/ent/pc_delete.go +++ b/entc/integration/ent/pc_delete.go @@ -19,8 +19,9 @@ import ( // PCDelete is the builder for deleting a PC entity. type PCDelete struct { config - hooks []Hook - mutation *PCMutation + hooks []Hook + mutation *PCMutation + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the PCDelete builder. @@ -45,6 +46,7 @@ func (_d *PCDelete) ExecX(ctx context.Context) int { func (_d *PCDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(pc.Table, sqlgraph.NewFieldSpec(pc.FieldID, field.TypeInt)) + _spec.RetryConfig = _d.retryConfig if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { @@ -60,6 +62,13 @@ func (_d *PCDelete) sqlExec(ctx context.Context) (int, error) { return affected, err } +// WithRetryOptions sets the retry options for the delete operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_d *PCDelete) WithRetryOptions(opts ...any) *PCDelete { + _d.retryConfig.Options = opts + return _d +} + // PCDeleteOne is the builder for deleting a single PC entity. type PCDeleteOne struct { _d *PCDelete diff --git a/entc/integration/ent/pc_query.go b/entc/integration/ent/pc_query.go index 0e1d7e0d82..3ab0ef4610 100644 --- a/entc/integration/ent/pc_query.go +++ b/entc/integration/ent/pc_query.go @@ -23,11 +23,12 @@ import ( // PCQuery is the builder for querying PC entities. type PCQuery struct { config - ctx *QueryContext - order []pc.OrderOption - inters []Interceptor - predicates []predicate.PC - modifiers []func(*sql.Selector) + ctx *QueryContext + order []pc.OrderOption + inters []Interceptor + predicates []predicate.PC + modifiers []func(*sql.Selector) + retryConfig sqlgraph.RetryConfig // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -331,6 +332,7 @@ func (_q *PCQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*PC, error if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig for i := range hooks { hooks[i](ctx, _spec) } @@ -348,6 +350,7 @@ func (_q *PCQuery) sqlCount(ctx context.Context) (int, error) { if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig _spec.Node.Columns = _q.ctx.Fields if len(_q.ctx.Fields) > 0 { _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique @@ -462,6 +465,13 @@ func (_q *PCQuery) Modify(modifiers ...func(s *sql.Selector)) *PCSelect { return _q.Select() } +// WithRetryOptions sets the retry options for the query operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_q *PCQuery) WithRetryOptions(opts ...any) *PCQuery { + _q.retryConfig.Options = opts + return _q +} + // PCGroupBy is the group-by builder for PC entities. type PCGroupBy struct { selector diff --git a/entc/integration/ent/pc_update.go b/entc/integration/ent/pc_update.go index cfcfe797a4..728a59a72d 100644 --- a/entc/integration/ent/pc_update.go +++ b/entc/integration/ent/pc_update.go @@ -21,9 +21,10 @@ import ( // PCUpdate is the builder for updating PC entities. type PCUpdate struct { config - hooks []Hook - mutation *PCMutation - modifiers []func(*sql.UpdateBuilder) + hooks []Hook + mutation *PCMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the PCUpdate builder. @@ -70,6 +71,13 @@ func (_u *PCUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *PCUpdate { return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *PCUpdate) WithRetryOptions(opts ...any) *PCUpdate { + _u.retryConfig.Options = opts + return _u +} + func (_u *PCUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec := sqlgraph.NewUpdateSpec(pc.Table, pc.Columns, sqlgraph.NewFieldSpec(pc.FieldID, field.TypeInt)) if ps := _u.mutation.predicates; len(ps) > 0 { @@ -80,6 +88,7 @@ func (_u *PCUpdate) sqlSave(ctx context.Context) (_node int, err error) { } } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{pc.Label} @@ -95,10 +104,11 @@ func (_u *PCUpdate) sqlSave(ctx context.Context) (_node int, err error) { // PCUpdateOne is the builder for updating a single PC entity. type PCUpdateOne struct { config - fields []string - hooks []Hook - mutation *PCMutation - modifiers []func(*sql.UpdateBuilder) + fields []string + hooks []Hook + mutation *PCMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // Mutation returns the PCMutation object of the builder. @@ -152,6 +162,13 @@ func (_u *PCUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *PCUpdate return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *PCUpdateOne) WithRetryOptions(opts ...any) *PCUpdateOne { + _u.retryConfig.Options = opts + return _u +} + func (_u *PCUpdateOne) sqlSave(ctx context.Context) (_node *PC, err error) { _spec := sqlgraph.NewUpdateSpec(pc.Table, pc.Columns, sqlgraph.NewFieldSpec(pc.FieldID, field.TypeInt)) id, ok := _u.mutation.ID() @@ -179,6 +196,7 @@ func (_u *PCUpdateOne) sqlSave(ctx context.Context) (_node *PC, err error) { } } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig _node = &PC{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/entc/integration/ent/pet_create.go b/entc/integration/ent/pet_create.go index d2164af6eb..208c2e4a75 100644 --- a/entc/integration/ent/pet_create.go +++ b/entc/integration/ent/pet_create.go @@ -23,9 +23,10 @@ import ( // PetCreate is the builder for creating a Pet entity. type PetCreate struct { config - mutation *PetMutation - hooks []Hook - conflict []sql.ConflictOption + mutation *PetMutation + hooks []Hook + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // SetAge sets the "age" field. @@ -224,6 +225,7 @@ func (_c *PetCreate) createSpec() (*Pet, *sqlgraph.CreateSpec) { _node = &Pet{config: _c.config} _spec = sqlgraph.NewCreateSpec(pet.Table, sqlgraph.NewFieldSpec(pet.FieldID, field.TypeInt)) ) + _spec.RetryConfig = _c.retryConfig _spec.OnConflict = _c.conflict if value, ok := _c.mutation.Age(); ok { _spec.SetField(pet.FieldAge, field.TypeFloat64, value) @@ -286,6 +288,13 @@ func (_c *PetCreate) createSpec() (*Pet, *sqlgraph.CreateSpec) { return _node, _spec } +// WithRetryOptions sets the retry options for the create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *PetCreate) WithRetryOptions(opts ...any) *PetCreate { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // @@ -619,9 +628,10 @@ func (u *PetUpsertOne) IDX(ctx context.Context) int { // PetCreateBulk is the builder for creating many Pet entities in bulk. type PetCreateBulk struct { config - err error - builders []*PetCreate - conflict []sql.ConflictOption + err error + builders []*PetCreate + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // Save creates the Pet entities in the database. @@ -651,6 +661,7 @@ func (_c *PetCreateBulk) Save(ctx context.Context) ([]*Pet, error) { _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.RetryConfig = _c.retryConfig 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 { @@ -706,6 +717,13 @@ func (_c *PetCreateBulk) ExecX(ctx context.Context) { } } +// WithRetryOptions sets the retry options for the bulk create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *PetCreateBulk) WithRetryOptions(opts ...any) *PetCreateBulk { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // diff --git a/entc/integration/ent/pet_delete.go b/entc/integration/ent/pet_delete.go index 431bea2dff..8cf51235a2 100644 --- a/entc/integration/ent/pet_delete.go +++ b/entc/integration/ent/pet_delete.go @@ -19,8 +19,9 @@ import ( // PetDelete is the builder for deleting a Pet entity. type PetDelete struct { config - hooks []Hook - mutation *PetMutation + hooks []Hook + mutation *PetMutation + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the PetDelete builder. @@ -45,6 +46,7 @@ func (_d *PetDelete) ExecX(ctx context.Context) int { func (_d *PetDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(pet.Table, sqlgraph.NewFieldSpec(pet.FieldID, field.TypeInt)) + _spec.RetryConfig = _d.retryConfig if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { @@ -60,6 +62,13 @@ func (_d *PetDelete) sqlExec(ctx context.Context) (int, error) { return affected, err } +// WithRetryOptions sets the retry options for the delete operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_d *PetDelete) WithRetryOptions(opts ...any) *PetDelete { + _d.retryConfig.Options = opts + return _d +} + // PetDeleteOne is the builder for deleting a single Pet entity. type PetDeleteOne struct { _d *PetDelete diff --git a/entc/integration/ent/pet_query.go b/entc/integration/ent/pet_query.go index 05f3de79a1..b751e89919 100644 --- a/entc/integration/ent/pet_query.go +++ b/entc/integration/ent/pet_query.go @@ -24,14 +24,15 @@ import ( // PetQuery is the builder for querying Pet entities. type PetQuery struct { config - ctx *QueryContext - order []pet.OrderOption - inters []Interceptor - predicates []predicate.Pet - withTeam *UserQuery - withOwner *UserQuery - withFKs bool - modifiers []func(*sql.Selector) + ctx *QueryContext + order []pet.OrderOption + inters []Interceptor + predicates []predicate.Pet + withTeam *UserQuery + withOwner *UserQuery + withFKs bool + modifiers []func(*sql.Selector) + retryConfig sqlgraph.RetryConfig // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -437,6 +438,7 @@ func (_q *PetQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Pet, err if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig for i := range hooks { hooks[i](ctx, _spec) } @@ -536,6 +538,7 @@ func (_q *PetQuery) sqlCount(ctx context.Context) (int, error) { if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig _spec.Node.Columns = _q.ctx.Fields if len(_q.ctx.Fields) > 0 { _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique @@ -650,6 +653,13 @@ func (_q *PetQuery) Modify(modifiers ...func(s *sql.Selector)) *PetSelect { return _q.Select() } +// WithRetryOptions sets the retry options for the query operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_q *PetQuery) WithRetryOptions(opts ...any) *PetQuery { + _q.retryConfig.Options = opts + return _q +} + // PetGroupBy is the group-by builder for Pet entities. type PetGroupBy struct { selector diff --git a/entc/integration/ent/pet_update.go b/entc/integration/ent/pet_update.go index 121a891571..86d42e92e2 100644 --- a/entc/integration/ent/pet_update.go +++ b/entc/integration/ent/pet_update.go @@ -24,9 +24,10 @@ import ( // PetUpdate is the builder for updating Pet entities. type PetUpdate struct { config - hooks []Hook - mutation *PetMutation - modifiers []func(*sql.UpdateBuilder) + hooks []Hook + mutation *PetMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the PetUpdate builder. @@ -232,6 +233,13 @@ func (_u *PetUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *PetUpdate return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *PetUpdate) WithRetryOptions(opts ...any) *PetUpdate { + _u.retryConfig.Options = opts + return _u +} + func (_u *PetUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec := sqlgraph.NewUpdateSpec(pet.Table, pet.Columns, sqlgraph.NewFieldSpec(pet.FieldID, field.TypeInt)) if ps := _u.mutation.predicates; len(ps) > 0 { @@ -330,6 +338,7 @@ func (_u *PetUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec.Edges.Add = append(_spec.Edges.Add, edge) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{pet.Label} @@ -345,10 +354,11 @@ func (_u *PetUpdate) sqlSave(ctx context.Context) (_node int, err error) { // PetUpdateOne is the builder for updating a single Pet entity. type PetUpdateOne struct { config - fields []string - hooks []Hook - mutation *PetMutation - modifiers []func(*sql.UpdateBuilder) + fields []string + hooks []Hook + mutation *PetMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // SetAge sets the "age" field. @@ -561,6 +571,13 @@ func (_u *PetUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *PetUpda return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *PetUpdateOne) WithRetryOptions(opts ...any) *PetUpdateOne { + _u.retryConfig.Options = opts + return _u +} + func (_u *PetUpdateOne) sqlSave(ctx context.Context) (_node *Pet, err error) { _spec := sqlgraph.NewUpdateSpec(pet.Table, pet.Columns, sqlgraph.NewFieldSpec(pet.FieldID, field.TypeInt)) id, ok := _u.mutation.ID() @@ -676,6 +693,7 @@ func (_u *PetUpdateOne) sqlSave(ctx context.Context) (_node *Pet, err error) { _spec.Edges.Add = append(_spec.Edges.Add, edge) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig _node = &Pet{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/entc/integration/ent/spec_create.go b/entc/integration/ent/spec_create.go index 0d561c1d0b..354231971f 100644 --- a/entc/integration/ent/spec_create.go +++ b/entc/integration/ent/spec_create.go @@ -21,9 +21,10 @@ import ( // SpecCreate is the builder for creating a Spec entity. type SpecCreate struct { config - mutation *SpecMutation - hooks []Hook - conflict []sql.ConflictOption + mutation *SpecMutation + hooks []Hook + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // AddCardIDs adds the "card" edge to the Card entity by IDs. @@ -101,6 +102,7 @@ func (_c *SpecCreate) createSpec() (*Spec, *sqlgraph.CreateSpec) { _node = &Spec{config: _c.config} _spec = sqlgraph.NewCreateSpec(spec.Table, sqlgraph.NewFieldSpec(spec.FieldID, field.TypeInt)) ) + _spec.RetryConfig = _c.retryConfig _spec.OnConflict = _c.conflict if nodes := _c.mutation.CardIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ @@ -121,6 +123,13 @@ func (_c *SpecCreate) createSpec() (*Spec, *sqlgraph.CreateSpec) { return _node, _spec } +// WithRetryOptions sets the retry options for the create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *SpecCreate) WithRetryOptions(opts ...any) *SpecCreate { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // @@ -240,9 +249,10 @@ func (u *SpecUpsertOne) IDX(ctx context.Context) int { // SpecCreateBulk is the builder for creating many Spec entities in bulk. type SpecCreateBulk struct { config - err error - builders []*SpecCreate - conflict []sql.ConflictOption + err error + builders []*SpecCreate + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // Save creates the Spec entities in the database. @@ -271,6 +281,7 @@ func (_c *SpecCreateBulk) Save(ctx context.Context) ([]*Spec, error) { _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.RetryConfig = _c.retryConfig 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 { @@ -326,6 +337,13 @@ func (_c *SpecCreateBulk) ExecX(ctx context.Context) { } } +// WithRetryOptions sets the retry options for the bulk create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *SpecCreateBulk) WithRetryOptions(opts ...any) *SpecCreateBulk { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // diff --git a/entc/integration/ent/spec_delete.go b/entc/integration/ent/spec_delete.go index 038590621b..4fd2627533 100644 --- a/entc/integration/ent/spec_delete.go +++ b/entc/integration/ent/spec_delete.go @@ -19,8 +19,9 @@ import ( // SpecDelete is the builder for deleting a Spec entity. type SpecDelete struct { config - hooks []Hook - mutation *SpecMutation + hooks []Hook + mutation *SpecMutation + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the SpecDelete builder. @@ -45,6 +46,7 @@ func (_d *SpecDelete) ExecX(ctx context.Context) int { func (_d *SpecDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(spec.Table, sqlgraph.NewFieldSpec(spec.FieldID, field.TypeInt)) + _spec.RetryConfig = _d.retryConfig if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { @@ -60,6 +62,13 @@ func (_d *SpecDelete) sqlExec(ctx context.Context) (int, error) { return affected, err } +// WithRetryOptions sets the retry options for the delete operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_d *SpecDelete) WithRetryOptions(opts ...any) *SpecDelete { + _d.retryConfig.Options = opts + return _d +} + // SpecDeleteOne is the builder for deleting a single Spec entity. type SpecDeleteOne struct { _d *SpecDelete diff --git a/entc/integration/ent/spec_query.go b/entc/integration/ent/spec_query.go index 6940136f97..50b972e1cf 100644 --- a/entc/integration/ent/spec_query.go +++ b/entc/integration/ent/spec_query.go @@ -32,6 +32,7 @@ type SpecQuery struct { withCard *CardQuery modifiers []func(*sql.Selector) withNamedCard map[string]*CardQuery + retryConfig sqlgraph.RetryConfig // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -373,6 +374,7 @@ func (_q *SpecQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Spec, e if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig for i := range hooks { hooks[i](ctx, _spec) } @@ -466,6 +468,7 @@ func (_q *SpecQuery) sqlCount(ctx context.Context) (int, error) { if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig _spec.Node.Columns = _q.ctx.Fields if len(_q.ctx.Fields) > 0 { _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique @@ -594,6 +597,13 @@ func (_q *SpecQuery) WithNamedCard(name string, opts ...func(*CardQuery)) *SpecQ return _q } +// WithRetryOptions sets the retry options for the query operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_q *SpecQuery) WithRetryOptions(opts ...any) *SpecQuery { + _q.retryConfig.Options = opts + return _q +} + // SpecGroupBy is the group-by builder for Spec entities. type SpecGroupBy struct { selector diff --git a/entc/integration/ent/spec_update.go b/entc/integration/ent/spec_update.go index c9df3fbecc..d0ce335f44 100644 --- a/entc/integration/ent/spec_update.go +++ b/entc/integration/ent/spec_update.go @@ -22,9 +22,10 @@ import ( // SpecUpdate is the builder for updating Spec entities. type SpecUpdate struct { config - hooks []Hook - mutation *SpecMutation - modifiers []func(*sql.UpdateBuilder) + hooks []Hook + mutation *SpecMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the SpecUpdate builder. @@ -107,6 +108,13 @@ func (_u *SpecUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *SpecUpdat return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *SpecUpdate) WithRetryOptions(opts ...any) *SpecUpdate { + _u.retryConfig.Options = opts + return _u +} + func (_u *SpecUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec := sqlgraph.NewUpdateSpec(spec.Table, spec.Columns, sqlgraph.NewFieldSpec(spec.FieldID, field.TypeInt)) if ps := _u.mutation.predicates; len(ps) > 0 { @@ -162,6 +170,7 @@ func (_u *SpecUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec.Edges.Add = append(_spec.Edges.Add, edge) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{spec.Label} @@ -177,10 +186,11 @@ func (_u *SpecUpdate) sqlSave(ctx context.Context) (_node int, err error) { // SpecUpdateOne is the builder for updating a single Spec entity. type SpecUpdateOne struct { config - fields []string - hooks []Hook - mutation *SpecMutation - modifiers []func(*sql.UpdateBuilder) + fields []string + hooks []Hook + mutation *SpecMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // AddCardIDs adds the "card" edge to the Card entity by IDs. @@ -270,6 +280,13 @@ func (_u *SpecUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *SpecUp return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *SpecUpdateOne) WithRetryOptions(opts ...any) *SpecUpdateOne { + _u.retryConfig.Options = opts + return _u +} + func (_u *SpecUpdateOne) sqlSave(ctx context.Context) (_node *Spec, err error) { _spec := sqlgraph.NewUpdateSpec(spec.Table, spec.Columns, sqlgraph.NewFieldSpec(spec.FieldID, field.TypeInt)) id, ok := _u.mutation.ID() @@ -342,6 +359,7 @@ func (_u *SpecUpdateOne) sqlSave(ctx context.Context) (_node *Spec, err error) { _spec.Edges.Add = append(_spec.Edges.Add, edge) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig _node = &Spec{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/entc/integration/ent/task_create.go b/entc/integration/ent/task_create.go index e99ff466c7..d06d1ac267 100644 --- a/entc/integration/ent/task_create.go +++ b/entc/integration/ent/task_create.go @@ -22,9 +22,10 @@ import ( // TaskCreate is the builder for creating a Task entity. type TaskCreate struct { config - mutation *TaskMutation - hooks []Hook - conflict []sql.ConflictOption + mutation *TaskMutation + hooks []Hook + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // SetPriority sets the "priority" field. @@ -227,6 +228,7 @@ func (_c *TaskCreate) createSpec() (*Task, *sqlgraph.CreateSpec) { _node = &Task{config: _c.config} _spec = sqlgraph.NewCreateSpec(enttask.Table, sqlgraph.NewFieldSpec(enttask.FieldID, field.TypeInt)) ) + _spec.RetryConfig = _c.retryConfig _spec.OnConflict = _c.conflict if value, ok := _c.mutation.Priority(); ok { _spec.SetField(enttask.FieldPriority, field.TypeInt, value) @@ -263,6 +265,13 @@ func (_c *TaskCreate) createSpec() (*Task, *sqlgraph.CreateSpec) { return _node, _spec } +// WithRetryOptions sets the retry options for the create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *TaskCreate) WithRetryOptions(opts ...any) *TaskCreate { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // @@ -679,9 +688,10 @@ func (u *TaskUpsertOne) IDX(ctx context.Context) int { // TaskCreateBulk is the builder for creating many Task entities in bulk. type TaskCreateBulk struct { config - err error - builders []*TaskCreate - conflict []sql.ConflictOption + err error + builders []*TaskCreate + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // Save creates the Task entities in the database. @@ -711,6 +721,7 @@ func (_c *TaskCreateBulk) Save(ctx context.Context) ([]*Task, error) { _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.RetryConfig = _c.retryConfig 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 { @@ -766,6 +777,13 @@ func (_c *TaskCreateBulk) ExecX(ctx context.Context) { } } +// WithRetryOptions sets the retry options for the bulk create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *TaskCreateBulk) WithRetryOptions(opts ...any) *TaskCreateBulk { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // diff --git a/entc/integration/ent/task_delete.go b/entc/integration/ent/task_delete.go index 21b49cae9d..ce2900fac8 100644 --- a/entc/integration/ent/task_delete.go +++ b/entc/integration/ent/task_delete.go @@ -20,8 +20,9 @@ import ( // TaskDelete is the builder for deleting a Task entity. type TaskDelete struct { config - hooks []Hook - mutation *TaskMutation + hooks []Hook + mutation *TaskMutation + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the TaskDelete builder. @@ -46,6 +47,7 @@ func (_d *TaskDelete) ExecX(ctx context.Context) int { func (_d *TaskDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(enttask.Table, sqlgraph.NewFieldSpec(enttask.FieldID, field.TypeInt)) + _spec.RetryConfig = _d.retryConfig if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { @@ -61,6 +63,13 @@ func (_d *TaskDelete) sqlExec(ctx context.Context) (int, error) { return affected, err } +// WithRetryOptions sets the retry options for the delete operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_d *TaskDelete) WithRetryOptions(opts ...any) *TaskDelete { + _d.retryConfig.Options = opts + return _d +} + // TaskDeleteOne is the builder for deleting a single Task entity. type TaskDeleteOne struct { _d *TaskDelete diff --git a/entc/integration/ent/task_query.go b/entc/integration/ent/task_query.go index 389a3b75ef..bdd6ec5540 100644 --- a/entc/integration/ent/task_query.go +++ b/entc/integration/ent/task_query.go @@ -23,11 +23,12 @@ import ( // TaskQuery is the builder for querying Task entities. type TaskQuery struct { config - ctx *QueryContext - order []enttask.OrderOption - inters []Interceptor - predicates []predicate.Task - modifiers []func(*sql.Selector) + ctx *QueryContext + order []enttask.OrderOption + inters []Interceptor + predicates []predicate.Task + modifiers []func(*sql.Selector) + retryConfig sqlgraph.RetryConfig // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -353,6 +354,7 @@ func (_q *TaskQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Task, e if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig for i := range hooks { hooks[i](ctx, _spec) } @@ -370,6 +372,7 @@ func (_q *TaskQuery) sqlCount(ctx context.Context) (int, error) { if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig _spec.Node.Columns = _q.ctx.Fields if len(_q.ctx.Fields) > 0 { _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique @@ -484,6 +487,13 @@ func (_q *TaskQuery) Modify(modifiers ...func(s *sql.Selector)) *TaskSelect { return _q.Select() } +// WithRetryOptions sets the retry options for the query operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_q *TaskQuery) WithRetryOptions(opts ...any) *TaskQuery { + _q.retryConfig.Options = opts + return _q +} + // TaskGroupBy is the group-by builder for Task entities. type TaskGroupBy struct { selector diff --git a/entc/integration/ent/task_update.go b/entc/integration/ent/task_update.go index 7f82b65f37..88d8a2b4e2 100644 --- a/entc/integration/ent/task_update.go +++ b/entc/integration/ent/task_update.go @@ -22,9 +22,10 @@ import ( // TaskUpdate is the builder for updating Task entities. type TaskUpdate struct { config - hooks []Hook - mutation *TaskMutation - modifiers []func(*sql.UpdateBuilder) + hooks []Hook + mutation *TaskMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the TaskUpdate builder. @@ -227,6 +228,13 @@ func (_u *TaskUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *TaskUpdat return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *TaskUpdate) WithRetryOptions(opts ...any) *TaskUpdate { + _u.retryConfig.Options = opts + return _u +} + func (_u *TaskUpdate) sqlSave(ctx context.Context) (_node int, err error) { if err := _u.check(); err != nil { return _node, err @@ -285,6 +293,7 @@ func (_u *TaskUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec.SetField(enttask.FieldOp, field.TypeString, value) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{enttask.Label} @@ -300,10 +309,11 @@ func (_u *TaskUpdate) sqlSave(ctx context.Context) (_node int, err error) { // TaskUpdateOne is the builder for updating a single Task entity. type TaskUpdateOne struct { config - fields []string - hooks []Hook - mutation *TaskMutation - modifiers []func(*sql.UpdateBuilder) + fields []string + hooks []Hook + mutation *TaskMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // SetPriority sets the "priority" field. @@ -513,6 +523,13 @@ func (_u *TaskUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *TaskUp return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *TaskUpdateOne) WithRetryOptions(opts ...any) *TaskUpdateOne { + _u.retryConfig.Options = opts + return _u +} + func (_u *TaskUpdateOne) sqlSave(ctx context.Context) (_node *Task, err error) { if err := _u.check(); err != nil { return _node, err @@ -588,6 +605,7 @@ func (_u *TaskUpdateOne) sqlSave(ctx context.Context) (_node *Task, err error) { _spec.SetField(enttask.FieldOp, field.TypeString, value) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig _node = &Task{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/entc/integration/ent/user_create.go b/entc/integration/ent/user_create.go index 098bc1e6e8..e9dcb84db3 100644 --- a/entc/integration/ent/user_create.go +++ b/entc/integration/ent/user_create.go @@ -24,9 +24,10 @@ import ( // UserCreate is the builder for creating a User entity. type UserCreate struct { config - mutation *UserMutation - hooks []Hook - conflict []sql.ConflictOption + mutation *UserMutation + hooks []Hook + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // SetOptionalInt sets the "optional_int" field. @@ -473,6 +474,7 @@ func (_c *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { _node = &User{config: _c.config} _spec = sqlgraph.NewCreateSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) ) + _spec.RetryConfig = _c.retryConfig _spec.OnConflict = _c.conflict if value, ok := _c.mutation.OptionalInt(); ok { _spec.SetField(user.FieldOptionalInt, field.TypeInt, value) @@ -703,6 +705,13 @@ func (_c *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { return _node, _spec } +// WithRetryOptions sets the retry options for the create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *UserCreate) WithRetryOptions(opts ...any) *UserCreate { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // @@ -1270,9 +1279,10 @@ func (u *UserUpsertOne) IDX(ctx context.Context) int { // UserCreateBulk is the builder for creating many User entities in bulk. type UserCreateBulk struct { config - err error - builders []*UserCreate - conflict []sql.ConflictOption + err error + builders []*UserCreate + retryConfig sqlgraph.RetryConfig + conflict []sql.ConflictOption } // Save creates the User entities in the database. @@ -1302,6 +1312,7 @@ func (_c *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.RetryConfig = _c.retryConfig 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 { @@ -1357,6 +1368,13 @@ func (_c *UserCreateBulk) ExecX(ctx context.Context) { } } +// WithRetryOptions sets the retry options for the bulk create operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_c *UserCreateBulk) WithRetryOptions(opts ...any) *UserCreateBulk { + _c.retryConfig.Options = opts + return _c +} + // OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause // of the `INSERT` statement. For example: // diff --git a/entc/integration/ent/user_delete.go b/entc/integration/ent/user_delete.go index a5c500abfa..f995536f25 100644 --- a/entc/integration/ent/user_delete.go +++ b/entc/integration/ent/user_delete.go @@ -19,8 +19,9 @@ import ( // UserDelete is the builder for deleting a User entity. type UserDelete struct { config - hooks []Hook - mutation *UserMutation + hooks []Hook + mutation *UserMutation + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the UserDelete builder. @@ -45,6 +46,7 @@ func (_d *UserDelete) ExecX(ctx context.Context) int { func (_d *UserDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) + _spec.RetryConfig = _d.retryConfig if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { @@ -60,6 +62,13 @@ func (_d *UserDelete) sqlExec(ctx context.Context) (int, error) { return affected, err } +// WithRetryOptions sets the retry options for the delete operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_d *UserDelete) WithRetryOptions(opts ...any) *UserDelete { + _d.retryConfig.Options = opts + return _d +} + // UserDeleteOne is the builder for deleting a single User entity. type UserDeleteOne struct { _d *UserDelete diff --git a/entc/integration/ent/user_query.go b/entc/integration/ent/user_query.go index 7781c3fa13..0927a941b3 100644 --- a/entc/integration/ent/user_query.go +++ b/entc/integration/ent/user_query.go @@ -52,6 +52,7 @@ type UserQuery struct { withNamedFollowers map[string]*UserQuery withNamedFollowing map[string]*UserQuery withNamedChildren map[string]*UserQuery + retryConfig sqlgraph.RetryConfig // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -772,6 +773,7 @@ func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig for i := range hooks { hooks[i](ctx, _spec) } @@ -1409,6 +1411,7 @@ func (_q *UserQuery) sqlCount(ctx context.Context) (int, error) { if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers } + _spec.RetryConfig = _q.retryConfig _spec.Node.Columns = _q.ctx.Fields if len(_q.ctx.Fields) > 0 { _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique @@ -1621,6 +1624,13 @@ func (_q *UserQuery) WithNamedChildren(name string, opts ...func(*UserQuery)) *U return _q } +// WithRetryOptions sets the retry options for the query operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_q *UserQuery) WithRetryOptions(opts ...any) *UserQuery { + _q.retryConfig.Options = opts + return _q +} + // UserGroupBy is the group-by builder for User entities. type UserGroupBy struct { selector diff --git a/entc/integration/ent/user_update.go b/entc/integration/ent/user_update.go index 126b7d2861..6620c6344b 100644 --- a/entc/integration/ent/user_update.go +++ b/entc/integration/ent/user_update.go @@ -25,9 +25,10 @@ import ( // UserUpdate is the builder for updating User entities. type UserUpdate struct { config - hooks []Hook - mutation *UserMutation - modifiers []func(*sql.UpdateBuilder) + hooks []Hook + mutation *UserMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // Where appends a list predicates to the UserUpdate builder. @@ -677,6 +678,13 @@ func (_u *UserUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *UserUpdat return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *UserUpdate) WithRetryOptions(opts ...any) *UserUpdate { + _u.retryConfig.Options = opts + return _u +} + func (_u *UserUpdate) sqlSave(ctx context.Context) (_node int, err error) { if err := _u.check(); err != nil { return _node, err @@ -1187,6 +1195,7 @@ func (_u *UserUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec.Edges.Add = append(_spec.Edges.Add, edge) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{user.Label} @@ -1202,10 +1211,11 @@ func (_u *UserUpdate) sqlSave(ctx context.Context) (_node int, err error) { // UserUpdateOne is the builder for updating a single User entity. type UserUpdateOne struct { config - fields []string - hooks []Hook - mutation *UserMutation - modifiers []func(*sql.UpdateBuilder) + fields []string + hooks []Hook + mutation *UserMutation + modifiers []func(*sql.UpdateBuilder) + retryConfig sqlgraph.RetryConfig } // SetOptionalInt sets the "optional_int" field. @@ -1862,6 +1872,13 @@ func (_u *UserUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *UserUp return _u } +// WithRetryOptions sets the retry options for the update operation. +// For YDB, these should be retry.Option values from ydb-go-sdk. +func (_u *UserUpdateOne) WithRetryOptions(opts ...any) *UserUpdateOne { + _u.retryConfig.Options = opts + return _u +} + func (_u *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) { if err := _u.check(); err != nil { return _node, err @@ -2389,6 +2406,7 @@ func (_u *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) { _spec.Edges.Add = append(_spec.Edges.Add, edge) } _spec.AddModifiers(_u.modifiers...) + _spec.RetryConfig = _u.retryConfig _node = &User{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/entc/integration/go.sum b/entc/integration/go.sum index 980501e17b..573eefc0a0 100644 --- a/entc/integration/go.sum +++ b/entc/integration/go.sum @@ -32,6 +32,8 @@ github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1m github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1/go.mod h1:KJwIaB5Mv44NWtYuAOFCVOjcI94vtpEz2JU/D2v6IjE= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= +github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= @@ -92,6 +94,12 @@ github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0 github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/lib/pq v1.10.7 h1:p7ZhMD+KsSRozJr34udlUrhboJwWAgCg34+/ZZNvZZw= github.com/lib/pq v1.10.7/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= +github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-sqlite3 v1.14.28 h1:ThEiQrnbtumT+QMknw63Befp/ce/nUPgBPMlRFEum7A= github.com/mattn/go-sqlite3 v1.14.28/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= @@ -103,16 +111,28 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/olekukonko/errors v0.0.0-20250405072817-4e6d85265da6 h1:r3FaAI0NZK3hSmtTDrBVREhKULp8oUeqLT5Eyl2mSPo= +github.com/olekukonko/errors v0.0.0-20250405072817-4e6d85265da6/go.mod h1:ppzxA5jBKcO1vIpCXQ9ZqgDh8iwODz6OXIGKU8r5m4Y= +github.com/olekukonko/ll v0.0.8 h1:sbGZ1Fx4QxJXEqL/6IG8GEFnYojUSQ45dJVwN2FH2fc= +github.com/olekukonko/ll v0.0.8/go.mod h1:En+sEW0JNETl26+K8eZ6/W4UQ7CYSrrgg/EdIYT2H8g= +github.com/olekukonko/tablewriter v1.0.8 h1:f6wJzHg4QUtJdvrVPKco4QTrAylgaU0+b9br/lJxEiQ= +github.com/olekukonko/tablewriter v1.0.8/go.mod h1:H428M+HzoUXC6JU2Abj9IT9ooRmdq9CxuDmKMtrOCMs= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/rekby/fixenv v0.6.1 h1:jUFiSPpajT4WY2cYuc++7Y1zWrnCxnovGCIX72PZniM= github.com/rekby/fixenv v0.6.1/go.mod h1:/b5LRc06BYJtslRtHKxsPWFT/ySpHV+rWvzTg+XWk4c= +github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8= github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I= +github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= +github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= @@ -187,6 +207,8 @@ golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ= +golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= diff --git a/entc/integration/hooks/ent/client.go b/entc/integration/hooks/ent/client.go index a8e9f11de8..d963edd315 100644 --- a/entc/integration/hooks/ent/client.go +++ b/entc/integration/hooks/ent/client.go @@ -19,6 +19,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/entc/integration/hooks/ent/card" "entgo.io/ent/entc/integration/hooks/ent/pet" "entgo.io/ent/entc/integration/hooks/ent/user" @@ -112,8 +113,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/entc/integration/idtype/ent/client.go b/entc/integration/idtype/ent/client.go index 18cfcf6566..93a3e0181e 100644 --- a/entc/integration/idtype/ent/client.go +++ b/entc/integration/idtype/ent/client.go @@ -19,6 +19,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/entc/integration/idtype/ent/user" ) @@ -104,8 +105,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/entc/integration/json/ent/client.go b/entc/integration/json/ent/client.go index 36ba6679f9..a9e54fe3c7 100644 --- a/entc/integration/json/ent/client.go +++ b/entc/integration/json/ent/client.go @@ -18,6 +18,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/entc/integration/json/ent/user" ) @@ -103,8 +104,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/entc/integration/migrate/entv1/client.go b/entc/integration/migrate/entv1/client.go index d3cae2b84f..7e75175637 100644 --- a/entc/integration/migrate/entv1/client.go +++ b/entc/integration/migrate/entv1/client.go @@ -19,6 +19,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/entc/integration/migrate/entv1/car" "entgo.io/ent/entc/integration/migrate/entv1/conversion" "entgo.io/ent/entc/integration/migrate/entv1/customtype" @@ -116,8 +117,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/entc/integration/migrate/entv2/blog_create.go b/entc/integration/migrate/entv2/blog_create.go index c1a2ad5f45..39e9ddbbaa 100644 --- a/entc/integration/migrate/entv2/blog_create.go +++ b/entc/integration/migrate/entv2/blog_create.go @@ -87,7 +87,7 @@ func (_c *BlogCreate) ExecX(ctx context.Context) { // check runs all checks and user-defined validators on the builder. func (_c *BlogCreate) check() error { switch _c.driver.Dialect() { - case dialect.MySQL, dialect.SQLite: + case dialect.MySQL, dialect.SQLite, dialect.YDB: if _, ok := _c.mutation.Oid(); !ok { return &ValidationError{Name: "oid", err: errors.New(`entv2: missing required field "Blog.oid"`)} } diff --git a/entc/integration/migrate/entv2/client.go b/entc/integration/migrate/entv2/client.go index ed15ab6937..2c1b3777c9 100644 --- a/entc/integration/migrate/entv2/client.go +++ b/entc/integration/migrate/entv2/client.go @@ -19,6 +19,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/entc/integration/migrate/entv2/blog" "entgo.io/ent/entc/integration/migrate/entv2/car" "entgo.io/ent/entc/integration/migrate/entv2/conversion" @@ -136,8 +137,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/entc/integration/migrate/versioned/client.go b/entc/integration/migrate/versioned/client.go index d745e43d82..d5afb29b91 100644 --- a/entc/integration/migrate/versioned/client.go +++ b/entc/integration/migrate/versioned/client.go @@ -18,6 +18,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/entc/integration/migrate/versioned/group" "entgo.io/ent/entc/integration/migrate/versioned/user" ) @@ -107,8 +108,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/entc/integration/multischema/ent/client.go b/entc/integration/multischema/ent/client.go index 50c593dd0b..8e1bcbc8ab 100644 --- a/entc/integration/multischema/ent/client.go +++ b/entc/integration/multischema/ent/client.go @@ -19,6 +19,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/entc/integration/multischema/ent/friendship" "entgo.io/ent/entc/integration/multischema/ent/group" "entgo.io/ent/entc/integration/multischema/ent/parent" @@ -128,8 +129,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/entc/integration/multischema/versioned/client.go b/entc/integration/multischema/versioned/client.go index 95f3b4cbc3..4fc86d49ae 100644 --- a/entc/integration/multischema/versioned/client.go +++ b/entc/integration/multischema/versioned/client.go @@ -19,6 +19,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/entc/integration/multischema/versioned/friendship" "entgo.io/ent/entc/integration/multischema/versioned/group" "entgo.io/ent/entc/integration/multischema/versioned/pet" @@ -121,8 +122,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/entc/integration/privacy/ent/client.go b/entc/integration/privacy/ent/client.go index 47091c9b3a..cac43ddb40 100644 --- a/entc/integration/privacy/ent/client.go +++ b/entc/integration/privacy/ent/client.go @@ -21,6 +21,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/entc/integration/privacy/ent/task" "entgo.io/ent/entc/integration/privacy/ent/team" "entgo.io/ent/entc/integration/privacy/ent/user" @@ -122,8 +123,16 @@ func HTTPClient(v *http.Client) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/entc/integration/template/ent/client.go b/entc/integration/template/ent/client.go index e15974b4c6..306c44f2cd 100644 --- a/entc/integration/template/ent/client.go +++ b/entc/integration/template/ent/client.go @@ -20,6 +20,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/entc/integration/template/ent/group" "entgo.io/ent/entc/integration/template/ent/pet" "entgo.io/ent/entc/integration/template/ent/user" @@ -126,8 +127,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } From 10ea0362a7f44a658438f8d92baea6515b6930d1 Mon Sep 17 00:00:00 2001 From: danilov6083 Date: Fri, 16 Jan 2026 16:12:28 +0300 Subject: [PATCH 10/13] ent/examples: regenerated all examples --- examples/compositetypes/ent/client.go | 13 +++++++++++-- examples/domaintypes/ent/client.go | 13 +++++++++++-- examples/edgeindex/ent/client.go | 13 +++++++++++-- examples/encryptfield/ent/client.go | 13 +++++++++++-- examples/entcpkg/ent/client.go | 13 +++++++++++-- examples/enumtypes/ent/client.go | 13 +++++++++++-- examples/extensions/ent/client.go | 13 +++++++++++-- examples/fs/ent/client.go | 13 +++++++++++-- examples/functionalidx/ent/client.go | 13 +++++++++++-- examples/go.sum | 21 +++++++++++++++++++++ examples/jsonencode/ent/client.go | 13 +++++++++++-- examples/m2m2types/ent/client.go | 13 +++++++++++-- examples/m2mbidi/ent/client.go | 13 +++++++++++-- examples/m2mrecur/ent/client.go | 13 +++++++++++-- examples/migration/ent/client.go | 13 +++++++++++-- examples/o2m2types/ent/client.go | 13 +++++++++++-- examples/o2mrecur/ent/client.go | 13 +++++++++++-- examples/o2o2types/ent/client.go | 13 +++++++++++-- examples/o2obidi/ent/client.go | 13 +++++++++++-- examples/o2orecur/ent/client.go | 13 +++++++++++-- examples/privacyadmin/ent/client.go | 13 +++++++++++-- examples/privacytenant/ent/client.go | 13 +++++++++++-- examples/rls/ent/client.go | 13 +++++++++++-- examples/start/ent/client.go | 13 +++++++++++-- examples/traversal/ent/client.go | 13 +++++++++++-- examples/triggers/ent/client.go | 13 +++++++++++-- examples/version/ent/client.go | 13 +++++++++++-- examples/viewcomposite/ent/client.go | 13 +++++++++++-- examples/viewschema/ent/client.go | 13 +++++++++++-- 29 files changed, 329 insertions(+), 56 deletions(-) diff --git a/examples/compositetypes/ent/client.go b/examples/compositetypes/ent/client.go index fb5d416157..6efaac3f20 100644 --- a/examples/compositetypes/ent/client.go +++ b/examples/compositetypes/ent/client.go @@ -14,6 +14,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/compositetypes/ent/user" ) @@ -99,8 +100,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/domaintypes/ent/client.go b/examples/domaintypes/ent/client.go index 205c437fad..5f9a38bb02 100644 --- a/examples/domaintypes/ent/client.go +++ b/examples/domaintypes/ent/client.go @@ -14,6 +14,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/domaintypes/ent/user" ) @@ -99,8 +100,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/edgeindex/ent/client.go b/examples/edgeindex/ent/client.go index d076f8201d..14decdaa89 100644 --- a/examples/edgeindex/ent/client.go +++ b/examples/edgeindex/ent/client.go @@ -19,6 +19,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/edgeindex/ent/city" "entgo.io/ent/examples/edgeindex/ent/street" ) @@ -108,8 +109,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/encryptfield/ent/client.go b/examples/encryptfield/ent/client.go index 0d9cfbde4c..858ec80a64 100644 --- a/examples/encryptfield/ent/client.go +++ b/examples/encryptfield/ent/client.go @@ -18,6 +18,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/encryptfield/ent/user" "gocloud.dev/secrets" ) @@ -112,8 +113,16 @@ func SecretsKeeper(v *secrets.Keeper) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/entcpkg/ent/client.go b/examples/entcpkg/ent/client.go index dfde64daa0..166e4a68e8 100644 --- a/examples/entcpkg/ent/client.go +++ b/examples/entcpkg/ent/client.go @@ -21,6 +21,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/entcpkg/ent/user" ) @@ -122,8 +123,16 @@ func Writer(v io.Writer) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/enumtypes/ent/client.go b/examples/enumtypes/ent/client.go index 0b08f4cfc8..ffdd2ec8c0 100644 --- a/examples/enumtypes/ent/client.go +++ b/examples/enumtypes/ent/client.go @@ -14,6 +14,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/enumtypes/ent/user" ) @@ -99,8 +100,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/extensions/ent/client.go b/examples/extensions/ent/client.go index b02d53c6ec..698414bc64 100644 --- a/examples/extensions/ent/client.go +++ b/examples/extensions/ent/client.go @@ -14,6 +14,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/extensions/ent/user" ) @@ -99,8 +100,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/fs/ent/client.go b/examples/fs/ent/client.go index 31c33c4669..9dd4076549 100644 --- a/examples/fs/ent/client.go +++ b/examples/fs/ent/client.go @@ -19,6 +19,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/fs/ent/file" ) @@ -104,8 +105,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/functionalidx/ent/client.go b/examples/functionalidx/ent/client.go index 678aa3dfb7..a09fe0c34b 100644 --- a/examples/functionalidx/ent/client.go +++ b/examples/functionalidx/ent/client.go @@ -14,6 +14,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/functionalidx/ent/user" ) @@ -99,8 +100,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/go.sum b/examples/go.sum index 57411018ba..6a309769b5 100644 --- a/examples/go.sum +++ b/examples/go.sum @@ -809,6 +809,8 @@ github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5Kwzbycv github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= github.com/fatih/color v1.10.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= +github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= +github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/felixge/httpsnoop v1.0.2/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/felixge/httpsnoop v1.0.3/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= @@ -1321,6 +1323,8 @@ github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= @@ -1330,7 +1334,11 @@ github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcME github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= +github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= +github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-shellwords v1.0.3/go.mod h1:3xCvwCdWdlDJUrvuMn7Wuy9eWs4pE8vqg+NOMyg4B2o= github.com/mattn/go-shellwords v1.0.6/go.mod h1:3xCvwCdWdlDJUrvuMn7Wuy9eWs4pE8vqg+NOMyg4B2o= github.com/mattn/go-shellwords v1.0.12/go.mod h1:EZzvwXDESEeg03EKmM+RmDnNOPKG4lLtQsUlTZDWQ8Y= @@ -1407,7 +1415,13 @@ github.com/oklog/oklog v0.3.2/go.mod h1:FCV+B7mhrz4o+ueLpx+KqkyXRGMWOYEvfiXtdGtb github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= github.com/oklog/run v1.1.0/go.mod h1:sVPdnTZT1zYwAJeCMu2Th4T21pA3FPOQRfWjQlk7DVU= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= +github.com/olekukonko/errors v0.0.0-20250405072817-4e6d85265da6 h1:r3FaAI0NZK3hSmtTDrBVREhKULp8oUeqLT5Eyl2mSPo= +github.com/olekukonko/errors v0.0.0-20250405072817-4e6d85265da6/go.mod h1:ppzxA5jBKcO1vIpCXQ9ZqgDh8iwODz6OXIGKU8r5m4Y= +github.com/olekukonko/ll v0.0.8 h1:sbGZ1Fx4QxJXEqL/6IG8GEFnYojUSQ45dJVwN2FH2fc= +github.com/olekukonko/ll v0.0.8/go.mod h1:En+sEW0JNETl26+K8eZ6/W4UQ7CYSrrgg/EdIYT2H8g= github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= +github.com/olekukonko/tablewriter v1.0.8 h1:f6wJzHg4QUtJdvrVPKco4QTrAylgaU0+b9br/lJxEiQ= +github.com/olekukonko/tablewriter v1.0.8/go.mod h1:H428M+HzoUXC6JU2Abj9IT9ooRmdq9CxuDmKMtrOCMs= github.com/onsi/ginkgo v0.0.0-20151202141238-7f8ab55aaf3b/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v0.0.0-20170829012221-11459a886d9c/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= @@ -1566,6 +1580,8 @@ github.com/rakyll/embedmd v0.0.0-20171029212350-c8060a0752a2/go.mod h1:7jOTMgqac github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= github.com/rekby/fixenv v0.6.1 h1:jUFiSPpajT4WY2cYuc++7Y1zWrnCxnovGCIX72PZniM= github.com/rekby/fixenv v0.6.1/go.mod h1:/b5LRc06BYJtslRtHKxsPWFT/ySpHV+rWvzTg+XWk4c= +github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.1.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= @@ -1625,11 +1641,14 @@ github.com/spf13/cobra v0.0.2-0.20171109065643-2da4a54c5cee/go.mod h1:1l0Ry5zgKv github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v1.0.0/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHNrgE= github.com/spf13/cobra v1.1.3/go.mod h1:pGADOWyqRD/YMrPZigI/zbliZ2wVD/23d+is3pSWzOo= +github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= +github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/pflag v0.0.0-20170130214245-9ff6c6923cff/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.1-0.20171106142849-4c012f6dcd95/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE= github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= @@ -2319,6 +2338,8 @@ golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.2.0/go.mod h1:y4OqIKeOV/fWJetJ8bXPU1sEVniLMIyDAZWeHdV+NTA= +golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ= +golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ= golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/examples/jsonencode/ent/client.go b/examples/jsonencode/ent/client.go index 77ee8dfb9e..2414de9cf1 100644 --- a/examples/jsonencode/ent/client.go +++ b/examples/jsonencode/ent/client.go @@ -19,6 +19,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/jsonencode/ent/card" "entgo.io/ent/examples/jsonencode/ent/pet" "entgo.io/ent/examples/jsonencode/ent/user" @@ -112,8 +113,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/m2m2types/ent/client.go b/examples/m2m2types/ent/client.go index 9704c44664..6622a651ee 100644 --- a/examples/m2m2types/ent/client.go +++ b/examples/m2m2types/ent/client.go @@ -19,6 +19,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/m2m2types/ent/group" "entgo.io/ent/examples/m2m2types/ent/user" ) @@ -108,8 +109,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/m2mbidi/ent/client.go b/examples/m2mbidi/ent/client.go index 51bb71efca..844fa092af 100644 --- a/examples/m2mbidi/ent/client.go +++ b/examples/m2mbidi/ent/client.go @@ -19,6 +19,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/m2mbidi/ent/user" ) @@ -104,8 +105,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/m2mrecur/ent/client.go b/examples/m2mrecur/ent/client.go index 9ee17212e3..a091524684 100644 --- a/examples/m2mrecur/ent/client.go +++ b/examples/m2mrecur/ent/client.go @@ -19,6 +19,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/m2mrecur/ent/user" ) @@ -104,8 +105,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/migration/ent/client.go b/examples/migration/ent/client.go index b9391670bd..4e9a791272 100644 --- a/examples/migration/ent/client.go +++ b/examples/migration/ent/client.go @@ -20,6 +20,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/migration/ent/card" "entgo.io/ent/examples/migration/ent/payment" "entgo.io/ent/examples/migration/ent/pet" @@ -125,8 +126,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/o2m2types/ent/client.go b/examples/o2m2types/ent/client.go index fcd9f865a4..ba285138f6 100644 --- a/examples/o2m2types/ent/client.go +++ b/examples/o2m2types/ent/client.go @@ -19,6 +19,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/o2m2types/ent/pet" "entgo.io/ent/examples/o2m2types/ent/user" ) @@ -108,8 +109,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/o2mrecur/ent/client.go b/examples/o2mrecur/ent/client.go index 534ef5bc91..61e5ee76b8 100644 --- a/examples/o2mrecur/ent/client.go +++ b/examples/o2mrecur/ent/client.go @@ -19,6 +19,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/o2mrecur/ent/node" ) @@ -104,8 +105,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/o2o2types/ent/client.go b/examples/o2o2types/ent/client.go index 6c036fd847..1a229c421f 100644 --- a/examples/o2o2types/ent/client.go +++ b/examples/o2o2types/ent/client.go @@ -19,6 +19,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/o2o2types/ent/card" "entgo.io/ent/examples/o2o2types/ent/user" ) @@ -108,8 +109,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/o2obidi/ent/client.go b/examples/o2obidi/ent/client.go index 688c30f135..6481b24719 100644 --- a/examples/o2obidi/ent/client.go +++ b/examples/o2obidi/ent/client.go @@ -19,6 +19,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/o2obidi/ent/user" ) @@ -104,8 +105,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/o2orecur/ent/client.go b/examples/o2orecur/ent/client.go index da01648ece..e3bfd1e0a0 100644 --- a/examples/o2orecur/ent/client.go +++ b/examples/o2orecur/ent/client.go @@ -19,6 +19,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/o2orecur/ent/node" ) @@ -104,8 +105,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/privacyadmin/ent/client.go b/examples/privacyadmin/ent/client.go index 5d39e39555..ddf6e09ea9 100644 --- a/examples/privacyadmin/ent/client.go +++ b/examples/privacyadmin/ent/client.go @@ -18,6 +18,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/privacyadmin/ent/user" ) @@ -103,8 +104,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/privacytenant/ent/client.go b/examples/privacytenant/ent/client.go index 1cc37d7a01..3049f613d8 100644 --- a/examples/privacytenant/ent/client.go +++ b/examples/privacytenant/ent/client.go @@ -19,6 +19,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/privacytenant/ent/group" "entgo.io/ent/examples/privacytenant/ent/tenant" "entgo.io/ent/examples/privacytenant/ent/user" @@ -112,8 +113,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/rls/ent/client.go b/examples/rls/ent/client.go index 2a22d9a75c..844735ece7 100644 --- a/examples/rls/ent/client.go +++ b/examples/rls/ent/client.go @@ -14,6 +14,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/rls/ent/tenant" "entgo.io/ent/examples/rls/ent/user" ) @@ -103,8 +104,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/start/ent/client.go b/examples/start/ent/client.go index b74da8d2dd..07c0d8ded0 100644 --- a/examples/start/ent/client.go +++ b/examples/start/ent/client.go @@ -19,6 +19,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/start/ent/car" "entgo.io/ent/examples/start/ent/group" "entgo.io/ent/examples/start/ent/user" @@ -112,8 +113,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/traversal/ent/client.go b/examples/traversal/ent/client.go index bfffe379e9..61d53840eb 100644 --- a/examples/traversal/ent/client.go +++ b/examples/traversal/ent/client.go @@ -19,6 +19,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/traversal/ent/group" "entgo.io/ent/examples/traversal/ent/pet" "entgo.io/ent/examples/traversal/ent/user" @@ -112,8 +113,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/triggers/ent/client.go b/examples/triggers/ent/client.go index 0d84c8e66b..441a83a35a 100644 --- a/examples/triggers/ent/client.go +++ b/examples/triggers/ent/client.go @@ -14,6 +14,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/triggers/ent/user" "entgo.io/ent/examples/triggers/ent/userauditlog" ) @@ -103,8 +104,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/version/ent/client.go b/examples/version/ent/client.go index a7e19b5699..09d70f04f1 100644 --- a/examples/version/ent/client.go +++ b/examples/version/ent/client.go @@ -18,6 +18,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/version/ent/user" ) @@ -103,8 +104,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/viewcomposite/ent/client.go b/examples/viewcomposite/ent/client.go index 826fed061d..ff92994b59 100644 --- a/examples/viewcomposite/ent/client.go +++ b/examples/viewcomposite/ent/client.go @@ -14,6 +14,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/viewcomposite/ent/pet" "entgo.io/ent/examples/viewcomposite/ent/user" ) @@ -109,8 +110,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } diff --git a/examples/viewschema/ent/client.go b/examples/viewschema/ent/client.go index 4144b1d068..e0f2bde1d8 100644 --- a/examples/viewschema/ent/client.go +++ b/examples/viewschema/ent/client.go @@ -14,6 +14,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/ydb" "entgo.io/ent/examples/viewschema/ent/pet" "entgo.io/ent/examples/viewschema/ent/user" ) @@ -109,8 +110,16 @@ func Driver(driver dialect.Driver) Option { // 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) + case dialect.MySQL, dialect.Postgres, dialect.SQLite, dialect.YDB: + var ( + drv dialect.Driver + err error + ) + if driverName == dialect.YDB { + drv, err = ydb.Open(context.Background(), dataSourceName) + } else { + drv, err = sql.Open(driverName, dataSourceName) + } if err != nil { return nil, err } From 9785b508a39e987179136192bbc2f701e6c1ccfa Mon Sep 17 00:00:00 2001 From: danilov6083 Date: Fri, 16 Jan 2026 17:05:06 +0300 Subject: [PATCH 11/13] updated go.mod --- dialect/sql/schema/ydb.go | 14 +++++++++----- entc/integration/go.mod | 2 +- entc/integration/go.sum | 26 ++------------------------ examples/go.mod | 2 +- examples/go.sum | 25 ++----------------------- go.mod | 2 +- go.sum | 4 ++-- 7 files changed, 18 insertions(+), 57 deletions(-) diff --git a/dialect/sql/schema/ydb.go b/dialect/sql/schema/ydb.go index cc64216537..c37218ffc9 100644 --- a/dialect/sql/schema/ydb.go +++ b/dialect/sql/schema/ydb.go @@ -157,11 +157,11 @@ func (d *YDB) atTypeC(column1 *Column, column2 *schema.Column) error { case field.TypeString: typ = &schema.StringType{T: atlas.TypeUtf8} case field.TypeJSON: - typ = &schema.JSONType{T: atlas.TypeJson} + typ = &schema.JSONType{T: atlas.TypeJSON} case field.TypeTime: typ = &schema.TimeType{T: atlas.TypeTimestamp} case field.TypeUUID: - typ = &schema.UUIDType{T: atlas.TypeUuid} + typ = &schema.UUIDType{T: atlas.TypeUUID} case field.TypeEnum: err = errors.New("ydb: Enum can't be used as column data type for tables") case field.TypeOther: @@ -198,7 +198,7 @@ func (d *YDB) atUniqueC( index := schema.NewUniqueIndex(idxName).AddColumns(column2) // Add YDB-specific attribute for GLOBAL SYNC index type. - index.AddAttrs(&atlas.YDBIndexAttributes{Global: true, Sync: true}) + index.AddAttrs(&atlas.IndexAttributes{Global: true, Sync: true}) table2.AddIndexes(index) } @@ -207,7 +207,11 @@ func (d *YDB) atUniqueC( // YDB uses Serial types for auto-increment. func (d *YDB) atIncrementC(table *schema.Table, column *schema.Column) { if intType, ok := column.Type.Type.(*schema.IntegerType); ok { - column.Type.Type = atlas.SerialFromInt(intType) + serial, err := atlas.SerialFromInt(intType) + if err != nil { + panic(err) + } + column.Type.Type = serial } } @@ -232,7 +236,7 @@ func (d *YDB) atIndex( // Set YDB-specific index attributes. // By default, use GLOBAL SYNC for consistency. - idxType := &atlas.YDBIndexAttributes{Global: true, Sync: true} + idxType := &atlas.IndexAttributes{Global: true, Sync: true} // Check for annotation overrides. if index1.Annotation != nil { diff --git a/entc/integration/go.mod b/entc/integration/go.mod index 30553da709..6ac5a6f8b2 100644 --- a/entc/integration/go.mod +++ b/entc/integration/go.mod @@ -50,4 +50,4 @@ require ( gopkg.in/yaml.v3 v3.0.1 // indirect ) -replace ariga.io/atlas => github.com/LostImagin4tion/atlas v0.0.5 +replace ariga.io/atlas => github.com/LostImagin4tion/atlas v0.0.18 diff --git a/entc/integration/go.sum b/entc/integration/go.sum index 573eefc0a0..350fb9eb87 100644 --- a/entc/integration/go.sum +++ b/entc/integration/go.sum @@ -5,8 +5,8 @@ cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60= github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= -github.com/LostImagin4tion/atlas v0.0.5 h1:SoP7EqpVLCMNCWPIZovdwOQUeJcO8ZY5cDTG5VMuIQM= -github.com/LostImagin4tion/atlas v0.0.5/go.mod h1:Rco1malutATQGeWEoYFzurfzIvs+galayoZ0+Pz4als= +github.com/LostImagin4tion/atlas v0.0.18 h1:RrLLU6zEXuRZAih3slblKFZ/lPLUDZ+wrHaTrxILqrA= +github.com/LostImagin4tion/atlas v0.0.18/go.mod h1:Rco1malutATQGeWEoYFzurfzIvs+galayoZ0+Pz4als= github.com/agext/levenshtein v1.2.3 h1:YB2fHEn0UJagG8T1rrWknE3ZQzWM06O8AMAatNn7lmo= github.com/agext/levenshtein v1.2.3/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= @@ -32,8 +32,6 @@ github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1m github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1/go.mod h1:KJwIaB5Mv44NWtYuAOFCVOjcI94vtpEz2JU/D2v6IjE= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= -github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= @@ -94,12 +92,6 @@ github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0 github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/lib/pq v1.10.7 h1:p7ZhMD+KsSRozJr34udlUrhboJwWAgCg34+/ZZNvZZw= github.com/lib/pq v1.10.7/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= -github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= -github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= -github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= -github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= -github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= -github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-sqlite3 v1.14.28 h1:ThEiQrnbtumT+QMknw63Befp/ce/nUPgBPMlRFEum7A= github.com/mattn/go-sqlite3 v1.14.28/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= @@ -111,28 +103,16 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/olekukonko/errors v0.0.0-20250405072817-4e6d85265da6 h1:r3FaAI0NZK3hSmtTDrBVREhKULp8oUeqLT5Eyl2mSPo= -github.com/olekukonko/errors v0.0.0-20250405072817-4e6d85265da6/go.mod h1:ppzxA5jBKcO1vIpCXQ9ZqgDh8iwODz6OXIGKU8r5m4Y= -github.com/olekukonko/ll v0.0.8 h1:sbGZ1Fx4QxJXEqL/6IG8GEFnYojUSQ45dJVwN2FH2fc= -github.com/olekukonko/ll v0.0.8/go.mod h1:En+sEW0JNETl26+K8eZ6/W4UQ7CYSrrgg/EdIYT2H8g= -github.com/olekukonko/tablewriter v1.0.8 h1:f6wJzHg4QUtJdvrVPKco4QTrAylgaU0+b9br/lJxEiQ= -github.com/olekukonko/tablewriter v1.0.8/go.mod h1:H428M+HzoUXC6JU2Abj9IT9ooRmdq9CxuDmKMtrOCMs= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/rekby/fixenv v0.6.1 h1:jUFiSPpajT4WY2cYuc++7Y1zWrnCxnovGCIX72PZniM= github.com/rekby/fixenv v0.6.1/go.mod h1:/b5LRc06BYJtslRtHKxsPWFT/ySpHV+rWvzTg+XWk4c= -github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= -github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8= github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I= -github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= -github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= -github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= -github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= @@ -207,8 +187,6 @@ golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ= -golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= diff --git a/examples/go.mod b/examples/go.mod index e4854a48d5..88748103b7 100644 --- a/examples/go.mod +++ b/examples/go.mod @@ -50,4 +50,4 @@ require ( gopkg.in/yaml.v3 v3.0.1 // indirect ) -replace ariga.io/atlas => github.com/LostImagin4tion/atlas v0.0.5 +replace ariga.io/atlas => github.com/LostImagin4tion/atlas v0.0.18 diff --git a/examples/go.sum b/examples/go.sum index 6a309769b5..3f5bdb7f00 100644 --- a/examples/go.sum +++ b/examples/go.sum @@ -449,8 +449,8 @@ github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= github.com/GoogleCloudPlatform/cloudsql-proxy v1.33.1/go.mod h1:n3KDPrdaY2p9Nr0B1allAdjYArwIpXQcitNbsS/Qiok= github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= -github.com/LostImagin4tion/atlas v0.0.5 h1:SoP7EqpVLCMNCWPIZovdwOQUeJcO8ZY5cDTG5VMuIQM= -github.com/LostImagin4tion/atlas v0.0.5/go.mod h1:Rco1malutATQGeWEoYFzurfzIvs+galayoZ0+Pz4als= +github.com/LostImagin4tion/atlas v0.0.18 h1:RrLLU6zEXuRZAih3slblKFZ/lPLUDZ+wrHaTrxILqrA= +github.com/LostImagin4tion/atlas v0.0.18/go.mod h1:Rco1malutATQGeWEoYFzurfzIvs+galayoZ0+Pz4als= github.com/Masterminds/semver/v3 v3.1.1/go.mod h1:VPu/7SZ7ePZ3QOrcuXROw5FAcLl4a0cBrbBpGY/8hQs= github.com/Microsoft/go-winio v0.4.11/go.mod h1:VhR8bwka0BXejwEJY73c50VrPtXAaKcyvVC4A4RozmA= github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA= @@ -809,8 +809,6 @@ github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5Kwzbycv github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= github.com/fatih/color v1.10.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= -github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= -github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/felixge/httpsnoop v1.0.2/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/felixge/httpsnoop v1.0.3/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= @@ -1323,8 +1321,6 @@ github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= -github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= -github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= @@ -1334,11 +1330,7 @@ github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcME github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= -github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= -github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= -github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= -github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-shellwords v1.0.3/go.mod h1:3xCvwCdWdlDJUrvuMn7Wuy9eWs4pE8vqg+NOMyg4B2o= github.com/mattn/go-shellwords v1.0.6/go.mod h1:3xCvwCdWdlDJUrvuMn7Wuy9eWs4pE8vqg+NOMyg4B2o= github.com/mattn/go-shellwords v1.0.12/go.mod h1:EZzvwXDESEeg03EKmM+RmDnNOPKG4lLtQsUlTZDWQ8Y= @@ -1415,13 +1407,7 @@ github.com/oklog/oklog v0.3.2/go.mod h1:FCV+B7mhrz4o+ueLpx+KqkyXRGMWOYEvfiXtdGtb github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= github.com/oklog/run v1.1.0/go.mod h1:sVPdnTZT1zYwAJeCMu2Th4T21pA3FPOQRfWjQlk7DVU= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= -github.com/olekukonko/errors v0.0.0-20250405072817-4e6d85265da6 h1:r3FaAI0NZK3hSmtTDrBVREhKULp8oUeqLT5Eyl2mSPo= -github.com/olekukonko/errors v0.0.0-20250405072817-4e6d85265da6/go.mod h1:ppzxA5jBKcO1vIpCXQ9ZqgDh8iwODz6OXIGKU8r5m4Y= -github.com/olekukonko/ll v0.0.8 h1:sbGZ1Fx4QxJXEqL/6IG8GEFnYojUSQ45dJVwN2FH2fc= -github.com/olekukonko/ll v0.0.8/go.mod h1:En+sEW0JNETl26+K8eZ6/W4UQ7CYSrrgg/EdIYT2H8g= github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= -github.com/olekukonko/tablewriter v1.0.8 h1:f6wJzHg4QUtJdvrVPKco4QTrAylgaU0+b9br/lJxEiQ= -github.com/olekukonko/tablewriter v1.0.8/go.mod h1:H428M+HzoUXC6JU2Abj9IT9ooRmdq9CxuDmKMtrOCMs= github.com/onsi/ginkgo v0.0.0-20151202141238-7f8ab55aaf3b/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v0.0.0-20170829012221-11459a886d9c/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= @@ -1580,8 +1566,6 @@ github.com/rakyll/embedmd v0.0.0-20171029212350-c8060a0752a2/go.mod h1:7jOTMgqac github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= github.com/rekby/fixenv v0.6.1 h1:jUFiSPpajT4WY2cYuc++7Y1zWrnCxnovGCIX72PZniM= github.com/rekby/fixenv v0.6.1/go.mod h1:/b5LRc06BYJtslRtHKxsPWFT/ySpHV+rWvzTg+XWk4c= -github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= -github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.1.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= @@ -1641,14 +1625,11 @@ github.com/spf13/cobra v0.0.2-0.20171109065643-2da4a54c5cee/go.mod h1:1l0Ry5zgKv github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v1.0.0/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHNrgE= github.com/spf13/cobra v1.1.3/go.mod h1:pGADOWyqRD/YMrPZigI/zbliZ2wVD/23d+is3pSWzOo= -github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= -github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/pflag v0.0.0-20170130214245-9ff6c6923cff/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.1-0.20171106142849-4c012f6dcd95/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= -github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE= github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= @@ -2338,8 +2319,6 @@ golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.2.0/go.mod h1:y4OqIKeOV/fWJetJ8bXPU1sEVniLMIyDAZWeHdV+NTA= -golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ= -golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ= golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/go.mod b/go.mod index e0ffb11189..b5843804c1 100644 --- a/go.mod +++ b/go.mod @@ -64,4 +64,4 @@ require ( gopkg.in/yaml.v3 v3.0.1 // indirect ) -replace ariga.io/atlas => github.com/LostImagin4tion/atlas v0.0.5 +replace ariga.io/atlas => github.com/LostImagin4tion/atlas v0.0.18 diff --git a/go.sum b/go.sum index 2d89673ef4..6a778248bb 100644 --- a/go.sum +++ b/go.sum @@ -3,8 +3,8 @@ cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60= github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= -github.com/LostImagin4tion/atlas v0.0.5 h1:SoP7EqpVLCMNCWPIZovdwOQUeJcO8ZY5cDTG5VMuIQM= -github.com/LostImagin4tion/atlas v0.0.5/go.mod h1:Rco1malutATQGeWEoYFzurfzIvs+galayoZ0+Pz4als= +github.com/LostImagin4tion/atlas v0.0.18 h1:RrLLU6zEXuRZAih3slblKFZ/lPLUDZ+wrHaTrxILqrA= +github.com/LostImagin4tion/atlas v0.0.18/go.mod h1:Rco1malutATQGeWEoYFzurfzIvs+galayoZ0+Pz4als= github.com/agext/levenshtein v1.2.3 h1:YB2fHEn0UJagG8T1rrWknE3ZQzWM06O8AMAatNn7lmo= github.com/agext/levenshtein v1.2.3/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= From 0067fbf2248765349626ccaf397ead3656147789 Mon Sep 17 00:00:00 2001 From: danilov6083 Date: Sun, 18 Jan 2026 18:30:21 +0300 Subject: [PATCH 12/13] dialect/ydb: a little refactoring --- dialect/ydb/retry.go | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/dialect/ydb/retry.go b/dialect/ydb/retry.go index efe1a67f94..1306c15d43 100644 --- a/dialect/ydb/retry.go +++ b/dialect/ydb/retry.go @@ -23,10 +23,10 @@ func NewRetryExecutor(db *sql.DB) *RetryExecutor { return &RetryExecutor{db: db} } -// DoTx executes the operation within a transaction with retry support. -// It uses ydb-go-sdk's retry.DoTx which handles YDB-specific retryable errors. +// Do executes a read-only operation with retry support. +// It uses ydb-go-sdk's retry.Do which handles YDB-specific retryable errors. // Options should be created using retry.WithIdempotent(), retry.WithLabel(), etc. -func (r *RetryExecutor) DoTx( +func (r *RetryExecutor) Do( ctx context.Context, fn func(ctx context.Context, drv dialect.Driver) error, opts ...any, @@ -38,20 +38,20 @@ func (r *RetryExecutor) DoTx( } } - return retry.DoTx( + return retry.Do( ctx, r.db, - func(ctx context.Context, tx *sql.Tx) error { - return fn(ctx, NewTxRetryDriver(tx)) + func(ctx context.Context, conn *sql.Conn) error { + return fn(ctx, NewRetryDriver(conn)) }, - retry.WithDoTxRetryOptions(retryOpts...), + retry.WithDoRetryOptions(retryOpts...), ) } -// Do executes a read-only operation with retry support. -// It uses ydb-go-sdk's retry.Do which handles YDB-specific retryable errors. +// DoTx executes the operation within a transaction with retry support. +// It uses ydb-go-sdk's retry.DoTx which handles YDB-specific retryable errors. // Options should be created using retry.WithIdempotent(), retry.WithLabel(), etc. -func (r *RetryExecutor) Do( +func (r *RetryExecutor) DoTx( ctx context.Context, fn func(ctx context.Context, drv dialect.Driver) error, opts ...any, @@ -63,13 +63,13 @@ func (r *RetryExecutor) Do( } } - return retry.Do( + return retry.DoTx( ctx, r.db, - func(ctx context.Context, conn *sql.Conn) error { - return fn(ctx, NewRetryDriver(conn)) + func(ctx context.Context, tx *sql.Tx) error { + return fn(ctx, NewTxRetryDriver(tx)) }, - retry.WithDoRetryOptions(retryOpts...), + retry.WithDoTxRetryOptions(retryOpts...), ) } @@ -102,7 +102,7 @@ func (d *RetryDriver) Tx(ctx context.Context) (dialect.Tx, error) { return dialect.NopTx(d), nil } -// Close is a no-op for TxDriver since retry.DoTx manages the transaction lifecycle. +// Close is a no-op for RetryDriver since retry.DoTx manages the transaction lifecycle. func (d *RetryDriver) Close() error { return nil } From 85cf6768ac2d06c33933b535a54932fed269810c Mon Sep 17 00:00:00 2001 From: danilov6083 Date: Tue, 20 Jan 2026 00:17:55 +0300 Subject: [PATCH 13/13] fixed lint --- dialect/sql/sqlgraph/graph.go | 12 +++++++----- dialect/ydb/retry.go | 29 +++++++++++++---------------- 2 files changed, 20 insertions(+), 21 deletions(-) diff --git a/dialect/sql/sqlgraph/graph.go b/dialect/sql/sqlgraph/graph.go index ca049cce04..6cb9d04a1c 100644 --- a/dialect/sql/sqlgraph/graph.go +++ b/dialect/sql/sqlgraph/graph.go @@ -791,10 +791,7 @@ func CreateNode(ctx context.Context, drv dialect.Driver, spec *CreateSpec) error cr := &creator{CreateSpec: spec, graph: gr} return cr.node(ctx, d) } - if retry := getRetryExecutor(drv); retry != nil { - return retry.DoTx(ctx, op, spec.RetryConfig.Options...) - } - return op(ctx, drv) + return execWithRetryTx(ctx, drv, op, spec.RetryConfig.Options) } // BatchCreate applies the BatchCreateSpec on the graph. @@ -804,8 +801,13 @@ func BatchCreate(ctx context.Context, drv dialect.Driver, spec *BatchCreateSpec) cr := &batchCreator{BatchCreateSpec: spec, graph: gr} return cr.nodes(ctx, d) } + return execWithRetryTx(ctx, drv, op, spec.RetryConfig.Options) +} + +// execWithRetryTx executes the operation with retry if available, otherwise executes directly. +func execWithRetryTx(ctx context.Context, drv dialect.Driver, op func(context.Context, dialect.Driver) error, opts []any) error { if retry := getRetryExecutor(drv); retry != nil { - return retry.DoTx(ctx, op, spec.RetryConfig.Options...) + return retry.DoTx(ctx, op, opts...) } return op(ctx, drv) } diff --git a/dialect/ydb/retry.go b/dialect/ydb/retry.go index 1306c15d43..dc0dde85e0 100644 --- a/dialect/ydb/retry.go +++ b/dialect/ydb/retry.go @@ -31,20 +31,13 @@ func (r *RetryExecutor) Do( fn func(ctx context.Context, drv dialect.Driver) error, opts ...any, ) error { - retryOpts := make([]retry.Option, 0, len(opts)) - for _, opt := range opts { - if ro, ok := opt.(retry.Option); ok { - retryOpts = append(retryOpts, ro) - } - } - return retry.Do( ctx, r.db, func(ctx context.Context, conn *sql.Conn) error { return fn(ctx, NewRetryDriver(conn)) }, - retry.WithDoRetryOptions(retryOpts...), + retry.WithDoRetryOptions(toRetryOptions(opts)...), ) } @@ -56,23 +49,27 @@ func (r *RetryExecutor) DoTx( fn func(ctx context.Context, drv dialect.Driver) error, opts ...any, ) error { - retryOpts := make([]retry.Option, 0, len(opts)) - for _, opt := range opts { - if ro, ok := opt.(retry.Option); ok { - retryOpts = append(retryOpts, ro) - } - } - return retry.DoTx( ctx, r.db, func(ctx context.Context, tx *sql.Tx) error { return fn(ctx, NewTxRetryDriver(tx)) }, - retry.WithDoTxRetryOptions(retryOpts...), + retry.WithDoTxRetryOptions(toRetryOptions(opts)...), ) } +// toRetryOptions converts a slice of any options to retry.Option slice +func toRetryOptions(opts []any) []retry.Option { + retryOpts := make([]retry.Option, 0, len(opts)) + for _, opt := range opts { + if ro, ok := opt.(retry.Option); ok { + retryOpts = append(retryOpts, ro) + } + } + return retryOpts +} + // RetryDriver is designed for use only in sqlgraph, // specifically - in retry.DoTx callbacks type RetryDriver struct {