examples/jsonencode: skip nodes without edges in template (#3187)

This commit is contained in:
Ariel Mashraki
2022-12-21 15:43:51 +02:00
committed by GitHub
parent 92bacc10e4
commit 33478c5fca
18 changed files with 1865 additions and 24 deletions

View File

@@ -0,0 +1,103 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/examples/jsonencode/ent/card"
)
// Card is the model entity for the Card schema.
type Card struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Number holds the value of the "number" field.
Number string `json:"number,omitempty"`
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Card) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case card.FieldID:
values[i] = new(sql.NullInt64)
case card.FieldNumber:
values[i] = new(sql.NullString)
default:
return nil, fmt.Errorf("unexpected column %q for type Card", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Card fields.
func (c *Card) assignValues(columns []string, values []any) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case card.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
c.ID = int(value.Int64)
case card.FieldNumber:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field number", values[i])
} else if value.Valid {
c.Number = value.String
}
}
}
return nil
}
// Update returns a builder for updating this Card.
// Note that you need to call Card.Unwrap() before calling this method if this Card
// was returned from a transaction, and the transaction was committed or rolled back.
func (c *Card) Update() *CardUpdateOne {
return (&CardClient{config: c.config}).UpdateOne(c)
}
// Unwrap unwraps the Card entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (c *Card) Unwrap() *Card {
_tx, ok := c.config.driver.(*txDriver)
if !ok {
panic("ent: Card is not a transactional entity")
}
c.config.driver = _tx.drv
return c
}
// String implements the fmt.Stringer.
func (c *Card) String() string {
var builder strings.Builder
builder.WriteString("Card(")
builder.WriteString(fmt.Sprintf("id=%v, ", c.ID))
builder.WriteString("number=")
builder.WriteString(c.Number)
builder.WriteByte(')')
return builder.String()
}
// Cards is a parsable slice of Card.
type Cards []*Card
func (c Cards) config(cfg config) {
for _i := range c {
c[_i].config = cfg
}
}

View File

@@ -0,0 +1,34 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package card
const (
// Label holds the string label denoting the card type in the database.
Label = "card"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldNumber holds the string denoting the number field in the database.
FieldNumber = "number"
// Table holds the table name of the card in the database.
Table = "cards"
)
// Columns holds all SQL columns for card fields.
var Columns = []string{
FieldID,
FieldNumber,
}
// 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
}

View File

