From 1c42c7dd7a6b5be965aa8de8b6754415bfe046ba Mon Sep 17 00:00:00 2001 From: Achim Rohn Date: Thu, 18 Sep 2025 09:59:40 +0200 Subject: [PATCH] Add todo schema --- starter/ent/client.go | 163 +++++++- starter/ent/ent.go | 2 + starter/ent/hook/hook.go | 12 + starter/ent/migrate/schema.go | 25 ++ starter/ent/mutation.go | 557 ++++++++++++++++++++++++++ starter/ent/pagination_query.go | 38 ++ starter/ent/predicate/predicate.go | 3 + starter/ent/runtime.go | 24 ++ starter/ent/schema/todo.go | 32 ++ starter/ent/todo.go | 180 +++++++++ starter/ent/todo/todo.go | 121 ++++++ starter/ent/todo/where.go | 269 +++++++++++++ starter/ent/todo_create.go | 314 +++++++++++++++ starter/ent/todo_delete.go | 88 +++++ starter/ent/todo_query.go | 614 +++++++++++++++++++++++++++++ starter/ent/todo_update.go | 389 ++++++++++++++++++ starter/ent/tx.go | 3 + 17 files changed, 2832 insertions(+), 2 deletions(-) create mode 100644 starter/ent/schema/todo.go create mode 100644 starter/ent/todo.go create mode 100644 starter/ent/todo/todo.go create mode 100644 starter/ent/todo/where.go create mode 100644 starter/ent/todo_create.go create mode 100644 starter/ent/todo_delete.go create mode 100644 starter/ent/todo_query.go create mode 100644 starter/ent/todo_update.go diff --git a/starter/ent/client.go b/starter/ent/client.go index 15d2c68..69d166e 100644 --- a/starter/ent/client.go +++ b/starter/ent/client.go @@ -12,6 +12,7 @@ import ( "ersteller-lib/starter/ent/migrate" "ersteller-lib/starter/ent/googleauth" + "ersteller-lib/starter/ent/todo" "ersteller-lib/starter/ent/user" "entgo.io/ent" @@ -27,6 +28,8 @@ type Client struct { Schema *migrate.Schema // GoogleAuth is the client for interacting with the GoogleAuth builders. GoogleAuth *GoogleAuthClient + // Todo is the client for interacting with the Todo builders. + Todo *TodoClient // User is the client for interacting with the User builders. User *UserClient } @@ -41,6 +44,7 @@ func NewClient(opts ...Option) *Client { func (c *Client) init() { c.Schema = migrate.NewSchema(c.driver) c.GoogleAuth = NewGoogleAuthClient(c.config) + c.Todo = NewTodoClient(c.config) c.User = NewUserClient(c.config) } @@ -135,6 +139,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { ctx: ctx, config: cfg, GoogleAuth: NewGoogleAuthClient(cfg), + Todo: NewTodoClient(cfg), User: NewUserClient(cfg), }, nil } @@ -156,6 +161,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) ctx: ctx, config: cfg, GoogleAuth: NewGoogleAuthClient(cfg), + Todo: NewTodoClient(cfg), User: NewUserClient(cfg), }, nil } @@ -186,6 +192,7 @@ func (c *Client) Close() error { // In order to add hooks to a specific client, call: `client.Node.Use(...)`. func (c *Client) Use(hooks ...Hook) { c.GoogleAuth.Use(hooks...) + c.Todo.Use(hooks...) c.User.Use(hooks...) } @@ -193,6 +200,7 @@ func (c *Client) Use(hooks ...Hook) { // In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. func (c *Client) Intercept(interceptors ...Interceptor) { c.GoogleAuth.Intercept(interceptors...) + c.Todo.Intercept(interceptors...) c.User.Intercept(interceptors...) } @@ -201,6 +209,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { switch m := m.(type) { case *GoogleAuthMutation: return c.GoogleAuth.mutate(ctx, m) + case *TodoMutation: + return c.Todo.mutate(ctx, m) case *UserMutation: return c.User.mutate(ctx, m) default: @@ -357,6 +367,155 @@ func (c *GoogleAuthClient) mutate(ctx context.Context, m *GoogleAuthMutation) (V } } +// TodoClient is a client for the Todo schema. +type TodoClient struct { + config +} + +// NewTodoClient returns a client for the Todo from the given config. +func NewTodoClient(c config) *TodoClient { + return &TodoClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `todo.Hooks(f(g(h())))`. +func (c *TodoClient) Use(hooks ...Hook) { + c.hooks.Todo = append(c.hooks.Todo, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `todo.Intercept(f(g(h())))`. +func (c *TodoClient) Intercept(interceptors ...Interceptor) { + c.inters.Todo = append(c.inters.Todo, interceptors...) +} + +// Create returns a builder for creating a Todo entity. +func (c *TodoClient) Create() *TodoCreate { + mutation := newTodoMutation(c.config, OpCreate) + return &TodoCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Todo entities. +func (c *TodoClient) CreateBulk(builders ...*TodoCreate) *TodoCreateBulk { + return &TodoCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *TodoClient) MapCreateBulk(slice any, setFunc func(*TodoCreate, int)) *TodoCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &TodoCreateBulk{err: fmt.Errorf("calling to TodoClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*TodoCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &TodoCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Todo. +func (c *TodoClient) Update() *TodoUpdate { + mutation := newTodoMutation(c.config, OpUpdate) + return &TodoUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *TodoClient) UpdateOne(_m *Todo) *TodoUpdateOne { + mutation := newTodoMutation(c.config, OpUpdateOne, withTodo(_m)) + return &TodoUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *TodoClient) UpdateOneID(id int) *TodoUpdateOne { + mutation := newTodoMutation(c.config, OpUpdateOne, withTodoID(id)) + return &TodoUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Todo. +func (c *TodoClient) Delete() *TodoDelete { + mutation := newTodoMutation(c.config, OpDelete) + return &TodoDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *TodoClient) DeleteOne(_m *Todo) *TodoDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *TodoClient) DeleteOneID(id int) *TodoDeleteOne { + builder := c.Delete().Where(todo.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &TodoDeleteOne{builder} +} + +// Query returns a query builder for Todo. +func (c *TodoClient) Query() *TodoQuery { + return &TodoQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeTodo}, + inters: c.Interceptors(), + } +} + +// Get returns a Todo entity by its id. +func (c *TodoClient) Get(ctx context.Context, id int) (*Todo, error) { + return c.Query().Where(todo.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *TodoClient) GetX(ctx context.Context, id int) *Todo { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryUser queries the user edge of a Todo. +func (c *TodoClient) QueryUser(_m *Todo) *UserQuery { + query := (&UserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(todo.Table, todo.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, todo.UserTable, todo.UserColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *TodoClient) Hooks() []Hook { + return c.hooks.Todo +} + +// Interceptors returns the client interceptors. +func (c *TodoClient) Interceptors() []Interceptor { + return c.inters.Todo +} + +func (c *TodoClient) mutate(ctx context.Context, m *TodoMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&TodoCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&TodoUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&TodoUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&TodoDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Todo mutation op: %q", m.Op()) + } +} + // UserClient is a client for the User schema. type UserClient struct { config @@ -493,9 +652,9 @@ func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error) // hooks and interceptors per client, for fast access. type ( hooks struct { - GoogleAuth, User []ent.Hook + GoogleAuth, Todo, User []ent.Hook } inters struct { - GoogleAuth, User []ent.Interceptor + GoogleAuth, Todo, User []ent.Interceptor } ) diff --git a/starter/ent/ent.go b/starter/ent/ent.go index 81a123c..2f67205 100644 --- a/starter/ent/ent.go +++ b/starter/ent/ent.go @@ -6,6 +6,7 @@ import ( "context" "errors" "ersteller-lib/starter/ent/googleauth" + "ersteller-lib/starter/ent/todo" "ersteller-lib/starter/ent/user" "fmt" "reflect" @@ -75,6 +76,7 @@ func checkColumn(t, c string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ googleauth.Table: googleauth.ValidColumn, + todo.Table: todo.ValidColumn, user.Table: user.ValidColumn, }) }) diff --git a/starter/ent/hook/hook.go b/starter/ent/hook/hook.go index 62e9eb5..690f2c8 100644 --- a/starter/ent/hook/hook.go +++ b/starter/ent/hook/hook.go @@ -20,6 +20,18 @@ func (f GoogleAuthFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GoogleAuthMutation", m) } +// The TodoFunc type is an adapter to allow the use of ordinary +// function as Todo mutator. +type TodoFunc func(context.Context, *ent.TodoMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f TodoFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.TodoMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.TodoMutation", m) +} + // The UserFunc type is an adapter to allow the use of ordinary // function as User mutator. type UserFunc func(context.Context, *ent.UserMutation) (ent.Value, error) diff --git a/starter/ent/migrate/schema.go b/starter/ent/migrate/schema.go index 888a6e0..b81de80 100644 --- a/starter/ent/migrate/schema.go +++ b/starter/ent/migrate/schema.go @@ -30,6 +30,29 @@ var ( }, }, } + // TodosColumns holds the columns for the "todos" table. + TodosColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "title", Type: field.TypeString, Default: ""}, + {Name: "completed", Type: field.TypeBool, Default: false}, + {Name: "todo_user", Type: field.TypeInt, Nullable: true}, + } + // TodosTable holds the schema information for the "todos" table. + TodosTable = &schema.Table{ + Name: "todos", + Columns: TodosColumns, + PrimaryKey: []*schema.Column{TodosColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "todos_users_user", + Columns: []*schema.Column{TodosColumns[5]}, + 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}, @@ -47,10 +70,12 @@ var ( // Tables holds all the tables in the schema. Tables = []*schema.Table{ GoogleAuthsTable, + TodosTable, UsersTable, } ) func init() { GoogleAuthsTable.ForeignKeys[0].RefTable = UsersTable + TodosTable.ForeignKeys[0].RefTable = UsersTable } diff --git a/starter/ent/mutation.go b/starter/ent/mutation.go index 5a7e4bd..9f21bc5 100644 --- a/starter/ent/mutation.go +++ b/starter/ent/mutation.go @@ -8,6 +8,7 @@ import ( "ersteller-lib/starter/ent/googleauth" "ersteller-lib/starter/ent/predicate" "ersteller-lib/starter/ent/schema" + "ersteller-lib/starter/ent/todo" "ersteller-lib/starter/ent/user" "fmt" "sync" @@ -27,6 +28,7 @@ const ( // Node types. TypeGoogleAuth = "GoogleAuth" + TypeTodo = "Todo" TypeUser = "User" ) @@ -531,6 +533,561 @@ func (m *GoogleAuthMutation) ResetEdge(name string) error { return fmt.Errorf("unknown GoogleAuth edge %s", name) } +// TodoMutation represents an operation that mutates the Todo nodes in the graph. +type TodoMutation struct { + config + op Op + typ string + id *int + created_at *time.Time + updated_at *time.Time + title *string + completed *bool + clearedFields map[string]struct{} + user *int + cleareduser bool + done bool + oldValue func(context.Context) (*Todo, error) + predicates []predicate.Todo +} + +var _ ent.Mutation = (*TodoMutation)(nil) + +// todoOption allows management of the mutation configuration using functional options. +type todoOption func(*TodoMutation) + +// newTodoMutation creates new mutation for the Todo entity. +func newTodoMutation(c config, op Op, opts ...todoOption) *TodoMutation { + m := &TodoMutation{ + config: c, + op: op, + typ: TypeTodo, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withTodoID sets the ID field of the mutation. +func withTodoID(id int) todoOption { + return func(m *TodoMutation) { + var ( + err error + once sync.Once + value *Todo + ) + m.oldValue = func(ctx context.Context) (*Todo, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Todo.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withTodo sets the old Todo of the mutation. +func withTodo(node *Todo) todoOption { + return func(m *TodoMutation) { + m.oldValue = func(context.Context) (*Todo, 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 TodoMutation) 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 TodoMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *TodoMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *TodoMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Todo.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetCreatedAt sets the "created_at" field. +func (m *TodoMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *TodoMutation) 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 Todo entity. +// If the Todo 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 *TodoMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("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 *TodoMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *TodoMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *TodoMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return + } + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the Todo entity. +// If the Todo 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 *TodoMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + } + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *TodoMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetTitle sets the "title" field. +func (m *TodoMutation) SetTitle(s string) { + m.title = &s +} + +// Title returns the value of the "title" field in the mutation. +func (m *TodoMutation) Title() (r string, exists bool) { + v := m.title + if v == nil { + return + } + return *v, true +} + +// OldTitle returns the old "title" field's value of the Todo entity. +// If the Todo 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 *TodoMutation) OldTitle(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTitle is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTitle requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTitle: %w", err) + } + return oldValue.Title, nil +} + +// ResetTitle resets all changes to the "title" field. +func (m *TodoMutation) ResetTitle() { + m.title = nil +} + +// SetCompleted sets the "completed" field. +func (m *TodoMutation) SetCompleted(b bool) { + m.completed = &b +} + +// Completed returns the value of the "completed" field in the mutation. +func (m *TodoMutation) Completed() (r bool, exists bool) { + v := m.completed + if v == nil { + return + } + return *v, true +} + +// OldCompleted returns the old "completed" field's value of the Todo entity. +// If the Todo 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 *TodoMutation) OldCompleted(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCompleted is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCompleted requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCompleted: %w", err) + } + return oldValue.Completed, nil +} + +// ResetCompleted resets all changes to the "completed" field. +func (m *TodoMutation) ResetCompleted() { + m.completed = nil +} + +// SetUserID sets the "user" edge to the User entity by id. +func (m *TodoMutation) SetUserID(id int) { + m.user = &id +} + +// ClearUser clears the "user" edge to the User entity. +func (m *TodoMutation) ClearUser() { + m.cleareduser = true +} + +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *TodoMutation) UserCleared() bool { + return m.cleareduser +} + +// UserID returns the "user" edge ID in the mutation. +func (m *TodoMutation) 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 *TodoMutation) UserIDs() (ids []int) { + if id := m.user; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetUser resets all changes to the "user" edge. +func (m *TodoMutation) ResetUser() { + m.user = nil + m.cleareduser = false +} + +// Where appends a list predicates to the TodoMutation builder. +func (m *TodoMutation) Where(ps ...predicate.Todo) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the TodoMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *TodoMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Todo, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *TodoMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *TodoMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Todo). +func (m *TodoMutation) 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 *TodoMutation) Fields() []string { + fields := make([]string, 0, 4) + if m.created_at != nil { + fields = append(fields, todo.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, todo.FieldUpdatedAt) + } + if m.title != nil { + fields = append(fields, todo.FieldTitle) + } + if m.completed != nil { + fields = append(fields, todo.FieldCompleted) + } + 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 *TodoMutation) Field(name string) (ent.Value, bool) { + switch name { + case todo.FieldCreatedAt: + return m.CreatedAt() + case todo.FieldUpdatedAt: + return m.UpdatedAt() + case todo.FieldTitle: + return m.Title() + case todo.FieldCompleted: + return m.Completed() + } + 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 *TodoMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case todo.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case todo.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case todo.FieldTitle: + return m.OldTitle(ctx) + case todo.FieldCompleted: + return m.OldCompleted(ctx) + } + return nil, fmt.Errorf("unknown Todo 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 *TodoMutation) SetField(name string, value ent.Value) error { + switch name { + case todo.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case todo.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + case todo.FieldTitle: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTitle(v) + return nil + case todo.FieldCompleted: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCompleted(v) + return nil + } + return fmt.Errorf("unknown Todo field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *TodoMutation) 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 *TodoMutation) 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 *TodoMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Todo numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *TodoMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *TodoMutation) 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 *TodoMutation) ClearField(name string) error { + return fmt.Errorf("unknown Todo 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 *TodoMutation) ResetField(name string) error { + switch name { + case todo.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case todo.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case todo.FieldTitle: + m.ResetTitle() + return nil + case todo.FieldCompleted: + m.ResetCompleted() + return nil + } + return fmt.Errorf("unknown Todo field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *TodoMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.user != nil { + edges = append(edges, todo.EdgeUser) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *TodoMutation) AddedIDs(name string) []ent.Value { + switch name { + case todo.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 *TodoMutation) 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 *TodoMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *TodoMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.cleareduser { + edges = append(edges, todo.EdgeUser) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *TodoMutation) EdgeCleared(name string) bool { + switch name { + case todo.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 *TodoMutation) ClearEdge(name string) error { + switch name { + case todo.EdgeUser: + m.ClearUser() + return nil + } + return fmt.Errorf("unknown Todo 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 *TodoMutation) ResetEdge(name string) error { + switch name { + case todo.EdgeUser: + m.ResetUser() + return nil + } + return fmt.Errorf("unknown Todo edge %s", name) +} + // UserMutation represents an operation that mutates the User nodes in the graph. type UserMutation struct { config diff --git a/starter/ent/pagination_query.go b/starter/ent/pagination_query.go index cf2a923..3dfb960 100644 --- a/starter/ent/pagination_query.go +++ b/starter/ent/pagination_query.go @@ -48,6 +48,44 @@ func (q *GoogleAuthQuery) PaginateAfterID(ctx context.Context, afterID, limit in return rows, next, hasNext, nil } +// PaginateAfterID paginates Todo by monotonically increasing "id". +// It preserves any existing filters/joins applied to the query, fetches up to "limit" items, +// and returns the next cursor (last ID of this page) and whether a next page exists. +func (q *TodoQuery) PaginateAfterID(ctx context.Context, afterID, limit int) ([]*Todo, int, bool, error) { + if limit <= 0 { + limit = 20 + } + + qq := q.Clone(). + Order(func(s *sql.Selector) { + s.OrderBy(s.C("id")) + }). + Limit(limit + 1) // fetch one extra to detect "has next" + + if afterID > 0 { + qq = qq.Where(func(s *sql.Selector) { + s.Where(sql.GT(s.C("id"), afterID)) + }) + } + + rows, err := qq.All(ctx) + if err != nil { + return nil, 0, false, err + } + + hasNext := len(rows) > limit + if hasNext { + rows = rows[:limit] + } + + next := 0 + if len(rows) > 0 { + next = rows[len(rows)-1].ID + } + + return rows, next, hasNext, nil +} + // PaginateAfterID paginates User by monotonically increasing "id". // It preserves any existing filters/joins applied to the query, fetches up to "limit" items, // and returns the next cursor (last ID of this page) and whether a next page exists. diff --git a/starter/ent/predicate/predicate.go b/starter/ent/predicate/predicate.go index b7abf6c..5975e83 100644 --- a/starter/ent/predicate/predicate.go +++ b/starter/ent/predicate/predicate.go @@ -9,5 +9,8 @@ import ( // GoogleAuth is the predicate function for googleauth builders. type GoogleAuth func(*sql.Selector) +// Todo is the predicate function for todo builders. +type Todo func(*sql.Selector) + // User is the predicate function for user builders. type User func(*sql.Selector) diff --git a/starter/ent/runtime.go b/starter/ent/runtime.go index bf3abe4..cf4a8f4 100644 --- a/starter/ent/runtime.go +++ b/starter/ent/runtime.go @@ -5,6 +5,7 @@ package ent import ( "ersteller-lib/starter/ent/googleauth" "ersteller-lib/starter/ent/schema" + "ersteller-lib/starter/ent/todo" "ersteller-lib/starter/ent/user" "time" ) @@ -28,6 +29,29 @@ func init() { googleauth.DefaultUpdatedAt = googleauthDescUpdatedAt.Default.(func() time.Time) // googleauth.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. googleauth.UpdateDefaultUpdatedAt = googleauthDescUpdatedAt.UpdateDefault.(func() time.Time) + todoMixin := schema.Todo{}.Mixin() + todoMixinFields0 := todoMixin[0].Fields() + _ = todoMixinFields0 + todoFields := schema.Todo{}.Fields() + _ = todoFields + // todoDescCreatedAt is the schema descriptor for created_at field. + todoDescCreatedAt := todoMixinFields0[0].Descriptor() + // todo.DefaultCreatedAt holds the default value on creation for the created_at field. + todo.DefaultCreatedAt = todoDescCreatedAt.Default.(func() time.Time) + // todoDescUpdatedAt is the schema descriptor for updated_at field. + todoDescUpdatedAt := todoMixinFields0[1].Descriptor() + // todo.DefaultUpdatedAt holds the default value on creation for the updated_at field. + todo.DefaultUpdatedAt = todoDescUpdatedAt.Default.(func() time.Time) + // todo.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + todo.UpdateDefaultUpdatedAt = todoDescUpdatedAt.UpdateDefault.(func() time.Time) + // todoDescTitle is the schema descriptor for title field. + todoDescTitle := todoFields[0].Descriptor() + // todo.DefaultTitle holds the default value on creation for the title field. + todo.DefaultTitle = todoDescTitle.Default.(string) + // todoDescCompleted is the schema descriptor for completed field. + todoDescCompleted := todoFields[1].Descriptor() + // todo.DefaultCompleted holds the default value on creation for the completed field. + todo.DefaultCompleted = todoDescCompleted.Default.(bool) userMixin := schema.User{}.Mixin() userMixinFields0 := userMixin[0].Fields() _ = userMixinFields0 diff --git a/starter/ent/schema/todo.go b/starter/ent/schema/todo.go new file mode 100644 index 0000000..72143a6 --- /dev/null +++ b/starter/ent/schema/todo.go @@ -0,0 +1,32 @@ +package schema + +import ( + "ersteller-lib/schema/ent" + + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +type Todo struct { + ent.Schema +} + +func (Todo) Mixin() []ent.Mixin { + return []ent.Mixin{ + ersteller_ent.TimeMixin{}, + } +} + +func (Todo) Fields() []ent.Field { + return []ent.Field{ + field.String("title").Default(""), + field.Bool("completed").Default(false), + } +} + +func (Todo) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("user", User.Type).Unique(), + } +} diff --git a/starter/ent/todo.go b/starter/ent/todo.go new file mode 100644 index 0000000..4a4ae0a --- /dev/null +++ b/starter/ent/todo.go @@ -0,0 +1,180 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "ersteller-lib/starter/ent/todo" + "ersteller-lib/starter/ent/user" + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// Todo is the model entity for the Todo schema. +type Todo struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // UpdatedAt holds the value of the "updated_at" field. + UpdatedAt time.Time `json:"updated_at,omitempty"` + // Title holds the value of the "title" field. + Title string `json:"title,omitempty"` + // Completed holds the value of the "completed" field. + Completed bool `json:"completed,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the TodoQuery when eager-loading is set. + Edges TodoEdges `json:"edges"` + todo_user *int + selectValues sql.SelectValues +} + +// TodoEdges holds the relations/edges for other nodes in the graph. +type TodoEdges 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 TodoEdges) UserOrErr() (*User, error) { + if e.User != nil { + return e.User, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: user.Label} + } + return nil, &NotLoadedError{edge: "user"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Todo) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case todo.FieldCompleted: + values[i] = new(sql.NullBool) + case todo.FieldID: + values[i] = new(sql.NullInt64) + case todo.FieldTitle: + values[i] = new(sql.NullString) + case todo.FieldCreatedAt, todo.FieldUpdatedAt: + values[i] = new(sql.NullTime) + case todo.ForeignKeys[0]: // todo_user + values[i] = new(sql.NullInt64) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Todo fields. +func (_m *Todo) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case todo.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int(value.Int64) + case todo.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + case todo.FieldUpdatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field updated_at", values[i]) + } else if value.Valid { + _m.UpdatedAt = value.Time + } + case todo.FieldTitle: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field title", values[i]) + } else if value.Valid { + _m.Title = value.String + } + case todo.FieldCompleted: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field completed", values[i]) + } else if value.Valid { + _m.Completed = value.Bool + } + case todo.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field todo_user", value) + } else if value.Valid { + _m.todo_user = new(int) + *_m.todo_user = int(value.Int64) + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Todo. +// This includes values selected through modifiers, order, etc. +func (_m *Todo) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryUser queries the "user" edge of the Todo entity. +func (_m *Todo) QueryUser() *UserQuery { + return NewTodoClient(_m.config).QueryUser(_m) +} + +// Update returns a builder for updating this Todo. +// Note that you need to call Todo.Unwrap() before calling this method if this Todo +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Todo) Update() *TodoUpdateOne { + return NewTodoClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Todo entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *Todo) Unwrap() *Todo { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: Todo is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Todo) String() string { + var builder strings.Builder + builder.WriteString("Todo(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(_m.UpdatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("title=") + builder.WriteString(_m.Title) + builder.WriteString(", ") + builder.WriteString("completed=") + builder.WriteString(fmt.Sprintf("%v", _m.Completed)) + builder.WriteByte(')') + return builder.String() +} + +// Todos is a parsable slice of Todo. +type Todos []*Todo diff --git a/starter/ent/todo/todo.go b/starter/ent/todo/todo.go new file mode 100644 index 0000000..12b6d10 --- /dev/null +++ b/starter/ent/todo/todo.go @@ -0,0 +1,121 @@ +// Code generated by ent, DO NOT EDIT. + +package todo + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the todo type in the database. + Label = "todo" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldUpdatedAt holds the string denoting the updated_at field in the database. + FieldUpdatedAt = "updated_at" + // FieldTitle holds the string denoting the title field in the database. + FieldTitle = "title" + // FieldCompleted holds the string denoting the completed field in the database. + FieldCompleted = "completed" + // EdgeUser holds the string denoting the user edge name in mutations. + EdgeUser = "user" + // Table holds the table name of the todo in the database. + Table = "todos" + // UserTable is the table that holds the user relation/edge. + UserTable = "todos" + // 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 = "todo_user" +) + +// Columns holds all SQL columns for todo fields. +var Columns = []string{ + FieldID, + FieldCreatedAt, + FieldUpdatedAt, + FieldTitle, + FieldCompleted, +} + +// ForeignKeys holds the SQL foreign-keys that are owned by the "todos" +// table and are not defined as standalone fields in the schema. +var ForeignKeys = []string{ + "todo_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 ( + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. + DefaultUpdatedAt func() time.Time + // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field. + UpdateDefaultUpdatedAt func() time.Time + // DefaultTitle holds the default value on creation for the "title" field. + DefaultTitle string + // DefaultCompleted holds the default value on creation for the "completed" field. + DefaultCompleted bool +) + +// OrderOption defines the ordering options for the Todo queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} + +// ByTitle orders the results by the title field. +func ByTitle(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTitle, opts...).ToFunc() +} + +// ByCompleted orders the results by the completed field. +func ByCompleted(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCompleted, opts...).ToFunc() +} + +// ByUserField orders the results by user field. +func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUserStep(), sql.OrderByField(field, opts...)) + } +} +func newUserStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn), + ) +} diff --git a/starter/ent/todo/where.go b/starter/ent/todo/where.go new file mode 100644 index 0000000..80d761f --- /dev/null +++ b/starter/ent/todo/where.go @@ -0,0 +1,269 @@ +// Code generated by ent, DO NOT EDIT. + +package todo + +import ( + "ersteller-lib/starter/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.Todo { + return predicate.Todo(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.Todo { + return predicate.Todo(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.Todo { + return predicate.Todo(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.Todo { + return predicate.Todo(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.Todo { + return predicate.Todo(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.Todo { + return predicate.Todo(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.Todo { + return predicate.Todo(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.Todo { + return predicate.Todo(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.Todo { + return predicate.Todo(sql.FieldLTE(FieldID, id)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.Todo { + return predicate.Todo(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.Todo { + return predicate.Todo(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// Title applies equality check predicate on the "title" field. It's identical to TitleEQ. +func Title(v string) predicate.Todo { + return predicate.Todo(sql.FieldEQ(FieldTitle, v)) +} + +// Completed applies equality check predicate on the "completed" field. It's identical to CompletedEQ. +func Completed(v bool) predicate.Todo { + return predicate.Todo(sql.FieldEQ(FieldCompleted, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Todo { + return predicate.Todo(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Todo { + return predicate.Todo(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Todo { + return predicate.Todo(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Todo { + return predicate.Todo(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Todo { + return predicate.Todo(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Todo { + return predicate.Todo(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Todo { + return predicate.Todo(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Todo { + return predicate.Todo(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.Todo { + return predicate.Todo(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.Todo { + return predicate.Todo(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.Todo { + return predicate.Todo(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.Todo { + return predicate.Todo(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.Todo { + return predicate.Todo(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.Todo { + return predicate.Todo(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.Todo { + return predicate.Todo(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.Todo { + return predicate.Todo(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// TitleEQ applies the EQ predicate on the "title" field. +func TitleEQ(v string) predicate.Todo { + return predicate.Todo(sql.FieldEQ(FieldTitle, v)) +} + +// TitleNEQ applies the NEQ predicate on the "title" field. +func TitleNEQ(v string) predicate.Todo { + return predicate.Todo(sql.FieldNEQ(FieldTitle, v)) +} + +// TitleIn applies the In predicate on the "title" field. +func TitleIn(vs ...string) predicate.Todo { + return predicate.Todo(sql.FieldIn(FieldTitle, vs...)) +} + +// TitleNotIn applies the NotIn predicate on the "title" field. +func TitleNotIn(vs ...string) predicate.Todo { + return predicate.Todo(sql.FieldNotIn(FieldTitle, vs...)) +} + +// TitleGT applies the GT predicate on the "title" field. +func TitleGT(v string) predicate.Todo { + return predicate.Todo(sql.FieldGT(FieldTitle, v)) +} + +// TitleGTE applies the GTE predicate on the "title" field. +func TitleGTE(v string) predicate.Todo { + return predicate.Todo(sql.FieldGTE(FieldTitle, v)) +} + +// TitleLT applies the LT predicate on the "title" field. +func TitleLT(v string) predicate.Todo { + return predicate.Todo(sql.FieldLT(FieldTitle, v)) +} + +// TitleLTE applies the LTE predicate on the "title" field. +func TitleLTE(v string) predicate.Todo { + return predicate.Todo(sql.FieldLTE(FieldTitle, v)) +} + +// TitleContains applies the Contains predicate on the "title" field. +func TitleContains(v string) predicate.Todo { + return predicate.Todo(sql.FieldContains(FieldTitle, v)) +} + +// TitleHasPrefix applies the HasPrefix predicate on the "title" field. +func TitleHasPrefix(v string) predicate.Todo { + return predicate.Todo(sql.FieldHasPrefix(FieldTitle, v)) +} + +// TitleHasSuffix applies the HasSuffix predicate on the "title" field. +func TitleHasSuffix(v string) predicate.Todo { + return predicate.Todo(sql.FieldHasSuffix(FieldTitle, v)) +} + +// TitleEqualFold applies the EqualFold predicate on the "title" field. +func TitleEqualFold(v string) predicate.Todo { + return predicate.Todo(sql.FieldEqualFold(FieldTitle, v)) +} + +// TitleContainsFold applies the ContainsFold predicate on the "title" field. +func TitleContainsFold(v string) predicate.Todo { + return predicate.Todo(sql.FieldContainsFold(FieldTitle, v)) +} + +// CompletedEQ applies the EQ predicate on the "completed" field. +func CompletedEQ(v bool) predicate.Todo { + return predicate.Todo(sql.FieldEQ(FieldCompleted, v)) +} + +// CompletedNEQ applies the NEQ predicate on the "completed" field. +func CompletedNEQ(v bool) predicate.Todo { + return predicate.Todo(sql.FieldNEQ(FieldCompleted, v)) +} + +// HasUser applies the HasEdge predicate on the "user" edge. +func HasUser() predicate.Todo { + return predicate.Todo(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, 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.Todo { + return predicate.Todo(func(s *sql.Selector) { + step := newUserStep() + 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.Todo) predicate.Todo { + return predicate.Todo(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Todo) predicate.Todo { + return predicate.Todo(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Todo) predicate.Todo { + return predicate.Todo(sql.NotPredicates(p)) +} diff --git a/starter/ent/todo_create.go b/starter/ent/todo_create.go new file mode 100644 index 0000000..7b6f9d1 --- /dev/null +++ b/starter/ent/todo_create.go @@ -0,0 +1,314 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "ersteller-lib/starter/ent/todo" + "ersteller-lib/starter/ent/user" + "fmt" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// TodoCreate is the builder for creating a Todo entity. +type TodoCreate struct { + config + mutation *TodoMutation + hooks []Hook +} + +// SetCreatedAt sets the "created_at" field. +func (_c *TodoCreate) SetCreatedAt(v time.Time) *TodoCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *TodoCreate) SetNillableCreatedAt(v *time.Time) *TodoCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *TodoCreate) SetUpdatedAt(v time.Time) *TodoCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *TodoCreate) SetNillableUpdatedAt(v *time.Time) *TodoCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetTitle sets the "title" field. +func (_c *TodoCreate) SetTitle(v string) *TodoCreate { + _c.mutation.SetTitle(v) + return _c +} + +// SetNillableTitle sets the "title" field if the given value is not nil. +func (_c *TodoCreate) SetNillableTitle(v *string) *TodoCreate { + if v != nil { + _c.SetTitle(*v) + } + return _c +} + +// SetCompleted sets the "completed" field. +func (_c *TodoCreate) SetCompleted(v bool) *TodoCreate { + _c.mutation.SetCompleted(v) + return _c +} + +// SetNillableCompleted sets the "completed" field if the given value is not nil. +func (_c *TodoCreate) SetNillableCompleted(v *bool) *TodoCreate { + if v != nil { + _c.SetCompleted(*v) + } + return _c +} + +// SetUserID sets the "user" edge to the User entity by ID. +func (_c *TodoCreate) SetUserID(id int) *TodoCreate { + _c.mutation.SetUserID(id) + return _c +} + +// SetNillableUserID sets the "user" edge to the User entity by ID if the given value is not nil. +func (_c *TodoCreate) SetNillableUserID(id *int) *TodoCreate { + if id != nil { + _c = _c.SetUserID(*id) + } + return _c +} + +// SetUser sets the "user" edge to the User entity. +func (_c *TodoCreate) SetUser(v *User) *TodoCreate { + return _c.SetUserID(v.ID) +} + +// Mutation returns the TodoMutation object of the builder. +func (_c *TodoCreate) Mutation() *TodoMutation { + return _c.mutation +} + +// Save creates the Todo in the database. +func (_c *TodoCreate) Save(ctx context.Context) (*Todo, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *TodoCreate) SaveX(ctx context.Context) *Todo { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *TodoCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *TodoCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *TodoCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := todo.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := todo.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.Title(); !ok { + v := todo.DefaultTitle + _c.mutation.SetTitle(v) + } + if _, ok := _c.mutation.Completed(); !ok { + v := todo.DefaultCompleted + _c.mutation.SetCompleted(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *TodoCreate) check() error { + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Todo.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Todo.updated_at"`)} + } + if _, ok := _c.mutation.Title(); !ok { + return &ValidationError{Name: "title", err: errors.New(`ent: missing required field "Todo.title"`)} + } + if _, ok := _c.mutation.Completed(); !ok { + return &ValidationError{Name: "completed", err: errors.New(`ent: missing required field "Todo.completed"`)} + } + return nil +} + +func (_c *TodoCreate) sqlSave(ctx context.Context) (*Todo, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *TodoCreate) createSpec() (*Todo, *sqlgraph.CreateSpec) { + var ( + _node = &Todo{config: _c.config} + _spec = sqlgraph.NewCreateSpec(todo.Table, sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt)) + ) + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(todo.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(todo.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.Title(); ok { + _spec.SetField(todo.FieldTitle, field.TypeString, value) + _node.Title = value + } + if value, ok := _c.mutation.Completed(); ok { + _spec.SetField(todo.FieldCompleted, field.TypeBool, value) + _node.Completed = value + } + if nodes := _c.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: todo.UserTable, + Columns: []string{todo.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.todo_user = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// TodoCreateBulk is the builder for creating many Todo entities in bulk. +type TodoCreateBulk struct { + config + err error + builders []*TodoCreate +} + +// Save creates the Todo entities in the database. +func (_c *TodoCreateBulk) Save(ctx context.Context) ([]*Todo, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Todo, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TodoMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *TodoCreateBulk) SaveX(ctx context.Context) []*Todo { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *TodoCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *TodoCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/starter/ent/todo_delete.go b/starter/ent/todo_delete.go new file mode 100644 index 0000000..61034f9 --- /dev/null +++ b/starter/ent/todo_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "ersteller-lib/starter/ent/predicate" + "ersteller-lib/starter/ent/todo" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// TodoDelete is the builder for deleting a Todo entity. +type TodoDelete struct { + config + hooks []Hook + mutation *TodoMutation +} + +// Where appends a list predicates to the TodoDelete builder. +func (_d *TodoDelete) Where(ps ...predicate.Todo) *TodoDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *TodoDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *TodoDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *TodoDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(todo.Table, sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// TodoDeleteOne is the builder for deleting a single Todo entity. +type TodoDeleteOne struct { + _d *TodoDelete +} + +// Where appends a list predicates to the TodoDelete builder. +func (_d *TodoDeleteOne) Where(ps ...predicate.Todo) *TodoDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *TodoDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{todo.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *TodoDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/starter/ent/todo_query.go b/starter/ent/todo_query.go new file mode 100644 index 0000000..744fedc --- /dev/null +++ b/starter/ent/todo_query.go @@ -0,0 +1,614 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "ersteller-lib/starter/ent/predicate" + "ersteller-lib/starter/ent/todo" + "ersteller-lib/starter/ent/user" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// TodoQuery is the builder for querying Todo entities. +type TodoQuery struct { + config + ctx *QueryContext + order []todo.OrderOption + inters []Interceptor + predicates []predicate.Todo + 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 TodoQuery builder. +func (_q *TodoQuery) Where(ps ...predicate.Todo) *TodoQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *TodoQuery) Limit(limit int) *TodoQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *TodoQuery) Offset(offset int) *TodoQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *TodoQuery) Unique(unique bool) *TodoQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *TodoQuery) Order(o ...todo.OrderOption) *TodoQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryUser chains the current query on the "user" edge. +func (_q *TodoQuery) QueryUser() *UserQuery { + query := (&UserClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(todo.Table, todo.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, todo.UserTable, todo.UserColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Todo entity from the query. +// Returns a *NotFoundError when no Todo was found. +func (_q *TodoQuery) First(ctx context.Context) (*Todo, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{todo.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *TodoQuery) FirstX(ctx context.Context) *Todo { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Todo ID from the query. +// Returns a *NotFoundError when no Todo ID was found. +func (_q *TodoQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{todo.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *TodoQuery) FirstIDX(ctx context.Context) int { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Todo entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Todo entity is found. +// Returns a *NotFoundError when no Todo entities are found. +func (_q *TodoQuery) Only(ctx context.Context) (*Todo, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{todo.Label} + default: + return nil, &NotSingularError{todo.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *TodoQuery) OnlyX(ctx context.Context) *Todo { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Todo ID in the query. +// Returns a *NotSingularError when more than one Todo ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *TodoQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{todo.Label} + default: + err = &NotSingularError{todo.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *TodoQuery) OnlyIDX(ctx context.Context) int { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Todos. +func (_q *TodoQuery) All(ctx context.Context) ([]*Todo, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Todo, *TodoQuery]() + return withInterceptors[[]*Todo](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *TodoQuery) AllX(ctx context.Context) []*Todo { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Todo IDs. +func (_q *TodoQuery) IDs(ctx context.Context) (ids []int, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(todo.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *TodoQuery) IDsX(ctx context.Context) []int { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *TodoQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*TodoQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *TodoQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *TodoQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *TodoQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the TodoQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *TodoQuery) Clone() *TodoQuery { + if _q == nil { + return nil + } + return &TodoQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]todo.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Todo{}, _q.predicates...), + withUser: _q.withUser.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.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 (_q *TodoQuery) WithUser(opts ...func(*UserQuery)) *TodoQuery { + query := (&UserClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withUser = query + return _q +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// CreatedAt time.Time `json:"created_at,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Todo.Query(). +// GroupBy(todo.FieldCreatedAt). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *TodoQuery) GroupBy(field string, fields ...string) *TodoGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &TodoGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = todo.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// CreatedAt time.Time `json:"created_at,omitempty"` +// } +// +// client.Todo.Query(). +// Select(todo.FieldCreatedAt). +// Scan(ctx, &v) +func (_q *TodoQuery) Select(fields ...string) *TodoSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &TodoSelect{TodoQuery: _q} + sbuild.label = todo.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a TodoSelect configured with the given aggregations. +func (_q *TodoQuery) Aggregate(fns ...AggregateFunc) *TodoSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *TodoQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !todo.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *TodoQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Todo, error) { + var ( + nodes = []*Todo{} + withFKs = _q.withFKs + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withUser != nil, + } + ) + if _q.withUser != nil { + withFKs = true + } + if withFKs { + _spec.Node.Columns = append(_spec.Node.Columns, todo.ForeignKeys...) + } + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Todo).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Todo{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withUser; query != nil { + if err := _q.loadUser(ctx, query, nodes, nil, + func(n *Todo, e *User) { n.Edges.User = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *TodoQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*Todo, init func(*Todo), assign func(*Todo, *User)) error { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*Todo) + for i := range nodes { + if nodes[i].todo_user == nil { + continue + } + fk := *nodes[i].todo_user + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(user.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "todo_user" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *TodoQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *TodoQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(todo.Table, todo.Columns, sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, todo.FieldID) + for i := range fields { + if fields[i] != todo.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *TodoQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(todo.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = todo.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// TodoGroupBy is the group-by builder for Todo entities. +type TodoGroupBy struct { + selector + build *TodoQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *TodoGroupBy) Aggregate(fns ...AggregateFunc) *TodoGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *TodoGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*TodoQuery, *TodoGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *TodoGroupBy) sqlScan(ctx context.Context, root *TodoQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// TodoSelect is the builder for selecting fields of Todo entities. +type TodoSelect struct { + *TodoQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *TodoSelect) Aggregate(fns ...AggregateFunc) *TodoSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *TodoSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*TodoQuery, *TodoSelect](ctx, _s.TodoQuery, _s, _s.inters, v) +} + +func (_s *TodoSelect) sqlScan(ctx context.Context, root *TodoQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/starter/ent/todo_update.go b/starter/ent/todo_update.go new file mode 100644 index 0000000..432bf2c --- /dev/null +++ b/starter/ent/todo_update.go @@ -0,0 +1,389 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "ersteller-lib/starter/ent/predicate" + "ersteller-lib/starter/ent/todo" + "ersteller-lib/starter/ent/user" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// TodoUpdate is the builder for updating Todo entities. +type TodoUpdate struct { + config + hooks []Hook + mutation *TodoMutation +} + +// Where appends a list predicates to the TodoUpdate builder. +func (_u *TodoUpdate) Where(ps ...predicate.Todo) *TodoUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *TodoUpdate) SetUpdatedAt(v time.Time) *TodoUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetTitle sets the "title" field. +func (_u *TodoUpdate) SetTitle(v string) *TodoUpdate { + _u.mutation.SetTitle(v) + return _u +} + +// SetNillableTitle sets the "title" field if the given value is not nil. +func (_u *TodoUpdate) SetNillableTitle(v *string) *TodoUpdate { + if v != nil { + _u.SetTitle(*v) + } + return _u +} + +// SetCompleted sets the "completed" field. +func (_u *TodoUpdate) SetCompleted(v bool) *TodoUpdate { + _u.mutation.SetCompleted(v) + return _u +} + +// SetNillableCompleted sets the "completed" field if the given value is not nil. +func (_u *TodoUpdate) SetNillableCompleted(v *bool) *TodoUpdate { + if v != nil { + _u.SetCompleted(*v) + } + return _u +} + +// SetUserID sets the "user" edge to the User entity by ID. +func (_u *TodoUpdate) SetUserID(id int) *TodoUpdate { + _u.mutation.SetUserID(id) + return _u +} + +// SetNillableUserID sets the "user" edge to the User entity by ID if the given value is not nil. +func (_u *TodoUpdate) SetNillableUserID(id *int) *TodoUpdate { + if id != nil { + _u = _u.SetUserID(*id) + } + return _u +} + +// SetUser sets the "user" edge to the User entity. +func (_u *TodoUpdate) SetUser(v *User) *TodoUpdate { + return _u.SetUserID(v.ID) +} + +// Mutation returns the TodoMutation object of the builder. +func (_u *TodoUpdate) Mutation() *TodoMutation { + return _u.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (_u *TodoUpdate) ClearUser() *TodoUpdate { + _u.mutation.ClearUser() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *TodoUpdate) Save(ctx context.Context) (int, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *TodoUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *TodoUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *TodoUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *TodoUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := todo.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +func (_u *TodoUpdate) sqlSave(ctx context.Context) (_node int, err error) { + _spec := sqlgraph.NewUpdateSpec(todo.Table, todo.Columns, sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(todo.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.Title(); ok { + _spec.SetField(todo.FieldTitle, field.TypeString, value) + } + if value, ok := _u.mutation.Completed(); ok { + _spec.SetField(todo.FieldCompleted, field.TypeBool, value) + } + if _u.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: todo.UserTable, + Columns: []string{todo.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: todo.UserTable, + Columns: []string{todo.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{todo.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// TodoUpdateOne is the builder for updating a single Todo entity. +type TodoUpdateOne struct { + config + fields []string + hooks []Hook + mutation *TodoMutation +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *TodoUpdateOne) SetUpdatedAt(v time.Time) *TodoUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetTitle sets the "title" field. +func (_u *TodoUpdateOne) SetTitle(v string) *TodoUpdateOne { + _u.mutation.SetTitle(v) + return _u +} + +// SetNillableTitle sets the "title" field if the given value is not nil. +func (_u *TodoUpdateOne) SetNillableTitle(v *string) *TodoUpdateOne { + if v != nil { + _u.SetTitle(*v) + } + return _u +} + +// SetCompleted sets the "completed" field. +func (_u *TodoUpdateOne) SetCompleted(v bool) *TodoUpdateOne { + _u.mutation.SetCompleted(v) + return _u +} + +// SetNillableCompleted sets the "completed" field if the given value is not nil. +func (_u *TodoUpdateOne) SetNillableCompleted(v *bool) *TodoUpdateOne { + if v != nil { + _u.SetCompleted(*v) + } + return _u +} + +// SetUserID sets the "user" edge to the User entity by ID. +func (_u *TodoUpdateOne) SetUserID(id int) *TodoUpdateOne { + _u.mutation.SetUserID(id) + return _u +} + +// SetNillableUserID sets the "user" edge to the User entity by ID if the given value is not nil. +func (_u *TodoUpdateOne) SetNillableUserID(id *int) *TodoUpdateOne { + if id != nil { + _u = _u.SetUserID(*id) + } + return _u +} + +// SetUser sets the "user" edge to the User entity. +func (_u *TodoUpdateOne) SetUser(v *User) *TodoUpdateOne { + return _u.SetUserID(v.ID) +} + +// Mutation returns the TodoMutation object of the builder. +func (_u *TodoUpdateOne) Mutation() *TodoMutation { + return _u.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (_u *TodoUpdateOne) ClearUser() *TodoUpdateOne { + _u.mutation.ClearUser() + return _u +} + +// Where appends a list predicates to the TodoUpdate builder. +func (_u *TodoUpdateOne) Where(ps ...predicate.Todo) *TodoUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *TodoUpdateOne) Select(field string, fields ...string) *TodoUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Todo entity. +func (_u *TodoUpdateOne) Save(ctx context.Context) (*Todo, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *TodoUpdateOne) SaveX(ctx context.Context) *Todo { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *TodoUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *TodoUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *TodoUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := todo.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +func (_u *TodoUpdateOne) sqlSave(ctx context.Context) (_node *Todo, err error) { + _spec := sqlgraph.NewUpdateSpec(todo.Table, todo.Columns, sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Todo.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, todo.FieldID) + for _, f := range fields { + if !todo.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != todo.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(todo.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.Title(); ok { + _spec.SetField(todo.FieldTitle, field.TypeString, value) + } + if value, ok := _u.mutation.Completed(); ok { + _spec.SetField(todo.FieldCompleted, field.TypeBool, value) + } + if _u.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: todo.UserTable, + Columns: []string{todo.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: todo.UserTable, + Columns: []string{todo.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &Todo{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{todo.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/starter/ent/tx.go b/starter/ent/tx.go index cf6f435..c2bf289 100644 --- a/starter/ent/tx.go +++ b/starter/ent/tx.go @@ -14,6 +14,8 @@ type Tx struct { config // GoogleAuth is the client for interacting with the GoogleAuth builders. GoogleAuth *GoogleAuthClient + // Todo is the client for interacting with the Todo builders. + Todo *TodoClient // User is the client for interacting with the User builders. User *UserClient @@ -148,6 +150,7 @@ func (tx *Tx) Client() *Client { func (tx *Tx) init() { tx.GoogleAuth = NewGoogleAuthClient(tx.config) + tx.Todo = NewTodoClient(tx.config) tx.User = NewUserClient(tx.config) }