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,193 @@
// 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/hooks/ent/card"
"entgo.io/ent/entc/integration/hooks/ent/user"
)
// Card is the model entity for the Card schema.
type Card struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Number holds the value of the "number" field.
Number string `json:"number,omitempty"`
// Exact name written on card
Name string `json:"name,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// InHook is a mandatory field that is set by the hook.
InHook string `json:"in_hook,omitempty"`
// ExpiredAt holds the value of the "expired_at" field.
ExpiredAt time.Time `json:"expired_at,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the CardQuery when eager-loading is set.
Edges CardEdges `json:"edges"`
user_cards *int
selectValues sql.SelectValues
}
// CardEdges holds the relations/edges for other nodes in the graph.
type CardEdges 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 CardEdges) 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 (*Card) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case card.FieldID:
values[i] = new(sql.NullInt64)
case card.FieldNumber, card.FieldName, card.FieldInHook:
values[i] = new(sql.NullString)
case card.FieldCreatedAt, card.FieldExpiredAt:
values[i] = new(sql.NullTime)
case card.ForeignKeys[0]: // user_cards
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 Card fields.
func (_m *Card) 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 card.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 card.FieldNumber:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field number", values[i])
} else if value.Valid {
_m.Number = value.String
}
case card.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 card.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 card.FieldInHook:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field in_hook", values[i])
} else if value.Valid {
_m.InHook = value.String
}
case card.FieldExpiredAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field expired_at", values[i])
} else if value.Valid {
_m.ExpiredAt = value.Time
}
case card.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for edge-field user_cards", value)
} else if value.Valid {
_m.user_cards = new(int)
*_m.user_cards = 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 Card.
// This includes values selected through modifiers, order, etc.
func (_m *Card) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryOwner queries the "owner" edge of the Card entity.
func (_m *Card) QueryOwner() *UserQuery {
return NewCardClient(_m.config).QueryOwner(_m)
}
// Update returns a builder for updating this Card.
// Note that you need to call Card.Unwrap() before calling this method if this Card
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Card) Update() *CardUpdateOne {
return NewCardClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Card 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 *Card) Unwrap() *Card {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: Card is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Card) String() string {
var builder strings.Builder
builder.WriteString("Card(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("number=")
builder.WriteString(_m.Number)
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(_m.Name)
builder.WriteString(", ")
builder.WriteString("created_at=")
builder.WriteString(_m.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("in_hook=")
builder.WriteString(_m.InHook)
builder.WriteString(", ")
builder.WriteString("expired_at=")
builder.WriteString(_m.ExpiredAt.Format(time.ANSIC))
builder.WriteByte(')')
return builder.String()
}
// Cards is a parsable slice of Card.
type Cards []*Card

View File

@@ -0,0 +1,137 @@
// 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 card
import (
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the card type in the database.
Label = "card"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldNumber holds the string denoting the number field in the database.
FieldNumber = "number"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldInHook holds the string denoting the in_hook field in the database.
FieldInHook = "in_hook"
// FieldExpiredAt holds the string denoting the expired_at field in the database.
FieldExpiredAt = "expired_at"
// EdgeOwner holds the string denoting the owner edge name in mutations.
EdgeOwner = "owner"
// Table holds the table name of the card in the database.
Table = "cards"
// OwnerTable is the table that holds the owner relation/edge.
OwnerTable = "cards"
// 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 = "user_cards"
)
// Columns holds all SQL columns for card fields.
var Columns = []string{
FieldID,
FieldNumber,
FieldName,
FieldCreatedAt,
FieldInHook,
FieldExpiredAt,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "cards"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"user_cards",
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
for i := range ForeignKeys {
if column == ForeignKeys[i] {
return true
}
}
return false
}
// Note that the variables below are initialized by the runtime
// package on the initialization of the application. Therefore,
// it should be imported in the main as follows:
//
// import _ "entgo.io/ent/entc/integration/hooks/ent/runtime"
var (
Hooks [3]ent.Hook
Interceptors [1]ent.Interceptor
// DefaultNumber holds the default value on creation for the "number" field.
DefaultNumber string
// NumberValidator is a validator for the "number" field. It is called by the builders before save.
NumberValidator func(string) error
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
)
// OrderOption defines the ordering options for the Card 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()
}
// ByNumber orders the results by the number field.
func ByNumber(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldNumber, opts...).ToFunc()
}
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, opts...).ToFunc()
}
// ByCreatedAt orders the results by the created_at field.
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
}
// ByInHook orders the results by the in_hook field.
func ByInHook(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldInHook, opts...).ToFunc()
}
// ByExpiredAt orders the results by the expired_at field.
func ByExpiredAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldExpiredAt, 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,482 @@
// 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 card
import (
"context"
"fmt"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/entc/integration/hooks/ent/predicate"
)
// Mutation represents an operation that mutates the Card nodes in the graph.
type Mutation struct {
op ent.Op
typ string
number *string
name *string
created_at *time.Time
in_hook *string
expired_at *time.Time
clearedFields map[string]struct{}
owner *int
clearedowner bool
predicates []predicate.Card
}
// NewMutation creates a new Mutation for the Card entity.
func NewMutation(op ent.Op) *Mutation {
return &Mutation{
op: op,
typ: "Card",
clearedFields: make(map[string]struct{}),
}
}
// Predicates returns the list of predicates set on the mutation.
func (m *Mutation) Predicates() []predicate.Card {
return m.predicates
}
// SetNumber sets the "number" field.
func (m *Mutation) SetNumber(s string) {
m.number = &s
}
// Number returns the value of the "number" field in the mutation.
func (m *Mutation) Number() (r string, exists bool) {
v := m.number
if v == nil {
return
}
return *v, true
}
// ResetNumber resets all changes to the "number" field.
func (m *Mutation) ResetNumber() {
m.number = nil
}
// 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
}
// ClearName clears the value of the "name" field.
func (m *Mutation) ClearName() {
m.name = nil
m.clearedFields[FieldName] = struct{}{}
}
// NameCleared returns if the "name" field was cleared in this mutation.
func (m *Mutation) NameCleared() bool {
_, ok := m.clearedFields[FieldName]
return ok
}
// ResetName resets all changes to the "name" field.
func (m *Mutation) ResetName() {
m.name = nil
delete(m.clearedFields, FieldName)
}
// 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
}
// SetInHook sets the "in_hook" field.
func (m *Mutation) SetInHook(s string) {
m.in_hook = &s
}
// InHook returns the value of the "in_hook" field in the mutation.
func (m *Mutation) InHook() (r string, exists bool) {
v := m.in_hook
if v == nil {
return
}
return *v, true
}
// ResetInHook resets all changes to the "in_hook" field.
func (m *Mutation) ResetInHook() {
m.in_hook = nil
}
// SetExpiredAt sets the "expired_at" field.
func (m *Mutation) SetExpiredAt(t time.Time) {
m.expired_at = &t
}
// ExpiredAt returns the value of the "expired_at" field in the mutation.
func (m *Mutation) ExpiredAt() (r time.Time, exists bool) {
v := m.expired_at
if v == nil {
return
}
return *v, true
}
// ClearExpiredAt clears the value of the "expired_at" field.
func (m *Mutation) ClearExpiredAt() {
m.expired_at = nil
m.clearedFields[FieldExpiredAt] = struct{}{}
}
// ExpiredAtCleared returns if the "expired_at" field was cleared in this mutation.
func (m *Mutation) ExpiredAtCleared() bool {
_, ok := m.clearedFields[FieldExpiredAt]
return ok
}
// ResetExpiredAt resets all changes to the "expired_at" field.
func (m *Mutation) ResetExpiredAt() {
m.expired_at = nil
delete(m.clearedFields, FieldExpiredAt)
}
// SetOwnerID sets the "owner" edge to the User entity by id.
func (m *Mutation) SetOwnerID(id int) {
m.owner = &id
}
// ClearOwner clears the "owner" edge to the User entity.
func (m *Mutation) ClearOwner() {
m.clearedowner = true
}
// OwnerCleared reports if the "owner" edge to the User entity was cleared.
func (m *Mutation) OwnerCleared() bool {
return m.clearedowner
}
// OwnerID returns the "owner" edge ID in the mutation.
func (m *Mutation) OwnerID() (id int, exists bool) {
if m.owner != nil {
return *m.owner, true
}
return
}
// 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.Card) {
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.Card, 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 (Card).
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, 5)
if m.number != nil {
fields = append(fields, FieldNumber)
}
if m.name != nil {
fields = append(fields, FieldName)
}
if m.created_at != nil {
fields = append(fields, FieldCreatedAt)
}
if m.in_hook != nil {
fields = append(fields, FieldInHook)
}
if m.expired_at != nil {
fields = append(fields, FieldExpiredAt)
}
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 FieldNumber:
return m.Number()
case FieldName:
return m.Name()
case FieldCreatedAt:
return m.CreatedAt()
case FieldInHook:
return m.InHook()
case FieldExpiredAt:
return m.ExpiredAt()
}
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 Card 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 FieldNumber:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetNumber(v)
return nil
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 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 FieldInHook:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetInHook(v)
return nil
case FieldExpiredAt:
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetExpiredAt(v)
return nil
}
return fmt.Errorf("unknown Card 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 Card 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(FieldName) {
fields = append(fields, FieldName)
}
if m.FieldCleared(FieldExpiredAt) {
fields = append(fields, FieldExpiredAt)
}
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 FieldName:
m.ClearName()
return nil
case FieldExpiredAt:
m.ClearExpiredAt()
return nil
}
return fmt.Errorf("unknown Card 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 FieldNumber:
m.ResetNumber()
return nil
case FieldName:
m.ResetName()
return nil
case FieldCreatedAt:
m.ResetCreatedAt()
return nil
case FieldInHook:
m.ResetInHook()
return nil
case FieldExpiredAt:
m.ResetExpiredAt()
return nil
}
return fmt.Errorf("unknown Card 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 Card 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 Card edge %s", name)
}

View File

