examples/migration: add payment entity (#3876)

This commit is contained in:
Ariel Mashraki
2023-12-31 12:27:32 +02:00
committed by GitHub
parent bd8f9eac01
commit 2341a71acb
25 changed files with 3676 additions and 45 deletions

View File

@@ -35,9 +35,11 @@ type Card struct {
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 [1]bool
loadedTypes [2]bool
}
// OwnerOrErr returns the Owner value or an error if the edge
@@ -53,6 +55,15 @@ func (e CardEdges) OwnerOrErr() (*User, error) {
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))
@@ -113,6 +124,11 @@ func (c *Card) QueryOwner() *UserQuery {
return NewCardClient(c.config).QueryOwner(c)
}
// QueryPayments queries the "payments" edge of the Card entity.
func (c *Card) QueryPayments() *PaymentQuery {
return NewCardClient(c.config).QueryPayments(c)
}
// 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.

View File

@@ -22,6 +22,8 @@ const (
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.
@@ -31,6 +33,13 @@ const (
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.
@@ -79,6 +88,20 @@ func ByOwnerField(field string, opts ...sql.OrderTermOption) OrderOption {
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),
@@ -86,3 +109,10 @@ func newOwnerStep() *sqlgraph.Step {
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),
)
}

View File

@@ -175,6 +175,29 @@ func HasOwnerWith(preds ...predicate.User) predicate.Card {
})
}
// 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...))

View File

