diff --git a/entc/gen/template/import.tmpl b/entc/gen/template/import.tmpl index ad1e72369..f18133e35 100644 --- a/entc/gen/template/import.tmpl +++ b/entc/gen/template/import.tmpl @@ -19,7 +19,8 @@ import ( "{{ $.Config.Package }}/predicate" {{- if $.HasOneFieldID }} {{- with $.ID.Type.PkgPath }} - "{{ . }}" + {{- $name := $.ID.Type.PkgName }} + {{ if ne $name (base $.ID.Type.PkgPath) }}{{ $name }} {{ end}}"{{ . }}" {{- end }} {{- end }} {{- /* Import external packages */}} diff --git a/entc/integration/customid/customid_test.go b/entc/integration/customid/customid_test.go index c8c569890..87948b57d 100644 --- a/entc/integration/customid/customid_test.go +++ b/entc/integration/customid/customid_test.go @@ -249,6 +249,14 @@ func CustomID(t *testing.T, client *ent.Client) { require.NotNil(t, ta.Edges.Account) require.Equal(t, a.ID, ta.Edges.Account.ID) }) + + t.Run("UUID compatible", func(t *testing.T) { + l := client.Link.Create().SaveX(ctx) + require.NotEmpty(t, l.ID) + require.Len(t, l.LinkInformation, 1) + require.Equal(t, "ent", l.LinkInformation["ent"].Name) + require.Equal(t, "https://entgo.io/", l.LinkInformation["ent"].Link) + }) } func BytesID(t *testing.T, client *ent.Client) { diff --git a/entc/integration/customid/ent/client.go b/entc/integration/customid/ent/client.go index 7782ee661..f9b916c53 100644 --- a/entc/integration/customid/ent/client.go +++ b/entc/integration/customid/ent/client.go @@ -15,6 +15,7 @@ import ( "entgo.io/ent/entc/integration/customid/ent/migrate" "entgo.io/ent/entc/integration/customid/ent/schema" "entgo.io/ent/entc/integration/customid/sid" + uuidc "entgo.io/ent/entc/integration/customid/uuidcompatible" "github.com/google/uuid" "entgo.io/ent/entc/integration/customid/ent/account" @@ -25,6 +26,7 @@ import ( "entgo.io/ent/entc/integration/customid/ent/doc" "entgo.io/ent/entc/integration/customid/ent/group" "entgo.io/ent/entc/integration/customid/ent/intsid" + "entgo.io/ent/entc/integration/customid/ent/link" "entgo.io/ent/entc/integration/customid/ent/mixinid" "entgo.io/ent/entc/integration/customid/ent/note" "entgo.io/ent/entc/integration/customid/ent/other" @@ -60,6 +62,8 @@ type Client struct { Group *GroupClient // IntSID is the client for interacting with the IntSID builders. IntSID *IntSIDClient + // Link is the client for interacting with the Link builders. + Link *LinkClient // MixinID is the client for interacting with the MixinID builders. MixinID *MixinIDClient // Note is the client for interacting with the Note builders. @@ -97,6 +101,7 @@ func (c *Client) init() { c.Doc = NewDocClient(c.config) c.Group = NewGroupClient(c.config) c.IntSID = NewIntSIDClient(c.config) + c.Link = NewLinkClient(c.config) c.MixinID = NewMixinIDClient(c.config) c.Note = NewNoteClient(c.config) c.Other = NewOtherClient(c.config) @@ -146,6 +151,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { Doc: NewDocClient(cfg), Group: NewGroupClient(cfg), IntSID: NewIntSIDClient(cfg), + Link: NewLinkClient(cfg), MixinID: NewMixinIDClient(cfg), Note: NewNoteClient(cfg), Other: NewOtherClient(cfg), @@ -181,6 +187,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) Doc: NewDocClient(cfg), Group: NewGroupClient(cfg), IntSID: NewIntSIDClient(cfg), + Link: NewLinkClient(cfg), MixinID: NewMixinIDClient(cfg), Note: NewNoteClient(cfg), Other: NewOtherClient(cfg), @@ -225,6 +232,7 @@ func (c *Client) Use(hooks ...Hook) { c.Doc.Use(hooks...) c.Group.Use(hooks...) c.IntSID.Use(hooks...) + c.Link.Use(hooks...) c.MixinID.Use(hooks...) c.Note.Use(hooks...) c.Other.Use(hooks...) @@ -1146,6 +1154,96 @@ func (c *IntSIDClient) Hooks() []Hook { return c.hooks.IntSID } +// LinkClient is a client for the Link schema. +type LinkClient struct { + config +} + +// NewLinkClient returns a client for the Link from the given config. +func NewLinkClient(c config) *LinkClient { + return &LinkClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `link.Hooks(f(g(h())))`. +func (c *LinkClient) Use(hooks ...Hook) { + c.hooks.Link = append(c.hooks.Link, hooks...) +} + +// Create returns a builder for creating a Link entity. +func (c *LinkClient) Create() *LinkCreate { + mutation := newLinkMutation(c.config, OpCreate) + return &LinkCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Link entities. +func (c *LinkClient) CreateBulk(builders ...*LinkCreate) *LinkCreateBulk { + return &LinkCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Link. +func (c *LinkClient) Update() *LinkUpdate { + mutation := newLinkMutation(c.config, OpUpdate) + return &LinkUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LinkClient) UpdateOne(l *Link) *LinkUpdateOne { + mutation := newLinkMutation(c.config, OpUpdateOne, withLink(l)) + return &LinkUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LinkClient) UpdateOneID(id uuidc.UUIDC) *LinkUpdateOne { + mutation := newLinkMutation(c.config, OpUpdateOne, withLinkID(id)) + return &LinkUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Link. +func (c *LinkClient) Delete() *LinkDelete { + mutation := newLinkMutation(c.config, OpDelete) + return &LinkDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *LinkClient) DeleteOne(l *Link) *LinkDeleteOne { + return c.DeleteOneID(l.ID) +} + +// DeleteOne returns a builder for deleting the given entity by its id. +func (c *LinkClient) DeleteOneID(id uuidc.UUIDC) *LinkDeleteOne { + builder := c.Delete().Where(link.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LinkDeleteOne{builder} +} + +// Query returns a query builder for Link. +func (c *LinkClient) Query() *LinkQuery { + return &LinkQuery{ + config: c.config, + } +} + +// Get returns a Link entity by its id. +func (c *LinkClient) Get(ctx context.Context, id uuidc.UUIDC) (*Link, error) { + return c.Query().Where(link.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LinkClient) GetX(ctx context.Context, id uuidc.UUIDC) *Link { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *LinkClient) Hooks() []Hook { + return c.hooks.Link +} + // MixinIDClient is a client for the MixinID schema. type MixinIDClient struct { config diff --git a/entc/integration/customid/ent/config.go b/entc/integration/customid/ent/config.go index 9fda14ed2..ca1e4b5e9 100644 --- a/entc/integration/customid/ent/config.go +++ b/entc/integration/customid/ent/config.go @@ -36,6 +36,7 @@ type hooks struct { Doc []ent.Hook Group []ent.Hook IntSID []ent.Hook + Link []ent.Hook MixinID []ent.Hook Note []ent.Hook Other []ent.Hook diff --git a/entc/integration/customid/ent/ent.go b/entc/integration/customid/ent/ent.go index edac60576..f96796df2 100644 --- a/entc/integration/customid/ent/ent.go +++ b/entc/integration/customid/ent/ent.go @@ -22,6 +22,7 @@ import ( "entgo.io/ent/entc/integration/customid/ent/doc" "entgo.io/ent/entc/integration/customid/ent/group" "entgo.io/ent/entc/integration/customid/ent/intsid" + "entgo.io/ent/entc/integration/customid/ent/link" "entgo.io/ent/entc/integration/customid/ent/mixinid" "entgo.io/ent/entc/integration/customid/ent/note" "entgo.io/ent/entc/integration/customid/ent/other" @@ -58,6 +59,7 @@ func columnChecker(table string) func(string) error { doc.Table: doc.ValidColumn, group.Table: group.ValidColumn, intsid.Table: intsid.ValidColumn, + link.Table: link.ValidColumn, mixinid.Table: mixinid.ValidColumn, note.Table: note.ValidColumn, other.Table: other.ValidColumn, diff --git a/entc/integration/customid/ent/entql.go b/entc/integration/customid/ent/entql.go index cdeb108a4..04a13a283 100644 --- a/entc/integration/customid/ent/entql.go +++ b/entc/integration/customid/ent/entql.go @@ -15,6 +15,7 @@ import ( "entgo.io/ent/entc/integration/customid/ent/doc" "entgo.io/ent/entc/integration/customid/ent/group" "entgo.io/ent/entc/integration/customid/ent/intsid" + "entgo.io/ent/entc/integration/customid/ent/link" "entgo.io/ent/entc/integration/customid/ent/mixinid" "entgo.io/ent/entc/integration/customid/ent/note" "entgo.io/ent/entc/integration/customid/ent/other" @@ -33,7 +34,7 @@ import ( // schemaGraph holds a representation of ent/schema at runtime. var schemaGraph = func() *sqlgraph.Schema { - graph := &sqlgraph.Schema{Nodes: make([]*sqlgraph.Node, 16)} + graph := &sqlgraph.Schema{Nodes: make([]*sqlgraph.Node, 17)} graph.Nodes[0] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: account.Table, @@ -152,6 +153,20 @@ var schemaGraph = func() *sqlgraph.Schema { Fields: map[string]*sqlgraph.FieldSpec{}, } graph.Nodes[8] = &sqlgraph.Node{ + NodeSpec: sqlgraph.NodeSpec{ + Table: link.Table, + Columns: link.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: link.FieldID, + }, + }, + Type: "Link", + Fields: map[string]*sqlgraph.FieldSpec{ + link.FieldLinkInformation: {Type: field.TypeJSON, Column: link.FieldLinkInformation}, + }, + } + graph.Nodes[9] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: mixinid.Table, Columns: mixinid.Columns, @@ -166,7 +181,7 @@ var schemaGraph = func() *sqlgraph.Schema { mixinid.FieldMixinField: {Type: field.TypeString, Column: mixinid.FieldMixinField}, }, } - graph.Nodes[9] = &sqlgraph.Node{ + graph.Nodes[10] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: note.Table, Columns: note.Columns, @@ -180,7 +195,7 @@ var schemaGraph = func() *sqlgraph.Schema { note.FieldText: {Type: field.TypeString, Column: note.FieldText}, }, } - graph.Nodes[10] = &sqlgraph.Node{ + graph.Nodes[11] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: other.Table, Columns: other.Columns, @@ -192,7 +207,7 @@ var schemaGraph = func() *sqlgraph.Schema { Type: "Other", Fields: map[string]*sqlgraph.FieldSpec{}, } - graph.Nodes[11] = &sqlgraph.Node{ + graph.Nodes[12] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: pet.Table, Columns: pet.Columns, @@ -204,7 +219,7 @@ var schemaGraph = func() *sqlgraph.Schema { Type: "Pet", Fields: map[string]*sqlgraph.FieldSpec{}, } - graph.Nodes[12] = &sqlgraph.Node{ + graph.Nodes[13] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: revision.Table, Columns: revision.Columns, @@ -216,7 +231,7 @@ var schemaGraph = func() *sqlgraph.Schema { Type: "Revision", Fields: map[string]*sqlgraph.FieldSpec{}, } - graph.Nodes[13] = &sqlgraph.Node{ + graph.Nodes[14] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: session.Table, Columns: session.Columns, @@ -228,7 +243,7 @@ var schemaGraph = func() *sqlgraph.Schema { Type: "Session", Fields: map[string]*sqlgraph.FieldSpec{}, } - graph.Nodes[14] = &sqlgraph.Node{ + graph.Nodes[15] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: token.Table, Columns: token.Columns, @@ -242,7 +257,7 @@ var schemaGraph = func() *sqlgraph.Schema { token.FieldBody: {Type: field.TypeString, Column: token.FieldBody}, }, } - graph.Nodes[15] = &sqlgraph.Node{ + graph.Nodes[16] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: user.Table, Columns: user.Columns, @@ -1162,6 +1177,51 @@ func (f *IntSIDFilter) WhereHasChildrenWith(preds ...predicate.IntSID) { }))) } +// addPredicate implements the predicateAdder interface. +func (lq *LinkQuery) addPredicate(pred func(s *sql.Selector)) { + lq.predicates = append(lq.predicates, pred) +} + +// Filter returns a Filter implementation to apply filters on the LinkQuery builder. +func (lq *LinkQuery) Filter() *LinkFilter { + return &LinkFilter{config: lq.config, predicateAdder: lq} +} + +// addPredicate implements the predicateAdder interface. +func (m *LinkMutation) addPredicate(pred func(s *sql.Selector)) { + m.predicates = append(m.predicates, pred) +} + +// Filter returns an entql.Where implementation to apply filters on the LinkMutation builder. +func (m *LinkMutation) Filter() *LinkFilter { + return &LinkFilter{config: m.config, predicateAdder: m} +} + +// LinkFilter provides a generic filtering capability at runtime for LinkQuery. +type LinkFilter struct { + predicateAdder + config +} + +// Where applies the entql predicate on the query filter. +func (f *LinkFilter) Where(p entql.P) { + f.addPredicate(func(s *sql.Selector) { + if err := schemaGraph.EvalP(schemaGraph.Nodes[8].Type, p, s); err != nil { + s.AddError(err) + } + }) +} + +// WhereID applies the entql [16]byte predicate on the id field. +func (f *LinkFilter) WhereID(p entql.ValueP) { + f.Where(p.Field(link.FieldID)) +} + +// WhereLinkInformation applies the entql json.RawMessage predicate on the link_information field. +func (f *LinkFilter) WhereLinkInformation(p entql.BytesP) { + f.Where(p.Field(link.FieldLinkInformation)) +} + // addPredicate implements the predicateAdder interface. func (miq *MixinIDQuery) addPredicate(pred func(s *sql.Selector)) { miq.predicates = append(miq.predicates, pred) @@ -1191,7 +1251,7 @@ type MixinIDFilter struct { // Where applies the entql predicate on the query filter. func (f *MixinIDFilter) Where(p entql.P) { f.addPredicate(func(s *sql.Selector) { - if err := schemaGraph.EvalP(schemaGraph.Nodes[8].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[9].Type, p, s); err != nil { s.AddError(err) } }) @@ -1241,7 +1301,7 @@ type NoteFilter struct { // Where applies the entql predicate on the query filter. func (f *NoteFilter) Where(p entql.P) { f.addPredicate(func(s *sql.Selector) { - if err := schemaGraph.EvalP(schemaGraph.Nodes[9].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[10].Type, p, s); err != nil { s.AddError(err) } }) @@ -1314,7 +1374,7 @@ type OtherFilter struct { // Where applies the entql predicate on the query filter. func (f *OtherFilter) Where(p entql.P) { f.addPredicate(func(s *sql.Selector) { - if err := schemaGraph.EvalP(schemaGraph.Nodes[10].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[11].Type, p, s); err != nil { s.AddError(err) } }) @@ -1354,7 +1414,7 @@ type PetFilter struct { // Where applies the entql predicate on the query filter. func (f *PetFilter) Where(p entql.P) { f.addPredicate(func(s *sql.Selector) { - if err := schemaGraph.EvalP(schemaGraph.Nodes[11].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[12].Type, p, s); err != nil { s.AddError(err) } }) @@ -1450,7 +1510,7 @@ type RevisionFilter struct { // Where applies the entql predicate on the query filter. func (f *RevisionFilter) Where(p entql.P) { f.addPredicate(func(s *sql.Selector) { - if err := schemaGraph.EvalP(schemaGraph.Nodes[12].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[13].Type, p, s); err != nil { s.AddError(err) } }) @@ -1490,7 +1550,7 @@ type SessionFilter struct { // Where applies the entql predicate on the query filter. func (f *SessionFilter) Where(p entql.P) { f.addPredicate(func(s *sql.Selector) { - if err := schemaGraph.EvalP(schemaGraph.Nodes[13].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[14].Type, p, s); err != nil { s.AddError(err) } }) @@ -1544,7 +1604,7 @@ type TokenFilter struct { // Where applies the entql predicate on the query filter. func (f *TokenFilter) Where(p entql.P) { f.addPredicate(func(s *sql.Selector) { - if err := schemaGraph.EvalP(schemaGraph.Nodes[14].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[15].Type, p, s); err != nil { s.AddError(err) } }) @@ -1603,7 +1663,7 @@ type UserFilter struct { // Where applies the entql predicate on the query filter. func (f *UserFilter) Where(p entql.P) { f.addPredicate(func(s *sql.Selector) { - if err := schemaGraph.EvalP(schemaGraph.Nodes[15].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[16].Type, p, s); err != nil { s.AddError(err) } }) diff --git a/entc/integration/customid/ent/hook/hook.go b/entc/integration/customid/ent/hook/hook.go index 64b72cb2f..079e6e20c 100644 --- a/entc/integration/customid/ent/hook/hook.go +++ b/entc/integration/customid/ent/hook/hook.go @@ -117,6 +117,19 @@ func (f IntSIDFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, erro return f(ctx, mv) } +// The LinkFunc type is an adapter to allow the use of ordinary +// function as Link mutator. +type LinkFunc func(context.Context, *ent.LinkMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f LinkFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + mv, ok := m.(*ent.LinkMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.LinkMutation", m) + } + return f(ctx, mv) +} + // The MixinIDFunc type is an adapter to allow the use of ordinary // function as MixinID mutator. type MixinIDFunc func(context.Context, *ent.MixinIDMutation) (ent.Value, error) diff --git a/entc/integration/customid/ent/link.go b/entc/integration/customid/ent/link.go new file mode 100644 index 000000000..7efa2205e --- /dev/null +++ b/entc/integration/customid/ent/link.go @@ -0,0 +1,107 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "encoding/json" + "fmt" + "strings" + + "entgo.io/ent/entc/integration/customid/ent/link" + "entgo.io/ent/entc/integration/customid/ent/schema" + uuidc "entgo.io/ent/entc/integration/customid/uuidcompatible" +) + +// Link is the model entity for the Link schema. +type Link struct { + config `json:"-"` + // ID of the ent. + ID uuidc.UUIDC `json:"id,omitempty"` + // LinkInformation holds the value of the "link_information" field. + LinkInformation map[string]schema.LinkInformation `json:"link_information,omitempty"` +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Link) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case link.FieldLinkInformation: + values[i] = new([]byte) + case link.FieldID: + values[i] = new(uuidc.UUIDC) + default: + return nil, fmt.Errorf("unexpected column %q for type Link", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Link fields. +func (l *Link) 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 link.FieldID: + if value, ok := values[i].(*uuidc.UUIDC); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + l.ID = *value + } + case link.FieldLinkInformation: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field link_information", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &l.LinkInformation); err != nil { + return fmt.Errorf("unmarshal field link_information: %w", err) + } + } + } + } + return nil +} + +// Update returns a builder for updating this Link. +// Note that you need to call Link.Unwrap() before calling this method if this Link +// was returned from a transaction, and the transaction was committed or rolled back. +func (l *Link) Update() *LinkUpdateOne { + return (&LinkClient{config: l.config}).UpdateOne(l) +} + +// Unwrap unwraps the Link 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 (l *Link) Unwrap() *Link { + _tx, ok := l.config.driver.(*txDriver) + if !ok { + panic("ent: Link is not a transactional entity") + } + l.config.driver = _tx.drv + return l +} + +// String implements the fmt.Stringer. +func (l *Link) String() string { + var builder strings.Builder + builder.WriteString("Link(") + builder.WriteString(fmt.Sprintf("id=%v, ", l.ID)) + builder.WriteString("link_information=") + builder.WriteString(fmt.Sprintf("%v", l.LinkInformation)) + builder.WriteByte(')') + return builder.String() +} + +// Links is a parsable slice of Link. +type Links []*Link + +func (l Links) config(cfg config) { + for _i := range l { + l[_i].config = cfg + } +} diff --git a/entc/integration/customid/ent/link/link.go b/entc/integration/customid/ent/link/link.go new file mode 100644 index 000000000..7753c2899 --- /dev/null +++ b/entc/integration/customid/ent/link/link.go @@ -0,0 +1,46 @@ +// 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 link + +import ( + "entgo.io/ent/entc/integration/customid/ent/schema" + uuidc "entgo.io/ent/entc/integration/customid/uuidcompatible" +) + +const ( + // Label holds the string label denoting the link type in the database. + Label = "link" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldLinkInformation holds the string denoting the link_information field in the database. + FieldLinkInformation = "link_information" + // Table holds the table name of the link in the database. + Table = "links" +) + +// Columns holds all SQL columns for link fields. +var Columns = []string{ + FieldID, + FieldLinkInformation, +} + +// 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 ( + // DefaultLinkInformation holds the default value on creation for the "link_information" field. + DefaultLinkInformation map[string]schema.LinkInformation + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() uuidc.UUIDC +) diff --git a/entc/integration/customid/ent/link/where.go b/entc/integration/customid/ent/link/where.go new file mode 100644 index 000000000..7cae62598 --- /dev/null +++ b/entc/integration/customid/ent/link/where.go @@ -0,0 +1,116 @@ +// 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 link + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/entc/integration/customid/ent/predicate" + uuidc "entgo.io/ent/entc/integration/customid/uuidcompatible" +) + +// ID filters vertices based on their ID field. +func ID(id uuidc.UUIDC) predicate.Link { + return predicate.Link(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuidc.UUIDC) predicate.Link { + return predicate.Link(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuidc.UUIDC) predicate.Link { + return predicate.Link(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuidc.UUIDC) predicate.Link { + return predicate.Link(func(s *sql.Selector) { + v := make([]any, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.In(s.C(FieldID), v...)) + }) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuidc.UUIDC) predicate.Link { + return predicate.Link(func(s *sql.Selector) { + v := make([]any, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.NotIn(s.C(FieldID), v...)) + }) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuidc.UUIDC) predicate.Link { + return predicate.Link(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuidc.UUIDC) predicate.Link { + return predicate.Link(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuidc.UUIDC) predicate.Link { + return predicate.Link(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuidc.UUIDC) predicate.Link { + return predicate.Link(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Link) predicate.Link { + return predicate.Link(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.Link) predicate.Link { + return predicate.Link(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.Link) predicate.Link { + return predicate.Link(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/entc/integration/customid/ent/link_create.go b/entc/integration/customid/ent/link_create.go new file mode 100644 index 000000000..740cba589 --- /dev/null +++ b/entc/integration/customid/ent/link_create.go @@ -0,0 +1,557 @@ +// 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" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/customid/ent/link" + "entgo.io/ent/entc/integration/customid/ent/schema" + uuidc "entgo.io/ent/entc/integration/customid/uuidcompatible" + "entgo.io/ent/schema/field" +) + +// LinkCreate is the builder for creating a Link entity. +type LinkCreate struct { + config + mutation *LinkMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetLinkInformation sets the "link_information" field. +func (lc *LinkCreate) SetLinkInformation(mi map[string]schema.LinkInformation) *LinkCreate { + lc.mutation.SetLinkInformation(mi) + return lc +} + +// SetID sets the "id" field. +func (lc *LinkCreate) SetID(u uuidc.UUIDC) *LinkCreate { + lc.mutation.SetID(u) + return lc +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (lc *LinkCreate) SetNillableID(u *uuidc.UUIDC) *LinkCreate { + if u != nil { + lc.SetID(*u) + } + return lc +} + +// Mutation returns the LinkMutation object of the builder. +func (lc *LinkCreate) Mutation() *LinkMutation { + return lc.mutation +} + +// Save creates the Link in the database. +func (lc *LinkCreate) Save(ctx context.Context) (*Link, error) { + var ( + err error + node *Link + ) + lc.defaults() + if len(lc.hooks) == 0 { + if err = lc.check(); err != nil { + return nil, err + } + node, err = lc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinkMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = lc.check(); err != nil { + return nil, err + } + lc.mutation = mutation + if node, err = lc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(lc.hooks) - 1; i >= 0; i-- { + if lc.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = lc.hooks[i](mut) + } + v, err := mut.Mutate(ctx, lc.mutation) + if err != nil { + return nil, err + } + nv, ok := v.(*Link) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from LinkMutation", v) + } + node = nv + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (lc *LinkCreate) SaveX(ctx context.Context) *Link { + v, err := lc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (lc *LinkCreate) Exec(ctx context.Context) error { + _, err := lc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lc *LinkCreate) ExecX(ctx context.Context) { + if err := lc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (lc *LinkCreate) defaults() { + if _, ok := lc.mutation.LinkInformation(); !ok { + v := link.DefaultLinkInformation + lc.mutation.SetLinkInformation(v) + } + if _, ok := lc.mutation.ID(); !ok { + v := link.DefaultID() + lc.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (lc *LinkCreate) check() error { + if _, ok := lc.mutation.LinkInformation(); !ok { + return &ValidationError{Name: "link_information", err: errors.New(`ent: missing required field "Link.link_information"`)} + } + return nil +} + +func (lc *LinkCreate) sqlSave(ctx context.Context) (*Link, error) { + _node, _spec := lc.createSpec() + if err := sqlgraph.CreateNode(ctx, lc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != nil { + if id, ok := _spec.ID.Value.(*uuidc.UUIDC); ok { + _node.ID = *id + } else if err := _node.ID.Scan(_spec.ID.Value); err != nil { + return nil, err + } + } + return _node, nil +} + +func (lc *LinkCreate) createSpec() (*Link, *sqlgraph.CreateSpec) { + var ( + _node = &Link{config: lc.config} + _spec = &sqlgraph.CreateSpec{ + Table: link.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: link.FieldID, + }, + } + ) + _spec.OnConflict = lc.conflict + if id, ok := lc.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := lc.mutation.LinkInformation(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeJSON, + Value: value, + Column: link.FieldLinkInformation, + }) + _node.LinkInformation = value + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.Link.Create(). +// SetLinkInformation(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.LinkUpsert) { +// SetLinkInformation(v+v). +// }). +// Exec(ctx) +func (lc *LinkCreate) OnConflict(opts ...sql.ConflictOption) *LinkUpsertOne { + lc.conflict = opts + return &LinkUpsertOne{ + create: lc, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Link.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (lc *LinkCreate) OnConflictColumns(columns ...string) *LinkUpsertOne { + lc.conflict = append(lc.conflict, sql.ConflictColumns(columns...)) + return &LinkUpsertOne{ + create: lc, + } +} + +type ( + // LinkUpsertOne is the builder for "upsert"-ing + // one Link node. + LinkUpsertOne struct { + create *LinkCreate + } + + // LinkUpsert is the "OnConflict" setter. + LinkUpsert struct { + *sql.UpdateSet + } +) + +// SetLinkInformation sets the "link_information" field. +func (u *LinkUpsert) SetLinkInformation(v map[string]schema.LinkInformation) *LinkUpsert { + u.Set(link.FieldLinkInformation, v) + return u +} + +// UpdateLinkInformation sets the "link_information" field to the value that was provided on create. +func (u *LinkUpsert) UpdateLinkInformation() *LinkUpsert { + u.SetExcluded(link.FieldLinkInformation) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.Link.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(link.FieldID) +// }), +// ). +// Exec(ctx) +func (u *LinkUpsertOne) UpdateNewValues() *LinkUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + if _, exists := u.create.mutation.ID(); exists { + s.SetIgnore(link.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Link.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *LinkUpsertOne) Ignore() *LinkUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *LinkUpsertOne) DoNothing() *LinkUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the LinkCreate.OnConflict +// documentation for more info. +func (u *LinkUpsertOne) Update(set func(*LinkUpsert)) *LinkUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&LinkUpsert{UpdateSet: update}) + })) + return u +} + +// SetLinkInformation sets the "link_information" field. +func (u *LinkUpsertOne) SetLinkInformation(v map[string]schema.LinkInformation) *LinkUpsertOne { + return u.Update(func(s *LinkUpsert) { + s.SetLinkInformation(v) + }) +} + +// UpdateLinkInformation sets the "link_information" field to the value that was provided on create. +func (u *LinkUpsertOne) UpdateLinkInformation() *LinkUpsertOne { + return u.Update(func(s *LinkUpsert) { + s.UpdateLinkInformation() + }) +} + +// Exec executes the query. +func (u *LinkUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for LinkCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *LinkUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated ID. +func (u *LinkUpsertOne) ID(ctx context.Context) (id uuidc.UUIDC, err error) { + if u.create.driver.Dialect() == dialect.MySQL { + // In case of "ON CONFLICT", there is no way to get back non-numeric ID + // fields from the database since MySQL does not support the RETURNING clause. + return id, errors.New("ent: LinkUpsertOne.ID is not supported by MySQL driver. Use LinkUpsertOne.Exec instead") + } + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.ID, nil +} + +// IDX is like ID, but panics if an error occurs. +func (u *LinkUpsertOne) IDX(ctx context.Context) uuidc.UUIDC { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// LinkCreateBulk is the builder for creating many Link entities in bulk. +type LinkCreateBulk struct { + config + builders []*LinkCreate + conflict []sql.ConflictOption +} + +// Save creates the Link entities in the database. +func (lcb *LinkCreateBulk) Save(ctx context.Context) ([]*Link, error) { + specs := make([]*sqlgraph.CreateSpec, len(lcb.builders)) + nodes := make([]*Link, len(lcb.builders)) + mutators := make([]Mutator, len(lcb.builders)) + for i := range lcb.builders { + func(i int, root context.Context) { + builder := lcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinkMutation) + 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, lcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = lcb.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, lcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, lcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (lcb *LinkCreateBulk) SaveX(ctx context.Context) []*Link { + v, err := lcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (lcb *LinkCreateBulk) Exec(ctx context.Context) error { + _, err := lcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lcb *LinkCreateBulk) ExecX(ctx context.Context) { + if err := lcb.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.Link.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.LinkUpsert) { +// SetLinkInformation(v+v). +// }). +// Exec(ctx) +func (lcb *LinkCreateBulk) OnConflict(opts ...sql.ConflictOption) *LinkUpsertBulk { + lcb.conflict = opts + return &LinkUpsertBulk{ + create: lcb, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Link.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (lcb *LinkCreateBulk) OnConflictColumns(columns ...string) *LinkUpsertBulk { + lcb.conflict = append(lcb.conflict, sql.ConflictColumns(columns...)) + return &LinkUpsertBulk{ + create: lcb, + } +} + +// LinkUpsertBulk is the builder for "upsert"-ing +// a bulk of Link nodes. +type LinkUpsertBulk struct { + create *LinkCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.Link.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(link.FieldID) +// }), +// ). +// Exec(ctx) +func (u *LinkUpsertBulk) UpdateNewValues() *LinkUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + for _, b := range u.create.builders { + if _, exists := b.mutation.ID(); exists { + s.SetIgnore(link.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Link.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *LinkUpsertBulk) Ignore() *LinkUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *LinkUpsertBulk) DoNothing() *LinkUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the LinkCreateBulk.OnConflict +// documentation for more info. +func (u *LinkUpsertBulk) Update(set func(*LinkUpsert)) *LinkUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&LinkUpsert{UpdateSet: update}) + })) + return u +} + +// SetLinkInformation sets the "link_information" field. +func (u *LinkUpsertBulk) SetLinkInformation(v map[string]schema.LinkInformation) *LinkUpsertBulk { + return u.Update(func(s *LinkUpsert) { + s.SetLinkInformation(v) + }) +} + +// UpdateLinkInformation sets the "link_information" field to the value that was provided on create. +func (u *LinkUpsertBulk) UpdateLinkInformation() *LinkUpsertBulk { + return u.Update(func(s *LinkUpsert) { + s.UpdateLinkInformation() + }) +} + +// Exec executes the query. +func (u *LinkUpsertBulk) Exec(ctx context.Context) error { + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the LinkCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for LinkCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *LinkUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/customid/ent/link_delete.go b/entc/integration/customid/ent/link_delete.go new file mode 100644 index 000000000..fef006d5f --- /dev/null +++ b/entc/integration/customid/ent/link_delete.go @@ -0,0 +1,119 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/customid/ent/link" + "entgo.io/ent/entc/integration/customid/ent/predicate" + "entgo.io/ent/schema/field" +) + +// LinkDelete is the builder for deleting a Link entity. +type LinkDelete struct { + config + hooks []Hook + mutation *LinkMutation +} + +// Where appends a list predicates to the LinkDelete builder. +func (ld *LinkDelete) Where(ps ...predicate.Link) *LinkDelete { + ld.mutation.Where(ps...) + return ld +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (ld *LinkDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(ld.hooks) == 0 { + affected, err = ld.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinkMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + ld.mutation = mutation + affected, err = ld.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(ld.hooks) - 1; i >= 0; i-- { + if ld.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = ld.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, ld.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ld *LinkDelete) ExecX(ctx context.Context) int { + n, err := ld.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (ld *LinkDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: link.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: link.FieldID, + }, + }, + } + if ps := ld.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, ld.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return affected, err +} + +// LinkDeleteOne is the builder for deleting a single Link entity. +type LinkDeleteOne struct { + ld *LinkDelete +} + +// Exec executes the deletion query. +func (ldo *LinkDeleteOne) Exec(ctx context.Context) error { + n, err := ldo.ld.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{link.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (ldo *LinkDeleteOne) ExecX(ctx context.Context) { + ldo.ld.ExecX(ctx) +} diff --git a/entc/integration/customid/ent/link_query.go b/entc/integration/customid/ent/link_query.go new file mode 100644 index 000000000..01f0402bb --- /dev/null +++ b/entc/integration/customid/ent/link_query.go @@ -0,0 +1,534 @@ +// 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/entc/integration/customid/ent/link" + "entgo.io/ent/entc/integration/customid/ent/predicate" + uuidc "entgo.io/ent/entc/integration/customid/uuidcompatible" + "entgo.io/ent/schema/field" +) + +// LinkQuery is the builder for querying Link entities. +type LinkQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.Link + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the LinkQuery builder. +func (lq *LinkQuery) Where(ps ...predicate.Link) *LinkQuery { + lq.predicates = append(lq.predicates, ps...) + return lq +} + +// Limit adds a limit step to the query. +func (lq *LinkQuery) Limit(limit int) *LinkQuery { + lq.limit = &limit + return lq +} + +// Offset adds an offset step to the query. +func (lq *LinkQuery) Offset(offset int) *LinkQuery { + lq.offset = &offset + return lq +} + +// 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 (lq *LinkQuery) Unique(unique bool) *LinkQuery { + lq.unique = &unique + return lq +} + +// Order adds an order step to the query. +func (lq *LinkQuery) Order(o ...OrderFunc) *LinkQuery { + lq.order = append(lq.order, o...) + return lq +} + +// First returns the first Link entity from the query. +// Returns a *NotFoundError when no Link was found. +func (lq *LinkQuery) First(ctx context.Context) (*Link, error) { + nodes, err := lq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{link.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (lq *LinkQuery) FirstX(ctx context.Context) *Link { + node, err := lq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Link ID from the query. +// Returns a *NotFoundError when no Link ID was found. +func (lq *LinkQuery) FirstID(ctx context.Context) (id uuidc.UUIDC, err error) { + var ids []uuidc.UUIDC + if ids, err = lq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{link.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (lq *LinkQuery) FirstIDX(ctx context.Context) uuidc.UUIDC { + id, err := lq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Link entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Link entity is found. +// Returns a *NotFoundError when no Link entities are found. +func (lq *LinkQuery) Only(ctx context.Context) (*Link, error) { + nodes, err := lq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{link.Label} + default: + return nil, &NotSingularError{link.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (lq *LinkQuery) OnlyX(ctx context.Context) *Link { + node, err := lq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Link ID in the query. +// Returns a *NotSingularError when more than one Link ID is found. +// Returns a *NotFoundError when no entities are found. +func (lq *LinkQuery) OnlyID(ctx context.Context) (id uuidc.UUIDC, err error) { + var ids []uuidc.UUIDC + if ids, err = lq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{link.Label} + default: + err = &NotSingularError{link.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (lq *LinkQuery) OnlyIDX(ctx context.Context) uuidc.UUIDC { + id, err := lq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Links. +func (lq *LinkQuery) All(ctx context.Context) ([]*Link, error) { + if err := lq.prepareQuery(ctx); err != nil { + return nil, err + } + return lq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (lq *LinkQuery) AllX(ctx context.Context) []*Link { + nodes, err := lq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Link IDs. +func (lq *LinkQuery) IDs(ctx context.Context) ([]uuidc.UUIDC, error) { + var ids []uuidc.UUIDC + if err := lq.Select(link.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (lq *LinkQuery) IDsX(ctx context.Context) []uuidc.UUIDC { + ids, err := lq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (lq *LinkQuery) Count(ctx context.Context) (int, error) { + if err := lq.prepareQuery(ctx); err != nil { + return 0, err + } + return lq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (lq *LinkQuery) CountX(ctx context.Context) int { + count, err := lq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (lq *LinkQuery) Exist(ctx context.Context) (bool, error) { + if err := lq.prepareQuery(ctx); err != nil { + return false, err + } + return lq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (lq *LinkQuery) ExistX(ctx context.Context) bool { + exist, err := lq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LinkQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (lq *LinkQuery) Clone() *LinkQuery { + if lq == nil { + return nil + } + return &LinkQuery{ + config: lq.config, + limit: lq.limit, + offset: lq.offset, + order: append([]OrderFunc{}, lq.order...), + predicates: append([]predicate.Link{}, lq.predicates...), + // clone intermediate query. + sql: lq.sql.Clone(), + path: lq.path, + unique: lq.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 { +// LinkInformation map[string]schema.LinkInformation `json:"link_information,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Link.Query(). +// GroupBy(link.FieldLinkInformation). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (lq *LinkQuery) GroupBy(field string, fields ...string) *LinkGroupBy { + grbuild := &LinkGroupBy{config: lq.config} + grbuild.fields = append([]string{field}, fields...) + grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := lq.prepareQuery(ctx); err != nil { + return nil, err + } + return lq.sqlQuery(ctx), nil + } + grbuild.label = link.Label + grbuild.flds, grbuild.scan = &grbuild.fields, 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 { +// LinkInformation map[string]schema.LinkInformation `json:"link_information,omitempty"` +// } +// +// client.Link.Query(). +// Select(link.FieldLinkInformation). +// Scan(ctx, &v) +func (lq *LinkQuery) Select(fields ...string) *LinkSelect { + lq.fields = append(lq.fields, fields...) + selbuild := &LinkSelect{LinkQuery: lq} + selbuild.label = link.Label + selbuild.flds, selbuild.scan = &lq.fields, selbuild.Scan + return selbuild +} + +func (lq *LinkQuery) prepareQuery(ctx context.Context) error { + for _, f := range lq.fields { + if !link.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if lq.path != nil { + prev, err := lq.path(ctx) + if err != nil { + return err + } + lq.sql = prev + } + return nil +} + +func (lq *LinkQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Link, error) { + var ( + nodes = []*Link{} + _spec = lq.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Link).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Link{config: lq.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, lq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (lq *LinkQuery) sqlCount(ctx context.Context) (int, error) { + _spec := lq.querySpec() + _spec.Node.Columns = lq.fields + if len(lq.fields) > 0 { + _spec.Unique = lq.unique != nil && *lq.unique + } + return sqlgraph.CountNodes(ctx, lq.driver, _spec) +} + +func (lq *LinkQuery) sqlExist(ctx context.Context) (bool, error) { + switch _, err := lq.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +func (lq *LinkQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: link.Table, + Columns: link.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: link.FieldID, + }, + }, + From: lq.sql, + Unique: true, + } + if unique := lq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := lq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, link.FieldID) + for i := range fields { + if fields[i] != link.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := lq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := lq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := lq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := lq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (lq *LinkQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(lq.driver.Dialect()) + t1 := builder.Table(link.Table) + columns := lq.fields + if len(columns) == 0 { + columns = link.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if lq.sql != nil { + selector = lq.sql + selector.Select(selector.Columns(columns...)...) + } + if lq.unique != nil && *lq.unique { + selector.Distinct() + } + for _, p := range lq.predicates { + p(selector) + } + for _, p := range lq.order { + p(selector) + } + if offset := lq.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 := lq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// LinkGroupBy is the group-by builder for Link entities. +type LinkGroupBy struct { + config + selector + fields []string + fns []AggregateFunc + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (lgb *LinkGroupBy) Aggregate(fns ...AggregateFunc) *LinkGroupBy { + lgb.fns = append(lgb.fns, fns...) + return lgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (lgb *LinkGroupBy) Scan(ctx context.Context, v any) error { + query, err := lgb.path(ctx) + if err != nil { + return err + } + lgb.sql = query + return lgb.sqlScan(ctx, v) +} + +func (lgb *LinkGroupBy) sqlScan(ctx context.Context, v any) error { + for _, f := range lgb.fields { + if !link.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := lgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := lgb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (lgb *LinkGroupBy) sqlQuery() *sql.Selector { + selector := lgb.sql.Select() + aggregation := make([]string, 0, len(lgb.fns)) + for _, fn := range lgb.fns { + aggregation = append(aggregation, fn(selector)) + } + // If no columns were selected in a custom aggregation function, the default + // selection is the fields used for "group-by", and the aggregation functions. + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(lgb.fields)+len(lgb.fns)) + for _, f := range lgb.fields { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(lgb.fields...)...) +} + +// LinkSelect is the builder for selecting fields of Link entities. +type LinkSelect struct { + *LinkQuery + selector + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (ls *LinkSelect) Scan(ctx context.Context, v any) error { + if err := ls.prepareQuery(ctx); err != nil { + return err + } + ls.sql = ls.LinkQuery.sqlQuery(ctx) + return ls.sqlScan(ctx, v) +} + +func (ls *LinkSelect) sqlScan(ctx context.Context, v any) error { + rows := &sql.Rows{} + query, args := ls.sql.Query() + if err := ls.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/entc/integration/customid/ent/link_update.go b/entc/integration/customid/ent/link_update.go new file mode 100644 index 000000000..241788736 --- /dev/null +++ b/entc/integration/customid/ent/link_update.go @@ -0,0 +1,276 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/customid/ent/link" + "entgo.io/ent/entc/integration/customid/ent/predicate" + "entgo.io/ent/entc/integration/customid/ent/schema" + "entgo.io/ent/schema/field" +) + +// LinkUpdate is the builder for updating Link entities. +type LinkUpdate struct { + config + hooks []Hook + mutation *LinkMutation +} + +// Where appends a list predicates to the LinkUpdate builder. +func (lu *LinkUpdate) Where(ps ...predicate.Link) *LinkUpdate { + lu.mutation.Where(ps...) + return lu +} + +// SetLinkInformation sets the "link_information" field. +func (lu *LinkUpdate) SetLinkInformation(mi map[string]schema.LinkInformation) *LinkUpdate { + lu.mutation.SetLinkInformation(mi) + return lu +} + +// Mutation returns the LinkMutation object of the builder. +func (lu *LinkUpdate) Mutation() *LinkMutation { + return lu.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (lu *LinkUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(lu.hooks) == 0 { + affected, err = lu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinkMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lu.mutation = mutation + affected, err = lu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(lu.hooks) - 1; i >= 0; i-- { + if lu.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = lu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (lu *LinkUpdate) SaveX(ctx context.Context) int { + affected, err := lu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (lu *LinkUpdate) Exec(ctx context.Context) error { + _, err := lu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lu *LinkUpdate) ExecX(ctx context.Context) { + if err := lu.Exec(ctx); err != nil { + panic(err) + } +} + +func (lu *LinkUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: link.Table, + Columns: link.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: link.FieldID, + }, + }, + } + if ps := lu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := lu.mutation.LinkInformation(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeJSON, + Value: value, + Column: link.FieldLinkInformation, + }) + } + if n, err = sqlgraph.UpdateNodes(ctx, lu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{link.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + return n, nil +} + +// LinkUpdateOne is the builder for updating a single Link entity. +type LinkUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LinkMutation +} + +// SetLinkInformation sets the "link_information" field. +func (luo *LinkUpdateOne) SetLinkInformation(mi map[string]schema.LinkInformation) *LinkUpdateOne { + luo.mutation.SetLinkInformation(mi) + return luo +} + +// Mutation returns the LinkMutation object of the builder. +func (luo *LinkUpdateOne) Mutation() *LinkMutation { + return luo.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 (luo *LinkUpdateOne) Select(field string, fields ...string) *LinkUpdateOne { + luo.fields = append([]string{field}, fields...) + return luo +} + +// Save executes the query and returns the updated Link entity. +func (luo *LinkUpdateOne) Save(ctx context.Context) (*Link, error) { + var ( + err error + node *Link + ) + if len(luo.hooks) == 0 { + node, err = luo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinkMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + luo.mutation = mutation + node, err = luo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(luo.hooks) - 1; i >= 0; i-- { + if luo.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = luo.hooks[i](mut) + } + v, err := mut.Mutate(ctx, luo.mutation) + if err != nil { + return nil, err + } + nv, ok := v.(*Link) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from LinkMutation", v) + } + node = nv + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (luo *LinkUpdateOne) SaveX(ctx context.Context) *Link { + node, err := luo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (luo *LinkUpdateOne) Exec(ctx context.Context) error { + _, err := luo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (luo *LinkUpdateOne) ExecX(ctx context.Context) { + if err := luo.Exec(ctx); err != nil { + panic(err) + } +} + +func (luo *LinkUpdateOne) sqlSave(ctx context.Context) (_node *Link, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: link.Table, + Columns: link.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: link.FieldID, + }, + }, + } + id, ok := luo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Link.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := luo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, link.FieldID) + for _, f := range fields { + if !link.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != link.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := luo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := luo.mutation.LinkInformation(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeJSON, + Value: value, + Column: link.FieldLinkInformation, + }) + } + _node = &Link{config: luo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, luo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{link.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + return _node, nil +} diff --git a/entc/integration/customid/ent/migrate/schema.go b/entc/integration/customid/ent/migrate/schema.go index 0d05dcc31..b57433148 100644 --- a/entc/integration/customid/ent/migrate/schema.go +++ b/entc/integration/customid/ent/migrate/schema.go @@ -160,6 +160,17 @@ var ( }, }, } + // LinksColumns holds the columns for the "links" table. + LinksColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "link_information", Type: field.TypeJSON}, + } + // LinksTable holds the schema information for the "links" table. + LinksTable = &schema.Table{ + Name: "links", + Columns: LinksColumns, + PrimaryKey: []*schema.Column{LinksColumns[0]}, + } // MixinIdsColumns holds the columns for the "mixin_ids" table. MixinIdsColumns = []*schema.Column{ {Name: "id", Type: field.TypeUUID}, @@ -403,6 +414,7 @@ var ( DocsTable, GroupsTable, IntSiDsTable, + LinksTable, MixinIdsTable, NotesTable, OthersTable, diff --git a/entc/integration/customid/ent/mutation.go b/entc/integration/customid/ent/mutation.go index 59b40678c..50c453f02 100644 --- a/entc/integration/customid/ent/mutation.go +++ b/entc/integration/customid/ent/mutation.go @@ -21,6 +21,7 @@ import ( "entgo.io/ent/entc/integration/customid/ent/doc" "entgo.io/ent/entc/integration/customid/ent/group" "entgo.io/ent/entc/integration/customid/ent/intsid" + "entgo.io/ent/entc/integration/customid/ent/link" "entgo.io/ent/entc/integration/customid/ent/mixinid" "entgo.io/ent/entc/integration/customid/ent/note" "entgo.io/ent/entc/integration/customid/ent/pet" @@ -30,6 +31,7 @@ import ( "entgo.io/ent/entc/integration/customid/ent/token" "entgo.io/ent/entc/integration/customid/ent/user" "entgo.io/ent/entc/integration/customid/sid" + uuidc "entgo.io/ent/entc/integration/customid/uuidcompatible" "github.com/google/uuid" "entgo.io/ent" @@ -52,6 +54,7 @@ const ( TypeDoc = "Doc" TypeGroup = "Group" TypeIntSID = "IntSID" + TypeLink = "Link" TypeMixinID = "MixinID" TypeNote = "Note" TypeOther = "Other" @@ -3768,6 +3771,323 @@ func (m *IntSIDMutation) ResetEdge(name string) error { return fmt.Errorf("unknown IntSID edge %s", name) } +// LinkMutation represents an operation that mutates the Link nodes in the graph. +type LinkMutation struct { + config + op Op + typ string + id *uuidc.UUIDC + link_information *map[string]schema.LinkInformation + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Link, error) + predicates []predicate.Link +} + +var _ ent.Mutation = (*LinkMutation)(nil) + +// linkOption allows management of the mutation configuration using functional options. +type linkOption func(*LinkMutation) + +// newLinkMutation creates new mutation for the Link entity. +func newLinkMutation(c config, op Op, opts ...linkOption) *LinkMutation { + m := &LinkMutation{ + config: c, + op: op, + typ: TypeLink, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLinkID sets the ID field of the mutation. +func withLinkID(id uuidc.UUIDC) linkOption { + return func(m *LinkMutation) { + var ( + err error + once sync.Once + value *Link + ) + m.oldValue = func(ctx context.Context) (*Link, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Link.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLink sets the old Link of the mutation. +func withLink(node *Link) linkOption { + return func(m *LinkMutation) { + m.oldValue = func(context.Context) (*Link, 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 LinkMutation) 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 LinkMutation) 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 +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of Link entities. +func (m *LinkMutation) SetID(id uuidc.UUIDC) { + m.id = &id +} + +// 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 *LinkMutation) ID() (id uuidc.UUIDC, 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 *LinkMutation) IDs(ctx context.Context) ([]uuidc.UUIDC, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []uuidc.UUIDC{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Link.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetLinkInformation sets the "link_information" field. +func (m *LinkMutation) SetLinkInformation(mi map[string]schema.LinkInformation) { + m.link_information = &mi +} + +// LinkInformation returns the value of the "link_information" field in the mutation. +func (m *LinkMutation) LinkInformation() (r map[string]schema.LinkInformation, exists bool) { + v := m.link_information + if v == nil { + return + } + return *v, true +} + +// OldLinkInformation returns the old "link_information" field's value of the Link entity. +// If the Link 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 *LinkMutation) OldLinkInformation(ctx context.Context) (v map[string]schema.LinkInformation, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLinkInformation is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLinkInformation requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLinkInformation: %w", err) + } + return oldValue.LinkInformation, nil +} + +// ResetLinkInformation resets all changes to the "link_information" field. +func (m *LinkMutation) ResetLinkInformation() { + m.link_information = nil +} + +// Where appends a list predicates to the LinkMutation builder. +func (m *LinkMutation) Where(ps ...predicate.Link) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *LinkMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (Link). +func (m *LinkMutation) 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 *LinkMutation) Fields() []string { + fields := make([]string, 0, 1) + if m.link_information != nil { + fields = append(fields, link.FieldLinkInformation) + } + 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 *LinkMutation) Field(name string) (ent.Value, bool) { + switch name { + case link.FieldLinkInformation: + return m.LinkInformation() + } + 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 *LinkMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case link.FieldLinkInformation: + return m.OldLinkInformation(ctx) + } + return nil, fmt.Errorf("unknown Link 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 *LinkMutation) SetField(name string, value ent.Value) error { + switch name { + case link.FieldLinkInformation: + v, ok := value.(map[string]schema.LinkInformation) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLinkInformation(v) + return nil + } + return fmt.Errorf("unknown Link field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LinkMutation) 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 *LinkMutation) 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 *LinkMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Link numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LinkMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LinkMutation) 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 *LinkMutation) ClearField(name string) error { + return fmt.Errorf("unknown Link 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 *LinkMutation) ResetField(name string) error { + switch name { + case link.FieldLinkInformation: + m.ResetLinkInformation() + return nil + } + return fmt.Errorf("unknown Link field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LinkMutation) 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 *LinkMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LinkMutation) 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 *LinkMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LinkMutation) 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 *LinkMutation) 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 *LinkMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Link 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 *LinkMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Link edge %s", name) +} + // MixinIDMutation represents an operation that mutates the MixinID nodes in the graph. type MixinIDMutation struct { config diff --git a/entc/integration/customid/ent/predicate/predicate.go b/entc/integration/customid/ent/predicate/predicate.go index d5e7034fc..f9838988f 100644 --- a/entc/integration/customid/ent/predicate/predicate.go +++ b/entc/integration/customid/ent/predicate/predicate.go @@ -34,6 +34,9 @@ type Group func(*sql.Selector) // IntSID is the predicate function for intsid builders. type IntSID func(*sql.Selector) +// Link is the predicate function for link builders. +type Link func(*sql.Selector) + // MixinID is the predicate function for mixinid builders. type MixinID func(*sql.Selector) diff --git a/entc/integration/customid/ent/privacy/privacy.go b/entc/integration/customid/ent/privacy/privacy.go index 3654205d9..e4e852980 100644 --- a/entc/integration/customid/ent/privacy/privacy.go +++ b/entc/integration/customid/ent/privacy/privacy.go @@ -346,6 +346,30 @@ func (f IntSIDMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.IntSIDMutation", m) } +// The LinkQueryRuleFunc type is an adapter to allow the use of ordinary +// functions as a query rule. +type LinkQueryRuleFunc func(context.Context, *ent.LinkQuery) error + +// EvalQuery return f(ctx, q). +func (f LinkQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error { + if q, ok := q.(*ent.LinkQuery); ok { + return f(ctx, q) + } + return Denyf("ent/privacy: unexpected query type %T, expect *ent.LinkQuery", q) +} + +// The LinkMutationRuleFunc type is an adapter to allow the use of ordinary +// functions as a mutation rule. +type LinkMutationRuleFunc func(context.Context, *ent.LinkMutation) error + +// EvalMutation calls f(ctx, m). +func (f LinkMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error { + if m, ok := m.(*ent.LinkMutation); ok { + return f(ctx, m) + } + return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.LinkMutation", m) +} + // The MixinIDQueryRuleFunc type is an adapter to allow the use of ordinary // functions as a query rule. type MixinIDQueryRuleFunc func(context.Context, *ent.MixinIDQuery) error @@ -589,6 +613,8 @@ func queryFilter(q ent.Query) (Filter, error) { return q.Filter(), nil case *ent.IntSIDQuery: return q.Filter(), nil + case *ent.LinkQuery: + return q.Filter(), nil case *ent.MixinIDQuery: return q.Filter(), nil case *ent.NoteQuery: @@ -628,6 +654,8 @@ func mutationFilter(m ent.Mutation) (Filter, error) { return m.Filter(), nil case *ent.IntSIDMutation: return m.Filter(), nil + case *ent.LinkMutation: + return m.Filter(), nil case *ent.MixinIDMutation: return m.Filter(), nil case *ent.NoteMutation: diff --git a/entc/integration/customid/ent/runtime.go b/entc/integration/customid/ent/runtime.go index b31e3ea18..7fa4a3427 100644 --- a/entc/integration/customid/ent/runtime.go +++ b/entc/integration/customid/ent/runtime.go @@ -15,6 +15,7 @@ import ( "entgo.io/ent/entc/integration/customid/ent/car" "entgo.io/ent/entc/integration/customid/ent/device" "entgo.io/ent/entc/integration/customid/ent/doc" + "entgo.io/ent/entc/integration/customid/ent/link" "entgo.io/ent/entc/integration/customid/ent/mixinid" "entgo.io/ent/entc/integration/customid/ent/note" "entgo.io/ent/entc/integration/customid/ent/other" @@ -23,6 +24,7 @@ import ( "entgo.io/ent/entc/integration/customid/ent/session" "entgo.io/ent/entc/integration/customid/ent/token" "entgo.io/ent/entc/integration/customid/sid" + uuidc "entgo.io/ent/entc/integration/customid/uuidcompatible" "github.com/google/uuid" ) @@ -107,6 +109,16 @@ func init() { return nil } }() + linkFields := schema.Link{}.Fields() + _ = linkFields + // linkDescLinkInformation is the schema descriptor for link_information field. + linkDescLinkInformation := linkFields[1].Descriptor() + // link.DefaultLinkInformation holds the default value on creation for the link_information field. + link.DefaultLinkInformation = linkDescLinkInformation.Default.(map[string]schema.LinkInformation) + // linkDescID is the schema descriptor for id field. + linkDescID := linkFields[0].Descriptor() + // link.DefaultID holds the default value on creation for the id field. + link.DefaultID = linkDescID.Default.(func() uuidc.UUIDC) mixinidMixin := schema.MixinID{}.Mixin() mixinidMixinFields0 := mixinidMixin[0].Fields() _ = mixinidMixinFields0 diff --git a/entc/integration/customid/ent/schema/link.go b/entc/integration/customid/ent/schema/link.go new file mode 100644 index 000000000..093b5e0b8 --- /dev/null +++ b/entc/integration/customid/ent/schema/link.go @@ -0,0 +1,35 @@ +// 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" + uuidc "entgo.io/ent/entc/integration/customid/uuidcompatible" + "entgo.io/ent/schema/field" +) + +type LinkInformation struct { + Name string + Link string +} + +// Link holds the schema definition for the Link entity. +type Link struct { + ent.Schema +} + +// Fields of the IntSid. +func (Link) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuidc.UUIDC{}).Default(uuidc.NewUUIDC), + field.JSON("link_information", map[string]LinkInformation{}). + Default(map[string]LinkInformation{ + "ent": { + Name: "ent", + Link: "https://entgo.io/", + }, + }), + } +} diff --git a/entc/integration/customid/ent/tx.go b/entc/integration/customid/ent/tx.go index 620ea68f3..d4f06abc4 100644 --- a/entc/integration/customid/ent/tx.go +++ b/entc/integration/customid/ent/tx.go @@ -32,6 +32,8 @@ type Tx struct { Group *GroupClient // IntSID is the client for interacting with the IntSID builders. IntSID *IntSIDClient + // Link is the client for interacting with the Link builders. + Link *LinkClient // MixinID is the client for interacting with the MixinID builders. MixinID *MixinIDClient // Note is the client for interacting with the Note builders. @@ -191,6 +193,7 @@ func (tx *Tx) init() { tx.Doc = NewDocClient(tx.config) tx.Group = NewGroupClient(tx.config) tx.IntSID = NewIntSIDClient(tx.config) + tx.Link = NewLinkClient(tx.config) tx.MixinID = NewMixinIDClient(tx.config) tx.Note = NewNoteClient(tx.config) tx.Other = NewOtherClient(tx.config) diff --git a/entc/integration/customid/uuidcompatible/uuidc.go b/entc/integration/customid/uuidcompatible/uuidc.go new file mode 100644 index 000000000..80ce40ae1 --- /dev/null +++ b/entc/integration/customid/uuidcompatible/uuidc.go @@ -0,0 +1,29 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +package uuidc + +import ( + "database/sql/driver" + + "github.com/google/uuid" +) + +type UUIDC struct { + uuid uuid.UUID +} + +func NewUUIDC() UUIDC { + return UUIDC{ + uuid: uuid.New(), + } +} + +func (u *UUIDC) Scan(src interface{}) error { + return u.uuid.Scan(src) +} + +func (u UUIDC) Value() (driver.Value, error) { + return u.uuid.Value() +}