@@ -0,0 +1,418 @@
// 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 card
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/hooks/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Card {
return predicate.Card(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Card {
return predicate.Card(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Card {
return predicate.Card(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Card {
return predicate.Card(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Card {
return predicate.Card(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Card {
return predicate.Card(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Card {
return predicate.Card(sql.FieldLTE(FieldID, id))
}
// Number applies equality check predicate on the "number" field. It's identical to NumberEQ.
func Number(v string) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldNumber, v))
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldName, v))
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldCreatedAt, v))
}
// InHook applies equality check predicate on the "in_hook" field. It's identical to InHookEQ.
func InHook(v string) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldInHook, v))
}
// ExpiredAt applies equality check predicate on the "expired_at" field. It's identical to ExpiredAtEQ.
func ExpiredAt(v time.Time) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldExpiredAt, v))
}
// NumberEQ applies the EQ predicate on the "number" field.
func NumberEQ(v string) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldNumber, v))
}
// NumberNEQ applies the NEQ predicate on the "number" field.
func NumberNEQ(v string) predicate.Card {
return predicate.Card(sql.FieldNEQ(FieldNumber, v))
}
// NumberIn applies the In predicate on the "number" field.
func NumberIn(vs ...string) predicate.Card {
return predicate.Card(sql.FieldIn(FieldNumber, vs...))
}
// NumberNotIn applies the NotIn predicate on the "number" field.
func NumberNotIn(vs ...string) predicate.Card {
return predicate.Card(sql.FieldNotIn(FieldNumber, vs...))
}
// NumberGT applies the GT predicate on the "number" field.
func NumberGT(v string) predicate.Card {
return predicate.Card(sql.FieldGT(FieldNumber, v))
}
// NumberGTE applies the GTE predicate on the "number" field.
func NumberGTE(v string) predicate.Card {
return predicate.Card(sql.FieldGTE(FieldNumber, v))
}
// NumberLT applies the LT predicate on the "number" field.
func NumberLT(v string) predicate.Card {
return predicate.Card(sql.FieldLT(FieldNumber, v))
}
// NumberLTE applies the LTE predicate on the "number" field.
func NumberLTE(v string) predicate.Card {
return predicate.Card(sql.FieldLTE(FieldNumber, v))
}
// NumberContains applies the Contains predicate on the "number" field.
func NumberContains(v string) predicate.Card {
return predicate.Card(sql.FieldContains(FieldNumber, v))
}
// NumberHasPrefix applies the HasPrefix predicate on the "number" field.
func NumberHasPrefix(v string) predicate.Card {
return predicate.Card(sql.FieldHasPrefix(FieldNumber, v))
}
// NumberHasSuffix applies the HasSuffix predicate on the "number" field.
func NumberHasSuffix(v string) predicate.Card {
return predicate.Card(sql.FieldHasSuffix(FieldNumber, v))
}
// NumberEqualFold applies the EqualFold predicate on the "number" field.
func NumberEqualFold(v string) predicate.Card {
return predicate.Card(sql.FieldEqualFold(FieldNumber, v))
}
// NumberContainsFold applies the ContainsFold predicate on the "number" field.
func NumberContainsFold(v string) predicate.Card {
return predicate.Card(sql.FieldContainsFold(FieldNumber, v))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldName, v))
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.Card {
return predicate.Card(sql.FieldNEQ(FieldName, v))
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.Card {
return predicate.Card(sql.FieldIn(FieldName, vs...))
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.Card {
return predicate.Card(sql.FieldNotIn(FieldName, vs...))
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.Card {
return predicate.Card(sql.FieldGT(FieldName, v))
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.Card {
return predicate.Card(sql.FieldGTE(FieldName, v))
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.Card {
return predicate.Card(sql.FieldLT(FieldName, v))
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.Card {
return predicate.Card(sql.FieldLTE(FieldName, v))
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.Card {
return predicate.Card(sql.FieldContains(FieldName, v))
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.Card {
return predicate.Card(sql.FieldHasPrefix(FieldName, v))
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.Card {
return predicate.Card(sql.FieldHasSuffix(FieldName, v))
}
// NameIsNil applies the IsNil predicate on the "name" field.
func NameIsNil() predicate.Card {
return predicate.Card(sql.FieldIsNull(FieldName))
}
// NameNotNil applies the NotNil predicate on the "name" field.
func NameNotNil() predicate.Card {
return predicate.Card(sql.FieldNotNull(FieldName))
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.Card {
return predicate.Card(sql.FieldEqualFold(FieldName, v))
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.Card {
return predicate.Card(sql.FieldContainsFold(FieldName, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.Card {
return predicate.Card(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.Card {
return predicate.Card(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.Card {
return predicate.Card(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.Card {
return predicate.Card(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.Card {
return predicate.Card(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.Card {
return predicate.Card(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.Card {
return predicate.Card(sql.FieldLTE(FieldCreatedAt, v))
}
// InHookEQ applies the EQ predicate on the "in_hook" field.
func InHookEQ(v string) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldInHook, v))
}
// InHookNEQ applies the NEQ predicate on the "in_hook" field.
func InHookNEQ(v string) predicate.Card {
return predicate.Card(sql.FieldNEQ(FieldInHook, v))
}
// InHookIn applies the In predicate on the "in_hook" field.
func InHookIn(vs ...string) predicate.Card {
return predicate.Card(sql.FieldIn(FieldInHook, vs...))
}
// InHookNotIn applies the NotIn predicate on the "in_hook" field.
func InHookNotIn(vs ...string) predicate.Card {
return predicate.Card(sql.FieldNotIn(FieldInHook, vs...))
}
// InHookGT applies the GT predicate on the "in_hook" field.
func InHookGT(v string) predicate.Card {
return predicate.Card(sql.FieldGT(FieldInHook, v))
}
// InHookGTE applies the GTE predicate on the "in_hook" field.
func InHookGTE(v string) predicate.Card {
return predicate.Card(sql.FieldGTE(FieldInHook, v))
}
// InHookLT applies the LT predicate on the "in_hook" field.
func InHookLT(v string) predicate.Card {
return predicate.Card(sql.FieldLT(FieldInHook, v))
}
// InHookLTE applies the LTE predicate on the "in_hook" field.
func InHookLTE(v string) predicate.Card {
return predicate.Card(sql.FieldLTE(FieldInHook, v))
}
// InHookContains applies the Contains predicate on the "in_hook" field.
func InHookContains(v string) predicate.Card {
return predicate.Card(sql.FieldContains(FieldInHook, v))
}
// InHookHasPrefix applies the HasPrefix predicate on the "in_hook" field.
func InHookHasPrefix(v string) predicate.Card {
return predicate.Card(sql.FieldHasPrefix(FieldInHook, v))
}
// InHookHasSuffix applies the HasSuffix predicate on the "in_hook" field.
func InHookHasSuffix(v string) predicate.Card {
return predicate.Card(sql.FieldHasSuffix(FieldInHook, v))
}
// InHookEqualFold applies the EqualFold predicate on the "in_hook" field.
func InHookEqualFold(v string) predicate.Card {
return predicate.Card(sql.FieldEqualFold(FieldInHook, v))
}
// InHookContainsFold applies the ContainsFold predicate on the "in_hook" field.
func InHookContainsFold(v string) predicate.Card {
return predicate.Card(sql.FieldContainsFold(FieldInHook, v))
}
// ExpiredAtEQ applies the EQ predicate on the "expired_at" field.
func ExpiredAtEQ(v time.Time) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldExpiredAt, v))
}
// ExpiredAtNEQ applies the NEQ predicate on the "expired_at" field.
func ExpiredAtNEQ(v time.Time) predicate.Card {
return predicate.Card(sql.FieldNEQ(FieldExpiredAt, v))
}
// ExpiredAtIn applies the In predicate on the "expired_at" field.
func ExpiredAtIn(vs ...time.Time) predicate.Card {
return predicate.Card(sql.FieldIn(FieldExpiredAt, vs...))
}
// ExpiredAtNotIn applies the NotIn predicate on the "expired_at" field.
func ExpiredAtNotIn(vs ...time.Time) predicate.Card {
return predicate.Card(sql.FieldNotIn(FieldExpiredAt, vs...))
}
// ExpiredAtGT applies the GT predicate on the "expired_at" field.
func ExpiredAtGT(v time.Time) predicate.Card {
return predicate.Card(sql.FieldGT(FieldExpiredAt, v))
}
// ExpiredAtGTE applies the GTE predicate on the "expired_at" field.
func ExpiredAtGTE(v time.Time) predicate.Card {
return predicate.Card(sql.FieldGTE(FieldExpiredAt, v))
}
// ExpiredAtLT applies the LT predicate on the "expired_at" field.
func ExpiredAtLT(v time.Time) predicate.Card {
return predicate.Card(sql.FieldLT(FieldExpiredAt, v))
}
// ExpiredAtLTE applies the LTE predicate on the "expired_at" field.
func ExpiredAtLTE(v time.Time) predicate.Card {
return predicate.Card(sql.FieldLTE(FieldExpiredAt, v))
}
// ExpiredAtIsNil applies the IsNil predicate on the "expired_at" field.
func ExpiredAtIsNil() predicate.Card {
return predicate.Card(sql.FieldIsNull(FieldExpiredAt))
}
// ExpiredAtNotNil applies the NotNil predicate on the "expired_at" field.
func ExpiredAtNotNil() predicate.Card {
return predicate.Card(sql.FieldNotNull(FieldExpiredAt))
}
// HasOwner applies the HasEdge predicate on the "owner" edge.
func HasOwner() predicate.Card {
return predicate.Card(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, OwnerTable, OwnerColumn),
)
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.Card {
return predicate.Card(func(s *sql.Selector) {
step := newOwnerStep()
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.Card) predicate.Card {
return predicate.Card(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Card) predicate.Card {
return predicate.Card(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Card) predicate.Card {
return predicate.Card(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,328 @@
// 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/hooks/ent/card"
"entgo.io/ent/entc/integration/hooks/ent/user"
"entgo.io/ent/schema/field"
)
// CardCreate is the builder for creating a Card entity.
type CardCreate struct {
config
mutation *CardMutation
hooks []Hook
}
// SetNumber sets the "number" field.
func (_c *CardCreate) SetNumber(v string) *CardCreate {
_c.mutation.SetNumber(v)
return _c
}
// SetNillableNumber sets the "number" field if the given value is not nil.
func (_c *CardCreate) SetNillableNumber(v *string) *CardCreate {
if v != nil {
_c.SetNumber(*v)
}
return _c
}
// SetName sets the "name" field.
func (_c *CardCreate) SetName(v string) *CardCreate {
_c.mutation.SetName(v)
return _c
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_c *CardCreate) SetNillableName(v *string) *CardCreate {
if v != nil {
_c.SetName(*v)
}
return _c
}
// SetCreatedAt sets the "created_at" field.
func (_c *CardCreate) SetCreatedAt(v time.Time) *CardCreate {
_c.mutation.SetCreatedAt(v)
return _c
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (_c *CardCreate) SetNillableCreatedAt(v *time.Time) *CardCreate {
if v != nil {
_c.SetCreatedAt(*v)
}
return _c
}
// SetInHook sets the "in_hook" field.
func (_c *CardCreate) SetInHook(v string) *CardCreate {
_c.mutation.SetInHook(v)
return _c
}
// SetExpiredAt sets the "expired_at" field.
func (_c *CardCreate) SetExpiredAt(v time.Time) *CardCreate {
_c.mutation.SetExpiredAt(v)
return _c
}
// SetNillableExpiredAt sets the "expired_at" field if the given value is not nil.
func (_c *CardCreate) SetNillableExpiredAt(v *time.Time) *CardCreate {
if v != nil {
_c.SetExpiredAt(*v)
}
return _c
}
// SetOwnerID sets the "owner" edge to the User entity by ID.
func (_c *CardCreate) SetOwnerID(id int) *CardCreate {
_c.mutation.SetOwnerID(id)
return _c
}
// SetNillableOwnerID sets the "owner" edge to the User entity by ID if the given value is not nil.
func (_c *CardCreate) SetNillableOwnerID(id *int) *CardCreate {
if id != nil {
_c = _c.SetOwnerID(*id)
}
return _c
}
// SetOwner sets the "owner" edge to the User entity.
func (_c *CardCreate) SetOwner(v *User) *CardCreate {
return _c.SetOwnerID(v.ID)
}
// Mutation returns the CardMutation object of the builder.
func (_c *CardCreate) Mutation() *CardMutation {
return _c.mutation
}
// Save creates the Card in the database.
func (_c *CardCreate) Save(ctx context.Context) (*Card, error) {
if err := _c.defaults(); err != nil {
return nil, err
}
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *CardCreate) SaveX(ctx context.Context) *Card {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *CardCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *CardCreate) 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 *CardCreate) defaults() error {
if _, ok := _c.mutation.Number(); !ok {
v := card.DefaultNumber
_c.mutation.SetNumber(v)
}
if _, ok := _c.mutation.CreatedAt(); !ok {
if card.DefaultCreatedAt == nil {
return fmt.Errorf("ent: uninitialized card.DefaultCreatedAt (forgotten import ent/runtime?)")
}
v := card.DefaultCreatedAt()
_c.mutation.SetCreatedAt(v)
}
return nil
}
// check runs all checks and user-defined validators on the builder.
func (_c *CardCreate) check() error {
if _, ok := _c.mutation.Number(); !ok {
return &ValidationError{Name: "number", err: errors.New(`ent: missing required field "Card.number"`)}
}
if v, ok := _c.mutation.Number(); ok {
if err := card.NumberValidator(v); err != nil {
return &ValidationError{Name: "number", err: fmt.Errorf(`ent: validator failed for field "Card.number": %w`, err)}
}
}
if _, ok := _c.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Card.created_at"`)}
}
if _, ok := _c.mutation.InHook(); !ok {
return &ValidationError{Name: "in_hook", err: errors.New(`ent: missing required field "Card.in_hook"`)}
}
return nil
}
func (_c *CardCreate) sqlSave(ctx context.Context) (*Card, 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 *CardCreate) createSpec() (*Card, *sqlgraph.CreateSpec) {
var (
_node = &Card{config: _c.config}
_spec = sqlgraph.NewCreateSpec(card.Table, sqlgraph.NewFieldSpec(card.FieldID, field.TypeInt))
)
if value, ok := _c.mutation.Number(); ok {
_spec.SetField(card.FieldNumber, field.TypeString, value)
_node.Number = value
}
if value, ok := _c.mutation.Name(); ok {
_spec.SetField(card.FieldName, field.TypeString, value)
_node.Name = value
}
if value, ok := _c.mutation.CreatedAt(); ok {
_spec.SetField(card.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = value
}
if value, ok := _c.mutation.InHook(); ok {
_spec.SetField(card.FieldInHook, field.TypeString, value)
_node.InHook = value
}
if value, ok := _c.mutation.ExpiredAt(); ok {
_spec.SetField(card.FieldExpiredAt, field.TypeTime, value)
_node.ExpiredAt = value
}
if nodes := _c.mutation.OwnerIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: card.OwnerTable,
Columns: []string{card.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.user_cards = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// CardCreateBulk is the builder for creating many Card entities in bulk.
type CardCreateBulk struct {
config
err error
builders []*CardCreate
}
// Save creates the Card entities in the database.
func (_c *CardCreateBulk) Save(ctx context.Context) ([]*Card, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*Card, 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.(*CardMutation)
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 *CardCreateBulk) SaveX(ctx context.Context) []*Card {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *CardCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *CardCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,92 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/hooks/ent/card"
"entgo.io/ent/entc/integration/hooks/ent/predicate"
"entgo.io/ent/schema/field"
)
// CardDelete is the builder for deleting a Card entity.
type CardDelete struct {
config
hooks []Hook
mutation *CardMutation
}
// Where appends a list predicates to the CardDelete builder.
func (_d *CardDelete) Where(ps ...predicate.Card) *CardDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *CardDelete) 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 *CardDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *CardDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(card.Table, sqlgraph.NewFieldSpec(card.FieldID, field.TypeInt))
if ps := _d.mutation.Predicates(); len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
_d.mutation.done = true
return affected, err
}
// CardDeleteOne is the builder for deleting a single Card entity.
type CardDeleteOne struct {
_d *CardDelete
}
// Where appends a list predicates to the CardDelete builder.
func (_d *CardDeleteOne) Where(ps ...predicate.Card) *CardDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *CardDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{card.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *CardDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

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 ent
import (
"context"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/hooks/ent/card"
"entgo.io/ent/entc/integration/hooks/ent/predicate"
"entgo.io/ent/entc/integration/hooks/ent/user"
"entgo.io/ent/schema/field"
)
// CardQuery is the builder for querying Card entities.
type CardQuery struct {
config
ctx *QueryContext
order []card.OrderOption
inters []Interceptor
predicates []predicate.Card
withOwner *UserQuery
withFKs bool
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the CardQuery builder.
func (_q *CardQuery) Where(ps ...predicate.Card) *CardQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *CardQuery) Limit(limit int) *CardQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *CardQuery) Offset(offset int) *CardQuery {
_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 *CardQuery) Unique(unique bool) *CardQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *CardQuery) Order(o ...card.OrderOption) *CardQuery {
_q.order = append(_q.order, o...)
return _q
}
// QueryOwner chains the current query on the "owner" edge.
func (_q *CardQuery) 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(card.Table, card.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, card.OwnerTable, card.OwnerColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Card entity from the query.
// Returns a *NotFoundError when no Card was found.
func (_q *CardQuery) First(ctx context.Context) (*Card, 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{card.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *CardQuery) FirstX(ctx context.Context) *Card {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Card ID from the query.
// Returns a *NotFoundError when no Card ID was found.
func (_q *CardQuery) 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{card.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *CardQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Card entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Card entity is found.
// Returns a *NotFoundError when no Card entities are found.
func (_q *CardQuery) Only(ctx context.Context) (*Card, 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{card.Label}
default:
return nil, &NotSingularError{card.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *CardQuery) OnlyX(ctx context.Context) *Card {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Card ID in the query.
// Returns a *NotSingularError when more than one Card ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *CardQuery) 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{card.Label}
default:
err = &NotSingularError{card.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *CardQuery) 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 Cards.
func (_q *CardQuery) All(ctx context.Context) ([]*Card, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Card, *CardQuery]()
return withInterceptors[[]*Card](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *CardQuery) AllX(ctx context.Context) []*Card {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Card IDs.
func (_q *CardQuery) 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(card.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *CardQuery) 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 *CardQuery) 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[*CardQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *CardQuery) 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 *CardQuery) 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 *CardQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the CardQuery 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 *CardQuery) Clone() *CardQuery {
if _q == nil {
return nil
}
return &CardQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]card.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Card{}, _q.predicates...),
withOwner: _q.withOwner.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// 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 *CardQuery) WithOwner(opts ...func(*UserQuery)) *CardQuery {
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 {
// Number string `json:"number,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Card.Query().
// GroupBy(card.FieldNumber).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *CardQuery) GroupBy(field string, fields ...string) *CardGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &CardGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = card.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 {
// Number string `json:"number,omitempty"`
// }
//
// client.Card.Query().
// Select(card.FieldNumber).
// Scan(ctx, &v)
func (_q *CardQuery) Select(fields ...string) *CardSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &CardSelect{CardQuery: _q}
sbuild.label = card.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a CardSelect configured with the given aggregations.
func (_q *CardQuery) Aggregate(fns ...AggregateFunc) *CardSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *CardQuery) 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 !card.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 *CardQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Card, error) {
var (
nodes = []*Card{}
withFKs = _q.withFKs
_spec = _q.querySpec()
loadedTypes = [1]bool{
_q.withOwner != nil,
}
)
if _q.withOwner != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, card.ForeignKeys...)
}
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Card).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Card{config: _q.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := _q.withOwner; query != nil {
if err := _q.loadOwner(ctx, query, nodes, nil,
func(n *Card, e *User) { n.Edges.Owner = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *CardQuery) loadOwner(ctx context.Context, query *UserQuery, nodes []*Card, init func(*Card), assign func(*Card, *User)) error {
ids := make([]int, 0, len(nodes))
nodeids := make(map[int][]*Card)
for i := range nodes {
if nodes[i].user_cards == nil {
continue
}
fk := *nodes[i].user_cards
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_cards" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *CardQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *CardQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(card.Table, card.Columns, sqlgraph.NewFieldSpec(card.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, card.FieldID)
for i := range fields {
if fields[i] != card.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 *CardQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(card.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = card.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// CardGroupBy is the group-by builder for Card entities.
type CardGroupBy struct {
selector
build *CardQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *CardGroupBy) Aggregate(fns ...AggregateFunc) *CardGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *CardGroupBy) 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[*CardQuery, *CardGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *CardGroupBy) sqlScan(ctx context.Context, root *CardQuery, 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)
}
// CardSelect is the builder for selecting fields of Card entities.
type CardSelect struct {
*CardQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *CardSelect) Aggregate(fns ...AggregateFunc) *CardSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *CardSelect) 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[*CardQuery, *CardSelect](ctx, _s.CardQuery, _s, _s.inters, v)
}
func (_s *CardSelect) sqlScan(ctx context.Context, root *CardQuery, 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)
}

View File

@@ -0,0 +1,461 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/hooks/ent/card"
"entgo.io/ent/entc/integration/hooks/ent/predicate"
"entgo.io/ent/entc/integration/hooks/ent/user"
"entgo.io/ent/schema/field"
)
// CardUpdate is the builder for updating Card entities.
type CardUpdate struct {
config
hooks []Hook
mutation *CardMutation
}
// Where appends a list predicates to the CardUpdate builder.
func (_u *CardUpdate) Where(ps ...predicate.Card) *CardUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetName sets the "name" field.
func (_u *CardUpdate) SetName(v string) *CardUpdate {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *CardUpdate) SetNillableName(v *string) *CardUpdate {
if v != nil {
_u.SetName(*v)
}
return _u
}
// ClearName clears the value of the "name" field.
func (_u *CardUpdate) ClearName() *CardUpdate {
_u.mutation.ClearName()
return _u
}
// SetCreatedAt sets the "created_at" field.
func (_u *CardUpdate) SetCreatedAt(v time.Time) *CardUpdate {
_u.mutation.SetCreatedAt(v)
return _u
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (_u *CardUpdate) SetNillableCreatedAt(v *time.Time) *CardUpdate {
if v != nil {
_u.SetCreatedAt(*v)
}
return _u
}
// SetInHook sets the "in_hook" field.
func (_u *CardUpdate) SetInHook(v string) *CardUpdate {
_u.mutation.SetInHook(v)
return _u
}
// SetNillableInHook sets the "in_hook" field if the given value is not nil.
func (_u *CardUpdate) SetNillableInHook(v *string) *CardUpdate {
if v != nil {
_u.SetInHook(*v)
}
return _u
}
// SetExpiredAt sets the "expired_at" field.
func (_u *CardUpdate) SetExpiredAt(v time.Time) *CardUpdate {
_u.mutation.SetExpiredAt(v)
return _u
}
// SetNillableExpiredAt sets the "expired_at" field if the given value is not nil.
func (_u *CardUpdate) SetNillableExpiredAt(v *time.Time) *CardUpdate {
if v != nil {
_u.SetExpiredAt(*v)
}
return _u
}
// ClearExpiredAt clears the value of the "expired_at" field.
func (_u *CardUpdate) ClearExpiredAt() *CardUpdate {
_u.mutation.ClearExpiredAt()
return _u
}
// SetOwnerID sets the "owner" edge to the User entity by ID.
func (_u *CardUpdate) SetOwnerID(id int) *CardUpdate {
_u.mutation.SetOwnerID(id)
return _u
}
// SetNillableOwnerID sets the "owner" edge to the User entity by ID if the given value is not nil.
func (_u *CardUpdate) SetNillableOwnerID(id *int) *CardUpdate {
if id != nil {
_u = _u.SetOwnerID(*id)
}
return _u
}
// SetOwner sets the "owner" edge to the User entity.
func (_u *CardUpdate) SetOwner(v *User) *CardUpdate {
return _u.SetOwnerID(v.ID)
}
// Mutation returns the CardMutation object of the builder.
func (_u *CardUpdate) Mutation() *CardMutation {
return _u.mutation
}
// ClearOwner clears the "owner" edge to the User entity.
func (_u *CardUpdate) ClearOwner() *CardUpdate {
_u.mutation.ClearOwner()
return _u
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *CardUpdate) 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 *CardUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *CardUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *CardUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
func (_u *CardUpdate) sqlSave(ctx context.Context) (_node int, err error) {
_spec := sqlgraph.NewUpdateSpec(card.Table, card.Columns, sqlgraph.NewFieldSpec(card.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(card.FieldName, field.TypeString, value)
}
if _u.mutation.NameCleared() {
_spec.ClearField(card.FieldName, field.TypeString)
}
if value, ok := _u.mutation.CreatedAt(); ok {
_spec.SetField(card.FieldCreatedAt, field.TypeTime, value)
}
if value, ok := _u.mutation.InHook(); ok {
_spec.SetField(card.FieldInHook, field.TypeString, value)
}
if value, ok := _u.mutation.ExpiredAt(); ok {
_spec.SetField(card.FieldExpiredAt, field.TypeTime, value)
}
if _u.mutation.ExpiredAtCleared() {
_spec.ClearField(card.FieldExpiredAt, field.TypeTime)
}
if _u.mutation.OwnerCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: card.OwnerTable,
Columns: []string{card.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
_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: card.OwnerTable,
Columns: []string{card.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{card.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// CardUpdateOne is the builder for updating a single Card entity.
type CardUpdateOne struct {
config
fields []string
hooks []Hook
mutation *CardMutation
}
// SetName sets the "name" field.
func (_u *CardUpdateOne) SetName(v string) *CardUpdateOne {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *CardUpdateOne) SetNillableName(v *string) *CardUpdateOne {
if v != nil {
_u.SetName(*v)
}
return _u
}
// ClearName clears the value of the "name" field.
func (_u *CardUpdateOne) ClearName() *CardUpdateOne {
_u.mutation.ClearName()
return _u
}
// SetCreatedAt sets the "created_at" field.
func (_u *CardUpdateOne) SetCreatedAt(v time.Time) *CardUpdateOne {
_u.mutation.SetCreatedAt(v)
return _u
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (_u *CardUpdateOne) SetNillableCreatedAt(v *time.Time) *CardUpdateOne {
if v != nil {
_u.SetCreatedAt(*v)
}
return _u
}
// SetInHook sets the "in_hook" field.
func (_u *CardUpdateOne) SetInHook(v string) *CardUpdateOne {
_u.mutation.SetInHook(v)
return _u
}
// SetNillableInHook sets the "in_hook" field if the given value is not nil.
func (_u *CardUpdateOne) SetNillableInHook(v *string) *CardUpdateOne {
if v != nil {
_u.SetInHook(*v)
}
return _u
}
// SetExpiredAt sets the "expired_at" field.
func (_u *CardUpdateOne) SetExpiredAt(v time.Time) *CardUpdateOne {
_u.mutation.SetExpiredAt(v)
return _u
}
// SetNillableExpiredAt sets the "expired_at" field if the given value is not nil.
func (_u *CardUpdateOne) SetNillableExpiredAt(v *time.Time) *CardUpdateOne {
if v != nil {
_u.SetExpiredAt(*v)
}
return _u
}
// ClearExpiredAt clears the value of the "expired_at" field.
func (_u *CardUpdateOne) ClearExpiredAt() *CardUpdateOne {
_u.mutation.ClearExpiredAt()
return _u
}
// SetOwnerID sets the "owner" edge to the User entity by ID.
func (_u *CardUpdateOne) SetOwnerID(id int) *CardUpdateOne {
_u.mutation.SetOwnerID(id)
return _u
}
// SetNillableOwnerID sets the "owner" edge to the User entity by ID if the given value is not nil.
func (_u *CardUpdateOne) SetNillableOwnerID(id *int) *CardUpdateOne {
if id != nil {
_u = _u.SetOwnerID(*id)
}
return _u
}
// SetOwner sets the "owner" edge to the User entity.
func (_u *CardUpdateOne) SetOwner(v *User) *CardUpdateOne {
return _u.SetOwnerID(v.ID)
}
// Mutation returns the CardMutation object of the builder.
func (_u *CardUpdateOne) Mutation() *CardMutation {
return _u.mutation
}
// ClearOwner clears the "owner" edge to the User entity.
func (_u *CardUpdateOne) ClearOwner() *CardUpdateOne {
_u.mutation.ClearOwner()
return _u
}
// Where appends a list predicates to the CardUpdate builder.
func (_u *CardUpdateOne) Where(ps ...predicate.Card) *CardUpdateOne {
_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 *CardUpdateOne) Select(field string, fields ...string) *CardUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated Card entity.
func (_u *CardUpdateOne) Save(ctx context.Context) (*Card, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *CardUpdateOne) SaveX(ctx context.Context) *Card {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *CardUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *CardUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
func (_u *CardUpdateOne) sqlSave(ctx context.Context) (_node *Card, err error) {
_spec := sqlgraph.NewUpdateSpec(card.Table, card.Columns, sqlgraph.NewFieldSpec(card.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Card.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, card.FieldID)
for _, f := range fields {
if !card.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != card.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(card.FieldName, field.TypeString, value)
}
if _u.mutation.NameCleared() {
_spec.ClearField(card.FieldName, field.TypeString)
}
if value, ok := _u.mutation.CreatedAt(); ok {
_spec.SetField(card.FieldCreatedAt, field.TypeTime, value)
}
if value, ok := _u.mutation.InHook(); ok {
_spec.SetField(card.FieldInHook, field.TypeString, value)
}
if value, ok := _u.mutation.ExpiredAt(); ok {
_spec.SetField(card.FieldExpiredAt, field.TypeTime, value)
}
if _u.mutation.ExpiredAtCleared() {
_spec.ClearField(card.FieldExpiredAt, field.TypeTime)
}
if _u.mutation.OwnerCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: card.OwnerTable,
Columns: []string{card.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
_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: card.OwnerTable,
Columns: []string{card.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &Card{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{card.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,732 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"log"
"reflect"
"entgo.io/ent"
"entgo.io/ent/entc/integration/hooks/ent/migrate"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/hooks/ent/card"
"entgo.io/ent/entc/integration/hooks/ent/pet"
"entgo.io/ent/entc/integration/hooks/ent/user"
)
// 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
// Card is the client for interacting with the Card builders.
Card *CardClient
// 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.Card = NewCardClient(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
}
// Option function to configure the client.
Option func(*config)
)
// newConfig creates a new config for the client.
func newConfig(opts ...Option) config {
cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}}
cfg.options(opts...)
return cfg
}
// options applies the options on the config object.
func (c *config) options(opts ...Option) {
for _, opt := range opts {
opt(c)
}
if c.debug {
c.driver = dialect.Debug(c.driver, c.log)
}
}
// Debug enables debug logging on the ent.Driver.
func Debug() Option {
return func(c *config) {
c.debug = true
}
}
// Log sets the logging function for debug mode.
func Log(fn func(...any)) Option {
return func(c *config) {
c.log = fn
}
}
// Driver configures the client driver.
func Driver(driver dialect.Driver) Option {
return func(c *config) {
c.driver = driver
}
}
// Open opens a database/sql.DB specified by the driver name and
// the data source name, and returns a new client attached to it.
// Optional parameters can be added for configuring the client.
func Open(driverName, dataSourceName string, options ...Option) (*Client, error) {
switch driverName {
case dialect.MySQL, dialect.Postgres, dialect.SQLite:
drv, err := sql.Open(driverName, dataSourceName)
if err != nil {
return nil, err
}
return NewClient(append(options, Driver(drv))...), nil
default:
return nil, fmt.Errorf("unsupported driver: %q", driverName)
}
}
// ErrTxStarted is returned when trying to start a new transaction from a transactional client.
var ErrTxStarted = errors.New("ent: cannot start a transaction within a transaction")
// Tx returns a new transactional client. The provided context
// is used until the transaction is committed or rolled back.
func (c *Client) Tx(ctx context.Context) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, ErrTxStarted
}
tx, err := newTx(ctx, c.driver)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
}
cfg := c.config
cfg.driver = tx
return &Tx{
ctx: ctx,
config: cfg,
Card: NewCardClient(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,
Card: NewCardClient(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().
// Card.
// 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.Card.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.Card.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 *CardMutation:
return c.Card.mutate(ctx, m)
case *PetMutation:
return c.Pet.mutate(ctx, m)
case *UserMutation:
return c.User.mutate(ctx, m)
default:
return nil, fmt.Errorf("ent: unknown mutation type %T", m)
}
}
// CardClient is a client for the Card schema.
type CardClient struct {
config
}
// NewCardClient returns a client for the Card from the given config.
func NewCardClient(c config) *CardClient {
return &CardClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `card.Hooks(f(g(h())))`.
func (c *CardClient) Use(hooks ...Hook) {
c.hooks.Card = append(c.hooks.Card, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `card.Intercept(f(g(h())))`.
func (c *CardClient) Intercept(interceptors ...Interceptor) {
c.inters.Card = append(c.inters.Card, interceptors...)
}
// Create returns a builder for creating a Card entity.
func (c *CardClient) Create() *CardCreate {
mutation := newCardMutation(c.config, OpCreate)
return &CardCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Card entities.
func (c *CardClient) CreateBulk(builders ...*CardCreate) *CardCreateBulk {
return &CardCreateBulk{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 *CardClient) MapCreateBulk(slice any, setFunc func(*CardCreate, int)) *CardCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &CardCreateBulk{err: fmt.Errorf("calling to CardClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*CardCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &CardCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Card.
func (c *CardClient) Update() *CardUpdate {
mutation := newCardMutation(c.config, OpUpdate)
return &CardUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *CardClient) UpdateOne(_m *Card) *CardUpdateOne {
mutation := newCardMutation(c.config, OpUpdateOne, withCard(_m))
return &CardUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *CardClient) UpdateOneID(id int) *CardUpdateOne {
mutation := newCardMutation(c.config, OpUpdateOne, withCardID(id))
return &CardUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Card.
func (c *CardClient) Delete() *CardDelete {
mutation := newCardMutation(c.config, OpDelete)
return &CardDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *CardClient) DeleteOne(_m *Card) *CardDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *CardClient) DeleteOneID(id int) *CardDeleteOne {
builder := c.Delete().Where(card.ID(id))
builder.mutation.id = &id
builder.mutation.SetOp(OpDeleteOne)
return &CardDeleteOne{builder}
}
// Query returns a query builder for Card.
func (c *CardClient) Query() *CardQuery {
return &CardQuery{
config: c.config,
ctx: &QueryContext{Type: TypeCard},
inters: c.Interceptors(),
}
}
// Get returns a Card entity by its id.
func (c *CardClient) Get(ctx context.Context, id int) (*Card, error) {
return c.Query().Where(card.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *CardClient) GetX(ctx context.Context, id int) *Card {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryOwner queries the owner edge of a Card.
func (c *CardClient) QueryOwner(_m *Card) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(card.Table, card.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, card.OwnerTable, card.OwnerColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *CardClient) Hooks() []Hook {
hooks := c.hooks.Card
return append(hooks[:len(hooks):len(hooks)], card.Hooks[:]...)
}
// Interceptors returns the client interceptors.
func (c *CardClient) Interceptors() []Interceptor {
inters := c.inters.Card
return append(inters[:len(inters):len(inters)], card.Interceptors[:]...)
}
func (c *CardClient) mutate(ctx context.Context, m *CardMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&CardCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&CardUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&CardUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&CardDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Card 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),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *PetClient) Hooks() []Hook {
hooks := c.hooks.Pet
return append(hooks[:len(hooks):len(hooks)], pet.Hooks[:]...)
}
// Interceptors returns the client interceptors.
func (c *PetClient) Interceptors() []Interceptor {
inters := c.inters.Pet
return append(inters[:len(inters):len(inters)], pet.Interceptors[:]...)
}
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("ent: 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
}
// QueryCards queries the cards edge of a User.
func (c *UserClient) QueryCards(_m *User) *CardQuery {
query := (&CardClient{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(card.Table, card.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, user.CardsTable, user.CardsColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// 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),
)
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...),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryBestFriend queries the best_friend edge of a User.
func (c *UserClient) QueryBestFriend(_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.O2O, false, user.BestFriendTable, user.BestFriendColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *UserClient) Hooks() []Hook {
hooks := c.hooks.User
return append(hooks[:len(hooks):len(hooks)], user.Hooks[:]...)
}
// 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("ent: unknown User mutation op: %q", m.Op())
}
}
// hooks and interceptors per client, for fast access.
type (
hooks struct {
Card, Pet, User []ent.Hook
}
inters struct {
Card, Pet, User []ent.Interceptor
}
)

View File

@@ -0,0 +1,616 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"reflect"
"sync"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/hooks/ent/card"
"entgo.io/ent/entc/integration/hooks/ent/pet"
"entgo.io/ent/entc/integration/hooks/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{
card.Table: card.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/hooks/ent"
// required by schema hooks.
_ "entgo.io/ent/entc/integration/hooks/ent/runtime"
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/entc/integration/hooks/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,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 intercept,schema/snapshot --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,227 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package hook
import (
"context"
"fmt"
"entgo.io/ent/entc/integration/hooks/ent"
)
// The CardFunc type is an adapter to allow the use of ordinary
// function as Card mutator.
type CardFunc func(context.Context, *ent.CardMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f CardFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.CardMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.CardMutation", 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,213 @@
// 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 intercept
import (
"context"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/entc/integration/hooks/ent"
"entgo.io/ent/entc/integration/hooks/ent/card"
"entgo.io/ent/entc/integration/hooks/ent/pet"
"entgo.io/ent/entc/integration/hooks/ent/predicate"
"entgo.io/ent/entc/integration/hooks/ent/user"
)
// The Query interface represents an operation that queries a graph.
// By using this interface, users can write generic code that manipulates
// query builders of different types.
type Query interface {
// Type returns the string representation of the query type.
Type() string
// Limit the number of records to be returned by this query.
Limit(int)
// Offset to start from.
Offset(int)
// Unique configures the query builder to filter duplicate records.
Unique(bool)
// Order specifies how the records should be ordered.
Order(...func(*sql.Selector))
// WhereP appends storage-level predicates to the query builder. Using this method, users
// can use type-assertion to append predicates that do not depend on any generated package.
WhereP(...func(*sql.Selector))
}
// The Func type is an adapter that allows ordinary functions to be used as interceptors.
// Unlike traversal functions, interceptors are skipped during graph traversals. Note that the
// implementation of Func is different from the one defined in entgo.io/ent.InterceptFunc.
type Func func(context.Context, Query) error
// Intercept calls f(ctx, q) and then applied the next Querier.
func (f Func) Intercept(next ent.Querier) ent.Querier {
return ent.QuerierFunc(func(ctx context.Context, q ent.Query) (ent.Value, error) {
query, err := NewQuery(q)
if err != nil {
return nil, err
}
if err := f(ctx, query); err != nil {
return nil, err
}
return next.Query(ctx, q)
})
}
// The TraverseFunc type is an adapter to allow the use of ordinary function as Traverser.
// If f is a function with the appropriate signature, TraverseFunc(f) is a Traverser that calls f.
type TraverseFunc func(context.Context, Query) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseFunc) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseFunc) Traverse(ctx context.Context, q ent.Query) error {
query, err := NewQuery(q)
if err != nil {
return err
}
return f(ctx, query)
}
// The CardFunc type is an adapter to allow the use of ordinary function as a Querier.
type CardFunc func(context.Context, *ent.CardQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f CardFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.CardQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.CardQuery", q)
}
// The TraverseCard type is an adapter to allow the use of ordinary function as Traverser.
type TraverseCard func(context.Context, *ent.CardQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseCard) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseCard) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.CardQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.CardQuery", q)
}
// The PetFunc type is an adapter to allow the use of ordinary function as a Querier.
type PetFunc func(context.Context, *ent.PetQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f PetFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.PetQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.PetQuery", q)
}
// The TraversePet type is an adapter to allow the use of ordinary function as Traverser.
type TraversePet func(context.Context, *ent.PetQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraversePet) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraversePet) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.PetQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.PetQuery", q)
}
// The UserFunc type is an adapter to allow the use of ordinary function as a Querier.
type UserFunc func(context.Context, *ent.UserQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f UserFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.UserQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.UserQuery", q)
}
// The TraverseUser type is an adapter to allow the use of ordinary function as Traverser.
type TraverseUser func(context.Context, *ent.UserQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseUser) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseUser) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.UserQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.UserQuery", q)
}
// NewQuery returns the generic Query interface for the given typed query.
func NewQuery(q ent.Query) (Query, error) {
switch q := q.(type) {
case *ent.CardQuery:
return &query[*ent.CardQuery, predicate.Card, card.OrderOption]{typ: ent.TypeCard, tq: q}, nil
case *ent.PetQuery:
return &query[*ent.PetQuery, predicate.Pet, pet.OrderOption]{typ: ent.TypePet, tq: q}, nil
case *ent.UserQuery:
return &query[*ent.UserQuery, predicate.User, user.OrderOption]{typ: ent.TypeUser, tq: q}, nil
default:
return nil, fmt.Errorf("unknown query type %T", q)
}
}
type query[T any, P ~func(*sql.Selector), R ~func(*sql.Selector)] struct {
typ string
tq interface {
Limit(int) T
Offset(int) T
Unique(bool) T
Order(...R) T
Where(...P) T
}
}
func (q query[T, P, R]) Type() string {
return q.typ
}
func (q query[T, P, R]) Limit(limit int) {
q.tq.Limit(limit)
}
func (q query[T, P, R]) Offset(offset int) {
q.tq.Offset(offset)
}
func (q query[T, P, R]) Unique(unique bool) {
q.tq.Unique(unique)
}
func (q query[T, P, R]) Order(orders ...func(*sql.Selector)) {
rs := make([]R, len(orders))
for i := range orders {
rs[i] = orders[i]
}
q.tq.Order(rs...)
}
func (q query[T, P, R]) WhereP(ps ...func(*sql.Selector)) {
p := make([]P, len(ps))
for i := range ps {
p[i] = ps[i]
}
q.tq.Where(p...)
}

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.
//go:build tools
// +build tools
// Package internal holds a loadable version of the latest schema.
package internal
const Schema = "{\"Schema\":\"entgo.io/ent/entc/integration/hooks/ent/schema\",\"Package\":\"entgo.io/ent/entc/integration/hooks/ent\",\"Schemas\":[{\"name\":\"Card\",\"config\":{\"Table\":\"\"},\"edges\":[{\"name\":\"owner\",\"type\":\"User\",\"ref_name\":\"cards\",\"unique\":true,\"inverse\":true}],\"fields\":[{\"name\":\"number\",\"type\":{\"Type\":7,\"Ident\":\"\",\"PkgPath\":\"\",\"PkgName\":\"\",\"Nillable\":false,\"RType\":null},\"default\":true,\"default_value\":\"unknown\",\"default_kind\":24,\"immutable\":true,\"validators\":1,\"position\":{\"Index\":0,\"MixedIn\":false,\"MixinIndex\":0}},{\"name\":\"name\",\"type\":{\"Type\":7,\"Ident\":\"\",\"PkgPath\":\"\",\"PkgName\":\"\",\"Nillable\":false,\"RType\":null},\"optional\":true,\"position\":{\"Index\":1,\"MixedIn\":false,\"MixinIndex\":0},\"comment\":\"Exact name written on card\"},{\"name\":\"created_at\",\"type\":{\"Type\":2,\"Ident\":\"\",\"PkgPath\":\"time\",\"PkgName\":\"\",\"Nillable\":false,\"RType\":null},\"default\":true,\"default_kind\":19,\"position\":{\"Index\":2,\"MixedIn\":false,\"MixinIndex\":0}},{\"name\":\"in_hook\",\"type\":{\"Type\":7,\"Ident\":\"\",\"PkgPath\":\"\",\"PkgName\":\"\",\"Nillable\":false,\"RType\":null},\"position\":{\"Index\":3,\"MixedIn\":false,\"MixinIndex\":0},\"comment\":\"InHook is a mandatory field that is set by the hook.\"},{\"name\":\"expired_at\",\"type\":{\"Type\":2,\"Ident\":\"\",\"PkgPath\":\"time\",\"PkgName\":\"\",\"Nillable\":false,\"RType\":null},\"optional\":true,\"position\":{\"Index\":4,\"MixedIn\":false,\"MixinIndex\":0}}],\"hooks\":[{\"Index\":0,\"MixedIn\":true,\"MixinIndex\":0},{\"Index\":0,\"MixedIn\":false,\"MixinIndex\":0},{\"Index\":1,\"MixedIn\":false,\"MixinIndex\":0}],\"interceptors\":[{\"Index\":0,\"MixedIn\":false,\"MixinIndex\":0}]},{\"name\":\"Pet\",\"config\":{\"Table\":\"\"},\"edges\":[{\"name\":\"owner\",\"type\":\"User\",\"ref_name\":\"pets\",\"unique\":true,\"inverse\":true}],\"fields\":[{\"name\":\"delete_time\",\"type\":{\"Type\":2,\"Ident\":\"\",\"PkgPath\":\"time\",\"PkgName\":\"\",\"Nillable\":false,\"RType\":null},\"optional\":true,\"position\":{\"Index\":0,\"MixedIn\":true,\"MixinIndex\":0}},{\"name\":\"name\",\"type\":{\"Type\":7,\"Ident\":\"\",\"PkgPath\":\"\",\"PkgName\":\"\",\"Nillable\":false,\"RType\":null},\"optional\":true,\"position\":{\"Index\":0,\"MixedIn\":false,\"MixinIndex\":0}}],\"hooks\":[{\"Index\":0,\"MixedIn\":true,\"MixinIndex\":0}],\"interceptors\":[{\"Index\":0,\"MixedIn\":true,\"MixinIndex\":0}]},{\"name\":\"User\",\"config\":{\"Table\":\"\"},\"edges\":[{\"name\":\"cards\",\"type\":\"Card\"},{\"name\":\"pets\",\"type\":\"Pet\"},{\"name\":\"friends\",\"type\":\"User\"},{\"name\":\"best_friend\",\"type\":\"User\",\"unique\":true}],\"fields\":[{\"name\":\"version\",\"type\":{\"Type\":12,\"Ident\":\"\",\"PkgPath\":\"\",\"PkgName\":\"\",\"Nillable\":false,\"RType\":null},\"default\":true,\"default_value\":0,\"default_kind\":2,\"position\":{\"Index\":0,\"MixedIn\":true,\"MixinIndex\":0}},{\"name\":\"name\",\"type\":{\"Type\":7,\"Ident\":\"\",\"PkgPath\":\"\",\"PkgName\":\"\",\"Nillable\":false,\"RType\":null},\"position\":{\"Index\":0,\"MixedIn\":false,\"MixinIndex\":0}},{\"name\":\"worth\",\"type\":{\"Type\":17,\"Ident\":\"\",\"PkgPath\":\"\",\"PkgName\":\"\",\"Nillable\":false,\"RType\":null},\"optional\":true,\"position\":{\"Index\":1,\"MixedIn\":false,\"MixinIndex\":0}},{\"name\":\"password\",\"type\":{\"Type\":7,\"Ident\":\"\",\"PkgPath\":\"\",\"PkgName\":\"\",\"Nillable\":false,\"RType\":null},\"optional\":true,\"position\":{\"Index\":2,\"MixedIn\":false,\"MixinIndex\":0},\"sensitive\":true},{\"name\":\"active\",\"type\":{\"Type\":1,\"Ident\":\"\",\"PkgPath\":\"\",\"PkgName\":\"\",\"Nillable\":false,\"RType\":null},\"default\":true,\"default_value\":true,\"default_kind\":1,\"position\":{\"Index\":3,\"MixedIn\":false,\"MixinIndex\":0}}],\"hooks\":[{\"Index\":0,\"MixedIn\":true,\"MixinIndex\":0},{\"Index\":0,\"MixedIn\":false,\"MixinIndex\":0}]}],\"Features\":[\"intercept\",\"schema/snapshot\"]}"

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,124 @@
// 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 (
// CardsColumns holds the columns for the "cards" table.
CardsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "number", Type: field.TypeString, Default: "unknown"},
{Name: "name", Type: field.TypeString, Nullable: true},
{Name: "created_at", Type: field.TypeTime},
{Name: "in_hook", Type: field.TypeString},
{Name: "expired_at", Type: field.TypeTime, Nullable: true},
{Name: "user_cards", Type: field.TypeInt, Nullable: true},
}
// CardsTable holds the schema information for the "cards" table.
CardsTable = &schema.Table{
Name: "cards",
Columns: CardsColumns,
PrimaryKey: []*schema.Column{CardsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "cards_users_cards",
Columns: []*schema.Column{CardsColumns[6]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.SetNull,
},
},
}
// PetsColumns holds the columns for the "pets" table.
PetsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "delete_time", Type: field.TypeTime, Nullable: true},
{Name: "name", Type: field.TypeString, Nullable: true},
{Name: "user_pets", 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[3]},
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: "version", Type: field.TypeInt, Default: 0},
{Name: "name", Type: field.TypeString},
{Name: "worth", Type: field.TypeUint, Nullable: true},
{Name: "password", Type: field.TypeString, Nullable: true},
{Name: "active", Type: field.TypeBool, Default: true},
{Name: "user_best_friend", Type: field.TypeInt, Unique: true, Nullable: true},
}
// UsersTable holds the schema information for the "users" table.
UsersTable = &schema.Table{
Name: "users",
Columns: UsersColumns,
PrimaryKey: []*schema.Column{UsersColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "users_users_best_friend",
Columns: []*schema.Column{UsersColumns[6]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.SetNull,
},
},
}
// UserFriendsColumns holds the columns for the "user_friends" table.
UserFriendsColumns = []*schema.Column{
{Name: "user_id", Type: field.TypeInt},
{Name: "friend_id", Type: field.TypeInt},
}
// UserFriendsTable holds the schema information for the "user_friends" table.
UserFriendsTable = &schema.Table{
Name: "user_friends",
Columns: UserFriendsColumns,
PrimaryKey: []*schema.Column{UserFriendsColumns[0], UserFriendsColumns[1]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "user_friends_user_id",
Columns: []*schema.Column{UserFriendsColumns[0]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.Cascade,
},
{
Symbol: "user_friends_friend_id",
Columns: []*schema.Column{UserFriendsColumns[1]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.Cascade,
},
},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
CardsTable,
PetsTable,
UsersTable,
UserFriendsTable,
}
)
func init() {
CardsTable.ForeignKeys[0].RefTable = UsersTable
PetsTable.ForeignKeys[0].RefTable = UsersTable
UsersTable.ForeignKeys[0].RefTable = UsersTable
UserFriendsTable.ForeignKeys[0].RefTable = UsersTable
UserFriendsTable.ForeignKeys[1].RefTable = UsersTable
}

View File

@@ -0,0 +1,604 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"sync"
"time"
"entgo.io/ent"
"entgo.io/ent/entc/integration/hooks/ent/card"
"entgo.io/ent/entc/integration/hooks/ent/pet"
"entgo.io/ent/entc/integration/hooks/ent/user"
)
const (
// Operation types.
OpCreate = ent.OpCreate
OpDelete = ent.OpDelete
OpDeleteOne = ent.OpDeleteOne
OpUpdate = ent.OpUpdate
OpUpdateOne = ent.OpUpdateOne
// Node types.
TypeCard = "Card"
TypePet = "Pet"
TypeUser = "User"
)
// CardMutation represents an operation that mutates the Card nodes in the graph.
type CardMutation struct {
card.Mutation
config
id *int
done bool
oldValue func(context.Context) (*Card, error)
}
var _ ent.Mutation = (*CardMutation)(nil)
// cardOption allows management of the mutation configuration using functional options.
type cardOption func(*CardMutation)
// newCardMutation creates new mutation for the Card entity.
func newCardMutation(c config, op Op, opts ...cardOption) *CardMutation {
m := &CardMutation{
Mutation: *card.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 *CardMutation) ID() (id int, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// withCardID sets the ID field of the mutation.
func withCardID(id int) cardOption {
return func(m *CardMutation) {
var (
err error
once sync.Once
value *Card
)
m.oldValue = func(ctx context.Context) (*Card, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().Card.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withCard sets the old Card of the mutation.
func withCard(node *Card) cardOption {
return func(m *CardMutation) {
m.oldValue = func(context.Context) (*Card, 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 CardMutation) 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 CardMutation) 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 *CardMutation) 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().Card.Query().Where(m.Predicates()...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.Op())
}
}
// OldNumber returns the old "number" field's value of the Card entity.
// If the Card 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 *CardMutation) OldNumber(ctx context.Context) (v string, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldNumber is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldNumber requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldNumber: %w", err)
}
return oldValue.Number, nil
}
// OldName returns the old "name" field's value of the Card entity.
// If the Card 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 *CardMutation) 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
}
// OldCreatedAt returns the old "created_at" field's value of the Card entity.
// If the Card 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 *CardMutation) 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
}
// OldInHook returns the old "in_hook" field's value of the Card entity.
// If the Card 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 *CardMutation) OldInHook(ctx context.Context) (v string, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldInHook is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldInHook requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldInHook: %w", err)
}
return oldValue.InHook, nil
}
// OldExpiredAt returns the old "expired_at" field's value of the Card entity.
// If the Card 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 *CardMutation) OldExpiredAt(ctx context.Context) (v time.Time, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldExpiredAt is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldExpiredAt requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldExpiredAt: %w", err)
}
return oldValue.ExpiredAt, 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 *CardMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case card.FieldNumber:
return m.OldNumber(ctx)
case card.FieldName:
return m.OldName(ctx)
case card.FieldCreatedAt:
return m.OldCreatedAt(ctx)
case card.FieldInHook:
return m.OldInHook(ctx)
case card.FieldExpiredAt:
return m.OldExpiredAt(ctx)
}
return nil, fmt.Errorf("unknown Card 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())
}
}
// OldDeleteTime returns the old "delete_time" 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) OldDeleteTime(ctx context.Context) (v time.Time, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldDeleteTime is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldDeleteTime requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldDeleteTime: %w", err)
}
return oldValue.DeleteTime, nil
}
// 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
}
// 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.FieldDeleteTime:
return m.OldDeleteTime(ctx)
case pet.FieldName:
return m.OldName(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())
}
}
// OldVersion returns the old "version" 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) OldVersion(ctx context.Context) (v int, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldVersion is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldVersion requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldVersion: %w", err)
}
return oldValue.Version, nil
}
// 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
}
// OldWorth returns the old "worth" 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) OldWorth(ctx context.Context) (v uint, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldWorth is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldWorth requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldWorth: %w", err)
}
return oldValue.Worth, nil
}
// OldPassword returns the old "password" 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) OldPassword(ctx context.Context) (v string, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldPassword is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldPassword requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldPassword: %w", err)
}
return oldValue.Password, nil
}
// OldActive returns the old "active" 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) OldActive(ctx context.Context) (v bool, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldActive is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldActive requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldActive: %w", err)
}
return oldValue.Active, 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.FieldVersion:
return m.OldVersion(ctx)
case user.FieldName:
return m.OldName(ctx)
case user.FieldWorth:
return m.OldWorth(ctx)
case user.FieldPassword:
return m.OldPassword(ctx)
case user.FieldActive:
return m.OldActive(ctx)
}
return nil, fmt.Errorf("unknown User field %s", name)
}

View File

@@ -0,0 +1,160 @@
// 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/hooks/ent/pet"
"entgo.io/ent/entc/integration/hooks/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"`
// DeleteTime holds the value of the "delete_time" field.
DeleteTime time.Time `json:"delete_time,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 PetQuery when eager-loading is set.
Edges PetEdges `json:"edges"`
user_pets *int
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:
values[i] = new(sql.NullInt64)
case pet.FieldName:
values[i] = new(sql.NullString)
case pet.FieldDeleteTime:
values[i] = new(sql.NullTime)
case pet.ForeignKeys[0]: // user_pets
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 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.FieldDeleteTime:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field delete_time", values[i])
} else if value.Valid {
_m.DeleteTime = value.Time
}
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.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for edge-field user_pets", value)
} else if value.Valid {
_m.user_pets = new(int)
*_m.user_pets = 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("delete_time=")
builder.WriteString(_m.DeleteTime.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(_m.Name)
builder.WriteByte(')')
return builder.String()
}
// Pets is a parsable slice of Pet.
type Pets []*Pet

View File

@@ -0,0 +1,377 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package pet
import (
"context"
"fmt"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/entc/integration/hooks/ent/predicate"
)
// Mutation represents an operation that mutates the Pet nodes in the graph.
type Mutation struct {
op ent.Op
typ string
delete_time *time.Time
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
}
// SetDeleteTime sets the "delete_time" field.
func (m *Mutation) SetDeleteTime(t time.Time) {
m.delete_time = &t
}
// DeleteTime returns the value of the "delete_time" field in the mutation.
func (m *Mutation) DeleteTime() (r time.Time, exists bool) {
v := m.delete_time
if v == nil {
return
}
return *v, true
}
// ClearDeleteTime clears the value of the "delete_time" field.
func (m *Mutation) ClearDeleteTime() {
m.delete_time = nil
m.clearedFields[FieldDeleteTime] = struct{}{}
}
// DeleteTimeCleared returns if the "delete_time" field was cleared in this mutation.
func (m *Mutation) DeleteTimeCleared() bool {
_, ok := m.clearedFields[FieldDeleteTime]
return ok
}
// ResetDeleteTime resets all changes to the "delete_time" field.
func (m *Mutation) ResetDeleteTime() {
m.delete_time = nil
delete(m.clearedFields, FieldDeleteTime)
}
// 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
}
// ClearName clears the value of the "name" field.
func (m *Mutation) ClearName() {
m.name = nil
m.clearedFields[FieldName] = struct{}{}
}
// NameCleared returns if the "name" field was cleared in this mutation.
func (m *Mutation) NameCleared() bool {
_, ok := m.clearedFields[FieldName]
return ok
}
// ResetName resets all changes to the "name" field.
func (m *Mutation) ResetName() {
m.name = nil
delete(m.clearedFields, FieldName)
}
// SetOwnerID sets the "owner" edge to the User entity by id.
func (m *Mutation) SetOwnerID(id int) {
m.owner = &id
}
// ClearOwner clears the "owner" edge to the User entity.
func (m *Mutation) ClearOwner() {
m.clearedowner = true
}
// OwnerCleared reports if the "owner" edge to the User entity was cleared.
func (m *Mutation) OwnerCleared() bool {
return m.clearedowner
}
// OwnerID returns the "owner" edge ID in the mutation.
func (m *Mutation) OwnerID() (id int, exists bool) {
if m.owner != nil {
return *m.owner, true
}
return
}
// 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.delete_time != nil {
fields = append(fields, FieldDeleteTime)
}
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 FieldDeleteTime:
return m.DeleteTime()
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 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 FieldDeleteTime:
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetDeleteTime(v)
return nil
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 Pet 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 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(FieldDeleteTime) {
fields = append(fields, FieldDeleteTime)
}
if m.FieldCleared(FieldName) {
fields = append(fields, FieldName)
}
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 FieldDeleteTime:
m.ClearDeleteTime()
return nil
case FieldName:
m.ClearName()
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 FieldDeleteTime:
m.ResetDeleteTime()
return nil
case FieldName:
m.ResetName()
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,105 @@
// 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"
"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"
// FieldDeleteTime holds the string denoting the delete_time field in the database.
FieldDeleteTime = "delete_time"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// 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 = "user_pets"
)
// Columns holds all SQL columns for pet fields.
var Columns = []string{
FieldID,
FieldDeleteTime,
FieldName,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "pets"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"user_pets",
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
for i := range ForeignKeys {
if column == ForeignKeys[i] {
return true
}
}
return false
}
// Note that the variables below are initialized by the runtime
// package on the initialization of the application. Therefore,
// it should be imported in the main as follows:
//
// import _ "entgo.io/ent/entc/integration/hooks/ent/runtime"
var (
Hooks [1]ent.Hook
Interceptors [1]ent.Interceptor
)
// 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()
}
// ByDeleteTime orders the results by the delete_time field.
func ByDeleteTime(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDeleteTime, opts...).ToFunc()
}
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, 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,233 @@
// 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 (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/hooks/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))
}
// DeleteTime applies equality check predicate on the "delete_time" field. It's identical to DeleteTimeEQ.
func DeleteTime(v time.Time) predicate.Pet {
return predicate.Pet(sql.FieldEQ(FieldDeleteTime, v))
}
// 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))
}
// DeleteTimeEQ applies the EQ predicate on the "delete_time" field.
func DeleteTimeEQ(v time.Time) predicate.Pet {
return predicate.Pet(sql.FieldEQ(FieldDeleteTime, v))
}
// DeleteTimeNEQ applies the NEQ predicate on the "delete_time" field.
func DeleteTimeNEQ(v time.Time) predicate.Pet {
return predicate.Pet(sql.FieldNEQ(FieldDeleteTime, v))
}
// DeleteTimeIn applies the In predicate on the "delete_time" field.
func DeleteTimeIn(vs ...time.Time) predicate.Pet {
return predicate.Pet(sql.FieldIn(FieldDeleteTime, vs...))
}
// DeleteTimeNotIn applies the NotIn predicate on the "delete_time" field.
func DeleteTimeNotIn(vs ...time.Time) predicate.Pet {
return predicate.Pet(sql.FieldNotIn(FieldDeleteTime, vs...))
}
// DeleteTimeGT applies the GT predicate on the "delete_time" field.
func DeleteTimeGT(v time.Time) predicate.Pet {
return predicate.Pet(sql.FieldGT(FieldDeleteTime, v))
}
// DeleteTimeGTE applies the GTE predicate on the "delete_time" field.
func DeleteTimeGTE(v time.Time) predicate.Pet {
return predicate.Pet(sql.FieldGTE(FieldDeleteTime, v))
}
// DeleteTimeLT applies the LT predicate on the "delete_time" field.
func DeleteTimeLT(v time.Time) predicate.Pet {
return predicate.Pet(sql.FieldLT(FieldDeleteTime, v))
}
// DeleteTimeLTE applies the LTE predicate on the "delete_time" field.
func DeleteTimeLTE(v time.Time) predicate.Pet {
return predicate.Pet(sql.FieldLTE(FieldDeleteTime, v))
}
// DeleteTimeIsNil applies the IsNil predicate on the "delete_time" field.
func DeleteTimeIsNil() predicate.Pet {
return predicate.Pet(sql.FieldIsNull(FieldDeleteTime))
}
// DeleteTimeNotNil applies the NotNil predicate on the "delete_time" field.
func DeleteTimeNotNil() predicate.Pet {
return predicate.Pet(sql.FieldNotNull(FieldDeleteTime))
}
// 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))
}
// NameIsNil applies the IsNil predicate on the "name" field.
func NameIsNil() predicate.Pet {
return predicate.Pet(sql.FieldIsNull(FieldName))
}
// NameNotNil applies the NotNil predicate on the "name" field.
func NameNotNil() predicate.Pet {
return predicate.Pet(sql.FieldNotNull(FieldName))
}
// 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))
}
// 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),
)
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()
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,247 @@
// 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"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/hooks/ent/pet"
"entgo.io/ent/entc/integration/hooks/ent/user"
"entgo.io/ent/schema/field"
)
// PetCreate is the builder for creating a Pet entity.
type PetCreate struct {
config
mutation *PetMutation
hooks []Hook
}
// SetDeleteTime sets the "delete_time" field.
func (_c *PetCreate) SetDeleteTime(v time.Time) *PetCreate {
_c.mutation.SetDeleteTime(v)
return _c
}
// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil.
func (_c *PetCreate) SetNillableDeleteTime(v *time.Time) *PetCreate {
if v != nil {
_c.SetDeleteTime(*v)
}
return _c
}
// 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" edge to the User entity by ID.
func (_c *PetCreate) SetOwnerID(id int) *PetCreate {
_c.mutation.SetOwnerID(id)
return _c
}
// SetNillableOwnerID sets the "owner" edge to the User entity by ID if the given value is not nil.
func (_c *PetCreate) SetNillableOwnerID(id *int) *PetCreate {
if id != nil {
_c = _c.SetOwnerID(*id)
}
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) {
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)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *PetCreate) check() error {
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))
)
if value, ok := _c.mutation.DeleteTime(); ok {
_spec.SetField(pet.FieldDeleteTime, field.TypeTime, value)
_node.DeleteTime = value
}
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),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.user_pets = &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]
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,92 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/hooks/ent/pet"
"entgo.io/ent/entc/integration/hooks/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))
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,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 ent
import (
"context"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/hooks/ent/pet"
"entgo.io/ent/entc/integration/hooks/ent/predicate"
"entgo.io/ent/entc/integration/hooks/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
withFKs bool
// 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),
)
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,
}
}
// 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 {
// DeleteTime time.Time `json:"delete_time,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Pet.Query().
// GroupBy(pet.FieldDeleteTime).
// 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 {
// DeleteTime time.Time `json:"delete_time,omitempty"`
// }
//
// client.Pet.Query().
// Select(pet.FieldDeleteTime).
// 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{}
withFKs = _q.withFKs
_spec = _q.querySpec()
loadedTypes = [1]bool{
_q.withOwner != nil,
}
)
if _q.withOwner != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, pet.ForeignKeys...)
}
_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)
}
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 {
if nodes[i].user_pets == nil {
continue
}
fk := *nodes[i].user_pets
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_pets" 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.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 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()
}
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
}
// 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)
}

