From c9d50cb3d47c71c3f8469e2b85978d46a3b88afb Mon Sep 17 00:00:00 2001 From: mikestefanello Date: Wed, 15 Dec 2021 08:48:51 -0500 Subject: [PATCH] Added password token entity. --- config/config.go | 9 +- ent/client.go | 142 ++++- ent/config.go | 3 +- ent/ent.go | 4 +- ent/hook/hook.go | 13 + ent/migrate/schema.go | 23 + ent/mutation.go | 518 ++++++++++++++- ent/passwordtoken.go | 153 +++++ ent/passwordtoken/passwordtoken.go | 64 ++ ent/passwordtoken/where.go | 355 +++++++++++ ent/passwordtoken_create.go | 296 +++++++++ ent/passwordtoken_delete.go | 111 ++++ ent/passwordtoken_query.go | 994 +++++++++++++++++++++++++++++ ent/passwordtoken_update.go | 408 ++++++++++++ ent/predicate/predicate.go | 3 + ent/runtime.go | 11 + ent/schema/passwordtoken.go | 35 + ent/schema/user.go | 6 +- ent/tx.go | 5 +- ent/user.go | 26 + ent/user/user.go | 9 + ent/user/where.go | 29 + ent/user_create.go | 35 + ent/user_query.go | 76 ++- ent/user_update.go | 181 ++++++ 25 files changed, 3489 insertions(+), 20 deletions(-) create mode 100644 ent/passwordtoken.go create mode 100644 ent/passwordtoken/passwordtoken.go create mode 100644 ent/passwordtoken/where.go create mode 100644 ent/passwordtoken_create.go create mode 100644 ent/passwordtoken_delete.go create mode 100644 ent/passwordtoken_query.go create mode 100644 ent/passwordtoken_update.go create mode 100644 ent/schema/passwordtoken.go diff --git a/config/config.go b/config/config.go index 89aab02..a9ec743 100644 --- a/config/config.go +++ b/config/config.go @@ -46,10 +46,11 @@ type ( // AppConfig stores application configuration AppConfig struct { - Name string `env:"APP_NAME,default=Goweb"` - Environment Environment `env:"APP_ENVIRONMENT,default=local"` - EncryptionKey string `env:"APP_ENCRYPTION_KEY,default=?E(G+KbPeShVmYq3t6w9z$C&F)J@McQf"` - Timeout time.Duration `env:"APP_TIMEOUT,default=20s"` + Name string `env:"APP_NAME,default=Goweb"` + Environment Environment `env:"APP_ENVIRONMENT,default=local"` + EncryptionKey string `env:"APP_ENCRYPTION_KEY,default=?E(G+KbPeShVmYq3t6w9z$C&F)J@McQf"` + Timeout time.Duration `env:"APP_TIMEOUT,default=20s"` + PasswordTokenExpiration time.Duration `env:"APP_PASSWORD_TOKEN_EXPIRATION,default=60m"` } CacheConfig struct { diff --git a/ent/client.go b/ent/client.go index 0fb5c34..7b249f1 100644 --- a/ent/client.go +++ b/ent/client.go @@ -9,10 +9,12 @@ import ( "goweb/ent/migrate" + "goweb/ent/passwordtoken" "goweb/ent/user" "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" ) // Client is the client that holds all ent builders. @@ -20,6 +22,8 @@ type Client struct { config // Schema is the client for creating, migrating and dropping schema. Schema *migrate.Schema + // PasswordToken is the client for interacting with the PasswordToken builders. + PasswordToken *PasswordTokenClient // User is the client for interacting with the User builders. User *UserClient } @@ -35,6 +39,7 @@ func NewClient(opts ...Option) *Client { func (c *Client) init() { c.Schema = migrate.NewSchema(c.driver) + c.PasswordToken = NewPasswordTokenClient(c.config) c.User = NewUserClient(c.config) } @@ -67,9 +72,10 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { cfg := c.config cfg.driver = tx return &Tx{ - ctx: ctx, - config: cfg, - User: NewUserClient(cfg), + ctx: ctx, + config: cfg, + PasswordToken: NewPasswordTokenClient(cfg), + User: NewUserClient(cfg), }, nil } @@ -87,15 +93,16 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) cfg := c.config cfg.driver = &txDriver{tx: tx, drv: c.driver} return &Tx{ - config: cfg, - User: NewUserClient(cfg), + config: cfg, + PasswordToken: NewPasswordTokenClient(cfg), + User: NewUserClient(cfg), }, nil } // Debug returns a new debug-client. It's used to get verbose logging on specific operations. // // client.Debug(). -// User. +// PasswordToken. // Query(). // Count(ctx) // @@ -118,9 +125,116 @@ 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.PasswordToken.Use(hooks...) c.User.Use(hooks...) } +// PasswordTokenClient is a client for the PasswordToken schema. +type PasswordTokenClient struct { + config +} + +// NewPasswordTokenClient returns a client for the PasswordToken from the given config. +func NewPasswordTokenClient(c config) *PasswordTokenClient { + return &PasswordTokenClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `passwordtoken.Hooks(f(g(h())))`. +func (c *PasswordTokenClient) Use(hooks ...Hook) { + c.hooks.PasswordToken = append(c.hooks.PasswordToken, hooks...) +} + +// Create returns a create builder for PasswordToken. +func (c *PasswordTokenClient) Create() *PasswordTokenCreate { + mutation := newPasswordTokenMutation(c.config, OpCreate) + return &PasswordTokenCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of PasswordToken entities. +func (c *PasswordTokenClient) CreateBulk(builders ...*PasswordTokenCreate) *PasswordTokenCreateBulk { + return &PasswordTokenCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for PasswordToken. +func (c *PasswordTokenClient) Update() *PasswordTokenUpdate { + mutation := newPasswordTokenMutation(c.config, OpUpdate) + return &PasswordTokenUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *PasswordTokenClient) UpdateOne(pt *PasswordToken) *PasswordTokenUpdateOne { + mutation := newPasswordTokenMutation(c.config, OpUpdateOne, withPasswordToken(pt)) + return &PasswordTokenUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *PasswordTokenClient) UpdateOneID(id int) *PasswordTokenUpdateOne { + mutation := newPasswordTokenMutation(c.config, OpUpdateOne, withPasswordTokenID(id)) + return &PasswordTokenUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for PasswordToken. +func (c *PasswordTokenClient) Delete() *PasswordTokenDelete { + mutation := newPasswordTokenMutation(c.config, OpDelete) + return &PasswordTokenDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *PasswordTokenClient) DeleteOne(pt *PasswordToken) *PasswordTokenDeleteOne { + return c.DeleteOneID(pt.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *PasswordTokenClient) DeleteOneID(id int) *PasswordTokenDeleteOne { + builder := c.Delete().Where(passwordtoken.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &PasswordTokenDeleteOne{builder} +} + +// Query returns a query builder for PasswordToken. +func (c *PasswordTokenClient) Query() *PasswordTokenQuery { + return &PasswordTokenQuery{ + config: c.config, + } +} + +// Get returns a PasswordToken entity by its id. +func (c *PasswordTokenClient) Get(ctx context.Context, id int) (*PasswordToken, error) { + return c.Query().Where(passwordtoken.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *PasswordTokenClient) GetX(ctx context.Context, id int) *PasswordToken { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryUser queries the user edge of a PasswordToken. +func (c *PasswordTokenClient) QueryUser(pt *PasswordToken) *UserQuery { + query := &UserQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := pt.ID + step := sqlgraph.NewStep( + sqlgraph.From(passwordtoken.Table, passwordtoken.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, passwordtoken.UserTable, passwordtoken.UserColumn), + ) + fromV = sqlgraph.Neighbors(pt.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *PasswordTokenClient) Hooks() []Hook { + return c.hooks.PasswordToken +} + // UserClient is a client for the User schema. type UserClient struct { config @@ -206,6 +320,22 @@ func (c *UserClient) GetX(ctx context.Context, id int) *User { return obj } +// QueryOwner queries the owner edge of a User. +func (c *UserClient) QueryOwner(u *User) *PasswordTokenQuery { + query := &PasswordTokenQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := u.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(passwordtoken.Table, passwordtoken.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, user.OwnerTable, user.OwnerColumn), + ) + fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) + return fromV, nil + } + return query +} + // Hooks returns the client hooks. func (c *UserClient) Hooks() []Hook { return c.hooks.User diff --git a/ent/config.go b/ent/config.go index 854a830..a7d1d36 100644 --- a/ent/config.go +++ b/ent/config.go @@ -24,7 +24,8 @@ type config struct { // hooks per client, for fast access. type hooks struct { - User []ent.Hook + PasswordToken []ent.Hook + User []ent.Hook } // Options applies the options on the config object. diff --git a/ent/ent.go b/ent/ent.go index 7233b23..23d08c9 100644 --- a/ent/ent.go +++ b/ent/ent.go @@ -5,6 +5,7 @@ package ent import ( "errors" "fmt" + "goweb/ent/passwordtoken" "goweb/ent/user" "entgo.io/ent" @@ -29,7 +30,8 @@ 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{ - user.Table: user.ValidColumn, + passwordtoken.Table: passwordtoken.ValidColumn, + user.Table: user.ValidColumn, } check, ok := checks[table] if !ok { diff --git a/ent/hook/hook.go b/ent/hook/hook.go index fe38698..00aec9a 100644 --- a/ent/hook/hook.go +++ b/ent/hook/hook.go @@ -8,6 +8,19 @@ import ( "goweb/ent" ) +// The PasswordTokenFunc type is an adapter to allow the use of ordinary +// function as PasswordToken mutator. +type PasswordTokenFunc func(context.Context, *ent.PasswordTokenMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f PasswordTokenFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + mv, ok := m.(*ent.PasswordTokenMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.PasswordTokenMutation", m) + } + return f(ctx, mv) +} + // The UserFunc type is an adapter to allow the use of ordinary // function as User mutator. type UserFunc func(context.Context, *ent.UserMutation) (ent.Value, error) diff --git a/ent/migrate/schema.go b/ent/migrate/schema.go index f2d540e..005da13 100644 --- a/ent/migrate/schema.go +++ b/ent/migrate/schema.go @@ -8,6 +8,27 @@ import ( ) var ( + // PasswordTokensColumns holds the columns for the "password_tokens" table. + PasswordTokensColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "hash", Type: field.TypeString}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "password_token_user", Type: field.TypeInt, Nullable: true}, + } + // PasswordTokensTable holds the schema information for the "password_tokens" table. + PasswordTokensTable = &schema.Table{ + Name: "password_tokens", + Columns: PasswordTokensColumns, + PrimaryKey: []*schema.Column{PasswordTokensColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "password_tokens_users_user", + Columns: []*schema.Column{PasswordTokensColumns[3]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + } // UsersColumns holds the columns for the "users" table. UsersColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, @@ -24,9 +45,11 @@ var ( } // Tables holds all the tables in the schema. Tables = []*schema.Table{ + PasswordTokensTable, UsersTable, } ) func init() { + PasswordTokensTable.ForeignKeys[0].RefTable = UsersTable } diff --git a/ent/mutation.go b/ent/mutation.go index d8a8e73..bc344c1 100644 --- a/ent/mutation.go +++ b/ent/mutation.go @@ -5,6 +5,7 @@ package ent import ( "context" "fmt" + "goweb/ent/passwordtoken" "goweb/ent/predicate" "goweb/ent/user" "sync" @@ -22,9 +23,425 @@ const ( OpUpdateOne = ent.OpUpdateOne // Node types. - TypeUser = "User" + TypePasswordToken = "PasswordToken" + TypeUser = "User" ) +// PasswordTokenMutation represents an operation that mutates the PasswordToken nodes in the graph. +type PasswordTokenMutation struct { + config + op Op + typ string + id *int + hash *string + created_at *time.Time + clearedFields map[string]struct{} + user *int + cleareduser bool + done bool + oldValue func(context.Context) (*PasswordToken, error) + predicates []predicate.PasswordToken +} + +var _ ent.Mutation = (*PasswordTokenMutation)(nil) + +// passwordtokenOption allows management of the mutation configuration using functional options. +type passwordtokenOption func(*PasswordTokenMutation) + +// newPasswordTokenMutation creates new mutation for the PasswordToken entity. +func newPasswordTokenMutation(c config, op Op, opts ...passwordtokenOption) *PasswordTokenMutation { + m := &PasswordTokenMutation{ + config: c, + op: op, + typ: TypePasswordToken, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withPasswordTokenID sets the ID field of the mutation. +func withPasswordTokenID(id int) passwordtokenOption { + return func(m *PasswordTokenMutation) { + var ( + err error + once sync.Once + value *PasswordToken + ) + m.oldValue = func(ctx context.Context) (*PasswordToken, error) { + once.Do(func() { + if m.done { + err = fmt.Errorf("querying old values post mutation is not allowed") + } else { + value, err = m.Client().PasswordToken.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withPasswordToken sets the old PasswordToken of the mutation. +func withPasswordToken(node *PasswordToken) passwordtokenOption { + return func(m *PasswordTokenMutation) { + m.oldValue = func(context.Context) (*PasswordToken, 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 PasswordTokenMutation) 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 PasswordTokenMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, fmt.Errorf("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 *PasswordTokenMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// SetHash sets the "hash" field. +func (m *PasswordTokenMutation) SetHash(s string) { + m.hash = &s +} + +// Hash returns the value of the "hash" field in the mutation. +func (m *PasswordTokenMutation) Hash() (r string, exists bool) { + v := m.hash + if v == nil { + return + } + return *v, true +} + +// OldHash returns the old "hash" field's value of the PasswordToken entity. +// If the PasswordToken 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 *PasswordTokenMutation) OldHash(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldHash is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldHash requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldHash: %w", err) + } + return oldValue.Hash, nil +} + +// ResetHash resets all changes to the "hash" field. +func (m *PasswordTokenMutation) ResetHash() { + m.hash = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *PasswordTokenMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *PasswordTokenMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the PasswordToken entity. +// If the PasswordToken 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 *PasswordTokenMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *PasswordTokenMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUserID sets the "user" edge to the User entity by id. +func (m *PasswordTokenMutation) SetUserID(id int) { + m.user = &id +} + +// ClearUser clears the "user" edge to the User entity. +func (m *PasswordTokenMutation) ClearUser() { + m.cleareduser = true +} + +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *PasswordTokenMutation) UserCleared() bool { + return m.cleareduser +} + +// UserID returns the "user" edge ID in the mutation. +func (m *PasswordTokenMutation) UserID() (id int, exists bool) { + if m.user != nil { + return *m.user, true + } + return +} + +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *PasswordTokenMutation) UserIDs() (ids []int) { + if id := m.user; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetUser resets all changes to the "user" edge. +func (m *PasswordTokenMutation) ResetUser() { + m.user = nil + m.cleareduser = false +} + +// Where appends a list predicates to the PasswordTokenMutation builder. +func (m *PasswordTokenMutation) Where(ps ...predicate.PasswordToken) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *PasswordTokenMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (PasswordToken). +func (m *PasswordTokenMutation) 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 *PasswordTokenMutation) Fields() []string { + fields := make([]string, 0, 2) + if m.hash != nil { + fields = append(fields, passwordtoken.FieldHash) + } + if m.created_at != nil { + fields = append(fields, passwordtoken.FieldCreatedAt) + } + 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 *PasswordTokenMutation) Field(name string) (ent.Value, bool) { + switch name { + case passwordtoken.FieldHash: + return m.Hash() + case passwordtoken.FieldCreatedAt: + return m.CreatedAt() + } + 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 *PasswordTokenMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case passwordtoken.FieldHash: + return m.OldHash(ctx) + case passwordtoken.FieldCreatedAt: + return m.OldCreatedAt(ctx) + } + return nil, fmt.Errorf("unknown PasswordToken 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 *PasswordTokenMutation) SetField(name string, value ent.Value) error { + switch name { + case passwordtoken.FieldHash: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetHash(v) + return nil + case passwordtoken.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + } + return fmt.Errorf("unknown PasswordToken field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *PasswordTokenMutation) 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 *PasswordTokenMutation) 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 *PasswordTokenMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown PasswordToken numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *PasswordTokenMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *PasswordTokenMutation) 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 *PasswordTokenMutation) ClearField(name string) error { + return fmt.Errorf("unknown PasswordToken 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 *PasswordTokenMutation) ResetField(name string) error { + switch name { + case passwordtoken.FieldHash: + m.ResetHash() + return nil + case passwordtoken.FieldCreatedAt: + m.ResetCreatedAt() + return nil + } + return fmt.Errorf("unknown PasswordToken field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *PasswordTokenMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.user != nil { + edges = append(edges, passwordtoken.EdgeUser) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *PasswordTokenMutation) AddedIDs(name string) []ent.Value { + switch name { + case passwordtoken.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *PasswordTokenMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *PasswordTokenMutation) RemovedIDs(name string) []ent.Value { + switch name { + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *PasswordTokenMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.cleareduser { + edges = append(edges, passwordtoken.EdgeUser) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *PasswordTokenMutation) EdgeCleared(name string) bool { + switch name { + case passwordtoken.EdgeUser: + return m.cleareduser + } + 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 *PasswordTokenMutation) ClearEdge(name string) error { + switch name { + case passwordtoken.EdgeUser: + m.ClearUser() + return nil + } + return fmt.Errorf("unknown PasswordToken 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 *PasswordTokenMutation) ResetEdge(name string) error { + switch name { + case passwordtoken.EdgeUser: + m.ResetUser() + return nil + } + return fmt.Errorf("unknown PasswordToken edge %s", name) +} + // UserMutation represents an operation that mutates the User nodes in the graph. type UserMutation struct { config @@ -36,6 +453,9 @@ type UserMutation struct { password *string created_at *time.Time clearedFields map[string]struct{} + owner map[int]struct{} + removedowner map[int]struct{} + clearedowner bool done bool oldValue func(context.Context) (*User, error) predicates []predicate.User @@ -264,6 +684,60 @@ func (m *UserMutation) ResetCreatedAt() { m.created_at = nil } +// AddOwnerIDs adds the "owner" edge to the PasswordToken entity by ids. +func (m *UserMutation) AddOwnerIDs(ids ...int) { + if m.owner == nil { + m.owner = make(map[int]struct{}) + } + for i := range ids { + m.owner[ids[i]] = struct{}{} + } +} + +// ClearOwner clears the "owner" edge to the PasswordToken entity. +func (m *UserMutation) ClearOwner() { + m.clearedowner = true +} + +// OwnerCleared reports if the "owner" edge to the PasswordToken entity was cleared. +func (m *UserMutation) OwnerCleared() bool { + return m.clearedowner +} + +// RemoveOwnerIDs removes the "owner" edge to the PasswordToken entity by IDs. +func (m *UserMutation) RemoveOwnerIDs(ids ...int) { + if m.removedowner == nil { + m.removedowner = make(map[int]struct{}) + } + for i := range ids { + delete(m.owner, ids[i]) + m.removedowner[ids[i]] = struct{}{} + } +} + +// RemovedOwner returns the removed IDs of the "owner" edge to the PasswordToken entity. +func (m *UserMutation) RemovedOwnerIDs() (ids []int) { + for id := range m.removedowner { + ids = append(ids, id) + } + return +} + +// OwnerIDs returns the "owner" edge IDs in the mutation. +func (m *UserMutation) OwnerIDs() (ids []int) { + for id := range m.owner { + ids = append(ids, id) + } + return +} + +// ResetOwner resets all changes to the "owner" edge. +func (m *UserMutation) ResetOwner() { + m.owner = nil + m.clearedowner = false + m.removedowner = nil +} + // Where appends a list predicates to the UserMutation builder. func (m *UserMutation) Where(ps ...predicate.User) { m.predicates = append(m.predicates, ps...) @@ -433,48 +907,84 @@ func (m *UserMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *UserMutation) AddedEdges() []string { - edges := make([]string, 0, 0) + edges := make([]string, 0, 1) + if m.owner != nil { + edges = append(edges, user.EdgeOwner) + } return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. func (m *UserMutation) AddedIDs(name string) []ent.Value { + switch name { + case user.EdgeOwner: + ids := make([]ent.Value, 0, len(m.owner)) + for id := range m.owner { + ids = append(ids, id) + } + return ids + } return nil } // RemovedEdges returns all edge names that were removed in this mutation. func (m *UserMutation) RemovedEdges() []string { - edges := make([]string, 0, 0) + edges := make([]string, 0, 1) + if m.removedowner != nil { + edges = append(edges, user.EdgeOwner) + } return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. func (m *UserMutation) RemovedIDs(name string) []ent.Value { + switch name { + case user.EdgeOwner: + ids := make([]ent.Value, 0, len(m.removedowner)) + for id := range m.removedowner { + ids = append(ids, id) + } + return ids + } return nil } // ClearedEdges returns all edge names that were cleared in this mutation. func (m *UserMutation) ClearedEdges() []string { - edges := make([]string, 0, 0) + edges := make([]string, 0, 1) + if m.clearedowner { + edges = append(edges, user.EdgeOwner) + } return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. func (m *UserMutation) EdgeCleared(name string) bool { + switch name { + case user.EdgeOwner: + return m.clearedowner + } return false } // ClearEdge clears the value of the edge with the given name. It returns an error // if that edge is not defined in the schema. func (m *UserMutation) ClearEdge(name string) error { + switch name { + } return fmt.Errorf("unknown User unique edge %s", name) } // ResetEdge resets all changes to the edge with the given name in this mutation. // It returns an error if the edge is not defined in the schema. func (m *UserMutation) ResetEdge(name string) error { + switch name { + case user.EdgeOwner: + m.ResetOwner() + return nil + } return fmt.Errorf("unknown User edge %s", name) } diff --git a/ent/passwordtoken.go b/ent/passwordtoken.go new file mode 100644 index 0000000..86f92e9 --- /dev/null +++ b/ent/passwordtoken.go @@ -0,0 +1,153 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "fmt" + "goweb/ent/passwordtoken" + "goweb/ent/user" + "strings" + "time" + + "entgo.io/ent/dialect/sql" +) + +// PasswordToken is the model entity for the PasswordToken schema. +type PasswordToken struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Hash holds the value of the "hash" field. + Hash string `json:"-"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the PasswordTokenQuery when eager-loading is set. + Edges PasswordTokenEdges `json:"edges"` + password_token_user *int +} + +// PasswordTokenEdges holds the relations/edges for other nodes in the graph. +type PasswordTokenEdges struct { + // User holds the value of the user edge. + User *User `json:"user,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// UserOrErr returns the User value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e PasswordTokenEdges) UserOrErr() (*User, error) { + if e.loadedTypes[0] { + if e.User == nil { + // The edge user was loaded in eager-loading, + // but was not found. + return nil, &NotFoundError{label: user.Label} + } + return e.User, nil + } + return nil, &NotLoadedError{edge: "user"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*PasswordToken) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case passwordtoken.FieldID: + values[i] = new(sql.NullInt64) + case passwordtoken.FieldHash: + values[i] = new(sql.NullString) + case passwordtoken.FieldCreatedAt: + values[i] = new(sql.NullTime) + case passwordtoken.ForeignKeys[0]: // password_token_user + values[i] = new(sql.NullInt64) + default: + return nil, fmt.Errorf("unexpected column %q for type PasswordToken", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the PasswordToken fields. +func (pt *PasswordToken) assignValues(columns []string, values []interface{}) 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 passwordtoken.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + pt.ID = int(value.Int64) + case passwordtoken.FieldHash: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field hash", values[i]) + } else if value.Valid { + pt.Hash = value.String + } + case passwordtoken.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + pt.CreatedAt = value.Time + } + case passwordtoken.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field password_token_user", value) + } else if value.Valid { + pt.password_token_user = new(int) + *pt.password_token_user = int(value.Int64) + } + } + } + return nil +} + +// QueryUser queries the "user" edge of the PasswordToken entity. +func (pt *PasswordToken) QueryUser() *UserQuery { + return (&PasswordTokenClient{config: pt.config}).QueryUser(pt) +} + +// Update returns a builder for updating this PasswordToken. +// Note that you need to call PasswordToken.Unwrap() before calling this method if this PasswordToken +// was returned from a transaction, and the transaction was committed or rolled back. +func (pt *PasswordToken) Update() *PasswordTokenUpdateOne { + return (&PasswordTokenClient{config: pt.config}).UpdateOne(pt) +} + +// Unwrap unwraps the PasswordToken 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 (pt *PasswordToken) Unwrap() *PasswordToken { + tx, ok := pt.config.driver.(*txDriver) + if !ok { + panic("ent: PasswordToken is not a transactional entity") + } + pt.config.driver = tx.drv + return pt +} + +// String implements the fmt.Stringer. +func (pt *PasswordToken) String() string { + var builder strings.Builder + builder.WriteString("PasswordToken(") + builder.WriteString(fmt.Sprintf("id=%v", pt.ID)) + builder.WriteString(", hash=") + builder.WriteString(", created_at=") + builder.WriteString(pt.CreatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// PasswordTokens is a parsable slice of PasswordToken. +type PasswordTokens []*PasswordToken + +func (pt PasswordTokens) config(cfg config) { + for _i := range pt { + pt[_i].config = cfg + } +} diff --git a/ent/passwordtoken/passwordtoken.go b/ent/passwordtoken/passwordtoken.go new file mode 100644 index 0000000..56bff22 --- /dev/null +++ b/ent/passwordtoken/passwordtoken.go @@ -0,0 +1,64 @@ +// Code generated by entc, DO NOT EDIT. + +package passwordtoken + +import ( + "time" +) + +const ( + // Label holds the string label denoting the passwordtoken type in the database. + Label = "password_token" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldHash holds the string denoting the hash field in the database. + FieldHash = "hash" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // EdgeUser holds the string denoting the user edge name in mutations. + EdgeUser = "user" + // Table holds the table name of the passwordtoken in the database. + Table = "password_tokens" + // UserTable is the table that holds the user relation/edge. + UserTable = "password_tokens" + // UserInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + UserInverseTable = "users" + // UserColumn is the table column denoting the user relation/edge. + UserColumn = "password_token_user" +) + +// Columns holds all SQL columns for passwordtoken fields. +var Columns = []string{ + FieldID, + FieldHash, + FieldCreatedAt, +} + +// ForeignKeys holds the SQL foreign-keys that are owned by the "password_tokens" +// table and are not defined as standalone fields in the schema. +var ForeignKeys = []string{ + "password_token_user", +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + for i := range ForeignKeys { + if column == ForeignKeys[i] { + return true + } + } + return false +} + +var ( + // HashValidator is a validator for the "hash" field. It is called by the builders before save. + HashValidator func(string) error + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time +) diff --git a/ent/passwordtoken/where.go b/ent/passwordtoken/where.go new file mode 100644 index 0000000..cec00b7 --- /dev/null +++ b/ent/passwordtoken/where.go @@ -0,0 +1,355 @@ +// Code generated by entc, DO NOT EDIT. + +package passwordtoken + +import ( + "goweb/ent/predicate" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, 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 ...int) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, 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 int) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// Hash applies equality check predicate on the "hash" field. It's identical to HashEQ. +func Hash(v string) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldHash), v)) + }) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCreatedAt), v)) + }) +} + +// HashEQ applies the EQ predicate on the "hash" field. +func HashEQ(v string) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldHash), v)) + }) +} + +// HashNEQ applies the NEQ predicate on the "hash" field. +func HashNEQ(v string) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldHash), v)) + }) +} + +// HashIn applies the In predicate on the "hash" field. +func HashIn(vs ...string) predicate.PasswordToken { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.PasswordToken(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldHash), v...)) + }) +} + +// HashNotIn applies the NotIn predicate on the "hash" field. +func HashNotIn(vs ...string) predicate.PasswordToken { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.PasswordToken(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldHash), v...)) + }) +} + +// HashGT applies the GT predicate on the "hash" field. +func HashGT(v string) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldHash), v)) + }) +} + +// HashGTE applies the GTE predicate on the "hash" field. +func HashGTE(v string) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldHash), v)) + }) +} + +// HashLT applies the LT predicate on the "hash" field. +func HashLT(v string) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldHash), v)) + }) +} + +// HashLTE applies the LTE predicate on the "hash" field. +func HashLTE(v string) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldHash), v)) + }) +} + +// HashContains applies the Contains predicate on the "hash" field. +func HashContains(v string) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldHash), v)) + }) +} + +// HashHasPrefix applies the HasPrefix predicate on the "hash" field. +func HashHasPrefix(v string) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldHash), v)) + }) +} + +// HashHasSuffix applies the HasSuffix predicate on the "hash" field. +func HashHasSuffix(v string) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldHash), v)) + }) +} + +// HashEqualFold applies the EqualFold predicate on the "hash" field. +func HashEqualFold(v string) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldHash), v)) + }) +} + +// HashContainsFold applies the ContainsFold predicate on the "hash" field. +func HashContainsFold(v string) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldHash), v)) + }) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCreatedAt), v)) + }) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldCreatedAt), v)) + }) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.PasswordToken { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.PasswordToken(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldCreatedAt), v...)) + }) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.PasswordToken { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.PasswordToken(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldCreatedAt), v...)) + }) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldCreatedAt), v)) + }) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldCreatedAt), v)) + }) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldCreatedAt), v)) + }) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldCreatedAt), v)) + }) +} + +// HasUser applies the HasEdge predicate on the "user" edge. +func HasUser() predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates). +func HasUserWith(preds ...predicate.User) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.PasswordToken) predicate.PasswordToken { + return predicate.PasswordToken(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.PasswordToken) predicate.PasswordToken { + return predicate.PasswordToken(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.PasswordToken) predicate.PasswordToken { + return predicate.PasswordToken(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/ent/passwordtoken_create.go b/ent/passwordtoken_create.go new file mode 100644 index 0000000..3a7614f --- /dev/null +++ b/ent/passwordtoken_create.go @@ -0,0 +1,296 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "goweb/ent/passwordtoken" + "goweb/ent/user" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// PasswordTokenCreate is the builder for creating a PasswordToken entity. +type PasswordTokenCreate struct { + config + mutation *PasswordTokenMutation + hooks []Hook +} + +// SetHash sets the "hash" field. +func (ptc *PasswordTokenCreate) SetHash(s string) *PasswordTokenCreate { + ptc.mutation.SetHash(s) + return ptc +} + +// SetCreatedAt sets the "created_at" field. +func (ptc *PasswordTokenCreate) SetCreatedAt(t time.Time) *PasswordTokenCreate { + ptc.mutation.SetCreatedAt(t) + return ptc +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (ptc *PasswordTokenCreate) SetNillableCreatedAt(t *time.Time) *PasswordTokenCreate { + if t != nil { + ptc.SetCreatedAt(*t) + } + return ptc +} + +// SetUserID sets the "user" edge to the User entity by ID. +func (ptc *PasswordTokenCreate) SetUserID(id int) *PasswordTokenCreate { + ptc.mutation.SetUserID(id) + return ptc +} + +// SetUser sets the "user" edge to the User entity. +func (ptc *PasswordTokenCreate) SetUser(u *User) *PasswordTokenCreate { + return ptc.SetUserID(u.ID) +} + +// Mutation returns the PasswordTokenMutation object of the builder. +func (ptc *PasswordTokenCreate) Mutation() *PasswordTokenMutation { + return ptc.mutation +} + +// Save creates the PasswordToken in the database. +func (ptc *PasswordTokenCreate) Save(ctx context.Context) (*PasswordToken, error) { + var ( + err error + node *PasswordToken + ) + ptc.defaults() + if len(ptc.hooks) == 0 { + if err = ptc.check(); err != nil { + return nil, err + } + node, err = ptc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*PasswordTokenMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = ptc.check(); err != nil { + return nil, err + } + ptc.mutation = mutation + if node, err = ptc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(ptc.hooks) - 1; i >= 0; i-- { + if ptc.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = ptc.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, ptc.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (ptc *PasswordTokenCreate) SaveX(ctx context.Context) *PasswordToken { + v, err := ptc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ptc *PasswordTokenCreate) Exec(ctx context.Context) error { + _, err := ptc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ptc *PasswordTokenCreate) ExecX(ctx context.Context) { + if err := ptc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (ptc *PasswordTokenCreate) defaults() { + if _, ok := ptc.mutation.CreatedAt(); !ok { + v := passwordtoken.DefaultCreatedAt() + ptc.mutation.SetCreatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ptc *PasswordTokenCreate) check() error { + if _, ok := ptc.mutation.Hash(); !ok { + return &ValidationError{Name: "hash", err: errors.New(`ent: missing required field "hash"`)} + } + if v, ok := ptc.mutation.Hash(); ok { + if err := passwordtoken.HashValidator(v); err != nil { + return &ValidationError{Name: "hash", err: fmt.Errorf(`ent: validator failed for field "hash": %w`, err)} + } + } + if _, ok := ptc.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "created_at"`)} + } + if _, ok := ptc.mutation.UserID(); !ok { + return &ValidationError{Name: "user", err: errors.New("ent: missing required edge \"user\"")} + } + return nil +} + +func (ptc *PasswordTokenCreate) sqlSave(ctx context.Context) (*PasswordToken, error) { + _node, _spec := ptc.createSpec() + if err := sqlgraph.CreateNode(ctx, ptc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (ptc *PasswordTokenCreate) createSpec() (*PasswordToken, *sqlgraph.CreateSpec) { + var ( + _node = &PasswordToken{config: ptc.config} + _spec = &sqlgraph.CreateSpec{ + Table: passwordtoken.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: passwordtoken.FieldID, + }, + } + ) + if value, ok := ptc.mutation.Hash(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: passwordtoken.FieldHash, + }) + _node.Hash = value + } + if value, ok := ptc.mutation.CreatedAt(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: passwordtoken.FieldCreatedAt, + }) + _node.CreatedAt = value + } + if nodes := ptc.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: passwordtoken.UserTable, + Columns: []string{passwordtoken.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.password_token_user = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// PasswordTokenCreateBulk is the builder for creating many PasswordToken entities in bulk. +type PasswordTokenCreateBulk struct { + config + builders []*PasswordTokenCreate +} + +// Save creates the PasswordToken entities in the database. +func (ptcb *PasswordTokenCreateBulk) Save(ctx context.Context) ([]*PasswordToken, error) { + specs := make([]*sqlgraph.CreateSpec, len(ptcb.builders)) + nodes := make([]*PasswordToken, len(ptcb.builders)) + mutators := make([]Mutator, len(ptcb.builders)) + for i := range ptcb.builders { + func(i int, root context.Context) { + builder := ptcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*PasswordTokenMutation) + 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, ptcb.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, ptcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + 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, ptcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (ptcb *PasswordTokenCreateBulk) SaveX(ctx context.Context) []*PasswordToken { + v, err := ptcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ptcb *PasswordTokenCreateBulk) Exec(ctx context.Context) error { + _, err := ptcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ptcb *PasswordTokenCreateBulk) ExecX(ctx context.Context) { + if err := ptcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/passwordtoken_delete.go b/ent/passwordtoken_delete.go new file mode 100644 index 0000000..6a9ee38 --- /dev/null +++ b/ent/passwordtoken_delete.go @@ -0,0 +1,111 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "goweb/ent/passwordtoken" + "goweb/ent/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// PasswordTokenDelete is the builder for deleting a PasswordToken entity. +type PasswordTokenDelete struct { + config + hooks []Hook + mutation *PasswordTokenMutation +} + +// Where appends a list predicates to the PasswordTokenDelete builder. +func (ptd *PasswordTokenDelete) Where(ps ...predicate.PasswordToken) *PasswordTokenDelete { + ptd.mutation.Where(ps...) + return ptd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (ptd *PasswordTokenDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(ptd.hooks) == 0 { + affected, err = ptd.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*PasswordTokenMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + ptd.mutation = mutation + affected, err = ptd.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(ptd.hooks) - 1; i >= 0; i-- { + if ptd.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = ptd.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, ptd.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ptd *PasswordTokenDelete) ExecX(ctx context.Context) int { + n, err := ptd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (ptd *PasswordTokenDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: passwordtoken.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: passwordtoken.FieldID, + }, + }, + } + if ps := ptd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, ptd.driver, _spec) +} + +// PasswordTokenDeleteOne is the builder for deleting a single PasswordToken entity. +type PasswordTokenDeleteOne struct { + ptd *PasswordTokenDelete +} + +// Exec executes the deletion query. +func (ptdo *PasswordTokenDeleteOne) Exec(ctx context.Context) error { + n, err := ptdo.ptd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{passwordtoken.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (ptdo *PasswordTokenDeleteOne) ExecX(ctx context.Context) { + ptdo.ptd.ExecX(ctx) +} diff --git a/ent/passwordtoken_query.go b/ent/passwordtoken_query.go new file mode 100644 index 0000000..1e34e6a --- /dev/null +++ b/ent/passwordtoken_query.go @@ -0,0 +1,994 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "goweb/ent/passwordtoken" + "goweb/ent/predicate" + "goweb/ent/user" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// PasswordTokenQuery is the builder for querying PasswordToken entities. +type PasswordTokenQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.PasswordToken + // eager-loading edges. + withUser *UserQuery + withFKs bool + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the PasswordTokenQuery builder. +func (ptq *PasswordTokenQuery) Where(ps ...predicate.PasswordToken) *PasswordTokenQuery { + ptq.predicates = append(ptq.predicates, ps...) + return ptq +} + +// Limit adds a limit step to the query. +func (ptq *PasswordTokenQuery) Limit(limit int) *PasswordTokenQuery { + ptq.limit = &limit + return ptq +} + +// Offset adds an offset step to the query. +func (ptq *PasswordTokenQuery) Offset(offset int) *PasswordTokenQuery { + ptq.offset = &offset + return ptq +} + +// 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 (ptq *PasswordTokenQuery) Unique(unique bool) *PasswordTokenQuery { + ptq.unique = &unique + return ptq +} + +// Order adds an order step to the query. +func (ptq *PasswordTokenQuery) Order(o ...OrderFunc) *PasswordTokenQuery { + ptq.order = append(ptq.order, o...) + return ptq +} + +// QueryUser chains the current query on the "user" edge. +func (ptq *PasswordTokenQuery) QueryUser() *UserQuery { + query := &UserQuery{config: ptq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := ptq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := ptq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(passwordtoken.Table, passwordtoken.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, passwordtoken.UserTable, passwordtoken.UserColumn), + ) + fromU = sqlgraph.SetNeighbors(ptq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first PasswordToken entity from the query. +// Returns a *NotFoundError when no PasswordToken was found. +func (ptq *PasswordTokenQuery) First(ctx context.Context) (*PasswordToken, error) { + nodes, err := ptq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{passwordtoken.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (ptq *PasswordTokenQuery) FirstX(ctx context.Context) *PasswordToken { + node, err := ptq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first PasswordToken ID from the query. +// Returns a *NotFoundError when no PasswordToken ID was found. +func (ptq *PasswordTokenQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = ptq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{passwordtoken.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (ptq *PasswordTokenQuery) FirstIDX(ctx context.Context) int { + id, err := ptq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single PasswordToken entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when exactly one PasswordToken entity is not found. +// Returns a *NotFoundError when no PasswordToken entities are found. +func (ptq *PasswordTokenQuery) Only(ctx context.Context) (*PasswordToken, error) { + nodes, err := ptq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{passwordtoken.Label} + default: + return nil, &NotSingularError{passwordtoken.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (ptq *PasswordTokenQuery) OnlyX(ctx context.Context) *PasswordToken { + node, err := ptq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only PasswordToken ID in the query. +// Returns a *NotSingularError when exactly one PasswordToken ID is not found. +// Returns a *NotFoundError when no entities are found. +func (ptq *PasswordTokenQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = ptq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{passwordtoken.Label} + default: + err = &NotSingularError{passwordtoken.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (ptq *PasswordTokenQuery) OnlyIDX(ctx context.Context) int { + id, err := ptq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of PasswordTokens. +func (ptq *PasswordTokenQuery) All(ctx context.Context) ([]*PasswordToken, error) { + if err := ptq.prepareQuery(ctx); err != nil { + return nil, err + } + return ptq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (ptq *PasswordTokenQuery) AllX(ctx context.Context) []*PasswordToken { + nodes, err := ptq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of PasswordToken IDs. +func (ptq *PasswordTokenQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := ptq.Select(passwordtoken.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (ptq *PasswordTokenQuery) IDsX(ctx context.Context) []int { + ids, err := ptq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (ptq *PasswordTokenQuery) Count(ctx context.Context) (int, error) { + if err := ptq.prepareQuery(ctx); err != nil { + return 0, err + } + return ptq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (ptq *PasswordTokenQuery) CountX(ctx context.Context) int { + count, err := ptq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (ptq *PasswordTokenQuery) Exist(ctx context.Context) (bool, error) { + if err := ptq.prepareQuery(ctx); err != nil { + return false, err + } + return ptq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (ptq *PasswordTokenQuery) ExistX(ctx context.Context) bool { + exist, err := ptq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the PasswordTokenQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (ptq *PasswordTokenQuery) Clone() *PasswordTokenQuery { + if ptq == nil { + return nil + } + return &PasswordTokenQuery{ + config: ptq.config, + limit: ptq.limit, + offset: ptq.offset, + order: append([]OrderFunc{}, ptq.order...), + predicates: append([]predicate.PasswordToken{}, ptq.predicates...), + withUser: ptq.withUser.Clone(), + // clone intermediate query. + sql: ptq.sql.Clone(), + path: ptq.path, + } +} + +// WithUser tells the query-builder to eager-load the nodes that are connected to +// the "user" edge. The optional arguments are used to configure the query builder of the edge. +func (ptq *PasswordTokenQuery) WithUser(opts ...func(*UserQuery)) *PasswordTokenQuery { + query := &UserQuery{config: ptq.config} + for _, opt := range opts { + opt(query) + } + ptq.withUser = query + return ptq +} + +// 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 { +// Hash string `json:"hash,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.PasswordToken.Query(). +// GroupBy(passwordtoken.FieldHash). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +// +func (ptq *PasswordTokenQuery) GroupBy(field string, fields ...string) *PasswordTokenGroupBy { + group := &PasswordTokenGroupBy{config: ptq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := ptq.prepareQuery(ctx); err != nil { + return nil, err + } + return ptq.sqlQuery(ctx), nil + } + return group +} + +// 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 { +// Hash string `json:"hash,omitempty"` +// } +// +// client.PasswordToken.Query(). +// Select(passwordtoken.FieldHash). +// Scan(ctx, &v) +// +func (ptq *PasswordTokenQuery) Select(fields ...string) *PasswordTokenSelect { + ptq.fields = append(ptq.fields, fields...) + return &PasswordTokenSelect{PasswordTokenQuery: ptq} +} + +func (ptq *PasswordTokenQuery) prepareQuery(ctx context.Context) error { + for _, f := range ptq.fields { + if !passwordtoken.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if ptq.path != nil { + prev, err := ptq.path(ctx) + if err != nil { + return err + } + ptq.sql = prev + } + return nil +} + +func (ptq *PasswordTokenQuery) sqlAll(ctx context.Context) ([]*PasswordToken, error) { + var ( + nodes = []*PasswordToken{} + withFKs = ptq.withFKs + _spec = ptq.querySpec() + loadedTypes = [1]bool{ + ptq.withUser != nil, + } + ) + if ptq.withUser != nil { + withFKs = true + } + if withFKs { + _spec.Node.Columns = append(_spec.Node.Columns, passwordtoken.ForeignKeys...) + } + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + node := &PasswordToken{config: ptq.config} + nodes = append(nodes, node) + return node.scanValues(columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + if len(nodes) == 0 { + return fmt.Errorf("ent: Assign called without calling ScanValues") + } + node := nodes[len(nodes)-1] + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if err := sqlgraph.QueryNodes(ctx, ptq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + + if query := ptq.withUser; query != nil { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*PasswordToken) + for i := range nodes { + if nodes[i].password_token_user == nil { + continue + } + fk := *nodes[i].password_token_user + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + query.Where(user.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "password_token_user" returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.User = n + } + } + } + + return nodes, nil +} + +func (ptq *PasswordTokenQuery) sqlCount(ctx context.Context) (int, error) { + _spec := ptq.querySpec() + return sqlgraph.CountNodes(ctx, ptq.driver, _spec) +} + +func (ptq *PasswordTokenQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := ptq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("ent: check existence: %w", err) + } + return n > 0, nil +} + +func (ptq *PasswordTokenQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: passwordtoken.Table, + Columns: passwordtoken.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: passwordtoken.FieldID, + }, + }, + From: ptq.sql, + Unique: true, + } + if unique := ptq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := ptq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, passwordtoken.FieldID) + for i := range fields { + if fields[i] != passwordtoken.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := ptq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := ptq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := ptq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := ptq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (ptq *PasswordTokenQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(ptq.driver.Dialect()) + t1 := builder.Table(passwordtoken.Table) + columns := ptq.fields + if len(columns) == 0 { + columns = passwordtoken.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if ptq.sql != nil { + selector = ptq.sql + selector.Select(selector.Columns(columns...)...) + } + for _, p := range ptq.predicates { + p(selector) + } + for _, p := range ptq.order { + p(selector) + } + if offset := ptq.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 := ptq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// PasswordTokenGroupBy is the group-by builder for PasswordToken entities. +type PasswordTokenGroupBy struct { + config + 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 (ptgb *PasswordTokenGroupBy) Aggregate(fns ...AggregateFunc) *PasswordTokenGroupBy { + ptgb.fns = append(ptgb.fns, fns...) + return ptgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (ptgb *PasswordTokenGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := ptgb.path(ctx) + if err != nil { + return err + } + ptgb.sql = query + return ptgb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (ptgb *PasswordTokenGroupBy) ScanX(ctx context.Context, v interface{}) { + if err := ptgb.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from group-by. +// It is only allowed when executing a group-by query with one field. +func (ptgb *PasswordTokenGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(ptgb.fields) > 1 { + return nil, errors.New("ent: PasswordTokenGroupBy.Strings is not achievable when grouping more than 1 field") + } + var v []string + if err := ptgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (ptgb *PasswordTokenGroupBy) StringsX(ctx context.Context) []string { + v, err := ptgb.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (ptgb *PasswordTokenGroupBy) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = ptgb.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{passwordtoken.Label} + default: + err = fmt.Errorf("ent: PasswordTokenGroupBy.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (ptgb *PasswordTokenGroupBy) StringX(ctx context.Context) string { + v, err := ptgb.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from group-by. +// It is only allowed when executing a group-by query with one field. +func (ptgb *PasswordTokenGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(ptgb.fields) > 1 { + return nil, errors.New("ent: PasswordTokenGroupBy.Ints is not achievable when grouping more than 1 field") + } + var v []int + if err := ptgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (ptgb *PasswordTokenGroupBy) IntsX(ctx context.Context) []int { + v, err := ptgb.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (ptgb *PasswordTokenGroupBy) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = ptgb.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{passwordtoken.Label} + default: + err = fmt.Errorf("ent: PasswordTokenGroupBy.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (ptgb *PasswordTokenGroupBy) IntX(ctx context.Context) int { + v, err := ptgb.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from group-by. +// It is only allowed when executing a group-by query with one field. +func (ptgb *PasswordTokenGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(ptgb.fields) > 1 { + return nil, errors.New("ent: PasswordTokenGroupBy.Float64s is not achievable when grouping more than 1 field") + } + var v []float64 + if err := ptgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (ptgb *PasswordTokenGroupBy) Float64sX(ctx context.Context) []float64 { + v, err := ptgb.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (ptgb *PasswordTokenGroupBy) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = ptgb.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{passwordtoken.Label} + default: + err = fmt.Errorf("ent: PasswordTokenGroupBy.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (ptgb *PasswordTokenGroupBy) Float64X(ctx context.Context) float64 { + v, err := ptgb.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from group-by. +// It is only allowed when executing a group-by query with one field. +func (ptgb *PasswordTokenGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(ptgb.fields) > 1 { + return nil, errors.New("ent: PasswordTokenGroupBy.Bools is not achievable when grouping more than 1 field") + } + var v []bool + if err := ptgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (ptgb *PasswordTokenGroupBy) BoolsX(ctx context.Context) []bool { + v, err := ptgb.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (ptgb *PasswordTokenGroupBy) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = ptgb.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{passwordtoken.Label} + default: + err = fmt.Errorf("ent: PasswordTokenGroupBy.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (ptgb *PasswordTokenGroupBy) BoolX(ctx context.Context) bool { + v, err := ptgb.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (ptgb *PasswordTokenGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range ptgb.fields { + if !passwordtoken.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := ptgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := ptgb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (ptgb *PasswordTokenGroupBy) sqlQuery() *sql.Selector { + selector := ptgb.sql.Select() + aggregation := make([]string, 0, len(ptgb.fns)) + for _, fn := range ptgb.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(ptgb.fields)+len(ptgb.fns)) + for _, f := range ptgb.fields { + columns = append(columns, selector.C(f)) + } + for _, c := range aggregation { + columns = append(columns, c) + } + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(ptgb.fields...)...) +} + +// PasswordTokenSelect is the builder for selecting fields of PasswordToken entities. +type PasswordTokenSelect struct { + *PasswordTokenQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (pts *PasswordTokenSelect) Scan(ctx context.Context, v interface{}) error { + if err := pts.prepareQuery(ctx); err != nil { + return err + } + pts.sql = pts.PasswordTokenQuery.sqlQuery(ctx) + return pts.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (pts *PasswordTokenSelect) ScanX(ctx context.Context, v interface{}) { + if err := pts.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (pts *PasswordTokenSelect) Strings(ctx context.Context) ([]string, error) { + if len(pts.fields) > 1 { + return nil, errors.New("ent: PasswordTokenSelect.Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := pts.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (pts *PasswordTokenSelect) StringsX(ctx context.Context) []string { + v, err := pts.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (pts *PasswordTokenSelect) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = pts.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{passwordtoken.Label} + default: + err = fmt.Errorf("ent: PasswordTokenSelect.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (pts *PasswordTokenSelect) StringX(ctx context.Context) string { + v, err := pts.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (pts *PasswordTokenSelect) Ints(ctx context.Context) ([]int, error) { + if len(pts.fields) > 1 { + return nil, errors.New("ent: PasswordTokenSelect.Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := pts.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (pts *PasswordTokenSelect) IntsX(ctx context.Context) []int { + v, err := pts.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (pts *PasswordTokenSelect) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = pts.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{passwordtoken.Label} + default: + err = fmt.Errorf("ent: PasswordTokenSelect.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (pts *PasswordTokenSelect) IntX(ctx context.Context) int { + v, err := pts.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (pts *PasswordTokenSelect) Float64s(ctx context.Context) ([]float64, error) { + if len(pts.fields) > 1 { + return nil, errors.New("ent: PasswordTokenSelect.Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := pts.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (pts *PasswordTokenSelect) Float64sX(ctx context.Context) []float64 { + v, err := pts.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (pts *PasswordTokenSelect) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = pts.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{passwordtoken.Label} + default: + err = fmt.Errorf("ent: PasswordTokenSelect.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (pts *PasswordTokenSelect) Float64X(ctx context.Context) float64 { + v, err := pts.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (pts *PasswordTokenSelect) Bools(ctx context.Context) ([]bool, error) { + if len(pts.fields) > 1 { + return nil, errors.New("ent: PasswordTokenSelect.Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := pts.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (pts *PasswordTokenSelect) BoolsX(ctx context.Context) []bool { + v, err := pts.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (pts *PasswordTokenSelect) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = pts.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{passwordtoken.Label} + default: + err = fmt.Errorf("ent: PasswordTokenSelect.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (pts *PasswordTokenSelect) BoolX(ctx context.Context) bool { + v, err := pts.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (pts *PasswordTokenSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := pts.sql.Query() + if err := pts.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/ent/passwordtoken_update.go b/ent/passwordtoken_update.go new file mode 100644 index 0000000..9f4e3ff --- /dev/null +++ b/ent/passwordtoken_update.go @@ -0,0 +1,408 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "goweb/ent/passwordtoken" + "goweb/ent/predicate" + "goweb/ent/user" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// PasswordTokenUpdate is the builder for updating PasswordToken entities. +type PasswordTokenUpdate struct { + config + hooks []Hook + mutation *PasswordTokenMutation +} + +// Where appends a list predicates to the PasswordTokenUpdate builder. +func (ptu *PasswordTokenUpdate) Where(ps ...predicate.PasswordToken) *PasswordTokenUpdate { + ptu.mutation.Where(ps...) + return ptu +} + +// SetHash sets the "hash" field. +func (ptu *PasswordTokenUpdate) SetHash(s string) *PasswordTokenUpdate { + ptu.mutation.SetHash(s) + return ptu +} + +// SetUserID sets the "user" edge to the User entity by ID. +func (ptu *PasswordTokenUpdate) SetUserID(id int) *PasswordTokenUpdate { + ptu.mutation.SetUserID(id) + return ptu +} + +// SetUser sets the "user" edge to the User entity. +func (ptu *PasswordTokenUpdate) SetUser(u *User) *PasswordTokenUpdate { + return ptu.SetUserID(u.ID) +} + +// Mutation returns the PasswordTokenMutation object of the builder. +func (ptu *PasswordTokenUpdate) Mutation() *PasswordTokenMutation { + return ptu.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (ptu *PasswordTokenUpdate) ClearUser() *PasswordTokenUpdate { + ptu.mutation.ClearUser() + return ptu +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (ptu *PasswordTokenUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(ptu.hooks) == 0 { + if err = ptu.check(); err != nil { + return 0, err + } + affected, err = ptu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*PasswordTokenMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = ptu.check(); err != nil { + return 0, err + } + ptu.mutation = mutation + affected, err = ptu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(ptu.hooks) - 1; i >= 0; i-- { + if ptu.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = ptu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, ptu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (ptu *PasswordTokenUpdate) SaveX(ctx context.Context) int { + affected, err := ptu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (ptu *PasswordTokenUpdate) Exec(ctx context.Context) error { + _, err := ptu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ptu *PasswordTokenUpdate) ExecX(ctx context.Context) { + if err := ptu.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ptu *PasswordTokenUpdate) check() error { + if v, ok := ptu.mutation.Hash(); ok { + if err := passwordtoken.HashValidator(v); err != nil { + return &ValidationError{Name: "hash", err: fmt.Errorf("ent: validator failed for field \"hash\": %w", err)} + } + } + if _, ok := ptu.mutation.UserID(); ptu.mutation.UserCleared() && !ok { + return errors.New("ent: clearing a required unique edge \"user\"") + } + return nil +} + +func (ptu *PasswordTokenUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: passwordtoken.Table, + Columns: passwordtoken.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: passwordtoken.FieldID, + }, + }, + } + if ps := ptu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := ptu.mutation.Hash(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: passwordtoken.FieldHash, + }) + } + if ptu.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: passwordtoken.UserTable, + Columns: []string{passwordtoken.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ptu.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: passwordtoken.UserTable, + Columns: []string{passwordtoken.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if n, err = sqlgraph.UpdateNodes(ctx, ptu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{passwordtoken.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// PasswordTokenUpdateOne is the builder for updating a single PasswordToken entity. +type PasswordTokenUpdateOne struct { + config + fields []string + hooks []Hook + mutation *PasswordTokenMutation +} + +// SetHash sets the "hash" field. +func (ptuo *PasswordTokenUpdateOne) SetHash(s string) *PasswordTokenUpdateOne { + ptuo.mutation.SetHash(s) + return ptuo +} + +// SetUserID sets the "user" edge to the User entity by ID. +func (ptuo *PasswordTokenUpdateOne) SetUserID(id int) *PasswordTokenUpdateOne { + ptuo.mutation.SetUserID(id) + return ptuo +} + +// SetUser sets the "user" edge to the User entity. +func (ptuo *PasswordTokenUpdateOne) SetUser(u *User) *PasswordTokenUpdateOne { + return ptuo.SetUserID(u.ID) +} + +// Mutation returns the PasswordTokenMutation object of the builder. +func (ptuo *PasswordTokenUpdateOne) Mutation() *PasswordTokenMutation { + return ptuo.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (ptuo *PasswordTokenUpdateOne) ClearUser() *PasswordTokenUpdateOne { + ptuo.mutation.ClearUser() + return ptuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (ptuo *PasswordTokenUpdateOne) Select(field string, fields ...string) *PasswordTokenUpdateOne { + ptuo.fields = append([]string{field}, fields...) + return ptuo +} + +// Save executes the query and returns the updated PasswordToken entity. +func (ptuo *PasswordTokenUpdateOne) Save(ctx context.Context) (*PasswordToken, error) { + var ( + err error + node *PasswordToken + ) + if len(ptuo.hooks) == 0 { + if err = ptuo.check(); err != nil { + return nil, err + } + node, err = ptuo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*PasswordTokenMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = ptuo.check(); err != nil { + return nil, err + } + ptuo.mutation = mutation + node, err = ptuo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(ptuo.hooks) - 1; i >= 0; i-- { + if ptuo.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = ptuo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, ptuo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (ptuo *PasswordTokenUpdateOne) SaveX(ctx context.Context) *PasswordToken { + node, err := ptuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (ptuo *PasswordTokenUpdateOne) Exec(ctx context.Context) error { + _, err := ptuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ptuo *PasswordTokenUpdateOne) ExecX(ctx context.Context) { + if err := ptuo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ptuo *PasswordTokenUpdateOne) check() error { + if v, ok := ptuo.mutation.Hash(); ok { + if err := passwordtoken.HashValidator(v); err != nil { + return &ValidationError{Name: "hash", err: fmt.Errorf("ent: validator failed for field \"hash\": %w", err)} + } + } + if _, ok := ptuo.mutation.UserID(); ptuo.mutation.UserCleared() && !ok { + return errors.New("ent: clearing a required unique edge \"user\"") + } + return nil +} + +func (ptuo *PasswordTokenUpdateOne) sqlSave(ctx context.Context) (_node *PasswordToken, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: passwordtoken.Table, + Columns: passwordtoken.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: passwordtoken.FieldID, + }, + }, + } + id, ok := ptuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing PasswordToken.ID for update")} + } + _spec.Node.ID.Value = id + if fields := ptuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, passwordtoken.FieldID) + for _, f := range fields { + if !passwordtoken.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != passwordtoken.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := ptuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := ptuo.mutation.Hash(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: passwordtoken.FieldHash, + }) + } + if ptuo.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: passwordtoken.UserTable, + Columns: []string{passwordtoken.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ptuo.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: passwordtoken.UserTable, + Columns: []string{passwordtoken.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &PasswordToken{config: ptuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, ptuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{passwordtoken.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/ent/predicate/predicate.go b/ent/predicate/predicate.go index 8c7579f..c10c042 100644 --- a/ent/predicate/predicate.go +++ b/ent/predicate/predicate.go @@ -6,5 +6,8 @@ import ( "entgo.io/ent/dialect/sql" ) +// PasswordToken is the predicate function for passwordtoken builders. +type PasswordToken func(*sql.Selector) + // User is the predicate function for user builders. type User func(*sql.Selector) diff --git a/ent/runtime.go b/ent/runtime.go index 508003d..1a08773 100644 --- a/ent/runtime.go +++ b/ent/runtime.go @@ -3,6 +3,7 @@ package ent import ( + "goweb/ent/passwordtoken" "goweb/ent/schema" "goweb/ent/user" "time" @@ -12,6 +13,16 @@ import ( // (default values, validators, hooks and policies) and stitches it // to their package variables. func init() { + passwordtokenFields := schema.PasswordToken{}.Fields() + _ = passwordtokenFields + // passwordtokenDescHash is the schema descriptor for hash field. + passwordtokenDescHash := passwordtokenFields[0].Descriptor() + // passwordtoken.HashValidator is a validator for the "hash" field. It is called by the builders before save. + passwordtoken.HashValidator = passwordtokenDescHash.Validators[0].(func(string) error) + // passwordtokenDescCreatedAt is the schema descriptor for created_at field. + passwordtokenDescCreatedAt := passwordtokenFields[1].Descriptor() + // passwordtoken.DefaultCreatedAt holds the default value on creation for the created_at field. + passwordtoken.DefaultCreatedAt = passwordtokenDescCreatedAt.Default.(func() time.Time) userFields := schema.User{}.Fields() _ = userFields // userDescName is the schema descriptor for name field. diff --git a/ent/schema/passwordtoken.go b/ent/schema/passwordtoken.go new file mode 100644 index 0000000..3384172 --- /dev/null +++ b/ent/schema/passwordtoken.go @@ -0,0 +1,35 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +// PasswordToken holds the schema definition for the PasswordToken entity. +type PasswordToken struct { + ent.Schema +} + +// Fields of the PasswordToken. +func (PasswordToken) Fields() []ent.Field { + return []ent.Field{ + field.String("hash"). + Sensitive(). + NotEmpty(), + field.Time("created_at"). + Default(time.Now). + Immutable(), + } +} + +// Edges of the PasswordToken. +func (PasswordToken) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("user", User.Type). + Required(). + Unique(), + } +} diff --git a/ent/schema/user.go b/ent/schema/user.go index 1abd475..d81ec5a 100644 --- a/ent/schema/user.go +++ b/ent/schema/user.go @@ -4,6 +4,7 @@ import ( "time" "entgo.io/ent" + "entgo.io/ent/schema/edge" "entgo.io/ent/schema/field" ) @@ -31,5 +32,8 @@ func (User) Fields() []ent.Field { // Edges of the User. func (User) Edges() []ent.Edge { - return nil + return []ent.Edge{ + edge.From("owner", PasswordToken.Type). + Ref("user"), + } } diff --git a/ent/tx.go b/ent/tx.go index f2149ed..7b4c06a 100644 --- a/ent/tx.go +++ b/ent/tx.go @@ -12,6 +12,8 @@ import ( // Tx is a transactional client that is created by calling Client.Tx(). type Tx struct { config + // PasswordToken is the client for interacting with the PasswordToken builders. + PasswordToken *PasswordTokenClient // User is the client for interacting with the User builders. User *UserClient @@ -149,6 +151,7 @@ func (tx *Tx) Client() *Client { } func (tx *Tx) init() { + tx.PasswordToken = NewPasswordTokenClient(tx.config) tx.User = NewUserClient(tx.config) } @@ -159,7 +162,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: User.QueryXXX(), the query will be executed +// applies a query, for example: PasswordToken.QueryXXX(), the query will be executed // through the driver which created this transaction. // // Note that txDriver is not goroutine safe. diff --git a/ent/user.go b/ent/user.go index 7f52873..2dfe64a 100644 --- a/ent/user.go +++ b/ent/user.go @@ -24,6 +24,27 @@ type User struct { Password string `json:"-"` // CreatedAt holds the value of the "created_at" field. CreatedAt time.Time `json:"created_at,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the UserQuery when eager-loading is set. + Edges UserEdges `json:"edges"` +} + +// UserEdges holds the relations/edges for other nodes in the graph. +type UserEdges struct { + // Owner holds the value of the owner edge. + Owner []*PasswordToken `json:"owner,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// OwnerOrErr returns the Owner value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) OwnerOrErr() ([]*PasswordToken, error) { + if e.loadedTypes[0] { + return e.Owner, nil + } + return nil, &NotLoadedError{edge: "owner"} } // scanValues returns the types for scanning values from sql.Rows. @@ -87,6 +108,11 @@ func (u *User) assignValues(columns []string, values []interface{}) error { return nil } +// QueryOwner queries the "owner" edge of the User entity. +func (u *User) QueryOwner() *PasswordTokenQuery { + return (&UserClient{config: u.config}).QueryOwner(u) +} + // Update returns a builder for updating this User. // Note that you need to call User.Unwrap() before calling this method if this User // was returned from a transaction, and the transaction was committed or rolled back. diff --git a/ent/user/user.go b/ent/user/user.go index 47acf2a..d411174 100644 --- a/ent/user/user.go +++ b/ent/user/user.go @@ -19,8 +19,17 @@ const ( FieldPassword = "password" // FieldCreatedAt holds the string denoting the created_at field in the database. FieldCreatedAt = "created_at" + // EdgeOwner holds the string denoting the owner edge name in mutations. + EdgeOwner = "owner" // Table holds the table name of the user in the database. Table = "users" + // OwnerTable is the table that holds the owner relation/edge. + OwnerTable = "password_tokens" + // OwnerInverseTable is the table name for the PasswordToken entity. + // It exists in this package in order to avoid circular dependency with the "passwordtoken" package. + OwnerInverseTable = "password_tokens" + // OwnerColumn is the table column denoting the owner relation/edge. + OwnerColumn = "password_token_user" ) // Columns holds all SQL columns for user fields. diff --git a/ent/user/where.go b/ent/user/where.go index fde4aad..550ba77 100644 --- a/ent/user/where.go +++ b/ent/user/where.go @@ -7,6 +7,7 @@ import ( "time" "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" ) // ID filters vertices based on their ID field. @@ -529,6 +530,34 @@ func CreatedAtLTE(v time.Time) predicate.User { }) } +// HasOwner applies the HasEdge predicate on the "owner" edge. +func HasOwner() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(OwnerTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, OwnerTable, OwnerColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasOwnerWith applies the HasEdge predicate on the "owner" edge with a given conditions (other predicates). +func HasOwnerWith(preds ...predicate.PasswordToken) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(OwnerInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, OwnerTable, OwnerColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + // And groups predicates with the AND operator between them. func And(predicates ...predicate.User) predicate.User { return predicate.User(func(s *sql.Selector) { diff --git a/ent/user_create.go b/ent/user_create.go index 176bef7..470242f 100644 --- a/ent/user_create.go +++ b/ent/user_create.go @@ -6,6 +6,7 @@ import ( "context" "errors" "fmt" + "goweb/ent/passwordtoken" "goweb/ent/user" "time" @@ -52,6 +53,21 @@ func (uc *UserCreate) SetNillableCreatedAt(t *time.Time) *UserCreate { return uc } +// AddOwnerIDs adds the "owner" edge to the PasswordToken entity by IDs. +func (uc *UserCreate) AddOwnerIDs(ids ...int) *UserCreate { + uc.mutation.AddOwnerIDs(ids...) + return uc +} + +// AddOwner adds the "owner" edges to the PasswordToken entity. +func (uc *UserCreate) AddOwner(p ...*PasswordToken) *UserCreate { + ids := make([]int, len(p)) + for i := range p { + ids[i] = p[i].ID + } + return uc.AddOwnerIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (uc *UserCreate) Mutation() *UserMutation { return uc.mutation @@ -217,6 +233,25 @@ func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { }) _node.CreatedAt = value } + if nodes := uc.mutation.OwnerIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.OwnerTable, + Columns: []string{user.OwnerColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: passwordtoken.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } return _node, _spec } diff --git a/ent/user_query.go b/ent/user_query.go index 02622fd..c955ecc 100644 --- a/ent/user_query.go +++ b/ent/user_query.go @@ -4,8 +4,10 @@ package ent import ( "context" + "database/sql/driver" "errors" "fmt" + "goweb/ent/passwordtoken" "goweb/ent/predicate" "goweb/ent/user" "math" @@ -24,6 +26,8 @@ type UserQuery struct { order []OrderFunc fields []string predicates []predicate.User + // eager-loading edges. + withOwner *PasswordTokenQuery // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -60,6 +64,28 @@ func (uq *UserQuery) Order(o ...OrderFunc) *UserQuery { return uq } +// QueryOwner chains the current query on the "owner" edge. +func (uq *UserQuery) QueryOwner() *PasswordTokenQuery { + query := &PasswordTokenQuery{config: uq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := uq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(passwordtoken.Table, passwordtoken.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, user.OwnerTable, user.OwnerColumn), + ) + fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step) + return fromU, nil + } + return query +} + // First returns the first User entity from the query. // Returns a *NotFoundError when no User was found. func (uq *UserQuery) First(ctx context.Context) (*User, error) { @@ -241,12 +267,24 @@ func (uq *UserQuery) Clone() *UserQuery { offset: uq.offset, order: append([]OrderFunc{}, uq.order...), predicates: append([]predicate.User{}, uq.predicates...), + withOwner: uq.withOwner.Clone(), // clone intermediate query. sql: uq.sql.Clone(), path: uq.path, } } +// WithOwner tells the query-builder to eager-load the nodes that are connected to +// the "owner" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithOwner(opts ...func(*PasswordTokenQuery)) *UserQuery { + query := &PasswordTokenQuery{config: uq.config} + for _, opt := range opts { + opt(query) + } + uq.withOwner = query + return uq +} + // 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. // @@ -310,8 +348,11 @@ func (uq *UserQuery) prepareQuery(ctx context.Context) error { func (uq *UserQuery) sqlAll(ctx context.Context) ([]*User, error) { var ( - nodes = []*User{} - _spec = uq.querySpec() + nodes = []*User{} + _spec = uq.querySpec() + loadedTypes = [1]bool{ + uq.withOwner != nil, + } ) _spec.ScanValues = func(columns []string) ([]interface{}, error) { node := &User{config: uq.config} @@ -323,6 +364,7 @@ func (uq *UserQuery) sqlAll(ctx context.Context) ([]*User, error) { return fmt.Errorf("ent: Assign called without calling ScanValues") } node := nodes[len(nodes)-1] + node.Edges.loadedTypes = loadedTypes return node.assignValues(columns, values) } if err := sqlgraph.QueryNodes(ctx, uq.driver, _spec); err != nil { @@ -331,6 +373,36 @@ func (uq *UserQuery) sqlAll(ctx context.Context) ([]*User, error) { if len(nodes) == 0 { return nodes, nil } + + if query := uq.withOwner; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*User) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + nodes[i].Edges.Owner = []*PasswordToken{} + } + query.withFKs = true + query.Where(predicate.PasswordToken(func(s *sql.Selector) { + s.Where(sql.InValues(user.OwnerColumn, fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + fk := n.password_token_user + if fk == nil { + return nil, fmt.Errorf(`foreign-key "password_token_user" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "password_token_user" returned %v for node %v`, *fk, n.ID) + } + node.Edges.Owner = append(node.Edges.Owner, n) + } + } + return nodes, nil } diff --git a/ent/user_update.go b/ent/user_update.go index e48690a..bedec7a 100644 --- a/ent/user_update.go +++ b/ent/user_update.go @@ -5,6 +5,7 @@ package ent import ( "context" "fmt" + "goweb/ent/passwordtoken" "goweb/ent/predicate" "goweb/ent/user" @@ -44,11 +45,47 @@ func (uu *UserUpdate) SetPassword(s string) *UserUpdate { return uu } +// AddOwnerIDs adds the "owner" edge to the PasswordToken entity by IDs. +func (uu *UserUpdate) AddOwnerIDs(ids ...int) *UserUpdate { + uu.mutation.AddOwnerIDs(ids...) + return uu +} + +// AddOwner adds the "owner" edges to the PasswordToken entity. +func (uu *UserUpdate) AddOwner(p ...*PasswordToken) *UserUpdate { + ids := make([]int, len(p)) + for i := range p { + ids[i] = p[i].ID + } + return uu.AddOwnerIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (uu *UserUpdate) Mutation() *UserMutation { return uu.mutation } +// ClearOwner clears all "owner" edges to the PasswordToken entity. +func (uu *UserUpdate) ClearOwner() *UserUpdate { + uu.mutation.ClearOwner() + return uu +} + +// RemoveOwnerIDs removes the "owner" edge to PasswordToken entities by IDs. +func (uu *UserUpdate) RemoveOwnerIDs(ids ...int) *UserUpdate { + uu.mutation.RemoveOwnerIDs(ids...) + return uu +} + +// RemoveOwner removes "owner" edges to PasswordToken entities. +func (uu *UserUpdate) RemoveOwner(p ...*PasswordToken) *UserUpdate { + ids := make([]int, len(p)) + for i := range p { + ids[i] = p[i].ID + } + return uu.RemoveOwnerIDs(ids...) +} + // Save executes the query and returns the number of nodes affected by the update operation. func (uu *UserUpdate) Save(ctx context.Context) (int, error) { var ( @@ -168,6 +205,60 @@ func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) { Column: user.FieldPassword, }) } + if uu.mutation.OwnerCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.OwnerTable, + Columns: []string{user.OwnerColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: passwordtoken.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.RemovedOwnerIDs(); len(nodes) > 0 && !uu.mutation.OwnerCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.OwnerTable, + Columns: []string{user.OwnerColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: passwordtoken.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.OwnerIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.OwnerTable, + Columns: []string{user.OwnerColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: passwordtoken.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if n, err = sqlgraph.UpdateNodes(ctx, uu.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{user.Label} @@ -205,11 +296,47 @@ func (uuo *UserUpdateOne) SetPassword(s string) *UserUpdateOne { return uuo } +// AddOwnerIDs adds the "owner" edge to the PasswordToken entity by IDs. +func (uuo *UserUpdateOne) AddOwnerIDs(ids ...int) *UserUpdateOne { + uuo.mutation.AddOwnerIDs(ids...) + return uuo +} + +// AddOwner adds the "owner" edges to the PasswordToken entity. +func (uuo *UserUpdateOne) AddOwner(p ...*PasswordToken) *UserUpdateOne { + ids := make([]int, len(p)) + for i := range p { + ids[i] = p[i].ID + } + return uuo.AddOwnerIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (uuo *UserUpdateOne) Mutation() *UserMutation { return uuo.mutation } +// ClearOwner clears all "owner" edges to the PasswordToken entity. +func (uuo *UserUpdateOne) ClearOwner() *UserUpdateOne { + uuo.mutation.ClearOwner() + return uuo +} + +// RemoveOwnerIDs removes the "owner" edge to PasswordToken entities by IDs. +func (uuo *UserUpdateOne) RemoveOwnerIDs(ids ...int) *UserUpdateOne { + uuo.mutation.RemoveOwnerIDs(ids...) + return uuo +} + +// RemoveOwner removes "owner" edges to PasswordToken entities. +func (uuo *UserUpdateOne) RemoveOwner(p ...*PasswordToken) *UserUpdateOne { + ids := make([]int, len(p)) + for i := range p { + ids[i] = p[i].ID + } + return uuo.RemoveOwnerIDs(ids...) +} + // Select allows selecting one or more fields (columns) of the returned entity. // The default is selecting all fields defined in the entity schema. func (uuo *UserUpdateOne) Select(field string, fields ...string) *UserUpdateOne { @@ -353,6 +480,60 @@ func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) Column: user.FieldPassword, }) } + if uuo.mutation.OwnerCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.OwnerTable, + Columns: []string{user.OwnerColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: passwordtoken.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.RemovedOwnerIDs(); len(nodes) > 0 && !uuo.mutation.OwnerCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.OwnerTable, + Columns: []string{user.OwnerColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: passwordtoken.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.OwnerIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.OwnerTable, + Columns: []string{user.OwnerColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: passwordtoken.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _node = &User{config: uuo.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues