snapshot of https://github.com/ent/ent.git (master, 2026-09-15; blobs > 131072B omitted)
Some checks failed
Atlas CI Public / lint (push) Failing after 13s
Atlas CI Public / sync (push) Has been skipped

This commit is contained in:
upstream-mirror
2026-09-15 22:12:36 +05:00
commit 4b3ad0b611
2680 changed files with 719472 additions and 0 deletions

View File

@@ -0,0 +1,32 @@
## Multi-schema support for versioned migration
Login first:
```shell
atlas login
```
Generate migrations:
```shell
atlas migrate diff --to ent://versioned/schema \
--dev-url docker://mysql/8 \
--format '{{ sql . " " }}'
```
Apply migrations:
```shell
atlas migrate apply \
--url mysql://root:pass@:3308/ \
--dir file://versioned/migrate/migrations
```
Inspect/Visualize the schema:
```shell
atlas schema inspect \
--url ent://versioned/schema \
--dev-url docker://mysql/8 \
-w
```

View File

@@ -0,0 +1,89 @@
// 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/entc/integration/multischema/ent/cleanuser"
)
// CleanUser is the model entity for the CleanUser schema.
type CleanUser struct {
config `json:"-"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
selectValues sql.SelectValues
}
// scanValues returns the types for scanning values from sql.Rows.
func (*CleanUser) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case cleanuser.FieldName:
values[i] = new(sql.NullString)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the CleanUser fields.
func (_m *CleanUser) 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 cleanuser.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
_m.Name = value.String
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the CleanUser.
// This includes values selected through modifiers, order, etc.
func (_m *CleanUser) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// Unwrap unwraps the CleanUser 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 *CleanUser) Unwrap() *CleanUser {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: CleanUser is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *CleanUser) String() string {
var builder strings.Builder
builder.WriteString("CleanUser(")
builder.WriteString("name=")
builder.WriteString(_m.Name)
builder.WriteByte(')')
return builder.String()
}
// CleanUsers is a parsable slice of CleanUser.
type CleanUsers []*CleanUser

View 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 cleanuser
import (
"entgo.io/ent/dialect/sql"
)
const (
// Label holds the string label denoting the cleanuser type in the database.
Label = "clean_user"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// Table holds the table name of the cleanuser in the database.
Table = "clean_users"
)
// Columns holds all SQL columns for cleanuser fields.
var Columns = []string{
FieldName,
}
// 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 CleanUser queries.
type OrderOption func(*sql.Selector)
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, opts...).ToFunc()
}

View File

@@ -0,0 +1,97 @@
// 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 cleanuser
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
)
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.CleanUser {
return predicate.CleanUser(sql.FieldEQ(FieldName, v))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.CleanUser {
return predicate.CleanUser(sql.FieldEQ(FieldName, v))
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.CleanUser {
return predicate.CleanUser(sql.FieldNEQ(FieldName, v))
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.CleanUser {
return predicate.CleanUser(sql.FieldIn(FieldName, vs...))
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.CleanUser {
return predicate.CleanUser(sql.FieldNotIn(FieldName, vs...))
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.CleanUser {
return predicate.CleanUser(sql.FieldGT(FieldName, v))
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.CleanUser {
return predicate.CleanUser(sql.FieldGTE(FieldName, v))
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.CleanUser {
return predicate.CleanUser(sql.FieldLT(FieldName, v))
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.CleanUser {
return predicate.CleanUser(sql.FieldLTE(FieldName, v))
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.CleanUser {
return predicate.CleanUser(sql.FieldContains(FieldName, v))
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.CleanUser {
return predicate.CleanUser(sql.FieldHasPrefix(FieldName, v))
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.CleanUser {
return predicate.CleanUser(sql.FieldHasSuffix(FieldName, v))
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.CleanUser {
return predicate.CleanUser(sql.FieldEqualFold(FieldName, v))
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.CleanUser {
return predicate.CleanUser(sql.FieldContainsFold(FieldName, v))
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.CleanUser) predicate.CleanUser {
return predicate.CleanUser(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.CleanUser) predicate.CleanUser {
return predicate.CleanUser(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.CleanUser) predicate.CleanUser {
return predicate.CleanUser(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,486 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/ent/cleanuser"
"entgo.io/ent/entc/integration/multischema/ent/internal"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
)
// CleanUserQuery is the builder for querying CleanUser entities.
type CleanUserQuery struct {
config
ctx *QueryContext
order []cleanuser.OrderOption
inters []Interceptor
predicates []predicate.CleanUser
modifiers []func(*sql.Selector)
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the CleanUserQuery builder.
func (_q *CleanUserQuery) Where(ps ...predicate.CleanUser) *CleanUserQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *CleanUserQuery) Limit(limit int) *CleanUserQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *CleanUserQuery) Offset(offset int) *CleanUserQuery {
_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 *CleanUserQuery) Unique(unique bool) *CleanUserQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *CleanUserQuery) Order(o ...cleanuser.OrderOption) *CleanUserQuery {
_q.order = append(_q.order, o...)
return _q
}
// First returns the first CleanUser entity from the query.
// Returns a *NotFoundError when no CleanUser was found.
func (_q *CleanUserQuery) First(ctx context.Context) (*CleanUser, 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{cleanuser.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *CleanUserQuery) FirstX(ctx context.Context) *CleanUser {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// Only returns a single CleanUser entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one CleanUser entity is found.
// Returns a *NotFoundError when no CleanUser entities are found.
func (_q *CleanUserQuery) Only(ctx context.Context) (*CleanUser, 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{cleanuser.Label}
default:
return nil, &NotSingularError{cleanuser.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *CleanUserQuery) OnlyX(ctx context.Context) *CleanUser {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// All executes the query and returns a list of CleanUsers.
func (_q *CleanUserQuery) All(ctx context.Context) ([]*CleanUser, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*CleanUser, *CleanUserQuery]()
return withInterceptors[[]*CleanUser](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *CleanUserQuery) AllX(ctx context.Context) []*CleanUser {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// Count returns the count of the given query.
func (_q *CleanUserQuery) 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[*CleanUserQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *CleanUserQuery) 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 *CleanUserQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
switch _, err := _q.First(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 *CleanUserQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the CleanUserQuery 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 *CleanUserQuery) Clone() *CleanUserQuery {
if _q == nil {
return nil
}
return &CleanUserQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]cleanuser.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.CleanUser{}, _q.predicates...),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
modifiers: append([]func(*sql.Selector){}, _q.modifiers...),
}
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// Name string `json:"name,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.CleanUser.Query().
// GroupBy(cleanuser.FieldName).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *CleanUserQuery) GroupBy(field string, fields ...string) *CleanUserGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &CleanUserGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = cleanuser.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 {
// Name string `json:"name,omitempty"`
// }
//
// client.CleanUser.Query().
// Select(cleanuser.FieldName).
// Scan(ctx, &v)
func (_q *CleanUserQuery) Select(fields ...string) *CleanUserSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &CleanUserSelect{CleanUserQuery: _q}
sbuild.label = cleanuser.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a CleanUserSelect configured with the given aggregations.
func (_q *CleanUserQuery) Aggregate(fns ...AggregateFunc) *CleanUserSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *CleanUserQuery) 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 !cleanuser.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 *CleanUserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*CleanUser, error) {
var (
nodes = []*CleanUser{}
_spec = _q.querySpec()
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*CleanUser).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &CleanUser{config: _q.config}
nodes = append(nodes, node)
return node.assignValues(columns, values)
}
_spec.Node.Schema = _q.schemaConfig.CleanUser
ctx = internal.NewSchemaConfigContext(ctx, _q.schemaConfig)
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (_q *CleanUserQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Schema = _q.schemaConfig.CleanUser
ctx = internal.NewSchemaConfigContext(ctx, _q.schemaConfig)
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *CleanUserQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(cleanuser.Table, cleanuser.Columns, nil)
_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))
for i := range fields {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
if ps := _q.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := _q.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := _q.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := _q.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (_q *CleanUserQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(cleanuser.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = cleanuser.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()
}
t1.Schema(_q.schemaConfig.CleanUser)
ctx = internal.NewSchemaConfigContext(ctx, _q.schemaConfig)
selector.WithContext(ctx)
for _, m := range _q.modifiers {
m(selector)
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// Modify adds a query modifier for attaching custom logic to queries.
func (_q *CleanUserQuery) Modify(modifiers ...func(s *sql.Selector)) *CleanUserSelect {
_q.modifiers = append(_q.modifiers, modifiers...)
return _q.Select()
}
// CleanUserGroupBy is the group-by builder for CleanUser entities.
type CleanUserGroupBy struct {
selector
build *CleanUserQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *CleanUserGroupBy) Aggregate(fns ...AggregateFunc) *CleanUserGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *CleanUserGroupBy) 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[*CleanUserQuery, *CleanUserGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *CleanUserGroupBy) sqlScan(ctx context.Context, root *CleanUserQuery, 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)
}
// CleanUserSelect is the builder for selecting fields of CleanUser entities.
type CleanUserSelect struct {
*CleanUserQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *CleanUserSelect) Aggregate(fns ...AggregateFunc) *CleanUserSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *CleanUserSelect) 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[*CleanUserQuery, *CleanUserSelect](ctx, _s.CleanUserQuery, _s, _s.inters, v)
}
func (_s *CleanUserSelect) sqlScan(ctx context.Context, root *CleanUserQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(_s.fns))
for _, fn := range _s.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*_s.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// Modify adds a query modifier for attaching custom logic to queries.
func (_s *CleanUserSelect) Modify(modifiers ...func(s *sql.Selector)) *CleanUserSelect {
_s.modifiers = append(_s.modifiers, modifiers...)
return _s
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,622 @@
// 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/entc/integration/multischema/ent/cleanuser"
"entgo.io/ent/entc/integration/multischema/ent/friendship"
"entgo.io/ent/entc/integration/multischema/ent/group"
"entgo.io/ent/entc/integration/multischema/ent/parent"
"entgo.io/ent/entc/integration/multischema/ent/pet"
"entgo.io/ent/entc/integration/multischema/ent/user"
)
// 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{
cleanuser.Table: cleanuser.ValidColumn,
friendship.Table: friendship.ValidColumn,
group.Table: group.ValidColumn,
parent.Table: parent.ValidColumn,
pet.Table: pet.ValidColumn,
user.Table: user.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)

View 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/entc/integration/multischema/ent"
// required by schema hooks.
_ "entgo.io/ent/entc/integration/multischema/ent/runtime"
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/entc/integration/multischema/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()
}
}

View File

@@ -0,0 +1,188 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/entc/integration/multischema/ent/friendship"
"entgo.io/ent/entc/integration/multischema/ent/user"
)
// Friendship is the model entity for the Friendship schema.
type Friendship struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Weight holds the value of the "weight" field.
Weight int `json:"weight,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// UserID holds the value of the "user_id" field.
UserID int `json:"user_id,omitempty"`
// FriendID holds the value of the "friend_id" field.
FriendID int `json:"friend_id,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the FriendshipQuery when eager-loading is set.
Edges FriendshipEdges `json:"edges"`
selectValues sql.SelectValues
}
// FriendshipEdges holds the relations/edges for other nodes in the graph.
type FriendshipEdges struct {
// User holds the value of the user edge.
User *User `json:"user,omitempty"`
// Friend holds the value of the friend edge.
Friend *User `json:"friend,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// UserOrErr returns the User value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e FriendshipEdges) UserOrErr() (*User, error) {
if e.User != nil {
return e.User, nil
} else if e.loadedTypes[0] {
return nil, &NotFoundError{label: user.Label}
}
return nil, &NotLoadedError{edge: "user"}
}
// FriendOrErr returns the Friend value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e FriendshipEdges) FriendOrErr() (*User, error) {
if e.Friend != nil {
return e.Friend, nil
} else if e.loadedTypes[1] {
return nil, &NotFoundError{label: user.Label}
}
return nil, &NotLoadedError{edge: "friend"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Friendship) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case friendship.FieldID, friendship.FieldWeight, friendship.FieldUserID, friendship.FieldFriendID:
values[i] = new(sql.NullInt64)
case friendship.FieldCreatedAt:
values[i] = new(sql.NullTime)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Friendship fields.
func (_m *Friendship) 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 friendship.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 friendship.FieldWeight:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field weight", values[i])
} else if value.Valid {
_m.Weight = int(value.Int64)
}
case friendship.FieldCreatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
_m.CreatedAt = value.Time
}
case friendship.FieldUserID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field user_id", values[i])
} else if value.Valid {
_m.UserID = int(value.Int64)
}
case friendship.FieldFriendID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field friend_id", values[i])
} else if value.Valid {
_m.FriendID = int(value.Int64)
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Friendship.
// This includes values selected through modifiers, order, etc.
func (_m *Friendship) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryUser queries the "user" edge of the Friendship entity.
func (_m *Friendship) QueryUser() *UserQuery {
return NewFriendshipClient(_m.config).QueryUser(_m)
}
// QueryFriend queries the "friend" edge of the Friendship entity.
func (_m *Friendship) QueryFriend() *UserQuery {
return NewFriendshipClient(_m.config).QueryFriend(_m)
}
// Update returns a builder for updating this Friendship.
// Note that you need to call Friendship.Unwrap() before calling this method if this Friendship
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Friendship) Update() *FriendshipUpdateOne {
return NewFriendshipClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Friendship 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 *Friendship) Unwrap() *Friendship {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: Friendship is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Friendship) String() string {
var builder strings.Builder
builder.WriteString("Friendship(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("weight=")
builder.WriteString(fmt.Sprintf("%v", _m.Weight))
builder.WriteString(", ")
builder.WriteString("created_at=")
builder.WriteString(_m.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("user_id=")
builder.WriteString(fmt.Sprintf("%v", _m.UserID))
builder.WriteString(", ")
builder.WriteString("friend_id=")
builder.WriteString(fmt.Sprintf("%v", _m.FriendID))
builder.WriteByte(')')
return builder.String()
}
// Friendships is a parsable slice of Friendship.
type Friendships []*Friendship

View File

@@ -0,0 +1,131 @@
// 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 friendship
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the friendship type in the database.
Label = "friendship"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldWeight holds the string denoting the weight field in the database.
FieldWeight = "weight"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldUserID holds the string denoting the user_id field in the database.
FieldUserID = "user_id"
// FieldFriendID holds the string denoting the friend_id field in the database.
FieldFriendID = "friend_id"
// EdgeUser holds the string denoting the user edge name in mutations.
EdgeUser = "user"
// EdgeFriend holds the string denoting the friend edge name in mutations.
EdgeFriend = "friend"
// Table holds the table name of the friendship in the database.
Table = "friendships"
// UserTable is the table that holds the user relation/edge.
UserTable = "friendships"
// UserInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
UserInverseTable = "users"
// UserColumn is the table column denoting the user relation/edge.
UserColumn = "user_id"
// FriendTable is the table that holds the friend relation/edge.
FriendTable = "friendships"
// FriendInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
FriendInverseTable = "users"
// FriendColumn is the table column denoting the friend relation/edge.
FriendColumn = "friend_id"
)
// Columns holds all SQL columns for friendship fields.
var Columns = []string{
FieldID,
FieldWeight,
FieldCreatedAt,
FieldUserID,
FieldFriendID,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// DefaultWeight holds the default value on creation for the "weight" field.
DefaultWeight int
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
)
// OrderOption defines the ordering options for the Friendship 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()
}
// ByWeight orders the results by the weight field.
func ByWeight(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldWeight, opts...).ToFunc()
}
// ByCreatedAt orders the results by the created_at field.
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
}
// ByUserID orders the results by the user_id field.
func ByUserID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUserID, opts...).ToFunc()
}
// ByFriendID orders the results by the friend_id field.
func ByFriendID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldFriendID, opts...).ToFunc()
}
// ByUserField orders the results by user field.
func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newUserStep(), sql.OrderByField(field, opts...))
}
}
// ByFriendField orders the results by friend field.
func ByFriendField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newFriendStep(), sql.OrderByField(field, opts...))
}
}
func newUserStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UserInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn),
)
}
func newFriendStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(FriendInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, FriendTable, FriendColumn),
)
}

View File

@@ -0,0 +1,475 @@
// 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 friendship
import (
"context"
"fmt"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
)
// Mutation represents an operation that mutates the Friendship nodes in the graph.
type Mutation struct {
op ent.Op
typ string
weight *int
addweight *int
created_at *time.Time
clearedFields map[string]struct{}
user *int
cleareduser bool
friend *int
clearedfriend bool
predicates []predicate.Friendship
}
// NewMutation creates a new Mutation for the Friendship entity.
func NewMutation(op ent.Op) *Mutation {
return &Mutation{
op: op,
typ: "Friendship",
clearedFields: make(map[string]struct{}),
}
}
// Predicates returns the list of predicates set on the mutation.
func (m *Mutation) Predicates() []predicate.Friendship {
return m.predicates
}
// SetWeight sets the "weight" field.
func (m *Mutation) SetWeight(i int) {
m.weight = &i
m.addweight = nil
}
// Weight returns the value of the "weight" field in the mutation.
func (m *Mutation) Weight() (r int, exists bool) {
v := m.weight
if v == nil {
return
}
return *v, true
}
// AddWeight adds i to the "weight" field.
func (m *Mutation) AddWeight(i int) {
if m.addweight != nil {
*m.addweight += i
} else {
m.addweight = &i
}
}
// AddedWeight returns the value that was added to the "weight" field in this mutation.
func (m *Mutation) AddedWeight() (r int, exists bool) {
v := m.addweight
if v == nil {
return
}
return *v, true
}
// ResetWeight resets all changes to the "weight" field.
func (m *Mutation) ResetWeight() {
m.weight = nil
m.addweight = nil
}
// SetCreatedAt sets the "created_at" field.
func (m *Mutation) SetCreatedAt(t time.Time) {
m.created_at = &t
}
// CreatedAt returns the value of the "created_at" field in the mutation.
func (m *Mutation) CreatedAt() (r time.Time, exists bool) {
v := m.created_at
if v == nil {
return
}
return *v, true
}
// ResetCreatedAt resets all changes to the "created_at" field.
func (m *Mutation) ResetCreatedAt() {
m.created_at = nil
}
// SetUserID sets the "user_id" field.
func (m *Mutation) SetUserID(i int) {
m.user = &i
}
// UserID returns the value of the "user_id" field in the mutation.
func (m *Mutation) UserID() (r int, exists bool) {
v := m.user
if v == nil {
return
}
return *v, true
}
// ResetUserID resets all changes to the "user_id" field.
func (m *Mutation) ResetUserID() {
m.user = nil
}
// SetFriendID sets the "friend_id" field.
func (m *Mutation) SetFriendID(i int) {
m.friend = &i
}
// FriendID returns the value of the "friend_id" field in the mutation.
func (m *Mutation) FriendID() (r int, exists bool) {
v := m.friend
if v == nil {
return
}
return *v, true
}
// ResetFriendID resets all changes to the "friend_id" field.
func (m *Mutation) ResetFriendID() {
m.friend = nil
}
// ClearUser clears the "user" edge to the User entity.
func (m *Mutation) ClearUser() {
m.cleareduser = true
m.clearedFields[FieldUserID] = struct{}{}
}
// UserCleared reports if the "user" edge to the User entity was cleared.
func (m *Mutation) UserCleared() bool {
return m.cleareduser
}
// UserIDs returns the "user" edge IDs in the mutation.
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
// UserID instead. It exists only for internal usage by the builders.
func (m *Mutation) UserIDs() (ids []int) {
if id := m.user; id != nil {
ids = append(ids, *id)
}
return
}
// ResetUser resets all changes to the "user" edge.
func (m *Mutation) ResetUser() {
m.user = nil
m.cleareduser = false
}
// ClearFriend clears the "friend" edge to the User entity.
func (m *Mutation) ClearFriend() {
m.clearedfriend = true
m.clearedFields[FieldFriendID] = struct{}{}
}
// FriendCleared reports if the "friend" edge to the User entity was cleared.
func (m *Mutation) FriendCleared() bool {
return m.clearedfriend
}
// FriendIDs returns the "friend" edge IDs in the mutation.
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
// FriendID instead. It exists only for internal usage by the builders.
func (m *Mutation) FriendIDs() (ids []int) {
if id := m.friend; id != nil {
ids = append(ids, *id)
}
return
}
// ResetFriend resets all changes to the "friend" edge.
func (m *Mutation) ResetFriend() {
m.friend = nil
m.clearedfriend = false
}
// Where appends a list predicates to the Mutation builder.
func (m *Mutation) Where(ps ...predicate.Friendship) {
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.Friendship, 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 (Friendship).
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, 4)
if m.weight != nil {
fields = append(fields, FieldWeight)
}
if m.created_at != nil {
fields = append(fields, FieldCreatedAt)
}
if m.user != nil {
fields = append(fields, FieldUserID)
}
if m.friend != nil {
fields = append(fields, FieldFriendID)
}
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 FieldWeight:
return m.Weight()
case FieldCreatedAt:
return m.CreatedAt()
case FieldUserID:
return m.UserID()
case FieldFriendID:
return m.FriendID()
}
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 Friendship 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 FieldWeight:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetWeight(v)
return nil
case FieldCreatedAt:
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetCreatedAt(v)
return nil
case FieldUserID:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetUserID(v)
return nil
case FieldFriendID:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetFriendID(v)
return nil
}
return fmt.Errorf("unknown Friendship 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.addweight != nil {
fields = append(fields, FieldWeight)
}
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 FieldWeight:
return m.AddedWeight()
}
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 FieldWeight:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.AddWeight(v)
return nil
}
return fmt.Errorf("unknown Friendship numeric field %s", name)
}
// ClearedFields returns all nullable fields that were cleared during this
// mutation.
func (m *Mutation) ClearedFields() []string {
return nil
}
// 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 {
return fmt.Errorf("unknown Friendship 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 FieldWeight:
m.ResetWeight()
return nil
case FieldCreatedAt:
m.ResetCreatedAt()
return nil
case FieldUserID:
m.ResetUserID()
return nil
case FieldFriendID:
m.ResetFriendID()
return nil
}
return fmt.Errorf("unknown Friendship 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.user != nil {
edges = append(edges, EdgeUser)
}
if m.friend != nil {
edges = append(edges, EdgeFriend)
}
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 EdgeUser:
if id := m.user; id != nil {
return []ent.Value{*id}
}
case EdgeFriend:
if id := m.friend; 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.cleareduser {
edges = append(edges, EdgeUser)
}
if m.clearedfriend {
edges = append(edges, EdgeFriend)
}
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 EdgeUser:
return m.cleareduser
case EdgeFriend:
return m.clearedfriend
}
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 EdgeUser:
m.ClearUser()
return nil
case EdgeFriend:
m.ClearFriend()
return nil
}
return fmt.Errorf("unknown Friendship 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 EdgeUser:
m.ResetUser()
return nil
case EdgeFriend:
m.ResetFriend()
return nil
}
return fmt.Errorf("unknown Friendship edge %s", name)
}

View File

@@ -0,0 +1,274 @@
// 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 friendship
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/ent/internal"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Friendship {
return predicate.Friendship(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Friendship {
return predicate.Friendship(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Friendship {
return predicate.Friendship(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Friendship {
return predicate.Friendship(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Friendship {
return predicate.Friendship(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Friendship {
return predicate.Friendship(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Friendship {
return predicate.Friendship(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Friendship {
return predicate.Friendship(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Friendship {
return predicate.Friendship(sql.FieldLTE(FieldID, id))
}
// Weight applies equality check predicate on the "weight" field. It's identical to WeightEQ.
func Weight(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldEQ(FieldWeight, v))
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.Friendship {
return predicate.Friendship(sql.FieldEQ(FieldCreatedAt, v))
}
// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
func UserID(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldEQ(FieldUserID, v))
}
// FriendID applies equality check predicate on the "friend_id" field. It's identical to FriendIDEQ.
func FriendID(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldEQ(FieldFriendID, v))
}
// WeightEQ applies the EQ predicate on the "weight" field.
func WeightEQ(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldEQ(FieldWeight, v))
}
// WeightNEQ applies the NEQ predicate on the "weight" field.
func WeightNEQ(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldNEQ(FieldWeight, v))
}
// WeightIn applies the In predicate on the "weight" field.
func WeightIn(vs ...int) predicate.Friendship {
return predicate.Friendship(sql.FieldIn(FieldWeight, vs...))
}
// WeightNotIn applies the NotIn predicate on the "weight" field.
func WeightNotIn(vs ...int) predicate.Friendship {
return predicate.Friendship(sql.FieldNotIn(FieldWeight, vs...))
}
// WeightGT applies the GT predicate on the "weight" field.
func WeightGT(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldGT(FieldWeight, v))
}
// WeightGTE applies the GTE predicate on the "weight" field.
func WeightGTE(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldGTE(FieldWeight, v))
}
// WeightLT applies the LT predicate on the "weight" field.
func WeightLT(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldLT(FieldWeight, v))
}
// WeightLTE applies the LTE predicate on the "weight" field.
func WeightLTE(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldLTE(FieldWeight, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Friendship {
return predicate.Friendship(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.Friendship {
return predicate.Friendship(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.Friendship {
return predicate.Friendship(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.Friendship {
return predicate.Friendship(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.Friendship {
return predicate.Friendship(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.Friendship {
return predicate.Friendship(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.Friendship {
return predicate.Friendship(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.Friendship {
return predicate.Friendship(sql.FieldLTE(FieldCreatedAt, v))
}
// UserIDEQ applies the EQ predicate on the "user_id" field.
func UserIDEQ(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldEQ(FieldUserID, v))
}
// UserIDNEQ applies the NEQ predicate on the "user_id" field.
func UserIDNEQ(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldNEQ(FieldUserID, v))
}
// UserIDIn applies the In predicate on the "user_id" field.
func UserIDIn(vs ...int) predicate.Friendship {
return predicate.Friendship(sql.FieldIn(FieldUserID, vs...))
}
// UserIDNotIn applies the NotIn predicate on the "user_id" field.
func UserIDNotIn(vs ...int) predicate.Friendship {
return predicate.Friendship(sql.FieldNotIn(FieldUserID, vs...))
}
// FriendIDEQ applies the EQ predicate on the "friend_id" field.
func FriendIDEQ(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldEQ(FieldFriendID, v))
}
// FriendIDNEQ applies the NEQ predicate on the "friend_id" field.
func FriendIDNEQ(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldNEQ(FieldFriendID, v))
}
// FriendIDIn applies the In predicate on the "friend_id" field.
func FriendIDIn(vs ...int) predicate.Friendship {
return predicate.Friendship(sql.FieldIn(FieldFriendID, vs...))
}
// FriendIDNotIn applies the NotIn predicate on the "friend_id" field.
func FriendIDNotIn(vs ...int) predicate.Friendship {
return predicate.Friendship(sql.FieldNotIn(FieldFriendID, vs...))
}
// HasUser applies the HasEdge predicate on the "user" edge.
func HasUser() predicate.Friendship {
return predicate.Friendship(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn),
)
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Friendship
sqlgraph.HasNeighbors(s, step)
})
}
// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates).
func HasUserWith(preds ...predicate.User) predicate.Friendship {
return predicate.Friendship(func(s *sql.Selector) {
step := newUserStep()
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Friendship
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasFriend applies the HasEdge predicate on the "friend" edge.
func HasFriend() predicate.Friendship {
return predicate.Friendship(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, FriendTable, FriendColumn),
)
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Friendship
sqlgraph.HasNeighbors(s, step)
})
}
// HasFriendWith applies the HasEdge predicate on the "friend" edge with a given conditions (other predicates).
func HasFriendWith(preds ...predicate.User) predicate.Friendship {
return predicate.Friendship(func(s *sql.Selector) {
step := newFriendStep()
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Friendship
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.Friendship) predicate.Friendship {
return predicate.Friendship(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Friendship) predicate.Friendship {
return predicate.Friendship(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Friendship) predicate.Friendship {
return predicate.Friendship(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,303 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/ent/friendship"
"entgo.io/ent/entc/integration/multischema/ent/user"
"entgo.io/ent/schema/field"
)
// FriendshipCreate is the builder for creating a Friendship entity.
type FriendshipCreate struct {
config
mutation *FriendshipMutation
hooks []Hook
}
// SetWeight sets the "weight" field.
func (_c *FriendshipCreate) SetWeight(v int) *FriendshipCreate {
_c.mutation.SetWeight(v)
return _c
}
// SetNillableWeight sets the "weight" field if the given value is not nil.
func (_c *FriendshipCreate) SetNillableWeight(v *int) *FriendshipCreate {
if v != nil {
_c.SetWeight(*v)
}
return _c
}
// SetCreatedAt sets the "created_at" field.
func (_c *FriendshipCreate) SetCreatedAt(v time.Time) *FriendshipCreate {
_c.mutation.SetCreatedAt(v)
return _c
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (_c *FriendshipCreate) SetNillableCreatedAt(v *time.Time) *FriendshipCreate {
if v != nil {
_c.SetCreatedAt(*v)
}
return _c
}
// SetUserID sets the "user_id" field.
func (_c *FriendshipCreate) SetUserID(v int) *FriendshipCreate {
_c.mutation.SetUserID(v)
return _c
}
// SetFriendID sets the "friend_id" field.
func (_c *FriendshipCreate) SetFriendID(v int) *FriendshipCreate {
_c.mutation.SetFriendID(v)
return _c
}
// SetUser sets the "user" edge to the User entity.
func (_c *FriendshipCreate) SetUser(v *User) *FriendshipCreate {
return _c.SetUserID(v.ID)
}
// SetFriend sets the "friend" edge to the User entity.
func (_c *FriendshipCreate) SetFriend(v *User) *FriendshipCreate {
return _c.SetFriendID(v.ID)
}
// Mutation returns the FriendshipMutation object of the builder.
func (_c *FriendshipCreate) Mutation() *FriendshipMutation {
return _c.mutation
}
// Save creates the Friendship in the database.
func (_c *FriendshipCreate) Save(ctx context.Context) (*Friendship, error) {
_c.defaults()
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *FriendshipCreate) SaveX(ctx context.Context) *Friendship {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *FriendshipCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *FriendshipCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_c *FriendshipCreate) defaults() {
if _, ok := _c.mutation.Weight(); !ok {
v := friendship.DefaultWeight
_c.mutation.SetWeight(v)
}
if _, ok := _c.mutation.CreatedAt(); !ok {
v := friendship.DefaultCreatedAt()
_c.mutation.SetCreatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *FriendshipCreate) check() error {
if _, ok := _c.mutation.Weight(); !ok {
return &ValidationError{Name: "weight", err: errors.New(`ent: missing required field "Friendship.weight"`)}
}
if _, ok := _c.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Friendship.created_at"`)}
}
if _, ok := _c.mutation.UserID(); !ok {
return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "Friendship.user_id"`)}
}
if _, ok := _c.mutation.FriendID(); !ok {
return &ValidationError{Name: "friend_id", err: errors.New(`ent: missing required field "Friendship.friend_id"`)}
}
if len(_c.mutation.UserIDs()) == 0 {
return &ValidationError{Name: "user", err: errors.New(`ent: missing required edge "Friendship.user"`)}
}
if len(_c.mutation.FriendIDs()) == 0 {
return &ValidationError{Name: "friend", err: errors.New(`ent: missing required edge "Friendship.friend"`)}
}
return nil
}
func (_c *FriendshipCreate) sqlSave(ctx context.Context) (*Friendship, 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 *FriendshipCreate) createSpec() (*Friendship, *sqlgraph.CreateSpec) {
var (
_node = &Friendship{config: _c.config}
_spec = sqlgraph.NewCreateSpec(friendship.Table, sqlgraph.NewFieldSpec(friendship.FieldID, field.TypeInt))
)
_spec.Schema = _c.schemaConfig.Friendship
if value, ok := _c.mutation.Weight(); ok {
_spec.SetField(friendship.FieldWeight, field.TypeInt, value)
_node.Weight = value
}
if value, ok := _c.mutation.CreatedAt(); ok {
_spec.SetField(friendship.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = value
}
if nodes := _c.mutation.UserIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: friendship.UserTable,
Columns: []string{friendship.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _c.schemaConfig.Friendship
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.UserID = nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.FriendIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: friendship.FriendTable,
Columns: []string{friendship.FriendColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _c.schemaConfig.Friendship
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.FriendID = nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// FriendshipCreateBulk is the builder for creating many Friendship entities in bulk.
type FriendshipCreateBulk struct {
config
err error
builders []*FriendshipCreate
}
// Save creates the Friendship entities in the database.
func (_c *FriendshipCreateBulk) Save(ctx context.Context) ([]*Friendship, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*Friendship, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*FriendshipMutation)
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 *FriendshipCreateBulk) SaveX(ctx context.Context) []*Friendship {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *FriendshipCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *FriendshipCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,95 @@
// 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/entc/integration/multischema/ent/friendship"
"entgo.io/ent/entc/integration/multischema/ent/internal"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
"entgo.io/ent/schema/field"
)
// FriendshipDelete is the builder for deleting a Friendship entity.
type FriendshipDelete struct {
config
hooks []Hook
mutation *FriendshipMutation
}
// Where appends a list predicates to the FriendshipDelete builder.
func (_d *FriendshipDelete) Where(ps ...predicate.Friendship) *FriendshipDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *FriendshipDelete) 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 *FriendshipDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *FriendshipDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(friendship.Table, sqlgraph.NewFieldSpec(friendship.FieldID, field.TypeInt))
_spec.Node.Schema = _d.schemaConfig.Friendship
ctx = internal.NewSchemaConfigContext(ctx, _d.schemaConfig)
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
}
// FriendshipDeleteOne is the builder for deleting a single Friendship entity.
type FriendshipDeleteOne struct {
_d *FriendshipDelete
}
// Where appends a list predicates to the FriendshipDelete builder.
func (_d *FriendshipDeleteOne) Where(ps ...predicate.Friendship) *FriendshipDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *FriendshipDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{friendship.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *FriendshipDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,721 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/ent/friendship"
"entgo.io/ent/entc/integration/multischema/ent/internal"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
"entgo.io/ent/entc/integration/multischema/ent/user"
"entgo.io/ent/schema/field"
)
// FriendshipQuery is the builder for querying Friendship entities.
type FriendshipQuery struct {
config
ctx *QueryContext
order []friendship.OrderOption
inters []Interceptor
predicates []predicate.Friendship
withUser *UserQuery
withFriend *UserQuery
modifiers []func(*sql.Selector)
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the FriendshipQuery builder.
func (_q *FriendshipQuery) Where(ps ...predicate.Friendship) *FriendshipQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *FriendshipQuery) Limit(limit int) *FriendshipQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *FriendshipQuery) Offset(offset int) *FriendshipQuery {
_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 *FriendshipQuery) Unique(unique bool) *FriendshipQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *FriendshipQuery) Order(o ...friendship.OrderOption) *FriendshipQuery {
_q.order = append(_q.order, o...)
return _q
}
// QueryUser chains the current query on the "user" edge.
func (_q *FriendshipQuery) QueryUser() *UserQuery {
query := (&UserClient{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(friendship.Table, friendship.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, friendship.UserTable, friendship.UserColumn),
)
schemaConfig := _q.schemaConfig
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Friendship
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryFriend chains the current query on the "friend" edge.
func (_q *FriendshipQuery) QueryFriend() *UserQuery {
query := (&UserClient{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(friendship.Table, friendship.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, friendship.FriendTable, friendship.FriendColumn),
)
schemaConfig := _q.schemaConfig
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Friendship
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Friendship entity from the query.
// Returns a *NotFoundError when no Friendship was found.
func (_q *FriendshipQuery) First(ctx context.Context) (*Friendship, 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{friendship.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *FriendshipQuery) FirstX(ctx context.Context) *Friendship {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Friendship ID from the query.
// Returns a *NotFoundError when no Friendship ID was found.
func (_q *FriendshipQuery) 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{friendship.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *FriendshipQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Friendship entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Friendship entity is found.
// Returns a *NotFoundError when no Friendship entities are found.
func (_q *FriendshipQuery) Only(ctx context.Context) (*Friendship, 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{friendship.Label}
default:
return nil, &NotSingularError{friendship.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *FriendshipQuery) OnlyX(ctx context.Context) *Friendship {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Friendship ID in the query.
// Returns a *NotSingularError when more than one Friendship ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *FriendshipQuery) 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{friendship.Label}
default:
err = &NotSingularError{friendship.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *FriendshipQuery) 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 Friendships.
func (_q *FriendshipQuery) All(ctx context.Context) ([]*Friendship, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Friendship, *FriendshipQuery]()
return withInterceptors[[]*Friendship](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *FriendshipQuery) AllX(ctx context.Context) []*Friendship {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Friendship IDs.
func (_q *FriendshipQuery) 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(friendship.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *FriendshipQuery) 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 *FriendshipQuery) 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[*FriendshipQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *FriendshipQuery) 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 *FriendshipQuery) 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 *FriendshipQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the FriendshipQuery 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 *FriendshipQuery) Clone() *FriendshipQuery {
if _q == nil {
return nil
}
return &FriendshipQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]friendship.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Friendship{}, _q.predicates...),
withUser: _q.withUser.Clone(),
withFriend: _q.withFriend.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
modifiers: append([]func(*sql.Selector){}, _q.modifiers...),
}
}
// WithUser tells the query-builder to eager-load the nodes that are connected to
// the "user" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *FriendshipQuery) WithUser(opts ...func(*UserQuery)) *FriendshipQuery {
query := (&UserClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withUser = query
return _q
}
// WithFriend tells the query-builder to eager-load the nodes that are connected to
// the "friend" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *FriendshipQuery) WithFriend(opts ...func(*UserQuery)) *FriendshipQuery {
query := (&UserClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withFriend = 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 {
// Weight int `json:"weight,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Friendship.Query().
// GroupBy(friendship.FieldWeight).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *FriendshipQuery) GroupBy(field string, fields ...string) *FriendshipGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &FriendshipGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = friendship.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 {
// Weight int `json:"weight,omitempty"`
// }
//
// client.Friendship.Query().
// Select(friendship.FieldWeight).
// Scan(ctx, &v)
func (_q *FriendshipQuery) Select(fields ...string) *FriendshipSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &FriendshipSelect{FriendshipQuery: _q}
sbuild.label = friendship.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a FriendshipSelect configured with the given aggregations.
func (_q *FriendshipQuery) Aggregate(fns ...AggregateFunc) *FriendshipSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *FriendshipQuery) 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 !friendship.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 *FriendshipQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Friendship, error) {
var (
nodes = []*Friendship{}
_spec = _q.querySpec()
loadedTypes = [2]bool{
_q.withUser != nil,
_q.withFriend != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Friendship).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Friendship{config: _q.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
_spec.Node.Schema = _q.schemaConfig.Friendship
ctx = internal.NewSchemaConfigContext(ctx, _q.schemaConfig)
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := _q.withUser; query != nil {
if err := _q.loadUser(ctx, query, nodes, nil,
func(n *Friendship, e *User) { n.Edges.User = e }); err != nil {
return nil, err
}
}
if query := _q.withFriend; query != nil {
if err := _q.loadFriend(ctx, query, nodes, nil,
func(n *Friendship, e *User) { n.Edges.Friend = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *FriendshipQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*Friendship, init func(*Friendship), assign func(*Friendship, *User)) error {
ids := make([]int, 0, len(nodes))
nodeids := make(map[int][]*Friendship)
for i := range nodes {
fk := nodes[i].UserID
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(user.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 "user_id" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *FriendshipQuery) loadFriend(ctx context.Context, query *UserQuery, nodes []*Friendship, init func(*Friendship), assign func(*Friendship, *User)) error {
ids := make([]int, 0, len(nodes))
nodeids := make(map[int][]*Friendship)
for i := range nodes {
fk := nodes[i].FriendID
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(user.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 "friend_id" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *FriendshipQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Schema = _q.schemaConfig.Friendship
ctx = internal.NewSchemaConfigContext(ctx, _q.schemaConfig)
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *FriendshipQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(friendship.Table, friendship.Columns, sqlgraph.NewFieldSpec(friendship.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, friendship.FieldID)
for i := range fields {
if fields[i] != friendship.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
if _q.withUser != nil {
_spec.Node.AddColumnOnce(friendship.FieldUserID)
}
if _q.withFriend != nil {
_spec.Node.AddColumnOnce(friendship.FieldFriendID)
}
}
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 *FriendshipQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(friendship.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = friendship.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()
}
t1.Schema(_q.schemaConfig.Friendship)
ctx = internal.NewSchemaConfigContext(ctx, _q.schemaConfig)
selector.WithContext(ctx)
for _, m := range _q.modifiers {
m(selector)
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// Modify adds a query modifier for attaching custom logic to queries.
func (_q *FriendshipQuery) Modify(modifiers ...func(s *sql.Selector)) *FriendshipSelect {
_q.modifiers = append(_q.modifiers, modifiers...)
return _q.Select()
}
// FriendshipGroupBy is the group-by builder for Friendship entities.
type FriendshipGroupBy struct {
selector
build *FriendshipQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *FriendshipGroupBy) Aggregate(fns ...AggregateFunc) *FriendshipGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *FriendshipGroupBy) 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[*FriendshipQuery, *FriendshipGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *FriendshipGroupBy) sqlScan(ctx context.Context, root *FriendshipQuery, 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)
}
// FriendshipSelect is the builder for selecting fields of Friendship entities.
type FriendshipSelect struct {
*FriendshipQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *FriendshipSelect) Aggregate(fns ...AggregateFunc) *FriendshipSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *FriendshipSelect) 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[*FriendshipQuery, *FriendshipSelect](ctx, _s.FriendshipQuery, _s, _s.inters, v)
}
func (_s *FriendshipSelect) sqlScan(ctx context.Context, root *FriendshipQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(_s.fns))
for _, fn := range _s.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*_s.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// Modify adds a query modifier for attaching custom logic to queries.
func (_s *FriendshipSelect) Modify(modifiers ...func(s *sql.Selector)) *FriendshipSelect {
_s.modifiers = append(_s.modifiers, modifiers...)
return _s
}

View File

@@ -0,0 +1,317 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/ent/friendship"
"entgo.io/ent/entc/integration/multischema/ent/internal"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
"entgo.io/ent/schema/field"
)
// FriendshipUpdate is the builder for updating Friendship entities.
type FriendshipUpdate struct {
config
hooks []Hook
mutation *FriendshipMutation
modifiers []func(*sql.UpdateBuilder)
}
// Where appends a list predicates to the FriendshipUpdate builder.
func (_u *FriendshipUpdate) Where(ps ...predicate.Friendship) *FriendshipUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetWeight sets the "weight" field.
func (_u *FriendshipUpdate) SetWeight(v int) *FriendshipUpdate {
_u.mutation.ResetWeight()
_u.mutation.SetWeight(v)
return _u
}
// SetNillableWeight sets the "weight" field if the given value is not nil.
func (_u *FriendshipUpdate) SetNillableWeight(v *int) *FriendshipUpdate {
if v != nil {
_u.SetWeight(*v)
}
return _u
}
// AddWeight adds value to the "weight" field.
func (_u *FriendshipUpdate) AddWeight(v int) *FriendshipUpdate {
_u.mutation.AddWeight(v)
return _u
}
// SetCreatedAt sets the "created_at" field.
func (_u *FriendshipUpdate) SetCreatedAt(v time.Time) *FriendshipUpdate {
_u.mutation.SetCreatedAt(v)
return _u
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (_u *FriendshipUpdate) SetNillableCreatedAt(v *time.Time) *FriendshipUpdate {
if v != nil {
_u.SetCreatedAt(*v)
}
return _u
}
// Mutation returns the FriendshipMutation object of the builder.
func (_u *FriendshipUpdate) Mutation() *FriendshipMutation {
return _u.mutation
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *FriendshipUpdate) 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 *FriendshipUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *FriendshipUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *FriendshipUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *FriendshipUpdate) check() error {
if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "Friendship.user"`)
}
if _u.mutation.FriendCleared() && len(_u.mutation.FriendIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "Friendship.friend"`)
}
return nil
}
// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
func (_u *FriendshipUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *FriendshipUpdate {
_u.modifiers = append(_u.modifiers, modifiers...)
return _u
}
func (_u *FriendshipUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(friendship.Table, friendship.Columns, sqlgraph.NewFieldSpec(friendship.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.Weight(); ok {
_spec.SetField(friendship.FieldWeight, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedWeight(); ok {
_spec.AddField(friendship.FieldWeight, field.TypeInt, value)
}
if value, ok := _u.mutation.CreatedAt(); ok {
_spec.SetField(friendship.FieldCreatedAt, field.TypeTime, value)
}
_spec.Node.Schema = _u.schemaConfig.Friendship
ctx = internal.NewSchemaConfigContext(ctx, _u.schemaConfig)
_spec.AddModifiers(_u.modifiers...)
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{friendship.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// FriendshipUpdateOne is the builder for updating a single Friendship entity.
type FriendshipUpdateOne struct {
config
fields []string
hooks []Hook
mutation *FriendshipMutation
modifiers []func(*sql.UpdateBuilder)
}
// SetWeight sets the "weight" field.
func (_u *FriendshipUpdateOne) SetWeight(v int) *FriendshipUpdateOne {
_u.mutation.ResetWeight()
_u.mutation.SetWeight(v)
return _u
}
// SetNillableWeight sets the "weight" field if the given value is not nil.
func (_u *FriendshipUpdateOne) SetNillableWeight(v *int) *FriendshipUpdateOne {
if v != nil {
_u.SetWeight(*v)
}
return _u
}
// AddWeight adds value to the "weight" field.
func (_u *FriendshipUpdateOne) AddWeight(v int) *FriendshipUpdateOne {
_u.mutation.AddWeight(v)
return _u
}
// SetCreatedAt sets the "created_at" field.
func (_u *FriendshipUpdateOne) SetCreatedAt(v time.Time) *FriendshipUpdateOne {
_u.mutation.SetCreatedAt(v)
return _u
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (_u *FriendshipUpdateOne) SetNillableCreatedAt(v *time.Time) *FriendshipUpdateOne {
if v != nil {
_u.SetCreatedAt(*v)
}
return _u
}
// Mutation returns the FriendshipMutation object of the builder.
func (_u *FriendshipUpdateOne) Mutation() *FriendshipMutation {
return _u.mutation
}
// Where appends a list predicates to the FriendshipUpdate builder.
func (_u *FriendshipUpdateOne) Where(ps ...predicate.Friendship) *FriendshipUpdateOne {
_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 *FriendshipUpdateOne) Select(field string, fields ...string) *FriendshipUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated Friendship entity.
func (_u *FriendshipUpdateOne) Save(ctx context.Context) (*Friendship, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *FriendshipUpdateOne) SaveX(ctx context.Context) *Friendship {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *FriendshipUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *FriendshipUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *FriendshipUpdateOne) check() error {
if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "Friendship.user"`)
}
if _u.mutation.FriendCleared() && len(_u.mutation.FriendIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "Friendship.friend"`)
}
return nil
}
// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
func (_u *FriendshipUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *FriendshipUpdateOne {
_u.modifiers = append(_u.modifiers, modifiers...)
return _u
}
func (_u *FriendshipUpdateOne) sqlSave(ctx context.Context) (_node *Friendship, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(friendship.Table, friendship.Columns, sqlgraph.NewFieldSpec(friendship.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Friendship.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, friendship.FieldID)
for _, f := range fields {
if !friendship.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != friendship.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.Weight(); ok {
_spec.SetField(friendship.FieldWeight, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedWeight(); ok {
_spec.AddField(friendship.FieldWeight, field.TypeInt, value)
}
if value, ok := _u.mutation.CreatedAt(); ok {
_spec.SetField(friendship.FieldCreatedAt, field.TypeTime, value)
}
_spec.Node.Schema = _u.schemaConfig.Friendship
ctx = internal.NewSchemaConfigContext(ctx, _u.schemaConfig)
_spec.AddModifiers(_u.modifiers...)
_node = &Friendship{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{friendship.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

View 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 --feature sql/modifier,sql/schemaconfig --template ./template --header "// Copyright 2019-present Facebook Inc. All rights reserved.\n// This source code is licensed under the Apache 2.0 license found\n// in the LICENSE file in the root directory of this source tree.\n\n// Code generated by ent, DO NOT EDIT." ./schema

View File

@@ -0,0 +1,133 @@
// 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/entc/integration/multischema/ent/group"
)
// Group is the model entity for the Group schema.
type Group struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the GroupQuery when eager-loading is set.
Edges GroupEdges `json:"edges"`
selectValues sql.SelectValues
}
// GroupEdges holds the relations/edges for other nodes in the graph.
type GroupEdges struct {
// Users holds the value of the users edge.
Users []*User `json:"users,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [1]bool
}
// UsersOrErr returns the Users value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) UsersOrErr() ([]*User, error) {
if e.loadedTypes[0] {
return e.Users, nil
}
return nil, &NotLoadedError{edge: "users"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Group) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case group.FieldID:
values[i] = new(sql.NullInt64)
case group.FieldName:
values[i] = new(sql.NullString)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Group fields.
func (_m *Group) 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 group.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 group.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
_m.Name = value.String
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Group.
// This includes values selected through modifiers, order, etc.
func (_m *Group) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryUsers queries the "users" edge of the Group entity.
func (_m *Group) QueryUsers() *UserQuery {
return NewGroupClient(_m.config).QueryUsers(_m)
}
// Update returns a builder for updating this Group.
// Note that you need to call Group.Unwrap() before calling this method if this Group
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Group) Update() *GroupUpdateOne {
return NewGroupClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Group 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 *Group) Unwrap() *Group {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: Group is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Group) String() string {
var builder strings.Builder
builder.WriteString("Group(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("name=")
builder.WriteString(_m.Name)
builder.WriteByte(')')
return builder.String()
}
// Groups is a parsable slice of Group.
type Groups []*Group

View File

@@ -0,0 +1,91 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package group
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the group type in the database.
Label = "group"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// EdgeUsers holds the string denoting the users edge name in mutations.
EdgeUsers = "users"
// Table holds the table name of the group in the database.
Table = "groups"
// UsersTable is the table that holds the users relation/edge. The primary key declared below.
UsersTable = "group_users"
// UsersInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
UsersInverseTable = "users"
)
// Columns holds all SQL columns for group fields.
var Columns = []string{
FieldID,
FieldName,
}
var (
// UsersPrimaryKey and UsersColumn2 are the table columns denoting the
// primary key for the users relation (M2M).
UsersPrimaryKey = []string{"group_id", "user_id"}
)
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// DefaultName holds the default value on creation for the "name" field.
DefaultName string
)
// OrderOption defines the ordering options for the Group 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()
}
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, opts...).ToFunc()
}
// ByUsersCount orders the results by users count.
func ByUsersCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newUsersStep(), opts...)
}
}
// ByUsers orders the results by users terms.
func ByUsers(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newUsersStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
func newUsersStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UsersInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, UsersTable, UsersPrimaryKey...),
)
}

View File

@@ -0,0 +1,326 @@
// 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 group
import (
"context"
"fmt"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
)
// Mutation represents an operation that mutates the Group nodes in the graph.
type Mutation struct {
op ent.Op
typ string
name *string
clearedFields map[string]struct{}
users map[int]struct{}
removedusers map[int]struct{}
clearedusers bool
predicates []predicate.Group
}
// NewMutation creates a new Mutation for the Group entity.
func NewMutation(op ent.Op) *Mutation {
return &Mutation{
op: op,
typ: "Group",
clearedFields: make(map[string]struct{}),
}
}
// Predicates returns the list of predicates set on the mutation.
func (m *Mutation) Predicates() []predicate.Group {
return m.predicates
}
// SetName sets the "name" field.
func (m *Mutation) SetName(s string) {
m.name = &s
}
// Name returns the value of the "name" field in the mutation.
func (m *Mutation) Name() (r string, exists bool) {
v := m.name
if v == nil {
return
}
return *v, true
}
// ResetName resets all changes to the "name" field.
func (m *Mutation) ResetName() {
m.name = nil
}
// AddUserIDs adds the "users" edge to the User entity by ids.
func (m *Mutation) AddUserIDs(ids ...int) {
if m.users == nil {
m.users = make(map[int]struct{})
}
for i := range ids {
m.users[ids[i]] = struct{}{}
}
}
// ClearUsers clears the "users" edge to the User entity.
func (m *Mutation) ClearUsers() {
m.clearedusers = true
}
// UsersCleared reports if the "users" edge to the User entity was cleared.
func (m *Mutation) UsersCleared() bool {
return m.clearedusers
}
// RemoveUserIDs removes the "users" edge to the User entity by IDs.
func (m *Mutation) RemoveUserIDs(ids ...int) {
if m.removedusers == nil {
m.removedusers = make(map[int]struct{})
}
for i := range ids {
delete(m.users, ids[i])
m.removedusers[ids[i]] = struct{}{}
}
}
// RemovedUsers returns the removed IDs of the "users" edge to the User entity.
func (m *Mutation) RemovedUsersIDs() (ids []int) {
for id := range m.removedusers {
ids = append(ids, id)
}
return
}
// UsersIDs returns the "users" edge IDs in the mutation.
func (m *Mutation) UsersIDs() (ids []int) {
for id := range m.users {
ids = append(ids, id)
}
return
}
// ResetUsers resets all changes to the "users" edge.
func (m *Mutation) ResetUsers() {
m.users = nil
m.clearedusers = false
m.removedusers = nil
}
// Where appends a list predicates to the Mutation builder.
func (m *Mutation) Where(ps ...predicate.Group) {
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.Group, 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 (Group).
func (m *Mutation) Type() string {
return m.typ
}
// Fields returns all fields that were changed during this mutation. Note that in
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *Mutation) Fields() []string {
fields := make([]string, 0, 1)
if m.name != nil {
fields = append(fields, FieldName)
}
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 FieldName:
return m.Name()
}
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 Group 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 FieldName:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetName(v)
return nil
}
return fmt.Errorf("unknown Group field %s", name)
}
// AddedFields returns all numeric fields that were incremented/decremented during
// this mutation.
func (m *Mutation) AddedFields() []string {
return nil
}
// AddedField returns the numeric value that was incremented/decremented on a field
// with the given name. The second boolean return value indicates that this field
// was not set, or was not defined in the schema.
func (m *Mutation) AddedField(name string) (ent.Value, bool) {
return nil, false
}
// AddField adds the value to the field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *Mutation) AddField(name string, value ent.Value) error {
switch name {
}
return fmt.Errorf("unknown Group numeric field %s", name)
}
// ClearedFields returns all nullable fields that were cleared during this
// mutation.
func (m *Mutation) ClearedFields() []string {
return nil
}
// 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 {
return fmt.Errorf("unknown Group 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 FieldName:
m.ResetName()
return nil
}
return fmt.Errorf("unknown Group field %s", name)
}
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *Mutation) AddedEdges() []string {
edges := make([]string, 0, 1)
if m.users != nil {
edges = append(edges, EdgeUsers)
}
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 EdgeUsers:
ids := make([]ent.Value, 0, len(m.users))
for id := range m.users {
ids = append(ids, id)
}
return ids
}
return nil
}
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *Mutation) RemovedEdges() []string {
edges := make([]string, 0, 1)
if m.removedusers != nil {
edges = append(edges, EdgeUsers)
}
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 {
switch name {
case EdgeUsers:
ids := make([]ent.Value, 0, len(m.removedusers))
for id := range m.removedusers {
ids = append(ids, id)
}
return ids
}
return nil
}
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *Mutation) ClearedEdges() []string {
edges := make([]string, 0, 1)
if m.clearedusers {
edges = append(edges, EdgeUsers)
}
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 EdgeUsers:
return m.clearedusers
}
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 {
}
return fmt.Errorf("unknown Group 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 EdgeUsers:
m.ResetUsers()
return nil
}
return fmt.Errorf("unknown Group edge %s", name)
}

View File

@@ -0,0 +1,173 @@
// 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 group
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/ent/internal"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Group {
return predicate.Group(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Group {
return predicate.Group(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Group {
return predicate.Group(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldID, id))
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldName, v))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldName, v))
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldName, v))
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldIn(FieldName, vs...))
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldName, vs...))
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.Group {
return predicate.Group(sql.FieldGT(FieldName, v))
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldName, v))
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.Group {
return predicate.Group(sql.FieldLT(FieldName, v))
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldName, v))
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.Group {
return predicate.Group(sql.FieldContains(FieldName, v))
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.Group {
return predicate.Group(sql.FieldHasPrefix(FieldName, v))
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.Group {
return predicate.Group(sql.FieldHasSuffix(FieldName, v))
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.Group {
return predicate.Group(sql.FieldEqualFold(FieldName, v))
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.Group {
return predicate.Group(sql.FieldContainsFold(FieldName, v))
}
// HasUsers applies the HasEdge predicate on the "users" edge.
func HasUsers() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, UsersTable, UsersPrimaryKey...),
)
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.GroupUsers
sqlgraph.HasNeighbors(s, step)
})
}
// HasUsersWith applies the HasEdge predicate on the "users" edge with a given conditions (other predicates).
func HasUsersWith(preds ...predicate.User) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := newUsersStep()
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.GroupUsers
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.Group) predicate.Group {
return predicate.Group(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Group) predicate.Group {
return predicate.Group(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Group) predicate.Group {
return predicate.Group(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,239 @@
// 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/entc/integration/multischema/ent/group"
"entgo.io/ent/entc/integration/multischema/ent/user"
"entgo.io/ent/schema/field"
)
// GroupCreate is the builder for creating a Group entity.
type GroupCreate struct {
config
mutation *GroupMutation
hooks []Hook
}
// SetName sets the "name" field.
func (_c *GroupCreate) SetName(v string) *GroupCreate {
_c.mutation.SetName(v)
return _c
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_c *GroupCreate) SetNillableName(v *string) *GroupCreate {
if v != nil {
_c.SetName(*v)
}
return _c
}
// AddUserIDs adds the "users" edge to the User entity by IDs.
func (_c *GroupCreate) AddUserIDs(ids ...int) *GroupCreate {
_c.mutation.AddUserIDs(ids...)
return _c
}
// AddUsers adds the "users" edges to the User entity.
func (_c *GroupCreate) AddUsers(v ...*User) *GroupCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddUserIDs(ids...)
}
// Mutation returns the GroupMutation object of the builder.
func (_c *GroupCreate) Mutation() *GroupMutation {
return _c.mutation
}
// Save creates the Group in the database.
func (_c *GroupCreate) Save(ctx context.Context) (*Group, error) {
_c.defaults()
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *GroupCreate) SaveX(ctx context.Context) *Group {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *GroupCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *GroupCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_c *GroupCreate) defaults() {
if _, ok := _c.mutation.Name(); !ok {
v := group.DefaultName
_c.mutation.SetName(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *GroupCreate) check() error {
if _, ok := _c.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Group.name"`)}
}
return nil
}
func (_c *GroupCreate) sqlSave(ctx context.Context) (*Group, 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 *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
var (
_node = &Group{config: _c.config}
_spec = sqlgraph.NewCreateSpec(group.Table, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt))
)
_spec.Schema = _c.schemaConfig.Group
if value, ok := _c.mutation.Name(); ok {
_spec.SetField(group.FieldName, field.TypeString, value)
_node.Name = value
}
if nodes := _c.mutation.UsersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _c.schemaConfig.GroupUsers
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// GroupCreateBulk is the builder for creating many Group entities in bulk.
type GroupCreateBulk struct {
config
err error
builders []*GroupCreate
}
// Save creates the Group entities in the database.
func (_c *GroupCreateBulk) Save(ctx context.Context) ([]*Group, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*Group, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*GroupMutation)
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 *GroupCreateBulk) SaveX(ctx context.Context) []*Group {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *GroupCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *GroupCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,95 @@
// 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/entc/integration/multischema/ent/group"
"entgo.io/ent/entc/integration/multischema/ent/internal"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
"entgo.io/ent/schema/field"
)
// GroupDelete is the builder for deleting a Group entity.
type GroupDelete struct {
config
hooks []Hook
mutation *GroupMutation
}
// Where appends a list predicates to the GroupDelete builder.
func (_d *GroupDelete) Where(ps ...predicate.Group) *GroupDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *GroupDelete) 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 *GroupDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *GroupDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(group.Table, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt))
_spec.Node.Schema = _d.schemaConfig.Group
ctx = internal.NewSchemaConfigContext(ctx, _d.schemaConfig)
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
}
// GroupDeleteOne is the builder for deleting a single Group entity.
type GroupDeleteOne struct {
_d *GroupDelete
}
// Where appends a list predicates to the GroupDelete builder.
func (_d *GroupDeleteOne) Where(ps ...predicate.Group) *GroupDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *GroupDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{group.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *GroupDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,676 @@
// 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/entc/integration/multischema/ent/group"
"entgo.io/ent/entc/integration/multischema/ent/internal"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
"entgo.io/ent/entc/integration/multischema/ent/user"
"entgo.io/ent/schema/field"
)
// GroupQuery is the builder for querying Group entities.
type GroupQuery struct {
config
ctx *QueryContext
order []group.OrderOption
inters []Interceptor
predicates []predicate.Group
withUsers *UserQuery
modifiers []func(*sql.Selector)
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the GroupQuery builder.
func (_q *GroupQuery) Where(ps ...predicate.Group) *GroupQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *GroupQuery) Limit(limit int) *GroupQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *GroupQuery) Offset(offset int) *GroupQuery {
_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 *GroupQuery) Unique(unique bool) *GroupQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *GroupQuery) Order(o ...group.OrderOption) *GroupQuery {
_q.order = append(_q.order, o...)
return _q
}
// QueryUsers chains the current query on the "users" edge.
func (_q *GroupQuery) QueryUsers() *UserQuery {
query := (&UserClient{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(group.Table, group.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, group.UsersTable, group.UsersPrimaryKey...),
)
schemaConfig := _q.schemaConfig
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.GroupUsers
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Group entity from the query.
// Returns a *NotFoundError when no Group was found.
func (_q *GroupQuery) First(ctx context.Context) (*Group, 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{group.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *GroupQuery) FirstX(ctx context.Context) *Group {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Group ID from the query.
// Returns a *NotFoundError when no Group ID was found.
func (_q *GroupQuery) 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{group.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *GroupQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Group entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Group entity is found.
// Returns a *NotFoundError when no Group entities are found.
func (_q *GroupQuery) Only(ctx context.Context) (*Group, 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{group.Label}
default:
return nil, &NotSingularError{group.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *GroupQuery) OnlyX(ctx context.Context) *Group {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Group ID in the query.
// Returns a *NotSingularError when more than one Group ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *GroupQuery) 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{group.Label}
default:
err = &NotSingularError{group.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *GroupQuery) 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 Groups.
func (_q *GroupQuery) All(ctx context.Context) ([]*Group, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Group, *GroupQuery]()
return withInterceptors[[]*Group](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *GroupQuery) AllX(ctx context.Context) []*Group {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Group IDs.
func (_q *GroupQuery) 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(group.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *GroupQuery) 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 *GroupQuery) 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[*GroupQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *GroupQuery) 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 *GroupQuery) 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 *GroupQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the GroupQuery 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 *GroupQuery) Clone() *GroupQuery {
if _q == nil {
return nil
}
return &GroupQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]group.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Group{}, _q.predicates...),
withUsers: _q.withUsers.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
modifiers: append([]func(*sql.Selector){}, _q.modifiers...),
}
}
// WithUsers tells the query-builder to eager-load the nodes that are connected to
// the "users" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *GroupQuery) WithUsers(opts ...func(*UserQuery)) *GroupQuery {
query := (&UserClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withUsers = 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 {
// Name string `json:"name,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Group.Query().
// GroupBy(group.FieldName).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *GroupQuery) GroupBy(field string, fields ...string) *GroupGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &GroupGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = group.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 {
// Name string `json:"name,omitempty"`
// }
//
// client.Group.Query().
// Select(group.FieldName).
// Scan(ctx, &v)
func (_q *GroupQuery) Select(fields ...string) *GroupSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &GroupSelect{GroupQuery: _q}
sbuild.label = group.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a GroupSelect configured with the given aggregations.
func (_q *GroupQuery) Aggregate(fns ...AggregateFunc) *GroupSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *GroupQuery) 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 !group.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 *GroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Group, error) {
var (
nodes = []*Group{}
_spec = _q.querySpec()
loadedTypes = [1]bool{
_q.withUsers != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Group).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Group{config: _q.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
_spec.Node.Schema = _q.schemaConfig.Group
ctx = internal.NewSchemaConfigContext(ctx, _q.schemaConfig)
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := _q.withUsers; query != nil {
if err := _q.loadUsers(ctx, query, nodes,
func(n *Group) { n.Edges.Users = []*User{} },
func(n *Group, e *User) { n.Edges.Users = append(n.Edges.Users, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *GroupQuery) loadUsers(ctx context.Context, query *UserQuery, nodes []*Group, init func(*Group), assign func(*Group, *User)) error {
edgeIDs := make([]driver.Value, len(nodes))
byID := make(map[int]*Group)
nids := make(map[int]map[*Group]struct{})
for i, node := range nodes {
edgeIDs[i] = node.ID
byID[node.ID] = node
if init != nil {
init(node)
}
}
query.Where(func(s *sql.Selector) {
joinT := sql.Table(group.UsersTable)
joinT.Schema(_q.schemaConfig.GroupUsers)
s.Join(joinT).On(s.C(user.FieldID), joinT.C(group.UsersPrimaryKey[1]))
s.Where(sql.InValues(joinT.C(group.UsersPrimaryKey[0]), edgeIDs...))
columns := s.SelectedColumns()
s.Select(joinT.C(group.UsersPrimaryKey[0]))
s.AppendSelect(columns...)
s.SetDistinct(false)
})
if err := query.prepareQuery(ctx); err != nil {
return err
}
qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) {
assign := spec.Assign
values := spec.ScanValues
spec.ScanValues = func(columns []string) ([]any, error) {
values, err := values(columns[1:])
if err != nil {
return nil, err
}
return append([]any{new(sql.NullInt64)}, values...), nil
}
spec.Assign = func(columns []string, values []any) error {
outValue := int(values[0].(*sql.NullInt64).Int64)
inValue := int(values[1].(*sql.NullInt64).Int64)
if nids[inValue] == nil {
nids[inValue] = map[*Group]struct{}{byID[outValue]: {}}
return assign(columns[1:], values[1:])
}
nids[inValue][byID[outValue]] = struct{}{}
return nil
}
})
})
neighbors, err := withInterceptors[[]*User](ctx, query, qr, query.inters)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nids[n.ID]
if !ok {
return fmt.Errorf(`unexpected "users" node returned %v`, n.ID)
}
for kn := range nodes {
assign(kn, n)
}
}
return nil
}
func (_q *GroupQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Schema = _q.schemaConfig.Group
ctx = internal.NewSchemaConfigContext(ctx, _q.schemaConfig)
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *GroupQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(group.Table, group.Columns, sqlgraph.NewFieldSpec(group.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, group.FieldID)
for i := range fields {
if fields[i] != group.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := _q.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := _q.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := _q.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := _q.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (_q *GroupQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(group.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = group.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()
}
t1.Schema(_q.schemaConfig.Group)
ctx = internal.NewSchemaConfigContext(ctx, _q.schemaConfig)
selector.WithContext(ctx)
for _, m := range _q.modifiers {
m(selector)
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// Modify adds a query modifier for attaching custom logic to queries.
func (_q *GroupQuery) Modify(modifiers ...func(s *sql.Selector)) *GroupSelect {
_q.modifiers = append(_q.modifiers, modifiers...)
return _q.Select()
}
// GroupGroupBy is the group-by builder for Group entities.
type GroupGroupBy struct {
selector
build *GroupQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *GroupGroupBy) Aggregate(fns ...AggregateFunc) *GroupGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *GroupGroupBy) 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[*GroupQuery, *GroupGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *GroupGroupBy) sqlScan(ctx context.Context, root *GroupQuery, 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)
}
// GroupSelect is the builder for selecting fields of Group entities.
type GroupSelect struct {
*GroupQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *GroupSelect) Aggregate(fns ...AggregateFunc) *GroupSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *GroupSelect) 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[*GroupQuery, *GroupSelect](ctx, _s.GroupQuery, _s, _s.inters, v)
}
func (_s *GroupSelect) sqlScan(ctx context.Context, root *GroupQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(_s.fns))
for _, fn := range _s.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*_s.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// Modify adds a query modifier for attaching custom logic to queries.
func (_s *GroupSelect) Modify(modifiers ...func(s *sql.Selector)) *GroupSelect {
_s.modifiers = append(_s.modifiers, modifiers...)
return _s
}

View File

@@ -0,0 +1,403 @@
// 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/entc/integration/multischema/ent/group"
"entgo.io/ent/entc/integration/multischema/ent/internal"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
"entgo.io/ent/entc/integration/multischema/ent/user"
"entgo.io/ent/schema/field"
)
// GroupUpdate is the builder for updating Group entities.
type GroupUpdate struct {
config
hooks []Hook
mutation *GroupMutation
modifiers []func(*sql.UpdateBuilder)
}
// Where appends a list predicates to the GroupUpdate builder.
func (_u *GroupUpdate) Where(ps ...predicate.Group) *GroupUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetName sets the "name" field.
func (_u *GroupUpdate) SetName(v string) *GroupUpdate {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *GroupUpdate) SetNillableName(v *string) *GroupUpdate {
if v != nil {
_u.SetName(*v)
}
return _u
}
// AddUserIDs adds the "users" edge to the User entity by IDs.
func (_u *GroupUpdate) AddUserIDs(ids ...int) *GroupUpdate {
_u.mutation.AddUserIDs(ids...)
return _u
}
// AddUsers adds the "users" edges to the User entity.
func (_u *GroupUpdate) AddUsers(v ...*User) *GroupUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddUserIDs(ids...)
}
// Mutation returns the GroupMutation object of the builder.
func (_u *GroupUpdate) Mutation() *GroupMutation {
return _u.mutation
}
// ClearUsers clears all "users" edges to the User entity.
func (_u *GroupUpdate) ClearUsers() *GroupUpdate {
_u.mutation.ClearUsers()
return _u
}
// RemoveUserIDs removes the "users" edge to User entities by IDs.
func (_u *GroupUpdate) RemoveUserIDs(ids ...int) *GroupUpdate {
_u.mutation.RemoveUserIDs(ids...)
return _u
}
// RemoveUsers removes "users" edges to User entities.
func (_u *GroupUpdate) RemoveUsers(v ...*User) *GroupUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveUserIDs(ids...)
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *GroupUpdate) 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 *GroupUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *GroupUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *GroupUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
func (_u *GroupUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *GroupUpdate {
_u.modifiers = append(_u.modifiers, modifiers...)
return _u
}
func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
_spec := sqlgraph.NewUpdateSpec(group.Table, group.Columns, sqlgraph.NewFieldSpec(group.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.Name(); ok {
_spec.SetField(group.FieldName, field.TypeString, value)
}
if _u.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _u.schemaConfig.GroupUsers
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedUsersIDs(); len(nodes) > 0 && !_u.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _u.schemaConfig.GroupUsers
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.UsersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _u.schemaConfig.GroupUsers
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_spec.Node.Schema = _u.schemaConfig.Group
ctx = internal.NewSchemaConfigContext(ctx, _u.schemaConfig)
_spec.AddModifiers(_u.modifiers...)
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{group.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// GroupUpdateOne is the builder for updating a single Group entity.
type GroupUpdateOne struct {
config
fields []string
hooks []Hook
mutation *GroupMutation
modifiers []func(*sql.UpdateBuilder)
}
// SetName sets the "name" field.
func (_u *GroupUpdateOne) SetName(v string) *GroupUpdateOne {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *GroupUpdateOne) SetNillableName(v *string) *GroupUpdateOne {
if v != nil {
_u.SetName(*v)
}
return _u
}
// AddUserIDs adds the "users" edge to the User entity by IDs.
func (_u *GroupUpdateOne) AddUserIDs(ids ...int) *GroupUpdateOne {
_u.mutation.AddUserIDs(ids...)
return _u
}
// AddUsers adds the "users" edges to the User entity.
func (_u *GroupUpdateOne) AddUsers(v ...*User) *GroupUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddUserIDs(ids...)
}
// Mutation returns the GroupMutation object of the builder.
func (_u *GroupUpdateOne) Mutation() *GroupMutation {
return _u.mutation
}
// ClearUsers clears all "users" edges to the User entity.
func (_u *GroupUpdateOne) ClearUsers() *GroupUpdateOne {
_u.mutation.ClearUsers()
return _u
}
// RemoveUserIDs removes the "users" edge to User entities by IDs.
func (_u *GroupUpdateOne) RemoveUserIDs(ids ...int) *GroupUpdateOne {
_u.mutation.RemoveUserIDs(ids...)
return _u
}
// RemoveUsers removes "users" edges to User entities.
func (_u *GroupUpdateOne) RemoveUsers(v ...*User) *GroupUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveUserIDs(ids...)
}
// Where appends a list predicates to the GroupUpdate builder.
func (_u *GroupUpdateOne) Where(ps ...predicate.Group) *GroupUpdateOne {
_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 *GroupUpdateOne) Select(field string, fields ...string) *GroupUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated Group entity.
func (_u *GroupUpdateOne) Save(ctx context.Context) (*Group, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *GroupUpdateOne) SaveX(ctx context.Context) *Group {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *GroupUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *GroupUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
func (_u *GroupUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *GroupUpdateOne {
_u.modifiers = append(_u.modifiers, modifiers...)
return _u
}
func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error) {
_spec := sqlgraph.NewUpdateSpec(group.Table, group.Columns, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Group.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, group.FieldID)
for _, f := range fields {
if !group.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != group.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.Name(); ok {
_spec.SetField(group.FieldName, field.TypeString, value)
}
if _u.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _u.schemaConfig.GroupUsers
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedUsersIDs(); len(nodes) > 0 && !_u.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _u.schemaConfig.GroupUsers
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.UsersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _u.schemaConfig.GroupUsers
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_spec.Node.Schema = _u.schemaConfig.Group
ctx = internal.NewSchemaConfigContext(ctx, _u.schemaConfig)
_spec.AddModifiers(_u.modifiers...)
_node = &Group{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{group.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

View File

@@ -0,0 +1,251 @@
// 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/entc/integration/multischema/ent"
)
// The FriendshipFunc type is an adapter to allow the use of ordinary
// function as Friendship mutator.
type FriendshipFunc func(context.Context, *ent.FriendshipMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f FriendshipFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.FriendshipMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.FriendshipMutation", m)
}
// The GroupFunc type is an adapter to allow the use of ordinary
// function as Group mutator.
type GroupFunc func(context.Context, *ent.GroupMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f GroupFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.GroupMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GroupMutation", m)
}
// The ParentFunc type is an adapter to allow the use of ordinary
// function as Parent mutator.
type ParentFunc func(context.Context, *ent.ParentMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f ParentFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.ParentMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ParentMutation", m)
}
// The PetFunc type is an adapter to allow the use of ordinary
// function as Pet mutator.
type PetFunc func(context.Context, *ent.PetMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f PetFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.PetMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.PetMutation", m)
}
// The UserFunc type is an adapter to allow the use of ordinary
// function as User mutator.
type UserFunc func(context.Context, *ent.UserMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f UserFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.UserMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserMutation", 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...)
}

View 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.
// Code generated by ent, DO NOT EDIT.
package internal
import "context"
// SchemaConfig represents alternative schema names for all tables
// that can be passed at runtime.
type SchemaConfig struct {
CleanUser string // CleanUser table.
Friendship string // Friendship table.
Group string // Group table.
GroupUsers string // Group-users->User table.
Parent string // Parent table.
Pet string // Pet table.
User string // User table.
UserFriends string // User-friends->User table.
UserChildren string // User-children->User table.
}
type schemaCtxKey struct{}
// SchemaConfigFromContext returns a SchemaConfig stored inside a context, or empty if there isn't one.
func SchemaConfigFromContext(ctx context.Context) SchemaConfig {
config, _ := ctx.Value(schemaCtxKey{}).(SchemaConfig)
return config
}
// NewSchemaConfigContext returns a new context with the given SchemaConfig attached.
func NewSchemaConfigContext(parent context.Context, config SchemaConfig) context.Context {
return context.WithValue(parent, schemaCtxKey{}, config)
}

View 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...)
}

View File

@@ -0,0 +1,175 @@
// 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 (
// FriendshipsColumns holds the columns for the "friendships" table.
FriendshipsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "weight", Type: field.TypeInt, Default: 1},
{Name: "created_at", Type: field.TypeTime},
{Name: "user_id", Type: field.TypeInt},
{Name: "friend_id", Type: field.TypeInt},
}
// FriendshipsTable holds the schema information for the "friendships" table.
FriendshipsTable = &schema.Table{
Name: "friendships",
Columns: FriendshipsColumns,
PrimaryKey: []*schema.Column{FriendshipsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "friendships_users_user",
Columns: []*schema.Column{FriendshipsColumns[3]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.NoAction,
},
{
Symbol: "friendships_users_friend",
Columns: []*schema.Column{FriendshipsColumns[4]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.NoAction,
},
},
Indexes: []*schema.Index{
{
Name: "friendship_created_at",
Unique: false,
Columns: []*schema.Column{FriendshipsColumns[2]},
},
{
Name: "friendship_user_id_friend_id",
Unique: true,
Columns: []*schema.Column{FriendshipsColumns[3], FriendshipsColumns[4]},
},
},
}
// GroupsColumns holds the columns for the "groups" table.
GroupsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "name", Type: field.TypeString, Default: "unknown"},
}
// GroupsTable holds the schema information for the "groups" table.
GroupsTable = &schema.Table{
Name: "groups",
Columns: GroupsColumns,
PrimaryKey: []*schema.Column{GroupsColumns[0]},
}
// ParentsColumns holds the columns for the "parents" table.
ParentsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "by_adoption", Type: field.TypeBool, Default: false},
{Name: "user_id", Type: field.TypeInt},
{Name: "parent_id", Type: field.TypeInt},
}
// ParentsTable holds the schema information for the "parents" table.
ParentsTable = &schema.Table{
Name: "parents",
Columns: ParentsColumns,
PrimaryKey: []*schema.Column{ParentsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "parents_users_child",
Columns: []*schema.Column{ParentsColumns[2]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.NoAction,
},
{
Symbol: "parents_users_parent",
Columns: []*schema.Column{ParentsColumns[3]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.NoAction,
},
},
Indexes: []*schema.Index{
{
Name: "parent_user_id_parent_id",
Unique: true,
Columns: []*schema.Column{ParentsColumns[2], ParentsColumns[3]},
},
},
}
// PetsColumns holds the columns for the "pets" table.
PetsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "name", Type: field.TypeString, Default: "unknown"},
{Name: "owner_id", Type: field.TypeInt, Nullable: true},
}
// PetsTable holds the schema information for the "pets" table.
PetsTable = &schema.Table{
Name: "pets",
Columns: PetsColumns,
PrimaryKey: []*schema.Column{PetsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "pets_users_pets",
Columns: []*schema.Column{PetsColumns[2]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.SetNull,
},
},
}
// UsersColumns holds the columns for the "users" table.
UsersColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "name", Type: field.TypeString, Default: "unknown"},
}
// UsersTable holds the schema information for the "users" table.
UsersTable = &schema.Table{
Name: "users",
Columns: UsersColumns,
PrimaryKey: []*schema.Column{UsersColumns[0]},
}
// GroupUsersColumns holds the columns for the "group_users" table.
GroupUsersColumns = []*schema.Column{
{Name: "group_id", Type: field.TypeInt},
{Name: "user_id", Type: field.TypeInt},
}
// GroupUsersTable holds the schema information for the "group_users" table.
GroupUsersTable = &schema.Table{
Name: "group_users",
Columns: GroupUsersColumns,
PrimaryKey: []*schema.Column{GroupUsersColumns[0], GroupUsersColumns[1]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "group_users_group_id",
Columns: []*schema.Column{GroupUsersColumns[0]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.Cascade,
},
{
Symbol: "group_users_user_id",
Columns: []*schema.Column{GroupUsersColumns[1]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.Cascade,
},
},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
FriendshipsTable,
GroupsTable,
ParentsTable,
PetsTable,
UsersTable,
GroupUsersTable,
}
)
func init() {
FriendshipsTable.ForeignKeys[0].RefTable = UsersTable
FriendshipsTable.ForeignKeys[1].RefTable = UsersTable
ParentsTable.ForeignKeys[0].RefTable = UsersTable
ParentsTable.ForeignKeys[1].RefTable = UsersTable
PetsTable.ForeignKeys[0].RefTable = UsersTable
GroupUsersTable.ForeignKeys[0].RefTable = GroupsTable
GroupUsersTable.ForeignKeys[1].RefTable = UsersTable
}

View File

@@ -0,0 +1,818 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"sync"
"time"
"entgo.io/ent"
"entgo.io/ent/entc/integration/multischema/ent/friendship"
"entgo.io/ent/entc/integration/multischema/ent/group"
"entgo.io/ent/entc/integration/multischema/ent/parent"
"entgo.io/ent/entc/integration/multischema/ent/pet"
"entgo.io/ent/entc/integration/multischema/ent/user"
)
const (
// Operation types.
OpCreate = ent.OpCreate
OpDelete = ent.OpDelete
OpDeleteOne = ent.OpDeleteOne
OpUpdate = ent.OpUpdate
OpUpdateOne = ent.OpUpdateOne
// Node types.
TypeCleanUser = "CleanUser"
TypeFriendship = "Friendship"
TypeGroup = "Group"
TypeParent = "Parent"
TypePet = "Pet"
TypeUser = "User"
)
// FriendshipMutation represents an operation that mutates the Friendship nodes in the graph.
type FriendshipMutation struct {
friendship.Mutation
config
id *int
done bool
oldValue func(context.Context) (*Friendship, error)
}
var _ ent.Mutation = (*FriendshipMutation)(nil)
// friendshipOption allows management of the mutation configuration using functional options.
type friendshipOption func(*FriendshipMutation)
// newFriendshipMutation creates new mutation for the Friendship entity.
func newFriendshipMutation(c config, op Op, opts ...friendshipOption) *FriendshipMutation {
m := &FriendshipMutation{
Mutation: *friendship.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 *FriendshipMutation) ID() (id int, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// withFriendshipID sets the ID field of the mutation.
func withFriendshipID(id int) friendshipOption {
return func(m *FriendshipMutation) {
var (
err error
once sync.Once
value *Friendship
)
m.oldValue = func(ctx context.Context) (*Friendship, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().Friendship.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withFriendship sets the old Friendship of the mutation.
func withFriendship(node *Friendship) friendshipOption {
return func(m *FriendshipMutation) {
m.oldValue = func(context.Context) (*Friendship, 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 FriendshipMutation) 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 FriendshipMutation) 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 *FriendshipMutation) 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().Friendship.Query().Where(m.Predicates()...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.Op())
}
}
// OldWeight returns the old "weight" field's value of the Friendship entity.
// If the Friendship 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 *FriendshipMutation) OldWeight(ctx context.Context) (v int, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldWeight is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldWeight requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldWeight: %w", err)
}
return oldValue.Weight, nil
}
// OldCreatedAt returns the old "created_at" field's value of the Friendship entity.
// If the Friendship 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 *FriendshipMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldCreatedAt requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err)
}
return oldValue.CreatedAt, nil
}
// OldUserID returns the old "user_id" field's value of the Friendship entity.
// If the Friendship 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 *FriendshipMutation) OldUserID(ctx context.Context) (v int, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldUserID is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldUserID requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldUserID: %w", err)
}
return oldValue.UserID, nil
}
// OldFriendID returns the old "friend_id" field's value of the Friendship entity.
// If the Friendship 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 *FriendshipMutation) OldFriendID(ctx context.Context) (v int, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldFriendID is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldFriendID requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldFriendID: %w", err)
}
return oldValue.FriendID, 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 *FriendshipMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case friendship.FieldWeight:
return m.OldWeight(ctx)
case friendship.FieldCreatedAt:
return m.OldCreatedAt(ctx)
case friendship.FieldUserID:
return m.OldUserID(ctx)
case friendship.FieldFriendID:
return m.OldFriendID(ctx)
}
return nil, fmt.Errorf("unknown Friendship field %s", name)
}
// GroupMutation represents an operation that mutates the Group nodes in the graph.
type GroupMutation struct {
group.Mutation
config
id *int
done bool
oldValue func(context.Context) (*Group, error)
}
var _ ent.Mutation = (*GroupMutation)(nil)
// groupOption allows management of the mutation configuration using functional options.
type groupOption func(*GroupMutation)
// newGroupMutation creates new mutation for the Group entity.
func newGroupMutation(c config, op Op, opts ...groupOption) *GroupMutation {
m := &GroupMutation{
Mutation: *group.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 *GroupMutation) ID() (id int, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// withGroupID sets the ID field of the mutation.
func withGroupID(id int) groupOption {
return func(m *GroupMutation) {
var (
err error
once sync.Once
value *Group
)
m.oldValue = func(ctx context.Context) (*Group, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().Group.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withGroup sets the old Group of the mutation.
func withGroup(node *Group) groupOption {
return func(m *GroupMutation) {
m.oldValue = func(context.Context) (*Group, 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 GroupMutation) 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 GroupMutation) 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 *GroupMutation) 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().Group.Query().Where(m.Predicates()...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.Op())
}
}
// OldName returns the old "name" field's value of the Group entity.
// If the Group 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 *GroupMutation) OldName(ctx context.Context) (v string, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldName is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldName requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldName: %w", err)
}
return oldValue.Name, nil
}
// 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 *GroupMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case group.FieldName:
return m.OldName(ctx)
}
return nil, fmt.Errorf("unknown Group field %s", name)
}
// ParentMutation represents an operation that mutates the Parent nodes in the graph.
type ParentMutation struct {
parent.Mutation
config
id *int
done bool
oldValue func(context.Context) (*Parent, error)
}
var _ ent.Mutation = (*ParentMutation)(nil)
// parentOption allows management of the mutation configuration using functional options.
type parentOption func(*ParentMutation)
// newParentMutation creates new mutation for the Parent entity.
func newParentMutation(c config, op Op, opts ...parentOption) *ParentMutation {
m := &ParentMutation{
Mutation: *parent.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 *ParentMutation) ID() (id int, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// withParentID sets the ID field of the mutation.
func withParentID(id int) parentOption {
return func(m *ParentMutation) {
var (
err error
once sync.Once
value *Parent
)
m.oldValue = func(ctx context.Context) (*Parent, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().Parent.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withParent sets the old Parent of the mutation.
func withParent(node *Parent) parentOption {
return func(m *ParentMutation) {
m.oldValue = func(context.Context) (*Parent, 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 ParentMutation) 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 ParentMutation) 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 *ParentMutation) 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().Parent.Query().Where(m.Predicates()...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.Op())
}
}
// OldByAdoption returns the old "by_adoption" field's value of the Parent entity.
// If the Parent 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 *ParentMutation) OldByAdoption(ctx context.Context) (v bool, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldByAdoption is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldByAdoption requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldByAdoption: %w", err)
}
return oldValue.ByAdoption, nil
}
// OldUserID returns the old "user_id" field's value of the Parent entity.
// If the Parent 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 *ParentMutation) OldUserID(ctx context.Context) (v int, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldUserID is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldUserID requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldUserID: %w", err)
}
return oldValue.UserID, nil
}
// OldParentID returns the old "parent_id" field's value of the Parent entity.
// If the Parent 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 *ParentMutation) OldParentID(ctx context.Context) (v int, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldParentID is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldParentID requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldParentID: %w", err)
}
return oldValue.ParentID, nil
}
// 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 *ParentMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case parent.FieldByAdoption:
return m.OldByAdoption(ctx)
case parent.FieldUserID:
return m.OldUserID(ctx)
case parent.FieldParentID:
return m.OldParentID(ctx)
}
return nil, fmt.Errorf("unknown Parent field %s", name)
}
// PetMutation represents an operation that mutates the Pet nodes in the graph.
type PetMutation struct {
pet.Mutation
config
id *int
done bool
oldValue func(context.Context) (*Pet, error)
}
var _ ent.Mutation = (*PetMutation)(nil)
// petOption allows management of the mutation configuration using functional options.
type petOption func(*PetMutation)
// newPetMutation creates new mutation for the Pet entity.
func newPetMutation(c config, op Op, opts ...petOption) *PetMutation {
m := &PetMutation{
Mutation: *pet.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 *PetMutation) ID() (id int, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// withPetID sets the ID field of the mutation.
func withPetID(id int) petOption {
return func(m *PetMutation) {
var (
err error
once sync.Once
value *Pet
)
m.oldValue = func(ctx context.Context) (*Pet, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().Pet.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withPet sets the old Pet of the mutation.
func withPet(node *Pet) petOption {
return func(m *PetMutation) {
m.oldValue = func(context.Context) (*Pet, 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 PetMutation) 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 PetMutation) 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 *PetMutation) 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().Pet.Query().Where(m.Predicates()...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.Op())
}
}
// OldName returns the old "name" field's value of the Pet entity.
// If the Pet 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 *PetMutation) OldName(ctx context.Context) (v string, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldName is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldName requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldName: %w", err)
}
return oldValue.Name, nil
}
// OldOwnerID returns the old "owner_id" field's value of the Pet entity.
// If the Pet 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 *PetMutation) OldOwnerID(ctx context.Context) (v int, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldOwnerID is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldOwnerID requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldOwnerID: %w", err)
}
return oldValue.OwnerID, 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 *PetMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case pet.FieldName:
return m.OldName(ctx)
case pet.FieldOwnerID:
return m.OldOwnerID(ctx)
}
return nil, fmt.Errorf("unknown Pet field %s", name)
}
// UserMutation represents an operation that mutates the User nodes in the graph.
type UserMutation struct {
user.Mutation
config
id *int
done bool
oldValue func(context.Context) (*User, error)
}
var _ ent.Mutation = (*UserMutation)(nil)
// userOption allows management of the mutation configuration using functional options.
type userOption func(*UserMutation)
// newUserMutation creates new mutation for the User entity.
func newUserMutation(c config, op Op, opts ...userOption) *UserMutation {
m := &UserMutation{
Mutation: *user.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 *UserMutation) ID() (id int, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// withUserID sets the ID field of the mutation.
func withUserID(id int) userOption {
return func(m *UserMutation) {
var (
err error
once sync.Once
value *User
)
m.oldValue = func(ctx context.Context) (*User, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().User.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withUser sets the old User of the mutation.
func withUser(node *User) userOption {
return func(m *UserMutation) {
m.oldValue = func(context.Context) (*User, 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 UserMutation) 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 UserMutation) 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 *UserMutation) 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().User.Query().Where(m.Predicates()...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.Op())
}
}
// OldName returns the old "name" field's value of the User entity.
// If the User 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 *UserMutation) OldName(ctx context.Context) (v string, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldName is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldName requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldName: %w", err)
}
return oldValue.Name, nil
}
// 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 *UserMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case user.FieldName:
return m.OldName(ctx)
}
return nil, fmt.Errorf("unknown User field %s", name)
}

View File

@@ -0,0 +1,176 @@
// 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/entc/integration/multischema/ent/parent"
"entgo.io/ent/entc/integration/multischema/ent/user"
)
// Parent is the model entity for the Parent schema.
type Parent struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// ByAdoption holds the value of the "by_adoption" field.
ByAdoption bool `json:"by_adoption,omitempty"`
// UserID holds the value of the "user_id" field.
UserID int `json:"user_id,omitempty"`
// ParentID holds the value of the "parent_id" field.
ParentID int `json:"parent_id,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the ParentQuery when eager-loading is set.
Edges ParentEdges `json:"edges"`
selectValues sql.SelectValues
}
// ParentEdges holds the relations/edges for other nodes in the graph.
type ParentEdges struct {
// Child holds the value of the child edge.
Child *User `json:"child,omitempty"`
// Parent holds the value of the parent edge.
Parent *User `json:"parent,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// ChildOrErr returns the Child value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e ParentEdges) ChildOrErr() (*User, error) {
if e.Child != nil {
return e.Child, nil
} else if e.loadedTypes[0] {
return nil, &NotFoundError{label: user.Label}
}
return nil, &NotLoadedError{edge: "child"}
}
// ParentOrErr returns the Parent value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e ParentEdges) ParentOrErr() (*User, error) {
if e.Parent != nil {
return e.Parent, nil
} else if e.loadedTypes[1] {
return nil, &NotFoundError{label: user.Label}
}
return nil, &NotLoadedError{edge: "parent"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Parent) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case parent.FieldByAdoption:
values[i] = new(sql.NullBool)
case parent.FieldID, parent.FieldUserID, parent.FieldParentID:
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 Parent fields.
func (_m *Parent) 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 parent.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 parent.FieldByAdoption:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field by_adoption", values[i])
} else if value.Valid {
_m.ByAdoption = value.Bool
}
case parent.FieldUserID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field user_id", values[i])
} else if value.Valid {
_m.UserID = int(value.Int64)
}
case parent.FieldParentID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field parent_id", values[i])
} else if value.Valid {
_m.ParentID = int(value.Int64)
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Parent.
// This includes values selected through modifiers, order, etc.
func (_m *Parent) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryChild queries the "child" edge of the Parent entity.
func (_m *Parent) QueryChild() *UserQuery {
return NewParentClient(_m.config).QueryChild(_m)
}
// QueryParent queries the "parent" edge of the Parent entity.
func (_m *Parent) QueryParent() *UserQuery {
return NewParentClient(_m.config).QueryParent(_m)
}
// Update returns a builder for updating this Parent.
// Note that you need to call Parent.Unwrap() before calling this method if this Parent
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Parent) Update() *ParentUpdateOne {
return NewParentClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Parent 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 *Parent) Unwrap() *Parent {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: Parent is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Parent) String() string {
var builder strings.Builder
builder.WriteString("Parent(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("by_adoption=")
builder.WriteString(fmt.Sprintf("%v", _m.ByAdoption))
builder.WriteString(", ")
builder.WriteString("user_id=")
builder.WriteString(fmt.Sprintf("%v", _m.UserID))
builder.WriteString(", ")
builder.WriteString("parent_id=")
builder.WriteString(fmt.Sprintf("%v", _m.ParentID))
builder.WriteByte(')')
return builder.String()
}
// Parents is a parsable slice of Parent.
type Parents []*Parent

View File

@@ -0,0 +1,419 @@
// 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 parent
import (
"context"
"fmt"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
)
// Mutation represents an operation that mutates the Parent nodes in the graph.
type Mutation struct {
op ent.Op
typ string
by_adoption *bool
clearedFields map[string]struct{}
child *int
clearedchild bool
parent *int
clearedparent bool
predicates []predicate.Parent
}
// NewMutation creates a new Mutation for the Parent entity.
func NewMutation(op ent.Op) *Mutation {
return &Mutation{
op: op,
typ: "Parent",
clearedFields: make(map[string]struct{}),
}
}
// Predicates returns the list of predicates set on the mutation.
func (m *Mutation) Predicates() []predicate.Parent {
return m.predicates
}
// SetByAdoption sets the "by_adoption" field.
func (m *Mutation) SetByAdoption(b bool) {
m.by_adoption = &b
}
// ByAdoption returns the value of the "by_adoption" field in the mutation.
func (m *Mutation) ByAdoption() (r bool, exists bool) {
v := m.by_adoption
if v == nil {
return
}
return *v, true
}
// ResetByAdoption resets all changes to the "by_adoption" field.
func (m *Mutation) ResetByAdoption() {
m.by_adoption = nil
}
// SetUserID sets the "user_id" field.
func (m *Mutation) SetUserID(i int) {
m.child = &i
}
// UserID returns the value of the "user_id" field in the mutation.
func (m *Mutation) UserID() (r int, exists bool) {
v := m.child
if v == nil {
return
}
return *v, true
}
// ResetUserID resets all changes to the "user_id" field.
func (m *Mutation) ResetUserID() {
m.child = nil
}
// SetParentID sets the "parent_id" field.
func (m *Mutation) SetParentID(i int) {
m.parent = &i
}
// ParentID returns the value of the "parent_id" field in the mutation.
func (m *Mutation) ParentID() (r int, exists bool) {
v := m.parent
if v == nil {
return
}
return *v, true
}
// ResetParentID resets all changes to the "parent_id" field.
func (m *Mutation) ResetParentID() {
m.parent = nil
}
// SetChildID sets the "child" edge to the User entity by id.
func (m *Mutation) SetChildID(id int) {
m.child = &id
}
// ClearChild clears the "child" edge to the User entity.
func (m *Mutation) ClearChild() {
m.clearedchild = true
m.clearedFields[FieldUserID] = struct{}{}
}
// ChildCleared reports if the "child" edge to the User entity was cleared.
func (m *Mutation) ChildCleared() bool {
return m.clearedchild
}
// ChildID returns the "child" edge ID in the mutation.
func (m *Mutation) ChildID() (id int, exists bool) {
if m.child != nil {
return *m.child, true
}
return
}
// ChildIDs returns the "child" edge IDs in the mutation.
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
// ChildID instead. It exists only for internal usage by the builders.
func (m *Mutation) ChildIDs() (ids []int) {
if id := m.child; id != nil {
ids = append(ids, *id)
}
return
}
// ResetChild resets all changes to the "child" edge.
func (m *Mutation) ResetChild() {
m.child = nil
m.clearedchild = false
}
// ClearParent clears the "parent" edge to the User entity.
func (m *Mutation) ClearParent() {
m.clearedparent = true
m.clearedFields[FieldParentID] = struct{}{}
}
// ParentCleared reports if the "parent" edge to the User entity was cleared.
func (m *Mutation) ParentCleared() bool {
return m.clearedparent
}
// ParentIDs returns the "parent" edge IDs in the mutation.
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
// ParentID instead. It exists only for internal usage by the builders.
func (m *Mutation) ParentIDs() (ids []int) {
if id := m.parent; id != nil {
ids = append(ids, *id)
}
return
}
// ResetParent resets all changes to the "parent" edge.
func (m *Mutation) ResetParent() {
m.parent = nil
m.clearedparent = false
}
// Where appends a list predicates to the Mutation builder.
func (m *Mutation) Where(ps ...predicate.Parent) {
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.Parent, 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 (Parent).
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, 3)
if m.by_adoption != nil {
fields = append(fields, FieldByAdoption)
}
if m.child != nil {
fields = append(fields, FieldUserID)
}
if m.parent != nil {
fields = append(fields, FieldParentID)
}
return fields
}
// Field returns the value of a field with the given name. The second boolean
// return value indicates that this field was not set, or was not defined in the
// schema.
func (m *Mutation) Field(name string) (ent.Value, bool) {
switch name {
case FieldByAdoption:
return m.ByAdoption()
case FieldUserID:
return m.UserID()
case FieldParentID:
return m.ParentID()
}
return nil, false
}
// OldField returns the old value of the field from the database. An error is
// returned if the mutation operation is not UpdateOne, or the query to the
// database failed.
func (m *Mutation) OldField(ctx context.Context, name string) (ent.Value, error) {
return nil, fmt.Errorf("unknown Parent 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 FieldByAdoption:
v, ok := value.(bool)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetByAdoption(v)
return nil
case FieldUserID:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetUserID(v)
return nil
case FieldParentID:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetParentID(v)
return nil
}
return fmt.Errorf("unknown Parent field %s", name)
}
// AddedFields returns all numeric fields that were incremented/decremented during
// this mutation.
func (m *Mutation) AddedFields() []string {
var fields []string
return fields
}
// AddedField returns the numeric value that was incremented/decremented on a field
// with the given name. The second boolean return value indicates that this field
// was not set, or was not defined in the schema.
func (m *Mutation) AddedField(name string) (ent.Value, bool) {
switch name {
}
return nil, false
}
// AddField adds the value to the field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *Mutation) AddField(name string, value ent.Value) error {
switch name {
}
return fmt.Errorf("unknown Parent numeric field %s", name)
}
// ClearedFields returns all nullable fields that were cleared during this
// mutation.
func (m *Mutation) ClearedFields() []string {
return nil
}
// 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 {
return fmt.Errorf("unknown Parent 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 FieldByAdoption:
m.ResetByAdoption()
return nil
case FieldUserID:
m.ResetUserID()
return nil
case FieldParentID:
m.ResetParentID()
return nil
}
return fmt.Errorf("unknown Parent 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.child != nil {
edges = append(edges, EdgeChild)
}
if m.parent != nil {
edges = append(edges, EdgeParent)
}
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 EdgeChild:
if id := m.child; id != nil {
return []ent.Value{*id}
}
case EdgeParent:
if id := m.parent; 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.clearedchild {
edges = append(edges, EdgeChild)
}
if m.clearedparent {
edges = append(edges, EdgeParent)
}
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 EdgeChild:
return m.clearedchild
case EdgeParent:
return m.clearedparent
}
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 EdgeChild:
m.ClearChild()
return nil
case EdgeParent:
m.ClearParent()
return nil
}
return fmt.Errorf("unknown Parent 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 EdgeChild:
m.ResetChild()
return nil
case EdgeParent:
m.ResetParent()
return nil
}
return fmt.Errorf("unknown Parent edge %s", name)
}

View File

@@ -0,0 +1,119 @@
// 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 parent
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the parent type in the database.
Label = "parent"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldByAdoption holds the string denoting the by_adoption field in the database.
FieldByAdoption = "by_adoption"
// FieldUserID holds the string denoting the user_id field in the database.
FieldUserID = "user_id"
// FieldParentID holds the string denoting the parent_id field in the database.
FieldParentID = "parent_id"
// EdgeChild holds the string denoting the child edge name in mutations.
EdgeChild = "child"
// EdgeParent holds the string denoting the parent edge name in mutations.
EdgeParent = "parent"
// Table holds the table name of the parent in the database.
Table = "parents"
// ChildTable is the table that holds the child relation/edge.
ChildTable = "parents"
// ChildInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
ChildInverseTable = "users"
// ChildColumn is the table column denoting the child relation/edge.
ChildColumn = "user_id"
// ParentTable is the table that holds the parent relation/edge.
ParentTable = "parents"
// ParentInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
ParentInverseTable = "users"
// ParentColumn is the table column denoting the parent relation/edge.
ParentColumn = "parent_id"
)
// Columns holds all SQL columns for parent fields.
var Columns = []string{
FieldID,
FieldByAdoption,
FieldUserID,
FieldParentID,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// DefaultByAdoption holds the default value on creation for the "by_adoption" field.
DefaultByAdoption bool
)
// OrderOption defines the ordering options for the Parent 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()
}
// ByByAdoption orders the results by the by_adoption field.
func ByByAdoption(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldByAdoption, opts...).ToFunc()
}
// ByUserID orders the results by the user_id field.
func ByUserID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUserID, opts...).ToFunc()
}
// ByParentID orders the results by the parent_id field.
func ByParentID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldParentID, opts...).ToFunc()
}
// ByChildField orders the results by child field.
func ByChildField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newChildStep(), sql.OrderByField(field, opts...))
}
}
// ByParentField orders the results by parent field.
func ByParentField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newParentStep(), sql.OrderByField(field, opts...))
}
}
func newChildStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(ChildInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, ChildTable, ChildColumn),
)
}
func newParentStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(ParentInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, ParentTable, ParentColumn),
)
}

View File

@@ -0,0 +1,197 @@
// 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 parent
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/ent/internal"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Parent {
return predicate.Parent(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Parent {
return predicate.Parent(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Parent {
return predicate.Parent(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Parent {
return predicate.Parent(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Parent {
return predicate.Parent(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Parent {
return predicate.Parent(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Parent {
return predicate.Parent(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Parent {
return predicate.Parent(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Parent {
return predicate.Parent(sql.FieldLTE(FieldID, id))
}
// ByAdoption applies equality check predicate on the "by_adoption" field. It's identical to ByAdoptionEQ.
func ByAdoption(v bool) predicate.Parent {
return predicate.Parent(sql.FieldEQ(FieldByAdoption, v))
}
// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
func UserID(v int) predicate.Parent {
return predicate.Parent(sql.FieldEQ(FieldUserID, v))
}
// ParentID applies equality check predicate on the "parent_id" field. It's identical to ParentIDEQ.
func ParentID(v int) predicate.Parent {
return predicate.Parent(sql.FieldEQ(FieldParentID, v))
}
// ByAdoptionEQ applies the EQ predicate on the "by_adoption" field.
func ByAdoptionEQ(v bool) predicate.Parent {
return predicate.Parent(sql.FieldEQ(FieldByAdoption, v))
}
// ByAdoptionNEQ applies the NEQ predicate on the "by_adoption" field.
func ByAdoptionNEQ(v bool) predicate.Parent {
return predicate.Parent(sql.FieldNEQ(FieldByAdoption, v))
}
// UserIDEQ applies the EQ predicate on the "user_id" field.
func UserIDEQ(v int) predicate.Parent {
return predicate.Parent(sql.FieldEQ(FieldUserID, v))
}
// UserIDNEQ applies the NEQ predicate on the "user_id" field.
func UserIDNEQ(v int) predicate.Parent {
return predicate.Parent(sql.FieldNEQ(FieldUserID, v))
}
// UserIDIn applies the In predicate on the "user_id" field.
func UserIDIn(vs ...int) predicate.Parent {
return predicate.Parent(sql.FieldIn(FieldUserID, vs...))
}
// UserIDNotIn applies the NotIn predicate on the "user_id" field.
func UserIDNotIn(vs ...int) predicate.Parent {
return predicate.Parent(sql.FieldNotIn(FieldUserID, vs...))
}
// ParentIDEQ applies the EQ predicate on the "parent_id" field.
func ParentIDEQ(v int) predicate.Parent {
return predicate.Parent(sql.FieldEQ(FieldParentID, v))
}
// ParentIDNEQ applies the NEQ predicate on the "parent_id" field.
func ParentIDNEQ(v int) predicate.Parent {
return predicate.Parent(sql.FieldNEQ(FieldParentID, v))
}
// ParentIDIn applies the In predicate on the "parent_id" field.
func ParentIDIn(vs ...int) predicate.Parent {
return predicate.Parent(sql.FieldIn(FieldParentID, vs...))
}
// ParentIDNotIn applies the NotIn predicate on the "parent_id" field.
func ParentIDNotIn(vs ...int) predicate.Parent {
return predicate.Parent(sql.FieldNotIn(FieldParentID, vs...))
}
// HasChild applies the HasEdge predicate on the "child" edge.
func HasChild() predicate.Parent {
return predicate.Parent(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, ChildTable, ChildColumn),
)
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Parent
sqlgraph.HasNeighbors(s, step)
})
}
// HasChildWith applies the HasEdge predicate on the "child" edge with a given conditions (other predicates).
func HasChildWith(preds ...predicate.User) predicate.Parent {
return predicate.Parent(func(s *sql.Selector) {
step := newChildStep()
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Parent
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasParent applies the HasEdge predicate on the "parent" edge.
func HasParent() predicate.Parent {
return predicate.Parent(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, ParentTable, ParentColumn),
)
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Parent
sqlgraph.HasNeighbors(s, step)
})
}
// HasParentWith applies the HasEdge predicate on the "parent" edge with a given conditions (other predicates).
func HasParentWith(preds ...predicate.User) predicate.Parent {
return predicate.Parent(func(s *sql.Selector) {
step := newParentStep()
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Parent
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.Parent) predicate.Parent {
return predicate.Parent(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Parent) predicate.Parent {
return predicate.Parent(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Parent) predicate.Parent {
return predicate.Parent(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,283 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/ent/parent"
"entgo.io/ent/entc/integration/multischema/ent/user"
"entgo.io/ent/schema/field"
)
// ParentCreate is the builder for creating a Parent entity.
type ParentCreate struct {
config
mutation *ParentMutation
hooks []Hook
}
// SetByAdoption sets the "by_adoption" field.
func (_c *ParentCreate) SetByAdoption(v bool) *ParentCreate {
_c.mutation.SetByAdoption(v)
return _c
}
// SetNillableByAdoption sets the "by_adoption" field if the given value is not nil.
func (_c *ParentCreate) SetNillableByAdoption(v *bool) *ParentCreate {
if v != nil {
_c.SetByAdoption(*v)
}
return _c
}
// SetUserID sets the "user_id" field.
func (_c *ParentCreate) SetUserID(v int) *ParentCreate {
_c.mutation.SetUserID(v)
return _c
}
// SetParentID sets the "parent_id" field.
func (_c *ParentCreate) SetParentID(v int) *ParentCreate {
_c.mutation.SetParentID(v)
return _c
}
// SetChildID sets the "child" edge to the User entity by ID.
func (_c *ParentCreate) SetChildID(id int) *ParentCreate {
_c.mutation.SetChildID(id)
return _c
}
// SetChild sets the "child" edge to the User entity.
func (_c *ParentCreate) SetChild(v *User) *ParentCreate {
return _c.SetChildID(v.ID)
}
// SetParent sets the "parent" edge to the User entity.
func (_c *ParentCreate) SetParent(v *User) *ParentCreate {
return _c.SetParentID(v.ID)
}
// Mutation returns the ParentMutation object of the builder.
func (_c *ParentCreate) Mutation() *ParentMutation {
return _c.mutation
}
// Save creates the Parent in the database.
func (_c *ParentCreate) Save(ctx context.Context) (*Parent, error) {
_c.defaults()
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *ParentCreate) SaveX(ctx context.Context) *Parent {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *ParentCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *ParentCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_c *ParentCreate) defaults() {
if _, ok := _c.mutation.ByAdoption(); !ok {
v := parent.DefaultByAdoption
_c.mutation.SetByAdoption(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *ParentCreate) check() error {
if _, ok := _c.mutation.ByAdoption(); !ok {
return &ValidationError{Name: "by_adoption", err: errors.New(`ent: missing required field "Parent.by_adoption"`)}
}
if _, ok := _c.mutation.UserID(); !ok {
return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "Parent.user_id"`)}
}
if _, ok := _c.mutation.ParentID(); !ok {
return &ValidationError{Name: "parent_id", err: errors.New(`ent: missing required field "Parent.parent_id"`)}
}
if len(_c.mutation.ChildIDs()) == 0 {
return &ValidationError{Name: "child", err: errors.New(`ent: missing required edge "Parent.child"`)}
}
if len(_c.mutation.ParentIDs()) == 0 {
return &ValidationError{Name: "parent", err: errors.New(`ent: missing required edge "Parent.parent"`)}
}
return nil
}
func (_c *ParentCreate) sqlSave(ctx context.Context) (*Parent, 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 *ParentCreate) createSpec() (*Parent, *sqlgraph.CreateSpec) {
var (
_node = &Parent{config: _c.config}
_spec = sqlgraph.NewCreateSpec(parent.Table, sqlgraph.NewFieldSpec(parent.FieldID, field.TypeInt))
)
_spec.Schema = _c.schemaConfig.Parent
if value, ok := _c.mutation.ByAdoption(); ok {
_spec.SetField(parent.FieldByAdoption, field.TypeBool, value)
_node.ByAdoption = value
}
if nodes := _c.mutation.ChildIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: parent.ChildTable,
Columns: []string{parent.ChildColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _c.schemaConfig.Parent
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.UserID = nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.ParentIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: parent.ParentTable,
Columns: []string{parent.ParentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _c.schemaConfig.Parent
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.ParentID = nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// ParentCreateBulk is the builder for creating many Parent entities in bulk.
type ParentCreateBulk struct {
config
err error
builders []*ParentCreate
}
// Save creates the Parent entities in the database.
func (_c *ParentCreateBulk) Save(ctx context.Context) ([]*Parent, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*Parent, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ParentMutation)
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 *ParentCreateBulk) SaveX(ctx context.Context) []*Parent {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *ParentCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *ParentCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,95 @@
// 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/entc/integration/multischema/ent/internal"
"entgo.io/ent/entc/integration/multischema/ent/parent"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
"entgo.io/ent/schema/field"
)
// ParentDelete is the builder for deleting a Parent entity.
type ParentDelete struct {
config
hooks []Hook
mutation *ParentMutation
}
// Where appends a list predicates to the ParentDelete builder.
func (_d *ParentDelete) Where(ps ...predicate.Parent) *ParentDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *ParentDelete) 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 *ParentDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *ParentDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(parent.Table, sqlgraph.NewFieldSpec(parent.FieldID, field.TypeInt))
_spec.Node.Schema = _d.schemaConfig.Parent
ctx = internal.NewSchemaConfigContext(ctx, _d.schemaConfig)
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
}
// ParentDeleteOne is the builder for deleting a single Parent entity.
type ParentDeleteOne struct {
_d *ParentDelete
}
// Where appends a list predicates to the ParentDelete builder.
func (_d *ParentDeleteOne) Where(ps ...predicate.Parent) *ParentDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *ParentDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{parent.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *ParentDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,721 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/ent/internal"
"entgo.io/ent/entc/integration/multischema/ent/parent"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
"entgo.io/ent/entc/integration/multischema/ent/user"
"entgo.io/ent/schema/field"
)
// ParentQuery is the builder for querying Parent entities.
type ParentQuery struct {
config
ctx *QueryContext
order []parent.OrderOption
inters []Interceptor
predicates []predicate.Parent
withChild *UserQuery
withParent *UserQuery
modifiers []func(*sql.Selector)
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the ParentQuery builder.
func (_q *ParentQuery) Where(ps ...predicate.Parent) *ParentQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *ParentQuery) Limit(limit int) *ParentQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *ParentQuery) Offset(offset int) *ParentQuery {
_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 *ParentQuery) Unique(unique bool) *ParentQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *ParentQuery) Order(o ...parent.OrderOption) *ParentQuery {
_q.order = append(_q.order, o...)
return _q
}
// QueryChild chains the current query on the "child" edge.
func (_q *ParentQuery) QueryChild() *UserQuery {
query := (&UserClient{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(parent.Table, parent.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, parent.ChildTable, parent.ChildColumn),
)
schemaConfig := _q.schemaConfig
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Parent
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryParent chains the current query on the "parent" edge.
func (_q *ParentQuery) QueryParent() *UserQuery {
query := (&UserClient{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(parent.Table, parent.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, parent.ParentTable, parent.ParentColumn),
)
schemaConfig := _q.schemaConfig
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Parent
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Parent entity from the query.
// Returns a *NotFoundError when no Parent was found.
func (_q *ParentQuery) First(ctx context.Context) (*Parent, 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{parent.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *ParentQuery) FirstX(ctx context.Context) *Parent {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Parent ID from the query.
// Returns a *NotFoundError when no Parent ID was found.
func (_q *ParentQuery) 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{parent.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *ParentQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Parent entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Parent entity is found.
// Returns a *NotFoundError when no Parent entities are found.
func (_q *ParentQuery) Only(ctx context.Context) (*Parent, 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{parent.Label}
default:
return nil, &NotSingularError{parent.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *ParentQuery) OnlyX(ctx context.Context) *Parent {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Parent ID in the query.
// Returns a *NotSingularError when more than one Parent ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *ParentQuery) 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{parent.Label}
default:
err = &NotSingularError{parent.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *ParentQuery) 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 Parents.
func (_q *ParentQuery) All(ctx context.Context) ([]*Parent, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Parent, *ParentQuery]()
return withInterceptors[[]*Parent](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *ParentQuery) AllX(ctx context.Context) []*Parent {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Parent IDs.
func (_q *ParentQuery) 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(parent.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *ParentQuery) 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 *ParentQuery) 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[*ParentQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *ParentQuery) 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 *ParentQuery) 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 *ParentQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the ParentQuery 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 *ParentQuery) Clone() *ParentQuery {
if _q == nil {
return nil
}
return &ParentQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]parent.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Parent{}, _q.predicates...),
withChild: _q.withChild.Clone(),
withParent: _q.withParent.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
modifiers: append([]func(*sql.Selector){}, _q.modifiers...),
}
}
// WithChild tells the query-builder to eager-load the nodes that are connected to
// the "child" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *ParentQuery) WithChild(opts ...func(*UserQuery)) *ParentQuery {
query := (&UserClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withChild = query
return _q
}
// WithParent tells the query-builder to eager-load the nodes that are connected to
// the "parent" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *ParentQuery) WithParent(opts ...func(*UserQuery)) *ParentQuery {
query := (&UserClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withParent = 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 {
// ByAdoption bool `json:"by_adoption,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Parent.Query().
// GroupBy(parent.FieldByAdoption).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *ParentQuery) GroupBy(field string, fields ...string) *ParentGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &ParentGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = parent.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 {
// ByAdoption bool `json:"by_adoption,omitempty"`
// }
//
// client.Parent.Query().
// Select(parent.FieldByAdoption).
// Scan(ctx, &v)
func (_q *ParentQuery) Select(fields ...string) *ParentSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &ParentSelect{ParentQuery: _q}
sbuild.label = parent.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a ParentSelect configured with the given aggregations.
func (_q *ParentQuery) Aggregate(fns ...AggregateFunc) *ParentSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *ParentQuery) 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 !parent.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 *ParentQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Parent, error) {
var (
nodes = []*Parent{}
_spec = _q.querySpec()
loadedTypes = [2]bool{
_q.withChild != nil,
_q.withParent != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Parent).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Parent{config: _q.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
_spec.Node.Schema = _q.schemaConfig.Parent
ctx = internal.NewSchemaConfigContext(ctx, _q.schemaConfig)
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := _q.withChild; query != nil {
if err := _q.loadChild(ctx, query, nodes, nil,
func(n *Parent, e *User) { n.Edges.Child = e }); err != nil {
return nil, err
}
}
if query := _q.withParent; query != nil {
if err := _q.loadParent(ctx, query, nodes, nil,
func(n *Parent, e *User) { n.Edges.Parent = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *ParentQuery) loadChild(ctx context.Context, query *UserQuery, nodes []*Parent, init func(*Parent), assign func(*Parent, *User)) error {
ids := make([]int, 0, len(nodes))
nodeids := make(map[int][]*Parent)
for i := range nodes {
fk := nodes[i].UserID
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(user.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 "user_id" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *ParentQuery) loadParent(ctx context.Context, query *UserQuery, nodes []*Parent, init func(*Parent), assign func(*Parent, *User)) error {
ids := make([]int, 0, len(nodes))
nodeids := make(map[int][]*Parent)
for i := range nodes {
fk := nodes[i].ParentID
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(user.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 "parent_id" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *ParentQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Schema = _q.schemaConfig.Parent
ctx = internal.NewSchemaConfigContext(ctx, _q.schemaConfig)
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *ParentQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(parent.Table, parent.Columns, sqlgraph.NewFieldSpec(parent.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, parent.FieldID)
for i := range fields {
if fields[i] != parent.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
if _q.withChild != nil {
_spec.Node.AddColumnOnce(parent.FieldUserID)
}
if _q.withParent != nil {
_spec.Node.AddColumnOnce(parent.FieldParentID)
}
}
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 *ParentQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(parent.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = parent.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()
}
t1.Schema(_q.schemaConfig.Parent)
ctx = internal.NewSchemaConfigContext(ctx, _q.schemaConfig)
selector.WithContext(ctx)
for _, m := range _q.modifiers {
m(selector)
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// Modify adds a query modifier for attaching custom logic to queries.
func (_q *ParentQuery) Modify(modifiers ...func(s *sql.Selector)) *ParentSelect {
_q.modifiers = append(_q.modifiers, modifiers...)
return _q.Select()
}
// ParentGroupBy is the group-by builder for Parent entities.
type ParentGroupBy struct {
selector
build *ParentQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *ParentGroupBy) Aggregate(fns ...AggregateFunc) *ParentGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *ParentGroupBy) 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[*ParentQuery, *ParentGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *ParentGroupBy) sqlScan(ctx context.Context, root *ParentQuery, 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)
}
// ParentSelect is the builder for selecting fields of Parent entities.
type ParentSelect struct {
*ParentQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *ParentSelect) Aggregate(fns ...AggregateFunc) *ParentSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *ParentSelect) 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[*ParentQuery, *ParentSelect](ctx, _s.ParentQuery, _s, _s.inters, v)
}
func (_s *ParentSelect) sqlScan(ctx context.Context, root *ParentQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(_s.fns))
for _, fn := range _s.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*_s.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// Modify adds a query modifier for attaching custom logic to queries.
func (_s *ParentSelect) Modify(modifiers ...func(s *sql.Selector)) *ParentSelect {
_s.modifiers = append(_s.modifiers, modifiers...)
return _s
}

View File

@@ -0,0 +1,262 @@
// 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/entc/integration/multischema/ent/internal"
"entgo.io/ent/entc/integration/multischema/ent/parent"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
"entgo.io/ent/schema/field"
)
// ParentUpdate is the builder for updating Parent entities.
type ParentUpdate struct {
config
hooks []Hook
mutation *ParentMutation
modifiers []func(*sql.UpdateBuilder)
}
// Where appends a list predicates to the ParentUpdate builder.
func (_u *ParentUpdate) Where(ps ...predicate.Parent) *ParentUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetByAdoption sets the "by_adoption" field.
func (_u *ParentUpdate) SetByAdoption(v bool) *ParentUpdate {
_u.mutation.SetByAdoption(v)
return _u
}
// SetNillableByAdoption sets the "by_adoption" field if the given value is not nil.
func (_u *ParentUpdate) SetNillableByAdoption(v *bool) *ParentUpdate {
if v != nil {
_u.SetByAdoption(*v)
}
return _u
}
// Mutation returns the ParentMutation object of the builder.
func (_u *ParentUpdate) Mutation() *ParentMutation {
return _u.mutation
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *ParentUpdate) 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 *ParentUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *ParentUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *ParentUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *ParentUpdate) check() error {
if _u.mutation.ChildCleared() && len(_u.mutation.ChildIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "Parent.child"`)
}
if _u.mutation.ParentCleared() && len(_u.mutation.ParentIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "Parent.parent"`)
}
return nil
}
// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
func (_u *ParentUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *ParentUpdate {
_u.modifiers = append(_u.modifiers, modifiers...)
return _u
}
func (_u *ParentUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(parent.Table, parent.Columns, sqlgraph.NewFieldSpec(parent.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.ByAdoption(); ok {
_spec.SetField(parent.FieldByAdoption, field.TypeBool, value)
}
_spec.Node.Schema = _u.schemaConfig.Parent
ctx = internal.NewSchemaConfigContext(ctx, _u.schemaConfig)
_spec.AddModifiers(_u.modifiers...)
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{parent.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// ParentUpdateOne is the builder for updating a single Parent entity.
type ParentUpdateOne struct {
config
fields []string
hooks []Hook
mutation *ParentMutation
modifiers []func(*sql.UpdateBuilder)
}
// SetByAdoption sets the "by_adoption" field.
func (_u *ParentUpdateOne) SetByAdoption(v bool) *ParentUpdateOne {
_u.mutation.SetByAdoption(v)
return _u
}
// SetNillableByAdoption sets the "by_adoption" field if the given value is not nil.
func (_u *ParentUpdateOne) SetNillableByAdoption(v *bool) *ParentUpdateOne {
if v != nil {
_u.SetByAdoption(*v)
}
return _u
}
// Mutation returns the ParentMutation object of the builder.
func (_u *ParentUpdateOne) Mutation() *ParentMutation {
return _u.mutation
}
// Where appends a list predicates to the ParentUpdate builder.
func (_u *ParentUpdateOne) Where(ps ...predicate.Parent) *ParentUpdateOne {
_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 *ParentUpdateOne) Select(field string, fields ...string) *ParentUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated Parent entity.
func (_u *ParentUpdateOne) Save(ctx context.Context) (*Parent, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *ParentUpdateOne) SaveX(ctx context.Context) *Parent {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *ParentUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *ParentUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *ParentUpdateOne) check() error {
if _u.mutation.ChildCleared() && len(_u.mutation.ChildIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "Parent.child"`)
}
if _u.mutation.ParentCleared() && len(_u.mutation.ParentIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "Parent.parent"`)
}
return nil
}
// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
func (_u *ParentUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *ParentUpdateOne {
_u.modifiers = append(_u.modifiers, modifiers...)
return _u
}
func (_u *ParentUpdateOne) sqlSave(ctx context.Context) (_node *Parent, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(parent.Table, parent.Columns, sqlgraph.NewFieldSpec(parent.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Parent.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, parent.FieldID)
for _, f := range fields {
if !parent.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != parent.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.ByAdoption(); ok {
_spec.SetField(parent.FieldByAdoption, field.TypeBool, value)
}
_spec.Node.Schema = _u.schemaConfig.Parent
ctx = internal.NewSchemaConfigContext(ctx, _u.schemaConfig)
_spec.AddModifiers(_u.modifiers...)
_node = &Parent{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{parent.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

View File

@@ -0,0 +1,147 @@
// 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/entc/integration/multischema/ent/pet"
"entgo.io/ent/entc/integration/multischema/ent/user"
)
// Pet is the model entity for the Pet schema.
type Pet struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// OwnerID holds the value of the "owner_id" field.
OwnerID int `json:"owner_id,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the PetQuery when eager-loading is set.
Edges PetEdges `json:"edges"`
selectValues sql.SelectValues
}
// PetEdges holds the relations/edges for other nodes in the graph.
type PetEdges struct {
// Owner holds the value of the owner edge.
Owner *User `json:"owner,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [1]bool
}
// OwnerOrErr returns the Owner value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e PetEdges) OwnerOrErr() (*User, error) {
if e.Owner != nil {
return e.Owner, nil
} else if e.loadedTypes[0] {
return nil, &NotFoundError{label: user.Label}
}
return nil, &NotLoadedError{edge: "owner"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Pet) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case pet.FieldID, pet.FieldOwnerID:
values[i] = new(sql.NullInt64)
case pet.FieldName:
values[i] = new(sql.NullString)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Pet fields.
func (_m *Pet) 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 pet.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 pet.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
_m.Name = value.String
}
case pet.FieldOwnerID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field owner_id", values[i])
} else if value.Valid {
_m.OwnerID = int(value.Int64)
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Pet.
// This includes values selected through modifiers, order, etc.
func (_m *Pet) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryOwner queries the "owner" edge of the Pet entity.
func (_m *Pet) QueryOwner() *UserQuery {
return NewPetClient(_m.config).QueryOwner(_m)
}
// Update returns a builder for updating this Pet.
// Note that you need to call Pet.Unwrap() before calling this method if this Pet
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Pet) Update() *PetUpdateOne {
return NewPetClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Pet 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 *Pet) Unwrap() *Pet {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: Pet is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Pet) String() string {
var builder strings.Builder
builder.WriteString("Pet(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("name=")
builder.WriteString(_m.Name)
builder.WriteString(", ")
builder.WriteString("owner_id=")
builder.WriteString(fmt.Sprintf("%v", _m.OwnerID))
builder.WriteByte(')')
return builder.String()
}
// Pets is a parsable slice of Pet.
type Pets []*Pet

View File

@@ -0,0 +1,347 @@
// 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 pet
import (
"context"
"fmt"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
)
// Mutation represents an operation that mutates the Pet nodes in the graph.
type Mutation struct {
op ent.Op
typ string
name *string
clearedFields map[string]struct{}
owner *int
clearedowner bool
predicates []predicate.Pet
}
// NewMutation creates a new Mutation for the Pet entity.
func NewMutation(op ent.Op) *Mutation {
return &Mutation{
op: op,
typ: "Pet",
clearedFields: make(map[string]struct{}),
}
}
// Predicates returns the list of predicates set on the mutation.
func (m *Mutation) Predicates() []predicate.Pet {
return m.predicates
}
// SetName sets the "name" field.
func (m *Mutation) SetName(s string) {
m.name = &s
}
// Name returns the value of the "name" field in the mutation.
func (m *Mutation) Name() (r string, exists bool) {
v := m.name
if v == nil {
return
}
return *v, true
}
// ResetName resets all changes to the "name" field.
func (m *Mutation) ResetName() {
m.name = nil
}
// SetOwnerID sets the "owner_id" field.
func (m *Mutation) SetOwnerID(i int) {
m.owner = &i
}
// OwnerID returns the value of the "owner_id" field in the mutation.
func (m *Mutation) OwnerID() (r int, exists bool) {
v := m.owner
if v == nil {
return
}
return *v, true
}
// ClearOwnerID clears the value of the "owner_id" field.
func (m *Mutation) ClearOwnerID() {
m.owner = nil
m.clearedFields[FieldOwnerID] = struct{}{}
}
// OwnerIDCleared returns if the "owner_id" field was cleared in this mutation.
func (m *Mutation) OwnerIDCleared() bool {
_, ok := m.clearedFields[FieldOwnerID]
return ok
}
// ResetOwnerID resets all changes to the "owner_id" field.
func (m *Mutation) ResetOwnerID() {
m.owner = nil
delete(m.clearedFields, FieldOwnerID)
}
// ClearOwner clears the "owner" edge to the User entity.
func (m *Mutation) ClearOwner() {
m.clearedowner = true
m.clearedFields[FieldOwnerID] = struct{}{}
}
// OwnerCleared reports if the "owner" edge to the User entity was cleared.
func (m *Mutation) OwnerCleared() bool {
return m.OwnerIDCleared() || m.clearedowner
}
// OwnerIDs returns the "owner" edge IDs in the mutation.
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
// OwnerID instead. It exists only for internal usage by the builders.
func (m *Mutation) OwnerIDs() (ids []int) {
if id := m.owner; id != nil {
ids = append(ids, *id)
}
return
}
// ResetOwner resets all changes to the "owner" edge.
func (m *Mutation) ResetOwner() {
m.owner = nil
m.clearedowner = false
}
// Where appends a list predicates to the Mutation builder.
func (m *Mutation) Where(ps ...predicate.Pet) {
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.Pet, 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 (Pet).
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.name != nil {
fields = append(fields, FieldName)
}
if m.owner != nil {
fields = append(fields, FieldOwnerID)
}
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 FieldName:
return m.Name()
case FieldOwnerID:
return m.OwnerID()
}
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 Pet 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 FieldName:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetName(v)
return nil
case FieldOwnerID:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetOwnerID(v)
return nil
}
return fmt.Errorf("unknown Pet field %s", name)
}
// AddedFields returns all numeric fields that were incremented/decremented during
// this mutation.
func (m *Mutation) AddedFields() []string {
var fields []string
return fields
}
// AddedField returns the numeric value that was incremented/decremented on a field
// with the given name. The second boolean return value indicates that this field
// was not set, or was not defined in the schema.
func (m *Mutation) AddedField(name string) (ent.Value, bool) {
switch name {
}
return nil, false
}
// AddField adds the value to the field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *Mutation) AddField(name string, value ent.Value) error {
switch name {
}
return fmt.Errorf("unknown Pet 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(FieldOwnerID) {
fields = append(fields, FieldOwnerID)
}
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 FieldOwnerID:
m.ClearOwnerID()
return nil
}
return fmt.Errorf("unknown Pet 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 FieldName:
m.ResetName()
return nil
case FieldOwnerID:
m.ResetOwnerID()
return nil
}
return fmt.Errorf("unknown Pet field %s", name)
}
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *Mutation) AddedEdges() []string {
edges := make([]string, 0, 1)
if m.owner != nil {
edges = append(edges, EdgeOwner)
}
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 EdgeOwner:
if id := m.owner; id != nil {
return []ent.Value{*id}
}
}
return nil
}
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *Mutation) RemovedEdges() []string {
edges := make([]string, 0, 1)
return edges
}
// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
// the given name in this mutation.
func (m *Mutation) RemovedIDs(name string) []ent.Value {
return nil
}
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *Mutation) ClearedEdges() []string {
edges := make([]string, 0, 1)
if m.clearedowner {
edges = append(edges, EdgeOwner)
}
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 EdgeOwner:
return m.clearedowner
}
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 EdgeOwner:
m.ClearOwner()
return nil
}
return fmt.Errorf("unknown Pet 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 EdgeOwner:
m.ResetOwner()
return nil
}
return fmt.Errorf("unknown Pet edge %s", name)
}

View 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 pet
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the pet type in the database.
Label = "pet"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldOwnerID holds the string denoting the owner_id field in the database.
FieldOwnerID = "owner_id"
// EdgeOwner holds the string denoting the owner edge name in mutations.
EdgeOwner = "owner"
// Table holds the table name of the pet in the database.
Table = "pets"
// OwnerTable is the table that holds the owner relation/edge.
OwnerTable = "pets"
// OwnerInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
OwnerInverseTable = "users"
// OwnerColumn is the table column denoting the owner relation/edge.
OwnerColumn = "owner_id"
)
// Columns holds all SQL columns for pet fields.
var Columns = []string{
FieldID,
FieldName,
FieldOwnerID,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// DefaultName holds the default value on creation for the "name" field.
DefaultName string
)
// OrderOption defines the ordering options for the Pet 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()
}
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, opts...).ToFunc()
}
// ByOwnerID orders the results by the owner_id field.
func ByOwnerID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldOwnerID, opts...).ToFunc()
}
// ByOwnerField orders the results by owner field.
func ByOwnerField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newOwnerStep(), sql.OrderByField(field, opts...))
}
}
func newOwnerStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(OwnerInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, OwnerTable, OwnerColumn),
)
}

View File

@@ -0,0 +1,208 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package pet
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/ent/internal"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Pet {
return predicate.Pet(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Pet {
return predicate.Pet(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Pet {
return predicate.Pet(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Pet {
return predicate.Pet(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Pet {
return predicate.Pet(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Pet {
return predicate.Pet(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Pet {
return predicate.Pet(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Pet {
return predicate.Pet(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Pet {
return predicate.Pet(sql.FieldLTE(FieldID, id))
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Pet {
return predicate.Pet(sql.FieldEQ(FieldName, v))
}
// OwnerID applies equality check predicate on the "owner_id" field. It's identical to OwnerIDEQ.
func OwnerID(v int) predicate.Pet {
return predicate.Pet(sql.FieldEQ(FieldOwnerID, v))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Pet {
return predicate.Pet(sql.FieldEQ(FieldName, v))
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.Pet {
return predicate.Pet(sql.FieldNEQ(FieldName, v))
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.Pet {
return predicate.Pet(sql.FieldIn(FieldName, vs...))
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.Pet {
return predicate.Pet(sql.FieldNotIn(FieldName, vs...))
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.Pet {
return predicate.Pet(sql.FieldGT(FieldName, v))
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.Pet {
return predicate.Pet(sql.FieldGTE(FieldName, v))
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.Pet {
return predicate.Pet(sql.FieldLT(FieldName, v))
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.Pet {
return predicate.Pet(sql.FieldLTE(FieldName, v))
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.Pet {
return predicate.Pet(sql.FieldContains(FieldName, v))
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.Pet {
return predicate.Pet(sql.FieldHasPrefix(FieldName, v))
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.Pet {
return predicate.Pet(sql.FieldHasSuffix(FieldName, v))
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.Pet {
return predicate.Pet(sql.FieldEqualFold(FieldName, v))
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.Pet {
return predicate.Pet(sql.FieldContainsFold(FieldName, v))
}
// OwnerIDEQ applies the EQ predicate on the "owner_id" field.
func OwnerIDEQ(v int) predicate.Pet {
return predicate.Pet(sql.FieldEQ(FieldOwnerID, v))
}
// OwnerIDNEQ applies the NEQ predicate on the "owner_id" field.
func OwnerIDNEQ(v int) predicate.Pet {
return predicate.Pet(sql.FieldNEQ(FieldOwnerID, v))
}
// OwnerIDIn applies the In predicate on the "owner_id" field.
func OwnerIDIn(vs ...int) predicate.Pet {
return predicate.Pet(sql.FieldIn(FieldOwnerID, vs...))
}
// OwnerIDNotIn applies the NotIn predicate on the "owner_id" field.
func OwnerIDNotIn(vs ...int) predicate.Pet {
return predicate.Pet(sql.FieldNotIn(FieldOwnerID, vs...))
}
// OwnerIDIsNil applies the IsNil predicate on the "owner_id" field.
func OwnerIDIsNil() predicate.Pet {
return predicate.Pet(sql.FieldIsNull(FieldOwnerID))
}
// OwnerIDNotNil applies the NotNil predicate on the "owner_id" field.
func OwnerIDNotNil() predicate.Pet {
return predicate.Pet(sql.FieldNotNull(FieldOwnerID))
}
// HasOwner applies the HasEdge predicate on the "owner" edge.
func HasOwner() predicate.Pet {
return predicate.Pet(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, OwnerTable, OwnerColumn),
)
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Pet
sqlgraph.HasNeighbors(s, step)
})
}
// HasOwnerWith applies the HasEdge predicate on the "owner" edge with a given conditions (other predicates).
func HasOwnerWith(preds ...predicate.User) predicate.Pet {
return predicate.Pet(func(s *sql.Selector) {
step := newOwnerStep()
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Pet
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.Pet) predicate.Pet {
return predicate.Pet(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Pet) predicate.Pet {
return predicate.Pet(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Pet) predicate.Pet {
return predicate.Pet(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,244 @@
// 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/entc/integration/multischema/ent/pet"
"entgo.io/ent/entc/integration/multischema/ent/user"
"entgo.io/ent/schema/field"
)
// PetCreate is the builder for creating a Pet entity.
type PetCreate struct {
config
mutation *PetMutation
hooks []Hook
}
// SetName sets the "name" field.
func (_c *PetCreate) SetName(v string) *PetCreate {
_c.mutation.SetName(v)
return _c
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_c *PetCreate) SetNillableName(v *string) *PetCreate {
if v != nil {
_c.SetName(*v)
}
return _c
}
// SetOwnerID sets the "owner_id" field.
func (_c *PetCreate) SetOwnerID(v int) *PetCreate {
_c.mutation.SetOwnerID(v)
return _c
}
// SetNillableOwnerID sets the "owner_id" field if the given value is not nil.
func (_c *PetCreate) SetNillableOwnerID(v *int) *PetCreate {
if v != nil {
_c.SetOwnerID(*v)
}
return _c
}
// SetOwner sets the "owner" edge to the User entity.
func (_c *PetCreate) SetOwner(v *User) *PetCreate {
return _c.SetOwnerID(v.ID)
}
// Mutation returns the PetMutation object of the builder.
func (_c *PetCreate) Mutation() *PetMutation {
return _c.mutation
}
// Save creates the Pet in the database.
func (_c *PetCreate) Save(ctx context.Context) (*Pet, error) {
_c.defaults()
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *PetCreate) SaveX(ctx context.Context) *Pet {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *PetCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *PetCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_c *PetCreate) defaults() {
if _, ok := _c.mutation.Name(); !ok {
v := pet.DefaultName
_c.mutation.SetName(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *PetCreate) check() error {
if _, ok := _c.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Pet.name"`)}
}
return nil
}
func (_c *PetCreate) sqlSave(ctx context.Context) (*Pet, 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 *PetCreate) createSpec() (*Pet, *sqlgraph.CreateSpec) {
var (
_node = &Pet{config: _c.config}
_spec = sqlgraph.NewCreateSpec(pet.Table, sqlgraph.NewFieldSpec(pet.FieldID, field.TypeInt))
)
_spec.Schema = _c.schemaConfig.Pet
if value, ok := _c.mutation.Name(); ok {
_spec.SetField(pet.FieldName, field.TypeString, value)
_node.Name = value
}
if nodes := _c.mutation.OwnerIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: pet.OwnerTable,
Columns: []string{pet.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _c.schemaConfig.Pet
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.OwnerID = nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// PetCreateBulk is the builder for creating many Pet entities in bulk.
type PetCreateBulk struct {
config
err error
builders []*PetCreate
}
// Save creates the Pet entities in the database.
func (_c *PetCreateBulk) Save(ctx context.Context) ([]*Pet, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*Pet, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*PetMutation)
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 *PetCreateBulk) SaveX(ctx context.Context) []*Pet {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *PetCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *PetCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,95 @@
// 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/entc/integration/multischema/ent/internal"
"entgo.io/ent/entc/integration/multischema/ent/pet"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
"entgo.io/ent/schema/field"
)
// PetDelete is the builder for deleting a Pet entity.
type PetDelete struct {
config
hooks []Hook
mutation *PetMutation
}
// Where appends a list predicates to the PetDelete builder.
func (_d *PetDelete) Where(ps ...predicate.Pet) *PetDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *PetDelete) 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 *PetDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *PetDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(pet.Table, sqlgraph.NewFieldSpec(pet.FieldID, field.TypeInt))
_spec.Node.Schema = _d.schemaConfig.Pet
ctx = internal.NewSchemaConfigContext(ctx, _d.schemaConfig)
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
}
// PetDeleteOne is the builder for deleting a single Pet entity.
type PetDeleteOne struct {
_d *PetDelete
}
// Where appends a list predicates to the PetDelete builder.
func (_d *PetDeleteOne) Where(ps ...predicate.Pet) *PetDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *PetDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{pet.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *PetDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,644 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/ent/internal"
"entgo.io/ent/entc/integration/multischema/ent/pet"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
"entgo.io/ent/entc/integration/multischema/ent/user"
"entgo.io/ent/schema/field"
)
// PetQuery is the builder for querying Pet entities.
type PetQuery struct {
config
ctx *QueryContext
order []pet.OrderOption
inters []Interceptor
predicates []predicate.Pet
withOwner *UserQuery
modifiers []func(*sql.Selector)
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the PetQuery builder.
func (_q *PetQuery) Where(ps ...predicate.Pet) *PetQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *PetQuery) Limit(limit int) *PetQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *PetQuery) Offset(offset int) *PetQuery {
_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 *PetQuery) Unique(unique bool) *PetQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *PetQuery) Order(o ...pet.OrderOption) *PetQuery {
_q.order = append(_q.order, o...)
return _q
}
// QueryOwner chains the current query on the "owner" edge.
func (_q *PetQuery) QueryOwner() *UserQuery {
query := (&UserClient{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(pet.Table, pet.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, pet.OwnerTable, pet.OwnerColumn),
)
schemaConfig := _q.schemaConfig
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Pet
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Pet entity from the query.
// Returns a *NotFoundError when no Pet was found.
func (_q *PetQuery) First(ctx context.Context) (*Pet, 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{pet.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *PetQuery) FirstX(ctx context.Context) *Pet {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Pet ID from the query.
// Returns a *NotFoundError when no Pet ID was found.
func (_q *PetQuery) 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{pet.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *PetQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Pet entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Pet entity is found.
// Returns a *NotFoundError when no Pet entities are found.
func (_q *PetQuery) Only(ctx context.Context) (*Pet, 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{pet.Label}
default:
return nil, &NotSingularError{pet.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *PetQuery) OnlyX(ctx context.Context) *Pet {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Pet ID in the query.
// Returns a *NotSingularError when more than one Pet ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *PetQuery) 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{pet.Label}
default:
err = &NotSingularError{pet.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *PetQuery) 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 Pets.
func (_q *PetQuery) All(ctx context.Context) ([]*Pet, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Pet, *PetQuery]()
return withInterceptors[[]*Pet](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *PetQuery) AllX(ctx context.Context) []*Pet {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Pet IDs.
func (_q *PetQuery) 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(pet.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *PetQuery) 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 *PetQuery) 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[*PetQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *PetQuery) 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 *PetQuery) 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 *PetQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the PetQuery 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 *PetQuery) Clone() *PetQuery {
if _q == nil {
return nil
}
return &PetQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]pet.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Pet{}, _q.predicates...),
withOwner: _q.withOwner.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
modifiers: append([]func(*sql.Selector){}, _q.modifiers...),
}
}
// WithOwner tells the query-builder to eager-load the nodes that are connected to
// the "owner" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *PetQuery) WithOwner(opts ...func(*UserQuery)) *PetQuery {
query := (&UserClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withOwner = 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 {
// Name string `json:"name,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Pet.Query().
// GroupBy(pet.FieldName).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *PetQuery) GroupBy(field string, fields ...string) *PetGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &PetGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = pet.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 {
// Name string `json:"name,omitempty"`
// }
//
// client.Pet.Query().
// Select(pet.FieldName).
// Scan(ctx, &v)
func (_q *PetQuery) Select(fields ...string) *PetSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &PetSelect{PetQuery: _q}
sbuild.label = pet.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a PetSelect configured with the given aggregations.
func (_q *PetQuery) Aggregate(fns ...AggregateFunc) *PetSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *PetQuery) 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 !pet.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 *PetQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Pet, error) {
var (
nodes = []*Pet{}
_spec = _q.querySpec()
loadedTypes = [1]bool{
_q.withOwner != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Pet).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Pet{config: _q.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
_spec.Node.Schema = _q.schemaConfig.Pet
ctx = internal.NewSchemaConfigContext(ctx, _q.schemaConfig)
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := _q.withOwner; query != nil {
if err := _q.loadOwner(ctx, query, nodes, nil,
func(n *Pet, e *User) { n.Edges.Owner = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *PetQuery) loadOwner(ctx context.Context, query *UserQuery, nodes []*Pet, init func(*Pet), assign func(*Pet, *User)) error {
ids := make([]int, 0, len(nodes))
nodeids := make(map[int][]*Pet)
for i := range nodes {
fk := nodes[i].OwnerID
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(user.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "owner_id" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *PetQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Schema = _q.schemaConfig.Pet
ctx = internal.NewSchemaConfigContext(ctx, _q.schemaConfig)
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *PetQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(pet.Table, pet.Columns, sqlgraph.NewFieldSpec(pet.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, pet.FieldID)
for i := range fields {
if fields[i] != pet.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
if _q.withOwner != nil {
_spec.Node.AddColumnOnce(pet.FieldOwnerID)
}
}
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 *PetQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(pet.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = pet.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()
}
t1.Schema(_q.schemaConfig.Pet)
ctx = internal.NewSchemaConfigContext(ctx, _q.schemaConfig)
selector.WithContext(ctx)
for _, m := range _q.modifiers {
m(selector)
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// Modify adds a query modifier for attaching custom logic to queries.
func (_q *PetQuery) Modify(modifiers ...func(s *sql.Selector)) *PetSelect {
_q.modifiers = append(_q.modifiers, modifiers...)
return _q.Select()
}
// PetGroupBy is the group-by builder for Pet entities.
type PetGroupBy struct {
selector
build *PetQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *PetGroupBy) Aggregate(fns ...AggregateFunc) *PetGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *PetGroupBy) 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[*PetQuery, *PetGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *PetGroupBy) sqlScan(ctx context.Context, root *PetQuery, 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)
}
// PetSelect is the builder for selecting fields of Pet entities.
type PetSelect struct {
*PetQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *PetSelect) Aggregate(fns ...AggregateFunc) *PetSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *PetSelect) 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[*PetQuery, *PetSelect](ctx, _s.PetQuery, _s, _s.inters, v)
}
func (_s *PetSelect) sqlScan(ctx context.Context, root *PetQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(_s.fns))
for _, fn := range _s.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*_s.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// Modify adds a query modifier for attaching custom logic to queries.
func (_s *PetSelect) Modify(modifiers ...func(s *sql.Selector)) *PetSelect {
_s.modifiers = append(_s.modifiers, modifiers...)
return _s
}

View File

@@ -0,0 +1,359 @@
// 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/entc/integration/multischema/ent/internal"
"entgo.io/ent/entc/integration/multischema/ent/pet"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
"entgo.io/ent/entc/integration/multischema/ent/user"
"entgo.io/ent/schema/field"
)
// PetUpdate is the builder for updating Pet entities.
type PetUpdate struct {
config
hooks []Hook
mutation *PetMutation
modifiers []func(*sql.UpdateBuilder)
}
// Where appends a list predicates to the PetUpdate builder.
func (_u *PetUpdate) Where(ps ...predicate.Pet) *PetUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetName sets the "name" field.
func (_u *PetUpdate) SetName(v string) *PetUpdate {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *PetUpdate) SetNillableName(v *string) *PetUpdate {
if v != nil {
_u.SetName(*v)
}
return _u
}
// SetOwnerID sets the "owner_id" field.
func (_u *PetUpdate) SetOwnerID(v int) *PetUpdate {
_u.mutation.SetOwnerID(v)
return _u
}
// SetNillableOwnerID sets the "owner_id" field if the given value is not nil.
func (_u *PetUpdate) SetNillableOwnerID(v *int) *PetUpdate {
if v != nil {
_u.SetOwnerID(*v)
}
return _u
}
// ClearOwnerID clears the value of the "owner_id" field.
func (_u *PetUpdate) ClearOwnerID() *PetUpdate {
_u.mutation.ClearOwnerID()
return _u
}
// SetOwner sets the "owner" edge to the User entity.
func (_u *PetUpdate) SetOwner(v *User) *PetUpdate {
return _u.SetOwnerID(v.ID)
}
// Mutation returns the PetMutation object of the builder.
func (_u *PetUpdate) Mutation() *PetMutation {
return _u.mutation
}
// ClearOwner clears the "owner" edge to the User entity.
func (_u *PetUpdate) ClearOwner() *PetUpdate {
_u.mutation.ClearOwner()
return _u
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *PetUpdate) 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 *PetUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *PetUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *PetUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
func (_u *PetUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *PetUpdate {
_u.modifiers = append(_u.modifiers, modifiers...)
return _u
}
func (_u *PetUpdate) sqlSave(ctx context.Context) (_node int, err error) {
_spec := sqlgraph.NewUpdateSpec(pet.Table, pet.Columns, sqlgraph.NewFieldSpec(pet.FieldID, field.TypeInt))
if ps := _u.mutation.Predicates(); len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Name(); ok {
_spec.SetField(pet.FieldName, field.TypeString, value)
}
if _u.mutation.OwnerCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: pet.OwnerTable,
Columns: []string{pet.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _u.schemaConfig.Pet
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.OwnerIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: pet.OwnerTable,
Columns: []string{pet.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _u.schemaConfig.Pet
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_spec.Node.Schema = _u.schemaConfig.Pet
ctx = internal.NewSchemaConfigContext(ctx, _u.schemaConfig)
_spec.AddModifiers(_u.modifiers...)
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{pet.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// PetUpdateOne is the builder for updating a single Pet entity.
type PetUpdateOne struct {
config
fields []string
hooks []Hook
mutation *PetMutation
modifiers []func(*sql.UpdateBuilder)
}
// SetName sets the "name" field.
func (_u *PetUpdateOne) SetName(v string) *PetUpdateOne {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *PetUpdateOne) SetNillableName(v *string) *PetUpdateOne {
if v != nil {
_u.SetName(*v)
}
return _u
}
// SetOwnerID sets the "owner_id" field.
func (_u *PetUpdateOne) SetOwnerID(v int) *PetUpdateOne {
_u.mutation.SetOwnerID(v)
return _u
}
// SetNillableOwnerID sets the "owner_id" field if the given value is not nil.
func (_u *PetUpdateOne) SetNillableOwnerID(v *int) *PetUpdateOne {
if v != nil {
_u.SetOwnerID(*v)
}
return _u
}
// ClearOwnerID clears the value of the "owner_id" field.
func (_u *PetUpdateOne) ClearOwnerID() *PetUpdateOne {
_u.mutation.ClearOwnerID()
return _u
}
// SetOwner sets the "owner" edge to the User entity.
func (_u *PetUpdateOne) SetOwner(v *User) *PetUpdateOne {
return _u.SetOwnerID(v.ID)
}
// Mutation returns the PetMutation object of the builder.
func (_u *PetUpdateOne) Mutation() *PetMutation {
return _u.mutation
}
// ClearOwner clears the "owner" edge to the User entity.
func (_u *PetUpdateOne) ClearOwner() *PetUpdateOne {
_u.mutation.ClearOwner()
return _u
}
// Where appends a list predicates to the PetUpdate builder.
func (_u *PetUpdateOne) Where(ps ...predicate.Pet) *PetUpdateOne {
_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 *PetUpdateOne) Select(field string, fields ...string) *PetUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated Pet entity.
func (_u *PetUpdateOne) Save(ctx context.Context) (*Pet, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *PetUpdateOne) SaveX(ctx context.Context) *Pet {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *PetUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *PetUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
func (_u *PetUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *PetUpdateOne {
_u.modifiers = append(_u.modifiers, modifiers...)
return _u
}
func (_u *PetUpdateOne) sqlSave(ctx context.Context) (_node *Pet, err error) {
_spec := sqlgraph.NewUpdateSpec(pet.Table, pet.Columns, sqlgraph.NewFieldSpec(pet.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Pet.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, pet.FieldID)
for _, f := range fields {
if !pet.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != pet.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.Name(); ok {
_spec.SetField(pet.FieldName, field.TypeString, value)
}
if _u.mutation.OwnerCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: pet.OwnerTable,
Columns: []string{pet.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _u.schemaConfig.Pet
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.OwnerIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: pet.OwnerTable,
Columns: []string{pet.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _u.schemaConfig.Pet
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_spec.Node.Schema = _u.schemaConfig.Pet
ctx = internal.NewSchemaConfigContext(ctx, _u.schemaConfig)
_spec.AddModifiers(_u.modifiers...)
_node = &Pet{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{pet.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

View File

@@ -0,0 +1,29 @@
// 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"
)
// CleanUser is the predicate function for cleanuser builders.
type CleanUser func(*sql.Selector)
// Friendship is the predicate function for friendship builders.
type Friendship func(*sql.Selector)
// Group is the predicate function for group builders.
type Group func(*sql.Selector)
// Parent is the predicate function for parent builders.
type Parent func(*sql.Selector)
// Pet is the predicate function for pet builders.
type Pet func(*sql.Selector)
// User is the predicate function for user builders.
type User func(*sql.Selector)

View File

@@ -0,0 +1,58 @@
// 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 (
"time"
"entgo.io/ent/entc/integration/multischema/ent/friendship"
"entgo.io/ent/entc/integration/multischema/ent/group"
"entgo.io/ent/entc/integration/multischema/ent/parent"
"entgo.io/ent/entc/integration/multischema/ent/pet"
"entgo.io/ent/entc/integration/multischema/ent/schema"
"entgo.io/ent/entc/integration/multischema/ent/user"
)
// 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() {
friendshipFields := schema.Friendship{}.Fields()
_ = friendshipFields
// friendshipDescWeight is the schema descriptor for weight field.
friendshipDescWeight := friendshipFields[0].Descriptor()
// friendship.DefaultWeight holds the default value on creation for the weight field.
friendship.DefaultWeight = friendshipDescWeight.Default.(int)
// friendshipDescCreatedAt is the schema descriptor for created_at field.
friendshipDescCreatedAt := friendshipFields[1].Descriptor()
// friendship.DefaultCreatedAt holds the default value on creation for the created_at field.
friendship.DefaultCreatedAt = friendshipDescCreatedAt.Default.(func() time.Time)
groupFields := schema.Group{}.Fields()
_ = groupFields
// groupDescName is the schema descriptor for name field.
groupDescName := groupFields[0].Descriptor()
// group.DefaultName holds the default value on creation for the name field.
group.DefaultName = groupDescName.Default.(string)
parentFields := schema.Parent{}.Fields()
_ = parentFields
// parentDescByAdoption is the schema descriptor for by_adoption field.
parentDescByAdoption := parentFields[0].Descriptor()
// parent.DefaultByAdoption holds the default value on creation for the by_adoption field.
parent.DefaultByAdoption = parentDescByAdoption.Default.(bool)
petFields := schema.Pet{}.Fields()
_ = petFields
// petDescName is the schema descriptor for name field.
petDescName := petFields[0].Descriptor()
// pet.DefaultName holds the default value on creation for the name field.
pet.DefaultName = petDescName.Default.(string)
userFields := schema.User{}.Fields()
_ = userFields
// userDescName is the schema descriptor for name field.
userDescName := userFields[0].Descriptor()
// user.DefaultName holds the default value on creation for the name field.
user.DefaultName = userDescName.Default.(string)
}

View 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/entc/integration/multischema/ent/runtime.go
const (
Version = "v0.0.0-00010101000000-000000000000" // Version of ent codegen.
)

View File

@@ -0,0 +1,19 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
)
// base holds the default configuration for most schemas in this package.
type base struct {
ent.Schema
}
// Annotations of the base schema.
func (base) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Schema("db1"),
}
}

View File

@@ -0,0 +1,65 @@
// 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 (
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
// Friendship holds the edge schema definition of the Friendship relationship.
type Friendship struct {
ent.Schema
}
// Fields of the Friendship.
func (Friendship) Fields() []ent.Field {
return []ent.Field{
field.Int("weight").
Default(1),
field.Time("created_at").
Default(time.Now),
field.Int("user_id").
Immutable(),
field.Int("friend_id").
Immutable(),
}
}
// Edges of the Friendship.
func (Friendship) Edges() []ent.Edge {
return []ent.Edge{
edge.To("user", User.Type).
Unique().
Required().
Immutable().
Field("user_id"),
edge.To("friend", User.Type).
Unique().
Required().
Immutable().
Field("friend_id"),
}
}
// Indexes of the Friendship.
func (Friendship) Indexes() []ent.Index {
return []ent.Index{
index.Fields("created_at"),
}
}
// Annotations of the Friendship.
func (Friendship) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Schema("db2"),
}
}

View File

@@ -0,0 +1,40 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package schema
import (
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
)
// Group holds the schema definition for the Group entity.
type Group struct {
ent.Schema
}
// Fields of the Group.
func (Group) Fields() []ent.Field {
return []ent.Field{
field.String("name").
Default("unknown"),
}
}
// Edges of the Group.
func (Group) Edges() []ent.Edge {
return []ent.Edge{
edge.To("users", User.Type),
}
}
// Annotations of the Group.
func (Group) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Schema("db2"),
}
}

View File

@@ -0,0 +1,44 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
)
// Parent holds the schema definition for the Parent entity.
type Parent struct {
base
}
// Fields of the Parent.
func (Parent) Fields() []ent.Field {
return []ent.Field{
field.Bool("by_adoption").
Default(false),
field.Int("user_id").
Immutable(),
field.Int("parent_id").
Immutable(),
}
}
// Edges of the Parent.
func (Parent) Edges() []ent.Edge {
return []ent.Edge{
edge.To("child", User.Type).
Unique().
Required().
Immutable().
Field("user_id"),
edge.To("parent", User.Type).
Unique().
Required().
Immutable().
Field("parent_id"),
}
}

View 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"
)
// Pet holds the schema definition for the Pet entity.
type Pet struct {
base
}
// Fields of the Pet.
func (Pet) Fields() []ent.Field {
return []ent.Field{
field.String("name").
Default("unknown"),
field.Int("owner_id").
Optional(),
}
}
// Edges of the Pet.
func (Pet) Edges() []ent.Edge {
return []ent.Edge{
edge.From("owner", User.Type).
Ref("pets").
Field("owner_id").
Unique(),
}
}

View File

@@ -0,0 +1,60 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package schema
import (
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
)
// User holds the schema definition for the User entity.
type User struct {
base
}
// Fields of the User.
func (User) Fields() []ent.Field {
return []ent.Field{
field.String("name").
Default("unknown"),
}
}
// Edges of the User.
func (User) Edges() []ent.Edge {
return []ent.Edge{
edge.To("pets", Pet.Type),
edge.From("groups", Group.Type).
Ref("users"),
edge.To("friends", User.Type).
Through("friendships", Friendship.Type),
edge.To("children", User.Type).
Through("parent_hood", Parent.Type).
From("parents"),
}
}
// CleanUser represents a user without its PII field.
type CleanUser struct {
ent.View
}
// Annotations of the CleanUser.
func (CleanUser) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.View("SELECT id, name FROM users"),
entsql.Schema("db1"),
}
}
// Fields of the CleanUser.
func (CleanUser) Fields() []ent.Field {
return []ent.Field{
field.String("name"),
}
}

View File

@@ -0,0 +1,16 @@
{{/*
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.
*/}}
{{/* The line below tells Intellij/GoLand to enable the autocompletion based *gen.Graph type. */}}
{{/* gotype: entgo.io/ent/entc/gen.Graph */}}
{{ define "config/options/schemaconfig" }}
// SchemaConfigFromContext exports the internal.SchemaConfigFromContext
// for external usage (inside custom predicates or modifiers).
func SchemaConfigFromContext(ctx context.Context) SchemaConfig {
return internal.SchemaConfigFromContext(ctx)
}
{{ end }}

View File

@@ -0,0 +1,229 @@
// 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
// CleanUser is the client for interacting with the CleanUser builders.
CleanUser *CleanUserClient
// Friendship is the client for interacting with the Friendship builders.
Friendship *FriendshipClient
// Group is the client for interacting with the Group builders.
Group *GroupClient
// Parent is the client for interacting with the Parent builders.
Parent *ParentClient
// Pet is the client for interacting with the Pet builders.
Pet *PetClient
// User is the client for interacting with the User builders.
User *UserClient
// 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.CleanUser = NewCleanUserClient(tx.config)
tx.Friendship = NewFriendshipClient(tx.config)
tx.Group = NewGroupClient(tx.config)
tx.Parent = NewParentClient(tx.config)
tx.Pet = NewPetClient(tx.config)
tx.User = NewUserClient(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: CleanUser.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)

View File

@@ -0,0 +1,229 @@
// 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/entc/integration/multischema/ent/user"
)
// User is the model entity for the User schema.
type User struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the UserQuery when eager-loading is set.
Edges UserEdges `json:"edges"`
selectValues sql.SelectValues
}
// UserEdges holds the relations/edges for other nodes in the graph.
type UserEdges struct {
// Pets holds the value of the pets edge.
Pets []*Pet `json:"pets,omitempty"`
// Groups holds the value of the groups edge.
Groups []*Group `json:"groups,omitempty"`
// Friends holds the value of the friends edge.
Friends []*User `json:"friends,omitempty"`
// Parents holds the value of the parents edge.
Parents []*User `json:"parents,omitempty"`
// Children holds the value of the children edge.
Children []*User `json:"children,omitempty"`
// Friendships holds the value of the friendships edge.
Friendships []*Friendship `json:"friendships,omitempty"`
// ParentHood holds the value of the parent_hood edge.
ParentHood []*Parent `json:"parent_hood,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [7]bool
}
// PetsOrErr returns the Pets value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) PetsOrErr() ([]*Pet, error) {
if e.loadedTypes[0] {
return e.Pets, nil
}
return nil, &NotLoadedError{edge: "pets"}
}
// GroupsOrErr returns the Groups value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) GroupsOrErr() ([]*Group, error) {
if e.loadedTypes[1] {
return e.Groups, nil
}
return nil, &NotLoadedError{edge: "groups"}
}
// FriendsOrErr returns the Friends value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) FriendsOrErr() ([]*User, error) {
if e.loadedTypes[2] {
return e.Friends, nil
}
return nil, &NotLoadedError{edge: "friends"}
}
// ParentsOrErr returns the Parents value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) ParentsOrErr() ([]*User, error) {
if e.loadedTypes[3] {
return e.Parents, nil
}
return nil, &NotLoadedError{edge: "parents"}
}
// ChildrenOrErr returns the Children value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) ChildrenOrErr() ([]*User, error) {
if e.loadedTypes[4] {
return e.Children, nil
}
return nil, &NotLoadedError{edge: "children"}
}
// FriendshipsOrErr returns the Friendships value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) FriendshipsOrErr() ([]*Friendship, error) {
if e.loadedTypes[5] {
return e.Friendships, nil
}
return nil, &NotLoadedError{edge: "friendships"}
}
// ParentHoodOrErr returns the ParentHood value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) ParentHoodOrErr() ([]*Parent, error) {
if e.loadedTypes[6] {
return e.ParentHood, nil
}
return nil, &NotLoadedError{edge: "parent_hood"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*User) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case user.FieldID:
values[i] = new(sql.NullInt64)
case user.FieldName:
values[i] = new(sql.NullString)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the User fields.
func (_m *User) 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 user.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 user.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
_m.Name = value.String
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the User.
// This includes values selected through modifiers, order, etc.
func (_m *User) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryPets queries the "pets" edge of the User entity.
func (_m *User) QueryPets() *PetQuery {
return NewUserClient(_m.config).QueryPets(_m)
}
// QueryGroups queries the "groups" edge of the User entity.
func (_m *User) QueryGroups() *GroupQuery {
return NewUserClient(_m.config).QueryGroups(_m)
}
// QueryFriends queries the "friends" edge of the User entity.
func (_m *User) QueryFriends() *UserQuery {
return NewUserClient(_m.config).QueryFriends(_m)
}
// QueryParents queries the "parents" edge of the User entity.
func (_m *User) QueryParents() *UserQuery {
return NewUserClient(_m.config).QueryParents(_m)
}
// QueryChildren queries the "children" edge of the User entity.
func (_m *User) QueryChildren() *UserQuery {
return NewUserClient(_m.config).QueryChildren(_m)
}
// QueryFriendships queries the "friendships" edge of the User entity.
func (_m *User) QueryFriendships() *FriendshipQuery {
return NewUserClient(_m.config).QueryFriendships(_m)
}
// QueryParentHood queries the "parent_hood" edge of the User entity.
func (_m *User) QueryParentHood() *ParentQuery {
return NewUserClient(_m.config).QueryParentHood(_m)
}
// Update returns a builder for updating this User.
// Note that you need to call User.Unwrap() before calling this method if this User
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *User) Update() *UserUpdateOne {
return NewUserClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the User 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 *User) Unwrap() *User {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: User is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *User) String() string {
var builder strings.Builder
builder.WriteString("User(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("name=")
builder.WriteString(_m.Name)
builder.WriteByte(')')
return builder.String()
}
// Users is a parsable slice of User.
type Users []*User

View File

@@ -0,0 +1,824 @@
// 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 user
import (
"context"
"fmt"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
)
// Mutation represents an operation that mutates the User nodes in the graph.
type Mutation struct {
op ent.Op
typ string
name *string
clearedFields map[string]struct{}
pets map[int]struct{}
removedpets map[int]struct{}
clearedpets bool
groups map[int]struct{}
removedgroups map[int]struct{}
clearedgroups bool
friends map[int]struct{}
removedfriends map[int]struct{}
clearedfriends bool
parents map[int]struct{}
removedparents map[int]struct{}
clearedparents bool
children map[int]struct{}
removedchildren map[int]struct{}
clearedchildren bool
friendships map[int]struct{}
removedfriendships map[int]struct{}
clearedfriendships bool
parent_hood map[int]struct{}
removedparent_hood map[int]struct{}
clearedparent_hood bool
predicates []predicate.User
}
// NewMutation creates a new Mutation for the User entity.
func NewMutation(op ent.Op) *Mutation {
return &Mutation{
op: op,
typ: "User",
clearedFields: make(map[string]struct{}),
}
}
// Predicates returns the list of predicates set on the mutation.
func (m *Mutation) Predicates() []predicate.User {
return m.predicates
}
// SetName sets the "name" field.
func (m *Mutation) SetName(s string) {
m.name = &s
}
// Name returns the value of the "name" field in the mutation.
func (m *Mutation) Name() (r string, exists bool) {
v := m.name
if v == nil {
return
}
return *v, true
}
// ResetName resets all changes to the "name" field.
func (m *Mutation) ResetName() {
m.name = nil
}
// AddPetIDs adds the "pets" edge to the Pet entity by ids.
func (m *Mutation) AddPetIDs(ids ...int) {
if m.pets == nil {
m.pets = make(map[int]struct{})
}
for i := range ids {
m.pets[ids[i]] = struct{}{}
}
}
// ClearPets clears the "pets" edge to the Pet entity.
func (m *Mutation) ClearPets() {
m.clearedpets = true
}
// PetsCleared reports if the "pets" edge to the Pet entity was cleared.
func (m *Mutation) PetsCleared() bool {
return m.clearedpets
}
// RemovePetIDs removes the "pets" edge to the Pet entity by IDs.
func (m *Mutation) RemovePetIDs(ids ...int) {
if m.removedpets == nil {
m.removedpets = make(map[int]struct{})
}
for i := range ids {
delete(m.pets, ids[i])
m.removedpets[ids[i]] = struct{}{}
}
}
// RemovedPets returns the removed IDs of the "pets" edge to the Pet entity.
func (m *Mutation) RemovedPetsIDs() (ids []int) {
for id := range m.removedpets {
ids = append(ids, id)
}
return
}
// PetsIDs returns the "pets" edge IDs in the mutation.
func (m *Mutation) PetsIDs() (ids []int) {
for id := range m.pets {
ids = append(ids, id)
}
return
}
// ResetPets resets all changes to the "pets" edge.
func (m *Mutation) ResetPets() {
m.pets = nil
m.clearedpets = false
m.removedpets = nil
}
// AddGroupIDs adds the "groups" edge to the Group entity by ids.
func (m *Mutation) AddGroupIDs(ids ...int) {
if m.groups == nil {
m.groups = make(map[int]struct{})
}
for i := range ids {
m.groups[ids[i]] = struct{}{}
}
}
// ClearGroups clears the "groups" edge to the Group entity.
func (m *Mutation) ClearGroups() {
m.clearedgroups = true
}
// GroupsCleared reports if the "groups" edge to the Group entity was cleared.
func (m *Mutation) GroupsCleared() bool {
return m.clearedgroups
}
// RemoveGroupIDs removes the "groups" edge to the Group entity by IDs.
func (m *Mutation) RemoveGroupIDs(ids ...int) {
if m.removedgroups == nil {
m.removedgroups = make(map[int]struct{})
}
for i := range ids {
delete(m.groups, ids[i])
m.removedgroups[ids[i]] = struct{}{}
}
}
// RemovedGroups returns the removed IDs of the "groups" edge to the Group entity.
func (m *Mutation) RemovedGroupsIDs() (ids []int) {
for id := range m.removedgroups {
ids = append(ids, id)
}
return
}
// GroupsIDs returns the "groups" edge IDs in the mutation.
func (m *Mutation) GroupsIDs() (ids []int) {
for id := range m.groups {
ids = append(ids, id)
}
return
}
// ResetGroups resets all changes to the "groups" edge.
func (m *Mutation) ResetGroups() {
m.groups = nil
m.clearedgroups = false
m.removedgroups = nil
}
// AddFriendIDs adds the "friends" edge to the User entity by ids.
func (m *Mutation) AddFriendIDs(ids ...int) {
if m.friends == nil {
m.friends = make(map[int]struct{})
}
for i := range ids {
m.friends[ids[i]] = struct{}{}
}
}
// ClearFriends clears the "friends" edge to the User entity.
func (m *Mutation) ClearFriends() {
m.clearedfriends = true
}
// FriendsCleared reports if the "friends" edge to the User entity was cleared.
func (m *Mutation) FriendsCleared() bool {
return m.clearedfriends
}
// RemoveFriendIDs removes the "friends" edge to the User entity by IDs.
func (m *Mutation) RemoveFriendIDs(ids ...int) {
if m.removedfriends == nil {
m.removedfriends = make(map[int]struct{})
}
for i := range ids {
delete(m.friends, ids[i])
m.removedfriends[ids[i]] = struct{}{}
}
}
// RemovedFriends returns the removed IDs of the "friends" edge to the User entity.
func (m *Mutation) RemovedFriendsIDs() (ids []int) {
for id := range m.removedfriends {
ids = append(ids, id)
}
return
}
// FriendsIDs returns the "friends" edge IDs in the mutation.
func (m *Mutation) FriendsIDs() (ids []int) {
for id := range m.friends {
ids = append(ids, id)
}
return
}
// ResetFriends resets all changes to the "friends" edge.
func (m *Mutation) ResetFriends() {
m.friends = nil
m.clearedfriends = false
m.removedfriends = nil
}
// AddParentIDs adds the "parents" edge to the User entity by ids.
func (m *Mutation) AddParentIDs(ids ...int) {
if m.parents == nil {
m.parents = make(map[int]struct{})
}
for i := range ids {
m.parents[ids[i]] = struct{}{}
}
}
// ClearParents clears the "parents" edge to the User entity.
func (m *Mutation) ClearParents() {
m.clearedparents = true
}
// ParentsCleared reports if the "parents" edge to the User entity was cleared.
func (m *Mutation) ParentsCleared() bool {
return m.clearedparents
}
// RemoveParentIDs removes the "parents" edge to the User entity by IDs.
func (m *Mutation) RemoveParentIDs(ids ...int) {
if m.removedparents == nil {
m.removedparents = make(map[int]struct{})
}
for i := range ids {
delete(m.parents, ids[i])
m.removedparents[ids[i]] = struct{}{}
}
}
// RemovedParents returns the removed IDs of the "parents" edge to the User entity.
func (m *Mutation) RemovedParentsIDs() (ids []int) {
for id := range m.removedparents {
ids = append(ids, id)
}
return
}
// ParentsIDs returns the "parents" edge IDs in the mutation.
func (m *Mutation) ParentsIDs() (ids []int) {
for id := range m.parents {
ids = append(ids, id)
}
return
}
// ResetParents resets all changes to the "parents" edge.
func (m *Mutation) ResetParents() {
m.parents = nil
m.clearedparents = false
m.removedparents = nil
}
// AddChildIDs adds the "children" edge to the User entity by ids.
func (m *Mutation) AddChildIDs(ids ...int) {
if m.children == nil {
m.children = make(map[int]struct{})
}
for i := range ids {
m.children[ids[i]] = struct{}{}
}
}
// ClearChildren clears the "children" edge to the User entity.
func (m *Mutation) ClearChildren() {
m.clearedchildren = true
}
// ChildrenCleared reports if the "children" edge to the User entity was cleared.
func (m *Mutation) ChildrenCleared() bool {
return m.clearedchildren
}
// RemoveChildIDs removes the "children" edge to the User entity by IDs.
func (m *Mutation) RemoveChildIDs(ids ...int) {
if m.removedchildren == nil {
m.removedchildren = make(map[int]struct{})
}
for i := range ids {
delete(m.children, ids[i])
m.removedchildren[ids[i]] = struct{}{}
}
}
// RemovedChildren returns the removed IDs of the "children" edge to the User entity.
func (m *Mutation) RemovedChildrenIDs() (ids []int) {
for id := range m.removedchildren {
ids = append(ids, id)
}
return
}
// ChildrenIDs returns the "children" edge IDs in the mutation.
func (m *Mutation) ChildrenIDs() (ids []int) {
for id := range m.children {
ids = append(ids, id)
}
return
}
// ResetChildren resets all changes to the "children" edge.
func (m *Mutation) ResetChildren() {
m.children = nil
m.clearedchildren = false
m.removedchildren = nil
}
// AddFriendshipIDs adds the "friendships" edge to the Friendship entity by ids.
func (m *Mutation) AddFriendshipIDs(ids ...int) {
if m.friendships == nil {
m.friendships = make(map[int]struct{})
}
for i := range ids {
m.friendships[ids[i]] = struct{}{}
}
}
// ClearFriendships clears the "friendships" edge to the Friendship entity.
func (m *Mutation) ClearFriendships() {
m.clearedfriendships = true
}
// FriendshipsCleared reports if the "friendships" edge to the Friendship entity was cleared.
func (m *Mutation) FriendshipsCleared() bool {
return m.clearedfriendships
}
// RemoveFriendshipIDs removes the "friendships" edge to the Friendship entity by IDs.
func (m *Mutation) RemoveFriendshipIDs(ids ...int) {
if m.removedfriendships == nil {
m.removedfriendships = make(map[int]struct{})
}
for i := range ids {
delete(m.friendships, ids[i])
m.removedfriendships[ids[i]] = struct{}{}
}
}
// RemovedFriendships returns the removed IDs of the "friendships" edge to the Friendship entity.
func (m *Mutation) RemovedFriendshipsIDs() (ids []int) {
for id := range m.removedfriendships {
ids = append(ids, id)
}
return
}
// FriendshipsIDs returns the "friendships" edge IDs in the mutation.
func (m *Mutation) FriendshipsIDs() (ids []int) {
for id := range m.friendships {
ids = append(ids, id)
}
return
}
// ResetFriendships resets all changes to the "friendships" edge.
func (m *Mutation) ResetFriendships() {
m.friendships = nil
m.clearedfriendships = false
m.removedfriendships = nil
}
// AddParentHoodIDs adds the "parent_hood" edge to the Parent entity by ids.
func (m *Mutation) AddParentHoodIDs(ids ...int) {
if m.parent_hood == nil {
m.parent_hood = make(map[int]struct{})
}
for i := range ids {
m.parent_hood[ids[i]] = struct{}{}
}
}
// ClearParentHood clears the "parent_hood" edge to the Parent entity.
func (m *Mutation) ClearParentHood() {
m.clearedparent_hood = true
}
// ParentHoodCleared reports if the "parent_hood" edge to the Parent entity was cleared.
func (m *Mutation) ParentHoodCleared() bool {
return m.clearedparent_hood
}
// RemoveParentHoodIDs removes the "parent_hood" edge to the Parent entity by IDs.
func (m *Mutation) RemoveParentHoodIDs(ids ...int) {
if m.removedparent_hood == nil {
m.removedparent_hood = make(map[int]struct{})
}
for i := range ids {
delete(m.parent_hood, ids[i])
m.removedparent_hood[ids[i]] = struct{}{}
}
}
// RemovedParentHood returns the removed IDs of the "parent_hood" edge to the Parent entity.
func (m *Mutation) RemovedParentHoodIDs() (ids []int) {
for id := range m.removedparent_hood {
ids = append(ids, id)
}
return
}
// ParentHoodIDs returns the "parent_hood" edge IDs in the mutation.
func (m *Mutation) ParentHoodIDs() (ids []int) {
for id := range m.parent_hood {
ids = append(ids, id)
}
return
}
// ResetParentHood resets all changes to the "parent_hood" edge.
func (m *Mutation) ResetParentHood() {
m.parent_hood = nil
m.clearedparent_hood = false
m.removedparent_hood = nil
}
// Where appends a list predicates to the Mutation builder.
func (m *Mutation) Where(ps ...predicate.User) {
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.User, 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 (User).
func (m *Mutation) Type() string {
return m.typ
}
// Fields returns all fields that were changed during this mutation. Note that in
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *Mutation) Fields() []string {
fields := make([]string, 0, 1)
if m.name != nil {
fields = append(fields, FieldName)
}
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 FieldName:
return m.Name()
}
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 User 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 FieldName:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetName(v)
return nil
}
return fmt.Errorf("unknown User field %s", name)
}
// AddedFields returns all numeric fields that were incremented/decremented during
// this mutation.
func (m *Mutation) AddedFields() []string {
return nil
}
// AddedField returns the numeric value that was incremented/decremented on a field
// with the given name. The second boolean return value indicates that this field
// was not set, or was not defined in the schema.
func (m *Mutation) AddedField(name string) (ent.Value, bool) {
return nil, false
}
// AddField adds the value to the field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *Mutation) AddField(name string, value ent.Value) error {
switch name {
}
return fmt.Errorf("unknown User numeric field %s", name)
}
// ClearedFields returns all nullable fields that were cleared during this
// mutation.
func (m *Mutation) ClearedFields() []string {
return nil
}
// 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 {
return fmt.Errorf("unknown User 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 FieldName:
m.ResetName()
return nil
}
return fmt.Errorf("unknown User field %s", name)
}
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *Mutation) AddedEdges() []string {
edges := make([]string, 0, 7)
if m.pets != nil {
edges = append(edges, EdgePets)
}
if m.groups != nil {
edges = append(edges, EdgeGroups)
}
if m.friends != nil {
edges = append(edges, EdgeFriends)
}
if m.parents != nil {
edges = append(edges, EdgeParents)
}
if m.children != nil {
edges = append(edges, EdgeChildren)
}
if m.friendships != nil {
edges = append(edges, EdgeFriendships)
}
if m.parent_hood != nil {
edges = append(edges, EdgeParentHood)
}
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 EdgePets:
ids := make([]ent.Value, 0, len(m.pets))
for id := range m.pets {
ids = append(ids, id)
}
return ids
case EdgeGroups:
ids := make([]ent.Value, 0, len(m.groups))
for id := range m.groups {
ids = append(ids, id)
}
return ids
case EdgeFriends:
ids := make([]ent.Value, 0, len(m.friends))
for id := range m.friends {
ids = append(ids, id)
}
return ids
case EdgeParents:
ids := make([]ent.Value, 0, len(m.parents))
for id := range m.parents {
ids = append(ids, id)
}
return ids
case EdgeChildren:
ids := make([]ent.Value, 0, len(m.children))
for id := range m.children {
ids = append(ids, id)
}
return ids
case EdgeFriendships:
ids := make([]ent.Value, 0, len(m.friendships))
for id := range m.friendships {
ids = append(ids, id)
}
return ids
case EdgeParentHood:
ids := make([]ent.Value, 0, len(m.parent_hood))
for id := range m.parent_hood {
ids = append(ids, id)
}
return ids
}
return nil
}
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *Mutation) RemovedEdges() []string {
edges := make([]string, 0, 7)
if m.removedpets != nil {
edges = append(edges, EdgePets)
}
if m.removedgroups != nil {
edges = append(edges, EdgeGroups)
}
if m.removedfriends != nil {
edges = append(edges, EdgeFriends)
}
if m.removedparents != nil {
edges = append(edges, EdgeParents)
}
if m.removedchildren != nil {
edges = append(edges, EdgeChildren)
}
if m.removedfriendships != nil {
edges = append(edges, EdgeFriendships)
}
if m.removedparent_hood != nil {
edges = append(edges, EdgeParentHood)
}
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 {
switch name {
case EdgePets:
ids := make([]ent.Value, 0, len(m.removedpets))
for id := range m.removedpets {
ids = append(ids, id)
}
return ids
case EdgeGroups:
ids := make([]ent.Value, 0, len(m.removedgroups))
for id := range m.removedgroups {
ids = append(ids, id)
}
return ids
case EdgeFriends:
ids := make([]ent.Value, 0, len(m.removedfriends))
for id := range m.removedfriends {
ids = append(ids, id)
}
return ids
case EdgeParents:
ids := make([]ent.Value, 0, len(m.removedparents))
for id := range m.removedparents {
ids = append(ids, id)
}
return ids
case EdgeChildren:
ids := make([]ent.Value, 0, len(m.removedchildren))
for id := range m.removedchildren {
ids = append(ids, id)
}
return ids
case EdgeFriendships:
ids := make([]ent.Value, 0, len(m.removedfriendships))
for id := range m.removedfriendships {
ids = append(ids, id)
}
return ids
case EdgeParentHood:
ids := make([]ent.Value, 0, len(m.removedparent_hood))
for id := range m.removedparent_hood {
ids = append(ids, id)
}
return ids
}
return nil
}
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *Mutation) ClearedEdges() []string {
edges := make([]string, 0, 7)
if m.clearedpets {
edges = append(edges, EdgePets)
}
if m.clearedgroups {
edges = append(edges, EdgeGroups)
}
if m.clearedfriends {
edges = append(edges, EdgeFriends)
}
if m.clearedparents {
edges = append(edges, EdgeParents)
}
if m.clearedchildren {
edges = append(edges, EdgeChildren)
}
if m.clearedfriendships {
edges = append(edges, EdgeFriendships)
}
if m.clearedparent_hood {
edges = append(edges, EdgeParentHood)
}
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 EdgePets:
return m.clearedpets
case EdgeGroups:
return m.clearedgroups
case EdgeFriends:
return m.clearedfriends
case EdgeParents:
return m.clearedparents
case EdgeChildren:
return m.clearedchildren
case EdgeFriendships:
return m.clearedfriendships
case EdgeParentHood:
return m.clearedparent_hood
}
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 {
}
return fmt.Errorf("unknown User 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 EdgePets:
m.ResetPets()
return nil
case EdgeGroups:
m.ResetGroups()
return nil
case EdgeFriends:
m.ResetFriends()
return nil
case EdgeParents:
m.ResetParents()
return nil
case EdgeChildren:
m.ResetChildren()
return nil
case EdgeFriendships:
m.ResetFriendships()
return nil
case EdgeParentHood:
m.ResetParentHood()
return nil
}
return fmt.Errorf("unknown User edge %s", name)
}

View File

@@ -0,0 +1,265 @@
// 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 user
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the user type in the database.
Label = "user"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// EdgePets holds the string denoting the pets edge name in mutations.
EdgePets = "pets"
// EdgeGroups holds the string denoting the groups edge name in mutations.
EdgeGroups = "groups"
// EdgeFriends holds the string denoting the friends edge name in mutations.
EdgeFriends = "friends"
// EdgeParents holds the string denoting the parents edge name in mutations.
EdgeParents = "parents"
// EdgeChildren holds the string denoting the children edge name in mutations.
EdgeChildren = "children"
// EdgeFriendships holds the string denoting the friendships edge name in mutations.
EdgeFriendships = "friendships"
// EdgeParentHood holds the string denoting the parent_hood edge name in mutations.
EdgeParentHood = "parent_hood"
// Table holds the table name of the user in the database.
Table = "users"
// PetsTable is the table that holds the pets relation/edge.
PetsTable = "pets"
// PetsInverseTable is the table name for the Pet entity.
// It exists in this package in order to avoid circular dependency with the "pet" package.
PetsInverseTable = "pets"
// PetsColumn is the table column denoting the pets relation/edge.
PetsColumn = "owner_id"
// GroupsTable is the table that holds the groups relation/edge. The primary key declared below.
GroupsTable = "group_users"
// GroupsInverseTable is the table name for the Group entity.
// It exists in this package in order to avoid circular dependency with the "group" package.
GroupsInverseTable = "groups"
// FriendsTable is the table that holds the friends relation/edge. The primary key declared below.
FriendsTable = "friendships"
// ParentsTable is the table that holds the parents relation/edge. The primary key declared below.
ParentsTable = "parents"
// ChildrenTable is the table that holds the children relation/edge. The primary key declared below.
ChildrenTable = "parents"
// FriendshipsTable is the table that holds the friendships relation/edge.
FriendshipsTable = "friendships"
// FriendshipsInverseTable is the table name for the Friendship entity.
// It exists in this package in order to avoid circular dependency with the "friendship" package.
FriendshipsInverseTable = "friendships"
// FriendshipsColumn is the table column denoting the friendships relation/edge.
FriendshipsColumn = "user_id"
// ParentHoodTable is the table that holds the parent_hood relation/edge.
ParentHoodTable = "parents"
// ParentHoodInverseTable is the table name for the Parent entity.
// It exists in this package in order to avoid circular dependency with the "parent" package.
ParentHoodInverseTable = "parents"
// ParentHoodColumn is the table column denoting the parent_hood relation/edge.
ParentHoodColumn = "user_id"
)
// Columns holds all SQL columns for user fields.
var Columns = []string{
FieldID,
FieldName,
}
var (
// GroupsPrimaryKey and GroupsColumn2 are the table columns denoting the
// primary key for the groups relation (M2M).
GroupsPrimaryKey = []string{"group_id", "user_id"}
// FriendsPrimaryKey and FriendsColumn2 are the table columns denoting the
// primary key for the friends relation (M2M).
FriendsPrimaryKey = []string{"user_id", "friend_id"}
// ParentsPrimaryKey and ParentsColumn2 are the table columns denoting the
// primary key for the parents relation (M2M).
ParentsPrimaryKey = []string{"user_id", "parent_id"}
// ChildrenPrimaryKey and ChildrenColumn2 are the table columns denoting the
// primary key for the children relation (M2M).
ChildrenPrimaryKey = []string{"user_id", "parent_id"}
)
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// DefaultName holds the default value on creation for the "name" field.
DefaultName string
)
// OrderOption defines the ordering options for the User 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()
}
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, opts...).ToFunc()
}
// ByPetsCount orders the results by pets count.
func ByPetsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newPetsStep(), opts...)
}
}
// ByPets orders the results by pets terms.
func ByPets(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newPetsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByGroupsCount orders the results by groups count.
func ByGroupsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newGroupsStep(), opts...)
}
}
// ByGroups orders the results by groups terms.
func ByGroups(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newGroupsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByFriendsCount orders the results by friends count.
func ByFriendsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newFriendsStep(), opts...)
}
}
// ByFriends orders the results by friends terms.
func ByFriends(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newFriendsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByParentsCount orders the results by parents count.
func ByParentsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newParentsStep(), opts...)
}
}
// ByParents orders the results by parents terms.
func ByParents(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newParentsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByChildrenCount orders the results by children count.
func ByChildrenCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newChildrenStep(), opts...)
}
}
// ByChildren orders the results by children terms.
func ByChildren(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newChildrenStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByFriendshipsCount orders the results by friendships count.
func ByFriendshipsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newFriendshipsStep(), opts...)
}
}
// ByFriendships orders the results by friendships terms.
func ByFriendships(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newFriendshipsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByParentHoodCount orders the results by parent_hood count.
func ByParentHoodCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newParentHoodStep(), opts...)
}
}
// ByParentHood orders the results by parent_hood terms.
func ByParentHood(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newParentHoodStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
func newPetsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(PetsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, PetsTable, PetsColumn),
)
}
func newGroupsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(GroupsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, GroupsTable, GroupsPrimaryKey...),
)
}
func newFriendsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, FriendsTable, FriendsPrimaryKey...),
)
}
func newParentsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, ParentsTable, ParentsPrimaryKey...),
)
}
func newChildrenStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, ChildrenTable, ChildrenPrimaryKey...),
)
}
func newFriendshipsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(FriendshipsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, FriendshipsTable, FriendshipsColumn),
)
}
func newParentHoodStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(ParentHoodInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, ParentHoodTable, ParentHoodColumn),
)
}

View File

@@ -0,0 +1,347 @@
// 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 user
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/ent/internal"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.User {
return predicate.User(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.User {
return predicate.User(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.User {
return predicate.User(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.User {
return predicate.User(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.User {
return predicate.User(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.User {
return predicate.User(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.User {
return predicate.User(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.User {
return predicate.User(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.User {
return predicate.User(sql.FieldLTE(FieldID, id))
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldName, v))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldName, v))
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.User {
return predicate.User(sql.FieldNEQ(FieldName, v))
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.User {
return predicate.User(sql.FieldIn(FieldName, vs...))
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.User {
return predicate.User(sql.FieldNotIn(FieldName, vs...))
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.User {
return predicate.User(sql.FieldGT(FieldName, v))
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.User {
return predicate.User(sql.FieldGTE(FieldName, v))
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.User {
return predicate.User(sql.FieldLT(FieldName, v))
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.User {
return predicate.User(sql.FieldLTE(FieldName, v))
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.User {
return predicate.User(sql.FieldContains(FieldName, v))
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.User {
return predicate.User(sql.FieldHasPrefix(FieldName, v))
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.User {
return predicate.User(sql.FieldHasSuffix(FieldName, v))
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.User {
return predicate.User(sql.FieldEqualFold(FieldName, v))
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.User {
return predicate.User(sql.FieldContainsFold(FieldName, v))
}
// HasPets applies the HasEdge predicate on the "pets" edge.
func HasPets() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, PetsTable, PetsColumn),
)
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.Pet
step.Edge.Schema = schemaConfig.Pet
sqlgraph.HasNeighbors(s, step)
})
}
// HasPetsWith applies the HasEdge predicate on the "pets" edge with a given conditions (other predicates).
func HasPetsWith(preds ...predicate.Pet) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newPetsStep()
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.Pet
step.Edge.Schema = schemaConfig.Pet
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasGroups applies the HasEdge predicate on the "groups" edge.
func HasGroups() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, GroupsTable, GroupsPrimaryKey...),
)
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.Group
step.Edge.Schema = schemaConfig.GroupUsers
sqlgraph.HasNeighbors(s, step)
})
}
// HasGroupsWith applies the HasEdge predicate on the "groups" edge with a given conditions (other predicates).
func HasGroupsWith(preds ...predicate.Group) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newGroupsStep()
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.Group
step.Edge.Schema = schemaConfig.GroupUsers
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasFriends applies the HasEdge predicate on the "friends" edge.
func HasFriends() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, FriendsTable, FriendsPrimaryKey...),
)
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Friendship
sqlgraph.HasNeighbors(s, step)
})
}
// HasFriendsWith applies the HasEdge predicate on the "friends" edge with a given conditions (other predicates).
func HasFriendsWith(preds ...predicate.User) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newFriendsStep()
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Friendship
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasParents applies the HasEdge predicate on the "parents" edge.
func HasParents() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, ParentsTable, ParentsPrimaryKey...),
)
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.UserChildren
sqlgraph.HasNeighbors(s, step)
})
}
// HasParentsWith applies the HasEdge predicate on the "parents" edge with a given conditions (other predicates).
func HasParentsWith(preds ...predicate.User) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newParentsStep()
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.UserChildren
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasChildren applies the HasEdge predicate on the "children" edge.
func HasChildren() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, ChildrenTable, ChildrenPrimaryKey...),
)
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Parent
sqlgraph.HasNeighbors(s, step)
})
}
// HasChildrenWith applies the HasEdge predicate on the "children" edge with a given conditions (other predicates).
func HasChildrenWith(preds ...predicate.User) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newChildrenStep()
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Parent
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasFriendships applies the HasEdge predicate on the "friendships" edge.
func HasFriendships() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, FriendshipsTable, FriendshipsColumn),
)
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.Friendship
step.Edge.Schema = schemaConfig.Friendship
sqlgraph.HasNeighbors(s, step)
})
}
// HasFriendshipsWith applies the HasEdge predicate on the "friendships" edge with a given conditions (other predicates).
func HasFriendshipsWith(preds ...predicate.Friendship) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newFriendshipsStep()
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.Friendship
step.Edge.Schema = schemaConfig.Friendship
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasParentHood applies the HasEdge predicate on the "parent_hood" edge.
func HasParentHood() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, ParentHoodTable, ParentHoodColumn),
)
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.Parent
step.Edge.Schema = schemaConfig.Parent
sqlgraph.HasNeighbors(s, step)
})
}
// HasParentHoodWith applies the HasEdge predicate on the "parent_hood" edge with a given conditions (other predicates).
func HasParentHoodWith(preds ...predicate.Parent) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newParentHoodStep()
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.Parent
step.Edge.Schema = schemaConfig.Parent
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.User) predicate.User {
return predicate.User(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.User) predicate.User {
return predicate.User(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.User) predicate.User {
return predicate.User(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,442 @@
// 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/entc/integration/multischema/ent/friendship"
"entgo.io/ent/entc/integration/multischema/ent/group"
"entgo.io/ent/entc/integration/multischema/ent/parent"
"entgo.io/ent/entc/integration/multischema/ent/pet"
"entgo.io/ent/entc/integration/multischema/ent/user"
"entgo.io/ent/schema/field"
)
// UserCreate is the builder for creating a User entity.
type UserCreate struct {
config
mutation *UserMutation
hooks []Hook
}
// SetName sets the "name" field.
func (_c *UserCreate) SetName(v string) *UserCreate {
_c.mutation.SetName(v)
return _c
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_c *UserCreate) SetNillableName(v *string) *UserCreate {
if v != nil {
_c.SetName(*v)
}
return _c
}
// AddPetIDs adds the "pets" edge to the Pet entity by IDs.
func (_c *UserCreate) AddPetIDs(ids ...int) *UserCreate {
_c.mutation.AddPetIDs(ids...)
return _c
}
// AddPets adds the "pets" edges to the Pet entity.
func (_c *UserCreate) AddPets(v ...*Pet) *UserCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddPetIDs(ids...)
}
// AddGroupIDs adds the "groups" edge to the Group entity by IDs.
func (_c *UserCreate) AddGroupIDs(ids ...int) *UserCreate {
_c.mutation.AddGroupIDs(ids...)
return _c
}
// AddGroups adds the "groups" edges to the Group entity.
func (_c *UserCreate) AddGroups(v ...*Group) *UserCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddGroupIDs(ids...)
}
// AddFriendIDs adds the "friends" edge to the User entity by IDs.
func (_c *UserCreate) AddFriendIDs(ids ...int) *UserCreate {
_c.mutation.AddFriendIDs(ids...)
return _c
}
// AddFriends adds the "friends" edges to the User entity.
func (_c *UserCreate) AddFriends(v ...*User) *UserCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddFriendIDs(ids...)
}
// AddParentIDs adds the "parents" edge to the User entity by IDs.
func (_c *UserCreate) AddParentIDs(ids ...int) *UserCreate {
_c.mutation.AddParentIDs(ids...)
return _c
}
// AddParents adds the "parents" edges to the User entity.
func (_c *UserCreate) AddParents(v ...*User) *UserCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddParentIDs(ids...)
}
// AddChildIDs adds the "children" edge to the User entity by IDs.
func (_c *UserCreate) AddChildIDs(ids ...int) *UserCreate {
_c.mutation.AddChildIDs(ids...)
return _c
}
// AddChildren adds the "children" edges to the User entity.
func (_c *UserCreate) AddChildren(v ...*User) *UserCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddChildIDs(ids...)
}
// AddFriendshipIDs adds the "friendships" edge to the Friendship entity by IDs.
func (_c *UserCreate) AddFriendshipIDs(ids ...int) *UserCreate {
_c.mutation.AddFriendshipIDs(ids...)
return _c
}
// AddFriendships adds the "friendships" edges to the Friendship entity.
func (_c *UserCreate) AddFriendships(v ...*Friendship) *UserCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddFriendshipIDs(ids...)
}
// AddParentHoodIDs adds the "parent_hood" edge to the Parent entity by IDs.
func (_c *UserCreate) AddParentHoodIDs(ids ...int) *UserCreate {
_c.mutation.AddParentHoodIDs(ids...)
return _c
}
// AddParentHood adds the "parent_hood" edges to the Parent entity.
func (_c *UserCreate) AddParentHood(v ...*Parent) *UserCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddParentHoodIDs(ids...)
}
// Mutation returns the UserMutation object of the builder.
func (_c *UserCreate) Mutation() *UserMutation {
return _c.mutation
}
// Save creates the User in the database.
func (_c *UserCreate) Save(ctx context.Context) (*User, error) {
_c.defaults()
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *UserCreate) SaveX(ctx context.Context) *User {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *UserCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *UserCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_c *UserCreate) defaults() {
if _, ok := _c.mutation.Name(); !ok {
v := user.DefaultName
_c.mutation.SetName(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *UserCreate) check() error {
if _, ok := _c.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "User.name"`)}
}
return nil
}
func (_c *UserCreate) sqlSave(ctx context.Context) (*User, 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 *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) {
var (
_node = &User{config: _c.config}
_spec = sqlgraph.NewCreateSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt))
)
_spec.Schema = _c.schemaConfig.User
if value, ok := _c.mutation.Name(); ok {
_spec.SetField(user.FieldName, field.TypeString, value)
_node.Name = value
}
if nodes := _c.mutation.PetsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.PetsTable,
Columns: []string{user.PetsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(pet.FieldID, field.TypeInt),
},
}
edge.Schema = _c.schemaConfig.Pet
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.GroupsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: user.GroupsTable,
Columns: user.GroupsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt),
},
}
edge.Schema = _c.schemaConfig.GroupUsers
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.FriendsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.FriendsTable,
Columns: user.FriendsPrimaryKey,
Bidi: true,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _c.schemaConfig.Friendship
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
createE := &FriendshipCreate{config: _c.config, mutation: newFriendshipMutation(_c.config, OpCreate)}
createE.defaults()
_, specE := createE.createSpec()
edge.Target.Fields = specE.Fields
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.ParentsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: user.ParentsTable,
Columns: user.ParentsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _c.schemaConfig.UserChildren
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.ChildrenIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.ChildrenTable,
Columns: user.ChildrenPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _c.schemaConfig.Parent
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
createE := &ParentCreate{config: _c.config, mutation: newParentMutation(_c.config, OpCreate)}
createE.defaults()
_, specE := createE.createSpec()
edge.Target.Fields = specE.Fields
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.FriendshipsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: user.FriendshipsTable,
Columns: []string{user.FriendshipsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(friendship.FieldID, field.TypeInt),
},
}
edge.Schema = _c.schemaConfig.Friendship
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.ParentHoodIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: user.ParentHoodTable,
Columns: []string{user.ParentHoodColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(parent.FieldID, field.TypeInt),
},
}
edge.Schema = _c.schemaConfig.Parent
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// UserCreateBulk is the builder for creating many User entities in bulk.
type UserCreateBulk struct {
config
err error
builders []*UserCreate
}
// Save creates the User entities in the database.
func (_c *UserCreateBulk) Save(ctx context.Context) ([]*User, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*User, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*UserMutation)
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 *UserCreateBulk) SaveX(ctx context.Context) []*User {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *UserCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *UserCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,95 @@
// 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/entc/integration/multischema/ent/internal"
"entgo.io/ent/entc/integration/multischema/ent/predicate"
"entgo.io/ent/entc/integration/multischema/ent/user"
"entgo.io/ent/schema/field"
)
// UserDelete is the builder for deleting a User entity.
type UserDelete struct {
config
hooks []Hook
mutation *UserMutation
}
// Where appends a list predicates to the UserDelete builder.
func (_d *UserDelete) Where(ps ...predicate.User) *UserDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *UserDelete) 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 *UserDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *UserDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt))
_spec.Node.Schema = _d.schemaConfig.User
ctx = internal.NewSchemaConfigContext(ctx, _d.schemaConfig)
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
}
// UserDeleteOne is the builder for deleting a single User entity.
type UserDeleteOne struct {
_d *UserDelete
}
// Where appends a list predicates to the UserDelete builder.
func (_d *UserDeleteOne) Where(ps ...predicate.User) *UserDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *UserDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{user.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *UserDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,59 @@
-- Add new schema named "db1"
CREATE DATABASE IF NOT EXISTS`db1`;
-- Add new schema named "db2"
CREATE DATABASE IF NOT EXISTS `db2`;
-- Add new schema named "db3"
CREATE DATABASE IF NOT EXISTS `db3`;
-- Create "users" table
CREATE TABLE `db3`.`users` (
`id` bigint NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL DEFAULT "unknown",
PRIMARY KEY (`id`)
) CHARSET utf8mb4 COLLATE utf8mb4_bin;
-- Create "friendships" table
CREATE TABLE `db1`.`friendships` (
`id` bigint NOT NULL AUTO_INCREMENT,
`weight` bigint NOT NULL DEFAULT 1,
`created_at` timestamp NOT NULL,
`user_id` bigint NOT NULL,
`friend_id` bigint NOT NULL,
PRIMARY KEY (`id`),
INDEX `friendship_created_at` (`created_at`),
UNIQUE INDEX `friendship_user_id_friend_id` (`user_id`, `friend_id`),
INDEX `friendships_users_friend` (`friend_id`),
CONSTRAINT `friendships_users_friend` FOREIGN KEY (`friend_id`) REFERENCES `db3`.`users` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT `friendships_users_user` FOREIGN KEY (`user_id`) REFERENCES `db3`.`users` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION
) CHARSET utf8mb4 COLLATE utf8mb4_bin;
-- Create "groups" table
CREATE TABLE `db1`.`groups` (
`id` bigint NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL DEFAULT "unknown",
PRIMARY KEY (`id`)
) CHARSET utf8mb4 COLLATE utf8mb4_bin;
-- Create "group_users" table
CREATE TABLE `db1`.`group_users` (
`group_id` bigint NOT NULL,
`user_id` bigint NOT NULL,
PRIMARY KEY (`group_id`, `user_id`),
INDEX `group_users_user_id` (`user_id`),
CONSTRAINT `group_users_group_id` FOREIGN KEY (`group_id`) REFERENCES `db1`.`groups` (`id`) ON UPDATE NO ACTION ON DELETE CASCADE,
CONSTRAINT `group_users_user_id` FOREIGN KEY (`user_id`) REFERENCES `db3`.`users` (`id`) ON UPDATE NO ACTION ON DELETE CASCADE
) CHARSET utf8mb4 COLLATE utf8mb4_bin;
-- Create "pets" table
CREATE TABLE `db2`.`pets` (
`id` bigint NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL DEFAULT "unknown",
`owner_id` bigint NULL,
PRIMARY KEY (`id`),
INDEX `pets_users_pets` (`owner_id`),
CONSTRAINT `pets_users_pets` FOREIGN KEY (`owner_id`) REFERENCES `db3`.`users` (`id`) ON UPDATE NO ACTION ON DELETE SET NULL
) CHARSET utf8mb4 COLLATE utf8mb4_bin;
-- Create "user_following" table
CREATE TABLE `db3`.`user_following` (
`user_id` bigint NOT NULL,
`follower_id` bigint NOT NULL,
PRIMARY KEY (`user_id`, `follower_id`),
INDEX `user_following_follower_id` (`follower_id`),
CONSTRAINT `user_following_follower_id` FOREIGN KEY (`follower_id`) REFERENCES `db3`.`users` (`id`) ON UPDATE NO ACTION ON DELETE CASCADE,
CONSTRAINT `user_following_user_id` FOREIGN KEY (`user_id`) REFERENCES `db3`.`users` (`id`) ON UPDATE NO ACTION ON DELETE CASCADE
) CHARSET utf8mb4 COLLATE utf8mb4_bin;

View File

@@ -0,0 +1,2 @@
h1:dgJ2p+pgyvwfHWXgc6cqDwDEPUAu82Yw9j+Xdf2tUoQ=
20231112192027.sql h1:eOYTh18vQiGGMxAQC6eWWcwR6KuyXXWpwn/dAEN+R7U=

View File

@@ -0,0 +1,287 @@
// 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 multischema
import (
"context"
"fmt"
"log"
"os"
"slices"
"testing"
"ariga.io/atlas-go-sdk/atlasexec"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/entc/integration/multischema/ent"
"entgo.io/ent/entc/integration/multischema/ent/group"
"entgo.io/ent/entc/integration/multischema/ent/migrate"
"entgo.io/ent/entc/integration/multischema/ent/pet"
"entgo.io/ent/entc/integration/multischema/ent/user"
"entgo.io/ent/entc/integration/multischema/versioned"
vgroup "entgo.io/ent/entc/integration/multischema/versioned/group"
vpet "entgo.io/ent/entc/integration/multischema/versioned/pet"
vuser "entgo.io/ent/entc/integration/multischema/versioned/user"
_ "github.com/go-sql-driver/mysql"
"github.com/stretchr/testify/require"
)
func TestMySQL(t *testing.T) {
db, err := sql.Open("mysql", "root:pass@tcp(localhost:3308)/?parseTime=true&multiStatements=true")
require.NoError(t, err)
ctx := context.Background()
t.Cleanup(func() {
db.ExecContext(ctx, "SET foreign_key_checks = 0")
db.ExecContext(ctx, "DROP DATABASE IF EXISTS db1")
db.ExecContext(ctx, "DROP DATABASE IF EXISTS db2")
db.ExecContext(ctx, "SET foreign_key_checks = 1")
db.Close()
})
migrate.ParentsTable.Schema = "db1"
migrate.PetsTable.Schema = "db1"
migrate.UsersTable.Schema = "db1"
migrate.GroupsTable.Schema = "db2"
migrate.GroupUsersTable.Schema = "db2"
migrate.FriendshipsTable.Schema = "db2"
pl, err := schema.Dump(ctx, dialect.MySQL, "8.0.19", migrate.Tables)
require.NoError(t, err)
_, err = db.ExecContext(ctx, pl)
require.NoError(t, err)
// Default schema for the connection is db1.
db1, err := sql.Open("mysql", "root:pass@tcp(localhost:3308)/db1?parseTime=true")
require.NoError(t, err)
defer db1.Close()
cfg := ent.SchemaConfig{
// The "users" and the "pets" table reside in the same schema
// as the connection (the default search schema). Thus, there
// is no need to set them explicitly both in the migration and
// runtime statements.
//
// Pet: "db1",
// User: "db1",
// The "groups", "group_users" and "friendship" reside in external schema (db2).
Group: "db2",
GroupUsers: "db2",
// An edge with the "Through" definition is set on its edge-schema.
Friendship: "db2",
}
client := ent.NewClient(ent.Driver(db1), ent.AlternateSchema(cfg))
pedro := client.Pet.Create().SetName("Pedro").SaveX(ctx)
groups := client.Group.CreateBulk(
client.Group.Create().SetName("GitHub"),
client.Group.Create().SetName("GitLab"),
).SaveX(ctx)
a8m := client.User.Create().SetName("a8m").AddPets(pedro).AddGroups(groups...).SaveX(ctx)
// Custom modifier with schema config.
var names []struct {
User string `sql:"user_name"`
Pet string `sql:"pet_name"`
}
client.Pet.Query().
Modify(func(s *sql.Selector) {
// The below function is exported using a custom
// template defined in ent/template/config.tmpl.
cfg := ent.SchemaConfigFromContext(s.Context())
t := sql.Table(user.Table).Schema(cfg.User)
s.Join(t).On(s.C(pet.FieldOwnerID), t.C(user.FieldID))
s.Select(
sql.As(t.C(user.FieldName), "user_name"),
sql.As(s.C(pet.FieldName), "pet_name"),
)
}).
ScanX(ctx, &names)
require.Len(t, names, 1)
require.Equal(t, "a8m", names[0].User)
require.Equal(t, "Pedro", names[0].Pet)
id := client.Group.Query().
Where(group.HasUsersWith(user.ID(a8m.ID))).
Limit(1).
QueryUsers().
QueryPets().
OnlyIDX(ctx)
require.Equal(t, pedro.ID, id)
affected := client.Group.
Update().
ClearUsers().
Where(
group.And(
group.Name(groups[0].Name),
group.HasUsersWith(
user.HasPetsWith(
pet.Name(pedro.Name),
),
),
),
).
SaveX(ctx)
require.Equal(t, 1, affected)
exist := groups[0].QueryUsers().ExistX(ctx)
require.False(t, exist)
exist = groups[1].QueryUsers().ExistX(ctx)
require.True(t, exist)
exist = pedro.QueryOwner().ExistX(ctx)
require.True(t, exist)
pedro = pedro.Update().ClearOwner().SaveX(ctx)
exist = pedro.QueryOwner().ExistX(ctx)
require.False(t, exist)
require.Equal(t, client.User.Query().CountX(ctx), len(client.User.Query().AllX(ctx)))
require.Equal(t, client.Pet.Query().CountX(ctx), len(client.Pet.Query().AllX(ctx)))
nat := client.User.Create().SetName("nati").AddFriends(a8m).SaveX(ctx)
users := client.User.Query().WithFriends().WithFriendships().WithGroups().Order(ent.Asc(user.FieldName)).AllX(ctx)
require.Len(t, users, 2)
require.Equal(t, users[0].Name, a8m.Name)
require.Equal(t, users[1].Name, nat.Name)
require.Len(t, users[0].Edges.Groups, 1)
require.Len(t, users[1].Edges.Groups, 0)
require.Len(t, users[0].Edges.Friends, 1)
require.Len(t, users[1].Edges.Friends, 1)
require.Len(t, users[0].Edges.Friendships, 1)
require.Len(t, users[1].Edges.Friendships, 1)
ta := client.User.Create().SetName("ta").AddParents(a8m, nat).SaveX(ctx)
el := client.User.Create().SetName("el").AddParents(a8m, nat).SaveX(ctx)
jo := client.User.Create().SetName("be").AddParents(a8m, nat).SaveX(ctx)
require.Equal(t, 3, client.User.Query().Where(user.HasParents()).CountX(ctx))
require.Equal(t, 3, a8m.QueryChildren().CountX(ctx))
sib := ta.QueryParents().QueryChildren().Where(user.NameNEQ(ta.Name)).AllX(ctx)
require.Len(t, sib, 2)
require.True(t, slices.ContainsFunc(sib, func(u *ent.User) bool { return u.Name == el.Name }))
require.True(t, slices.ContainsFunc(sib, func(u *ent.User) bool { return u.Name == jo.Name }))
// Cross-schema edge predicate: QueryGroups().Where(HasUsersWith(...))
// must qualify group_users with db2, since the connection defaults to db1.
got := a8m.QueryGroups().
Where(group.HasUsersWith(user.ID(a8m.ID))).
CountX(ctx)
require.Equal(t, 1, got) // a8m was removed from GitHub above; only GitLab remains
}
func TestVersionedMigration(t *testing.T) {
if os.Getenv("CI") != "" {
t.Skip("skipping on CI")
}
t.Cleanup(func() {
db, err := sql.Open("mysql", "root:pass@tcp(localhost:3308)/")
require.NoError(t, err)
defer db.Close()
for _, name := range []string{"db1", "db2", "db3", "atlas_schema_revisions"} {
_, err := db.ExecContext(context.Background(), fmt.Sprintf("DROP DATABASE IF EXISTS `%s`", name))
require.NoError(t, err, "drop database")
}
})
ac, err := atlasexec.NewClient(".", "atlas")
if err != nil {
log.Fatalf("failed to initialize client: %v", err)
}
// Run `atlas migrate apply` on a SQLite database under /tmp.
res, err := ac.MigrateApply(context.Background(), &atlasexec.MigrateApplyParams{
URL: "mysql://root:pass@:3308/",
AllowDirty: true,
})
if err != nil {
log.Fatalf("failed to apply migrations: %v", err)
}
if len(res.Applied) > 0 {
t.Logf("Applied %d migrations", len(res.Applied))
}
client, err := versioned.Open("mysql", "root:pass@tcp(localhost:3308)/?parseTime=true")
require.NoError(t, err)
defer client.Close()
// Copy of the test above.
ctx := context.Background()
pedro := client.Pet.Create().SetName("Pedro").SaveX(ctx)
groups := client.Group.CreateBulk(
client.Group.Create().SetName("GitHub"),
client.Group.Create().SetName("GitLab"),
).SaveX(ctx)
a8m := client.User.Create().SetName("a8m").AddPets(pedro).AddGroups(groups...).SaveX(ctx)
// Custom modifier with schema config.
var names []struct {
User string `sql:"user_name"`
Pet string `sql:"pet_name"`
}
client.Pet.Query().
Modify(func(s *sql.Selector) {
// The below function is exported using a custom
// template defined in ent/template/config.tmpl.
cfg := versioned.DefaultSchemaConfig
t := sql.Table(user.Table).Schema(cfg.User)
s.Join(t).On(s.C(pet.FieldOwnerID), t.C(user.FieldID))
s.Select(
sql.As(t.C(user.FieldName), "user_name"),
sql.As(s.C(pet.FieldName), "pet_name"),
)
}).
ScanX(ctx, &names)
require.Len(t, names, 1)
require.Equal(t, "a8m", names[0].User)
require.Equal(t, "Pedro", names[0].Pet)
id := client.Group.Query().
Where(vgroup.HasUsersWith(vuser.ID(a8m.ID))).
Limit(1).
QueryUsers().
QueryPets().
OnlyIDX(ctx)
require.Equal(t, pedro.ID, id)
affected := client.Group.
Update().
ClearUsers().
Where(
vgroup.And(
vgroup.Name(groups[0].Name),
vgroup.HasUsersWith(
vuser.HasPetsWith(
vpet.Name(pedro.Name),
),
),
),
).
SaveX(ctx)
require.Equal(t, 1, affected)
exist := groups[0].QueryUsers().ExistX(ctx)
require.False(t, exist)
exist = groups[1].QueryUsers().ExistX(ctx)
require.True(t, exist)
exist = pedro.QueryOwner().ExistX(ctx)
require.True(t, exist)
pedro = pedro.Update().ClearOwner().SaveX(ctx)
exist = pedro.QueryOwner().ExistX(ctx)
require.False(t, exist)
require.Equal(t, client.User.Query().CountX(ctx), len(client.User.Query().AllX(ctx)))
require.Equal(t, client.Pet.Query().CountX(ctx), len(client.Pet.Query().AllX(ctx)))
nat := client.User.Create().SetName("nati").AddFriends(a8m).SaveX(ctx)
users := client.User.Query().WithFriends().WithFriendships().WithGroups().Order(ent.Asc(user.FieldName)).AllX(ctx)
require.Len(t, users, 2)
require.Equal(t, users[0].Name, a8m.Name)
require.Equal(t, users[1].Name, nat.Name)
require.Len(t, users[0].Edges.Groups, 1)
require.Len(t, users[1].Edges.Groups, 0)
require.Len(t, users[0].Edges.Friends, 1)
require.Len(t, users[1].Edges.Friends, 1)
require.Len(t, users[0].Edges.Friendships, 1)
require.Len(t, users[1].Edges.Friendships, 1)
}

View File

@@ -0,0 +1,994 @@
// 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 versioned
import (
"context"
"errors"
"fmt"
"log"
"reflect"
"entgo.io/ent"
"entgo.io/ent/entc/integration/multischema/versioned/migrate"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/versioned/friendship"
"entgo.io/ent/entc/integration/multischema/versioned/group"
"entgo.io/ent/entc/integration/multischema/versioned/pet"
"entgo.io/ent/entc/integration/multischema/versioned/user"
"entgo.io/ent/entc/integration/multischema/versioned/internal"
)
// 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
// Friendship is the client for interacting with the Friendship builders.
Friendship *FriendshipClient
// Group is the client for interacting with the Group builders.
Group *GroupClient
// Pet is the client for interacting with the Pet builders.
Pet *PetClient
// User is the client for interacting with the User builders.
User *UserClient
}
// 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.Friendship = NewFriendshipClient(c.config)
c.Group = NewGroupClient(c.config)
c.Pet = NewPetClient(c.config)
c.User = NewUserClient(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
// schemaConfig contains alternative names for all tables.
schemaConfig SchemaConfig
}
// 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.schemaConfig = DefaultSchemaConfig
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("versioned: 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("versioned: starting a transaction: %w", err)
}
cfg := c.config
cfg.driver = tx
return &Tx{
ctx: ctx,
config: cfg,
Friendship: NewFriendshipClient(cfg),
Group: NewGroupClient(cfg),
Pet: NewPetClient(cfg),
User: NewUserClient(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,
Friendship: NewFriendshipClient(cfg),
Group: NewGroupClient(cfg),
Pet: NewPetClient(cfg),
User: NewUserClient(cfg),
}, nil
}
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
//
// client.Debug().
// Friendship.
// 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.Friendship.Use(hooks...)
c.Group.Use(hooks...)
c.Pet.Use(hooks...)
c.User.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.Friendship.Intercept(interceptors...)
c.Group.Intercept(interceptors...)
c.Pet.Intercept(interceptors...)
c.User.Intercept(interceptors...)
}
// Mutate implements the ent.Mutator interface.
func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
switch m := m.(type) {
case *FriendshipMutation:
return c.Friendship.mutate(ctx, m)
case *GroupMutation:
return c.Group.mutate(ctx, m)
case *PetMutation:
return c.Pet.mutate(ctx, m)
case *UserMutation:
return c.User.mutate(ctx, m)
default:
return nil, fmt.Errorf("versioned: unknown mutation type %T", m)
}
}
// FriendshipClient is a client for the Friendship schema.
type FriendshipClient struct {
config
}
// NewFriendshipClient returns a client for the Friendship from the given config.
func NewFriendshipClient(c config) *FriendshipClient {
return &FriendshipClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `friendship.Hooks(f(g(h())))`.
func (c *FriendshipClient) Use(hooks ...Hook) {
c.hooks.Friendship = append(c.hooks.Friendship, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `friendship.Intercept(f(g(h())))`.
func (c *FriendshipClient) Intercept(interceptors ...Interceptor) {
c.inters.Friendship = append(c.inters.Friendship, interceptors...)
}
// Create returns a builder for creating a Friendship entity.
func (c *FriendshipClient) Create() *FriendshipCreate {
mutation := newFriendshipMutation(c.config, OpCreate)
return &FriendshipCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Friendship entities.
func (c *FriendshipClient) CreateBulk(builders ...*FriendshipCreate) *FriendshipCreateBulk {
return &FriendshipCreateBulk{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 *FriendshipClient) MapCreateBulk(slice any, setFunc func(*FriendshipCreate, int)) *FriendshipCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &FriendshipCreateBulk{err: fmt.Errorf("calling to FriendshipClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*FriendshipCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &FriendshipCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Friendship.
func (c *FriendshipClient) Update() *FriendshipUpdate {
mutation := newFriendshipMutation(c.config, OpUpdate)
return &FriendshipUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *FriendshipClient) UpdateOne(_m *Friendship) *FriendshipUpdateOne {
mutation := newFriendshipMutation(c.config, OpUpdateOne, withFriendship(_m))
return &FriendshipUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *FriendshipClient) UpdateOneID(id int) *FriendshipUpdateOne {
mutation := newFriendshipMutation(c.config, OpUpdateOne, withFriendshipID(id))
return &FriendshipUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Friendship.
func (c *FriendshipClient) Delete() *FriendshipDelete {
mutation := newFriendshipMutation(c.config, OpDelete)
return &FriendshipDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *FriendshipClient) DeleteOne(_m *Friendship) *FriendshipDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *FriendshipClient) DeleteOneID(id int) *FriendshipDeleteOne {
builder := c.Delete().Where(friendship.ID(id))
builder.mutation.id = &id
builder.mutation.SetOp(OpDeleteOne)
return &FriendshipDeleteOne{builder}
}
// Query returns a query builder for Friendship.
func (c *FriendshipClient) Query() *FriendshipQuery {
return &FriendshipQuery{
config: c.config,
ctx: &QueryContext{Type: TypeFriendship},
inters: c.Interceptors(),
}
}
// Get returns a Friendship entity by its id.
func (c *FriendshipClient) Get(ctx context.Context, id int) (*Friendship, error) {
return c.Query().Where(friendship.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *FriendshipClient) GetX(ctx context.Context, id int) *Friendship {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryUser queries the user edge of a Friendship.
func (c *FriendshipClient) QueryUser(_m *Friendship) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(friendship.Table, friendship.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, friendship.UserTable, friendship.UserColumn),
)
schemaConfig := _m.schemaConfig
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Friendship
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryFriend queries the friend edge of a Friendship.
func (c *FriendshipClient) QueryFriend(_m *Friendship) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(friendship.Table, friendship.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, friendship.FriendTable, friendship.FriendColumn),
)
schemaConfig := _m.schemaConfig
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Friendship
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *FriendshipClient) Hooks() []Hook {
return c.hooks.Friendship
}
// Interceptors returns the client interceptors.
func (c *FriendshipClient) Interceptors() []Interceptor {
return c.inters.Friendship
}
func (c *FriendshipClient) mutate(ctx context.Context, m *FriendshipMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&FriendshipCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&FriendshipUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&FriendshipUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&FriendshipDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("versioned: unknown Friendship mutation op: %q", m.Op())
}
}
// GroupClient is a client for the Group schema.
type GroupClient struct {
config
}
// NewGroupClient returns a client for the Group from the given config.
func NewGroupClient(c config) *GroupClient {
return &GroupClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `group.Hooks(f(g(h())))`.
func (c *GroupClient) Use(hooks ...Hook) {
c.hooks.Group = append(c.hooks.Group, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `group.Intercept(f(g(h())))`.
func (c *GroupClient) Intercept(interceptors ...Interceptor) {
c.inters.Group = append(c.inters.Group, interceptors...)
}
// Create returns a builder for creating a Group entity.
func (c *GroupClient) Create() *GroupCreate {
mutation := newGroupMutation(c.config, OpCreate)
return &GroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Group entities.
func (c *GroupClient) CreateBulk(builders ...*GroupCreate) *GroupCreateBulk {
return &GroupCreateBulk{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 *GroupClient) MapCreateBulk(slice any, setFunc func(*GroupCreate, int)) *GroupCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &GroupCreateBulk{err: fmt.Errorf("calling to GroupClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*GroupCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &GroupCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Group.
func (c *GroupClient) Update() *GroupUpdate {
mutation := newGroupMutation(c.config, OpUpdate)
return &GroupUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *GroupClient) UpdateOne(_m *Group) *GroupUpdateOne {
mutation := newGroupMutation(c.config, OpUpdateOne, withGroup(_m))
return &GroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *GroupClient) UpdateOneID(id int) *GroupUpdateOne {
mutation := newGroupMutation(c.config, OpUpdateOne, withGroupID(id))
return &GroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Group.
func (c *GroupClient) Delete() *GroupDelete {
mutation := newGroupMutation(c.config, OpDelete)
return &GroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *GroupClient) DeleteOne(_m *Group) *GroupDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *GroupClient) DeleteOneID(id int) *GroupDeleteOne {
builder := c.Delete().Where(group.ID(id))
builder.mutation.id = &id
builder.mutation.SetOp(OpDeleteOne)
return &GroupDeleteOne{builder}
}
// Query returns a query builder for Group.
func (c *GroupClient) Query() *GroupQuery {
return &GroupQuery{
config: c.config,
ctx: &QueryContext{Type: TypeGroup},
inters: c.Interceptors(),
}
}
// Get returns a Group entity by its id.
func (c *GroupClient) Get(ctx context.Context, id int) (*Group, error) {
return c.Query().Where(group.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *GroupClient) GetX(ctx context.Context, id int) *Group {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryUsers queries the users edge of a Group.
func (c *GroupClient) QueryUsers(_m *Group) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, group.UsersTable, group.UsersPrimaryKey...),
)
schemaConfig := _m.schemaConfig
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.GroupUsers
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *GroupClient) Hooks() []Hook {
return c.hooks.Group
}
// Interceptors returns the client interceptors.
func (c *GroupClient) Interceptors() []Interceptor {
return c.inters.Group
}
func (c *GroupClient) mutate(ctx context.Context, m *GroupMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&GroupCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&GroupUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&GroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&GroupDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("versioned: unknown Group mutation op: %q", m.Op())
}
}
// PetClient is a client for the Pet schema.
type PetClient struct {
config
}
// NewPetClient returns a client for the Pet from the given config.
func NewPetClient(c config) *PetClient {
return &PetClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `pet.Hooks(f(g(h())))`.
func (c *PetClient) Use(hooks ...Hook) {
c.hooks.Pet = append(c.hooks.Pet, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `pet.Intercept(f(g(h())))`.
func (c *PetClient) Intercept(interceptors ...Interceptor) {
c.inters.Pet = append(c.inters.Pet, interceptors...)
}
// Create returns a builder for creating a Pet entity.
func (c *PetClient) Create() *PetCreate {
mutation := newPetMutation(c.config, OpCreate)
return &PetCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Pet entities.
func (c *PetClient) CreateBulk(builders ...*PetCreate) *PetCreateBulk {
return &PetCreateBulk{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 *PetClient) MapCreateBulk(slice any, setFunc func(*PetCreate, int)) *PetCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &PetCreateBulk{err: fmt.Errorf("calling to PetClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*PetCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &PetCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Pet.
func (c *PetClient) Update() *PetUpdate {
mutation := newPetMutation(c.config, OpUpdate)
return &PetUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *PetClient) UpdateOne(_m *Pet) *PetUpdateOne {
mutation := newPetMutation(c.config, OpUpdateOne, withPet(_m))
return &PetUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *PetClient) UpdateOneID(id int) *PetUpdateOne {
mutation := newPetMutation(c.config, OpUpdateOne, withPetID(id))
return &PetUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Pet.
func (c *PetClient) Delete() *PetDelete {
mutation := newPetMutation(c.config, OpDelete)
return &PetDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *PetClient) DeleteOne(_m *Pet) *PetDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *PetClient) DeleteOneID(id int) *PetDeleteOne {
builder := c.Delete().Where(pet.ID(id))
builder.mutation.id = &id
builder.mutation.SetOp(OpDeleteOne)
return &PetDeleteOne{builder}
}
// Query returns a query builder for Pet.
func (c *PetClient) Query() *PetQuery {
return &PetQuery{
config: c.config,
ctx: &QueryContext{Type: TypePet},
inters: c.Interceptors(),
}
}
// Get returns a Pet entity by its id.
func (c *PetClient) Get(ctx context.Context, id int) (*Pet, error) {
return c.Query().Where(pet.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *PetClient) GetX(ctx context.Context, id int) *Pet {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryOwner queries the owner edge of a Pet.
func (c *PetClient) QueryOwner(_m *Pet) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(pet.Table, pet.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, pet.OwnerTable, pet.OwnerColumn),
)
schemaConfig := _m.schemaConfig
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Pet
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *PetClient) Hooks() []Hook {
return c.hooks.Pet
}
// Interceptors returns the client interceptors.
func (c *PetClient) Interceptors() []Interceptor {
return c.inters.Pet
}
func (c *PetClient) mutate(ctx context.Context, m *PetMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&PetCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&PetUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&PetUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&PetDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("versioned: unknown Pet mutation op: %q", m.Op())
}
}
// UserClient is a client for the User schema.
type UserClient struct {
config
}
// NewUserClient returns a client for the User from the given config.
func NewUserClient(c config) *UserClient {
return &UserClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `user.Hooks(f(g(h())))`.
func (c *UserClient) Use(hooks ...Hook) {
c.hooks.User = append(c.hooks.User, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `user.Intercept(f(g(h())))`.
func (c *UserClient) Intercept(interceptors ...Interceptor) {
c.inters.User = append(c.inters.User, interceptors...)
}
// Create returns a builder for creating a User entity.
func (c *UserClient) Create() *UserCreate {
mutation := newUserMutation(c.config, OpCreate)
return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of User entities.
func (c *UserClient) CreateBulk(builders ...*UserCreate) *UserCreateBulk {
return &UserCreateBulk{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 *UserClient) MapCreateBulk(slice any, setFunc func(*UserCreate, int)) *UserCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &UserCreateBulk{err: fmt.Errorf("calling to UserClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*UserCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &UserCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for User.
func (c *UserClient) Update() *UserUpdate {
mutation := newUserMutation(c.config, OpUpdate)
return &UserUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *UserClient) UpdateOne(_m *User) *UserUpdateOne {
mutation := newUserMutation(c.config, OpUpdateOne, withUser(_m))
return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *UserClient) UpdateOneID(id int) *UserUpdateOne {
mutation := newUserMutation(c.config, OpUpdateOne, withUserID(id))
return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for User.
func (c *UserClient) Delete() *UserDelete {
mutation := newUserMutation(c.config, OpDelete)
return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *UserClient) DeleteOne(_m *User) *UserDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *UserClient) DeleteOneID(id int) *UserDeleteOne {
builder := c.Delete().Where(user.ID(id))
builder.mutation.id = &id
builder.mutation.SetOp(OpDeleteOne)
return &UserDeleteOne{builder}
}
// Query returns a query builder for User.
func (c *UserClient) Query() *UserQuery {
return &UserQuery{
config: c.config,
ctx: &QueryContext{Type: TypeUser},
inters: c.Interceptors(),
}
}
// Get returns a User entity by its id.
func (c *UserClient) Get(ctx context.Context, id int) (*User, error) {
return c.Query().Where(user.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *UserClient) GetX(ctx context.Context, id int) *User {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryPets queries the pets edge of a User.
func (c *UserClient) QueryPets(_m *User) *PetQuery {
query := (&PetClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, id),
sqlgraph.To(pet.Table, pet.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, user.PetsTable, user.PetsColumn),
)
schemaConfig := _m.schemaConfig
step.To.Schema = schemaConfig.Pet
step.Edge.Schema = schemaConfig.Pet
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryGroups queries the groups edge of a User.
func (c *UserClient) QueryGroups(_m *User) *GroupQuery {
query := (&GroupClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, id),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, user.GroupsTable, user.GroupsPrimaryKey...),
)
schemaConfig := _m.schemaConfig
step.To.Schema = schemaConfig.Group
step.Edge.Schema = schemaConfig.GroupUsers
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryFriends queries the friends edge of a User.
func (c *UserClient) QueryFriends(_m *User) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, user.FriendsTable, user.FriendsPrimaryKey...),
)
schemaConfig := _m.schemaConfig
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Friendship
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryFollowers queries the followers edge of a User.
func (c *UserClient) QueryFollowers(_m *User) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, user.FollowersTable, user.FollowersPrimaryKey...),
)
schemaConfig := _m.schemaConfig
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.UserFollowing
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryFollowing queries the following edge of a User.
func (c *UserClient) QueryFollowing(_m *User) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, user.FollowingTable, user.FollowingPrimaryKey...),
)
schemaConfig := _m.schemaConfig
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.UserFollowing
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryFriendships queries the friendships edge of a User.
func (c *UserClient) QueryFriendships(_m *User) *FriendshipQuery {
query := (&FriendshipClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, id),
sqlgraph.To(friendship.Table, friendship.FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, user.FriendshipsTable, user.FriendshipsColumn),
)
schemaConfig := _m.schemaConfig
step.To.Schema = schemaConfig.Friendship
step.Edge.Schema = schemaConfig.Friendship
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *UserClient) Hooks() []Hook {
return c.hooks.User
}
// Interceptors returns the client interceptors.
func (c *UserClient) Interceptors() []Interceptor {
return c.inters.User
}
func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&UserCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&UserUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&UserDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("versioned: unknown User mutation op: %q", m.Op())
}
}
// hooks and interceptors per client, for fast access.
type (
hooks struct {
Friendship, Group, Pet, User []ent.Hook
}
inters struct {
Friendship, Group, Pet, User []ent.Interceptor
}
)
var (
// DefaultSchemaConfig represents the default schema names for all tables as defined in ent/schema.
DefaultSchemaConfig = SchemaConfig{
Friendship: tableSchemas[0],
Group: tableSchemas[0],
GroupUsers: tableSchemas[0],
Pet: tableSchemas[1],
User: tableSchemas[2],
UserFollowing: tableSchemas[2],
}
tableSchemas = [...]string{"db1", "db2", "db3"}
)
// SchemaConfig represents alternative schema names for all tables
// that can be passed at runtime.
type SchemaConfig = internal.SchemaConfig
// AlternateSchemas allows alternate schema names to be
// passed into ent operations.
func AlternateSchema(schemaConfig SchemaConfig) Option {
return func(c *config) {
c.schemaConfig = schemaConfig
}
}

View File

@@ -0,0 +1,618 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package versioned
import (
"context"
"errors"
"fmt"
"reflect"
"sync"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/versioned/friendship"
"entgo.io/ent/entc/integration/multischema/versioned/group"
"entgo.io/ent/entc/integration/multischema/versioned/pet"
"entgo.io/ent/entc/integration/multischema/versioned/user"
)
// 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{
friendship.Table: friendship.ValidColumn,
group.Table: group.ValidColumn,
pet.Table: pet.ValidColumn,
user.Table: user.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("versioned: %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("versioned: %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(versioned.As(versioned.Sum(field1), "sum_field1"), (versioned.As(versioned.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("versioned: %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("versioned: %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("versioned: %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("versioned: %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 "versioned: " + 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 "versioned: " + 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 "versioned: " + 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 "versioned: 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("versioned: 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("versioned: 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("versioned: 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("versioned: 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("versioned: 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("versioned: 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("versioned: 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("versioned: 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)

View File

@@ -0,0 +1,30 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
//go:build ignore
// +build ignore
package main
import (
"log"
"entgo.io/ent/entc"
"entgo.io/ent/entc/gen"
)
func main() {
err := entc.Generate("./schema", &gen.Config{
Header: `
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
`,
}, entc.FeatureNames("sql/modifier"))
if err != nil {
log.Fatalf("running ent codegen: %v", err)
}
}

View 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/entc/integration/multischema/versioned"
// required by schema hooks.
_ "entgo.io/ent/entc/integration/multischema/versioned/runtime"
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/entc/integration/multischema/versioned/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 []versioned.Option
migrateOpts []schema.MigrateOption
}
)
// WithOptions forwards options to client creation.
func WithOptions(opts ...versioned.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 versioned.Open and auto-run migration.
func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *versioned.Client {
o := newOptions(opts)
c, err := versioned.Open(driverName, dataSourceName, o.opts...)
if err != nil {
t.Error(err)
t.FailNow()
}
migrateSchema(t, c, o)
return c
}
// NewClient calls versioned.NewClient and auto-run migration.
func NewClient(t TestingT, opts ...Option) *versioned.Client {
o := newOptions(opts)
c := versioned.NewClient(o.opts...)
migrateSchema(t, c, o)
return c
}
func migrateSchema(t TestingT, c *versioned.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()
}
}

View File

@@ -0,0 +1,188 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package versioned
import (
"fmt"
"strings"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/entc/integration/multischema/versioned/friendship"
"entgo.io/ent/entc/integration/multischema/versioned/user"
)
// Friendship is the model entity for the Friendship schema.
type Friendship struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Weight holds the value of the "weight" field.
Weight int `json:"weight,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// UserID holds the value of the "user_id" field.
UserID int `json:"user_id,omitempty"`
// FriendID holds the value of the "friend_id" field.
FriendID int `json:"friend_id,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the FriendshipQuery when eager-loading is set.
Edges FriendshipEdges `json:"edges"`
selectValues sql.SelectValues
}
// FriendshipEdges holds the relations/edges for other nodes in the graph.
type FriendshipEdges struct {
// User holds the value of the user edge.
User *User `json:"user,omitempty"`
// Friend holds the value of the friend edge.
Friend *User `json:"friend,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// UserOrErr returns the User value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e FriendshipEdges) UserOrErr() (*User, error) {
if e.User != nil {
return e.User, nil
} else if e.loadedTypes[0] {
return nil, &NotFoundError{label: user.Label}
}
return nil, &NotLoadedError{edge: "user"}
}
// FriendOrErr returns the Friend value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e FriendshipEdges) FriendOrErr() (*User, error) {
if e.Friend != nil {
return e.Friend, nil
} else if e.loadedTypes[1] {
return nil, &NotFoundError{label: user.Label}
}
return nil, &NotLoadedError{edge: "friend"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Friendship) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case friendship.FieldID, friendship.FieldWeight, friendship.FieldUserID, friendship.FieldFriendID:
values[i] = new(sql.NullInt64)
case friendship.FieldCreatedAt:
values[i] = new(sql.NullTime)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Friendship fields.
func (_m *Friendship) 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 friendship.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 friendship.FieldWeight:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field weight", values[i])
} else if value.Valid {
_m.Weight = int(value.Int64)
}
case friendship.FieldCreatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
_m.CreatedAt = value.Time
}
case friendship.FieldUserID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field user_id", values[i])
} else if value.Valid {
_m.UserID = int(value.Int64)
}
case friendship.FieldFriendID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field friend_id", values[i])
} else if value.Valid {
_m.FriendID = int(value.Int64)
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Friendship.
// This includes values selected through modifiers, order, etc.
func (_m *Friendship) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryUser queries the "user" edge of the Friendship entity.
func (_m *Friendship) QueryUser() *UserQuery {
return NewFriendshipClient(_m.config).QueryUser(_m)
}
// QueryFriend queries the "friend" edge of the Friendship entity.
func (_m *Friendship) QueryFriend() *UserQuery {
return NewFriendshipClient(_m.config).QueryFriend(_m)
}
// Update returns a builder for updating this Friendship.
// Note that you need to call Friendship.Unwrap() before calling this method if this Friendship
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Friendship) Update() *FriendshipUpdateOne {
return NewFriendshipClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Friendship 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 *Friendship) Unwrap() *Friendship {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("versioned: Friendship is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Friendship) String() string {
var builder strings.Builder
builder.WriteString("Friendship(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("weight=")
builder.WriteString(fmt.Sprintf("%v", _m.Weight))
builder.WriteString(", ")
builder.WriteString("created_at=")
builder.WriteString(_m.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("user_id=")
builder.WriteString(fmt.Sprintf("%v", _m.UserID))
builder.WriteString(", ")
builder.WriteString("friend_id=")
builder.WriteString(fmt.Sprintf("%v", _m.FriendID))
builder.WriteByte(')')
return builder.String()
}
// Friendships is a parsable slice of Friendship.
type Friendships []*Friendship

View File

@@ -0,0 +1,131 @@
// 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 friendship
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the friendship type in the database.
Label = "friendship"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldWeight holds the string denoting the weight field in the database.
FieldWeight = "weight"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldUserID holds the string denoting the user_id field in the database.
FieldUserID = "user_id"
// FieldFriendID holds the string denoting the friend_id field in the database.
FieldFriendID = "friend_id"
// EdgeUser holds the string denoting the user edge name in mutations.
EdgeUser = "user"
// EdgeFriend holds the string denoting the friend edge name in mutations.
EdgeFriend = "friend"
// Table holds the table name of the friendship in the database.
Table = "friendships"
// UserTable is the table that holds the user relation/edge.
UserTable = "friendships"
// UserInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
UserInverseTable = "users"
// UserColumn is the table column denoting the user relation/edge.
UserColumn = "user_id"
// FriendTable is the table that holds the friend relation/edge.
FriendTable = "friendships"
// FriendInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
FriendInverseTable = "users"
// FriendColumn is the table column denoting the friend relation/edge.
FriendColumn = "friend_id"
)
// Columns holds all SQL columns for friendship fields.
var Columns = []string{
FieldID,
FieldWeight,
FieldCreatedAt,
FieldUserID,
FieldFriendID,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// DefaultWeight holds the default value on creation for the "weight" field.
DefaultWeight int
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
)
// OrderOption defines the ordering options for the Friendship 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()
}
// ByWeight orders the results by the weight field.
func ByWeight(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldWeight, opts...).ToFunc()
}
// ByCreatedAt orders the results by the created_at field.
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
}
// ByUserID orders the results by the user_id field.
func ByUserID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUserID, opts...).ToFunc()
}
// ByFriendID orders the results by the friend_id field.
func ByFriendID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldFriendID, opts...).ToFunc()
}
// ByUserField orders the results by user field.
func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newUserStep(), sql.OrderByField(field, opts...))
}
}
// ByFriendField orders the results by friend field.
func ByFriendField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newFriendStep(), sql.OrderByField(field, opts...))
}
}
func newUserStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UserInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn),
)
}
func newFriendStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(FriendInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, FriendTable, FriendColumn),
)
}

View File

@@ -0,0 +1,475 @@
// 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 friendship
import (
"context"
"fmt"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/entc/integration/multischema/versioned/predicate"
)
// Mutation represents an operation that mutates the Friendship nodes in the graph.
type Mutation struct {
op ent.Op
typ string
weight *int
addweight *int
created_at *time.Time
clearedFields map[string]struct{}
user *int
cleareduser bool
friend *int
clearedfriend bool
predicates []predicate.Friendship
}
// NewMutation creates a new Mutation for the Friendship entity.
func NewMutation(op ent.Op) *Mutation {
return &Mutation{
op: op,
typ: "Friendship",
clearedFields: make(map[string]struct{}),
}
}
// Predicates returns the list of predicates set on the mutation.
func (m *Mutation) Predicates() []predicate.Friendship {
return m.predicates
}
// SetWeight sets the "weight" field.
func (m *Mutation) SetWeight(i int) {
m.weight = &i
m.addweight = nil
}
// Weight returns the value of the "weight" field in the mutation.
func (m *Mutation) Weight() (r int, exists bool) {
v := m.weight
if v == nil {
return
}
return *v, true
}
// AddWeight adds i to the "weight" field.
func (m *Mutation) AddWeight(i int) {
if m.addweight != nil {
*m.addweight += i
} else {
m.addweight = &i
}
}
// AddedWeight returns the value that was added to the "weight" field in this mutation.
func (m *Mutation) AddedWeight() (r int, exists bool) {
v := m.addweight
if v == nil {
return
}
return *v, true
}
// ResetWeight resets all changes to the "weight" field.
func (m *Mutation) ResetWeight() {
m.weight = nil
m.addweight = nil
}
// SetCreatedAt sets the "created_at" field.
func (m *Mutation) SetCreatedAt(t time.Time) {
m.created_at = &t
}
// CreatedAt returns the value of the "created_at" field in the mutation.
func (m *Mutation) CreatedAt() (r time.Time, exists bool) {
v := m.created_at
if v == nil {
return
}
return *v, true
}
// ResetCreatedAt resets all changes to the "created_at" field.
func (m *Mutation) ResetCreatedAt() {
m.created_at = nil
}
// SetUserID sets the "user_id" field.
func (m *Mutation) SetUserID(i int) {
m.user = &i
}
// UserID returns the value of the "user_id" field in the mutation.
func (m *Mutation) UserID() (r int, exists bool) {
v := m.user
if v == nil {
return
}
return *v, true
}
// ResetUserID resets all changes to the "user_id" field.
func (m *Mutation) ResetUserID() {
m.user = nil
}
// SetFriendID sets the "friend_id" field.
func (m *Mutation) SetFriendID(i int) {
m.friend = &i
}
// FriendID returns the value of the "friend_id" field in the mutation.
func (m *Mutation) FriendID() (r int, exists bool) {
v := m.friend
if v == nil {
return
}
return *v, true
}
// ResetFriendID resets all changes to the "friend_id" field.
func (m *Mutation) ResetFriendID() {
m.friend = nil
}
// ClearUser clears the "user" edge to the User entity.
func (m *Mutation) ClearUser() {
m.cleareduser = true
m.clearedFields[FieldUserID] = struct{}{}
}
// UserCleared reports if the "user" edge to the User entity was cleared.
func (m *Mutation) UserCleared() bool {
return m.cleareduser
}
// UserIDs returns the "user" edge IDs in the mutation.
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
// UserID instead. It exists only for internal usage by the builders.
func (m *Mutation) UserIDs() (ids []int) {
if id := m.user; id != nil {
ids = append(ids, *id)
}
return
}
// ResetUser resets all changes to the "user" edge.
func (m *Mutation) ResetUser() {
m.user = nil
m.cleareduser = false
}
// ClearFriend clears the "friend" edge to the User entity.
func (m *Mutation) ClearFriend() {
m.clearedfriend = true
m.clearedFields[FieldFriendID] = struct{}{}
}
// FriendCleared reports if the "friend" edge to the User entity was cleared.
func (m *Mutation) FriendCleared() bool {
return m.clearedfriend
}
// FriendIDs returns the "friend" edge IDs in the mutation.
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
// FriendID instead. It exists only for internal usage by the builders.
func (m *Mutation) FriendIDs() (ids []int) {
if id := m.friend; id != nil {
ids = append(ids, *id)
}
return
}
// ResetFriend resets all changes to the "friend" edge.
func (m *Mutation) ResetFriend() {
m.friend = nil
m.clearedfriend = false
}
// Where appends a list predicates to the Mutation builder.
func (m *Mutation) Where(ps ...predicate.Friendship) {
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.Friendship, 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 (Friendship).
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, 4)
if m.weight != nil {
fields = append(fields, FieldWeight)
}
if m.created_at != nil {
fields = append(fields, FieldCreatedAt)
}
if m.user != nil {
fields = append(fields, FieldUserID)
}
if m.friend != nil {
fields = append(fields, FieldFriendID)
}
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 FieldWeight:
return m.Weight()
case FieldCreatedAt:
return m.CreatedAt()
case FieldUserID:
return m.UserID()
case FieldFriendID:
return m.FriendID()
}
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 Friendship 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 FieldWeight:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetWeight(v)
return nil
case FieldCreatedAt:
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetCreatedAt(v)
return nil
case FieldUserID:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetUserID(v)
return nil
case FieldFriendID:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetFriendID(v)
return nil
}
return fmt.Errorf("unknown Friendship 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.addweight != nil {
fields = append(fields, FieldWeight)
}
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 FieldWeight:
return m.AddedWeight()
}
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 FieldWeight:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.AddWeight(v)
return nil
}
return fmt.Errorf("unknown Friendship numeric field %s", name)
}
// ClearedFields returns all nullable fields that were cleared during this
// mutation.
func (m *Mutation) ClearedFields() []string {
return nil
}
// 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 {
return fmt.Errorf("unknown Friendship 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 FieldWeight:
m.ResetWeight()
return nil
case FieldCreatedAt:
m.ResetCreatedAt()
return nil
case FieldUserID:
m.ResetUserID()
return nil
case FieldFriendID:
m.ResetFriendID()
return nil
}
return fmt.Errorf("unknown Friendship 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.user != nil {
edges = append(edges, EdgeUser)
}
if m.friend != nil {
edges = append(edges, EdgeFriend)
}
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 EdgeUser:
if id := m.user; id != nil {
return []ent.Value{*id}
}
case EdgeFriend:
if id := m.friend; 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.cleareduser {
edges = append(edges, EdgeUser)
}
if m.clearedfriend {
edges = append(edges, EdgeFriend)
}
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 EdgeUser:
return m.cleareduser
case EdgeFriend:
return m.clearedfriend
}
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 EdgeUser:
m.ClearUser()
return nil
case EdgeFriend:
m.ClearFriend()
return nil
}
return fmt.Errorf("unknown Friendship 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 EdgeUser:
m.ResetUser()
return nil
case EdgeFriend:
m.ResetFriend()
return nil
}
return fmt.Errorf("unknown Friendship edge %s", name)
}

View File

@@ -0,0 +1,274 @@
// 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 friendship
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/versioned/internal"
"entgo.io/ent/entc/integration/multischema/versioned/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Friendship {
return predicate.Friendship(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Friendship {
return predicate.Friendship(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Friendship {
return predicate.Friendship(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Friendship {
return predicate.Friendship(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Friendship {
return predicate.Friendship(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Friendship {
return predicate.Friendship(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Friendship {
return predicate.Friendship(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Friendship {
return predicate.Friendship(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Friendship {
return predicate.Friendship(sql.FieldLTE(FieldID, id))
}
// Weight applies equality check predicate on the "weight" field. It's identical to WeightEQ.
func Weight(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldEQ(FieldWeight, v))
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.Friendship {
return predicate.Friendship(sql.FieldEQ(FieldCreatedAt, v))
}
// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
func UserID(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldEQ(FieldUserID, v))
}
// FriendID applies equality check predicate on the "friend_id" field. It's identical to FriendIDEQ.
func FriendID(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldEQ(FieldFriendID, v))
}
// WeightEQ applies the EQ predicate on the "weight" field.
func WeightEQ(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldEQ(FieldWeight, v))
}
// WeightNEQ applies the NEQ predicate on the "weight" field.
func WeightNEQ(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldNEQ(FieldWeight, v))
}
// WeightIn applies the In predicate on the "weight" field.
func WeightIn(vs ...int) predicate.Friendship {
return predicate.Friendship(sql.FieldIn(FieldWeight, vs...))
}
// WeightNotIn applies the NotIn predicate on the "weight" field.
func WeightNotIn(vs ...int) predicate.Friendship {
return predicate.Friendship(sql.FieldNotIn(FieldWeight, vs...))
}
// WeightGT applies the GT predicate on the "weight" field.
func WeightGT(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldGT(FieldWeight, v))
}
// WeightGTE applies the GTE predicate on the "weight" field.
func WeightGTE(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldGTE(FieldWeight, v))
}
// WeightLT applies the LT predicate on the "weight" field.
func WeightLT(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldLT(FieldWeight, v))
}
// WeightLTE applies the LTE predicate on the "weight" field.
func WeightLTE(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldLTE(FieldWeight, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Friendship {
return predicate.Friendship(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.Friendship {
return predicate.Friendship(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.Friendship {
return predicate.Friendship(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.Friendship {
return predicate.Friendship(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.Friendship {
return predicate.Friendship(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.Friendship {
return predicate.Friendship(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.Friendship {
return predicate.Friendship(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.Friendship {
return predicate.Friendship(sql.FieldLTE(FieldCreatedAt, v))
}
// UserIDEQ applies the EQ predicate on the "user_id" field.
func UserIDEQ(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldEQ(FieldUserID, v))
}
// UserIDNEQ applies the NEQ predicate on the "user_id" field.
func UserIDNEQ(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldNEQ(FieldUserID, v))
}
// UserIDIn applies the In predicate on the "user_id" field.
func UserIDIn(vs ...int) predicate.Friendship {
return predicate.Friendship(sql.FieldIn(FieldUserID, vs...))
}
// UserIDNotIn applies the NotIn predicate on the "user_id" field.
func UserIDNotIn(vs ...int) predicate.Friendship {
return predicate.Friendship(sql.FieldNotIn(FieldUserID, vs...))
}
// FriendIDEQ applies the EQ predicate on the "friend_id" field.
func FriendIDEQ(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldEQ(FieldFriendID, v))
}
// FriendIDNEQ applies the NEQ predicate on the "friend_id" field.
func FriendIDNEQ(v int) predicate.Friendship {
return predicate.Friendship(sql.FieldNEQ(FieldFriendID, v))
}
// FriendIDIn applies the In predicate on the "friend_id" field.
func FriendIDIn(vs ...int) predicate.Friendship {
return predicate.Friendship(sql.FieldIn(FieldFriendID, vs...))
}
// FriendIDNotIn applies the NotIn predicate on the "friend_id" field.
func FriendIDNotIn(vs ...int) predicate.Friendship {
return predicate.Friendship(sql.FieldNotIn(FieldFriendID, vs...))
}
// HasUser applies the HasEdge predicate on the "user" edge.
func HasUser() predicate.Friendship {
return predicate.Friendship(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn),
)
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Friendship
sqlgraph.HasNeighbors(s, step)
})
}
// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates).
func HasUserWith(preds ...predicate.User) predicate.Friendship {
return predicate.Friendship(func(s *sql.Selector) {
step := newUserStep()
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Friendship
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasFriend applies the HasEdge predicate on the "friend" edge.
func HasFriend() predicate.Friendship {
return predicate.Friendship(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, FriendTable, FriendColumn),
)
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Friendship
sqlgraph.HasNeighbors(s, step)
})
}
// HasFriendWith applies the HasEdge predicate on the "friend" edge with a given conditions (other predicates).
func HasFriendWith(preds ...predicate.User) predicate.Friendship {
return predicate.Friendship(func(s *sql.Selector) {
step := newFriendStep()
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Friendship
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.Friendship) predicate.Friendship {
return predicate.Friendship(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Friendship) predicate.Friendship {
return predicate.Friendship(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Friendship) predicate.Friendship {
return predicate.Friendship(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,303 @@
// 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 versioned
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/versioned/friendship"
"entgo.io/ent/entc/integration/multischema/versioned/user"
"entgo.io/ent/schema/field"
)
// FriendshipCreate is the builder for creating a Friendship entity.
type FriendshipCreate struct {
config
mutation *FriendshipMutation
hooks []Hook
}
// SetWeight sets the "weight" field.
func (_c *FriendshipCreate) SetWeight(v int) *FriendshipCreate {
_c.mutation.SetWeight(v)
return _c
}
// SetNillableWeight sets the "weight" field if the given value is not nil.
func (_c *FriendshipCreate) SetNillableWeight(v *int) *FriendshipCreate {
if v != nil {
_c.SetWeight(*v)
}
return _c
}
// SetCreatedAt sets the "created_at" field.
func (_c *FriendshipCreate) SetCreatedAt(v time.Time) *FriendshipCreate {
_c.mutation.SetCreatedAt(v)
return _c
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (_c *FriendshipCreate) SetNillableCreatedAt(v *time.Time) *FriendshipCreate {
if v != nil {
_c.SetCreatedAt(*v)
}
return _c
}
// SetUserID sets the "user_id" field.
func (_c *FriendshipCreate) SetUserID(v int) *FriendshipCreate {
_c.mutation.SetUserID(v)
return _c
}
// SetFriendID sets the "friend_id" field.
func (_c *FriendshipCreate) SetFriendID(v int) *FriendshipCreate {
_c.mutation.SetFriendID(v)
return _c
}
// SetUser sets the "user" edge to the User entity.
func (_c *FriendshipCreate) SetUser(v *User) *FriendshipCreate {
return _c.SetUserID(v.ID)
}
// SetFriend sets the "friend" edge to the User entity.
func (_c *FriendshipCreate) SetFriend(v *User) *FriendshipCreate {
return _c.SetFriendID(v.ID)
}
// Mutation returns the FriendshipMutation object of the builder.
func (_c *FriendshipCreate) Mutation() *FriendshipMutation {
return _c.mutation
}
// Save creates the Friendship in the database.
func (_c *FriendshipCreate) Save(ctx context.Context) (*Friendship, error) {
_c.defaults()
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *FriendshipCreate) SaveX(ctx context.Context) *Friendship {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *FriendshipCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *FriendshipCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_c *FriendshipCreate) defaults() {
if _, ok := _c.mutation.Weight(); !ok {
v := friendship.DefaultWeight
_c.mutation.SetWeight(v)
}
if _, ok := _c.mutation.CreatedAt(); !ok {
v := friendship.DefaultCreatedAt()
_c.mutation.SetCreatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *FriendshipCreate) check() error {
if _, ok := _c.mutation.Weight(); !ok {
return &ValidationError{Name: "weight", err: errors.New(`versioned: missing required field "Friendship.weight"`)}
}
if _, ok := _c.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`versioned: missing required field "Friendship.created_at"`)}
}
if _, ok := _c.mutation.UserID(); !ok {
return &ValidationError{Name: "user_id", err: errors.New(`versioned: missing required field "Friendship.user_id"`)}
}
if _, ok := _c.mutation.FriendID(); !ok {
return &ValidationError{Name: "friend_id", err: errors.New(`versioned: missing required field "Friendship.friend_id"`)}
}
if len(_c.mutation.UserIDs()) == 0 {
return &ValidationError{Name: "user", err: errors.New(`versioned: missing required edge "Friendship.user"`)}
}
if len(_c.mutation.FriendIDs()) == 0 {
return &ValidationError{Name: "friend", err: errors.New(`versioned: missing required edge "Friendship.friend"`)}
}
return nil
}
func (_c *FriendshipCreate) sqlSave(ctx context.Context) (*Friendship, 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 *FriendshipCreate) createSpec() (*Friendship, *sqlgraph.CreateSpec) {
var (
_node = &Friendship{config: _c.config}
_spec = sqlgraph.NewCreateSpec(friendship.Table, sqlgraph.NewFieldSpec(friendship.FieldID, field.TypeInt))
)
_spec.Schema = _c.schemaConfig.Friendship
if value, ok := _c.mutation.Weight(); ok {
_spec.SetField(friendship.FieldWeight, field.TypeInt, value)
_node.Weight = value
}
if value, ok := _c.mutation.CreatedAt(); ok {
_spec.SetField(friendship.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = value
}
if nodes := _c.mutation.UserIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: friendship.UserTable,
Columns: []string{friendship.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _c.schemaConfig.Friendship
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.UserID = nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.FriendIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: friendship.FriendTable,
Columns: []string{friendship.FriendColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _c.schemaConfig.Friendship
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.FriendID = nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// FriendshipCreateBulk is the builder for creating many Friendship entities in bulk.
type FriendshipCreateBulk struct {
config
err error
builders []*FriendshipCreate
}
// Save creates the Friendship entities in the database.
func (_c *FriendshipCreateBulk) Save(ctx context.Context) ([]*Friendship, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*Friendship, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*FriendshipMutation)
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 *FriendshipCreateBulk) SaveX(ctx context.Context) []*Friendship {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *FriendshipCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *FriendshipCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,95 @@
// 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 versioned
import (
"context"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/versioned/friendship"
"entgo.io/ent/entc/integration/multischema/versioned/internal"
"entgo.io/ent/entc/integration/multischema/versioned/predicate"
"entgo.io/ent/schema/field"
)
// FriendshipDelete is the builder for deleting a Friendship entity.
type FriendshipDelete struct {
config
hooks []Hook
mutation *FriendshipMutation
}
// Where appends a list predicates to the FriendshipDelete builder.
func (_d *FriendshipDelete) Where(ps ...predicate.Friendship) *FriendshipDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *FriendshipDelete) 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 *FriendshipDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *FriendshipDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(friendship.Table, sqlgraph.NewFieldSpec(friendship.FieldID, field.TypeInt))
_spec.Node.Schema = _d.schemaConfig.Friendship
ctx = internal.NewSchemaConfigContext(ctx, _d.schemaConfig)
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
}
// FriendshipDeleteOne is the builder for deleting a single Friendship entity.
type FriendshipDeleteOne struct {
_d *FriendshipDelete
}
// Where appends a list predicates to the FriendshipDelete builder.
func (_d *FriendshipDeleteOne) Where(ps ...predicate.Friendship) *FriendshipDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *FriendshipDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{friendship.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *FriendshipDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,721 @@
// 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 versioned
import (
"context"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/versioned/friendship"
"entgo.io/ent/entc/integration/multischema/versioned/internal"
"entgo.io/ent/entc/integration/multischema/versioned/predicate"
"entgo.io/ent/entc/integration/multischema/versioned/user"
"entgo.io/ent/schema/field"
)
// FriendshipQuery is the builder for querying Friendship entities.
type FriendshipQuery struct {
config
ctx *QueryContext
order []friendship.OrderOption
inters []Interceptor
predicates []predicate.Friendship
withUser *UserQuery
withFriend *UserQuery
modifiers []func(*sql.Selector)
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the FriendshipQuery builder.
func (_q *FriendshipQuery) Where(ps ...predicate.Friendship) *FriendshipQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *FriendshipQuery) Limit(limit int) *FriendshipQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *FriendshipQuery) Offset(offset int) *FriendshipQuery {
_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 *FriendshipQuery) Unique(unique bool) *FriendshipQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *FriendshipQuery) Order(o ...friendship.OrderOption) *FriendshipQuery {
_q.order = append(_q.order, o...)
return _q
}
// QueryUser chains the current query on the "user" edge.
func (_q *FriendshipQuery) QueryUser() *UserQuery {
query := (&UserClient{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(friendship.Table, friendship.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, friendship.UserTable, friendship.UserColumn),
)
schemaConfig := _q.schemaConfig
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Friendship
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryFriend chains the current query on the "friend" edge.
func (_q *FriendshipQuery) QueryFriend() *UserQuery {
query := (&UserClient{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(friendship.Table, friendship.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, friendship.FriendTable, friendship.FriendColumn),
)
schemaConfig := _q.schemaConfig
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Friendship
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Friendship entity from the query.
// Returns a *NotFoundError when no Friendship was found.
func (_q *FriendshipQuery) First(ctx context.Context) (*Friendship, 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{friendship.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *FriendshipQuery) FirstX(ctx context.Context) *Friendship {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Friendship ID from the query.
// Returns a *NotFoundError when no Friendship ID was found.
func (_q *FriendshipQuery) 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{friendship.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *FriendshipQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Friendship entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Friendship entity is found.
// Returns a *NotFoundError when no Friendship entities are found.
func (_q *FriendshipQuery) Only(ctx context.Context) (*Friendship, 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{friendship.Label}
default:
return nil, &NotSingularError{friendship.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *FriendshipQuery) OnlyX(ctx context.Context) *Friendship {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Friendship ID in the query.
// Returns a *NotSingularError when more than one Friendship ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *FriendshipQuery) 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{friendship.Label}
default:
err = &NotSingularError{friendship.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *FriendshipQuery) 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 Friendships.
func (_q *FriendshipQuery) All(ctx context.Context) ([]*Friendship, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Friendship, *FriendshipQuery]()
return withInterceptors[[]*Friendship](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *FriendshipQuery) AllX(ctx context.Context) []*Friendship {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Friendship IDs.
func (_q *FriendshipQuery) 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(friendship.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *FriendshipQuery) 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 *FriendshipQuery) 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[*FriendshipQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *FriendshipQuery) 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 *FriendshipQuery) 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("versioned: check existence: %w", err)
default:
return true, nil
}
}
// ExistX is like Exist, but panics if an error occurs.
func (_q *FriendshipQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the FriendshipQuery 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 *FriendshipQuery) Clone() *FriendshipQuery {
if _q == nil {
return nil
}
return &FriendshipQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]friendship.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Friendship{}, _q.predicates...),
withUser: _q.withUser.Clone(),
withFriend: _q.withFriend.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
modifiers: append([]func(*sql.Selector){}, _q.modifiers...),
}
}
// WithUser tells the query-builder to eager-load the nodes that are connected to
// the "user" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *FriendshipQuery) WithUser(opts ...func(*UserQuery)) *FriendshipQuery {
query := (&UserClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withUser = query
return _q
}
// WithFriend tells the query-builder to eager-load the nodes that are connected to
// the "friend" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *FriendshipQuery) WithFriend(opts ...func(*UserQuery)) *FriendshipQuery {
query := (&UserClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withFriend = 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 {
// Weight int `json:"weight,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Friendship.Query().
// GroupBy(friendship.FieldWeight).
// Aggregate(versioned.Count()).
// Scan(ctx, &v)
func (_q *FriendshipQuery) GroupBy(field string, fields ...string) *FriendshipGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &FriendshipGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = friendship.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 {
// Weight int `json:"weight,omitempty"`
// }
//
// client.Friendship.Query().
// Select(friendship.FieldWeight).
// Scan(ctx, &v)
func (_q *FriendshipQuery) Select(fields ...string) *FriendshipSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &FriendshipSelect{FriendshipQuery: _q}
sbuild.label = friendship.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a FriendshipSelect configured with the given aggregations.
func (_q *FriendshipQuery) Aggregate(fns ...AggregateFunc) *FriendshipSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *FriendshipQuery) prepareQuery(ctx context.Context) error {
for _, inter := range _q.inters {
if inter == nil {
return fmt.Errorf("versioned: uninitialized interceptor (forgotten import versioned/runtime?)")
}
if trv, ok := inter.(Traverser); ok {
if err := trv.Traverse(ctx, _q); err != nil {
return err
}
}
}
for _, f := range _q.ctx.Fields {
if !friendship.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("versioned: 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 *FriendshipQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Friendship, error) {
var (
nodes = []*Friendship{}
_spec = _q.querySpec()
loadedTypes = [2]bool{
_q.withUser != nil,
_q.withFriend != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Friendship).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Friendship{config: _q.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
_spec.Node.Schema = _q.schemaConfig.Friendship
ctx = internal.NewSchemaConfigContext(ctx, _q.schemaConfig)
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := _q.withUser; query != nil {
if err := _q.loadUser(ctx, query, nodes, nil,
func(n *Friendship, e *User) { n.Edges.User = e }); err != nil {
return nil, err
}
}
if query := _q.withFriend; query != nil {
if err := _q.loadFriend(ctx, query, nodes, nil,
func(n *Friendship, e *User) { n.Edges.Friend = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *FriendshipQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*Friendship, init func(*Friendship), assign func(*Friendship, *User)) error {
ids := make([]int, 0, len(nodes))
nodeids := make(map[int][]*Friendship)
for i := range nodes {
fk := nodes[i].UserID
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(user.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 "user_id" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *FriendshipQuery) loadFriend(ctx context.Context, query *UserQuery, nodes []*Friendship, init func(*Friendship), assign func(*Friendship, *User)) error {
ids := make([]int, 0, len(nodes))
nodeids := make(map[int][]*Friendship)
for i := range nodes {
fk := nodes[i].FriendID
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(user.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 "friend_id" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *FriendshipQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Schema = _q.schemaConfig.Friendship
ctx = internal.NewSchemaConfigContext(ctx, _q.schemaConfig)
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *FriendshipQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(friendship.Table, friendship.Columns, sqlgraph.NewFieldSpec(friendship.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, friendship.FieldID)
for i := range fields {
if fields[i] != friendship.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
if _q.withUser != nil {
_spec.Node.AddColumnOnce(friendship.FieldUserID)
}
if _q.withFriend != nil {
_spec.Node.AddColumnOnce(friendship.FieldFriendID)
}
}
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 *FriendshipQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(friendship.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = friendship.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()
}
t1.Schema(_q.schemaConfig.Friendship)
ctx = internal.NewSchemaConfigContext(ctx, _q.schemaConfig)
selector.WithContext(ctx)
for _, m := range _q.modifiers {
m(selector)
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// Modify adds a query modifier for attaching custom logic to queries.
func (_q *FriendshipQuery) Modify(modifiers ...func(s *sql.Selector)) *FriendshipSelect {
_q.modifiers = append(_q.modifiers, modifiers...)
return _q.Select()
}
// FriendshipGroupBy is the group-by builder for Friendship entities.
type FriendshipGroupBy struct {
selector
build *FriendshipQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *FriendshipGroupBy) Aggregate(fns ...AggregateFunc) *FriendshipGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *FriendshipGroupBy) 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[*FriendshipQuery, *FriendshipGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *FriendshipGroupBy) sqlScan(ctx context.Context, root *FriendshipQuery, 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)
}
// FriendshipSelect is the builder for selecting fields of Friendship entities.
type FriendshipSelect struct {
*FriendshipQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *FriendshipSelect) Aggregate(fns ...AggregateFunc) *FriendshipSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *FriendshipSelect) 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[*FriendshipQuery, *FriendshipSelect](ctx, _s.FriendshipQuery, _s, _s.inters, v)
}
func (_s *FriendshipSelect) sqlScan(ctx context.Context, root *FriendshipQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(_s.fns))
for _, fn := range _s.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*_s.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// Modify adds a query modifier for attaching custom logic to queries.
func (_s *FriendshipSelect) Modify(modifiers ...func(s *sql.Selector)) *FriendshipSelect {
_s.modifiers = append(_s.modifiers, modifiers...)
return _s
}

View File

@@ -0,0 +1,317 @@
// 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 versioned
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/versioned/friendship"
"entgo.io/ent/entc/integration/multischema/versioned/internal"
"entgo.io/ent/entc/integration/multischema/versioned/predicate"
"entgo.io/ent/schema/field"
)
// FriendshipUpdate is the builder for updating Friendship entities.
type FriendshipUpdate struct {
config
hooks []Hook
mutation *FriendshipMutation
modifiers []func(*sql.UpdateBuilder)
}
// Where appends a list predicates to the FriendshipUpdate builder.
func (_u *FriendshipUpdate) Where(ps ...predicate.Friendship) *FriendshipUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetWeight sets the "weight" field.
func (_u *FriendshipUpdate) SetWeight(v int) *FriendshipUpdate {
_u.mutation.ResetWeight()
_u.mutation.SetWeight(v)
return _u
}
// SetNillableWeight sets the "weight" field if the given value is not nil.
func (_u *FriendshipUpdate) SetNillableWeight(v *int) *FriendshipUpdate {
if v != nil {
_u.SetWeight(*v)
}
return _u
}
// AddWeight adds value to the "weight" field.
func (_u *FriendshipUpdate) AddWeight(v int) *FriendshipUpdate {
_u.mutation.AddWeight(v)
return _u
}
// SetCreatedAt sets the "created_at" field.
func (_u *FriendshipUpdate) SetCreatedAt(v time.Time) *FriendshipUpdate {
_u.mutation.SetCreatedAt(v)
return _u
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (_u *FriendshipUpdate) SetNillableCreatedAt(v *time.Time) *FriendshipUpdate {
if v != nil {
_u.SetCreatedAt(*v)
}
return _u
}
// Mutation returns the FriendshipMutation object of the builder.
func (_u *FriendshipUpdate) Mutation() *FriendshipMutation {
return _u.mutation
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *FriendshipUpdate) 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 *FriendshipUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *FriendshipUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *FriendshipUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *FriendshipUpdate) check() error {
if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 {
return errors.New(`versioned: clearing a required unique edge "Friendship.user"`)
}
if _u.mutation.FriendCleared() && len(_u.mutation.FriendIDs()) > 0 {
return errors.New(`versioned: clearing a required unique edge "Friendship.friend"`)
}
return nil
}
// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
func (_u *FriendshipUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *FriendshipUpdate {
_u.modifiers = append(_u.modifiers, modifiers...)
return _u
}
func (_u *FriendshipUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(friendship.Table, friendship.Columns, sqlgraph.NewFieldSpec(friendship.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.Weight(); ok {
_spec.SetField(friendship.FieldWeight, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedWeight(); ok {
_spec.AddField(friendship.FieldWeight, field.TypeInt, value)
}
if value, ok := _u.mutation.CreatedAt(); ok {
_spec.SetField(friendship.FieldCreatedAt, field.TypeTime, value)
}
_spec.Node.Schema = _u.schemaConfig.Friendship
ctx = internal.NewSchemaConfigContext(ctx, _u.schemaConfig)
_spec.AddModifiers(_u.modifiers...)
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{friendship.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// FriendshipUpdateOne is the builder for updating a single Friendship entity.
type FriendshipUpdateOne struct {
config
fields []string
hooks []Hook
mutation *FriendshipMutation
modifiers []func(*sql.UpdateBuilder)
}
// SetWeight sets the "weight" field.
func (_u *FriendshipUpdateOne) SetWeight(v int) *FriendshipUpdateOne {
_u.mutation.ResetWeight()
_u.mutation.SetWeight(v)
return _u
}
// SetNillableWeight sets the "weight" field if the given value is not nil.
func (_u *FriendshipUpdateOne) SetNillableWeight(v *int) *FriendshipUpdateOne {
if v != nil {
_u.SetWeight(*v)
}
return _u
}
// AddWeight adds value to the "weight" field.
func (_u *FriendshipUpdateOne) AddWeight(v int) *FriendshipUpdateOne {
_u.mutation.AddWeight(v)
return _u
}
// SetCreatedAt sets the "created_at" field.
func (_u *FriendshipUpdateOne) SetCreatedAt(v time.Time) *FriendshipUpdateOne {
_u.mutation.SetCreatedAt(v)
return _u
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (_u *FriendshipUpdateOne) SetNillableCreatedAt(v *time.Time) *FriendshipUpdateOne {
if v != nil {
_u.SetCreatedAt(*v)
}
return _u
}
// Mutation returns the FriendshipMutation object of the builder.
func (_u *FriendshipUpdateOne) Mutation() *FriendshipMutation {
return _u.mutation
}
// Where appends a list predicates to the FriendshipUpdate builder.
func (_u *FriendshipUpdateOne) Where(ps ...predicate.Friendship) *FriendshipUpdateOne {
_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 *FriendshipUpdateOne) Select(field string, fields ...string) *FriendshipUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated Friendship entity.
func (_u *FriendshipUpdateOne) Save(ctx context.Context) (*Friendship, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *FriendshipUpdateOne) SaveX(ctx context.Context) *Friendship {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *FriendshipUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *FriendshipUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *FriendshipUpdateOne) check() error {
if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 {
return errors.New(`versioned: clearing a required unique edge "Friendship.user"`)
}
if _u.mutation.FriendCleared() && len(_u.mutation.FriendIDs()) > 0 {
return errors.New(`versioned: clearing a required unique edge "Friendship.friend"`)
}
return nil
}
// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
func (_u *FriendshipUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *FriendshipUpdateOne {
_u.modifiers = append(_u.modifiers, modifiers...)
return _u
}
func (_u *FriendshipUpdateOne) sqlSave(ctx context.Context) (_node *Friendship, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(friendship.Table, friendship.Columns, sqlgraph.NewFieldSpec(friendship.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`versioned: missing "Friendship.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, friendship.FieldID)
for _, f := range fields {
if !friendship.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("versioned: invalid field %q for query", f)}
}
if f != friendship.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.Weight(); ok {
_spec.SetField(friendship.FieldWeight, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedWeight(); ok {
_spec.AddField(friendship.FieldWeight, field.TypeInt, value)
}
if value, ok := _u.mutation.CreatedAt(); ok {
_spec.SetField(friendship.FieldCreatedAt, field.TypeTime, value)
}
_spec.Node.Schema = _u.schemaConfig.Friendship
ctx = internal.NewSchemaConfigContext(ctx, _u.schemaConfig)
_spec.AddModifiers(_u.modifiers...)
_node = &Friendship{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{friendship.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

View 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 versioned
//go:generate go run -mod=mod entc.go

View File

@@ -0,0 +1,133 @@
// 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 versioned
import (
"fmt"
"strings"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/entc/integration/multischema/versioned/group"
)
// Group is the model entity for the Group schema.
type Group struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the GroupQuery when eager-loading is set.
Edges GroupEdges `json:"edges"`
selectValues sql.SelectValues
}
// GroupEdges holds the relations/edges for other nodes in the graph.
type GroupEdges struct {
// Users holds the value of the users edge.
Users []*User `json:"users,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [1]bool
}
// UsersOrErr returns the Users value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) UsersOrErr() ([]*User, error) {
if e.loadedTypes[0] {
return e.Users, nil
}
return nil, &NotLoadedError{edge: "users"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Group) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case group.FieldID:
values[i] = new(sql.NullInt64)
case group.FieldName:
values[i] = new(sql.NullString)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Group fields.
func (_m *Group) 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 group.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 group.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
_m.Name = value.String
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Group.
// This includes values selected through modifiers, order, etc.
func (_m *Group) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryUsers queries the "users" edge of the Group entity.
func (_m *Group) QueryUsers() *UserQuery {
return NewGroupClient(_m.config).QueryUsers(_m)
}
// Update returns a builder for updating this Group.
// Note that you need to call Group.Unwrap() before calling this method if this Group
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Group) Update() *GroupUpdateOne {
return NewGroupClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Group 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 *Group) Unwrap() *Group {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("versioned: Group is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Group) String() string {
var builder strings.Builder
builder.WriteString("Group(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("name=")
builder.WriteString(_m.Name)
builder.WriteByte(')')
return builder.String()
}
// Groups is a parsable slice of Group.
type Groups []*Group

View File

@@ -0,0 +1,91 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package group
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the group type in the database.
Label = "group"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// EdgeUsers holds the string denoting the users edge name in mutations.
EdgeUsers = "users"
// Table holds the table name of the group in the database.
Table = "groups"
// UsersTable is the table that holds the users relation/edge. The primary key declared below.
UsersTable = "group_users"
// UsersInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
UsersInverseTable = "users"
)
// Columns holds all SQL columns for group fields.
var Columns = []string{
FieldID,
FieldName,
}
var (
// UsersPrimaryKey and UsersColumn2 are the table columns denoting the
// primary key for the users relation (M2M).
UsersPrimaryKey = []string{"group_id", "user_id"}
)
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// DefaultName holds the default value on creation for the "name" field.
DefaultName string
)
// OrderOption defines the ordering options for the Group 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()
}
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, opts...).ToFunc()
}
// ByUsersCount orders the results by users count.
func ByUsersCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newUsersStep(), opts...)
}
}
// ByUsers orders the results by users terms.
func ByUsers(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newUsersStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
func newUsersStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UsersInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, UsersTable, UsersPrimaryKey...),
)
}

View File

@@ -0,0 +1,326 @@
// 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 group
import (
"context"
"fmt"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/entc/integration/multischema/versioned/predicate"
)
// Mutation represents an operation that mutates the Group nodes in the graph.
type Mutation struct {
op ent.Op
typ string
name *string
clearedFields map[string]struct{}
users map[int]struct{}
removedusers map[int]struct{}
clearedusers bool
predicates []predicate.Group
}
// NewMutation creates a new Mutation for the Group entity.
func NewMutation(op ent.Op) *Mutation {
return &Mutation{
op: op,
typ: "Group",
clearedFields: make(map[string]struct{}),
}
}
// Predicates returns the list of predicates set on the mutation.
func (m *Mutation) Predicates() []predicate.Group {
return m.predicates
}
// SetName sets the "name" field.
func (m *Mutation) SetName(s string) {
m.name = &s
}
// Name returns the value of the "name" field in the mutation.
func (m *Mutation) Name() (r string, exists bool) {
v := m.name
if v == nil {
return
}
return *v, true
}
// ResetName resets all changes to the "name" field.
func (m *Mutation) ResetName() {
m.name = nil
}
// AddUserIDs adds the "users" edge to the User entity by ids.
func (m *Mutation) AddUserIDs(ids ...int) {
if m.users == nil {
m.users = make(map[int]struct{})
}
for i := range ids {
m.users[ids[i]] = struct{}{}
}
}
// ClearUsers clears the "users" edge to the User entity.
func (m *Mutation) ClearUsers() {
m.clearedusers = true
}
// UsersCleared reports if the "users" edge to the User entity was cleared.
func (m *Mutation) UsersCleared() bool {
return m.clearedusers
}
// RemoveUserIDs removes the "users" edge to the User entity by IDs.
func (m *Mutation) RemoveUserIDs(ids ...int) {
if m.removedusers == nil {
m.removedusers = make(map[int]struct{})
}
for i := range ids {
delete(m.users, ids[i])
m.removedusers[ids[i]] = struct{}{}
}
}
// RemovedUsers returns the removed IDs of the "users" edge to the User entity.
func (m *Mutation) RemovedUsersIDs() (ids []int) {
for id := range m.removedusers {
ids = append(ids, id)
}
return
}
// UsersIDs returns the "users" edge IDs in the mutation.
func (m *Mutation) UsersIDs() (ids []int) {
for id := range m.users {
ids = append(ids, id)
}
return
}
// ResetUsers resets all changes to the "users" edge.
func (m *Mutation) ResetUsers() {
m.users = nil
m.clearedusers = false
m.removedusers = nil
}
// Where appends a list predicates to the Mutation builder.
func (m *Mutation) Where(ps ...predicate.Group) {
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.Group, 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 (Group).
func (m *Mutation) Type() string {
return m.typ
}
// Fields returns all fields that were changed during this mutation. Note that in
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *Mutation) Fields() []string {
fields := make([]string, 0, 1)
if m.name != nil {
fields = append(fields, FieldName)
}
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 FieldName:
return m.Name()
}
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 Group 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 FieldName:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetName(v)
return nil
}
return fmt.Errorf("unknown Group field %s", name)
}
// AddedFields returns all numeric fields that were incremented/decremented during
// this mutation.
func (m *Mutation) AddedFields() []string {
return nil
}
// AddedField returns the numeric value that was incremented/decremented on a field
// with the given name. The second boolean return value indicates that this field
// was not set, or was not defined in the schema.
func (m *Mutation) AddedField(name string) (ent.Value, bool) {
return nil, false
}
// AddField adds the value to the field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *Mutation) AddField(name string, value ent.Value) error {
switch name {
}
return fmt.Errorf("unknown Group numeric field %s", name)
}
// ClearedFields returns all nullable fields that were cleared during this
// mutation.
func (m *Mutation) ClearedFields() []string {
return nil
}
// 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 {
return fmt.Errorf("unknown Group 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 FieldName:
m.ResetName()
return nil
}
return fmt.Errorf("unknown Group field %s", name)
}
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *Mutation) AddedEdges() []string {
edges := make([]string, 0, 1)
if m.users != nil {
edges = append(edges, EdgeUsers)
}
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 EdgeUsers:
ids := make([]ent.Value, 0, len(m.users))
for id := range m.users {
ids = append(ids, id)
}
return ids
}
return nil
}
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *Mutation) RemovedEdges() []string {
edges := make([]string, 0, 1)
if m.removedusers != nil {
edges = append(edges, EdgeUsers)
}
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 {
switch name {
case EdgeUsers:
ids := make([]ent.Value, 0, len(m.removedusers))
for id := range m.removedusers {
ids = append(ids, id)
}
return ids
}
return nil
}
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *Mutation) ClearedEdges() []string {
edges := make([]string, 0, 1)
if m.clearedusers {
edges = append(edges, EdgeUsers)
}
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 EdgeUsers:
return m.clearedusers
}
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 {
}
return fmt.Errorf("unknown Group 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 EdgeUsers:
m.ResetUsers()
return nil
}
return fmt.Errorf("unknown Group edge %s", name)
}

View File

@@ -0,0 +1,173 @@
// 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 group
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/versioned/internal"
"entgo.io/ent/entc/integration/multischema/versioned/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Group {
return predicate.Group(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Group {
return predicate.Group(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Group {
return predicate.Group(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldID, id))
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldName, v))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldName, v))
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldName, v))
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldIn(FieldName, vs...))
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldName, vs...))
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.Group {
return predicate.Group(sql.FieldGT(FieldName, v))
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldName, v))
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.Group {
return predicate.Group(sql.FieldLT(FieldName, v))
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldName, v))
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.Group {
return predicate.Group(sql.FieldContains(FieldName, v))
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.Group {
return predicate.Group(sql.FieldHasPrefix(FieldName, v))
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.Group {
return predicate.Group(sql.FieldHasSuffix(FieldName, v))
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.Group {
return predicate.Group(sql.FieldEqualFold(FieldName, v))
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.Group {
return predicate.Group(sql.FieldContainsFold(FieldName, v))
}
// HasUsers applies the HasEdge predicate on the "users" edge.
func HasUsers() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, UsersTable, UsersPrimaryKey...),
)
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.GroupUsers
sqlgraph.HasNeighbors(s, step)
})
}
// HasUsersWith applies the HasEdge predicate on the "users" edge with a given conditions (other predicates).
func HasUsersWith(preds ...predicate.User) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := newUsersStep()
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.GroupUsers
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.Group) predicate.Group {
return predicate.Group(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Group) predicate.Group {
return predicate.Group(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Group) predicate.Group {
return predicate.Group(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,239 @@
// 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 versioned
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/versioned/group"
"entgo.io/ent/entc/integration/multischema/versioned/user"
"entgo.io/ent/schema/field"
)
// GroupCreate is the builder for creating a Group entity.
type GroupCreate struct {
config
mutation *GroupMutation
hooks []Hook
}
// SetName sets the "name" field.
func (_c *GroupCreate) SetName(v string) *GroupCreate {
_c.mutation.SetName(v)
return _c
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_c *GroupCreate) SetNillableName(v *string) *GroupCreate {
if v != nil {
_c.SetName(*v)
}
return _c
}
// AddUserIDs adds the "users" edge to the User entity by IDs.
func (_c *GroupCreate) AddUserIDs(ids ...int) *GroupCreate {
_c.mutation.AddUserIDs(ids...)
return _c
}
// AddUsers adds the "users" edges to the User entity.
func (_c *GroupCreate) AddUsers(v ...*User) *GroupCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddUserIDs(ids...)
}
// Mutation returns the GroupMutation object of the builder.
func (_c *GroupCreate) Mutation() *GroupMutation {
return _c.mutation
}
// Save creates the Group in the database.
func (_c *GroupCreate) Save(ctx context.Context) (*Group, error) {
_c.defaults()
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *GroupCreate) SaveX(ctx context.Context) *Group {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *GroupCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *GroupCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_c *GroupCreate) defaults() {
if _, ok := _c.mutation.Name(); !ok {
v := group.DefaultName
_c.mutation.SetName(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *GroupCreate) check() error {
if _, ok := _c.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`versioned: missing required field "Group.name"`)}
}
return nil
}
func (_c *GroupCreate) sqlSave(ctx context.Context) (*Group, 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 *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
var (
_node = &Group{config: _c.config}
_spec = sqlgraph.NewCreateSpec(group.Table, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt))
)
_spec.Schema = _c.schemaConfig.Group
if value, ok := _c.mutation.Name(); ok {
_spec.SetField(group.FieldName, field.TypeString, value)
_node.Name = value
}
if nodes := _c.mutation.UsersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _c.schemaConfig.GroupUsers
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// GroupCreateBulk is the builder for creating many Group entities in bulk.
type GroupCreateBulk struct {
config
err error
builders []*GroupCreate
}
// Save creates the Group entities in the database.
func (_c *GroupCreateBulk) Save(ctx context.Context) ([]*Group, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*Group, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*GroupMutation)
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 *GroupCreateBulk) SaveX(ctx context.Context) []*Group {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *GroupCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *GroupCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,95 @@
// 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 versioned
import (
"context"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/versioned/group"
"entgo.io/ent/entc/integration/multischema/versioned/internal"
"entgo.io/ent/entc/integration/multischema/versioned/predicate"
"entgo.io/ent/schema/field"
)
// GroupDelete is the builder for deleting a Group entity.
type GroupDelete struct {
config
hooks []Hook
mutation *GroupMutation
}
// Where appends a list predicates to the GroupDelete builder.
func (_d *GroupDelete) Where(ps ...predicate.Group) *GroupDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *GroupDelete) 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 *GroupDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *GroupDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(group.Table, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt))
_spec.Node.Schema = _d.schemaConfig.Group
ctx = internal.NewSchemaConfigContext(ctx, _d.schemaConfig)
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
}
// GroupDeleteOne is the builder for deleting a single Group entity.
type GroupDeleteOne struct {
_d *GroupDelete
}
// Where appends a list predicates to the GroupDelete builder.
func (_d *GroupDeleteOne) Where(ps ...predicate.Group) *GroupDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *GroupDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{group.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *GroupDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,676 @@
// 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 versioned
import (
"context"
"database/sql/driver"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/versioned/group"
"entgo.io/ent/entc/integration/multischema/versioned/internal"
"entgo.io/ent/entc/integration/multischema/versioned/predicate"
"entgo.io/ent/entc/integration/multischema/versioned/user"
"entgo.io/ent/schema/field"
)
// GroupQuery is the builder for querying Group entities.
type GroupQuery struct {
config
ctx *QueryContext
order []group.OrderOption
inters []Interceptor
predicates []predicate.Group
withUsers *UserQuery
modifiers []func(*sql.Selector)
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the GroupQuery builder.
func (_q *GroupQuery) Where(ps ...predicate.Group) *GroupQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *GroupQuery) Limit(limit int) *GroupQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *GroupQuery) Offset(offset int) *GroupQuery {
_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 *GroupQuery) Unique(unique bool) *GroupQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *GroupQuery) Order(o ...group.OrderOption) *GroupQuery {
_q.order = append(_q.order, o...)
return _q
}
// QueryUsers chains the current query on the "users" edge.
func (_q *GroupQuery) QueryUsers() *UserQuery {
query := (&UserClient{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(group.Table, group.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, group.UsersTable, group.UsersPrimaryKey...),
)
schemaConfig := _q.schemaConfig
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.GroupUsers
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Group entity from the query.
// Returns a *NotFoundError when no Group was found.
func (_q *GroupQuery) First(ctx context.Context) (*Group, 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{group.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *GroupQuery) FirstX(ctx context.Context) *Group {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Group ID from the query.
// Returns a *NotFoundError when no Group ID was found.
func (_q *GroupQuery) 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{group.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *GroupQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Group entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Group entity is found.
// Returns a *NotFoundError when no Group entities are found.
func (_q *GroupQuery) Only(ctx context.Context) (*Group, 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{group.Label}
default:
return nil, &NotSingularError{group.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *GroupQuery) OnlyX(ctx context.Context) *Group {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Group ID in the query.
// Returns a *NotSingularError when more than one Group ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *GroupQuery) 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{group.Label}
default:
err = &NotSingularError{group.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *GroupQuery) 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 Groups.
func (_q *GroupQuery) All(ctx context.Context) ([]*Group, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Group, *GroupQuery]()
return withInterceptors[[]*Group](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *GroupQuery) AllX(ctx context.Context) []*Group {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Group IDs.
func (_q *GroupQuery) 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(group.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *GroupQuery) 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 *GroupQuery) 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[*GroupQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *GroupQuery) 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 *GroupQuery) 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("versioned: check existence: %w", err)
default:
return true, nil
}
}
// ExistX is like Exist, but panics if an error occurs.
func (_q *GroupQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the GroupQuery 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 *GroupQuery) Clone() *GroupQuery {
if _q == nil {
return nil
}
return &GroupQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]group.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Group{}, _q.predicates...),
withUsers: _q.withUsers.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
modifiers: append([]func(*sql.Selector){}, _q.modifiers...),
}
}
// WithUsers tells the query-builder to eager-load the nodes that are connected to
// the "users" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *GroupQuery) WithUsers(opts ...func(*UserQuery)) *GroupQuery {
query := (&UserClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withUsers = 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 {
// Name string `json:"name,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Group.Query().
// GroupBy(group.FieldName).
// Aggregate(versioned.Count()).
// Scan(ctx, &v)
func (_q *GroupQuery) GroupBy(field string, fields ...string) *GroupGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &GroupGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = group.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 {
// Name string `json:"name,omitempty"`
// }
//
// client.Group.Query().
// Select(group.FieldName).
// Scan(ctx, &v)
func (_q *GroupQuery) Select(fields ...string) *GroupSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &GroupSelect{GroupQuery: _q}
sbuild.label = group.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a GroupSelect configured with the given aggregations.
func (_q *GroupQuery) Aggregate(fns ...AggregateFunc) *GroupSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *GroupQuery) prepareQuery(ctx context.Context) error {
for _, inter := range _q.inters {
if inter == nil {
return fmt.Errorf("versioned: uninitialized interceptor (forgotten import versioned/runtime?)")
}
if trv, ok := inter.(Traverser); ok {
if err := trv.Traverse(ctx, _q); err != nil {
return err
}
}
}
for _, f := range _q.ctx.Fields {
if !group.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("versioned: 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 *GroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Group, error) {
var (
nodes = []*Group{}
_spec = _q.querySpec()
loadedTypes = [1]bool{
_q.withUsers != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Group).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Group{config: _q.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
_spec.Node.Schema = _q.schemaConfig.Group
ctx = internal.NewSchemaConfigContext(ctx, _q.schemaConfig)
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := _q.withUsers; query != nil {
if err := _q.loadUsers(ctx, query, nodes,
func(n *Group) { n.Edges.Users = []*User{} },
func(n *Group, e *User) { n.Edges.Users = append(n.Edges.Users, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *GroupQuery) loadUsers(ctx context.Context, query *UserQuery, nodes []*Group, init func(*Group), assign func(*Group, *User)) error {
edgeIDs := make([]driver.Value, len(nodes))
byID := make(map[int]*Group)
nids := make(map[int]map[*Group]struct{})
for i, node := range nodes {
edgeIDs[i] = node.ID
byID[node.ID] = node
if init != nil {
init(node)
}
}
query.Where(func(s *sql.Selector) {
joinT := sql.Table(group.UsersTable)
joinT.Schema(_q.schemaConfig.GroupUsers)
s.Join(joinT).On(s.C(user.FieldID), joinT.C(group.UsersPrimaryKey[1]))
s.Where(sql.InValues(joinT.C(group.UsersPrimaryKey[0]), edgeIDs...))
columns := s.SelectedColumns()
s.Select(joinT.C(group.UsersPrimaryKey[0]))
s.AppendSelect(columns...)
s.SetDistinct(false)
})
if err := query.prepareQuery(ctx); err != nil {
return err
}
qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) {
assign := spec.Assign
values := spec.ScanValues
spec.ScanValues = func(columns []string) ([]any, error) {
values, err := values(columns[1:])
if err != nil {
return nil, err
}
return append([]any{new(sql.NullInt64)}, values...), nil
}
spec.Assign = func(columns []string, values []any) error {
outValue := int(values[0].(*sql.NullInt64).Int64)
inValue := int(values[1].(*sql.NullInt64).Int64)
if nids[inValue] == nil {
nids[inValue] = map[*Group]struct{}{byID[outValue]: {}}
return assign(columns[1:], values[1:])
}
nids[inValue][byID[outValue]] = struct{}{}
return nil
}
})
})
neighbors, err := withInterceptors[[]*User](ctx, query, qr, query.inters)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nids[n.ID]
if !ok {
return fmt.Errorf(`unexpected "users" node returned %v`, n.ID)
}
for kn := range nodes {
assign(kn, n)
}
}
return nil
}
func (_q *GroupQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Schema = _q.schemaConfig.Group
ctx = internal.NewSchemaConfigContext(ctx, _q.schemaConfig)
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *GroupQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(group.Table, group.Columns, sqlgraph.NewFieldSpec(group.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, group.FieldID)
for i := range fields {
if fields[i] != group.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := _q.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := _q.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := _q.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := _q.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (_q *GroupQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(group.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = group.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()
}
t1.Schema(_q.schemaConfig.Group)
ctx = internal.NewSchemaConfigContext(ctx, _q.schemaConfig)
selector.WithContext(ctx)
for _, m := range _q.modifiers {
m(selector)
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// Modify adds a query modifier for attaching custom logic to queries.
func (_q *GroupQuery) Modify(modifiers ...func(s *sql.Selector)) *GroupSelect {
_q.modifiers = append(_q.modifiers, modifiers...)
return _q.Select()
}
// GroupGroupBy is the group-by builder for Group entities.
type GroupGroupBy struct {
selector
build *GroupQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *GroupGroupBy) Aggregate(fns ...AggregateFunc) *GroupGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *GroupGroupBy) 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[*GroupQuery, *GroupGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *GroupGroupBy) sqlScan(ctx context.Context, root *GroupQuery, 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)
}
// GroupSelect is the builder for selecting fields of Group entities.
type GroupSelect struct {
*GroupQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *GroupSelect) Aggregate(fns ...AggregateFunc) *GroupSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *GroupSelect) 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[*GroupQuery, *GroupSelect](ctx, _s.GroupQuery, _s, _s.inters, v)
}
func (_s *GroupSelect) sqlScan(ctx context.Context, root *GroupQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(_s.fns))
for _, fn := range _s.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*_s.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// Modify adds a query modifier for attaching custom logic to queries.
func (_s *GroupSelect) Modify(modifiers ...func(s *sql.Selector)) *GroupSelect {
_s.modifiers = append(_s.modifiers, modifiers...)
return _s
}

View File

@@ -0,0 +1,403 @@
// 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 versioned
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/versioned/group"
"entgo.io/ent/entc/integration/multischema/versioned/internal"
"entgo.io/ent/entc/integration/multischema/versioned/predicate"
"entgo.io/ent/entc/integration/multischema/versioned/user"
"entgo.io/ent/schema/field"
)
// GroupUpdate is the builder for updating Group entities.
type GroupUpdate struct {
config
hooks []Hook
mutation *GroupMutation
modifiers []func(*sql.UpdateBuilder)
}
// Where appends a list predicates to the GroupUpdate builder.
func (_u *GroupUpdate) Where(ps ...predicate.Group) *GroupUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetName sets the "name" field.
func (_u *GroupUpdate) SetName(v string) *GroupUpdate {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *GroupUpdate) SetNillableName(v *string) *GroupUpdate {
if v != nil {
_u.SetName(*v)
}
return _u
}
// AddUserIDs adds the "users" edge to the User entity by IDs.
func (_u *GroupUpdate) AddUserIDs(ids ...int) *GroupUpdate {
_u.mutation.AddUserIDs(ids...)
return _u
}
// AddUsers adds the "users" edges to the User entity.
func (_u *GroupUpdate) AddUsers(v ...*User) *GroupUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddUserIDs(ids...)
}
// Mutation returns the GroupMutation object of the builder.
func (_u *GroupUpdate) Mutation() *GroupMutation {
return _u.mutation
}
// ClearUsers clears all "users" edges to the User entity.
func (_u *GroupUpdate) ClearUsers() *GroupUpdate {
_u.mutation.ClearUsers()
return _u
}
// RemoveUserIDs removes the "users" edge to User entities by IDs.
func (_u *GroupUpdate) RemoveUserIDs(ids ...int) *GroupUpdate {
_u.mutation.RemoveUserIDs(ids...)
return _u
}
// RemoveUsers removes "users" edges to User entities.
func (_u *GroupUpdate) RemoveUsers(v ...*User) *GroupUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveUserIDs(ids...)
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *GroupUpdate) 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 *GroupUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *GroupUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *GroupUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
func (_u *GroupUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *GroupUpdate {
_u.modifiers = append(_u.modifiers, modifiers...)
return _u
}
func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
_spec := sqlgraph.NewUpdateSpec(group.Table, group.Columns, sqlgraph.NewFieldSpec(group.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.Name(); ok {
_spec.SetField(group.FieldName, field.TypeString, value)
}
if _u.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _u.schemaConfig.GroupUsers
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedUsersIDs(); len(nodes) > 0 && !_u.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _u.schemaConfig.GroupUsers
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.UsersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _u.schemaConfig.GroupUsers
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_spec.Node.Schema = _u.schemaConfig.Group
ctx = internal.NewSchemaConfigContext(ctx, _u.schemaConfig)
_spec.AddModifiers(_u.modifiers...)
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{group.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// GroupUpdateOne is the builder for updating a single Group entity.
type GroupUpdateOne struct {
config
fields []string
hooks []Hook
mutation *GroupMutation
modifiers []func(*sql.UpdateBuilder)
}
// SetName sets the "name" field.
func (_u *GroupUpdateOne) SetName(v string) *GroupUpdateOne {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *GroupUpdateOne) SetNillableName(v *string) *GroupUpdateOne {
if v != nil {
_u.SetName(*v)
}
return _u
}
// AddUserIDs adds the "users" edge to the User entity by IDs.
func (_u *GroupUpdateOne) AddUserIDs(ids ...int) *GroupUpdateOne {
_u.mutation.AddUserIDs(ids...)
return _u
}
// AddUsers adds the "users" edges to the User entity.
func (_u *GroupUpdateOne) AddUsers(v ...*User) *GroupUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddUserIDs(ids...)
}
// Mutation returns the GroupMutation object of the builder.
func (_u *GroupUpdateOne) Mutation() *GroupMutation {
return _u.mutation
}
// ClearUsers clears all "users" edges to the User entity.
func (_u *GroupUpdateOne) ClearUsers() *GroupUpdateOne {
_u.mutation.ClearUsers()
return _u
}
// RemoveUserIDs removes the "users" edge to User entities by IDs.
func (_u *GroupUpdateOne) RemoveUserIDs(ids ...int) *GroupUpdateOne {
_u.mutation.RemoveUserIDs(ids...)
return _u
}
// RemoveUsers removes "users" edges to User entities.
func (_u *GroupUpdateOne) RemoveUsers(v ...*User) *GroupUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveUserIDs(ids...)
}
// Where appends a list predicates to the GroupUpdate builder.
func (_u *GroupUpdateOne) Where(ps ...predicate.Group) *GroupUpdateOne {
_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 *GroupUpdateOne) Select(field string, fields ...string) *GroupUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated Group entity.
func (_u *GroupUpdateOne) Save(ctx context.Context) (*Group, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *GroupUpdateOne) SaveX(ctx context.Context) *Group {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *GroupUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *GroupUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
func (_u *GroupUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *GroupUpdateOne {
_u.modifiers = append(_u.modifiers, modifiers...)
return _u
}
func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error) {
_spec := sqlgraph.NewUpdateSpec(group.Table, group.Columns, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`versioned: missing "Group.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, group.FieldID)
for _, f := range fields {
if !group.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("versioned: invalid field %q for query", f)}
}
if f != group.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.Name(); ok {
_spec.SetField(group.FieldName, field.TypeString, value)
}
if _u.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _u.schemaConfig.GroupUsers
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedUsersIDs(); len(nodes) > 0 && !_u.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _u.schemaConfig.GroupUsers
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.UsersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _u.schemaConfig.GroupUsers
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_spec.Node.Schema = _u.schemaConfig.Group
ctx = internal.NewSchemaConfigContext(ctx, _u.schemaConfig)
_spec.AddModifiers(_u.modifiers...)
_node = &Group{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{group.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

View File

@@ -0,0 +1,239 @@
// 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/entc/integration/multischema/versioned"
)
// The FriendshipFunc type is an adapter to allow the use of ordinary
// function as Friendship mutator.
type FriendshipFunc func(context.Context, *versioned.FriendshipMutation) (versioned.Value, error)
// Mutate calls f(ctx, m).
func (f FriendshipFunc) Mutate(ctx context.Context, m versioned.Mutation) (versioned.Value, error) {
if mv, ok := m.(*versioned.FriendshipMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *versioned.FriendshipMutation", m)
}
// The GroupFunc type is an adapter to allow the use of ordinary
// function as Group mutator.
type GroupFunc func(context.Context, *versioned.GroupMutation) (versioned.Value, error)
// Mutate calls f(ctx, m).
func (f GroupFunc) Mutate(ctx context.Context, m versioned.Mutation) (versioned.Value, error) {
if mv, ok := m.(*versioned.GroupMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *versioned.GroupMutation", m)
}
// The PetFunc type is an adapter to allow the use of ordinary
// function as Pet mutator.
type PetFunc func(context.Context, *versioned.PetMutation) (versioned.Value, error)
// Mutate calls f(ctx, m).
func (f PetFunc) Mutate(ctx context.Context, m versioned.Mutation) (versioned.Value, error) {
if mv, ok := m.(*versioned.PetMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *versioned.PetMutation", m)
}
// The UserFunc type is an adapter to allow the use of ordinary
// function as User mutator.
type UserFunc func(context.Context, *versioned.UserMutation) (versioned.Value, error)
// Mutate calls f(ctx, m).
func (f UserFunc) Mutate(ctx context.Context, m versioned.Mutation) (versioned.Value, error) {
if mv, ok := m.(*versioned.UserMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *versioned.UserMutation", m)
}
// Condition is a hook condition function.
type Condition func(context.Context, versioned.Mutation) bool
// And groups conditions with the AND operator.
func And(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m versioned.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 versioned.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 versioned.Mutation) bool {
return !cond(ctx, m)
}
}
// HasOp is a condition testing mutation operation.
func HasOp(op versioned.Op) Condition {
return func(_ context.Context, m versioned.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 versioned.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 versioned.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 versioned.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 versioned.Hook, cond Condition) versioned.Hook {
return func(next versioned.Mutator) versioned.Mutator {
return versioned.MutateFunc(func(ctx context.Context, m versioned.Mutation) (versioned.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, versioned.Delete|versioned.Create)
func On(hk versioned.Hook, op versioned.Op) versioned.Hook {
return If(hk, HasOp(op))
}
// Unless skips the given hook only for the given operation.
//
// hook.Unless(Log, versioned.Update|versioned.UpdateOne)
func Unless(hk versioned.Hook, op versioned.Op) versioned.Hook {
return If(hk, Not(HasOp(op)))
}
// FixedError is a hook returning a fixed error.
func FixedError(err error) versioned.Hook {
return func(versioned.Mutator) versioned.Mutator {
return versioned.MutateFunc(func(context.Context, versioned.Mutation) (versioned.Value, error) {
return nil, err
})
}
}
// Reject returns a hook that rejects all operations that match op.
//
// func (T) Hooks() []versioned.Hook {
// return []versioned.Hook{
// Reject(versioned.Delete|versioned.Update),
// }
// }
func Reject(op versioned.Op) versioned.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 []versioned.Hook
}
// NewChain creates a new chain of hooks.
func NewChain(hooks ...versioned.Hook) Chain {
return Chain{append([]versioned.Hook(nil), hooks...)}
}
// Hook chains the list of hooks and returns the final hook.
func (c Chain) Hook() versioned.Hook {
return func(mutator versioned.Mutator) versioned.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 ...versioned.Hook) Chain {
newHooks := make([]versioned.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...)
}

View File

@@ -0,0 +1,34 @@
// 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 internal
import "context"
// SchemaConfig represents alternative schema names for all tables
// that can be passed at runtime.
type SchemaConfig struct {
Friendship string // Friendship table.
Group string // Group table.
GroupUsers string // Group-users->User table.
Pet string // Pet table.
User string // User table.
UserFriends string // User-friends->User table.
UserFollowing string // User-following->User table.
}
type schemaCtxKey struct{}
// SchemaConfigFromContext returns a SchemaConfig stored inside a context, or empty if there isn't one.
func SchemaConfigFromContext(ctx context.Context) SchemaConfig {
config, _ := ctx.Value(schemaCtxKey{}).(SchemaConfig)
return config
}
// NewSchemaConfigContext returns a new context with the given SchemaConfig attached.
func NewSchemaConfigContext(parent context.Context, config SchemaConfig) context.Context {
return context.WithValue(parent, schemaCtxKey{}, config)
}

View 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...)
}

View File

@@ -0,0 +1,166 @@
// 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 (
// FriendshipsColumns holds the columns for the "friendships" table.
FriendshipsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "weight", Type: field.TypeInt, Default: 1},
{Name: "created_at", Type: field.TypeTime},
{Name: "user_id", Type: field.TypeInt},
{Name: "friend_id", Type: field.TypeInt},
}
// FriendshipsTable holds the schema information for the "friendships" table.
FriendshipsTable = &schema.Table{
Name: "friendships",
Columns: FriendshipsColumns,
PrimaryKey: []*schema.Column{FriendshipsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "friendships_users_user",
Columns: []*schema.Column{FriendshipsColumns[3]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.NoAction,
},
{
Symbol: "friendships_users_friend",
Columns: []*schema.Column{FriendshipsColumns[4]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.NoAction,
},
},
Indexes: []*schema.Index{
{
Name: "friendship_created_at",
Unique: false,
Columns: []*schema.Column{FriendshipsColumns[2]},
},
{
Name: "friendship_user_id_friend_id",
Unique: true,
Columns: []*schema.Column{FriendshipsColumns[3], FriendshipsColumns[4]},
},
},
}
// GroupsColumns holds the columns for the "groups" table.
GroupsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "name", Type: field.TypeString, Default: "unknown"},
}
// GroupsTable holds the schema information for the "groups" table.
GroupsTable = &schema.Table{
Name: "groups",
Columns: GroupsColumns,
PrimaryKey: []*schema.Column{GroupsColumns[0]},
}
// PetsColumns holds the columns for the "pets" table.
PetsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "name", Type: field.TypeString, Default: "unknown"},
{Name: "owner_id", Type: field.TypeInt, Nullable: true},
}
// PetsTable holds the schema information for the "pets" table.
PetsTable = &schema.Table{
Name: "pets",
Columns: PetsColumns,
PrimaryKey: []*schema.Column{PetsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "pets_users_pets",
Columns: []*schema.Column{PetsColumns[2]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.SetNull,
},
},
}
// UsersColumns holds the columns for the "users" table.
UsersColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "name", Type: field.TypeString, Default: "unknown"},
}
// UsersTable holds the schema information for the "users" table.
UsersTable = &schema.Table{
Name: "users",
Columns: UsersColumns,
PrimaryKey: []*schema.Column{UsersColumns[0]},
}
// GroupUsersColumns holds the columns for the "group_users" table.
GroupUsersColumns = []*schema.Column{
{Name: "group_id", Type: field.TypeInt},
{Name: "user_id", Type: field.TypeInt},
}
// GroupUsersTable holds the schema information for the "group_users" table.
GroupUsersTable = &schema.Table{
Name: "group_users",
Columns: GroupUsersColumns,
PrimaryKey: []*schema.Column{GroupUsersColumns[0], GroupUsersColumns[1]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "group_users_group_id",
Columns: []*schema.Column{GroupUsersColumns[0]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.Cascade,
},
{
Symbol: "group_users_user_id",
Columns: []*schema.Column{GroupUsersColumns[1]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.Cascade,
},
},
}
// UserFollowingColumns holds the columns for the "user_following" table.
UserFollowingColumns = []*schema.Column{
{Name: "user_id", Type: field.TypeInt},
{Name: "follower_id", Type: field.TypeInt},
}
// UserFollowingTable holds the schema information for the "user_following" table.
UserFollowingTable = &schema.Table{
Name: "user_following",
Columns: UserFollowingColumns,
PrimaryKey: []*schema.Column{UserFollowingColumns[0], UserFollowingColumns[1]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "user_following_user_id",
Columns: []*schema.Column{UserFollowingColumns[0]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.Cascade,
},
{
Symbol: "user_following_follower_id",
Columns: []*schema.Column{UserFollowingColumns[1]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.Cascade,
},
},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
FriendshipsTable,
GroupsTable,
PetsTable,
UsersTable,
GroupUsersTable,
UserFollowingTable,
}
)
func init() {
FriendshipsTable.ForeignKeys[0].RefTable = UsersTable
FriendshipsTable.ForeignKeys[1].RefTable = UsersTable
PetsTable.ForeignKeys[0].RefTable = UsersTable
GroupUsersTable.ForeignKeys[0].RefTable = GroupsTable
GroupUsersTable.ForeignKeys[1].RefTable = UsersTable
UserFollowingTable.ForeignKeys[0].RefTable = UsersTable
UserFollowingTable.ForeignKeys[1].RefTable = UsersTable
}

View File

@@ -0,0 +1,644 @@
// 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 versioned
import (
"context"
"errors"
"fmt"
"sync"
"time"
"entgo.io/ent"
"entgo.io/ent/entc/integration/multischema/versioned/friendship"
"entgo.io/ent/entc/integration/multischema/versioned/group"
"entgo.io/ent/entc/integration/multischema/versioned/pet"
"entgo.io/ent/entc/integration/multischema/versioned/user"
)
const (
// Operation types.
OpCreate = ent.OpCreate
OpDelete = ent.OpDelete
OpDeleteOne = ent.OpDeleteOne
OpUpdate = ent.OpUpdate
OpUpdateOne = ent.OpUpdateOne
// Node types.
TypeFriendship = "Friendship"
TypeGroup = "Group"
TypePet = "Pet"
TypeUser = "User"
)
// FriendshipMutation represents an operation that mutates the Friendship nodes in the graph.
type FriendshipMutation struct {
friendship.Mutation
config
id *int
done bool
oldValue func(context.Context) (*Friendship, error)
}
var _ ent.Mutation = (*FriendshipMutation)(nil)
// friendshipOption allows management of the mutation configuration using functional options.
type friendshipOption func(*FriendshipMutation)
// newFriendshipMutation creates new mutation for the Friendship entity.
func newFriendshipMutation(c config, op Op, opts ...friendshipOption) *FriendshipMutation {
m := &FriendshipMutation{
Mutation: *friendship.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 *FriendshipMutation) ID() (id int, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// withFriendshipID sets the ID field of the mutation.
func withFriendshipID(id int) friendshipOption {
return func(m *FriendshipMutation) {
var (
err error
once sync.Once
value *Friendship
)
m.oldValue = func(ctx context.Context) (*Friendship, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().Friendship.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withFriendship sets the old Friendship of the mutation.
func withFriendship(node *Friendship) friendshipOption {
return func(m *FriendshipMutation) {
m.oldValue = func(context.Context) (*Friendship, 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 FriendshipMutation) 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 FriendshipMutation) Tx() (*Tx, error) {
if _, ok := m.driver.(*txDriver); !ok {
return nil, errors.New("versioned: 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 *FriendshipMutation) 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().Friendship.Query().Where(m.Predicates()...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.Op())
}
}
// OldWeight returns the old "weight" field's value of the Friendship entity.
// If the Friendship 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 *FriendshipMutation) OldWeight(ctx context.Context) (v int, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldWeight is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldWeight requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldWeight: %w", err)
}
return oldValue.Weight, nil
}
// OldCreatedAt returns the old "created_at" field's value of the Friendship entity.
// If the Friendship 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 *FriendshipMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldCreatedAt requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err)
}
return oldValue.CreatedAt, nil
}
// OldUserID returns the old "user_id" field's value of the Friendship entity.
// If the Friendship 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 *FriendshipMutation) OldUserID(ctx context.Context) (v int, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldUserID is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldUserID requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldUserID: %w", err)
}
return oldValue.UserID, nil
}
// OldFriendID returns the old "friend_id" field's value of the Friendship entity.
// If the Friendship 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 *FriendshipMutation) OldFriendID(ctx context.Context) (v int, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldFriendID is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldFriendID requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldFriendID: %w", err)
}
return oldValue.FriendID, 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 *FriendshipMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case friendship.FieldWeight:
return m.OldWeight(ctx)
case friendship.FieldCreatedAt:
return m.OldCreatedAt(ctx)
case friendship.FieldUserID:
return m.OldUserID(ctx)
case friendship.FieldFriendID:
return m.OldFriendID(ctx)
}
return nil, fmt.Errorf("unknown Friendship field %s", name)
}
// GroupMutation represents an operation that mutates the Group nodes in the graph.
type GroupMutation struct {
group.Mutation
config
id *int
done bool
oldValue func(context.Context) (*Group, error)
}
var _ ent.Mutation = (*GroupMutation)(nil)
// groupOption allows management of the mutation configuration using functional options.
type groupOption func(*GroupMutation)
// newGroupMutation creates new mutation for the Group entity.
func newGroupMutation(c config, op Op, opts ...groupOption) *GroupMutation {
m := &GroupMutation{
Mutation: *group.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 *GroupMutation) ID() (id int, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// withGroupID sets the ID field of the mutation.
func withGroupID(id int) groupOption {
return func(m *GroupMutation) {
var (
err error
once sync.Once
value *Group
)
m.oldValue = func(ctx context.Context) (*Group, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().Group.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withGroup sets the old Group of the mutation.
func withGroup(node *Group) groupOption {
return func(m *GroupMutation) {
m.oldValue = func(context.Context) (*Group, 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 GroupMutation) 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 GroupMutation) Tx() (*Tx, error) {
if _, ok := m.driver.(*txDriver); !ok {
return nil, errors.New("versioned: 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 *GroupMutation) 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().Group.Query().Where(m.Predicates()...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.Op())
}
}
// OldName returns the old "name" field's value of the Group entity.
// If the Group 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 *GroupMutation) OldName(ctx context.Context) (v string, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldName is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldName requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldName: %w", err)
}
return oldValue.Name, nil
}
// 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 *GroupMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case group.FieldName:
return m.OldName(ctx)
}
return nil, fmt.Errorf("unknown Group field %s", name)
}
// PetMutation represents an operation that mutates the Pet nodes in the graph.
type PetMutation struct {
pet.Mutation
config
id *int
done bool
oldValue func(context.Context) (*Pet, error)
}
var _ ent.Mutation = (*PetMutation)(nil)
// petOption allows management of the mutation configuration using functional options.
type petOption func(*PetMutation)
// newPetMutation creates new mutation for the Pet entity.
func newPetMutation(c config, op Op, opts ...petOption) *PetMutation {
m := &PetMutation{
Mutation: *pet.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 *PetMutation) ID() (id int, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// withPetID sets the ID field of the mutation.
func withPetID(id int) petOption {
return func(m *PetMutation) {
var (
err error
once sync.Once
value *Pet
)
m.oldValue = func(ctx context.Context) (*Pet, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().Pet.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withPet sets the old Pet of the mutation.
func withPet(node *Pet) petOption {
return func(m *PetMutation) {
m.oldValue = func(context.Context) (*Pet, 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 PetMutation) 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 PetMutation) Tx() (*Tx, error) {
if _, ok := m.driver.(*txDriver); !ok {
return nil, errors.New("versioned: 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 *PetMutation) 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().Pet.Query().Where(m.Predicates()...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.Op())
}
}
// OldName returns the old "name" field's value of the Pet entity.
// If the Pet 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 *PetMutation) OldName(ctx context.Context) (v string, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldName is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldName requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldName: %w", err)
}
return oldValue.Name, nil
}
// OldOwnerID returns the old "owner_id" field's value of the Pet entity.
// If the Pet 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 *PetMutation) OldOwnerID(ctx context.Context) (v int, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldOwnerID is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldOwnerID requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldOwnerID: %w", err)
}
return oldValue.OwnerID, 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 *PetMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case pet.FieldName:
return m.OldName(ctx)
case pet.FieldOwnerID:
return m.OldOwnerID(ctx)
}
return nil, fmt.Errorf("unknown Pet field %s", name)
}
// UserMutation represents an operation that mutates the User nodes in the graph.
type UserMutation struct {
user.Mutation
config
id *int
done bool
oldValue func(context.Context) (*User, error)
}
var _ ent.Mutation = (*UserMutation)(nil)
// userOption allows management of the mutation configuration using functional options.
type userOption func(*UserMutation)
// newUserMutation creates new mutation for the User entity.
func newUserMutation(c config, op Op, opts ...userOption) *UserMutation {
m := &UserMutation{
Mutation: *user.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 *UserMutation) ID() (id int, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// withUserID sets the ID field of the mutation.
func withUserID(id int) userOption {
return func(m *UserMutation) {
var (
err error
once sync.Once
value *User
)
m.oldValue = func(ctx context.Context) (*User, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().User.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withUser sets the old User of the mutation.
func withUser(node *User) userOption {
return func(m *UserMutation) {
m.oldValue = func(context.Context) (*User, 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 UserMutation) 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 UserMutation) Tx() (*Tx, error) {
if _, ok := m.driver.(*txDriver); !ok {
return nil, errors.New("versioned: 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 *UserMutation) 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().User.Query().Where(m.Predicates()...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.Op())
}
}
// OldName returns the old "name" field's value of the User entity.
// If the User 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 *UserMutation) OldName(ctx context.Context) (v string, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldName is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldName requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldName: %w", err)
}
return oldValue.Name, nil
}
// 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 *UserMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case user.FieldName:
return m.OldName(ctx)
}
return nil, fmt.Errorf("unknown User field %s", name)
}

View File

@@ -0,0 +1,147 @@
// 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 versioned
import (
"fmt"
"strings"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/entc/integration/multischema/versioned/pet"
"entgo.io/ent/entc/integration/multischema/versioned/user"
)
// Pet is the model entity for the Pet schema.
type Pet struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// OwnerID holds the value of the "owner_id" field.
OwnerID int `json:"owner_id,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the PetQuery when eager-loading is set.
Edges PetEdges `json:"edges"`
selectValues sql.SelectValues
}
// PetEdges holds the relations/edges for other nodes in the graph.
type PetEdges struct {
// Owner holds the value of the owner edge.
Owner *User `json:"owner,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [1]bool
}
// OwnerOrErr returns the Owner value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e PetEdges) OwnerOrErr() (*User, error) {
if e.Owner != nil {
return e.Owner, nil
} else if e.loadedTypes[0] {
return nil, &NotFoundError{label: user.Label}
}
return nil, &NotLoadedError{edge: "owner"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Pet) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case pet.FieldID, pet.FieldOwnerID:
values[i] = new(sql.NullInt64)
case pet.FieldName:
values[i] = new(sql.NullString)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Pet fields.
func (_m *Pet) 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 pet.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 pet.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
_m.Name = value.String
}
case pet.FieldOwnerID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field owner_id", values[i])
} else if value.Valid {
_m.OwnerID = int(value.Int64)
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Pet.
// This includes values selected through modifiers, order, etc.
func (_m *Pet) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryOwner queries the "owner" edge of the Pet entity.
func (_m *Pet) QueryOwner() *UserQuery {
return NewPetClient(_m.config).QueryOwner(_m)
}
// Update returns a builder for updating this Pet.
// Note that you need to call Pet.Unwrap() before calling this method if this Pet
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Pet) Update() *PetUpdateOne {
return NewPetClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Pet 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 *Pet) Unwrap() *Pet {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("versioned: Pet is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Pet) String() string {
var builder strings.Builder
builder.WriteString("Pet(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("name=")
builder.WriteString(_m.Name)
builder.WriteString(", ")
builder.WriteString("owner_id=")
builder.WriteString(fmt.Sprintf("%v", _m.OwnerID))
builder.WriteByte(')')
return builder.String()
}
// Pets is a parsable slice of Pet.
type Pets []*Pet

View File

@@ -0,0 +1,347 @@
// 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 pet
import (
"context"
"fmt"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/entc/integration/multischema/versioned/predicate"
)
// Mutation represents an operation that mutates the Pet nodes in the graph.
type Mutation struct {
op ent.Op
typ string
name *string
clearedFields map[string]struct{}
owner *int
clearedowner bool
predicates []predicate.Pet
}
// NewMutation creates a new Mutation for the Pet entity.
func NewMutation(op ent.Op) *Mutation {
return &Mutation{
op: op,
typ: "Pet",
clearedFields: make(map[string]struct{}),
}
}
// Predicates returns the list of predicates set on the mutation.
func (m *Mutation) Predicates() []predicate.Pet {
return m.predicates
}
// SetName sets the "name" field.
func (m *Mutation) SetName(s string) {
m.name = &s
}
// Name returns the value of the "name" field in the mutation.
func (m *Mutation) Name() (r string, exists bool) {
v := m.name
if v == nil {
return
}
return *v, true
}
// ResetName resets all changes to the "name" field.
func (m *Mutation) ResetName() {
m.name = nil
}
// SetOwnerID sets the "owner_id" field.
func (m *Mutation) SetOwnerID(i int) {
m.owner = &i
}
// OwnerID returns the value of the "owner_id" field in the mutation.
func (m *Mutation) OwnerID() (r int, exists bool) {
v := m.owner
if v == nil {
return
}
return *v, true
}
// ClearOwnerID clears the value of the "owner_id" field.
func (m *Mutation) ClearOwnerID() {
m.owner = nil
m.clearedFields[FieldOwnerID] = struct{}{}
}
// OwnerIDCleared returns if the "owner_id" field was cleared in this mutation.
func (m *Mutation) OwnerIDCleared() bool {
_, ok := m.clearedFields[FieldOwnerID]
return ok
}
// ResetOwnerID resets all changes to the "owner_id" field.
func (m *Mutation) ResetOwnerID() {
m.owner = nil
delete(m.clearedFields, FieldOwnerID)
}
// ClearOwner clears the "owner" edge to the User entity.
func (m *Mutation) ClearOwner() {
m.clearedowner = true
m.clearedFields[FieldOwnerID] = struct{}{}
}
// OwnerCleared reports if the "owner" edge to the User entity was cleared.
func (m *Mutation) OwnerCleared() bool {
return m.OwnerIDCleared() || m.clearedowner
}
// OwnerIDs returns the "owner" edge IDs in the mutation.
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
// OwnerID instead. It exists only for internal usage by the builders.
func (m *Mutation) OwnerIDs() (ids []int) {
if id := m.owner; id != nil {
ids = append(ids, *id)
}
return
}
// ResetOwner resets all changes to the "owner" edge.
func (m *Mutation) ResetOwner() {
m.owner = nil
m.clearedowner = false
}
// Where appends a list predicates to the Mutation builder.
func (m *Mutation) Where(ps ...predicate.Pet) {
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.Pet, 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 (Pet).
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.name != nil {
fields = append(fields, FieldName)
}
if m.owner != nil {
fields = append(fields, FieldOwnerID)
}
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 FieldName:
return m.Name()
case FieldOwnerID:
return m.OwnerID()
}
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 Pet 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 FieldName:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetName(v)
return nil
case FieldOwnerID:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetOwnerID(v)
return nil
}
return fmt.Errorf("unknown Pet field %s", name)
}
// AddedFields returns all numeric fields that were incremented/decremented during
// this mutation.
func (m *Mutation) AddedFields() []string {
var fields []string
return fields
}
// AddedField returns the numeric value that was incremented/decremented on a field
// with the given name. The second boolean return value indicates that this field
// was not set, or was not defined in the schema.
func (m *Mutation) AddedField(name string) (ent.Value, bool) {
switch name {
}
return nil, false
}
// AddField adds the value to the field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *Mutation) AddField(name string, value ent.Value) error {
switch name {
}
return fmt.Errorf("unknown Pet 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(FieldOwnerID) {
fields = append(fields, FieldOwnerID)
}
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 FieldOwnerID:
m.ClearOwnerID()
return nil
}
return fmt.Errorf("unknown Pet 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 FieldName:
m.ResetName()
return nil
case FieldOwnerID:
m.ResetOwnerID()
return nil
}
return fmt.Errorf("unknown Pet field %s", name)
}
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *Mutation) AddedEdges() []string {
edges := make([]string, 0, 1)
if m.owner != nil {
edges = append(edges, EdgeOwner)
}
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 EdgeOwner:
if id := m.owner; id != nil {
return []ent.Value{*id}
}
}
return nil
}
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *Mutation) RemovedEdges() []string {
edges := make([]string, 0, 1)
return edges
}
// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
// the given name in this mutation.
func (m *Mutation) RemovedIDs(name string) []ent.Value {
return nil
}
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *Mutation) ClearedEdges() []string {
edges := make([]string, 0, 1)
if m.clearedowner {
edges = append(edges, EdgeOwner)
}
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 EdgeOwner:
return m.clearedowner
}
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 EdgeOwner:
m.ClearOwner()
return nil
}
return fmt.Errorf("unknown Pet 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 EdgeOwner:
m.ResetOwner()
return nil
}
return fmt.Errorf("unknown Pet edge %s", name)
}

View 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 pet
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the pet type in the database.
Label = "pet"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldOwnerID holds the string denoting the owner_id field in the database.
FieldOwnerID = "owner_id"
// EdgeOwner holds the string denoting the owner edge name in mutations.
EdgeOwner = "owner"
// Table holds the table name of the pet in the database.
Table = "pets"
// OwnerTable is the table that holds the owner relation/edge.
OwnerTable = "pets"
// OwnerInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
OwnerInverseTable = "users"
// OwnerColumn is the table column denoting the owner relation/edge.
OwnerColumn = "owner_id"
)
// Columns holds all SQL columns for pet fields.
var Columns = []string{
FieldID,
FieldName,
FieldOwnerID,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// DefaultName holds the default value on creation for the "name" field.
DefaultName string
)
// OrderOption defines the ordering options for the Pet 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()
}
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, opts...).ToFunc()
}
// ByOwnerID orders the results by the owner_id field.
func ByOwnerID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldOwnerID, opts...).ToFunc()
}
// ByOwnerField orders the results by owner field.
func ByOwnerField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newOwnerStep(), sql.OrderByField(field, opts...))
}
}
func newOwnerStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(OwnerInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, OwnerTable, OwnerColumn),
)
}

View File

@@ -0,0 +1,208 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package pet
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/versioned/internal"
"entgo.io/ent/entc/integration/multischema/versioned/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Pet {
return predicate.Pet(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Pet {
return predicate.Pet(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Pet {
return predicate.Pet(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Pet {
return predicate.Pet(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Pet {
return predicate.Pet(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Pet {
return predicate.Pet(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Pet {
return predicate.Pet(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Pet {
return predicate.Pet(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Pet {
return predicate.Pet(sql.FieldLTE(FieldID, id))
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Pet {
return predicate.Pet(sql.FieldEQ(FieldName, v))
}
// OwnerID applies equality check predicate on the "owner_id" field. It's identical to OwnerIDEQ.
func OwnerID(v int) predicate.Pet {
return predicate.Pet(sql.FieldEQ(FieldOwnerID, v))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Pet {
return predicate.Pet(sql.FieldEQ(FieldName, v))
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.Pet {
return predicate.Pet(sql.FieldNEQ(FieldName, v))
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.Pet {
return predicate.Pet(sql.FieldIn(FieldName, vs...))
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.Pet {
return predicate.Pet(sql.FieldNotIn(FieldName, vs...))
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.Pet {
return predicate.Pet(sql.FieldGT(FieldName, v))
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.Pet {
return predicate.Pet(sql.FieldGTE(FieldName, v))
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.Pet {
return predicate.Pet(sql.FieldLT(FieldName, v))
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.Pet {
return predicate.Pet(sql.FieldLTE(FieldName, v))
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.Pet {
return predicate.Pet(sql.FieldContains(FieldName, v))
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.Pet {
return predicate.Pet(sql.FieldHasPrefix(FieldName, v))
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.Pet {
return predicate.Pet(sql.FieldHasSuffix(FieldName, v))
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.Pet {
return predicate.Pet(sql.FieldEqualFold(FieldName, v))
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.Pet {
return predicate.Pet(sql.FieldContainsFold(FieldName, v))
}
// OwnerIDEQ applies the EQ predicate on the "owner_id" field.
func OwnerIDEQ(v int) predicate.Pet {
return predicate.Pet(sql.FieldEQ(FieldOwnerID, v))
}
// OwnerIDNEQ applies the NEQ predicate on the "owner_id" field.
func OwnerIDNEQ(v int) predicate.Pet {
return predicate.Pet(sql.FieldNEQ(FieldOwnerID, v))
}
// OwnerIDIn applies the In predicate on the "owner_id" field.
func OwnerIDIn(vs ...int) predicate.Pet {
return predicate.Pet(sql.FieldIn(FieldOwnerID, vs...))
}
// OwnerIDNotIn applies the NotIn predicate on the "owner_id" field.
func OwnerIDNotIn(vs ...int) predicate.Pet {
return predicate.Pet(sql.FieldNotIn(FieldOwnerID, vs...))
}
// OwnerIDIsNil applies the IsNil predicate on the "owner_id" field.
func OwnerIDIsNil() predicate.Pet {
return predicate.Pet(sql.FieldIsNull(FieldOwnerID))
}
// OwnerIDNotNil applies the NotNil predicate on the "owner_id" field.
func OwnerIDNotNil() predicate.Pet {
return predicate.Pet(sql.FieldNotNull(FieldOwnerID))
}
// HasOwner applies the HasEdge predicate on the "owner" edge.
func HasOwner() predicate.Pet {
return predicate.Pet(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, OwnerTable, OwnerColumn),
)
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Pet
sqlgraph.HasNeighbors(s, step)
})
}
// HasOwnerWith applies the HasEdge predicate on the "owner" edge with a given conditions (other predicates).
func HasOwnerWith(preds ...predicate.User) predicate.Pet {
return predicate.Pet(func(s *sql.Selector) {
step := newOwnerStep()
schemaConfig := internal.SchemaConfigFromContext(s.Context())
step.To.Schema = schemaConfig.User
step.Edge.Schema = schemaConfig.Pet
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.Pet) predicate.Pet {
return predicate.Pet(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Pet) predicate.Pet {
return predicate.Pet(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Pet) predicate.Pet {
return predicate.Pet(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,244 @@
// 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 versioned
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/versioned/pet"
"entgo.io/ent/entc/integration/multischema/versioned/user"
"entgo.io/ent/schema/field"
)
// PetCreate is the builder for creating a Pet entity.
type PetCreate struct {
config
mutation *PetMutation
hooks []Hook
}
// SetName sets the "name" field.
func (_c *PetCreate) SetName(v string) *PetCreate {
_c.mutation.SetName(v)
return _c
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_c *PetCreate) SetNillableName(v *string) *PetCreate {
if v != nil {
_c.SetName(*v)
}
return _c
}
// SetOwnerID sets the "owner_id" field.
func (_c *PetCreate) SetOwnerID(v int) *PetCreate {
_c.mutation.SetOwnerID(v)
return _c
}
// SetNillableOwnerID sets the "owner_id" field if the given value is not nil.
func (_c *PetCreate) SetNillableOwnerID(v *int) *PetCreate {
if v != nil {
_c.SetOwnerID(*v)
}
return _c
}
// SetOwner sets the "owner" edge to the User entity.
func (_c *PetCreate) SetOwner(v *User) *PetCreate {
return _c.SetOwnerID(v.ID)
}
// Mutation returns the PetMutation object of the builder.
func (_c *PetCreate) Mutation() *PetMutation {
return _c.mutation
}
// Save creates the Pet in the database.
func (_c *PetCreate) Save(ctx context.Context) (*Pet, error) {
_c.defaults()
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *PetCreate) SaveX(ctx context.Context) *Pet {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *PetCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *PetCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_c *PetCreate) defaults() {
if _, ok := _c.mutation.Name(); !ok {
v := pet.DefaultName
_c.mutation.SetName(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *PetCreate) check() error {
if _, ok := _c.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`versioned: missing required field "Pet.name"`)}
}
return nil
}
func (_c *PetCreate) sqlSave(ctx context.Context) (*Pet, 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 *PetCreate) createSpec() (*Pet, *sqlgraph.CreateSpec) {
var (
_node = &Pet{config: _c.config}
_spec = sqlgraph.NewCreateSpec(pet.Table, sqlgraph.NewFieldSpec(pet.FieldID, field.TypeInt))
)
_spec.Schema = _c.schemaConfig.Pet
if value, ok := _c.mutation.Name(); ok {
_spec.SetField(pet.FieldName, field.TypeString, value)
_node.Name = value
}
if nodes := _c.mutation.OwnerIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: pet.OwnerTable,
Columns: []string{pet.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
edge.Schema = _c.schemaConfig.Pet
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.OwnerID = nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// PetCreateBulk is the builder for creating many Pet entities in bulk.
type PetCreateBulk struct {
config
err error
builders []*PetCreate
}
// Save creates the Pet entities in the database.
func (_c *PetCreateBulk) Save(ctx context.Context) ([]*Pet, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*Pet, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*PetMutation)
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 *PetCreateBulk) SaveX(ctx context.Context) []*Pet {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *PetCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *PetCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,95 @@
// 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 versioned
import (
"context"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/multischema/versioned/internal"
"entgo.io/ent/entc/integration/multischema/versioned/pet"
"entgo.io/ent/entc/integration/multischema/versioned/predicate"
"entgo.io/ent/schema/field"
)
// PetDelete is the builder for deleting a Pet entity.
type PetDelete struct {
config
hooks []Hook
mutation *PetMutation
}
// Where appends a list predicates to the PetDelete builder.
func (_d *PetDelete) Where(ps ...predicate.Pet) *PetDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *PetDelete) 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 *PetDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *PetDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(pet.Table, sqlgraph.NewFieldSpec(pet.FieldID, field.TypeInt))
_spec.Node.Schema = _d.schemaConfig.Pet
ctx = internal.NewSchemaConfigContext(ctx, _d.schemaConfig)
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
}
// PetDeleteOne is the builder for deleting a single Pet entity.
type PetDeleteOne struct {
_d *PetDelete
}
// Where appends a list predicates to the PetDelete builder.
func (_d *PetDeleteOne) Where(ps ...predicate.Pet) *PetDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *PetDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{pet.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *PetDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

Some files were not shown because too many files have changed in this diff Show More