View File

@@ -0,0 +1,393 @@
// 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/hooks/ent/pet"
"entgo.io/ent/entc/integration/hooks/ent/predicate"
"entgo.io/ent/entc/integration/hooks/ent/user"
"entgo.io/ent/schema/field"
)
// PetUpdate is the builder for updating Pet entities.
type PetUpdate struct {
config
hooks []Hook
mutation *PetMutation
}
// Where appends a list predicates to the PetUpdate builder.
func (_u *PetUpdate) Where(ps ...predicate.Pet) *PetUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetDeleteTime sets the "delete_time" field.
func (_u *PetUpdate) SetDeleteTime(v time.Time) *PetUpdate {
_u.mutation.SetDeleteTime(v)
return _u
}
// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil.
func (_u *PetUpdate) SetNillableDeleteTime(v *time.Time) *PetUpdate {
if v != nil {
_u.SetDeleteTime(*v)
}
return _u
}
// ClearDeleteTime clears the value of the "delete_time" field.
func (_u *PetUpdate) ClearDeleteTime() *PetUpdate {
_u.mutation.ClearDeleteTime()
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
}
// ClearName clears the value of the "name" field.
func (_u *PetUpdate) ClearName() *PetUpdate {
_u.mutation.ClearName()
return _u
}
// SetOwnerID sets the "owner" edge to the User entity by ID.
func (_u *PetUpdate) SetOwnerID(id int) *PetUpdate {
_u.mutation.SetOwnerID(id)
return _u
}
// SetNillableOwnerID sets the "owner" edge to the User entity by ID if the given value is not nil.
func (_u *PetUpdate) SetNillableOwnerID(id *int) *PetUpdate {
if id != nil {
_u = _u.SetOwnerID(*id)
}
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)
}
}
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.DeleteTime(); ok {
_spec.SetField(pet.FieldDeleteTime, field.TypeTime, value)
}
if _u.mutation.DeleteTimeCleared() {
_spec.ClearField(pet.FieldDeleteTime, field.TypeTime)
}
if value, ok := _u.mutation.Name(); ok {
_spec.SetField(pet.FieldName, field.TypeString, value)
}
if _u.mutation.NameCleared() {
_spec.ClearField(pet.FieldName, field.TypeString)
}
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),
},
}
_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),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{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
}
// SetDeleteTime sets the "delete_time" field.
func (_u *PetUpdateOne) SetDeleteTime(v time.Time) *PetUpdateOne {
_u.mutation.SetDeleteTime(v)
return _u
}
// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil.
func (_u *PetUpdateOne) SetNillableDeleteTime(v *time.Time) *PetUpdateOne {
if v != nil {
_u.SetDeleteTime(*v)
}
return _u
}
// ClearDeleteTime clears the value of the "delete_time" field.
func (_u *PetUpdateOne) ClearDeleteTime() *PetUpdateOne {
_u.mutation.ClearDeleteTime()
return _u
}
// 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
}
// ClearName clears the value of the "name" field.
func (_u *PetUpdateOne) ClearName() *PetUpdateOne {
_u.mutation.ClearName()
return _u
}
// SetOwnerID sets the "owner" edge to the User entity by ID.
func (_u *PetUpdateOne) SetOwnerID(id int) *PetUpdateOne {
_u.mutation.SetOwnerID(id)
return _u
}
// SetNillableOwnerID sets the "owner" edge to the User entity by ID if the given value is not nil.
func (_u *PetUpdateOne) SetNillableOwnerID(id *int) *PetUpdateOne {
if id != nil {
_u = _u.SetOwnerID(*id)
}
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)
}
}
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.DeleteTime(); ok {
_spec.SetField(pet.FieldDeleteTime, field.TypeTime, value)
}
if _u.mutation.DeleteTimeCleared() {
_spec.ClearField(pet.FieldDeleteTime, field.TypeTime)
}
if value, ok := _u.mutation.Name(); ok {
_spec.SetField(pet.FieldName, field.TypeString, value)
}
if _u.mutation.NameCleared() {
_spec.ClearField(pet.FieldName, field.TypeString)
}
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),
},
}
_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),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_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,20 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package predicate
import (
"entgo.io/ent/dialect/sql"
)
// Card is the predicate function for card builders.
type Card 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,9 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
// The schema-stitching logic is generated in entgo.io/ent/entc/integration/hooks/ent/runtime/runtime.go

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 runtime
import (
"time"
"entgo.io/ent/entc/integration/hooks/ent/card"
"entgo.io/ent/entc/integration/hooks/ent/pet"
"entgo.io/ent/entc/integration/hooks/ent/schema"
"entgo.io/ent/entc/integration/hooks/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() {
cardMixin := schema.Card{}.Mixin()
cardMixinHooks0 := cardMixin[0].Hooks()
cardHooks := schema.Card{}.Hooks()
card.Hooks[0] = cardMixinHooks0[0]
card.Hooks[1] = cardHooks[0]
card.Hooks[2] = cardHooks[1]
cardInters := schema.Card{}.Interceptors()
card.Interceptors[0] = cardInters[0]
cardFields := schema.Card{}.Fields()
_ = cardFields
// cardDescNumber is the schema descriptor for number field.
cardDescNumber := cardFields[0].Descriptor()
// card.DefaultNumber holds the default value on creation for the number field.
card.DefaultNumber = cardDescNumber.Default.(string)
// card.NumberValidator is a validator for the "number" field. It is called by the builders before save.
card.NumberValidator = cardDescNumber.Validators[0].(func(string) error)
// cardDescCreatedAt is the schema descriptor for created_at field.
cardDescCreatedAt := cardFields[2].Descriptor()
// card.DefaultCreatedAt holds the default value on creation for the created_at field.
card.DefaultCreatedAt = cardDescCreatedAt.Default.(func() time.Time)
petMixin := schema.Pet{}.Mixin()
petMixinHooks0 := petMixin[0].Hooks()
pet.Hooks[0] = petMixinHooks0[0]
petMixinInters0 := petMixin[0].Interceptors()
pet.Interceptors[0] = petMixinInters0[0]
userMixin := schema.User{}.Mixin()
userMixinHooks0 := userMixin[0].Hooks()
userHooks := schema.User{}.Hooks()
user.Hooks[0] = userMixinHooks0[0]
user.Hooks[1] = userHooks[0]
userMixinFields0 := userMixin[0].Fields()
_ = userMixinFields0
userFields := schema.User{}.Fields()
_ = userFields
// userDescVersion is the schema descriptor for version field.
userDescVersion := userMixinFields0[0].Descriptor()
// user.DefaultVersion holds the default value on creation for the version field.
user.DefaultVersion = userDescVersion.Default.(int)
// userDescActive is the schema descriptor for active field.
userDescActive := userFields[3].Descriptor()
// user.DefaultActive holds the default value on creation for the active field.
user.DefaultActive = userDescActive.Default.(bool)
}
const (
Version = "v0.0.0-00010101000000-000000000000" // Version of ent codegen.
)