@@ -0,0 +1,159 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package card
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/examples/jsonencode/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Card {
return predicate.Card(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Card {
return predicate.Card(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Card {
return predicate.Card(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Card {
return predicate.Card(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Card {
return predicate.Card(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Card {
return predicate.Card(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Card {
return predicate.Card(sql.FieldLTE(FieldID, id))
}
// Number applies equality check predicate on the "number" field. It's identical to NumberEQ.
func Number(v string) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldNumber, v))
}
// NumberEQ applies the EQ predicate on the "number" field.
func NumberEQ(v string) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldNumber, v))
}
// NumberNEQ applies the NEQ predicate on the "number" field.
func NumberNEQ(v string) predicate.Card {
return predicate.Card(sql.FieldNEQ(FieldNumber, v))
}
// NumberIn applies the In predicate on the "number" field.
func NumberIn(vs ...string) predicate.Card {
return predicate.Card(sql.FieldIn(FieldNumber, vs...))
}
// NumberNotIn applies the NotIn predicate on the "number" field.
func NumberNotIn(vs ...string) predicate.Card {
return predicate.Card(sql.FieldNotIn(FieldNumber, vs...))
}
// NumberGT applies the GT predicate on the "number" field.
func NumberGT(v string) predicate.Card {
return predicate.Card(sql.FieldGT(FieldNumber, v))
}
// NumberGTE applies the GTE predicate on the "number" field.
func NumberGTE(v string) predicate.Card {
return predicate.Card(sql.FieldGTE(FieldNumber, v))
}
// NumberLT applies the LT predicate on the "number" field.
func NumberLT(v string) predicate.Card {
return predicate.Card(sql.FieldLT(FieldNumber, v))
}
// NumberLTE applies the LTE predicate on the "number" field.
func NumberLTE(v string) predicate.Card {
return predicate.Card(sql.FieldLTE(FieldNumber, v))
}
// NumberContains applies the Contains predicate on the "number" field.
func NumberContains(v string) predicate.Card {
return predicate.Card(sql.FieldContains(FieldNumber, v))
}
// NumberHasPrefix applies the HasPrefix predicate on the "number" field.
func NumberHasPrefix(v string) predicate.Card {
return predicate.Card(sql.FieldHasPrefix(FieldNumber, v))
}
// NumberHasSuffix applies the HasSuffix predicate on the "number" field.
func NumberHasSuffix(v string) predicate.Card {
return predicate.Card(sql.FieldHasSuffix(FieldNumber, v))
}
// NumberEqualFold applies the EqualFold predicate on the "number" field.
func NumberEqualFold(v string) predicate.Card {
return predicate.Card(sql.FieldEqualFold(FieldNumber, v))
}
// NumberContainsFold applies the ContainsFold predicate on the "number" field.
func NumberContainsFold(v string) predicate.Card {
return predicate.Card(sql.FieldContainsFold(FieldNumber, v))
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Card) predicate.Card {
return predicate.Card(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for _, p := range predicates {
p(s1)
}
s.Where(s1.P())
})
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Card) predicate.Card {
return predicate.Card(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for i, p := range predicates {
if i > 0 {
s1.Or()
}
p(s1)
}
s.Where(s1.P())
})
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Card) predicate.Card {
return predicate.Card(func(s *sql.Selector) {
p(s.Not())
})
}

View File

@@ -0,0 +1,189 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/examples/jsonencode/ent/card"
"entgo.io/ent/schema/field"
)
// CardCreate is the builder for creating a Card entity.
type CardCreate struct {
config
mutation *CardMutation
hooks []Hook
}
// SetNumber sets the "number" field.
func (cc *CardCreate) SetNumber(s string) *CardCreate {
cc.mutation.SetNumber(s)
return cc
}
// Mutation returns the CardMutation object of the builder.
func (cc *CardCreate) Mutation() *CardMutation {
return cc.mutation
}
// Save creates the Card in the database.
func (cc *CardCreate) Save(ctx context.Context) (*Card, error) {
return withHooks[*Card, CardMutation](ctx, cc.sqlSave, cc.mutation, cc.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (cc *CardCreate) SaveX(ctx context.Context) *Card {
v, err := cc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (cc *CardCreate) Exec(ctx context.Context) error {
_, err := cc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (cc *CardCreate) ExecX(ctx context.Context) {
if err := cc.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (cc *CardCreate) check() error {
if _, ok := cc.mutation.Number(); !ok {
return &ValidationError{Name: "number", err: errors.New(`ent: missing required field "Card.number"`)}
}
return nil
}
func (cc *CardCreate) sqlSave(ctx context.Context) (*Card, error) {
if err := cc.check(); err != nil {
return nil, err
}
_node, _spec := cc.createSpec()
if err := sqlgraph.CreateNode(ctx, cc.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)
cc.mutation.id = &_node.ID
cc.mutation.done = true
return _node, nil
}
func (cc *CardCreate) createSpec() (*Card, *sqlgraph.CreateSpec) {
var (
_node = &Card{config: cc.config}
_spec = &sqlgraph.CreateSpec{
Table: card.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: card.FieldID,
},
}
)
if value, ok := cc.mutation.Number(); ok {
_spec.SetField(card.FieldNumber, field.TypeString, value)
_node.Number = value
}
return _node, _spec
}
// CardCreateBulk is the builder for creating many Card entities in bulk.
type CardCreateBulk struct {
config
builders []*CardCreate
}
// Save creates the Card entities in the database.
func (ccb *CardCreateBulk) Save(ctx context.Context) ([]*Card, error) {
specs := make([]*sqlgraph.CreateSpec, len(ccb.builders))
nodes := make([]*Card, len(ccb.builders))
mutators := make([]Mutator, len(ccb.builders))
for i := range ccb.builders {
func(i int, root context.Context) {
builder := ccb.builders[i]
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*CardMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, ccb.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, ccb.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, ccb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (ccb *CardCreateBulk) SaveX(ctx context.Context) []*Card {
v, err := ccb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (ccb *CardCreateBulk) Exec(ctx context.Context) error {
_, err := ccb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (ccb *CardCreateBulk) ExecX(ctx context.Context) {
if err := ccb.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/jsonencode/ent/card"
"entgo.io/ent/examples/jsonencode/ent/predicate"
"entgo.io/ent/schema/field"
)
// CardDelete is the builder for deleting a Card entity.
type CardDelete struct {
config
hooks []Hook
mutation *CardMutation
}
// Where appends a list predicates to the CardDelete builder.
func (cd *CardDelete) Where(ps ...predicate.Card) *CardDelete {
cd.mutation.Where(ps...)
return cd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (cd *CardDelete) Exec(ctx context.Context) (int, error) {
return withHooks[int, CardMutation](ctx, cd.sqlExec, cd.mutation, cd.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (cd *CardDelete) ExecX(ctx context.Context) int {
n, err := cd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (cd *CardDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: card.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: card.FieldID,
},
},
}
if ps := cd.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, cd.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
cd.mutation.done = true
return affected, err
}
// CardDeleteOne is the builder for deleting a single Card entity.
type CardDeleteOne struct {
cd *CardDelete
}
// Exec executes the deletion query.
func (cdo *CardDeleteOne) Exec(ctx context.Context) error {
n, err := cdo.cd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{card.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (cdo *CardDeleteOne) ExecX(ctx context.Context) {
cdo.cd.ExecX(ctx)
}

View File

@@ -0,0 +1,540 @@
// 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/jsonencode/ent/card"
"entgo.io/ent/examples/jsonencode/ent/predicate"
"entgo.io/ent/schema/field"
)
// CardQuery is the builder for querying Card entities.
type CardQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
inters []Interceptor
predicates []predicate.Card
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the CardQuery builder.
func (cq *CardQuery) Where(ps ...predicate.Card) *CardQuery {
cq.predicates = append(cq.predicates, ps...)
return cq
}
// Limit the number of records to be returned by this query.
func (cq *CardQuery) Limit(limit int) *CardQuery {
cq.limit = &limit
return cq
}
// Offset to start from.
func (cq *CardQuery) Offset(offset int) *CardQuery {
cq.offset = &offset
return cq
}
// 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 (cq *CardQuery) Unique(unique bool) *CardQuery {
cq.unique = &unique
return cq
}
// Order specifies how the records should be ordered.
func (cq *CardQuery) Order(o ...OrderFunc) *CardQuery {
cq.order = append(cq.order, o...)
return cq
}
// 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) {
nodes, err := cq.Limit(1).All(newQueryContext(ctx, TypeCard, "First"))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{card.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (cq *CardQuery) FirstX(ctx context.Context) *Card {
node, err := cq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Card ID from the query.
// Returns a *NotFoundError when no Card ID was found.
func (cq *CardQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = cq.Limit(1).IDs(newQueryContext(ctx, TypeCard, "FirstID")); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{card.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (cq *CardQuery) FirstIDX(ctx context.Context) int {
id, err := cq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Card entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Card entity is found.
// Returns a *NotFoundError when no Card entities are found.
func (cq *CardQuery) Only(ctx context.Context) (*Card, error) {
nodes, err := cq.Limit(2).All(newQueryContext(ctx, TypeCard, "Only"))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{card.Label}
default:
return nil, &NotSingularError{card.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (cq *CardQuery) OnlyX(ctx context.Context) *Card {
node, err := cq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Card ID in the query.
// Returns a *NotSingularError when more than one Card ID is found.
// Returns a *NotFoundError when no entities are found.
func (cq *CardQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = cq.Limit(2).IDs(newQueryContext(ctx, TypeCard, "OnlyID")); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{card.Label}
default:
err = &NotSingularError{card.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (cq *CardQuery) OnlyIDX(ctx context.Context) int {
id, err := cq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Cards.
func (cq *CardQuery) All(ctx context.Context) ([]*Card, error) {
ctx = newQueryContext(ctx, TypeCard, "All")
if err := cq.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Card, *CardQuery]()
return withInterceptors[[]*Card](ctx, cq, qr, cq.inters)
}
// AllX is like All, but panics if an error occurs.
func (cq *CardQuery) AllX(ctx context.Context) []*Card {
nodes, err := cq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Card IDs.
func (cq *CardQuery) IDs(ctx context.Context) ([]int, error) {
var ids []int
ctx = newQueryContext(ctx, TypeCard, "IDs")
if err := cq.Select(card.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (cq *CardQuery) IDsX(ctx context.Context) []int {
ids, err := cq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (cq *CardQuery) Count(ctx context.Context) (int, error) {
ctx = newQueryContext(ctx, TypeCard, "Count")
if err := cq.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, cq, querierCount[*CardQuery](), cq.inters)
}
// CountX is like Count, but panics if an error occurs.
func (cq *CardQuery) CountX(ctx context.Context) int {
count, err := cq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (cq *CardQuery) Exist(ctx context.Context) (bool, error) {
ctx = newQueryContext(ctx, TypeCard, "Exist")
switch _, err := cq.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 (cq *CardQuery) ExistX(ctx context.Context) bool {
exist, err := cq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the CardQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (cq *CardQuery) Clone() *CardQuery {
if cq == nil {
return nil
}
return &CardQuery{
config: cq.config,
limit: cq.limit,
offset: cq.offset,
order: append([]OrderFunc{}, cq.order...),
predicates: append([]predicate.Card{}, cq.predicates...),
// clone intermediate query.
sql: cq.sql.Clone(),
path: cq.path,
unique: cq.unique,
}
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// Number string `json:"number,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Card.Query().
// GroupBy(card.FieldNumber).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (cq *CardQuery) GroupBy(field string, fields ...string) *CardGroupBy {
cq.fields = append([]string{field}, fields...)
grbuild := &CardGroupBy{build: cq}
grbuild.flds = &cq.fields
grbuild.label = card.Label
grbuild.scan = grbuild.Scan
return grbuild
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// Number string `json:"number,omitempty"`
// }
//
// client.Card.Query().
// Select(card.FieldNumber).
// Scan(ctx, &v)
func (cq *CardQuery) Select(fields ...string) *CardSelect {
cq.fields = append(cq.fields, fields...)
sbuild := &CardSelect{CardQuery: cq}
sbuild.label = card.Label
sbuild.flds, sbuild.scan = &cq.fields, sbuild.Scan
return sbuild
}
// Aggregate returns a CardSelect configured with the given aggregations.
func (cq *CardQuery) Aggregate(fns ...AggregateFunc) *CardSelect {
return cq.Select().Aggregate(fns...)
}
func (cq *CardQuery) prepareQuery(ctx context.Context) error {
for _, inter := range cq.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, cq); err != nil {
return err
}
}
}
for _, f := range cq.fields {
if !card.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if cq.path != nil {
prev, err := cq.path(ctx)
if err != nil {
return err
}
cq.sql = prev
}
return nil
}
func (cq *CardQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Card, error) {
var (
nodes = []*Card{}
_spec = cq.querySpec()
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Card).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Card{config: cq.config}
nodes = append(nodes, node)
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, cq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (cq *CardQuery) sqlCount(ctx context.Context) (int, error) {
_spec := cq.querySpec()
_spec.Node.Columns = cq.fields
if len(cq.fields) > 0 {
_spec.Unique = cq.unique != nil && *cq.unique
}
return sqlgraph.CountNodes(ctx, cq.driver, _spec)
}
func (cq *CardQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: card.Table,
Columns: card.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: card.FieldID,
},
},
From: cq.sql,
Unique: true,
}
if unique := cq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := cq.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, card.FieldID)
for i := range fields {
if fields[i] != card.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := cq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := cq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := cq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := cq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (cq *CardQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(cq.driver.Dialect())
t1 := builder.Table(card.Table)
columns := cq.fields
if len(columns) == 0 {
columns = card.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if cq.sql != nil {
selector = cq.sql
selector.Select(selector.Columns(columns...)...)
}
if cq.unique != nil && *cq.unique {
selector.Distinct()
}
for _, p := range cq.predicates {
p(selector)
}
for _, p := range cq.order {
p(selector)
}
if offset := cq.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 := cq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// CardGroupBy is the group-by builder for Card entities.
type CardGroupBy struct {
selector
build *CardQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (cgb *CardGroupBy) Aggregate(fns ...AggregateFunc) *CardGroupBy {
cgb.fns = append(cgb.fns, fns...)
return cgb
}
// Scan applies the selector query and scans the result into the given value.
func (cgb *CardGroupBy) Scan(ctx context.Context, v any) error {
ctx = newQueryContext(ctx, TypeCard, "GroupBy")
if err := cgb.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*CardQuery, *CardGroupBy](ctx, cgb.build, cgb, cgb.build.inters, v)
}
func (cgb *CardGroupBy) sqlScan(ctx context.Context, root *CardQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(cgb.fns))
for _, fn := range cgb.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*cgb.flds)+len(cgb.fns))
for _, f := range *cgb.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*cgb.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := cgb.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// CardSelect is the builder for selecting fields of Card entities.
type CardSelect struct {
*CardQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (cs *CardSelect) Aggregate(fns ...AggregateFunc) *CardSelect {
cs.fns = append(cs.fns, fns...)
return cs
}
// Scan applies the selector query and scans the result into the given value.
func (cs *CardSelect) Scan(ctx context.Context, v any) error {
ctx = newQueryContext(ctx, TypeCard, "Select")
if err := cs.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*CardQuery, *CardSelect](ctx, cs.CardQuery, cs, cs.inters, v)
}
func (cs *CardSelect) sqlScan(ctx context.Context, root *CardQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(cs.fns))
for _, fn := range cs.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*cs.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 := cs.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

View File

@@ -0,0 +1,209 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/examples/jsonencode/ent/card"
"entgo.io/ent/examples/jsonencode/ent/predicate"
"entgo.io/ent/schema/field"
)
// CardUpdate is the builder for updating Card entities.
type CardUpdate struct {
config
hooks []Hook
mutation *CardMutation
}
// Where appends a list predicates to the CardUpdate builder.
func (cu *CardUpdate) Where(ps ...predicate.Card) *CardUpdate {
cu.mutation.Where(ps...)
return cu
}
// SetNumber sets the "number" field.
func (cu *CardUpdate) SetNumber(s string) *CardUpdate {
cu.mutation.SetNumber(s)
return cu
}
// Mutation returns the CardMutation object of the builder.
func (cu *CardUpdate) Mutation() *CardMutation {
return cu.mutation
}
// 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[int, CardMutation](ctx, cu.sqlSave, cu.mutation, cu.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (cu *CardUpdate) SaveX(ctx context.Context) int {
affected, err := cu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (cu *CardUpdate) Exec(ctx context.Context) error {
_, err := cu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (cu *CardUpdate) ExecX(ctx context.Context) {
if err := cu.Exec(ctx); err != nil {
panic(err)
}
}
func (cu *CardUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: card.Table,
Columns: card.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: card.FieldID,
},
},
}
if ps := cu.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := cu.mutation.Number(); ok {
_spec.SetField(card.FieldNumber, field.TypeString, value)
}
if n, err = sqlgraph.UpdateNodes(ctx, cu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{card.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
cu.mutation.done = true
return n, nil
}
// CardUpdateOne is the builder for updating a single Card entity.
type CardUpdateOne struct {
config
fields []string
hooks []Hook
mutation *CardMutation
}
// SetNumber sets the "number" field.
func (cuo *CardUpdateOne) SetNumber(s string) *CardUpdateOne {
cuo.mutation.SetNumber(s)
return cuo
}
// Mutation returns the CardMutation object of the builder.
func (cuo *CardUpdateOne) Mutation() *CardMutation {
return cuo.mutation
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (cuo *CardUpdateOne) Select(field string, fields ...string) *CardUpdateOne {
cuo.fields = append([]string{field}, fields...)
return cuo
}
// Save executes the query and returns the updated Card entity.
func (cuo *CardUpdateOne) Save(ctx context.Context) (*Card, error) {
return withHooks[*Card, CardMutation](ctx, cuo.sqlSave, cuo.mutation, cuo.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (cuo *CardUpdateOne) SaveX(ctx context.Context) *Card {
node, err := cuo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (cuo *CardUpdateOne) Exec(ctx context.Context) error {
_, err := cuo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (cuo *CardUpdateOne) ExecX(ctx context.Context) {
if err := cuo.Exec(ctx); err != nil {
panic(err)
}
}
func (cuo *CardUpdateOne) sqlSave(ctx context.Context) (_node *Card, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: card.Table,
Columns: card.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: card.FieldID,
},
},
}
id, ok := cuo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Card.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := cuo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, card.FieldID)
for _, f := range fields {
if !card.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != card.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := cuo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := cuo.mutation.Number(); ok {
_spec.SetField(card.FieldNumber, field.TypeString, value)
}
_node = &Card{config: cuo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, cuo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{card.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
cuo.mutation.done = true
return _node, nil
}

View File

@@ -14,6 +14,7 @@ import (
"entgo.io/ent/examples/jsonencode/ent/migrate"
"entgo.io/ent/examples/jsonencode/ent/card"
"entgo.io/ent/examples/jsonencode/ent/pet"
"entgo.io/ent/examples/jsonencode/ent/user"
@@ -27,6 +28,8 @@ type Client struct {
config
// Schema is the client for creating, migrating and dropping schema.
Schema *migrate.Schema
// Card is the client for interacting with the Card builders.
Card *CardClient
// Pet is the client for interacting with the Pet builders.
Pet *PetClient
// User is the client for interacting with the User builders.
@@ -44,6 +47,7 @@ func NewClient(opts ...Option) *Client {
func (c *Client) init() {
c.Schema = migrate.NewSchema(c.driver)
c.Card = NewCardClient(c.config)
c.Pet = NewPetClient(c.config)
c.User = NewUserClient(c.config)
}
@@ -79,6 +83,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) {
return &Tx{
ctx: ctx,
config: cfg,
Card: NewCardClient(cfg),
Pet: NewPetClient(cfg),
User: NewUserClient(cfg),
}, nil
@@ -100,6 +105,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
return &Tx{
ctx: ctx,
config: cfg,
Card: NewCardClient(cfg),
Pet: NewPetClient(cfg),
User: NewUserClient(cfg),
}, nil
@@ -108,7 +114,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
//
// client.Debug().
// Pet.
// Card.
// Query().
// Count(ctx)
func (c *Client) Debug() *Client {
@@ -130,6 +136,7 @@ func (c *Client) Close() error {
// Use adds the mutation hooks to all the entity clients.
// In order to add hooks to a specific client, call: `client.Node.Use(...)`.
func (c *Client) Use(hooks ...Hook) {
c.Card.Use(hooks...)
c.Pet.Use(hooks...)
c.User.Use(hooks...)
}
@@ -137,6 +144,7 @@ func (c *Client) Use(hooks ...Hook) {
// Intercept adds the query interceptors to all the entity clients.
// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`.
func (c *Client) Intercept(interceptors ...Interceptor) {
c.Card.Intercept(interceptors...)
c.Pet.Intercept(interceptors...)
c.User.Intercept(interceptors...)
}
@@ -144,6 +152,8 @@ func (c *Client) Intercept(interceptors ...Interceptor) {
// Mutate implements the ent.Mutator interface.
func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
switch m := m.(type) {
case *CardMutation:
return c.Card.mutate(ctx, m)
case *PetMutation:
return c.Pet.mutate(ctx, m)
case *UserMutation:
@@ -153,6 +163,123 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
}
}
// CardClient is a client for the Card schema.
type CardClient struct {
config
}
// NewCardClient returns a client for the Card from the given config.
func NewCardClient(c config) *CardClient {
return &CardClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `card.Hooks(f(g(h())))`.
func (c *CardClient) Use(hooks ...Hook) {
c.hooks.Card = append(c.hooks.Card, hooks...)
}
// Use adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `card.Intercept(f(g(h())))`.
func (c *CardClient) Intercept(interceptors ...Interceptor) {
c.inters.Card = append(c.inters.Card, interceptors...)
}
// Create returns a builder for creating a Card entity.
func (c *CardClient) Create() *CardCreate {
mutation := newCardMutation(c.config, OpCreate)
return &CardCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Card entities.
func (c *CardClient) CreateBulk(builders ...*CardCreate) *CardCreateBulk {
return &CardCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Card.
func (c *CardClient) Update() *CardUpdate {
mutation := newCardMutation(c.config, OpUpdate)
return &CardUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *CardClient) UpdateOne(ca *Card) *CardUpdateOne {
mutation := newCardMutation(c.config, OpUpdateOne, withCard(ca))
return &CardUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *CardClient) UpdateOneID(id int) *CardUpdateOne {
mutation := newCardMutation(c.config, OpUpdateOne, withCardID(id))
return &CardUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Card.
func (c *CardClient) Delete() *CardDelete {
mutation := newCardMutation(c.config, OpDelete)
return &CardDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *CardClient) DeleteOne(ca *Card) *CardDeleteOne {
return c.DeleteOneID(ca.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *CardClient) DeleteOneID(id int) *CardDeleteOne {
builder := c.Delete().Where(card.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &CardDeleteOne{builder}
}
// Query returns a query builder for Card.
func (c *CardClient) Query() *CardQuery {
return &CardQuery{
config: c.config,
inters: c.Interceptors(),
}
}
// Get returns a Card entity by its id.
func (c *CardClient) Get(ctx context.Context, id int) (*Card, error) {
return c.Query().Where(card.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *CardClient) GetX(ctx context.Context, id int) *Card {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// Hooks returns the client hooks.
func (c *CardClient) Hooks() []Hook {
return c.hooks.Card
}
// Interceptors returns the client interceptors.
func (c *CardClient) Interceptors() []Interceptor {
return c.inters.Card
}
func (c *CardClient) mutate(ctx context.Context, m *CardMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&CardCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&CardUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&CardUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&CardDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Card mutation op: %q", m.Op())
}
}
// PetClient is a client for the Pet schema.
type PetClient struct {
config

View File

@@ -31,10 +31,12 @@ type config struct {
// hooks and interceptors per client, for fast access.
type (
hooks struct {
Card []ent.Hook
Pet []ent.Hook
User []ent.Hook
}
inters struct {
Card []ent.Interceptor
Pet []ent.Interceptor
User []ent.Interceptor
}

View File

@@ -15,6 +15,7 @@ import (
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/examples/jsonencode/ent/card"
"entgo.io/ent/examples/jsonencode/ent/pet"
"entgo.io/ent/examples/jsonencode/ent/user"
)
@@ -43,6 +44,7 @@ type OrderFunc func(*sql.Selector)
// columnChecker returns a function indicates if the column exists in the given column.
func columnChecker(table string) func(string) error {
checks := map[string]func(string) bool{
card.Table: card.ValidColumn,
pet.Table: pet.ValidColumn,
user.Table: user.ValidColumn,
}

View File

@@ -46,17 +46,19 @@ func (e *EncodeExtension) Templates() []*gen.Template {
return []*gen.Template{
gen.MustParse(gen.NewTemplate("model/additional/jsonencode").
Parse(`
// MarshalJSON implements the json.Marshaler interface.
func ({{ $.Receiver }} *{{ $.Name }}) MarshalJSON() ([]byte, error) {
type Alias {{ $.Name }}
return json.Marshal(&struct {
*Alias
{{ $.Name }}Edges
}{
Alias: (*Alias)({{ $.Receiver }}),
{{ $.Name }}Edges: {{ $.Receiver }}.Edges,
})
}
{{ if $.Edges }}
// MarshalJSON implements the json.Marshaler interface.
func ({{ $.Receiver }} *{{ $.Name }}) MarshalJSON() ([]byte, error) {
type Alias {{ $.Name }}
return json.Marshal(&struct {
*Alias
{{ $.Name }}Edges
}{
Alias: (*Alias)({{ $.Receiver }}),
{{ $.Name }}Edges: {{ $.Receiver }}.Edges,
})
}
{{ end }}
`)),
}
}

View File

@@ -13,6 +13,18 @@ import (
"entgo.io/ent/examples/jsonencode/ent"
)
// The CardFunc type is an adapter to allow the use of ordinary
// function as Card mutator.
type CardFunc func(context.Context, *ent.CardMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f CardFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.CardMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.CardMutation", m)
}
// The PetFunc type is an adapter to allow the use of ordinary
// function as Pet mutator.
type PetFunc func(context.Context, *ent.PetMutation) (ent.Value, error)

View File

@@ -12,6 +12,17 @@ import (
)
var (
// CardsColumns holds the columns for the "cards" table.
CardsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "number", Type: field.TypeString},
}
// CardsTable holds the schema information for the "cards" table.
CardsTable = &schema.Table{
Name: "cards",
Columns: CardsColumns,
PrimaryKey: []*schema.Column{CardsColumns[0]},
}
// PetsColumns holds the columns for the "pets" table.
PetsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
@@ -47,6 +58,7 @@ var (
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
CardsTable,
PetsTable,
UsersTable,
}

View File

@@ -13,6 +13,7 @@ import (
"sync"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/examples/jsonencode/ent/card"
"entgo.io/ent/examples/jsonencode/ent/pet"
"entgo.io/ent/examples/jsonencode/ent/predicate"
"entgo.io/ent/examples/jsonencode/ent/user"
@@ -29,10 +30,337 @@ const (
OpUpdateOne = ent.OpUpdateOne
// Node types.
TypeCard = "Card"
TypePet = "Pet"
TypeUser = "User"
)
// CardMutation represents an operation that mutates the Card nodes in the graph.
type CardMutation struct {
config
op Op
typ string
id *int
number *string
clearedFields map[string]struct{}
done bool
oldValue func(context.Context) (*Card, error)
predicates []predicate.Card
}
var _ ent.Mutation = (*CardMutation)(nil)
// cardOption allows management of the mutation configuration using functional options.
type cardOption func(*CardMutation)
// newCardMutation creates new mutation for the Card entity.
func newCardMutation(c config, op Op, opts ...cardOption) *CardMutation {
m := &CardMutation{
config: c,
op: op,
typ: TypeCard,
clearedFields: make(map[string]struct{}),
}
for _, opt := range opts {
opt(m)
}
return m
}
// withCardID sets the ID field of the mutation.
func withCardID(id int) cardOption {
return func(m *CardMutation) {
var (
err error
once sync.Once
value *Card
)
m.oldValue = func(ctx context.Context) (*Card, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().Card.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withCard sets the old Card of the mutation.
func withCard(node *Card) cardOption {
return func(m *CardMutation) {
m.oldValue = func(context.Context) (*Card, error) {
return node, nil
}
m.id = &node.ID
}
}
// Client returns a new `ent.Client` from the mutation. If the mutation was
// executed in a transaction (ent.Tx), a transactional client is returned.
func (m CardMutation) Client() *Client {
client := &Client{config: m.config}
client.init()
return client
}
// Tx returns an `ent.Tx` for mutations that were executed in transactions;
// it returns an error otherwise.
func (m CardMutation) Tx() (*Tx, error) {
if _, ok := m.driver.(*txDriver); !ok {
return nil, errors.New("ent: mutation is not running in a transaction")
}
tx := &Tx{config: m.config}
tx.init()
return tx, nil
}
// ID returns the ID value in the mutation. Note that the ID is only available
// if it was provided to the builder or after it was returned from the database.
func (m *CardMutation) ID() (id int, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// IDs queries the database and returns the entity ids that match the mutation's predicate.
// That means, if the mutation is applied within a transaction with an isolation level such
// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated
// or updated by the mutation.
func (m *CardMutation) IDs(ctx context.Context) ([]int, error) {
switch {
case m.op.Is(OpUpdateOne | OpDeleteOne):
id, exists := m.ID()
if exists {
return []int{id}, nil
}
fallthrough
case m.op.Is(OpUpdate | OpDelete):
return m.Client().Card.Query().Where(m.predicates...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
}
}
// SetNumber sets the "number" field.
func (m *CardMutation) SetNumber(s string) {
m.number = &s
}
// Number returns the value of the "number" field in the mutation.
func (m *CardMutation) Number() (r string, exists bool) {
v := m.number
if v == nil {
return
}
return *v, true
}
// OldNumber returns the old "number" field's value of the Card entity.
// If the Card object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *CardMutation) OldNumber(ctx context.Context) (v string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldNumber is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldNumber requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldNumber: %w", err)
}
return oldValue.Number, nil
}
// ResetNumber resets all changes to the "number" field.
func (m *CardMutation) ResetNumber() {
m.number = nil
}
// Where appends a list predicates to the CardMutation builder.
func (m *CardMutation) Where(ps ...predicate.Card) {
m.predicates = append(m.predicates, ps...)
}
// WhereP appends storage-level predicates to the CardMutation builder. Using this method,
// users can use type-assertion to append predicates that do not depend on any generated package.
func (m *CardMutation) WhereP(ps ...func(*sql.Selector)) {
p := make([]predicate.Card, len(ps))
for i := range ps {
p[i] = ps[i]
}
m.Where(p...)
}
// Op returns the operation name.
func (m *CardMutation) Op() Op {
return m.op
}
// SetOp allows setting the mutation operation.
func (m *CardMutation) SetOp(op Op) {
m.op = op
}
// Type returns the node type of this mutation (Card).
func (m *CardMutation) 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 *CardMutation) Fields() []string {
fields := make([]string, 0, 1)
if m.number != nil {
fields = append(fields, card.FieldNumber)
}
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 *CardMutation) Field(name string) (ent.Value, bool) {
switch name {
case card.FieldNumber:
return m.Number()
}
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 *CardMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case card.FieldNumber:
return m.OldNumber(ctx)
}
return nil, fmt.Errorf("unknown Card field %s", name)
}
// SetField sets the value of a field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *CardMutation) SetField(name string, value ent.Value) error {
switch name {
case card.FieldNumber:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetNumber(v)
return nil
}
return fmt.Errorf("unknown Card field %s", name)
}
// AddedFields returns all numeric fields that were incremented/decremented during
// this mutation.
func (m *CardMutation) AddedFields() []string {
return nil
}
// AddedField returns the numeric value that was incremented/decremented on a field
// with the given name. The second boolean return value indicates that this field
// was not set, or was not defined in the schema.
func (m *CardMutation) AddedField(name string) (ent.Value, bool) {
return nil, false
}
// AddField adds the value to the field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *CardMutation) AddField(name string, value ent.Value) error {
switch name {
}
return fmt.Errorf("unknown Card numeric field %s", name)
}
// ClearedFields returns all nullable fields that were cleared during this
// mutation.
func (m *CardMutation) ClearedFields() []string {
return nil
}
// FieldCleared returns a boolean indicating if a field with the given name was
// cleared in this mutation.
func (m *CardMutation) 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 *CardMutation) ClearField(name string) error {
return fmt.Errorf("unknown Card nullable field %s", name)
}
// ResetField resets all changes in the mutation for the field with the given name.
// It returns an error if the field is not defined in the schema.
func (m *CardMutation) ResetField(name string) error {
switch name {
case card.FieldNumber:
m.ResetNumber()
return nil
}
return fmt.Errorf("unknown Card field %s", name)
}
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *CardMutation) AddedEdges() []string {
edges := make([]string, 0, 0)
return edges
}
// AddedIDs returns all IDs (to other nodes) that were added for the given edge
// name in this mutation.
func (m *CardMutation) AddedIDs(name string) []ent.Value {
return nil
}
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *CardMutation) RemovedEdges() []string {
edges := make([]string, 0, 0)
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 {
return nil
}
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *CardMutation) ClearedEdges() []string {
edges := make([]string, 0, 0)
return edges
}
// EdgeCleared returns a boolean which indicates if the edge with the given name
// was cleared in this mutation.
func (m *CardMutation) EdgeCleared(name string) bool {
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 *CardMutation) ClearEdge(name string) error {
return fmt.Errorf("unknown Card unique edge %s", name)
}
// ResetEdge resets all changes to the edge with the given name in this mutation.
// It returns an error if the edge is not defined in the schema.
func (m *CardMutation) ResetEdge(name string) error {
return fmt.Errorf("unknown Card edge %s", name)
}
// PetMutation represents an operation that mutates the Pet nodes in the graph.
type PetMutation struct {
config

View File

@@ -10,6 +10,9 @@ import (
"entgo.io/ent/dialect/sql"
)
// Card is the predicate function for card builders.
type Card func(*sql.Selector)
// Pet is the predicate function for pet builders.
type Pet func(*sql.Selector)

View File

@@ -0,0 +1,22 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/field"
)
// Card holds the schema definition for the Card entity.
type Card struct {
ent.Schema
}
// Fields of the Card.
func (Card) Fields() []ent.Field {
return []ent.Field{
field.String("number"),
}
}

View File

@@ -16,6 +16,8 @@ import (
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
// Card is the client for interacting with the Card builders.
Card *CardClient
// Pet is the client for interacting with the Pet builders.
Pet *PetClient
// User is the client for interacting with the User builders.
@@ -151,6 +153,7 @@ func (tx *Tx) Client() *Client {
}
func (tx *Tx) init() {
tx.Card = NewCardClient(tx.config)
tx.Pet = NewPetClient(tx.config)
tx.User = NewUserClient(tx.config)
}
@@ -162,7 +165,7 @@ func (tx *Tx) init() {
// of them in order to commit or rollback the transaction.
//
// If a closed transaction is embedded in one of the generated entities, and the entity
// applies a query, for example: Pet.QueryXXX(), the query will be executed
// applies a query, for example: Card.QueryXXX(), the query will be executed
// through the driver which created this transaction.
//
// Note that txDriver is not goroutine safe.