@@ -13,6 +13,7 @@ import (
"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"
)
@@ -49,6 +50,21 @@ func (cc *CardCreate) SetOwner(u *User) *CardCreate {
return cc.SetOwnerID(u.ID)
}
// AddPaymentIDs adds the "payments" edge to the Payment entity by IDs.
func (cc *CardCreate) AddPaymentIDs(ids ...int) *CardCreate {
cc.mutation.AddPaymentIDs(ids...)
return cc
}
// AddPayments adds the "payments" edges to the Payment entity.
func (cc *CardCreate) AddPayments(p ...*Payment) *CardCreate {
ids := make([]int, len(p))
for i := range p {
ids[i] = p[i].ID
}
return cc.AddPaymentIDs(ids...)
}
// Mutation returns the CardMutation object of the builder.
func (cc *CardCreate) Mutation() *CardMutation {
return cc.mutation
@@ -148,6 +164,22 @@ func (cc *CardCreate) createSpec() (*Card, *sqlgraph.CreateSpec) {
_node.OwnerID = nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := cc.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
}

View File

@@ -8,12 +8,14 @@ package ent
import (
"context"
"database/sql/driver"
"fmt"
"math"
"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"
@@ -22,11 +24,12 @@ import (
// CardQuery is the builder for querying Card entities.
type CardQuery struct {
config
ctx *QueryContext
order []card.OrderOption
inters []Interceptor
predicates []predicate.Card
withOwner *UserQuery
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)
@@ -85,6 +88,28 @@ func (cq *CardQuery) QueryOwner() *UserQuery {
return query
}
// QueryPayments chains the current query on the "payments" edge.
func (cq *CardQuery) QueryPayments() *PaymentQuery {
query := (&PaymentClient{config: cq.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := cq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := cq.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(cq.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 (cq *CardQuery) First(ctx context.Context) (*Card, error) {
@@ -272,12 +297,13 @@ func (cq *CardQuery) Clone() *CardQuery {
return nil
}
return &CardQuery{
config: cq.config,
ctx: cq.ctx.Clone(),
order: append([]card.OrderOption{}, cq.order...),
inters: append([]Interceptor{}, cq.inters...),
predicates: append([]predicate.Card{}, cq.predicates...),
withOwner: cq.withOwner.Clone(),
config: cq.config,
ctx: cq.ctx.Clone(),
order: append([]card.OrderOption{}, cq.order...),
inters: append([]Interceptor{}, cq.inters...),
predicates: append([]predicate.Card{}, cq.predicates...),
withOwner: cq.withOwner.Clone(),
withPayments: cq.withPayments.Clone(),
// clone intermediate query.
sql: cq.sql.Clone(),
path: cq.path,
@@ -295,6 +321,17 @@ func (cq *CardQuery) WithOwner(opts ...func(*UserQuery)) *CardQuery {
return cq
}
// 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 (cq *CardQuery) WithPayments(opts ...func(*PaymentQuery)) *CardQuery {
query := (&PaymentClient{config: cq.config}).Query()
for _, opt := range opts {
opt(query)
}
cq.withPayments = query
return cq
}
// 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.
//
@@ -373,8 +410,9 @@ func (cq *CardQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Card, e
var (
nodes = []*Card{}
_spec = cq.querySpec()
loadedTypes = [1]bool{
loadedTypes = [2]bool{
cq.withOwner != nil,
cq.withPayments != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
@@ -401,6 +439,13 @@ func (cq *CardQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Card, e
return nil, err
}
}
if query := cq.withPayments; query != nil {
if err := cq.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
}
@@ -433,6 +478,36 @@ func (cq *CardQuery) loadOwner(ctx context.Context, query *UserQuery, nodes []*C
}
return nil
}
func (cq *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 (cq *CardQuery) sqlCount(ctx context.Context) (int, error) {
_spec := cq.querySpec()

View File

@@ -14,6 +14,7 @@ import (
"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"
@@ -65,6 +66,21 @@ func (cu *CardUpdate) SetOwner(u *User) *CardUpdate {
return cu.SetOwnerID(u.ID)
}
// AddPaymentIDs adds the "payments" edge to the Payment entity by IDs.
func (cu *CardUpdate) AddPaymentIDs(ids ...int) *CardUpdate {
cu.mutation.AddPaymentIDs(ids...)
return cu
}
// AddPayments adds the "payments" edges to the Payment entity.
func (cu *CardUpdate) AddPayments(p ...*Payment) *CardUpdate {
ids := make([]int, len(p))
for i := range p {
ids[i] = p[i].ID
}
return cu.AddPaymentIDs(ids...)
}
// Mutation returns the CardMutation object of the builder.
func (cu *CardUpdate) Mutation() *CardMutation {
return cu.mutation
@@ -76,6 +92,27 @@ func (cu *CardUpdate) ClearOwner() *CardUpdate {
return cu
}
// ClearPayments clears all "payments" edges to the Payment entity.
func (cu *CardUpdate) ClearPayments() *CardUpdate {
cu.mutation.ClearPayments()
return cu
}
// RemovePaymentIDs removes the "payments" edge to Payment entities by IDs.
func (cu *CardUpdate) RemovePaymentIDs(ids ...int) *CardUpdate {
cu.mutation.RemovePaymentIDs(ids...)
return cu
}
// RemovePayments removes "payments" edges to Payment entities.
func (cu *CardUpdate) RemovePayments(p ...*Payment) *CardUpdate {
ids := make([]int, len(p))
for i := range p {
ids[i] = p[i].ID
}
return cu.RemovePaymentIDs(ids...)
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (cu *CardUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, cu.sqlSave, cu.mutation, cu.hooks)
@@ -155,6 +192,51 @@ func (cu *CardUpdate) sqlSave(ctx context.Context) (n int, err error) {
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if cu.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 := cu.mutation.RemovedPaymentsIDs(); len(nodes) > 0 && !cu.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 := cu.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 n, err = sqlgraph.UpdateNodes(ctx, cu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{card.Label}
@@ -208,6 +290,21 @@ func (cuo *CardUpdateOne) SetOwner(u *User) *CardUpdateOne {
return cuo.SetOwnerID(u.ID)
}
// AddPaymentIDs adds the "payments" edge to the Payment entity by IDs.
func (cuo *CardUpdateOne) AddPaymentIDs(ids ...int) *CardUpdateOne {
cuo.mutation.AddPaymentIDs(ids...)
return cuo
}
// AddPayments adds the "payments" edges to the Payment entity.
func (cuo *CardUpdateOne) AddPayments(p ...*Payment) *CardUpdateOne {
ids := make([]int, len(p))
for i := range p {
ids[i] = p[i].ID
}
return cuo.AddPaymentIDs(ids...)
}
// Mutation returns the CardMutation object of the builder.
func (cuo *CardUpdateOne) Mutation() *CardMutation {
return cuo.mutation
@@ -219,6 +316,27 @@ func (cuo *CardUpdateOne) ClearOwner() *CardUpdateOne {
return cuo
}
// ClearPayments clears all "payments" edges to the Payment entity.
func (cuo *CardUpdateOne) ClearPayments() *CardUpdateOne {
cuo.mutation.ClearPayments()
return cuo
}
// RemovePaymentIDs removes the "payments" edge to Payment entities by IDs.
func (cuo *CardUpdateOne) RemovePaymentIDs(ids ...int) *CardUpdateOne {
cuo.mutation.RemovePaymentIDs(ids...)
return cuo
}
// RemovePayments removes "payments" edges to Payment entities.
func (cuo *CardUpdateOne) RemovePayments(p ...*Payment) *CardUpdateOne {
ids := make([]int, len(p))
for i := range p {
ids[i] = p[i].ID
}
return cuo.RemovePaymentIDs(ids...)
}
// Where appends a list predicates to the CardUpdate builder.
func (cuo *CardUpdateOne) Where(ps ...predicate.Card) *CardUpdateOne {
cuo.mutation.Where(ps...)
@@ -328,6 +446,51 @@ func (cuo *CardUpdateOne) sqlSave(ctx context.Context) (_node *Card, err error)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if cuo.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 := cuo.mutation.RemovedPaymentsIDs(); len(nodes) > 0 && !cuo.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 := cuo.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: cuo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues

View File

@@ -21,6 +21,7 @@ import (
"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/user"
)
@@ -32,6 +33,8 @@ type Client struct {
Schema *migrate.Schema
// 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
// User is the client for interacting with the User builders.
@@ -48,6 +51,7 @@ func NewClient(opts ...Option) *Client {
func (c *Client) init() {
c.Schema = migrate.NewSchema(c.driver)
c.Card = NewCardClient(c.config)
c.Payment = NewPaymentClient(c.config)
c.Pet = NewPetClient(c.config)
c.User = NewUserClient(c.config)
}
@@ -140,11 +144,12 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) {
cfg := c.config
cfg.driver = tx
return &Tx{
ctx: ctx,
config: cfg,
Card: NewCardClient(cfg),
Pet: NewPetClient(cfg),
User: NewUserClient(cfg),
ctx: ctx,
config: cfg,
Card: NewCardClient(cfg),
Payment: NewPaymentClient(cfg),
Pet: NewPetClient(cfg),
User: NewUserClient(cfg),
}, nil
}
@@ -162,11 +167,12 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
cfg := c.config
cfg.driver = &txDriver{tx: tx, drv: c.driver}
return &Tx{
ctx: ctx,
config: cfg,
Card: NewCardClient(cfg),
Pet: NewPetClient(cfg),
User: NewUserClient(cfg),
ctx: ctx,
config: cfg,
Card: NewCardClient(cfg),
Payment: NewPaymentClient(cfg),
Pet: NewPetClient(cfg),
User: NewUserClient(cfg),
}, nil
}
@@ -196,6 +202,7 @@ func (c *Client) Close() error {
// In order to add hooks to a specific client, call: `client.Node.Use(...)`.
func (c *Client) Use(hooks ...Hook) {
c.Card.Use(hooks...)
c.Payment.Use(hooks...)
c.Pet.Use(hooks...)
c.User.Use(hooks...)
}
@@ -204,6 +211,7 @@ func (c *Client) Use(hooks ...Hook) {
// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`.
func (c *Client) Intercept(interceptors ...Interceptor) {
c.Card.Intercept(interceptors...)
c.Payment.Intercept(interceptors...)
c.Pet.Intercept(interceptors...)
c.User.Intercept(interceptors...)
}
@@ -213,6 +221,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
switch m := m.(type) {
case *CardMutation:
return c.Card.mutate(ctx, m)
case *PaymentMutation:
return c.Payment.mutate(ctx, m)
case *PetMutation:
return c.Pet.mutate(ctx, m)
case *UserMutation:
@@ -346,6 +356,22 @@ func (c *CardClient) QueryOwner(ca *Card) *UserQuery {
return query
}
// QueryPayments queries the payments edge of a Card.
func (c *CardClient) QueryPayments(ca *Card) *PaymentQuery {
query := (&PaymentClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := ca.ID
step := sqlgraph.NewStep(
sqlgraph.From(card.Table, card.FieldID, id),
sqlgraph.To(payment.Table, payment.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, card.PaymentsTable, card.PaymentsColumn),
)
fromV = sqlgraph.Neighbors(ca.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *CardClient) Hooks() []Hook {
return c.hooks.Card
@@ -371,6 +397,155 @@ func (c *CardClient) mutate(ctx context.Context, m *CardMutation) (Value, error)
}
}
// PaymentClient is a client for the Payment schema.
type PaymentClient struct {
config
}
// NewPaymentClient returns a client for the Payment from the given config.
func NewPaymentClient(c config) *PaymentClient {
return &PaymentClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `payment.Hooks(f(g(h())))`.
func (c *PaymentClient) Use(hooks ...Hook) {
c.hooks.Payment = append(c.hooks.Payment, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `payment.Intercept(f(g(h())))`.
func (c *PaymentClient) Intercept(interceptors ...Interceptor) {
c.inters.Payment = append(c.inters.Payment, interceptors...)
}
// Create returns a builder for creating a Payment entity.
func (c *PaymentClient) Create() *PaymentCreate {
mutation := newPaymentMutation(c.config, OpCreate)
return &PaymentCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Payment entities.
func (c *PaymentClient) CreateBulk(builders ...*PaymentCreate) *PaymentCreateBulk {
return &PaymentCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *PaymentClient) MapCreateBulk(slice any, setFunc func(*PaymentCreate, int)) *PaymentCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &PaymentCreateBulk{err: fmt.Errorf("calling to PaymentClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*PaymentCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &PaymentCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Payment.
func (c *PaymentClient) Update() *PaymentUpdate {
mutation := newPaymentMutation(c.config, OpUpdate)
return &PaymentUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *PaymentClient) UpdateOne(pa *Payment) *PaymentUpdateOne {
mutation := newPaymentMutation(c.config, OpUpdateOne, withPayment(pa))
return &PaymentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *PaymentClient) UpdateOneID(id int) *PaymentUpdateOne {
mutation := newPaymentMutation(c.config, OpUpdateOne, withPaymentID(id))
return &PaymentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Payment.
func (c *PaymentClient) Delete() *PaymentDelete {
mutation := newPaymentMutation(c.config, OpDelete)
return &PaymentDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *PaymentClient) DeleteOne(pa *Payment) *PaymentDeleteOne {
return c.DeleteOneID(pa.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *PaymentClient) DeleteOneID(id int) *PaymentDeleteOne {
builder := c.Delete().Where(payment.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &PaymentDeleteOne{builder}
}
// Query returns a query builder for Payment.
func (c *PaymentClient) Query() *PaymentQuery {
return &PaymentQuery{
config: c.config,
ctx: &QueryContext{Type: TypePayment},
inters: c.Interceptors(),
}
}
// Get returns a Payment entity by its id.
func (c *PaymentClient) Get(ctx context.Context, id int) (*Payment, error) {
return c.Query().Where(payment.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *PaymentClient) GetX(ctx context.Context, id int) *Payment {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryCard queries the card edge of a Payment.
func (c *PaymentClient) QueryCard(pa *Payment) *CardQuery {
query := (&CardClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := pa.ID
step := sqlgraph.NewStep(
sqlgraph.From(payment.Table, payment.FieldID, id),
sqlgraph.To(card.Table, card.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, payment.CardTable, payment.CardColumn),
)
fromV = sqlgraph.Neighbors(pa.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *PaymentClient) Hooks() []Hook {
return c.hooks.Payment
}
// Interceptors returns the client interceptors.
func (c *PaymentClient) Interceptors() []Interceptor {
return c.inters.Payment
}
func (c *PaymentClient) mutate(ctx context.Context, m *PaymentMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&PaymentCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&PaymentUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&PaymentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&PaymentDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Payment mutation op: %q", m.Op())
}
}
// PetClient is a client for the Pet schema.
type PetClient struct {
config
@@ -688,9 +863,9 @@ func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error)
// hooks and interceptors per client, for fast access.
type (
hooks struct {
Card, Pet, User []ent.Hook
Card, Payment, Pet, User []ent.Hook
}
inters struct {
Card, Pet, User []ent.Interceptor
Card, Payment, Pet, User []ent.Interceptor
}
)

View File

@@ -17,6 +17,7 @@ import (
"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/user"
)
@@ -79,9 +80,10 @@ var (
func checkColumn(table, column string) error {
initCheck.Do(func() {
columnCheck = sql.NewColumnCheck(map[string]func(string) bool{
card.Table: card.ValidColumn,
pet.Table: pet.ValidColumn,
user.Table: user.ValidColumn,
card.Table: card.ValidColumn,
payment.Table: payment.ValidColumn,
pet.Table: pet.ValidColumn,
user.Table: user.ValidColumn,
})
})
return columnCheck(table, column)

View File

@@ -25,6 +25,18 @@ func (f CardFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error)
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)

View File

@@ -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;

View File

@@ -1,4 +1,4 @@
h1:bWNwoQD451P0fV9kAd46VfreaOAJdrpDXYJ9xmgATtw=
h1:BZ/m+1lip4UqNLaufWxuuYirZn+gqq4srr3X5JpGuOY=
20221114082343_create_users.sql h1:EeOPKbOeYUHO830P1MCXKUsxT3wLk/hSgcpT9GzlGZQ=
20221114090322_add_age.sql h1:weRCTqS5cqKyrvIjGXk7Bn24YUXo0nhLNWD0EZBcaoQ=
20221114101516_add_name.sql h1:leQgI2JN3URZyujlNzX3gI53MSiTA02MKI/G9cnMu6I=
@@ -7,3 +7,4 @@ h1:bWNwoQD451P0fV9kAd46VfreaOAJdrpDXYJ9xmgATtw=
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=

View File

@@ -33,6 +33,37 @@ var (
},
},
}
// 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", "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},
@@ -83,6 +114,7 @@ var (
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
CardsTable,
PaymentsTable,
PetsTable,
UsersTable,
}
@@ -94,6 +126,11 @@ func init() {
CardsTable.Annotation.Checks = map[string]string{
"number_length": "(LENGTH(`number`) = 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
UsersTable.Annotation = &entsql.Annotation{

View File

@@ -11,10 +11,12 @@ import (
"errors"
"fmt"
"sync"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"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/predicate"
"entgo.io/ent/examples/migration/ent/user"
@@ -30,24 +32,28 @@ const (
OpUpdateOne = ent.OpUpdateOne
// Node types.
TypeCard = "Card"
TypePet = "Pet"
TypeUser = "User"
TypeCard = "Card"
TypePayment = "Payment"
TypePet = "Pet"
TypeUser = "User"
)
// CardMutation represents an operation that mutates the Card nodes in the graph.
type CardMutation struct {
config
op Op
typ string
id *int
number *string
clearedFields map[string]struct{}
owner *int
clearedowner bool
done bool
oldValue func(context.Context) (*Card, error)
predicates []predicate.Card
op Op
typ string
id *int
number *string
clearedFields map[string]struct{}
owner *int
clearedowner bool
payments map[int]struct{}
removedpayments map[int]struct{}
clearedpayments bool
done bool
oldValue func(context.Context) (*Card, error)
predicates []predicate.Card
}
var _ ent.Mutation = (*CardMutation)(nil)
@@ -247,6 +253,60 @@ func (m *CardMutation) ResetOwner() {
m.clearedowner = false
}
// AddPaymentIDs adds the "payments" edge to the Payment entity by ids.
func (m *CardMutation) 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 *CardMutation) ClearPayments() {
m.clearedpayments = true
}
// PaymentsCleared reports if the "payments" edge to the Payment entity was cleared.
func (m *CardMutation) PaymentsCleared() bool {
return m.clearedpayments
}
// RemovePaymentIDs removes the "payments" edge to the Payment entity by IDs.
func (m *CardMutation) 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 *CardMutation) RemovedPaymentsIDs() (ids []int) {
for id := range m.removedpayments {
ids = append(ids, id)
}
return
}
// PaymentsIDs returns the "payments" edge IDs in the mutation.
func (m *CardMutation) PaymentsIDs() (ids []int) {
for id := range m.payments {
ids = append(ids, id)
}
return
}
// ResetPayments resets all changes to the "payments" edge.
func (m *CardMutation) ResetPayments() {
m.payments = nil
m.clearedpayments = false
m.removedpayments = nil
}
// Where appends a list predicates to the CardMutation builder.
func (m *CardMutation) Where(ps ...predicate.Card) {
m.predicates = append(m.predicates, ps...)
@@ -400,10 +460,13 @@ func (m *CardMutation) ResetField(name string) error {
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *CardMutation) AddedEdges() []string {
edges := make([]string, 0, 1)
edges := make([]string, 0, 2)
if m.owner != nil {
edges = append(edges, card.EdgeOwner)
}
if m.payments != nil {
edges = append(edges, card.EdgePayments)
}
return edges
}
@@ -415,28 +478,48 @@ func (m *CardMutation) AddedIDs(name string) []ent.Value {
if id := m.owner; id != nil {
return []ent.Value{*id}
}
case card.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 *CardMutation) RemovedEdges() []string {
edges := make([]string, 0, 1)
edges := make([]string, 0, 2)
if m.removedpayments != nil {
edges = append(edges, card.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 *CardMutation) RemovedIDs(name string) []ent.Value {
switch name {
case card.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 *CardMutation) ClearedEdges() []string {
edges := make([]string, 0, 1)
edges := make([]string, 0, 2)
if m.clearedowner {
edges = append(edges, card.EdgeOwner)
}
if m.clearedpayments {
edges = append(edges, card.EdgePayments)
}
return edges
}
@@ -446,6 +529,8 @@ func (m *CardMutation) EdgeCleared(name string) bool {
switch name {
case card.EdgeOwner:
return m.clearedowner
case card.EdgePayments:
return m.clearedpayments
}
return false
}
@@ -468,10 +553,699 @@ func (m *CardMutation) ResetEdge(name string) error {
case card.EdgeOwner:
m.ResetOwner()
return nil
case card.EdgePayments:
m.ResetPayments()
return nil
}
return fmt.Errorf("unknown Card edge %s", name)
}
// PaymentMutation represents an operation that mutates the Payment nodes in the graph.
type PaymentMutation struct {
config
op Op
typ string
id *int
amount *float64
addamount *float64
currency *payment.Currency
time *time.Time
description *string
status *payment.Status
clearedFields map[string]struct{}
card *int
clearedcard bool
done bool
oldValue func(context.Context) (*Payment, error)
predicates []predicate.Payment
}
var _ ent.Mutation = (*PaymentMutation)(nil)
// paymentOption allows management of the mutation configuration using functional options.
type paymentOption func(*PaymentMutation)
// newPaymentMutation creates new mutation for the Payment entity.
func newPaymentMutation(c config, op Op, opts ...paymentOption) *PaymentMutation {
m := &PaymentMutation{
config: c,
op: op,
typ: TypePayment,
clearedFields: make(map[string]struct{}),
}
for _, opt := range opts {
opt(m)
}
return m
}
// withPaymentID sets the ID field of the mutation.
func withPaymentID(id int) paymentOption {
return func(m *PaymentMutation) {
var (
err error
once sync.Once
value *Payment
)
m.oldValue = func(ctx context.Context) (*Payment, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().Payment.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withPayment sets the old Payment of the mutation.
func withPayment(node *Payment) paymentOption {
return func(m *PaymentMutation) {
m.oldValue = func(context.Context) (*Payment, error) {
return node, nil
}
m.id = &node.ID
}
}
// Client returns a new `ent.Client` from the mutation. If the mutation was
// executed in a transaction (ent.Tx), a transactional client is returned.
func (m PaymentMutation) Client() *Client {
client := &Client{config: m.config}
client.init()
return client
}
// Tx returns an `ent.Tx` for mutations that were executed in transactions;
// it returns an error otherwise.
func (m PaymentMutation) Tx() (*Tx, error) {
if _, ok := m.driver.(*txDriver); !ok {
return nil, errors.New("ent: mutation is not running in a transaction")
}
tx := &Tx{config: m.config}
tx.init()
return tx, nil
}
// ID returns the ID value in the mutation. Note that the ID is only available
// if it was provided to the builder or after it was returned from the database.
func (m *PaymentMutation) ID() (id int, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// IDs queries the database and returns the entity ids that match the mutation's predicate.
// That means, if the mutation is applied within a transaction with an isolation level such
// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated
// or updated by the mutation.
func (m *PaymentMutation) IDs(ctx context.Context) ([]int, error) {
switch {
case m.op.Is(OpUpdateOne | OpDeleteOne):
id, exists := m.ID()
if exists {
return []int{id}, nil
}
fallthrough
case m.op.Is(OpUpdate | OpDelete):
return m.Client().Payment.Query().Where(m.predicates...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
}
}
// SetCardID sets the "card_id" field.
func (m *PaymentMutation) SetCardID(i int) {
m.card = &i
}
// CardID returns the value of the "card_id" field in the mutation.
func (m *PaymentMutation) CardID() (r int, exists bool) {
v := m.card
if v == nil {
return
}
return *v, true
}
// OldCardID returns the old "card_id" field's value of the Payment entity.
// If the Payment object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *PaymentMutation) OldCardID(ctx context.Context) (v int, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldCardID is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldCardID requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldCardID: %w", err)
}
return oldValue.CardID, nil
}
// ResetCardID resets all changes to the "card_id" field.
func (m *PaymentMutation) ResetCardID() {
m.card = nil
}
// SetAmount sets the "amount" field.
func (m *PaymentMutation) SetAmount(f float64) {
m.amount = &f
m.addamount = nil
}
// Amount returns the value of the "amount" field in the mutation.
func (m *PaymentMutation) Amount() (r float64, exists bool) {
v := m.amount
if v == nil {
return
}
return *v, true
}
// OldAmount returns the old "amount" field's value of the Payment entity.
// If the Payment object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *PaymentMutation) OldAmount(ctx context.Context) (v float64, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldAmount is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldAmount requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldAmount: %w", err)
}
return oldValue.Amount, nil
}
// AddAmount adds f to the "amount" field.
func (m *PaymentMutation) 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 *PaymentMutation) 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 *PaymentMutation) ResetAmount() {
m.amount = nil
m.addamount = nil
}
// SetCurrency sets the "currency" field.
func (m *PaymentMutation) SetCurrency(pa payment.Currency) {
m.currency = &pa
}
// Currency returns the value of the "currency" field in the mutation.
func (m *PaymentMutation) Currency() (r payment.Currency, exists bool) {
v := m.currency
if v == nil {
return
}
return *v, true
}
// OldCurrency returns the old "currency" field's value of the Payment entity.
// If the Payment object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *PaymentMutation) OldCurrency(ctx context.Context) (v payment.Currency, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldCurrency is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldCurrency requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldCurrency: %w", err)
}
return oldValue.Currency, nil
}
// ResetCurrency resets all changes to the "currency" field.
func (m *PaymentMutation) ResetCurrency() {
m.currency = nil
}
// SetTime sets the "time" field.
func (m *PaymentMutation) SetTime(t time.Time) {
m.time = &t
}
// Time returns the value of the "time" field in the mutation.
func (m *PaymentMutation) Time() (r time.Time, exists bool) {
v := m.time
if v == nil {
return
}
return *v, true
}
// OldTime returns the old "time" field's value of the Payment entity.
// If the Payment object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *PaymentMutation) OldTime(ctx context.Context) (v time.Time, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldTime is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldTime requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldTime: %w", err)
}
return oldValue.Time, nil
}
// ResetTime resets all changes to the "time" field.
func (m *PaymentMutation) ResetTime() {
m.time = nil
}
// SetDescription sets the "description" field.
func (m *PaymentMutation) SetDescription(s string) {
m.description = &s
}
// Description returns the value of the "description" field in the mutation.
func (m *PaymentMutation) Description() (r string, exists bool) {
v := m.description
if v == nil {
return
}
return *v, true
}
// OldDescription returns the old "description" field's value of the Payment entity.
// If the Payment object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *PaymentMutation) OldDescription(ctx context.Context) (v string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldDescription is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldDescription requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldDescription: %w", err)
}
return oldValue.Description, nil
}
// ResetDescription resets all changes to the "description" field.
func (m *PaymentMutation) ResetDescription() {
m.description = nil
}
// SetStatus sets the "status" field.
func (m *PaymentMutation) SetStatus(pa payment.Status) {
m.status = &pa
}
// Status returns the value of the "status" field in the mutation.
func (m *PaymentMutation) Status() (r payment.Status, exists bool) {
v := m.status
if v == nil {
return
}
return *v, true
}
// OldStatus returns the old "status" field's value of the Payment entity.
// If the Payment object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *PaymentMutation) OldStatus(ctx context.Context) (v payment.Status, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldStatus is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldStatus requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldStatus: %w", err)
}
return oldValue.Status, nil
}
// ResetStatus resets all changes to the "status" field.
func (m *PaymentMutation) ResetStatus() {
m.status = nil
}
// ClearCard clears the "card" edge to the Card entity.
func (m *PaymentMutation) ClearCard() {
m.clearedcard = true
m.clearedFields[payment.FieldCardID] = struct{}{}
}
// CardCleared reports if the "card" edge to the Card entity was cleared.
func (m *PaymentMutation) 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 *PaymentMutation) CardIDs() (ids []int) {
if id := m.card; id != nil {
ids = append(ids, *id)
}
return
}
// ResetCard resets all changes to the "card" edge.
func (m *PaymentMutation) ResetCard() {
m.card = nil
m.clearedcard = false
}
// Where appends a list predicates to the PaymentMutation builder.
func (m *PaymentMutation) Where(ps ...predicate.Payment) {
m.predicates = append(m.predicates, ps...)
}
// WhereP appends storage-level predicates to the PaymentMutation builder. Using this method,
// users can use type-assertion to append predicates that do not depend on any generated package.
func (m *PaymentMutation) 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 *PaymentMutation) Op() Op {
return m.op
}
// SetOp allows setting the mutation operation.
func (m *PaymentMutation) SetOp(op Op) {
m.op = op
}
// Type returns the node type of this mutation (Payment).
func (m *PaymentMutation) 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 *PaymentMutation) Fields() []string {
fields := make([]string, 0, 6)
if m.card != nil {
fields = append(fields, payment.FieldCardID)
}
if m.amount != nil {
fields = append(fields, payment.FieldAmount)
}
if m.currency != nil {
fields = append(fields, payment.FieldCurrency)
}
if m.time != nil {
fields = append(fields, payment.FieldTime)
}
if m.description != nil {
fields = append(fields, payment.FieldDescription)
}
if m.status != nil {
fields = append(fields, payment.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 *PaymentMutation) Field(name string) (ent.Value, bool) {
switch name {
case payment.FieldCardID:
return m.CardID()
case payment.FieldAmount:
return m.Amount()
case payment.FieldCurrency:
return m.Currency()
case payment.FieldTime:
return m.Time()
case payment.FieldDescription:
return m.Description()
case payment.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 *PaymentMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case payment.FieldCardID:
return m.OldCardID(ctx)
case payment.FieldAmount:
return m.OldAmount(ctx)
case payment.FieldCurrency:
return m.OldCurrency(ctx)
case payment.FieldTime:
return m.OldTime(ctx)
case payment.FieldDescription:
return m.OldDescription(ctx)
case payment.FieldStatus:
return m.OldStatus(ctx)
}
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 *PaymentMutation) SetField(name string, value ent.Value) error {
switch name {
case payment.FieldCardID:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetCardID(v)
return nil
case payment.FieldAmount:
v, ok := value.(float64)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetAmount(v)
return nil
case payment.FieldCurrency:
v, ok := value.(payment.Currency)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetCurrency(v)
return nil
case payment.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 payment.FieldDescription:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetDescription(v)
return nil
case payment.FieldStatus:
v, ok := value.(payment.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 *PaymentMutation) AddedFields() []string {
var fields []string
if m.addamount != nil {
fields = append(fields, payment.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 *PaymentMutation) AddedField(name string) (ent.Value, bool) {
switch name {
case payment.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 *PaymentMutation) AddField(name string, value ent.Value) error {
switch name {
case payment.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 *PaymentMutation) ClearedFields() []string {
return nil
}
// FieldCleared returns a boolean indicating if a field with the given name was
// cleared in this mutation.
func (m *PaymentMutation) 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 *PaymentMutation) 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 *PaymentMutation) ResetField(name string) error {
switch name {
case payment.FieldCardID:
m.ResetCardID()
return nil
case payment.FieldAmount:
m.ResetAmount()
return nil
case payment.FieldCurrency:
m.ResetCurrency()
return nil
case payment.FieldTime:
m.ResetTime()
return nil
case payment.FieldDescription:
m.ResetDescription()
return nil
case payment.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 *PaymentMutation) AddedEdges() []string {
edges := make([]string, 0, 1)
if m.card != nil {
edges = append(edges, payment.EdgeCard)
}
return edges
}
// AddedIDs returns all IDs (to other nodes) that were added for the given edge
// name in this mutation.
func (m *PaymentMutation) AddedIDs(name string) []ent.Value {
switch name {
case payment.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 *PaymentMutation) 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 *PaymentMutation) RemovedIDs(name string) []ent.Value {
return nil
}
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *PaymentMutation) ClearedEdges() []string {
edges := make([]string, 0, 1)
if m.clearedcard {
edges = append(edges, payment.EdgeCard)
}
return edges
}
// EdgeCleared returns a boolean which indicates if the edge with the given name
// was cleared in this mutation.
func (m *PaymentMutation) EdgeCleared(name string) bool {
switch name {
case payment.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 *PaymentMutation) ClearEdge(name string) error {
switch name {
case payment.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 *PaymentMutation) ResetEdge(name string) error {
switch name {
case payment.EdgeCard:
m.ResetCard()
return nil
}
return fmt.Errorf("unknown Payment edge %s", name)
}
// PetMutation represents an operation that mutates the Pet nodes in the graph.
type PetMutation struct {
config

View File

@@ -0,0 +1,198 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// 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.loadedTypes[0] {
if e.Card == nil {
// Edge was loaded but was not found.
return nil, &NotFoundError{label: card.Label}
}
return e.Card, nil
}
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 (pa *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)
}
pa.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 {
pa.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 {
pa.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 {
pa.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 {
pa.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 {
pa.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 {
pa.Status = payment.Status(value.String)
}
default:
pa.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 (pa *Payment) Value(name string) (ent.Value, error) {
return pa.selectValues.Get(name)
}
// QueryCard queries the "card" edge of the Payment entity.
func (pa *Payment) QueryCard() *CardQuery {
return NewPaymentClient(pa.config).QueryCard(pa)
}
// 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 (pa *Payment) Update() *PaymentUpdateOne {
return NewPaymentClient(pa.config).UpdateOne(pa)
}
// 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 (pa *Payment) Unwrap() *Payment {
_tx, ok := pa.config.driver.(*txDriver)
if !ok {
panic("ent: Payment is not a transactional entity")
}
pa.config.driver = _tx.drv
return pa
}
// String implements the fmt.Stringer.
func (pa *Payment) String() string {
var builder strings.Builder
builder.WriteString("Payment(")
builder.WriteString(fmt.Sprintf("id=%v, ", pa.ID))
builder.WriteString("card_id=")
builder.WriteString(fmt.Sprintf("%v", pa.CardID))
builder.WriteString(", ")
builder.WriteString("amount=")
builder.WriteString(fmt.Sprintf("%v", pa.Amount))
builder.WriteString(", ")
builder.WriteString("currency=")
builder.WriteString(fmt.Sprintf("%v", pa.Currency))
builder.WriteString(", ")
builder.WriteString("time=")
builder.WriteString(pa.Time.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("description=")
builder.WriteString(pa.Description)
builder.WriteString(", ")
builder.WriteString("status=")
builder.WriteString(fmt.Sprintf("%v", pa.Status))
builder.WriteByte(')')
return builder.String()
}
// Payments is a parsable slice of Payment.
type Payments []*Payment

View File

@@ -0,0 +1,169 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// 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"
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, 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),
)
}

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

View 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 (pc *PaymentCreate) SetCardID(i int) *PaymentCreate {
pc.mutation.SetCardID(i)
return pc
}
// SetAmount sets the "amount" field.
func (pc *PaymentCreate) SetAmount(f float64) *PaymentCreate {
pc.mutation.SetAmount(f)
return pc
}
// SetCurrency sets the "currency" field.
func (pc *PaymentCreate) SetCurrency(pa payment.Currency) *PaymentCreate {
pc.mutation.SetCurrency(pa)
return pc
}
// SetTime sets the "time" field.
func (pc *PaymentCreate) SetTime(t time.Time) *PaymentCreate {
pc.mutation.SetTime(t)
return pc
}
// SetDescription sets the "description" field.
func (pc *PaymentCreate) SetDescription(s string) *PaymentCreate {
pc.mutation.SetDescription(s)
return pc
}
// SetStatus sets the "status" field.
func (pc *PaymentCreate) SetStatus(pa payment.Status) *PaymentCreate {
pc.mutation.SetStatus(pa)
return pc
}
// SetCard sets the "card" edge to the Card entity.
func (pc *PaymentCreate) SetCard(c *Card) *PaymentCreate {
return pc.SetCardID(c.ID)
}
// Mutation returns the PaymentMutation object of the builder.
func (pc *PaymentCreate) Mutation() *PaymentMutation {
return pc.mutation
}
// Save creates the Payment in the database.
func (pc *PaymentCreate) Save(ctx context.Context) (*Payment, error) {
return withHooks(ctx, pc.sqlSave, pc.mutation, pc.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (pc *PaymentCreate) SaveX(ctx context.Context) *Payment {
v, err := pc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (pc *PaymentCreate) Exec(ctx context.Context) error {
_, err := pc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (pc *PaymentCreate) ExecX(ctx context.Context) {
if err := pc.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (pc *PaymentCreate) check() error {
if _, ok := pc.mutation.CardID(); !ok {
return &ValidationError{Name: "card_id", err: errors.New(`ent: missing required field "Payment.card_id"`)}
}
if _, ok := pc.mutation.Amount(); !ok {
return &ValidationError{Name: "amount", err: errors.New(`ent: missing required field "Payment.amount"`)}
}
if v, ok := pc.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 := pc.mutation.Currency(); !ok {
return &ValidationError{Name: "currency", err: errors.New(`ent: missing required field "Payment.currency"`)}
}
if v, ok := pc.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 := pc.mutation.Time(); !ok {
return &ValidationError{Name: "time", err: errors.New(`ent: missing required field "Payment.time"`)}
}
if _, ok := pc.mutation.Description(); !ok {
return &ValidationError{Name: "description", err: errors.New(`ent: missing required field "Payment.description"`)}
}
if _, ok := pc.mutation.Status(); !ok {
return &ValidationError{Name: "status", err: errors.New(`ent: missing required field "Payment.status"`)}
}
if v, ok := pc.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 _, ok := pc.mutation.CardID(); !ok {
return &ValidationError{Name: "card", err: errors.New(`ent: missing required edge "Payment.card"`)}
}
return nil
}
func (pc *PaymentCreate) sqlSave(ctx context.Context) (*Payment, error) {
if err := pc.check(); err != nil {
return nil, err
}
_node, _spec := pc.createSpec()
if err := sqlgraph.CreateNode(ctx, pc.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)
pc.mutation.id = &_node.ID
pc.mutation.done = true
return _node, nil
}
func (pc *PaymentCreate) createSpec() (*Payment, *sqlgraph.CreateSpec) {
var (
_node = &Payment{config: pc.config}
_spec = sqlgraph.NewCreateSpec(payment.Table, sqlgraph.NewFieldSpec(payment.FieldID, field.TypeInt))
)
if value, ok := pc.mutation.Amount(); ok {
_spec.SetField(payment.FieldAmount, field.TypeFloat64, value)
_node.Amount = value
}
if value, ok := pc.mutation.Currency(); ok {
_spec.SetField(payment.FieldCurrency, field.TypeEnum, value)
_node.Currency = value
}
if value, ok := pc.mutation.Time(); ok {
_spec.SetField(payment.FieldTime, field.TypeTime, value)
_node.Time = value
}
if value, ok := pc.mutation.Description(); ok {
_spec.SetField(payment.FieldDescription, field.TypeString, value)
_node.Description = value
}
if value, ok := pc.mutation.Status(); ok {
_spec.SetField(payment.FieldStatus, field.TypeEnum, value)
_node.Status = value
}
if nodes := pc.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 (pcb *PaymentCreateBulk) Save(ctx context.Context) ([]*Payment, error) {
if pcb.err != nil {
return nil, pcb.err
}
specs := make([]*sqlgraph.CreateSpec, len(pcb.builders))
nodes := make([]*Payment, len(pcb.builders))
mutators := make([]Mutator, len(pcb.builders))
for i := range pcb.builders {
func(i int, root context.Context) {
builder := pcb.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, pcb.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, pcb.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, pcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (pcb *PaymentCreateBulk) SaveX(ctx context.Context) []*Payment {
v, err := pcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (pcb *PaymentCreateBulk) Exec(ctx context.Context) error {
_, err := pcb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (pcb *PaymentCreateBulk) ExecX(ctx context.Context) {
if err := pcb.Exec(ctx); err != nil {
panic(err)
}
}

View File

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

View File

@@ -0,0 +1,609 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// 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/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 (pq *PaymentQuery) Where(ps ...predicate.Payment) *PaymentQuery {
pq.predicates = append(pq.predicates, ps...)
return pq
}
// Limit the number of records to be returned by this query.
func (pq *PaymentQuery) Limit(limit int) *PaymentQuery {
pq.ctx.Limit = &limit
return pq
}
// Offset to start from.
func (pq *PaymentQuery) Offset(offset int) *PaymentQuery {
pq.ctx.Offset = &offset
return pq
}
// 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 (pq *PaymentQuery) Unique(unique bool) *PaymentQuery {
pq.ctx.Unique = &unique
return pq
}
// Order specifies how the records should be ordered.
func (pq *PaymentQuery) Order(o ...payment.OrderOption) *PaymentQuery {
pq.order = append(pq.order, o...)
return pq
}
// QueryCard chains the current query on the "card" edge.
func (pq *PaymentQuery) QueryCard() *CardQuery {
query := (&CardClient{config: pq.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := pq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := pq.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(pq.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 (pq *PaymentQuery) First(ctx context.Context) (*Payment, error) {
nodes, err := pq.Limit(1).All(setContextOp(ctx, pq.ctx, "First"))
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 (pq *PaymentQuery) FirstX(ctx context.Context) *Payment {
node, err := pq.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 (pq *PaymentQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = pq.Limit(1).IDs(setContextOp(ctx, pq.ctx, "FirstID")); 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 (pq *PaymentQuery) FirstIDX(ctx context.Context) int {
id, err := pq.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 (pq *PaymentQuery) Only(ctx context.Context) (*Payment, error) {
nodes, err := pq.Limit(2).All(setContextOp(ctx, pq.ctx, "Only"))
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 (pq *PaymentQuery) OnlyX(ctx context.Context) *Payment {
node, err := pq.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 (pq *PaymentQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = pq.Limit(2).IDs(setContextOp(ctx, pq.ctx, "OnlyID")); 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 (pq *PaymentQuery) OnlyIDX(ctx context.Context) int {
id, err := pq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Payments.
func (pq *PaymentQuery) All(ctx context.Context) ([]*Payment, error) {
ctx = setContextOp(ctx, pq.ctx, "All")
if err := pq.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Payment, *PaymentQuery]()
return withInterceptors[[]*Payment](ctx, pq, qr, pq.inters)
}
// AllX is like All, but panics if an error occurs.
func (pq *PaymentQuery) AllX(ctx context.Context) []*Payment {
nodes, err := pq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Payment IDs.
func (pq *PaymentQuery) IDs(ctx context.Context) (ids []int, err error) {
if pq.ctx.Unique == nil && pq.path != nil {
pq.Unique(true)
}
ctx = setContextOp(ctx, pq.ctx, "IDs")
if err = pq.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 (pq *PaymentQuery) IDsX(ctx context.Context) []int {
ids, err := pq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (pq *PaymentQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, pq.ctx, "Count")
if err := pq.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, pq, querierCount[*PaymentQuery](), pq.inters)
}
// CountX is like Count, but panics if an error occurs.
func (pq *PaymentQuery) CountX(ctx context.Context) int {
count, err := pq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (pq *PaymentQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, pq.ctx, "Exist")
switch _, err := pq.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 (pq *PaymentQuery) ExistX(ctx context.Context) bool {
exist, err := pq.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 (pq *PaymentQuery) Clone() *PaymentQuery {
if pq == nil {
return nil
}
return &PaymentQuery{
config: pq.config,
ctx: pq.ctx.Clone(),
order: append([]payment.OrderOption{}, pq.order...),
inters: append([]Interceptor{}, pq.inters...),
predicates: append([]predicate.Payment{}, pq.predicates...),
withCard: pq.withCard.Clone(),
// clone intermediate query.
sql: pq.sql.Clone(),
path: pq.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 (pq *PaymentQuery) WithCard(opts ...func(*CardQuery)) *PaymentQuery {
query := (&CardClient{config: pq.config}).Query()
for _, opt := range opts {
opt(query)
}
pq.withCard = query
return pq
}
// 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 (pq *PaymentQuery) GroupBy(field string, fields ...string) *PaymentGroupBy {
pq.ctx.Fields = append([]string{field}, fields...)
grbuild := &PaymentGroupBy{build: pq}
grbuild.flds = &pq.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 (pq *PaymentQuery) Select(fields ...string) *PaymentSelect {
pq.ctx.Fields = append(pq.ctx.Fields, fields...)
sbuild := &PaymentSelect{PaymentQuery: pq}
sbuild.label = payment.Label
sbuild.flds, sbuild.scan = &pq.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a PaymentSelect configured with the given aggregations.
func (pq *PaymentQuery) Aggregate(fns ...AggregateFunc) *PaymentSelect {
return pq.Select().Aggregate(fns...)
}
func (pq *PaymentQuery) prepareQuery(ctx context.Context) error {
for _, inter := range pq.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, pq); err != nil {
return err
}
}
}
for _, f := range pq.ctx.Fields {
if !payment.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if pq.path != nil {
prev, err := pq.path(ctx)
if err != nil {
return err
}
pq.sql = prev
}
return nil
}
func (pq *PaymentQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Payment, error) {
var (
nodes = []*Payment{}
_spec = pq.querySpec()
loadedTypes = [1]bool{
pq.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: pq.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, pq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := pq.withCard; query != nil {
if err := pq.loadCard(ctx, query, nodes, nil,
func(n *Payment, e *Card) { n.Edges.Card = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (pq *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 (pq *PaymentQuery) sqlCount(ctx context.Context) (int, error) {
_spec := pq.querySpec()
_spec.Node.Columns = pq.ctx.Fields
if len(pq.ctx.Fields) > 0 {
_spec.Unique = pq.ctx.Unique != nil && *pq.ctx.Unique
}
return sqlgraph.CountNodes(ctx, pq.driver, _spec)
}
func (pq *PaymentQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(payment.Table, payment.Columns, sqlgraph.NewFieldSpec(payment.FieldID, field.TypeInt))
_spec.From = pq.sql
if unique := pq.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if pq.path != nil {
_spec.Unique = true
}
if fields := pq.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 pq.withCard != nil {
_spec.Node.AddColumnOnce(payment.FieldCardID)
}
}
if ps := pq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := pq.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := pq.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := pq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (pq *PaymentQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(pq.driver.Dialect())
t1 := builder.Table(payment.Table)
columns := pq.ctx.Fields
if len(columns) == 0 {
columns = payment.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if pq.sql != nil {
selector = pq.sql
selector.Select(selector.Columns(columns...)...)
}
if pq.ctx.Unique != nil && *pq.ctx.Unique {
selector.Distinct()
}
for _, p := range pq.predicates {
p(selector)
}
for _, p := range pq.order {
p(selector)
}
if offset := pq.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 := pq.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 (pgb *PaymentGroupBy) Aggregate(fns ...AggregateFunc) *PaymentGroupBy {
pgb.fns = append(pgb.fns, fns...)
return pgb
}
// Scan applies the selector query and scans the result into the given value.
func (pgb *PaymentGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, pgb.build.ctx, "GroupBy")
if err := pgb.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*PaymentQuery, *PaymentGroupBy](ctx, pgb.build, pgb, pgb.build.inters, v)
}
func (pgb *PaymentGroupBy) sqlScan(ctx context.Context, root *PaymentQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(pgb.fns))
for _, fn := range pgb.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*pgb.flds)+len(pgb.fns))
for _, f := range *pgb.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*pgb.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := pgb.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 (ps *PaymentSelect) Aggregate(fns ...AggregateFunc) *PaymentSelect {
ps.fns = append(ps.fns, fns...)
return ps
}
// Scan applies the selector query and scans the result into the given value.
func (ps *PaymentSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, ps.ctx, "Select")
if err := ps.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*PaymentQuery, *PaymentSelect](ctx, ps.PaymentQuery, ps, ps.inters, v)
}
func (ps *PaymentSelect) sqlScan(ctx context.Context, root *PaymentQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(ps.fns))
for _, fn := range ps.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*ps.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 := ps.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

View 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 (pu *PaymentUpdate) Where(ps ...predicate.Payment) *PaymentUpdate {
pu.mutation.Where(ps...)
return pu
}
// SetCardID sets the "card_id" field.
func (pu *PaymentUpdate) SetCardID(i int) *PaymentUpdate {
pu.mutation.SetCardID(i)
return pu
}
// SetNillableCardID sets the "card_id" field if the given value is not nil.
func (pu *PaymentUpdate) SetNillableCardID(i *int) *PaymentUpdate {
if i != nil {
pu.SetCardID(*i)
}
return pu
}
// SetAmount sets the "amount" field.
func (pu *PaymentUpdate) SetAmount(f float64) *PaymentUpdate {
pu.mutation.ResetAmount()
pu.mutation.SetAmount(f)
return pu
}
// SetNillableAmount sets the "amount" field if the given value is not nil.
func (pu *PaymentUpdate) SetNillableAmount(f *float64) *PaymentUpdate {
if f != nil {
pu.SetAmount(*f)
}
return pu
}
// AddAmount adds f to the "amount" field.
func (pu *PaymentUpdate) AddAmount(f float64) *PaymentUpdate {
pu.mutation.AddAmount(f)
return pu
}
// SetCurrency sets the "currency" field.
func (pu *PaymentUpdate) SetCurrency(pa payment.Currency) *PaymentUpdate {
pu.mutation.SetCurrency(pa)
return pu
}
// SetNillableCurrency sets the "currency" field if the given value is not nil.
func (pu *PaymentUpdate) SetNillableCurrency(pa *payment.Currency) *PaymentUpdate {
if pa != nil {
pu.SetCurrency(*pa)
}
return pu
}
// SetTime sets the "time" field.
func (pu *PaymentUpdate) SetTime(t time.Time) *PaymentUpdate {
pu.mutation.SetTime(t)
return pu
}
// SetNillableTime sets the "time" field if the given value is not nil.
func (pu *PaymentUpdate) SetNillableTime(t *time.Time) *PaymentUpdate {
if t != nil {
pu.SetTime(*t)
}
return pu
}
// SetDescription sets the "description" field.
func (pu *PaymentUpdate) SetDescription(s string) *PaymentUpdate {
pu.mutation.SetDescription(s)
return pu
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (pu *PaymentUpdate) SetNillableDescription(s *string) *PaymentUpdate {
if s != nil {
pu.SetDescription(*s)
}
return pu
}
// SetStatus sets the "status" field.
func (pu *PaymentUpdate) SetStatus(pa payment.Status) *PaymentUpdate {
pu.mutation.SetStatus(pa)
return pu
}
// SetNillableStatus sets the "status" field if the given value is not nil.
func (pu *PaymentUpdate) SetNillableStatus(pa *payment.Status) *PaymentUpdate {
if pa != nil {
pu.SetStatus(*pa)
}
return pu
}
// SetCard sets the "card" edge to the Card entity.
func (pu *PaymentUpdate) SetCard(c *Card) *PaymentUpdate {
return pu.SetCardID(c.ID)
}
// Mutation returns the PaymentMutation object of the builder.
func (pu *PaymentUpdate) Mutation() *PaymentMutation {
return pu.mutation
}
// ClearCard clears the "card" edge to the Card entity.
func (pu *PaymentUpdate) ClearCard() *PaymentUpdate {
pu.mutation.ClearCard()
return pu
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (pu *PaymentUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, pu.sqlSave, pu.mutation, pu.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (pu *PaymentUpdate) SaveX(ctx context.Context) int {
affected, err := pu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (pu *PaymentUpdate) Exec(ctx context.Context) error {
_, err := pu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (pu *PaymentUpdate) ExecX(ctx context.Context) {
if err := pu.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (pu *PaymentUpdate) check() error {
if v, ok := pu.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 := pu.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 := pu.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 _, ok := pu.mutation.CardID(); pu.mutation.CardCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "Payment.card"`)
}
return nil
}
func (pu *PaymentUpdate) sqlSave(ctx context.Context) (n int, err error) {
if err := pu.check(); err != nil {
return n, err
}
_spec := sqlgraph.NewUpdateSpec(payment.Table, payment.Columns, sqlgraph.NewFieldSpec(payment.FieldID, field.TypeInt))
if ps := pu.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := pu.mutation.Amount(); ok {
_spec.SetField(payment.FieldAmount, field.TypeFloat64, value)
}
if value, ok := pu.mutation.AddedAmount(); ok {
_spec.AddField(payment.FieldAmount, field.TypeFloat64, value)
}
if value, ok := pu.mutation.Currency(); ok {
_spec.SetField(payment.FieldCurrency, field.TypeEnum, value)
}
if value, ok := pu.mutation.Time(); ok {
_spec.SetField(payment.FieldTime, field.TypeTime, value)
}
if value, ok := pu.mutation.Description(); ok {
_spec.SetField(payment.FieldDescription, field.TypeString, value)
}
if value, ok := pu.mutation.Status(); ok {
_spec.SetField(payment.FieldStatus, field.TypeEnum, value)
}
if pu.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 := pu.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 n, err = sqlgraph.UpdateNodes(ctx, pu.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
}
pu.mutation.done = true
return n, 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 (puo *PaymentUpdateOne) SetCardID(i int) *PaymentUpdateOne {
puo.mutation.SetCardID(i)
return puo
}
// SetNillableCardID sets the "card_id" field if the given value is not nil.
func (puo *PaymentUpdateOne) SetNillableCardID(i *int) *PaymentUpdateOne {
if i != nil {
puo.SetCardID(*i)
}
return puo
}
// SetAmount sets the "amount" field.
func (puo *PaymentUpdateOne) SetAmount(f float64) *PaymentUpdateOne {
puo.mutation.ResetAmount()
puo.mutation.SetAmount(f)
return puo
}
// SetNillableAmount sets the "amount" field if the given value is not nil.
func (puo *PaymentUpdateOne) SetNillableAmount(f *float64) *PaymentUpdateOne {
if f != nil {
puo.SetAmount(*f)
}
return puo
}
// AddAmount adds f to the "amount" field.
func (puo *PaymentUpdateOne) AddAmount(f float64) *PaymentUpdateOne {
puo.mutation.AddAmount(f)
return puo
}
// SetCurrency sets the "currency" field.
func (puo *PaymentUpdateOne) SetCurrency(pa payment.Currency) *PaymentUpdateOne {
puo.mutation.SetCurrency(pa)
return puo
}
// SetNillableCurrency sets the "currency" field if the given value is not nil.
func (puo *PaymentUpdateOne) SetNillableCurrency(pa *payment.Currency) *PaymentUpdateOne {
if pa != nil {
puo.SetCurrency(*pa)
}
return puo
}
// SetTime sets the "time" field.
func (puo *PaymentUpdateOne) SetTime(t time.Time) *PaymentUpdateOne {
puo.mutation.SetTime(t)
return puo
}
// SetNillableTime sets the "time" field if the given value is not nil.
func (puo *PaymentUpdateOne) SetNillableTime(t *time.Time) *PaymentUpdateOne {
if t != nil {
puo.SetTime(*t)
}
return puo
}
// SetDescription sets the "description" field.
func (puo *PaymentUpdateOne) SetDescription(s string) *PaymentUpdateOne {
puo.mutation.SetDescription(s)
return puo
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (puo *PaymentUpdateOne) SetNillableDescription(s *string) *PaymentUpdateOne {
if s != nil {
puo.SetDescription(*s)
}
return puo
}
// SetStatus sets the "status" field.
func (puo *PaymentUpdateOne) SetStatus(pa payment.Status) *PaymentUpdateOne {
puo.mutation.SetStatus(pa)
return puo
}
// SetNillableStatus sets the "status" field if the given value is not nil.
func (puo *PaymentUpdateOne) SetNillableStatus(pa *payment.Status) *PaymentUpdateOne {
if pa != nil {
puo.SetStatus(*pa)
}
return puo
}
// SetCard sets the "card" edge to the Card entity.
func (puo *PaymentUpdateOne) SetCard(c *Card) *PaymentUpdateOne {
return puo.SetCardID(c.ID)
}
// Mutation returns the PaymentMutation object of the builder.
func (puo *PaymentUpdateOne) Mutation() *PaymentMutation {
return puo.mutation
}
// ClearCard clears the "card" edge to the Card entity.
func (puo *PaymentUpdateOne) ClearCard() *PaymentUpdateOne {
puo.mutation.ClearCard()
return puo
}
// Where appends a list predicates to the PaymentUpdate builder.
func (puo *PaymentUpdateOne) Where(ps ...predicate.Payment) *PaymentUpdateOne {
puo.mutation.Where(ps...)
return puo
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (puo *PaymentUpdateOne) Select(field string, fields ...string) *PaymentUpdateOne {
puo.fields = append([]string{field}, fields...)
return puo
}
// Save executes the query and returns the updated Payment entity.
func (puo *PaymentUpdateOne) Save(ctx context.Context) (*Payment, error) {
return withHooks(ctx, puo.sqlSave, puo.mutation, puo.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (puo *PaymentUpdateOne) SaveX(ctx context.Context) *Payment {
node, err := puo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (puo *PaymentUpdateOne) Exec(ctx context.Context) error {
_, err := puo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (puo *PaymentUpdateOne) ExecX(ctx context.Context) {
if err := puo.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (puo *PaymentUpdateOne) check() error {
if v, ok := puo.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 := puo.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 := puo.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 _, ok := puo.mutation.CardID(); puo.mutation.CardCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "Payment.card"`)
}
return nil
}
func (puo *PaymentUpdateOne) sqlSave(ctx context.Context) (_node *Payment, err error) {
if err := puo.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(payment.Table, payment.Columns, sqlgraph.NewFieldSpec(payment.FieldID, field.TypeInt))
id, ok := puo.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 := puo.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 := puo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := puo.mutation.Amount(); ok {
_spec.SetField(payment.FieldAmount, field.TypeFloat64, value)
}
if value, ok := puo.mutation.AddedAmount(); ok {
_spec.AddField(payment.FieldAmount, field.TypeFloat64, value)
}
if value, ok := puo.mutation.Currency(); ok {
_spec.SetField(payment.FieldCurrency, field.TypeEnum, value)
}
if value, ok := puo.mutation.Time(); ok {
_spec.SetField(payment.FieldTime, field.TypeTime, value)
}
if value, ok := puo.mutation.Description(); ok {
_spec.SetField(payment.FieldDescription, field.TypeString, value)
}
if value, ok := puo.mutation.Status(); ok {
_spec.SetField(payment.FieldStatus, field.TypeEnum, value)
}
if puo.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 := puo.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: puo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, puo.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
}
puo.mutation.done = true
return _node, nil
}

View File

@@ -13,6 +13,9 @@ import (
// 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)

View File

@@ -8,6 +8,7 @@ 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"
"github.com/google/uuid"
@@ -23,6 +24,12 @@ func init() {
cardDescOwnerID := cardFields[1].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.

View File

@@ -34,6 +34,7 @@ func (Card) Edges() []ent.Edge {
Unique().
Required().
Field("owner_id"),
edge.To("payments", Payment.Type),
}
}

View 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", "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)",
}),
}
}

View File

@@ -18,6 +18,8 @@ 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
// User is the client for interacting with the User builders.
@@ -154,6 +156,7 @@ func (tx *Tx) Client() *Client {
func (tx *Tx) init() {
tx.Card = NewCardClient(tx.config)
tx.Payment = NewPaymentClient(tx.config)
tx.Pet = NewPetClient(tx.config)
tx.User = NewUserClient(tx.config)
}