View File

@@ -0,0 +1,112 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package schema
import (
"context"
"fmt"
"time"
"entgo.io/ent"
gen "entgo.io/ent/entc/integration/hooks/ent"
"entgo.io/ent/entc/integration/hooks/ent/card"
"entgo.io/ent/entc/integration/hooks/ent/hook"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/mixin"
)
// RejectUpdate rejects ~all update operations
// that are not on a specific entity.
type RejectUpdate struct {
mixin.Schema
}
func (RejectUpdate) Hooks() []ent.Hook {
return []ent.Hook{
hook.If(
hook.Reject(ent.OpUpdate),
// Accept only updates that contains the "expired_at" field.
hook.Not(hook.HasFields(card.FieldExpiredAt)),
),
}
}
// Card holds the schema definition for the CreditCard entity.
type Card struct {
ent.Schema
}
func (Card) Mixin() []ent.Mixin {
return []ent.Mixin{
RejectUpdate{},
}
}
func (Card) Hooks() []ent.Hook {
return []ent.Hook{
hook.On(
func(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
num, ok := m.Field(card.FieldNumber)
if !ok {
return nil, fmt.Errorf("missing card number value")
}
// Validator in hooks.
if len(num.(string)) < 4 {
return nil, fmt.Errorf("card number is too short")
}
return next.Mutate(ctx, m)
})
},
ent.OpCreate,
),
func(next ent.Mutator) ent.Mutator {
return hook.CardFunc(func(ctx context.Context, m *gen.CardMutation) (ent.Value, error) {
m.SetInHook("value was set in hook")
if _, ok := m.Name(); !ok {
m.SetName("unknown")
}
return next.Mutate(ctx, m)
})
},
}
}
func (Card) Fields() []ent.Field {
return []ent.Field{
field.String("number").
Immutable().
Default("unknown").
NotEmpty(),
field.String("name").
Optional().
Comment("Exact name written on card"),
field.Time("created_at").
Default(time.Now),
field.String("in_hook").
Comment("InHook is a mandatory field that is set by the hook."),
field.Time("expired_at").
Optional(),
}
}
func (Card) Edges() []ent.Edge {
return []ent.Edge{
edge.From("owner", User.Type).
Ref("cards").
Unique(),
}
}
func (Card) Interceptors() []ent.Interceptor {
return []ent.Interceptor{
ent.InterceptFunc(func(next ent.Querier) ent.Querier {
return ent.QuerierFunc(func(ctx context.Context, q ent.Query) (ent.Value, error) {
return next.Query(ctx, q)
})
}),
}
}

