snapshot of https://github.com/ent/ent.git (master, 2026-09-15; blobs > 131072B omitted)
This commit is contained in:
31
examples/migration/README.md
Normal file
31
examples/migration/README.md
Normal file
@@ -0,0 +1,31 @@
|
||||
# Versioned Migration Example
|
||||
|
||||
The full reference example for https://entgo.io/docs/versioned-migrations#create-a-migration-files-generator.
|
||||
|
||||
### Migration directory
|
||||
|
||||
Versioned migration files exists under `ent/migrate/migrations`.
|
||||
|
||||
### Changes to the Ent schema
|
||||
|
||||
1\. Change the `ent/schema`.
|
||||
|
||||
2\. Run `go generate ./ent`
|
||||
|
||||
### Generate a new migration file
|
||||
|
||||
```bash
|
||||
atlas migrate diff <migration_name> \
|
||||
--dir "file://ent/migrate/migrations" \
|
||||
--to "ent://ent/schema" \
|
||||
--dev-url "docker://mysql/8/ent"
|
||||
```
|
||||
|
||||
### Run migration linting
|
||||
|
||||
```bash
|
||||
atlas migrate lint \
|
||||
--dev-url="docker://mysql/8/dev" \
|
||||
--dir="file://ent/migrate/migrations" \
|
||||
--latest=1
|
||||
```
|
||||
199
examples/migration/ent/card.go
Normal file
199
examples/migration/ent/card.go
Normal file
@@ -0,0 +1,199 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/examples/migration/ent/card"
|
||||
"entgo.io/ent/examples/migration/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"`
|
||||
// Type holds the value of the "type" field.
|
||||
Type string `json:"type,omitempty"`
|
||||
// NumberHash holds the value of the "number_hash" field.
|
||||
NumberHash string `json:"number_hash,omitempty"`
|
||||
// CvvHash holds the value of the "cvv_hash" field.
|
||||
CvvHash string `json:"cvv_hash,omitempty"`
|
||||
// ExpiresAt holds the value of the "expires_at" field.
|
||||
ExpiresAt time.Time `json:"expires_at,omitempty"`
|
||||
// OwnerID holds the value of the "owner_id" field.
|
||||
OwnerID int `json:"owner_id,omitempty"`
|
||||
// Edges holds the relations/edges for other nodes in the graph.
|
||||
// The values are being populated by the CardQuery when eager-loading is set.
|
||||
Edges CardEdges `json:"edges"`
|
||||
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"`
|
||||
// Payments holds the value of the payments edge.
|
||||
Payments []*Payment `json:"payments,omitempty"`
|
||||
// loadedTypes holds the information for reporting if a
|
||||
// type was loaded (or requested) in eager-loading or not.
|
||||
loadedTypes [2]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"}
|
||||
}
|
||||
|
||||
// PaymentsOrErr returns the Payments value or an error if the edge
|
||||
// was not loaded in eager-loading.
|
||||
func (e CardEdges) PaymentsOrErr() ([]*Payment, error) {
|
||||
if e.loadedTypes[1] {
|
||||
return e.Payments, nil
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "payments"}
|
||||
}
|
||||
|
||||
// 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, card.FieldOwnerID:
|
||||
values[i] = new(sql.NullInt64)
|
||||
case card.FieldType, card.FieldNumberHash, card.FieldCvvHash:
|
||||
values[i] = new(sql.NullString)
|
||||
case card.FieldExpiresAt:
|
||||
values[i] = new(sql.NullTime)
|
||||
default:
|
||||
values[i] = new(sql.UnknownType)
|
||||
}
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// assignValues assigns the values that were returned from sql.Rows (after scanning)
|
||||
// to the 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.FieldType:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field type", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Type = value.String
|
||||
}
|
||||
case card.FieldNumberHash:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field number_hash", values[i])
|
||||
} else if value.Valid {
|
||||
_m.NumberHash = value.String
|
||||
}
|
||||
case card.FieldCvvHash:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field cvv_hash", values[i])
|
||||
} else if value.Valid {
|
||||
_m.CvvHash = value.String
|
||||
}
|
||||
case card.FieldExpiresAt:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field expires_at", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ExpiresAt = value.Time
|
||||
}
|
||||
case card.FieldOwnerID:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field owner_id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.OwnerID = int(value.Int64)
|
||||
}
|
||||
default:
|
||||
_m.selectValues.Set(columns[i], values[i])
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Value returns the ent.Value that was dynamically selected and assigned to the 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)
|
||||
}
|
||||
|
||||
// QueryPayments queries the "payments" edge of the Card entity.
|
||||
func (_m *Card) QueryPayments() *PaymentQuery {
|
||||
return NewCardClient(_m.config).QueryPayments(_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("type=")
|
||||
builder.WriteString(_m.Type)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("number_hash=")
|
||||
builder.WriteString(_m.NumberHash)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("cvv_hash=")
|
||||
builder.WriteString(_m.CvvHash)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("expires_at=")
|
||||
builder.WriteString(_m.ExpiresAt.Format(time.ANSIC))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("owner_id=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.OwnerID))
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// Cards is a parsable slice of Card.
|
||||
type Cards []*Card
|
||||
144
examples/migration/ent/card/card.go
Normal file
144
examples/migration/ent/card/card.go
Normal file
@@ -0,0 +1,144 @@
|
||||
// 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 (
|
||||
"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"
|
||||
// FieldType holds the string denoting the type field in the database.
|
||||
FieldType = "type"
|
||||
// FieldNumberHash holds the string denoting the number_hash field in the database.
|
||||
FieldNumberHash = "number_hash"
|
||||
// FieldCvvHash holds the string denoting the cvv_hash field in the database.
|
||||
FieldCvvHash = "cvv_hash"
|
||||
// FieldExpiresAt holds the string denoting the expires_at field in the database.
|
||||
FieldExpiresAt = "expires_at"
|
||||
// FieldOwnerID holds the string denoting the owner_id field in the database.
|
||||
FieldOwnerID = "owner_id"
|
||||
// EdgeOwner holds the string denoting the owner edge name in mutations.
|
||||
EdgeOwner = "owner"
|
||||
// EdgePayments holds the string denoting the payments edge name in mutations.
|
||||
EdgePayments = "payments"
|
||||
// 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 = "owner_id"
|
||||
// PaymentsTable is the table that holds the payments relation/edge.
|
||||
PaymentsTable = "payments"
|
||||
// PaymentsInverseTable is the table name for the Payment entity.
|
||||
// It exists in this package in order to avoid circular dependency with the "payment" package.
|
||||
PaymentsInverseTable = "payments"
|
||||
// PaymentsColumn is the table column denoting the payments relation/edge.
|
||||
PaymentsColumn = "card_id"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for card fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldType,
|
||||
FieldNumberHash,
|
||||
FieldCvvHash,
|
||||
FieldExpiresAt,
|
||||
FieldOwnerID,
|
||||
}
|
||||
|
||||
// ValidColumn reports if the column name is valid (part of the table columns).
|
||||
func ValidColumn(column string) bool {
|
||||
for i := range Columns {
|
||||
if column == Columns[i] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var (
|
||||
// DefaultType holds the default value on creation for the "type" field.
|
||||
DefaultType string
|
||||
// DefaultOwnerID holds the default value on creation for the "owner_id" field.
|
||||
DefaultOwnerID int
|
||||
)
|
||||
|
||||
// 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()
|
||||
}
|
||||
|
||||
// ByType orders the results by the type field.
|
||||
func ByType(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldType, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByNumberHash orders the results by the number_hash field.
|
||||
func ByNumberHash(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldNumberHash, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByCvvHash orders the results by the cvv_hash field.
|
||||
func ByCvvHash(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldCvvHash, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByExpiresAt orders the results by the expires_at field.
|
||||
func ByExpiresAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldExpiresAt, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByOwnerID orders the results by the owner_id field.
|
||||
func ByOwnerID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldOwnerID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByOwnerField orders the results by owner field.
|
||||
func ByOwnerField(field string, opts ...sql.OrderTermOption) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborTerms(s, newOwnerStep(), sql.OrderByField(field, opts...))
|
||||
}
|
||||
}
|
||||
|
||||
// ByPaymentsCount orders the results by payments count.
|
||||
func ByPaymentsCount(opts ...sql.OrderTermOption) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborsCount(s, newPaymentsStep(), opts...)
|
||||
}
|
||||
}
|
||||
|
||||
// ByPayments orders the results by payments terms.
|
||||
func ByPayments(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborTerms(s, newPaymentsStep(), append([]sql.OrderTerm{term}, terms...)...)
|
||||
}
|
||||
}
|
||||
func newOwnerStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(OwnerInverseTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, OwnerTable, OwnerColumn),
|
||||
)
|
||||
}
|
||||
func newPaymentsStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(PaymentsInverseTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, PaymentsTable, PaymentsColumn),
|
||||
)
|
||||
}
|
||||
538
examples/migration/ent/card/mutation.go
Normal file
538
examples/migration/ent/card/mutation.go
Normal file
@@ -0,0 +1,538 @@
|
||||
// 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/examples/migration/ent/predicate"
|
||||
)
|
||||
|
||||
// Mutation represents an operation that mutates the Card nodes in the graph.
|
||||
type Mutation struct {
|
||||
op ent.Op
|
||||
typ string
|
||||
_type *string
|
||||
number_hash *string
|
||||
cvv_hash *string
|
||||
expires_at *time.Time
|
||||
clearedFields map[string]struct{}
|
||||
owner *int
|
||||
clearedowner bool
|
||||
payments map[int]struct{}
|
||||
removedpayments map[int]struct{}
|
||||
clearedpayments 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
|
||||
}
|
||||
|
||||
// SetType sets the "type" field.
|
||||
func (m *Mutation) SetType(s string) {
|
||||
m._type = &s
|
||||
}
|
||||
|
||||
// GetType returns the value of the "type" field in the mutation.
|
||||
func (m *Mutation) GetType() (r string, exists bool) {
|
||||
v := m._type
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetType resets all changes to the "type" field.
|
||||
func (m *Mutation) ResetType() {
|
||||
m._type = nil
|
||||
}
|
||||
|
||||
// SetNumberHash sets the "number_hash" field.
|
||||
func (m *Mutation) SetNumberHash(s string) {
|
||||
m.number_hash = &s
|
||||
}
|
||||
|
||||
// NumberHash returns the value of the "number_hash" field in the mutation.
|
||||
func (m *Mutation) NumberHash() (r string, exists bool) {
|
||||
v := m.number_hash
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetNumberHash resets all changes to the "number_hash" field.
|
||||
func (m *Mutation) ResetNumberHash() {
|
||||
m.number_hash = nil
|
||||
}
|
||||
|
||||
// SetCvvHash sets the "cvv_hash" field.
|
||||
func (m *Mutation) SetCvvHash(s string) {
|
||||
m.cvv_hash = &s
|
||||
}
|
||||
|
||||
// CvvHash returns the value of the "cvv_hash" field in the mutation.
|
||||
func (m *Mutation) CvvHash() (r string, exists bool) {
|
||||
v := m.cvv_hash
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetCvvHash resets all changes to the "cvv_hash" field.
|
||||
func (m *Mutation) ResetCvvHash() {
|
||||
m.cvv_hash = nil
|
||||
}
|
||||
|
||||
// SetExpiresAt sets the "expires_at" field.
|
||||
func (m *Mutation) SetExpiresAt(t time.Time) {
|
||||
m.expires_at = &t
|
||||
}
|
||||
|
||||
// ExpiresAt returns the value of the "expires_at" field in the mutation.
|
||||
func (m *Mutation) ExpiresAt() (r time.Time, exists bool) {
|
||||
v := m.expires_at
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ClearExpiresAt clears the value of the "expires_at" field.
|
||||
func (m *Mutation) ClearExpiresAt() {
|
||||
m.expires_at = nil
|
||||
m.clearedFields[FieldExpiresAt] = struct{}{}
|
||||
}
|
||||
|
||||
// ExpiresAtCleared returns if the "expires_at" field was cleared in this mutation.
|
||||
func (m *Mutation) ExpiresAtCleared() bool {
|
||||
_, ok := m.clearedFields[FieldExpiresAt]
|
||||
return ok
|
||||
}
|
||||
|
||||
// ResetExpiresAt resets all changes to the "expires_at" field.
|
||||
func (m *Mutation) ResetExpiresAt() {
|
||||
m.expires_at = nil
|
||||
delete(m.clearedFields, FieldExpiresAt)
|
||||
}
|
||||
|
||||
// SetOwnerID sets the "owner_id" field.
|
||||
func (m *Mutation) SetOwnerID(i int) {
|
||||
m.owner = &i
|
||||
}
|
||||
|
||||
// OwnerID returns the value of the "owner_id" field in the mutation.
|
||||
func (m *Mutation) OwnerID() (r int, exists bool) {
|
||||
v := m.owner
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetOwnerID resets all changes to the "owner_id" field.
|
||||
func (m *Mutation) ResetOwnerID() {
|
||||
m.owner = nil
|
||||
}
|
||||
|
||||
// ClearOwner clears the "owner" edge to the User entity.
|
||||
func (m *Mutation) ClearOwner() {
|
||||
m.clearedowner = true
|
||||
m.clearedFields[FieldOwnerID] = struct{}{}
|
||||
}
|
||||
|
||||
// OwnerCleared reports if the "owner" edge to the User entity was cleared.
|
||||
func (m *Mutation) OwnerCleared() bool {
|
||||
return m.clearedowner
|
||||
}
|
||||
|
||||
// OwnerIDs returns the "owner" edge IDs in the mutation.
|
||||
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
|
||||
// OwnerID instead. It exists only for internal usage by the builders.
|
||||
func (m *Mutation) OwnerIDs() (ids []int) {
|
||||
if id := m.owner; id != nil {
|
||||
ids = append(ids, *id)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ResetOwner resets all changes to the "owner" edge.
|
||||
func (m *Mutation) ResetOwner() {
|
||||
m.owner = nil
|
||||
m.clearedowner = false
|
||||
}
|
||||
|
||||
// AddPaymentIDs adds the "payments" edge to the Payment entity by ids.
|
||||
func (m *Mutation) AddPaymentIDs(ids ...int) {
|
||||
if m.payments == nil {
|
||||
m.payments = make(map[int]struct{})
|
||||
}
|
||||
for i := range ids {
|
||||
m.payments[ids[i]] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
// ClearPayments clears the "payments" edge to the Payment entity.
|
||||
func (m *Mutation) ClearPayments() {
|
||||
m.clearedpayments = true
|
||||
}
|
||||
|
||||
// PaymentsCleared reports if the "payments" edge to the Payment entity was cleared.
|
||||
func (m *Mutation) PaymentsCleared() bool {
|
||||
return m.clearedpayments
|
||||
}
|
||||
|
||||
// RemovePaymentIDs removes the "payments" edge to the Payment entity by IDs.
|
||||
func (m *Mutation) RemovePaymentIDs(ids ...int) {
|
||||
if m.removedpayments == nil {
|
||||
m.removedpayments = make(map[int]struct{})
|
||||
}
|
||||
for i := range ids {
|
||||
delete(m.payments, ids[i])
|
||||
m.removedpayments[ids[i]] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
// RemovedPayments returns the removed IDs of the "payments" edge to the Payment entity.
|
||||
func (m *Mutation) RemovedPaymentsIDs() (ids []int) {
|
||||
for id := range m.removedpayments {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// PaymentsIDs returns the "payments" edge IDs in the mutation.
|
||||
func (m *Mutation) PaymentsIDs() (ids []int) {
|
||||
for id := range m.payments {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ResetPayments resets all changes to the "payments" edge.
|
||||
func (m *Mutation) ResetPayments() {
|
||||
m.payments = nil
|
||||
m.clearedpayments = false
|
||||
m.removedpayments = nil
|
||||
}
|
||||
|
||||
// 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._type != nil {
|
||||
fields = append(fields, FieldType)
|
||||
}
|
||||
if m.number_hash != nil {
|
||||
fields = append(fields, FieldNumberHash)
|
||||
}
|
||||
if m.cvv_hash != nil {
|
||||
fields = append(fields, FieldCvvHash)
|
||||
}
|
||||
if m.expires_at != nil {
|
||||
fields = append(fields, FieldExpiresAt)
|
||||
}
|
||||
if m.owner != nil {
|
||||
fields = append(fields, FieldOwnerID)
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
// Field returns the value of a field with the given name. The second boolean
|
||||
// return value indicates that this field was not set, or was not defined in the
|
||||
// schema.
|
||||
func (m *Mutation) Field(name string) (ent.Value, bool) {
|
||||
switch name {
|
||||
case FieldType:
|
||||
return m.GetType()
|
||||
case FieldNumberHash:
|
||||
return m.NumberHash()
|
||||
case FieldCvvHash:
|
||||
return m.CvvHash()
|
||||
case FieldExpiresAt:
|
||||
return m.ExpiresAt()
|
||||
case FieldOwnerID:
|
||||
return m.OwnerID()
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// OldField returns the old value of the field from the database. An error is
|
||||
// returned if the mutation operation is not UpdateOne, or the query to the
|
||||
// database failed.
|
||||
func (m *Mutation) OldField(ctx context.Context, name string) (ent.Value, error) {
|
||||
return nil, fmt.Errorf("unknown 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 FieldType:
|
||||
v, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetType(v)
|
||||
return nil
|
||||
case FieldNumberHash:
|
||||
v, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetNumberHash(v)
|
||||
return nil
|
||||
case FieldCvvHash:
|
||||
v, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetCvvHash(v)
|
||||
return nil
|
||||
case FieldExpiresAt:
|
||||
v, ok := value.(time.Time)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetExpiresAt(v)
|
||||
return nil
|
||||
case FieldOwnerID:
|
||||
v, ok := value.(int)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetOwnerID(v)
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown Card field %s", name)
|
||||
}
|
||||
|
||||
// AddedFields returns all numeric fields that were incremented/decremented during
|
||||
// this mutation.
|
||||
func (m *Mutation) AddedFields() []string {
|
||||
var fields []string
|
||||
return fields
|
||||
}
|
||||
|
||||
// AddedField returns the numeric value that was incremented/decremented on a field
|
||||
// with the given name. The second boolean return value indicates that this field
|
||||
// was not set, or was not defined in the schema.
|
||||
func (m *Mutation) AddedField(name string) (ent.Value, bool) {
|
||||
switch name {
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// AddField adds the value to the field with the given name. It returns an error if
|
||||
// the field is not defined in the schema, or if the type mismatched the field
|
||||
// type.
|
||||
func (m *Mutation) AddField(name string, value ent.Value) error {
|
||||
switch name {
|
||||
}
|
||||
return fmt.Errorf("unknown 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(FieldExpiresAt) {
|
||||
fields = append(fields, FieldExpiresAt)
|
||||
}
|
||||
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 FieldExpiresAt:
|
||||
m.ClearExpiresAt()
|
||||
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 FieldType:
|
||||
m.ResetType()
|
||||
return nil
|
||||
case FieldNumberHash:
|
||||
m.ResetNumberHash()
|
||||
return nil
|
||||
case FieldCvvHash:
|
||||
m.ResetCvvHash()
|
||||
return nil
|
||||
case FieldExpiresAt:
|
||||
m.ResetExpiresAt()
|
||||
return nil
|
||||
case FieldOwnerID:
|
||||
m.ResetOwnerID()
|
||||
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, 2)
|
||||
if m.owner != nil {
|
||||
edges = append(edges, EdgeOwner)
|
||||
}
|
||||
if m.payments != nil {
|
||||
edges = append(edges, EdgePayments)
|
||||
}
|
||||
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}
|
||||
}
|
||||
case EdgePayments:
|
||||
ids := make([]ent.Value, 0, len(m.payments))
|
||||
for id := range m.payments {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemovedEdges returns all edge names that were removed in this mutation.
|
||||
func (m *Mutation) RemovedEdges() []string {
|
||||
edges := make([]string, 0, 2)
|
||||
if m.removedpayments != nil {
|
||||
edges = append(edges, EdgePayments)
|
||||
}
|
||||
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 EdgePayments:
|
||||
ids := make([]ent.Value, 0, len(m.removedpayments))
|
||||
for id := range m.removedpayments {
|
||||
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, 2)
|
||||
if m.clearedowner {
|
||||
edges = append(edges, EdgeOwner)
|
||||
}
|
||||
if m.clearedpayments {
|
||||
edges = append(edges, EdgePayments)
|
||||
}
|
||||
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
|
||||
case EdgePayments:
|
||||
return m.clearedpayments
|
||||
}
|
||||
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
|
||||
case EdgePayments:
|
||||
m.ResetPayments()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown Card edge %s", name)
|
||||
}
|
||||
411
examples/migration/ent/card/where.go
Normal file
411
examples/migration/ent/card/where.go
Normal file
@@ -0,0 +1,411 @@
|
||||
// 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/examples/migration/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))
|
||||
}
|
||||
|
||||
// Type applies equality check predicate on the "type" field. It's identical to TypeEQ.
|
||||
func Type(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldEQ(FieldType, v))
|
||||
}
|
||||
|
||||
// NumberHash applies equality check predicate on the "number_hash" field. It's identical to NumberHashEQ.
|
||||
func NumberHash(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldEQ(FieldNumberHash, v))
|
||||
}
|
||||
|
||||
// CvvHash applies equality check predicate on the "cvv_hash" field. It's identical to CvvHashEQ.
|
||||
func CvvHash(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldEQ(FieldCvvHash, v))
|
||||
}
|
||||
|
||||
// ExpiresAt applies equality check predicate on the "expires_at" field. It's identical to ExpiresAtEQ.
|
||||
func ExpiresAt(v time.Time) predicate.Card {
|
||||
return predicate.Card(sql.FieldEQ(FieldExpiresAt, v))
|
||||
}
|
||||
|
||||
// OwnerID applies equality check predicate on the "owner_id" field. It's identical to OwnerIDEQ.
|
||||
func OwnerID(v int) predicate.Card {
|
||||
return predicate.Card(sql.FieldEQ(FieldOwnerID, v))
|
||||
}
|
||||
|
||||
// TypeEQ applies the EQ predicate on the "type" field.
|
||||
func TypeEQ(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldEQ(FieldType, v))
|
||||
}
|
||||
|
||||
// TypeNEQ applies the NEQ predicate on the "type" field.
|
||||
func TypeNEQ(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldNEQ(FieldType, v))
|
||||
}
|
||||
|
||||
// TypeIn applies the In predicate on the "type" field.
|
||||
func TypeIn(vs ...string) predicate.Card {
|
||||
return predicate.Card(sql.FieldIn(FieldType, vs...))
|
||||
}
|
||||
|
||||
// TypeNotIn applies the NotIn predicate on the "type" field.
|
||||
func TypeNotIn(vs ...string) predicate.Card {
|
||||
return predicate.Card(sql.FieldNotIn(FieldType, vs...))
|
||||
}
|
||||
|
||||
// TypeGT applies the GT predicate on the "type" field.
|
||||
func TypeGT(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldGT(FieldType, v))
|
||||
}
|
||||
|
||||
// TypeGTE applies the GTE predicate on the "type" field.
|
||||
func TypeGTE(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldGTE(FieldType, v))
|
||||
}
|
||||
|
||||
// TypeLT applies the LT predicate on the "type" field.
|
||||
func TypeLT(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldLT(FieldType, v))
|
||||
}
|
||||
|
||||
// TypeLTE applies the LTE predicate on the "type" field.
|
||||
func TypeLTE(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldLTE(FieldType, v))
|
||||
}
|
||||
|
||||
// TypeContains applies the Contains predicate on the "type" field.
|
||||
func TypeContains(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldContains(FieldType, v))
|
||||
}
|
||||
|
||||
// TypeHasPrefix applies the HasPrefix predicate on the "type" field.
|
||||
func TypeHasPrefix(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldHasPrefix(FieldType, v))
|
||||
}
|
||||
|
||||
// TypeHasSuffix applies the HasSuffix predicate on the "type" field.
|
||||
func TypeHasSuffix(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldHasSuffix(FieldType, v))
|
||||
}
|
||||
|
||||
// TypeEqualFold applies the EqualFold predicate on the "type" field.
|
||||
func TypeEqualFold(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldEqualFold(FieldType, v))
|
||||
}
|
||||
|
||||
// TypeContainsFold applies the ContainsFold predicate on the "type" field.
|
||||
func TypeContainsFold(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldContainsFold(FieldType, v))
|
||||
}
|
||||
|
||||
// NumberHashEQ applies the EQ predicate on the "number_hash" field.
|
||||
func NumberHashEQ(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldEQ(FieldNumberHash, v))
|
||||
}
|
||||
|
||||
// NumberHashNEQ applies the NEQ predicate on the "number_hash" field.
|
||||
func NumberHashNEQ(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldNEQ(FieldNumberHash, v))
|
||||
}
|
||||
|
||||
// NumberHashIn applies the In predicate on the "number_hash" field.
|
||||
func NumberHashIn(vs ...string) predicate.Card {
|
||||
return predicate.Card(sql.FieldIn(FieldNumberHash, vs...))
|
||||
}
|
||||
|
||||
// NumberHashNotIn applies the NotIn predicate on the "number_hash" field.
|
||||
func NumberHashNotIn(vs ...string) predicate.Card {
|
||||
return predicate.Card(sql.FieldNotIn(FieldNumberHash, vs...))
|
||||
}
|
||||
|
||||
// NumberHashGT applies the GT predicate on the "number_hash" field.
|
||||
func NumberHashGT(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldGT(FieldNumberHash, v))
|
||||
}
|
||||
|
||||
// NumberHashGTE applies the GTE predicate on the "number_hash" field.
|
||||
func NumberHashGTE(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldGTE(FieldNumberHash, v))
|
||||
}
|
||||
|
||||
// NumberHashLT applies the LT predicate on the "number_hash" field.
|
||||
func NumberHashLT(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldLT(FieldNumberHash, v))
|
||||
}
|
||||
|
||||
// NumberHashLTE applies the LTE predicate on the "number_hash" field.
|
||||
func NumberHashLTE(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldLTE(FieldNumberHash, v))
|
||||
}
|
||||
|
||||
// NumberHashContains applies the Contains predicate on the "number_hash" field.
|
||||
func NumberHashContains(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldContains(FieldNumberHash, v))
|
||||
}
|
||||
|
||||
// NumberHashHasPrefix applies the HasPrefix predicate on the "number_hash" field.
|
||||
func NumberHashHasPrefix(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldHasPrefix(FieldNumberHash, v))
|
||||
}
|
||||
|
||||
// NumberHashHasSuffix applies the HasSuffix predicate on the "number_hash" field.
|
||||
func NumberHashHasSuffix(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldHasSuffix(FieldNumberHash, v))
|
||||
}
|
||||
|
||||
// NumberHashEqualFold applies the EqualFold predicate on the "number_hash" field.
|
||||
func NumberHashEqualFold(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldEqualFold(FieldNumberHash, v))
|
||||
}
|
||||
|
||||
// NumberHashContainsFold applies the ContainsFold predicate on the "number_hash" field.
|
||||
func NumberHashContainsFold(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldContainsFold(FieldNumberHash, v))
|
||||
}
|
||||
|
||||
// CvvHashEQ applies the EQ predicate on the "cvv_hash" field.
|
||||
func CvvHashEQ(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldEQ(FieldCvvHash, v))
|
||||
}
|
||||
|
||||
// CvvHashNEQ applies the NEQ predicate on the "cvv_hash" field.
|
||||
func CvvHashNEQ(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldNEQ(FieldCvvHash, v))
|
||||
}
|
||||
|
||||
// CvvHashIn applies the In predicate on the "cvv_hash" field.
|
||||
func CvvHashIn(vs ...string) predicate.Card {
|
||||
return predicate.Card(sql.FieldIn(FieldCvvHash, vs...))
|
||||
}
|
||||
|
||||
// CvvHashNotIn applies the NotIn predicate on the "cvv_hash" field.
|
||||
func CvvHashNotIn(vs ...string) predicate.Card {
|
||||
return predicate.Card(sql.FieldNotIn(FieldCvvHash, vs...))
|
||||
}
|
||||
|
||||
// CvvHashGT applies the GT predicate on the "cvv_hash" field.
|
||||
func CvvHashGT(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldGT(FieldCvvHash, v))
|
||||
}
|
||||
|
||||
// CvvHashGTE applies the GTE predicate on the "cvv_hash" field.
|
||||
func CvvHashGTE(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldGTE(FieldCvvHash, v))
|
||||
}
|
||||
|
||||
// CvvHashLT applies the LT predicate on the "cvv_hash" field.
|
||||
func CvvHashLT(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldLT(FieldCvvHash, v))
|
||||
}
|
||||
|
||||
// CvvHashLTE applies the LTE predicate on the "cvv_hash" field.
|
||||
func CvvHashLTE(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldLTE(FieldCvvHash, v))
|
||||
}
|
||||
|
||||
// CvvHashContains applies the Contains predicate on the "cvv_hash" field.
|
||||
func CvvHashContains(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldContains(FieldCvvHash, v))
|
||||
}
|
||||
|
||||
// CvvHashHasPrefix applies the HasPrefix predicate on the "cvv_hash" field.
|
||||
func CvvHashHasPrefix(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldHasPrefix(FieldCvvHash, v))
|
||||
}
|
||||
|
||||
// CvvHashHasSuffix applies the HasSuffix predicate on the "cvv_hash" field.
|
||||
func CvvHashHasSuffix(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldHasSuffix(FieldCvvHash, v))
|
||||
}
|
||||
|
||||
// CvvHashEqualFold applies the EqualFold predicate on the "cvv_hash" field.
|
||||
func CvvHashEqualFold(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldEqualFold(FieldCvvHash, v))
|
||||
}
|
||||
|
||||
// CvvHashContainsFold applies the ContainsFold predicate on the "cvv_hash" field.
|
||||
func CvvHashContainsFold(v string) predicate.Card {
|
||||
return predicate.Card(sql.FieldContainsFold(FieldCvvHash, v))
|
||||
}
|
||||
|
||||
// ExpiresAtEQ applies the EQ predicate on the "expires_at" field.
|
||||
func ExpiresAtEQ(v time.Time) predicate.Card {
|
||||
return predicate.Card(sql.FieldEQ(FieldExpiresAt, v))
|
||||
}
|
||||
|
||||
// ExpiresAtNEQ applies the NEQ predicate on the "expires_at" field.
|
||||
func ExpiresAtNEQ(v time.Time) predicate.Card {
|
||||
return predicate.Card(sql.FieldNEQ(FieldExpiresAt, v))
|
||||
}
|
||||
|
||||
// ExpiresAtIn applies the In predicate on the "expires_at" field.
|
||||
func ExpiresAtIn(vs ...time.Time) predicate.Card {
|
||||
return predicate.Card(sql.FieldIn(FieldExpiresAt, vs...))
|
||||
}
|
||||
|
||||
// ExpiresAtNotIn applies the NotIn predicate on the "expires_at" field.
|
||||
func ExpiresAtNotIn(vs ...time.Time) predicate.Card {
|
||||
return predicate.Card(sql.FieldNotIn(FieldExpiresAt, vs...))
|
||||
}
|
||||
|
||||
// ExpiresAtGT applies the GT predicate on the "expires_at" field.
|
||||
func ExpiresAtGT(v time.Time) predicate.Card {
|
||||
return predicate.Card(sql.FieldGT(FieldExpiresAt, v))
|
||||
}
|
||||
|
||||
// ExpiresAtGTE applies the GTE predicate on the "expires_at" field.
|
||||
func ExpiresAtGTE(v time.Time) predicate.Card {
|
||||
return predicate.Card(sql.FieldGTE(FieldExpiresAt, v))
|
||||
}
|
||||
|
||||
// ExpiresAtLT applies the LT predicate on the "expires_at" field.
|
||||
func ExpiresAtLT(v time.Time) predicate.Card {
|
||||
return predicate.Card(sql.FieldLT(FieldExpiresAt, v))
|
||||
}
|
||||
|
||||
// ExpiresAtLTE applies the LTE predicate on the "expires_at" field.
|
||||
func ExpiresAtLTE(v time.Time) predicate.Card {
|
||||
return predicate.Card(sql.FieldLTE(FieldExpiresAt, v))
|
||||
}
|
||||
|
||||
// ExpiresAtIsNil applies the IsNil predicate on the "expires_at" field.
|
||||
func ExpiresAtIsNil() predicate.Card {
|
||||
return predicate.Card(sql.FieldIsNull(FieldExpiresAt))
|
||||
}
|
||||
|
||||
// ExpiresAtNotNil applies the NotNil predicate on the "expires_at" field.
|
||||
func ExpiresAtNotNil() predicate.Card {
|
||||
return predicate.Card(sql.FieldNotNull(FieldExpiresAt))
|
||||
}
|
||||
|
||||
// OwnerIDEQ applies the EQ predicate on the "owner_id" field.
|
||||
func OwnerIDEQ(v int) predicate.Card {
|
||||
return predicate.Card(sql.FieldEQ(FieldOwnerID, v))
|
||||
}
|
||||
|
||||
// OwnerIDNEQ applies the NEQ predicate on the "owner_id" field.
|
||||
func OwnerIDNEQ(v int) predicate.Card {
|
||||
return predicate.Card(sql.FieldNEQ(FieldOwnerID, v))
|
||||
}
|
||||
|
||||
// OwnerIDIn applies the In predicate on the "owner_id" field.
|
||||
func OwnerIDIn(vs ...int) predicate.Card {
|
||||
return predicate.Card(sql.FieldIn(FieldOwnerID, vs...))
|
||||
}
|
||||
|
||||
// OwnerIDNotIn applies the NotIn predicate on the "owner_id" field.
|
||||
func OwnerIDNotIn(vs ...int) predicate.Card {
|
||||
return predicate.Card(sql.FieldNotIn(FieldOwnerID, vs...))
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// HasPayments applies the HasEdge predicate on the "payments" edge.
|
||||
func HasPayments() predicate.Card {
|
||||
return predicate.Card(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, PaymentsTable, PaymentsColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
})
|
||||
}
|
||||
|
||||
// HasPaymentsWith applies the HasEdge predicate on the "payments" edge with a given conditions (other predicates).
|
||||
func HasPaymentsWith(preds ...predicate.Payment) predicate.Card {
|
||||
return predicate.Card(func(s *sql.Selector) {
|
||||
step := newPaymentsStep()
|
||||
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))
|
||||
}
|
||||
329
examples/migration/ent/card_create.go
Normal file
329
examples/migration/ent/card_create.go
Normal file
@@ -0,0 +1,329 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/card"
|
||||
"entgo.io/ent/examples/migration/ent/payment"
|
||||
"entgo.io/ent/examples/migration/ent/user"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// CardCreate is the builder for creating a Card entity.
|
||||
type CardCreate struct {
|
||||
config
|
||||
mutation *CardMutation
|
||||
hooks []Hook
|
||||
}
|
||||
|
||||
// SetType sets the "type" field.
|
||||
func (_c *CardCreate) SetType(v string) *CardCreate {
|
||||
_c.mutation.SetType(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableType sets the "type" field if the given value is not nil.
|
||||
func (_c *CardCreate) SetNillableType(v *string) *CardCreate {
|
||||
if v != nil {
|
||||
_c.SetType(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNumberHash sets the "number_hash" field.
|
||||
func (_c *CardCreate) SetNumberHash(v string) *CardCreate {
|
||||
_c.mutation.SetNumberHash(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetCvvHash sets the "cvv_hash" field.
|
||||
func (_c *CardCreate) SetCvvHash(v string) *CardCreate {
|
||||
_c.mutation.SetCvvHash(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetExpiresAt sets the "expires_at" field.
|
||||
func (_c *CardCreate) SetExpiresAt(v time.Time) *CardCreate {
|
||||
_c.mutation.SetExpiresAt(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.
|
||||
func (_c *CardCreate) SetNillableExpiresAt(v *time.Time) *CardCreate {
|
||||
if v != nil {
|
||||
_c.SetExpiresAt(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetOwnerID sets the "owner_id" field.
|
||||
func (_c *CardCreate) SetOwnerID(v int) *CardCreate {
|
||||
_c.mutation.SetOwnerID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableOwnerID sets the "owner_id" field if the given value is not nil.
|
||||
func (_c *CardCreate) SetNillableOwnerID(v *int) *CardCreate {
|
||||
if v != nil {
|
||||
_c.SetOwnerID(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetOwner sets the "owner" edge to the User entity.
|
||||
func (_c *CardCreate) SetOwner(v *User) *CardCreate {
|
||||
return _c.SetOwnerID(v.ID)
|
||||
}
|
||||
|
||||
// AddPaymentIDs adds the "payments" edge to the Payment entity by IDs.
|
||||
func (_c *CardCreate) AddPaymentIDs(ids ...int) *CardCreate {
|
||||
_c.mutation.AddPaymentIDs(ids...)
|
||||
return _c
|
||||
}
|
||||
|
||||
// AddPayments adds the "payments" edges to the Payment entity.
|
||||
func (_c *CardCreate) AddPayments(v ...*Payment) *CardCreate {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _c.AddPaymentIDs(ids...)
|
||||
}
|
||||
|
||||
// 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) {
|
||||
_c.defaults()
|
||||
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() {
|
||||
if _, ok := _c.mutation.GetType(); !ok {
|
||||
v := card.DefaultType
|
||||
_c.mutation.SetType(v)
|
||||
}
|
||||
if _, ok := _c.mutation.OwnerID(); !ok {
|
||||
v := card.DefaultOwnerID
|
||||
_c.mutation.SetOwnerID(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_c *CardCreate) check() error {
|
||||
if _, ok := _c.mutation.GetType(); !ok {
|
||||
return &ValidationError{Name: "type", err: errors.New(`ent: missing required field "Card.type"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.NumberHash(); !ok {
|
||||
return &ValidationError{Name: "number_hash", err: errors.New(`ent: missing required field "Card.number_hash"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.CvvHash(); !ok {
|
||||
return &ValidationError{Name: "cvv_hash", err: errors.New(`ent: missing required field "Card.cvv_hash"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.OwnerID(); !ok {
|
||||
return &ValidationError{Name: "owner_id", err: errors.New(`ent: missing required field "Card.owner_id"`)}
|
||||
}
|
||||
if len(_c.mutation.OwnerIDs()) == 0 {
|
||||
return &ValidationError{Name: "owner", err: errors.New(`ent: missing required edge "Card.owner"`)}
|
||||
}
|
||||
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.GetType(); ok {
|
||||
_spec.SetField(card.FieldType, field.TypeString, value)
|
||||
_node.Type = value
|
||||
}
|
||||
if value, ok := _c.mutation.NumberHash(); ok {
|
||||
_spec.SetField(card.FieldNumberHash, field.TypeString, value)
|
||||
_node.NumberHash = value
|
||||
}
|
||||
if value, ok := _c.mutation.CvvHash(); ok {
|
||||
_spec.SetField(card.FieldCvvHash, field.TypeString, value)
|
||||
_node.CvvHash = value
|
||||
}
|
||||
if value, ok := _c.mutation.ExpiresAt(); ok {
|
||||
_spec.SetField(card.FieldExpiresAt, field.TypeTime, value)
|
||||
_node.ExpiresAt = 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.OwnerID = nodes[0]
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
if nodes := _c.mutation.PaymentsIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: card.PaymentsTable,
|
||||
Columns: []string{card.PaymentsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(payment.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_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)
|
||||
}
|
||||
}
|
||||
92
examples/migration/ent/card_delete.go
Normal file
92
examples/migration/ent/card_delete.go
Normal file
@@ -0,0 +1,92 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/card"
|
||||
"entgo.io/ent/examples/migration/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)
|
||||
}
|
||||
}
|
||||
685
examples/migration/ent/card_query.go
Normal file
685
examples/migration/ent/card_query.go
Normal file
@@ -0,0 +1,685 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql/driver"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/card"
|
||||
"entgo.io/ent/examples/migration/ent/payment"
|
||||
"entgo.io/ent/examples/migration/ent/predicate"
|
||||
"entgo.io/ent/examples/migration/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
|
||||
withPayments *PaymentQuery
|
||||
// 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
|
||||
}
|
||||
|
||||
// QueryPayments chains the current query on the "payments" edge.
|
||||
func (_q *CardQuery) QueryPayments() *PaymentQuery {
|
||||
query := (&PaymentClient{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(payment.Table, payment.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, card.PaymentsTable, card.PaymentsColumn),
|
||||
)
|
||||
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(),
|
||||
withPayments: _q.withPayments.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
|
||||
}
|
||||
|
||||
// WithPayments tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "payments" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (_q *CardQuery) WithPayments(opts ...func(*PaymentQuery)) *CardQuery {
|
||||
query := (&PaymentClient{config: _q.config}).Query()
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
_q.withPayments = 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 {
|
||||
// Type string `json:"type,omitempty"`
|
||||
// Count int `json:"count,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.Card.Query().
|
||||
// GroupBy(card.FieldType).
|
||||
// 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 {
|
||||
// Type string `json:"type,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.Card.Query().
|
||||
// Select(card.FieldType).
|
||||
// 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{}
|
||||
_spec = _q.querySpec()
|
||||
loadedTypes = [2]bool{
|
||||
_q.withOwner != nil,
|
||||
_q.withPayments != nil,
|
||||
}
|
||||
)
|
||||
_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
|
||||
}
|
||||
}
|
||||
if query := _q.withPayments; query != nil {
|
||||
if err := _q.loadPayments(ctx, query, nodes,
|
||||
func(n *Card) { n.Edges.Payments = []*Payment{} },
|
||||
func(n *Card, e *Payment) { n.Edges.Payments = append(n.Edges.Payments, 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 {
|
||||
fk := nodes[i].OwnerID
|
||||
if _, ok := nodeids[fk]; !ok {
|
||||
ids = append(ids, fk)
|
||||
}
|
||||
nodeids[fk] = append(nodeids[fk], nodes[i])
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
query.Where(user.IDIn(ids...))
|
||||
neighbors, err := query.All(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, n := range neighbors {
|
||||
nodes, ok := nodeids[n.ID]
|
||||
if !ok {
|
||||
return fmt.Errorf(`unexpected foreign-key "owner_id" returned %v`, n.ID)
|
||||
}
|
||||
for i := range nodes {
|
||||
assign(nodes[i], n)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (_q *CardQuery) loadPayments(ctx context.Context, query *PaymentQuery, nodes []*Card, init func(*Card), assign func(*Card, *Payment)) error {
|
||||
fks := make([]driver.Value, 0, len(nodes))
|
||||
nodeids := make(map[int]*Card)
|
||||
for i := range nodes {
|
||||
fks = append(fks, nodes[i].ID)
|
||||
nodeids[nodes[i].ID] = nodes[i]
|
||||
if init != nil {
|
||||
init(nodes[i])
|
||||
}
|
||||
}
|
||||
if len(query.ctx.Fields) > 0 {
|
||||
query.ctx.AppendFieldOnce(payment.FieldCardID)
|
||||
}
|
||||
query.Where(predicate.Payment(func(s *sql.Selector) {
|
||||
s.Where(sql.InValues(s.C(card.PaymentsColumn), fks...))
|
||||
}))
|
||||
neighbors, err := query.All(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, n := range neighbors {
|
||||
fk := n.CardID
|
||||
node, ok := nodeids[fk]
|
||||
if !ok {
|
||||
return fmt.Errorf(`unexpected referenced foreign-key "card_id" returned %v for node %v`, fk, n.ID)
|
||||
}
|
||||
assign(node, 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 _q.withOwner != nil {
|
||||
_spec.Node.AddColumnOnce(card.FieldOwnerID)
|
||||
}
|
||||
}
|
||||
if ps := _q.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if limit := _q.ctx.Limit; limit != nil {
|
||||
_spec.Limit = *limit
|
||||
}
|
||||
if offset := _q.ctx.Offset; offset != nil {
|
||||
_spec.Offset = *offset
|
||||
}
|
||||
if ps := _q.order; len(ps) > 0 {
|
||||
_spec.Order = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
return _spec
|
||||
}
|
||||
|
||||
func (_q *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)
|
||||
}
|
||||
628
examples/migration/ent/card_update.go
Normal file
628
examples/migration/ent/card_update.go
Normal file
@@ -0,0 +1,628 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/card"
|
||||
"entgo.io/ent/examples/migration/ent/payment"
|
||||
"entgo.io/ent/examples/migration/ent/predicate"
|
||||
"entgo.io/ent/examples/migration/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
|
||||
}
|
||||
|
||||
// SetType sets the "type" field.
|
||||
func (_u *CardUpdate) SetType(v string) *CardUpdate {
|
||||
_u.mutation.SetType(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableType sets the "type" field if the given value is not nil.
|
||||
func (_u *CardUpdate) SetNillableType(v *string) *CardUpdate {
|
||||
if v != nil {
|
||||
_u.SetType(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNumberHash sets the "number_hash" field.
|
||||
func (_u *CardUpdate) SetNumberHash(v string) *CardUpdate {
|
||||
_u.mutation.SetNumberHash(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableNumberHash sets the "number_hash" field if the given value is not nil.
|
||||
func (_u *CardUpdate) SetNillableNumberHash(v *string) *CardUpdate {
|
||||
if v != nil {
|
||||
_u.SetNumberHash(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetCvvHash sets the "cvv_hash" field.
|
||||
func (_u *CardUpdate) SetCvvHash(v string) *CardUpdate {
|
||||
_u.mutation.SetCvvHash(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableCvvHash sets the "cvv_hash" field if the given value is not nil.
|
||||
func (_u *CardUpdate) SetNillableCvvHash(v *string) *CardUpdate {
|
||||
if v != nil {
|
||||
_u.SetCvvHash(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetExpiresAt sets the "expires_at" field.
|
||||
func (_u *CardUpdate) SetExpiresAt(v time.Time) *CardUpdate {
|
||||
_u.mutation.SetExpiresAt(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.
|
||||
func (_u *CardUpdate) SetNillableExpiresAt(v *time.Time) *CardUpdate {
|
||||
if v != nil {
|
||||
_u.SetExpiresAt(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearExpiresAt clears the value of the "expires_at" field.
|
||||
func (_u *CardUpdate) ClearExpiresAt() *CardUpdate {
|
||||
_u.mutation.ClearExpiresAt()
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetOwnerID sets the "owner_id" field.
|
||||
func (_u *CardUpdate) SetOwnerID(v int) *CardUpdate {
|
||||
_u.mutation.SetOwnerID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableOwnerID sets the "owner_id" field if the given value is not nil.
|
||||
func (_u *CardUpdate) SetNillableOwnerID(v *int) *CardUpdate {
|
||||
if v != nil {
|
||||
_u.SetOwnerID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetOwner sets the "owner" edge to the User entity.
|
||||
func (_u *CardUpdate) SetOwner(v *User) *CardUpdate {
|
||||
return _u.SetOwnerID(v.ID)
|
||||
}
|
||||
|
||||
// AddPaymentIDs adds the "payments" edge to the Payment entity by IDs.
|
||||
func (_u *CardUpdate) AddPaymentIDs(ids ...int) *CardUpdate {
|
||||
_u.mutation.AddPaymentIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddPayments adds the "payments" edges to the Payment entity.
|
||||
func (_u *CardUpdate) AddPayments(v ...*Payment) *CardUpdate {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.AddPaymentIDs(ids...)
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// ClearPayments clears all "payments" edges to the Payment entity.
|
||||
func (_u *CardUpdate) ClearPayments() *CardUpdate {
|
||||
_u.mutation.ClearPayments()
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemovePaymentIDs removes the "payments" edge to Payment entities by IDs.
|
||||
func (_u *CardUpdate) RemovePaymentIDs(ids ...int) *CardUpdate {
|
||||
_u.mutation.RemovePaymentIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemovePayments removes "payments" edges to Payment entities.
|
||||
func (_u *CardUpdate) RemovePayments(v ...*Payment) *CardUpdate {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.RemovePaymentIDs(ids...)
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *CardUpdate) check() error {
|
||||
if _u.mutation.OwnerCleared() && len(_u.mutation.OwnerIDs()) > 0 {
|
||||
return errors.New(`ent: clearing a required unique edge "Card.owner"`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *CardUpdate) sqlSave(ctx context.Context) (_node int, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_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.GetType(); ok {
|
||||
_spec.SetField(card.FieldType, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.NumberHash(); ok {
|
||||
_spec.SetField(card.FieldNumberHash, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.CvvHash(); ok {
|
||||
_spec.SetField(card.FieldCvvHash, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ExpiresAt(); ok {
|
||||
_spec.SetField(card.FieldExpiresAt, field.TypeTime, value)
|
||||
}
|
||||
if _u.mutation.ExpiresAtCleared() {
|
||||
_spec.ClearField(card.FieldExpiresAt, 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 _u.mutation.PaymentsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: card.PaymentsTable,
|
||||
Columns: []string{card.PaymentsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(payment.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.RemovedPaymentsIDs(); len(nodes) > 0 && !_u.mutation.PaymentsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: card.PaymentsTable,
|
||||
Columns: []string{card.PaymentsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(payment.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.PaymentsIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: card.PaymentsTable,
|
||||
Columns: []string{card.PaymentsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(payment.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
|
||||
}
|
||||
|
||||
// SetType sets the "type" field.
|
||||
func (_u *CardUpdateOne) SetType(v string) *CardUpdateOne {
|
||||
_u.mutation.SetType(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableType sets the "type" field if the given value is not nil.
|
||||
func (_u *CardUpdateOne) SetNillableType(v *string) *CardUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetType(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNumberHash sets the "number_hash" field.
|
||||
func (_u *CardUpdateOne) SetNumberHash(v string) *CardUpdateOne {
|
||||
_u.mutation.SetNumberHash(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableNumberHash sets the "number_hash" field if the given value is not nil.
|
||||
func (_u *CardUpdateOne) SetNillableNumberHash(v *string) *CardUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetNumberHash(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetCvvHash sets the "cvv_hash" field.
|
||||
func (_u *CardUpdateOne) SetCvvHash(v string) *CardUpdateOne {
|
||||
_u.mutation.SetCvvHash(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableCvvHash sets the "cvv_hash" field if the given value is not nil.
|
||||
func (_u *CardUpdateOne) SetNillableCvvHash(v *string) *CardUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetCvvHash(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetExpiresAt sets the "expires_at" field.
|
||||
func (_u *CardUpdateOne) SetExpiresAt(v time.Time) *CardUpdateOne {
|
||||
_u.mutation.SetExpiresAt(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.
|
||||
func (_u *CardUpdateOne) SetNillableExpiresAt(v *time.Time) *CardUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetExpiresAt(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearExpiresAt clears the value of the "expires_at" field.
|
||||
func (_u *CardUpdateOne) ClearExpiresAt() *CardUpdateOne {
|
||||
_u.mutation.ClearExpiresAt()
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetOwnerID sets the "owner_id" field.
|
||||
func (_u *CardUpdateOne) SetOwnerID(v int) *CardUpdateOne {
|
||||
_u.mutation.SetOwnerID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableOwnerID sets the "owner_id" field if the given value is not nil.
|
||||
func (_u *CardUpdateOne) SetNillableOwnerID(v *int) *CardUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetOwnerID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetOwner sets the "owner" edge to the User entity.
|
||||
func (_u *CardUpdateOne) SetOwner(v *User) *CardUpdateOne {
|
||||
return _u.SetOwnerID(v.ID)
|
||||
}
|
||||
|
||||
// AddPaymentIDs adds the "payments" edge to the Payment entity by IDs.
|
||||
func (_u *CardUpdateOne) AddPaymentIDs(ids ...int) *CardUpdateOne {
|
||||
_u.mutation.AddPaymentIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddPayments adds the "payments" edges to the Payment entity.
|
||||
func (_u *CardUpdateOne) AddPayments(v ...*Payment) *CardUpdateOne {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.AddPaymentIDs(ids...)
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// ClearPayments clears all "payments" edges to the Payment entity.
|
||||
func (_u *CardUpdateOne) ClearPayments() *CardUpdateOne {
|
||||
_u.mutation.ClearPayments()
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemovePaymentIDs removes the "payments" edge to Payment entities by IDs.
|
||||
func (_u *CardUpdateOne) RemovePaymentIDs(ids ...int) *CardUpdateOne {
|
||||
_u.mutation.RemovePaymentIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemovePayments removes "payments" edges to Payment entities.
|
||||
func (_u *CardUpdateOne) RemovePayments(v ...*Payment) *CardUpdateOne {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.RemovePaymentIDs(ids...)
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *CardUpdateOne) check() error {
|
||||
if _u.mutation.OwnerCleared() && len(_u.mutation.OwnerIDs()) > 0 {
|
||||
return errors.New(`ent: clearing a required unique edge "Card.owner"`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *CardUpdateOne) sqlSave(ctx context.Context) (_node *Card, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_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.GetType(); ok {
|
||||
_spec.SetField(card.FieldType, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.NumberHash(); ok {
|
||||
_spec.SetField(card.FieldNumberHash, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.CvvHash(); ok {
|
||||
_spec.SetField(card.FieldCvvHash, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ExpiresAt(); ok {
|
||||
_spec.SetField(card.FieldExpiresAt, field.TypeTime, value)
|
||||
}
|
||||
if _u.mutation.ExpiresAtCleared() {
|
||||
_spec.ClearField(card.FieldExpiresAt, 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 _u.mutation.PaymentsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: card.PaymentsTable,
|
||||
Columns: []string{card.PaymentsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(payment.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.RemovedPaymentsIDs(); len(nodes) > 0 && !_u.mutation.PaymentsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: card.PaymentsTable,
|
||||
Columns: []string{card.PaymentsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(payment.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.PaymentsIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: card.PaymentsTable,
|
||||
Columns: []string{card.PaymentsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(payment.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
|
||||
}
|
||||
1187
examples/migration/ent/client.go
Normal file
1187
examples/migration/ent/client.go
Normal file
File diff suppressed because it is too large
Load Diff
622
examples/migration/ent/ent.go
Normal file
622
examples/migration/ent/ent.go
Normal file
@@ -0,0 +1,622 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"sync"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/card"
|
||||
"entgo.io/ent/examples/migration/ent/payment"
|
||||
"entgo.io/ent/examples/migration/ent/pet"
|
||||
"entgo.io/ent/examples/migration/ent/session"
|
||||
"entgo.io/ent/examples/migration/ent/sessiondevice"
|
||||
"entgo.io/ent/examples/migration/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,
|
||||
payment.Table: payment.ValidColumn,
|
||||
pet.Table: pet.ValidColumn,
|
||||
session.Table: session.ValidColumn,
|
||||
sessiondevice.Table: sessiondevice.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)
|
||||
88
examples/migration/ent/enttest/enttest.go
Normal file
88
examples/migration/ent/enttest/enttest.go
Normal file
@@ -0,0 +1,88 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package enttest
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"entgo.io/ent/examples/migration/ent"
|
||||
// required by schema hooks.
|
||||
_ "entgo.io/ent/examples/migration/ent/runtime"
|
||||
|
||||
"entgo.io/ent/dialect/sql/schema"
|
||||
"entgo.io/ent/examples/migration/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()
|
||||
}
|
||||
}
|
||||
3
examples/migration/ent/generate.go
Normal file
3
examples/migration/ent/generate.go
Normal file
@@ -0,0 +1,3 @@
|
||||
package ent
|
||||
|
||||
//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate --feature sql/versioned-migration --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
|
||||
263
examples/migration/ent/hook/hook.go
Normal file
263
examples/migration/ent/hook/hook.go
Normal file
@@ -0,0 +1,263 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package hook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"entgo.io/ent/examples/migration/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 PaymentFunc type is an adapter to allow the use of ordinary
|
||||
// function as Payment mutator.
|
||||
type PaymentFunc func(context.Context, *ent.PaymentMutation) (ent.Value, error)
|
||||
|
||||
// Mutate calls f(ctx, m).
|
||||
func (f PaymentFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
|
||||
if mv, ok := m.(*ent.PaymentMutation); ok {
|
||||
return f(ctx, mv)
|
||||
}
|
||||
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.PaymentMutation", 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 SessionFunc type is an adapter to allow the use of ordinary
|
||||
// function as Session mutator.
|
||||
type SessionFunc func(context.Context, *ent.SessionMutation) (ent.Value, error)
|
||||
|
||||
// Mutate calls f(ctx, m).
|
||||
func (f SessionFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
|
||||
if mv, ok := m.(*ent.SessionMutation); ok {
|
||||
return f(ctx, mv)
|
||||
}
|
||||
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.SessionMutation", m)
|
||||
}
|
||||
|
||||
// The SessionDeviceFunc type is an adapter to allow the use of ordinary
|
||||
// function as SessionDevice mutator.
|
||||
type SessionDeviceFunc func(context.Context, *ent.SessionDeviceMutation) (ent.Value, error)
|
||||
|
||||
// Mutate calls f(ctx, m).
|
||||
func (f SessionDeviceFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
|
||||
if mv, ok := m.(*ent.SessionDeviceMutation); ok {
|
||||
return f(ctx, mv)
|
||||
}
|
||||
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.SessionDeviceMutation", 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...)
|
||||
}
|
||||
42
examples/migration/ent/migrate/main.go
Normal file
42
examples/migration/ent/migrate/main.go
Normal file
@@ -0,0 +1,42 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
//go:build ignore
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
atlas "ariga.io/atlas/sql/migrate"
|
||||
"entgo.io/ent/dialect"
|
||||
"entgo.io/ent/dialect/sql/schema"
|
||||
"entgo.io/ent/examples/migration/ent/migrate"
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
)
|
||||
|
||||
func main() {
|
||||
ctx := context.Background()
|
||||
dir, err := atlas.NewLocalDir("ent/migrate/migrations")
|
||||
if err != nil {
|
||||
log.Fatalf("failed creating atlas migration directory: %v", err)
|
||||
}
|
||||
// Migrate diff options.
|
||||
opts := []schema.MigrateOption{
|
||||
schema.WithDir(dir), // provide migration directory
|
||||
schema.WithMigrationMode(schema.ModeReplay), // provide migration mode
|
||||
schema.WithDialect(dialect.MySQL), // Ent dialect to use
|
||||
schema.WithFormatter(atlas.DefaultFormatter), // Default Atlas formatter
|
||||
}
|
||||
if len(os.Args) != 2 {
|
||||
log.Fatalln("migration name is required. Use: 'go run -mod=mod ./ent/migrate/main.go <name>'")
|
||||
}
|
||||
// Generate migrations using Atlas support for MySQL (note the Ent dialect option passed above).
|
||||
err = migrate.NamedDiff(ctx, "mysql://root:pass@localhost:3306/test", os.Args[1], opts...)
|
||||
if err != nil {
|
||||
log.Fatalf("failed generating migration file: %v", err)
|
||||
}
|
||||
}
|
||||
100
examples/migration/ent/migrate/migrate.go
Normal file
100
examples/migration/ent/migrate/migrate.go
Normal file
@@ -0,0 +1,100 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package 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...)
|
||||
}
|
||||
|
||||
// Diff compares the state read from a database connection or migration directory with
|
||||
// the state defined by the Ent schema. Changes will be written to new migration files.
|
||||
func Diff(ctx context.Context, url string, opts ...schema.MigrateOption) error {
|
||||
return NamedDiff(ctx, url, "changes", opts...)
|
||||
}
|
||||
|
||||
// NamedDiff compares the state read from a database connection or migration directory with
|
||||
// the state defined by the Ent schema. Changes will be written to new named migration files.
|
||||
func NamedDiff(ctx context.Context, url, name string, opts ...schema.MigrateOption) error {
|
||||
return schema.Diff(ctx, url, name, Tables, opts...)
|
||||
}
|
||||
|
||||
// Diff creates a migration file containing the statements to resolve the diff
|
||||
// between the Ent schema and the connected database.
|
||||
func (s *Schema) Diff(ctx context.Context, opts ...schema.MigrateOption) error {
|
||||
migrate, err := schema.NewMigrate(s.drv, opts...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ent/migrate: %w", err)
|
||||
}
|
||||
return migrate.Diff(ctx, Tables...)
|
||||
}
|
||||
|
||||
// NamedDiff creates a named migration file containing the statements to resolve the diff
|
||||
// between the Ent schema and the connected database.
|
||||
func (s *Schema) NamedDiff(ctx context.Context, name string, opts ...schema.MigrateOption) error {
|
||||
migrate, err := schema.NewMigrate(s.drv, opts...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ent/migrate: %w", err)
|
||||
}
|
||||
return migrate.NamedDiff(ctx, name, 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...)
|
||||
}
|
||||
120
examples/migration/ent/migrate/migratedata/migratedata.go
Normal file
120
examples/migration/ent/migrate/migratedata/migratedata.go
Normal file
@@ -0,0 +1,120 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
//go:build migratedata_20221126185750
|
||||
|
||||
// Package migratedata holds the functions for generating data migration files.
|
||||
// It exists here for documentation and reference purpose only and has no runtime
|
||||
// effect on the actual migration files.
|
||||
package migratedata
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"ariga.io/atlas/sql/migrate"
|
||||
"entgo.io/ent/dialect"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/schema"
|
||||
"entgo.io/ent/dialect/sql/sqljson"
|
||||
"entgo.io/ent/examples/migration/ent"
|
||||
"entgo.io/ent/examples/migration/ent/user"
|
||||
)
|
||||
|
||||
// BackfillUserTags was used to generate the migration file '20221126185750_backfill_user_tags.sql'.
|
||||
// It exists here for documentation purpose only, and can be used as a reference for future data migrations.
|
||||
func BackfillUserTags(dir *migrate.LocalDir) error {
|
||||
w := &schema.DirWriter{Dir: dir}
|
||||
client := ent.NewClient(ent.Driver(schema.NewWriteDriver(dialect.MySQL, w)))
|
||||
|
||||
// Add defaults "foo" and "bar" tags for users without any.
|
||||
err := client.User.
|
||||
Update().
|
||||
Where(func(s *sql.Selector) {
|
||||
s.Where(
|
||||
sql.Or(
|
||||
sql.IsNull(user.FieldTags),
|
||||
sqljson.ValueIsNull(user.FieldTags),
|
||||
),
|
||||
)
|
||||
}).
|
||||
SetTags([]string{"foo", "bar"}).
|
||||
Exec(context.Background())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed generating backfill statement: %w", err)
|
||||
}
|
||||
// Document all changes until now with a custom comment.
|
||||
w.Change("Backfill NULL or null tags with a default value.")
|
||||
|
||||
// Append the "org" special tag for users with a specific prefix or suffix.
|
||||
err = client.User.
|
||||
Update().
|
||||
Where(
|
||||
user.Or(
|
||||
user.NameHasPrefix("org-"),
|
||||
user.NameHasSuffix("-org"),
|
||||
),
|
||||
// Append to only those without this tag.
|
||||
func(s *sql.Selector) {
|
||||
s.Where(
|
||||
sql.Not(sqljson.ValueContains(user.FieldTags, "org")),
|
||||
)
|
||||
},
|
||||
).
|
||||
AppendTags([]string{"org"}).
|
||||
Exec(context.Background())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed generating backfill statement: %w", err)
|
||||
}
|
||||
// Document all changes until now with a custom comment.
|
||||
w.Change("Append the 'org' tag for organization accounts in case they don't have it.")
|
||||
|
||||
// Write the content to the migration directory.
|
||||
return w.Flush("backfill_user_tags")
|
||||
}
|
||||
|
||||
// BackfillUnknown back-fills all empty users' names with the default value 'Unknown'.
|
||||
func BackfillUnknown(dir *migrate.LocalDir) error {
|
||||
w := &schema.DirWriter{Dir: dir}
|
||||
client := ent.NewClient(ent.Driver(schema.NewWriteDriver(dialect.MySQL, w)))
|
||||
|
||||
// Change all empty names to 'unknown'.
|
||||
err := client.User.
|
||||
Update().
|
||||
Where(
|
||||
user.NameEQ(""),
|
||||
).
|
||||
SetName("Unknown").
|
||||
Exec(context.Background())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed generating statement: %w", err)
|
||||
}
|
||||
|
||||
// Write the content to the migration directory.
|
||||
return w.FlushChange(
|
||||
"unknown_names",
|
||||
"Backfill all empty user names with default value 'unknown'.",
|
||||
)
|
||||
}
|
||||
|
||||
// SeedUsers add the initial users to the database.
|
||||
func SeedUsers(dir *migrate.LocalDir) error {
|
||||
w := &schema.DirWriter{Dir: dir}
|
||||
client := ent.NewClient(ent.Driver(schema.NewWriteDriver(dialect.MySQL, w)))
|
||||
|
||||
// The statement that generates the INSERT statement.
|
||||
err := client.User.CreateBulk(
|
||||
client.User.Create().SetName("a8m").SetAge(1).SetTags([]string{"foo"}),
|
||||
client.User.Create().SetName("nati").SetAge(1).SetTags([]string{"bar"}),
|
||||
).Exec(context.Background())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed generating statement: %w", err)
|
||||
}
|
||||
|
||||
// Write the content to the migration directory.
|
||||
return w.FlushChange(
|
||||
"seed_users",
|
||||
"Add the initial users to the database.",
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
-- create "users" table
|
||||
CREATE TABLE `users` (`id` bigint NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`)) CHARSET utf8mb4 COLLATE utf8mb4_bin;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- modify "users" table
|
||||
ALTER TABLE `users` ADD CHECK (age > 0), ADD COLUMN `age` double NOT NULL;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- modify "users" table
|
||||
ALTER TABLE `users` ADD CONSTRAINT `name_not_empty` CHECK (name <> ''), ADD COLUMN `name` varchar(255) NOT NULL;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- modify "users" table
|
||||
ALTER TABLE `users` ADD COLUMN `tags` json NULL;
|
||||
@@ -0,0 +1,4 @@
|
||||
-- Backfill NULL or null tags with a default value.
|
||||
UPDATE `users` SET `tags` = '["foo","bar"]' WHERE `tags` IS NULL OR JSON_CONTAINS(`tags`, 'null', '$');
|
||||
-- Append the 'org' tag for organization accounts in case they don't have it.
|
||||
UPDATE `users` SET `tags` = CASE WHEN (JSON_TYPE(JSON_EXTRACT(`tags`, '$')) IS NULL OR JSON_TYPE(JSON_EXTRACT(`tags`, '$')) = 'NULL') THEN JSON_ARRAY('org') ELSE JSON_ARRAY_APPEND(`tags`, '$', 'org') END WHERE (`users`.`name` LIKE 'org-%' OR `users`.`name` LIKE '%-org') AND (NOT (JSON_CONTAINS(`tags`, '"org"', '$') = 1));
|
||||
@@ -0,0 +1,4 @@
|
||||
-- create "cards" table
|
||||
CREATE TABLE `cards` (`id` bigint NOT NULL AUTO_INCREMENT, `owner_id` bigint NOT NULL DEFAULT 0, PRIMARY KEY (`id`), INDEX `cards_users_cards` (`owner_id`), CONSTRAINT `cards_users_cards` FOREIGN KEY (`owner_id`) REFERENCES `users` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION) CHARSET utf8mb4 COLLATE utf8mb4_bin;
|
||||
-- create "pets" table
|
||||
CREATE TABLE `pets` (`id` char(36) NOT NULL, `best_friend_id` char(36) NULL DEFAULT "00000000-0000-0000-0000-000000000000", `owner_id` bigint NOT NULL DEFAULT 0, PRIMARY KEY (`id`), UNIQUE INDEX `best_friend_id` (`best_friend_id`), INDEX `pets_users_owner` (`owner_id`), CONSTRAINT `pets_pets_best_friend` FOREIGN KEY (`best_friend_id`) REFERENCES `pets` (`id`) ON UPDATE NO ACTION ON DELETE SET NULL, CONSTRAINT `pets_users_owner` FOREIGN KEY (`owner_id`) REFERENCES `users` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION) CHARSET utf8mb4 COLLATE utf8mb4_bin;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Modify "cards" table
|
||||
ALTER TABLE `cards` ADD CONSTRAINT `number_length` CHECK (length(`number`) = 16), ADD COLUMN `number` varchar(255) NOT NULL;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Modify "pets" table
|
||||
ALTER TABLE `pets` ADD COLUMN `name` varchar(255) NOT NULL, ADD UNIQUE INDEX `pet_name_owner_id` (`name`, `owner_id`);
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Create "payments" table
|
||||
CREATE TABLE `payments` (`id` bigint NOT NULL AUTO_INCREMENT, `amount` double NOT NULL, `currency` enum('USD','ILS') NOT NULL, `time` timestamp NOT NULL, `description` varchar(255) NOT NULL, `status` enum('pending','completed','failed') NOT NULL, `card_id` bigint NOT NULL, PRIMARY KEY (`id`), INDEX `payment_status_time` (`status`, `time`), INDEX `payments_cards_payments` (`card_id`), CONSTRAINT `payments_cards_payments` FOREIGN KEY (`card_id`) REFERENCES `cards` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION, CONSTRAINT `amount_positive` CHECK (`amount` > 0)) CHARSET utf8mb4 COLLATE utf8mb4_bin;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Modify "payments" table
|
||||
ALTER TABLE `payments` MODIFY COLUMN `currency` enum('USD','EUR','ILS') NOT NULL;
|
||||
@@ -0,0 +1,6 @@
|
||||
-- Modify "users" table
|
||||
ALTER TABLE `users` DROP CONSTRAINT `name_not_empty`, ADD CONSTRAINT `first_last_not_empty` CHECK ((`first_name` <> _utf8mb4'') and (`last_name` <> _utf8mb4'')), DROP COLUMN `name`, ADD COLUMN `first_name` varchar(255) NOT NULL, ADD COLUMN `last_name` varchar(255) NOT NULL;
|
||||
-- Create "session_devices" table
|
||||
CREATE TABLE `session_devices` (`id` char(36) NOT NULL, `ip_address` varchar(50) NOT NULL, `user_agent` varchar(512) NOT NULL, `location` varchar(512) NOT NULL, `created_at` timestamp NOT NULL, `updated_at` timestamp NULL, PRIMARY KEY (`id`), INDEX `sessiondevice_ip_address_user_agent` (`ip_address`, `user_agent`), INDEX `sessiondevice_location_updated_at` (`location`, `updated_at`)) CHARSET utf8mb4 COLLATE utf8mb4_bin;
|
||||
-- Create "sessions" table
|
||||
CREATE TABLE `sessions` (`id` char(36) NOT NULL, `active` bool NOT NULL DEFAULT 0, `issued_at` timestamp NOT NULL, `expires_at` timestamp NULL, `token` varchar(255) NULL, `method` json NULL, `device_id` char(36) NULL, PRIMARY KEY (`id`), INDEX `session_active_expires_at` (`active`, `expires_at`), INDEX `sessions_session_devices_sessions` (`device_id`), CONSTRAINT `sessions_session_devices_sessions` FOREIGN KEY (`device_id`) REFERENCES `session_devices` (`id`) ON UPDATE NO ACTION ON DELETE SET NULL, CONSTRAINT `token_length` CHECK (length(`token`) = 64)) CHARSET utf8mb4 COLLATE utf8mb4_bin;
|
||||
@@ -0,0 +1,4 @@
|
||||
-- Modify "cards" table
|
||||
ALTER TABLE `cards` DROP CONSTRAINT `number_length`, ADD CONSTRAINT `number_hash_length` CHECK (length(`number_hash`) = 16), RENAME COLUMN `number` TO `number_hash`, ADD COLUMN `cvv_hash` varchar(255) NOT NULL, ADD COLUMN `expires_at` timestamp NULL;
|
||||
-- Modify "pets" table
|
||||
ALTER TABLE `pets` ADD COLUMN `age` double NOT NULL AFTER `id`, ADD COLUMN `weight` double NOT NULL AFTER `id`;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Modify "cards" table
|
||||
ALTER TABLE `cards` ADD COLUMN `type` varchar(255) NOT NULL DEFAULT "unknown";
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Modify "payments" table
|
||||
ALTER TABLE `payments` MODIFY COLUMN `currency` enum('USD','EUR','VND','ILS') NOT NULL;
|
||||
15
examples/migration/ent/migrate/migrations/atlas.sum
Normal file
15
examples/migration/ent/migrate/migrations/atlas.sum
Normal file
@@ -0,0 +1,15 @@
|
||||
h1:QMBPKnW6IBUAFXLNorT9V6E3OkehchN72/bgEHavP/0=
|
||||
20221114082343_create_users.sql h1:EeOPKbOeYUHO830P1MCXKUsxT3wLk/hSgcpT9GzlGZQ=
|
||||
20221114090322_add_age.sql h1:weRCTqS5cqKyrvIjGXk7Bn24YUXo0nhLNWD0EZBcaoQ=
|
||||
20221114101516_add_name.sql h1:leQgI2JN3URZyujlNzX3gI53MSiTA02MKI/G9cnMu6I=
|
||||
20221126173531_add_user_tags.sql h1:9yq4x41NnP8gqBg3IUbHKwE7gP/23Mx3ylf5IorLoFs=
|
||||
20221126185750_backfill_user_tags.sql h1:qBPBJD4ry+uwj1eGPmTr5COJwv8Sjo2o+OR7TWFj6qs=
|
||||
20230101214930_default_values.sql h1:W07mGRkz22lrW0dvcChRtRc5b03Kp2CsFAQZvsnb8qs=
|
||||
20231231083716_add_card_number.sql h1:sBxY6RlbqEsE8hx6Q/hSuNXfBGvVmZ0OYiZcP8uDNOc=
|
||||
20231231091550_add_pet_name.sql h1:80NyHhZ/ZC4Um0j0NLzUpf1UBj4GKvMu678EqkJsFuU=
|
||||
20231231101555_add_payment.sql h1:Je16hh6fEWuL5/nbQN5v+MNkC8ruhtTgEcEgkh+Gyyg=
|
||||
20231231102849_add_currency.sql h1:Dzm4fDibgEV841whj7Y1TMeat6Qt5d7kQojBXNIh2nY=
|
||||
20231231120006_add_session.sql h1:n725mYZBuwUU2Nl8XdUFDgn2Dbm2kpVwAASEtWOqQuo=
|
||||
20231231123114_hash_card.sql h1:ZsZUe2+vJ6echLKnQxBhXyVoBJja2IAY7rX/P5UZ0iE=
|
||||
20240229200634_add_card_type.sql h1:y6kam4J45wzdgUh7eU9TTgbs8GwKuqNWyfqaFEtNgbY=
|
||||
20240317101809_add_payment_vnd.sql h1:IuRWMJvwkPoZJ+T9luhjvnaBwGQIvgU5vJbduE4HMok=
|
||||
213
examples/migration/ent/migrate/schema.go
Normal file
213
examples/migration/ent/migrate/schema.go
Normal 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 migrate
|
||||
|
||||
import (
|
||||
"entgo.io/ent/dialect/entsql"
|
||||
"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: "type", Type: field.TypeString, Default: "unknown"},
|
||||
{Name: "number_hash", Type: field.TypeString},
|
||||
{Name: "cvv_hash", Type: field.TypeString},
|
||||
{Name: "expires_at", Type: field.TypeTime, Nullable: true},
|
||||
{Name: "owner_id", Type: field.TypeInt, Default: 0},
|
||||
}
|
||||
// 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[5]},
|
||||
RefColumns: []*schema.Column{UsersColumns[0]},
|
||||
OnDelete: schema.NoAction,
|
||||
},
|
||||
},
|
||||
}
|
||||
// PaymentsColumns holds the columns for the "payments" table.
|
||||
PaymentsColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeInt, Increment: true},
|
||||
{Name: "amount", Type: field.TypeFloat64},
|
||||
{Name: "currency", Type: field.TypeEnum, Enums: []string{"USD", "EUR", "VND", "ILS"}},
|
||||
{Name: "time", Type: field.TypeTime},
|
||||
{Name: "description", Type: field.TypeString},
|
||||
{Name: "status", Type: field.TypeEnum, Enums: []string{"pending", "completed", "failed"}},
|
||||
{Name: "card_id", Type: field.TypeInt},
|
||||
}
|
||||
// PaymentsTable holds the schema information for the "payments" table.
|
||||
PaymentsTable = &schema.Table{
|
||||
Name: "payments",
|
||||
Columns: PaymentsColumns,
|
||||
PrimaryKey: []*schema.Column{PaymentsColumns[0]},
|
||||
ForeignKeys: []*schema.ForeignKey{
|
||||
{
|
||||
Symbol: "payments_cards_payments",
|
||||
Columns: []*schema.Column{PaymentsColumns[6]},
|
||||
RefColumns: []*schema.Column{CardsColumns[0]},
|
||||
OnDelete: schema.NoAction,
|
||||
},
|
||||
},
|
||||
Indexes: []*schema.Index{
|
||||
{
|
||||
Name: "payment_status_time",
|
||||
Unique: false,
|
||||
Columns: []*schema.Column{PaymentsColumns[5], PaymentsColumns[3]},
|
||||
},
|
||||
},
|
||||
}
|
||||
// PetsColumns holds the columns for the "pets" table.
|
||||
PetsColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeUUID},
|
||||
{Name: "name", Type: field.TypeString},
|
||||
{Name: "age", Type: field.TypeFloat64},
|
||||
{Name: "weight", Type: field.TypeFloat64},
|
||||
{Name: "best_friend_id", Type: field.TypeUUID, Unique: true, Nullable: true, Default: "00000000-0000-0000-0000-000000000000"},
|
||||
{Name: "owner_id", Type: field.TypeInt, Default: 0},
|
||||
}
|
||||
// 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_pets_best_friend",
|
||||
Columns: []*schema.Column{PetsColumns[4]},
|
||||
RefColumns: []*schema.Column{PetsColumns[0]},
|
||||
OnDelete: schema.SetNull,
|
||||
},
|
||||
{
|
||||
Symbol: "pets_users_owner",
|
||||
Columns: []*schema.Column{PetsColumns[5]},
|
||||
RefColumns: []*schema.Column{UsersColumns[0]},
|
||||
OnDelete: schema.NoAction,
|
||||
},
|
||||
},
|
||||
Indexes: []*schema.Index{
|
||||
{
|
||||
Name: "pet_name_owner_id",
|
||||
Unique: true,
|
||||
Columns: []*schema.Column{PetsColumns[1], PetsColumns[5]},
|
||||
},
|
||||
},
|
||||
}
|
||||
// SessionsColumns holds the columns for the "sessions" table.
|
||||
SessionsColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeUUID},
|
||||
{Name: "active", Type: field.TypeBool, Default: false},
|
||||
{Name: "issued_at", Type: field.TypeTime},
|
||||
{Name: "expires_at", Type: field.TypeTime, Nullable: true},
|
||||
{Name: "token", Type: field.TypeString, Nullable: true},
|
||||
{Name: "method", Type: field.TypeJSON, Nullable: true},
|
||||
{Name: "device_id", Type: field.TypeUUID, Nullable: true},
|
||||
}
|
||||
// SessionsTable holds the schema information for the "sessions" table.
|
||||
SessionsTable = &schema.Table{
|
||||
Name: "sessions",
|
||||
Columns: SessionsColumns,
|
||||
PrimaryKey: []*schema.Column{SessionsColumns[0]},
|
||||
ForeignKeys: []*schema.ForeignKey{
|
||||
{
|
||||
Symbol: "sessions_session_devices_sessions",
|
||||
Columns: []*schema.Column{SessionsColumns[6]},
|
||||
RefColumns: []*schema.Column{SessionDevicesColumns[0]},
|
||||
OnDelete: schema.SetNull,
|
||||
},
|
||||
},
|
||||
Indexes: []*schema.Index{
|
||||
{
|
||||
Name: "session_active_expires_at",
|
||||
Unique: false,
|
||||
Columns: []*schema.Column{SessionsColumns[1], SessionsColumns[3]},
|
||||
},
|
||||
},
|
||||
}
|
||||
// SessionDevicesColumns holds the columns for the "session_devices" table.
|
||||
SessionDevicesColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeUUID},
|
||||
{Name: "ip_address", Type: field.TypeString, Size: 50},
|
||||
{Name: "user_agent", Type: field.TypeString, Size: 512},
|
||||
{Name: "location", Type: field.TypeString, Size: 512},
|
||||
{Name: "created_at", Type: field.TypeTime},
|
||||
{Name: "updated_at", Type: field.TypeTime, Nullable: true},
|
||||
}
|
||||
// SessionDevicesTable holds the schema information for the "session_devices" table.
|
||||
SessionDevicesTable = &schema.Table{
|
||||
Name: "session_devices",
|
||||
Columns: SessionDevicesColumns,
|
||||
PrimaryKey: []*schema.Column{SessionDevicesColumns[0]},
|
||||
Indexes: []*schema.Index{
|
||||
{
|
||||
Name: "sessiondevice_ip_address_user_agent",
|
||||
Unique: false,
|
||||
Columns: []*schema.Column{SessionDevicesColumns[1], SessionDevicesColumns[2]},
|
||||
},
|
||||
{
|
||||
Name: "sessiondevice_location_updated_at",
|
||||
Unique: false,
|
||||
Columns: []*schema.Column{SessionDevicesColumns[3], SessionDevicesColumns[5]},
|
||||
},
|
||||
},
|
||||
}
|
||||
// UsersColumns holds the columns for the "users" table.
|
||||
UsersColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeInt, Increment: true},
|
||||
{Name: "age", Type: field.TypeFloat64},
|
||||
{Name: "first_name", Type: field.TypeString},
|
||||
{Name: "last_name", Type: field.TypeString},
|
||||
{Name: "tags", Type: field.TypeJSON, Nullable: true},
|
||||
}
|
||||
// UsersTable holds the schema information for the "users" table.
|
||||
UsersTable = &schema.Table{
|
||||
Name: "users",
|
||||
Columns: UsersColumns,
|
||||
PrimaryKey: []*schema.Column{UsersColumns[0]},
|
||||
}
|
||||
// Tables holds all the tables in the schema.
|
||||
Tables = []*schema.Table{
|
||||
CardsTable,
|
||||
PaymentsTable,
|
||||
PetsTable,
|
||||
SessionsTable,
|
||||
SessionDevicesTable,
|
||||
UsersTable,
|
||||
}
|
||||
)
|
||||
|
||||
func init() {
|
||||
CardsTable.ForeignKeys[0].RefTable = UsersTable
|
||||
CardsTable.Annotation = &entsql.Annotation{}
|
||||
CardsTable.Annotation.Checks = map[string]string{
|
||||
"number_hash_length": "(LENGTH(`number_hash`) = 16)",
|
||||
}
|
||||
PaymentsTable.ForeignKeys[0].RefTable = CardsTable
|
||||
PaymentsTable.Annotation = &entsql.Annotation{}
|
||||
PaymentsTable.Annotation.Checks = map[string]string{
|
||||
"amount_positive": "(`amount` > 0)",
|
||||
}
|
||||
PetsTable.ForeignKeys[0].RefTable = PetsTable
|
||||
PetsTable.ForeignKeys[1].RefTable = UsersTable
|
||||
SessionsTable.ForeignKeys[0].RefTable = SessionDevicesTable
|
||||
SessionsTable.Annotation = &entsql.Annotation{}
|
||||
SessionsTable.Annotation.Checks = map[string]string{
|
||||
"token_length": "(LENGTH(`token`) = 64)",
|
||||
}
|
||||
UsersTable.Annotation = &entsql.Annotation{
|
||||
Check: "age > 0",
|
||||
}
|
||||
UsersTable.Annotation.Checks = map[string]string{
|
||||
"first_last_not_empty": "(`first_name` <> '' AND `last_name` <> '')",
|
||||
}
|
||||
}
|
||||
1332
examples/migration/ent/mutation.go
Normal file
1332
examples/migration/ent/mutation.go
Normal file
File diff suppressed because it is too large
Load Diff
196
examples/migration/ent/payment.go
Normal file
196
examples/migration/ent/payment.go
Normal file
@@ -0,0 +1,196 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/examples/migration/ent/card"
|
||||
"entgo.io/ent/examples/migration/ent/payment"
|
||||
)
|
||||
|
||||
// Payment is the model entity for the Payment schema.
|
||||
type Payment struct {
|
||||
config `json:"-"`
|
||||
// ID of the ent.
|
||||
ID int `json:"id,omitempty"`
|
||||
// CardID holds the value of the "card_id" field.
|
||||
CardID int `json:"card_id,omitempty"`
|
||||
// Amount holds the value of the "amount" field.
|
||||
Amount float64 `json:"amount,omitempty"`
|
||||
// Currency holds the value of the "currency" field.
|
||||
Currency payment.Currency `json:"currency,omitempty"`
|
||||
// Time holds the value of the "time" field.
|
||||
Time time.Time `json:"time,omitempty"`
|
||||
// Description holds the value of the "description" field.
|
||||
Description string `json:"description,omitempty"`
|
||||
// Status holds the value of the "status" field.
|
||||
Status payment.Status `json:"status,omitempty"`
|
||||
// Edges holds the relations/edges for other nodes in the graph.
|
||||
// The values are being populated by the PaymentQuery when eager-loading is set.
|
||||
Edges PaymentEdges `json:"edges"`
|
||||
selectValues sql.SelectValues
|
||||
}
|
||||
|
||||
// PaymentEdges holds the relations/edges for other nodes in the graph.
|
||||
type PaymentEdges struct {
|
||||
// Card holds the value of the card edge.
|
||||
Card *Card `json:"card,omitempty"`
|
||||
// loadedTypes holds the information for reporting if a
|
||||
// type was loaded (or requested) in eager-loading or not.
|
||||
loadedTypes [1]bool
|
||||
}
|
||||
|
||||
// CardOrErr returns the Card value or an error if the edge
|
||||
// was not loaded in eager-loading, or loaded but was not found.
|
||||
func (e PaymentEdges) CardOrErr() (*Card, error) {
|
||||
if e.Card != nil {
|
||||
return e.Card, nil
|
||||
} else if e.loadedTypes[0] {
|
||||
return nil, &NotFoundError{label: card.Label}
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "card"}
|
||||
}
|
||||
|
||||
// scanValues returns the types for scanning values from sql.Rows.
|
||||
func (*Payment) scanValues(columns []string) ([]any, error) {
|
||||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case payment.FieldAmount:
|
||||
values[i] = new(sql.NullFloat64)
|
||||
case payment.FieldID, payment.FieldCardID:
|
||||
values[i] = new(sql.NullInt64)
|
||||
case payment.FieldCurrency, payment.FieldDescription, payment.FieldStatus:
|
||||
values[i] = new(sql.NullString)
|
||||
case payment.FieldTime:
|
||||
values[i] = new(sql.NullTime)
|
||||
default:
|
||||
values[i] = new(sql.UnknownType)
|
||||
}
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// assignValues assigns the values that were returned from sql.Rows (after scanning)
|
||||
// to the Payment fields.
|
||||
func (_m *Payment) 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 payment.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 payment.FieldCardID:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field card_id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.CardID = int(value.Int64)
|
||||
}
|
||||
case payment.FieldAmount:
|
||||
if value, ok := values[i].(*sql.NullFloat64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field amount", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Amount = value.Float64
|
||||
}
|
||||
case payment.FieldCurrency:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field currency", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Currency = payment.Currency(value.String)
|
||||
}
|
||||
case payment.FieldTime:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field time", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Time = value.Time
|
||||
}
|
||||
case payment.FieldDescription:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field description", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Description = value.String
|
||||
}
|
||||
case payment.FieldStatus:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field status", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Status = payment.Status(value.String)
|
||||
}
|
||||
default:
|
||||
_m.selectValues.Set(columns[i], values[i])
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Value returns the ent.Value that was dynamically selected and assigned to the Payment.
|
||||
// This includes values selected through modifiers, order, etc.
|
||||
func (_m *Payment) Value(name string) (ent.Value, error) {
|
||||
return _m.selectValues.Get(name)
|
||||
}
|
||||
|
||||
// QueryCard queries the "card" edge of the Payment entity.
|
||||
func (_m *Payment) QueryCard() *CardQuery {
|
||||
return NewPaymentClient(_m.config).QueryCard(_m)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this Payment.
|
||||
// Note that you need to call Payment.Unwrap() before calling this method if this Payment
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (_m *Payment) Update() *PaymentUpdateOne {
|
||||
return NewPaymentClient(_m.config).UpdateOne(_m)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the Payment 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 *Payment) Unwrap() *Payment {
|
||||
_tx, ok := _m.config.driver.(*txDriver)
|
||||
if !ok {
|
||||
panic("ent: Payment is not a transactional entity")
|
||||
}
|
||||
_m.config.driver = _tx.drv
|
||||
return _m
|
||||
}
|
||||
|
||||
// String implements the fmt.Stringer.
|
||||
func (_m *Payment) String() string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("Payment(")
|
||||
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
|
||||
builder.WriteString("card_id=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.CardID))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("amount=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.Amount))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("currency=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.Currency))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("time=")
|
||||
builder.WriteString(_m.Time.Format(time.ANSIC))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("description=")
|
||||
builder.WriteString(_m.Description)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("status=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.Status))
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// Payments is a parsable slice of Payment.
|
||||
type Payments []*Payment
|
||||
499
examples/migration/ent/payment/mutation.go
Normal file
499
examples/migration/ent/payment/mutation.go
Normal file
@@ -0,0 +1,499 @@
|
||||
// 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 payment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/examples/migration/ent/predicate"
|
||||
)
|
||||
|
||||
// Mutation represents an operation that mutates the Payment nodes in the graph.
|
||||
type Mutation struct {
|
||||
op ent.Op
|
||||
typ string
|
||||
amount *float64
|
||||
addamount *float64
|
||||
currency *Currency
|
||||
time *time.Time
|
||||
description *string
|
||||
status *Status
|
||||
clearedFields map[string]struct{}
|
||||
card *int
|
||||
clearedcard bool
|
||||
predicates []predicate.Payment
|
||||
}
|
||||
|
||||
// NewMutation creates a new Mutation for the Payment entity.
|
||||
func NewMutation(op ent.Op) *Mutation {
|
||||
return &Mutation{
|
||||
op: op,
|
||||
typ: "Payment",
|
||||
clearedFields: make(map[string]struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
// Predicates returns the list of predicates set on the mutation.
|
||||
func (m *Mutation) Predicates() []predicate.Payment {
|
||||
return m.predicates
|
||||
}
|
||||
|
||||
// SetCardID sets the "card_id" field.
|
||||
func (m *Mutation) SetCardID(i int) {
|
||||
m.card = &i
|
||||
}
|
||||
|
||||
// CardID returns the value of the "card_id" field in the mutation.
|
||||
func (m *Mutation) CardID() (r int, exists bool) {
|
||||
v := m.card
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetCardID resets all changes to the "card_id" field.
|
||||
func (m *Mutation) ResetCardID() {
|
||||
m.card = nil
|
||||
}
|
||||
|
||||
// SetAmount sets the "amount" field.
|
||||
func (m *Mutation) SetAmount(f float64) {
|
||||
m.amount = &f
|
||||
m.addamount = nil
|
||||
}
|
||||
|
||||
// Amount returns the value of the "amount" field in the mutation.
|
||||
func (m *Mutation) Amount() (r float64, exists bool) {
|
||||
v := m.amount
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// AddAmount adds f to the "amount" field.
|
||||
func (m *Mutation) AddAmount(f float64) {
|
||||
if m.addamount != nil {
|
||||
*m.addamount += f
|
||||
} else {
|
||||
m.addamount = &f
|
||||
}
|
||||
}
|
||||
|
||||
// AddedAmount returns the value that was added to the "amount" field in this mutation.
|
||||
func (m *Mutation) AddedAmount() (r float64, exists bool) {
|
||||
v := m.addamount
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetAmount resets all changes to the "amount" field.
|
||||
func (m *Mutation) ResetAmount() {
|
||||
m.amount = nil
|
||||
m.addamount = nil
|
||||
}
|
||||
|
||||
// SetCurrency sets the "currency" field.
|
||||
func (m *Mutation) SetCurrency(pa Currency) {
|
||||
m.currency = &pa
|
||||
}
|
||||
|
||||
// Currency returns the value of the "currency" field in the mutation.
|
||||
func (m *Mutation) Currency() (r Currency, exists bool) {
|
||||
v := m.currency
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetCurrency resets all changes to the "currency" field.
|
||||
func (m *Mutation) ResetCurrency() {
|
||||
m.currency = nil
|
||||
}
|
||||
|
||||
// SetTime sets the "time" field.
|
||||
func (m *Mutation) SetTime(t time.Time) {
|
||||
m.time = &t
|
||||
}
|
||||
|
||||
// Time returns the value of the "time" field in the mutation.
|
||||
func (m *Mutation) Time() (r time.Time, exists bool) {
|
||||
v := m.time
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetTime resets all changes to the "time" field.
|
||||
func (m *Mutation) ResetTime() {
|
||||
m.time = nil
|
||||
}
|
||||
|
||||
// SetDescription sets the "description" field.
|
||||
func (m *Mutation) SetDescription(s string) {
|
||||
m.description = &s
|
||||
}
|
||||
|
||||
// Description returns the value of the "description" field in the mutation.
|
||||
func (m *Mutation) Description() (r string, exists bool) {
|
||||
v := m.description
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetDescription resets all changes to the "description" field.
|
||||
func (m *Mutation) ResetDescription() {
|
||||
m.description = nil
|
||||
}
|
||||
|
||||
// SetStatus sets the "status" field.
|
||||
func (m *Mutation) SetStatus(pa Status) {
|
||||
m.status = &pa
|
||||
}
|
||||
|
||||
// Status returns the value of the "status" field in the mutation.
|
||||
func (m *Mutation) Status() (r Status, exists bool) {
|
||||
v := m.status
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetStatus resets all changes to the "status" field.
|
||||
func (m *Mutation) ResetStatus() {
|
||||
m.status = nil
|
||||
}
|
||||
|
||||
// ClearCard clears the "card" edge to the Card entity.
|
||||
func (m *Mutation) ClearCard() {
|
||||
m.clearedcard = true
|
||||
m.clearedFields[FieldCardID] = struct{}{}
|
||||
}
|
||||
|
||||
// CardCleared reports if the "card" edge to the Card entity was cleared.
|
||||
func (m *Mutation) CardCleared() bool {
|
||||
return m.clearedcard
|
||||
}
|
||||
|
||||
// CardIDs returns the "card" edge IDs in the mutation.
|
||||
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
|
||||
// CardID instead. It exists only for internal usage by the builders.
|
||||
func (m *Mutation) CardIDs() (ids []int) {
|
||||
if id := m.card; id != nil {
|
||||
ids = append(ids, *id)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ResetCard resets all changes to the "card" edge.
|
||||
func (m *Mutation) ResetCard() {
|
||||
m.card = nil
|
||||
m.clearedcard = false
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the Mutation builder.
|
||||
func (m *Mutation) Where(ps ...predicate.Payment) {
|
||||
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.Payment, 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 (Payment).
|
||||
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, 6)
|
||||
if m.card != nil {
|
||||
fields = append(fields, FieldCardID)
|
||||
}
|
||||
if m.amount != nil {
|
||||
fields = append(fields, FieldAmount)
|
||||
}
|
||||
if m.currency != nil {
|
||||
fields = append(fields, FieldCurrency)
|
||||
}
|
||||
if m.time != nil {
|
||||
fields = append(fields, FieldTime)
|
||||
}
|
||||
if m.description != nil {
|
||||
fields = append(fields, FieldDescription)
|
||||
}
|
||||
if m.status != nil {
|
||||
fields = append(fields, FieldStatus)
|
||||
}
|
||||
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 FieldCardID:
|
||||
return m.CardID()
|
||||
case FieldAmount:
|
||||
return m.Amount()
|
||||
case FieldCurrency:
|
||||
return m.Currency()
|
||||
case FieldTime:
|
||||
return m.Time()
|
||||
case FieldDescription:
|
||||
return m.Description()
|
||||
case FieldStatus:
|
||||
return m.Status()
|
||||
}
|
||||
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 Payment 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 FieldCardID:
|
||||
v, ok := value.(int)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetCardID(v)
|
||||
return nil
|
||||
case FieldAmount:
|
||||
v, ok := value.(float64)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetAmount(v)
|
||||
return nil
|
||||
case FieldCurrency:
|
||||
v, ok := value.(Currency)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetCurrency(v)
|
||||
return nil
|
||||
case FieldTime:
|
||||
v, ok := value.(time.Time)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetTime(v)
|
||||
return nil
|
||||
case FieldDescription:
|
||||
v, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetDescription(v)
|
||||
return nil
|
||||
case FieldStatus:
|
||||
v, ok := value.(Status)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetStatus(v)
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown Payment 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.addamount != nil {
|
||||
fields = append(fields, FieldAmount)
|
||||
}
|
||||
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 FieldAmount:
|
||||
return m.AddedAmount()
|
||||
}
|
||||
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 FieldAmount:
|
||||
v, ok := value.(float64)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.AddAmount(v)
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown Payment numeric field %s", name)
|
||||
}
|
||||
|
||||
// ClearedFields returns all nullable fields that were cleared during this
|
||||
// mutation.
|
||||
func (m *Mutation) ClearedFields() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
// FieldCleared returns a boolean indicating if a field with the given name was
|
||||
// cleared in this mutation.
|
||||
func (m *Mutation) FieldCleared(name string) bool {
|
||||
_, ok := m.clearedFields[name]
|
||||
return ok
|
||||
}
|
||||
|
||||
// ClearField clears the value of the field with the given name. It returns an
|
||||
// error if the field is not defined in the schema.
|
||||
func (m *Mutation) ClearField(name string) error {
|
||||
return fmt.Errorf("unknown Payment 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 FieldCardID:
|
||||
m.ResetCardID()
|
||||
return nil
|
||||
case FieldAmount:
|
||||
m.ResetAmount()
|
||||
return nil
|
||||
case FieldCurrency:
|
||||
m.ResetCurrency()
|
||||
return nil
|
||||
case FieldTime:
|
||||
m.ResetTime()
|
||||
return nil
|
||||
case FieldDescription:
|
||||
m.ResetDescription()
|
||||
return nil
|
||||
case FieldStatus:
|
||||
m.ResetStatus()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown Payment 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.card != nil {
|
||||
edges = append(edges, EdgeCard)
|
||||
}
|
||||
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 EdgeCard:
|
||||
if id := m.card; 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.clearedcard {
|
||||
edges = append(edges, EdgeCard)
|
||||
}
|
||||
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 EdgeCard:
|
||||
return m.clearedcard
|
||||
}
|
||||
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 EdgeCard:
|
||||
m.ClearCard()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown Payment 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 EdgeCard:
|
||||
m.ResetCard()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown Payment edge %s", name)
|
||||
}
|
||||
171
examples/migration/ent/payment/payment.go
Normal file
171
examples/migration/ent/payment/payment.go
Normal file
@@ -0,0 +1,171 @@
|
||||
// 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 payment
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
)
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the payment type in the database.
|
||||
Label = "payment"
|
||||
// FieldID holds the string denoting the id field in the database.
|
||||
FieldID = "id"
|
||||
// FieldCardID holds the string denoting the card_id field in the database.
|
||||
FieldCardID = "card_id"
|
||||
// FieldAmount holds the string denoting the amount field in the database.
|
||||
FieldAmount = "amount"
|
||||
// FieldCurrency holds the string denoting the currency field in the database.
|
||||
FieldCurrency = "currency"
|
||||
// FieldTime holds the string denoting the time field in the database.
|
||||
FieldTime = "time"
|
||||
// FieldDescription holds the string denoting the description field in the database.
|
||||
FieldDescription = "description"
|
||||
// FieldStatus holds the string denoting the status field in the database.
|
||||
FieldStatus = "status"
|
||||
// EdgeCard holds the string denoting the card edge name in mutations.
|
||||
EdgeCard = "card"
|
||||
// Table holds the table name of the payment in the database.
|
||||
Table = "payments"
|
||||
// CardTable is the table that holds the card relation/edge.
|
||||
CardTable = "payments"
|
||||
// CardInverseTable is the table name for the Card entity.
|
||||
// It exists in this package in order to avoid circular dependency with the "card" package.
|
||||
CardInverseTable = "cards"
|
||||
// CardColumn is the table column denoting the card relation/edge.
|
||||
CardColumn = "card_id"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for payment fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldCardID,
|
||||
FieldAmount,
|
||||
FieldCurrency,
|
||||
FieldTime,
|
||||
FieldDescription,
|
||||
FieldStatus,
|
||||
}
|
||||
|
||||
// ValidColumn reports if the column name is valid (part of the table columns).
|
||||
func ValidColumn(column string) bool {
|
||||
for i := range Columns {
|
||||
if column == Columns[i] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var (
|
||||
// AmountValidator is a validator for the "amount" field. It is called by the builders before save.
|
||||
AmountValidator func(float64) error
|
||||
)
|
||||
|
||||
// Currency defines the type for the "currency" enum field.
|
||||
type Currency string
|
||||
|
||||
// Currency values.
|
||||
const (
|
||||
CurrencyUSD Currency = "USD"
|
||||
CurrencyEUR Currency = "EUR"
|
||||
CurrencyVND Currency = "VND"
|
||||
CurrencyILS Currency = "ILS"
|
||||
)
|
||||
|
||||
func (c Currency) String() string {
|
||||
return string(c)
|
||||
}
|
||||
|
||||
// CurrencyValidator is a validator for the "currency" field enum values. It is called by the builders before save.
|
||||
func CurrencyValidator(c Currency) error {
|
||||
switch c {
|
||||
case CurrencyUSD, CurrencyEUR, CurrencyVND, CurrencyILS:
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("payment: invalid enum value for currency field: %q", c)
|
||||
}
|
||||
}
|
||||
|
||||
// Status defines the type for the "status" enum field.
|
||||
type Status string
|
||||
|
||||
// Status values.
|
||||
const (
|
||||
StatusPending Status = "pending"
|
||||
StatusCompleted Status = "completed"
|
||||
StatusFailed Status = "failed"
|
||||
)
|
||||
|
||||
func (s Status) String() string {
|
||||
return string(s)
|
||||
}
|
||||
|
||||
// StatusValidator is a validator for the "status" field enum values. It is called by the builders before save.
|
||||
func StatusValidator(s Status) error {
|
||||
switch s {
|
||||
case StatusPending, StatusCompleted, StatusFailed:
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("payment: invalid enum value for status field: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// OrderOption defines the ordering options for the Payment 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()
|
||||
}
|
||||
|
||||
// ByCardID orders the results by the card_id field.
|
||||
func ByCardID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldCardID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByAmount orders the results by the amount field.
|
||||
func ByAmount(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldAmount, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByCurrency orders the results by the currency field.
|
||||
func ByCurrency(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldCurrency, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByTime orders the results by the time field.
|
||||
func ByTime(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldTime, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByDescription orders the results by the description field.
|
||||
func ByDescription(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldDescription, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByStatus orders the results by the status field.
|
||||
func ByStatus(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldStatus, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByCardField orders the results by card field.
|
||||
func ByCardField(field string, opts ...sql.OrderTermOption) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborTerms(s, newCardStep(), sql.OrderByField(field, opts...))
|
||||
}
|
||||
}
|
||||
func newCardStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(CardInverseTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, CardTable, CardColumn),
|
||||
)
|
||||
}
|
||||
323
examples/migration/ent/payment/where.go
Normal file
323
examples/migration/ent/payment/where.go
Normal file
@@ -0,0 +1,323 @@
|
||||
// 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 payment
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/predicate"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id int) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id int) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id int) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldNEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...int) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...int) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldNotIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id int) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldGT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id int) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldGTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id int) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldLT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id int) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldLTE(FieldID, id))
|
||||
}
|
||||
|
||||
// CardID applies equality check predicate on the "card_id" field. It's identical to CardIDEQ.
|
||||
func CardID(v int) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldEQ(FieldCardID, v))
|
||||
}
|
||||
|
||||
// Amount applies equality check predicate on the "amount" field. It's identical to AmountEQ.
|
||||
func Amount(v float64) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldEQ(FieldAmount, v))
|
||||
}
|
||||
|
||||
// Time applies equality check predicate on the "time" field. It's identical to TimeEQ.
|
||||
func Time(v time.Time) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldEQ(FieldTime, v))
|
||||
}
|
||||
|
||||
// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ.
|
||||
func Description(v string) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldEQ(FieldDescription, v))
|
||||
}
|
||||
|
||||
// CardIDEQ applies the EQ predicate on the "card_id" field.
|
||||
func CardIDEQ(v int) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldEQ(FieldCardID, v))
|
||||
}
|
||||
|
||||
// CardIDNEQ applies the NEQ predicate on the "card_id" field.
|
||||
func CardIDNEQ(v int) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldNEQ(FieldCardID, v))
|
||||
}
|
||||
|
||||
// CardIDIn applies the In predicate on the "card_id" field.
|
||||
func CardIDIn(vs ...int) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldIn(FieldCardID, vs...))
|
||||
}
|
||||
|
||||
// CardIDNotIn applies the NotIn predicate on the "card_id" field.
|
||||
func CardIDNotIn(vs ...int) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldNotIn(FieldCardID, vs...))
|
||||
}
|
||||
|
||||
// AmountEQ applies the EQ predicate on the "amount" field.
|
||||
func AmountEQ(v float64) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldEQ(FieldAmount, v))
|
||||
}
|
||||
|
||||
// AmountNEQ applies the NEQ predicate on the "amount" field.
|
||||
func AmountNEQ(v float64) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldNEQ(FieldAmount, v))
|
||||
}
|
||||
|
||||
// AmountIn applies the In predicate on the "amount" field.
|
||||
func AmountIn(vs ...float64) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldIn(FieldAmount, vs...))
|
||||
}
|
||||
|
||||
// AmountNotIn applies the NotIn predicate on the "amount" field.
|
||||
func AmountNotIn(vs ...float64) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldNotIn(FieldAmount, vs...))
|
||||
}
|
||||
|
||||
// AmountGT applies the GT predicate on the "amount" field.
|
||||
func AmountGT(v float64) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldGT(FieldAmount, v))
|
||||
}
|
||||
|
||||
// AmountGTE applies the GTE predicate on the "amount" field.
|
||||
func AmountGTE(v float64) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldGTE(FieldAmount, v))
|
||||
}
|
||||
|
||||
// AmountLT applies the LT predicate on the "amount" field.
|
||||
func AmountLT(v float64) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldLT(FieldAmount, v))
|
||||
}
|
||||
|
||||
// AmountLTE applies the LTE predicate on the "amount" field.
|
||||
func AmountLTE(v float64) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldLTE(FieldAmount, v))
|
||||
}
|
||||
|
||||
// CurrencyEQ applies the EQ predicate on the "currency" field.
|
||||
func CurrencyEQ(v Currency) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldEQ(FieldCurrency, v))
|
||||
}
|
||||
|
||||
// CurrencyNEQ applies the NEQ predicate on the "currency" field.
|
||||
func CurrencyNEQ(v Currency) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldNEQ(FieldCurrency, v))
|
||||
}
|
||||
|
||||
// CurrencyIn applies the In predicate on the "currency" field.
|
||||
func CurrencyIn(vs ...Currency) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldIn(FieldCurrency, vs...))
|
||||
}
|
||||
|
||||
// CurrencyNotIn applies the NotIn predicate on the "currency" field.
|
||||
func CurrencyNotIn(vs ...Currency) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldNotIn(FieldCurrency, vs...))
|
||||
}
|
||||
|
||||
// TimeEQ applies the EQ predicate on the "time" field.
|
||||
func TimeEQ(v time.Time) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldEQ(FieldTime, v))
|
||||
}
|
||||
|
||||
// TimeNEQ applies the NEQ predicate on the "time" field.
|
||||
func TimeNEQ(v time.Time) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldNEQ(FieldTime, v))
|
||||
}
|
||||
|
||||
// TimeIn applies the In predicate on the "time" field.
|
||||
func TimeIn(vs ...time.Time) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldIn(FieldTime, vs...))
|
||||
}
|
||||
|
||||
// TimeNotIn applies the NotIn predicate on the "time" field.
|
||||
func TimeNotIn(vs ...time.Time) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldNotIn(FieldTime, vs...))
|
||||
}
|
||||
|
||||
// TimeGT applies the GT predicate on the "time" field.
|
||||
func TimeGT(v time.Time) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldGT(FieldTime, v))
|
||||
}
|
||||
|
||||
// TimeGTE applies the GTE predicate on the "time" field.
|
||||
func TimeGTE(v time.Time) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldGTE(FieldTime, v))
|
||||
}
|
||||
|
||||
// TimeLT applies the LT predicate on the "time" field.
|
||||
func TimeLT(v time.Time) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldLT(FieldTime, v))
|
||||
}
|
||||
|
||||
// TimeLTE applies the LTE predicate on the "time" field.
|
||||
func TimeLTE(v time.Time) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldLTE(FieldTime, v))
|
||||
}
|
||||
|
||||
// DescriptionEQ applies the EQ predicate on the "description" field.
|
||||
func DescriptionEQ(v string) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldEQ(FieldDescription, v))
|
||||
}
|
||||
|
||||
// DescriptionNEQ applies the NEQ predicate on the "description" field.
|
||||
func DescriptionNEQ(v string) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldNEQ(FieldDescription, v))
|
||||
}
|
||||
|
||||
// DescriptionIn applies the In predicate on the "description" field.
|
||||
func DescriptionIn(vs ...string) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldIn(FieldDescription, vs...))
|
||||
}
|
||||
|
||||
// DescriptionNotIn applies the NotIn predicate on the "description" field.
|
||||
func DescriptionNotIn(vs ...string) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldNotIn(FieldDescription, vs...))
|
||||
}
|
||||
|
||||
// DescriptionGT applies the GT predicate on the "description" field.
|
||||
func DescriptionGT(v string) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldGT(FieldDescription, v))
|
||||
}
|
||||
|
||||
// DescriptionGTE applies the GTE predicate on the "description" field.
|
||||
func DescriptionGTE(v string) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldGTE(FieldDescription, v))
|
||||
}
|
||||
|
||||
// DescriptionLT applies the LT predicate on the "description" field.
|
||||
func DescriptionLT(v string) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldLT(FieldDescription, v))
|
||||
}
|
||||
|
||||
// DescriptionLTE applies the LTE predicate on the "description" field.
|
||||
func DescriptionLTE(v string) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldLTE(FieldDescription, v))
|
||||
}
|
||||
|
||||
// DescriptionContains applies the Contains predicate on the "description" field.
|
||||
func DescriptionContains(v string) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldContains(FieldDescription, v))
|
||||
}
|
||||
|
||||
// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field.
|
||||
func DescriptionHasPrefix(v string) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldHasPrefix(FieldDescription, v))
|
||||
}
|
||||
|
||||
// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field.
|
||||
func DescriptionHasSuffix(v string) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldHasSuffix(FieldDescription, v))
|
||||
}
|
||||
|
||||
// DescriptionEqualFold applies the EqualFold predicate on the "description" field.
|
||||
func DescriptionEqualFold(v string) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldEqualFold(FieldDescription, v))
|
||||
}
|
||||
|
||||
// DescriptionContainsFold applies the ContainsFold predicate on the "description" field.
|
||||
func DescriptionContainsFold(v string) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldContainsFold(FieldDescription, v))
|
||||
}
|
||||
|
||||
// StatusEQ applies the EQ predicate on the "status" field.
|
||||
func StatusEQ(v Status) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldEQ(FieldStatus, v))
|
||||
}
|
||||
|
||||
// StatusNEQ applies the NEQ predicate on the "status" field.
|
||||
func StatusNEQ(v Status) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldNEQ(FieldStatus, v))
|
||||
}
|
||||
|
||||
// StatusIn applies the In predicate on the "status" field.
|
||||
func StatusIn(vs ...Status) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldIn(FieldStatus, vs...))
|
||||
}
|
||||
|
||||
// StatusNotIn applies the NotIn predicate on the "status" field.
|
||||
func StatusNotIn(vs ...Status) predicate.Payment {
|
||||
return predicate.Payment(sql.FieldNotIn(FieldStatus, vs...))
|
||||
}
|
||||
|
||||
// HasCard applies the HasEdge predicate on the "card" edge.
|
||||
func HasCard() predicate.Payment {
|
||||
return predicate.Payment(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, CardTable, CardColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
})
|
||||
}
|
||||
|
||||
// HasCardWith applies the HasEdge predicate on the "card" edge with a given conditions (other predicates).
|
||||
func HasCardWith(preds ...predicate.Card) predicate.Payment {
|
||||
return predicate.Payment(func(s *sql.Selector) {
|
||||
step := newCardStep()
|
||||
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.Payment) predicate.Payment {
|
||||
return predicate.Payment(sql.AndPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Or groups predicates with the OR operator between them.
|
||||
func Or(predicates ...predicate.Payment) predicate.Payment {
|
||||
return predicate.Payment(sql.OrPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Not applies the not operator on the given predicate.
|
||||
func Not(p predicate.Payment) predicate.Payment {
|
||||
return predicate.Payment(sql.NotPredicates(p))
|
||||
}
|
||||
290
examples/migration/ent/payment_create.go
Normal file
290
examples/migration/ent/payment_create.go
Normal file
@@ -0,0 +1,290 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/card"
|
||||
"entgo.io/ent/examples/migration/ent/payment"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// PaymentCreate is the builder for creating a Payment entity.
|
||||
type PaymentCreate struct {
|
||||
config
|
||||
mutation *PaymentMutation
|
||||
hooks []Hook
|
||||
}
|
||||
|
||||
// SetCardID sets the "card_id" field.
|
||||
func (_c *PaymentCreate) SetCardID(v int) *PaymentCreate {
|
||||
_c.mutation.SetCardID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetAmount sets the "amount" field.
|
||||
func (_c *PaymentCreate) SetAmount(v float64) *PaymentCreate {
|
||||
_c.mutation.SetAmount(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetCurrency sets the "currency" field.
|
||||
func (_c *PaymentCreate) SetCurrency(v payment.Currency) *PaymentCreate {
|
||||
_c.mutation.SetCurrency(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetTime sets the "time" field.
|
||||
func (_c *PaymentCreate) SetTime(v time.Time) *PaymentCreate {
|
||||
_c.mutation.SetTime(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetDescription sets the "description" field.
|
||||
func (_c *PaymentCreate) SetDescription(v string) *PaymentCreate {
|
||||
_c.mutation.SetDescription(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetStatus sets the "status" field.
|
||||
func (_c *PaymentCreate) SetStatus(v payment.Status) *PaymentCreate {
|
||||
_c.mutation.SetStatus(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetCard sets the "card" edge to the Card entity.
|
||||
func (_c *PaymentCreate) SetCard(v *Card) *PaymentCreate {
|
||||
return _c.SetCardID(v.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the PaymentMutation object of the builder.
|
||||
func (_c *PaymentCreate) Mutation() *PaymentMutation {
|
||||
return _c.mutation
|
||||
}
|
||||
|
||||
// Save creates the Payment in the database.
|
||||
func (_c *PaymentCreate) Save(ctx context.Context) (*Payment, error) {
|
||||
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
func (_c *PaymentCreate) SaveX(ctx context.Context) *Payment {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *PaymentCreate) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *PaymentCreate) 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 *PaymentCreate) check() error {
|
||||
if _, ok := _c.mutation.CardID(); !ok {
|
||||
return &ValidationError{Name: "card_id", err: errors.New(`ent: missing required field "Payment.card_id"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.Amount(); !ok {
|
||||
return &ValidationError{Name: "amount", err: errors.New(`ent: missing required field "Payment.amount"`)}
|
||||
}
|
||||
if v, ok := _c.mutation.Amount(); ok {
|
||||
if err := payment.AmountValidator(v); err != nil {
|
||||
return &ValidationError{Name: "amount", err: fmt.Errorf(`ent: validator failed for field "Payment.amount": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := _c.mutation.Currency(); !ok {
|
||||
return &ValidationError{Name: "currency", err: errors.New(`ent: missing required field "Payment.currency"`)}
|
||||
}
|
||||
if v, ok := _c.mutation.Currency(); ok {
|
||||
if err := payment.CurrencyValidator(v); err != nil {
|
||||
return &ValidationError{Name: "currency", err: fmt.Errorf(`ent: validator failed for field "Payment.currency": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := _c.mutation.Time(); !ok {
|
||||
return &ValidationError{Name: "time", err: errors.New(`ent: missing required field "Payment.time"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.Description(); !ok {
|
||||
return &ValidationError{Name: "description", err: errors.New(`ent: missing required field "Payment.description"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.Status(); !ok {
|
||||
return &ValidationError{Name: "status", err: errors.New(`ent: missing required field "Payment.status"`)}
|
||||
}
|
||||
if v, ok := _c.mutation.Status(); ok {
|
||||
if err := payment.StatusValidator(v); err != nil {
|
||||
return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Payment.status": %w`, err)}
|
||||
}
|
||||
}
|
||||
if len(_c.mutation.CardIDs()) == 0 {
|
||||
return &ValidationError{Name: "card", err: errors.New(`ent: missing required edge "Payment.card"`)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_c *PaymentCreate) sqlSave(ctx context.Context) (*Payment, 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 *PaymentCreate) createSpec() (*Payment, *sqlgraph.CreateSpec) {
|
||||
var (
|
||||
_node = &Payment{config: _c.config}
|
||||
_spec = sqlgraph.NewCreateSpec(payment.Table, sqlgraph.NewFieldSpec(payment.FieldID, field.TypeInt))
|
||||
)
|
||||
if value, ok := _c.mutation.Amount(); ok {
|
||||
_spec.SetField(payment.FieldAmount, field.TypeFloat64, value)
|
||||
_node.Amount = value
|
||||
}
|
||||
if value, ok := _c.mutation.Currency(); ok {
|
||||
_spec.SetField(payment.FieldCurrency, field.TypeEnum, value)
|
||||
_node.Currency = value
|
||||
}
|
||||
if value, ok := _c.mutation.Time(); ok {
|
||||
_spec.SetField(payment.FieldTime, field.TypeTime, value)
|
||||
_node.Time = value
|
||||
}
|
||||
if value, ok := _c.mutation.Description(); ok {
|
||||
_spec.SetField(payment.FieldDescription, field.TypeString, value)
|
||||
_node.Description = value
|
||||
}
|
||||
if value, ok := _c.mutation.Status(); ok {
|
||||
_spec.SetField(payment.FieldStatus, field.TypeEnum, value)
|
||||
_node.Status = value
|
||||
}
|
||||
if nodes := _c.mutation.CardIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: payment.CardTable,
|
||||
Columns: []string{payment.CardColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(card.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_node.CardID = nodes[0]
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
return _node, _spec
|
||||
}
|
||||
|
||||
// PaymentCreateBulk is the builder for creating many Payment entities in bulk.
|
||||
type PaymentCreateBulk struct {
|
||||
config
|
||||
err error
|
||||
builders []*PaymentCreate
|
||||
}
|
||||
|
||||
// Save creates the Payment entities in the database.
|
||||
func (_c *PaymentCreateBulk) Save(ctx context.Context) ([]*Payment, error) {
|
||||
if _c.err != nil {
|
||||
return nil, _c.err
|
||||
}
|
||||
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
|
||||
nodes := make([]*Payment, 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.(*PaymentMutation)
|
||||
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 *PaymentCreateBulk) SaveX(ctx context.Context) []*Payment {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *PaymentCreateBulk) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *PaymentCreateBulk) ExecX(ctx context.Context) {
|
||||
if err := _c.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
92
examples/migration/ent/payment_delete.go
Normal file
92
examples/migration/ent/payment_delete.go
Normal file
@@ -0,0 +1,92 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/payment"
|
||||
"entgo.io/ent/examples/migration/ent/predicate"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// PaymentDelete is the builder for deleting a Payment entity.
|
||||
type PaymentDelete struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *PaymentMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the PaymentDelete builder.
|
||||
func (_d *PaymentDelete) Where(ps ...predicate.Payment) *PaymentDelete {
|
||||
_d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (_d *PaymentDelete) 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 *PaymentDelete) ExecX(ctx context.Context) int {
|
||||
n, err := _d.Exec(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (_d *PaymentDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
_spec := sqlgraph.NewDeleteSpec(payment.Table, sqlgraph.NewFieldSpec(payment.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
|
||||
}
|
||||
|
||||
// PaymentDeleteOne is the builder for deleting a single Payment entity.
|
||||
type PaymentDeleteOne struct {
|
||||
_d *PaymentDelete
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the PaymentDelete builder.
|
||||
func (_d *PaymentDeleteOne) Where(ps ...predicate.Payment) *PaymentDeleteOne {
|
||||
_d._d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (_d *PaymentDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := _d._d.Exec(ctx)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case n == 0:
|
||||
return &NotFoundError{payment.Label}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_d *PaymentDeleteOne) ExecX(ctx context.Context) {
|
||||
if err := _d.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
610
examples/migration/ent/payment_query.go
Normal file
610
examples/migration/ent/payment_query.go
Normal file
@@ -0,0 +1,610 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/card"
|
||||
"entgo.io/ent/examples/migration/ent/payment"
|
||||
"entgo.io/ent/examples/migration/ent/predicate"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// PaymentQuery is the builder for querying Payment entities.
|
||||
type PaymentQuery struct {
|
||||
config
|
||||
ctx *QueryContext
|
||||
order []payment.OrderOption
|
||||
inters []Interceptor
|
||||
predicates []predicate.Payment
|
||||
withCard *CardQuery
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
path func(context.Context) (*sql.Selector, error)
|
||||
}
|
||||
|
||||
// Where adds a new predicate for the PaymentQuery builder.
|
||||
func (_q *PaymentQuery) Where(ps ...predicate.Payment) *PaymentQuery {
|
||||
_q.predicates = append(_q.predicates, ps...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// Limit the number of records to be returned by this query.
|
||||
func (_q *PaymentQuery) Limit(limit int) *PaymentQuery {
|
||||
_q.ctx.Limit = &limit
|
||||
return _q
|
||||
}
|
||||
|
||||
// Offset to start from.
|
||||
func (_q *PaymentQuery) Offset(offset int) *PaymentQuery {
|
||||
_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 *PaymentQuery) Unique(unique bool) *PaymentQuery {
|
||||
_q.ctx.Unique = &unique
|
||||
return _q
|
||||
}
|
||||
|
||||
// Order specifies how the records should be ordered.
|
||||
func (_q *PaymentQuery) Order(o ...payment.OrderOption) *PaymentQuery {
|
||||
_q.order = append(_q.order, o...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// QueryCard chains the current query on the "card" edge.
|
||||
func (_q *PaymentQuery) QueryCard() *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(payment.Table, payment.FieldID, selector),
|
||||
sqlgraph.To(card.Table, card.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, payment.CardTable, payment.CardColumn),
|
||||
)
|
||||
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
|
||||
return fromU, nil
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// First returns the first Payment entity from the query.
|
||||
// Returns a *NotFoundError when no Payment was found.
|
||||
func (_q *PaymentQuery) First(ctx context.Context) (*Payment, 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{payment.Label}
|
||||
}
|
||||
return nodes[0], nil
|
||||
}
|
||||
|
||||
// FirstX is like First, but panics if an error occurs.
|
||||
func (_q *PaymentQuery) FirstX(ctx context.Context) *Payment {
|
||||
node, err := _q.First(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// FirstID returns the first Payment ID from the query.
|
||||
// Returns a *NotFoundError when no Payment ID was found.
|
||||
func (_q *PaymentQuery) 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{payment.Label}
|
||||
return
|
||||
}
|
||||
return ids[0], nil
|
||||
}
|
||||
|
||||
// FirstIDX is like FirstID, but panics if an error occurs.
|
||||
func (_q *PaymentQuery) FirstIDX(ctx context.Context) int {
|
||||
id, err := _q.FirstID(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Only returns a single Payment entity found by the query, ensuring it only returns one.
|
||||
// Returns a *NotSingularError when more than one Payment entity is found.
|
||||
// Returns a *NotFoundError when no Payment entities are found.
|
||||
func (_q *PaymentQuery) Only(ctx context.Context) (*Payment, 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{payment.Label}
|
||||
default:
|
||||
return nil, &NotSingularError{payment.Label}
|
||||
}
|
||||
}
|
||||
|
||||
// OnlyX is like Only, but panics if an error occurs.
|
||||
func (_q *PaymentQuery) OnlyX(ctx context.Context) *Payment {
|
||||
node, err := _q.Only(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// OnlyID is like Only, but returns the only Payment ID in the query.
|
||||
// Returns a *NotSingularError when more than one Payment ID is found.
|
||||
// Returns a *NotFoundError when no entities are found.
|
||||
func (_q *PaymentQuery) 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{payment.Label}
|
||||
default:
|
||||
err = &NotSingularError{payment.Label}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// OnlyIDX is like OnlyID, but panics if an error occurs.
|
||||
func (_q *PaymentQuery) 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 Payments.
|
||||
func (_q *PaymentQuery) All(ctx context.Context) ([]*Payment, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
|
||||
if err := _q.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qr := querierAll[[]*Payment, *PaymentQuery]()
|
||||
return withInterceptors[[]*Payment](ctx, _q, qr, _q.inters)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
func (_q *PaymentQuery) AllX(ctx context.Context) []*Payment {
|
||||
nodes, err := _q.All(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
// IDs executes the query and returns a list of Payment IDs.
|
||||
func (_q *PaymentQuery) 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(payment.FieldID).Scan(ctx, &ids); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// IDsX is like IDs, but panics if an error occurs.
|
||||
func (_q *PaymentQuery) 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 *PaymentQuery) 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[*PaymentQuery](), _q.inters)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
func (_q *PaymentQuery) 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 *PaymentQuery) 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 *PaymentQuery) ExistX(ctx context.Context) bool {
|
||||
exist, err := _q.Exist(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return exist
|
||||
}
|
||||
|
||||
// Clone returns a duplicate of the PaymentQuery 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 *PaymentQuery) Clone() *PaymentQuery {
|
||||
if _q == nil {
|
||||
return nil
|
||||
}
|
||||
return &PaymentQuery{
|
||||
config: _q.config,
|
||||
ctx: _q.ctx.Clone(),
|
||||
order: append([]payment.OrderOption{}, _q.order...),
|
||||
inters: append([]Interceptor{}, _q.inters...),
|
||||
predicates: append([]predicate.Payment{}, _q.predicates...),
|
||||
withCard: _q.withCard.Clone(),
|
||||
// clone intermediate query.
|
||||
sql: _q.sql.Clone(),
|
||||
path: _q.path,
|
||||
}
|
||||
}
|
||||
|
||||
// WithCard tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "card" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (_q *PaymentQuery) WithCard(opts ...func(*CardQuery)) *PaymentQuery {
|
||||
query := (&CardClient{config: _q.config}).Query()
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
_q.withCard = 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 {
|
||||
// CardID int `json:"card_id,omitempty"`
|
||||
// Count int `json:"count,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.Payment.Query().
|
||||
// GroupBy(payment.FieldCardID).
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *PaymentQuery) GroupBy(field string, fields ...string) *PaymentGroupBy {
|
||||
_q.ctx.Fields = append([]string{field}, fields...)
|
||||
grbuild := &PaymentGroupBy{build: _q}
|
||||
grbuild.flds = &_q.ctx.Fields
|
||||
grbuild.label = payment.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 {
|
||||
// CardID int `json:"card_id,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.Payment.Query().
|
||||
// Select(payment.FieldCardID).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *PaymentQuery) Select(fields ...string) *PaymentSelect {
|
||||
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
|
||||
sbuild := &PaymentSelect{PaymentQuery: _q}
|
||||
sbuild.label = payment.Label
|
||||
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
|
||||
return sbuild
|
||||
}
|
||||
|
||||
// Aggregate returns a PaymentSelect configured with the given aggregations.
|
||||
func (_q *PaymentQuery) Aggregate(fns ...AggregateFunc) *PaymentSelect {
|
||||
return _q.Select().Aggregate(fns...)
|
||||
}
|
||||
|
||||
func (_q *PaymentQuery) 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 !payment.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 *PaymentQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Payment, error) {
|
||||
var (
|
||||
nodes = []*Payment{}
|
||||
_spec = _q.querySpec()
|
||||
loadedTypes = [1]bool{
|
||||
_q.withCard != nil,
|
||||
}
|
||||
)
|
||||
_spec.ScanValues = func(columns []string) ([]any, error) {
|
||||
return (*Payment).scanValues(nil, columns)
|
||||
}
|
||||
_spec.Assign = func(columns []string, values []any) error {
|
||||
node := &Payment{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.withCard; query != nil {
|
||||
if err := _q.loadCard(ctx, query, nodes, nil,
|
||||
func(n *Payment, e *Card) { n.Edges.Card = e }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
func (_q *PaymentQuery) loadCard(ctx context.Context, query *CardQuery, nodes []*Payment, init func(*Payment), assign func(*Payment, *Card)) error {
|
||||
ids := make([]int, 0, len(nodes))
|
||||
nodeids := make(map[int][]*Payment)
|
||||
for i := range nodes {
|
||||
fk := nodes[i].CardID
|
||||
if _, ok := nodeids[fk]; !ok {
|
||||
ids = append(ids, fk)
|
||||
}
|
||||
nodeids[fk] = append(nodeids[fk], nodes[i])
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
query.Where(card.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 "card_id" returned %v`, n.ID)
|
||||
}
|
||||
for i := range nodes {
|
||||
assign(nodes[i], n)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_q *PaymentQuery) 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 *PaymentQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
_spec := sqlgraph.NewQuerySpec(payment.Table, payment.Columns, sqlgraph.NewFieldSpec(payment.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, payment.FieldID)
|
||||
for i := range fields {
|
||||
if fields[i] != payment.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
|
||||
}
|
||||
}
|
||||
if _q.withCard != nil {
|
||||
_spec.Node.AddColumnOnce(payment.FieldCardID)
|
||||
}
|
||||
}
|
||||
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 *PaymentQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
builder := sql.Dialect(_q.driver.Dialect())
|
||||
t1 := builder.Table(payment.Table)
|
||||
columns := _q.ctx.Fields
|
||||
if len(columns) == 0 {
|
||||
columns = payment.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
|
||||
}
|
||||
|
||||
// PaymentGroupBy is the group-by builder for Payment entities.
|
||||
type PaymentGroupBy struct {
|
||||
selector
|
||||
build *PaymentQuery
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the group-by query.
|
||||
func (_g *PaymentGroupBy) Aggregate(fns ...AggregateFunc) *PaymentGroupBy {
|
||||
_g.fns = append(_g.fns, fns...)
|
||||
return _g
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_g *PaymentGroupBy) 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[*PaymentQuery, *PaymentGroupBy](ctx, _g.build, _g, _g.build.inters, v)
|
||||
}
|
||||
|
||||
func (_g *PaymentGroupBy) sqlScan(ctx context.Context, root *PaymentQuery, 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)
|
||||
}
|
||||
|
||||
// PaymentSelect is the builder for selecting fields of Payment entities.
|
||||
type PaymentSelect struct {
|
||||
*PaymentQuery
|
||||
selector
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the selector query.
|
||||
func (_s *PaymentSelect) Aggregate(fns ...AggregateFunc) *PaymentSelect {
|
||||
_s.fns = append(_s.fns, fns...)
|
||||
return _s
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_s *PaymentSelect) 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[*PaymentQuery, *PaymentSelect](ctx, _s.PaymentQuery, _s, _s.inters, v)
|
||||
}
|
||||
|
||||
func (_s *PaymentSelect) sqlScan(ctx context.Context, root *PaymentQuery, 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)
|
||||
}
|
||||
531
examples/migration/ent/payment_update.go
Normal file
531
examples/migration/ent/payment_update.go
Normal file
@@ -0,0 +1,531 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/card"
|
||||
"entgo.io/ent/examples/migration/ent/payment"
|
||||
"entgo.io/ent/examples/migration/ent/predicate"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// PaymentUpdate is the builder for updating Payment entities.
|
||||
type PaymentUpdate struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *PaymentMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the PaymentUpdate builder.
|
||||
func (_u *PaymentUpdate) Where(ps ...predicate.Payment) *PaymentUpdate {
|
||||
_u.mutation.Where(ps...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetCardID sets the "card_id" field.
|
||||
func (_u *PaymentUpdate) SetCardID(v int) *PaymentUpdate {
|
||||
_u.mutation.SetCardID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableCardID sets the "card_id" field if the given value is not nil.
|
||||
func (_u *PaymentUpdate) SetNillableCardID(v *int) *PaymentUpdate {
|
||||
if v != nil {
|
||||
_u.SetCardID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetAmount sets the "amount" field.
|
||||
func (_u *PaymentUpdate) SetAmount(v float64) *PaymentUpdate {
|
||||
_u.mutation.ResetAmount()
|
||||
_u.mutation.SetAmount(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableAmount sets the "amount" field if the given value is not nil.
|
||||
func (_u *PaymentUpdate) SetNillableAmount(v *float64) *PaymentUpdate {
|
||||
if v != nil {
|
||||
_u.SetAmount(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddAmount adds value to the "amount" field.
|
||||
func (_u *PaymentUpdate) AddAmount(v float64) *PaymentUpdate {
|
||||
_u.mutation.AddAmount(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetCurrency sets the "currency" field.
|
||||
func (_u *PaymentUpdate) SetCurrency(v payment.Currency) *PaymentUpdate {
|
||||
_u.mutation.SetCurrency(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableCurrency sets the "currency" field if the given value is not nil.
|
||||
func (_u *PaymentUpdate) SetNillableCurrency(v *payment.Currency) *PaymentUpdate {
|
||||
if v != nil {
|
||||
_u.SetCurrency(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetTime sets the "time" field.
|
||||
func (_u *PaymentUpdate) SetTime(v time.Time) *PaymentUpdate {
|
||||
_u.mutation.SetTime(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableTime sets the "time" field if the given value is not nil.
|
||||
func (_u *PaymentUpdate) SetNillableTime(v *time.Time) *PaymentUpdate {
|
||||
if v != nil {
|
||||
_u.SetTime(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetDescription sets the "description" field.
|
||||
func (_u *PaymentUpdate) SetDescription(v string) *PaymentUpdate {
|
||||
_u.mutation.SetDescription(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableDescription sets the "description" field if the given value is not nil.
|
||||
func (_u *PaymentUpdate) SetNillableDescription(v *string) *PaymentUpdate {
|
||||
if v != nil {
|
||||
_u.SetDescription(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetStatus sets the "status" field.
|
||||
func (_u *PaymentUpdate) SetStatus(v payment.Status) *PaymentUpdate {
|
||||
_u.mutation.SetStatus(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableStatus sets the "status" field if the given value is not nil.
|
||||
func (_u *PaymentUpdate) SetNillableStatus(v *payment.Status) *PaymentUpdate {
|
||||
if v != nil {
|
||||
_u.SetStatus(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetCard sets the "card" edge to the Card entity.
|
||||
func (_u *PaymentUpdate) SetCard(v *Card) *PaymentUpdate {
|
||||
return _u.SetCardID(v.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the PaymentMutation object of the builder.
|
||||
func (_u *PaymentUpdate) Mutation() *PaymentMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// ClearCard clears the "card" edge to the Card entity.
|
||||
func (_u *PaymentUpdate) ClearCard() *PaymentUpdate {
|
||||
_u.mutation.ClearCard()
|
||||
return _u
|
||||
}
|
||||
|
||||
// Save executes the query and returns the number of nodes affected by the update operation.
|
||||
func (_u *PaymentUpdate) 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 *PaymentUpdate) SaveX(ctx context.Context) int {
|
||||
affected, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return affected
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_u *PaymentUpdate) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *PaymentUpdate) ExecX(ctx context.Context) {
|
||||
if err := _u.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *PaymentUpdate) check() error {
|
||||
if v, ok := _u.mutation.Amount(); ok {
|
||||
if err := payment.AmountValidator(v); err != nil {
|
||||
return &ValidationError{Name: "amount", err: fmt.Errorf(`ent: validator failed for field "Payment.amount": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.Currency(); ok {
|
||||
if err := payment.CurrencyValidator(v); err != nil {
|
||||
return &ValidationError{Name: "currency", err: fmt.Errorf(`ent: validator failed for field "Payment.currency": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.Status(); ok {
|
||||
if err := payment.StatusValidator(v); err != nil {
|
||||
return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Payment.status": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _u.mutation.CardCleared() && len(_u.mutation.CardIDs()) > 0 {
|
||||
return errors.New(`ent: clearing a required unique edge "Payment.card"`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *PaymentUpdate) sqlSave(ctx context.Context) (_node int, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(payment.Table, payment.Columns, sqlgraph.NewFieldSpec(payment.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.Amount(); ok {
|
||||
_spec.SetField(payment.FieldAmount, field.TypeFloat64, value)
|
||||
}
|
||||
if value, ok := _u.mutation.AddedAmount(); ok {
|
||||
_spec.AddField(payment.FieldAmount, field.TypeFloat64, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Currency(); ok {
|
||||
_spec.SetField(payment.FieldCurrency, field.TypeEnum, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Time(); ok {
|
||||
_spec.SetField(payment.FieldTime, field.TypeTime, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Description(); ok {
|
||||
_spec.SetField(payment.FieldDescription, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Status(); ok {
|
||||
_spec.SetField(payment.FieldStatus, field.TypeEnum, value)
|
||||
}
|
||||
if _u.mutation.CardCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: payment.CardTable,
|
||||
Columns: []string{payment.CardColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(card.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.CardIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: payment.CardTable,
|
||||
Columns: []string{payment.CardColumn},
|
||||
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.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{payment.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
// PaymentUpdateOne is the builder for updating a single Payment entity.
|
||||
type PaymentUpdateOne struct {
|
||||
config
|
||||
fields []string
|
||||
hooks []Hook
|
||||
mutation *PaymentMutation
|
||||
}
|
||||
|
||||
// SetCardID sets the "card_id" field.
|
||||
func (_u *PaymentUpdateOne) SetCardID(v int) *PaymentUpdateOne {
|
||||
_u.mutation.SetCardID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableCardID sets the "card_id" field if the given value is not nil.
|
||||
func (_u *PaymentUpdateOne) SetNillableCardID(v *int) *PaymentUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetCardID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetAmount sets the "amount" field.
|
||||
func (_u *PaymentUpdateOne) SetAmount(v float64) *PaymentUpdateOne {
|
||||
_u.mutation.ResetAmount()
|
||||
_u.mutation.SetAmount(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableAmount sets the "amount" field if the given value is not nil.
|
||||
func (_u *PaymentUpdateOne) SetNillableAmount(v *float64) *PaymentUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetAmount(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddAmount adds value to the "amount" field.
|
||||
func (_u *PaymentUpdateOne) AddAmount(v float64) *PaymentUpdateOne {
|
||||
_u.mutation.AddAmount(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetCurrency sets the "currency" field.
|
||||
func (_u *PaymentUpdateOne) SetCurrency(v payment.Currency) *PaymentUpdateOne {
|
||||
_u.mutation.SetCurrency(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableCurrency sets the "currency" field if the given value is not nil.
|
||||
func (_u *PaymentUpdateOne) SetNillableCurrency(v *payment.Currency) *PaymentUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetCurrency(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetTime sets the "time" field.
|
||||
func (_u *PaymentUpdateOne) SetTime(v time.Time) *PaymentUpdateOne {
|
||||
_u.mutation.SetTime(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableTime sets the "time" field if the given value is not nil.
|
||||
func (_u *PaymentUpdateOne) SetNillableTime(v *time.Time) *PaymentUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetTime(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetDescription sets the "description" field.
|
||||
func (_u *PaymentUpdateOne) SetDescription(v string) *PaymentUpdateOne {
|
||||
_u.mutation.SetDescription(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableDescription sets the "description" field if the given value is not nil.
|
||||
func (_u *PaymentUpdateOne) SetNillableDescription(v *string) *PaymentUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetDescription(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetStatus sets the "status" field.
|
||||
func (_u *PaymentUpdateOne) SetStatus(v payment.Status) *PaymentUpdateOne {
|
||||
_u.mutation.SetStatus(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableStatus sets the "status" field if the given value is not nil.
|
||||
func (_u *PaymentUpdateOne) SetNillableStatus(v *payment.Status) *PaymentUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetStatus(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetCard sets the "card" edge to the Card entity.
|
||||
func (_u *PaymentUpdateOne) SetCard(v *Card) *PaymentUpdateOne {
|
||||
return _u.SetCardID(v.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the PaymentMutation object of the builder.
|
||||
func (_u *PaymentUpdateOne) Mutation() *PaymentMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// ClearCard clears the "card" edge to the Card entity.
|
||||
func (_u *PaymentUpdateOne) ClearCard() *PaymentUpdateOne {
|
||||
_u.mutation.ClearCard()
|
||||
return _u
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the PaymentUpdate builder.
|
||||
func (_u *PaymentUpdateOne) Where(ps ...predicate.Payment) *PaymentUpdateOne {
|
||||
_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 *PaymentUpdateOne) Select(field string, fields ...string) *PaymentUpdateOne {
|
||||
_u.fields = append([]string{field}, fields...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// Save executes the query and returns the updated Payment entity.
|
||||
func (_u *PaymentUpdateOne) Save(ctx context.Context) (*Payment, error) {
|
||||
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_u *PaymentUpdateOne) SaveX(ctx context.Context) *Payment {
|
||||
node, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// Exec executes the query on the entity.
|
||||
func (_u *PaymentUpdateOne) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *PaymentUpdateOne) ExecX(ctx context.Context) {
|
||||
if err := _u.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *PaymentUpdateOne) check() error {
|
||||
if v, ok := _u.mutation.Amount(); ok {
|
||||
if err := payment.AmountValidator(v); err != nil {
|
||||
return &ValidationError{Name: "amount", err: fmt.Errorf(`ent: validator failed for field "Payment.amount": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.Currency(); ok {
|
||||
if err := payment.CurrencyValidator(v); err != nil {
|
||||
return &ValidationError{Name: "currency", err: fmt.Errorf(`ent: validator failed for field "Payment.currency": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.Status(); ok {
|
||||
if err := payment.StatusValidator(v); err != nil {
|
||||
return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Payment.status": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _u.mutation.CardCleared() && len(_u.mutation.CardIDs()) > 0 {
|
||||
return errors.New(`ent: clearing a required unique edge "Payment.card"`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *PaymentUpdateOne) sqlSave(ctx context.Context) (_node *Payment, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(payment.Table, payment.Columns, sqlgraph.NewFieldSpec(payment.FieldID, field.TypeInt))
|
||||
id, ok := _u.mutation.ID()
|
||||
if !ok {
|
||||
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Payment.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, payment.FieldID)
|
||||
for _, f := range fields {
|
||||
if !payment.ValidColumn(f) {
|
||||
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
if f != payment.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.Amount(); ok {
|
||||
_spec.SetField(payment.FieldAmount, field.TypeFloat64, value)
|
||||
}
|
||||
if value, ok := _u.mutation.AddedAmount(); ok {
|
||||
_spec.AddField(payment.FieldAmount, field.TypeFloat64, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Currency(); ok {
|
||||
_spec.SetField(payment.FieldCurrency, field.TypeEnum, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Time(); ok {
|
||||
_spec.SetField(payment.FieldTime, field.TypeTime, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Description(); ok {
|
||||
_spec.SetField(payment.FieldDescription, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Status(); ok {
|
||||
_spec.SetField(payment.FieldStatus, field.TypeEnum, value)
|
||||
}
|
||||
if _u.mutation.CardCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: payment.CardTable,
|
||||
Columns: []string{payment.CardColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(card.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.CardIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: payment.CardTable,
|
||||
Columns: []string{payment.CardColumn},
|
||||
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.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
_node = &Payment{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{payment.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
203
examples/migration/ent/pet.go
Normal file
203
examples/migration/ent/pet.go
Normal file
@@ -0,0 +1,203 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/examples/migration/ent/pet"
|
||||
"entgo.io/ent/examples/migration/ent/user"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Pet is the model entity for the Pet schema.
|
||||
type Pet struct {
|
||||
config `json:"-"`
|
||||
// ID of the ent.
|
||||
ID uuid.UUID `json:"id,omitempty"`
|
||||
// Name holds the value of the "name" field.
|
||||
Name string `json:"name,omitempty"`
|
||||
// Age holds the value of the "age" field.
|
||||
Age float64 `json:"age,omitempty"`
|
||||
// Weight holds the value of the "weight" field.
|
||||
Weight float64 `json:"weight,omitempty"`
|
||||
// BestFriendID holds the value of the "best_friend_id" field.
|
||||
BestFriendID uuid.UUID `json:"best_friend_id,omitempty"`
|
||||
// OwnerID holds the value of the "owner_id" field.
|
||||
OwnerID int `json:"owner_id,omitempty"`
|
||||
// Edges holds the relations/edges for other nodes in the graph.
|
||||
// The values are being populated by the PetQuery when eager-loading is set.
|
||||
Edges PetEdges `json:"edges"`
|
||||
selectValues sql.SelectValues
|
||||
}
|
||||
|
||||
// PetEdges holds the relations/edges for other nodes in the graph.
|
||||
type PetEdges struct {
|
||||
// BestFriend holds the value of the best_friend edge.
|
||||
BestFriend *Pet `json:"best_friend,omitempty"`
|
||||
// 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 [2]bool
|
||||
}
|
||||
|
||||
// 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 PetEdges) BestFriendOrErr() (*Pet, error) {
|
||||
if e.BestFriend != nil {
|
||||
return e.BestFriend, nil
|
||||
} else if e.loadedTypes[0] {
|
||||
return nil, &NotFoundError{label: pet.Label}
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "best_friend"}
|
||||
}
|
||||
|
||||
// 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[1] {
|
||||
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.FieldAge, pet.FieldWeight:
|
||||
values[i] = new(sql.NullFloat64)
|
||||
case pet.FieldOwnerID:
|
||||
values[i] = new(sql.NullInt64)
|
||||
case pet.FieldName:
|
||||
values[i] = new(sql.NullString)
|
||||
case pet.FieldID, pet.FieldBestFriendID:
|
||||
values[i] = new(uuid.UUID)
|
||||
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:
|
||||
if value, ok := values[i].(*uuid.UUID); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field id", values[i])
|
||||
} else if value != nil {
|
||||
_m.ID = *value
|
||||
}
|
||||
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.FieldAge:
|
||||
if value, ok := values[i].(*sql.NullFloat64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field age", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Age = value.Float64
|
||||
}
|
||||
case pet.FieldWeight:
|
||||
if value, ok := values[i].(*sql.NullFloat64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field weight", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Weight = value.Float64
|
||||
}
|
||||
case pet.FieldBestFriendID:
|
||||
if value, ok := values[i].(*uuid.UUID); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field best_friend_id", values[i])
|
||||
} else if value != nil {
|
||||
_m.BestFriendID = *value
|
||||
}
|
||||
case pet.FieldOwnerID:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field owner_id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.OwnerID = int(value.Int64)
|
||||
}
|
||||
default:
|
||||
_m.selectValues.Set(columns[i], values[i])
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Value returns the ent.Value that was dynamically selected and assigned to the Pet.
|
||||
// This includes values selected through modifiers, order, etc.
|
||||
func (_m *Pet) Value(name string) (ent.Value, error) {
|
||||
return _m.selectValues.Get(name)
|
||||
}
|
||||
|
||||
// QueryBestFriend queries the "best_friend" edge of the Pet entity.
|
||||
func (_m *Pet) QueryBestFriend() *PetQuery {
|
||||
return NewPetClient(_m.config).QueryBestFriend(_m)
|
||||
}
|
||||
|
||||
// QueryOwner queries the "owner" edge of the Pet entity.
|
||||
func (_m *Pet) QueryOwner() *UserQuery {
|
||||
return NewPetClient(_m.config).QueryOwner(_m)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this Pet.
|
||||
// Note that you need to call Pet.Unwrap() before calling this method if this Pet
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (_m *Pet) Update() *PetUpdateOne {
|
||||
return NewPetClient(_m.config).UpdateOne(_m)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the Pet entity that was returned from a transaction after it was closed,
|
||||
// so that all future queries will be executed through the driver which created the transaction.
|
||||
func (_m *Pet) Unwrap() *Pet {
|
||||
_tx, ok := _m.config.driver.(*txDriver)
|
||||
if !ok {
|
||||
panic("ent: Pet is not a transactional entity")
|
||||
}
|
||||
_m.config.driver = _tx.drv
|
||||
return _m
|
||||
}
|
||||
|
||||
// String implements the fmt.Stringer.
|
||||
func (_m *Pet) String() string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("Pet(")
|
||||
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
|
||||
builder.WriteString("name=")
|
||||
builder.WriteString(_m.Name)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("age=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.Age))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("weight=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.Weight))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("best_friend_id=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.BestFriendID))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("owner_id=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.OwnerID))
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// Pets is a parsable slice of Pet.
|
||||
type Pets []*Pet
|
||||
543
examples/migration/ent/pet/mutation.go
Normal file
543
examples/migration/ent/pet/mutation.go
Normal file
@@ -0,0 +1,543 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package pet
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/examples/migration/ent/predicate"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Mutation represents an operation that mutates the Pet nodes in the graph.
|
||||
type Mutation struct {
|
||||
op ent.Op
|
||||
typ string
|
||||
name *string
|
||||
age *float64
|
||||
addage *float64
|
||||
weight *float64
|
||||
addweight *float64
|
||||
clearedFields map[string]struct{}
|
||||
best_friend *uuid.UUID
|
||||
clearedbest_friend bool
|
||||
owner *int
|
||||
clearedowner bool
|
||||
predicates []predicate.Pet
|
||||
}
|
||||
|
||||
// NewMutation creates a new Mutation for the Pet entity.
|
||||
func NewMutation(op ent.Op) *Mutation {
|
||||
return &Mutation{
|
||||
op: op,
|
||||
typ: "Pet",
|
||||
clearedFields: make(map[string]struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
// Predicates returns the list of predicates set on the mutation.
|
||||
func (m *Mutation) Predicates() []predicate.Pet {
|
||||
return m.predicates
|
||||
}
|
||||
|
||||
// SetName sets the "name" field.
|
||||
func (m *Mutation) SetName(s string) {
|
||||
m.name = &s
|
||||
}
|
||||
|
||||
// Name returns the value of the "name" field in the mutation.
|
||||
func (m *Mutation) Name() (r string, exists bool) {
|
||||
v := m.name
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetName resets all changes to the "name" field.
|
||||
func (m *Mutation) ResetName() {
|
||||
m.name = nil
|
||||
}
|
||||
|
||||
// SetAge sets the "age" field.
|
||||
func (m *Mutation) SetAge(f float64) {
|
||||
m.age = &f
|
||||
m.addage = nil
|
||||
}
|
||||
|
||||
// Age returns the value of the "age" field in the mutation.
|
||||
func (m *Mutation) Age() (r float64, exists bool) {
|
||||
v := m.age
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// AddAge adds f to the "age" field.
|
||||
func (m *Mutation) AddAge(f float64) {
|
||||
if m.addage != nil {
|
||||
*m.addage += f
|
||||
} else {
|
||||
m.addage = &f
|
||||
}
|
||||
}
|
||||
|
||||
// AddedAge returns the value that was added to the "age" field in this mutation.
|
||||
func (m *Mutation) AddedAge() (r float64, exists bool) {
|
||||
v := m.addage
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetAge resets all changes to the "age" field.
|
||||
func (m *Mutation) ResetAge() {
|
||||
m.age = nil
|
||||
m.addage = nil
|
||||
}
|
||||
|
||||
// SetWeight sets the "weight" field.
|
||||
func (m *Mutation) SetWeight(f float64) {
|
||||
m.weight = &f
|
||||
m.addweight = nil
|
||||
}
|
||||
|
||||
// Weight returns the value of the "weight" field in the mutation.
|
||||
func (m *Mutation) Weight() (r float64, exists bool) {
|
||||
v := m.weight
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// AddWeight adds f to the "weight" field.
|
||||
func (m *Mutation) AddWeight(f float64) {
|
||||
if m.addweight != nil {
|
||||
*m.addweight += f
|
||||
} else {
|
||||
m.addweight = &f
|
||||
}
|
||||
}
|
||||
|
||||
// AddedWeight returns the value that was added to the "weight" field in this mutation.
|
||||
func (m *Mutation) AddedWeight() (r float64, exists bool) {
|
||||
v := m.addweight
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetWeight resets all changes to the "weight" field.
|
||||
func (m *Mutation) ResetWeight() {
|
||||
m.weight = nil
|
||||
m.addweight = nil
|
||||
}
|
||||
|
||||
// SetBestFriendID sets the "best_friend_id" field.
|
||||
func (m *Mutation) SetBestFriendID(u uuid.UUID) {
|
||||
m.best_friend = &u
|
||||
}
|
||||
|
||||
// BestFriendID returns the value of the "best_friend_id" field in the mutation.
|
||||
func (m *Mutation) BestFriendID() (r uuid.UUID, exists bool) {
|
||||
v := m.best_friend
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetBestFriendID resets all changes to the "best_friend_id" field.
|
||||
func (m *Mutation) ResetBestFriendID() {
|
||||
m.best_friend = nil
|
||||
}
|
||||
|
||||
// SetOwnerID sets the "owner_id" field.
|
||||
func (m *Mutation) SetOwnerID(i int) {
|
||||
m.owner = &i
|
||||
}
|
||||
|
||||
// OwnerID returns the value of the "owner_id" field in the mutation.
|
||||
func (m *Mutation) OwnerID() (r int, exists bool) {
|
||||
v := m.owner
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetOwnerID resets all changes to the "owner_id" field.
|
||||
func (m *Mutation) ResetOwnerID() {
|
||||
m.owner = nil
|
||||
}
|
||||
|
||||
// ClearBestFriend clears the "best_friend" edge to the Pet entity.
|
||||
func (m *Mutation) ClearBestFriend() {
|
||||
m.clearedbest_friend = true
|
||||
m.clearedFields[FieldBestFriendID] = struct{}{}
|
||||
}
|
||||
|
||||
// BestFriendCleared reports if the "best_friend" edge to the Pet entity was cleared.
|
||||
func (m *Mutation) BestFriendCleared() bool {
|
||||
return m.clearedbest_friend
|
||||
}
|
||||
|
||||
// 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 []uuid.UUID) {
|
||||
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
|
||||
}
|
||||
|
||||
// ClearOwner clears the "owner" edge to the User entity.
|
||||
func (m *Mutation) ClearOwner() {
|
||||
m.clearedowner = true
|
||||
m.clearedFields[FieldOwnerID] = struct{}{}
|
||||
}
|
||||
|
||||
// OwnerCleared reports if the "owner" edge to the User entity was cleared.
|
||||
func (m *Mutation) OwnerCleared() bool {
|
||||
return m.clearedowner
|
||||
}
|
||||
|
||||
// OwnerIDs returns the "owner" edge IDs in the mutation.
|
||||
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
|
||||
// OwnerID instead. It exists only for internal usage by the builders.
|
||||
func (m *Mutation) OwnerIDs() (ids []int) {
|
||||
if id := m.owner; id != nil {
|
||||
ids = append(ids, *id)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ResetOwner resets all changes to the "owner" edge.
|
||||
func (m *Mutation) ResetOwner() {
|
||||
m.owner = nil
|
||||
m.clearedowner = false
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the Mutation builder.
|
||||
func (m *Mutation) Where(ps ...predicate.Pet) {
|
||||
m.predicates = append(m.predicates, ps...)
|
||||
}
|
||||
|
||||
// WhereP appends storage-level predicates to the Mutation builder. Using this method,
|
||||
// users can use type-assertion to append predicates that do not depend on any generated package.
|
||||
func (m *Mutation) WhereP(ps ...func(*sql.Selector)) {
|
||||
p := make([]predicate.Pet, len(ps))
|
||||
for i := range ps {
|
||||
p[i] = ps[i]
|
||||
}
|
||||
m.Where(p...)
|
||||
}
|
||||
|
||||
// Op returns the operation name.
|
||||
func (m *Mutation) Op() ent.Op {
|
||||
return m.op
|
||||
}
|
||||
|
||||
// SetOp allows setting the mutation operation.
|
||||
func (m *Mutation) SetOp(op ent.Op) {
|
||||
m.op = op
|
||||
}
|
||||
|
||||
// Type returns the node type of this mutation (Pet).
|
||||
func (m *Mutation) Type() string {
|
||||
return m.typ
|
||||
}
|
||||
|
||||
// Fields returns all fields that were changed during this mutation. Note that in
|
||||
// order to get all numeric fields that were incremented/decremented, call
|
||||
// AddedFields().
|
||||
func (m *Mutation) Fields() []string {
|
||||
fields := make([]string, 0, 5)
|
||||
if m.name != nil {
|
||||
fields = append(fields, FieldName)
|
||||
}
|
||||
if m.age != nil {
|
||||
fields = append(fields, FieldAge)
|
||||
}
|
||||
if m.weight != nil {
|
||||
fields = append(fields, FieldWeight)
|
||||
}
|
||||
if m.best_friend != nil {
|
||||
fields = append(fields, FieldBestFriendID)
|
||||
}
|
||||
if m.owner != nil {
|
||||
fields = append(fields, FieldOwnerID)
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
// Field returns the value of a field with the given name. The second boolean
|
||||
// return value indicates that this field was not set, or was not defined in the
|
||||
// schema.
|
||||
func (m *Mutation) Field(name string) (ent.Value, bool) {
|
||||
switch name {
|
||||
case FieldName:
|
||||
return m.Name()
|
||||
case FieldAge:
|
||||
return m.Age()
|
||||
case FieldWeight:
|
||||
return m.Weight()
|
||||
case FieldBestFriendID:
|
||||
return m.BestFriendID()
|
||||
case FieldOwnerID:
|
||||
return m.OwnerID()
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// OldField returns the old value of the field from the database. An error is
|
||||
// returned if the mutation operation is not UpdateOne, or the query to the
|
||||
// database failed.
|
||||
func (m *Mutation) OldField(ctx context.Context, name string) (ent.Value, error) {
|
||||
return nil, fmt.Errorf("unknown Pet field %s", name)
|
||||
}
|
||||
|
||||
// SetField sets the value of a field with the given name. It returns an error if
|
||||
// the field is not defined in the schema, or if the type mismatched the field
|
||||
// type.
|
||||
func (m *Mutation) SetField(name string, value ent.Value) error {
|
||||
switch name {
|
||||
case FieldName:
|
||||
v, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetName(v)
|
||||
return nil
|
||||
case FieldAge:
|
||||
v, ok := value.(float64)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetAge(v)
|
||||
return nil
|
||||
case FieldWeight:
|
||||
v, ok := value.(float64)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetWeight(v)
|
||||
return nil
|
||||
case FieldBestFriendID:
|
||||
v, ok := value.(uuid.UUID)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetBestFriendID(v)
|
||||
return nil
|
||||
case FieldOwnerID:
|
||||
v, ok := value.(int)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetOwnerID(v)
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown Pet field %s", name)
|
||||
}
|
||||
|
||||
// AddedFields returns all numeric fields that were incremented/decremented during
|
||||
// this mutation.
|
||||
func (m *Mutation) AddedFields() []string {
|
||||
var fields []string
|
||||
if m.addage != nil {
|
||||
fields = append(fields, FieldAge)
|
||||
}
|
||||
if m.addweight != nil {
|
||||
fields = append(fields, FieldWeight)
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
// AddedField returns the numeric value that was incremented/decremented on a field
|
||||
// with the given name. The second boolean return value indicates that this field
|
||||
// was not set, or was not defined in the schema.
|
||||
func (m *Mutation) AddedField(name string) (ent.Value, bool) {
|
||||
switch name {
|
||||
case FieldAge:
|
||||
return m.AddedAge()
|
||||
case FieldWeight:
|
||||
return m.AddedWeight()
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// AddField adds the value to the field with the given name. It returns an error if
|
||||
// the field is not defined in the schema, or if the type mismatched the field
|
||||
// type.
|
||||
func (m *Mutation) AddField(name string, value ent.Value) error {
|
||||
switch name {
|
||||
case FieldAge:
|
||||
v, ok := value.(float64)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.AddAge(v)
|
||||
return nil
|
||||
case FieldWeight:
|
||||
v, ok := value.(float64)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.AddWeight(v)
|
||||
return nil
|
||||
}
|
||||
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 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// FieldCleared returns a boolean indicating if a field with the given name was
|
||||
// cleared in this mutation.
|
||||
func (m *Mutation) FieldCleared(name string) bool {
|
||||
_, ok := m.clearedFields[name]
|
||||
return ok
|
||||
}
|
||||
|
||||
// ClearField clears the value of the field with the given name. It returns an
|
||||
// error if the field is not defined in the schema.
|
||||
func (m *Mutation) ClearField(name string) error {
|
||||
return fmt.Errorf("unknown Pet nullable field %s", name)
|
||||
}
|
||||
|
||||
// ResetField resets all changes in the mutation for the field with the given name.
|
||||
// It returns an error if the field is not defined in the schema.
|
||||
func (m *Mutation) ResetField(name string) error {
|
||||
switch name {
|
||||
case FieldName:
|
||||
m.ResetName()
|
||||
return nil
|
||||
case FieldAge:
|
||||
m.ResetAge()
|
||||
return nil
|
||||
case FieldWeight:
|
||||
m.ResetWeight()
|
||||
return nil
|
||||
case FieldBestFriendID:
|
||||
m.ResetBestFriendID()
|
||||
return nil
|
||||
case FieldOwnerID:
|
||||
m.ResetOwnerID()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown Pet field %s", name)
|
||||
}
|
||||
|
||||
// AddedEdges returns all edge names that were set/added in this mutation.
|
||||
func (m *Mutation) AddedEdges() []string {
|
||||
edges := make([]string, 0, 2)
|
||||
if m.best_friend != nil {
|
||||
edges = append(edges, EdgeBestFriend)
|
||||
}
|
||||
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 EdgeBestFriend:
|
||||
if id := m.best_friend; id != nil {
|
||||
return []ent.Value{*id}
|
||||
}
|
||||
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, 2)
|
||||
return edges
|
||||
}
|
||||
|
||||
// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
|
||||
// the given name in this mutation.
|
||||
func (m *Mutation) RemovedIDs(name string) []ent.Value {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClearedEdges returns all edge names that were cleared in this mutation.
|
||||
func (m *Mutation) ClearedEdges() []string {
|
||||
edges := make([]string, 0, 2)
|
||||
if m.clearedbest_friend {
|
||||
edges = append(edges, EdgeBestFriend)
|
||||
}
|
||||
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 EdgeBestFriend:
|
||||
return m.clearedbest_friend
|
||||
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 EdgeBestFriend:
|
||||
m.ClearBestFriend()
|
||||
return nil
|
||||
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 EdgeBestFriend:
|
||||
m.ResetBestFriend()
|
||||
return nil
|
||||
case EdgeOwner:
|
||||
m.ResetOwner()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown Pet edge %s", name)
|
||||
}
|
||||
135
examples/migration/ent/pet/pet.go
Normal file
135
examples/migration/ent/pet/pet.go
Normal file
@@ -0,0 +1,135 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package pet
|
||||
|
||||
import (
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the pet type in the database.
|
||||
Label = "pet"
|
||||
// FieldID holds the string denoting the id field in the database.
|
||||
FieldID = "id"
|
||||
// FieldName holds the string denoting the name field in the database.
|
||||
FieldName = "name"
|
||||
// FieldAge holds the string denoting the age field in the database.
|
||||
FieldAge = "age"
|
||||
// FieldWeight holds the string denoting the weight field in the database.
|
||||
FieldWeight = "weight"
|
||||
// FieldBestFriendID holds the string denoting the best_friend_id field in the database.
|
||||
FieldBestFriendID = "best_friend_id"
|
||||
// FieldOwnerID holds the string denoting the owner_id field in the database.
|
||||
FieldOwnerID = "owner_id"
|
||||
// EdgeBestFriend holds the string denoting the best_friend edge name in mutations.
|
||||
EdgeBestFriend = "best_friend"
|
||||
// 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"
|
||||
// BestFriendTable is the table that holds the best_friend relation/edge.
|
||||
BestFriendTable = "pets"
|
||||
// BestFriendColumn is the table column denoting the best_friend relation/edge.
|
||||
BestFriendColumn = "best_friend_id"
|
||||
// OwnerTable is the table that holds the owner relation/edge.
|
||||
OwnerTable = "pets"
|
||||
// OwnerInverseTable is the table name for the User entity.
|
||||
// It exists in this package in order to avoid circular dependency with the "user" package.
|
||||
OwnerInverseTable = "users"
|
||||
// OwnerColumn is the table column denoting the owner relation/edge.
|
||||
OwnerColumn = "owner_id"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for pet fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldName,
|
||||
FieldAge,
|
||||
FieldWeight,
|
||||
FieldBestFriendID,
|
||||
FieldOwnerID,
|
||||
}
|
||||
|
||||
// ValidColumn reports if the column name is valid (part of the table columns).
|
||||
func ValidColumn(column string) bool {
|
||||
for i := range Columns {
|
||||
if column == Columns[i] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var (
|
||||
// DefaultOwnerID holds the default value on creation for the "owner_id" field.
|
||||
DefaultOwnerID int
|
||||
// DefaultID holds the default value on creation for the "id" field.
|
||||
DefaultID func() uuid.UUID
|
||||
)
|
||||
|
||||
// OrderOption defines the ordering options for the Pet queries.
|
||||
type OrderOption func(*sql.Selector)
|
||||
|
||||
// ByID orders the results by the id field.
|
||||
func ByID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByName orders the results by the name field.
|
||||
func ByName(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldName, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByAge orders the results by the age field.
|
||||
func ByAge(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldAge, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByWeight orders the results by the weight field.
|
||||
func ByWeight(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldWeight, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByBestFriendID orders the results by the best_friend_id field.
|
||||
func ByBestFriendID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldBestFriendID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByOwnerID orders the results by the owner_id field.
|
||||
func ByOwnerID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldOwnerID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// 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...))
|
||||
}
|
||||
}
|
||||
|
||||
// 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 newBestFriendStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2O, false, BestFriendTable, BestFriendColumn),
|
||||
)
|
||||
}
|
||||
func newOwnerStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(OwnerInverseTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, false, OwnerTable, OwnerColumn),
|
||||
)
|
||||
}
|
||||
330
examples/migration/ent/pet/where.go
Normal file
330
examples/migration/ent/pet/where.go
Normal file
@@ -0,0 +1,330 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package pet
|
||||
|
||||
import (
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/predicate"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id uuid.UUID) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id uuid.UUID) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id uuid.UUID) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldNEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...uuid.UUID) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...uuid.UUID) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldNotIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id uuid.UUID) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldGT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id uuid.UUID) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldGTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id uuid.UUID) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldLT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id uuid.UUID) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldLTE(FieldID, id))
|
||||
}
|
||||
|
||||
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
|
||||
func Name(v string) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldEQ(FieldName, v))
|
||||
}
|
||||
|
||||
// Age applies equality check predicate on the "age" field. It's identical to AgeEQ.
|
||||
func Age(v float64) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldEQ(FieldAge, v))
|
||||
}
|
||||
|
||||
// Weight applies equality check predicate on the "weight" field. It's identical to WeightEQ.
|
||||
func Weight(v float64) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldEQ(FieldWeight, v))
|
||||
}
|
||||
|
||||
// BestFriendID applies equality check predicate on the "best_friend_id" field. It's identical to BestFriendIDEQ.
|
||||
func BestFriendID(v uuid.UUID) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldEQ(FieldBestFriendID, v))
|
||||
}
|
||||
|
||||
// OwnerID applies equality check predicate on the "owner_id" field. It's identical to OwnerIDEQ.
|
||||
func OwnerID(v int) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldEQ(FieldOwnerID, v))
|
||||
}
|
||||
|
||||
// NameEQ applies the EQ predicate on the "name" field.
|
||||
func NameEQ(v string) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldEQ(FieldName, v))
|
||||
}
|
||||
|
||||
// NameNEQ applies the NEQ predicate on the "name" field.
|
||||
func NameNEQ(v string) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldNEQ(FieldName, v))
|
||||
}
|
||||
|
||||
// NameIn applies the In predicate on the "name" field.
|
||||
func NameIn(vs ...string) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldIn(FieldName, vs...))
|
||||
}
|
||||
|
||||
// NameNotIn applies the NotIn predicate on the "name" field.
|
||||
func NameNotIn(vs ...string) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldNotIn(FieldName, vs...))
|
||||
}
|
||||
|
||||
// NameGT applies the GT predicate on the "name" field.
|
||||
func NameGT(v string) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldGT(FieldName, v))
|
||||
}
|
||||
|
||||
// NameGTE applies the GTE predicate on the "name" field.
|
||||
func NameGTE(v string) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldGTE(FieldName, v))
|
||||
}
|
||||
|
||||
// NameLT applies the LT predicate on the "name" field.
|
||||
func NameLT(v string) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldLT(FieldName, v))
|
||||
}
|
||||
|
||||
// NameLTE applies the LTE predicate on the "name" field.
|
||||
func NameLTE(v string) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldLTE(FieldName, v))
|
||||
}
|
||||
|
||||
// NameContains applies the Contains predicate on the "name" field.
|
||||
func NameContains(v string) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldContains(FieldName, v))
|
||||
}
|
||||
|
||||
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
|
||||
func NameHasPrefix(v string) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldHasPrefix(FieldName, v))
|
||||
}
|
||||
|
||||
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
|
||||
func NameHasSuffix(v string) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldHasSuffix(FieldName, v))
|
||||
}
|
||||
|
||||
// NameEqualFold applies the EqualFold predicate on the "name" field.
|
||||
func NameEqualFold(v string) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldEqualFold(FieldName, v))
|
||||
}
|
||||
|
||||
// NameContainsFold applies the ContainsFold predicate on the "name" field.
|
||||
func NameContainsFold(v string) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldContainsFold(FieldName, v))
|
||||
}
|
||||
|
||||
// AgeEQ applies the EQ predicate on the "age" field.
|
||||
func AgeEQ(v float64) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldEQ(FieldAge, v))
|
||||
}
|
||||
|
||||
// AgeNEQ applies the NEQ predicate on the "age" field.
|
||||
func AgeNEQ(v float64) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldNEQ(FieldAge, v))
|
||||
}
|
||||
|
||||
// AgeIn applies the In predicate on the "age" field.
|
||||
func AgeIn(vs ...float64) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldIn(FieldAge, vs...))
|
||||
}
|
||||
|
||||
// AgeNotIn applies the NotIn predicate on the "age" field.
|
||||
func AgeNotIn(vs ...float64) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldNotIn(FieldAge, vs...))
|
||||
}
|
||||
|
||||
// AgeGT applies the GT predicate on the "age" field.
|
||||
func AgeGT(v float64) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldGT(FieldAge, v))
|
||||
}
|
||||
|
||||
// AgeGTE applies the GTE predicate on the "age" field.
|
||||
func AgeGTE(v float64) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldGTE(FieldAge, v))
|
||||
}
|
||||
|
||||
// AgeLT applies the LT predicate on the "age" field.
|
||||
func AgeLT(v float64) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldLT(FieldAge, v))
|
||||
}
|
||||
|
||||
// AgeLTE applies the LTE predicate on the "age" field.
|
||||
func AgeLTE(v float64) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldLTE(FieldAge, v))
|
||||
}
|
||||
|
||||
// WeightEQ applies the EQ predicate on the "weight" field.
|
||||
func WeightEQ(v float64) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldEQ(FieldWeight, v))
|
||||
}
|
||||
|
||||
// WeightNEQ applies the NEQ predicate on the "weight" field.
|
||||
func WeightNEQ(v float64) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldNEQ(FieldWeight, v))
|
||||
}
|
||||
|
||||
// WeightIn applies the In predicate on the "weight" field.
|
||||
func WeightIn(vs ...float64) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldIn(FieldWeight, vs...))
|
||||
}
|
||||
|
||||
// WeightNotIn applies the NotIn predicate on the "weight" field.
|
||||
func WeightNotIn(vs ...float64) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldNotIn(FieldWeight, vs...))
|
||||
}
|
||||
|
||||
// WeightGT applies the GT predicate on the "weight" field.
|
||||
func WeightGT(v float64) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldGT(FieldWeight, v))
|
||||
}
|
||||
|
||||
// WeightGTE applies the GTE predicate on the "weight" field.
|
||||
func WeightGTE(v float64) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldGTE(FieldWeight, v))
|
||||
}
|
||||
|
||||
// WeightLT applies the LT predicate on the "weight" field.
|
||||
func WeightLT(v float64) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldLT(FieldWeight, v))
|
||||
}
|
||||
|
||||
// WeightLTE applies the LTE predicate on the "weight" field.
|
||||
func WeightLTE(v float64) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldLTE(FieldWeight, v))
|
||||
}
|
||||
|
||||
// BestFriendIDEQ applies the EQ predicate on the "best_friend_id" field.
|
||||
func BestFriendIDEQ(v uuid.UUID) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldEQ(FieldBestFriendID, v))
|
||||
}
|
||||
|
||||
// BestFriendIDNEQ applies the NEQ predicate on the "best_friend_id" field.
|
||||
func BestFriendIDNEQ(v uuid.UUID) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldNEQ(FieldBestFriendID, v))
|
||||
}
|
||||
|
||||
// BestFriendIDIn applies the In predicate on the "best_friend_id" field.
|
||||
func BestFriendIDIn(vs ...uuid.UUID) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldIn(FieldBestFriendID, vs...))
|
||||
}
|
||||
|
||||
// BestFriendIDNotIn applies the NotIn predicate on the "best_friend_id" field.
|
||||
func BestFriendIDNotIn(vs ...uuid.UUID) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldNotIn(FieldBestFriendID, vs...))
|
||||
}
|
||||
|
||||
// OwnerIDEQ applies the EQ predicate on the "owner_id" field.
|
||||
func OwnerIDEQ(v int) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldEQ(FieldOwnerID, v))
|
||||
}
|
||||
|
||||
// OwnerIDNEQ applies the NEQ predicate on the "owner_id" field.
|
||||
func OwnerIDNEQ(v int) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldNEQ(FieldOwnerID, v))
|
||||
}
|
||||
|
||||
// OwnerIDIn applies the In predicate on the "owner_id" field.
|
||||
func OwnerIDIn(vs ...int) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldIn(FieldOwnerID, vs...))
|
||||
}
|
||||
|
||||
// OwnerIDNotIn applies the NotIn predicate on the "owner_id" field.
|
||||
func OwnerIDNotIn(vs ...int) predicate.Pet {
|
||||
return predicate.Pet(sql.FieldNotIn(FieldOwnerID, vs...))
|
||||
}
|
||||
|
||||
// HasBestFriend applies the HasEdge predicate on the "best_friend" edge.
|
||||
func HasBestFriend() predicate.Pet {
|
||||
return predicate.Pet(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.Pet) predicate.Pet {
|
||||
return predicate.Pet(func(s *sql.Selector) {
|
||||
step := newBestFriendStep()
|
||||
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
|
||||
for _, p := range preds {
|
||||
p(s)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// 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, false, 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))
|
||||
}
|
||||
324
examples/migration/ent/pet_create.go
Normal file
324
examples/migration/ent/pet_create.go
Normal file
@@ -0,0 +1,324 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/pet"
|
||||
"entgo.io/ent/examples/migration/ent/user"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// PetCreate is the builder for creating a Pet entity.
|
||||
type PetCreate struct {
|
||||
config
|
||||
mutation *PetMutation
|
||||
hooks []Hook
|
||||
}
|
||||
|
||||
// SetName sets the "name" field.
|
||||
func (_c *PetCreate) SetName(v string) *PetCreate {
|
||||
_c.mutation.SetName(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetAge sets the "age" field.
|
||||
func (_c *PetCreate) SetAge(v float64) *PetCreate {
|
||||
_c.mutation.SetAge(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetWeight sets the "weight" field.
|
||||
func (_c *PetCreate) SetWeight(v float64) *PetCreate {
|
||||
_c.mutation.SetWeight(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetBestFriendID sets the "best_friend_id" field.
|
||||
func (_c *PetCreate) SetBestFriendID(v uuid.UUID) *PetCreate {
|
||||
_c.mutation.SetBestFriendID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetOwnerID sets the "owner_id" field.
|
||||
func (_c *PetCreate) SetOwnerID(v int) *PetCreate {
|
||||
_c.mutation.SetOwnerID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableOwnerID sets the "owner_id" field if the given value is not nil.
|
||||
func (_c *PetCreate) SetNillableOwnerID(v *int) *PetCreate {
|
||||
if v != nil {
|
||||
_c.SetOwnerID(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetID sets the "id" field.
|
||||
func (_c *PetCreate) SetID(v uuid.UUID) *PetCreate {
|
||||
_c.mutation.SetID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableID sets the "id" field if the given value is not nil.
|
||||
func (_c *PetCreate) SetNillableID(v *uuid.UUID) *PetCreate {
|
||||
if v != nil {
|
||||
_c.SetID(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetBestFriend sets the "best_friend" edge to the Pet entity.
|
||||
func (_c *PetCreate) SetBestFriend(v *Pet) *PetCreate {
|
||||
return _c.SetBestFriendID(v.ID)
|
||||
}
|
||||
|
||||
// SetOwner sets the "owner" edge to the User entity.
|
||||
func (_c *PetCreate) SetOwner(v *User) *PetCreate {
|
||||
return _c.SetOwnerID(v.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the PetMutation object of the builder.
|
||||
func (_c *PetCreate) Mutation() *PetMutation {
|
||||
return _c.mutation
|
||||
}
|
||||
|
||||
// Save creates the Pet in the database.
|
||||
func (_c *PetCreate) Save(ctx context.Context) (*Pet, error) {
|
||||
_c.defaults()
|
||||
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
func (_c *PetCreate) SaveX(ctx context.Context) *Pet {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *PetCreate) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *PetCreate) ExecX(ctx context.Context) {
|
||||
if err := _c.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// defaults sets the default values of the builder before save.
|
||||
func (_c *PetCreate) defaults() {
|
||||
if _, ok := _c.mutation.OwnerID(); !ok {
|
||||
v := pet.DefaultOwnerID
|
||||
_c.mutation.SetOwnerID(v)
|
||||
}
|
||||
if _, ok := _c.mutation.ID(); !ok {
|
||||
v := pet.DefaultID()
|
||||
_c.mutation.SetID(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_c *PetCreate) check() error {
|
||||
if _, ok := _c.mutation.Name(); !ok {
|
||||
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Pet.name"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.Age(); !ok {
|
||||
return &ValidationError{Name: "age", err: errors.New(`ent: missing required field "Pet.age"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.Weight(); !ok {
|
||||
return &ValidationError{Name: "weight", err: errors.New(`ent: missing required field "Pet.weight"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.BestFriendID(); !ok {
|
||||
return &ValidationError{Name: "best_friend_id", err: errors.New(`ent: missing required field "Pet.best_friend_id"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.OwnerID(); !ok {
|
||||
return &ValidationError{Name: "owner_id", err: errors.New(`ent: missing required field "Pet.owner_id"`)}
|
||||
}
|
||||
if len(_c.mutation.BestFriendIDs()) == 0 {
|
||||
return &ValidationError{Name: "best_friend", err: errors.New(`ent: missing required edge "Pet.best_friend"`)}
|
||||
}
|
||||
if len(_c.mutation.OwnerIDs()) == 0 {
|
||||
return &ValidationError{Name: "owner", err: errors.New(`ent: missing required edge "Pet.owner"`)}
|
||||
}
|
||||
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
|
||||
}
|
||||
if _spec.ID.Value != nil {
|
||||
if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
|
||||
_node.ID = *id
|
||||
} else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
_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.TypeUUID))
|
||||
)
|
||||
if id, ok := _c.mutation.ID(); ok {
|
||||
_node.ID = id
|
||||
_spec.ID.Value = &id
|
||||
}
|
||||
if value, ok := _c.mutation.Name(); ok {
|
||||
_spec.SetField(pet.FieldName, field.TypeString, value)
|
||||
_node.Name = value
|
||||
}
|
||||
if value, ok := _c.mutation.Age(); ok {
|
||||
_spec.SetField(pet.FieldAge, field.TypeFloat64, value)
|
||||
_node.Age = value
|
||||
}
|
||||
if value, ok := _c.mutation.Weight(); ok {
|
||||
_spec.SetField(pet.FieldWeight, field.TypeFloat64, value)
|
||||
_node.Weight = value
|
||||
}
|
||||
if nodes := _c.mutation.BestFriendIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2O,
|
||||
Inverse: false,
|
||||
Table: pet.BestFriendTable,
|
||||
Columns: []string{pet.BestFriendColumn},
|
||||
Bidi: true,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(pet.FieldID, field.TypeUUID),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_node.BestFriendID = nodes[0]
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
if nodes := _c.mutation.OwnerIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: false,
|
||||
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.OwnerID = nodes[0]
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
return _node, _spec
|
||||
}
|
||||
|
||||
// PetCreateBulk is the builder for creating many Pet entities in bulk.
|
||||
type PetCreateBulk struct {
|
||||
config
|
||||
err error
|
||||
builders []*PetCreate
|
||||
}
|
||||
|
||||
// Save creates the Pet entities in the database.
|
||||
func (_c *PetCreateBulk) Save(ctx context.Context) ([]*Pet, error) {
|
||||
if _c.err != nil {
|
||||
return nil, _c.err
|
||||
}
|
||||
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
|
||||
nodes := make([]*Pet, len(_c.builders))
|
||||
mutators := make([]Mutator, len(_c.builders))
|
||||
for i := range _c.builders {
|
||||
func(i int, root context.Context) {
|
||||
builder := _c.builders[i]
|
||||
builder.defaults()
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*PetMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err := builder.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
builder.mutation = mutation
|
||||
var err error
|
||||
nodes[i], specs[i] = builder.createSpec()
|
||||
if i < len(mutators)-1 {
|
||||
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
|
||||
} else {
|
||||
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
|
||||
// Invoke the actual operation on the latest mutation in the chain.
|
||||
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mutation.id = &nodes[i].ID
|
||||
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)
|
||||
}
|
||||
}
|
||||
92
examples/migration/ent/pet_delete.go
Normal file
92
examples/migration/ent/pet_delete.go
Normal file
@@ -0,0 +1,92 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/pet"
|
||||
"entgo.io/ent/examples/migration/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.TypeUUID))
|
||||
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)
|
||||
}
|
||||
}
|
||||
685
examples/migration/ent/pet_query.go
Normal file
685
examples/migration/ent/pet_query.go
Normal file
@@ -0,0 +1,685 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/pet"
|
||||
"entgo.io/ent/examples/migration/ent/predicate"
|
||||
"entgo.io/ent/examples/migration/ent/user"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// PetQuery is the builder for querying Pet entities.
|
||||
type PetQuery struct {
|
||||
config
|
||||
ctx *QueryContext
|
||||
order []pet.OrderOption
|
||||
inters []Interceptor
|
||||
predicates []predicate.Pet
|
||||
withBestFriend *PetQuery
|
||||
withOwner *UserQuery
|
||||
// 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
|
||||
}
|
||||
|
||||
// QueryBestFriend chains the current query on the "best_friend" edge.
|
||||
func (_q *PetQuery) QueryBestFriend() *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(pet.Table, pet.FieldID, selector),
|
||||
sqlgraph.To(pet.Table, pet.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2O, false, pet.BestFriendTable, pet.BestFriendColumn),
|
||||
)
|
||||
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
|
||||
return fromU, nil
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// 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, false, 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 uuid.UUID, err error) {
|
||||
var ids []uuid.UUID
|
||||
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) uuid.UUID {
|
||||
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 uuid.UUID, err error) {
|
||||
var ids []uuid.UUID
|
||||
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) uuid.UUID {
|
||||
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 []uuid.UUID, 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) []uuid.UUID {
|
||||
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...),
|
||||
withBestFriend: _q.withBestFriend.Clone(),
|
||||
withOwner: _q.withOwner.Clone(),
|
||||
// clone intermediate query.
|
||||
sql: _q.sql.Clone(),
|
||||
path: _q.path,
|
||||
}
|
||||
}
|
||||
|
||||
// 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 *PetQuery) WithBestFriend(opts ...func(*PetQuery)) *PetQuery {
|
||||
query := (&PetClient{config: _q.config}).Query()
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
_q.withBestFriend = query
|
||||
return _q
|
||||
}
|
||||
|
||||
// WithOwner tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "owner" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (_q *PetQuery) WithOwner(opts ...func(*UserQuery)) *PetQuery {
|
||||
query := (&UserClient{config: _q.config}).Query()
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
_q.withOwner = query
|
||||
return _q
|
||||
}
|
||||
|
||||
// GroupBy is used to group vertices by one or more fields/columns.
|
||||
// It is often used with aggregate functions, like: count, max, mean, min, sum.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// var v []struct {
|
||||
// Name string `json:"name,omitempty"`
|
||||
// Count int `json:"count,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.Pet.Query().
|
||||
// GroupBy(pet.FieldName).
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *PetQuery) GroupBy(field string, fields ...string) *PetGroupBy {
|
||||
_q.ctx.Fields = append([]string{field}, fields...)
|
||||
grbuild := &PetGroupBy{build: _q}
|
||||
grbuild.flds = &_q.ctx.Fields
|
||||
grbuild.label = pet.Label
|
||||
grbuild.scan = grbuild.Scan
|
||||
return grbuild
|
||||
}
|
||||
|
||||
// Select allows the selection one or more fields/columns for the given query,
|
||||
// instead of selecting all fields in the entity.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// var v []struct {
|
||||
// Name string `json:"name,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.Pet.Query().
|
||||
// Select(pet.FieldName).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *PetQuery) Select(fields ...string) *PetSelect {
|
||||
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
|
||||
sbuild := &PetSelect{PetQuery: _q}
|
||||
sbuild.label = pet.Label
|
||||
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
|
||||
return sbuild
|
||||
}
|
||||
|
||||
// Aggregate returns a PetSelect configured with the given aggregations.
|
||||
func (_q *PetQuery) Aggregate(fns ...AggregateFunc) *PetSelect {
|
||||
return _q.Select().Aggregate(fns...)
|
||||
}
|
||||
|
||||
func (_q *PetQuery) prepareQuery(ctx context.Context) error {
|
||||
for _, inter := range _q.inters {
|
||||
if inter == nil {
|
||||
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
|
||||
}
|
||||
if trv, ok := inter.(Traverser); ok {
|
||||
if err := trv.Traverse(ctx, _q); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, f := range _q.ctx.Fields {
|
||||
if !pet.ValidColumn(f) {
|
||||
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
}
|
||||
if _q.path != nil {
|
||||
prev, err := _q.path(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_q.sql = prev
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_q *PetQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Pet, error) {
|
||||
var (
|
||||
nodes = []*Pet{}
|
||||
_spec = _q.querySpec()
|
||||
loadedTypes = [2]bool{
|
||||
_q.withBestFriend != nil,
|
||||
_q.withOwner != nil,
|
||||
}
|
||||
)
|
||||
_spec.ScanValues = func(columns []string) ([]any, error) {
|
||||
return (*Pet).scanValues(nil, columns)
|
||||
}
|
||||
_spec.Assign = func(columns []string, values []any) error {
|
||||
node := &Pet{config: _q.config}
|
||||
nodes = append(nodes, node)
|
||||
node.Edges.loadedTypes = loadedTypes
|
||||
return node.assignValues(columns, values)
|
||||
}
|
||||
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.withBestFriend; query != nil {
|
||||
if err := _q.loadBestFriend(ctx, query, nodes, nil,
|
||||
func(n *Pet, e *Pet) { n.Edges.BestFriend = e }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
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) loadBestFriend(ctx context.Context, query *PetQuery, nodes []*Pet, init func(*Pet), assign func(*Pet, *Pet)) error {
|
||||
ids := make([]uuid.UUID, 0, len(nodes))
|
||||
nodeids := make(map[uuid.UUID][]*Pet)
|
||||
for i := range nodes {
|
||||
fk := nodes[i].BestFriendID
|
||||
if _, ok := nodeids[fk]; !ok {
|
||||
ids = append(ids, fk)
|
||||
}
|
||||
nodeids[fk] = append(nodeids[fk], nodes[i])
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
query.Where(pet.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 "best_friend_id" returned %v`, n.ID)
|
||||
}
|
||||
for i := range nodes {
|
||||
assign(nodes[i], n)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (_q *PetQuery) loadOwner(ctx context.Context, query *UserQuery, nodes []*Pet, init func(*Pet), assign func(*Pet, *User)) error {
|
||||
ids := make([]int, 0, len(nodes))
|
||||
nodeids := make(map[int][]*Pet)
|
||||
for i := range nodes {
|
||||
fk := nodes[i].OwnerID
|
||||
if _, ok := nodeids[fk]; !ok {
|
||||
ids = append(ids, fk)
|
||||
}
|
||||
nodeids[fk] = append(nodeids[fk], nodes[i])
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
query.Where(user.IDIn(ids...))
|
||||
neighbors, err := query.All(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, n := range neighbors {
|
||||
nodes, ok := nodeids[n.ID]
|
||||
if !ok {
|
||||
return fmt.Errorf(`unexpected foreign-key "owner_id" returned %v`, n.ID)
|
||||
}
|
||||
for i := range nodes {
|
||||
assign(nodes[i], n)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_q *PetQuery) sqlCount(ctx context.Context) (int, error) {
|
||||
_spec := _q.querySpec()
|
||||
_spec.Node.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.TypeUUID))
|
||||
_spec.From = _q.sql
|
||||
if unique := _q.ctx.Unique; unique != nil {
|
||||
_spec.Unique = *unique
|
||||
} else if _q.path != nil {
|
||||
_spec.Unique = true
|
||||
}
|
||||
if fields := _q.ctx.Fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, pet.FieldID)
|
||||
for i := range fields {
|
||||
if fields[i] != pet.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
|
||||
}
|
||||
}
|
||||
if _q.withBestFriend != nil {
|
||||
_spec.Node.AddColumnOnce(pet.FieldBestFriendID)
|
||||
}
|
||||
if _q.withOwner != nil {
|
||||
_spec.Node.AddColumnOnce(pet.FieldOwnerID)
|
||||
}
|
||||
}
|
||||
if ps := _q.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if limit := _q.ctx.Limit; limit != nil {
|
||||
_spec.Limit = *limit
|
||||
}
|
||||
if offset := _q.ctx.Offset; offset != nil {
|
||||
_spec.Offset = *offset
|
||||
}
|
||||
if ps := _q.order; len(ps) > 0 {
|
||||
_spec.Order = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
return _spec
|
||||
}
|
||||
|
||||
func (_q *PetQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
builder := sql.Dialect(_q.driver.Dialect())
|
||||
t1 := builder.Table(pet.Table)
|
||||
columns := _q.ctx.Fields
|
||||
if len(columns) == 0 {
|
||||
columns = pet.Columns
|
||||
}
|
||||
selector := builder.Select(t1.Columns(columns...)...).From(t1)
|
||||
if _q.sql != nil {
|
||||
selector = _q.sql
|
||||
selector.Select(selector.Columns(columns...)...)
|
||||
}
|
||||
if _q.ctx.Unique != nil && *_q.ctx.Unique {
|
||||
selector.Distinct()
|
||||
}
|
||||
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)
|
||||
}
|
||||
567
examples/migration/ent/pet_update.go
Normal file
567
examples/migration/ent/pet_update.go
Normal file
@@ -0,0 +1,567 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/pet"
|
||||
"entgo.io/ent/examples/migration/ent/predicate"
|
||||
"entgo.io/ent/examples/migration/ent/user"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// SetAge sets the "age" field.
|
||||
func (_u *PetUpdate) SetAge(v float64) *PetUpdate {
|
||||
_u.mutation.ResetAge()
|
||||
_u.mutation.SetAge(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableAge sets the "age" field if the given value is not nil.
|
||||
func (_u *PetUpdate) SetNillableAge(v *float64) *PetUpdate {
|
||||
if v != nil {
|
||||
_u.SetAge(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddAge adds value to the "age" field.
|
||||
func (_u *PetUpdate) AddAge(v float64) *PetUpdate {
|
||||
_u.mutation.AddAge(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetWeight sets the "weight" field.
|
||||
func (_u *PetUpdate) SetWeight(v float64) *PetUpdate {
|
||||
_u.mutation.ResetWeight()
|
||||
_u.mutation.SetWeight(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableWeight sets the "weight" field if the given value is not nil.
|
||||
func (_u *PetUpdate) SetNillableWeight(v *float64) *PetUpdate {
|
||||
if v != nil {
|
||||
_u.SetWeight(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddWeight adds value to the "weight" field.
|
||||
func (_u *PetUpdate) AddWeight(v float64) *PetUpdate {
|
||||
_u.mutation.AddWeight(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetBestFriendID sets the "best_friend_id" field.
|
||||
func (_u *PetUpdate) SetBestFriendID(v uuid.UUID) *PetUpdate {
|
||||
_u.mutation.SetBestFriendID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableBestFriendID sets the "best_friend_id" field if the given value is not nil.
|
||||
func (_u *PetUpdate) SetNillableBestFriendID(v *uuid.UUID) *PetUpdate {
|
||||
if v != nil {
|
||||
_u.SetBestFriendID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetOwnerID sets the "owner_id" field.
|
||||
func (_u *PetUpdate) SetOwnerID(v int) *PetUpdate {
|
||||
_u.mutation.SetOwnerID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableOwnerID sets the "owner_id" field if the given value is not nil.
|
||||
func (_u *PetUpdate) SetNillableOwnerID(v *int) *PetUpdate {
|
||||
if v != nil {
|
||||
_u.SetOwnerID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetBestFriend sets the "best_friend" edge to the Pet entity.
|
||||
func (_u *PetUpdate) SetBestFriend(v *Pet) *PetUpdate {
|
||||
return _u.SetBestFriendID(v.ID)
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// ClearBestFriend clears the "best_friend" edge to the Pet entity.
|
||||
func (_u *PetUpdate) ClearBestFriend() *PetUpdate {
|
||||
_u.mutation.ClearBestFriend()
|
||||
return _u
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *PetUpdate) check() error {
|
||||
if _u.mutation.BestFriendCleared() && len(_u.mutation.BestFriendIDs()) > 0 {
|
||||
return errors.New(`ent: clearing a required unique edge "Pet.best_friend"`)
|
||||
}
|
||||
if _u.mutation.OwnerCleared() && len(_u.mutation.OwnerIDs()) > 0 {
|
||||
return errors.New(`ent: clearing a required unique edge "Pet.owner"`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *PetUpdate) sqlSave(ctx context.Context) (_node int, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(pet.Table, pet.Columns, sqlgraph.NewFieldSpec(pet.FieldID, field.TypeUUID))
|
||||
if ps := _u.mutation.Predicates(); len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if value, ok := _u.mutation.Name(); ok {
|
||||
_spec.SetField(pet.FieldName, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Age(); ok {
|
||||
_spec.SetField(pet.FieldAge, field.TypeFloat64, value)
|
||||
}
|
||||
if value, ok := _u.mutation.AddedAge(); ok {
|
||||
_spec.AddField(pet.FieldAge, field.TypeFloat64, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Weight(); ok {
|
||||
_spec.SetField(pet.FieldWeight, field.TypeFloat64, value)
|
||||
}
|
||||
if value, ok := _u.mutation.AddedWeight(); ok {
|
||||
_spec.AddField(pet.FieldWeight, field.TypeFloat64, value)
|
||||
}
|
||||
if _u.mutation.BestFriendCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2O,
|
||||
Inverse: false,
|
||||
Table: pet.BestFriendTable,
|
||||
Columns: []string{pet.BestFriendColumn},
|
||||
Bidi: true,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(pet.FieldID, field.TypeUUID),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.BestFriendIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2O,
|
||||
Inverse: false,
|
||||
Table: pet.BestFriendTable,
|
||||
Columns: []string{pet.BestFriendColumn},
|
||||
Bidi: true,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(pet.FieldID, field.TypeUUID),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if _u.mutation.OwnerCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: false,
|
||||
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: false,
|
||||
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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// SetAge sets the "age" field.
|
||||
func (_u *PetUpdateOne) SetAge(v float64) *PetUpdateOne {
|
||||
_u.mutation.ResetAge()
|
||||
_u.mutation.SetAge(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableAge sets the "age" field if the given value is not nil.
|
||||
func (_u *PetUpdateOne) SetNillableAge(v *float64) *PetUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetAge(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddAge adds value to the "age" field.
|
||||
func (_u *PetUpdateOne) AddAge(v float64) *PetUpdateOne {
|
||||
_u.mutation.AddAge(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetWeight sets the "weight" field.
|
||||
func (_u *PetUpdateOne) SetWeight(v float64) *PetUpdateOne {
|
||||
_u.mutation.ResetWeight()
|
||||
_u.mutation.SetWeight(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableWeight sets the "weight" field if the given value is not nil.
|
||||
func (_u *PetUpdateOne) SetNillableWeight(v *float64) *PetUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetWeight(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddWeight adds value to the "weight" field.
|
||||
func (_u *PetUpdateOne) AddWeight(v float64) *PetUpdateOne {
|
||||
_u.mutation.AddWeight(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetBestFriendID sets the "best_friend_id" field.
|
||||
func (_u *PetUpdateOne) SetBestFriendID(v uuid.UUID) *PetUpdateOne {
|
||||
_u.mutation.SetBestFriendID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableBestFriendID sets the "best_friend_id" field if the given value is not nil.
|
||||
func (_u *PetUpdateOne) SetNillableBestFriendID(v *uuid.UUID) *PetUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetBestFriendID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetOwnerID sets the "owner_id" field.
|
||||
func (_u *PetUpdateOne) SetOwnerID(v int) *PetUpdateOne {
|
||||
_u.mutation.SetOwnerID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableOwnerID sets the "owner_id" field if the given value is not nil.
|
||||
func (_u *PetUpdateOne) SetNillableOwnerID(v *int) *PetUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetOwnerID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetBestFriend sets the "best_friend" edge to the Pet entity.
|
||||
func (_u *PetUpdateOne) SetBestFriend(v *Pet) *PetUpdateOne {
|
||||
return _u.SetBestFriendID(v.ID)
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// ClearBestFriend clears the "best_friend" edge to the Pet entity.
|
||||
func (_u *PetUpdateOne) ClearBestFriend() *PetUpdateOne {
|
||||
_u.mutation.ClearBestFriend()
|
||||
return _u
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *PetUpdateOne) check() error {
|
||||
if _u.mutation.BestFriendCleared() && len(_u.mutation.BestFriendIDs()) > 0 {
|
||||
return errors.New(`ent: clearing a required unique edge "Pet.best_friend"`)
|
||||
}
|
||||
if _u.mutation.OwnerCleared() && len(_u.mutation.OwnerIDs()) > 0 {
|
||||
return errors.New(`ent: clearing a required unique edge "Pet.owner"`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *PetUpdateOne) sqlSave(ctx context.Context) (_node *Pet, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(pet.Table, pet.Columns, sqlgraph.NewFieldSpec(pet.FieldID, field.TypeUUID))
|
||||
id, ok := _u.mutation.ID()
|
||||
if !ok {
|
||||
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Pet.id" for update`)}
|
||||
}
|
||||
_spec.Node.ID.Value = id
|
||||
if fields := _u.fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, pet.FieldID)
|
||||
for _, f := range fields {
|
||||
if !pet.ValidColumn(f) {
|
||||
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
if f != pet.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
if ps := _u.mutation.Predicates(); len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if value, ok := _u.mutation.Name(); ok {
|
||||
_spec.SetField(pet.FieldName, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Age(); ok {
|
||||
_spec.SetField(pet.FieldAge, field.TypeFloat64, value)
|
||||
}
|
||||
if value, ok := _u.mutation.AddedAge(); ok {
|
||||
_spec.AddField(pet.FieldAge, field.TypeFloat64, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Weight(); ok {
|
||||
_spec.SetField(pet.FieldWeight, field.TypeFloat64, value)
|
||||
}
|
||||
if value, ok := _u.mutation.AddedWeight(); ok {
|
||||
_spec.AddField(pet.FieldWeight, field.TypeFloat64, value)
|
||||
}
|
||||
if _u.mutation.BestFriendCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2O,
|
||||
Inverse: false,
|
||||
Table: pet.BestFriendTable,
|
||||
Columns: []string{pet.BestFriendColumn},
|
||||
Bidi: true,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(pet.FieldID, field.TypeUUID),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.BestFriendIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2O,
|
||||
Inverse: false,
|
||||
Table: pet.BestFriendTable,
|
||||
Columns: []string{pet.BestFriendColumn},
|
||||
Bidi: true,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(pet.FieldID, field.TypeUUID),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if _u.mutation.OwnerCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: false,
|
||||
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: false,
|
||||
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
|
||||
}
|
||||
29
examples/migration/ent/predicate/predicate.go
Normal file
29
examples/migration/ent/predicate/predicate.go
Normal file
@@ -0,0 +1,29 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package predicate
|
||||
|
||||
import (
|
||||
"entgo.io/ent/dialect/sql"
|
||||
)
|
||||
|
||||
// Card is the predicate function for card builders.
|
||||
type Card func(*sql.Selector)
|
||||
|
||||
// Payment is the predicate function for payment builders.
|
||||
type Payment func(*sql.Selector)
|
||||
|
||||
// Pet is the predicate function for pet builders.
|
||||
type Pet func(*sql.Selector)
|
||||
|
||||
// Session is the predicate function for session builders.
|
||||
type Session func(*sql.Selector)
|
||||
|
||||
// SessionDevice is the predicate function for sessiondevice builders.
|
||||
type SessionDevice func(*sql.Selector)
|
||||
|
||||
// User is the predicate function for user builders.
|
||||
type User func(*sql.Selector)
|
||||
77
examples/migration/ent/runtime.go
Normal file
77
examples/migration/ent/runtime.go
Normal file
@@ -0,0 +1,77 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"entgo.io/ent/examples/migration/ent/card"
|
||||
"entgo.io/ent/examples/migration/ent/payment"
|
||||
"entgo.io/ent/examples/migration/ent/pet"
|
||||
"entgo.io/ent/examples/migration/ent/schema"
|
||||
"entgo.io/ent/examples/migration/ent/session"
|
||||
"entgo.io/ent/examples/migration/ent/sessiondevice"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// 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() {
|
||||
cardFields := schema.Card{}.Fields()
|
||||
_ = cardFields
|
||||
// cardDescType is the schema descriptor for type field.
|
||||
cardDescType := cardFields[0].Descriptor()
|
||||
// card.DefaultType holds the default value on creation for the type field.
|
||||
card.DefaultType = cardDescType.Default.(string)
|
||||
// cardDescOwnerID is the schema descriptor for owner_id field.
|
||||
cardDescOwnerID := cardFields[4].Descriptor()
|
||||
// card.DefaultOwnerID holds the default value on creation for the owner_id field.
|
||||
card.DefaultOwnerID = cardDescOwnerID.Default.(int)
|
||||
paymentFields := schema.Payment{}.Fields()
|
||||
_ = paymentFields
|
||||
// paymentDescAmount is the schema descriptor for amount field.
|
||||
paymentDescAmount := paymentFields[1].Descriptor()
|
||||
// payment.AmountValidator is a validator for the "amount" field. It is called by the builders before save.
|
||||
payment.AmountValidator = paymentDescAmount.Validators[0].(func(float64) error)
|
||||
petFields := schema.Pet{}.Fields()
|
||||
_ = petFields
|
||||
// petDescOwnerID is the schema descriptor for owner_id field.
|
||||
petDescOwnerID := petFields[5].Descriptor()
|
||||
// pet.DefaultOwnerID holds the default value on creation for the owner_id field.
|
||||
pet.DefaultOwnerID = petDescOwnerID.Default.(int)
|
||||
// petDescID is the schema descriptor for id field.
|
||||
petDescID := petFields[0].Descriptor()
|
||||
// pet.DefaultID holds the default value on creation for the id field.
|
||||
pet.DefaultID = petDescID.Default.(func() uuid.UUID)
|
||||
sessionFields := schema.Session{}.Fields()
|
||||
_ = sessionFields
|
||||
// sessionDescActive is the schema descriptor for active field.
|
||||
sessionDescActive := sessionFields[1].Descriptor()
|
||||
// session.DefaultActive holds the default value on creation for the active field.
|
||||
session.DefaultActive = sessionDescActive.Default.(bool)
|
||||
// sessionDescID is the schema descriptor for id field.
|
||||
sessionDescID := sessionFields[0].Descriptor()
|
||||
// session.DefaultID holds the default value on creation for the id field.
|
||||
session.DefaultID = sessionDescID.Default.(func() uuid.UUID)
|
||||
sessiondeviceFields := schema.SessionDevice{}.Fields()
|
||||
_ = sessiondeviceFields
|
||||
// sessiondeviceDescIPAddress is the schema descriptor for ip_address field.
|
||||
sessiondeviceDescIPAddress := sessiondeviceFields[1].Descriptor()
|
||||
// sessiondevice.IPAddressValidator is a validator for the "ip_address" field. It is called by the builders before save.
|
||||
sessiondevice.IPAddressValidator = sessiondeviceDescIPAddress.Validators[0].(func(string) error)
|
||||
// sessiondeviceDescUserAgent is the schema descriptor for user_agent field.
|
||||
sessiondeviceDescUserAgent := sessiondeviceFields[2].Descriptor()
|
||||
// sessiondevice.UserAgentValidator is a validator for the "user_agent" field. It is called by the builders before save.
|
||||
sessiondevice.UserAgentValidator = sessiondeviceDescUserAgent.Validators[0].(func(string) error)
|
||||
// sessiondeviceDescLocation is the schema descriptor for location field.
|
||||
sessiondeviceDescLocation := sessiondeviceFields[3].Descriptor()
|
||||
// sessiondevice.LocationValidator is a validator for the "location" field. It is called by the builders before save.
|
||||
sessiondevice.LocationValidator = sessiondeviceDescLocation.Validators[0].(func(string) error)
|
||||
// sessiondeviceDescID is the schema descriptor for id field.
|
||||
sessiondeviceDescID := sessiondeviceFields[0].Descriptor()
|
||||
// sessiondevice.DefaultID holds the default value on creation for the id field.
|
||||
sessiondevice.DefaultID = sessiondeviceDescID.Default.(func() uuid.UUID)
|
||||
}
|
||||
13
examples/migration/ent/runtime/runtime.go
Normal file
13
examples/migration/ent/runtime/runtime.go
Normal file
@@ -0,0 +1,13 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package runtime
|
||||
|
||||
// The schema-stitching logic is generated in entgo.io/ent/examples/migration/ent/runtime.go
|
||||
|
||||
const (
|
||||
Version = "v0.0.0-00010101000000-000000000000" // Version of ent codegen.
|
||||
)
|
||||
55
examples/migration/ent/schema/card.go
Normal file
55
examples/migration/ent/schema/card.go
Normal file
@@ -0,0 +1,55 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
package schema
|
||||
|
||||
import (
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/entsql"
|
||||
"entgo.io/ent/schema"
|
||||
"entgo.io/ent/schema/edge"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// Card holds the schema definition for the Card entity.
|
||||
type Card struct {
|
||||
ent.Schema
|
||||
}
|
||||
|
||||
// Fields of the Card.
|
||||
func (Card) Fields() []ent.Field {
|
||||
return []ent.Field{
|
||||
field.String("type").
|
||||
Default("unknown"),
|
||||
field.String("number_hash"),
|
||||
field.String("cvv_hash"),
|
||||
field.Time("expires_at").
|
||||
Optional(),
|
||||
field.Int("owner_id").
|
||||
Default(0),
|
||||
}
|
||||
}
|
||||
|
||||
// Edges of the Card.
|
||||
func (Card) Edges() []ent.Edge {
|
||||
return []ent.Edge{
|
||||
edge.From("owner", User.Type).
|
||||
Ref("cards").
|
||||
Unique().
|
||||
Required().
|
||||
Field("owner_id"),
|
||||
edge.To("payments", Payment.Type),
|
||||
}
|
||||
}
|
||||
|
||||
// Annotations of the Card.
|
||||
func (Card) Annotations() []schema.Annotation {
|
||||
return []schema.Annotation{
|
||||
// Named check constraints are compared by their name.
|
||||
// Thus, the definition does not need to be normalized.
|
||||
entsql.Checks(map[string]string{
|
||||
"number_hash_length": "(LENGTH(`number_hash`) = 16)",
|
||||
}),
|
||||
}
|
||||
}
|
||||
63
examples/migration/ent/schema/payment.go
Normal file
63
examples/migration/ent/schema/payment.go
Normal file
@@ -0,0 +1,63 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
package schema
|
||||
|
||||
import (
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/entsql"
|
||||
"entgo.io/ent/schema"
|
||||
"entgo.io/ent/schema/edge"
|
||||
"entgo.io/ent/schema/field"
|
||||
"entgo.io/ent/schema/index"
|
||||
)
|
||||
|
||||
// Payment holds the schema definition for the Payment entity.
|
||||
type Payment struct {
|
||||
ent.Schema
|
||||
}
|
||||
|
||||
// Fields of the Payment.
|
||||
func (Payment) Fields() []ent.Field {
|
||||
return []ent.Field{
|
||||
field.Int("card_id"),
|
||||
field.Float("amount").
|
||||
Positive(),
|
||||
field.Enum("currency").
|
||||
Values("USD", "EUR", "VND", "ILS"),
|
||||
field.Time("time"),
|
||||
field.String("description"),
|
||||
field.Enum("status").
|
||||
Values("pending", "completed", "failed"),
|
||||
}
|
||||
}
|
||||
|
||||
// Edges of the Payment.
|
||||
func (Payment) Edges() []ent.Edge {
|
||||
return []ent.Edge{
|
||||
edge.From("card", Card.Type).
|
||||
Ref("payments").
|
||||
Unique().
|
||||
Required().
|
||||
Field("card_id"),
|
||||
}
|
||||
}
|
||||
|
||||
// Indexes of the Payment.
|
||||
func (Payment) Indexes() []ent.Index {
|
||||
return []ent.Index{
|
||||
index.Fields("status", "time"),
|
||||
}
|
||||
}
|
||||
|
||||
// Annotations of the Payment.
|
||||
func (Payment) Annotations() []schema.Annotation {
|
||||
return []schema.Annotation{
|
||||
// Named check constraints are compared by their name.
|
||||
// Thus, the definition does not need to be normalized.
|
||||
entsql.Checks(map[string]string{
|
||||
"amount_positive": "(`amount` > 0)",
|
||||
}),
|
||||
}
|
||||
}
|
||||
58
examples/migration/ent/schema/pet.go
Normal file
58
examples/migration/ent/schema/pet.go
Normal file
@@ -0,0 +1,58 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
package schema
|
||||
|
||||
import (
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/entsql"
|
||||
"entgo.io/ent/schema/edge"
|
||||
"entgo.io/ent/schema/field"
|
||||
"entgo.io/ent/schema/index"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Pet holds the schema definition for the Pet entity.
|
||||
type Pet struct {
|
||||
ent.Schema
|
||||
}
|
||||
|
||||
// Fields of the Pet.
|
||||
func (Pet) Fields() []ent.Field {
|
||||
return []ent.Field{
|
||||
field.UUID("id", uuid.Nil).
|
||||
Default(uuid.New),
|
||||
field.String("name"),
|
||||
field.Float("age"),
|
||||
field.Float("weight"),
|
||||
field.UUID("best_friend_id", uuid.Nil).
|
||||
Annotations(
|
||||
entsql.Default(uuid.Nil.String()),
|
||||
),
|
||||
field.Int("owner_id").
|
||||
Default(0),
|
||||
}
|
||||
}
|
||||
|
||||
// Edges of the Pet.
|
||||
func (Pet) Edges() []ent.Edge {
|
||||
return []ent.Edge{
|
||||
edge.To("best_friend", Pet.Type).
|
||||
Unique().
|
||||
Required().
|
||||
Field("best_friend_id"),
|
||||
edge.To("owner", User.Type).
|
||||
Unique().
|
||||
Required().
|
||||
Field("owner_id"),
|
||||
}
|
||||
}
|
||||
|
||||
// Indexes of the Pet.
|
||||
func (Pet) Indexes() []ent.Index {
|
||||
return []ent.Index{
|
||||
index.Fields("name", "owner_id").
|
||||
Unique(),
|
||||
}
|
||||
}
|
||||
100
examples/migration/ent/schema/session.go
Normal file
100
examples/migration/ent/schema/session.go
Normal file
@@ -0,0 +1,100 @@
|
||||
package schema
|
||||
|
||||
import (
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/entsql"
|
||||
"entgo.io/ent/schema"
|
||||
"entgo.io/ent/schema/edge"
|
||||
"entgo.io/ent/schema/field"
|
||||
"entgo.io/ent/schema/index"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Session holds the schema definition for the Session entity.
|
||||
type Session struct {
|
||||
ent.Schema
|
||||
}
|
||||
|
||||
// Fields of the Session.
|
||||
func (Session) Fields() []ent.Field {
|
||||
return []ent.Field{
|
||||
field.UUID("id", uuid.Nil).
|
||||
Default(uuid.New),
|
||||
field.Bool("active").
|
||||
Default(false),
|
||||
field.Time("issued_at"),
|
||||
field.Time("expires_at").
|
||||
Optional(),
|
||||
field.String("token").
|
||||
Optional(),
|
||||
field.JSON("method", map[string]any{}).
|
||||
Optional(),
|
||||
field.UUID("device_id", uuid.Nil).
|
||||
Optional(),
|
||||
}
|
||||
}
|
||||
|
||||
// Edges of the Session.
|
||||
func (Session) Edges() []ent.Edge {
|
||||
return []ent.Edge{
|
||||
edge.From("device", SessionDevice.Type).
|
||||
Ref("sessions").
|
||||
Unique().
|
||||
Field("device_id"),
|
||||
}
|
||||
}
|
||||
|
||||
// Indexes of the Session.
|
||||
func (Session) Indexes() []ent.Index {
|
||||
return []ent.Index{
|
||||
index.Fields("active", "expires_at"),
|
||||
}
|
||||
}
|
||||
|
||||
// Annotations of the Session.
|
||||
func (Session) Annotations() []schema.Annotation {
|
||||
return []schema.Annotation{
|
||||
// Named check constraints are compared by their name.
|
||||
// Thus, the definition does not need to be normalized.
|
||||
entsql.Checks(map[string]string{
|
||||
"token_length": "(LENGTH(`token`) = 64)",
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
// SessionDevice holds the schema definition for the SessionDevice entity.
|
||||
type SessionDevice struct {
|
||||
ent.Schema
|
||||
}
|
||||
|
||||
// Fields of the SessionDevice.
|
||||
func (SessionDevice) Fields() []ent.Field {
|
||||
return []ent.Field{
|
||||
field.UUID("id", uuid.Nil).
|
||||
Default(uuid.New),
|
||||
field.String("ip_address").
|
||||
MaxLen(50),
|
||||
field.String("user_agent").
|
||||
MaxLen(512),
|
||||
field.String("location").
|
||||
MaxLen(512),
|
||||
field.Time("created_at"),
|
||||
field.Time("updated_at").
|
||||
Optional(),
|
||||
}
|
||||
}
|
||||
|
||||
// Edges of the SessionDevice.
|
||||
func (SessionDevice) Edges() []ent.Edge {
|
||||
return []ent.Edge{
|
||||
edge.To("sessions", Session.Type),
|
||||
}
|
||||
}
|
||||
|
||||
// Indexes of the SessionDevice.
|
||||
func (SessionDevice) Indexes() []ent.Index {
|
||||
return []ent.Index{
|
||||
index.Fields("ip_address", "user_agent"),
|
||||
index.Fields("location", "updated_at"),
|
||||
}
|
||||
}
|
||||
52
examples/migration/ent/schema/user.go
Normal file
52
examples/migration/ent/schema/user.go
Normal file
@@ -0,0 +1,52 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
package schema
|
||||
|
||||
import (
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/entsql"
|
||||
"entgo.io/ent/schema"
|
||||
"entgo.io/ent/schema/edge"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// User holds the schema definition for the User entity.
|
||||
type User struct {
|
||||
ent.Schema
|
||||
}
|
||||
|
||||
// Fields of the User.
|
||||
func (User) Fields() []ent.Field {
|
||||
return []ent.Field{
|
||||
field.Float("age"),
|
||||
field.String("first_name"),
|
||||
field.String("last_name"),
|
||||
field.Strings("tags").
|
||||
Optional(),
|
||||
}
|
||||
}
|
||||
|
||||
// Annotations of the User.
|
||||
func (User) Annotations() []schema.Annotation {
|
||||
return []schema.Annotation{
|
||||
// In case schema.ModeInspect is used without a dev-database, unnamed check constraints
|
||||
// should be normalized (i.e. identical to their definition in the database). In this
|
||||
// case, it is entsql.Check("(`age` > 0)"). See: https://atlasgo.io/concepts/dev-database.
|
||||
entsql.Check("age > 0"),
|
||||
|
||||
// Named check constraints are compared by their name.
|
||||
// Thus, the definition does not need to be normalized.
|
||||
entsql.Checks(map[string]string{
|
||||
"first_last_not_empty": "(`first_name` <> '' AND `last_name` <> '')",
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
// Edges of the User.
|
||||
func (User) Edges() []ent.Edge {
|
||||
return []ent.Edge{
|
||||
edge.To("cards", Card.Type),
|
||||
}
|
||||
}
|
||||
202
examples/migration/ent/session.go
Normal file
202
examples/migration/ent/session.go
Normal file
@@ -0,0 +1,202 @@
|
||||
// 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 (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/examples/migration/ent/session"
|
||||
"entgo.io/ent/examples/migration/ent/sessiondevice"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Session is the model entity for the Session schema.
|
||||
type Session struct {
|
||||
config `json:"-"`
|
||||
// ID of the ent.
|
||||
ID uuid.UUID `json:"id,omitempty"`
|
||||
// Active holds the value of the "active" field.
|
||||
Active bool `json:"active,omitempty"`
|
||||
// IssuedAt holds the value of the "issued_at" field.
|
||||
IssuedAt time.Time `json:"issued_at,omitempty"`
|
||||
// ExpiresAt holds the value of the "expires_at" field.
|
||||
ExpiresAt time.Time `json:"expires_at,omitempty"`
|
||||
// Token holds the value of the "token" field.
|
||||
Token string `json:"token,omitempty"`
|
||||
// Method holds the value of the "method" field.
|
||||
Method map[string]interface{} `json:"method,omitempty"`
|
||||
// DeviceID holds the value of the "device_id" field.
|
||||
DeviceID uuid.UUID `json:"device_id,omitempty"`
|
||||
// Edges holds the relations/edges for other nodes in the graph.
|
||||
// The values are being populated by the SessionQuery when eager-loading is set.
|
||||
Edges SessionEdges `json:"edges"`
|
||||
selectValues sql.SelectValues
|
||||
}
|
||||
|
||||
// SessionEdges holds the relations/edges for other nodes in the graph.
|
||||
type SessionEdges struct {
|
||||
// Device holds the value of the device edge.
|
||||
Device *SessionDevice `json:"device,omitempty"`
|
||||
// loadedTypes holds the information for reporting if a
|
||||
// type was loaded (or requested) in eager-loading or not.
|
||||
loadedTypes [1]bool
|
||||
}
|
||||
|
||||
// DeviceOrErr returns the Device value or an error if the edge
|
||||
// was not loaded in eager-loading, or loaded but was not found.
|
||||
func (e SessionEdges) DeviceOrErr() (*SessionDevice, error) {
|
||||
if e.Device != nil {
|
||||
return e.Device, nil
|
||||
} else if e.loadedTypes[0] {
|
||||
return nil, &NotFoundError{label: sessiondevice.Label}
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "device"}
|
||||
}
|
||||
|
||||
// scanValues returns the types for scanning values from sql.Rows.
|
||||
func (*Session) scanValues(columns []string) ([]any, error) {
|
||||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case session.FieldMethod:
|
||||
values[i] = new([]byte)
|
||||
case session.FieldActive:
|
||||
values[i] = new(sql.NullBool)
|
||||
case session.FieldToken:
|
||||
values[i] = new(sql.NullString)
|
||||
case session.FieldIssuedAt, session.FieldExpiresAt:
|
||||
values[i] = new(sql.NullTime)
|
||||
case session.FieldID, session.FieldDeviceID:
|
||||
values[i] = new(uuid.UUID)
|
||||
default:
|
||||
values[i] = new(sql.UnknownType)
|
||||
}
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// assignValues assigns the values that were returned from sql.Rows (after scanning)
|
||||
// to the Session fields.
|
||||
func (_m *Session) 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 session.FieldID:
|
||||
if value, ok := values[i].(*uuid.UUID); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field id", values[i])
|
||||
} else if value != nil {
|
||||
_m.ID = *value
|
||||
}
|
||||
case session.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 session.FieldIssuedAt:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field issued_at", values[i])
|
||||
} else if value.Valid {
|
||||
_m.IssuedAt = value.Time
|
||||
}
|
||||
case session.FieldExpiresAt:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field expires_at", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ExpiresAt = value.Time
|
||||
}
|
||||
case session.FieldToken:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field token", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Token = value.String
|
||||
}
|
||||
case session.FieldMethod:
|
||||
if value, ok := values[i].(*[]byte); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field method", values[i])
|
||||
} else if value != nil && len(*value) > 0 {
|
||||
if err := json.Unmarshal(*value, &_m.Method); err != nil {
|
||||
return fmt.Errorf("unmarshal field method: %w", err)
|
||||
}
|
||||
}
|
||||
case session.FieldDeviceID:
|
||||
if value, ok := values[i].(*uuid.UUID); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field device_id", values[i])
|
||||
} else if value != nil {
|
||||
_m.DeviceID = *value
|
||||
}
|
||||
default:
|
||||
_m.selectValues.Set(columns[i], values[i])
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Value returns the ent.Value that was dynamically selected and assigned to the Session.
|
||||
// This includes values selected through modifiers, order, etc.
|
||||
func (_m *Session) Value(name string) (ent.Value, error) {
|
||||
return _m.selectValues.Get(name)
|
||||
}
|
||||
|
||||
// QueryDevice queries the "device" edge of the Session entity.
|
||||
func (_m *Session) QueryDevice() *SessionDeviceQuery {
|
||||
return NewSessionClient(_m.config).QueryDevice(_m)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this Session.
|
||||
// Note that you need to call Session.Unwrap() before calling this method if this Session
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (_m *Session) Update() *SessionUpdateOne {
|
||||
return NewSessionClient(_m.config).UpdateOne(_m)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the Session 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 *Session) Unwrap() *Session {
|
||||
_tx, ok := _m.config.driver.(*txDriver)
|
||||
if !ok {
|
||||
panic("ent: Session is not a transactional entity")
|
||||
}
|
||||
_m.config.driver = _tx.drv
|
||||
return _m
|
||||
}
|
||||
|
||||
// String implements the fmt.Stringer.
|
||||
func (_m *Session) String() string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("Session(")
|
||||
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
|
||||
builder.WriteString("active=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.Active))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("issued_at=")
|
||||
builder.WriteString(_m.IssuedAt.Format(time.ANSIC))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("expires_at=")
|
||||
builder.WriteString(_m.ExpiresAt.Format(time.ANSIC))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("token=")
|
||||
builder.WriteString(_m.Token)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("method=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.Method))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("device_id=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.DeviceID))
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// Sessions is a parsable slice of Session.
|
||||
type Sessions []*Session
|
||||
543
examples/migration/ent/session/mutation.go
Normal file
543
examples/migration/ent/session/mutation.go
Normal file
@@ -0,0 +1,543 @@
|
||||
// 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 session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/examples/migration/ent/predicate"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Mutation represents an operation that mutates the Session nodes in the graph.
|
||||
type Mutation struct {
|
||||
op ent.Op
|
||||
typ string
|
||||
active *bool
|
||||
issued_at *time.Time
|
||||
expires_at *time.Time
|
||||
token *string
|
||||
method *map[string]interface{}
|
||||
clearedFields map[string]struct{}
|
||||
device *uuid.UUID
|
||||
cleareddevice bool
|
||||
predicates []predicate.Session
|
||||
}
|
||||
|
||||
// NewMutation creates a new Mutation for the Session entity.
|
||||
func NewMutation(op ent.Op) *Mutation {
|
||||
return &Mutation{
|
||||
op: op,
|
||||
typ: "Session",
|
||||
clearedFields: make(map[string]struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
// Predicates returns the list of predicates set on the mutation.
|
||||
func (m *Mutation) Predicates() []predicate.Session {
|
||||
return m.predicates
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// SetIssuedAt sets the "issued_at" field.
|
||||
func (m *Mutation) SetIssuedAt(t time.Time) {
|
||||
m.issued_at = &t
|
||||
}
|
||||
|
||||
// IssuedAt returns the value of the "issued_at" field in the mutation.
|
||||
func (m *Mutation) IssuedAt() (r time.Time, exists bool) {
|
||||
v := m.issued_at
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetIssuedAt resets all changes to the "issued_at" field.
|
||||
func (m *Mutation) ResetIssuedAt() {
|
||||
m.issued_at = nil
|
||||
}
|
||||
|
||||
// SetExpiresAt sets the "expires_at" field.
|
||||
func (m *Mutation) SetExpiresAt(t time.Time) {
|
||||
m.expires_at = &t
|
||||
}
|
||||
|
||||
// ExpiresAt returns the value of the "expires_at" field in the mutation.
|
||||
func (m *Mutation) ExpiresAt() (r time.Time, exists bool) {
|
||||
v := m.expires_at
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ClearExpiresAt clears the value of the "expires_at" field.
|
||||
func (m *Mutation) ClearExpiresAt() {
|
||||
m.expires_at = nil
|
||||
m.clearedFields[FieldExpiresAt] = struct{}{}
|
||||
}
|
||||
|
||||
// ExpiresAtCleared returns if the "expires_at" field was cleared in this mutation.
|
||||
func (m *Mutation) ExpiresAtCleared() bool {
|
||||
_, ok := m.clearedFields[FieldExpiresAt]
|
||||
return ok
|
||||
}
|
||||
|
||||
// ResetExpiresAt resets all changes to the "expires_at" field.
|
||||
func (m *Mutation) ResetExpiresAt() {
|
||||
m.expires_at = nil
|
||||
delete(m.clearedFields, FieldExpiresAt)
|
||||
}
|
||||
|
||||
// SetToken sets the "token" field.
|
||||
func (m *Mutation) SetToken(s string) {
|
||||
m.token = &s
|
||||
}
|
||||
|
||||
// Token returns the value of the "token" field in the mutation.
|
||||
func (m *Mutation) Token() (r string, exists bool) {
|
||||
v := m.token
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ClearToken clears the value of the "token" field.
|
||||
func (m *Mutation) ClearToken() {
|
||||
m.token = nil
|
||||
m.clearedFields[FieldToken] = struct{}{}
|
||||
}
|
||||
|
||||
// TokenCleared returns if the "token" field was cleared in this mutation.
|
||||
func (m *Mutation) TokenCleared() bool {
|
||||
_, ok := m.clearedFields[FieldToken]
|
||||
return ok
|
||||
}
|
||||
|
||||
// ResetToken resets all changes to the "token" field.
|
||||
func (m *Mutation) ResetToken() {
|
||||
m.token = nil
|
||||
delete(m.clearedFields, FieldToken)
|
||||
}
|
||||
|
||||
// SetMethod sets the "method" field.
|
||||
func (m *Mutation) SetMethod(value map[string]interface{}) {
|
||||
m.method = &value
|
||||
}
|
||||
|
||||
// Method returns the value of the "method" field in the mutation.
|
||||
func (m *Mutation) Method() (r map[string]interface{}, exists bool) {
|
||||
v := m.method
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ClearMethod clears the value of the "method" field.
|
||||
func (m *Mutation) ClearMethod() {
|
||||
m.method = nil
|
||||
m.clearedFields[FieldMethod] = struct{}{}
|
||||
}
|
||||
|
||||
// MethodCleared returns if the "method" field was cleared in this mutation.
|
||||
func (m *Mutation) MethodCleared() bool {
|
||||
_, ok := m.clearedFields[FieldMethod]
|
||||
return ok
|
||||
}
|
||||
|
||||
// ResetMethod resets all changes to the "method" field.
|
||||
func (m *Mutation) ResetMethod() {
|
||||
m.method = nil
|
||||
delete(m.clearedFields, FieldMethod)
|
||||
}
|
||||
|
||||
// SetDeviceID sets the "device_id" field.
|
||||
func (m *Mutation) SetDeviceID(u uuid.UUID) {
|
||||
m.device = &u
|
||||
}
|
||||
|
||||
// DeviceID returns the value of the "device_id" field in the mutation.
|
||||
func (m *Mutation) DeviceID() (r uuid.UUID, exists bool) {
|
||||
v := m.device
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ClearDeviceID clears the value of the "device_id" field.
|
||||
func (m *Mutation) ClearDeviceID() {
|
||||
m.device = nil
|
||||
m.clearedFields[FieldDeviceID] = struct{}{}
|
||||
}
|
||||
|
||||
// DeviceIDCleared returns if the "device_id" field was cleared in this mutation.
|
||||
func (m *Mutation) DeviceIDCleared() bool {
|
||||
_, ok := m.clearedFields[FieldDeviceID]
|
||||
return ok
|
||||
}
|
||||
|
||||
// ResetDeviceID resets all changes to the "device_id" field.
|
||||
func (m *Mutation) ResetDeviceID() {
|
||||
m.device = nil
|
||||
delete(m.clearedFields, FieldDeviceID)
|
||||
}
|
||||
|
||||
// ClearDevice clears the "device" edge to the SessionDevice entity.
|
||||
func (m *Mutation) ClearDevice() {
|
||||
m.cleareddevice = true
|
||||
m.clearedFields[FieldDeviceID] = struct{}{}
|
||||
}
|
||||
|
||||
// DeviceCleared reports if the "device" edge to the SessionDevice entity was cleared.
|
||||
func (m *Mutation) DeviceCleared() bool {
|
||||
return m.DeviceIDCleared() || m.cleareddevice
|
||||
}
|
||||
|
||||
// DeviceIDs returns the "device" edge IDs in the mutation.
|
||||
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
|
||||
// DeviceID instead. It exists only for internal usage by the builders.
|
||||
func (m *Mutation) DeviceIDs() (ids []uuid.UUID) {
|
||||
if id := m.device; id != nil {
|
||||
ids = append(ids, *id)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ResetDevice resets all changes to the "device" edge.
|
||||
func (m *Mutation) ResetDevice() {
|
||||
m.device = nil
|
||||
m.cleareddevice = false
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the Mutation builder.
|
||||
func (m *Mutation) Where(ps ...predicate.Session) {
|
||||
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.Session, 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 (Session).
|
||||
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, 6)
|
||||
if m.active != nil {
|
||||
fields = append(fields, FieldActive)
|
||||
}
|
||||
if m.issued_at != nil {
|
||||
fields = append(fields, FieldIssuedAt)
|
||||
}
|
||||
if m.expires_at != nil {
|
||||
fields = append(fields, FieldExpiresAt)
|
||||
}
|
||||
if m.token != nil {
|
||||
fields = append(fields, FieldToken)
|
||||
}
|
||||
if m.method != nil {
|
||||
fields = append(fields, FieldMethod)
|
||||
}
|
||||
if m.device != nil {
|
||||
fields = append(fields, FieldDeviceID)
|
||||
}
|
||||
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 FieldActive:
|
||||
return m.Active()
|
||||
case FieldIssuedAt:
|
||||
return m.IssuedAt()
|
||||
case FieldExpiresAt:
|
||||
return m.ExpiresAt()
|
||||
case FieldToken:
|
||||
return m.Token()
|
||||
case FieldMethod:
|
||||
return m.Method()
|
||||
case FieldDeviceID:
|
||||
return m.DeviceID()
|
||||
}
|
||||
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 Session 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 FieldActive:
|
||||
v, ok := value.(bool)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetActive(v)
|
||||
return nil
|
||||
case FieldIssuedAt:
|
||||
v, ok := value.(time.Time)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetIssuedAt(v)
|
||||
return nil
|
||||
case FieldExpiresAt:
|
||||
v, ok := value.(time.Time)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetExpiresAt(v)
|
||||
return nil
|
||||
case FieldToken:
|
||||
v, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetToken(v)
|
||||
return nil
|
||||
case FieldMethod:
|
||||
v, ok := value.(map[string]interface{})
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetMethod(v)
|
||||
return nil
|
||||
case FieldDeviceID:
|
||||
v, ok := value.(uuid.UUID)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetDeviceID(v)
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown Session 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 Session 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(FieldExpiresAt) {
|
||||
fields = append(fields, FieldExpiresAt)
|
||||
}
|
||||
if m.FieldCleared(FieldToken) {
|
||||
fields = append(fields, FieldToken)
|
||||
}
|
||||
if m.FieldCleared(FieldMethod) {
|
||||
fields = append(fields, FieldMethod)
|
||||
}
|
||||
if m.FieldCleared(FieldDeviceID) {
|
||||
fields = append(fields, FieldDeviceID)
|
||||
}
|
||||
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 FieldExpiresAt:
|
||||
m.ClearExpiresAt()
|
||||
return nil
|
||||
case FieldToken:
|
||||
m.ClearToken()
|
||||
return nil
|
||||
case FieldMethod:
|
||||
m.ClearMethod()
|
||||
return nil
|
||||
case FieldDeviceID:
|
||||
m.ClearDeviceID()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown Session 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 FieldActive:
|
||||
m.ResetActive()
|
||||
return nil
|
||||
case FieldIssuedAt:
|
||||
m.ResetIssuedAt()
|
||||
return nil
|
||||
case FieldExpiresAt:
|
||||
m.ResetExpiresAt()
|
||||
return nil
|
||||
case FieldToken:
|
||||
m.ResetToken()
|
||||
return nil
|
||||
case FieldMethod:
|
||||
m.ResetMethod()
|
||||
return nil
|
||||
case FieldDeviceID:
|
||||
m.ResetDeviceID()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown Session 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.device != nil {
|
||||
edges = append(edges, EdgeDevice)
|
||||
}
|
||||
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 EdgeDevice:
|
||||
if id := m.device; 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.cleareddevice {
|
||||
edges = append(edges, EdgeDevice)
|
||||
}
|
||||
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 EdgeDevice:
|
||||
return m.cleareddevice
|
||||
}
|
||||
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 EdgeDevice:
|
||||
m.ClearDevice()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown Session 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 EdgeDevice:
|
||||
m.ResetDevice()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown Session edge %s", name)
|
||||
}
|
||||
118
examples/migration/ent/session/session.go
Normal file
118
examples/migration/ent/session/session.go
Normal file
@@ -0,0 +1,118 @@
|
||||
// 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 session
|
||||
|
||||
import (
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the session type in the database.
|
||||
Label = "session"
|
||||
// FieldID holds the string denoting the id field in the database.
|
||||
FieldID = "id"
|
||||
// FieldActive holds the string denoting the active field in the database.
|
||||
FieldActive = "active"
|
||||
// FieldIssuedAt holds the string denoting the issued_at field in the database.
|
||||
FieldIssuedAt = "issued_at"
|
||||
// FieldExpiresAt holds the string denoting the expires_at field in the database.
|
||||
FieldExpiresAt = "expires_at"
|
||||
// FieldToken holds the string denoting the token field in the database.
|
||||
FieldToken = "token"
|
||||
// FieldMethod holds the string denoting the method field in the database.
|
||||
FieldMethod = "method"
|
||||
// FieldDeviceID holds the string denoting the device_id field in the database.
|
||||
FieldDeviceID = "device_id"
|
||||
// EdgeDevice holds the string denoting the device edge name in mutations.
|
||||
EdgeDevice = "device"
|
||||
// Table holds the table name of the session in the database.
|
||||
Table = "sessions"
|
||||
// DeviceTable is the table that holds the device relation/edge.
|
||||
DeviceTable = "sessions"
|
||||
// DeviceInverseTable is the table name for the SessionDevice entity.
|
||||
// It exists in this package in order to avoid circular dependency with the "sessiondevice" package.
|
||||
DeviceInverseTable = "session_devices"
|
||||
// DeviceColumn is the table column denoting the device relation/edge.
|
||||
DeviceColumn = "device_id"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for session fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldActive,
|
||||
FieldIssuedAt,
|
||||
FieldExpiresAt,
|
||||
FieldToken,
|
||||
FieldMethod,
|
||||
FieldDeviceID,
|
||||
}
|
||||
|
||||
// ValidColumn reports if the column name is valid (part of the table columns).
|
||||
func ValidColumn(column string) bool {
|
||||
for i := range Columns {
|
||||
if column == Columns[i] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var (
|
||||
// DefaultActive holds the default value on creation for the "active" field.
|
||||
DefaultActive bool
|
||||
// DefaultID holds the default value on creation for the "id" field.
|
||||
DefaultID func() uuid.UUID
|
||||
)
|
||||
|
||||
// OrderOption defines the ordering options for the Session 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()
|
||||
}
|
||||
|
||||
// ByActive orders the results by the active field.
|
||||
func ByActive(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldActive, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByIssuedAt orders the results by the issued_at field.
|
||||
func ByIssuedAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldIssuedAt, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByExpiresAt orders the results by the expires_at field.
|
||||
func ByExpiresAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldExpiresAt, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByToken orders the results by the token field.
|
||||
func ByToken(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldToken, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByDeviceID orders the results by the device_id field.
|
||||
func ByDeviceID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldDeviceID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByDeviceField orders the results by device field.
|
||||
func ByDeviceField(field string, opts ...sql.OrderTermOption) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborTerms(s, newDeviceStep(), sql.OrderByField(field, opts...))
|
||||
}
|
||||
}
|
||||
func newDeviceStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(DeviceInverseTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, DeviceTable, DeviceColumn),
|
||||
)
|
||||
}
|
||||
339
examples/migration/ent/session/where.go
Normal file
339
examples/migration/ent/session/where.go
Normal file
@@ -0,0 +1,339 @@
|
||||
// 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 session
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/predicate"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id uuid.UUID) predicate.Session {
|
||||
return predicate.Session(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id uuid.UUID) predicate.Session {
|
||||
return predicate.Session(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id uuid.UUID) predicate.Session {
|
||||
return predicate.Session(sql.FieldNEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...uuid.UUID) predicate.Session {
|
||||
return predicate.Session(sql.FieldIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...uuid.UUID) predicate.Session {
|
||||
return predicate.Session(sql.FieldNotIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id uuid.UUID) predicate.Session {
|
||||
return predicate.Session(sql.FieldGT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id uuid.UUID) predicate.Session {
|
||||
return predicate.Session(sql.FieldGTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id uuid.UUID) predicate.Session {
|
||||
return predicate.Session(sql.FieldLT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id uuid.UUID) predicate.Session {
|
||||
return predicate.Session(sql.FieldLTE(FieldID, id))
|
||||
}
|
||||
|
||||
// Active applies equality check predicate on the "active" field. It's identical to ActiveEQ.
|
||||
func Active(v bool) predicate.Session {
|
||||
return predicate.Session(sql.FieldEQ(FieldActive, v))
|
||||
}
|
||||
|
||||
// IssuedAt applies equality check predicate on the "issued_at" field. It's identical to IssuedAtEQ.
|
||||
func IssuedAt(v time.Time) predicate.Session {
|
||||
return predicate.Session(sql.FieldEQ(FieldIssuedAt, v))
|
||||
}
|
||||
|
||||
// ExpiresAt applies equality check predicate on the "expires_at" field. It's identical to ExpiresAtEQ.
|
||||
func ExpiresAt(v time.Time) predicate.Session {
|
||||
return predicate.Session(sql.FieldEQ(FieldExpiresAt, v))
|
||||
}
|
||||
|
||||
// Token applies equality check predicate on the "token" field. It's identical to TokenEQ.
|
||||
func Token(v string) predicate.Session {
|
||||
return predicate.Session(sql.FieldEQ(FieldToken, v))
|
||||
}
|
||||
|
||||
// DeviceID applies equality check predicate on the "device_id" field. It's identical to DeviceIDEQ.
|
||||
func DeviceID(v uuid.UUID) predicate.Session {
|
||||
return predicate.Session(sql.FieldEQ(FieldDeviceID, v))
|
||||
}
|
||||
|
||||
// ActiveEQ applies the EQ predicate on the "active" field.
|
||||
func ActiveEQ(v bool) predicate.Session {
|
||||
return predicate.Session(sql.FieldEQ(FieldActive, v))
|
||||
}
|
||||
|
||||
// ActiveNEQ applies the NEQ predicate on the "active" field.
|
||||
func ActiveNEQ(v bool) predicate.Session {
|
||||
return predicate.Session(sql.FieldNEQ(FieldActive, v))
|
||||
}
|
||||
|
||||
// IssuedAtEQ applies the EQ predicate on the "issued_at" field.
|
||||
func IssuedAtEQ(v time.Time) predicate.Session {
|
||||
return predicate.Session(sql.FieldEQ(FieldIssuedAt, v))
|
||||
}
|
||||
|
||||
// IssuedAtNEQ applies the NEQ predicate on the "issued_at" field.
|
||||
func IssuedAtNEQ(v time.Time) predicate.Session {
|
||||
return predicate.Session(sql.FieldNEQ(FieldIssuedAt, v))
|
||||
}
|
||||
|
||||
// IssuedAtIn applies the In predicate on the "issued_at" field.
|
||||
func IssuedAtIn(vs ...time.Time) predicate.Session {
|
||||
return predicate.Session(sql.FieldIn(FieldIssuedAt, vs...))
|
||||
}
|
||||
|
||||
// IssuedAtNotIn applies the NotIn predicate on the "issued_at" field.
|
||||
func IssuedAtNotIn(vs ...time.Time) predicate.Session {
|
||||
return predicate.Session(sql.FieldNotIn(FieldIssuedAt, vs...))
|
||||
}
|
||||
|
||||
// IssuedAtGT applies the GT predicate on the "issued_at" field.
|
||||
func IssuedAtGT(v time.Time) predicate.Session {
|
||||
return predicate.Session(sql.FieldGT(FieldIssuedAt, v))
|
||||
}
|
||||
|
||||
// IssuedAtGTE applies the GTE predicate on the "issued_at" field.
|
||||
func IssuedAtGTE(v time.Time) predicate.Session {
|
||||
return predicate.Session(sql.FieldGTE(FieldIssuedAt, v))
|
||||
}
|
||||
|
||||
// IssuedAtLT applies the LT predicate on the "issued_at" field.
|
||||
func IssuedAtLT(v time.Time) predicate.Session {
|
||||
return predicate.Session(sql.FieldLT(FieldIssuedAt, v))
|
||||
}
|
||||
|
||||
// IssuedAtLTE applies the LTE predicate on the "issued_at" field.
|
||||
func IssuedAtLTE(v time.Time) predicate.Session {
|
||||
return predicate.Session(sql.FieldLTE(FieldIssuedAt, v))
|
||||
}
|
||||
|
||||
// ExpiresAtEQ applies the EQ predicate on the "expires_at" field.
|
||||
func ExpiresAtEQ(v time.Time) predicate.Session {
|
||||
return predicate.Session(sql.FieldEQ(FieldExpiresAt, v))
|
||||
}
|
||||
|
||||
// ExpiresAtNEQ applies the NEQ predicate on the "expires_at" field.
|
||||
func ExpiresAtNEQ(v time.Time) predicate.Session {
|
||||
return predicate.Session(sql.FieldNEQ(FieldExpiresAt, v))
|
||||
}
|
||||
|
||||
// ExpiresAtIn applies the In predicate on the "expires_at" field.
|
||||
func ExpiresAtIn(vs ...time.Time) predicate.Session {
|
||||
return predicate.Session(sql.FieldIn(FieldExpiresAt, vs...))
|
||||
}
|
||||
|
||||
// ExpiresAtNotIn applies the NotIn predicate on the "expires_at" field.
|
||||
func ExpiresAtNotIn(vs ...time.Time) predicate.Session {
|
||||
return predicate.Session(sql.FieldNotIn(FieldExpiresAt, vs...))
|
||||
}
|
||||
|
||||
// ExpiresAtGT applies the GT predicate on the "expires_at" field.
|
||||
func ExpiresAtGT(v time.Time) predicate.Session {
|
||||
return predicate.Session(sql.FieldGT(FieldExpiresAt, v))
|
||||
}
|
||||
|
||||
// ExpiresAtGTE applies the GTE predicate on the "expires_at" field.
|
||||
func ExpiresAtGTE(v time.Time) predicate.Session {
|
||||
return predicate.Session(sql.FieldGTE(FieldExpiresAt, v))
|
||||
}
|
||||
|
||||
// ExpiresAtLT applies the LT predicate on the "expires_at" field.
|
||||
func ExpiresAtLT(v time.Time) predicate.Session {
|
||||
return predicate.Session(sql.FieldLT(FieldExpiresAt, v))
|
||||
}
|
||||
|
||||
// ExpiresAtLTE applies the LTE predicate on the "expires_at" field.
|
||||
func ExpiresAtLTE(v time.Time) predicate.Session {
|
||||
return predicate.Session(sql.FieldLTE(FieldExpiresAt, v))
|
||||
}
|
||||
|
||||
// ExpiresAtIsNil applies the IsNil predicate on the "expires_at" field.
|
||||
func ExpiresAtIsNil() predicate.Session {
|
||||
return predicate.Session(sql.FieldIsNull(FieldExpiresAt))
|
||||
}
|
||||
|
||||
// ExpiresAtNotNil applies the NotNil predicate on the "expires_at" field.
|
||||
func ExpiresAtNotNil() predicate.Session {
|
||||
return predicate.Session(sql.FieldNotNull(FieldExpiresAt))
|
||||
}
|
||||
|
||||
// TokenEQ applies the EQ predicate on the "token" field.
|
||||
func TokenEQ(v string) predicate.Session {
|
||||
return predicate.Session(sql.FieldEQ(FieldToken, v))
|
||||
}
|
||||
|
||||
// TokenNEQ applies the NEQ predicate on the "token" field.
|
||||
func TokenNEQ(v string) predicate.Session {
|
||||
return predicate.Session(sql.FieldNEQ(FieldToken, v))
|
||||
}
|
||||
|
||||
// TokenIn applies the In predicate on the "token" field.
|
||||
func TokenIn(vs ...string) predicate.Session {
|
||||
return predicate.Session(sql.FieldIn(FieldToken, vs...))
|
||||
}
|
||||
|
||||
// TokenNotIn applies the NotIn predicate on the "token" field.
|
||||
func TokenNotIn(vs ...string) predicate.Session {
|
||||
return predicate.Session(sql.FieldNotIn(FieldToken, vs...))
|
||||
}
|
||||
|
||||
// TokenGT applies the GT predicate on the "token" field.
|
||||
func TokenGT(v string) predicate.Session {
|
||||
return predicate.Session(sql.FieldGT(FieldToken, v))
|
||||
}
|
||||
|
||||
// TokenGTE applies the GTE predicate on the "token" field.
|
||||
func TokenGTE(v string) predicate.Session {
|
||||
return predicate.Session(sql.FieldGTE(FieldToken, v))
|
||||
}
|
||||
|
||||
// TokenLT applies the LT predicate on the "token" field.
|
||||
func TokenLT(v string) predicate.Session {
|
||||
return predicate.Session(sql.FieldLT(FieldToken, v))
|
||||
}
|
||||
|
||||
// TokenLTE applies the LTE predicate on the "token" field.
|
||||
func TokenLTE(v string) predicate.Session {
|
||||
return predicate.Session(sql.FieldLTE(FieldToken, v))
|
||||
}
|
||||
|
||||
// TokenContains applies the Contains predicate on the "token" field.
|
||||
func TokenContains(v string) predicate.Session {
|
||||
return predicate.Session(sql.FieldContains(FieldToken, v))
|
||||
}
|
||||
|
||||
// TokenHasPrefix applies the HasPrefix predicate on the "token" field.
|
||||
func TokenHasPrefix(v string) predicate.Session {
|
||||
return predicate.Session(sql.FieldHasPrefix(FieldToken, v))
|
||||
}
|
||||
|
||||
// TokenHasSuffix applies the HasSuffix predicate on the "token" field.
|
||||
func TokenHasSuffix(v string) predicate.Session {
|
||||
return predicate.Session(sql.FieldHasSuffix(FieldToken, v))
|
||||
}
|
||||
|
||||
// TokenIsNil applies the IsNil predicate on the "token" field.
|
||||
func TokenIsNil() predicate.Session {
|
||||
return predicate.Session(sql.FieldIsNull(FieldToken))
|
||||
}
|
||||
|
||||
// TokenNotNil applies the NotNil predicate on the "token" field.
|
||||
func TokenNotNil() predicate.Session {
|
||||
return predicate.Session(sql.FieldNotNull(FieldToken))
|
||||
}
|
||||
|
||||
// TokenEqualFold applies the EqualFold predicate on the "token" field.
|
||||
func TokenEqualFold(v string) predicate.Session {
|
||||
return predicate.Session(sql.FieldEqualFold(FieldToken, v))
|
||||
}
|
||||
|
||||
// TokenContainsFold applies the ContainsFold predicate on the "token" field.
|
||||
func TokenContainsFold(v string) predicate.Session {
|
||||
return predicate.Session(sql.FieldContainsFold(FieldToken, v))
|
||||
}
|
||||
|
||||
// MethodIsNil applies the IsNil predicate on the "method" field.
|
||||
func MethodIsNil() predicate.Session {
|
||||
return predicate.Session(sql.FieldIsNull(FieldMethod))
|
||||
}
|
||||
|
||||
// MethodNotNil applies the NotNil predicate on the "method" field.
|
||||
func MethodNotNil() predicate.Session {
|
||||
return predicate.Session(sql.FieldNotNull(FieldMethod))
|
||||
}
|
||||
|
||||
// DeviceIDEQ applies the EQ predicate on the "device_id" field.
|
||||
func DeviceIDEQ(v uuid.UUID) predicate.Session {
|
||||
return predicate.Session(sql.FieldEQ(FieldDeviceID, v))
|
||||
}
|
||||
|
||||
// DeviceIDNEQ applies the NEQ predicate on the "device_id" field.
|
||||
func DeviceIDNEQ(v uuid.UUID) predicate.Session {
|
||||
return predicate.Session(sql.FieldNEQ(FieldDeviceID, v))
|
||||
}
|
||||
|
||||
// DeviceIDIn applies the In predicate on the "device_id" field.
|
||||
func DeviceIDIn(vs ...uuid.UUID) predicate.Session {
|
||||
return predicate.Session(sql.FieldIn(FieldDeviceID, vs...))
|
||||
}
|
||||
|
||||
// DeviceIDNotIn applies the NotIn predicate on the "device_id" field.
|
||||
func DeviceIDNotIn(vs ...uuid.UUID) predicate.Session {
|
||||
return predicate.Session(sql.FieldNotIn(FieldDeviceID, vs...))
|
||||
}
|
||||
|
||||
// DeviceIDIsNil applies the IsNil predicate on the "device_id" field.
|
||||
func DeviceIDIsNil() predicate.Session {
|
||||
return predicate.Session(sql.FieldIsNull(FieldDeviceID))
|
||||
}
|
||||
|
||||
// DeviceIDNotNil applies the NotNil predicate on the "device_id" field.
|
||||
func DeviceIDNotNil() predicate.Session {
|
||||
return predicate.Session(sql.FieldNotNull(FieldDeviceID))
|
||||
}
|
||||
|
||||
// HasDevice applies the HasEdge predicate on the "device" edge.
|
||||
func HasDevice() predicate.Session {
|
||||
return predicate.Session(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, DeviceTable, DeviceColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
})
|
||||
}
|
||||
|
||||
// HasDeviceWith applies the HasEdge predicate on the "device" edge with a given conditions (other predicates).
|
||||
func HasDeviceWith(preds ...predicate.SessionDevice) predicate.Session {
|
||||
return predicate.Session(func(s *sql.Selector) {
|
||||
step := newDeviceStep()
|
||||
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.Session) predicate.Session {
|
||||
return predicate.Session(sql.AndPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Or groups predicates with the OR operator between them.
|
||||
func Or(predicates ...predicate.Session) predicate.Session {
|
||||
return predicate.Session(sql.OrPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Not applies the not operator on the given predicate.
|
||||
func Not(p predicate.Session) predicate.Session {
|
||||
return predicate.Session(sql.NotPredicates(p))
|
||||
}
|
||||
326
examples/migration/ent/session_create.go
Normal file
326
examples/migration/ent/session_create.go
Normal file
@@ -0,0 +1,326 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/session"
|
||||
"entgo.io/ent/examples/migration/ent/sessiondevice"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// SessionCreate is the builder for creating a Session entity.
|
||||
type SessionCreate struct {
|
||||
config
|
||||
mutation *SessionMutation
|
||||
hooks []Hook
|
||||
}
|
||||
|
||||
// SetActive sets the "active" field.
|
||||
func (_c *SessionCreate) SetActive(v bool) *SessionCreate {
|
||||
_c.mutation.SetActive(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableActive sets the "active" field if the given value is not nil.
|
||||
func (_c *SessionCreate) SetNillableActive(v *bool) *SessionCreate {
|
||||
if v != nil {
|
||||
_c.SetActive(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetIssuedAt sets the "issued_at" field.
|
||||
func (_c *SessionCreate) SetIssuedAt(v time.Time) *SessionCreate {
|
||||
_c.mutation.SetIssuedAt(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetExpiresAt sets the "expires_at" field.
|
||||
func (_c *SessionCreate) SetExpiresAt(v time.Time) *SessionCreate {
|
||||
_c.mutation.SetExpiresAt(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.
|
||||
func (_c *SessionCreate) SetNillableExpiresAt(v *time.Time) *SessionCreate {
|
||||
if v != nil {
|
||||
_c.SetExpiresAt(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetToken sets the "token" field.
|
||||
func (_c *SessionCreate) SetToken(v string) *SessionCreate {
|
||||
_c.mutation.SetToken(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableToken sets the "token" field if the given value is not nil.
|
||||
func (_c *SessionCreate) SetNillableToken(v *string) *SessionCreate {
|
||||
if v != nil {
|
||||
_c.SetToken(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetMethod sets the "method" field.
|
||||
func (_c *SessionCreate) SetMethod(v map[string]interface{}) *SessionCreate {
|
||||
_c.mutation.SetMethod(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetDeviceID sets the "device_id" field.
|
||||
func (_c *SessionCreate) SetDeviceID(v uuid.UUID) *SessionCreate {
|
||||
_c.mutation.SetDeviceID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableDeviceID sets the "device_id" field if the given value is not nil.
|
||||
func (_c *SessionCreate) SetNillableDeviceID(v *uuid.UUID) *SessionCreate {
|
||||
if v != nil {
|
||||
_c.SetDeviceID(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetID sets the "id" field.
|
||||
func (_c *SessionCreate) SetID(v uuid.UUID) *SessionCreate {
|
||||
_c.mutation.SetID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableID sets the "id" field if the given value is not nil.
|
||||
func (_c *SessionCreate) SetNillableID(v *uuid.UUID) *SessionCreate {
|
||||
if v != nil {
|
||||
_c.SetID(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetDevice sets the "device" edge to the SessionDevice entity.
|
||||
func (_c *SessionCreate) SetDevice(v *SessionDevice) *SessionCreate {
|
||||
return _c.SetDeviceID(v.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the SessionMutation object of the builder.
|
||||
func (_c *SessionCreate) Mutation() *SessionMutation {
|
||||
return _c.mutation
|
||||
}
|
||||
|
||||
// Save creates the Session in the database.
|
||||
func (_c *SessionCreate) Save(ctx context.Context) (*Session, error) {
|
||||
_c.defaults()
|
||||
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
func (_c *SessionCreate) SaveX(ctx context.Context) *Session {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *SessionCreate) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *SessionCreate) 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 *SessionCreate) defaults() {
|
||||
if _, ok := _c.mutation.Active(); !ok {
|
||||
v := session.DefaultActive
|
||||
_c.mutation.SetActive(v)
|
||||
}
|
||||
if _, ok := _c.mutation.ID(); !ok {
|
||||
v := session.DefaultID()
|
||||
_c.mutation.SetID(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_c *SessionCreate) check() error {
|
||||
if _, ok := _c.mutation.Active(); !ok {
|
||||
return &ValidationError{Name: "active", err: errors.New(`ent: missing required field "Session.active"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.IssuedAt(); !ok {
|
||||
return &ValidationError{Name: "issued_at", err: errors.New(`ent: missing required field "Session.issued_at"`)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_c *SessionCreate) sqlSave(ctx context.Context) (*Session, error) {
|
||||
if err := _c.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_node, _spec := _c.createSpec()
|
||||
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if _spec.ID.Value != nil {
|
||||
if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
|
||||
_node.ID = *id
|
||||
} else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
_c.mutation.id = &_node.ID
|
||||
_c.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
func (_c *SessionCreate) createSpec() (*Session, *sqlgraph.CreateSpec) {
|
||||
var (
|
||||
_node = &Session{config: _c.config}
|
||||
_spec = sqlgraph.NewCreateSpec(session.Table, sqlgraph.NewFieldSpec(session.FieldID, field.TypeUUID))
|
||||
)
|
||||
if id, ok := _c.mutation.ID(); ok {
|
||||
_node.ID = id
|
||||
_spec.ID.Value = &id
|
||||
}
|
||||
if value, ok := _c.mutation.Active(); ok {
|
||||
_spec.SetField(session.FieldActive, field.TypeBool, value)
|
||||
_node.Active = value
|
||||
}
|
||||
if value, ok := _c.mutation.IssuedAt(); ok {
|
||||
_spec.SetField(session.FieldIssuedAt, field.TypeTime, value)
|
||||
_node.IssuedAt = value
|
||||
}
|
||||
if value, ok := _c.mutation.ExpiresAt(); ok {
|
||||
_spec.SetField(session.FieldExpiresAt, field.TypeTime, value)
|
||||
_node.ExpiresAt = value
|
||||
}
|
||||
if value, ok := _c.mutation.Token(); ok {
|
||||
_spec.SetField(session.FieldToken, field.TypeString, value)
|
||||
_node.Token = value
|
||||
}
|
||||
if value, ok := _c.mutation.Method(); ok {
|
||||
_spec.SetField(session.FieldMethod, field.TypeJSON, value)
|
||||
_node.Method = value
|
||||
}
|
||||
if nodes := _c.mutation.DeviceIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: session.DeviceTable,
|
||||
Columns: []string{session.DeviceColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(sessiondevice.FieldID, field.TypeUUID),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_node.DeviceID = nodes[0]
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
return _node, _spec
|
||||
}
|
||||
|
||||
// SessionCreateBulk is the builder for creating many Session entities in bulk.
|
||||
type SessionCreateBulk struct {
|
||||
config
|
||||
err error
|
||||
builders []*SessionCreate
|
||||
}
|
||||
|
||||
// Save creates the Session entities in the database.
|
||||
func (_c *SessionCreateBulk) Save(ctx context.Context) ([]*Session, error) {
|
||||
if _c.err != nil {
|
||||
return nil, _c.err
|
||||
}
|
||||
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
|
||||
nodes := make([]*Session, 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.(*SessionMutation)
|
||||
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
|
||||
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 *SessionCreateBulk) SaveX(ctx context.Context) []*Session {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *SessionCreateBulk) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *SessionCreateBulk) ExecX(ctx context.Context) {
|
||||
if err := _c.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
92
examples/migration/ent/session_delete.go
Normal file
92
examples/migration/ent/session_delete.go
Normal file
@@ -0,0 +1,92 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/predicate"
|
||||
"entgo.io/ent/examples/migration/ent/session"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// SessionDelete is the builder for deleting a Session entity.
|
||||
type SessionDelete struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *SessionMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the SessionDelete builder.
|
||||
func (_d *SessionDelete) Where(ps ...predicate.Session) *SessionDelete {
|
||||
_d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (_d *SessionDelete) 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 *SessionDelete) ExecX(ctx context.Context) int {
|
||||
n, err := _d.Exec(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (_d *SessionDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
_spec := sqlgraph.NewDeleteSpec(session.Table, sqlgraph.NewFieldSpec(session.FieldID, field.TypeUUID))
|
||||
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
|
||||
}
|
||||
|
||||
// SessionDeleteOne is the builder for deleting a single Session entity.
|
||||
type SessionDeleteOne struct {
|
||||
_d *SessionDelete
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the SessionDelete builder.
|
||||
func (_d *SessionDeleteOne) Where(ps ...predicate.Session) *SessionDeleteOne {
|
||||
_d._d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (_d *SessionDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := _d._d.Exec(ctx)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case n == 0:
|
||||
return &NotFoundError{session.Label}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_d *SessionDeleteOne) ExecX(ctx context.Context) {
|
||||
if err := _d.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
611
examples/migration/ent/session_query.go
Normal file
611
examples/migration/ent/session_query.go
Normal file
@@ -0,0 +1,611 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/predicate"
|
||||
"entgo.io/ent/examples/migration/ent/session"
|
||||
"entgo.io/ent/examples/migration/ent/sessiondevice"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// SessionQuery is the builder for querying Session entities.
|
||||
type SessionQuery struct {
|
||||
config
|
||||
ctx *QueryContext
|
||||
order []session.OrderOption
|
||||
inters []Interceptor
|
||||
predicates []predicate.Session
|
||||
withDevice *SessionDeviceQuery
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
path func(context.Context) (*sql.Selector, error)
|
||||
}
|
||||
|
||||
// Where adds a new predicate for the SessionQuery builder.
|
||||
func (_q *SessionQuery) Where(ps ...predicate.Session) *SessionQuery {
|
||||
_q.predicates = append(_q.predicates, ps...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// Limit the number of records to be returned by this query.
|
||||
func (_q *SessionQuery) Limit(limit int) *SessionQuery {
|
||||
_q.ctx.Limit = &limit
|
||||
return _q
|
||||
}
|
||||
|
||||
// Offset to start from.
|
||||
func (_q *SessionQuery) Offset(offset int) *SessionQuery {
|
||||
_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 *SessionQuery) Unique(unique bool) *SessionQuery {
|
||||
_q.ctx.Unique = &unique
|
||||
return _q
|
||||
}
|
||||
|
||||
// Order specifies how the records should be ordered.
|
||||
func (_q *SessionQuery) Order(o ...session.OrderOption) *SessionQuery {
|
||||
_q.order = append(_q.order, o...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// QueryDevice chains the current query on the "device" edge.
|
||||
func (_q *SessionQuery) QueryDevice() *SessionDeviceQuery {
|
||||
query := (&SessionDeviceClient{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(session.Table, session.FieldID, selector),
|
||||
sqlgraph.To(sessiondevice.Table, sessiondevice.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, session.DeviceTable, session.DeviceColumn),
|
||||
)
|
||||
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
|
||||
return fromU, nil
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// First returns the first Session entity from the query.
|
||||
// Returns a *NotFoundError when no Session was found.
|
||||
func (_q *SessionQuery) First(ctx context.Context) (*Session, 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{session.Label}
|
||||
}
|
||||
return nodes[0], nil
|
||||
}
|
||||
|
||||
// FirstX is like First, but panics if an error occurs.
|
||||
func (_q *SessionQuery) FirstX(ctx context.Context) *Session {
|
||||
node, err := _q.First(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// FirstID returns the first Session ID from the query.
|
||||
// Returns a *NotFoundError when no Session ID was found.
|
||||
func (_q *SessionQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
|
||||
var ids []uuid.UUID
|
||||
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
|
||||
return
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
err = &NotFoundError{session.Label}
|
||||
return
|
||||
}
|
||||
return ids[0], nil
|
||||
}
|
||||
|
||||
// FirstIDX is like FirstID, but panics if an error occurs.
|
||||
func (_q *SessionQuery) FirstIDX(ctx context.Context) uuid.UUID {
|
||||
id, err := _q.FirstID(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Only returns a single Session entity found by the query, ensuring it only returns one.
|
||||
// Returns a *NotSingularError when more than one Session entity is found.
|
||||
// Returns a *NotFoundError when no Session entities are found.
|
||||
func (_q *SessionQuery) Only(ctx context.Context) (*Session, 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{session.Label}
|
||||
default:
|
||||
return nil, &NotSingularError{session.Label}
|
||||
}
|
||||
}
|
||||
|
||||
// OnlyX is like Only, but panics if an error occurs.
|
||||
func (_q *SessionQuery) OnlyX(ctx context.Context) *Session {
|
||||
node, err := _q.Only(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// OnlyID is like Only, but returns the only Session ID in the query.
|
||||
// Returns a *NotSingularError when more than one Session ID is found.
|
||||
// Returns a *NotFoundError when no entities are found.
|
||||
func (_q *SessionQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
|
||||
var ids []uuid.UUID
|
||||
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{session.Label}
|
||||
default:
|
||||
err = &NotSingularError{session.Label}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// OnlyIDX is like OnlyID, but panics if an error occurs.
|
||||
func (_q *SessionQuery) OnlyIDX(ctx context.Context) uuid.UUID {
|
||||
id, err := _q.OnlyID(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// All executes the query and returns a list of Sessions.
|
||||
func (_q *SessionQuery) All(ctx context.Context) ([]*Session, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
|
||||
if err := _q.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qr := querierAll[[]*Session, *SessionQuery]()
|
||||
return withInterceptors[[]*Session](ctx, _q, qr, _q.inters)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
func (_q *SessionQuery) AllX(ctx context.Context) []*Session {
|
||||
nodes, err := _q.All(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
// IDs executes the query and returns a list of Session IDs.
|
||||
func (_q *SessionQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
|
||||
if _q.ctx.Unique == nil && _q.path != nil {
|
||||
_q.Unique(true)
|
||||
}
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
|
||||
if err = _q.Select(session.FieldID).Scan(ctx, &ids); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// IDsX is like IDs, but panics if an error occurs.
|
||||
func (_q *SessionQuery) IDsX(ctx context.Context) []uuid.UUID {
|
||||
ids, err := _q.IDs(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// Count returns the count of the given query.
|
||||
func (_q *SessionQuery) 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[*SessionQuery](), _q.inters)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
func (_q *SessionQuery) 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 *SessionQuery) 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 *SessionQuery) ExistX(ctx context.Context) bool {
|
||||
exist, err := _q.Exist(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return exist
|
||||
}
|
||||
|
||||
// Clone returns a duplicate of the SessionQuery 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 *SessionQuery) Clone() *SessionQuery {
|
||||
if _q == nil {
|
||||
return nil
|
||||
}
|
||||
return &SessionQuery{
|
||||
config: _q.config,
|
||||
ctx: _q.ctx.Clone(),
|
||||
order: append([]session.OrderOption{}, _q.order...),
|
||||
inters: append([]Interceptor{}, _q.inters...),
|
||||
predicates: append([]predicate.Session{}, _q.predicates...),
|
||||
withDevice: _q.withDevice.Clone(),
|
||||
// clone intermediate query.
|
||||
sql: _q.sql.Clone(),
|
||||
path: _q.path,
|
||||
}
|
||||
}
|
||||
|
||||
// WithDevice tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "device" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (_q *SessionQuery) WithDevice(opts ...func(*SessionDeviceQuery)) *SessionQuery {
|
||||
query := (&SessionDeviceClient{config: _q.config}).Query()
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
_q.withDevice = 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 {
|
||||
// Active bool `json:"active,omitempty"`
|
||||
// Count int `json:"count,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.Session.Query().
|
||||
// GroupBy(session.FieldActive).
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *SessionQuery) GroupBy(field string, fields ...string) *SessionGroupBy {
|
||||
_q.ctx.Fields = append([]string{field}, fields...)
|
||||
grbuild := &SessionGroupBy{build: _q}
|
||||
grbuild.flds = &_q.ctx.Fields
|
||||
grbuild.label = session.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 {
|
||||
// Active bool `json:"active,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.Session.Query().
|
||||
// Select(session.FieldActive).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *SessionQuery) Select(fields ...string) *SessionSelect {
|
||||
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
|
||||
sbuild := &SessionSelect{SessionQuery: _q}
|
||||
sbuild.label = session.Label
|
||||
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
|
||||
return sbuild
|
||||
}
|
||||
|
||||
// Aggregate returns a SessionSelect configured with the given aggregations.
|
||||
func (_q *SessionQuery) Aggregate(fns ...AggregateFunc) *SessionSelect {
|
||||
return _q.Select().Aggregate(fns...)
|
||||
}
|
||||
|
||||
func (_q *SessionQuery) 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 !session.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 *SessionQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Session, error) {
|
||||
var (
|
||||
nodes = []*Session{}
|
||||
_spec = _q.querySpec()
|
||||
loadedTypes = [1]bool{
|
||||
_q.withDevice != nil,
|
||||
}
|
||||
)
|
||||
_spec.ScanValues = func(columns []string) ([]any, error) {
|
||||
return (*Session).scanValues(nil, columns)
|
||||
}
|
||||
_spec.Assign = func(columns []string, values []any) error {
|
||||
node := &Session{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.withDevice; query != nil {
|
||||
if err := _q.loadDevice(ctx, query, nodes, nil,
|
||||
func(n *Session, e *SessionDevice) { n.Edges.Device = e }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
func (_q *SessionQuery) loadDevice(ctx context.Context, query *SessionDeviceQuery, nodes []*Session, init func(*Session), assign func(*Session, *SessionDevice)) error {
|
||||
ids := make([]uuid.UUID, 0, len(nodes))
|
||||
nodeids := make(map[uuid.UUID][]*Session)
|
||||
for i := range nodes {
|
||||
fk := nodes[i].DeviceID
|
||||
if _, ok := nodeids[fk]; !ok {
|
||||
ids = append(ids, fk)
|
||||
}
|
||||
nodeids[fk] = append(nodeids[fk], nodes[i])
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
query.Where(sessiondevice.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 "device_id" returned %v`, n.ID)
|
||||
}
|
||||
for i := range nodes {
|
||||
assign(nodes[i], n)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_q *SessionQuery) 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 *SessionQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
_spec := sqlgraph.NewQuerySpec(session.Table, session.Columns, sqlgraph.NewFieldSpec(session.FieldID, field.TypeUUID))
|
||||
_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, session.FieldID)
|
||||
for i := range fields {
|
||||
if fields[i] != session.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
|
||||
}
|
||||
}
|
||||
if _q.withDevice != nil {
|
||||
_spec.Node.AddColumnOnce(session.FieldDeviceID)
|
||||
}
|
||||
}
|
||||
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 *SessionQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
builder := sql.Dialect(_q.driver.Dialect())
|
||||
t1 := builder.Table(session.Table)
|
||||
columns := _q.ctx.Fields
|
||||
if len(columns) == 0 {
|
||||
columns = session.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
|
||||
}
|
||||
|
||||
// SessionGroupBy is the group-by builder for Session entities.
|
||||
type SessionGroupBy struct {
|
||||
selector
|
||||
build *SessionQuery
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the group-by query.
|
||||
func (_g *SessionGroupBy) Aggregate(fns ...AggregateFunc) *SessionGroupBy {
|
||||
_g.fns = append(_g.fns, fns...)
|
||||
return _g
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_g *SessionGroupBy) 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[*SessionQuery, *SessionGroupBy](ctx, _g.build, _g, _g.build.inters, v)
|
||||
}
|
||||
|
||||
func (_g *SessionGroupBy) sqlScan(ctx context.Context, root *SessionQuery, 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)
|
||||
}
|
||||
|
||||
// SessionSelect is the builder for selecting fields of Session entities.
|
||||
type SessionSelect struct {
|
||||
*SessionQuery
|
||||
selector
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the selector query.
|
||||
func (_s *SessionSelect) Aggregate(fns ...AggregateFunc) *SessionSelect {
|
||||
_s.fns = append(_s.fns, fns...)
|
||||
return _s
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_s *SessionSelect) 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[*SessionQuery, *SessionSelect](ctx, _s.SessionQuery, _s, _s.inters, v)
|
||||
}
|
||||
|
||||
func (_s *SessionSelect) sqlScan(ctx context.Context, root *SessionQuery, 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)
|
||||
}
|
||||
510
examples/migration/ent/session_update.go
Normal file
510
examples/migration/ent/session_update.go
Normal file
@@ -0,0 +1,510 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/predicate"
|
||||
"entgo.io/ent/examples/migration/ent/session"
|
||||
"entgo.io/ent/examples/migration/ent/sessiondevice"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// SessionUpdate is the builder for updating Session entities.
|
||||
type SessionUpdate struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *SessionMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the SessionUpdate builder.
|
||||
func (_u *SessionUpdate) Where(ps ...predicate.Session) *SessionUpdate {
|
||||
_u.mutation.Where(ps...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetActive sets the "active" field.
|
||||
func (_u *SessionUpdate) SetActive(v bool) *SessionUpdate {
|
||||
_u.mutation.SetActive(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableActive sets the "active" field if the given value is not nil.
|
||||
func (_u *SessionUpdate) SetNillableActive(v *bool) *SessionUpdate {
|
||||
if v != nil {
|
||||
_u.SetActive(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetIssuedAt sets the "issued_at" field.
|
||||
func (_u *SessionUpdate) SetIssuedAt(v time.Time) *SessionUpdate {
|
||||
_u.mutation.SetIssuedAt(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableIssuedAt sets the "issued_at" field if the given value is not nil.
|
||||
func (_u *SessionUpdate) SetNillableIssuedAt(v *time.Time) *SessionUpdate {
|
||||
if v != nil {
|
||||
_u.SetIssuedAt(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetExpiresAt sets the "expires_at" field.
|
||||
func (_u *SessionUpdate) SetExpiresAt(v time.Time) *SessionUpdate {
|
||||
_u.mutation.SetExpiresAt(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.
|
||||
func (_u *SessionUpdate) SetNillableExpiresAt(v *time.Time) *SessionUpdate {
|
||||
if v != nil {
|
||||
_u.SetExpiresAt(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearExpiresAt clears the value of the "expires_at" field.
|
||||
func (_u *SessionUpdate) ClearExpiresAt() *SessionUpdate {
|
||||
_u.mutation.ClearExpiresAt()
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetToken sets the "token" field.
|
||||
func (_u *SessionUpdate) SetToken(v string) *SessionUpdate {
|
||||
_u.mutation.SetToken(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableToken sets the "token" field if the given value is not nil.
|
||||
func (_u *SessionUpdate) SetNillableToken(v *string) *SessionUpdate {
|
||||
if v != nil {
|
||||
_u.SetToken(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearToken clears the value of the "token" field.
|
||||
func (_u *SessionUpdate) ClearToken() *SessionUpdate {
|
||||
_u.mutation.ClearToken()
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetMethod sets the "method" field.
|
||||
func (_u *SessionUpdate) SetMethod(v map[string]interface{}) *SessionUpdate {
|
||||
_u.mutation.SetMethod(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearMethod clears the value of the "method" field.
|
||||
func (_u *SessionUpdate) ClearMethod() *SessionUpdate {
|
||||
_u.mutation.ClearMethod()
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetDeviceID sets the "device_id" field.
|
||||
func (_u *SessionUpdate) SetDeviceID(v uuid.UUID) *SessionUpdate {
|
||||
_u.mutation.SetDeviceID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableDeviceID sets the "device_id" field if the given value is not nil.
|
||||
func (_u *SessionUpdate) SetNillableDeviceID(v *uuid.UUID) *SessionUpdate {
|
||||
if v != nil {
|
||||
_u.SetDeviceID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearDeviceID clears the value of the "device_id" field.
|
||||
func (_u *SessionUpdate) ClearDeviceID() *SessionUpdate {
|
||||
_u.mutation.ClearDeviceID()
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetDevice sets the "device" edge to the SessionDevice entity.
|
||||
func (_u *SessionUpdate) SetDevice(v *SessionDevice) *SessionUpdate {
|
||||
return _u.SetDeviceID(v.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the SessionMutation object of the builder.
|
||||
func (_u *SessionUpdate) Mutation() *SessionMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// ClearDevice clears the "device" edge to the SessionDevice entity.
|
||||
func (_u *SessionUpdate) ClearDevice() *SessionUpdate {
|
||||
_u.mutation.ClearDevice()
|
||||
return _u
|
||||
}
|
||||
|
||||
// Save executes the query and returns the number of nodes affected by the update operation.
|
||||
func (_u *SessionUpdate) 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 *SessionUpdate) SaveX(ctx context.Context) int {
|
||||
affected, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return affected
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_u *SessionUpdate) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *SessionUpdate) ExecX(ctx context.Context) {
|
||||
if err := _u.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (_u *SessionUpdate) sqlSave(ctx context.Context) (_node int, err error) {
|
||||
_spec := sqlgraph.NewUpdateSpec(session.Table, session.Columns, sqlgraph.NewFieldSpec(session.FieldID, field.TypeUUID))
|
||||
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.Active(); ok {
|
||||
_spec.SetField(session.FieldActive, field.TypeBool, value)
|
||||
}
|
||||
if value, ok := _u.mutation.IssuedAt(); ok {
|
||||
_spec.SetField(session.FieldIssuedAt, field.TypeTime, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ExpiresAt(); ok {
|
||||
_spec.SetField(session.FieldExpiresAt, field.TypeTime, value)
|
||||
}
|
||||
if _u.mutation.ExpiresAtCleared() {
|
||||
_spec.ClearField(session.FieldExpiresAt, field.TypeTime)
|
||||
}
|
||||
if value, ok := _u.mutation.Token(); ok {
|
||||
_spec.SetField(session.FieldToken, field.TypeString, value)
|
||||
}
|
||||
if _u.mutation.TokenCleared() {
|
||||
_spec.ClearField(session.FieldToken, field.TypeString)
|
||||
}
|
||||
if value, ok := _u.mutation.Method(); ok {
|
||||
_spec.SetField(session.FieldMethod, field.TypeJSON, value)
|
||||
}
|
||||
if _u.mutation.MethodCleared() {
|
||||
_spec.ClearField(session.FieldMethod, field.TypeJSON)
|
||||
}
|
||||
if _u.mutation.DeviceCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: session.DeviceTable,
|
||||
Columns: []string{session.DeviceColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(sessiondevice.FieldID, field.TypeUUID),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.DeviceIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: session.DeviceTable,
|
||||
Columns: []string{session.DeviceColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(sessiondevice.FieldID, field.TypeUUID),
|
||||
},
|
||||
}
|
||||
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{session.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
// SessionUpdateOne is the builder for updating a single Session entity.
|
||||
type SessionUpdateOne struct {
|
||||
config
|
||||
fields []string
|
||||
hooks []Hook
|
||||
mutation *SessionMutation
|
||||
}
|
||||
|
||||
// SetActive sets the "active" field.
|
||||
func (_u *SessionUpdateOne) SetActive(v bool) *SessionUpdateOne {
|
||||
_u.mutation.SetActive(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableActive sets the "active" field if the given value is not nil.
|
||||
func (_u *SessionUpdateOne) SetNillableActive(v *bool) *SessionUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetActive(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetIssuedAt sets the "issued_at" field.
|
||||
func (_u *SessionUpdateOne) SetIssuedAt(v time.Time) *SessionUpdateOne {
|
||||
_u.mutation.SetIssuedAt(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableIssuedAt sets the "issued_at" field if the given value is not nil.
|
||||
func (_u *SessionUpdateOne) SetNillableIssuedAt(v *time.Time) *SessionUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetIssuedAt(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetExpiresAt sets the "expires_at" field.
|
||||
func (_u *SessionUpdateOne) SetExpiresAt(v time.Time) *SessionUpdateOne {
|
||||
_u.mutation.SetExpiresAt(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.
|
||||
func (_u *SessionUpdateOne) SetNillableExpiresAt(v *time.Time) *SessionUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetExpiresAt(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearExpiresAt clears the value of the "expires_at" field.
|
||||
func (_u *SessionUpdateOne) ClearExpiresAt() *SessionUpdateOne {
|
||||
_u.mutation.ClearExpiresAt()
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetToken sets the "token" field.
|
||||
func (_u *SessionUpdateOne) SetToken(v string) *SessionUpdateOne {
|
||||
_u.mutation.SetToken(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableToken sets the "token" field if the given value is not nil.
|
||||
func (_u *SessionUpdateOne) SetNillableToken(v *string) *SessionUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetToken(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearToken clears the value of the "token" field.
|
||||
func (_u *SessionUpdateOne) ClearToken() *SessionUpdateOne {
|
||||
_u.mutation.ClearToken()
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetMethod sets the "method" field.
|
||||
func (_u *SessionUpdateOne) SetMethod(v map[string]interface{}) *SessionUpdateOne {
|
||||
_u.mutation.SetMethod(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearMethod clears the value of the "method" field.
|
||||
func (_u *SessionUpdateOne) ClearMethod() *SessionUpdateOne {
|
||||
_u.mutation.ClearMethod()
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetDeviceID sets the "device_id" field.
|
||||
func (_u *SessionUpdateOne) SetDeviceID(v uuid.UUID) *SessionUpdateOne {
|
||||
_u.mutation.SetDeviceID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableDeviceID sets the "device_id" field if the given value is not nil.
|
||||
func (_u *SessionUpdateOne) SetNillableDeviceID(v *uuid.UUID) *SessionUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetDeviceID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearDeviceID clears the value of the "device_id" field.
|
||||
func (_u *SessionUpdateOne) ClearDeviceID() *SessionUpdateOne {
|
||||
_u.mutation.ClearDeviceID()
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetDevice sets the "device" edge to the SessionDevice entity.
|
||||
func (_u *SessionUpdateOne) SetDevice(v *SessionDevice) *SessionUpdateOne {
|
||||
return _u.SetDeviceID(v.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the SessionMutation object of the builder.
|
||||
func (_u *SessionUpdateOne) Mutation() *SessionMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// ClearDevice clears the "device" edge to the SessionDevice entity.
|
||||
func (_u *SessionUpdateOne) ClearDevice() *SessionUpdateOne {
|
||||
_u.mutation.ClearDevice()
|
||||
return _u
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the SessionUpdate builder.
|
||||
func (_u *SessionUpdateOne) Where(ps ...predicate.Session) *SessionUpdateOne {
|
||||
_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 *SessionUpdateOne) Select(field string, fields ...string) *SessionUpdateOne {
|
||||
_u.fields = append([]string{field}, fields...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// Save executes the query and returns the updated Session entity.
|
||||
func (_u *SessionUpdateOne) Save(ctx context.Context) (*Session, error) {
|
||||
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_u *SessionUpdateOne) SaveX(ctx context.Context) *Session {
|
||||
node, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// Exec executes the query on the entity.
|
||||
func (_u *SessionUpdateOne) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *SessionUpdateOne) ExecX(ctx context.Context) {
|
||||
if err := _u.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (_u *SessionUpdateOne) sqlSave(ctx context.Context) (_node *Session, err error) {
|
||||
_spec := sqlgraph.NewUpdateSpec(session.Table, session.Columns, sqlgraph.NewFieldSpec(session.FieldID, field.TypeUUID))
|
||||
id, ok := _u.mutation.ID()
|
||||
if !ok {
|
||||
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Session.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, session.FieldID)
|
||||
for _, f := range fields {
|
||||
if !session.ValidColumn(f) {
|
||||
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
if f != session.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.Active(); ok {
|
||||
_spec.SetField(session.FieldActive, field.TypeBool, value)
|
||||
}
|
||||
if value, ok := _u.mutation.IssuedAt(); ok {
|
||||
_spec.SetField(session.FieldIssuedAt, field.TypeTime, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ExpiresAt(); ok {
|
||||
_spec.SetField(session.FieldExpiresAt, field.TypeTime, value)
|
||||
}
|
||||
if _u.mutation.ExpiresAtCleared() {
|
||||
_spec.ClearField(session.FieldExpiresAt, field.TypeTime)
|
||||
}
|
||||
if value, ok := _u.mutation.Token(); ok {
|
||||
_spec.SetField(session.FieldToken, field.TypeString, value)
|
||||
}
|
||||
if _u.mutation.TokenCleared() {
|
||||
_spec.ClearField(session.FieldToken, field.TypeString)
|
||||
}
|
||||
if value, ok := _u.mutation.Method(); ok {
|
||||
_spec.SetField(session.FieldMethod, field.TypeJSON, value)
|
||||
}
|
||||
if _u.mutation.MethodCleared() {
|
||||
_spec.ClearField(session.FieldMethod, field.TypeJSON)
|
||||
}
|
||||
if _u.mutation.DeviceCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: session.DeviceTable,
|
||||
Columns: []string{session.DeviceColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(sessiondevice.FieldID, field.TypeUUID),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.DeviceIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: session.DeviceTable,
|
||||
Columns: []string{session.DeviceColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(sessiondevice.FieldID, field.TypeUUID),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
_node = &Session{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{session.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
181
examples/migration/ent/sessiondevice.go
Normal file
181
examples/migration/ent/sessiondevice.go
Normal file
@@ -0,0 +1,181 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/examples/migration/ent/sessiondevice"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// SessionDevice is the model entity for the SessionDevice schema.
|
||||
type SessionDevice struct {
|
||||
config `json:"-"`
|
||||
// ID of the ent.
|
||||
ID uuid.UUID `json:"id,omitempty"`
|
||||
// IPAddress holds the value of the "ip_address" field.
|
||||
IPAddress string `json:"ip_address,omitempty"`
|
||||
// UserAgent holds the value of the "user_agent" field.
|
||||
UserAgent string `json:"user_agent,omitempty"`
|
||||
// Location holds the value of the "location" field.
|
||||
Location string `json:"location,omitempty"`
|
||||
// CreatedAt holds the value of the "created_at" field.
|
||||
CreatedAt time.Time `json:"created_at,omitempty"`
|
||||
// UpdatedAt holds the value of the "updated_at" field.
|
||||
UpdatedAt time.Time `json:"updated_at,omitempty"`
|
||||
// Edges holds the relations/edges for other nodes in the graph.
|
||||
// The values are being populated by the SessionDeviceQuery when eager-loading is set.
|
||||
Edges SessionDeviceEdges `json:"edges"`
|
||||
selectValues sql.SelectValues
|
||||
}
|
||||
|
||||
// SessionDeviceEdges holds the relations/edges for other nodes in the graph.
|
||||
type SessionDeviceEdges struct {
|
||||
// Sessions holds the value of the sessions edge.
|
||||
Sessions []*Session `json:"sessions,omitempty"`
|
||||
// loadedTypes holds the information for reporting if a
|
||||
// type was loaded (or requested) in eager-loading or not.
|
||||
loadedTypes [1]bool
|
||||
}
|
||||
|
||||
// SessionsOrErr returns the Sessions value or an error if the edge
|
||||
// was not loaded in eager-loading.
|
||||
func (e SessionDeviceEdges) SessionsOrErr() ([]*Session, error) {
|
||||
if e.loadedTypes[0] {
|
||||
return e.Sessions, nil
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "sessions"}
|
||||
}
|
||||
|
||||
// scanValues returns the types for scanning values from sql.Rows.
|
||||
func (*SessionDevice) scanValues(columns []string) ([]any, error) {
|
||||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case sessiondevice.FieldIPAddress, sessiondevice.FieldUserAgent, sessiondevice.FieldLocation:
|
||||
values[i] = new(sql.NullString)
|
||||
case sessiondevice.FieldCreatedAt, sessiondevice.FieldUpdatedAt:
|
||||
values[i] = new(sql.NullTime)
|
||||
case sessiondevice.FieldID:
|
||||
values[i] = new(uuid.UUID)
|
||||
default:
|
||||
values[i] = new(sql.UnknownType)
|
||||
}
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// assignValues assigns the values that were returned from sql.Rows (after scanning)
|
||||
// to the SessionDevice fields.
|
||||
func (_m *SessionDevice) 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 sessiondevice.FieldID:
|
||||
if value, ok := values[i].(*uuid.UUID); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field id", values[i])
|
||||
} else if value != nil {
|
||||
_m.ID = *value
|
||||
}
|
||||
case sessiondevice.FieldIPAddress:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field ip_address", values[i])
|
||||
} else if value.Valid {
|
||||
_m.IPAddress = value.String
|
||||
}
|
||||
case sessiondevice.FieldUserAgent:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field user_agent", values[i])
|
||||
} else if value.Valid {
|
||||
_m.UserAgent = value.String
|
||||
}
|
||||
case sessiondevice.FieldLocation:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field location", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Location = value.String
|
||||
}
|
||||
case sessiondevice.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 sessiondevice.FieldUpdatedAt:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
|
||||
} else if value.Valid {
|
||||
_m.UpdatedAt = value.Time
|
||||
}
|
||||
default:
|
||||
_m.selectValues.Set(columns[i], values[i])
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Value returns the ent.Value that was dynamically selected and assigned to the SessionDevice.
|
||||
// This includes values selected through modifiers, order, etc.
|
||||
func (_m *SessionDevice) Value(name string) (ent.Value, error) {
|
||||
return _m.selectValues.Get(name)
|
||||
}
|
||||
|
||||
// QuerySessions queries the "sessions" edge of the SessionDevice entity.
|
||||
func (_m *SessionDevice) QuerySessions() *SessionQuery {
|
||||
return NewSessionDeviceClient(_m.config).QuerySessions(_m)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this SessionDevice.
|
||||
// Note that you need to call SessionDevice.Unwrap() before calling this method if this SessionDevice
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (_m *SessionDevice) Update() *SessionDeviceUpdateOne {
|
||||
return NewSessionDeviceClient(_m.config).UpdateOne(_m)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the SessionDevice 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 *SessionDevice) Unwrap() *SessionDevice {
|
||||
_tx, ok := _m.config.driver.(*txDriver)
|
||||
if !ok {
|
||||
panic("ent: SessionDevice is not a transactional entity")
|
||||
}
|
||||
_m.config.driver = _tx.drv
|
||||
return _m
|
||||
}
|
||||
|
||||
// String implements the fmt.Stringer.
|
||||
func (_m *SessionDevice) String() string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("SessionDevice(")
|
||||
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
|
||||
builder.WriteString("ip_address=")
|
||||
builder.WriteString(_m.IPAddress)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("user_agent=")
|
||||
builder.WriteString(_m.UserAgent)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("location=")
|
||||
builder.WriteString(_m.Location)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("created_at=")
|
||||
builder.WriteString(_m.CreatedAt.Format(time.ANSIC))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("updated_at=")
|
||||
builder.WriteString(_m.UpdatedAt.Format(time.ANSIC))
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// SessionDevices is a parsable slice of SessionDevice.
|
||||
type SessionDevices []*SessionDevice
|
||||
490
examples/migration/ent/sessiondevice/mutation.go
Normal file
490
examples/migration/ent/sessiondevice/mutation.go
Normal file
@@ -0,0 +1,490 @@
|
||||
// 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 sessiondevice
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/examples/migration/ent/predicate"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Mutation represents an operation that mutates the SessionDevice nodes in the graph.
|
||||
type Mutation struct {
|
||||
op ent.Op
|
||||
typ string
|
||||
ip_address *string
|
||||
user_agent *string
|
||||
location *string
|
||||
created_at *time.Time
|
||||
updated_at *time.Time
|
||||
clearedFields map[string]struct{}
|
||||
sessions map[uuid.UUID]struct{}
|
||||
removedsessions map[uuid.UUID]struct{}
|
||||
clearedsessions bool
|
||||
predicates []predicate.SessionDevice
|
||||
}
|
||||
|
||||
// NewMutation creates a new Mutation for the SessionDevice entity.
|
||||
func NewMutation(op ent.Op) *Mutation {
|
||||
return &Mutation{
|
||||
op: op,
|
||||
typ: "SessionDevice",
|
||||
clearedFields: make(map[string]struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
// Predicates returns the list of predicates set on the mutation.
|
||||
func (m *Mutation) Predicates() []predicate.SessionDevice {
|
||||
return m.predicates
|
||||
}
|
||||
|
||||
// SetIPAddress sets the "ip_address" field.
|
||||
func (m *Mutation) SetIPAddress(s string) {
|
||||
m.ip_address = &s
|
||||
}
|
||||
|
||||
// IPAddress returns the value of the "ip_address" field in the mutation.
|
||||
func (m *Mutation) IPAddress() (r string, exists bool) {
|
||||
v := m.ip_address
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetIPAddress resets all changes to the "ip_address" field.
|
||||
func (m *Mutation) ResetIPAddress() {
|
||||
m.ip_address = nil
|
||||
}
|
||||
|
||||
// SetUserAgent sets the "user_agent" field.
|
||||
func (m *Mutation) SetUserAgent(s string) {
|
||||
m.user_agent = &s
|
||||
}
|
||||
|
||||
// UserAgent returns the value of the "user_agent" field in the mutation.
|
||||
func (m *Mutation) UserAgent() (r string, exists bool) {
|
||||
v := m.user_agent
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetUserAgent resets all changes to the "user_agent" field.
|
||||
func (m *Mutation) ResetUserAgent() {
|
||||
m.user_agent = nil
|
||||
}
|
||||
|
||||
// SetLocation sets the "location" field.
|
||||
func (m *Mutation) SetLocation(s string) {
|
||||
m.location = &s
|
||||
}
|
||||
|
||||
// Location returns the value of the "location" field in the mutation.
|
||||
func (m *Mutation) Location() (r string, exists bool) {
|
||||
v := m.location
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetLocation resets all changes to the "location" field.
|
||||
func (m *Mutation) ResetLocation() {
|
||||
m.location = nil
|
||||
}
|
||||
|
||||
// SetCreatedAt sets the "created_at" field.
|
||||
func (m *Mutation) SetCreatedAt(t time.Time) {
|
||||
m.created_at = &t
|
||||
}
|
||||
|
||||
// CreatedAt returns the value of the "created_at" field in the mutation.
|
||||
func (m *Mutation) CreatedAt() (r time.Time, exists bool) {
|
||||
v := m.created_at
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetCreatedAt resets all changes to the "created_at" field.
|
||||
func (m *Mutation) ResetCreatedAt() {
|
||||
m.created_at = nil
|
||||
}
|
||||
|
||||
// SetUpdatedAt sets the "updated_at" field.
|
||||
func (m *Mutation) SetUpdatedAt(t time.Time) {
|
||||
m.updated_at = &t
|
||||
}
|
||||
|
||||
// UpdatedAt returns the value of the "updated_at" field in the mutation.
|
||||
func (m *Mutation) UpdatedAt() (r time.Time, exists bool) {
|
||||
v := m.updated_at
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ClearUpdatedAt clears the value of the "updated_at" field.
|
||||
func (m *Mutation) ClearUpdatedAt() {
|
||||
m.updated_at = nil
|
||||
m.clearedFields[FieldUpdatedAt] = struct{}{}
|
||||
}
|
||||
|
||||
// UpdatedAtCleared returns if the "updated_at" field was cleared in this mutation.
|
||||
func (m *Mutation) UpdatedAtCleared() bool {
|
||||
_, ok := m.clearedFields[FieldUpdatedAt]
|
||||
return ok
|
||||
}
|
||||
|
||||
// ResetUpdatedAt resets all changes to the "updated_at" field.
|
||||
func (m *Mutation) ResetUpdatedAt() {
|
||||
m.updated_at = nil
|
||||
delete(m.clearedFields, FieldUpdatedAt)
|
||||
}
|
||||
|
||||
// AddSessionIDs adds the "sessions" edge to the Session entity by ids.
|
||||
func (m *Mutation) AddSessionIDs(ids ...uuid.UUID) {
|
||||
if m.sessions == nil {
|
||||
m.sessions = make(map[uuid.UUID]struct{})
|
||||
}
|
||||
for i := range ids {
|
||||
m.sessions[ids[i]] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
// ClearSessions clears the "sessions" edge to the Session entity.
|
||||
func (m *Mutation) ClearSessions() {
|
||||
m.clearedsessions = true
|
||||
}
|
||||
|
||||
// SessionsCleared reports if the "sessions" edge to the Session entity was cleared.
|
||||
func (m *Mutation) SessionsCleared() bool {
|
||||
return m.clearedsessions
|
||||
}
|
||||
|
||||
// RemoveSessionIDs removes the "sessions" edge to the Session entity by IDs.
|
||||
func (m *Mutation) RemoveSessionIDs(ids ...uuid.UUID) {
|
||||
if m.removedsessions == nil {
|
||||
m.removedsessions = make(map[uuid.UUID]struct{})
|
||||
}
|
||||
for i := range ids {
|
||||
delete(m.sessions, ids[i])
|
||||
m.removedsessions[ids[i]] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
// RemovedSessions returns the removed IDs of the "sessions" edge to the Session entity.
|
||||
func (m *Mutation) RemovedSessionsIDs() (ids []uuid.UUID) {
|
||||
for id := range m.removedsessions {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// SessionsIDs returns the "sessions" edge IDs in the mutation.
|
||||
func (m *Mutation) SessionsIDs() (ids []uuid.UUID) {
|
||||
for id := range m.sessions {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ResetSessions resets all changes to the "sessions" edge.
|
||||
func (m *Mutation) ResetSessions() {
|
||||
m.sessions = nil
|
||||
m.clearedsessions = false
|
||||
m.removedsessions = nil
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the Mutation builder.
|
||||
func (m *Mutation) Where(ps ...predicate.SessionDevice) {
|
||||
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.SessionDevice, 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 (SessionDevice).
|
||||
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.ip_address != nil {
|
||||
fields = append(fields, FieldIPAddress)
|
||||
}
|
||||
if m.user_agent != nil {
|
||||
fields = append(fields, FieldUserAgent)
|
||||
}
|
||||
if m.location != nil {
|
||||
fields = append(fields, FieldLocation)
|
||||
}
|
||||
if m.created_at != nil {
|
||||
fields = append(fields, FieldCreatedAt)
|
||||
}
|
||||
if m.updated_at != nil {
|
||||
fields = append(fields, FieldUpdatedAt)
|
||||
}
|
||||
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 FieldIPAddress:
|
||||
return m.IPAddress()
|
||||
case FieldUserAgent:
|
||||
return m.UserAgent()
|
||||
case FieldLocation:
|
||||
return m.Location()
|
||||
case FieldCreatedAt:
|
||||
return m.CreatedAt()
|
||||
case FieldUpdatedAt:
|
||||
return m.UpdatedAt()
|
||||
}
|
||||
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 SessionDevice 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 FieldIPAddress:
|
||||
v, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetIPAddress(v)
|
||||
return nil
|
||||
case FieldUserAgent:
|
||||
v, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetUserAgent(v)
|
||||
return nil
|
||||
case FieldLocation:
|
||||
v, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetLocation(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 FieldUpdatedAt:
|
||||
v, ok := value.(time.Time)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetUpdatedAt(v)
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown SessionDevice 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 SessionDevice 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(FieldUpdatedAt) {
|
||||
fields = append(fields, FieldUpdatedAt)
|
||||
}
|
||||
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 FieldUpdatedAt:
|
||||
m.ClearUpdatedAt()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown SessionDevice 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 FieldIPAddress:
|
||||
m.ResetIPAddress()
|
||||
return nil
|
||||
case FieldUserAgent:
|
||||
m.ResetUserAgent()
|
||||
return nil
|
||||
case FieldLocation:
|
||||
m.ResetLocation()
|
||||
return nil
|
||||
case FieldCreatedAt:
|
||||
m.ResetCreatedAt()
|
||||
return nil
|
||||
case FieldUpdatedAt:
|
||||
m.ResetUpdatedAt()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown SessionDevice 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.sessions != nil {
|
||||
edges = append(edges, EdgeSessions)
|
||||
}
|
||||
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 EdgeSessions:
|
||||
ids := make([]ent.Value, 0, len(m.sessions))
|
||||
for id := range m.sessions {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemovedEdges returns all edge names that were removed in this mutation.
|
||||
func (m *Mutation) RemovedEdges() []string {
|
||||
edges := make([]string, 0, 1)
|
||||
if m.removedsessions != nil {
|
||||
edges = append(edges, EdgeSessions)
|
||||
}
|
||||
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 EdgeSessions:
|
||||
ids := make([]ent.Value, 0, len(m.removedsessions))
|
||||
for id := range m.removedsessions {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClearedEdges returns all edge names that were cleared in this mutation.
|
||||
func (m *Mutation) ClearedEdges() []string {
|
||||
edges := make([]string, 0, 1)
|
||||
if m.clearedsessions {
|
||||
edges = append(edges, EdgeSessions)
|
||||
}
|
||||
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 EdgeSessions:
|
||||
return m.clearedsessions
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ClearEdge clears the value of the edge with the given name. It returns an error
|
||||
// if that edge is not defined in the schema.
|
||||
func (m *Mutation) ClearEdge(name string) error {
|
||||
switch name {
|
||||
}
|
||||
return fmt.Errorf("unknown SessionDevice 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 EdgeSessions:
|
||||
m.ResetSessions()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown SessionDevice edge %s", name)
|
||||
}
|
||||
126
examples/migration/ent/sessiondevice/sessiondevice.go
Normal file
126
examples/migration/ent/sessiondevice/sessiondevice.go
Normal file
@@ -0,0 +1,126 @@
|
||||
// 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 sessiondevice
|
||||
|
||||
import (
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the sessiondevice type in the database.
|
||||
Label = "session_device"
|
||||
// FieldID holds the string denoting the id field in the database.
|
||||
FieldID = "id"
|
||||
// FieldIPAddress holds the string denoting the ip_address field in the database.
|
||||
FieldIPAddress = "ip_address"
|
||||
// FieldUserAgent holds the string denoting the user_agent field in the database.
|
||||
FieldUserAgent = "user_agent"
|
||||
// FieldLocation holds the string denoting the location field in the database.
|
||||
FieldLocation = "location"
|
||||
// FieldCreatedAt holds the string denoting the created_at field in the database.
|
||||
FieldCreatedAt = "created_at"
|
||||
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
|
||||
FieldUpdatedAt = "updated_at"
|
||||
// EdgeSessions holds the string denoting the sessions edge name in mutations.
|
||||
EdgeSessions = "sessions"
|
||||
// Table holds the table name of the sessiondevice in the database.
|
||||
Table = "session_devices"
|
||||
// SessionsTable is the table that holds the sessions relation/edge.
|
||||
SessionsTable = "sessions"
|
||||
// SessionsInverseTable is the table name for the Session entity.
|
||||
// It exists in this package in order to avoid circular dependency with the "session" package.
|
||||
SessionsInverseTable = "sessions"
|
||||
// SessionsColumn is the table column denoting the sessions relation/edge.
|
||||
SessionsColumn = "device_id"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for sessiondevice fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldIPAddress,
|
||||
FieldUserAgent,
|
||||
FieldLocation,
|
||||
FieldCreatedAt,
|
||||
FieldUpdatedAt,
|
||||
}
|
||||
|
||||
// ValidColumn reports if the column name is valid (part of the table columns).
|
||||
func ValidColumn(column string) bool {
|
||||
for i := range Columns {
|
||||
if column == Columns[i] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var (
|
||||
// IPAddressValidator is a validator for the "ip_address" field. It is called by the builders before save.
|
||||
IPAddressValidator func(string) error
|
||||
// UserAgentValidator is a validator for the "user_agent" field. It is called by the builders before save.
|
||||
UserAgentValidator func(string) error
|
||||
// LocationValidator is a validator for the "location" field. It is called by the builders before save.
|
||||
LocationValidator func(string) error
|
||||
// DefaultID holds the default value on creation for the "id" field.
|
||||
DefaultID func() uuid.UUID
|
||||
)
|
||||
|
||||
// OrderOption defines the ordering options for the SessionDevice 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()
|
||||
}
|
||||
|
||||
// ByIPAddress orders the results by the ip_address field.
|
||||
func ByIPAddress(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldIPAddress, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByUserAgent orders the results by the user_agent field.
|
||||
func ByUserAgent(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldUserAgent, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByLocation orders the results by the location field.
|
||||
func ByLocation(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldLocation, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByCreatedAt orders the results by the created_at field.
|
||||
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByUpdatedAt orders the results by the updated_at field.
|
||||
func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// BySessionsCount orders the results by sessions count.
|
||||
func BySessionsCount(opts ...sql.OrderTermOption) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborsCount(s, newSessionsStep(), opts...)
|
||||
}
|
||||
}
|
||||
|
||||
// BySessions orders the results by sessions terms.
|
||||
func BySessions(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborTerms(s, newSessionsStep(), append([]sql.OrderTerm{term}, terms...)...)
|
||||
}
|
||||
}
|
||||
func newSessionsStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(SessionsInverseTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, SessionsTable, SessionsColumn),
|
||||
)
|
||||
}
|
||||
409
examples/migration/ent/sessiondevice/where.go
Normal file
409
examples/migration/ent/sessiondevice/where.go
Normal file
@@ -0,0 +1,409 @@
|
||||
// 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 sessiondevice
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/predicate"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id uuid.UUID) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id uuid.UUID) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id uuid.UUID) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldNEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...uuid.UUID) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...uuid.UUID) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldNotIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id uuid.UUID) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldGT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id uuid.UUID) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldGTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id uuid.UUID) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldLT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id uuid.UUID) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldLTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IPAddress applies equality check predicate on the "ip_address" field. It's identical to IPAddressEQ.
|
||||
func IPAddress(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldEQ(FieldIPAddress, v))
|
||||
}
|
||||
|
||||
// UserAgent applies equality check predicate on the "user_agent" field. It's identical to UserAgentEQ.
|
||||
func UserAgent(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldEQ(FieldUserAgent, v))
|
||||
}
|
||||
|
||||
// Location applies equality check predicate on the "location" field. It's identical to LocationEQ.
|
||||
func Location(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldEQ(FieldLocation, v))
|
||||
}
|
||||
|
||||
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
|
||||
func CreatedAt(v time.Time) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
|
||||
func UpdatedAt(v time.Time) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldEQ(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// IPAddressEQ applies the EQ predicate on the "ip_address" field.
|
||||
func IPAddressEQ(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldEQ(FieldIPAddress, v))
|
||||
}
|
||||
|
||||
// IPAddressNEQ applies the NEQ predicate on the "ip_address" field.
|
||||
func IPAddressNEQ(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldNEQ(FieldIPAddress, v))
|
||||
}
|
||||
|
||||
// IPAddressIn applies the In predicate on the "ip_address" field.
|
||||
func IPAddressIn(vs ...string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldIn(FieldIPAddress, vs...))
|
||||
}
|
||||
|
||||
// IPAddressNotIn applies the NotIn predicate on the "ip_address" field.
|
||||
func IPAddressNotIn(vs ...string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldNotIn(FieldIPAddress, vs...))
|
||||
}
|
||||
|
||||
// IPAddressGT applies the GT predicate on the "ip_address" field.
|
||||
func IPAddressGT(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldGT(FieldIPAddress, v))
|
||||
}
|
||||
|
||||
// IPAddressGTE applies the GTE predicate on the "ip_address" field.
|
||||
func IPAddressGTE(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldGTE(FieldIPAddress, v))
|
||||
}
|
||||
|
||||
// IPAddressLT applies the LT predicate on the "ip_address" field.
|
||||
func IPAddressLT(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldLT(FieldIPAddress, v))
|
||||
}
|
||||
|
||||
// IPAddressLTE applies the LTE predicate on the "ip_address" field.
|
||||
func IPAddressLTE(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldLTE(FieldIPAddress, v))
|
||||
}
|
||||
|
||||
// IPAddressContains applies the Contains predicate on the "ip_address" field.
|
||||
func IPAddressContains(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldContains(FieldIPAddress, v))
|
||||
}
|
||||
|
||||
// IPAddressHasPrefix applies the HasPrefix predicate on the "ip_address" field.
|
||||
func IPAddressHasPrefix(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldHasPrefix(FieldIPAddress, v))
|
||||
}
|
||||
|
||||
// IPAddressHasSuffix applies the HasSuffix predicate on the "ip_address" field.
|
||||
func IPAddressHasSuffix(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldHasSuffix(FieldIPAddress, v))
|
||||
}
|
||||
|
||||
// IPAddressEqualFold applies the EqualFold predicate on the "ip_address" field.
|
||||
func IPAddressEqualFold(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldEqualFold(FieldIPAddress, v))
|
||||
}
|
||||
|
||||
// IPAddressContainsFold applies the ContainsFold predicate on the "ip_address" field.
|
||||
func IPAddressContainsFold(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldContainsFold(FieldIPAddress, v))
|
||||
}
|
||||
|
||||
// UserAgentEQ applies the EQ predicate on the "user_agent" field.
|
||||
func UserAgentEQ(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldEQ(FieldUserAgent, v))
|
||||
}
|
||||
|
||||
// UserAgentNEQ applies the NEQ predicate on the "user_agent" field.
|
||||
func UserAgentNEQ(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldNEQ(FieldUserAgent, v))
|
||||
}
|
||||
|
||||
// UserAgentIn applies the In predicate on the "user_agent" field.
|
||||
func UserAgentIn(vs ...string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldIn(FieldUserAgent, vs...))
|
||||
}
|
||||
|
||||
// UserAgentNotIn applies the NotIn predicate on the "user_agent" field.
|
||||
func UserAgentNotIn(vs ...string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldNotIn(FieldUserAgent, vs...))
|
||||
}
|
||||
|
||||
// UserAgentGT applies the GT predicate on the "user_agent" field.
|
||||
func UserAgentGT(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldGT(FieldUserAgent, v))
|
||||
}
|
||||
|
||||
// UserAgentGTE applies the GTE predicate on the "user_agent" field.
|
||||
func UserAgentGTE(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldGTE(FieldUserAgent, v))
|
||||
}
|
||||
|
||||
// UserAgentLT applies the LT predicate on the "user_agent" field.
|
||||
func UserAgentLT(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldLT(FieldUserAgent, v))
|
||||
}
|
||||
|
||||
// UserAgentLTE applies the LTE predicate on the "user_agent" field.
|
||||
func UserAgentLTE(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldLTE(FieldUserAgent, v))
|
||||
}
|
||||
|
||||
// UserAgentContains applies the Contains predicate on the "user_agent" field.
|
||||
func UserAgentContains(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldContains(FieldUserAgent, v))
|
||||
}
|
||||
|
||||
// UserAgentHasPrefix applies the HasPrefix predicate on the "user_agent" field.
|
||||
func UserAgentHasPrefix(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldHasPrefix(FieldUserAgent, v))
|
||||
}
|
||||
|
||||
// UserAgentHasSuffix applies the HasSuffix predicate on the "user_agent" field.
|
||||
func UserAgentHasSuffix(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldHasSuffix(FieldUserAgent, v))
|
||||
}
|
||||
|
||||
// UserAgentEqualFold applies the EqualFold predicate on the "user_agent" field.
|
||||
func UserAgentEqualFold(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldEqualFold(FieldUserAgent, v))
|
||||
}
|
||||
|
||||
// UserAgentContainsFold applies the ContainsFold predicate on the "user_agent" field.
|
||||
func UserAgentContainsFold(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldContainsFold(FieldUserAgent, v))
|
||||
}
|
||||
|
||||
// LocationEQ applies the EQ predicate on the "location" field.
|
||||
func LocationEQ(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldEQ(FieldLocation, v))
|
||||
}
|
||||
|
||||
// LocationNEQ applies the NEQ predicate on the "location" field.
|
||||
func LocationNEQ(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldNEQ(FieldLocation, v))
|
||||
}
|
||||
|
||||
// LocationIn applies the In predicate on the "location" field.
|
||||
func LocationIn(vs ...string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldIn(FieldLocation, vs...))
|
||||
}
|
||||
|
||||
// LocationNotIn applies the NotIn predicate on the "location" field.
|
||||
func LocationNotIn(vs ...string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldNotIn(FieldLocation, vs...))
|
||||
}
|
||||
|
||||
// LocationGT applies the GT predicate on the "location" field.
|
||||
func LocationGT(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldGT(FieldLocation, v))
|
||||
}
|
||||
|
||||
// LocationGTE applies the GTE predicate on the "location" field.
|
||||
func LocationGTE(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldGTE(FieldLocation, v))
|
||||
}
|
||||
|
||||
// LocationLT applies the LT predicate on the "location" field.
|
||||
func LocationLT(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldLT(FieldLocation, v))
|
||||
}
|
||||
|
||||
// LocationLTE applies the LTE predicate on the "location" field.
|
||||
func LocationLTE(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldLTE(FieldLocation, v))
|
||||
}
|
||||
|
||||
// LocationContains applies the Contains predicate on the "location" field.
|
||||
func LocationContains(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldContains(FieldLocation, v))
|
||||
}
|
||||
|
||||
// LocationHasPrefix applies the HasPrefix predicate on the "location" field.
|
||||
func LocationHasPrefix(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldHasPrefix(FieldLocation, v))
|
||||
}
|
||||
|
||||
// LocationHasSuffix applies the HasSuffix predicate on the "location" field.
|
||||
func LocationHasSuffix(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldHasSuffix(FieldLocation, v))
|
||||
}
|
||||
|
||||
// LocationEqualFold applies the EqualFold predicate on the "location" field.
|
||||
func LocationEqualFold(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldEqualFold(FieldLocation, v))
|
||||
}
|
||||
|
||||
// LocationContainsFold applies the ContainsFold predicate on the "location" field.
|
||||
func LocationContainsFold(v string) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldContainsFold(FieldLocation, v))
|
||||
}
|
||||
|
||||
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
|
||||
func CreatedAtEQ(v time.Time) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
|
||||
func CreatedAtNEQ(v time.Time) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldNEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtIn applies the In predicate on the "created_at" field.
|
||||
func CreatedAtIn(vs ...time.Time) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldIn(FieldCreatedAt, vs...))
|
||||
}
|
||||
|
||||
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
|
||||
func CreatedAtNotIn(vs ...time.Time) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldNotIn(FieldCreatedAt, vs...))
|
||||
}
|
||||
|
||||
// CreatedAtGT applies the GT predicate on the "created_at" field.
|
||||
func CreatedAtGT(v time.Time) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldGT(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
|
||||
func CreatedAtGTE(v time.Time) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldGTE(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtLT applies the LT predicate on the "created_at" field.
|
||||
func CreatedAtLT(v time.Time) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldLT(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
|
||||
func CreatedAtLTE(v time.Time) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldLTE(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
|
||||
func UpdatedAtEQ(v time.Time) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldEQ(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
|
||||
func UpdatedAtNEQ(v time.Time) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldNEQ(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtIn applies the In predicate on the "updated_at" field.
|
||||
func UpdatedAtIn(vs ...time.Time) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldIn(FieldUpdatedAt, vs...))
|
||||
}
|
||||
|
||||
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
|
||||
func UpdatedAtNotIn(vs ...time.Time) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldNotIn(FieldUpdatedAt, vs...))
|
||||
}
|
||||
|
||||
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
|
||||
func UpdatedAtGT(v time.Time) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldGT(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
|
||||
func UpdatedAtGTE(v time.Time) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldGTE(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
|
||||
func UpdatedAtLT(v time.Time) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldLT(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
|
||||
func UpdatedAtLTE(v time.Time) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldLTE(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtIsNil applies the IsNil predicate on the "updated_at" field.
|
||||
func UpdatedAtIsNil() predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldIsNull(FieldUpdatedAt))
|
||||
}
|
||||
|
||||
// UpdatedAtNotNil applies the NotNil predicate on the "updated_at" field.
|
||||
func UpdatedAtNotNil() predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.FieldNotNull(FieldUpdatedAt))
|
||||
}
|
||||
|
||||
// HasSessions applies the HasEdge predicate on the "sessions" edge.
|
||||
func HasSessions() predicate.SessionDevice {
|
||||
return predicate.SessionDevice(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, SessionsTable, SessionsColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
})
|
||||
}
|
||||
|
||||
// HasSessionsWith applies the HasEdge predicate on the "sessions" edge with a given conditions (other predicates).
|
||||
func HasSessionsWith(preds ...predicate.Session) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(func(s *sql.Selector) {
|
||||
step := newSessionsStep()
|
||||
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.SessionDevice) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.AndPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Or groups predicates with the OR operator between them.
|
||||
func Or(predicates ...predicate.SessionDevice) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.OrPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Not applies the not operator on the given predicate.
|
||||
func Not(p predicate.SessionDevice) predicate.SessionDevice {
|
||||
return predicate.SessionDevice(sql.NotPredicates(p))
|
||||
}
|
||||
322
examples/migration/ent/sessiondevice_create.go
Normal file
322
examples/migration/ent/sessiondevice_create.go
Normal file
@@ -0,0 +1,322 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/session"
|
||||
"entgo.io/ent/examples/migration/ent/sessiondevice"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// SessionDeviceCreate is the builder for creating a SessionDevice entity.
|
||||
type SessionDeviceCreate struct {
|
||||
config
|
||||
mutation *SessionDeviceMutation
|
||||
hooks []Hook
|
||||
}
|
||||
|
||||
// SetIPAddress sets the "ip_address" field.
|
||||
func (_c *SessionDeviceCreate) SetIPAddress(v string) *SessionDeviceCreate {
|
||||
_c.mutation.SetIPAddress(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetUserAgent sets the "user_agent" field.
|
||||
func (_c *SessionDeviceCreate) SetUserAgent(v string) *SessionDeviceCreate {
|
||||
_c.mutation.SetUserAgent(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetLocation sets the "location" field.
|
||||
func (_c *SessionDeviceCreate) SetLocation(v string) *SessionDeviceCreate {
|
||||
_c.mutation.SetLocation(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetCreatedAt sets the "created_at" field.
|
||||
func (_c *SessionDeviceCreate) SetCreatedAt(v time.Time) *SessionDeviceCreate {
|
||||
_c.mutation.SetCreatedAt(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetUpdatedAt sets the "updated_at" field.
|
||||
func (_c *SessionDeviceCreate) SetUpdatedAt(v time.Time) *SessionDeviceCreate {
|
||||
_c.mutation.SetUpdatedAt(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
|
||||
func (_c *SessionDeviceCreate) SetNillableUpdatedAt(v *time.Time) *SessionDeviceCreate {
|
||||
if v != nil {
|
||||
_c.SetUpdatedAt(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetID sets the "id" field.
|
||||
func (_c *SessionDeviceCreate) SetID(v uuid.UUID) *SessionDeviceCreate {
|
||||
_c.mutation.SetID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableID sets the "id" field if the given value is not nil.
|
||||
func (_c *SessionDeviceCreate) SetNillableID(v *uuid.UUID) *SessionDeviceCreate {
|
||||
if v != nil {
|
||||
_c.SetID(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// AddSessionIDs adds the "sessions" edge to the Session entity by IDs.
|
||||
func (_c *SessionDeviceCreate) AddSessionIDs(ids ...uuid.UUID) *SessionDeviceCreate {
|
||||
_c.mutation.AddSessionIDs(ids...)
|
||||
return _c
|
||||
}
|
||||
|
||||
// AddSessions adds the "sessions" edges to the Session entity.
|
||||
func (_c *SessionDeviceCreate) AddSessions(v ...*Session) *SessionDeviceCreate {
|
||||
ids := make([]uuid.UUID, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _c.AddSessionIDs(ids...)
|
||||
}
|
||||
|
||||
// Mutation returns the SessionDeviceMutation object of the builder.
|
||||
func (_c *SessionDeviceCreate) Mutation() *SessionDeviceMutation {
|
||||
return _c.mutation
|
||||
}
|
||||
|
||||
// Save creates the SessionDevice in the database.
|
||||
func (_c *SessionDeviceCreate) Save(ctx context.Context) (*SessionDevice, error) {
|
||||
_c.defaults()
|
||||
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
func (_c *SessionDeviceCreate) SaveX(ctx context.Context) *SessionDevice {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *SessionDeviceCreate) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *SessionDeviceCreate) 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 *SessionDeviceCreate) defaults() {
|
||||
if _, ok := _c.mutation.ID(); !ok {
|
||||
v := sessiondevice.DefaultID()
|
||||
_c.mutation.SetID(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_c *SessionDeviceCreate) check() error {
|
||||
if _, ok := _c.mutation.IPAddress(); !ok {
|
||||
return &ValidationError{Name: "ip_address", err: errors.New(`ent: missing required field "SessionDevice.ip_address"`)}
|
||||
}
|
||||
if v, ok := _c.mutation.IPAddress(); ok {
|
||||
if err := sessiondevice.IPAddressValidator(v); err != nil {
|
||||
return &ValidationError{Name: "ip_address", err: fmt.Errorf(`ent: validator failed for field "SessionDevice.ip_address": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := _c.mutation.UserAgent(); !ok {
|
||||
return &ValidationError{Name: "user_agent", err: errors.New(`ent: missing required field "SessionDevice.user_agent"`)}
|
||||
}
|
||||
if v, ok := _c.mutation.UserAgent(); ok {
|
||||
if err := sessiondevice.UserAgentValidator(v); err != nil {
|
||||
return &ValidationError{Name: "user_agent", err: fmt.Errorf(`ent: validator failed for field "SessionDevice.user_agent": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := _c.mutation.Location(); !ok {
|
||||
return &ValidationError{Name: "location", err: errors.New(`ent: missing required field "SessionDevice.location"`)}
|
||||
}
|
||||
if v, ok := _c.mutation.Location(); ok {
|
||||
if err := sessiondevice.LocationValidator(v); err != nil {
|
||||
return &ValidationError{Name: "location", err: fmt.Errorf(`ent: validator failed for field "SessionDevice.location": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := _c.mutation.CreatedAt(); !ok {
|
||||
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "SessionDevice.created_at"`)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_c *SessionDeviceCreate) sqlSave(ctx context.Context) (*SessionDevice, error) {
|
||||
if err := _c.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_node, _spec := _c.createSpec()
|
||||
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if _spec.ID.Value != nil {
|
||||
if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
|
||||
_node.ID = *id
|
||||
} else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
_c.mutation.id = &_node.ID
|
||||
_c.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
func (_c *SessionDeviceCreate) createSpec() (*SessionDevice, *sqlgraph.CreateSpec) {
|
||||
var (
|
||||
_node = &SessionDevice{config: _c.config}
|
||||
_spec = sqlgraph.NewCreateSpec(sessiondevice.Table, sqlgraph.NewFieldSpec(sessiondevice.FieldID, field.TypeUUID))
|
||||
)
|
||||
if id, ok := _c.mutation.ID(); ok {
|
||||
_node.ID = id
|
||||
_spec.ID.Value = &id
|
||||
}
|
||||
if value, ok := _c.mutation.IPAddress(); ok {
|
||||
_spec.SetField(sessiondevice.FieldIPAddress, field.TypeString, value)
|
||||
_node.IPAddress = value
|
||||
}
|
||||
if value, ok := _c.mutation.UserAgent(); ok {
|
||||
_spec.SetField(sessiondevice.FieldUserAgent, field.TypeString, value)
|
||||
_node.UserAgent = value
|
||||
}
|
||||
if value, ok := _c.mutation.Location(); ok {
|
||||
_spec.SetField(sessiondevice.FieldLocation, field.TypeString, value)
|
||||
_node.Location = value
|
||||
}
|
||||
if value, ok := _c.mutation.CreatedAt(); ok {
|
||||
_spec.SetField(sessiondevice.FieldCreatedAt, field.TypeTime, value)
|
||||
_node.CreatedAt = value
|
||||
}
|
||||
if value, ok := _c.mutation.UpdatedAt(); ok {
|
||||
_spec.SetField(sessiondevice.FieldUpdatedAt, field.TypeTime, value)
|
||||
_node.UpdatedAt = value
|
||||
}
|
||||
if nodes := _c.mutation.SessionsIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: sessiondevice.SessionsTable,
|
||||
Columns: []string{sessiondevice.SessionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(session.FieldID, field.TypeUUID),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
return _node, _spec
|
||||
}
|
||||
|
||||
// SessionDeviceCreateBulk is the builder for creating many SessionDevice entities in bulk.
|
||||
type SessionDeviceCreateBulk struct {
|
||||
config
|
||||
err error
|
||||
builders []*SessionDeviceCreate
|
||||
}
|
||||
|
||||
// Save creates the SessionDevice entities in the database.
|
||||
func (_c *SessionDeviceCreateBulk) Save(ctx context.Context) ([]*SessionDevice, error) {
|
||||
if _c.err != nil {
|
||||
return nil, _c.err
|
||||
}
|
||||
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
|
||||
nodes := make([]*SessionDevice, 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.(*SessionDeviceMutation)
|
||||
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
|
||||
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 *SessionDeviceCreateBulk) SaveX(ctx context.Context) []*SessionDevice {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *SessionDeviceCreateBulk) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *SessionDeviceCreateBulk) ExecX(ctx context.Context) {
|
||||
if err := _c.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
92
examples/migration/ent/sessiondevice_delete.go
Normal file
92
examples/migration/ent/sessiondevice_delete.go
Normal file
@@ -0,0 +1,92 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/predicate"
|
||||
"entgo.io/ent/examples/migration/ent/sessiondevice"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// SessionDeviceDelete is the builder for deleting a SessionDevice entity.
|
||||
type SessionDeviceDelete struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *SessionDeviceMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the SessionDeviceDelete builder.
|
||||
func (_d *SessionDeviceDelete) Where(ps ...predicate.SessionDevice) *SessionDeviceDelete {
|
||||
_d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (_d *SessionDeviceDelete) 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 *SessionDeviceDelete) ExecX(ctx context.Context) int {
|
||||
n, err := _d.Exec(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (_d *SessionDeviceDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
_spec := sqlgraph.NewDeleteSpec(sessiondevice.Table, sqlgraph.NewFieldSpec(sessiondevice.FieldID, field.TypeUUID))
|
||||
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
|
||||
}
|
||||
|
||||
// SessionDeviceDeleteOne is the builder for deleting a single SessionDevice entity.
|
||||
type SessionDeviceDeleteOne struct {
|
||||
_d *SessionDeviceDelete
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the SessionDeviceDelete builder.
|
||||
func (_d *SessionDeviceDeleteOne) Where(ps ...predicate.SessionDevice) *SessionDeviceDeleteOne {
|
||||
_d._d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (_d *SessionDeviceDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := _d._d.Exec(ctx)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case n == 0:
|
||||
return &NotFoundError{sessiondevice.Label}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_d *SessionDeviceDeleteOne) ExecX(ctx context.Context) {
|
||||
if err := _d.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
611
examples/migration/ent/sessiondevice_query.go
Normal file
611
examples/migration/ent/sessiondevice_query.go
Normal file
@@ -0,0 +1,611 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql/driver"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/predicate"
|
||||
"entgo.io/ent/examples/migration/ent/session"
|
||||
"entgo.io/ent/examples/migration/ent/sessiondevice"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// SessionDeviceQuery is the builder for querying SessionDevice entities.
|
||||
type SessionDeviceQuery struct {
|
||||
config
|
||||
ctx *QueryContext
|
||||
order []sessiondevice.OrderOption
|
||||
inters []Interceptor
|
||||
predicates []predicate.SessionDevice
|
||||
withSessions *SessionQuery
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
path func(context.Context) (*sql.Selector, error)
|
||||
}
|
||||
|
||||
// Where adds a new predicate for the SessionDeviceQuery builder.
|
||||
func (_q *SessionDeviceQuery) Where(ps ...predicate.SessionDevice) *SessionDeviceQuery {
|
||||
_q.predicates = append(_q.predicates, ps...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// Limit the number of records to be returned by this query.
|
||||
func (_q *SessionDeviceQuery) Limit(limit int) *SessionDeviceQuery {
|
||||
_q.ctx.Limit = &limit
|
||||
return _q
|
||||
}
|
||||
|
||||
// Offset to start from.
|
||||
func (_q *SessionDeviceQuery) Offset(offset int) *SessionDeviceQuery {
|
||||
_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 *SessionDeviceQuery) Unique(unique bool) *SessionDeviceQuery {
|
||||
_q.ctx.Unique = &unique
|
||||
return _q
|
||||
}
|
||||
|
||||
// Order specifies how the records should be ordered.
|
||||
func (_q *SessionDeviceQuery) Order(o ...sessiondevice.OrderOption) *SessionDeviceQuery {
|
||||
_q.order = append(_q.order, o...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// QuerySessions chains the current query on the "sessions" edge.
|
||||
func (_q *SessionDeviceQuery) QuerySessions() *SessionQuery {
|
||||
query := (&SessionClient{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(sessiondevice.Table, sessiondevice.FieldID, selector),
|
||||
sqlgraph.To(session.Table, session.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, sessiondevice.SessionsTable, sessiondevice.SessionsColumn),
|
||||
)
|
||||
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
|
||||
return fromU, nil
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// First returns the first SessionDevice entity from the query.
|
||||
// Returns a *NotFoundError when no SessionDevice was found.
|
||||
func (_q *SessionDeviceQuery) First(ctx context.Context) (*SessionDevice, 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{sessiondevice.Label}
|
||||
}
|
||||
return nodes[0], nil
|
||||
}
|
||||
|
||||
// FirstX is like First, but panics if an error occurs.
|
||||
func (_q *SessionDeviceQuery) FirstX(ctx context.Context) *SessionDevice {
|
||||
node, err := _q.First(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// FirstID returns the first SessionDevice ID from the query.
|
||||
// Returns a *NotFoundError when no SessionDevice ID was found.
|
||||
func (_q *SessionDeviceQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
|
||||
var ids []uuid.UUID
|
||||
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
|
||||
return
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
err = &NotFoundError{sessiondevice.Label}
|
||||
return
|
||||
}
|
||||
return ids[0], nil
|
||||
}
|
||||
|
||||
// FirstIDX is like FirstID, but panics if an error occurs.
|
||||
func (_q *SessionDeviceQuery) FirstIDX(ctx context.Context) uuid.UUID {
|
||||
id, err := _q.FirstID(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Only returns a single SessionDevice entity found by the query, ensuring it only returns one.
|
||||
// Returns a *NotSingularError when more than one SessionDevice entity is found.
|
||||
// Returns a *NotFoundError when no SessionDevice entities are found.
|
||||
func (_q *SessionDeviceQuery) Only(ctx context.Context) (*SessionDevice, 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{sessiondevice.Label}
|
||||
default:
|
||||
return nil, &NotSingularError{sessiondevice.Label}
|
||||
}
|
||||
}
|
||||
|
||||
// OnlyX is like Only, but panics if an error occurs.
|
||||
func (_q *SessionDeviceQuery) OnlyX(ctx context.Context) *SessionDevice {
|
||||
node, err := _q.Only(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// OnlyID is like Only, but returns the only SessionDevice ID in the query.
|
||||
// Returns a *NotSingularError when more than one SessionDevice ID is found.
|
||||
// Returns a *NotFoundError when no entities are found.
|
||||
func (_q *SessionDeviceQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
|
||||
var ids []uuid.UUID
|
||||
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{sessiondevice.Label}
|
||||
default:
|
||||
err = &NotSingularError{sessiondevice.Label}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// OnlyIDX is like OnlyID, but panics if an error occurs.
|
||||
func (_q *SessionDeviceQuery) OnlyIDX(ctx context.Context) uuid.UUID {
|
||||
id, err := _q.OnlyID(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// All executes the query and returns a list of SessionDevices.
|
||||
func (_q *SessionDeviceQuery) All(ctx context.Context) ([]*SessionDevice, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
|
||||
if err := _q.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qr := querierAll[[]*SessionDevice, *SessionDeviceQuery]()
|
||||
return withInterceptors[[]*SessionDevice](ctx, _q, qr, _q.inters)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
func (_q *SessionDeviceQuery) AllX(ctx context.Context) []*SessionDevice {
|
||||
nodes, err := _q.All(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
// IDs executes the query and returns a list of SessionDevice IDs.
|
||||
func (_q *SessionDeviceQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
|
||||
if _q.ctx.Unique == nil && _q.path != nil {
|
||||
_q.Unique(true)
|
||||
}
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
|
||||
if err = _q.Select(sessiondevice.FieldID).Scan(ctx, &ids); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// IDsX is like IDs, but panics if an error occurs.
|
||||
func (_q *SessionDeviceQuery) IDsX(ctx context.Context) []uuid.UUID {
|
||||
ids, err := _q.IDs(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// Count returns the count of the given query.
|
||||
func (_q *SessionDeviceQuery) 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[*SessionDeviceQuery](), _q.inters)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
func (_q *SessionDeviceQuery) 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 *SessionDeviceQuery) 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 *SessionDeviceQuery) ExistX(ctx context.Context) bool {
|
||||
exist, err := _q.Exist(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return exist
|
||||
}
|
||||
|
||||
// Clone returns a duplicate of the SessionDeviceQuery 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 *SessionDeviceQuery) Clone() *SessionDeviceQuery {
|
||||
if _q == nil {
|
||||
return nil
|
||||
}
|
||||
return &SessionDeviceQuery{
|
||||
config: _q.config,
|
||||
ctx: _q.ctx.Clone(),
|
||||
order: append([]sessiondevice.OrderOption{}, _q.order...),
|
||||
inters: append([]Interceptor{}, _q.inters...),
|
||||
predicates: append([]predicate.SessionDevice{}, _q.predicates...),
|
||||
withSessions: _q.withSessions.Clone(),
|
||||
// clone intermediate query.
|
||||
sql: _q.sql.Clone(),
|
||||
path: _q.path,
|
||||
}
|
||||
}
|
||||
|
||||
// WithSessions tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "sessions" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (_q *SessionDeviceQuery) WithSessions(opts ...func(*SessionQuery)) *SessionDeviceQuery {
|
||||
query := (&SessionClient{config: _q.config}).Query()
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
_q.withSessions = 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 {
|
||||
// IPAddress string `json:"ip_address,omitempty"`
|
||||
// Count int `json:"count,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.SessionDevice.Query().
|
||||
// GroupBy(sessiondevice.FieldIPAddress).
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *SessionDeviceQuery) GroupBy(field string, fields ...string) *SessionDeviceGroupBy {
|
||||
_q.ctx.Fields = append([]string{field}, fields...)
|
||||
grbuild := &SessionDeviceGroupBy{build: _q}
|
||||
grbuild.flds = &_q.ctx.Fields
|
||||
grbuild.label = sessiondevice.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 {
|
||||
// IPAddress string `json:"ip_address,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.SessionDevice.Query().
|
||||
// Select(sessiondevice.FieldIPAddress).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *SessionDeviceQuery) Select(fields ...string) *SessionDeviceSelect {
|
||||
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
|
||||
sbuild := &SessionDeviceSelect{SessionDeviceQuery: _q}
|
||||
sbuild.label = sessiondevice.Label
|
||||
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
|
||||
return sbuild
|
||||
}
|
||||
|
||||
// Aggregate returns a SessionDeviceSelect configured with the given aggregations.
|
||||
func (_q *SessionDeviceQuery) Aggregate(fns ...AggregateFunc) *SessionDeviceSelect {
|
||||
return _q.Select().Aggregate(fns...)
|
||||
}
|
||||
|
||||
func (_q *SessionDeviceQuery) 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 !sessiondevice.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 *SessionDeviceQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*SessionDevice, error) {
|
||||
var (
|
||||
nodes = []*SessionDevice{}
|
||||
_spec = _q.querySpec()
|
||||
loadedTypes = [1]bool{
|
||||
_q.withSessions != nil,
|
||||
}
|
||||
)
|
||||
_spec.ScanValues = func(columns []string) ([]any, error) {
|
||||
return (*SessionDevice).scanValues(nil, columns)
|
||||
}
|
||||
_spec.Assign = func(columns []string, values []any) error {
|
||||
node := &SessionDevice{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.withSessions; query != nil {
|
||||
if err := _q.loadSessions(ctx, query, nodes,
|
||||
func(n *SessionDevice) { n.Edges.Sessions = []*Session{} },
|
||||
func(n *SessionDevice, e *Session) { n.Edges.Sessions = append(n.Edges.Sessions, e) }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
func (_q *SessionDeviceQuery) loadSessions(ctx context.Context, query *SessionQuery, nodes []*SessionDevice, init func(*SessionDevice), assign func(*SessionDevice, *Session)) error {
|
||||
fks := make([]driver.Value, 0, len(nodes))
|
||||
nodeids := make(map[uuid.UUID]*SessionDevice)
|
||||
for i := range nodes {
|
||||
fks = append(fks, nodes[i].ID)
|
||||
nodeids[nodes[i].ID] = nodes[i]
|
||||
if init != nil {
|
||||
init(nodes[i])
|
||||
}
|
||||
}
|
||||
if len(query.ctx.Fields) > 0 {
|
||||
query.ctx.AppendFieldOnce(session.FieldDeviceID)
|
||||
}
|
||||
query.Where(predicate.Session(func(s *sql.Selector) {
|
||||
s.Where(sql.InValues(s.C(sessiondevice.SessionsColumn), fks...))
|
||||
}))
|
||||
neighbors, err := query.All(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, n := range neighbors {
|
||||
fk := n.DeviceID
|
||||
node, ok := nodeids[fk]
|
||||
if !ok {
|
||||
return fmt.Errorf(`unexpected referenced foreign-key "device_id" returned %v for node %v`, fk, n.ID)
|
||||
}
|
||||
assign(node, n)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_q *SessionDeviceQuery) 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 *SessionDeviceQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
_spec := sqlgraph.NewQuerySpec(sessiondevice.Table, sessiondevice.Columns, sqlgraph.NewFieldSpec(sessiondevice.FieldID, field.TypeUUID))
|
||||
_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, sessiondevice.FieldID)
|
||||
for i := range fields {
|
||||
if fields[i] != sessiondevice.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 *SessionDeviceQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
builder := sql.Dialect(_q.driver.Dialect())
|
||||
t1 := builder.Table(sessiondevice.Table)
|
||||
columns := _q.ctx.Fields
|
||||
if len(columns) == 0 {
|
||||
columns = sessiondevice.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
|
||||
}
|
||||
|
||||
// SessionDeviceGroupBy is the group-by builder for SessionDevice entities.
|
||||
type SessionDeviceGroupBy struct {
|
||||
selector
|
||||
build *SessionDeviceQuery
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the group-by query.
|
||||
func (_g *SessionDeviceGroupBy) Aggregate(fns ...AggregateFunc) *SessionDeviceGroupBy {
|
||||
_g.fns = append(_g.fns, fns...)
|
||||
return _g
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_g *SessionDeviceGroupBy) 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[*SessionDeviceQuery, *SessionDeviceGroupBy](ctx, _g.build, _g, _g.build.inters, v)
|
||||
}
|
||||
|
||||
func (_g *SessionDeviceGroupBy) sqlScan(ctx context.Context, root *SessionDeviceQuery, 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)
|
||||
}
|
||||
|
||||
// SessionDeviceSelect is the builder for selecting fields of SessionDevice entities.
|
||||
type SessionDeviceSelect struct {
|
||||
*SessionDeviceQuery
|
||||
selector
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the selector query.
|
||||
func (_s *SessionDeviceSelect) Aggregate(fns ...AggregateFunc) *SessionDeviceSelect {
|
||||
_s.fns = append(_s.fns, fns...)
|
||||
return _s
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_s *SessionDeviceSelect) 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[*SessionDeviceQuery, *SessionDeviceSelect](ctx, _s.SessionDeviceQuery, _s, _s.inters, v)
|
||||
}
|
||||
|
||||
func (_s *SessionDeviceSelect) sqlScan(ctx context.Context, root *SessionDeviceQuery, 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)
|
||||
}
|
||||
578
examples/migration/ent/sessiondevice_update.go
Normal file
578
examples/migration/ent/sessiondevice_update.go
Normal file
@@ -0,0 +1,578 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/predicate"
|
||||
"entgo.io/ent/examples/migration/ent/session"
|
||||
"entgo.io/ent/examples/migration/ent/sessiondevice"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// SessionDeviceUpdate is the builder for updating SessionDevice entities.
|
||||
type SessionDeviceUpdate struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *SessionDeviceMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the SessionDeviceUpdate builder.
|
||||
func (_u *SessionDeviceUpdate) Where(ps ...predicate.SessionDevice) *SessionDeviceUpdate {
|
||||
_u.mutation.Where(ps...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetIPAddress sets the "ip_address" field.
|
||||
func (_u *SessionDeviceUpdate) SetIPAddress(v string) *SessionDeviceUpdate {
|
||||
_u.mutation.SetIPAddress(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableIPAddress sets the "ip_address" field if the given value is not nil.
|
||||
func (_u *SessionDeviceUpdate) SetNillableIPAddress(v *string) *SessionDeviceUpdate {
|
||||
if v != nil {
|
||||
_u.SetIPAddress(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetUserAgent sets the "user_agent" field.
|
||||
func (_u *SessionDeviceUpdate) SetUserAgent(v string) *SessionDeviceUpdate {
|
||||
_u.mutation.SetUserAgent(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableUserAgent sets the "user_agent" field if the given value is not nil.
|
||||
func (_u *SessionDeviceUpdate) SetNillableUserAgent(v *string) *SessionDeviceUpdate {
|
||||
if v != nil {
|
||||
_u.SetUserAgent(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetLocation sets the "location" field.
|
||||
func (_u *SessionDeviceUpdate) SetLocation(v string) *SessionDeviceUpdate {
|
||||
_u.mutation.SetLocation(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableLocation sets the "location" field if the given value is not nil.
|
||||
func (_u *SessionDeviceUpdate) SetNillableLocation(v *string) *SessionDeviceUpdate {
|
||||
if v != nil {
|
||||
_u.SetLocation(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetCreatedAt sets the "created_at" field.
|
||||
func (_u *SessionDeviceUpdate) SetCreatedAt(v time.Time) *SessionDeviceUpdate {
|
||||
_u.mutation.SetCreatedAt(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
|
||||
func (_u *SessionDeviceUpdate) SetNillableCreatedAt(v *time.Time) *SessionDeviceUpdate {
|
||||
if v != nil {
|
||||
_u.SetCreatedAt(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetUpdatedAt sets the "updated_at" field.
|
||||
func (_u *SessionDeviceUpdate) SetUpdatedAt(v time.Time) *SessionDeviceUpdate {
|
||||
_u.mutation.SetUpdatedAt(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
|
||||
func (_u *SessionDeviceUpdate) SetNillableUpdatedAt(v *time.Time) *SessionDeviceUpdate {
|
||||
if v != nil {
|
||||
_u.SetUpdatedAt(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearUpdatedAt clears the value of the "updated_at" field.
|
||||
func (_u *SessionDeviceUpdate) ClearUpdatedAt() *SessionDeviceUpdate {
|
||||
_u.mutation.ClearUpdatedAt()
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddSessionIDs adds the "sessions" edge to the Session entity by IDs.
|
||||
func (_u *SessionDeviceUpdate) AddSessionIDs(ids ...uuid.UUID) *SessionDeviceUpdate {
|
||||
_u.mutation.AddSessionIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddSessions adds the "sessions" edges to the Session entity.
|
||||
func (_u *SessionDeviceUpdate) AddSessions(v ...*Session) *SessionDeviceUpdate {
|
||||
ids := make([]uuid.UUID, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.AddSessionIDs(ids...)
|
||||
}
|
||||
|
||||
// Mutation returns the SessionDeviceMutation object of the builder.
|
||||
func (_u *SessionDeviceUpdate) Mutation() *SessionDeviceMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// ClearSessions clears all "sessions" edges to the Session entity.
|
||||
func (_u *SessionDeviceUpdate) ClearSessions() *SessionDeviceUpdate {
|
||||
_u.mutation.ClearSessions()
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveSessionIDs removes the "sessions" edge to Session entities by IDs.
|
||||
func (_u *SessionDeviceUpdate) RemoveSessionIDs(ids ...uuid.UUID) *SessionDeviceUpdate {
|
||||
_u.mutation.RemoveSessionIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveSessions removes "sessions" edges to Session entities.
|
||||
func (_u *SessionDeviceUpdate) RemoveSessions(v ...*Session) *SessionDeviceUpdate {
|
||||
ids := make([]uuid.UUID, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.RemoveSessionIDs(ids...)
|
||||
}
|
||||
|
||||
// Save executes the query and returns the number of nodes affected by the update operation.
|
||||
func (_u *SessionDeviceUpdate) 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 *SessionDeviceUpdate) SaveX(ctx context.Context) int {
|
||||
affected, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return affected
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_u *SessionDeviceUpdate) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *SessionDeviceUpdate) ExecX(ctx context.Context) {
|
||||
if err := _u.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *SessionDeviceUpdate) check() error {
|
||||
if v, ok := _u.mutation.IPAddress(); ok {
|
||||
if err := sessiondevice.IPAddressValidator(v); err != nil {
|
||||
return &ValidationError{Name: "ip_address", err: fmt.Errorf(`ent: validator failed for field "SessionDevice.ip_address": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.UserAgent(); ok {
|
||||
if err := sessiondevice.UserAgentValidator(v); err != nil {
|
||||
return &ValidationError{Name: "user_agent", err: fmt.Errorf(`ent: validator failed for field "SessionDevice.user_agent": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.Location(); ok {
|
||||
if err := sessiondevice.LocationValidator(v); err != nil {
|
||||
return &ValidationError{Name: "location", err: fmt.Errorf(`ent: validator failed for field "SessionDevice.location": %w`, err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *SessionDeviceUpdate) sqlSave(ctx context.Context) (_node int, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(sessiondevice.Table, sessiondevice.Columns, sqlgraph.NewFieldSpec(sessiondevice.FieldID, field.TypeUUID))
|
||||
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.IPAddress(); ok {
|
||||
_spec.SetField(sessiondevice.FieldIPAddress, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.UserAgent(); ok {
|
||||
_spec.SetField(sessiondevice.FieldUserAgent, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Location(); ok {
|
||||
_spec.SetField(sessiondevice.FieldLocation, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.CreatedAt(); ok {
|
||||
_spec.SetField(sessiondevice.FieldCreatedAt, field.TypeTime, value)
|
||||
}
|
||||
if value, ok := _u.mutation.UpdatedAt(); ok {
|
||||
_spec.SetField(sessiondevice.FieldUpdatedAt, field.TypeTime, value)
|
||||
}
|
||||
if _u.mutation.UpdatedAtCleared() {
|
||||
_spec.ClearField(sessiondevice.FieldUpdatedAt, field.TypeTime)
|
||||
}
|
||||
if _u.mutation.SessionsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: sessiondevice.SessionsTable,
|
||||
Columns: []string{sessiondevice.SessionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(session.FieldID, field.TypeUUID),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.RemovedSessionsIDs(); len(nodes) > 0 && !_u.mutation.SessionsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: sessiondevice.SessionsTable,
|
||||
Columns: []string{sessiondevice.SessionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(session.FieldID, field.TypeUUID),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.SessionsIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: sessiondevice.SessionsTable,
|
||||
Columns: []string{sessiondevice.SessionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(session.FieldID, field.TypeUUID),
|
||||
},
|
||||
}
|
||||
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{sessiondevice.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
// SessionDeviceUpdateOne is the builder for updating a single SessionDevice entity.
|
||||
type SessionDeviceUpdateOne struct {
|
||||
config
|
||||
fields []string
|
||||
hooks []Hook
|
||||
mutation *SessionDeviceMutation
|
||||
}
|
||||
|
||||
// SetIPAddress sets the "ip_address" field.
|
||||
func (_u *SessionDeviceUpdateOne) SetIPAddress(v string) *SessionDeviceUpdateOne {
|
||||
_u.mutation.SetIPAddress(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableIPAddress sets the "ip_address" field if the given value is not nil.
|
||||
func (_u *SessionDeviceUpdateOne) SetNillableIPAddress(v *string) *SessionDeviceUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetIPAddress(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetUserAgent sets the "user_agent" field.
|
||||
func (_u *SessionDeviceUpdateOne) SetUserAgent(v string) *SessionDeviceUpdateOne {
|
||||
_u.mutation.SetUserAgent(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableUserAgent sets the "user_agent" field if the given value is not nil.
|
||||
func (_u *SessionDeviceUpdateOne) SetNillableUserAgent(v *string) *SessionDeviceUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetUserAgent(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetLocation sets the "location" field.
|
||||
func (_u *SessionDeviceUpdateOne) SetLocation(v string) *SessionDeviceUpdateOne {
|
||||
_u.mutation.SetLocation(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableLocation sets the "location" field if the given value is not nil.
|
||||
func (_u *SessionDeviceUpdateOne) SetNillableLocation(v *string) *SessionDeviceUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetLocation(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetCreatedAt sets the "created_at" field.
|
||||
func (_u *SessionDeviceUpdateOne) SetCreatedAt(v time.Time) *SessionDeviceUpdateOne {
|
||||
_u.mutation.SetCreatedAt(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
|
||||
func (_u *SessionDeviceUpdateOne) SetNillableCreatedAt(v *time.Time) *SessionDeviceUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetCreatedAt(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetUpdatedAt sets the "updated_at" field.
|
||||
func (_u *SessionDeviceUpdateOne) SetUpdatedAt(v time.Time) *SessionDeviceUpdateOne {
|
||||
_u.mutation.SetUpdatedAt(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
|
||||
func (_u *SessionDeviceUpdateOne) SetNillableUpdatedAt(v *time.Time) *SessionDeviceUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetUpdatedAt(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearUpdatedAt clears the value of the "updated_at" field.
|
||||
func (_u *SessionDeviceUpdateOne) ClearUpdatedAt() *SessionDeviceUpdateOne {
|
||||
_u.mutation.ClearUpdatedAt()
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddSessionIDs adds the "sessions" edge to the Session entity by IDs.
|
||||
func (_u *SessionDeviceUpdateOne) AddSessionIDs(ids ...uuid.UUID) *SessionDeviceUpdateOne {
|
||||
_u.mutation.AddSessionIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddSessions adds the "sessions" edges to the Session entity.
|
||||
func (_u *SessionDeviceUpdateOne) AddSessions(v ...*Session) *SessionDeviceUpdateOne {
|
||||
ids := make([]uuid.UUID, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.AddSessionIDs(ids...)
|
||||
}
|
||||
|
||||
// Mutation returns the SessionDeviceMutation object of the builder.
|
||||
func (_u *SessionDeviceUpdateOne) Mutation() *SessionDeviceMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// ClearSessions clears all "sessions" edges to the Session entity.
|
||||
func (_u *SessionDeviceUpdateOne) ClearSessions() *SessionDeviceUpdateOne {
|
||||
_u.mutation.ClearSessions()
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveSessionIDs removes the "sessions" edge to Session entities by IDs.
|
||||
func (_u *SessionDeviceUpdateOne) RemoveSessionIDs(ids ...uuid.UUID) *SessionDeviceUpdateOne {
|
||||
_u.mutation.RemoveSessionIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveSessions removes "sessions" edges to Session entities.
|
||||
func (_u *SessionDeviceUpdateOne) RemoveSessions(v ...*Session) *SessionDeviceUpdateOne {
|
||||
ids := make([]uuid.UUID, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.RemoveSessionIDs(ids...)
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the SessionDeviceUpdate builder.
|
||||
func (_u *SessionDeviceUpdateOne) Where(ps ...predicate.SessionDevice) *SessionDeviceUpdateOne {
|
||||
_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 *SessionDeviceUpdateOne) Select(field string, fields ...string) *SessionDeviceUpdateOne {
|
||||
_u.fields = append([]string{field}, fields...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// Save executes the query and returns the updated SessionDevice entity.
|
||||
func (_u *SessionDeviceUpdateOne) Save(ctx context.Context) (*SessionDevice, error) {
|
||||
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_u *SessionDeviceUpdateOne) SaveX(ctx context.Context) *SessionDevice {
|
||||
node, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// Exec executes the query on the entity.
|
||||
func (_u *SessionDeviceUpdateOne) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *SessionDeviceUpdateOne) ExecX(ctx context.Context) {
|
||||
if err := _u.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *SessionDeviceUpdateOne) check() error {
|
||||
if v, ok := _u.mutation.IPAddress(); ok {
|
||||
if err := sessiondevice.IPAddressValidator(v); err != nil {
|
||||
return &ValidationError{Name: "ip_address", err: fmt.Errorf(`ent: validator failed for field "SessionDevice.ip_address": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.UserAgent(); ok {
|
||||
if err := sessiondevice.UserAgentValidator(v); err != nil {
|
||||
return &ValidationError{Name: "user_agent", err: fmt.Errorf(`ent: validator failed for field "SessionDevice.user_agent": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.Location(); ok {
|
||||
if err := sessiondevice.LocationValidator(v); err != nil {
|
||||
return &ValidationError{Name: "location", err: fmt.Errorf(`ent: validator failed for field "SessionDevice.location": %w`, err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *SessionDeviceUpdateOne) sqlSave(ctx context.Context) (_node *SessionDevice, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(sessiondevice.Table, sessiondevice.Columns, sqlgraph.NewFieldSpec(sessiondevice.FieldID, field.TypeUUID))
|
||||
id, ok := _u.mutation.ID()
|
||||
if !ok {
|
||||
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "SessionDevice.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, sessiondevice.FieldID)
|
||||
for _, f := range fields {
|
||||
if !sessiondevice.ValidColumn(f) {
|
||||
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
if f != sessiondevice.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.IPAddress(); ok {
|
||||
_spec.SetField(sessiondevice.FieldIPAddress, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.UserAgent(); ok {
|
||||
_spec.SetField(sessiondevice.FieldUserAgent, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Location(); ok {
|
||||
_spec.SetField(sessiondevice.FieldLocation, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.CreatedAt(); ok {
|
||||
_spec.SetField(sessiondevice.FieldCreatedAt, field.TypeTime, value)
|
||||
}
|
||||
if value, ok := _u.mutation.UpdatedAt(); ok {
|
||||
_spec.SetField(sessiondevice.FieldUpdatedAt, field.TypeTime, value)
|
||||
}
|
||||
if _u.mutation.UpdatedAtCleared() {
|
||||
_spec.ClearField(sessiondevice.FieldUpdatedAt, field.TypeTime)
|
||||
}
|
||||
if _u.mutation.SessionsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: sessiondevice.SessionsTable,
|
||||
Columns: []string{sessiondevice.SessionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(session.FieldID, field.TypeUUID),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.RemovedSessionsIDs(); len(nodes) > 0 && !_u.mutation.SessionsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: sessiondevice.SessionsTable,
|
||||
Columns: []string{sessiondevice.SessionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(session.FieldID, field.TypeUUID),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.SessionsIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: sessiondevice.SessionsTable,
|
||||
Columns: []string{sessiondevice.SessionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(session.FieldID, field.TypeUUID),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
_node = &SessionDevice{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{sessiondevice.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
229
examples/migration/ent/tx.go
Normal file
229
examples/migration/ent/tx.go
Normal file
@@ -0,0 +1,229 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"entgo.io/ent/dialect"
|
||||
)
|
||||
|
||||
// Tx is a transactional client that is created by calling Client.Tx().
|
||||
type Tx struct {
|
||||
config
|
||||
// Card is the client for interacting with the Card builders.
|
||||
Card *CardClient
|
||||
// Payment is the client for interacting with the Payment builders.
|
||||
Payment *PaymentClient
|
||||
// Pet is the client for interacting with the Pet builders.
|
||||
Pet *PetClient
|
||||
// Session is the client for interacting with the Session builders.
|
||||
Session *SessionClient
|
||||
// SessionDevice is the client for interacting with the SessionDevice builders.
|
||||
SessionDevice *SessionDeviceClient
|
||||
// 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.Payment = NewPaymentClient(tx.config)
|
||||
tx.Pet = NewPetClient(tx.config)
|
||||
tx.Session = NewSessionClient(tx.config)
|
||||
tx.SessionDevice = NewSessionDeviceClient(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)
|
||||
173
examples/migration/ent/user.go
Normal file
173
examples/migration/ent/user.go
Normal file
@@ -0,0 +1,173 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/examples/migration/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"`
|
||||
// Age holds the value of the "age" field.
|
||||
Age float64 `json:"age,omitempty"`
|
||||
// FirstName holds the value of the "first_name" field.
|
||||
FirstName string `json:"first_name,omitempty"`
|
||||
// LastName holds the value of the "last_name" field.
|
||||
LastName string `json:"last_name,omitempty"`
|
||||
// Tags holds the value of the "tags" field.
|
||||
Tags []string `json:"tags,omitempty"`
|
||||
// Edges holds the relations/edges for other nodes in the graph.
|
||||
// The values are being populated by the UserQuery when eager-loading is set.
|
||||
Edges UserEdges `json:"edges"`
|
||||
selectValues sql.SelectValues
|
||||
}
|
||||
|
||||
// UserEdges holds the relations/edges for other nodes in the graph.
|
||||
type UserEdges struct {
|
||||
// Cards holds the value of the cards edge.
|
||||
Cards []*Card `json:"cards,omitempty"`
|
||||
// loadedTypes holds the information for reporting if a
|
||||
// type was loaded (or requested) in eager-loading or not.
|
||||
loadedTypes [1]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"}
|
||||
}
|
||||
|
||||
// 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.FieldTags:
|
||||
values[i] = new([]byte)
|
||||
case user.FieldAge:
|
||||
values[i] = new(sql.NullFloat64)
|
||||
case user.FieldID:
|
||||
values[i] = new(sql.NullInt64)
|
||||
case user.FieldFirstName, user.FieldLastName:
|
||||
values[i] = new(sql.NullString)
|
||||
default:
|
||||
values[i] = new(sql.UnknownType)
|
||||
}
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// assignValues assigns the values that were returned from sql.Rows (after scanning)
|
||||
// to the User fields.
|
||||
func (_m *User) assignValues(columns []string, values []any) error {
|
||||
if m, n := len(values), len(columns); m < n {
|
||||
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
|
||||
}
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case user.FieldID:
|
||||
value, ok := values[i].(*sql.NullInt64)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field id", value)
|
||||
}
|
||||
_m.ID = int(value.Int64)
|
||||
case user.FieldAge:
|
||||
if value, ok := values[i].(*sql.NullFloat64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field age", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Age = value.Float64
|
||||
}
|
||||
case user.FieldFirstName:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field first_name", values[i])
|
||||
} else if value.Valid {
|
||||
_m.FirstName = value.String
|
||||
}
|
||||
case user.FieldLastName:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field last_name", values[i])
|
||||
} else if value.Valid {
|
||||
_m.LastName = value.String
|
||||
}
|
||||
case user.FieldTags:
|
||||
if value, ok := values[i].(*[]byte); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field tags", values[i])
|
||||
} else if value != nil && len(*value) > 0 {
|
||||
if err := json.Unmarshal(*value, &_m.Tags); err != nil {
|
||||
return fmt.Errorf("unmarshal field tags: %w", err)
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
// 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("age=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.Age))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("first_name=")
|
||||
builder.WriteString(_m.FirstName)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("last_name=")
|
||||
builder.WriteString(_m.LastName)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("tags=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.Tags))
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// Users is a parsable slice of User.
|
||||
type Users []*User
|
||||
506
examples/migration/ent/user/mutation.go
Normal file
506
examples/migration/ent/user/mutation.go
Normal file
@@ -0,0 +1,506 @@
|
||||
// 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/examples/migration/ent/predicate"
|
||||
)
|
||||
|
||||
// Mutation represents an operation that mutates the User nodes in the graph.
|
||||
type Mutation struct {
|
||||
op ent.Op
|
||||
typ string
|
||||
age *float64
|
||||
addage *float64
|
||||
first_name *string
|
||||
last_name *string
|
||||
tags *[]string
|
||||
appendtags []string
|
||||
clearedFields map[string]struct{}
|
||||
cards map[int]struct{}
|
||||
removedcards map[int]struct{}
|
||||
clearedcards 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
|
||||
}
|
||||
|
||||
// SetAge sets the "age" field.
|
||||
func (m *Mutation) SetAge(f float64) {
|
||||
m.age = &f
|
||||
m.addage = nil
|
||||
}
|
||||
|
||||
// Age returns the value of the "age" field in the mutation.
|
||||
func (m *Mutation) Age() (r float64, exists bool) {
|
||||
v := m.age
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// AddAge adds f to the "age" field.
|
||||
func (m *Mutation) AddAge(f float64) {
|
||||
if m.addage != nil {
|
||||
*m.addage += f
|
||||
} else {
|
||||
m.addage = &f
|
||||
}
|
||||
}
|
||||
|
||||
// AddedAge returns the value that was added to the "age" field in this mutation.
|
||||
func (m *Mutation) AddedAge() (r float64, exists bool) {
|
||||
v := m.addage
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetAge resets all changes to the "age" field.
|
||||
func (m *Mutation) ResetAge() {
|
||||
m.age = nil
|
||||
m.addage = nil
|
||||
}
|
||||
|
||||
// SetFirstName sets the "first_name" field.
|
||||
func (m *Mutation) SetFirstName(s string) {
|
||||
m.first_name = &s
|
||||
}
|
||||
|
||||
// FirstName returns the value of the "first_name" field in the mutation.
|
||||
func (m *Mutation) FirstName() (r string, exists bool) {
|
||||
v := m.first_name
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetFirstName resets all changes to the "first_name" field.
|
||||
func (m *Mutation) ResetFirstName() {
|
||||
m.first_name = nil
|
||||
}
|
||||
|
||||
// SetLastName sets the "last_name" field.
|
||||
func (m *Mutation) SetLastName(s string) {
|
||||
m.last_name = &s
|
||||
}
|
||||
|
||||
// LastName returns the value of the "last_name" field in the mutation.
|
||||
func (m *Mutation) LastName() (r string, exists bool) {
|
||||
v := m.last_name
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// ResetLastName resets all changes to the "last_name" field.
|
||||
func (m *Mutation) ResetLastName() {
|
||||
m.last_name = nil
|
||||
}
|
||||
|
||||
// SetTags sets the "tags" field.
|
||||
func (m *Mutation) SetTags(s []string) {
|
||||
m.tags = &s
|
||||
m.appendtags = nil
|
||||
}
|
||||
|
||||
// Tags returns the value of the "tags" field in the mutation.
|
||||
func (m *Mutation) Tags() (r []string, exists bool) {
|
||||
v := m.tags
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// AppendTags adds s to the "tags" field.
|
||||
func (m *Mutation) AppendTags(s []string) {
|
||||
m.appendtags = append(m.appendtags, s...)
|
||||
}
|
||||
|
||||
// AppendedTags returns the list of values that were appended to the "tags" field in this mutation.
|
||||
func (m *Mutation) AppendedTags() ([]string, bool) {
|
||||
if len(m.appendtags) == 0 {
|
||||
return nil, false
|
||||
}
|
||||
return m.appendtags, true
|
||||
}
|
||||
|
||||
// ClearTags clears the value of the "tags" field.
|
||||
func (m *Mutation) ClearTags() {
|
||||
m.tags = nil
|
||||
m.appendtags = nil
|
||||
m.clearedFields[FieldTags] = struct{}{}
|
||||
}
|
||||
|
||||
// TagsCleared returns if the "tags" field was cleared in this mutation.
|
||||
func (m *Mutation) TagsCleared() bool {
|
||||
_, ok := m.clearedFields[FieldTags]
|
||||
return ok
|
||||
}
|
||||
|
||||
// ResetTags resets all changes to the "tags" field.
|
||||
func (m *Mutation) ResetTags() {
|
||||
m.tags = nil
|
||||
m.appendtags = nil
|
||||
delete(m.clearedFields, FieldTags)
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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, 4)
|
||||
if m.age != nil {
|
||||
fields = append(fields, FieldAge)
|
||||
}
|
||||
if m.first_name != nil {
|
||||
fields = append(fields, FieldFirstName)
|
||||
}
|
||||
if m.last_name != nil {
|
||||
fields = append(fields, FieldLastName)
|
||||
}
|
||||
if m.tags != nil {
|
||||
fields = append(fields, FieldTags)
|
||||
}
|
||||
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 FieldAge:
|
||||
return m.Age()
|
||||
case FieldFirstName:
|
||||
return m.FirstName()
|
||||
case FieldLastName:
|
||||
return m.LastName()
|
||||
case FieldTags:
|
||||
return m.Tags()
|
||||
}
|
||||
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 FieldAge:
|
||||
v, ok := value.(float64)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetAge(v)
|
||||
return nil
|
||||
case FieldFirstName:
|
||||
v, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetFirstName(v)
|
||||
return nil
|
||||
case FieldLastName:
|
||||
v, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetLastName(v)
|
||||
return nil
|
||||
case FieldTags:
|
||||
v, ok := value.([]string)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetTags(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.addage != nil {
|
||||
fields = append(fields, FieldAge)
|
||||
}
|
||||
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 FieldAge:
|
||||
return m.AddedAge()
|
||||
}
|
||||
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 FieldAge:
|
||||
v, ok := value.(float64)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.AddAge(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(FieldTags) {
|
||||
fields = append(fields, FieldTags)
|
||||
}
|
||||
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 FieldTags:
|
||||
m.ClearTags()
|
||||
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 FieldAge:
|
||||
m.ResetAge()
|
||||
return nil
|
||||
case FieldFirstName:
|
||||
m.ResetFirstName()
|
||||
return nil
|
||||
case FieldLastName:
|
||||
m.ResetLastName()
|
||||
return nil
|
||||
case FieldTags:
|
||||
m.ResetTags()
|
||||
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, 1)
|
||||
if m.cards != nil {
|
||||
edges = append(edges, EdgeCards)
|
||||
}
|
||||
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
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemovedEdges returns all edge names that were removed in this mutation.
|
||||
func (m *Mutation) RemovedEdges() []string {
|
||||
edges := make([]string, 0, 1)
|
||||
if m.removedcards != nil {
|
||||
edges = append(edges, EdgeCards)
|
||||
}
|
||||
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
|
||||
}
|
||||
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.clearedcards {
|
||||
edges = append(edges, EdgeCards)
|
||||
}
|
||||
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
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ClearEdge clears the value of the edge with the given name. It returns an error
|
||||
// if that edge is not defined in the schema.
|
||||
func (m *Mutation) ClearEdge(name string) error {
|
||||
switch name {
|
||||
}
|
||||
return fmt.Errorf("unknown User unique edge %s", name)
|
||||
}
|
||||
|
||||
// ResetEdge resets all changes to the edge with the given name in this mutation.
|
||||
// It returns an error if the edge is not defined in the schema.
|
||||
func (m *Mutation) ResetEdge(name string) error {
|
||||
switch name {
|
||||
case EdgeCards:
|
||||
m.ResetCards()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown User edge %s", name)
|
||||
}
|
||||
101
examples/migration/ent/user/user.go
Normal file
101
examples/migration/ent/user/user.go
Normal file
@@ -0,0 +1,101 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package user
|
||||
|
||||
import (
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
)
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the user type in the database.
|
||||
Label = "user"
|
||||
// FieldID holds the string denoting the id field in the database.
|
||||
FieldID = "id"
|
||||
// FieldAge holds the string denoting the age field in the database.
|
||||
FieldAge = "age"
|
||||
// FieldFirstName holds the string denoting the first_name field in the database.
|
||||
FieldFirstName = "first_name"
|
||||
// FieldLastName holds the string denoting the last_name field in the database.
|
||||
FieldLastName = "last_name"
|
||||
// FieldTags holds the string denoting the tags field in the database.
|
||||
FieldTags = "tags"
|
||||
// EdgeCards holds the string denoting the cards edge name in mutations.
|
||||
EdgeCards = "cards"
|
||||
// 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 = "owner_id"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for user fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldAge,
|
||||
FieldFirstName,
|
||||
FieldLastName,
|
||||
FieldTags,
|
||||
}
|
||||
|
||||
// ValidColumn reports if the column name is valid (part of the table columns).
|
||||
func ValidColumn(column string) bool {
|
||||
for i := range Columns {
|
||||
if column == Columns[i] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// OrderOption defines the ordering options for the 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()
|
||||
}
|
||||
|
||||
// ByAge orders the results by the age field.
|
||||
func ByAge(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldAge, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByFirstName orders the results by the first_name field.
|
||||
func ByFirstName(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldFirstName, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByLastName orders the results by the last_name field.
|
||||
func ByLastName(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldLastName, 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...)...)
|
||||
}
|
||||
}
|
||||
func newCardsStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(CardsInverseTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, CardsTable, CardsColumn),
|
||||
)
|
||||
}
|
||||
291
examples/migration/ent/user/where.go
Normal file
291
examples/migration/ent/user/where.go
Normal file
@@ -0,0 +1,291 @@
|
||||
// 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/examples/migration/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))
|
||||
}
|
||||
|
||||
// Age applies equality check predicate on the "age" field. It's identical to AgeEQ.
|
||||
func Age(v float64) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldAge, v))
|
||||
}
|
||||
|
||||
// FirstName applies equality check predicate on the "first_name" field. It's identical to FirstNameEQ.
|
||||
func FirstName(v string) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldFirstName, v))
|
||||
}
|
||||
|
||||
// LastName applies equality check predicate on the "last_name" field. It's identical to LastNameEQ.
|
||||
func LastName(v string) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldLastName, v))
|
||||
}
|
||||
|
||||
// AgeEQ applies the EQ predicate on the "age" field.
|
||||
func AgeEQ(v float64) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldAge, v))
|
||||
}
|
||||
|
||||
// AgeNEQ applies the NEQ predicate on the "age" field.
|
||||
func AgeNEQ(v float64) predicate.User {
|
||||
return predicate.User(sql.FieldNEQ(FieldAge, v))
|
||||
}
|
||||
|
||||
// AgeIn applies the In predicate on the "age" field.
|
||||
func AgeIn(vs ...float64) predicate.User {
|
||||
return predicate.User(sql.FieldIn(FieldAge, vs...))
|
||||
}
|
||||
|
||||
// AgeNotIn applies the NotIn predicate on the "age" field.
|
||||
func AgeNotIn(vs ...float64) predicate.User {
|
||||
return predicate.User(sql.FieldNotIn(FieldAge, vs...))
|
||||
}
|
||||
|
||||
// AgeGT applies the GT predicate on the "age" field.
|
||||
func AgeGT(v float64) predicate.User {
|
||||
return predicate.User(sql.FieldGT(FieldAge, v))
|
||||
}
|
||||
|
||||
// AgeGTE applies the GTE predicate on the "age" field.
|
||||
func AgeGTE(v float64) predicate.User {
|
||||
return predicate.User(sql.FieldGTE(FieldAge, v))
|
||||
}
|
||||
|
||||
// AgeLT applies the LT predicate on the "age" field.
|
||||
func AgeLT(v float64) predicate.User {
|
||||
return predicate.User(sql.FieldLT(FieldAge, v))
|
||||
}
|
||||
|
||||
// AgeLTE applies the LTE predicate on the "age" field.
|
||||
func AgeLTE(v float64) predicate.User {
|
||||
return predicate.User(sql.FieldLTE(FieldAge, v))
|
||||
}
|
||||
|
||||
// FirstNameEQ applies the EQ predicate on the "first_name" field.
|
||||
func FirstNameEQ(v string) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldFirstName, v))
|
||||
}
|
||||
|
||||
// FirstNameNEQ applies the NEQ predicate on the "first_name" field.
|
||||
func FirstNameNEQ(v string) predicate.User {
|
||||
return predicate.User(sql.FieldNEQ(FieldFirstName, v))
|
||||
}
|
||||
|
||||
// FirstNameIn applies the In predicate on the "first_name" field.
|
||||
func FirstNameIn(vs ...string) predicate.User {
|
||||
return predicate.User(sql.FieldIn(FieldFirstName, vs...))
|
||||
}
|
||||
|
||||
// FirstNameNotIn applies the NotIn predicate on the "first_name" field.
|
||||
func FirstNameNotIn(vs ...string) predicate.User {
|
||||
return predicate.User(sql.FieldNotIn(FieldFirstName, vs...))
|
||||
}
|
||||
|
||||
// FirstNameGT applies the GT predicate on the "first_name" field.
|
||||
func FirstNameGT(v string) predicate.User {
|
||||
return predicate.User(sql.FieldGT(FieldFirstName, v))
|
||||
}
|
||||
|
||||
// FirstNameGTE applies the GTE predicate on the "first_name" field.
|
||||
func FirstNameGTE(v string) predicate.User {
|
||||
return predicate.User(sql.FieldGTE(FieldFirstName, v))
|
||||
}
|
||||
|
||||
// FirstNameLT applies the LT predicate on the "first_name" field.
|
||||
func FirstNameLT(v string) predicate.User {
|
||||
return predicate.User(sql.FieldLT(FieldFirstName, v))
|
||||
}
|
||||
|
||||
// FirstNameLTE applies the LTE predicate on the "first_name" field.
|
||||
func FirstNameLTE(v string) predicate.User {
|
||||
return predicate.User(sql.FieldLTE(FieldFirstName, v))
|
||||
}
|
||||
|
||||
// FirstNameContains applies the Contains predicate on the "first_name" field.
|
||||
func FirstNameContains(v string) predicate.User {
|
||||
return predicate.User(sql.FieldContains(FieldFirstName, v))
|
||||
}
|
||||
|
||||
// FirstNameHasPrefix applies the HasPrefix predicate on the "first_name" field.
|
||||
func FirstNameHasPrefix(v string) predicate.User {
|
||||
return predicate.User(sql.FieldHasPrefix(FieldFirstName, v))
|
||||
}
|
||||
|
||||
// FirstNameHasSuffix applies the HasSuffix predicate on the "first_name" field.
|
||||
func FirstNameHasSuffix(v string) predicate.User {
|
||||
return predicate.User(sql.FieldHasSuffix(FieldFirstName, v))
|
||||
}
|
||||
|
||||
// FirstNameEqualFold applies the EqualFold predicate on the "first_name" field.
|
||||
func FirstNameEqualFold(v string) predicate.User {
|
||||
return predicate.User(sql.FieldEqualFold(FieldFirstName, v))
|
||||
}
|
||||
|
||||
// FirstNameContainsFold applies the ContainsFold predicate on the "first_name" field.
|
||||
func FirstNameContainsFold(v string) predicate.User {
|
||||
return predicate.User(sql.FieldContainsFold(FieldFirstName, v))
|
||||
}
|
||||
|
||||
// LastNameEQ applies the EQ predicate on the "last_name" field.
|
||||
func LastNameEQ(v string) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldLastName, v))
|
||||
}
|
||||
|
||||
// LastNameNEQ applies the NEQ predicate on the "last_name" field.
|
||||
func LastNameNEQ(v string) predicate.User {
|
||||
return predicate.User(sql.FieldNEQ(FieldLastName, v))
|
||||
}
|
||||
|
||||
// LastNameIn applies the In predicate on the "last_name" field.
|
||||
func LastNameIn(vs ...string) predicate.User {
|
||||
return predicate.User(sql.FieldIn(FieldLastName, vs...))
|
||||
}
|
||||
|
||||
// LastNameNotIn applies the NotIn predicate on the "last_name" field.
|
||||
func LastNameNotIn(vs ...string) predicate.User {
|
||||
return predicate.User(sql.FieldNotIn(FieldLastName, vs...))
|
||||
}
|
||||
|
||||
// LastNameGT applies the GT predicate on the "last_name" field.
|
||||
func LastNameGT(v string) predicate.User {
|
||||
return predicate.User(sql.FieldGT(FieldLastName, v))
|
||||
}
|
||||
|
||||
// LastNameGTE applies the GTE predicate on the "last_name" field.
|
||||
func LastNameGTE(v string) predicate.User {
|
||||
return predicate.User(sql.FieldGTE(FieldLastName, v))
|
||||
}
|
||||
|
||||
// LastNameLT applies the LT predicate on the "last_name" field.
|
||||
func LastNameLT(v string) predicate.User {
|
||||
return predicate.User(sql.FieldLT(FieldLastName, v))
|
||||
}
|
||||
|
||||
// LastNameLTE applies the LTE predicate on the "last_name" field.
|
||||
func LastNameLTE(v string) predicate.User {
|
||||
return predicate.User(sql.FieldLTE(FieldLastName, v))
|
||||
}
|
||||
|
||||
// LastNameContains applies the Contains predicate on the "last_name" field.
|
||||
func LastNameContains(v string) predicate.User {
|
||||
return predicate.User(sql.FieldContains(FieldLastName, v))
|
||||
}
|
||||
|
||||
// LastNameHasPrefix applies the HasPrefix predicate on the "last_name" field.
|
||||
func LastNameHasPrefix(v string) predicate.User {
|
||||
return predicate.User(sql.FieldHasPrefix(FieldLastName, v))
|
||||
}
|
||||
|
||||
// LastNameHasSuffix applies the HasSuffix predicate on the "last_name" field.
|
||||
func LastNameHasSuffix(v string) predicate.User {
|
||||
return predicate.User(sql.FieldHasSuffix(FieldLastName, v))
|
||||
}
|
||||
|
||||
// LastNameEqualFold applies the EqualFold predicate on the "last_name" field.
|
||||
func LastNameEqualFold(v string) predicate.User {
|
||||
return predicate.User(sql.FieldEqualFold(FieldLastName, v))
|
||||
}
|
||||
|
||||
// LastNameContainsFold applies the ContainsFold predicate on the "last_name" field.
|
||||
func LastNameContainsFold(v string) predicate.User {
|
||||
return predicate.User(sql.FieldContainsFold(FieldLastName, v))
|
||||
}
|
||||
|
||||
// TagsIsNil applies the IsNil predicate on the "tags" field.
|
||||
func TagsIsNil() predicate.User {
|
||||
return predicate.User(sql.FieldIsNull(FieldTags))
|
||||
}
|
||||
|
||||
// TagsNotNil applies the NotNil predicate on the "tags" field.
|
||||
func TagsNotNil() predicate.User {
|
||||
return predicate.User(sql.FieldNotNull(FieldTags))
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// 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))
|
||||
}
|
||||
255
examples/migration/ent/user_create.go
Normal file
255
examples/migration/ent/user_create.go
Normal file
@@ -0,0 +1,255 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/card"
|
||||
"entgo.io/ent/examples/migration/ent/user"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// UserCreate is the builder for creating a User entity.
|
||||
type UserCreate struct {
|
||||
config
|
||||
mutation *UserMutation
|
||||
hooks []Hook
|
||||
}
|
||||
|
||||
// SetAge sets the "age" field.
|
||||
func (_c *UserCreate) SetAge(v float64) *UserCreate {
|
||||
_c.mutation.SetAge(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetFirstName sets the "first_name" field.
|
||||
func (_c *UserCreate) SetFirstName(v string) *UserCreate {
|
||||
_c.mutation.SetFirstName(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetLastName sets the "last_name" field.
|
||||
func (_c *UserCreate) SetLastName(v string) *UserCreate {
|
||||
_c.mutation.SetLastName(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetTags sets the "tags" field.
|
||||
func (_c *UserCreate) SetTags(v []string) *UserCreate {
|
||||
_c.mutation.SetTags(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...)
|
||||
}
|
||||
|
||||
// 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) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_c *UserCreate) check() error {
|
||||
if _, ok := _c.mutation.Age(); !ok {
|
||||
return &ValidationError{Name: "age", err: errors.New(`ent: missing required field "User.age"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.FirstName(); !ok {
|
||||
return &ValidationError{Name: "first_name", err: errors.New(`ent: missing required field "User.first_name"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.LastName(); !ok {
|
||||
return &ValidationError{Name: "last_name", err: errors.New(`ent: missing required field "User.last_name"`)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_c *UserCreate) sqlSave(ctx context.Context) (*User, error) {
|
||||
if err := _c.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_node, _spec := _c.createSpec()
|
||||
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
id := _spec.ID.Value.(int64)
|
||||
_node.ID = int(id)
|
||||
_c.mutation.id = &_node.ID
|
||||
_c.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
func (_c *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) {
|
||||
var (
|
||||
_node = &User{config: _c.config}
|
||||
_spec = sqlgraph.NewCreateSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt))
|
||||
)
|
||||
if value, ok := _c.mutation.Age(); ok {
|
||||
_spec.SetField(user.FieldAge, field.TypeFloat64, value)
|
||||
_node.Age = value
|
||||
}
|
||||
if value, ok := _c.mutation.FirstName(); ok {
|
||||
_spec.SetField(user.FieldFirstName, field.TypeString, value)
|
||||
_node.FirstName = value
|
||||
}
|
||||
if value, ok := _c.mutation.LastName(); ok {
|
||||
_spec.SetField(user.FieldLastName, field.TypeString, value)
|
||||
_node.LastName = value
|
||||
}
|
||||
if value, ok := _c.mutation.Tags(); ok {
|
||||
_spec.SetField(user.FieldTags, field.TypeJSON, value)
|
||||
_node.Tags = 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)
|
||||
}
|
||||
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]
|
||||
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)
|
||||
}
|
||||
}
|
||||
92
examples/migration/ent/user_delete.go
Normal file
92
examples/migration/ent/user_delete.go
Normal file
@@ -0,0 +1,92 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/predicate"
|
||||
"entgo.io/ent/examples/migration/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)
|
||||
}
|
||||
}
|
||||
610
examples/migration/ent/user_query.go
Normal file
610
examples/migration/ent/user_query.go
Normal file
@@ -0,0 +1,610 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql/driver"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/examples/migration/ent/card"
|
||||
"entgo.io/ent/examples/migration/ent/predicate"
|
||||
"entgo.io/ent/examples/migration/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
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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(),
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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 {
|
||||
// Age float64 `json:"age,omitempty"`
|
||||
// Count int `json:"count,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.User.Query().
|
||||
// GroupBy(user.FieldAge).
|
||||
// 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 {
|
||||
// Age float64 `json:"age,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.User.Query().
|
||||
// Select(user.FieldAge).
|
||||
// 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{}
|
||||
_spec = _q.querySpec()
|
||||
loadedTypes = [1]bool{
|
||||
_q.withCards != nil,
|
||||
}
|
||||
)
|
||||
_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
|
||||
}
|
||||
}
|
||||
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])
|
||||
}
|
||||
}
|
||||
if len(query.ctx.Fields) > 0 {
|
||||
query.ctx.AppendFieldOnce(card.FieldOwnerID)
|
||||
}
|
||||
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.OwnerID
|
||||
node, ok := nodeids[fk]
|
||||
if !ok {
|
||||
return fmt.Errorf(`unexpected referenced foreign-key "owner_id" returned %v for node %v`, fk, n.ID)
|
||||
}
|
||||
assign(node, 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)
|
||||
}
|
||||
523
examples/migration/ent/user_update.go
Normal file
523
examples/migration/ent/user_update.go
Normal file
@@ -0,0 +1,523 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/dialect/sql/sqljson"
|
||||
"entgo.io/ent/examples/migration/ent/card"
|
||||
"entgo.io/ent/examples/migration/ent/predicate"
|
||||
"entgo.io/ent/examples/migration/ent/user"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// UserUpdate is the builder for updating User entities.
|
||||
type UserUpdate struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *UserMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the UserUpdate builder.
|
||||
func (_u *UserUpdate) Where(ps ...predicate.User) *UserUpdate {
|
||||
_u.mutation.Where(ps...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetAge sets the "age" field.
|
||||
func (_u *UserUpdate) SetAge(v float64) *UserUpdate {
|
||||
_u.mutation.ResetAge()
|
||||
_u.mutation.SetAge(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableAge sets the "age" field if the given value is not nil.
|
||||
func (_u *UserUpdate) SetNillableAge(v *float64) *UserUpdate {
|
||||
if v != nil {
|
||||
_u.SetAge(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddAge adds value to the "age" field.
|
||||
func (_u *UserUpdate) AddAge(v float64) *UserUpdate {
|
||||
_u.mutation.AddAge(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetFirstName sets the "first_name" field.
|
||||
func (_u *UserUpdate) SetFirstName(v string) *UserUpdate {
|
||||
_u.mutation.SetFirstName(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableFirstName sets the "first_name" field if the given value is not nil.
|
||||
func (_u *UserUpdate) SetNillableFirstName(v *string) *UserUpdate {
|
||||
if v != nil {
|
||||
_u.SetFirstName(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetLastName sets the "last_name" field.
|
||||
func (_u *UserUpdate) SetLastName(v string) *UserUpdate {
|
||||
_u.mutation.SetLastName(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableLastName sets the "last_name" field if the given value is not nil.
|
||||
func (_u *UserUpdate) SetNillableLastName(v *string) *UserUpdate {
|
||||
if v != nil {
|
||||
_u.SetLastName(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetTags sets the "tags" field.
|
||||
func (_u *UserUpdate) SetTags(v []string) *UserUpdate {
|
||||
_u.mutation.SetTags(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AppendTags appends value to the "tags" field.
|
||||
func (_u *UserUpdate) AppendTags(v []string) *UserUpdate {
|
||||
_u.mutation.AppendTags(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearTags clears the value of the "tags" field.
|
||||
func (_u *UserUpdate) ClearTags() *UserUpdate {
|
||||
_u.mutation.ClearTags()
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddCardIDs adds the "cards" edge to the Card entity by IDs.
|
||||
func (_u *UserUpdate) AddCardIDs(ids ...int) *UserUpdate {
|
||||
_u.mutation.AddCardIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddCards adds the "cards" edges to the Card entity.
|
||||
func (_u *UserUpdate) AddCards(v ...*Card) *UserUpdate {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.AddCardIDs(ids...)
|
||||
}
|
||||
|
||||
// Mutation returns the UserMutation object of the builder.
|
||||
func (_u *UserUpdate) Mutation() *UserMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// ClearCards clears all "cards" edges to the Card entity.
|
||||
func (_u *UserUpdate) ClearCards() *UserUpdate {
|
||||
_u.mutation.ClearCards()
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveCardIDs removes the "cards" edge to Card entities by IDs.
|
||||
func (_u *UserUpdate) RemoveCardIDs(ids ...int) *UserUpdate {
|
||||
_u.mutation.RemoveCardIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveCards removes "cards" edges to Card entities.
|
||||
func (_u *UserUpdate) RemoveCards(v ...*Card) *UserUpdate {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.RemoveCardIDs(ids...)
|
||||
}
|
||||
|
||||
// Save executes the query and returns the number of nodes affected by the update operation.
|
||||
func (_u *UserUpdate) 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 *UserUpdate) SaveX(ctx context.Context) int {
|
||||
affected, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return affected
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_u *UserUpdate) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *UserUpdate) ExecX(ctx context.Context) {
|
||||
if err := _u.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (_u *UserUpdate) sqlSave(ctx context.Context) (_node int, err error) {
|
||||
_spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.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.Age(); ok {
|
||||
_spec.SetField(user.FieldAge, field.TypeFloat64, value)
|
||||
}
|
||||
if value, ok := _u.mutation.AddedAge(); ok {
|
||||
_spec.AddField(user.FieldAge, field.TypeFloat64, value)
|
||||
}
|
||||
if value, ok := _u.mutation.FirstName(); ok {
|
||||
_spec.SetField(user.FieldFirstName, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.LastName(); ok {
|
||||
_spec.SetField(user.FieldLastName, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Tags(); ok {
|
||||
_spec.SetField(user.FieldTags, field.TypeJSON, value)
|
||||
}
|
||||
if value, ok := _u.mutation.AppendedTags(); ok {
|
||||
_spec.AddModifier(func(u *sql.UpdateBuilder) {
|
||||
sqljson.Append(u, user.FieldTags, value)
|
||||
})
|
||||
}
|
||||
if _u.mutation.TagsCleared() {
|
||||
_spec.ClearField(user.FieldTags, field.TypeJSON)
|
||||
}
|
||||
if _u.mutation.CardsCleared() {
|
||||
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),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.RemovedCardsIDs(); len(nodes) > 0 && !_u.mutation.CardsCleared() {
|
||||
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.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.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.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{user.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
// UserUpdateOne is the builder for updating a single User entity.
|
||||
type UserUpdateOne struct {
|
||||
config
|
||||
fields []string
|
||||
hooks []Hook
|
||||
mutation *UserMutation
|
||||
}
|
||||
|
||||
// SetAge sets the "age" field.
|
||||
func (_u *UserUpdateOne) SetAge(v float64) *UserUpdateOne {
|
||||
_u.mutation.ResetAge()
|
||||
_u.mutation.SetAge(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableAge sets the "age" field if the given value is not nil.
|
||||
func (_u *UserUpdateOne) SetNillableAge(v *float64) *UserUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetAge(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddAge adds value to the "age" field.
|
||||
func (_u *UserUpdateOne) AddAge(v float64) *UserUpdateOne {
|
||||
_u.mutation.AddAge(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetFirstName sets the "first_name" field.
|
||||
func (_u *UserUpdateOne) SetFirstName(v string) *UserUpdateOne {
|
||||
_u.mutation.SetFirstName(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableFirstName sets the "first_name" field if the given value is not nil.
|
||||
func (_u *UserUpdateOne) SetNillableFirstName(v *string) *UserUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetFirstName(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetLastName sets the "last_name" field.
|
||||
func (_u *UserUpdateOne) SetLastName(v string) *UserUpdateOne {
|
||||
_u.mutation.SetLastName(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableLastName sets the "last_name" field if the given value is not nil.
|
||||
func (_u *UserUpdateOne) SetNillableLastName(v *string) *UserUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetLastName(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetTags sets the "tags" field.
|
||||
func (_u *UserUpdateOne) SetTags(v []string) *UserUpdateOne {
|
||||
_u.mutation.SetTags(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AppendTags appends value to the "tags" field.
|
||||
func (_u *UserUpdateOne) AppendTags(v []string) *UserUpdateOne {
|
||||
_u.mutation.AppendTags(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearTags clears the value of the "tags" field.
|
||||
func (_u *UserUpdateOne) ClearTags() *UserUpdateOne {
|
||||
_u.mutation.ClearTags()
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddCardIDs adds the "cards" edge to the Card entity by IDs.
|
||||
func (_u *UserUpdateOne) AddCardIDs(ids ...int) *UserUpdateOne {
|
||||
_u.mutation.AddCardIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddCards adds the "cards" edges to the Card entity.
|
||||
func (_u *UserUpdateOne) AddCards(v ...*Card) *UserUpdateOne {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.AddCardIDs(ids...)
|
||||
}
|
||||
|
||||
// Mutation returns the UserMutation object of the builder.
|
||||
func (_u *UserUpdateOne) Mutation() *UserMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// ClearCards clears all "cards" edges to the Card entity.
|
||||
func (_u *UserUpdateOne) ClearCards() *UserUpdateOne {
|
||||
_u.mutation.ClearCards()
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveCardIDs removes the "cards" edge to Card entities by IDs.
|
||||
func (_u *UserUpdateOne) RemoveCardIDs(ids ...int) *UserUpdateOne {
|
||||
_u.mutation.RemoveCardIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveCards removes "cards" edges to Card entities.
|
||||
func (_u *UserUpdateOne) RemoveCards(v ...*Card) *UserUpdateOne {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.RemoveCardIDs(ids...)
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the UserUpdate builder.
|
||||
func (_u *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne {
|
||||
_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 *UserUpdateOne) Select(field string, fields ...string) *UserUpdateOne {
|
||||
_u.fields = append([]string{field}, fields...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// Save executes the query and returns the updated User entity.
|
||||
func (_u *UserUpdateOne) Save(ctx context.Context) (*User, error) {
|
||||
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_u *UserUpdateOne) SaveX(ctx context.Context) *User {
|
||||
node, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// Exec executes the query on the entity.
|
||||
func (_u *UserUpdateOne) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *UserUpdateOne) ExecX(ctx context.Context) {
|
||||
if err := _u.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (_u *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) {
|
||||
_spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt))
|
||||
id, ok := _u.mutation.ID()
|
||||
if !ok {
|
||||
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "User.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, user.FieldID)
|
||||
for _, f := range fields {
|
||||
if !user.ValidColumn(f) {
|
||||
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
if f != user.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.Age(); ok {
|
||||
_spec.SetField(user.FieldAge, field.TypeFloat64, value)
|
||||
}
|
||||
if value, ok := _u.mutation.AddedAge(); ok {
|
||||
_spec.AddField(user.FieldAge, field.TypeFloat64, value)
|
||||
}
|
||||
if value, ok := _u.mutation.FirstName(); ok {
|
||||
_spec.SetField(user.FieldFirstName, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.LastName(); ok {
|
||||
_spec.SetField(user.FieldLastName, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Tags(); ok {
|
||||
_spec.SetField(user.FieldTags, field.TypeJSON, value)
|
||||
}
|
||||
if value, ok := _u.mutation.AppendedTags(); ok {
|
||||
_spec.AddModifier(func(u *sql.UpdateBuilder) {
|
||||
sqljson.Append(u, user.FieldTags, value)
|
||||
})
|
||||
}
|
||||
if _u.mutation.TagsCleared() {
|
||||
_spec.ClearField(user.FieldTags, field.TypeJSON)
|
||||
}
|
||||
if _u.mutation.CardsCleared() {
|
||||
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),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.RemovedCardsIDs(); len(nodes) > 0 && !_u.mutation.CardsCleared() {
|
||||
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.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.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.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
_node = &User{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{user.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
Reference in New Issue
Block a user