Add todo with interceptor

This commit is contained in:
Achim Rohn
2025-09-12 09:15:50 +02:00
parent cd1d85b1a9
commit 6cbd155db6
33 changed files with 5930 additions and 13 deletions
+354 -3
View File
@@ -11,11 +11,14 @@ import (
"ersteller-lib/schema/ent/example/ent/migrate"
"ersteller-lib/schema/ent/example/ent/group"
"ersteller-lib/schema/ent/example/ent/todo"
"ersteller-lib/schema/ent/example/ent/user"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
// Client is the client that holds all ent builders.
@@ -23,6 +26,10 @@ type Client struct {
config
// Schema is the client for creating, migrating and dropping schema.
Schema *migrate.Schema
// Group is the client for interacting with the Group builders.
Group *GroupClient
// Todo is the client for interacting with the Todo builders.
Todo *TodoClient
// User is the client for interacting with the User builders.
User *UserClient
}
@@ -36,6 +43,8 @@ func NewClient(opts ...Option) *Client {
func (c *Client) init() {
c.Schema = migrate.NewSchema(c.driver)
c.Group = NewGroupClient(c.config)
c.Todo = NewTodoClient(c.config)
c.User = NewUserClient(c.config)
}
@@ -129,6 +138,8 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) {
return &Tx{
ctx: ctx,
config: cfg,
Group: NewGroupClient(cfg),
Todo: NewTodoClient(cfg),
User: NewUserClient(cfg),
}, nil
}
@@ -149,6 +160,8 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
return &Tx{
ctx: ctx,
config: cfg,
Group: NewGroupClient(cfg),
Todo: NewTodoClient(cfg),
User: NewUserClient(cfg),
}, nil
}
@@ -156,7 +169,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
//
// client.Debug().
// User.
// Group.
// Query().
// Count(ctx)
func (c *Client) Debug() *Client {
@@ -178,18 +191,26 @@ func (c *Client) Close() error {
// Use adds the mutation hooks to all the entity clients.
// In order to add hooks to a specific client, call: `client.Node.Use(...)`.
func (c *Client) Use(hooks ...Hook) {
c.Group.Use(hooks...)
c.Todo.Use(hooks...)
c.User.Use(hooks...)
}
// Intercept adds the query interceptors to all the entity clients.
// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`.
func (c *Client) Intercept(interceptors ...Interceptor) {
c.Group.Intercept(interceptors...)
c.Todo.Intercept(interceptors...)
c.User.Intercept(interceptors...)
}
// Mutate implements the ent.Mutator interface.
func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
switch m := m.(type) {
case *GroupMutation:
return c.Group.mutate(ctx, m)
case *TodoMutation:
return c.Todo.mutate(ctx, m)
case *UserMutation:
return c.User.mutate(ctx, m)
default:
@@ -197,6 +218,320 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
}
}
// GroupClient is a client for the Group schema.
type GroupClient struct {
config
}
// NewGroupClient returns a client for the Group from the given config.
func NewGroupClient(c config) *GroupClient {
return &GroupClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `group.Hooks(f(g(h())))`.
func (c *GroupClient) Use(hooks ...Hook) {
c.hooks.Group = append(c.hooks.Group, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `group.Intercept(f(g(h())))`.
func (c *GroupClient) Intercept(interceptors ...Interceptor) {
c.inters.Group = append(c.inters.Group, interceptors...)
}
// Create returns a builder for creating a Group entity.
func (c *GroupClient) Create() *GroupCreate {
mutation := newGroupMutation(c.config, OpCreate)
return &GroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Group entities.
func (c *GroupClient) CreateBulk(builders ...*GroupCreate) *GroupCreateBulk {
return &GroupCreateBulk{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 *GroupClient) MapCreateBulk(slice any, setFunc func(*GroupCreate, int)) *GroupCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &GroupCreateBulk{err: fmt.Errorf("calling to GroupClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*GroupCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &GroupCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Group.
func (c *GroupClient) Update() *GroupUpdate {
mutation := newGroupMutation(c.config, OpUpdate)
return &GroupUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *GroupClient) UpdateOne(_m *Group) *GroupUpdateOne {
mutation := newGroupMutation(c.config, OpUpdateOne, withGroup(_m))
return &GroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *GroupClient) UpdateOneID(id int) *GroupUpdateOne {
mutation := newGroupMutation(c.config, OpUpdateOne, withGroupID(id))
return &GroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Group.
func (c *GroupClient) Delete() *GroupDelete {
mutation := newGroupMutation(c.config, OpDelete)
return &GroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *GroupClient) DeleteOne(_m *Group) *GroupDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *GroupClient) DeleteOneID(id int) *GroupDeleteOne {
builder := c.Delete().Where(group.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &GroupDeleteOne{builder}
}
// Query returns a query builder for Group.
func (c *GroupClient) Query() *GroupQuery {
return &GroupQuery{
config: c.config,
ctx: &QueryContext{Type: TypeGroup},
inters: c.Interceptors(),
}
}
// Get returns a Group entity by its id.
func (c *GroupClient) Get(ctx context.Context, id int) (*Group, error) {
return c.Query().Where(group.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *GroupClient) GetX(ctx context.Context, id int) *Group {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryUsers queries the users edge of a Group.
func (c *GroupClient) QueryUsers(_m *Group) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, group.UsersTable, group.UsersPrimaryKey...),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryTodos queries the todos edge of a Group.
func (c *GroupClient) QueryTodos(_m *Group) *TodoQuery {
query := (&TodoClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, id),
sqlgraph.To(todo.Table, todo.FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, group.TodosTable, group.TodosColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *GroupClient) Hooks() []Hook {
return c.hooks.Group
}
// Interceptors returns the client interceptors.
func (c *GroupClient) Interceptors() []Interceptor {
return c.inters.Group
}
func (c *GroupClient) mutate(ctx context.Context, m *GroupMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&GroupCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&GroupUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&GroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&GroupDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Group mutation op: %q", m.Op())
}
}
// 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
}
// QueryGroup queries the group edge of a Todo.
func (c *TodoClient) QueryGroup(_m *Todo) *GroupQuery {
query := (&GroupClient{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(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, todo.GroupTable, todo.GroupColumn),
)
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
@@ -305,6 +640,22 @@ func (c *UserClient) GetX(ctx context.Context, id int) *User {
return obj
}
// QueryGroup queries the group edge of a User.
func (c *UserClient) QueryGroup(_m *User) *GroupQuery {
query := (&GroupClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, id),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, user.GroupTable, user.GroupPrimaryKey...),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *UserClient) Hooks() []Hook {
return c.hooks.User
@@ -333,9 +684,9 @@ func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error)
// hooks and interceptors per client, for fast access.
type (
hooks struct {
User []ent.Hook
Group, Todo, User []ent.Hook
}
inters struct {
User []ent.Interceptor
Group, Todo, User []ent.Interceptor
}
)
+5 -1
View File
@@ -5,6 +5,8 @@ package ent
import (
"context"
"errors"
"ersteller-lib/schema/ent/example/ent/group"
"ersteller-lib/schema/ent/example/ent/todo"
"ersteller-lib/schema/ent/example/ent/user"
"fmt"
"reflect"
@@ -73,7 +75,9 @@ var (
func checkColumn(t, c string) error {
initCheck.Do(func() {
columnCheck = sql.NewColumnCheck(map[string]func(string) bool{
user.Table: user.ValidColumn,
group.Table: group.ValidColumn,
todo.Table: todo.ValidColumn,
user.Table: user.ValidColumn,
})
})
return columnCheck(t, c)
+145
View File
@@ -0,0 +1,145 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"ersteller-lib/schema/ent/example/ent/group"
"fmt"
"strings"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
)
// Group is the model entity for the Group schema.
type Group struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the GroupQuery when eager-loading is set.
Edges GroupEdges `json:"edges"`
selectValues sql.SelectValues
}
// GroupEdges holds the relations/edges for other nodes in the graph.
type GroupEdges struct {
// Users holds the value of the users edge.
Users []*User `json:"users,omitempty"`
// Todos holds the value of the todos edge.
Todos []*Todo `json:"todos,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// UsersOrErr returns the Users value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) UsersOrErr() ([]*User, error) {
if e.loadedTypes[0] {
return e.Users, nil
}
return nil, &NotLoadedError{edge: "users"}
}
// TodosOrErr returns the Todos value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) TodosOrErr() ([]*Todo, error) {
if e.loadedTypes[1] {
return e.Todos, nil
}
return nil, &NotLoadedError{edge: "todos"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Group) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case group.FieldID:
values[i] = new(sql.NullInt64)
case group.FieldName:
values[i] = new(sql.NullString)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Group fields.
func (_m *Group) 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 group.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 group.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
_m.Name = value.String
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Group.
// This includes values selected through modifiers, order, etc.
func (_m *Group) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryUsers queries the "users" edge of the Group entity.
func (_m *Group) QueryUsers() *UserQuery {
return NewGroupClient(_m.config).QueryUsers(_m)
}
// QueryTodos queries the "todos" edge of the Group entity.
func (_m *Group) QueryTodos() *TodoQuery {
return NewGroupClient(_m.config).QueryTodos(_m)
}
// Update returns a builder for updating this Group.
// Note that you need to call Group.Unwrap() before calling this method if this Group
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Group) Update() *GroupUpdateOne {
return NewGroupClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Group 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 *Group) Unwrap() *Group {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: Group is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Group) String() string {
var builder strings.Builder
builder.WriteString("Group(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("name=")
builder.WriteString(_m.Name)
builder.WriteByte(')')
return builder.String()
}
// Groups is a parsable slice of Group.
type Groups []*Group
+117
View File
@@ -0,0 +1,117 @@
// Code generated by ent, DO NOT EDIT.
package group
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the group type in the database.
Label = "group"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// EdgeUsers holds the string denoting the users edge name in mutations.
EdgeUsers = "users"
// EdgeTodos holds the string denoting the todos edge name in mutations.
EdgeTodos = "todos"
// Table holds the table name of the group in the database.
Table = "groups"
// UsersTable is the table that holds the users relation/edge. The primary key declared below.
UsersTable = "user_group"
// UsersInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
UsersInverseTable = "users"
// TodosTable is the table that holds the todos relation/edge.
TodosTable = "todos"
// TodosInverseTable is the table name for the Todo entity.
// It exists in this package in order to avoid circular dependency with the "todo" package.
TodosInverseTable = "todos"
// TodosColumn is the table column denoting the todos relation/edge.
TodosColumn = "todo_group"
)
// Columns holds all SQL columns for group fields.
var Columns = []string{
FieldID,
FieldName,
}
var (
// UsersPrimaryKey and UsersColumn2 are the table columns denoting the
// primary key for the users relation (M2M).
UsersPrimaryKey = []string{"user_id", "group_id"}
)
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// DefaultName holds the default value on creation for the "name" field.
DefaultName string
)
// OrderOption defines the ordering options for the Group 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()
}
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, opts...).ToFunc()
}
// ByUsersCount orders the results by users count.
func ByUsersCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newUsersStep(), opts...)
}
}
// ByUsers orders the results by users terms.
func ByUsers(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newUsersStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByTodosCount orders the results by todos count.
func ByTodosCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newTodosStep(), opts...)
}
}
// ByTodos orders the results by todos terms.
func ByTodos(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newTodosStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
func newUsersStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UsersInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, UsersTable, UsersPrimaryKey...),
)
}
func newTodosStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(TodosInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, TodosTable, TodosColumn),
)
}
+186
View File
@@ -0,0 +1,186 @@
// Code generated by ent, DO NOT EDIT.
package group
import (
"ersteller-lib/schema/ent/example/ent/predicate"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Group {
return predicate.Group(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Group {
return predicate.Group(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Group {
return predicate.Group(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldID, id))
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldName, v))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldName, v))
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldName, v))
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldIn(FieldName, vs...))
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldName, vs...))
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.Group {
return predicate.Group(sql.FieldGT(FieldName, v))
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldName, v))
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.Group {
return predicate.Group(sql.FieldLT(FieldName, v))
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldName, v))
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.Group {
return predicate.Group(sql.FieldContains(FieldName, v))
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.Group {
return predicate.Group(sql.FieldHasPrefix(FieldName, v))
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.Group {
return predicate.Group(sql.FieldHasSuffix(FieldName, v))
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.Group {
return predicate.Group(sql.FieldEqualFold(FieldName, v))
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.Group {
return predicate.Group(sql.FieldContainsFold(FieldName, v))
}
// HasUsers applies the HasEdge predicate on the "users" edge.
func HasUsers() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, UsersTable, UsersPrimaryKey...),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasUsersWith applies the HasEdge predicate on the "users" edge with a given conditions (other predicates).
func HasUsersWith(preds ...predicate.User) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := newUsersStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasTodos applies the HasEdge predicate on the "todos" edge.
func HasTodos() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, TodosTable, TodosColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasTodosWith applies the HasEdge predicate on the "todos" edge with a given conditions (other predicates).
func HasTodosWith(preds ...predicate.Todo) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := newTodosStep()
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.Group) predicate.Group {
return predicate.Group(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Group) predicate.Group {
return predicate.Group(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Group) predicate.Group {
return predicate.Group(sql.NotPredicates(p))
}
+265
View File
@@ -0,0 +1,265 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"ersteller-lib/schema/ent/example/ent/group"
"ersteller-lib/schema/ent/example/ent/todo"
"ersteller-lib/schema/ent/example/ent/user"
"fmt"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// GroupCreate is the builder for creating a Group entity.
type GroupCreate struct {
config
mutation *GroupMutation
hooks []Hook
}
// SetName sets the "name" field.
func (_c *GroupCreate) SetName(v string) *GroupCreate {
_c.mutation.SetName(v)
return _c
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_c *GroupCreate) SetNillableName(v *string) *GroupCreate {
if v != nil {
_c.SetName(*v)
}
return _c
}
// AddUserIDs adds the "users" edge to the User entity by IDs.
func (_c *GroupCreate) AddUserIDs(ids ...int) *GroupCreate {
_c.mutation.AddUserIDs(ids...)
return _c
}
// AddUsers adds the "users" edges to the User entity.
func (_c *GroupCreate) AddUsers(v ...*User) *GroupCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddUserIDs(ids...)
}
// AddTodoIDs adds the "todos" edge to the Todo entity by IDs.
func (_c *GroupCreate) AddTodoIDs(ids ...int) *GroupCreate {
_c.mutation.AddTodoIDs(ids...)
return _c
}
// AddTodos adds the "todos" edges to the Todo entity.
func (_c *GroupCreate) AddTodos(v ...*Todo) *GroupCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddTodoIDs(ids...)
}
// Mutation returns the GroupMutation object of the builder.
func (_c *GroupCreate) Mutation() *GroupMutation {
return _c.mutation
}
// Save creates the Group in the database.
func (_c *GroupCreate) Save(ctx context.Context) (*Group, error) {
_c.defaults()
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *GroupCreate) SaveX(ctx context.Context) *Group {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *GroupCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *GroupCreate) 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 *GroupCreate) defaults() {
if _, ok := _c.mutation.Name(); !ok {
v := group.DefaultName
_c.mutation.SetName(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *GroupCreate) check() error {
if _, ok := _c.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Group.name"`)}
}
return nil
}
func (_c *GroupCreate) sqlSave(ctx context.Context) (*Group, 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 *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
var (
_node = &Group{config: _c.config}
_spec = sqlgraph.NewCreateSpec(group.Table, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt))
)
if value, ok := _c.mutation.Name(); ok {
_spec.SetField(group.FieldName, field.TypeString, value)
_node.Name = value
}
if nodes := _c.mutation.UsersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
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 = append(_spec.Edges, edge)
}
if nodes := _c.mutation.TodosIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: group.TodosTable,
Columns: []string{group.TodosColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// GroupCreateBulk is the builder for creating many Group entities in bulk.
type GroupCreateBulk struct {
config
err error
builders []*GroupCreate
}
// Save creates the Group entities in the database.
func (_c *GroupCreateBulk) Save(ctx context.Context) ([]*Group, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*Group, 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.(*GroupMutation)
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 *GroupCreateBulk) SaveX(ctx context.Context) []*Group {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *GroupCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *GroupCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
+88
View File
@@ -0,0 +1,88 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"ersteller-lib/schema/ent/example/ent/group"
"ersteller-lib/schema/ent/example/ent/predicate"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// GroupDelete is the builder for deleting a Group entity.
type GroupDelete struct {
config
hooks []Hook
mutation *GroupMutation
}
// Where appends a list predicates to the GroupDelete builder.
func (_d *GroupDelete) Where(ps ...predicate.Group) *GroupDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *GroupDelete) 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 *GroupDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *GroupDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(group.Table, sqlgraph.NewFieldSpec(group.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
}
// GroupDeleteOne is the builder for deleting a single Group entity.
type GroupDeleteOne struct {
_d *GroupDelete
}
// Where appends a list predicates to the GroupDelete builder.
func (_d *GroupDeleteOne) Where(ps ...predicate.Group) *GroupDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *GroupDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{group.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *GroupDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}
+712
View File
@@ -0,0 +1,712 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"database/sql/driver"
"ersteller-lib/schema/ent/example/ent/group"
"ersteller-lib/schema/ent/example/ent/predicate"
"ersteller-lib/schema/ent/example/ent/todo"
"ersteller-lib/schema/ent/example/ent/user"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// GroupQuery is the builder for querying Group entities.
type GroupQuery struct {
config
ctx *QueryContext
order []group.OrderOption
inters []Interceptor
predicates []predicate.Group
withUsers *UserQuery
withTodos *TodoQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the GroupQuery builder.
func (_q *GroupQuery) Where(ps ...predicate.Group) *GroupQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *GroupQuery) Limit(limit int) *GroupQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *GroupQuery) Offset(offset int) *GroupQuery {
_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 *GroupQuery) Unique(unique bool) *GroupQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *GroupQuery) Order(o ...group.OrderOption) *GroupQuery {
_q.order = append(_q.order, o...)
return _q
}
// QueryUsers chains the current query on the "users" edge.
func (_q *GroupQuery) QueryUsers() *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(group.Table, group.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, group.UsersTable, group.UsersPrimaryKey...),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryTodos chains the current query on the "todos" edge.
func (_q *GroupQuery) QueryTodos() *TodoQuery {
query := (&TodoClient{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(group.Table, group.FieldID, selector),
sqlgraph.To(todo.Table, todo.FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, group.TodosTable, group.TodosColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Group entity from the query.
// Returns a *NotFoundError when no Group was found.
func (_q *GroupQuery) First(ctx context.Context) (*Group, 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{group.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *GroupQuery) FirstX(ctx context.Context) *Group {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Group ID from the query.
// Returns a *NotFoundError when no Group ID was found.
func (_q *GroupQuery) 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{group.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *GroupQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Group entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Group entity is found.
// Returns a *NotFoundError when no Group entities are found.
func (_q *GroupQuery) Only(ctx context.Context) (*Group, 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{group.Label}
default:
return nil, &NotSingularError{group.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *GroupQuery) OnlyX(ctx context.Context) *Group {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Group ID in the query.
// Returns a *NotSingularError when more than one Group ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *GroupQuery) 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{group.Label}
default:
err = &NotSingularError{group.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *GroupQuery) 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 Groups.
func (_q *GroupQuery) All(ctx context.Context) ([]*Group, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Group, *GroupQuery]()
return withInterceptors[[]*Group](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *GroupQuery) AllX(ctx context.Context) []*Group {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Group IDs.
func (_q *GroupQuery) 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(group.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *GroupQuery) 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 *GroupQuery) 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[*GroupQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *GroupQuery) 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 *GroupQuery) 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 *GroupQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the GroupQuery 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 *GroupQuery) Clone() *GroupQuery {
if _q == nil {
return nil
}
return &GroupQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]group.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Group{}, _q.predicates...),
withUsers: _q.withUsers.Clone(),
withTodos: _q.withTodos.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// WithUsers tells the query-builder to eager-load the nodes that are connected to
// the "users" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *GroupQuery) WithUsers(opts ...func(*UserQuery)) *GroupQuery {
query := (&UserClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withUsers = query
return _q
}
// WithTodos tells the query-builder to eager-load the nodes that are connected to
// the "todos" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *GroupQuery) WithTodos(opts ...func(*TodoQuery)) *GroupQuery {
query := (&TodoClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withTodos = 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 {
// Name string `json:"name,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Group.Query().
// GroupBy(group.FieldName).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *GroupQuery) GroupBy(field string, fields ...string) *GroupGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &GroupGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = group.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 {
// Name string `json:"name,omitempty"`
// }
//
// client.Group.Query().
// Select(group.FieldName).
// Scan(ctx, &v)
func (_q *GroupQuery) Select(fields ...string) *GroupSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &GroupSelect{GroupQuery: _q}
sbuild.label = group.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a GroupSelect configured with the given aggregations.
func (_q *GroupQuery) Aggregate(fns ...AggregateFunc) *GroupSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *GroupQuery) 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 !group.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 *GroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Group, error) {
var (
nodes = []*Group{}
_spec = _q.querySpec()
loadedTypes = [2]bool{
_q.withUsers != nil,
_q.withTodos != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Group).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Group{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.withUsers; query != nil {
if err := _q.loadUsers(ctx, query, nodes,
func(n *Group) { n.Edges.Users = []*User{} },
func(n *Group, e *User) { n.Edges.Users = append(n.Edges.Users, e) }); err != nil {
return nil, err
}
}
if query := _q.withTodos; query != nil {
if err := _q.loadTodos(ctx, query, nodes,
func(n *Group) { n.Edges.Todos = []*Todo{} },
func(n *Group, e *Todo) { n.Edges.Todos = append(n.Edges.Todos, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *GroupQuery) loadUsers(ctx context.Context, query *UserQuery, nodes []*Group, init func(*Group), assign func(*Group, *User)) error {
edgeIDs := make([]driver.Value, len(nodes))
byID := make(map[int]*Group)
nids := make(map[int]map[*Group]struct{})
for i, node := range nodes {
edgeIDs[i] = node.ID
byID[node.ID] = node
if init != nil {
init(node)
}
}
query.Where(func(s *sql.Selector) {
joinT := sql.Table(group.UsersTable)
s.Join(joinT).On(s.C(user.FieldID), joinT.C(group.UsersPrimaryKey[0]))
s.Where(sql.InValues(joinT.C(group.UsersPrimaryKey[1]), edgeIDs...))
columns := s.SelectedColumns()
s.Select(joinT.C(group.UsersPrimaryKey[1]))
s.AppendSelect(columns...)
s.SetDistinct(false)
})
if err := query.prepareQuery(ctx); err != nil {
return err
}
qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) {
assign := spec.Assign
values := spec.ScanValues
spec.ScanValues = func(columns []string) ([]any, error) {
values, err := values(columns[1:])
if err != nil {
return nil, err
}
return append([]any{new(sql.NullInt64)}, values...), nil
}
spec.Assign = func(columns []string, values []any) error {
outValue := int(values[0].(*sql.NullInt64).Int64)
inValue := int(values[1].(*sql.NullInt64).Int64)
if nids[inValue] == nil {
nids[inValue] = map[*Group]struct{}{byID[outValue]: {}}
return assign(columns[1:], values[1:])
}
nids[inValue][byID[outValue]] = struct{}{}
return nil
}
})
})
neighbors, err := withInterceptors[[]*User](ctx, query, qr, query.inters)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nids[n.ID]
if !ok {
return fmt.Errorf(`unexpected "users" node returned %v`, n.ID)
}
for kn := range nodes {
assign(kn, n)
}
}
return nil
}
func (_q *GroupQuery) loadTodos(ctx context.Context, query *TodoQuery, nodes []*Group, init func(*Group), assign func(*Group, *Todo)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[int]*Group)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.Todo(func(s *sql.Selector) {
s.Where(sql.InValues(s.C(group.TodosColumn), fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.todo_group
if fk == nil {
return fmt.Errorf(`foreign-key "todo_group" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected referenced foreign-key "todo_group" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (_q *GroupQuery) 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 *GroupQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(group.Table, group.Columns, sqlgraph.NewFieldSpec(group.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, group.FieldID)
for i := range fields {
if fields[i] != group.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 *GroupQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(group.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = group.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
}
// GroupGroupBy is the group-by builder for Group entities.
type GroupGroupBy struct {
selector
build *GroupQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *GroupGroupBy) Aggregate(fns ...AggregateFunc) *GroupGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *GroupGroupBy) 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[*GroupQuery, *GroupGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *GroupGroupBy) sqlScan(ctx context.Context, root *GroupQuery, 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)
}
// GroupSelect is the builder for selecting fields of Group entities.
type GroupSelect struct {
*GroupQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *GroupSelect) Aggregate(fns ...AggregateFunc) *GroupSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *GroupSelect) 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[*GroupQuery, *GroupSelect](ctx, _s.GroupQuery, _s, _s.inters, v)
}
func (_s *GroupSelect) sqlScan(ctx context.Context, root *GroupQuery, 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)
}
+535
View File
@@ -0,0 +1,535 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"ersteller-lib/schema/ent/example/ent/group"
"ersteller-lib/schema/ent/example/ent/predicate"
"ersteller-lib/schema/ent/example/ent/todo"
"ersteller-lib/schema/ent/example/ent/user"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// GroupUpdate is the builder for updating Group entities.
type GroupUpdate struct {
config
hooks []Hook
mutation *GroupMutation
}
// Where appends a list predicates to the GroupUpdate builder.
func (_u *GroupUpdate) Where(ps ...predicate.Group) *GroupUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetName sets the "name" field.
func (_u *GroupUpdate) SetName(v string) *GroupUpdate {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *GroupUpdate) SetNillableName(v *string) *GroupUpdate {
if v != nil {
_u.SetName(*v)
}
return _u
}
// AddUserIDs adds the "users" edge to the User entity by IDs.
func (_u *GroupUpdate) AddUserIDs(ids ...int) *GroupUpdate {
_u.mutation.AddUserIDs(ids...)
return _u
}
// AddUsers adds the "users" edges to the User entity.
func (_u *GroupUpdate) AddUsers(v ...*User) *GroupUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddUserIDs(ids...)
}
// AddTodoIDs adds the "todos" edge to the Todo entity by IDs.
func (_u *GroupUpdate) AddTodoIDs(ids ...int) *GroupUpdate {
_u.mutation.AddTodoIDs(ids...)
return _u
}
// AddTodos adds the "todos" edges to the Todo entity.
func (_u *GroupUpdate) AddTodos(v ...*Todo) *GroupUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddTodoIDs(ids...)
}
// Mutation returns the GroupMutation object of the builder.
func (_u *GroupUpdate) Mutation() *GroupMutation {
return _u.mutation
}
// ClearUsers clears all "users" edges to the User entity.
func (_u *GroupUpdate) ClearUsers() *GroupUpdate {
_u.mutation.ClearUsers()
return _u
}
// RemoveUserIDs removes the "users" edge to User entities by IDs.
func (_u *GroupUpdate) RemoveUserIDs(ids ...int) *GroupUpdate {
_u.mutation.RemoveUserIDs(ids...)
return _u
}
// RemoveUsers removes "users" edges to User entities.
func (_u *GroupUpdate) RemoveUsers(v ...*User) *GroupUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveUserIDs(ids...)
}
// ClearTodos clears all "todos" edges to the Todo entity.
func (_u *GroupUpdate) ClearTodos() *GroupUpdate {
_u.mutation.ClearTodos()
return _u
}
// RemoveTodoIDs removes the "todos" edge to Todo entities by IDs.
func (_u *GroupUpdate) RemoveTodoIDs(ids ...int) *GroupUpdate {
_u.mutation.RemoveTodoIDs(ids...)
return _u
}
// RemoveTodos removes "todos" edges to Todo entities.
func (_u *GroupUpdate) RemoveTodos(v ...*Todo) *GroupUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveTodoIDs(ids...)
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *GroupUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *GroupUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *GroupUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *GroupUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
_spec := sqlgraph.NewUpdateSpec(group.Table, group.Columns, sqlgraph.NewFieldSpec(group.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.Name(); ok {
_spec.SetField(group.FieldName, field.TypeString, value)
}
if _u.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedUsersIDs(); len(nodes) > 0 && !_u.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
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.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.UsersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
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 _u.mutation.TodosCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: group.TodosTable,
Columns: []string{group.TodosColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedTodosIDs(); len(nodes) > 0 && !_u.mutation.TodosCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: group.TodosTable,
Columns: []string{group.TodosColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.TodosIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: group.TodosTable,
Columns: []string{group.TodosColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(todo.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{group.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// GroupUpdateOne is the builder for updating a single Group entity.
type GroupUpdateOne struct {
config
fields []string
hooks []Hook
mutation *GroupMutation
}
// SetName sets the "name" field.
func (_u *GroupUpdateOne) SetName(v string) *GroupUpdateOne {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *GroupUpdateOne) SetNillableName(v *string) *GroupUpdateOne {
if v != nil {
_u.SetName(*v)
}
return _u
}
// AddUserIDs adds the "users" edge to the User entity by IDs.
func (_u *GroupUpdateOne) AddUserIDs(ids ...int) *GroupUpdateOne {
_u.mutation.AddUserIDs(ids...)
return _u
}
// AddUsers adds the "users" edges to the User entity.
func (_u *GroupUpdateOne) AddUsers(v ...*User) *GroupUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddUserIDs(ids...)
}
// AddTodoIDs adds the "todos" edge to the Todo entity by IDs.
func (_u *GroupUpdateOne) AddTodoIDs(ids ...int) *GroupUpdateOne {
_u.mutation.AddTodoIDs(ids...)
return _u
}
// AddTodos adds the "todos" edges to the Todo entity.
func (_u *GroupUpdateOne) AddTodos(v ...*Todo) *GroupUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddTodoIDs(ids...)
}
// Mutation returns the GroupMutation object of the builder.
func (_u *GroupUpdateOne) Mutation() *GroupMutation {
return _u.mutation
}
// ClearUsers clears all "users" edges to the User entity.
func (_u *GroupUpdateOne) ClearUsers() *GroupUpdateOne {
_u.mutation.ClearUsers()
return _u
}
// RemoveUserIDs removes the "users" edge to User entities by IDs.
func (_u *GroupUpdateOne) RemoveUserIDs(ids ...int) *GroupUpdateOne {
_u.mutation.RemoveUserIDs(ids...)
return _u
}
// RemoveUsers removes "users" edges to User entities.
func (_u *GroupUpdateOne) RemoveUsers(v ...*User) *GroupUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveUserIDs(ids...)
}
// ClearTodos clears all "todos" edges to the Todo entity.
func (_u *GroupUpdateOne) ClearTodos() *GroupUpdateOne {
_u.mutation.ClearTodos()
return _u
}
// RemoveTodoIDs removes the "todos" edge to Todo entities by IDs.
func (_u *GroupUpdateOne) RemoveTodoIDs(ids ...int) *GroupUpdateOne {
_u.mutation.RemoveTodoIDs(ids...)
return _u
}
// RemoveTodos removes "todos" edges to Todo entities.
func (_u *GroupUpdateOne) RemoveTodos(v ...*Todo) *GroupUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveTodoIDs(ids...)
}
// Where appends a list predicates to the GroupUpdate builder.
func (_u *GroupUpdateOne) Where(ps ...predicate.Group) *GroupUpdateOne {
_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 *GroupUpdateOne) Select(field string, fields ...string) *GroupUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated Group entity.
func (_u *GroupUpdateOne) Save(ctx context.Context) (*Group, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *GroupUpdateOne) SaveX(ctx context.Context) *Group {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *GroupUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *GroupUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error) {
_spec := sqlgraph.NewUpdateSpec(group.Table, group.Columns, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Group.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, group.FieldID)
for _, f := range fields {
if !group.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != group.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.Name(); ok {
_spec.SetField(group.FieldName, field.TypeString, value)
}
if _u.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedUsersIDs(); len(nodes) > 0 && !_u.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
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.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.UsersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
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 _u.mutation.TodosCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: group.TodosTable,
Columns: []string{group.TodosColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedTodosIDs(); len(nodes) > 0 && !_u.mutation.TodosCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: group.TodosTable,
Columns: []string{group.TodosColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.TodosIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: group.TodosTable,
Columns: []string{group.TodosColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &Group{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{group.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}
+24
View File
@@ -8,6 +8,30 @@ import (
"fmt"
)
// The GroupFunc type is an adapter to allow the use of ordinary
// function as Group mutator.
type GroupFunc func(context.Context, *ent.GroupMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f GroupFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.GroupMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GroupMutation", 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)
+63
View File
@@ -8,6 +8,38 @@ import (
)
var (
// GroupsColumns holds the columns for the "groups" table.
GroupsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "name", Type: field.TypeString, Default: ""},
}
// GroupsTable holds the schema information for the "groups" table.
GroupsTable = &schema.Table{
Name: "groups",
Columns: GroupsColumns,
PrimaryKey: []*schema.Column{GroupsColumns[0]},
}
// TodosColumns holds the columns for the "todos" table.
TodosColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "title", Type: field.TypeString, Default: ""},
{Name: "completed", Type: field.TypeBool, Default: false},
{Name: "todo_group", 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_groups_group",
Columns: []*schema.Column{TodosColumns[3]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.SetNull,
},
},
}
// UsersColumns holds the columns for the "users" table.
UsersColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
@@ -22,11 +54,42 @@ var (
Columns: UsersColumns,
PrimaryKey: []*schema.Column{UsersColumns[0]},
}
// UserGroupColumns holds the columns for the "user_group" table.
UserGroupColumns = []*schema.Column{
{Name: "user_id", Type: field.TypeInt},
{Name: "group_id", Type: field.TypeInt},
}
// UserGroupTable holds the schema information for the "user_group" table.
UserGroupTable = &schema.Table{
Name: "user_group",
Columns: UserGroupColumns,
PrimaryKey: []*schema.Column{UserGroupColumns[0], UserGroupColumns[1]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "user_group_user_id",
Columns: []*schema.Column{UserGroupColumns[0]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.Cascade,
},
{
Symbol: "user_group_group_id",
Columns: []*schema.Column{UserGroupColumns[1]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.Cascade,
},
},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
GroupsTable,
TodosTable,
UsersTable,
UserGroupTable,
}
)
func init() {
TodosTable.ForeignKeys[0].RefTable = GroupsTable
UserGroupTable.ForeignKeys[0].RefTable = UsersTable
UserGroupTable.ForeignKeys[1].RefTable = GroupsTable
}
File diff suppressed because it is too large Load Diff
@@ -10,6 +10,82 @@ import (
"entgo.io/ent/dialect/sql"
)
// PaginateAfterID paginates Group 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 *GroupQuery) PaginateAfterID(ctx context.Context, afterID, limit int) ([]*Group, 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 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.
@@ -6,5 +6,11 @@ import (
"entgo.io/ent/dialect/sql"
)
// Group is the predicate function for group builders.
type Group 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)
+18
View File
@@ -3,7 +3,9 @@
package ent
import (
"ersteller-lib/schema/ent/example/ent/group"
"ersteller-lib/schema/ent/example/ent/schema"
"ersteller-lib/schema/ent/example/ent/todo"
"ersteller-lib/schema/ent/example/ent/user"
"time"
)
@@ -12,6 +14,22 @@ import (
// (default values, validators, hooks and policies) and stitches it
// to their package variables.
func init() {
groupFields := schema.Group{}.Fields()
_ = groupFields
// groupDescName is the schema descriptor for name field.
groupDescName := groupFields[0].Descriptor()
// group.DefaultName holds the default value on creation for the name field.
group.DefaultName = groupDescName.Default.(string)
todoFields := schema.Todo{}.Fields()
_ = todoFields
// 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)
userFields := schema.User{}.Fields()
_ = userFields
// userDescEmail is the schema descriptor for email field.
+27
View File
@@ -0,0 +1,27 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
)
type Group struct {
ent.Schema
}
func (Group) Fields() []ent.Field {
return []ent.Field{
field.String("name").Default(""),
}
}
// Add edges to define relationships
func (Group) Edges() []ent.Edge {
return []ent.Edge{
// Back-reference to users that belong to this group
edge.From("users", User.Type).Ref("group"),
// Back-reference to todos that belong to this group
edge.From("todos", Todo.Type).Ref("group"),
}
}
+24
View File
@@ -0,0 +1,24 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
)
type Todo struct {
ent.Schema
}
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("group", Group.Type).Unique(),
}
}
+7
View File
@@ -4,6 +4,7 @@ import (
"time"
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
)
@@ -23,3 +24,9 @@ func (User) Fields() []ent.Field {
UpdateDefault(time.Now),
}
}
func (User) Edges() []ent.Edge {
return []ent.Edge{
edge.To("group", Group.Type),
}
}
+155
View File
@@ -0,0 +1,155 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"ersteller-lib/schema/ent/example/ent/group"
"ersteller-lib/schema/ent/example/ent/todo"
"fmt"
"strings"
"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"`
// 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_group *int
selectValues sql.SelectValues
}
// TodoEdges holds the relations/edges for other nodes in the graph.
type TodoEdges struct {
// Group holds the value of the group edge.
Group *Group `json:"group,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [1]bool
}
// GroupOrErr returns the Group value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e TodoEdges) GroupOrErr() (*Group, error) {
if e.Group != nil {
return e.Group, nil
} else if e.loadedTypes[0] {
return nil, &NotFoundError{label: group.Label}
}
return nil, &NotLoadedError{edge: "group"}
}
// 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.ForeignKeys[0]: // todo_group
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.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_group", value)
} else if value.Valid {
_m.todo_group = new(int)
*_m.todo_group = 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)
}
// QueryGroup queries the "group" edge of the Todo entity.
func (_m *Todo) QueryGroup() *GroupQuery {
return NewTodoClient(_m.config).QueryGroup(_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("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
+97
View File
@@ -0,0 +1,97 @@
// Code generated by ent, DO NOT EDIT.
package todo
import (
"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"
// 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"
// EdgeGroup holds the string denoting the group edge name in mutations.
EdgeGroup = "group"
// Table holds the table name of the todo in the database.
Table = "todos"
// GroupTable is the table that holds the group relation/edge.
GroupTable = "todos"
// GroupInverseTable is the table name for the Group entity.
// It exists in this package in order to avoid circular dependency with the "group" package.
GroupInverseTable = "groups"
// GroupColumn is the table column denoting the group relation/edge.
GroupColumn = "todo_group"
)
// Columns holds all SQL columns for todo fields.
var Columns = []string{
FieldID,
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_group",
}
// 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 (
// 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()
}
// 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()
}
// ByGroupField orders the results by group field.
func ByGroupField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newGroupStep(), sql.OrderByField(field, opts...))
}
}
func newGroupStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(GroupInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, GroupTable, GroupColumn),
)
}
+178
View File
@@ -0,0 +1,178 @@
// Code generated by ent, DO NOT EDIT.
package todo
import (
"ersteller-lib/schema/ent/example/ent/predicate"
"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))
}
// 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))
}
// 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))
}
// HasGroup applies the HasEdge predicate on the "group" edge.
func HasGroup() predicate.Todo {
return predicate.Todo(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, GroupTable, GroupColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasGroupWith applies the HasEdge predicate on the "group" edge with a given conditions (other predicates).
func HasGroupWith(preds ...predicate.Group) predicate.Todo {
return predicate.Todo(func(s *sql.Selector) {
step := newGroupStep()
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))
}
+263
View File
@@ -0,0 +1,263 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"ersteller-lib/schema/ent/example/ent/group"
"ersteller-lib/schema/ent/example/ent/todo"
"fmt"
"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
}
// 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
}
// SetGroupID sets the "group" edge to the Group entity by ID.
func (_c *TodoCreate) SetGroupID(id int) *TodoCreate {
_c.mutation.SetGroupID(id)
return _c
}
// SetNillableGroupID sets the "group" edge to the Group entity by ID if the given value is not nil.
func (_c *TodoCreate) SetNillableGroupID(id *int) *TodoCreate {
if id != nil {
_c = _c.SetGroupID(*id)
}
return _c
}
// SetGroup sets the "group" edge to the Group entity.
func (_c *TodoCreate) SetGroup(v *Group) *TodoCreate {
return _c.SetGroupID(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.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.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.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.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: todo.GroupTable,
Columns: []string{todo.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.todo_group = &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)
}
}
+88
View File
@@ -0,0 +1,88 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"ersteller-lib/schema/ent/example/ent/predicate"
"ersteller-lib/schema/ent/example/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)
}
}
+614
View File
@@ -0,0 +1,614 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"ersteller-lib/schema/ent/example/ent/group"
"ersteller-lib/schema/ent/example/ent/predicate"
"ersteller-lib/schema/ent/example/ent/todo"
"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
withGroup *GroupQuery
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
}
// QueryGroup chains the current query on the "group" edge.
func (_q *TodoQuery) QueryGroup() *GroupQuery {
query := (&GroupClient{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(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, todo.GroupTable, todo.GroupColumn),
)
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...),
withGroup: _q.withGroup.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// WithGroup tells the query-builder to eager-load the nodes that are connected to
// the "group" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *TodoQuery) WithGroup(opts ...func(*GroupQuery)) *TodoQuery {
query := (&GroupClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withGroup = 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 {
// Title string `json:"title,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Todo.Query().
// GroupBy(todo.FieldTitle).
// 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 {
// Title string `json:"title,omitempty"`
// }
//
// client.Todo.Query().
// Select(todo.FieldTitle).
// 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.withGroup != nil,
}
)
if _q.withGroup != 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.withGroup; query != nil {
if err := _q.loadGroup(ctx, query, nodes, nil,
func(n *Todo, e *Group) { n.Edges.Group = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *TodoQuery) loadGroup(ctx context.Context, query *GroupQuery, nodes []*Todo, init func(*Todo), assign func(*Todo, *Group)) error {
ids := make([]int, 0, len(nodes))
nodeids := make(map[int][]*Todo)
for i := range nodes {
if nodes[i].todo_group == nil {
continue
}
fk := *nodes[i].todo_group
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(group.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_group" 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)
}
+352
View File
@@ -0,0 +1,352 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"ersteller-lib/schema/ent/example/ent/group"
"ersteller-lib/schema/ent/example/ent/predicate"
"ersteller-lib/schema/ent/example/ent/todo"
"fmt"
"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
}
// 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
}
// SetGroupID sets the "group" edge to the Group entity by ID.
func (_u *TodoUpdate) SetGroupID(id int) *TodoUpdate {
_u.mutation.SetGroupID(id)
return _u
}
// SetNillableGroupID sets the "group" edge to the Group entity by ID if the given value is not nil.
func (_u *TodoUpdate) SetNillableGroupID(id *int) *TodoUpdate {
if id != nil {
_u = _u.SetGroupID(*id)
}
return _u
}
// SetGroup sets the "group" edge to the Group entity.
func (_u *TodoUpdate) SetGroup(v *Group) *TodoUpdate {
return _u.SetGroupID(v.ID)
}
// Mutation returns the TodoMutation object of the builder.
func (_u *TodoUpdate) Mutation() *TodoMutation {
return _u.mutation
}
// ClearGroup clears the "group" edge to the Group entity.
func (_u *TodoUpdate) ClearGroup() *TodoUpdate {
_u.mutation.ClearGroup()
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) {
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)
}
}
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.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.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: todo.GroupTable,
Columns: []string{todo.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: todo.GroupTable,
Columns: []string{todo.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.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
}
// 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
}
// SetGroupID sets the "group" edge to the Group entity by ID.
func (_u *TodoUpdateOne) SetGroupID(id int) *TodoUpdateOne {
_u.mutation.SetGroupID(id)
return _u
}
// SetNillableGroupID sets the "group" edge to the Group entity by ID if the given value is not nil.
func (_u *TodoUpdateOne) SetNillableGroupID(id *int) *TodoUpdateOne {
if id != nil {
_u = _u.SetGroupID(*id)
}
return _u
}
// SetGroup sets the "group" edge to the Group entity.
func (_u *TodoUpdateOne) SetGroup(v *Group) *TodoUpdateOne {
return _u.SetGroupID(v.ID)
}
// Mutation returns the TodoMutation object of the builder.
func (_u *TodoUpdateOne) Mutation() *TodoMutation {
return _u.mutation
}
// ClearGroup clears the "group" edge to the Group entity.
func (_u *TodoUpdateOne) ClearGroup() *TodoUpdateOne {
_u.mutation.ClearGroup()
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) {
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)
}
}
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.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.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: todo.GroupTable,
Columns: []string{todo.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: todo.GroupTable,
Columns: []string{todo.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.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
}
+7 -1
View File
@@ -12,6 +12,10 @@ import (
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
// Group is the client for interacting with the Group builders.
Group *GroupClient
// Todo is the client for interacting with the Todo builders.
Todo *TodoClient
// User is the client for interacting with the User builders.
User *UserClient
@@ -145,6 +149,8 @@ func (tx *Tx) Client() *Client {
}
func (tx *Tx) init() {
tx.Group = NewGroupClient(tx.config)
tx.Todo = NewTodoClient(tx.config)
tx.User = NewUserClient(tx.config)
}
@@ -155,7 +161,7 @@ func (tx *Tx) init() {
// of them in order to commit or rollback the transaction.
//
// If a closed transaction is embedded in one of the generated entities, and the entity
// applies a query, for example: User.QueryXXX(), the query will be executed
// applies a query, for example: Group.QueryXXX(), the query will be executed
// through the driver which created this transaction.
//
// Note that txDriver is not goroutine safe.
+27 -1
View File
@@ -24,10 +24,31 @@ type User struct {
// 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"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the UserQuery when eager-loading is set.
Edges UserEdges `json:"edges"`
selectValues sql.SelectValues
}
// UserEdges holds the relations/edges for other nodes in the graph.
type UserEdges struct {
// Group holds the value of the group edge.
Group []*Group `json:"group,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [1]bool
}
// GroupOrErr returns the Group value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) GroupOrErr() ([]*Group, error) {
if e.loadedTypes[0] {
return e.Group, nil
}
return nil, &NotLoadedError{edge: "group"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*User) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
@@ -97,6 +118,11 @@ func (_m *User) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryGroup queries the "group" edge of the User entity.
func (_m *User) QueryGroup() *GroupQuery {
return NewUserClient(_m.config).QueryGroup(_m)
}
// Update returns a builder for updating this User.
// Note that you need to call User.Unwrap() before calling this method if this User
// was returned from a transaction, and the transaction was committed or rolled back.
+35
View File
@@ -6,6 +6,7 @@ import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
@@ -21,8 +22,15 @@ const (
FieldCreatedAt = "created_at"
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
FieldUpdatedAt = "updated_at"
// EdgeGroup holds the string denoting the group edge name in mutations.
EdgeGroup = "group"
// Table holds the table name of the user in the database.
Table = "users"
// GroupTable is the table that holds the group relation/edge. The primary key declared below.
GroupTable = "user_group"
// GroupInverseTable is the table name for the Group entity.
// It exists in this package in order to avoid circular dependency with the "group" package.
GroupInverseTable = "groups"
)
// Columns holds all SQL columns for user fields.
@@ -34,6 +42,12 @@ var Columns = []string{
FieldUpdatedAt,
}
var (
// GroupPrimaryKey and GroupColumn2 are the table columns denoting the
// primary key for the group relation (M2M).
GroupPrimaryKey = []string{"user_id", "group_id"}
)
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
@@ -84,3 +98,24 @@ func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
}
// ByGroupCount orders the results by group count.
func ByGroupCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newGroupStep(), opts...)
}
}
// ByGroup orders the results by group terms.
func ByGroup(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newGroupStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
func newGroupStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(GroupInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, GroupTable, GroupPrimaryKey...),
)
}
+24
View File
@@ -7,6 +7,7 @@ import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
// ID filters vertices based on their ID field.
@@ -284,6 +285,29 @@ func UpdatedAtLTE(v time.Time) predicate.User {
return predicate.User(sql.FieldLTE(FieldUpdatedAt, v))
}
// HasGroup applies the HasEdge predicate on the "group" edge.
func HasGroup() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, GroupTable, GroupPrimaryKey...),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasGroupWith applies the HasEdge predicate on the "group" edge with a given conditions (other predicates).
func HasGroupWith(preds ...predicate.Group) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newGroupStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.User) predicate.User {
return predicate.User(sql.AndPredicates(predicates...))
+32
View File
@@ -5,6 +5,7 @@ package ent
import (
"context"
"errors"
"ersteller-lib/schema/ent/example/ent/group"
"ersteller-lib/schema/ent/example/ent/user"
"fmt"
"time"
@@ -76,6 +77,21 @@ func (_c *UserCreate) SetNillableUpdatedAt(v *time.Time) *UserCreate {
return _c
}
// AddGroupIDs adds the "group" edge to the Group entity by IDs.
func (_c *UserCreate) AddGroupIDs(ids ...int) *UserCreate {
_c.mutation.AddGroupIDs(ids...)
return _c
}
// AddGroup adds the "group" edges to the Group entity.
func (_c *UserCreate) AddGroup(v ...*Group) *UserCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddGroupIDs(ids...)
}
// Mutation returns the UserMutation object of the builder.
func (_c *UserCreate) Mutation() *UserMutation {
return _c.mutation
@@ -185,6 +201,22 @@ func (_c *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) {
_spec.SetField(user.FieldUpdatedAt, field.TypeTime, value)
_node.UpdatedAt = value
}
if nodes := _c.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.GroupTable,
Columns: user.GroupPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
+112 -2
View File
@@ -4,6 +4,8 @@ package ent
import (
"context"
"database/sql/driver"
"ersteller-lib/schema/ent/example/ent/group"
"ersteller-lib/schema/ent/example/ent/predicate"
"ersteller-lib/schema/ent/example/ent/user"
"fmt"
@@ -22,6 +24,7 @@ type UserQuery struct {
order []user.OrderOption
inters []Interceptor
predicates []predicate.User
withGroup *GroupQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
@@ -58,6 +61,28 @@ func (_q *UserQuery) Order(o ...user.OrderOption) *UserQuery {
return _q
}
// QueryGroup chains the current query on the "group" edge.
func (_q *UserQuery) QueryGroup() *GroupQuery {
query := (&GroupClient{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(user.Table, user.FieldID, selector),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, user.GroupTable, user.GroupPrimaryKey...),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first User entity from the query.
// Returns a *NotFoundError when no User was found.
func (_q *UserQuery) First(ctx context.Context) (*User, error) {
@@ -250,12 +275,24 @@ func (_q *UserQuery) Clone() *UserQuery {
order: append([]user.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.User{}, _q.predicates...),
withGroup: _q.withGroup.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// WithGroup tells the query-builder to eager-load the nodes that are connected to
// the "group" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *UserQuery) WithGroup(opts ...func(*GroupQuery)) *UserQuery {
query := (&GroupClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withGroup = 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.
//
@@ -332,8 +369,11 @@ func (_q *UserQuery) prepareQuery(ctx context.Context) error {
func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, error) {
var (
nodes = []*User{}
_spec = _q.querySpec()
nodes = []*User{}
_spec = _q.querySpec()
loadedTypes = [1]bool{
_q.withGroup != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*User).scanValues(nil, columns)
@@ -341,6 +381,7 @@ func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e
_spec.Assign = func(columns []string, values []any) error {
node := &User{config: _q.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
for i := range hooks {
@@ -352,9 +393,78 @@ func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e
if len(nodes) == 0 {
return nodes, nil
}
if query := _q.withGroup; query != nil {
if err := _q.loadGroup(ctx, query, nodes,
func(n *User) { n.Edges.Group = []*Group{} },
func(n *User, e *Group) { n.Edges.Group = append(n.Edges.Group, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *UserQuery) loadGroup(ctx context.Context, query *GroupQuery, nodes []*User, init func(*User), assign func(*User, *Group)) error {
edgeIDs := make([]driver.Value, len(nodes))
byID := make(map[int]*User)
nids := make(map[int]map[*User]struct{})
for i, node := range nodes {
edgeIDs[i] = node.ID
byID[node.ID] = node
if init != nil {
init(node)
}
}
query.Where(func(s *sql.Selector) {
joinT := sql.Table(user.GroupTable)
s.Join(joinT).On(s.C(group.FieldID), joinT.C(user.GroupPrimaryKey[1]))
s.Where(sql.InValues(joinT.C(user.GroupPrimaryKey[0]), edgeIDs...))
columns := s.SelectedColumns()
s.Select(joinT.C(user.GroupPrimaryKey[0]))
s.AppendSelect(columns...)
s.SetDistinct(false)
})
if err := query.prepareQuery(ctx); err != nil {
return err
}
qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) {
assign := spec.Assign
values := spec.ScanValues
spec.ScanValues = func(columns []string) ([]any, error) {
values, err := values(columns[1:])
if err != nil {
return nil, err
}
return append([]any{new(sql.NullInt64)}, values...), nil
}
spec.Assign = func(columns []string, values []any) error {
outValue := int(values[0].(*sql.NullInt64).Int64)
inValue := int(values[1].(*sql.NullInt64).Int64)
if nids[inValue] == nil {
nids[inValue] = map[*User]struct{}{byID[outValue]: {}}
return assign(columns[1:], values[1:])
}
nids[inValue][byID[outValue]] = struct{}{}
return nil
}
})
})
neighbors, err := withInterceptors[[]*Group](ctx, query, qr, query.inters)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nids[n.ID]
if !ok {
return fmt.Errorf(`unexpected "group" node returned %v`, n.ID)
}
for kn := range nodes {
assign(kn, n)
}
}
return nil
}
func (_q *UserQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Columns = _q.ctx.Fields
+163
View File
@@ -5,6 +5,7 @@ package ent
import (
"context"
"errors"
"ersteller-lib/schema/ent/example/ent/group"
"ersteller-lib/schema/ent/example/ent/predicate"
"ersteller-lib/schema/ent/example/ent/user"
"fmt"
@@ -62,11 +63,47 @@ func (_u *UserUpdate) SetUpdatedAt(v time.Time) *UserUpdate {
return _u
}
// AddGroupIDs adds the "group" edge to the Group entity by IDs.
func (_u *UserUpdate) AddGroupIDs(ids ...int) *UserUpdate {
_u.mutation.AddGroupIDs(ids...)
return _u
}
// AddGroup adds the "group" edges to the Group entity.
func (_u *UserUpdate) AddGroup(v ...*Group) *UserUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddGroupIDs(ids...)
}
// Mutation returns the UserMutation object of the builder.
func (_u *UserUpdate) Mutation() *UserMutation {
return _u.mutation
}
// ClearGroup clears all "group" edges to the Group entity.
func (_u *UserUpdate) ClearGroup() *UserUpdate {
_u.mutation.ClearGroup()
return _u
}
// RemoveGroupIDs removes the "group" edge to Group entities by IDs.
func (_u *UserUpdate) RemoveGroupIDs(ids ...int) *UserUpdate {
_u.mutation.RemoveGroupIDs(ids...)
return _u
}
// RemoveGroup removes "group" edges to Group entities.
func (_u *UserUpdate) RemoveGroup(v ...*Group) *UserUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveGroupIDs(ids...)
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *UserUpdate) Save(ctx context.Context) (int, error) {
_u.defaults()
@@ -121,6 +158,51 @@ func (_u *UserUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(user.FieldUpdatedAt, field.TypeTime, value)
}
if _u.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.GroupTable,
Columns: user.GroupPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedGroupIDs(); len(nodes) > 0 && !_u.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.GroupTable,
Columns: user.GroupPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.GroupTable,
Columns: user.GroupPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.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{user.Label}
@@ -175,11 +257,47 @@ func (_u *UserUpdateOne) SetUpdatedAt(v time.Time) *UserUpdateOne {
return _u
}
// AddGroupIDs adds the "group" edge to the Group entity by IDs.
func (_u *UserUpdateOne) AddGroupIDs(ids ...int) *UserUpdateOne {
_u.mutation.AddGroupIDs(ids...)
return _u
}
// AddGroup adds the "group" edges to the Group entity.
func (_u *UserUpdateOne) AddGroup(v ...*Group) *UserUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddGroupIDs(ids...)
}
// Mutation returns the UserMutation object of the builder.
func (_u *UserUpdateOne) Mutation() *UserMutation {
return _u.mutation
}
// ClearGroup clears all "group" edges to the Group entity.
func (_u *UserUpdateOne) ClearGroup() *UserUpdateOne {
_u.mutation.ClearGroup()
return _u
}
// RemoveGroupIDs removes the "group" edge to Group entities by IDs.
func (_u *UserUpdateOne) RemoveGroupIDs(ids ...int) *UserUpdateOne {
_u.mutation.RemoveGroupIDs(ids...)
return _u
}
// RemoveGroup removes "group" edges to Group entities.
func (_u *UserUpdateOne) RemoveGroup(v ...*Group) *UserUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveGroupIDs(ids...)
}
// Where appends a list predicates to the UserUpdate builder.
func (_u *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne {
_u.mutation.Where(ps...)
@@ -264,6 +382,51 @@ func (_u *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) {
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(user.FieldUpdatedAt, field.TypeTime, value)
}
if _u.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.GroupTable,
Columns: user.GroupPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedGroupIDs(); len(nodes) > 0 && !_u.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.GroupTable,
Columns: user.GroupPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.GroupTable,
Columns: user.GroupPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &User{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
+81 -1
View File
@@ -3,6 +3,10 @@ package main
import (
"context"
"ersteller-lib/schema/ent/example/ent"
"ersteller-lib/schema/ent/example/ent/group"
"ersteller-lib/schema/ent/example/ent/todo"
"ersteller-lib/schema/ent/example/ent/user"
"fmt"
"log"
"time"
@@ -18,15 +22,27 @@ func main() {
}
log.Println("client", client)
defer client.Close()
// Add authorization interceptor for Todo queries
client.Todo.Intercept(TodoAuthorizationInterceptor())
ctx, cancel := context.WithTimeout(context.Background(), time.Minute*5)
defer cancel()
if err := client.Schema.Create(ctx); err != nil {
log.Fatalf("failed creating schema resources: %v", err)
}
testGroup, err := client.Group.Create().SetName("Test").Save(ctx)
if err != nil {
log.Fatalf("failed creating group: %w", err)
}
u, err := client.User.
Create().
SetEmail("something@gorlug.de").
SetPassword("uhoh").Save(ctx)
SetPassword("uhoh").
AddGroup(testGroup).
Save(ctx)
if err != nil {
log.Fatalf("failed creating user: %w", err)
}
@@ -60,4 +76,68 @@ func main() {
}
}
todoItem, err := client.Todo.Create().SetTitle("test").
SetGroup(testGroup).Save(ctx)
if err != nil {
log.Fatalf("failed to create todo", err)
}
// Add user ID to context for authorization
authorizedCtx := context.WithValue(ctx, UserIDKey, u.ID)
// This should work - user is in the group
retrievedTodo, err := client.Todo.Get(authorizedCtx, todoItem.ID)
if err != nil {
log.Fatalf("failed getting todo with authorization: %v", err)
}
log.Println("retrieved todo:", retrievedTodo)
// This should fail - no user ID in context
_, err = client.Todo.Get(ctx, todoItem.ID)
if err != nil {
log.Println("expected authorization error:", err)
}
secondGroup, err := client.Group.Create().SetName("second").Save(ctx)
if err != nil {
log.Fatalf("failed creating group: %w", err)
}
secondUser, err := client.User.Create().SetEmail("abc@def.de").AddGroup(secondGroup).Save(ctx)
if err != nil {
log.Fatalf("failed creating user: %w", err)
}
// Add user ID to context for authorization
secondUserAuthorizedCtx := context.WithValue(ctx, UserIDKey, secondUser.ID)
_, err = client.Todo.Get(secondUserAuthorizedCtx, todoItem.ID)
if err != nil {
log.Println("expected authorization error:", err)
}
}
// UserIDKey is used to store user ID in context
type contextKey string
const UserIDKey = contextKey("userID")
// TodoAuthorizationInterceptor returns an interceptor that enforces user authorization for todos
func TodoAuthorizationInterceptor() ent.Interceptor {
return ent.InterceptFunc(func(next ent.Querier) ent.Querier {
return ent.QuerierFunc(func(ctx context.Context, query ent.Query) (ent.Value, error) {
// Get user ID from context
userID, ok := ctx.Value(UserIDKey).(int)
if !ok {
return nil, fmt.Errorf("user ID is required in context for todo operations")
}
// Cast to TodoQuery to add authorization filter
if tq, ok := query.(*ent.TodoQuery); ok {
// Add predicate to ensure user is in the same group as the todo
tq = tq.Where(todo.HasGroupWith(group.HasUsersWith(user.ID(userID))))
return next.Query(ctx, tq)
}
return next.Query(ctx, query)
})
})
}