View File

@@ -0,0 +1,85 @@
// 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 (
"context"
"fmt"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
gen "entgo.io/ent/entc/integration/hooks/ent"
"entgo.io/ent/entc/integration/hooks/ent/hook"
"entgo.io/ent/entc/integration/hooks/ent/intercept"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/mixin"
)
type SoftDeleteMixin struct {
mixin.Schema
}
func (SoftDeleteMixin) Fields() []ent.Field {
return []ent.Field{
field.Time("delete_time").
Optional(),
}
}
type softDeleteKey struct{}
// SkipSoftDelete returns a new context that skips the soft-delete interceptor/mutators.
func SkipSoftDelete(parent context.Context) context.Context {
return context.WithValue(parent, softDeleteKey{}, true)
}
func (d SoftDeleteMixin) Interceptors() []ent.Interceptor {
return []ent.Interceptor{
intercept.TraverseFunc(func(ctx context.Context, q intercept.Query) error {
// Skip soft-delete, means include soft-deleted entities.
if skip, _ := ctx.Value(softDeleteKey{}).(bool); skip {
return nil
}
d.P(q)
return nil
}),
}
}
func (d SoftDeleteMixin) Hooks() []ent.Hook {
return []ent.Hook{
hook.On(
func(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
// Skip soft-delete, means delete the entity permanently.
if skip, _ := ctx.Value(softDeleteKey{}).(bool); skip {
return next.Mutate(ctx, m)
}
mx, ok := m.(interface {
SetOp(ent.Op)
Client() *gen.Client
SetDeleteTime(time.Time)
WhereP(...func(*sql.Selector))
})
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
d.P(mx)
mx.SetOp(ent.OpUpdate)
mx.SetDeleteTime(time.Now())
return mx.Client().Mutate(ctx, m)
})
},
ent.OpDeleteOne|ent.OpDelete,
),
}
}
func (d SoftDeleteMixin) P(w interface{ WhereP(...func(*sql.Selector)) }) {
w.WhereP(
sql.FieldIsNull(d.Fields()[0].Descriptor().Name),
)
}

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

