snapshot of https://github.com/ent/ent.git (master, 2026-09-15; blobs > 131072B omitted)
This commit is contained in:
377
examples/o2orecur/ent/client.go
Normal file
377
examples/o2orecur/ent/client.go
Normal file
@@ -0,0 +1,377 @@
|
||||
// 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/o2orecur/ent/migrate"
|
||||
|
||||
"entgo.io/ent/dialect"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/o2orecur/ent/node"
|
||||
)
|
||||
|
||||
// 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
|
||||
// Node is the client for interacting with the Node builders.
|
||||
Node *NodeClient
|
||||
}
|
||||
|
||||
// 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.Node = NewNodeClient(c.config)
|
||||
}
|
||||
|
||||
type (
|
||||
// config is the configuration for the client and its builder.
|
||||
config struct {
|
||||
// driver used for executing database requests.
|
||||
driver dialect.Driver
|
||||
// debug enable a debug logging.
|
||||
debug bool
|
||||
// log used for logging on debug mode.
|
||||
log func(...any)
|
||||
// hooks to execute on mutations.
|
||||
hooks *hooks
|
||||
// interceptors to execute on queries.
|
||||
inters *inters
|
||||
}
|
||||
// Option function to configure the client.
|
||||
Option func(*config)
|
||||
)
|
||||
|
||||
// newConfig creates a new config for the client.
|
||||
func newConfig(opts ...Option) config {
|
||||
cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}}
|
||||
cfg.options(opts...)
|
||||
return cfg
|
||||
}
|
||||
|
||||
// options applies the options on the config object.
|
||||
func (c *config) options(opts ...Option) {
|
||||
for _, opt := range opts {
|
||||
opt(c)
|
||||
}
|
||||
if c.debug {
|
||||
c.driver = dialect.Debug(c.driver, c.log)
|
||||
}
|
||||
}
|
||||
|
||||
// Debug enables debug logging on the ent.Driver.
|
||||
func Debug() Option {
|
||||
return func(c *config) {
|
||||
c.debug = true
|
||||
}
|
||||
}
|
||||
|
||||
// Log sets the logging function for debug mode.
|
||||
func Log(fn func(...any)) Option {
|
||||
return func(c *config) {
|
||||
c.log = fn
|
||||
}
|
||||
}
|
||||
|
||||
// Driver configures the client driver.
|
||||
func Driver(driver dialect.Driver) Option {
|
||||
return func(c *config) {
|
||||
c.driver = driver
|
||||
}
|
||||
}
|
||||
|
||||
// Open opens a database/sql.DB specified by the driver name and
|
||||
// the data source name, and returns a new client attached to it.
|
||||
// Optional parameters can be added for configuring the client.
|
||||
func Open(driverName, dataSourceName string, options ...Option) (*Client, error) {
|
||||
switch driverName {
|
||||
case dialect.MySQL, dialect.Postgres, dialect.SQLite:
|
||||
drv, err := sql.Open(driverName, dataSourceName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewClient(append(options, Driver(drv))...), nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported driver: %q", driverName)
|
||||
}
|
||||
}
|
||||
|
||||
// ErrTxStarted is returned when trying to start a new transaction from a transactional client.
|
||||
var ErrTxStarted = errors.New("ent: cannot start a transaction within a transaction")
|
||||
|
||||
// Tx returns a new transactional client. The provided context
|
||||
// is used until the transaction is committed or rolled back.
|
||||
func (c *Client) Tx(ctx context.Context) (*Tx, error) {
|
||||
if _, ok := c.driver.(*txDriver); ok {
|
||||
return nil, ErrTxStarted
|
||||
}
|
||||
tx, err := newTx(ctx, c.driver)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
|
||||
}
|
||||
cfg := c.config
|
||||
cfg.driver = tx
|
||||
return &Tx{
|
||||
ctx: ctx,
|
||||
config: cfg,
|
||||
Node: NewNodeClient(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,
|
||||
Node: NewNodeClient(cfg),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
|
||||
//
|
||||
// client.Debug().
|
||||
// Node.
|
||||
// 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.Node.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.Node.Intercept(interceptors...)
|
||||
}
|
||||
|
||||
// Mutate implements the ent.Mutator interface.
|
||||
func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
|
||||
switch m := m.(type) {
|
||||
case *NodeMutation:
|
||||
return c.Node.mutate(ctx, m)
|
||||
default:
|
||||
return nil, fmt.Errorf("ent: unknown mutation type %T", m)
|
||||
}
|
||||
}
|
||||
|
||||
// NodeClient is a client for the Node schema.
|
||||
type NodeClient struct {
|
||||
config
|
||||
}
|
||||
|
||||
// NewNodeClient returns a client for the Node from the given config.
|
||||
func NewNodeClient(c config) *NodeClient {
|
||||
return &NodeClient{config: c}
|
||||
}
|
||||
|
||||
// Use adds a list of mutation hooks to the hooks stack.
|
||||
// A call to `Use(f, g, h)` equals to `node.Hooks(f(g(h())))`.
|
||||
func (c *NodeClient) Use(hooks ...Hook) {
|
||||
c.hooks.Node = append(c.hooks.Node, hooks...)
|
||||
}
|
||||
|
||||
// Intercept adds a list of query interceptors to the interceptors stack.
|
||||
// A call to `Intercept(f, g, h)` equals to `node.Intercept(f(g(h())))`.
|
||||
func (c *NodeClient) Intercept(interceptors ...Interceptor) {
|
||||
c.inters.Node = append(c.inters.Node, interceptors...)
|
||||
}
|
||||
|
||||
// Create returns a builder for creating a Node entity.
|
||||
func (c *NodeClient) Create() *NodeCreate {
|
||||
mutation := newNodeMutation(c.config, OpCreate)
|
||||
return &NodeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// CreateBulk returns a builder for creating a bulk of Node entities.
|
||||
func (c *NodeClient) CreateBulk(builders ...*NodeCreate) *NodeCreateBulk {
|
||||
return &NodeCreateBulk{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 *NodeClient) MapCreateBulk(slice any, setFunc func(*NodeCreate, int)) *NodeCreateBulk {
|
||||
rv := reflect.ValueOf(slice)
|
||||
if rv.Kind() != reflect.Slice {
|
||||
return &NodeCreateBulk{err: fmt.Errorf("calling to NodeClient.MapCreateBulk with wrong type %T, need slice", slice)}
|
||||
}
|
||||
builders := make([]*NodeCreate, rv.Len())
|
||||
for i := 0; i < rv.Len(); i++ {
|
||||
builders[i] = c.Create()
|
||||
setFunc(builders[i], i)
|
||||
}
|
||||
return &NodeCreateBulk{config: c.config, builders: builders}
|
||||
}
|
||||
|
||||
// Update returns an update builder for Node.
|
||||
func (c *NodeClient) Update() *NodeUpdate {
|
||||
mutation := newNodeMutation(c.config, OpUpdate)
|
||||
return &NodeUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// UpdateOne returns an update builder for the given entity.
|
||||
func (c *NodeClient) UpdateOne(_m *Node) *NodeUpdateOne {
|
||||
mutation := newNodeMutation(c.config, OpUpdateOne, withNode(_m))
|
||||
return &NodeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// UpdateOneID returns an update builder for the given id.
|
||||
func (c *NodeClient) UpdateOneID(id int) *NodeUpdateOne {
|
||||
mutation := newNodeMutation(c.config, OpUpdateOne, withNodeID(id))
|
||||
return &NodeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// Delete returns a delete builder for Node.
|
||||
func (c *NodeClient) Delete() *NodeDelete {
|
||||
mutation := newNodeMutation(c.config, OpDelete)
|
||||
return &NodeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// DeleteOne returns a builder for deleting the given entity.
|
||||
func (c *NodeClient) DeleteOne(_m *Node) *NodeDeleteOne {
|
||||
return c.DeleteOneID(_m.ID)
|
||||
}
|
||||
|
||||
// DeleteOneID returns a builder for deleting the given entity by its id.
|
||||
func (c *NodeClient) DeleteOneID(id int) *NodeDeleteOne {
|
||||
builder := c.Delete().Where(node.ID(id))
|
||||
builder.mutation.id = &id
|
||||
builder.mutation.SetOp(OpDeleteOne)
|
||||
return &NodeDeleteOne{builder}
|
||||
}
|
||||
|
||||
// Query returns a query builder for Node.
|
||||
func (c *NodeClient) Query() *NodeQuery {
|
||||
return &NodeQuery{
|
||||
config: c.config,
|
||||
ctx: &QueryContext{Type: TypeNode},
|
||||
inters: c.Interceptors(),
|
||||
}
|
||||
}
|
||||
|
||||
// Get returns a Node entity by its id.
|
||||
func (c *NodeClient) Get(ctx context.Context, id int) (*Node, error) {
|
||||
return c.Query().Where(node.ID(id)).Only(ctx)
|
||||
}
|
||||
|
||||
// GetX is like Get, but panics if an error occurs.
|
||||
func (c *NodeClient) GetX(ctx context.Context, id int) *Node {
|
||||
obj, err := c.Get(ctx, id)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return obj
|
||||
}
|
||||
|
||||
// QueryPrev queries the prev edge of a Node.
|
||||
func (c *NodeClient) QueryPrev(_m *Node) *NodeQuery {
|
||||
query := (&NodeClient{config: c.config}).Query()
|
||||
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
|
||||
id := _m.ID
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(node.Table, node.FieldID, id),
|
||||
sqlgraph.To(node.Table, node.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2O, true, node.PrevTable, node.PrevColumn),
|
||||
)
|
||||
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
|
||||
return fromV, nil
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// QueryNext queries the next edge of a Node.
|
||||
func (c *NodeClient) QueryNext(_m *Node) *NodeQuery {
|
||||
query := (&NodeClient{config: c.config}).Query()
|
||||
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
|
||||
id := _m.ID
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(node.Table, node.FieldID, id),
|
||||
sqlgraph.To(node.Table, node.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2O, false, node.NextTable, node.NextColumn),
|
||||
)
|
||||
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
|
||||
return fromV, nil
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// Hooks returns the client hooks.
|
||||
func (c *NodeClient) Hooks() []Hook {
|
||||
return c.hooks.Node
|
||||
}
|
||||
|
||||
// Interceptors returns the client interceptors.
|
||||
func (c *NodeClient) Interceptors() []Interceptor {
|
||||
return c.inters.Node
|
||||
}
|
||||
|
||||
func (c *NodeClient) mutate(ctx context.Context, m *NodeMutation) (Value, error) {
|
||||
switch m.Op() {
|
||||
case OpCreate:
|
||||
return (&NodeCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
|
||||
case OpUpdate:
|
||||
return (&NodeUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
|
||||
case OpUpdateOne:
|
||||
return (&NodeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
|
||||
case OpDelete, OpDeleteOne:
|
||||
return (&NodeDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
|
||||
default:
|
||||
return nil, fmt.Errorf("ent: unknown Node mutation op: %q", m.Op())
|
||||
}
|
||||
}
|
||||
|
||||
// hooks and interceptors per client, for fast access.
|
||||
type (
|
||||
hooks struct {
|
||||
Node []ent.Hook
|
||||
}
|
||||
inters struct {
|
||||
Node []ent.Interceptor
|
||||
}
|
||||
)
|
||||
612
examples/o2orecur/ent/ent.go
Normal file
612
examples/o2orecur/ent/ent.go
Normal file
@@ -0,0 +1,612 @@
|
||||
// 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/o2orecur/ent/node"
|
||||
)
|
||||
|
||||
// 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{
|
||||
node.Table: node.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)
|
||||
88
examples/o2orecur/ent/enttest/enttest.go
Normal file
88
examples/o2orecur/ent/enttest/enttest.go
Normal file
@@ -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/o2orecur/ent"
|
||||
// required by schema hooks.
|
||||
_ "entgo.io/ent/examples/o2orecur/ent/runtime"
|
||||
|
||||
"entgo.io/ent/dialect/sql/schema"
|
||||
"entgo.io/ent/examples/o2orecur/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()
|
||||
}
|
||||
}
|
||||
7
examples/o2orecur/ent/generate.go
Normal file
7
examples/o2orecur/ent/generate.go
Normal file
@@ -0,0 +1,7 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
package ent
|
||||
|
||||
//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate --header "// Copyright 2019-present Facebook Inc. All rights reserved.\n// This source code is licensed under the Apache 2.0 license found\n// in the LICENSE file in the root directory of this source tree.\n\n// Code generated by ent, DO NOT EDIT." ./schema
|
||||
203
examples/o2orecur/ent/hook/hook.go
Normal file
203
examples/o2orecur/ent/hook/hook.go
Normal file
@@ -0,0 +1,203 @@
|
||||
// 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/o2orecur/ent"
|
||||
)
|
||||
|
||||
// The NodeFunc type is an adapter to allow the use of ordinary
|
||||
// function as Node mutator.
|
||||
type NodeFunc func(context.Context, *ent.NodeMutation) (ent.Value, error)
|
||||
|
||||
// Mutate calls f(ctx, m).
|
||||
func (f NodeFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
|
||||
if mv, ok := m.(*ent.NodeMutation); ok {
|
||||
return f(ctx, mv)
|
||||
}
|
||||
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.NodeMutation", 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...)
|
||||
}
|
||||
68
examples/o2orecur/ent/migrate/migrate.go
Normal file
68
examples/o2orecur/ent/migrate/migrate.go
Normal file
@@ -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...)
|
||||
}
|
||||
43
examples/o2orecur/ent/migrate/schema.go
Normal file
43
examples/o2orecur/ent/migrate/schema.go
Normal file
@@ -0,0 +1,43 @@
|
||||
// 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/sql/schema"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
var (
|
||||
// NodesColumns holds the columns for the "nodes" table.
|
||||
NodesColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeInt, Increment: true},
|
||||
{Name: "value", Type: field.TypeInt},
|
||||
{Name: "prev_id", Type: field.TypeInt, Unique: true, Nullable: true},
|
||||
}
|
||||
// NodesTable holds the schema information for the "nodes" table.
|
||||
NodesTable = &schema.Table{
|
||||
Name: "nodes",
|
||||
Columns: NodesColumns,
|
||||
PrimaryKey: []*schema.Column{NodesColumns[0]},
|
||||
ForeignKeys: []*schema.ForeignKey{
|
||||
{
|
||||
Symbol: "nodes_nodes_next",
|
||||
Columns: []*schema.Column{NodesColumns[2]},
|
||||
RefColumns: []*schema.Column{NodesColumns[0]},
|
||||
OnDelete: schema.SetNull,
|
||||
},
|
||||
},
|
||||
}
|
||||
// Tables holds all the tables in the schema.
|
||||
Tables = []*schema.Table{
|
||||
NodesTable,
|
||||
}
|
||||
)
|
||||
|
||||
func init() {
|
||||
NodesTable.ForeignKeys[0].RefTable = NodesTable
|
||||
}
|
||||
181
examples/o2orecur/ent/mutation.go
Normal file
181
examples/o2orecur/ent/mutation.go
Normal file
@@ -0,0 +1,181 @@
|
||||
// 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"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/examples/o2orecur/ent/node"
|
||||
)
|
||||
|
||||
const (
|
||||
// Operation types.
|
||||
OpCreate = ent.OpCreate
|
||||
OpDelete = ent.OpDelete
|
||||
OpDeleteOne = ent.OpDeleteOne
|
||||
OpUpdate = ent.OpUpdate
|
||||
OpUpdateOne = ent.OpUpdateOne
|
||||
|
||||
// Node types.
|
||||
TypeNode = "Node"
|
||||
)
|
||||
|
||||
// NodeMutation represents an operation that mutates the Node nodes in the graph.
|
||||
type NodeMutation struct {
|
||||
node.Mutation
|
||||
config
|
||||
id *int
|
||||
done bool
|
||||
oldValue func(context.Context) (*Node, error)
|
||||
}
|
||||
|
||||
var _ ent.Mutation = (*NodeMutation)(nil)
|
||||
|
||||
// nodeOption allows management of the mutation configuration using functional options.
|
||||
type nodeOption func(*NodeMutation)
|
||||
|
||||
// newNodeMutation creates new mutation for the Node entity.
|
||||
func newNodeMutation(c config, op Op, opts ...nodeOption) *NodeMutation {
|
||||
m := &NodeMutation{
|
||||
Mutation: *node.NewMutation(op),
|
||||
config: c,
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(m)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// ID returns the ID value in the mutation. Note that the ID is only available
|
||||
// if it was provided to the builder or after it was returned from the database.
|
||||
func (m *NodeMutation) ID() (id int, exists bool) {
|
||||
if m.id == nil {
|
||||
return
|
||||
}
|
||||
return *m.id, true
|
||||
}
|
||||
|
||||
// withNodeID sets the ID field of the mutation.
|
||||
func withNodeID(id int) nodeOption {
|
||||
return func(m *NodeMutation) {
|
||||
var (
|
||||
err error
|
||||
once sync.Once
|
||||
value *Node
|
||||
)
|
||||
m.oldValue = func(ctx context.Context) (*Node, error) {
|
||||
once.Do(func() {
|
||||
if m.done {
|
||||
err = errors.New("querying old values post mutation is not allowed")
|
||||
} else {
|
||||
value, err = m.Client().Node.Get(ctx, id)
|
||||
}
|
||||
})
|
||||
return value, err
|
||||
}
|
||||
m.id = &id
|
||||
}
|
||||
}
|
||||
|
||||
// withNode sets the old Node of the mutation.
|
||||
func withNode(node *Node) nodeOption {
|
||||
return func(m *NodeMutation) {
|
||||
m.oldValue = func(context.Context) (*Node, 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 NodeMutation) 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 NodeMutation) Tx() (*Tx, error) {
|
||||
if _, ok := m.driver.(*txDriver); !ok {
|
||||
return nil, errors.New("ent: mutation is not running in a transaction")
|
||||
}
|
||||
tx := &Tx{config: m.config}
|
||||
tx.init()
|
||||
return tx, nil
|
||||
}
|
||||
|
||||
// IDs queries the database and returns the entity ids that match the mutation's predicate.
|
||||
// That means, if the mutation is applied within a transaction with an isolation level such
|
||||
// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated
|
||||
// or updated by the mutation.
|
||||
func (m *NodeMutation) IDs(ctx context.Context) ([]int, error) {
|
||||
switch {
|
||||
case m.Op().Is(OpUpdateOne | OpDeleteOne):
|
||||
id, exists := m.ID()
|
||||
if exists {
|
||||
return []int{id}, nil
|
||||
}
|
||||
fallthrough
|
||||
case m.Op().Is(OpUpdate | OpDelete):
|
||||
return m.Client().Node.Query().Where(m.Predicates()...).IDs(ctx)
|
||||
default:
|
||||
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.Op())
|
||||
}
|
||||
}
|
||||
|
||||
// OldValue returns the old "value" field's value of the Node entity.
|
||||
// If the Node 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 *NodeMutation) OldValue(ctx context.Context) (v int, err error) {
|
||||
if !m.Op().Is(OpUpdateOne) {
|
||||
return v, errors.New("OldValue is only allowed on UpdateOne operations")
|
||||
}
|
||||
if _, exists := m.ID(); !exists || m.oldValue == nil {
|
||||
return v, errors.New("OldValue requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldValue: %w", err)
|
||||
}
|
||||
return oldValue.Value, nil
|
||||
}
|
||||
|
||||
// OldPrevID returns the old "prev_id" field's value of the Node entity.
|
||||
// If the Node 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 *NodeMutation) OldPrevID(ctx context.Context) (v int, err error) {
|
||||
if !m.Op().Is(OpUpdateOne) {
|
||||
return v, errors.New("OldPrevID is only allowed on UpdateOne operations")
|
||||
}
|
||||
if _, exists := m.ID(); !exists || m.oldValue == nil {
|
||||
return v, errors.New("OldPrevID requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldPrevID: %w", err)
|
||||
}
|
||||
return oldValue.PrevID, nil
|
||||
}
|
||||
|
||||
// OldField returns the old value of the field from the database. An error is
|
||||
// returned if the mutation operation is not UpdateOne, or the query to the
|
||||
// database failed.
|
||||
func (m *NodeMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
|
||||
switch name {
|
||||
case node.FieldValue:
|
||||
return m.OldValue(ctx)
|
||||
case node.FieldPrevID:
|
||||
return m.OldPrevID(ctx)
|
||||
}
|
||||
return nil, fmt.Errorf("unknown Node field %s", name)
|
||||
}
|
||||
162
examples/o2orecur/ent/node.go
Normal file
162
examples/o2orecur/ent/node.go
Normal file
@@ -0,0 +1,162 @@
|
||||
// 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"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/examples/o2orecur/ent/node"
|
||||
)
|
||||
|
||||
// Node is the model entity for the Node schema.
|
||||
type Node struct {
|
||||
config `json:"-"`
|
||||
// ID of the ent.
|
||||
ID int `json:"id,omitempty"`
|
||||
// Value holds the value of the "value" field.
|
||||
Value int `json:"value,omitempty"`
|
||||
// PrevID holds the value of the "prev_id" field.
|
||||
PrevID int `json:"prev_id,omitempty"`
|
||||
// Edges holds the relations/edges for other nodes in the graph.
|
||||
// The values are being populated by the NodeQuery when eager-loading is set.
|
||||
Edges NodeEdges `json:"edges"`
|
||||
selectValues sql.SelectValues
|
||||
}
|
||||
|
||||
// NodeEdges holds the relations/edges for other nodes in the graph.
|
||||
type NodeEdges struct {
|
||||
// Prev holds the value of the prev edge.
|
||||
Prev *Node `json:"prev,omitempty"`
|
||||
// Next holds the value of the next edge.
|
||||
Next *Node `json:"next,omitempty"`
|
||||
// loadedTypes holds the information for reporting if a
|
||||
// type was loaded (or requested) in eager-loading or not.
|
||||
loadedTypes [2]bool
|
||||
}
|
||||
|
||||
// PrevOrErr returns the Prev value or an error if the edge
|
||||
// was not loaded in eager-loading, or loaded but was not found.
|
||||
func (e NodeEdges) PrevOrErr() (*Node, error) {
|
||||
if e.Prev != nil {
|
||||
return e.Prev, nil
|
||||
} else if e.loadedTypes[0] {
|
||||
return nil, &NotFoundError{label: node.Label}
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "prev"}
|
||||
}
|
||||
|
||||
// NextOrErr returns the Next value or an error if the edge
|
||||
// was not loaded in eager-loading, or loaded but was not found.
|
||||
func (e NodeEdges) NextOrErr() (*Node, error) {
|
||||
if e.Next != nil {
|
||||
return e.Next, nil
|
||||
} else if e.loadedTypes[1] {
|
||||
return nil, &NotFoundError{label: node.Label}
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "next"}
|
||||
}
|
||||
|
||||
// scanValues returns the types for scanning values from sql.Rows.
|
||||
func (*Node) scanValues(columns []string) ([]any, error) {
|
||||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case node.FieldID, node.FieldValue, node.FieldPrevID:
|
||||
values[i] = new(sql.NullInt64)
|
||||
default:
|
||||
values[i] = new(sql.UnknownType)
|
||||
}
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// assignValues assigns the values that were returned from sql.Rows (after scanning)
|
||||
// to the Node fields.
|
||||
func (_m *Node) 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 node.FieldID:
|
||||
value, ok := values[i].(*sql.NullInt64)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field id", value)
|
||||
}
|
||||
_m.ID = int(value.Int64)
|
||||
case node.FieldValue:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field value", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Value = int(value.Int64)
|
||||
}
|
||||
case node.FieldPrevID:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field prev_id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.PrevID = int(value.Int64)
|
||||
}
|
||||
default:
|
||||
_m.selectValues.Set(columns[i], values[i])
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetValue returns the ent.Value that was dynamically selected and assigned to the Node.
|
||||
// This includes values selected through modifiers, order, etc.
|
||||
func (_m *Node) GetValue(name string) (ent.Value, error) {
|
||||
return _m.selectValues.Get(name)
|
||||
}
|
||||
|
||||
// QueryPrev queries the "prev" edge of the Node entity.
|
||||
func (_m *Node) QueryPrev() *NodeQuery {
|
||||
return NewNodeClient(_m.config).QueryPrev(_m)
|
||||
}
|
||||
|
||||
// QueryNext queries the "next" edge of the Node entity.
|
||||
func (_m *Node) QueryNext() *NodeQuery {
|
||||
return NewNodeClient(_m.config).QueryNext(_m)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this Node.
|
||||
// Note that you need to call Node.Unwrap() before calling this method if this Node
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (_m *Node) Update() *NodeUpdateOne {
|
||||
return NewNodeClient(_m.config).UpdateOne(_m)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the Node 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 *Node) Unwrap() *Node {
|
||||
_tx, ok := _m.config.driver.(*txDriver)
|
||||
if !ok {
|
||||
panic("ent: Node is not a transactional entity")
|
||||
}
|
||||
_m.config.driver = _tx.drv
|
||||
return _m
|
||||
}
|
||||
|
||||
// String implements the fmt.Stringer.
|
||||
func (_m *Node) String() string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("Node(")
|
||||
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
|
||||
builder.WriteString("value=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.Value))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("prev_id=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.PrevID))
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// Nodes is a parsable slice of Node.
|
||||
type Nodes []*Node
|
||||
439
examples/o2orecur/ent/node/mutation.go
Normal file
439
examples/o2orecur/ent/node/mutation.go
Normal file
@@ -0,0 +1,439 @@
|
||||
// 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 node
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/examples/o2orecur/ent/predicate"
|
||||
)
|
||||
|
||||
// Mutation represents an operation that mutates the Node nodes in the graph.
|
||||
type Mutation struct {
|
||||
op ent.Op
|
||||
typ string
|
||||
value *int
|
||||
addvalue *int
|
||||
clearedFields map[string]struct{}
|
||||
prev *int
|
||||
clearedprev bool
|
||||
next *int
|
||||
clearednext bool
|
||||
predicates []predicate.Node
|
||||
}
|
||||
|
||||
// NewMutation creates a new Mutation for the Node entity.
|
||||
func NewMutation(op ent.Op) *Mutation {
|
||||
return &Mutation{
|
||||
op: op,
|
||||
typ: "Node",
|
||||
clearedFields: make(map[string]struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
// Predicates returns the list of predicates set on the mutation.
|
||||
func (m *Mutation) Predicates() []predicate.Node {
|
||||
return m.predicates
|
||||
}
|
||||
|
||||
// SetValue sets the "value" field.
|
||||
func (m *Mutation) SetValue(i int) {
|
||||
m.value = &i
|
||||
m.addvalue = nil
|
||||
}
|
||||
|
||||
// Value returns the value of the "value" field in the mutation.
|
||||
func (m *Mutation) Value() (r int, exists bool) {
|
||||
v := m.value
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// AddValue adds i to the "value" field.
|
||||
func (m *Mutation) AddValue(i int) {
|
||||
if m.addvalue != nil {
|
||||
*m.addvalue += i
|
||||
} else {
|
||||
m.addvalue = &i
|
||||
}
|
||||
}
|
||||
|
||||
// AddedValue returns the value that was added to the "value" field in this mutation.
|
||||
func (m *Mutation) AddedValue() (r int, exists bool) {
|
||||
v := m.addvalue
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetValue resets all changes to the "value" field.
|
||||
func (m *Mutation) ResetValue() {
|
||||
m.value = nil
|
||||
m.addvalue = nil
|
||||
}
|
||||
|
||||
// SetPrevID sets the "prev_id" field.
|
||||
func (m *Mutation) SetPrevID(i int) {
|
||||
m.prev = &i
|
||||
}
|
||||
|
||||
// PrevID returns the value of the "prev_id" field in the mutation.
|
||||
func (m *Mutation) PrevID() (r int, exists bool) {
|
||||
v := m.prev
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ClearPrevID clears the value of the "prev_id" field.
|
||||
func (m *Mutation) ClearPrevID() {
|
||||
m.prev = nil
|
||||
m.clearedFields[FieldPrevID] = struct{}{}
|
||||
}
|
||||
|
||||
// PrevIDCleared returns if the "prev_id" field was cleared in this mutation.
|
||||
func (m *Mutation) PrevIDCleared() bool {
|
||||
_, ok := m.clearedFields[FieldPrevID]
|
||||
return ok
|
||||
}
|
||||
|
||||
// ResetPrevID resets all changes to the "prev_id" field.
|
||||
func (m *Mutation) ResetPrevID() {
|
||||
m.prev = nil
|
||||
delete(m.clearedFields, FieldPrevID)
|
||||
}
|
||||
|
||||
// ClearPrev clears the "prev" edge to the Node entity.
|
||||
func (m *Mutation) ClearPrev() {
|
||||
m.clearedprev = true
|
||||
m.clearedFields[FieldPrevID] = struct{}{}
|
||||
}
|
||||
|
||||
// PrevCleared reports if the "prev" edge to the Node entity was cleared.
|
||||
func (m *Mutation) PrevCleared() bool {
|
||||
return m.PrevIDCleared() || m.clearedprev
|
||||
}
|
||||
|
||||
// PrevIDs returns the "prev" edge IDs in the mutation.
|
||||
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
|
||||
// PrevID instead. It exists only for internal usage by the builders.
|
||||
func (m *Mutation) PrevIDs() (ids []int) {
|
||||
if id := m.prev; id != nil {
|
||||
ids = append(ids, *id)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ResetPrev resets all changes to the "prev" edge.
|
||||
func (m *Mutation) ResetPrev() {
|
||||
m.prev = nil
|
||||
m.clearedprev = false
|
||||
}
|
||||
|
||||
// SetNextID sets the "next" edge to the Node entity by id.
|
||||
func (m *Mutation) SetNextID(id int) {
|
||||
m.next = &id
|
||||
}
|
||||
|
||||
// ClearNext clears the "next" edge to the Node entity.
|
||||
func (m *Mutation) ClearNext() {
|
||||
m.clearednext = true
|
||||
}
|
||||
|
||||
// NextCleared reports if the "next" edge to the Node entity was cleared.
|
||||
func (m *Mutation) NextCleared() bool {
|
||||
return m.clearednext
|
||||
}
|
||||
|
||||
// NextID returns the "next" edge ID in the mutation.
|
||||
func (m *Mutation) NextID() (id int, exists bool) {
|
||||
if m.next != nil {
|
||||
return *m.next, true
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// NextIDs returns the "next" edge IDs in the mutation.
|
||||
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
|
||||
// NextID instead. It exists only for internal usage by the builders.
|
||||
func (m *Mutation) NextIDs() (ids []int) {
|
||||
if id := m.next; id != nil {
|
||||
ids = append(ids, *id)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ResetNext resets all changes to the "next" edge.
|
||||
func (m *Mutation) ResetNext() {
|
||||
m.next = nil
|
||||
m.clearednext = false
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the Mutation builder.
|
||||
func (m *Mutation) Where(ps ...predicate.Node) {
|
||||
m.predicates = append(m.predicates, ps...)
|
||||
}
|
||||
|
||||
// WhereP appends storage-level predicates to the Mutation builder. Using this method,
|
||||
// users can use type-assertion to append predicates that do not depend on any generated package.
|
||||
func (m *Mutation) WhereP(ps ...func(*sql.Selector)) {
|
||||
p := make([]predicate.Node, len(ps))
|
||||
for i := range ps {
|
||||
p[i] = ps[i]
|
||||
}
|
||||
m.Where(p...)
|
||||
}
|
||||
|
||||
// Op returns the operation name.
|
||||
func (m *Mutation) Op() ent.Op {
|
||||
return m.op
|
||||
}
|
||||
|
||||
// SetOp allows setting the mutation operation.
|
||||
func (m *Mutation) SetOp(op ent.Op) {
|
||||
m.op = op
|
||||
}
|
||||
|
||||
// Type returns the node type of this mutation (Node).
|
||||
func (m *Mutation) Type() string {
|
||||
return m.typ
|
||||
}
|
||||
|
||||
// Fields returns all fields that were changed during this mutation. Note that in
|
||||
// order to get all numeric fields that were incremented/decremented, call
|
||||
// AddedFields().
|
||||
func (m *Mutation) Fields() []string {
|
||||
fields := make([]string, 0, 2)
|
||||
if m.value != nil {
|
||||
fields = append(fields, FieldValue)
|
||||
}
|
||||
if m.prev != nil {
|
||||
fields = append(fields, FieldPrevID)
|
||||
}
|
||||
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 *Mutation) Field(name string) (ent.Value, bool) {
|
||||
switch name {
|
||||
case FieldValue:
|
||||
return m.Value()
|
||||
case FieldPrevID:
|
||||
return m.PrevID()
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// OldField returns the old value of the field from the database. An error is
|
||||
// returned if the mutation operation is not UpdateOne, or the query to the
|
||||
// database failed.
|
||||
func (m *Mutation) OldField(ctx context.Context, name string) (ent.Value, error) {
|
||||
return nil, fmt.Errorf("unknown Node 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 *Mutation) SetField(name string, value ent.Value) error {
|
||||
switch name {
|
||||
case FieldValue:
|
||||
v, ok := value.(int)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetValue(v)
|
||||
return nil
|
||||
case FieldPrevID:
|
||||
v, ok := value.(int)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetPrevID(v)
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown Node field %s", name)
|
||||
}
|
||||
|
||||
// AddedFields returns all numeric fields that were incremented/decremented during
|
||||
// this mutation.
|
||||
func (m *Mutation) AddedFields() []string {
|
||||
var fields []string
|
||||
if m.addvalue != nil {
|
||||
fields = append(fields, FieldValue)
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
// AddedField returns the numeric value that was incremented/decremented on a field
|
||||
// with the given name. The second boolean return value indicates that this field
|
||||
// was not set, or was not defined in the schema.
|
||||
func (m *Mutation) AddedField(name string) (ent.Value, bool) {
|
||||
switch name {
|
||||
case FieldValue:
|
||||
return m.AddedValue()
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// AddField adds the value to the field with the given name. It returns an error if
|
||||
// the field is not defined in the schema, or if the type mismatched the field
|
||||
// type.
|
||||
func (m *Mutation) AddField(name string, value ent.Value) error {
|
||||
switch name {
|
||||
case FieldValue:
|
||||
v, ok := value.(int)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.AddValue(v)
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown Node numeric field %s", name)
|
||||
}
|
||||
|
||||
// ClearedFields returns all nullable fields that were cleared during this
|
||||
// mutation.
|
||||
func (m *Mutation) ClearedFields() []string {
|
||||
var fields []string
|
||||
if m.FieldCleared(FieldPrevID) {
|
||||
fields = append(fields, FieldPrevID)
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
// FieldCleared returns a boolean indicating if a field with the given name was
|
||||
// cleared in this mutation.
|
||||
func (m *Mutation) FieldCleared(name string) bool {
|
||||
_, ok := m.clearedFields[name]
|
||||
return ok
|
||||
}
|
||||
|
||||
// ClearField clears the value of the field with the given name. It returns an
|
||||
// error if the field is not defined in the schema.
|
||||
func (m *Mutation) ClearField(name string) error {
|
||||
switch name {
|
||||
case FieldPrevID:
|
||||
m.ClearPrevID()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown Node nullable field %s", name)
|
||||
}
|
||||
|
||||
// ResetField resets all changes in the mutation for the field with the given name.
|
||||
// It returns an error if the field is not defined in the schema.
|
||||
func (m *Mutation) ResetField(name string) error {
|
||||
switch name {
|
||||
case FieldValue:
|
||||
m.ResetValue()
|
||||
return nil
|
||||
case FieldPrevID:
|
||||
m.ResetPrevID()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown Node field %s", name)
|
||||
}
|
||||
|
||||
// AddedEdges returns all edge names that were set/added in this mutation.
|
||||
func (m *Mutation) AddedEdges() []string {
|
||||
edges := make([]string, 0, 2)
|
||||
if m.prev != nil {
|
||||
edges = append(edges, EdgePrev)
|
||||
}
|
||||
if m.next != nil {
|
||||
edges = append(edges, EdgeNext)
|
||||
}
|
||||
return edges
|
||||
}
|
||||
|
||||
// AddedIDs returns all IDs (to other nodes) that were added for the given edge
|
||||
// name in this mutation.
|
||||
func (m *Mutation) AddedIDs(name string) []ent.Value {
|
||||
switch name {
|
||||
case EdgePrev:
|
||||
if id := m.prev; id != nil {
|
||||
return []ent.Value{*id}
|
||||
}
|
||||
case EdgeNext:
|
||||
if id := m.next; id != nil {
|
||||
return []ent.Value{*id}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemovedEdges returns all edge names that were removed in this mutation.
|
||||
func (m *Mutation) RemovedEdges() []string {
|
||||
edges := make([]string, 0, 2)
|
||||
return edges
|
||||
}
|
||||
|
||||
// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
|
||||
// the given name in this mutation.
|
||||
func (m *Mutation) RemovedIDs(name string) []ent.Value {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClearedEdges returns all edge names that were cleared in this mutation.
|
||||
func (m *Mutation) ClearedEdges() []string {
|
||||
edges := make([]string, 0, 2)
|
||||
if m.clearedprev {
|
||||
edges = append(edges, EdgePrev)
|
||||
}
|
||||
if m.clearednext {
|
||||
edges = append(edges, EdgeNext)
|
||||
}
|
||||
return edges
|
||||
}
|
||||
|
||||
// EdgeCleared returns a boolean which indicates if the edge with the given name
|
||||
// was cleared in this mutation.
|
||||
func (m *Mutation) EdgeCleared(name string) bool {
|
||||
switch name {
|
||||
case EdgePrev:
|
||||
return m.clearedprev
|
||||
case EdgeNext:
|
||||
return m.clearednext
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ClearEdge clears the value of the edge with the given name. It returns an error
|
||||
// if that edge is not defined in the schema.
|
||||
func (m *Mutation) ClearEdge(name string) error {
|
||||
switch name {
|
||||
case EdgePrev:
|
||||
m.ClearPrev()
|
||||
return nil
|
||||
case EdgeNext:
|
||||
m.ClearNext()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown Node unique edge %s", name)
|
||||
}
|
||||
|
||||
// ResetEdge resets all changes to the edge with the given name in this mutation.
|
||||
// It returns an error if the edge is not defined in the schema.
|
||||
func (m *Mutation) ResetEdge(name string) error {
|
||||
switch name {
|
||||
case EdgePrev:
|
||||
m.ResetPrev()
|
||||
return nil
|
||||
case EdgeNext:
|
||||
m.ResetNext()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown Node edge %s", name)
|
||||
}
|
||||
100
examples/o2orecur/ent/node/node.go
Normal file
100
examples/o2orecur/ent/node/node.go
Normal file
@@ -0,0 +1,100 @@
|
||||
// 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 node
|
||||
|
||||
import (
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
)
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the node type in the database.
|
||||
Label = "node"
|
||||
// FieldID holds the string denoting the id field in the database.
|
||||
FieldID = "id"
|
||||
// FieldValue holds the string denoting the value field in the database.
|
||||
FieldValue = "value"
|
||||
// FieldPrevID holds the string denoting the prev_id field in the database.
|
||||
FieldPrevID = "prev_id"
|
||||
// EdgePrev holds the string denoting the prev edge name in mutations.
|
||||
EdgePrev = "prev"
|
||||
// EdgeNext holds the string denoting the next edge name in mutations.
|
||||
EdgeNext = "next"
|
||||
// Table holds the table name of the node in the database.
|
||||
Table = "nodes"
|
||||
// PrevTable is the table that holds the prev relation/edge.
|
||||
PrevTable = "nodes"
|
||||
// PrevColumn is the table column denoting the prev relation/edge.
|
||||
PrevColumn = "prev_id"
|
||||
// NextTable is the table that holds the next relation/edge.
|
||||
NextTable = "nodes"
|
||||
// NextColumn is the table column denoting the next relation/edge.
|
||||
NextColumn = "prev_id"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for node fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldValue,
|
||||
FieldPrevID,
|
||||
}
|
||||
|
||||
// ValidColumn reports if the column name is valid (part of the table columns).
|
||||
func ValidColumn(column string) bool {
|
||||
for i := range Columns {
|
||||
if column == Columns[i] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// OrderOption defines the ordering options for the Node 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()
|
||||
}
|
||||
|
||||
// ByValue orders the results by the value field.
|
||||
func ByValue(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldValue, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByPrevID orders the results by the prev_id field.
|
||||
func ByPrevID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldPrevID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByPrevField orders the results by prev field.
|
||||
func ByPrevField(field string, opts ...sql.OrderTermOption) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborTerms(s, newPrevStep(), sql.OrderByField(field, opts...))
|
||||
}
|
||||
}
|
||||
|
||||
// ByNextField orders the results by next field.
|
||||
func ByNextField(field string, opts ...sql.OrderTermOption) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborTerms(s, newNextStep(), sql.OrderByField(field, opts...))
|
||||
}
|
||||
}
|
||||
func newPrevStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2O, true, PrevTable, PrevColumn),
|
||||
)
|
||||
}
|
||||
func newNextStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2O, false, NextTable, NextColumn),
|
||||
)
|
||||
}
|
||||
199
examples/o2orecur/ent/node/where.go
Normal file
199
examples/o2orecur/ent/node/where.go
Normal file
@@ -0,0 +1,199 @@
|
||||
// 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 node
|
||||
|
||||
import (
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/o2orecur/ent/predicate"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id int) predicate.Node {
|
||||
return predicate.Node(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id int) predicate.Node {
|
||||
return predicate.Node(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id int) predicate.Node {
|
||||
return predicate.Node(sql.FieldNEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...int) predicate.Node {
|
||||
return predicate.Node(sql.FieldIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...int) predicate.Node {
|
||||
return predicate.Node(sql.FieldNotIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id int) predicate.Node {
|
||||
return predicate.Node(sql.FieldGT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id int) predicate.Node {
|
||||
return predicate.Node(sql.FieldGTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id int) predicate.Node {
|
||||
return predicate.Node(sql.FieldLT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id int) predicate.Node {
|
||||
return predicate.Node(sql.FieldLTE(FieldID, id))
|
||||
}
|
||||
|
||||
// Value applies equality check predicate on the "value" field. It's identical to ValueEQ.
|
||||
func Value(v int) predicate.Node {
|
||||
return predicate.Node(sql.FieldEQ(FieldValue, v))
|
||||
}
|
||||
|
||||
// PrevID applies equality check predicate on the "prev_id" field. It's identical to PrevIDEQ.
|
||||
func PrevID(v int) predicate.Node {
|
||||
return predicate.Node(sql.FieldEQ(FieldPrevID, v))
|
||||
}
|
||||
|
||||
// ValueEQ applies the EQ predicate on the "value" field.
|
||||
func ValueEQ(v int) predicate.Node {
|
||||
return predicate.Node(sql.FieldEQ(FieldValue, v))
|
||||
}
|
||||
|
||||
// ValueNEQ applies the NEQ predicate on the "value" field.
|
||||
func ValueNEQ(v int) predicate.Node {
|
||||
return predicate.Node(sql.FieldNEQ(FieldValue, v))
|
||||
}
|
||||
|
||||
// ValueIn applies the In predicate on the "value" field.
|
||||
func ValueIn(vs ...int) predicate.Node {
|
||||
return predicate.Node(sql.FieldIn(FieldValue, vs...))
|
||||
}
|
||||
|
||||
// ValueNotIn applies the NotIn predicate on the "value" field.
|
||||
func ValueNotIn(vs ...int) predicate.Node {
|
||||
return predicate.Node(sql.FieldNotIn(FieldValue, vs...))
|
||||
}
|
||||
|
||||
// ValueGT applies the GT predicate on the "value" field.
|
||||
func ValueGT(v int) predicate.Node {
|
||||
return predicate.Node(sql.FieldGT(FieldValue, v))
|
||||
}
|
||||
|
||||
// ValueGTE applies the GTE predicate on the "value" field.
|
||||
func ValueGTE(v int) predicate.Node {
|
||||
return predicate.Node(sql.FieldGTE(FieldValue, v))
|
||||
}
|
||||
|
||||
// ValueLT applies the LT predicate on the "value" field.
|
||||
func ValueLT(v int) predicate.Node {
|
||||
return predicate.Node(sql.FieldLT(FieldValue, v))
|
||||
}
|
||||
|
||||
// ValueLTE applies the LTE predicate on the "value" field.
|
||||
func ValueLTE(v int) predicate.Node {
|
||||
return predicate.Node(sql.FieldLTE(FieldValue, v))
|
||||
}
|
||||
|
||||
// PrevIDEQ applies the EQ predicate on the "prev_id" field.
|
||||
func PrevIDEQ(v int) predicate.Node {
|
||||
return predicate.Node(sql.FieldEQ(FieldPrevID, v))
|
||||
}
|
||||
|
||||
// PrevIDNEQ applies the NEQ predicate on the "prev_id" field.
|
||||
func PrevIDNEQ(v int) predicate.Node {
|
||||
return predicate.Node(sql.FieldNEQ(FieldPrevID, v))
|
||||
}
|
||||
|
||||
// PrevIDIn applies the In predicate on the "prev_id" field.
|
||||
func PrevIDIn(vs ...int) predicate.Node {
|
||||
return predicate.Node(sql.FieldIn(FieldPrevID, vs...))
|
||||
}
|
||||
|
||||
// PrevIDNotIn applies the NotIn predicate on the "prev_id" field.
|
||||
func PrevIDNotIn(vs ...int) predicate.Node {
|
||||
return predicate.Node(sql.FieldNotIn(FieldPrevID, vs...))
|
||||
}
|
||||
|
||||
// PrevIDIsNil applies the IsNil predicate on the "prev_id" field.
|
||||
func PrevIDIsNil() predicate.Node {
|
||||
return predicate.Node(sql.FieldIsNull(FieldPrevID))
|
||||
}
|
||||
|
||||
// PrevIDNotNil applies the NotNil predicate on the "prev_id" field.
|
||||
func PrevIDNotNil() predicate.Node {
|
||||
return predicate.Node(sql.FieldNotNull(FieldPrevID))
|
||||
}
|
||||
|
||||
// HasPrev applies the HasEdge predicate on the "prev" edge.
|
||||
func HasPrev() predicate.Node {
|
||||
return predicate.Node(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2O, true, PrevTable, PrevColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
})
|
||||
}
|
||||
|
||||
// HasPrevWith applies the HasEdge predicate on the "prev" edge with a given conditions (other predicates).
|
||||
func HasPrevWith(preds ...predicate.Node) predicate.Node {
|
||||
return predicate.Node(func(s *sql.Selector) {
|
||||
step := newPrevStep()
|
||||
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
|
||||
for _, p := range preds {
|
||||
p(s)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// HasNext applies the HasEdge predicate on the "next" edge.
|
||||
func HasNext() predicate.Node {
|
||||
return predicate.Node(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2O, false, NextTable, NextColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
})
|
||||
}
|
||||
|
||||
// HasNextWith applies the HasEdge predicate on the "next" edge with a given conditions (other predicates).
|
||||
func HasNextWith(preds ...predicate.Node) predicate.Node {
|
||||
return predicate.Node(func(s *sql.Selector) {
|
||||
step := newNextStep()
|
||||
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.Node) predicate.Node {
|
||||
return predicate.Node(sql.AndPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Or groups predicates with the OR operator between them.
|
||||
func Or(predicates ...predicate.Node) predicate.Node {
|
||||
return predicate.Node(sql.OrPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Not applies the not operator on the given predicate.
|
||||
func Not(p predicate.Node) predicate.Node {
|
||||
return predicate.Node(sql.NotPredicates(p))
|
||||
}
|
||||
258
examples/o2orecur/ent/node_create.go
Normal file
258
examples/o2orecur/ent/node_create.go
Normal file
@@ -0,0 +1,258 @@
|
||||
// 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"
|
||||
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/o2orecur/ent/node"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// NodeCreate is the builder for creating a Node entity.
|
||||
type NodeCreate struct {
|
||||
config
|
||||
mutation *NodeMutation
|
||||
hooks []Hook
|
||||
}
|
||||
|
||||
// SetValue sets the "value" field.
|
||||
func (_c *NodeCreate) SetValue(v int) *NodeCreate {
|
||||
_c.mutation.SetValue(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetPrevID sets the "prev_id" field.
|
||||
func (_c *NodeCreate) SetPrevID(v int) *NodeCreate {
|
||||
_c.mutation.SetPrevID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillablePrevID sets the "prev_id" field if the given value is not nil.
|
||||
func (_c *NodeCreate) SetNillablePrevID(v *int) *NodeCreate {
|
||||
if v != nil {
|
||||
_c.SetPrevID(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetPrev sets the "prev" edge to the Node entity.
|
||||
func (_c *NodeCreate) SetPrev(v *Node) *NodeCreate {
|
||||
return _c.SetPrevID(v.ID)
|
||||
}
|
||||
|
||||
// SetNextID sets the "next" edge to the Node entity by ID.
|
||||
func (_c *NodeCreate) SetNextID(id int) *NodeCreate {
|
||||
_c.mutation.SetNextID(id)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableNextID sets the "next" edge to the Node entity by ID if the given value is not nil.
|
||||
func (_c *NodeCreate) SetNillableNextID(id *int) *NodeCreate {
|
||||
if id != nil {
|
||||
_c = _c.SetNextID(*id)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNext sets the "next" edge to the Node entity.
|
||||
func (_c *NodeCreate) SetNext(v *Node) *NodeCreate {
|
||||
return _c.SetNextID(v.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the NodeMutation object of the builder.
|
||||
func (_c *NodeCreate) Mutation() *NodeMutation {
|
||||
return _c.mutation
|
||||
}
|
||||
|
||||
// Save creates the Node in the database.
|
||||
func (_c *NodeCreate) Save(ctx context.Context) (*Node, error) {
|
||||
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
func (_c *NodeCreate) SaveX(ctx context.Context) *Node {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *NodeCreate) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *NodeCreate) 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 *NodeCreate) check() error {
|
||||
if _, ok := _c.mutation.Value(); !ok {
|
||||
return &ValidationError{Name: "value", err: errors.New(`ent: missing required field "Node.value"`)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_c *NodeCreate) sqlSave(ctx context.Context) (*Node, error) {
|
||||
if err := _c.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_node, _spec := _c.createSpec()
|
||||
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
id := _spec.ID.Value.(int64)
|
||||
_node.ID = int(id)
|
||||
_c.mutation.id = &_node.ID
|
||||
_c.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
func (_c *NodeCreate) createSpec() (*Node, *sqlgraph.CreateSpec) {
|
||||
var (
|
||||
_node = &Node{config: _c.config}
|
||||
_spec = sqlgraph.NewCreateSpec(node.Table, sqlgraph.NewFieldSpec(node.FieldID, field.TypeInt))
|
||||
)
|
||||
if value, ok := _c.mutation.Value(); ok {
|
||||
_spec.SetField(node.FieldValue, field.TypeInt, value)
|
||||
_node.Value = value
|
||||
}
|
||||
if nodes := _c.mutation.PrevIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2O,
|
||||
Inverse: true,
|
||||
Table: node.PrevTable,
|
||||
Columns: []string{node.PrevColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(node.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_node.PrevID = nodes[0]
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
if nodes := _c.mutation.NextIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2O,
|
||||
Inverse: false,
|
||||
Table: node.NextTable,
|
||||
Columns: []string{node.NextColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(node.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
return _node, _spec
|
||||
}
|
||||
|
||||
// NodeCreateBulk is the builder for creating many Node entities in bulk.
|
||||
type NodeCreateBulk struct {
|
||||
config
|
||||
err error
|
||||
builders []*NodeCreate
|
||||
}
|
||||
|
||||
// Save creates the Node entities in the database.
|
||||
func (_c *NodeCreateBulk) Save(ctx context.Context) ([]*Node, error) {
|
||||
if _c.err != nil {
|
||||
return nil, _c.err
|
||||
}
|
||||
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
|
||||
nodes := make([]*Node, 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.(*NodeMutation)
|
||||
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}
|
||||
// Invoke the actual operation on the latest mutation in the chain.
|
||||
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mutation.id = &nodes[i].ID
|
||||
if specs[i].ID.Value != nil {
|
||||
id := specs[i].ID.Value.(int64)
|
||||
nodes[i].ID = int(id)
|
||||
}
|
||||
mutation.done = true
|
||||
return nodes[i], nil
|
||||
})
|
||||
for i := len(builder.hooks) - 1; i >= 0; i-- {
|
||||
mut = builder.hooks[i](mut)
|
||||
}
|
||||
mutators[i] = mut
|
||||
}(i, ctx)
|
||||
}
|
||||
if len(mutators) > 0 {
|
||||
if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_c *NodeCreateBulk) SaveX(ctx context.Context) []*Node {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *NodeCreateBulk) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *NodeCreateBulk) ExecX(ctx context.Context) {
|
||||
if err := _c.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
92
examples/o2orecur/ent/node_delete.go
Normal file
92
examples/o2orecur/ent/node_delete.go
Normal file
@@ -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 ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/o2orecur/ent/node"
|
||||
"entgo.io/ent/examples/o2orecur/ent/predicate"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// NodeDelete is the builder for deleting a Node entity.
|
||||
type NodeDelete struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *NodeMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the NodeDelete builder.
|
||||
func (_d *NodeDelete) Where(ps ...predicate.Node) *NodeDelete {
|
||||
_d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (_d *NodeDelete) 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 *NodeDelete) ExecX(ctx context.Context) int {
|
||||
n, err := _d.Exec(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (_d *NodeDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
_spec := sqlgraph.NewDeleteSpec(node.Table, sqlgraph.NewFieldSpec(node.FieldID, field.TypeInt))
|
||||
if ps := _d.mutation.Predicates(); len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
|
||||
if err != nil && sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
_d.mutation.done = true
|
||||
return affected, err
|
||||
}
|
||||
|
||||
// NodeDeleteOne is the builder for deleting a single Node entity.
|
||||
type NodeDeleteOne struct {
|
||||
_d *NodeDelete
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the NodeDelete builder.
|
||||
func (_d *NodeDeleteOne) Where(ps ...predicate.Node) *NodeDeleteOne {
|
||||
_d._d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (_d *NodeDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := _d._d.Exec(ctx)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case n == 0:
|
||||
return &NotFoundError{node.Label}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_d *NodeDeleteOne) ExecX(ctx context.Context) {
|
||||
if err := _d.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
679
examples/o2orecur/ent/node_query.go
Normal file
679
examples/o2orecur/ent/node_query.go
Normal file
@@ -0,0 +1,679 @@
|
||||
// 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/o2orecur/ent/node"
|
||||
"entgo.io/ent/examples/o2orecur/ent/predicate"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// 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
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
path func(context.Context) (*sql.Selector, error)
|
||||
}
|
||||
|
||||
// Where adds a new predicate for the NodeQuery builder.
|
||||
func (_q *NodeQuery) Where(ps ...predicate.Node) *NodeQuery {
|
||||
_q.predicates = append(_q.predicates, ps...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// Limit the number of records to be returned by this query.
|
||||
func (_q *NodeQuery) Limit(limit int) *NodeQuery {
|
||||
_q.ctx.Limit = &limit
|
||||
return _q
|
||||
}
|
||||
|
||||
// Offset to start from.
|
||||
func (_q *NodeQuery) Offset(offset int) *NodeQuery {
|
||||
_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 *NodeQuery) Unique(unique bool) *NodeQuery {
|
||||
_q.ctx.Unique = &unique
|
||||
return _q
|
||||
}
|
||||
|
||||
// Order specifies how the records should be ordered.
|
||||
func (_q *NodeQuery) Order(o ...node.OrderOption) *NodeQuery {
|
||||
_q.order = append(_q.order, o...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// QueryPrev chains the current query on the "prev" edge.
|
||||
func (_q *NodeQuery) QueryPrev() *NodeQuery {
|
||||
query := (&NodeClient{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(node.Table, node.FieldID, selector),
|
||||
sqlgraph.To(node.Table, node.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2O, true, node.PrevTable, node.PrevColumn),
|
||||
)
|
||||
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
|
||||
return fromU, nil
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// QueryNext chains the current query on the "next" edge.
|
||||
func (_q *NodeQuery) QueryNext() *NodeQuery {
|
||||
query := (&NodeClient{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(node.Table, node.FieldID, selector),
|
||||
sqlgraph.To(node.Table, node.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2O, false, node.NextTable, node.NextColumn),
|
||||
)
|
||||
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
|
||||
return fromU, nil
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// First returns the first Node entity from the query.
|
||||
// Returns a *NotFoundError when no Node was found.
|
||||
func (_q *NodeQuery) First(ctx context.Context) (*Node, 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{node.Label}
|
||||
}
|
||||
return nodes[0], nil
|
||||
}
|
||||
|
||||
// FirstX is like First, but panics if an error occurs.
|
||||
func (_q *NodeQuery) FirstX(ctx context.Context) *Node {
|
||||
node, err := _q.First(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// FirstID returns the first Node ID from the query.
|
||||
// Returns a *NotFoundError when no Node ID was found.
|
||||
func (_q *NodeQuery) FirstID(ctx context.Context) (id int, err error) {
|
||||
var ids []int
|
||||
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
|
||||
return
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
err = &NotFoundError{node.Label}
|
||||
return
|
||||
}
|
||||
return ids[0], nil
|
||||
}
|
||||
|
||||
// FirstIDX is like FirstID, but panics if an error occurs.
|
||||
func (_q *NodeQuery) FirstIDX(ctx context.Context) int {
|
||||
id, err := _q.FirstID(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Only returns a single Node entity found by the query, ensuring it only returns one.
|
||||
// Returns a *NotSingularError when more than one Node entity is found.
|
||||
// Returns a *NotFoundError when no Node entities are found.
|
||||
func (_q *NodeQuery) Only(ctx context.Context) (*Node, 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{node.Label}
|
||||
default:
|
||||
return nil, &NotSingularError{node.Label}
|
||||
}
|
||||
}
|
||||
|
||||
// OnlyX is like Only, but panics if an error occurs.
|
||||
func (_q *NodeQuery) OnlyX(ctx context.Context) *Node {
|
||||
node, err := _q.Only(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// OnlyID is like Only, but returns the only Node ID in the query.
|
||||
// Returns a *NotSingularError when more than one Node ID is found.
|
||||
// Returns a *NotFoundError when no entities are found.
|
||||
func (_q *NodeQuery) OnlyID(ctx context.Context) (id int, err error) {
|
||||
var ids []int
|
||||
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(ids) {
|
||||
case 1:
|
||||
id = ids[0]
|
||||
case 0:
|
||||
err = &NotFoundError{node.Label}
|
||||
default:
|
||||
err = &NotSingularError{node.Label}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// OnlyIDX is like OnlyID, but panics if an error occurs.
|
||||
func (_q *NodeQuery) OnlyIDX(ctx context.Context) int {
|
||||
id, err := _q.OnlyID(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// All executes the query and returns a list of Nodes.
|
||||
func (_q *NodeQuery) All(ctx context.Context) ([]*Node, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
|
||||
if err := _q.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qr := querierAll[[]*Node, *NodeQuery]()
|
||||
return withInterceptors[[]*Node](ctx, _q, qr, _q.inters)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
func (_q *NodeQuery) AllX(ctx context.Context) []*Node {
|
||||
nodes, err := _q.All(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
// IDs executes the query and returns a list of Node IDs.
|
||||
func (_q *NodeQuery) IDs(ctx context.Context) (ids []int, err error) {
|
||||
if _q.ctx.Unique == nil && _q.path != nil {
|
||||
_q.Unique(true)
|
||||
}
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
|
||||
if err = _q.Select(node.FieldID).Scan(ctx, &ids); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// IDsX is like IDs, but panics if an error occurs.
|
||||
func (_q *NodeQuery) IDsX(ctx context.Context) []int {
|
||||
ids, err := _q.IDs(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// Count returns the count of the given query.
|
||||
func (_q *NodeQuery) 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[*NodeQuery](), _q.inters)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
func (_q *NodeQuery) 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 *NodeQuery) 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 *NodeQuery) ExistX(ctx context.Context) bool {
|
||||
exist, err := _q.Exist(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return exist
|
||||
}
|
||||
|
||||
// Clone returns a duplicate of the NodeQuery 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 *NodeQuery) Clone() *NodeQuery {
|
||||
if _q == nil {
|
||||
return nil
|
||||
}
|
||||
return &NodeQuery{
|
||||
config: _q.config,
|
||||
ctx: _q.ctx.Clone(),
|
||||
order: append([]node.OrderOption{}, _q.order...),
|
||||
inters: append([]Interceptor{}, _q.inters...),
|
||||
predicates: append([]predicate.Node{}, _q.predicates...),
|
||||
withPrev: _q.withPrev.Clone(),
|
||||
withNext: _q.withNext.Clone(),
|
||||
// clone intermediate query.
|
||||
sql: _q.sql.Clone(),
|
||||
path: _q.path,
|
||||
}
|
||||
}
|
||||
|
||||
// WithPrev tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "prev" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (_q *NodeQuery) WithPrev(opts ...func(*NodeQuery)) *NodeQuery {
|
||||
query := (&NodeClient{config: _q.config}).Query()
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
_q.withPrev = query
|
||||
return _q
|
||||
}
|
||||
|
||||
// WithNext tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "next" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (_q *NodeQuery) WithNext(opts ...func(*NodeQuery)) *NodeQuery {
|
||||
query := (&NodeClient{config: _q.config}).Query()
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
_q.withNext = 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 {
|
||||
// Value int `json:"value,omitempty"`
|
||||
// Count int `json:"count,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.Node.Query().
|
||||
// GroupBy(node.FieldValue).
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *NodeQuery) GroupBy(field string, fields ...string) *NodeGroupBy {
|
||||
_q.ctx.Fields = append([]string{field}, fields...)
|
||||
grbuild := &NodeGroupBy{build: _q}
|
||||
grbuild.flds = &_q.ctx.Fields
|
||||
grbuild.label = node.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 {
|
||||
// Value int `json:"value,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.Node.Query().
|
||||
// Select(node.FieldValue).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *NodeQuery) Select(fields ...string) *NodeSelect {
|
||||
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
|
||||
sbuild := &NodeSelect{NodeQuery: _q}
|
||||
sbuild.label = node.Label
|
||||
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
|
||||
return sbuild
|
||||
}
|
||||
|
||||
// Aggregate returns a NodeSelect configured with the given aggregations.
|
||||
func (_q *NodeQuery) Aggregate(fns ...AggregateFunc) *NodeSelect {
|
||||
return _q.Select().Aggregate(fns...)
|
||||
}
|
||||
|
||||
func (_q *NodeQuery) 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 !node.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 *NodeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Node, error) {
|
||||
var (
|
||||
nodes = []*Node{}
|
||||
_spec = _q.querySpec()
|
||||
loadedTypes = [2]bool{
|
||||
_q.withPrev != nil,
|
||||
_q.withNext != nil,
|
||||
}
|
||||
)
|
||||
_spec.ScanValues = func(columns []string) ([]any, error) {
|
||||
return (*Node).scanValues(nil, columns)
|
||||
}
|
||||
_spec.Assign = func(columns []string, values []any) error {
|
||||
node := &Node{config: _q.config}
|
||||
nodes = append(nodes, node)
|
||||
node.Edges.loadedTypes = loadedTypes
|
||||
return node.assignValues(columns, values)
|
||||
}
|
||||
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.withPrev; query != nil {
|
||||
if err := _q.loadPrev(ctx, query, nodes, nil,
|
||||
func(n *Node, e *Node) { n.Edges.Prev = e }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if query := _q.withNext; query != nil {
|
||||
if err := _q.loadNext(ctx, query, nodes, nil,
|
||||
func(n *Node, e *Node) { n.Edges.Next = e }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
func (_q *NodeQuery) loadPrev(ctx context.Context, query *NodeQuery, nodes []*Node, init func(*Node), assign func(*Node, *Node)) error {
|
||||
ids := make([]int, 0, len(nodes))
|
||||
nodeids := make(map[int][]*Node)
|
||||
for i := range nodes {
|
||||
fk := nodes[i].PrevID
|
||||
if _, ok := nodeids[fk]; !ok {
|
||||
ids = append(ids, fk)
|
||||
}
|
||||
nodeids[fk] = append(nodeids[fk], nodes[i])
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
query.Where(node.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 "prev_id" returned %v`, n.ID)
|
||||
}
|
||||
for i := range nodes {
|
||||
assign(nodes[i], n)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (_q *NodeQuery) loadNext(ctx context.Context, query *NodeQuery, nodes []*Node, init func(*Node), assign func(*Node, *Node)) error {
|
||||
fks := make([]driver.Value, 0, len(nodes))
|
||||
nodeids := make(map[int]*Node)
|
||||
for i := range nodes {
|
||||
fks = append(fks, nodes[i].ID)
|
||||
nodeids[nodes[i].ID] = nodes[i]
|
||||
}
|
||||
if len(query.ctx.Fields) > 0 {
|
||||
query.ctx.AppendFieldOnce(node.FieldPrevID)
|
||||
}
|
||||
query.Where(predicate.Node(func(s *sql.Selector) {
|
||||
s.Where(sql.InValues(s.C(node.NextColumn), fks...))
|
||||
}))
|
||||
neighbors, err := query.All(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, n := range neighbors {
|
||||
fk := n.PrevID
|
||||
node, ok := nodeids[fk]
|
||||
if !ok {
|
||||
return fmt.Errorf(`unexpected referenced foreign-key "prev_id" returned %v for node %v`, fk, n.ID)
|
||||
}
|
||||
assign(node, n)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_q *NodeQuery) sqlCount(ctx context.Context) (int, error) {
|
||||
_spec := _q.querySpec()
|
||||
_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 *NodeQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
_spec := sqlgraph.NewQuerySpec(node.Table, node.Columns, sqlgraph.NewFieldSpec(node.FieldID, field.TypeInt))
|
||||
_spec.From = _q.sql
|
||||
if unique := _q.ctx.Unique; unique != nil {
|
||||
_spec.Unique = *unique
|
||||
} else if _q.path != nil {
|
||||
_spec.Unique = true
|
||||
}
|
||||
if fields := _q.ctx.Fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, node.FieldID)
|
||||
for i := range fields {
|
||||
if fields[i] != node.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
|
||||
}
|
||||
}
|
||||
if _q.withPrev != nil {
|
||||
_spec.Node.AddColumnOnce(node.FieldPrevID)
|
||||
}
|
||||
}
|
||||
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 *NodeQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
builder := sql.Dialect(_q.driver.Dialect())
|
||||
t1 := builder.Table(node.Table)
|
||||
columns := _q.ctx.Fields
|
||||
if len(columns) == 0 {
|
||||
columns = node.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
|
||||
}
|
||||
|
||||
// NodeGroupBy is the group-by builder for Node entities.
|
||||
type NodeGroupBy struct {
|
||||
selector
|
||||
build *NodeQuery
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the group-by query.
|
||||
func (_g *NodeGroupBy) Aggregate(fns ...AggregateFunc) *NodeGroupBy {
|
||||
_g.fns = append(_g.fns, fns...)
|
||||
return _g
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_g *NodeGroupBy) 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[*NodeQuery, *NodeGroupBy](ctx, _g.build, _g, _g.build.inters, v)
|
||||
}
|
||||
|
||||
func (_g *NodeGroupBy) sqlScan(ctx context.Context, root *NodeQuery, 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)
|
||||
}
|
||||
|
||||
// NodeSelect is the builder for selecting fields of Node entities.
|
||||
type NodeSelect struct {
|
||||
*NodeQuery
|
||||
selector
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the selector query.
|
||||
func (_s *NodeSelect) Aggregate(fns ...AggregateFunc) *NodeSelect {
|
||||
_s.fns = append(_s.fns, fns...)
|
||||
return _s
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_s *NodeSelect) 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[*NodeQuery, *NodeSelect](ctx, _s.NodeQuery, _s, _s.inters, v)
|
||||
}
|
||||
|
||||
func (_s *NodeSelect) sqlScan(ctx context.Context, root *NodeQuery, 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)
|
||||
}
|
||||
461
examples/o2orecur/ent/node_update.go
Normal file
461
examples/o2orecur/ent/node_update.go
Normal file
@@ -0,0 +1,461 @@
|
||||
// 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"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/o2orecur/ent/node"
|
||||
"entgo.io/ent/examples/o2orecur/ent/predicate"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// NodeUpdate is the builder for updating Node entities.
|
||||
type NodeUpdate struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *NodeMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the NodeUpdate builder.
|
||||
func (_u *NodeUpdate) Where(ps ...predicate.Node) *NodeUpdate {
|
||||
_u.mutation.Where(ps...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetValue sets the "value" field.
|
||||
func (_u *NodeUpdate) SetValue(v int) *NodeUpdate {
|
||||
_u.mutation.ResetValue()
|
||||
_u.mutation.SetValue(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableValue sets the "value" field if the given value is not nil.
|
||||
func (_u *NodeUpdate) SetNillableValue(v *int) *NodeUpdate {
|
||||
if v != nil {
|
||||
_u.SetValue(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddValue adds value to the "value" field.
|
||||
func (_u *NodeUpdate) AddValue(v int) *NodeUpdate {
|
||||
_u.mutation.AddValue(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetPrevID sets the "prev_id" field.
|
||||
func (_u *NodeUpdate) SetPrevID(v int) *NodeUpdate {
|
||||
_u.mutation.SetPrevID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillablePrevID sets the "prev_id" field if the given value is not nil.
|
||||
func (_u *NodeUpdate) SetNillablePrevID(v *int) *NodeUpdate {
|
||||
if v != nil {
|
||||
_u.SetPrevID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearPrevID clears the value of the "prev_id" field.
|
||||
func (_u *NodeUpdate) ClearPrevID() *NodeUpdate {
|
||||
_u.mutation.ClearPrevID()
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetPrev sets the "prev" edge to the Node entity.
|
||||
func (_u *NodeUpdate) SetPrev(v *Node) *NodeUpdate {
|
||||
return _u.SetPrevID(v.ID)
|
||||
}
|
||||
|
||||
// SetNextID sets the "next" edge to the Node entity by ID.
|
||||
func (_u *NodeUpdate) SetNextID(id int) *NodeUpdate {
|
||||
_u.mutation.SetNextID(id)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableNextID sets the "next" edge to the Node entity by ID if the given value is not nil.
|
||||
func (_u *NodeUpdate) SetNillableNextID(id *int) *NodeUpdate {
|
||||
if id != nil {
|
||||
_u = _u.SetNextID(*id)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNext sets the "next" edge to the Node entity.
|
||||
func (_u *NodeUpdate) SetNext(v *Node) *NodeUpdate {
|
||||
return _u.SetNextID(v.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the NodeMutation object of the builder.
|
||||
func (_u *NodeUpdate) Mutation() *NodeMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// ClearPrev clears the "prev" edge to the Node entity.
|
||||
func (_u *NodeUpdate) ClearPrev() *NodeUpdate {
|
||||
_u.mutation.ClearPrev()
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearNext clears the "next" edge to the Node entity.
|
||||
func (_u *NodeUpdate) ClearNext() *NodeUpdate {
|
||||
_u.mutation.ClearNext()
|
||||
return _u
|
||||
}
|
||||
|
||||
// Save executes the query and returns the number of nodes affected by the update operation.
|
||||
func (_u *NodeUpdate) 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 *NodeUpdate) SaveX(ctx context.Context) int {
|
||||
affected, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return affected
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_u *NodeUpdate) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *NodeUpdate) ExecX(ctx context.Context) {
|
||||
if err := _u.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if value, ok := _u.mutation.Value(); ok {
|
||||
_spec.SetField(node.FieldValue, field.TypeInt, value)
|
||||
}
|
||||
if value, ok := _u.mutation.AddedValue(); ok {
|
||||
_spec.AddField(node.FieldValue, field.TypeInt, value)
|
||||
}
|
||||
if _u.mutation.PrevCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2O,
|
||||
Inverse: true,
|
||||
Table: node.PrevTable,
|
||||
Columns: []string{node.PrevColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(node.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.PrevIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2O,
|
||||
Inverse: true,
|
||||
Table: node.PrevTable,
|
||||
Columns: []string{node.PrevColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(node.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if _u.mutation.NextCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2O,
|
||||
Inverse: false,
|
||||
Table: node.NextTable,
|
||||
Columns: []string{node.NextColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(node.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.NextIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2O,
|
||||
Inverse: false,
|
||||
Table: node.NextTable,
|
||||
Columns: []string{node.NextColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(node.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
|
||||
if _, ok := err.(*sqlgraph.NotFoundError); ok {
|
||||
err = &NotFoundError{node.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
// NodeUpdateOne is the builder for updating a single Node entity.
|
||||
type NodeUpdateOne struct {
|
||||
config
|
||||
fields []string
|
||||
hooks []Hook
|
||||
mutation *NodeMutation
|
||||
}
|
||||
|
||||
// SetValue sets the "value" field.
|
||||
func (_u *NodeUpdateOne) SetValue(v int) *NodeUpdateOne {
|
||||
_u.mutation.ResetValue()
|
||||
_u.mutation.SetValue(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableValue sets the "value" field if the given value is not nil.
|
||||
func (_u *NodeUpdateOne) SetNillableValue(v *int) *NodeUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetValue(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddValue adds value to the "value" field.
|
||||
func (_u *NodeUpdateOne) AddValue(v int) *NodeUpdateOne {
|
||||
_u.mutation.AddValue(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetPrevID sets the "prev_id" field.
|
||||
func (_u *NodeUpdateOne) SetPrevID(v int) *NodeUpdateOne {
|
||||
_u.mutation.SetPrevID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillablePrevID sets the "prev_id" field if the given value is not nil.
|
||||
func (_u *NodeUpdateOne) SetNillablePrevID(v *int) *NodeUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetPrevID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearPrevID clears the value of the "prev_id" field.
|
||||
func (_u *NodeUpdateOne) ClearPrevID() *NodeUpdateOne {
|
||||
_u.mutation.ClearPrevID()
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetPrev sets the "prev" edge to the Node entity.
|
||||
func (_u *NodeUpdateOne) SetPrev(v *Node) *NodeUpdateOne {
|
||||
return _u.SetPrevID(v.ID)
|
||||
}
|
||||
|
||||
// SetNextID sets the "next" edge to the Node entity by ID.
|
||||
func (_u *NodeUpdateOne) SetNextID(id int) *NodeUpdateOne {
|
||||
_u.mutation.SetNextID(id)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableNextID sets the "next" edge to the Node entity by ID if the given value is not nil.
|
||||
func (_u *NodeUpdateOne) SetNillableNextID(id *int) *NodeUpdateOne {
|
||||
if id != nil {
|
||||
_u = _u.SetNextID(*id)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNext sets the "next" edge to the Node entity.
|
||||
func (_u *NodeUpdateOne) SetNext(v *Node) *NodeUpdateOne {
|
||||
return _u.SetNextID(v.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the NodeMutation object of the builder.
|
||||
func (_u *NodeUpdateOne) Mutation() *NodeMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// ClearPrev clears the "prev" edge to the Node entity.
|
||||
func (_u *NodeUpdateOne) ClearPrev() *NodeUpdateOne {
|
||||
_u.mutation.ClearPrev()
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearNext clears the "next" edge to the Node entity.
|
||||
func (_u *NodeUpdateOne) ClearNext() *NodeUpdateOne {
|
||||
_u.mutation.ClearNext()
|
||||
return _u
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the NodeUpdate builder.
|
||||
func (_u *NodeUpdateOne) Where(ps ...predicate.Node) *NodeUpdateOne {
|
||||
_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 *NodeUpdateOne) Select(field string, fields ...string) *NodeUpdateOne {
|
||||
_u.fields = append([]string{field}, fields...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// Save executes the query and returns the updated Node entity.
|
||||
func (_u *NodeUpdateOne) Save(ctx context.Context) (*Node, error) {
|
||||
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_u *NodeUpdateOne) SaveX(ctx context.Context) *Node {
|
||||
node, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// Exec executes the query on the entity.
|
||||
func (_u *NodeUpdateOne) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *NodeUpdateOne) ExecX(ctx context.Context) {
|
||||
if err := _u.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
if !ok {
|
||||
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Node.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, node.FieldID)
|
||||
for _, f := range fields {
|
||||
if !node.ValidColumn(f) {
|
||||
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
if f != node.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.Value(); ok {
|
||||
_spec.SetField(node.FieldValue, field.TypeInt, value)
|
||||
}
|
||||
if value, ok := _u.mutation.AddedValue(); ok {
|
||||
_spec.AddField(node.FieldValue, field.TypeInt, value)
|
||||
}
|
||||
if _u.mutation.PrevCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2O,
|
||||
Inverse: true,
|
||||
Table: node.PrevTable,
|
||||
Columns: []string{node.PrevColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(node.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.PrevIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2O,
|
||||
Inverse: true,
|
||||
Table: node.PrevTable,
|
||||
Columns: []string{node.PrevColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(node.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if _u.mutation.NextCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2O,
|
||||
Inverse: false,
|
||||
Table: node.NextTable,
|
||||
Columns: []string{node.NextColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(node.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.NextIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2O,
|
||||
Inverse: false,
|
||||
Table: node.NextTable,
|
||||
Columns: []string{node.NextColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(node.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
_node = &Node{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{node.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
14
examples/o2orecur/ent/predicate/predicate.go
Normal file
14
examples/o2orecur/ent/predicate/predicate.go
Normal file
@@ -0,0 +1,14 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package predicate
|
||||
|
||||
import (
|
||||
"entgo.io/ent/dialect/sql"
|
||||
)
|
||||
|
||||
// Node is the predicate function for node builders.
|
||||
type Node func(*sql.Selector)
|
||||
13
examples/o2orecur/ent/runtime.go
Normal file
13
examples/o2orecur/ent/runtime.go
Normal file
@@ -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 ent
|
||||
|
||||
// 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() {
|
||||
}
|
||||
13
examples/o2orecur/ent/runtime/runtime.go
Normal file
13
examples/o2orecur/ent/runtime/runtime.go
Normal file
@@ -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/o2orecur/ent/runtime.go
|
||||
|
||||
const (
|
||||
Version = "v0.0.0-00010101000000-000000000000" // Version of ent codegen.
|
||||
)
|
||||
36
examples/o2orecur/ent/schema/node.go
Normal file
36
examples/o2orecur/ent/schema/node.go
Normal file
@@ -0,0 +1,36 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
package schema
|
||||
|
||||
import (
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/schema/edge"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// Node holds the schema definition for the Node entity.
|
||||
type Node struct {
|
||||
ent.Schema
|
||||
}
|
||||
|
||||
// Fields of the Node.
|
||||
func (Node) Fields() []ent.Field {
|
||||
return []ent.Field{
|
||||
field.Int("value"),
|
||||
field.Int("prev_id").
|
||||
Optional(),
|
||||
}
|
||||
}
|
||||
|
||||
// Edges of the Node.
|
||||
func (Node) Edges() []ent.Edge {
|
||||
return []ent.Edge{
|
||||
edge.To("next", Node.Type).
|
||||
Unique().
|
||||
From("prev").
|
||||
Field("prev_id").
|
||||
Unique(),
|
||||
}
|
||||
}
|
||||
214
examples/o2orecur/ent/tx.go
Normal file
214
examples/o2orecur/ent/tx.go
Normal file
@@ -0,0 +1,214 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by 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
|
||||
// Node is the client for interacting with the Node builders.
|
||||
Node *NodeClient
|
||||
|
||||
// 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.Node = NewNodeClient(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: Node.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)
|
||||
Reference in New Issue
Block a user