View File

@@ -0,0 +1,122 @@
// 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 (
"context"
"errors"
"fmt"
"entgo.io/ent/entc/integration/hooks/ent/user"
"entgo.io/ent"
"entgo.io/ent/entc/integration/hooks/ent/hook"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/mixin"
)
// User holds the schema definition for the User entity.
type User struct {
ent.Schema
}
// Mixin of the User.
func (User) Mixin() []ent.Mixin {
return []ent.Mixin{
VersionMixin{},
}
}
// Fields of the User.
func (User) Fields() []ent.Field {
return []ent.Field{
field.String("name"),
field.Uint("worth").
Optional(),
field.String("password").
Optional().
Sensitive(),
field.Bool("active").
Default(true),
}
}
// Edges of the User.
func (User) Edges() []ent.Edge {
return []ent.Edge{
edge.To("cards", Card.Type),
edge.To("pets", Pet.Type),
edge.To("friends", User.Type),
edge.To("best_friend", User.Type).
Unique(),
}
}
// Hooks of the User.
func (User) Hooks() []ent.Hook {
return []ent.Hook{
hook.If(
hook.FixedError(errors.New("password cannot be edited on update-many")),
hook.And(
hook.HasOp(ent.OpUpdate),
hook.Or(
hook.HasFields(user.FieldPassword),
hook.HasClearedFields(user.FieldPassword),
),
),
),
}
}
type VersionMixin struct {
mixin.Schema
}
func (VersionMixin) Fields() []ent.Field {
return []ent.Field{
field.Int("version").
Default(0),
}
}
func (VersionMixin) Hooks() []ent.Hook {
return []ent.Hook{
hook.On(VersionHook(), ent.OpUpdateOne),
}
}
func VersionHook() ent.Hook {
type OldSetVersion interface {
SetVersion(int)
Version() (int, bool)
OldVersion(context.Context) (int, error)
}
return func(next ent.Mutator) ent.Mutator {
// A hook that validates the "version" field is incremented by 1 on each update.
// Note that this is just a dummy example, and it doesn't promise consistency in
// the database.
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
ver, ok := m.(OldSetVersion)
if !ok {
return next.Mutate(ctx, m)
}
oldV, err := ver.OldVersion(ctx)
if err != nil {
return nil, err
}
curV, exists := ver.Version()
if !exists {
return nil, fmt.Errorf("version field is required in update mutation")
}
if curV != oldV+1 {
return nil, fmt.Errorf("version field must be incremented by 1")
}
// Add an SQL predicate that validates the "version" column is equal
// to "oldV" (it wasn't changed during the mutation by other process).
return next.Mutate(ctx, m)
})
}
}

View File

@@ -0,0 +1,220 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"sync"
"entgo.io/ent/dialect"
)
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
// Card is the client for interacting with the Card builders.
Card *CardClient
// 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.Card = NewCardClient(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: Card.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,238 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/entc/integration/hooks/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"`
// Version holds the value of the "version" field.
Version int `json:"version,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// Worth holds the value of the "worth" field.
Worth uint `json:"worth,omitempty"`
// Password holds the value of the "password" field.
Password string `json:"-"`
// Active holds the value of the "active" field.
Active bool `json:"active,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"`
user_best_friend *int
selectValues sql.SelectValues
}
// UserEdges holds the relations/edges for other nodes in the graph.
type UserEdges struct {
// Cards holds the value of the cards edge.
Cards []*Card `json:"cards,omitempty"`
// Pets holds the value of the pets edge.
Pets []*Pet `json:"pets,omitempty"`
// Friends holds the value of the friends edge.
Friends []*User `json:"friends,omitempty"`
// BestFriend holds the value of the best_friend edge.
BestFriend *User `json:"best_friend,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [4]bool
}
// CardsOrErr returns the Cards value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) CardsOrErr() ([]*Card, error) {
if e.loadedTypes[0] {
return e.Cards, nil
}
return nil, &NotLoadedError{edge: "cards"}
}
// 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[1] {
return e.Pets, nil
}
return nil, &NotLoadedError{edge: "pets"}
}
// 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"}
}
// BestFriendOrErr returns the BestFriend value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e UserEdges) BestFriendOrErr() (*User, error) {
if e.BestFriend != nil {
return e.BestFriend, nil
} else if e.loadedTypes[3] {
return nil, &NotFoundError{label: user.Label}
}
return nil, &NotLoadedError{edge: "best_friend"}
}
// 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.FieldActive:
values[i] = new(sql.NullBool)
case user.FieldID, user.FieldVersion, user.FieldWorth:
values[i] = new(sql.NullInt64)
case user.FieldName, user.FieldPassword:
values[i] = new(sql.NullString)
case user.ForeignKeys[0]: // user_best_friend
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 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.FieldVersion:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field version", values[i])
} else if value.Valid {
_m.Version = 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
}
case user.FieldWorth:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field worth", values[i])
} else if value.Valid {
_m.Worth = uint(value.Int64)
}
case user.FieldPassword:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field password", values[i])
} else if value.Valid {
_m.Password = value.String
}
case user.FieldActive:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field active", values[i])
} else if value.Valid {
_m.Active = value.Bool
}
case user.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for edge-field user_best_friend", value)
} else if value.Valid {
_m.user_best_friend = new(int)
*_m.user_best_friend = 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 User.
// This includes values selected through modifiers, order, etc.
func (_m *User) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryCards queries the "cards" edge of the User entity.
func (_m *User) QueryCards() *CardQuery {
return NewUserClient(_m.config).QueryCards(_m)
}
// QueryPets queries the "pets" edge of the User entity.
func (_m *User) QueryPets() *PetQuery {
return NewUserClient(_m.config).QueryPets(_m)
}
// QueryFriends queries the "friends" edge of the User entity.
func (_m *User) QueryFriends() *UserQuery {
return NewUserClient(_m.config).QueryFriends(_m)
}
// QueryBestFriend queries the "best_friend" edge of the User entity.
func (_m *User) QueryBestFriend() *UserQuery {
return NewUserClient(_m.config).QueryBestFriend(_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("version=")
builder.WriteString(fmt.Sprintf("%v", _m.Version))
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(_m.Name)
builder.WriteString(", ")
builder.WriteString("worth=")
builder.WriteString(fmt.Sprintf("%v", _m.Worth))
builder.WriteString(", ")
builder.WriteString("password=<sensitive>")
builder.WriteString(", ")
builder.WriteString("active=")
builder.WriteString(fmt.Sprintf("%v", _m.Active))
builder.WriteByte(')')
return builder.String()
}
// Users is a parsable slice of User.
type Users []*User

View File

@@ -0,0 +1,802 @@
// 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/hooks/ent/predicate"
)
// Mutation represents an operation that mutates the User nodes in the graph.
type Mutation struct {
op ent.Op
typ string
version *int
addversion *int
name *string
worth *uint
addworth *int
password *string
active *bool
clearedFields map[string]struct{}
cards map[int]struct{}
removedcards map[int]struct{}
clearedcards bool
pets map[int]struct{}
removedpets map[int]struct{}
clearedpets bool
friends map[int]struct{}
removedfriends map[int]struct{}
clearedfriends bool
best_friend *int
clearedbest_friend 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
}
// SetVersion sets the "version" field.
func (m *Mutation) SetVersion(i int) {
m.version = &i
m.addversion = nil
}
// Version returns the value of the "version" field in the mutation.
func (m *Mutation) Version() (r int, exists bool) {
v := m.version
if v == nil {
return
}
return *v, true
}
// AddVersion adds i to the "version" field.
func (m *Mutation) AddVersion(i int) {
if m.addversion != nil {
*m.addversion += i
} else {
m.addversion = &i
}
}
// AddedVersion returns the value that was added to the "version" field in this mutation.
func (m *Mutation) AddedVersion() (r int, exists bool) {
v := m.addversion
if v == nil {
return
}
return *v, true
}
// ResetVersion resets all changes to the "version" field.
func (m *Mutation) ResetVersion() {
m.version = nil
m.addversion = nil
}
// 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
}
// SetWorth sets the "worth" field.
func (m *Mutation) SetWorth(u uint) {
m.worth = &u
m.addworth = nil
}
// Worth returns the value of the "worth" field in the mutation.
func (m *Mutation) Worth() (r uint, exists bool) {
v := m.worth
if v == nil {
return
}
return *v, true
}
// AddWorth adds u to the "worth" field.
func (m *Mutation) AddWorth(u int) {
if m.addworth != nil {
*m.addworth += u
} else {
m.addworth = &u
}
}
// AddedWorth returns the value that was added to the "worth" field in this mutation.
func (m *Mutation) AddedWorth() (r int, exists bool) {
v := m.addworth
if v == nil {
return
}
return *v, true
}
// ClearWorth clears the value of the "worth" field.
func (m *Mutation) ClearWorth() {
m.worth = nil
m.addworth = nil
m.clearedFields[FieldWorth] = struct{}{}
}
// WorthCleared returns if the "worth" field was cleared in this mutation.
func (m *Mutation) WorthCleared() bool {
_, ok := m.clearedFields[FieldWorth]
return ok
}
// ResetWorth resets all changes to the "worth" field.
func (m *Mutation) ResetWorth() {
m.worth = nil
m.addworth = nil
delete(m.clearedFields, FieldWorth)
}
// SetPassword sets the "password" field.
func (m *Mutation) SetPassword(s string) {
m.password = &s
}
// Password returns the value of the "password" field in the mutation.
func (m *Mutation) Password() (r string, exists bool) {
v := m.password
if v == nil {
return
}
return *v, true
}
// ClearPassword clears the value of the "password" field.
func (m *Mutation) ClearPassword() {
m.password = nil
m.clearedFields[FieldPassword] = struct{}{}
}
// PasswordCleared returns if the "password" field was cleared in this mutation.
func (m *Mutation) PasswordCleared() bool {
_, ok := m.clearedFields[FieldPassword]
return ok
}
// ResetPassword resets all changes to the "password" field.
func (m *Mutation) ResetPassword() {
m.password = nil
delete(m.clearedFields, FieldPassword)
}
// SetActive sets the "active" field.
func (m *Mutation) SetActive(b bool) {
m.active = &b
}
// Active returns the value of the "active" field in the mutation.
func (m *Mutation) Active() (r bool, exists bool) {
v := m.active
if v == nil {
return
}
return *v, true
}
// ResetActive resets all changes to the "active" field.
func (m *Mutation) ResetActive() {
m.active = nil
}
// AddCardIDs adds the "cards" edge to the Card entity by ids.
func (m *Mutation) AddCardIDs(ids ...int) {
if m.cards == nil {
m.cards = make(map[int]struct{})
}
for i := range ids {
m.cards[ids[i]] = struct{}{}
}
}
// ClearCards clears the "cards" edge to the Card entity.
func (m *Mutation) ClearCards() {
m.clearedcards = true
}
// CardsCleared reports if the "cards" edge to the Card entity was cleared.
func (m *Mutation) CardsCleared() bool {
return m.clearedcards
}
// RemoveCardIDs removes the "cards" edge to the Card entity by IDs.
func (m *Mutation) RemoveCardIDs(ids ...int) {
if m.removedcards == nil {
m.removedcards = make(map[int]struct{})
}
for i := range ids {
delete(m.cards, ids[i])
m.removedcards[ids[i]] = struct{}{}
}
}
// RemovedCards returns the removed IDs of the "cards" edge to the Card entity.
func (m *Mutation) RemovedCardsIDs() (ids []int) {
for id := range m.removedcards {
ids = append(ids, id)
}
return
}
// CardsIDs returns the "cards" edge IDs in the mutation.
func (m *Mutation) CardsIDs() (ids []int) {
for id := range m.cards {
ids = append(ids, id)
}
return
}
// ResetCards resets all changes to the "cards" edge.
func (m *Mutation) ResetCards() {
m.cards = nil
m.clearedcards = false
m.removedcards = 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
}
// 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
}
// SetBestFriendID sets the "best_friend" edge to the User entity by id.
func (m *Mutation) SetBestFriendID(id int) {
m.best_friend = &id
}
// ClearBestFriend clears the "best_friend" edge to the User entity.
func (m *Mutation) ClearBestFriend() {
m.clearedbest_friend = true
}
// BestFriendCleared reports if the "best_friend" edge to the User entity was cleared.
func (m *Mutation) BestFriendCleared() bool {
return m.clearedbest_friend
}
// BestFriendID returns the "best_friend" edge ID in the mutation.
func (m *Mutation) BestFriendID() (id int, exists bool) {
if m.best_friend != nil {
return *m.best_friend, true
}
return
}
// BestFriendIDs returns the "best_friend" edge IDs in the mutation.
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
// BestFriendID instead. It exists only for internal usage by the builders.
func (m *Mutation) BestFriendIDs() (ids []int) {
if id := m.best_friend; id != nil {
ids = append(ids, *id)
}
return
}
// ResetBestFriend resets all changes to the "best_friend" edge.
func (m *Mutation) ResetBestFriend() {
m.best_friend = nil
m.clearedbest_friend = false
}
// 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, 5)
if m.version != nil {
fields = append(fields, FieldVersion)
}
if m.name != nil {
fields = append(fields, FieldName)
}
if m.worth != nil {
fields = append(fields, FieldWorth)
}
if m.password != nil {
fields = append(fields, FieldPassword)
}
if m.active != nil {
fields = append(fields, FieldActive)
}
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 FieldVersion:
return m.Version()
case FieldName:
return m.Name()
case FieldWorth:
return m.Worth()
case FieldPassword:
return m.Password()
case FieldActive:
return m.Active()
}
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 FieldVersion:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetVersion(v)
return nil
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 FieldWorth:
v, ok := value.(uint)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetWorth(v)
return nil
case FieldPassword:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetPassword(v)
return nil
case FieldActive:
v, ok := value.(bool)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetActive(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 {
var fields []string
if m.addversion != nil {
fields = append(fields, FieldVersion)
}
if m.addworth != nil {
fields = append(fields, FieldWorth)
}
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 FieldVersion:
return m.AddedVersion()
case FieldWorth:
return m.AddedWorth()
}
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 FieldVersion:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.AddVersion(v)
return nil
case FieldWorth:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.AddWorth(v)
return nil
}
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 {
var fields []string
if m.FieldCleared(FieldWorth) {
fields = append(fields, FieldWorth)
}
if m.FieldCleared(FieldPassword) {
fields = append(fields, FieldPassword)
}
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 FieldWorth:
m.ClearWorth()
return nil
case FieldPassword:
m.ClearPassword()
return nil
}
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 FieldVersion:
m.ResetVersion()
return nil
case FieldName:
m.ResetName()
return nil
case FieldWorth:
m.ResetWorth()
return nil
case FieldPassword:
m.ResetPassword()
return nil
case FieldActive:
m.ResetActive()
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, 4)
if m.cards != nil {
edges = append(edges, EdgeCards)
}
if m.pets != nil {
edges = append(edges, EdgePets)
}
if m.friends != nil {
edges = append(edges, EdgeFriends)
}
if m.best_friend != nil {
edges = append(edges, EdgeBestFriend)
}
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 EdgeCards:
ids := make([]ent.Value, 0, len(m.cards))
for id := range m.cards {
ids = append(ids, id)
}
return ids
case EdgePets:
ids := make([]ent.Value, 0, len(m.pets))
for id := range m.pets {
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 EdgeBestFriend:
if id := m.best_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, 4)
if m.removedcards != nil {
edges = append(edges, EdgeCards)
}
if m.removedpets != nil {
edges = append(edges, EdgePets)
}
if m.removedfriends != nil {
edges = append(edges, EdgeFriends)
}
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 EdgeCards:
ids := make([]ent.Value, 0, len(m.removedcards))
for id := range m.removedcards {
ids = append(ids, id)
}
return ids
case EdgePets:
ids := make([]ent.Value, 0, len(m.removedpets))
for id := range m.removedpets {
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
}
return nil
}
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *Mutation) ClearedEdges() []string {
edges := make([]string, 0, 4)
if m.clearedcards {
edges = append(edges, EdgeCards)
}
if m.clearedpets {
edges = append(edges, EdgePets)
}
if m.clearedfriends {
edges = append(edges, EdgeFriends)
}
if m.clearedbest_friend {
edges = append(edges, EdgeBestFriend)
}
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 EdgeCards:
return m.clearedcards
case EdgePets:
return m.clearedpets
case EdgeFriends:
return m.clearedfriends
case EdgeBestFriend:
return m.clearedbest_friend
}
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 EdgeBestFriend:
m.ClearBestFriend()
return nil
}
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 EdgeCards:
m.ResetCards()
return nil
case EdgePets:
m.ResetPets()
return nil
case EdgeFriends:
m.ResetFriends()
return nil
case EdgeBestFriend:
m.ResetBestFriend()
return nil
}
return fmt.Errorf("unknown User edge %s", name)
}

View File

@@ -0,0 +1,220 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package user
import (
"entgo.io/ent"
"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"
// FieldVersion holds the string denoting the version field in the database.
FieldVersion = "version"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldWorth holds the string denoting the worth field in the database.
FieldWorth = "worth"
// FieldPassword holds the string denoting the password field in the database.
FieldPassword = "password"
// FieldActive holds the string denoting the active field in the database.
FieldActive = "active"
// EdgeCards holds the string denoting the cards edge name in mutations.
EdgeCards = "cards"
// EdgePets holds the string denoting the pets edge name in mutations.
EdgePets = "pets"
// EdgeFriends holds the string denoting the friends edge name in mutations.
EdgeFriends = "friends"
// EdgeBestFriend holds the string denoting the best_friend edge name in mutations.
EdgeBestFriend = "best_friend"
// Table holds the table name of the user in the database.
Table = "users"
// CardsTable is the table that holds the cards relation/edge.
CardsTable = "cards"
// CardsInverseTable is the table name for the Card entity.
// It exists in this package in order to avoid circular dependency with the "card" package.
CardsInverseTable = "cards"
// CardsColumn is the table column denoting the cards relation/edge.
CardsColumn = "user_cards"
// 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 = "user_pets"
// FriendsTable is the table that holds the friends relation/edge. The primary key declared below.
FriendsTable = "user_friends"
// BestFriendTable is the table that holds the best_friend relation/edge.
BestFriendTable = "users"
// BestFriendColumn is the table column denoting the best_friend relation/edge.
BestFriendColumn = "user_best_friend"
)
// Columns holds all SQL columns for user fields.
var Columns = []string{
FieldID,
FieldVersion,
FieldName,
FieldWorth,
FieldPassword,
FieldActive,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "users"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"user_best_friend",
}
var (
// FriendsPrimaryKey and FriendsColumn2 are the table columns denoting the
// primary key for the friends relation (M2M).
FriendsPrimaryKey = []string{"user_id", "friend_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
}
}
for i := range ForeignKeys {
if column == ForeignKeys[i] {
return true
}
}
return false
}
// Note that the variables below are initialized by the runtime
// package on the initialization of the application. Therefore,
// it should be imported in the main as follows:
//
// import _ "entgo.io/ent/entc/integration/hooks/ent/runtime"
var (
Hooks [2]ent.Hook
// DefaultVersion holds the default value on creation for the "version" field.
DefaultVersion int
// DefaultActive holds the default value on creation for the "active" field.
DefaultActive bool
)
// 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()
}
// ByVersion orders the results by the version field.
func ByVersion(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldVersion, opts...).ToFunc()
}
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, opts...).ToFunc()
}
// ByWorth orders the results by the worth field.
func ByWorth(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldWorth, opts...).ToFunc()
}
// ByPassword orders the results by the password field.
func ByPassword(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPassword, opts...).ToFunc()
}
// ByActive orders the results by the active field.
func ByActive(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldActive, opts...).ToFunc()
}
// ByCardsCount orders the results by cards count.
func ByCardsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newCardsStep(), opts...)
}
}
// ByCards orders the results by cards terms.
func ByCards(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newCardsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// 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...)...)
}
}
// 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...)...)
}
}
// ByBestFriendField orders the results by best_friend field.
func ByBestFriendField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newBestFriendStep(), sql.OrderByField(field, opts...))
}
}
func newCardsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(CardsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, CardsTable, CardsColumn),
)
}
func newPetsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(PetsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, PetsTable, PetsColumn),
)
}
func newFriendsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, FriendsTable, FriendsPrimaryKey...),
)
}
func newBestFriendStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2O, false, BestFriendTable, BestFriendColumn),
)
}

View File

@@ -0,0 +1,430 @@
// 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/hooks/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))
}
// Version applies equality check predicate on the "version" field. It's identical to VersionEQ.
func Version(v int) predicate.User {
return predicate.User(sql.FieldEQ(FieldVersion, v))
}
// 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))
}
// Worth applies equality check predicate on the "worth" field. It's identical to WorthEQ.
func Worth(v uint) predicate.User {
return predicate.User(sql.FieldEQ(FieldWorth, v))
}
// Password applies equality check predicate on the "password" field. It's identical to PasswordEQ.
func Password(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldPassword, v))
}
// Active applies equality check predicate on the "active" field. It's identical to ActiveEQ.
func Active(v bool) predicate.User {
return predicate.User(sql.FieldEQ(FieldActive, v))
}
// VersionEQ applies the EQ predicate on the "version" field.
func VersionEQ(v int) predicate.User {
return predicate.User(sql.FieldEQ(FieldVersion, v))
}
// VersionNEQ applies the NEQ predicate on the "version" field.
func VersionNEQ(v int) predicate.User {
return predicate.User(sql.FieldNEQ(FieldVersion, v))
}
// VersionIn applies the In predicate on the "version" field.
func VersionIn(vs ...int) predicate.User {
return predicate.User(sql.FieldIn(FieldVersion, vs...))
}
// VersionNotIn applies the NotIn predicate on the "version" field.
func VersionNotIn(vs ...int) predicate.User {
return predicate.User(sql.FieldNotIn(FieldVersion, vs...))
}
// VersionGT applies the GT predicate on the "version" field.
func VersionGT(v int) predicate.User {
return predicate.User(sql.FieldGT(FieldVersion, v))
}
// VersionGTE applies the GTE predicate on the "version" field.
func VersionGTE(v int) predicate.User {
return predicate.User(sql.FieldGTE(FieldVersion, v))
}
// VersionLT applies the LT predicate on the "version" field.
func VersionLT(v int) predicate.User {
return predicate.User(sql.FieldLT(FieldVersion, v))
}
// VersionLTE applies the LTE predicate on the "version" field.
func VersionLTE(v int) predicate.User {
return predicate.User(sql.FieldLTE(FieldVersion, 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))
}
// WorthEQ applies the EQ predicate on the "worth" field.
func WorthEQ(v uint) predicate.User {
return predicate.User(sql.FieldEQ(FieldWorth, v))
}
// WorthNEQ applies the NEQ predicate on the "worth" field.
func WorthNEQ(v uint) predicate.User {
return predicate.User(sql.FieldNEQ(FieldWorth, v))
}
// WorthIn applies the In predicate on the "worth" field.
func WorthIn(vs ...uint) predicate.User {
return predicate.User(sql.FieldIn(FieldWorth, vs...))
}
// WorthNotIn applies the NotIn predicate on the "worth" field.
func WorthNotIn(vs ...uint) predicate.User {
return predicate.User(sql.FieldNotIn(FieldWorth, vs...))
}
// WorthGT applies the GT predicate on the "worth" field.
func WorthGT(v uint) predicate.User {
return predicate.User(sql.FieldGT(FieldWorth, v))
}
// WorthGTE applies the GTE predicate on the "worth" field.
func WorthGTE(v uint) predicate.User {
return predicate.User(sql.FieldGTE(FieldWorth, v))
}
// WorthLT applies the LT predicate on the "worth" field.
func WorthLT(v uint) predicate.User {
return predicate.User(sql.FieldLT(FieldWorth, v))
}
// WorthLTE applies the LTE predicate on the "worth" field.
func WorthLTE(v uint) predicate.User {
return predicate.User(sql.FieldLTE(FieldWorth, v))
}
// WorthIsNil applies the IsNil predicate on the "worth" field.
func WorthIsNil() predicate.User {
return predicate.User(sql.FieldIsNull(FieldWorth))
}
// WorthNotNil applies the NotNil predicate on the "worth" field.
func WorthNotNil() predicate.User {
return predicate.User(sql.FieldNotNull(FieldWorth))
}
// PasswordEQ applies the EQ predicate on the "password" field.
func PasswordEQ(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldPassword, v))
}
// PasswordNEQ applies the NEQ predicate on the "password" field.
func PasswordNEQ(v string) predicate.User {
return predicate.User(sql.FieldNEQ(FieldPassword, v))
}
// PasswordIn applies the In predicate on the "password" field.
func PasswordIn(vs ...string) predicate.User {
return predicate.User(sql.FieldIn(FieldPassword, vs...))
}
// PasswordNotIn applies the NotIn predicate on the "password" field.
func PasswordNotIn(vs ...string) predicate.User {
return predicate.User(sql.FieldNotIn(FieldPassword, vs...))
}
// PasswordGT applies the GT predicate on the "password" field.
func PasswordGT(v string) predicate.User {
return predicate.User(sql.FieldGT(FieldPassword, v))
}
// PasswordGTE applies the GTE predicate on the "password" field.
func PasswordGTE(v string) predicate.User {
return predicate.User(sql.FieldGTE(FieldPassword, v))
}
// PasswordLT applies the LT predicate on the "password" field.
func PasswordLT(v string) predicate.User {
return predicate.User(sql.FieldLT(FieldPassword, v))
}
// PasswordLTE applies the LTE predicate on the "password" field.
func PasswordLTE(v string) predicate.User {
return predicate.User(sql.FieldLTE(FieldPassword, v))
}
// PasswordContains applies the Contains predicate on the "password" field.
func PasswordContains(v string) predicate.User {
return predicate.User(sql.FieldContains(FieldPassword, v))
}
// PasswordHasPrefix applies the HasPrefix predicate on the "password" field.
func PasswordHasPrefix(v string) predicate.User {
return predicate.User(sql.FieldHasPrefix(FieldPassword, v))
}
// PasswordHasSuffix applies the HasSuffix predicate on the "password" field.
func PasswordHasSuffix(v string) predicate.User {
return predicate.User(sql.FieldHasSuffix(FieldPassword, v))
}
// PasswordIsNil applies the IsNil predicate on the "password" field.
func PasswordIsNil() predicate.User {
return predicate.User(sql.FieldIsNull(FieldPassword))
}
// PasswordNotNil applies the NotNil predicate on the "password" field.
func PasswordNotNil() predicate.User {
return predicate.User(sql.FieldNotNull(FieldPassword))
}
// PasswordEqualFold applies the EqualFold predicate on the "password" field.
func PasswordEqualFold(v string) predicate.User {
return predicate.User(sql.FieldEqualFold(FieldPassword, v))
}
// PasswordContainsFold applies the ContainsFold predicate on the "password" field.
func PasswordContainsFold(v string) predicate.User {
return predicate.User(sql.FieldContainsFold(FieldPassword, v))
}
// ActiveEQ applies the EQ predicate on the "active" field.
func ActiveEQ(v bool) predicate.User {
return predicate.User(sql.FieldEQ(FieldActive, v))
}
// ActiveNEQ applies the NEQ predicate on the "active" field.
func ActiveNEQ(v bool) predicate.User {
return predicate.User(sql.FieldNEQ(FieldActive, v))
}
// HasCards applies the HasEdge predicate on the "cards" edge.
func HasCards() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, CardsTable, CardsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasCardsWith applies the HasEdge predicate on the "cards" edge with a given conditions (other predicates).
func HasCardsWith(preds ...predicate.Card) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newCardsStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// 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),
)
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()
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...),
)
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()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasBestFriend applies the HasEdge predicate on the "best_friend" edge.
func HasBestFriend() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2O, false, BestFriendTable, BestFriendColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasBestFriendWith applies the HasEdge predicate on the "best_friend" edge with a given conditions (other predicates).
func HasBestFriendWith(preds ...predicate.User) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newBestFriendStep()
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,413 @@
// 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/hooks/ent/card"
"entgo.io/ent/entc/integration/hooks/ent/pet"
"entgo.io/ent/entc/integration/hooks/ent/user"
"entgo.io/ent/schema/field"
)
// UserCreate is the builder for creating a User entity.
type UserCreate struct {
config
mutation *UserMutation
hooks []Hook
}
// SetVersion sets the "version" field.
func (_c *UserCreate) SetVersion(v int) *UserCreate {
_c.mutation.SetVersion(v)
return _c
}
// SetNillableVersion sets the "version" field if the given value is not nil.
func (_c *UserCreate) SetNillableVersion(v *int) *UserCreate {
if v != nil {
_c.SetVersion(*v)
}
return _c
}
// SetName sets the "name" field.
func (_c *UserCreate) SetName(v string) *UserCreate {
_c.mutation.SetName(v)
return _c
}
// SetWorth sets the "worth" field.
func (_c *UserCreate) SetWorth(v uint) *UserCreate {
_c.mutation.SetWorth(v)
return _c
}
// SetNillableWorth sets the "worth" field if the given value is not nil.
func (_c *UserCreate) SetNillableWorth(v *uint) *UserCreate {
if v != nil {
_c.SetWorth(*v)
}
return _c
}
// SetPassword sets the "password" field.
func (_c *UserCreate) SetPassword(v string) *UserCreate {
_c.mutation.SetPassword(v)
return _c
}
// SetNillablePassword sets the "password" field if the given value is not nil.
func (_c *UserCreate) SetNillablePassword(v *string) *UserCreate {
if v != nil {
_c.SetPassword(*v)
}
return _c
}
// SetActive sets the "active" field.
func (_c *UserCreate) SetActive(v bool) *UserCreate {
_c.mutation.SetActive(v)
return _c
}
// SetNillableActive sets the "active" field if the given value is not nil.
func (_c *UserCreate) SetNillableActive(v *bool) *UserCreate {
if v != nil {
_c.SetActive(*v)
}
return _c
}
// AddCardIDs adds the "cards" edge to the Card entity by IDs.
func (_c *UserCreate) AddCardIDs(ids ...int) *UserCreate {
_c.mutation.AddCardIDs(ids...)
return _c
}
// AddCards adds the "cards" edges to the Card entity.
func (_c *UserCreate) AddCards(v ...*Card) *UserCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddCardIDs(ids...)
}
// 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...)
}
// 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...)
}
// SetBestFriendID sets the "best_friend" edge to the User entity by ID.
func (_c *UserCreate) SetBestFriendID(id int) *UserCreate {
_c.mutation.SetBestFriendID(id)
return _c
}
// SetNillableBestFriendID sets the "best_friend" edge to the User entity by ID if the given value is not nil.
func (_c *UserCreate) SetNillableBestFriendID(id *int) *UserCreate {
if id != nil {
_c = _c.SetBestFriendID(*id)
}
return _c
}
// SetBestFriend sets the "best_friend" edge to the User entity.
func (_c *UserCreate) SetBestFriend(v *User) *UserCreate {
return _c.SetBestFriendID(v.ID)
}
// 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) {
if err := _c.defaults(); err != nil {
return nil, err
}
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() error {
if _, ok := _c.mutation.Version(); !ok {
v := user.DefaultVersion
_c.mutation.SetVersion(v)
}
if _, ok := _c.mutation.Active(); !ok {
v := user.DefaultActive
_c.mutation.SetActive(v)
}
return nil
}
// check runs all checks and user-defined validators on the builder.
func (_c *UserCreate) check() error {
if _, ok := _c.mutation.Version(); !ok {
return &ValidationError{Name: "version", err: errors.New(`ent: missing required field "User.version"`)}
}
if _, ok := _c.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "User.name"`)}
}
if _, ok := _c.mutation.Active(); !ok {
return &ValidationError{Name: "active", err: errors.New(`ent: missing required field "User.active"`)}
}
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))
)
if value, ok := _c.mutation.Version(); ok {
_spec.SetField(user.FieldVersion, field.TypeInt, value)
_node.Version = value
}
if value, ok := _c.mutation.Name(); ok {
_spec.SetField(user.FieldName, field.TypeString, value)
_node.Name = value
}
if value, ok := _c.mutation.Worth(); ok {
_spec.SetField(user.FieldWorth, field.TypeUint, value)
_node.Worth = value
}
if value, ok := _c.mutation.Password(); ok {
_spec.SetField(user.FieldPassword, field.TypeString, value)
_node.Password = value
}
if value, ok := _c.mutation.Active(); ok {
_spec.SetField(user.FieldActive, field.TypeBool, value)
_node.Active = value
}
if nodes := _c.mutation.CardsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.CardsTable,
Columns: []string{user.CardsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(card.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
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),
},
}
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),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.BestFriendIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Inverse: false,
Table: user.BestFriendTable,
Columns: []string{user.BestFriendColumn},
Bidi: true,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.user_best_friend = &nodes[0]
_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,92 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/hooks/ent/predicate"
"entgo.io/ent/entc/integration/hooks/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))
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)
}
}

View File

@@ -0,0 +1,872 @@
// 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/hooks/ent/card"
"entgo.io/ent/entc/integration/hooks/ent/pet"
"entgo.io/ent/entc/integration/hooks/ent/predicate"
"entgo.io/ent/entc/integration/hooks/ent/user"
"entgo.io/ent/schema/field"
)
// UserQuery is the builder for querying User entities.
type UserQuery struct {
config
ctx *QueryContext
order []user.OrderOption
inters []Interceptor
predicates []predicate.User
withCards *CardQuery
withPets *PetQuery
withFriends *UserQuery
withBestFriend *UserQuery
withFKs bool
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the UserQuery builder.
func (_q *UserQuery) Where(ps ...predicate.User) *UserQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *UserQuery) Limit(limit int) *UserQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *UserQuery) Offset(offset int) *UserQuery {
_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 *UserQuery) Unique(unique bool) *UserQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *UserQuery) Order(o ...user.OrderOption) *UserQuery {
_q.order = append(_q.order, o...)
return _q
}
// QueryCards chains the current query on the "cards" edge.
func (_q *UserQuery) QueryCards() *CardQuery {
query := (&CardClient{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(user.Table, user.FieldID, selector),
sqlgraph.To(card.Table, card.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, user.CardsTable, user.CardsColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryPets chains the current query on the "pets" edge.
func (_q *UserQuery) QueryPets() *PetQuery {
query := (&PetClient{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(user.Table, user.FieldID, selector),
sqlgraph.To(pet.Table, pet.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, user.PetsTable, user.PetsColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryFriends chains the current query on the "friends" edge.
func (_q *UserQuery) QueryFriends() *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(user.Table, user.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, user.FriendsTable, user.FriendsPrimaryKey...),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryBestFriend chains the current query on the "best_friend" edge.
func (_q *UserQuery) QueryBestFriend() *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(user.Table, user.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.O2O, false, user.BestFriendTable, user.BestFriendColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first User entity from the query.
// Returns a *NotFoundError when no User was found.
func (_q *UserQuery) First(ctx context.Context) (*User, 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{user.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *UserQuery) FirstX(ctx context.Context) *User {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first User ID from the query.
// Returns a *NotFoundError when no User ID was found.
func (_q *UserQuery) 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{user.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *UserQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single User entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one User entity is found.
// Returns a *NotFoundError when no User entities are found.
func (_q *UserQuery) Only(ctx context.Context) (*User, 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{user.Label}
default:
return nil, &NotSingularError{user.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *UserQuery) OnlyX(ctx context.Context) *User {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only User ID in the query.
// Returns a *NotSingularError when more than one User ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *UserQuery) 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{user.Label}
default:
err = &NotSingularError{user.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *UserQuery) 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 Users.
func (_q *UserQuery) All(ctx context.Context) ([]*User, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*User, *UserQuery]()
return withInterceptors[[]*User](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *UserQuery) AllX(ctx context.Context) []*User {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of User IDs.
func (_q *UserQuery) 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(user.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *UserQuery) 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 *UserQuery) 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[*UserQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *UserQuery) 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 *UserQuery) 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 *UserQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the UserQuery 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 *UserQuery) Clone() *UserQuery {
if _q == nil {
return nil
}
return &UserQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]user.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.User{}, _q.predicates...),
withCards: _q.withCards.Clone(),
withPets: _q.withPets.Clone(),
withFriends: _q.withFriends.Clone(),
withBestFriend: _q.withBestFriend.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// WithCards tells the query-builder to eager-load the nodes that are connected to
// the "cards" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *UserQuery) WithCards(opts ...func(*CardQuery)) *UserQuery {
query := (&CardClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withCards = query
return _q
}
// WithPets tells the query-builder to eager-load the nodes that are connected to
// the "pets" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *UserQuery) WithPets(opts ...func(*PetQuery)) *UserQuery {
query := (&PetClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withPets = query
return _q
}
// WithFriends tells the query-builder to eager-load the nodes that are connected to
// the "friends" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *UserQuery) WithFriends(opts ...func(*UserQuery)) *UserQuery {
query := (&UserClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withFriends = query
return _q
}
// WithBestFriend tells the query-builder to eager-load the nodes that are connected to
// the "best_friend" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *UserQuery) WithBestFriend(opts ...func(*UserQuery)) *UserQuery {
query := (&UserClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withBestFriend = 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 {
// Version int `json:"version,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.User.Query().
// GroupBy(user.FieldVersion).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *UserQuery) GroupBy(field string, fields ...string) *UserGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &UserGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = user.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 {
// Version int `json:"version,omitempty"`
// }
//
// client.User.Query().
// Select(user.FieldVersion).
// Scan(ctx, &v)
func (_q *UserQuery) Select(fields ...string) *UserSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &UserSelect{UserQuery: _q}
sbuild.label = user.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a UserSelect configured with the given aggregations.
func (_q *UserQuery) Aggregate(fns ...AggregateFunc) *UserSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *UserQuery) 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 !user.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 *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, error) {
var (
nodes = []*User{}
withFKs = _q.withFKs
_spec = _q.querySpec()
loadedTypes = [4]bool{
_q.withCards != nil,
_q.withPets != nil,
_q.withFriends != nil,
_q.withBestFriend != nil,
}
)
if _q.withBestFriend != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, user.ForeignKeys...)
}
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*User).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &User{config: _q.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := _q.withCards; query != nil {
if err := _q.loadCards(ctx, query, nodes,
func(n *User) { n.Edges.Cards = []*Card{} },
func(n *User, e *Card) { n.Edges.Cards = append(n.Edges.Cards, e) }); err != nil {
return nil, err
}
}
if query := _q.withPets; query != nil {
if err := _q.loadPets(ctx, query, nodes,
func(n *User) { n.Edges.Pets = []*Pet{} },
func(n *User, e *Pet) { n.Edges.Pets = append(n.Edges.Pets, e) }); err != nil {
return nil, err
}
}
if query := _q.withFriends; query != nil {
if err := _q.loadFriends(ctx, query, nodes,
func(n *User) { n.Edges.Friends = []*User{} },
func(n *User, e *User) { n.Edges.Friends = append(n.Edges.Friends, e) }); err != nil {
return nil, err
}
}
if query := _q.withBestFriend; query != nil {
if err := _q.loadBestFriend(ctx, query, nodes, nil,
func(n *User, e *User) { n.Edges.BestFriend = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *UserQuery) loadCards(ctx context.Context, query *CardQuery, nodes []*User, init func(*User), assign func(*User, *Card)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[int]*User)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.Card(func(s *sql.Selector) {
s.Where(sql.InValues(s.C(user.CardsColumn), fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.user_cards
if fk == nil {
return fmt.Errorf(`foreign-key "user_cards" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected referenced foreign-key "user_cards" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (_q *UserQuery) loadPets(ctx context.Context, query *PetQuery, nodes []*User, init func(*User), assign func(*User, *Pet)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[int]*User)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.Pet(func(s *sql.Selector) {
s.Where(sql.InValues(s.C(user.PetsColumn), fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.user_pets
if fk == nil {
return fmt.Errorf(`foreign-key "user_pets" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected referenced foreign-key "user_pets" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (_q *UserQuery) loadFriends(ctx context.Context, query *UserQuery, nodes []*User, init func(*User), assign func(*User, *User)) error {
edgeIDs := make([]driver.Value, len(nodes))
byID := make(map[int]*User)
nids := make(map[int]map[*User]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(user.FriendsTable)
s.Join(joinT).On(s.C(user.FieldID), joinT.C(user.FriendsPrimaryKey[1]))
s.Where(sql.InValues(joinT.C(user.FriendsPrimaryKey[0]), edgeIDs...))
columns := s.SelectedColumns()
s.Select(joinT.C(user.FriendsPrimaryKey[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[*User]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 "friends" node returned %v`, n.ID)
}
for kn := range nodes {
assign(kn, n)
}
}
return nil
}
func (_q *UserQuery) loadBestFriend(ctx context.Context, query *UserQuery, nodes []*User, init func(*User), assign func(*User, *User)) error {
ids := make([]int, 0, len(nodes))
nodeids := make(map[int][]*User)
for i := range nodes {
if nodes[i].user_best_friend == nil {
continue
}
fk := *nodes[i].user_best_friend
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_best_friend" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *UserQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *UserQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.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, user.FieldID)
for i := range fields {
if fields[i] != user.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 *UserQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(user.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = user.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// UserGroupBy is the group-by builder for User entities.
type UserGroupBy struct {
selector
build *UserQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *UserGroupBy) Aggregate(fns ...AggregateFunc) *UserGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *UserGroupBy) 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[*UserQuery, *UserGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *UserGroupBy) sqlScan(ctx context.Context, root *UserQuery, 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)
}
// UserSelect is the builder for selecting fields of User entities.
type UserSelect struct {
*UserQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *UserSelect) Aggregate(fns ...AggregateFunc) *UserSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *UserSelect) 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[*UserQuery, *UserSelect](ctx, _s.UserQuery, _s, _s.inters, v)
}
func (_s *UserSelect) sqlScan(ctx context.Context, root *UserQuery, 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)
}

File diff suppressed because it is too large Load Diff