snapshot of https://github.com/ent/ent.git (master, 2026-09-15; blobs > 131072B omitted)
Some checks failed
Atlas CI Public / lint (push) Failing after 13s
Atlas CI Public / sync (push) Has been skipped

This commit is contained in:
upstream-mirror
2026-09-15 22:12:36 +05:00
commit 4b3ad0b611
2680 changed files with 719472 additions and 0 deletions

View File

@@ -0,0 +1,740 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"log"
"reflect"
"entgo.io/ent"
"entgo.io/ent/entc/integration/privacy/ent/migrate"
"net/http"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/privacy/ent/task"
"entgo.io/ent/entc/integration/privacy/ent/team"
"entgo.io/ent/entc/integration/privacy/ent/user"
)
// Client is the client that holds all ent builders.
type Client struct {
config
// Schema is the client for creating, migrating and dropping schema.
Schema *migrate.Schema
// Task is the client for interacting with the Task builders.
Task *TaskClient
// Team is the client for interacting with the Team builders.
Team *TeamClient
// User is the client for interacting with the User builders.
User *UserClient
}
// NewClient creates a new client configured with the given options.
func NewClient(opts ...Option) *Client {
client := &Client{config: newConfig(opts...)}
client.init()
return client
}
func (c *Client) init() {
c.Schema = migrate.NewSchema(c.driver)
c.Task = NewTaskClient(c.config)
c.Team = NewTeamClient(c.config)
c.User = NewUserClient(c.config)
}
type (
// config is the configuration for the client and its builder.
config struct {
// driver used for executing database requests.
driver dialect.Driver
// debug enable a debug logging.
debug bool
// log used for logging on debug mode.
log func(...any)
// hooks to execute on mutations.
hooks *hooks
// interceptors to execute on queries.
inters *inters
HTTPClient *http.Client
}
// Option function to configure the client.
Option func(*config)
)
// newConfig creates a new config for the client.
func newConfig(opts ...Option) config {
cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}}
cfg.options(opts...)
return cfg
}
// options applies the options on the config object.
func (c *config) options(opts ...Option) {
for _, opt := range opts {
opt(c)
}
if c.debug {
c.driver = dialect.Debug(c.driver, c.log)
}
}
// Debug enables debug logging on the ent.Driver.
func Debug() Option {
return func(c *config) {
c.debug = true
}
}
// Log sets the logging function for debug mode.
func Log(fn func(...any)) Option {
return func(c *config) {
c.log = fn
}
}
// Driver configures the client driver.
func Driver(driver dialect.Driver) Option {
return func(c *config) {
c.driver = driver
}
}
// HTTPClient configures the HTTPClient.
func HTTPClient(v *http.Client) Option {
return func(c *config) {
c.HTTPClient = v
}
}
// Open opens a database/sql.DB specified by the driver name and
// the data source name, and returns a new client attached to it.
// Optional parameters can be added for configuring the client.
func Open(driverName, dataSourceName string, options ...Option) (*Client, error) {
switch driverName {
case dialect.MySQL, dialect.Postgres, dialect.SQLite:
drv, err := sql.Open(driverName, dataSourceName)
if err != nil {
return nil, err
}
return NewClient(append(options, Driver(drv))...), nil
default:
return nil, fmt.Errorf("unsupported driver: %q", driverName)
}
}
// ErrTxStarted is returned when trying to start a new transaction from a transactional client.
var ErrTxStarted = errors.New("ent: cannot start a transaction within a transaction")
// Tx returns a new transactional client. The provided context
// is used until the transaction is committed or rolled back.
func (c *Client) Tx(ctx context.Context) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, ErrTxStarted
}
tx, err := newTx(ctx, c.driver)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
}
cfg := c.config
cfg.driver = tx
return &Tx{
ctx: ctx,
config: cfg,
Task: NewTaskClient(cfg),
Team: NewTeamClient(cfg),
User: NewUserClient(cfg),
}, nil
}
// BeginTx returns a transactional client with specified options.
func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, errors.New("ent: cannot start a transaction within a transaction")
}
tx, err := c.driver.(interface {
BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error)
}).BeginTx(ctx, opts)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
}
cfg := c.config
cfg.driver = &txDriver{tx: tx, drv: c.driver}
return &Tx{
ctx: ctx,
config: cfg,
Task: NewTaskClient(cfg),
Team: NewTeamClient(cfg),
User: NewUserClient(cfg),
}, nil
}
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
//
// client.Debug().
// Task.
// Query().
// Count(ctx)
func (c *Client) Debug() *Client {
if c.debug {
return c
}
cfg := c.config
cfg.driver = dialect.Debug(c.driver, c.log)
client := &Client{config: cfg}
client.init()
return client
}
// Close closes the database connection and prevents new queries from starting.
func (c *Client) Close() error {
return c.driver.Close()
}
// 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.Task.Use(hooks...)
c.Team.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.Task.Intercept(interceptors...)
c.Team.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 *TaskMutation:
return c.Task.mutate(ctx, m)
case *TeamMutation:
return c.Team.mutate(ctx, m)
case *UserMutation:
return c.User.mutate(ctx, m)
default:
return nil, fmt.Errorf("ent: unknown mutation type %T", m)
}
}
// TaskClient is a client for the Task schema.
type TaskClient struct {
config
}
// NewTaskClient returns a client for the Task from the given config.
func NewTaskClient(c config) *TaskClient {
return &TaskClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `task.Hooks(f(g(h())))`.
func (c *TaskClient) Use(hooks ...Hook) {
c.hooks.Task = append(c.hooks.Task, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `task.Intercept(f(g(h())))`.
func (c *TaskClient) Intercept(interceptors ...Interceptor) {
c.inters.Task = append(c.inters.Task, interceptors...)
}
// Create returns a builder for creating a Task entity.
func (c *TaskClient) Create() *TaskCreate {
mutation := newTaskMutation(c.config, OpCreate)
return &TaskCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Task entities.
func (c *TaskClient) CreateBulk(builders ...*TaskCreate) *TaskCreateBulk {
return &TaskCreateBulk{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 *TaskClient) MapCreateBulk(slice any, setFunc func(*TaskCreate, int)) *TaskCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &TaskCreateBulk{err: fmt.Errorf("calling to TaskClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*TaskCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &TaskCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Task.
func (c *TaskClient) Update() *TaskUpdate {
mutation := newTaskMutation(c.config, OpUpdate)
return &TaskUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *TaskClient) UpdateOne(_m *Task) *TaskUpdateOne {
mutation := newTaskMutation(c.config, OpUpdateOne, withTask(_m))
return &TaskUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *TaskClient) UpdateOneID(id int) *TaskUpdateOne {
mutation := newTaskMutation(c.config, OpUpdateOne, withTaskID(id))
return &TaskUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Task.
func (c *TaskClient) Delete() *TaskDelete {
mutation := newTaskMutation(c.config, OpDelete)
return &TaskDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *TaskClient) DeleteOne(_m *Task) *TaskDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *TaskClient) DeleteOneID(id int) *TaskDeleteOne {
builder := c.Delete().Where(task.ID(id))
builder.mutation.id = &id
builder.mutation.SetOp(OpDeleteOne)
return &TaskDeleteOne{builder}
}
// Query returns a query builder for Task.
func (c *TaskClient) Query() *TaskQuery {
return &TaskQuery{
config: c.config,
ctx: &QueryContext{Type: TypeTask},
inters: c.Interceptors(),
}
}
// Get returns a Task entity by its id.
func (c *TaskClient) Get(ctx context.Context, id int) (*Task, error) {
return c.Query().Where(task.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *TaskClient) GetX(ctx context.Context, id int) *Task {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryTeams queries the teams edge of a Task.
func (c *TaskClient) QueryTeams(_m *Task) *TeamQuery {
query := (&TeamClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(task.Table, task.FieldID, id),
sqlgraph.To(team.Table, team.FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, task.TeamsTable, task.TeamsPrimaryKey...),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryOwner queries the owner edge of a Task.
func (c *TaskClient) QueryOwner(_m *Task) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(task.Table, task.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, task.OwnerTable, task.OwnerColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *TaskClient) Hooks() []Hook {
hooks := c.hooks.Task
return append(hooks[:len(hooks):len(hooks)], task.Hooks[:]...)
}
// Interceptors returns the client interceptors.
func (c *TaskClient) Interceptors() []Interceptor {
return c.inters.Task
}
func (c *TaskClient) mutate(ctx context.Context, m *TaskMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&TaskCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&TaskUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&TaskUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&TaskDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Task mutation op: %q", m.Op())
}
}
// TeamClient is a client for the Team schema.
type TeamClient struct {
config
}
// NewTeamClient returns a client for the Team from the given config.
func NewTeamClient(c config) *TeamClient {
return &TeamClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `team.Hooks(f(g(h())))`.
func (c *TeamClient) Use(hooks ...Hook) {
c.hooks.Team = append(c.hooks.Team, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `team.Intercept(f(g(h())))`.
func (c *TeamClient) Intercept(interceptors ...Interceptor) {
c.inters.Team = append(c.inters.Team, interceptors...)
}
// Create returns a builder for creating a Team entity.
func (c *TeamClient) Create() *TeamCreate {
mutation := newTeamMutation(c.config, OpCreate)
return &TeamCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Team entities.
func (c *TeamClient) CreateBulk(builders ...*TeamCreate) *TeamCreateBulk {
return &TeamCreateBulk{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 *TeamClient) MapCreateBulk(slice any, setFunc func(*TeamCreate, int)) *TeamCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &TeamCreateBulk{err: fmt.Errorf("calling to TeamClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*TeamCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &TeamCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Team.
func (c *TeamClient) Update() *TeamUpdate {
mutation := newTeamMutation(c.config, OpUpdate)
return &TeamUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *TeamClient) UpdateOne(_m *Team) *TeamUpdateOne {
mutation := newTeamMutation(c.config, OpUpdateOne, withTeam(_m))
return &TeamUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *TeamClient) UpdateOneID(id int) *TeamUpdateOne {
mutation := newTeamMutation(c.config, OpUpdateOne, withTeamID(id))
return &TeamUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Team.
func (c *TeamClient) Delete() *TeamDelete {
mutation := newTeamMutation(c.config, OpDelete)
return &TeamDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *TeamClient) DeleteOne(_m *Team) *TeamDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *TeamClient) DeleteOneID(id int) *TeamDeleteOne {
builder := c.Delete().Where(team.ID(id))
builder.mutation.id = &id
builder.mutation.SetOp(OpDeleteOne)
return &TeamDeleteOne{builder}
}
// Query returns a query builder for Team.
func (c *TeamClient) Query() *TeamQuery {
return &TeamQuery{
config: c.config,
ctx: &QueryContext{Type: TypeTeam},
inters: c.Interceptors(),
}
}
// Get returns a Team entity by its id.
func (c *TeamClient) Get(ctx context.Context, id int) (*Team, error) {
return c.Query().Where(team.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *TeamClient) GetX(ctx context.Context, id int) *Team {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryTasks queries the tasks edge of a Team.
func (c *TeamClient) QueryTasks(_m *Team) *TaskQuery {
query := (&TaskClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(team.Table, team.FieldID, id),
sqlgraph.To(task.Table, task.FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, team.TasksTable, team.TasksPrimaryKey...),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryUsers queries the users edge of a Team.
func (c *TeamClient) QueryUsers(_m *Team) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(team.Table, team.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, team.UsersTable, team.UsersPrimaryKey...),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *TeamClient) Hooks() []Hook {
hooks := c.hooks.Team
return append(hooks[:len(hooks):len(hooks)], team.Hooks[:]...)
}
// Interceptors returns the client interceptors.
func (c *TeamClient) Interceptors() []Interceptor {
return c.inters.Team
}
func (c *TeamClient) mutate(ctx context.Context, m *TeamMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&TeamCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&TeamUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&TeamUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&TeamDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Team mutation op: %q", m.Op())
}
}
// UserClient is a client for the User schema.
type UserClient struct {
config
}
// NewUserClient returns a client for the User from the given config.
func NewUserClient(c config) *UserClient {
return &UserClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `user.Hooks(f(g(h())))`.
func (c *UserClient) Use(hooks ...Hook) {
c.hooks.User = append(c.hooks.User, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `user.Intercept(f(g(h())))`.
func (c *UserClient) Intercept(interceptors ...Interceptor) {
c.inters.User = append(c.inters.User, interceptors...)
}
// Create returns a builder for creating a User entity.
func (c *UserClient) Create() *UserCreate {
mutation := newUserMutation(c.config, OpCreate)
return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of User entities.
func (c *UserClient) CreateBulk(builders ...*UserCreate) *UserCreateBulk {
return &UserCreateBulk{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 *UserClient) MapCreateBulk(slice any, setFunc func(*UserCreate, int)) *UserCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &UserCreateBulk{err: fmt.Errorf("calling to UserClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*UserCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &UserCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for User.
func (c *UserClient) Update() *UserUpdate {
mutation := newUserMutation(c.config, OpUpdate)
return &UserUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *UserClient) UpdateOne(_m *User) *UserUpdateOne {
mutation := newUserMutation(c.config, OpUpdateOne, withUser(_m))
return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *UserClient) UpdateOneID(id int) *UserUpdateOne {
mutation := newUserMutation(c.config, OpUpdateOne, withUserID(id))
return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for User.
func (c *UserClient) Delete() *UserDelete {
mutation := newUserMutation(c.config, OpDelete)
return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *UserClient) DeleteOne(_m *User) *UserDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *UserClient) DeleteOneID(id int) *UserDeleteOne {
builder := c.Delete().Where(user.ID(id))
builder.mutation.id = &id
builder.mutation.SetOp(OpDeleteOne)
return &UserDeleteOne{builder}
}
// Query returns a query builder for User.
func (c *UserClient) Query() *UserQuery {
return &UserQuery{
config: c.config,
ctx: &QueryContext{Type: TypeUser},
inters: c.Interceptors(),
}
}
// Get returns a User entity by its id.
func (c *UserClient) Get(ctx context.Context, id int) (*User, error) {
return c.Query().Where(user.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *UserClient) GetX(ctx context.Context, id int) *User {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryTeams queries the teams edge of a User.
func (c *UserClient) QueryTeams(_m *User) *TeamQuery {
query := (&TeamClient{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(team.Table, team.FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, user.TeamsTable, user.TeamsPrimaryKey...),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryTasks queries the tasks edge of a User.
func (c *UserClient) QueryTasks(_m *User) *TaskQuery {
query := (&TaskClient{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(task.Table, task.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, user.TasksTable, user.TasksColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *UserClient) Hooks() []Hook {
hooks := c.hooks.User
return append(hooks[:len(hooks):len(hooks)], user.Hooks[:]...)
}
// Interceptors returns the client interceptors.
func (c *UserClient) Interceptors() []Interceptor {
return c.inters.User
}
func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&UserCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&UserUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&UserDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown User mutation op: %q", m.Op())
}
}
// hooks and interceptors per client, for fast access.
type (
hooks struct {
Task, Team, User []ent.Hook
}
inters struct {
Task, Team, User []ent.Interceptor
}
)

View File

@@ -0,0 +1,616 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"reflect"
"sync"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/privacy/ent/task"
"entgo.io/ent/entc/integration/privacy/ent/team"
"entgo.io/ent/entc/integration/privacy/ent/user"
)
// ent aliases to avoid import conflicts in user's code.
type (
Op = ent.Op
Hook = ent.Hook
Value = ent.Value
Query = ent.Query
QueryContext = ent.QueryContext
Querier = ent.Querier
QuerierFunc = ent.QuerierFunc
Interceptor = ent.Interceptor
InterceptFunc = ent.InterceptFunc
Traverser = ent.Traverser
TraverseFunc = ent.TraverseFunc
Policy = ent.Policy
Mutator = ent.Mutator
Mutation = ent.Mutation
MutateFunc = ent.MutateFunc
)
type clientCtxKey struct{}
// FromContext returns a Client stored inside a context, or nil if there isn't one.
func FromContext(ctx context.Context) *Client {
c, _ := ctx.Value(clientCtxKey{}).(*Client)
return c
}
// NewContext returns a new context with the given Client attached.
func NewContext(parent context.Context, c *Client) context.Context {
return context.WithValue(parent, clientCtxKey{}, c)
}
type txCtxKey struct{}
// TxFromContext returns a Tx stored inside a context, or nil if there isn't one.
func TxFromContext(ctx context.Context) *Tx {
tx, _ := ctx.Value(txCtxKey{}).(*Tx)
return tx
}
// NewTxContext returns a new context with the given Tx attached.
func NewTxContext(parent context.Context, tx *Tx) context.Context {
return context.WithValue(parent, txCtxKey{}, tx)
}
// OrderFunc applies an ordering on the sql selector.
// Deprecated: Use Asc/Desc functions or the package builders instead.
type OrderFunc func(*sql.Selector)
var (
initCheck sync.Once
columnCheck sql.ColumnCheck
)
// checkColumn checks if the column exists in the given table.
func checkColumn(t, c string) error {
initCheck.Do(func() {
columnCheck = sql.NewColumnCheck(map[string]func(string) bool{
task.Table: task.ValidColumn,
team.Table: team.ValidColumn,
user.Table: user.ValidColumn,
})
})
return columnCheck(t, c)
}
// Asc applies the given fields in ASC order.
func Asc(fields ...string) func(*sql.Selector) {
return func(s *sql.Selector) {
for _, f := range fields {
if err := checkColumn(s.TableName(), f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
}
s.OrderBy(sql.Asc(s.C(f)))
}
}
}
// Desc applies the given fields in DESC order.
func Desc(fields ...string) func(*sql.Selector) {
return func(s *sql.Selector) {
for _, f := range fields {
if err := checkColumn(s.TableName(), f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
}
s.OrderBy(sql.Desc(s.C(f)))
}
}
}
// AggregateFunc applies an aggregation step on the group-by traversal/selector.
type AggregateFunc func(*sql.Selector) string
// As is a pseudo aggregation function for renaming another other functions with custom names. For example:
//
// GroupBy(field1, field2).
// Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")).
// Scan(ctx, &v)
func As(fn AggregateFunc, end string) AggregateFunc {
return func(s *sql.Selector) string {
return sql.As(fn(s), end)
}
}
// Count applies the "count" aggregation function on each group.
func Count() AggregateFunc {
return func(s *sql.Selector) string {
return sql.Count("*")
}
}
// Max applies the "max" aggregation function on the given field of each group.
func Max(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Max(s.C(field))
}
}
// Mean applies the "mean" aggregation function on the given field of each group.
func Mean(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Avg(s.C(field))
}
}
// Min applies the "min" aggregation function on the given field of each group.
func Min(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Min(s.C(field))
}
}
// Sum applies the "sum" aggregation function on the given field of each group.
func Sum(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Sum(s.C(field))
}
}
// ValidationError returns when validating a field or edge fails.
type ValidationError struct {
Name string // Field or edge name.
err error
}
// Error implements the error interface.
func (e *ValidationError) Error() string {
return e.err.Error()
}
// Unwrap implements the errors.Wrapper interface.
func (e *ValidationError) Unwrap() error {
return e.err
}
// IsValidationError returns a boolean indicating whether the error is a validation error.
func IsValidationError(err error) bool {
if err == nil {
return false
}
var e *ValidationError
return errors.As(err, &e)
}
// NotFoundError returns when trying to fetch a specific entity and it was not found in the database.
type NotFoundError struct {
label string
}
// Error implements the error interface.
func (e *NotFoundError) Error() string {
return "ent: " + e.label + " not found"
}
// IsNotFound returns a boolean indicating whether the error is a not found error.
func IsNotFound(err error) bool {
if err == nil {
return false
}
var e *NotFoundError
return errors.As(err, &e)
}
// MaskNotFound masks not found error.
func MaskNotFound(err error) error {
if IsNotFound(err) {
return nil
}
return err
}
// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database.
type NotSingularError struct {
label string
}
// Error implements the error interface.
func (e *NotSingularError) Error() string {
return "ent: " + e.label + " not singular"
}
// IsNotSingular returns a boolean indicating whether the error is a not singular error.
func IsNotSingular(err error) bool {
if err == nil {
return false
}
var e *NotSingularError
return errors.As(err, &e)
}
// NotLoadedError returns when trying to get a node that was not loaded by the query.
type NotLoadedError struct {
edge string
}
// Error implements the error interface.
func (e *NotLoadedError) Error() string {
return "ent: " + e.edge + " edge was not loaded"
}
// IsNotLoaded returns a boolean indicating whether the error is a not loaded error.
func IsNotLoaded(err error) bool {
if err == nil {
return false
}
var e *NotLoadedError
return errors.As(err, &e)
}
// ConstraintError returns when trying to create/update one or more entities and
// one or more of their constraints failed. For example, violation of edge or
// field uniqueness.
type ConstraintError struct {
msg string
wrap error
}
// Error implements the error interface.
func (e ConstraintError) Error() string {
return "ent: constraint failed: " + e.msg
}
// Unwrap implements the errors.Wrapper interface.
func (e *ConstraintError) Unwrap() error {
return e.wrap
}
// IsConstraintError returns a boolean indicating whether the error is a constraint failure.
func IsConstraintError(err error) bool {
if err == nil {
return false
}
var e *ConstraintError
return errors.As(err, &e)
}
// selector embedded by the different Select/GroupBy builders.
type selector struct {
label string
flds *[]string
fns []AggregateFunc
scan func(context.Context, any) error
}
// ScanX is like Scan, but panics if an error occurs.
func (s *selector) ScanX(ctx context.Context, v any) {
if err := s.scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (s *selector) Strings(ctx context.Context) ([]string, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (s *selector) StringsX(ctx context.Context) []string {
v, err := s.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a selector. It is only allowed when selecting one field.
func (s *selector) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = s.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (s *selector) StringX(ctx context.Context) string {
v, err := s.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (s *selector) Ints(ctx context.Context) ([]int, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (s *selector) IntsX(ctx context.Context) []int {
v, err := s.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a selector. It is only allowed when selecting one field.
func (s *selector) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = s.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (s *selector) IntX(ctx context.Context) int {
v, err := s.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (s *selector) Float64s(ctx context.Context) ([]float64, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (s *selector) Float64sX(ctx context.Context) []float64 {
v, err := s.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (s *selector) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = s.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (s *selector) Float64X(ctx context.Context) float64 {
v, err := s.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (s *selector) Bools(ctx context.Context) ([]bool, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (s *selector) BoolsX(ctx context.Context) []bool {
v, err := s.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (s *selector) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = s.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (s *selector) BoolX(ctx context.Context) bool {
v, err := s.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
// withHooks invokes the builder operation with the given hooks, if any.
func withHooks[V Value, M any, PM interface {
*M
Mutation
}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) {
if len(hooks) == 0 {
return exec(ctx)
}
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutationT, ok := any(m).(PM)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
// Set the mutation to the builder.
*mutation = *mutationT
return exec(ctx)
})
for i := len(hooks) - 1; i >= 0; i-- {
if hooks[i] == nil {
return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = hooks[i](mut)
}
v, err := mut.Mutate(ctx, mutation)
if err != nil {
return value, err
}
nv, ok := v.(V)
if !ok {
return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation)
}
return nv, nil
}
// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist.
func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context {
if ent.QueryFromContext(ctx) == nil {
qc.Op = op
ctx = ent.NewQueryContext(ctx, qc)
}
return ctx
}
func querierAll[V Value, Q interface {
sqlAll(context.Context, ...queryHook) (V, error)
}]() Querier {
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
return query.sqlAll(ctx)
})
}
func querierCount[Q interface {
sqlCount(context.Context) (int, error)
}]() Querier {
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
return query.sqlCount(ctx)
})
}
func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) {
for i := len(inters) - 1; i >= 0; i-- {
qr = inters[i].Intercept(qr)
}
rv, err := qr.Query(ctx, q)
if err != nil {
return v, err
}
vt, ok := rv.(V)
if !ok {
return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v)
}
return vt, nil
}
func scanWithInterceptors[Q1 ent.Query, Q2 interface {
sqlScan(context.Context, Q1, any) error
}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error {
rv := reflect.ValueOf(v)
var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q1)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
if err := selectOrGroup.sqlScan(ctx, query, v); err != nil {
return nil, err
}
if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() {
return rv.Elem().Interface(), nil
}
return v, nil
})
for i := len(inters) - 1; i >= 0; i-- {
qr = inters[i].Intercept(qr)
}
vv, err := qr.Query(ctx, rootQuery)
if err != nil {
return err
}
switch rv2 := reflect.ValueOf(vv); {
case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer:
case rv.Type() == rv2.Type():
rv.Elem().Set(rv2.Elem())
case rv.Elem().Type() == rv2.Type():
rv.Elem().Set(rv2)
}
return nil
}
// queryHook describes an internal hook for the different sqlAll methods.
type queryHook func(context.Context, *sqlgraph.QuerySpec)

View File

@@ -0,0 +1,43 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
//go:build ignore
// +build ignore
package main
import (
"log"
"net/http"
"entgo.io/ent/entc"
"entgo.io/ent/entc/gen"
)
func main() {
// A usage for custom options to configure the code generator to use
// an extension and inject external dependencies in the generated API.
opts := []entc.Option{
entc.Dependency(
entc.DependencyType(&http.Client{}),
),
entc.FeatureNames(
"privacy",
"entql",
"schema/snapshot",
),
}
err := entc.Generate("./schema", &gen.Config{
Header: `
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
`,
}, opts...)
if err != nil {
log.Fatalf("running ent codegen: %v", err)
}
}

View File

@@ -0,0 +1,388 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"entgo.io/ent/entc/integration/privacy/ent/predicate"
"entgo.io/ent/entc/integration/privacy/ent/task"
"entgo.io/ent/entc/integration/privacy/ent/team"
"entgo.io/ent/entc/integration/privacy/ent/user"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entql"
"entgo.io/ent/schema/field"
)
// schemaGraph holds a representation of ent/schema at runtime.
var schemaGraph = func() *sqlgraph.Schema {
graph := &sqlgraph.Schema{Nodes: make([]*sqlgraph.Node, 3)}
graph.Nodes[0] = &sqlgraph.Node{
NodeSpec: sqlgraph.NodeSpec{
Table: task.Table,
Columns: task.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: task.FieldID,
},
},
Type: "Task",
Fields: map[string]*sqlgraph.FieldSpec{
task.FieldTitle: {Type: field.TypeString, Column: task.FieldTitle},
task.FieldDescription: {Type: field.TypeString, Column: task.FieldDescription},
task.FieldStatus: {Type: field.TypeEnum, Column: task.FieldStatus},
task.FieldUUID: {Type: field.TypeUUID, Column: task.FieldUUID},
},
}
graph.Nodes[1] = &sqlgraph.Node{
NodeSpec: sqlgraph.NodeSpec{
Table: team.Table,
Columns: team.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: team.FieldID,
},
},
Type: "Team",
Fields: map[string]*sqlgraph.FieldSpec{
team.FieldName: {Type: field.TypeString, Column: team.FieldName},
},
}
graph.Nodes[2] = &sqlgraph.Node{
NodeSpec: sqlgraph.NodeSpec{
Table: user.Table,
Columns: user.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: user.FieldID,
},
},
Type: "User",
Fields: map[string]*sqlgraph.FieldSpec{
user.FieldName: {Type: field.TypeString, Column: user.FieldName},
user.FieldAge: {Type: field.TypeUint, Column: user.FieldAge},
},
}
graph.MustAddE(
"teams",
&sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: task.TeamsTable,
Columns: task.TeamsPrimaryKey,
Bidi: false,
},
"Task",
"Team",
)
graph.MustAddE(
"owner",
&sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: task.OwnerTable,
Columns: []string{task.OwnerColumn},
Bidi: false,
},
"Task",
"User",
)
graph.MustAddE(
"tasks",
&sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: team.TasksTable,
Columns: team.TasksPrimaryKey,
Bidi: false,
},
"Team",
"Task",
)
graph.MustAddE(
"users",
&sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: team.UsersTable,
Columns: team.UsersPrimaryKey,
Bidi: false,
},
"Team",
"User",
)
graph.MustAddE(
"teams",
&sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.TeamsTable,
Columns: user.TeamsPrimaryKey,
Bidi: false,
},
"User",
"Team",
)
graph.MustAddE(
"tasks",
&sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.TasksTable,
Columns: []string{user.TasksColumn},
Bidi: false,
},
"User",
"Task",
)
return graph
}()
// predicateAdder wraps the addPredicate method.
// All update, update-one and query builders implement this interface.
type predicateAdder interface {
addPredicate(func(s *sql.Selector))
}
// addPredicate implements the predicateAdder interface.
func (_q *TaskQuery) addPredicate(pred func(s *sql.Selector)) {
_q.predicates = append(_q.predicates, pred)
}
// Filter returns a Filter implementation to apply filters on the TaskQuery builder.
func (_q *TaskQuery) Filter() *TaskFilter {
return &TaskFilter{config: _q.config, predicateAdder: _q}
}
// addPredicate implements the predicateAdder interface.
func (m *TaskMutation) addPredicate(pred func(s *sql.Selector)) {
m.Where(pred)
}
// Filter returns an entql.Where implementation to apply filters on the TaskMutation builder.
func (m *TaskMutation) Filter() *TaskFilter {
return &TaskFilter{config: m.config, predicateAdder: m}
}
// TaskFilter provides a generic filtering capability at runtime for TaskQuery.
type TaskFilter struct {
predicateAdder
config
}
// Where applies the entql predicate on the query filter.
func (f *TaskFilter) Where(p entql.P) {
f.addPredicate(func(s *sql.Selector) {
if err := schemaGraph.EvalP(schemaGraph.Nodes[0].Type, p, s); err != nil {
s.AddError(err)
}
})
}
// WhereID applies the entql int predicate on the id field.
func (f *TaskFilter) WhereID(p entql.IntP) {
f.Where(p.Field(task.FieldID))
}
// WhereTitle applies the entql string predicate on the title field.
func (f *TaskFilter) WhereTitle(p entql.StringP) {
f.Where(p.Field(task.FieldTitle))
}
// WhereDescription applies the entql string predicate on the description field.
func (f *TaskFilter) WhereDescription(p entql.StringP) {
f.Where(p.Field(task.FieldDescription))
}
// WhereStatus applies the entql string predicate on the status field.
func (f *TaskFilter) WhereStatus(p entql.StringP) {
f.Where(p.Field(task.FieldStatus))
}
// WhereUUID applies the entql [16]byte predicate on the uuid field.
func (f *TaskFilter) WhereUUID(p entql.ValueP) {
f.Where(p.Field(task.FieldUUID))
}
// WhereHasTeams applies a predicate to check if query has an edge teams.
func (f *TaskFilter) WhereHasTeams() {
f.Where(entql.HasEdge("teams"))
}
// WhereHasTeamsWith applies a predicate to check if query has an edge teams with a given conditions (other predicates).
func (f *TaskFilter) WhereHasTeamsWith(preds ...predicate.Team) {
f.Where(entql.HasEdgeWith("teams", sqlgraph.WrapFunc(func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})))
}
// WhereHasOwner applies a predicate to check if query has an edge owner.
func (f *TaskFilter) WhereHasOwner() {
f.Where(entql.HasEdge("owner"))
}
// WhereHasOwnerWith applies a predicate to check if query has an edge owner with a given conditions (other predicates).
func (f *TaskFilter) WhereHasOwnerWith(preds ...predicate.User) {
f.Where(entql.HasEdgeWith("owner", sqlgraph.WrapFunc(func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})))
}
// addPredicate implements the predicateAdder interface.
func (_q *TeamQuery) addPredicate(pred func(s *sql.Selector)) {
_q.predicates = append(_q.predicates, pred)
}
// Filter returns a Filter implementation to apply filters on the TeamQuery builder.
func (_q *TeamQuery) Filter() *TeamFilter {
return &TeamFilter{config: _q.config, predicateAdder: _q}
}
// addPredicate implements the predicateAdder interface.
func (m *TeamMutation) addPredicate(pred func(s *sql.Selector)) {
m.Where(pred)
}
// Filter returns an entql.Where implementation to apply filters on the TeamMutation builder.
func (m *TeamMutation) Filter() *TeamFilter {
return &TeamFilter{config: m.config, predicateAdder: m}
}
// TeamFilter provides a generic filtering capability at runtime for TeamQuery.
type TeamFilter struct {
predicateAdder
config
}
// Where applies the entql predicate on the query filter.
func (f *TeamFilter) Where(p entql.P) {
f.addPredicate(func(s *sql.Selector) {
if err := schemaGraph.EvalP(schemaGraph.Nodes[1].Type, p, s); err != nil {
s.AddError(err)
}
})
}
// WhereID applies the entql int predicate on the id field.
func (f *TeamFilter) WhereID(p entql.IntP) {
f.Where(p.Field(team.FieldID))
}
// WhereName applies the entql string predicate on the name field.
func (f *TeamFilter) WhereName(p entql.StringP) {
f.Where(p.Field(team.FieldName))
}
// WhereHasTasks applies a predicate to check if query has an edge tasks.
func (f *TeamFilter) WhereHasTasks() {
f.Where(entql.HasEdge("tasks"))
}
// WhereHasTasksWith applies a predicate to check if query has an edge tasks with a given conditions (other predicates).
func (f *TeamFilter) WhereHasTasksWith(preds ...predicate.Task) {
f.Where(entql.HasEdgeWith("tasks", sqlgraph.WrapFunc(func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})))
}
// WhereHasUsers applies a predicate to check if query has an edge users.
func (f *TeamFilter) WhereHasUsers() {
f.Where(entql.HasEdge("users"))
}
// WhereHasUsersWith applies a predicate to check if query has an edge users with a given conditions (other predicates).
func (f *TeamFilter) WhereHasUsersWith(preds ...predicate.User) {
f.Where(entql.HasEdgeWith("users", sqlgraph.WrapFunc(func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})))
}
// addPredicate implements the predicateAdder interface.
func (_q *UserQuery) addPredicate(pred func(s *sql.Selector)) {
_q.predicates = append(_q.predicates, pred)
}
// Filter returns a Filter implementation to apply filters on the UserQuery builder.
func (_q *UserQuery) Filter() *UserFilter {
return &UserFilter{config: _q.config, predicateAdder: _q}
}
// addPredicate implements the predicateAdder interface.
func (m *UserMutation) addPredicate(pred func(s *sql.Selector)) {
m.Where(pred)
}
// Filter returns an entql.Where implementation to apply filters on the UserMutation builder.
func (m *UserMutation) Filter() *UserFilter {
return &UserFilter{config: m.config, predicateAdder: m}
}
// UserFilter provides a generic filtering capability at runtime for UserQuery.
type UserFilter struct {
predicateAdder
config
}
// Where applies the entql predicate on the query filter.
func (f *UserFilter) Where(p entql.P) {
f.addPredicate(func(s *sql.Selector) {
if err := schemaGraph.EvalP(schemaGraph.Nodes[2].Type, p, s); err != nil {
s.AddError(err)
}
})
}
// WhereID applies the entql int predicate on the id field.
func (f *UserFilter) WhereID(p entql.IntP) {
f.Where(p.Field(user.FieldID))
}
// WhereName applies the entql string predicate on the name field.
func (f *UserFilter) WhereName(p entql.StringP) {
f.Where(p.Field(user.FieldName))
}
// WhereAge applies the entql uint predicate on the age field.
func (f *UserFilter) WhereAge(p entql.UintP) {
f.Where(p.Field(user.FieldAge))
}
// WhereHasTeams applies a predicate to check if query has an edge teams.
func (f *UserFilter) WhereHasTeams() {
f.Where(entql.HasEdge("teams"))
}
// WhereHasTeamsWith applies a predicate to check if query has an edge teams with a given conditions (other predicates).
func (f *UserFilter) WhereHasTeamsWith(preds ...predicate.Team) {
f.Where(entql.HasEdgeWith("teams", sqlgraph.WrapFunc(func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})))
}
// WhereHasTasks applies a predicate to check if query has an edge tasks.
func (f *UserFilter) WhereHasTasks() {
f.Where(entql.HasEdge("tasks"))
}
// WhereHasTasksWith applies a predicate to check if query has an edge tasks with a given conditions (other predicates).
func (f *UserFilter) WhereHasTasksWith(preds ...predicate.Task) {
f.Where(entql.HasEdgeWith("tasks", sqlgraph.WrapFunc(func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})))
}

View File

@@ -0,0 +1,88 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package enttest
import (
"context"
"entgo.io/ent/entc/integration/privacy/ent"
// required by schema hooks.
_ "entgo.io/ent/entc/integration/privacy/ent/runtime"
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/entc/integration/privacy/ent/migrate"
)
type (
// TestingT is the interface that is shared between
// testing.T and testing.B and used by enttest.
TestingT interface {
FailNow()
Error(...any)
}
// Option configures client creation.
Option func(*options)
options struct {
opts []ent.Option
migrateOpts []schema.MigrateOption
}
)
// WithOptions forwards options to client creation.
func WithOptions(opts ...ent.Option) Option {
return func(o *options) {
o.opts = append(o.opts, opts...)
}
}
// WithMigrateOptions forwards options to auto migration.
func WithMigrateOptions(opts ...schema.MigrateOption) Option {
return func(o *options) {
o.migrateOpts = append(o.migrateOpts, opts...)
}
}
func newOptions(opts []Option) *options {
o := &options{}
for _, opt := range opts {
opt(o)
}
return o
}
// Open calls ent.Open and auto-run migration.
func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Client {
o := newOptions(opts)
c, err := ent.Open(driverName, dataSourceName, o.opts...)
if err != nil {
t.Error(err)
t.FailNow()
}
migrateSchema(t, c, o)
return c
}
// NewClient calls ent.NewClient and auto-run migration.
func NewClient(t TestingT, opts ...Option) *ent.Client {
o := newOptions(opts)
c := ent.NewClient(o.opts...)
migrateSchema(t, c, o)
return c
}
func migrateSchema(t TestingT, c *ent.Client, o *options) {
tables, err := schema.CopyTables(migrate.Tables)
if err != nil {
t.Error(err)
t.FailNow()
}
if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil {
t.Error(err)
t.FailNow()
}
}

View File

@@ -0,0 +1,7 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package ent
//go:generate go run -mod=mod entc.go

View File

@@ -0,0 +1,227 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package hook
import (
"context"
"fmt"
"entgo.io/ent/entc/integration/privacy/ent"
)
// The TaskFunc type is an adapter to allow the use of ordinary
// function as Task mutator.
type TaskFunc func(context.Context, *ent.TaskMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f TaskFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.TaskMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.TaskMutation", m)
}
// The TeamFunc type is an adapter to allow the use of ordinary
// function as Team mutator.
type TeamFunc func(context.Context, *ent.TeamMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f TeamFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.TeamMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.TeamMutation", 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)
// Mutate calls f(ctx, m).
func (f UserFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.UserMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserMutation", m)
}
// Condition is a hook condition function.
type Condition func(context.Context, ent.Mutation) bool
// And groups conditions with the AND operator.
func And(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
if !first(ctx, m) || !second(ctx, m) {
return false
}
for _, cond := range rest {
if !cond(ctx, m) {
return false
}
}
return true
}
}
// Or groups conditions with the OR operator.
func Or(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
if first(ctx, m) || second(ctx, m) {
return true
}
for _, cond := range rest {
if cond(ctx, m) {
return true
}
}
return false
}
}
// Not negates a given condition.
func Not(cond Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
return !cond(ctx, m)
}
}
// HasOp is a condition testing mutation operation.
func HasOp(op ent.Op) Condition {
return func(_ context.Context, m ent.Mutation) bool {
return m.Op().Is(op)
}
}
// HasAddedFields is a condition validating `.AddedField` on fields.
func HasAddedFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if _, exists := m.AddedField(field); !exists {
return false
}
for _, field := range fields {
if _, exists := m.AddedField(field); !exists {
return false
}
}
return true
}
}
// HasClearedFields is a condition validating `.FieldCleared` on fields.
func HasClearedFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if exists := m.FieldCleared(field); !exists {
return false
}
for _, field := range fields {
if exists := m.FieldCleared(field); !exists {
return false
}
}
return true
}
}
// HasFields is a condition validating `.Field` on fields.
func HasFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if _, exists := m.Field(field); !exists {
return false
}
for _, field := range fields {
if _, exists := m.Field(field); !exists {
return false
}
}
return true
}
}
// If executes the given hook under condition.
//
// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...)))
func If(hk ent.Hook, cond Condition) ent.Hook {
return func(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if cond(ctx, m) {
return hk(next).Mutate(ctx, m)
}
return next.Mutate(ctx, m)
})
}
}
// On executes the given hook only for the given operation.
//
// hook.On(Log, ent.Delete|ent.Create)
func On(hk ent.Hook, op ent.Op) ent.Hook {
return If(hk, HasOp(op))
}
// Unless skips the given hook only for the given operation.
//
// hook.Unless(Log, ent.Update|ent.UpdateOne)
func Unless(hk ent.Hook, op ent.Op) ent.Hook {
return If(hk, Not(HasOp(op)))
}
// FixedError is a hook returning a fixed error.
func FixedError(err error) ent.Hook {
return func(ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(context.Context, ent.Mutation) (ent.Value, error) {
return nil, err
})
}
}
// Reject returns a hook that rejects all operations that match op.
//
// func (T) Hooks() []ent.Hook {
// return []ent.Hook{
// Reject(ent.Delete|ent.Update),
// }
// }
func Reject(op ent.Op) ent.Hook {
hk := FixedError(fmt.Errorf("%s operation is not allowed", op))
return On(hk, op)
}
// Chain acts as a list of hooks and is effectively immutable.
// Once created, it will always hold the same set of hooks in the same order.
type Chain struct {
hooks []ent.Hook
}
// NewChain creates a new chain of hooks.
func NewChain(hooks ...ent.Hook) Chain {
return Chain{append([]ent.Hook(nil), hooks...)}
}
// Hook chains the list of hooks and returns the final hook.
func (c Chain) Hook() ent.Hook {
return func(mutator ent.Mutator) ent.Mutator {
for i := len(c.hooks) - 1; i >= 0; i-- {
mutator = c.hooks[i](mutator)
}
return mutator
}
}
// Append extends a chain, adding the specified hook
// as the last ones in the mutation flow.
func (c Chain) Append(hooks ...ent.Hook) Chain {
newHooks := make([]ent.Hook, 0, len(c.hooks)+len(hooks))
newHooks = append(newHooks, c.hooks...)
newHooks = append(newHooks, hooks...)
return Chain{newHooks}
}
// Extend extends a chain, adding the specified chain
// as the last ones in the mutation flow.
func (c Chain) Extend(chain Chain) Chain {
return c.Append(chain.hooks...)
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,68 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package migrate
import (
"context"
"fmt"
"io"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql/schema"
)
var (
// WithGlobalUniqueID sets the universal ids options to the migration.
// If this option is enabled, ent migration will allocate a 1<<32 range
// for the ids of each entity (table).
// Note that this option cannot be applied on tables that already exist.
WithGlobalUniqueID = schema.WithGlobalUniqueID
// WithDropColumn sets the drop column option to the migration.
// If this option is enabled, ent migration will drop old columns
// that were used for both fields and edges. This defaults to false.
WithDropColumn = schema.WithDropColumn
// WithDropIndex sets the drop index option to the migration.
// If this option is enabled, ent migration will drop old indexes
// that were defined in the schema. This defaults to false.
// Note that unique constraints are defined using `UNIQUE INDEX`,
// and therefore, it's recommended to enable this option to get more
// flexibility in the schema changes.
WithDropIndex = schema.WithDropIndex
// WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true.
WithForeignKeys = schema.WithForeignKeys
)
// Schema is the API for creating, migrating and dropping a schema.
type Schema struct {
drv dialect.Driver
}
// NewSchema creates a new schema client.
func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} }
// Create creates all schema resources.
func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error {
return Create(ctx, s, Tables, opts...)
}
// Create creates all table resources using the given schema driver.
func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error {
migrate, err := schema.NewMigrate(s.drv, opts...)
if err != nil {
return fmt.Errorf("ent/migrate: %w", err)
}
return migrate.Create(ctx, tables...)
}
// WriteTo writes the schema changes to w instead of running them against the database.
//
// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil {
// log.Fatal(err)
// }
func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error {
return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...)
}

View File

@@ -0,0 +1,132 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package migrate
import (
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/schema/field"
)
var (
// TasksColumns holds the columns for the "tasks" table.
TasksColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "title", Type: field.TypeString},
{Name: "description", Type: field.TypeString, Nullable: true},
{Name: "status", Type: field.TypeEnum, Enums: []string{"planned", "in_progress", "closed"}, Default: "planned"},
{Name: "uuid", Type: field.TypeUUID, Nullable: true},
{Name: "user_tasks", Type: field.TypeInt, Nullable: true},
}
// TasksTable holds the schema information for the "tasks" table.
TasksTable = &schema.Table{
Name: "tasks",
Columns: TasksColumns,
PrimaryKey: []*schema.Column{TasksColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "tasks_users_tasks",
Columns: []*schema.Column{TasksColumns[5]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.SetNull,
},
},
}
// TeamsColumns holds the columns for the "teams" table.
TeamsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "name", Type: field.TypeString},
}
// TeamsTable holds the schema information for the "teams" table.
TeamsTable = &schema.Table{
Name: "teams",
Columns: TeamsColumns,
PrimaryKey: []*schema.Column{TeamsColumns[0]},
}
// UsersColumns holds the columns for the "users" table.
UsersColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "name", Type: field.TypeString, Unique: true},
{Name: "age", Type: field.TypeUint, Nullable: true},
}
// UsersTable holds the schema information for the "users" table.
UsersTable = &schema.Table{
Name: "users",
Columns: UsersColumns,
PrimaryKey: []*schema.Column{UsersColumns[0]},
}
// TaskTeamsColumns holds the columns for the "task_teams" table.
TaskTeamsColumns = []*schema.Column{
{Name: "task_id", Type: field.TypeInt},
{Name: "team_id", Type: field.TypeInt},
}
// TaskTeamsTable holds the schema information for the "task_teams" table.
TaskTeamsTable = &schema.Table{
Name: "task_teams",
Columns: TaskTeamsColumns,
PrimaryKey: []*schema.Column{TaskTeamsColumns[0], TaskTeamsColumns[1]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "task_teams_task_id",
Columns: []*schema.Column{TaskTeamsColumns[0]},
RefColumns: []*schema.Column{TasksColumns[0]},
OnDelete: schema.Cascade,
},
{
Symbol: "task_teams_team_id",
Columns: []*schema.Column{TaskTeamsColumns[1]},
RefColumns: []*schema.Column{TeamsColumns[0]},
OnDelete: schema.Cascade,
},
},
}
// UserTeamsColumns holds the columns for the "user_teams" table.
UserTeamsColumns = []*schema.Column{
{Name: "user_id", Type: field.TypeInt},
{Name: "team_id", Type: field.TypeInt},
}
// UserTeamsTable holds the schema information for the "user_teams" table.
UserTeamsTable = &schema.Table{
Name: "user_teams",
Columns: UserTeamsColumns,
PrimaryKey: []*schema.Column{UserTeamsColumns[0], UserTeamsColumns[1]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "user_teams_user_id",
Columns: []*schema.Column{UserTeamsColumns[0]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.Cascade,
},
{
Symbol: "user_teams_team_id",
Columns: []*schema.Column{UserTeamsColumns[1]},
RefColumns: []*schema.Column{TeamsColumns[0]},
OnDelete: schema.Cascade,
},
},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
TasksTable,
TeamsTable,
UsersTable,
TaskTeamsTable,
UserTeamsTable,
}
)
func init() {
TasksTable.ForeignKeys[0].RefTable = UsersTable
UsersTable.Annotation = &entsql.Annotation{}
UsersTable.Annotation.Checks = map[string]string{
"backticks": "`name` IS NOT NULL",
}
TaskTeamsTable.ForeignKeys[0].RefTable = TasksTable
TaskTeamsTable.ForeignKeys[1].RefTable = TeamsTable
UserTeamsTable.ForeignKeys[0].RefTable = UsersTable
UserTeamsTable.ForeignKeys[1].RefTable = TeamsTable
}

View File

@@ -0,0 +1,509 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"sync"
"entgo.io/ent"
"entgo.io/ent/entc/integration/privacy/ent/task"
"entgo.io/ent/entc/integration/privacy/ent/team"
"entgo.io/ent/entc/integration/privacy/ent/user"
"github.com/google/uuid"
)
const (
// Operation types.
OpCreate = ent.OpCreate
OpDelete = ent.OpDelete
OpDeleteOne = ent.OpDeleteOne
OpUpdate = ent.OpUpdate
OpUpdateOne = ent.OpUpdateOne
// Node types.
TypeTask = "Task"
TypeTeam = "Team"
TypeUser = "User"
)
// TaskMutation represents an operation that mutates the Task nodes in the graph.
type TaskMutation struct {
task.Mutation
config
id *int
done bool
oldValue func(context.Context) (*Task, error)
}
var _ ent.Mutation = (*TaskMutation)(nil)
// taskOption allows management of the mutation configuration using functional options.
type taskOption func(*TaskMutation)
// newTaskMutation creates new mutation for the Task entity.
func newTaskMutation(c config, op Op, opts ...taskOption) *TaskMutation {
m := &TaskMutation{
Mutation: *task.NewMutation(op),
config: c,
}
for _, opt := range opts {
opt(m)
}
return m
}
// ID returns the ID value in the mutation. Note that the ID is only available
// if it was provided to the builder or after it was returned from the database.
func (m *TaskMutation) ID() (id int, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// withTaskID sets the ID field of the mutation.
func withTaskID(id int) taskOption {
return func(m *TaskMutation) {
var (
err error
once sync.Once
value *Task
)
m.oldValue = func(ctx context.Context) (*Task, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().Task.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withTask sets the old Task of the mutation.
func withTask(node *Task) taskOption {
return func(m *TaskMutation) {
m.oldValue = func(context.Context) (*Task, error) {
return node, nil
}
m.id = &node.ID
}
}
// Client returns a new `ent.Client` from the mutation. If the mutation was
// executed in a transaction (ent.Tx), a transactional client is returned.
func (m TaskMutation) Client() *Client {
client := &Client{config: m.config}
client.init()
return client
}
// Tx returns an `ent.Tx` for mutations that were executed in transactions;
// it returns an error otherwise.
func (m TaskMutation) Tx() (*Tx, error) {
if _, ok := m.driver.(*txDriver); !ok {
return nil, errors.New("ent: mutation is not running in a transaction")
}
tx := &Tx{config: m.config}
tx.init()
return tx, nil
}
// IDs queries the database and returns the entity ids that match the mutation's predicate.
// That means, if the mutation is applied within a transaction with an isolation level such
// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated
// or updated by the mutation.
func (m *TaskMutation) IDs(ctx context.Context) ([]int, error) {
switch {
case m.Op().Is(OpUpdateOne | OpDeleteOne):
id, exists := m.ID()
if exists {
return []int{id}, nil
}
fallthrough
case m.Op().Is(OpUpdate | OpDelete):
return m.Client().Task.Query().Where(m.Predicates()...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.Op())
}
}
// OldTitle returns the old "title" field's value of the Task entity.
// If the Task object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *TaskMutation) OldTitle(ctx context.Context) (v string, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldTitle is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldTitle requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldTitle: %w", err)
}
return oldValue.Title, nil
}
// OldDescription returns the old "description" field's value of the Task entity.
// If the Task object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *TaskMutation) OldDescription(ctx context.Context) (v string, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldDescription is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldDescription requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldDescription: %w", err)
}
return oldValue.Description, nil
}
// OldStatus returns the old "status" field's value of the Task entity.
// If the Task object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *TaskMutation) OldStatus(ctx context.Context) (v task.Status, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldStatus is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldStatus requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldStatus: %w", err)
}
return oldValue.Status, nil
}
// OldUUID returns the old "uuid" field's value of the Task entity.
// If the Task object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *TaskMutation) OldUUID(ctx context.Context) (v uuid.UUID, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldUUID is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldUUID requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldUUID: %w", err)
}
return oldValue.UUID, nil
}
// OldField returns the old value of the field from the database. An error is
// returned if the mutation operation is not UpdateOne, or the query to the
// database failed.
func (m *TaskMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case task.FieldTitle:
return m.OldTitle(ctx)
case task.FieldDescription:
return m.OldDescription(ctx)
case task.FieldStatus:
return m.OldStatus(ctx)
case task.FieldUUID:
return m.OldUUID(ctx)
}
return nil, fmt.Errorf("unknown Task field %s", name)
}
// TeamMutation represents an operation that mutates the Team nodes in the graph.
type TeamMutation struct {
team.Mutation
config
id *int
done bool
oldValue func(context.Context) (*Team, error)
}
var _ ent.Mutation = (*TeamMutation)(nil)
// teamOption allows management of the mutation configuration using functional options.
type teamOption func(*TeamMutation)
// newTeamMutation creates new mutation for the Team entity.
func newTeamMutation(c config, op Op, opts ...teamOption) *TeamMutation {
m := &TeamMutation{
Mutation: *team.NewMutation(op),
config: c,
}
for _, opt := range opts {
opt(m)
}
return m
}
// ID returns the ID value in the mutation. Note that the ID is only available
// if it was provided to the builder or after it was returned from the database.
func (m *TeamMutation) ID() (id int, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// withTeamID sets the ID field of the mutation.
func withTeamID(id int) teamOption {
return func(m *TeamMutation) {
var (
err error
once sync.Once
value *Team
)
m.oldValue = func(ctx context.Context) (*Team, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().Team.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withTeam sets the old Team of the mutation.
func withTeam(node *Team) teamOption {
return func(m *TeamMutation) {
m.oldValue = func(context.Context) (*Team, error) {
return node, nil
}
m.id = &node.ID
}
}
// Client returns a new `ent.Client` from the mutation. If the mutation was
// executed in a transaction (ent.Tx), a transactional client is returned.
func (m TeamMutation) Client() *Client {
client := &Client{config: m.config}
client.init()
return client
}
// Tx returns an `ent.Tx` for mutations that were executed in transactions;
// it returns an error otherwise.
func (m TeamMutation) Tx() (*Tx, error) {
if _, ok := m.driver.(*txDriver); !ok {
return nil, errors.New("ent: mutation is not running in a transaction")
}
tx := &Tx{config: m.config}
tx.init()
return tx, nil
}
// IDs queries the database and returns the entity ids that match the mutation's predicate.
// That means, if the mutation is applied within a transaction with an isolation level such
// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated
// or updated by the mutation.
func (m *TeamMutation) IDs(ctx context.Context) ([]int, error) {
switch {
case m.Op().Is(OpUpdateOne | OpDeleteOne):
id, exists := m.ID()
if exists {
return []int{id}, nil
}
fallthrough
case m.Op().Is(OpUpdate | OpDelete):
return m.Client().Team.Query().Where(m.Predicates()...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.Op())
}
}
// OldName returns the old "name" field's value of the Team entity.
// If the Team object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *TeamMutation) OldName(ctx context.Context) (v string, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldName is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldName requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldName: %w", err)
}
return oldValue.Name, nil
}
// OldField returns the old value of the field from the database. An error is
// returned if the mutation operation is not UpdateOne, or the query to the
// database failed.
func (m *TeamMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case team.FieldName:
return m.OldName(ctx)
}
return nil, fmt.Errorf("unknown Team field %s", name)
}
// UserMutation represents an operation that mutates the User nodes in the graph.
type UserMutation struct {
user.Mutation
config
id *int
done bool
oldValue func(context.Context) (*User, error)
}
var _ ent.Mutation = (*UserMutation)(nil)
// userOption allows management of the mutation configuration using functional options.
type userOption func(*UserMutation)
// newUserMutation creates new mutation for the User entity.
func newUserMutation(c config, op Op, opts ...userOption) *UserMutation {
m := &UserMutation{
Mutation: *user.NewMutation(op),
config: c,
}
for _, opt := range opts {
opt(m)
}
return m
}
// ID returns the ID value in the mutation. Note that the ID is only available
// if it was provided to the builder or after it was returned from the database.
func (m *UserMutation) ID() (id int, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// withUserID sets the ID field of the mutation.
func withUserID(id int) userOption {
return func(m *UserMutation) {
var (
err error
once sync.Once
value *User
)
m.oldValue = func(ctx context.Context) (*User, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().User.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withUser sets the old User of the mutation.
func withUser(node *User) userOption {
return func(m *UserMutation) {
m.oldValue = func(context.Context) (*User, error) {
return node, nil
}
m.id = &node.ID
}
}
// Client returns a new `ent.Client` from the mutation. If the mutation was
// executed in a transaction (ent.Tx), a transactional client is returned.
func (m UserMutation) Client() *Client {
client := &Client{config: m.config}
client.init()
return client
}
// Tx returns an `ent.Tx` for mutations that were executed in transactions;
// it returns an error otherwise.
func (m UserMutation) Tx() (*Tx, error) {
if _, ok := m.driver.(*txDriver); !ok {
return nil, errors.New("ent: mutation is not running in a transaction")
}
tx := &Tx{config: m.config}
tx.init()
return tx, nil
}
// IDs queries the database and returns the entity ids that match the mutation's predicate.
// That means, if the mutation is applied within a transaction with an isolation level such
// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated
// or updated by the mutation.
func (m *UserMutation) IDs(ctx context.Context) ([]int, error) {
switch {
case m.Op().Is(OpUpdateOne | OpDeleteOne):
id, exists := m.ID()
if exists {
return []int{id}, nil
}
fallthrough
case m.Op().Is(OpUpdate | OpDelete):
return m.Client().User.Query().Where(m.Predicates()...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.Op())
}
}
// OldName returns the old "name" field's value of the User entity.
// If the User object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UserMutation) OldName(ctx context.Context) (v string, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldName is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldName requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldName: %w", err)
}
return oldValue.Name, nil
}
// OldAge returns the old "age" field's value of the User entity.
// If the User object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UserMutation) OldAge(ctx context.Context) (v uint, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldAge is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldAge requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldAge: %w", err)
}
return oldValue.Age, nil
}
// OldField returns the old value of the field from the database. An error is
// returned if the mutation operation is not UpdateOne, or the query to the
// database failed.
func (m *UserMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case user.FieldName:
return m.OldName(ctx)
case user.FieldAge:
return m.OldAge(ctx)
}
return nil, fmt.Errorf("unknown User field %s", name)
}

View File

@@ -0,0 +1,20 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package predicate
import (
"entgo.io/ent/dialect/sql"
)
// Task is the predicate function for task builders.
type Task func(*sql.Selector)
// Team is the predicate function for team builders.
type Team func(*sql.Selector)
// User is the predicate function for user builders.
type User func(*sql.Selector)

View File

@@ -0,0 +1,247 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package privacy
import (
"context"
"entgo.io/ent/entc/integration/privacy/ent"
"entgo.io/ent/entql"
"entgo.io/ent/privacy"
)
var (
// Allow may be returned by rules to indicate that the policy
// evaluation should terminate with allow decision.
Allow = privacy.Allow
// Deny may be returned by rules to indicate that the policy
// evaluation should terminate with deny decision.
Deny = privacy.Deny
// Skip may be returned by rules to indicate that the policy
// evaluation should continue to the next rule.
Skip = privacy.Skip
)
// Allowf returns a formatted wrapped Allow decision.
func Allowf(format string, a ...any) error {
return privacy.Allowf(format, a...)
}
// Denyf returns a formatted wrapped Deny decision.
func Denyf(format string, a ...any) error {
return privacy.Denyf(format, a...)
}
// Skipf returns a formatted wrapped Skip decision.
func Skipf(format string, a ...any) error {
return privacy.Skipf(format, a...)
}
// DecisionContext creates a new context from the given parent context with
// a policy decision attach to it.
func DecisionContext(parent context.Context, decision error) context.Context {
return privacy.DecisionContext(parent, decision)
}
// DecisionFromContext retrieves the policy decision from the context.
func DecisionFromContext(ctx context.Context) (error, bool) {
return privacy.DecisionFromContext(ctx)
}
type (
// Policy groups query and mutation policies.
Policy = privacy.Policy
// QueryRule defines the interface deciding whether a
// query is allowed and optionally modify it.
QueryRule = privacy.QueryRule
// QueryPolicy combines multiple query rules into a single policy.
QueryPolicy = privacy.QueryPolicy
// MutationRule defines the interface which decides whether a
// mutation is allowed and optionally modifies it.
MutationRule = privacy.MutationRule
// MutationPolicy combines multiple mutation rules into a single policy.
MutationPolicy = privacy.MutationPolicy
// MutationRuleFunc type is an adapter which allows the use of
// ordinary functions as mutation rules.
MutationRuleFunc = privacy.MutationRuleFunc
// QueryMutationRule is an interface which groups query and mutation rules.
QueryMutationRule = privacy.QueryMutationRule
)
// QueryRuleFunc type is an adapter to allow the use of
// ordinary functions as query rules.
type QueryRuleFunc func(context.Context, ent.Query) error
// Eval returns f(ctx, q).
func (f QueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error {
return f(ctx, q)
}
// AlwaysAllowRule returns a rule that returns an allow decision.
func AlwaysAllowRule() QueryMutationRule {
return privacy.AlwaysAllowRule()
}
// AlwaysDenyRule returns a rule that returns a deny decision.
func AlwaysDenyRule() QueryMutationRule {
return privacy.AlwaysDenyRule()
}
// ContextQueryMutationRule creates a query/mutation rule from a context eval func.
func ContextQueryMutationRule(eval func(context.Context) error) QueryMutationRule {
return privacy.ContextQueryMutationRule(eval)
}
// OnMutationOperation evaluates the given rule only on a given mutation operation.
func OnMutationOperation(rule MutationRule, op ent.Op) MutationRule {
return privacy.OnMutationOperation(rule, op)
}
// DenyMutationOperationRule returns a rule denying specified mutation operation.
func DenyMutationOperationRule(op ent.Op) MutationRule {
rule := MutationRuleFunc(func(_ context.Context, m ent.Mutation) error {
return Denyf("ent/privacy: operation %s is not allowed", m.Op())
})
return OnMutationOperation(rule, op)
}
// The TaskQueryRuleFunc type is an adapter to allow the use of ordinary
// functions as a query rule.
type TaskQueryRuleFunc func(context.Context, *ent.TaskQuery) error
// EvalQuery return f(ctx, q).
func (f TaskQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.TaskQuery); ok {
return f(ctx, q)
}
return Denyf("ent/privacy: unexpected query type %T, expect *ent.TaskQuery", q)
}
// The TaskMutationRuleFunc type is an adapter to allow the use of ordinary
// functions as a mutation rule.
type TaskMutationRuleFunc func(context.Context, *ent.TaskMutation) error
// EvalMutation calls f(ctx, m).
func (f TaskMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error {
if m, ok := m.(*ent.TaskMutation); ok {
return f(ctx, m)
}
return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.TaskMutation", m)
}
// The TeamQueryRuleFunc type is an adapter to allow the use of ordinary
// functions as a query rule.
type TeamQueryRuleFunc func(context.Context, *ent.TeamQuery) error
// EvalQuery return f(ctx, q).
func (f TeamQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.TeamQuery); ok {
return f(ctx, q)
}
return Denyf("ent/privacy: unexpected query type %T, expect *ent.TeamQuery", q)
}
// The TeamMutationRuleFunc type is an adapter to allow the use of ordinary
// functions as a mutation rule.
type TeamMutationRuleFunc func(context.Context, *ent.TeamMutation) error
// EvalMutation calls f(ctx, m).
func (f TeamMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error {
if m, ok := m.(*ent.TeamMutation); ok {
return f(ctx, m)
}
return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.TeamMutation", m)
}
// The UserQueryRuleFunc type is an adapter to allow the use of ordinary
// functions as a query rule.
type UserQueryRuleFunc func(context.Context, *ent.UserQuery) error
// EvalQuery return f(ctx, q).
func (f UserQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.UserQuery); ok {
return f(ctx, q)
}
return Denyf("ent/privacy: unexpected query type %T, expect *ent.UserQuery", q)
}
// The UserMutationRuleFunc type is an adapter to allow the use of ordinary
// functions as a mutation rule.
type UserMutationRuleFunc func(context.Context, *ent.UserMutation) error
// EvalMutation calls f(ctx, m).
func (f UserMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error {
if m, ok := m.(*ent.UserMutation); ok {
return f(ctx, m)
}
return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.UserMutation", m)
}
type (
// Filter is the interface that wraps the Where function
// for filtering nodes in queries and mutations.
Filter interface {
// Where applies a filter on the executed query/mutation.
Where(entql.P)
}
// The FilterFunc type is an adapter that allows the use of ordinary
// functions as filters for query and mutation types.
FilterFunc func(context.Context, Filter) error
)
// EvalQuery calls f(ctx, q) if the query implements the Filter interface, otherwise it is denied.
func (f FilterFunc) EvalQuery(ctx context.Context, q ent.Query) error {
fr, err := queryFilter(q)
if err != nil {
return err
}
return f(ctx, fr)
}
// EvalMutation calls f(ctx, q) if the mutation implements the Filter interface, otherwise it is denied.
func (f FilterFunc) EvalMutation(ctx context.Context, m ent.Mutation) error {
fr, err := mutationFilter(m)
if err != nil {
return err
}
return f(ctx, fr)
}
var _ QueryMutationRule = FilterFunc(nil)
func queryFilter(q ent.Query) (Filter, error) {
switch q := q.(type) {
case *ent.TaskQuery:
return q.Filter(), nil
case *ent.TeamQuery:
return q.Filter(), nil
case *ent.UserQuery:
return q.Filter(), nil
default:
return nil, Denyf("ent/privacy: unexpected query type %T for query filter", q)
}
}
func mutationFilter(m ent.Mutation) (Filter, error) {
switch m := m.(type) {
case *ent.TaskMutation:
return m.Filter(), nil
case *ent.TeamMutation:
return m.Filter(), nil
case *ent.UserMutation:
return m.Filter(), nil
default:
return nil, Denyf("ent/privacy: unexpected mutation type %T for mutation filter", m)
}
}

View File

@@ -0,0 +1,9 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
// The schema-stitching logic is generated in entgo.io/ent/entc/integration/privacy/ent/runtime/runtime.go

View File

@@ -0,0 +1,80 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package runtime
import (
"context"
"entgo.io/ent/entc/integration/privacy/ent/schema"
"entgo.io/ent/entc/integration/privacy/ent/task"
"entgo.io/ent/entc/integration/privacy/ent/team"
"entgo.io/ent/entc/integration/privacy/ent/user"
"entgo.io/ent"
"entgo.io/ent/privacy"
)
// The init function reads all schema descriptors with runtime code
// (default values, validators, hooks and policies) and stitches it
// to their package variables.
func init() {
taskMixin := schema.Task{}.Mixin()
task.Policy = privacy.NewPolicies(taskMixin[0], taskMixin[1], schema.Task{})
task.Hooks[0] = func(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if err := task.Policy.EvalMutation(ctx, m); err != nil {
return nil, err
}
return next.Mutate(ctx, m)
})
}
taskHooks := schema.Task{}.Hooks()
task.Hooks[1] = taskHooks[0]
taskFields := schema.Task{}.Fields()
_ = taskFields
// taskDescTitle is the schema descriptor for title field.
taskDescTitle := taskFields[0].Descriptor()
// task.TitleValidator is a validator for the "title" field. It is called by the builders before save.
task.TitleValidator = taskDescTitle.Validators[0].(func(string) error)
teamMixin := schema.Team{}.Mixin()
team.Policy = privacy.NewPolicies(teamMixin[0], schema.Team{})
team.Hooks[0] = func(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if err := team.Policy.EvalMutation(ctx, m); err != nil {
return nil, err
}
return next.Mutate(ctx, m)
})
}
teamFields := schema.Team{}.Fields()
_ = teamFields
// teamDescName is the schema descriptor for name field.
teamDescName := teamFields[0].Descriptor()
// team.NameValidator is a validator for the "name" field. It is called by the builders before save.
team.NameValidator = teamDescName.Validators[0].(func(string) error)
userMixin := schema.User{}.Mixin()
user.Policy = privacy.NewPolicies(userMixin[0], userMixin[1], schema.User{})
user.Hooks[0] = func(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if err := user.Policy.EvalMutation(ctx, m); err != nil {
return nil, err
}
return next.Mutate(ctx, m)
})
}
userFields := schema.User{}.Fields()
_ = userFields
// userDescName is the schema descriptor for name field.
userDescName := userFields[0].Descriptor()
// user.NameValidator is a validator for the "name" field. It is called by the builders before save.
user.NameValidator = userDescName.Validators[0].(func(string) error)
}
const (
Version = "v0.0.0-00010101000000-000000000000" // Version of ent codegen.
)

View File

@@ -0,0 +1,31 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package schema
import (
"entgo.io/ent"
"entgo.io/ent/entc/integration/privacy/ent/privacy"
"entgo.io/ent/entc/integration/privacy/rule"
"entgo.io/ent/schema/mixin"
)
// BaseMixin for all schemas.
type BaseMixin struct {
mixin.Schema
}
// Policy defines shared policy for all schemas.
func (BaseMixin) Policy() ent.Policy {
return privacy.Policy{
Mutation: privacy.MutationPolicy{
rule.DenyIfNoViewer(),
rule.AllowIfAdmin(),
},
Query: privacy.QueryPolicy{
rule.DenyIfNoViewer(),
rule.AllowIfAdmin(),
},
}
}

View File

@@ -0,0 +1,73 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package schema
import (
"entgo.io/ent"
"entgo.io/ent/entc/integration/privacy/ent/privacy"
"entgo.io/ent/entc/integration/privacy/rule"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
)
// Task defines the schema of a task.
type Task struct {
ent.Schema
}
// Mixin list of schemas to the task.
func (Task) Mixin() []ent.Mixin {
return []ent.Mixin{
BaseMixin{},
TeamMixin{},
}
}
// Fields of the task.
func (Task) Fields() []ent.Field {
return []ent.Field{
field.String("title").
NotEmpty(),
field.String("description").
Optional(),
field.Enum("status").
Values("planned", "in_progress", "closed").
Default("planned"),
field.UUID("uuid", uuid.UUID{}).
Optional(),
}
}
// Edges of the task.
func (Task) Edges() []ent.Edge {
return []ent.Edge{
edge.From("owner", User.Type).
Ref("tasks").
Unique(),
}
}
// Hooks for the task.
func (Task) Hooks() []ent.Hook {
return []ent.Hook{
rule.LogTaskMutationHook(),
}
}
// Policy of the task.
func (Task) Policy() ent.Policy {
return privacy.Policy{
Mutation: privacy.MutationPolicy{
rule.AllowTaskCreateIfOwner(),
rule.DenyIfStatusChangedByOther(),
rule.AllowIfViewerInTheSameTeam(),
privacy.AlwaysDenyRule(),
},
Query: privacy.QueryPolicy{
privacy.AlwaysAllowRule(),
},
}
}

View File

@@ -0,0 +1,75 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package schema
import (
"entgo.io/ent"
"entgo.io/ent/entc/integration/privacy/ent/privacy"
"entgo.io/ent/entc/integration/privacy/rule"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/mixin"
)
// Team defines the schema of a team.
type Team struct {
ent.Schema
}
// Mixin list of schemas to the team.
func (Team) Mixin() []ent.Mixin {
return []ent.Mixin{
BaseMixin{},
}
}
// Fields of the team.
func (Team) Fields() []ent.Field {
return []ent.Field{
field.String("name").
NotEmpty(),
}
}
// Edges of the team.
func (Team) Edges() []ent.Edge {
return []ent.Edge{
edge.From("tasks", Task.Type).
Ref("teams"),
edge.From("users", User.Type).
Ref("teams"),
}
}
// Policy of the team.
func (Team) Policy() ent.Policy {
return privacy.Policy{
Mutation: privacy.MutationPolicy{
rule.DenyIfNotAdmin(),
rule.DenyUpdateRule(),
},
}
}
// TeamMixin shared between task and user.
type TeamMixin struct {
mixin.Schema
}
// Edges of the team-mixin.
func (TeamMixin) Edges() []ent.Edge {
return []ent.Edge{
edge.To("teams", Team.Type),
}
}
// Policy of the team-mixin.
func (TeamMixin) Policy() ent.Policy {
return privacy.Policy{
Query: privacy.QueryPolicy{
rule.FilterTeamRule(),
},
}
}

View File

@@ -0,0 +1,69 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package schema
import (
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/entc/integration/privacy/ent/privacy"
"entgo.io/ent/entc/integration/privacy/rule"
"entgo.io/ent/schema"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
)
// User defines the schema of a user.
type User struct {
ent.Schema
}
// Mixin list of schemas to the user.
func (User) Mixin() []ent.Mixin {
return []ent.Mixin{
BaseMixin{},
TeamMixin{},
}
}
// Fields of the user.
func (User) Fields() []ent.Field {
return []ent.Field{
field.String("name").
Immutable().
NotEmpty().
Unique(),
field.Uint("age").
Optional(),
}
}
// Edges of the user.
func (User) Edges() []ent.Edge {
return []ent.Edge{
edge.To("tasks", Task.Type),
}
}
// Policy of the user.
func (User) Policy() ent.Policy {
return privacy.Policy{
Mutation: privacy.MutationPolicy{
rule.AllowUserCreateIfAdmin(),
privacy.AlwaysDenyRule(),
},
Query: privacy.QueryPolicy{
privacy.AlwaysAllowRule(),
},
}
}
// Annotations of the user.
func (User) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Checks(map[string]string{
"backticks": "`name` IS NOT NULL",
}),
}
}

View File

@@ -0,0 +1,198 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/entc/integration/privacy/ent/task"
"entgo.io/ent/entc/integration/privacy/ent/user"
"github.com/google/uuid"
)
// Task is the model entity for the Task schema.
type Task 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"`
// Description holds the value of the "description" field.
Description string `json:"description,omitempty"`
// Status holds the value of the "status" field.
Status task.Status `json:"status,omitempty"`
// UUID holds the value of the "uuid" field.
UUID uuid.UUID `json:"uuid,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the TaskQuery when eager-loading is set.
Edges TaskEdges `json:"edges"`
user_tasks *int
selectValues sql.SelectValues
}
// TaskEdges holds the relations/edges for other nodes in the graph.
type TaskEdges struct {
// Teams holds the value of the teams edge.
Teams []*Team `json:"teams,omitempty"`
// Owner holds the value of the owner edge.
Owner *User `json:"owner,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// TeamsOrErr returns the Teams value or an error if the edge
// was not loaded in eager-loading.
func (e TaskEdges) TeamsOrErr() ([]*Team, error) {
if e.loadedTypes[0] {
return e.Teams, nil
}
return nil, &NotLoadedError{edge: "teams"}
}
// OwnerOrErr returns the Owner value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e TaskEdges) OwnerOrErr() (*User, error) {
if e.Owner != nil {
return e.Owner, nil
} else if e.loadedTypes[1] {
return nil, &NotFoundError{label: user.Label}
}
return nil, &NotLoadedError{edge: "owner"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Task) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case task.FieldID:
values[i] = new(sql.NullInt64)
case task.FieldTitle, task.FieldDescription, task.FieldStatus:
values[i] = new(sql.NullString)
case task.FieldUUID:
values[i] = new(uuid.UUID)
case task.ForeignKeys[0]: // user_tasks
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 Task fields.
func (_m *Task) 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 task.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 task.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 task.FieldDescription:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field description", values[i])
} else if value.Valid {
_m.Description = value.String
}
case task.FieldStatus:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field status", values[i])
} else if value.Valid {
_m.Status = task.Status(value.String)
}
case task.FieldUUID:
if value, ok := values[i].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field uuid", values[i])
} else if value != nil {
_m.UUID = *value
}
case task.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for edge-field user_tasks", value)
} else if value.Valid {
_m.user_tasks = new(int)
*_m.user_tasks = 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 Task.
// This includes values selected through modifiers, order, etc.
func (_m *Task) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryTeams queries the "teams" edge of the Task entity.
func (_m *Task) QueryTeams() *TeamQuery {
return NewTaskClient(_m.config).QueryTeams(_m)
}
// QueryOwner queries the "owner" edge of the Task entity.
func (_m *Task) QueryOwner() *UserQuery {
return NewTaskClient(_m.config).QueryOwner(_m)
}
// Update returns a builder for updating this Task.
// Note that you need to call Task.Unwrap() before calling this method if this Task
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Task) Update() *TaskUpdateOne {
return NewTaskClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Task 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 *Task) Unwrap() *Task {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: Task is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Task) String() string {
var builder strings.Builder
builder.WriteString("Task(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("title=")
builder.WriteString(_m.Title)
builder.WriteString(", ")
builder.WriteString("description=")
builder.WriteString(_m.Description)
builder.WriteString(", ")
builder.WriteString("status=")
builder.WriteString(fmt.Sprintf("%v", _m.Status))
builder.WriteString(", ")
builder.WriteString("uuid=")
builder.WriteString(fmt.Sprintf("%v", _m.UUID))
builder.WriteByte(')')
return builder.String()
}
// Tasks is a parsable slice of Task.
type Tasks []*Task

View File

@@ -0,0 +1,532 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package task
import (
"context"
"fmt"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/entc/integration/privacy/ent/predicate"
"github.com/google/uuid"
)
// Mutation represents an operation that mutates the Task nodes in the graph.
type Mutation struct {
op ent.Op
typ string
title *string
description *string
status *Status
uuid *uuid.UUID
clearedFields map[string]struct{}
teams map[int]struct{}
removedteams map[int]struct{}
clearedteams bool
owner *int
clearedowner bool
predicates []predicate.Task
}
// NewMutation creates a new Mutation for the Task entity.
func NewMutation(op ent.Op) *Mutation {
return &Mutation{
op: op,
typ: "Task",
clearedFields: make(map[string]struct{}),
}
}
// Predicates returns the list of predicates set on the mutation.
func (m *Mutation) Predicates() []predicate.Task {
return m.predicates
}
// SetTitle sets the "title" field.
func (m *Mutation) SetTitle(s string) {
m.title = &s
}
// Title returns the value of the "title" field in the mutation.
func (m *Mutation) Title() (r string, exists bool) {
v := m.title
if v == nil {
return
}
return *v, true
}
// ResetTitle resets all changes to the "title" field.
func (m *Mutation) ResetTitle() {
m.title = nil
}
// SetDescription sets the "description" field.
func (m *Mutation) SetDescription(s string) {
m.description = &s
}
// Description returns the value of the "description" field in the mutation.
func (m *Mutation) Description() (r string, exists bool) {
v := m.description
if v == nil {
return
}
return *v, true
}
// ClearDescription clears the value of the "description" field.
func (m *Mutation) ClearDescription() {
m.description = nil
m.clearedFields[FieldDescription] = struct{}{}
}
// DescriptionCleared returns if the "description" field was cleared in this mutation.
func (m *Mutation) DescriptionCleared() bool {
_, ok := m.clearedFields[FieldDescription]
return ok
}
// ResetDescription resets all changes to the "description" field.
func (m *Mutation) ResetDescription() {
m.description = nil
delete(m.clearedFields, FieldDescription)
}
// SetStatus sets the "status" field.
func (m *Mutation) SetStatus(t Status) {
m.status = &t
}
// Status returns the value of the "status" field in the mutation.
func (m *Mutation) Status() (r Status, exists bool) {
v := m.status
if v == nil {
return
}
return *v, true
}
// ResetStatus resets all changes to the "status" field.
func (m *Mutation) ResetStatus() {
m.status = nil
}
// SetUUID sets the "uuid" field.
func (m *Mutation) SetUUID(u uuid.UUID) {
m.uuid = &u
}
// UUID returns the value of the "uuid" field in the mutation.
func (m *Mutation) UUID() (r uuid.UUID, exists bool) {
v := m.uuid
if v == nil {
return
}
return *v, true
}
// ClearUUID clears the value of the "uuid" field.
func (m *Mutation) ClearUUID() {
m.uuid = nil
m.clearedFields[FieldUUID] = struct{}{}
}
// UUIDCleared returns if the "uuid" field was cleared in this mutation.
func (m *Mutation) UUIDCleared() bool {
_, ok := m.clearedFields[FieldUUID]
return ok
}
// ResetUUID resets all changes to the "uuid" field.
func (m *Mutation) ResetUUID() {
m.uuid = nil
delete(m.clearedFields, FieldUUID)
}
// AddTeamIDs adds the "teams" edge to the Team entity by ids.
func (m *Mutation) AddTeamIDs(ids ...int) {
if m.teams == nil {
m.teams = make(map[int]struct{})
}
for i := range ids {
m.teams[ids[i]] = struct{}{}
}
}
// ClearTeams clears the "teams" edge to the Team entity.
func (m *Mutation) ClearTeams() {
m.clearedteams = true
}
// TeamsCleared reports if the "teams" edge to the Team entity was cleared.
func (m *Mutation) TeamsCleared() bool {
return m.clearedteams
}
// RemoveTeamIDs removes the "teams" edge to the Team entity by IDs.
func (m *Mutation) RemoveTeamIDs(ids ...int) {
if m.removedteams == nil {
m.removedteams = make(map[int]struct{})
}
for i := range ids {
delete(m.teams, ids[i])
m.removedteams[ids[i]] = struct{}{}
}
}
// RemovedTeams returns the removed IDs of the "teams" edge to the Team entity.
func (m *Mutation) RemovedTeamsIDs() (ids []int) {
for id := range m.removedteams {
ids = append(ids, id)
}
return
}
// TeamsIDs returns the "teams" edge IDs in the mutation.
func (m *Mutation) TeamsIDs() (ids []int) {
for id := range m.teams {
ids = append(ids, id)
}
return
}
// ResetTeams resets all changes to the "teams" edge.
func (m *Mutation) ResetTeams() {
m.teams = nil
m.clearedteams = false
m.removedteams = nil
}
// SetOwnerID sets the "owner" edge to the User entity by id.
func (m *Mutation) SetOwnerID(id int) {
m.owner = &id
}
// ClearOwner clears the "owner" edge to the User entity.
func (m *Mutation) ClearOwner() {
m.clearedowner = true
}
// OwnerCleared reports if the "owner" edge to the User entity was cleared.
func (m *Mutation) OwnerCleared() bool {
return m.clearedowner
}
// OwnerID returns the "owner" edge ID in the mutation.
func (m *Mutation) OwnerID() (id int, exists bool) {
if m.owner != nil {
return *m.owner, true
}
return
}
// OwnerIDs returns the "owner" edge IDs in the mutation.
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
// OwnerID instead. It exists only for internal usage by the builders.
func (m *Mutation) OwnerIDs() (ids []int) {
if id := m.owner; id != nil {
ids = append(ids, *id)
}
return
}
// ResetOwner resets all changes to the "owner" edge.
func (m *Mutation) ResetOwner() {
m.owner = nil
m.clearedowner = false
}
// Where appends a list predicates to the Mutation builder.
func (m *Mutation) Where(ps ...predicate.Task) {
m.predicates = append(m.predicates, ps...)
}
// WhereP appends storage-level predicates to the Mutation builder. Using this method,
// users can use type-assertion to append predicates that do not depend on any generated package.
func (m *Mutation) WhereP(ps ...func(*sql.Selector)) {
p := make([]predicate.Task, len(ps))
for i := range ps {
p[i] = ps[i]
}
m.Where(p...)
}
// Op returns the operation name.
func (m *Mutation) Op() ent.Op {
return m.op
}
// SetOp allows setting the mutation operation.
func (m *Mutation) SetOp(op ent.Op) {
m.op = op
}
// Type returns the node type of this mutation (Task).
func (m *Mutation) Type() string {
return m.typ
}
// Fields returns all fields that were changed during this mutation. Note that in
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *Mutation) Fields() []string {
fields := make([]string, 0, 4)
if m.title != nil {
fields = append(fields, FieldTitle)
}
if m.description != nil {
fields = append(fields, FieldDescription)
}
if m.status != nil {
fields = append(fields, FieldStatus)
}
if m.uuid != nil {
fields = append(fields, FieldUUID)
}
return fields
}
// Field returns the value of a field with the given name. The second boolean
// return value indicates that this field was not set, or was not defined in the
// schema.
func (m *Mutation) Field(name string) (ent.Value, bool) {
switch name {
case FieldTitle:
return m.Title()
case FieldDescription:
return m.Description()
case FieldStatus:
return m.Status()
case FieldUUID:
return m.UUID()
}
return nil, false
}
// OldField returns the old value of the field from the database. An error is
// returned if the mutation operation is not UpdateOne, or the query to the
// database failed.
func (m *Mutation) OldField(ctx context.Context, name string) (ent.Value, error) {
return nil, fmt.Errorf("unknown Task field %s", name)
}
// SetField sets the value of a field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *Mutation) SetField(name string, value ent.Value) error {
switch name {
case FieldTitle:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetTitle(v)
return nil
case FieldDescription:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetDescription(v)
return nil
case FieldStatus:
v, ok := value.(Status)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetStatus(v)
return nil
case FieldUUID:
v, ok := value.(uuid.UUID)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetUUID(v)
return nil
}
return fmt.Errorf("unknown Task field %s", name)
}
// AddedFields returns all numeric fields that were incremented/decremented during
// this mutation.
func (m *Mutation) AddedFields() []string {
return nil
}
// AddedField returns the numeric value that was incremented/decremented on a field
// with the given name. The second boolean return value indicates that this field
// was not set, or was not defined in the schema.
func (m *Mutation) AddedField(name string) (ent.Value, bool) {
return nil, false
}
// AddField adds the value to the field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *Mutation) AddField(name string, value ent.Value) error {
switch name {
}
return fmt.Errorf("unknown Task numeric field %s", name)
}
// ClearedFields returns all nullable fields that were cleared during this
// mutation.
func (m *Mutation) ClearedFields() []string {
var fields []string
if m.FieldCleared(FieldDescription) {
fields = append(fields, FieldDescription)
}
if m.FieldCleared(FieldUUID) {
fields = append(fields, FieldUUID)
}
return fields
}
// FieldCleared returns a boolean indicating if a field with the given name was
// cleared in this mutation.
func (m *Mutation) FieldCleared(name string) bool {
_, ok := m.clearedFields[name]
return ok
}
// ClearField clears the value of the field with the given name. It returns an
// error if the field is not defined in the schema.
func (m *Mutation) ClearField(name string) error {
switch name {
case FieldDescription:
m.ClearDescription()
return nil
case FieldUUID:
m.ClearUUID()
return nil
}
return fmt.Errorf("unknown Task nullable field %s", name)
}
// ResetField resets all changes in the mutation for the field with the given name.
// It returns an error if the field is not defined in the schema.
func (m *Mutation) ResetField(name string) error {
switch name {
case FieldTitle:
m.ResetTitle()
return nil
case FieldDescription:
m.ResetDescription()
return nil
case FieldStatus:
m.ResetStatus()
return nil
case FieldUUID:
m.ResetUUID()
return nil
}
return fmt.Errorf("unknown Task field %s", name)
}
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *Mutation) AddedEdges() []string {
edges := make([]string, 0, 2)
if m.teams != nil {
edges = append(edges, EdgeTeams)
}
if m.owner != nil {
edges = append(edges, EdgeOwner)
}
return edges
}
// AddedIDs returns all IDs (to other nodes) that were added for the given edge
// name in this mutation.
func (m *Mutation) AddedIDs(name string) []ent.Value {
switch name {
case EdgeTeams:
ids := make([]ent.Value, 0, len(m.teams))
for id := range m.teams {
ids = append(ids, id)
}
return ids
case EdgeOwner:
if id := m.owner; id != nil {
return []ent.Value{*id}
}
}
return nil
}
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *Mutation) RemovedEdges() []string {
edges := make([]string, 0, 2)
if m.removedteams != nil {
edges = append(edges, EdgeTeams)
}
return edges
}
// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
// the given name in this mutation.
func (m *Mutation) RemovedIDs(name string) []ent.Value {
switch name {
case EdgeTeams:
ids := make([]ent.Value, 0, len(m.removedteams))
for id := range m.removedteams {
ids = append(ids, id)
}
return ids
}
return nil
}
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *Mutation) ClearedEdges() []string {
edges := make([]string, 0, 2)
if m.clearedteams {
edges = append(edges, EdgeTeams)
}
if m.clearedowner {
edges = append(edges, EdgeOwner)
}
return edges
}
// EdgeCleared returns a boolean which indicates if the edge with the given name
// was cleared in this mutation.
func (m *Mutation) EdgeCleared(name string) bool {
switch name {
case EdgeTeams:
return m.clearedteams
case EdgeOwner:
return m.clearedowner
}
return false
}
// ClearEdge clears the value of the edge with the given name. It returns an error
// if that edge is not defined in the schema.
func (m *Mutation) ClearEdge(name string) error {
switch name {
case EdgeOwner:
m.ClearOwner()
return nil
}
return fmt.Errorf("unknown Task unique edge %s", name)
}
// ResetEdge resets all changes to the edge with the given name in this mutation.
// It returns an error if the edge is not defined in the schema.
func (m *Mutation) ResetEdge(name string) error {
switch name {
case EdgeTeams:
m.ResetTeams()
return nil
case EdgeOwner:
m.ResetOwner()
return nil
}
return fmt.Errorf("unknown Task edge %s", name)
}

View File

@@ -0,0 +1,186 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package task
import (
"fmt"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the task type in the database.
Label = "task"
// 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"
// FieldDescription holds the string denoting the description field in the database.
FieldDescription = "description"
// FieldStatus holds the string denoting the status field in the database.
FieldStatus = "status"
// FieldUUID holds the string denoting the uuid field in the database.
FieldUUID = "uuid"
// EdgeTeams holds the string denoting the teams edge name in mutations.
EdgeTeams = "teams"
// EdgeOwner holds the string denoting the owner edge name in mutations.
EdgeOwner = "owner"
// Table holds the table name of the task in the database.
Table = "tasks"
// TeamsTable is the table that holds the teams relation/edge. The primary key declared below.
TeamsTable = "task_teams"
// TeamsInverseTable is the table name for the Team entity.
// It exists in this package in order to avoid circular dependency with the "team" package.
TeamsInverseTable = "teams"
// OwnerTable is the table that holds the owner relation/edge.
OwnerTable = "tasks"
// OwnerInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
OwnerInverseTable = "users"
// OwnerColumn is the table column denoting the owner relation/edge.
OwnerColumn = "user_tasks"
)
// Columns holds all SQL columns for task fields.
var Columns = []string{
FieldID,
FieldTitle,
FieldDescription,
FieldStatus,
FieldUUID,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "tasks"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"user_tasks",
}
var (
// TeamsPrimaryKey and TeamsColumn2 are the table columns denoting the
// primary key for the teams relation (M2M).
TeamsPrimaryKey = []string{"task_id", "team_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
}
}
for i := range ForeignKeys {
if column == ForeignKeys[i] {
return true
}
}
return false
}
// Note that the variables below are initialized by the runtime
// package on the initialization of the application. Therefore,
// it should be imported in the main as follows:
//
// import _ "entgo.io/ent/entc/integration/privacy/ent/runtime"
var (
Hooks [2]ent.Hook
Policy ent.Policy
// TitleValidator is a validator for the "title" field. It is called by the builders before save.
TitleValidator func(string) error
)
// Status defines the type for the "status" enum field.
type Status string
// StatusPlanned is the default value of the Status enum.
const DefaultStatus = StatusPlanned
// Status values.
const (
StatusPlanned Status = "planned"
StatusInProgress Status = "in_progress"
StatusClosed Status = "closed"
)
func (s Status) String() string {
return string(s)
}
// StatusValidator is a validator for the "status" field enum values. It is called by the builders before save.
func StatusValidator(s Status) error {
switch s {
case StatusPlanned, StatusInProgress, StatusClosed:
return nil
default:
return fmt.Errorf("task: invalid enum value for status field: %q", s)
}
}
// OrderOption defines the ordering options for the Task 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()
}
// ByDescription orders the results by the description field.
func ByDescription(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDescription, opts...).ToFunc()
}
// ByStatus orders the results by the status field.
func ByStatus(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldStatus, opts...).ToFunc()
}
// ByUUID orders the results by the uuid field.
func ByUUID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUUID, opts...).ToFunc()
}
// ByTeamsCount orders the results by teams count.
func ByTeamsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newTeamsStep(), opts...)
}
}
// ByTeams orders the results by teams terms.
func ByTeams(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newTeamsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByOwnerField orders the results by owner field.
func ByOwnerField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newOwnerStep(), sql.OrderByField(field, opts...))
}
}
func newTeamsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(TeamsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, TeamsTable, TeamsPrimaryKey...),
)
}
func newOwnerStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(OwnerInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, OwnerTable, OwnerColumn),
)
}

View File

@@ -0,0 +1,345 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package task
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/privacy/ent/predicate"
"github.com/google/uuid"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Task {
return predicate.Task(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Task {
return predicate.Task(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Task {
return predicate.Task(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Task {
return predicate.Task(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Task {
return predicate.Task(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Task {
return predicate.Task(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Task {
return predicate.Task(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Task {
return predicate.Task(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Task {
return predicate.Task(sql.FieldLTE(FieldID, id))
}
// Title applies equality check predicate on the "title" field. It's identical to TitleEQ.
func Title(v string) predicate.Task {
return predicate.Task(sql.FieldEQ(FieldTitle, v))
}
// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ.
func Description(v string) predicate.Task {
return predicate.Task(sql.FieldEQ(FieldDescription, v))
}
// UUID applies equality check predicate on the "uuid" field. It's identical to UUIDEQ.
func UUID(v uuid.UUID) predicate.Task {
return predicate.Task(sql.FieldEQ(FieldUUID, v))
}
// TitleEQ applies the EQ predicate on the "title" field.
func TitleEQ(v string) predicate.Task {
return predicate.Task(sql.FieldEQ(FieldTitle, v))
}
// TitleNEQ applies the NEQ predicate on the "title" field.
func TitleNEQ(v string) predicate.Task {
return predicate.Task(sql.FieldNEQ(FieldTitle, v))
}
// TitleIn applies the In predicate on the "title" field.
func TitleIn(vs ...string) predicate.Task {
return predicate.Task(sql.FieldIn(FieldTitle, vs...))
}
// TitleNotIn applies the NotIn predicate on the "title" field.
func TitleNotIn(vs ...string) predicate.Task {
return predicate.Task(sql.FieldNotIn(FieldTitle, vs...))
}
// TitleGT applies the GT predicate on the "title" field.
func TitleGT(v string) predicate.Task {
return predicate.Task(sql.FieldGT(FieldTitle, v))
}
// TitleGTE applies the GTE predicate on the "title" field.
func TitleGTE(v string) predicate.Task {
return predicate.Task(sql.FieldGTE(FieldTitle, v))
}
// TitleLT applies the LT predicate on the "title" field.
func TitleLT(v string) predicate.Task {
return predicate.Task(sql.FieldLT(FieldTitle, v))
}
// TitleLTE applies the LTE predicate on the "title" field.
func TitleLTE(v string) predicate.Task {
return predicate.Task(sql.FieldLTE(FieldTitle, v))
}
// TitleContains applies the Contains predicate on the "title" field.
func TitleContains(v string) predicate.Task {
return predicate.Task(sql.FieldContains(FieldTitle, v))
}
// TitleHasPrefix applies the HasPrefix predicate on the "title" field.
func TitleHasPrefix(v string) predicate.Task {
return predicate.Task(sql.FieldHasPrefix(FieldTitle, v))
}
// TitleHasSuffix applies the HasSuffix predicate on the "title" field.
func TitleHasSuffix(v string) predicate.Task {
return predicate.Task(sql.FieldHasSuffix(FieldTitle, v))
}
// TitleEqualFold applies the EqualFold predicate on the "title" field.
func TitleEqualFold(v string) predicate.Task {
return predicate.Task(sql.FieldEqualFold(FieldTitle, v))
}
// TitleContainsFold applies the ContainsFold predicate on the "title" field.
func TitleContainsFold(v string) predicate.Task {
return predicate.Task(sql.FieldContainsFold(FieldTitle, v))
}
// DescriptionEQ applies the EQ predicate on the "description" field.
func DescriptionEQ(v string) predicate.Task {
return predicate.Task(sql.FieldEQ(FieldDescription, v))
}
// DescriptionNEQ applies the NEQ predicate on the "description" field.
func DescriptionNEQ(v string) predicate.Task {
return predicate.Task(sql.FieldNEQ(FieldDescription, v))
}
// DescriptionIn applies the In predicate on the "description" field.
func DescriptionIn(vs ...string) predicate.Task {
return predicate.Task(sql.FieldIn(FieldDescription, vs...))
}
// DescriptionNotIn applies the NotIn predicate on the "description" field.
func DescriptionNotIn(vs ...string) predicate.Task {
return predicate.Task(sql.FieldNotIn(FieldDescription, vs...))
}
// DescriptionGT applies the GT predicate on the "description" field.
func DescriptionGT(v string) predicate.Task {
return predicate.Task(sql.FieldGT(FieldDescription, v))
}
// DescriptionGTE applies the GTE predicate on the "description" field.
func DescriptionGTE(v string) predicate.Task {
return predicate.Task(sql.FieldGTE(FieldDescription, v))
}
// DescriptionLT applies the LT predicate on the "description" field.
func DescriptionLT(v string) predicate.Task {
return predicate.Task(sql.FieldLT(FieldDescription, v))
}
// DescriptionLTE applies the LTE predicate on the "description" field.
func DescriptionLTE(v string) predicate.Task {
return predicate.Task(sql.FieldLTE(FieldDescription, v))
}
// DescriptionContains applies the Contains predicate on the "description" field.
func DescriptionContains(v string) predicate.Task {
return predicate.Task(sql.FieldContains(FieldDescription, v))
}
// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field.
func DescriptionHasPrefix(v string) predicate.Task {
return predicate.Task(sql.FieldHasPrefix(FieldDescription, v))
}
// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field.
func DescriptionHasSuffix(v string) predicate.Task {
return predicate.Task(sql.FieldHasSuffix(FieldDescription, v))
}
// DescriptionIsNil applies the IsNil predicate on the "description" field.
func DescriptionIsNil() predicate.Task {
return predicate.Task(sql.FieldIsNull(FieldDescription))
}
// DescriptionNotNil applies the NotNil predicate on the "description" field.
func DescriptionNotNil() predicate.Task {
return predicate.Task(sql.FieldNotNull(FieldDescription))
}
// DescriptionEqualFold applies the EqualFold predicate on the "description" field.
func DescriptionEqualFold(v string) predicate.Task {
return predicate.Task(sql.FieldEqualFold(FieldDescription, v))
}
// DescriptionContainsFold applies the ContainsFold predicate on the "description" field.
func DescriptionContainsFold(v string) predicate.Task {
return predicate.Task(sql.FieldContainsFold(FieldDescription, v))
}
// StatusEQ applies the EQ predicate on the "status" field.
func StatusEQ(v Status) predicate.Task {
return predicate.Task(sql.FieldEQ(FieldStatus, v))
}
// StatusNEQ applies the NEQ predicate on the "status" field.
func StatusNEQ(v Status) predicate.Task {
return predicate.Task(sql.FieldNEQ(FieldStatus, v))
}
// StatusIn applies the In predicate on the "status" field.
func StatusIn(vs ...Status) predicate.Task {
return predicate.Task(sql.FieldIn(FieldStatus, vs...))
}
// StatusNotIn applies the NotIn predicate on the "status" field.
func StatusNotIn(vs ...Status) predicate.Task {
return predicate.Task(sql.FieldNotIn(FieldStatus, vs...))
}
// UUIDEQ applies the EQ predicate on the "uuid" field.
func UUIDEQ(v uuid.UUID) predicate.Task {
return predicate.Task(sql.FieldEQ(FieldUUID, v))
}
// UUIDNEQ applies the NEQ predicate on the "uuid" field.
func UUIDNEQ(v uuid.UUID) predicate.Task {
return predicate.Task(sql.FieldNEQ(FieldUUID, v))
}
// UUIDIn applies the In predicate on the "uuid" field.
func UUIDIn(vs ...uuid.UUID) predicate.Task {
return predicate.Task(sql.FieldIn(FieldUUID, vs...))
}
// UUIDNotIn applies the NotIn predicate on the "uuid" field.
func UUIDNotIn(vs ...uuid.UUID) predicate.Task {
return predicate.Task(sql.FieldNotIn(FieldUUID, vs...))
}
// UUIDGT applies the GT predicate on the "uuid" field.
func UUIDGT(v uuid.UUID) predicate.Task {
return predicate.Task(sql.FieldGT(FieldUUID, v))
}
// UUIDGTE applies the GTE predicate on the "uuid" field.
func UUIDGTE(v uuid.UUID) predicate.Task {
return predicate.Task(sql.FieldGTE(FieldUUID, v))
}
// UUIDLT applies the LT predicate on the "uuid" field.
func UUIDLT(v uuid.UUID) predicate.Task {
return predicate.Task(sql.FieldLT(FieldUUID, v))
}
// UUIDLTE applies the LTE predicate on the "uuid" field.
func UUIDLTE(v uuid.UUID) predicate.Task {
return predicate.Task(sql.FieldLTE(FieldUUID, v))
}
// UUIDIsNil applies the IsNil predicate on the "uuid" field.
func UUIDIsNil() predicate.Task {
return predicate.Task(sql.FieldIsNull(FieldUUID))
}
// UUIDNotNil applies the NotNil predicate on the "uuid" field.
func UUIDNotNil() predicate.Task {
return predicate.Task(sql.FieldNotNull(FieldUUID))
}
// HasTeams applies the HasEdge predicate on the "teams" edge.
func HasTeams() predicate.Task {
return predicate.Task(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, TeamsTable, TeamsPrimaryKey...),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasTeamsWith applies the HasEdge predicate on the "teams" edge with a given conditions (other predicates).
func HasTeamsWith(preds ...predicate.Team) predicate.Task {
return predicate.Task(func(s *sql.Selector) {
step := newTeamsStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasOwner applies the HasEdge predicate on the "owner" edge.
func HasOwner() predicate.Task {
return predicate.Task(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, OwnerTable, OwnerColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasOwnerWith applies the HasEdge predicate on the "owner" edge with a given conditions (other predicates).
func HasOwnerWith(preds ...predicate.User) predicate.Task {
return predicate.Task(func(s *sql.Selector) {
step := newOwnerStep()
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.Task) predicate.Task {
return predicate.Task(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Task) predicate.Task {
return predicate.Task(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Task) predicate.Task {
return predicate.Task(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,337 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/privacy/ent/task"
"entgo.io/ent/entc/integration/privacy/ent/team"
"entgo.io/ent/entc/integration/privacy/ent/user"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
)
// TaskCreate is the builder for creating a Task entity.
type TaskCreate struct {
config
mutation *TaskMutation
hooks []Hook
}
// SetTitle sets the "title" field.
func (_c *TaskCreate) SetTitle(v string) *TaskCreate {
_c.mutation.SetTitle(v)
return _c
}
// SetDescription sets the "description" field.
func (_c *TaskCreate) SetDescription(v string) *TaskCreate {
_c.mutation.SetDescription(v)
return _c
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (_c *TaskCreate) SetNillableDescription(v *string) *TaskCreate {
if v != nil {
_c.SetDescription(*v)
}
return _c
}
// SetStatus sets the "status" field.
func (_c *TaskCreate) SetStatus(v task.Status) *TaskCreate {
_c.mutation.SetStatus(v)
return _c
}
// SetNillableStatus sets the "status" field if the given value is not nil.
func (_c *TaskCreate) SetNillableStatus(v *task.Status) *TaskCreate {
if v != nil {
_c.SetStatus(*v)
}
return _c
}
// SetUUID sets the "uuid" field.
func (_c *TaskCreate) SetUUID(v uuid.UUID) *TaskCreate {
_c.mutation.SetUUID(v)
return _c
}
// SetNillableUUID sets the "uuid" field if the given value is not nil.
func (_c *TaskCreate) SetNillableUUID(v *uuid.UUID) *TaskCreate {
if v != nil {
_c.SetUUID(*v)
}
return _c
}
// AddTeamIDs adds the "teams" edge to the Team entity by IDs.
func (_c *TaskCreate) AddTeamIDs(ids ...int) *TaskCreate {
_c.mutation.AddTeamIDs(ids...)
return _c
}
// AddTeams adds the "teams" edges to the Team entity.
func (_c *TaskCreate) AddTeams(v ...*Team) *TaskCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddTeamIDs(ids...)
}
// SetOwnerID sets the "owner" edge to the User entity by ID.
func (_c *TaskCreate) SetOwnerID(id int) *TaskCreate {
_c.mutation.SetOwnerID(id)
return _c
}
// SetNillableOwnerID sets the "owner" edge to the User entity by ID if the given value is not nil.
func (_c *TaskCreate) SetNillableOwnerID(id *int) *TaskCreate {
if id != nil {
_c = _c.SetOwnerID(*id)
}
return _c
}
// SetOwner sets the "owner" edge to the User entity.
func (_c *TaskCreate) SetOwner(v *User) *TaskCreate {
return _c.SetOwnerID(v.ID)
}
// Mutation returns the TaskMutation object of the builder.
func (_c *TaskCreate) Mutation() *TaskMutation {
return _c.mutation
}
// Save creates the Task in the database.
func (_c *TaskCreate) Save(ctx context.Context) (*Task, error) {
if err := _c.defaults(); err != nil {
return nil, err
}
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *TaskCreate) SaveX(ctx context.Context) *Task {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *TaskCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *TaskCreate) 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 *TaskCreate) defaults() error {
if _, ok := _c.mutation.Status(); !ok {
v := task.DefaultStatus
_c.mutation.SetStatus(v)
}
return nil
}
// check runs all checks and user-defined validators on the builder.
func (_c *TaskCreate) check() error {
if _, ok := _c.mutation.Title(); !ok {
return &ValidationError{Name: "title", err: errors.New(`ent: missing required field "Task.title"`)}
}
if v, ok := _c.mutation.Title(); ok {
if err := task.TitleValidator(v); err != nil {
return &ValidationError{Name: "title", err: fmt.Errorf(`ent: validator failed for field "Task.title": %w`, err)}
}
}
if _, ok := _c.mutation.Status(); !ok {
return &ValidationError{Name: "status", err: errors.New(`ent: missing required field "Task.status"`)}
}
if v, ok := _c.mutation.Status(); ok {
if err := task.StatusValidator(v); err != nil {
return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Task.status": %w`, err)}
}
}
return nil
}
func (_c *TaskCreate) sqlSave(ctx context.Context) (*Task, 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 *TaskCreate) createSpec() (*Task, *sqlgraph.CreateSpec) {
var (
_node = &Task{config: _c.config}
_spec = sqlgraph.NewCreateSpec(task.Table, sqlgraph.NewFieldSpec(task.FieldID, field.TypeInt))
)
if value, ok := _c.mutation.Title(); ok {
_spec.SetField(task.FieldTitle, field.TypeString, value)
_node.Title = value
}
if value, ok := _c.mutation.Description(); ok {
_spec.SetField(task.FieldDescription, field.TypeString, value)
_node.Description = value
}
if value, ok := _c.mutation.Status(); ok {
_spec.SetField(task.FieldStatus, field.TypeEnum, value)
_node.Status = value
}
if value, ok := _c.mutation.UUID(); ok {
_spec.SetField(task.FieldUUID, field.TypeUUID, value)
_node.UUID = value
}
if nodes := _c.mutation.TeamsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: task.TeamsTable,
Columns: task.TeamsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(team.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.OwnerIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: task.OwnerTable,
Columns: []string{task.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.user_tasks = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// TaskCreateBulk is the builder for creating many Task entities in bulk.
type TaskCreateBulk struct {
config
err error
builders []*TaskCreate
}
// Save creates the Task entities in the database.
func (_c *TaskCreateBulk) Save(ctx context.Context) ([]*Task, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*Task, 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.(*TaskMutation)
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 *TaskCreateBulk) SaveX(ctx context.Context) []*Task {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *TaskCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *TaskCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,92 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/privacy/ent/predicate"
"entgo.io/ent/entc/integration/privacy/ent/task"
"entgo.io/ent/schema/field"
)
// TaskDelete is the builder for deleting a Task entity.
type TaskDelete struct {
config
hooks []Hook
mutation *TaskMutation
}
// Where appends a list predicates to the TaskDelete builder.
func (_d *TaskDelete) Where(ps ...predicate.Task) *TaskDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *TaskDelete) 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 *TaskDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *TaskDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(task.Table, sqlgraph.NewFieldSpec(task.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
}
// TaskDeleteOne is the builder for deleting a single Task entity.
type TaskDeleteOne struct {
_d *TaskDelete
}
// Where appends a list predicates to the TaskDelete builder.
func (_d *TaskDeleteOne) Where(ps ...predicate.Task) *TaskDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *TaskDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{task.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *TaskDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,731 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"database/sql/driver"
"errors"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/privacy/ent/predicate"
"entgo.io/ent/entc/integration/privacy/ent/task"
"entgo.io/ent/entc/integration/privacy/ent/team"
"entgo.io/ent/entc/integration/privacy/ent/user"
"entgo.io/ent/schema/field"
)
// TaskQuery is the builder for querying Task entities.
type TaskQuery struct {
config
ctx *QueryContext
order []task.OrderOption
inters []Interceptor
predicates []predicate.Task
withTeams *TeamQuery
withOwner *UserQuery
withFKs bool
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the TaskQuery builder.
func (_q *TaskQuery) Where(ps ...predicate.Task) *TaskQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *TaskQuery) Limit(limit int) *TaskQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *TaskQuery) Offset(offset int) *TaskQuery {
_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 *TaskQuery) Unique(unique bool) *TaskQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *TaskQuery) Order(o ...task.OrderOption) *TaskQuery {
_q.order = append(_q.order, o...)
return _q
}
// QueryTeams chains the current query on the "teams" edge.
func (_q *TaskQuery) QueryTeams() *TeamQuery {
query := (&TeamClient{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(task.Table, task.FieldID, selector),
sqlgraph.To(team.Table, team.FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, task.TeamsTable, task.TeamsPrimaryKey...),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryOwner chains the current query on the "owner" edge.
func (_q *TaskQuery) QueryOwner() *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(task.Table, task.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, task.OwnerTable, task.OwnerColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Task entity from the query.
// Returns a *NotFoundError when no Task was found.
func (_q *TaskQuery) First(ctx context.Context) (*Task, 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{task.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *TaskQuery) FirstX(ctx context.Context) *Task {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Task ID from the query.
// Returns a *NotFoundError when no Task ID was found.
func (_q *TaskQuery) 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{task.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *TaskQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Task entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Task entity is found.
// Returns a *NotFoundError when no Task entities are found.
func (_q *TaskQuery) Only(ctx context.Context) (*Task, 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{task.Label}
default:
return nil, &NotSingularError{task.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *TaskQuery) OnlyX(ctx context.Context) *Task {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Task ID in the query.
// Returns a *NotSingularError when more than one Task ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *TaskQuery) 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{task.Label}
default:
err = &NotSingularError{task.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *TaskQuery) 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 Tasks.
func (_q *TaskQuery) All(ctx context.Context) ([]*Task, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Task, *TaskQuery]()
return withInterceptors[[]*Task](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *TaskQuery) AllX(ctx context.Context) []*Task {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Task IDs.
func (_q *TaskQuery) 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(task.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *TaskQuery) 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 *TaskQuery) 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[*TaskQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *TaskQuery) 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 *TaskQuery) 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 *TaskQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the TaskQuery 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 *TaskQuery) Clone() *TaskQuery {
if _q == nil {
return nil
}
return &TaskQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]task.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Task{}, _q.predicates...),
withTeams: _q.withTeams.Clone(),
withOwner: _q.withOwner.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// WithTeams tells the query-builder to eager-load the nodes that are connected to
// the "teams" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *TaskQuery) WithTeams(opts ...func(*TeamQuery)) *TaskQuery {
query := (&TeamClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withTeams = query
return _q
}
// WithOwner tells the query-builder to eager-load the nodes that are connected to
// the "owner" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *TaskQuery) WithOwner(opts ...func(*UserQuery)) *TaskQuery {
query := (&UserClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withOwner = 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.Task.Query().
// GroupBy(task.FieldTitle).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *TaskQuery) GroupBy(field string, fields ...string) *TaskGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &TaskGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = task.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.Task.Query().
// Select(task.FieldTitle).
// Scan(ctx, &v)
func (_q *TaskQuery) Select(fields ...string) *TaskSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &TaskSelect{TaskQuery: _q}
sbuild.label = task.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a TaskSelect configured with the given aggregations.
func (_q *TaskQuery) Aggregate(fns ...AggregateFunc) *TaskSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *TaskQuery) 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 !task.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
}
if task.Policy == nil {
return errors.New("ent: uninitialized task.Policy (forgotten import ent/runtime?)")
}
if err := task.Policy.EvalQuery(ctx, _q); err != nil {
return err
}
return nil
}
func (_q *TaskQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Task, error) {
var (
nodes = []*Task{}
withFKs = _q.withFKs
_spec = _q.querySpec()
loadedTypes = [2]bool{
_q.withTeams != nil,
_q.withOwner != nil,
}
)
if _q.withOwner != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, task.ForeignKeys...)
}
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Task).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Task{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.withTeams; query != nil {
if err := _q.loadTeams(ctx, query, nodes,
func(n *Task) { n.Edges.Teams = []*Team{} },
func(n *Task, e *Team) { n.Edges.Teams = append(n.Edges.Teams, e) }); err != nil {
return nil, err
}
}
if query := _q.withOwner; query != nil {
if err := _q.loadOwner(ctx, query, nodes, nil,
func(n *Task, e *User) { n.Edges.Owner = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *TaskQuery) loadTeams(ctx context.Context, query *TeamQuery, nodes []*Task, init func(*Task), assign func(*Task, *Team)) error {
edgeIDs := make([]driver.Value, len(nodes))
byID := make(map[int]*Task)
nids := make(map[int]map[*Task]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(task.TeamsTable)
s.Join(joinT).On(s.C(team.FieldID), joinT.C(task.TeamsPrimaryKey[1]))
s.Where(sql.InValues(joinT.C(task.TeamsPrimaryKey[0]), edgeIDs...))
columns := s.SelectedColumns()
s.Select(joinT.C(task.TeamsPrimaryKey[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[*Task]struct{}{byID[outValue]: {}}
return assign(columns[1:], values[1:])
}
nids[inValue][byID[outValue]] = struct{}{}
return nil
}
})
})
neighbors, err := withInterceptors[[]*Team](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 "teams" node returned %v`, n.ID)
}
for kn := range nodes {
assign(kn, n)
}
}
return nil
}
func (_q *TaskQuery) loadOwner(ctx context.Context, query *UserQuery, nodes []*Task, init func(*Task), assign func(*Task, *User)) error {
ids := make([]int, 0, len(nodes))
nodeids := make(map[int][]*Task)
for i := range nodes {
if nodes[i].user_tasks == nil {
continue
}
fk := *nodes[i].user_tasks
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(user.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "user_tasks" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *TaskQuery) 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 *TaskQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(task.Table, task.Columns, sqlgraph.NewFieldSpec(task.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, task.FieldID)
for i := range fields {
if fields[i] != task.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 *TaskQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(task.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = task.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
}
// TaskGroupBy is the group-by builder for Task entities.
type TaskGroupBy struct {
selector
build *TaskQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *TaskGroupBy) Aggregate(fns ...AggregateFunc) *TaskGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *TaskGroupBy) 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[*TaskQuery, *TaskGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *TaskGroupBy) sqlScan(ctx context.Context, root *TaskQuery, 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)
}
// TaskSelect is the builder for selecting fields of Task entities.
type TaskSelect struct {
*TaskQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *TaskSelect) Aggregate(fns ...AggregateFunc) *TaskSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *TaskSelect) 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[*TaskQuery, *TaskSelect](ctx, _s.TaskQuery, _s, _s.inters, v)
}
func (_s *TaskSelect) sqlScan(ctx context.Context, root *TaskQuery, 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)
}

View File

@@ -0,0 +1,660 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/privacy/ent/predicate"
"entgo.io/ent/entc/integration/privacy/ent/task"
"entgo.io/ent/entc/integration/privacy/ent/team"
"entgo.io/ent/entc/integration/privacy/ent/user"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
)
// TaskUpdate is the builder for updating Task entities.
type TaskUpdate struct {
config
hooks []Hook
mutation *TaskMutation
}
// Where appends a list predicates to the TaskUpdate builder.
func (_u *TaskUpdate) Where(ps ...predicate.Task) *TaskUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetTitle sets the "title" field.
func (_u *TaskUpdate) SetTitle(v string) *TaskUpdate {
_u.mutation.SetTitle(v)
return _u
}
// SetNillableTitle sets the "title" field if the given value is not nil.
func (_u *TaskUpdate) SetNillableTitle(v *string) *TaskUpdate {
if v != nil {
_u.SetTitle(*v)
}
return _u
}
// SetDescription sets the "description" field.
func (_u *TaskUpdate) SetDescription(v string) *TaskUpdate {
_u.mutation.SetDescription(v)
return _u
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (_u *TaskUpdate) SetNillableDescription(v *string) *TaskUpdate {
if v != nil {
_u.SetDescription(*v)
}
return _u
}
// ClearDescription clears the value of the "description" field.
func (_u *TaskUpdate) ClearDescription() *TaskUpdate {
_u.mutation.ClearDescription()
return _u
}
// SetStatus sets the "status" field.
func (_u *TaskUpdate) SetStatus(v task.Status) *TaskUpdate {
_u.mutation.SetStatus(v)
return _u
}
// SetNillableStatus sets the "status" field if the given value is not nil.
func (_u *TaskUpdate) SetNillableStatus(v *task.Status) *TaskUpdate {
if v != nil {
_u.SetStatus(*v)
}
return _u
}
// SetUUID sets the "uuid" field.
func (_u *TaskUpdate) SetUUID(v uuid.UUID) *TaskUpdate {
_u.mutation.SetUUID(v)
return _u
}
// SetNillableUUID sets the "uuid" field if the given value is not nil.
func (_u *TaskUpdate) SetNillableUUID(v *uuid.UUID) *TaskUpdate {
if v != nil {
_u.SetUUID(*v)
}
return _u
}
// ClearUUID clears the value of the "uuid" field.
func (_u *TaskUpdate) ClearUUID() *TaskUpdate {
_u.mutation.ClearUUID()
return _u
}
// AddTeamIDs adds the "teams" edge to the Team entity by IDs.
func (_u *TaskUpdate) AddTeamIDs(ids ...int) *TaskUpdate {
_u.mutation.AddTeamIDs(ids...)
return _u
}
// AddTeams adds the "teams" edges to the Team entity.
func (_u *TaskUpdate) AddTeams(v ...*Team) *TaskUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddTeamIDs(ids...)
}
// SetOwnerID sets the "owner" edge to the User entity by ID.
func (_u *TaskUpdate) SetOwnerID(id int) *TaskUpdate {
_u.mutation.SetOwnerID(id)
return _u
}
// SetNillableOwnerID sets the "owner" edge to the User entity by ID if the given value is not nil.
func (_u *TaskUpdate) SetNillableOwnerID(id *int) *TaskUpdate {
if id != nil {
_u = _u.SetOwnerID(*id)
}
return _u
}
// SetOwner sets the "owner" edge to the User entity.
func (_u *TaskUpdate) SetOwner(v *User) *TaskUpdate {
return _u.SetOwnerID(v.ID)
}
// Mutation returns the TaskMutation object of the builder.
func (_u *TaskUpdate) Mutation() *TaskMutation {
return _u.mutation
}
// ClearTeams clears all "teams" edges to the Team entity.
func (_u *TaskUpdate) ClearTeams() *TaskUpdate {
_u.mutation.ClearTeams()
return _u
}
// RemoveTeamIDs removes the "teams" edge to Team entities by IDs.
func (_u *TaskUpdate) RemoveTeamIDs(ids ...int) *TaskUpdate {
_u.mutation.RemoveTeamIDs(ids...)
return _u
}
// RemoveTeams removes "teams" edges to Team entities.
func (_u *TaskUpdate) RemoveTeams(v ...*Team) *TaskUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveTeamIDs(ids...)
}
// ClearOwner clears the "owner" edge to the User entity.
func (_u *TaskUpdate) ClearOwner() *TaskUpdate {
_u.mutation.ClearOwner()
return _u
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *TaskUpdate) 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 *TaskUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *TaskUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *TaskUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *TaskUpdate) check() error {
if v, ok := _u.mutation.Title(); ok {
if err := task.TitleValidator(v); err != nil {
return &ValidationError{Name: "title", err: fmt.Errorf(`ent: validator failed for field "Task.title": %w`, err)}
}
}
if v, ok := _u.mutation.Status(); ok {
if err := task.StatusValidator(v); err != nil {
return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Task.status": %w`, err)}
}
}
return nil
}
func (_u *TaskUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(task.Table, task.Columns, sqlgraph.NewFieldSpec(task.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(task.FieldTitle, field.TypeString, value)
}
if value, ok := _u.mutation.Description(); ok {
_spec.SetField(task.FieldDescription, field.TypeString, value)
}
if _u.mutation.DescriptionCleared() {
_spec.ClearField(task.FieldDescription, field.TypeString)
}
if value, ok := _u.mutation.Status(); ok {
_spec.SetField(task.FieldStatus, field.TypeEnum, value)
}
if value, ok := _u.mutation.UUID(); ok {
_spec.SetField(task.FieldUUID, field.TypeUUID, value)
}
if _u.mutation.UUIDCleared() {
_spec.ClearField(task.FieldUUID, field.TypeUUID)
}
if _u.mutation.TeamsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: task.TeamsTable,
Columns: task.TeamsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(team.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedTeamsIDs(); len(nodes) > 0 && !_u.mutation.TeamsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: task.TeamsTable,
Columns: task.TeamsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(team.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.TeamsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: task.TeamsTable,
Columns: task.TeamsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(team.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.OwnerCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: task.OwnerTable,
Columns: []string{task.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.OwnerIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: task.OwnerTable,
Columns: []string{task.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{task.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// TaskUpdateOne is the builder for updating a single Task entity.
type TaskUpdateOne struct {
config
fields []string
hooks []Hook
mutation *TaskMutation
}
// SetTitle sets the "title" field.
func (_u *TaskUpdateOne) SetTitle(v string) *TaskUpdateOne {
_u.mutation.SetTitle(v)
return _u
}
// SetNillableTitle sets the "title" field if the given value is not nil.
func (_u *TaskUpdateOne) SetNillableTitle(v *string) *TaskUpdateOne {
if v != nil {
_u.SetTitle(*v)
}
return _u
}
// SetDescription sets the "description" field.
func (_u *TaskUpdateOne) SetDescription(v string) *TaskUpdateOne {
_u.mutation.SetDescription(v)
return _u
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (_u *TaskUpdateOne) SetNillableDescription(v *string) *TaskUpdateOne {
if v != nil {
_u.SetDescription(*v)
}
return _u
}
// ClearDescription clears the value of the "description" field.
func (_u *TaskUpdateOne) ClearDescription() *TaskUpdateOne {
_u.mutation.ClearDescription()
return _u
}
// SetStatus sets the "status" field.
func (_u *TaskUpdateOne) SetStatus(v task.Status) *TaskUpdateOne {
_u.mutation.SetStatus(v)
return _u
}
// SetNillableStatus sets the "status" field if the given value is not nil.
func (_u *TaskUpdateOne) SetNillableStatus(v *task.Status) *TaskUpdateOne {
if v != nil {
_u.SetStatus(*v)
}
return _u
}
// SetUUID sets the "uuid" field.
func (_u *TaskUpdateOne) SetUUID(v uuid.UUID) *TaskUpdateOne {
_u.mutation.SetUUID(v)
return _u
}
// SetNillableUUID sets the "uuid" field if the given value is not nil.
func (_u *TaskUpdateOne) SetNillableUUID(v *uuid.UUID) *TaskUpdateOne {
if v != nil {
_u.SetUUID(*v)
}
return _u
}
// ClearUUID clears the value of the "uuid" field.
func (_u *TaskUpdateOne) ClearUUID() *TaskUpdateOne {
_u.mutation.ClearUUID()
return _u
}
// AddTeamIDs adds the "teams" edge to the Team entity by IDs.
func (_u *TaskUpdateOne) AddTeamIDs(ids ...int) *TaskUpdateOne {
_u.mutation.AddTeamIDs(ids...)
return _u
}
// AddTeams adds the "teams" edges to the Team entity.
func (_u *TaskUpdateOne) AddTeams(v ...*Team) *TaskUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddTeamIDs(ids...)
}
// SetOwnerID sets the "owner" edge to the User entity by ID.
func (_u *TaskUpdateOne) SetOwnerID(id int) *TaskUpdateOne {
_u.mutation.SetOwnerID(id)
return _u
}
// SetNillableOwnerID sets the "owner" edge to the User entity by ID if the given value is not nil.
func (_u *TaskUpdateOne) SetNillableOwnerID(id *int) *TaskUpdateOne {
if id != nil {
_u = _u.SetOwnerID(*id)
}
return _u
}
// SetOwner sets the "owner" edge to the User entity.
func (_u *TaskUpdateOne) SetOwner(v *User) *TaskUpdateOne {
return _u.SetOwnerID(v.ID)
}
// Mutation returns the TaskMutation object of the builder.
func (_u *TaskUpdateOne) Mutation() *TaskMutation {
return _u.mutation
}
// ClearTeams clears all "teams" edges to the Team entity.
func (_u *TaskUpdateOne) ClearTeams() *TaskUpdateOne {
_u.mutation.ClearTeams()
return _u
}
// RemoveTeamIDs removes the "teams" edge to Team entities by IDs.
func (_u *TaskUpdateOne) RemoveTeamIDs(ids ...int) *TaskUpdateOne {
_u.mutation.RemoveTeamIDs(ids...)
return _u
}
// RemoveTeams removes "teams" edges to Team entities.
func (_u *TaskUpdateOne) RemoveTeams(v ...*Team) *TaskUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveTeamIDs(ids...)
}
// ClearOwner clears the "owner" edge to the User entity.
func (_u *TaskUpdateOne) ClearOwner() *TaskUpdateOne {
_u.mutation.ClearOwner()
return _u
}
// Where appends a list predicates to the TaskUpdate builder.
func (_u *TaskUpdateOne) Where(ps ...predicate.Task) *TaskUpdateOne {
_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 *TaskUpdateOne) Select(field string, fields ...string) *TaskUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated Task entity.
func (_u *TaskUpdateOne) Save(ctx context.Context) (*Task, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *TaskUpdateOne) SaveX(ctx context.Context) *Task {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *TaskUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *TaskUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *TaskUpdateOne) check() error {
if v, ok := _u.mutation.Title(); ok {
if err := task.TitleValidator(v); err != nil {
return &ValidationError{Name: "title", err: fmt.Errorf(`ent: validator failed for field "Task.title": %w`, err)}
}
}
if v, ok := _u.mutation.Status(); ok {
if err := task.StatusValidator(v); err != nil {
return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Task.status": %w`, err)}
}
}
return nil
}
func (_u *TaskUpdateOne) sqlSave(ctx context.Context) (_node *Task, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(task.Table, task.Columns, sqlgraph.NewFieldSpec(task.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Task.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, task.FieldID)
for _, f := range fields {
if !task.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != task.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(task.FieldTitle, field.TypeString, value)
}
if value, ok := _u.mutation.Description(); ok {
_spec.SetField(task.FieldDescription, field.TypeString, value)
}
if _u.mutation.DescriptionCleared() {
_spec.ClearField(task.FieldDescription, field.TypeString)
}
if value, ok := _u.mutation.Status(); ok {
_spec.SetField(task.FieldStatus, field.TypeEnum, value)
}
if value, ok := _u.mutation.UUID(); ok {
_spec.SetField(task.FieldUUID, field.TypeUUID, value)
}
if _u.mutation.UUIDCleared() {
_spec.ClearField(task.FieldUUID, field.TypeUUID)
}
if _u.mutation.TeamsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: task.TeamsTable,
Columns: task.TeamsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(team.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedTeamsIDs(); len(nodes) > 0 && !_u.mutation.TeamsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: task.TeamsTable,
Columns: task.TeamsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(team.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.TeamsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: task.TeamsTable,
Columns: task.TeamsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(team.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.OwnerCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: task.OwnerTable,
Columns: []string{task.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.OwnerIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: task.OwnerTable,
Columns: []string{task.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &Task{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{task.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

View File

@@ -0,0 +1,149 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/entc/integration/privacy/ent/team"
)
// Team is the model entity for the Team schema.
type Team 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 TeamQuery when eager-loading is set.
Edges TeamEdges `json:"edges"`
selectValues sql.SelectValues
}
// TeamEdges holds the relations/edges for other nodes in the graph.
type TeamEdges struct {
// Tasks holds the value of the tasks edge.
Tasks []*Task `json:"tasks,omitempty"`
// Users holds the value of the users edge.
Users []*User `json:"users,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// TasksOrErr returns the Tasks value or an error if the edge
// was not loaded in eager-loading.
func (e TeamEdges) TasksOrErr() ([]*Task, error) {
if e.loadedTypes[0] {
return e.Tasks, nil
}
return nil, &NotLoadedError{edge: "tasks"}
}
// UsersOrErr returns the Users value or an error if the edge
// was not loaded in eager-loading.
func (e TeamEdges) UsersOrErr() ([]*User, error) {
if e.loadedTypes[1] {
return e.Users, nil
}
return nil, &NotLoadedError{edge: "users"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Team) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case team.FieldID:
values[i] = new(sql.NullInt64)
case team.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 Team fields.
func (_m *Team) 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 team.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 team.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 Team.
// This includes values selected through modifiers, order, etc.
func (_m *Team) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryTasks queries the "tasks" edge of the Team entity.
func (_m *Team) QueryTasks() *TaskQuery {
return NewTeamClient(_m.config).QueryTasks(_m)
}
// QueryUsers queries the "users" edge of the Team entity.
func (_m *Team) QueryUsers() *UserQuery {
return NewTeamClient(_m.config).QueryUsers(_m)
}
// Update returns a builder for updating this Team.
// Note that you need to call Team.Unwrap() before calling this method if this Team
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Team) Update() *TeamUpdateOne {
return NewTeamClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Team 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 *Team) Unwrap() *Team {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: Team is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Team) String() string {
var builder strings.Builder
builder.WriteString("Team(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("name=")
builder.WriteString(_m.Name)
builder.WriteByte(')')
return builder.String()
}
// Teams is a parsable slice of Team.
type Teams []*Team

View File

@@ -0,0 +1,409 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package team
import (
"context"
"fmt"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/entc/integration/privacy/ent/predicate"
)
// Mutation represents an operation that mutates the Team nodes in the graph.
type Mutation struct {
op ent.Op
typ string
name *string
clearedFields map[string]struct{}
tasks map[int]struct{}
removedtasks map[int]struct{}
clearedtasks bool
users map[int]struct{}
removedusers map[int]struct{}
clearedusers bool
predicates []predicate.Team
}
// NewMutation creates a new Mutation for the Team entity.
func NewMutation(op ent.Op) *Mutation {
return &Mutation{
op: op,
typ: "Team",
clearedFields: make(map[string]struct{}),
}
}
// Predicates returns the list of predicates set on the mutation.
func (m *Mutation) Predicates() []predicate.Team {
return m.predicates
}
// SetName sets the "name" field.
func (m *Mutation) SetName(s string) {
m.name = &s
}
// Name returns the value of the "name" field in the mutation.
func (m *Mutation) Name() (r string, exists bool) {
v := m.name
if v == nil {
return
}
return *v, true
}
// ResetName resets all changes to the "name" field.
func (m *Mutation) ResetName() {
m.name = nil
}
// AddTaskIDs adds the "tasks" edge to the Task entity by ids.
func (m *Mutation) AddTaskIDs(ids ...int) {
if m.tasks == nil {
m.tasks = make(map[int]struct{})
}
for i := range ids {
m.tasks[ids[i]] = struct{}{}
}
}
// ClearTasks clears the "tasks" edge to the Task entity.
func (m *Mutation) ClearTasks() {
m.clearedtasks = true
}
// TasksCleared reports if the "tasks" edge to the Task entity was cleared.
func (m *Mutation) TasksCleared() bool {
return m.clearedtasks
}
// RemoveTaskIDs removes the "tasks" edge to the Task entity by IDs.
func (m *Mutation) RemoveTaskIDs(ids ...int) {
if m.removedtasks == nil {
m.removedtasks = make(map[int]struct{})
}
for i := range ids {
delete(m.tasks, ids[i])
m.removedtasks[ids[i]] = struct{}{}
}
}
// RemovedTasks returns the removed IDs of the "tasks" edge to the Task entity.
func (m *Mutation) RemovedTasksIDs() (ids []int) {
for id := range m.removedtasks {
ids = append(ids, id)
}
return
}
// TasksIDs returns the "tasks" edge IDs in the mutation.
func (m *Mutation) TasksIDs() (ids []int) {
for id := range m.tasks {
ids = append(ids, id)
}
return
}
// ResetTasks resets all changes to the "tasks" edge.
func (m *Mutation) ResetTasks() {
m.tasks = nil
m.clearedtasks = false
m.removedtasks = nil
}
// AddUserIDs adds the "users" edge to the User entity by ids.
func (m *Mutation) AddUserIDs(ids ...int) {
if m.users == nil {
m.users = make(map[int]struct{})
}
for i := range ids {
m.users[ids[i]] = struct{}{}
}
}
// ClearUsers clears the "users" edge to the User entity.
func (m *Mutation) ClearUsers() {
m.clearedusers = true
}
// UsersCleared reports if the "users" edge to the User entity was cleared.
func (m *Mutation) UsersCleared() bool {
return m.clearedusers
}
// RemoveUserIDs removes the "users" edge to the User entity by IDs.
func (m *Mutation) RemoveUserIDs(ids ...int) {
if m.removedusers == nil {
m.removedusers = make(map[int]struct{})
}
for i := range ids {
delete(m.users, ids[i])
m.removedusers[ids[i]] = struct{}{}
}
}
// RemovedUsers returns the removed IDs of the "users" edge to the User entity.
func (m *Mutation) RemovedUsersIDs() (ids []int) {
for id := range m.removedusers {
ids = append(ids, id)
}
return
}
// UsersIDs returns the "users" edge IDs in the mutation.
func (m *Mutation) UsersIDs() (ids []int) {
for id := range m.users {
ids = append(ids, id)
}
return
}
// ResetUsers resets all changes to the "users" edge.
func (m *Mutation) ResetUsers() {
m.users = nil
m.clearedusers = false
m.removedusers = nil
}
// Where appends a list predicates to the Mutation builder.
func (m *Mutation) Where(ps ...predicate.Team) {
m.predicates = append(m.predicates, ps...)
}
// WhereP appends storage-level predicates to the Mutation builder. Using this method,
// users can use type-assertion to append predicates that do not depend on any generated package.
func (m *Mutation) WhereP(ps ...func(*sql.Selector)) {
p := make([]predicate.Team, len(ps))
for i := range ps {
p[i] = ps[i]
}
m.Where(p...)
}
// Op returns the operation name.
func (m *Mutation) Op() ent.Op {
return m.op
}
// SetOp allows setting the mutation operation.
func (m *Mutation) SetOp(op ent.Op) {
m.op = op
}
// Type returns the node type of this mutation (Team).
func (m *Mutation) Type() string {
return m.typ
}
// Fields returns all fields that were changed during this mutation. Note that in
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *Mutation) Fields() []string {
fields := make([]string, 0, 1)
if m.name != nil {
fields = append(fields, FieldName)
}
return fields
}
// Field returns the value of a field with the given name. The second boolean
// return value indicates that this field was not set, or was not defined in the
// schema.
func (m *Mutation) Field(name string) (ent.Value, bool) {
switch name {
case FieldName:
return m.Name()
}
return nil, false
}
// OldField returns the old value of the field from the database. An error is
// returned if the mutation operation is not UpdateOne, or the query to the
// database failed.
func (m *Mutation) OldField(ctx context.Context, name string) (ent.Value, error) {
return nil, fmt.Errorf("unknown Team field %s", name)
}
// SetField sets the value of a field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *Mutation) SetField(name string, value ent.Value) error {
switch name {
case FieldName:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetName(v)
return nil
}
return fmt.Errorf("unknown Team field %s", name)
}
// AddedFields returns all numeric fields that were incremented/decremented during
// this mutation.
func (m *Mutation) AddedFields() []string {
return nil
}
// AddedField returns the numeric value that was incremented/decremented on a field
// with the given name. The second boolean return value indicates that this field
// was not set, or was not defined in the schema.
func (m *Mutation) AddedField(name string) (ent.Value, bool) {
return nil, false
}
// AddField adds the value to the field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *Mutation) AddField(name string, value ent.Value) error {
switch name {
}
return fmt.Errorf("unknown Team numeric field %s", name)
}
// ClearedFields returns all nullable fields that were cleared during this
// mutation.
func (m *Mutation) ClearedFields() []string {
return nil
}
// FieldCleared returns a boolean indicating if a field with the given name was
// cleared in this mutation.
func (m *Mutation) FieldCleared(name string) bool {
_, ok := m.clearedFields[name]
return ok
}
// ClearField clears the value of the field with the given name. It returns an
// error if the field is not defined in the schema.
func (m *Mutation) ClearField(name string) error {
return fmt.Errorf("unknown Team nullable field %s", name)
}
// ResetField resets all changes in the mutation for the field with the given name.
// It returns an error if the field is not defined in the schema.
func (m *Mutation) ResetField(name string) error {
switch name {
case FieldName:
m.ResetName()
return nil
}
return fmt.Errorf("unknown Team field %s", name)
}
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *Mutation) AddedEdges() []string {
edges := make([]string, 0, 2)
if m.tasks != nil {
edges = append(edges, EdgeTasks)
}
if m.users != nil {
edges = append(edges, EdgeUsers)
}
return edges
}
// AddedIDs returns all IDs (to other nodes) that were added for the given edge
// name in this mutation.
func (m *Mutation) AddedIDs(name string) []ent.Value {
switch name {
case EdgeTasks:
ids := make([]ent.Value, 0, len(m.tasks))
for id := range m.tasks {
ids = append(ids, id)
}
return ids
case EdgeUsers:
ids := make([]ent.Value, 0, len(m.users))
for id := range m.users {
ids = append(ids, id)
}
return ids
}
return nil
}
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *Mutation) RemovedEdges() []string {
edges := make([]string, 0, 2)
if m.removedtasks != nil {
edges = append(edges, EdgeTasks)
}
if m.removedusers != nil {
edges = append(edges, EdgeUsers)
}
return edges
}
// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
// the given name in this mutation.
func (m *Mutation) RemovedIDs(name string) []ent.Value {
switch name {
case EdgeTasks:
ids := make([]ent.Value, 0, len(m.removedtasks))
for id := range m.removedtasks {
ids = append(ids, id)
}
return ids
case EdgeUsers:
ids := make([]ent.Value, 0, len(m.removedusers))
for id := range m.removedusers {
ids = append(ids, id)
}
return ids
}
return nil
}
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *Mutation) ClearedEdges() []string {
edges := make([]string, 0, 2)
if m.clearedtasks {
edges = append(edges, EdgeTasks)
}
if m.clearedusers {
edges = append(edges, EdgeUsers)
}
return edges
}
// EdgeCleared returns a boolean which indicates if the edge with the given name
// was cleared in this mutation.
func (m *Mutation) EdgeCleared(name string) bool {
switch name {
case EdgeTasks:
return m.clearedtasks
case EdgeUsers:
return m.clearedusers
}
return false
}
// ClearEdge clears the value of the edge with the given name. It returns an error
// if that edge is not defined in the schema.
func (m *Mutation) ClearEdge(name string) error {
switch name {
}
return fmt.Errorf("unknown Team unique edge %s", name)
}
// ResetEdge resets all changes to the edge with the given name in this mutation.
// It returns an error if the edge is not defined in the schema.
func (m *Mutation) ResetEdge(name string) error {
switch name {
case EdgeTasks:
m.ResetTasks()
return nil
case EdgeUsers:
m.ResetUsers()
return nil
}
return fmt.Errorf("unknown Team edge %s", name)
}

View File

@@ -0,0 +1,130 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package team
import (
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the team type in the database.
Label = "team"
// 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"
// EdgeTasks holds the string denoting the tasks edge name in mutations.
EdgeTasks = "tasks"
// EdgeUsers holds the string denoting the users edge name in mutations.
EdgeUsers = "users"
// Table holds the table name of the team in the database.
Table = "teams"
// TasksTable is the table that holds the tasks relation/edge. The primary key declared below.
TasksTable = "task_teams"
// TasksInverseTable is the table name for the Task entity.
// It exists in this package in order to avoid circular dependency with the "task" package.
TasksInverseTable = "tasks"
// UsersTable is the table that holds the users relation/edge. The primary key declared below.
UsersTable = "user_teams"
// 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"
)
// Columns holds all SQL columns for team fields.
var Columns = []string{
FieldID,
FieldName,
}
var (
// TasksPrimaryKey and TasksColumn2 are the table columns denoting the
// primary key for the tasks relation (M2M).
TasksPrimaryKey = []string{"task_id", "team_id"}
// UsersPrimaryKey and UsersColumn2 are the table columns denoting the
// primary key for the users relation (M2M).
UsersPrimaryKey = []string{"user_id", "team_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
}
// Note that the variables below are initialized by the runtime
// package on the initialization of the application. Therefore,
// it should be imported in the main as follows:
//
// import _ "entgo.io/ent/entc/integration/privacy/ent/runtime"
var (
Hooks [1]ent.Hook
Policy ent.Policy
// NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error
)
// OrderOption defines the ordering options for the Team 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()
}
// ByTasksCount orders the results by tasks count.
func ByTasksCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newTasksStep(), opts...)
}
}
// ByTasks orders the results by tasks terms.
func ByTasks(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newTasksStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// 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...)...)
}
}
func newTasksStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(TasksInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, TasksTable, TasksPrimaryKey...),
)
}
func newUsersStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UsersInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, UsersTable, UsersPrimaryKey...),
)
}

View File

@@ -0,0 +1,189 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package team
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/privacy/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Team {
return predicate.Team(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Team {
return predicate.Team(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Team {
return predicate.Team(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Team {
return predicate.Team(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Team {
return predicate.Team(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Team {
return predicate.Team(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Team {
return predicate.Team(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Team {
return predicate.Team(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Team {
return predicate.Team(sql.FieldLTE(FieldID, id))
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Team {
return predicate.Team(sql.FieldEQ(FieldName, v))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Team {
return predicate.Team(sql.FieldEQ(FieldName, v))
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.Team {
return predicate.Team(sql.FieldNEQ(FieldName, v))
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.Team {
return predicate.Team(sql.FieldIn(FieldName, vs...))
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.Team {
return predicate.Team(sql.FieldNotIn(FieldName, vs...))
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.Team {
return predicate.Team(sql.FieldGT(FieldName, v))
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.Team {
return predicate.Team(sql.FieldGTE(FieldName, v))
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.Team {
return predicate.Team(sql.FieldLT(FieldName, v))
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.Team {
return predicate.Team(sql.FieldLTE(FieldName, v))
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.Team {
return predicate.Team(sql.FieldContains(FieldName, v))
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.Team {
return predicate.Team(sql.FieldHasPrefix(FieldName, v))
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.Team {
return predicate.Team(sql.FieldHasSuffix(FieldName, v))
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.Team {
return predicate.Team(sql.FieldEqualFold(FieldName, v))
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.Team {
return predicate.Team(sql.FieldContainsFold(FieldName, v))
}
// HasTasks applies the HasEdge predicate on the "tasks" edge.
func HasTasks() predicate.Team {
return predicate.Team(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, TasksTable, TasksPrimaryKey...),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasTasksWith applies the HasEdge predicate on the "tasks" edge with a given conditions (other predicates).
func HasTasksWith(preds ...predicate.Task) predicate.Team {
return predicate.Team(func(s *sql.Selector) {
step := newTasksStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasUsers applies the HasEdge predicate on the "users" edge.
func HasUsers() predicate.Team {
return predicate.Team(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.Team {
return predicate.Team(func(s *sql.Selector) {
step := newUsersStep()
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.Team) predicate.Team {
return predicate.Team(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Team) predicate.Team {
return predicate.Team(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Team) predicate.Team {
return predicate.Team(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,256 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/privacy/ent/task"
"entgo.io/ent/entc/integration/privacy/ent/team"
"entgo.io/ent/entc/integration/privacy/ent/user"
"entgo.io/ent/schema/field"
)
// TeamCreate is the builder for creating a Team entity.
type TeamCreate struct {
config
mutation *TeamMutation
hooks []Hook
}
// SetName sets the "name" field.
func (_c *TeamCreate) SetName(v string) *TeamCreate {
_c.mutation.SetName(v)
return _c
}
// AddTaskIDs adds the "tasks" edge to the Task entity by IDs.
func (_c *TeamCreate) AddTaskIDs(ids ...int) *TeamCreate {
_c.mutation.AddTaskIDs(ids...)
return _c
}
// AddTasks adds the "tasks" edges to the Task entity.
func (_c *TeamCreate) AddTasks(v ...*Task) *TeamCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddTaskIDs(ids...)
}
// AddUserIDs adds the "users" edge to the User entity by IDs.
func (_c *TeamCreate) AddUserIDs(ids ...int) *TeamCreate {
_c.mutation.AddUserIDs(ids...)
return _c
}
// AddUsers adds the "users" edges to the User entity.
func (_c *TeamCreate) AddUsers(v ...*User) *TeamCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddUserIDs(ids...)
}
// Mutation returns the TeamMutation object of the builder.
func (_c *TeamCreate) Mutation() *TeamMutation {
return _c.mutation
}
// Save creates the Team in the database.
func (_c *TeamCreate) Save(ctx context.Context) (*Team, error) {
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *TeamCreate) SaveX(ctx context.Context) *Team {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *TeamCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *TeamCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *TeamCreate) check() error {
if _, ok := _c.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Team.name"`)}
}
if v, ok := _c.mutation.Name(); ok {
if err := team.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Team.name": %w`, err)}
}
}
return nil
}
func (_c *TeamCreate) sqlSave(ctx context.Context) (*Team, 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 *TeamCreate) createSpec() (*Team, *sqlgraph.CreateSpec) {
var (
_node = &Team{config: _c.config}
_spec = sqlgraph.NewCreateSpec(team.Table, sqlgraph.NewFieldSpec(team.FieldID, field.TypeInt))
)
if value, ok := _c.mutation.Name(); ok {
_spec.SetField(team.FieldName, field.TypeString, value)
_node.Name = value
}
if nodes := _c.mutation.TasksIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: team.TasksTable,
Columns: team.TasksPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(task.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.UsersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: team.UsersTable,
Columns: team.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)
}
return _node, _spec
}
// TeamCreateBulk is the builder for creating many Team entities in bulk.
type TeamCreateBulk struct {
config
err error
builders []*TeamCreate
}
// Save creates the Team entities in the database.
func (_c *TeamCreateBulk) Save(ctx context.Context) ([]*Team, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*Team, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*TeamMutation)
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 *TeamCreateBulk) SaveX(ctx context.Context) []*Team {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *TeamCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *TeamCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,92 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/privacy/ent/predicate"
"entgo.io/ent/entc/integration/privacy/ent/team"
"entgo.io/ent/schema/field"
)
// TeamDelete is the builder for deleting a Team entity.
type TeamDelete struct {
config
hooks []Hook
mutation *TeamMutation
}
// Where appends a list predicates to the TeamDelete builder.
func (_d *TeamDelete) Where(ps ...predicate.Team) *TeamDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *TeamDelete) 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 *TeamDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *TeamDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(team.Table, sqlgraph.NewFieldSpec(team.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
}
// TeamDeleteOne is the builder for deleting a single Team entity.
type TeamDeleteOne struct {
_d *TeamDelete
}
// Where appends a list predicates to the TeamDelete builder.
func (_d *TeamDeleteOne) Where(ps ...predicate.Team) *TeamDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *TeamDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{team.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *TeamDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,753 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"database/sql/driver"
"errors"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/privacy/ent/predicate"
"entgo.io/ent/entc/integration/privacy/ent/task"
"entgo.io/ent/entc/integration/privacy/ent/team"
"entgo.io/ent/entc/integration/privacy/ent/user"
"entgo.io/ent/schema/field"
)
// TeamQuery is the builder for querying Team entities.
type TeamQuery struct {
config
ctx *QueryContext
order []team.OrderOption
inters []Interceptor
predicates []predicate.Team
withTasks *TaskQuery
withUsers *UserQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the TeamQuery builder.
func (_q *TeamQuery) Where(ps ...predicate.Team) *TeamQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *TeamQuery) Limit(limit int) *TeamQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *TeamQuery) Offset(offset int) *TeamQuery {
_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 *TeamQuery) Unique(unique bool) *TeamQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *TeamQuery) Order(o ...team.OrderOption) *TeamQuery {
_q.order = append(_q.order, o...)
return _q
}
// QueryTasks chains the current query on the "tasks" edge.
func (_q *TeamQuery) QueryTasks() *TaskQuery {
query := (&TaskClient{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(team.Table, team.FieldID, selector),
sqlgraph.To(task.Table, task.FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, team.TasksTable, team.TasksPrimaryKey...),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryUsers chains the current query on the "users" edge.
func (_q *TeamQuery) 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(team.Table, team.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, team.UsersTable, team.UsersPrimaryKey...),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Team entity from the query.
// Returns a *NotFoundError when no Team was found.
func (_q *TeamQuery) First(ctx context.Context) (*Team, 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{team.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *TeamQuery) FirstX(ctx context.Context) *Team {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Team ID from the query.
// Returns a *NotFoundError when no Team ID was found.
func (_q *TeamQuery) 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{team.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *TeamQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Team entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Team entity is found.
// Returns a *NotFoundError when no Team entities are found.
func (_q *TeamQuery) Only(ctx context.Context) (*Team, 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{team.Label}
default:
return nil, &NotSingularError{team.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *TeamQuery) OnlyX(ctx context.Context) *Team {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Team ID in the query.
// Returns a *NotSingularError when more than one Team ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *TeamQuery) 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{team.Label}
default:
err = &NotSingularError{team.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *TeamQuery) 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 Teams.
func (_q *TeamQuery) All(ctx context.Context) ([]*Team, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Team, *TeamQuery]()
return withInterceptors[[]*Team](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *TeamQuery) AllX(ctx context.Context) []*Team {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Team IDs.
func (_q *TeamQuery) 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(team.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *TeamQuery) 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 *TeamQuery) 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[*TeamQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *TeamQuery) 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 *TeamQuery) 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 *TeamQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the TeamQuery 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 *TeamQuery) Clone() *TeamQuery {
if _q == nil {
return nil
}
return &TeamQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]team.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Team{}, _q.predicates...),
withTasks: _q.withTasks.Clone(),
withUsers: _q.withUsers.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// WithTasks tells the query-builder to eager-load the nodes that are connected to
// the "tasks" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *TeamQuery) WithTasks(opts ...func(*TaskQuery)) *TeamQuery {
query := (&TaskClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withTasks = query
return _q
}
// 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 *TeamQuery) WithUsers(opts ...func(*UserQuery)) *TeamQuery {
query := (&UserClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withUsers = 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.Team.Query().
// GroupBy(team.FieldName).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *TeamQuery) GroupBy(field string, fields ...string) *TeamGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &TeamGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = team.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.Team.Query().
// Select(team.FieldName).
// Scan(ctx, &v)
func (_q *TeamQuery) Select(fields ...string) *TeamSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &TeamSelect{TeamQuery: _q}
sbuild.label = team.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a TeamSelect configured with the given aggregations.
func (_q *TeamQuery) Aggregate(fns ...AggregateFunc) *TeamSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *TeamQuery) 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 !team.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
}
if team.Policy == nil {
return errors.New("ent: uninitialized team.Policy (forgotten import ent/runtime?)")
}
if err := team.Policy.EvalQuery(ctx, _q); err != nil {
return err
}
return nil
}
func (_q *TeamQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Team, error) {
var (
nodes = []*Team{}
_spec = _q.querySpec()
loadedTypes = [2]bool{
_q.withTasks != nil,
_q.withUsers != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Team).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Team{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.withTasks; query != nil {
if err := _q.loadTasks(ctx, query, nodes,
func(n *Team) { n.Edges.Tasks = []*Task{} },
func(n *Team, e *Task) { n.Edges.Tasks = append(n.Edges.Tasks, e) }); err != nil {
return nil, err
}
}
if query := _q.withUsers; query != nil {
if err := _q.loadUsers(ctx, query, nodes,
func(n *Team) { n.Edges.Users = []*User{} },
func(n *Team, e *User) { n.Edges.Users = append(n.Edges.Users, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *TeamQuery) loadTasks(ctx context.Context, query *TaskQuery, nodes []*Team, init func(*Team), assign func(*Team, *Task)) error {
edgeIDs := make([]driver.Value, len(nodes))
byID := make(map[int]*Team)
nids := make(map[int]map[*Team]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(team.TasksTable)
s.Join(joinT).On(s.C(task.FieldID), joinT.C(team.TasksPrimaryKey[0]))
s.Where(sql.InValues(joinT.C(team.TasksPrimaryKey[1]), edgeIDs...))
columns := s.SelectedColumns()
s.Select(joinT.C(team.TasksPrimaryKey[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[*Team]struct{}{byID[outValue]: {}}
return assign(columns[1:], values[1:])
}
nids[inValue][byID[outValue]] = struct{}{}
return nil
}
})
})
neighbors, err := withInterceptors[[]*Task](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 "tasks" node returned %v`, n.ID)
}
for kn := range nodes {
assign(kn, n)
}
}
return nil
}
func (_q *TeamQuery) loadUsers(ctx context.Context, query *UserQuery, nodes []*Team, init func(*Team), assign func(*Team, *User)) error {
edgeIDs := make([]driver.Value, len(nodes))
byID := make(map[int]*Team)
nids := make(map[int]map[*Team]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(team.UsersTable)
s.Join(joinT).On(s.C(user.FieldID), joinT.C(team.UsersPrimaryKey[0]))
s.Where(sql.InValues(joinT.C(team.UsersPrimaryKey[1]), edgeIDs...))
columns := s.SelectedColumns()
s.Select(joinT.C(team.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[*Team]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 *TeamQuery) 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 *TeamQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(team.Table, team.Columns, sqlgraph.NewFieldSpec(team.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, team.FieldID)
for i := range fields {
if fields[i] != team.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 *TeamQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(team.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = team.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
}
// TeamGroupBy is the group-by builder for Team entities.
type TeamGroupBy struct {
selector
build *TeamQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *TeamGroupBy) Aggregate(fns ...AggregateFunc) *TeamGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *TeamGroupBy) 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[*TeamQuery, *TeamGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *TeamGroupBy) sqlScan(ctx context.Context, root *TeamQuery, 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)
}
// TeamSelect is the builder for selecting fields of Team entities.
type TeamSelect struct {
*TeamQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *TeamSelect) Aggregate(fns ...AggregateFunc) *TeamSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *TeamSelect) 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[*TeamQuery, *TeamSelect](ctx, _s.TeamQuery, _s, _s.inters, v)
}
func (_s *TeamSelect) sqlScan(ctx context.Context, root *TeamQuery, 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)
}

View File

@@ -0,0 +1,565 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/privacy/ent/predicate"
"entgo.io/ent/entc/integration/privacy/ent/task"
"entgo.io/ent/entc/integration/privacy/ent/team"
"entgo.io/ent/entc/integration/privacy/ent/user"
"entgo.io/ent/schema/field"
)
// TeamUpdate is the builder for updating Team entities.
type TeamUpdate struct {
config
hooks []Hook
mutation *TeamMutation
}
// Where appends a list predicates to the TeamUpdate builder.
func (_u *TeamUpdate) Where(ps ...predicate.Team) *TeamUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetName sets the "name" field.
func (_u *TeamUpdate) SetName(v string) *TeamUpdate {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *TeamUpdate) SetNillableName(v *string) *TeamUpdate {
if v != nil {
_u.SetName(*v)
}
return _u
}
// AddTaskIDs adds the "tasks" edge to the Task entity by IDs.
func (_u *TeamUpdate) AddTaskIDs(ids ...int) *TeamUpdate {
_u.mutation.AddTaskIDs(ids...)
return _u
}
// AddTasks adds the "tasks" edges to the Task entity.
func (_u *TeamUpdate) AddTasks(v ...*Task) *TeamUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddTaskIDs(ids...)
}
// AddUserIDs adds the "users" edge to the User entity by IDs.
func (_u *TeamUpdate) AddUserIDs(ids ...int) *TeamUpdate {
_u.mutation.AddUserIDs(ids...)
return _u
}
// AddUsers adds the "users" edges to the User entity.
func (_u *TeamUpdate) AddUsers(v ...*User) *TeamUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddUserIDs(ids...)
}
// Mutation returns the TeamMutation object of the builder.
func (_u *TeamUpdate) Mutation() *TeamMutation {
return _u.mutation
}
// ClearTasks clears all "tasks" edges to the Task entity.
func (_u *TeamUpdate) ClearTasks() *TeamUpdate {
_u.mutation.ClearTasks()
return _u
}
// RemoveTaskIDs removes the "tasks" edge to Task entities by IDs.
func (_u *TeamUpdate) RemoveTaskIDs(ids ...int) *TeamUpdate {
_u.mutation.RemoveTaskIDs(ids...)
return _u
}
// RemoveTasks removes "tasks" edges to Task entities.
func (_u *TeamUpdate) RemoveTasks(v ...*Task) *TeamUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveTaskIDs(ids...)
}
// ClearUsers clears all "users" edges to the User entity.
func (_u *TeamUpdate) ClearUsers() *TeamUpdate {
_u.mutation.ClearUsers()
return _u
}
// RemoveUserIDs removes the "users" edge to User entities by IDs.
func (_u *TeamUpdate) RemoveUserIDs(ids ...int) *TeamUpdate {
_u.mutation.RemoveUserIDs(ids...)
return _u
}
// RemoveUsers removes "users" edges to User entities.
func (_u *TeamUpdate) RemoveUsers(v ...*User) *TeamUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveUserIDs(ids...)
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *TeamUpdate) 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 *TeamUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *TeamUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *TeamUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *TeamUpdate) check() error {
if v, ok := _u.mutation.Name(); ok {
if err := team.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Team.name": %w`, err)}
}
}
return nil
}
func (_u *TeamUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(team.Table, team.Columns, sqlgraph.NewFieldSpec(team.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(team.FieldName, field.TypeString, value)
}
if _u.mutation.TasksCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: team.TasksTable,
Columns: team.TasksPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedTasksIDs(); len(nodes) > 0 && !_u.mutation.TasksCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: team.TasksTable,
Columns: team.TasksPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(task.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.TasksIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: team.TasksTable,
Columns: team.TasksPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(task.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.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: team.UsersTable,
Columns: team.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: team.UsersTable,
Columns: team.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: team.UsersTable,
Columns: team.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 _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{team.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// TeamUpdateOne is the builder for updating a single Team entity.
type TeamUpdateOne struct {
config
fields []string
hooks []Hook
mutation *TeamMutation
}
// SetName sets the "name" field.
func (_u *TeamUpdateOne) SetName(v string) *TeamUpdateOne {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *TeamUpdateOne) SetNillableName(v *string) *TeamUpdateOne {
if v != nil {
_u.SetName(*v)
}
return _u
}
// AddTaskIDs adds the "tasks" edge to the Task entity by IDs.
func (_u *TeamUpdateOne) AddTaskIDs(ids ...int) *TeamUpdateOne {
_u.mutation.AddTaskIDs(ids...)
return _u
}
// AddTasks adds the "tasks" edges to the Task entity.
func (_u *TeamUpdateOne) AddTasks(v ...*Task) *TeamUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddTaskIDs(ids...)
}
// AddUserIDs adds the "users" edge to the User entity by IDs.
func (_u *TeamUpdateOne) AddUserIDs(ids ...int) *TeamUpdateOne {
_u.mutation.AddUserIDs(ids...)
return _u
}
// AddUsers adds the "users" edges to the User entity.
func (_u *TeamUpdateOne) AddUsers(v ...*User) *TeamUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddUserIDs(ids...)
}
// Mutation returns the TeamMutation object of the builder.
func (_u *TeamUpdateOne) Mutation() *TeamMutation {
return _u.mutation
}
// ClearTasks clears all "tasks" edges to the Task entity.
func (_u *TeamUpdateOne) ClearTasks() *TeamUpdateOne {
_u.mutation.ClearTasks()
return _u
}
// RemoveTaskIDs removes the "tasks" edge to Task entities by IDs.
func (_u *TeamUpdateOne) RemoveTaskIDs(ids ...int) *TeamUpdateOne {
_u.mutation.RemoveTaskIDs(ids...)
return _u
}
// RemoveTasks removes "tasks" edges to Task entities.
func (_u *TeamUpdateOne) RemoveTasks(v ...*Task) *TeamUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveTaskIDs(ids...)
}
// ClearUsers clears all "users" edges to the User entity.
func (_u *TeamUpdateOne) ClearUsers() *TeamUpdateOne {
_u.mutation.ClearUsers()
return _u
}
// RemoveUserIDs removes the "users" edge to User entities by IDs.
func (_u *TeamUpdateOne) RemoveUserIDs(ids ...int) *TeamUpdateOne {
_u.mutation.RemoveUserIDs(ids...)
return _u
}
// RemoveUsers removes "users" edges to User entities.
func (_u *TeamUpdateOne) RemoveUsers(v ...*User) *TeamUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveUserIDs(ids...)
}
// Where appends a list predicates to the TeamUpdate builder.
func (_u *TeamUpdateOne) Where(ps ...predicate.Team) *TeamUpdateOne {
_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 *TeamUpdateOne) Select(field string, fields ...string) *TeamUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated Team entity.
func (_u *TeamUpdateOne) Save(ctx context.Context) (*Team, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *TeamUpdateOne) SaveX(ctx context.Context) *Team {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *TeamUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *TeamUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *TeamUpdateOne) check() error {
if v, ok := _u.mutation.Name(); ok {
if err := team.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Team.name": %w`, err)}
}
}
return nil
}
func (_u *TeamUpdateOne) sqlSave(ctx context.Context) (_node *Team, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(team.Table, team.Columns, sqlgraph.NewFieldSpec(team.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Team.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, team.FieldID)
for _, f := range fields {
if !team.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != team.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(team.FieldName, field.TypeString, value)
}
if _u.mutation.TasksCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: team.TasksTable,
Columns: team.TasksPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedTasksIDs(); len(nodes) > 0 && !_u.mutation.TasksCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: team.TasksTable,
Columns: team.TasksPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(task.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.TasksIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: team.TasksTable,
Columns: team.TasksPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(task.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.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: team.UsersTable,
Columns: team.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: team.UsersTable,
Columns: team.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: team.UsersTable,
Columns: team.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)
}
_node = &Team{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{team.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

View File

@@ -0,0 +1,220 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"sync"
"entgo.io/ent/dialect"
)
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
// Task is the client for interacting with the Task builders.
Task *TaskClient
// Team is the client for interacting with the Team builders.
Team *TeamClient
// User is the client for interacting with the User builders.
User *UserClient
// lazily loaded.
client *Client
clientOnce sync.Once
// ctx lives for the life of the transaction. It is
// the same context used by the underlying connection.
ctx context.Context
}
type (
// Committer is the interface that wraps the Commit method.
Committer interface {
Commit(context.Context, *Tx) error
}
// The CommitFunc type is an adapter to allow the use of ordinary
// function as a Committer. If f is a function with the appropriate
// signature, CommitFunc(f) is a Committer that calls f.
CommitFunc func(context.Context, *Tx) error
// CommitHook defines the "commit middleware". A function that gets a Committer
// and returns a Committer. For example:
//
// hook := func(next ent.Committer) ent.Committer {
// return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error {
// // Do some stuff before.
// if err := next.Commit(ctx, tx); err != nil {
// return err
// }
// // Do some stuff after.
// return nil
// })
// }
//
CommitHook func(Committer) Committer
)
// Commit calls f(ctx, m).
func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error {
return f(ctx, tx)
}
// Commit commits the transaction.
func (tx *Tx) Commit() error {
txDriver := tx.config.driver.(*txDriver)
var fn Committer = CommitFunc(func(context.Context, *Tx) error {
return txDriver.tx.Commit()
})
txDriver.mu.Lock()
hooks := append([]CommitHook(nil), txDriver.onCommit...)
txDriver.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
return fn.Commit(tx.ctx, tx)
}
// OnCommit adds a hook to call on commit.
func (tx *Tx) OnCommit(f CommitHook) {
txDriver := tx.config.driver.(*txDriver)
txDriver.mu.Lock()
txDriver.onCommit = append(txDriver.onCommit, f)
txDriver.mu.Unlock()
}
type (
// Rollbacker is the interface that wraps the Rollback method.
Rollbacker interface {
Rollback(context.Context, *Tx) error
}
// The RollbackFunc type is an adapter to allow the use of ordinary
// function as a Rollbacker. If f is a function with the appropriate
// signature, RollbackFunc(f) is a Rollbacker that calls f.
RollbackFunc func(context.Context, *Tx) error
// RollbackHook defines the "rollback middleware". A function that gets a Rollbacker
// and returns a Rollbacker. For example:
//
// hook := func(next ent.Rollbacker) ent.Rollbacker {
// return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error {
// // Do some stuff before.
// if err := next.Rollback(ctx, tx); err != nil {
// return err
// }
// // Do some stuff after.
// return nil
// })
// }
//
RollbackHook func(Rollbacker) Rollbacker
)
// Rollback calls f(ctx, m).
func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error {
return f(ctx, tx)
}
// Rollback rollbacks the transaction.
func (tx *Tx) Rollback() error {
txDriver := tx.config.driver.(*txDriver)
var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error {
return txDriver.tx.Rollback()
})
txDriver.mu.Lock()
hooks := append([]RollbackHook(nil), txDriver.onRollback...)
txDriver.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
return fn.Rollback(tx.ctx, tx)
}
// OnRollback adds a hook to call on rollback.
func (tx *Tx) OnRollback(f RollbackHook) {
txDriver := tx.config.driver.(*txDriver)
txDriver.mu.Lock()
txDriver.onRollback = append(txDriver.onRollback, f)
txDriver.mu.Unlock()
}
// Client returns a Client that binds to current transaction.
func (tx *Tx) Client() *Client {
tx.clientOnce.Do(func() {
tx.client = &Client{config: tx.config}
tx.client.init()
})
return tx.client
}
func (tx *Tx) init() {
tx.Task = NewTaskClient(tx.config)
tx.Team = NewTeamClient(tx.config)
tx.User = NewUserClient(tx.config)
}
// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation.
// The idea is to support transactions without adding any extra code to the builders.
// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance.
// Commit and Rollback are nop for the internal builders and the user must call one
// 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: Task.QueryXXX(), the query will be executed
// through the driver which created this transaction.
//
// Note that txDriver is not goroutine safe.
type txDriver struct {
// the driver we started the transaction from.
drv dialect.Driver
// tx is the underlying transaction.
tx dialect.Tx
// completion hooks.
mu sync.Mutex
onCommit []CommitHook
onRollback []RollbackHook
}
// newTx creates a new transactional driver.
func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) {
tx, err := drv.Tx(ctx)
if err != nil {
return nil, err
}
return &txDriver{tx: tx, drv: drv}, nil
}
// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls
// from the internal builders. Should be called only by the internal builders.
func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil }
// Dialect returns the dialect of the driver we started the transaction from.
func (tx *txDriver) Dialect() string { return tx.drv.Dialect() }
// Close is a nop close.
func (*txDriver) Close() error { return nil }
// Commit is a nop commit for the internal builders.
// User must call `Tx.Commit` in order to commit the transaction.
func (*txDriver) Commit() error { return nil }
// Rollback is a nop rollback for the internal builders.
// User must call `Tx.Rollback` in order to rollback the transaction.
func (*txDriver) Rollback() error { return nil }
// Exec calls tx.Exec.
func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error {
return tx.tx.Exec(ctx, query, args, v)
}
// Query calls tx.Query.
func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error {
return tx.tx.Query(ctx, query, args, v)
}
var _ dialect.Driver = (*txDriver)(nil)

View File

@@ -0,0 +1,160 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/entc/integration/privacy/ent/user"
)
// User is the model entity for the User schema.
type User 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"`
// Age holds the value of the "age" field.
Age uint `json:"age,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 {
// Teams holds the value of the teams edge.
Teams []*Team `json:"teams,omitempty"`
// Tasks holds the value of the tasks edge.
Tasks []*Task `json:"tasks,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// TeamsOrErr returns the Teams value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) TeamsOrErr() ([]*Team, error) {
if e.loadedTypes[0] {
return e.Teams, nil
}
return nil, &NotLoadedError{edge: "teams"}
}
// TasksOrErr returns the Tasks value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) TasksOrErr() ([]*Task, error) {
if e.loadedTypes[1] {
return e.Tasks, nil
}
return nil, &NotLoadedError{edge: "tasks"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*User) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case user.FieldID, user.FieldAge:
values[i] = new(sql.NullInt64)
case user.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 User fields.
func (_m *User) 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 user.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 user.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
}
case user.FieldAge:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field age", values[i])
} else if value.Valid {
_m.Age = uint(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 User.
// This includes values selected through modifiers, order, etc.
func (_m *User) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryTeams queries the "teams" edge of the User entity.
func (_m *User) QueryTeams() *TeamQuery {
return NewUserClient(_m.config).QueryTeams(_m)
}
// QueryTasks queries the "tasks" edge of the User entity.
func (_m *User) QueryTasks() *TaskQuery {
return NewUserClient(_m.config).QueryTasks(_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.
func (_m *User) Update() *UserUpdateOne {
return NewUserClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the User 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 *User) Unwrap() *User {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: User is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *User) String() string {
var builder strings.Builder
builder.WriteString("User(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("name=")
builder.WriteString(_m.Name)
builder.WriteString(", ")
builder.WriteString("age=")
builder.WriteString(fmt.Sprintf("%v", _m.Age))
builder.WriteByte(')')
return builder.String()
}
// Users is a parsable slice of User.
type Users []*User

View File

@@ -0,0 +1,503 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package user
import (
"context"
"fmt"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/entc/integration/privacy/ent/predicate"
)
// Mutation represents an operation that mutates the User nodes in the graph.
type Mutation struct {
op ent.Op
typ string
name *string
age *uint
addage *int
clearedFields map[string]struct{}
teams map[int]struct{}
removedteams map[int]struct{}
clearedteams bool
tasks map[int]struct{}
removedtasks map[int]struct{}
clearedtasks bool
predicates []predicate.User
}
// NewMutation creates a new Mutation for the User entity.
func NewMutation(op ent.Op) *Mutation {
return &Mutation{
op: op,
typ: "User",
clearedFields: make(map[string]struct{}),
}
}
// Predicates returns the list of predicates set on the mutation.
func (m *Mutation) Predicates() []predicate.User {
return m.predicates
}
// SetName sets the "name" field.
func (m *Mutation) SetName(s string) {
m.name = &s
}
// Name returns the value of the "name" field in the mutation.
func (m *Mutation) Name() (r string, exists bool) {
v := m.name
if v == nil {
return
}
return *v, true
}
// ResetName resets all changes to the "name" field.
func (m *Mutation) ResetName() {
m.name = nil
}
// SetAge sets the "age" field.
func (m *Mutation) SetAge(u uint) {
m.age = &u
m.addage = nil
}
// Age returns the value of the "age" field in the mutation.
func (m *Mutation) Age() (r uint, exists bool) {
v := m.age
if v == nil {
return
}
return *v, true
}
// AddAge adds u to the "age" field.
func (m *Mutation) AddAge(u int) {
if m.addage != nil {
*m.addage += u
} else {
m.addage = &u
}
}
// AddedAge returns the value that was added to the "age" field in this mutation.
func (m *Mutation) AddedAge() (r int, exists bool) {
v := m.addage
if v == nil {
return
}
return *v, true
}
// ClearAge clears the value of the "age" field.
func (m *Mutation) ClearAge() {
m.age = nil
m.addage = nil
m.clearedFields[FieldAge] = struct{}{}
}
// AgeCleared returns if the "age" field was cleared in this mutation.
func (m *Mutation) AgeCleared() bool {
_, ok := m.clearedFields[FieldAge]
return ok
}
// ResetAge resets all changes to the "age" field.
func (m *Mutation) ResetAge() {
m.age = nil
m.addage = nil
delete(m.clearedFields, FieldAge)
}
// AddTeamIDs adds the "teams" edge to the Team entity by ids.
func (m *Mutation) AddTeamIDs(ids ...int) {
if m.teams == nil {
m.teams = make(map[int]struct{})
}
for i := range ids {
m.teams[ids[i]] = struct{}{}
}
}
// ClearTeams clears the "teams" edge to the Team entity.
func (m *Mutation) ClearTeams() {
m.clearedteams = true
}
// TeamsCleared reports if the "teams" edge to the Team entity was cleared.
func (m *Mutation) TeamsCleared() bool {
return m.clearedteams
}
// RemoveTeamIDs removes the "teams" edge to the Team entity by IDs.
func (m *Mutation) RemoveTeamIDs(ids ...int) {
if m.removedteams == nil {
m.removedteams = make(map[int]struct{})
}
for i := range ids {
delete(m.teams, ids[i])
m.removedteams[ids[i]] = struct{}{}
}
}
// RemovedTeams returns the removed IDs of the "teams" edge to the Team entity.
func (m *Mutation) RemovedTeamsIDs() (ids []int) {
for id := range m.removedteams {
ids = append(ids, id)
}
return
}
// TeamsIDs returns the "teams" edge IDs in the mutation.
func (m *Mutation) TeamsIDs() (ids []int) {
for id := range m.teams {
ids = append(ids, id)
}
return
}
// ResetTeams resets all changes to the "teams" edge.
func (m *Mutation) ResetTeams() {
m.teams = nil
m.clearedteams = false
m.removedteams = nil
}
// AddTaskIDs adds the "tasks" edge to the Task entity by ids.
func (m *Mutation) AddTaskIDs(ids ...int) {
if m.tasks == nil {
m.tasks = make(map[int]struct{})
}
for i := range ids {
m.tasks[ids[i]] = struct{}{}
}
}
// ClearTasks clears the "tasks" edge to the Task entity.
func (m *Mutation) ClearTasks() {
m.clearedtasks = true
}
// TasksCleared reports if the "tasks" edge to the Task entity was cleared.
func (m *Mutation) TasksCleared() bool {
return m.clearedtasks
}
// RemoveTaskIDs removes the "tasks" edge to the Task entity by IDs.
func (m *Mutation) RemoveTaskIDs(ids ...int) {
if m.removedtasks == nil {
m.removedtasks = make(map[int]struct{})
}
for i := range ids {
delete(m.tasks, ids[i])
m.removedtasks[ids[i]] = struct{}{}
}
}
// RemovedTasks returns the removed IDs of the "tasks" edge to the Task entity.
func (m *Mutation) RemovedTasksIDs() (ids []int) {
for id := range m.removedtasks {
ids = append(ids, id)
}
return
}
// TasksIDs returns the "tasks" edge IDs in the mutation.
func (m *Mutation) TasksIDs() (ids []int) {
for id := range m.tasks {
ids = append(ids, id)
}
return
}
// ResetTasks resets all changes to the "tasks" edge.
func (m *Mutation) ResetTasks() {
m.tasks = nil
m.clearedtasks = false
m.removedtasks = nil
}
// Where appends a list predicates to the Mutation builder.
func (m *Mutation) Where(ps ...predicate.User) {
m.predicates = append(m.predicates, ps...)
}
// WhereP appends storage-level predicates to the Mutation builder. Using this method,
// users can use type-assertion to append predicates that do not depend on any generated package.
func (m *Mutation) WhereP(ps ...func(*sql.Selector)) {
p := make([]predicate.User, len(ps))
for i := range ps {
p[i] = ps[i]
}
m.Where(p...)
}
// Op returns the operation name.
func (m *Mutation) Op() ent.Op {
return m.op
}
// SetOp allows setting the mutation operation.
func (m *Mutation) SetOp(op ent.Op) {
m.op = op
}
// Type returns the node type of this mutation (User).
func (m *Mutation) Type() string {
return m.typ
}
// Fields returns all fields that were changed during this mutation. Note that in
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *Mutation) Fields() []string {
fields := make([]string, 0, 2)
if m.name != nil {
fields = append(fields, FieldName)
}
if m.age != nil {
fields = append(fields, FieldAge)
}
return fields
}
// Field returns the value of a field with the given name. The second boolean
// return value indicates that this field was not set, or was not defined in the
// schema.
func (m *Mutation) Field(name string) (ent.Value, bool) {
switch name {
case FieldName:
return m.Name()
case FieldAge:
return m.Age()
}
return nil, false
}
// OldField returns the old value of the field from the database. An error is
// returned if the mutation operation is not UpdateOne, or the query to the
// database failed.
func (m *Mutation) OldField(ctx context.Context, name string) (ent.Value, error) {
return nil, fmt.Errorf("unknown User field %s", name)
}
// SetField sets the value of a field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *Mutation) SetField(name string, value ent.Value) error {
switch name {
case FieldName:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetName(v)
return nil
case FieldAge:
v, ok := value.(uint)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetAge(v)
return nil
}
return fmt.Errorf("unknown User field %s", name)
}
// AddedFields returns all numeric fields that were incremented/decremented during
// this mutation.
func (m *Mutation) AddedFields() []string {
var fields []string
if m.addage != nil {
fields = append(fields, FieldAge)
}
return fields
}
// AddedField returns the numeric value that was incremented/decremented on a field
// with the given name. The second boolean return value indicates that this field
// was not set, or was not defined in the schema.
func (m *Mutation) AddedField(name string) (ent.Value, bool) {
switch name {
case FieldAge:
return m.AddedAge()
}
return nil, false
}
// AddField adds the value to the field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *Mutation) AddField(name string, value ent.Value) error {
switch name {
case FieldAge:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.AddAge(v)
return nil
}
return fmt.Errorf("unknown User numeric field %s", name)
}
// ClearedFields returns all nullable fields that were cleared during this
// mutation.
func (m *Mutation) ClearedFields() []string {
var fields []string
if m.FieldCleared(FieldAge) {
fields = append(fields, FieldAge)
}
return fields
}
// FieldCleared returns a boolean indicating if a field with the given name was
// cleared in this mutation.
func (m *Mutation) FieldCleared(name string) bool {
_, ok := m.clearedFields[name]
return ok
}
// ClearField clears the value of the field with the given name. It returns an
// error if the field is not defined in the schema.
func (m *Mutation) ClearField(name string) error {
switch name {
case FieldAge:
m.ClearAge()
return nil
}
return fmt.Errorf("unknown User nullable field %s", name)
}
// ResetField resets all changes in the mutation for the field with the given name.
// It returns an error if the field is not defined in the schema.
func (m *Mutation) ResetField(name string) error {
switch name {
case FieldName:
m.ResetName()
return nil
case FieldAge:
m.ResetAge()
return nil
}
return fmt.Errorf("unknown User field %s", name)
}
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *Mutation) AddedEdges() []string {
edges := make([]string, 0, 2)
if m.teams != nil {
edges = append(edges, EdgeTeams)
}
if m.tasks != nil {
edges = append(edges, EdgeTasks)
}
return edges
}
// AddedIDs returns all IDs (to other nodes) that were added for the given edge
// name in this mutation.
func (m *Mutation) AddedIDs(name string) []ent.Value {
switch name {
case EdgeTeams:
ids := make([]ent.Value, 0, len(m.teams))
for id := range m.teams {
ids = append(ids, id)
}
return ids
case EdgeTasks:
ids := make([]ent.Value, 0, len(m.tasks))
for id := range m.tasks {
ids = append(ids, id)
}
return ids
}
return nil
}
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *Mutation) RemovedEdges() []string {
edges := make([]string, 0, 2)
if m.removedteams != nil {
edges = append(edges, EdgeTeams)
}
if m.removedtasks != nil {
edges = append(edges, EdgeTasks)
}
return edges
}
// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
// the given name in this mutation.
func (m *Mutation) RemovedIDs(name string) []ent.Value {
switch name {
case EdgeTeams:
ids := make([]ent.Value, 0, len(m.removedteams))
for id := range m.removedteams {
ids = append(ids, id)
}
return ids
case EdgeTasks:
ids := make([]ent.Value, 0, len(m.removedtasks))
for id := range m.removedtasks {
ids = append(ids, id)
}
return ids
}
return nil
}
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *Mutation) ClearedEdges() []string {
edges := make([]string, 0, 2)
if m.clearedteams {
edges = append(edges, EdgeTeams)
}
if m.clearedtasks {
edges = append(edges, EdgeTasks)
}
return edges
}
// EdgeCleared returns a boolean which indicates if the edge with the given name
// was cleared in this mutation.
func (m *Mutation) EdgeCleared(name string) bool {
switch name {
case EdgeTeams:
return m.clearedteams
case EdgeTasks:
return m.clearedtasks
}
return false
}
// ClearEdge clears the value of the edge with the given name. It returns an error
// if that edge is not defined in the schema.
func (m *Mutation) ClearEdge(name string) error {
switch name {
}
return fmt.Errorf("unknown User unique edge %s", name)
}
// ResetEdge resets all changes to the edge with the given name in this mutation.
// It returns an error if the edge is not defined in the schema.
func (m *Mutation) ResetEdge(name string) error {
switch name {
case EdgeTeams:
m.ResetTeams()
return nil
case EdgeTasks:
m.ResetTasks()
return nil
}
return fmt.Errorf("unknown User edge %s", name)
}

View File

@@ -0,0 +1,137 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package user
import (
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the user type in the database.
Label = "user"
// 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"
// FieldAge holds the string denoting the age field in the database.
FieldAge = "age"
// EdgeTeams holds the string denoting the teams edge name in mutations.
EdgeTeams = "teams"
// EdgeTasks holds the string denoting the tasks edge name in mutations.
EdgeTasks = "tasks"
// Table holds the table name of the user in the database.
Table = "users"
// TeamsTable is the table that holds the teams relation/edge. The primary key declared below.
TeamsTable = "user_teams"
// TeamsInverseTable is the table name for the Team entity.
// It exists in this package in order to avoid circular dependency with the "team" package.
TeamsInverseTable = "teams"
// TasksTable is the table that holds the tasks relation/edge.
TasksTable = "tasks"
// TasksInverseTable is the table name for the Task entity.
// It exists in this package in order to avoid circular dependency with the "task" package.
TasksInverseTable = "tasks"
// TasksColumn is the table column denoting the tasks relation/edge.
TasksColumn = "user_tasks"
)
// Columns holds all SQL columns for user fields.
var Columns = []string{
FieldID,
FieldName,
FieldAge,
}
var (
// TeamsPrimaryKey and TeamsColumn2 are the table columns denoting the
// primary key for the teams relation (M2M).
TeamsPrimaryKey = []string{"user_id", "team_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
}
// Note that the variables below are initialized by the runtime
// package on the initialization of the application. Therefore,
// it should be imported in the main as follows:
//
// import _ "entgo.io/ent/entc/integration/privacy/ent/runtime"
var (
Hooks [1]ent.Hook
Policy ent.Policy
// NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error
)
// OrderOption defines the ordering options for the User 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()
}
// ByAge orders the results by the age field.
func ByAge(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldAge, opts...).ToFunc()
}
// ByTeamsCount orders the results by teams count.
func ByTeamsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newTeamsStep(), opts...)
}
}
// ByTeams orders the results by teams terms.
func ByTeams(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newTeamsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByTasksCount orders the results by tasks count.
func ByTasksCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newTasksStep(), opts...)
}
}
// ByTasks orders the results by tasks terms.
func ByTasks(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newTasksStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
func newTeamsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(TeamsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, TeamsTable, TeamsPrimaryKey...),
)
}
func newTasksStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(TasksInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, TasksTable, TasksColumn),
)
}

View File

@@ -0,0 +1,244 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package user
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/privacy/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.User {
return predicate.User(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.User {
return predicate.User(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.User {
return predicate.User(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.User {
return predicate.User(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.User {
return predicate.User(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.User {
return predicate.User(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.User {
return predicate.User(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.User {
return predicate.User(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.User {
return predicate.User(sql.FieldLTE(FieldID, id))
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldName, v))
}
// Age applies equality check predicate on the "age" field. It's identical to AgeEQ.
func Age(v uint) predicate.User {
return predicate.User(sql.FieldEQ(FieldAge, v))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldName, v))
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.User {
return predicate.User(sql.FieldNEQ(FieldName, v))
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.User {
return predicate.User(sql.FieldIn(FieldName, vs...))
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.User {
return predicate.User(sql.FieldNotIn(FieldName, vs...))
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.User {
return predicate.User(sql.FieldGT(FieldName, v))
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.User {
return predicate.User(sql.FieldGTE(FieldName, v))
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.User {
return predicate.User(sql.FieldLT(FieldName, v))
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.User {
return predicate.User(sql.FieldLTE(FieldName, v))
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.User {
return predicate.User(sql.FieldContains(FieldName, v))
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.User {
return predicate.User(sql.FieldHasPrefix(FieldName, v))
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.User {
return predicate.User(sql.FieldHasSuffix(FieldName, v))
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.User {
return predicate.User(sql.FieldEqualFold(FieldName, v))
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.User {
return predicate.User(sql.FieldContainsFold(FieldName, v))
}
// AgeEQ applies the EQ predicate on the "age" field.
func AgeEQ(v uint) predicate.User {
return predicate.User(sql.FieldEQ(FieldAge, v))
}
// AgeNEQ applies the NEQ predicate on the "age" field.
func AgeNEQ(v uint) predicate.User {
return predicate.User(sql.FieldNEQ(FieldAge, v))
}
// AgeIn applies the In predicate on the "age" field.
func AgeIn(vs ...uint) predicate.User {
return predicate.User(sql.FieldIn(FieldAge, vs...))
}
// AgeNotIn applies the NotIn predicate on the "age" field.
func AgeNotIn(vs ...uint) predicate.User {
return predicate.User(sql.FieldNotIn(FieldAge, vs...))
}
// AgeGT applies the GT predicate on the "age" field.
func AgeGT(v uint) predicate.User {
return predicate.User(sql.FieldGT(FieldAge, v))
}
// AgeGTE applies the GTE predicate on the "age" field.
func AgeGTE(v uint) predicate.User {
return predicate.User(sql.FieldGTE(FieldAge, v))
}
// AgeLT applies the LT predicate on the "age" field.
func AgeLT(v uint) predicate.User {
return predicate.User(sql.FieldLT(FieldAge, v))
}
// AgeLTE applies the LTE predicate on the "age" field.
func AgeLTE(v uint) predicate.User {
return predicate.User(sql.FieldLTE(FieldAge, v))
}
// AgeIsNil applies the IsNil predicate on the "age" field.
func AgeIsNil() predicate.User {
return predicate.User(sql.FieldIsNull(FieldAge))
}
// AgeNotNil applies the NotNil predicate on the "age" field.
func AgeNotNil() predicate.User {
return predicate.User(sql.FieldNotNull(FieldAge))
}
// HasTeams applies the HasEdge predicate on the "teams" edge.
func HasTeams() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, TeamsTable, TeamsPrimaryKey...),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasTeamsWith applies the HasEdge predicate on the "teams" edge with a given conditions (other predicates).
func HasTeamsWith(preds ...predicate.Team) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newTeamsStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasTasks applies the HasEdge predicate on the "tasks" edge.
func HasTasks() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, TasksTable, TasksColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasTasksWith applies the HasEdge predicate on the "tasks" edge with a given conditions (other predicates).
func HasTasksWith(preds ...predicate.Task) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newTasksStep()
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...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.User) predicate.User {
return predicate.User(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.User) predicate.User {
return predicate.User(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,274 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/privacy/ent/task"
"entgo.io/ent/entc/integration/privacy/ent/team"
"entgo.io/ent/entc/integration/privacy/ent/user"
"entgo.io/ent/schema/field"
)
// UserCreate is the builder for creating a User entity.
type UserCreate struct {
config
mutation *UserMutation
hooks []Hook
}
// SetName sets the "name" field.
func (_c *UserCreate) SetName(v string) *UserCreate {
_c.mutation.SetName(v)
return _c
}
// SetAge sets the "age" field.
func (_c *UserCreate) SetAge(v uint) *UserCreate {
_c.mutation.SetAge(v)
return _c
}
// SetNillableAge sets the "age" field if the given value is not nil.
func (_c *UserCreate) SetNillableAge(v *uint) *UserCreate {
if v != nil {
_c.SetAge(*v)
}
return _c
}
// AddTeamIDs adds the "teams" edge to the Team entity by IDs.
func (_c *UserCreate) AddTeamIDs(ids ...int) *UserCreate {
_c.mutation.AddTeamIDs(ids...)
return _c
}
// AddTeams adds the "teams" edges to the Team entity.
func (_c *UserCreate) AddTeams(v ...*Team) *UserCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddTeamIDs(ids...)
}
// AddTaskIDs adds the "tasks" edge to the Task entity by IDs.
func (_c *UserCreate) AddTaskIDs(ids ...int) *UserCreate {
_c.mutation.AddTaskIDs(ids...)
return _c
}
// AddTasks adds the "tasks" edges to the Task entity.
func (_c *UserCreate) AddTasks(v ...*Task) *UserCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddTaskIDs(ids...)
}
// Mutation returns the UserMutation object of the builder.
func (_c *UserCreate) Mutation() *UserMutation {
return _c.mutation
}
// Save creates the User in the database.
func (_c *UserCreate) Save(ctx context.Context) (*User, error) {
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *UserCreate) SaveX(ctx context.Context) *User {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *UserCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *UserCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *UserCreate) check() error {
if _, ok := _c.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "User.name"`)}
}
if v, ok := _c.mutation.Name(); ok {
if err := user.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "User.name": %w`, err)}
}
}
return nil
}
func (_c *UserCreate) sqlSave(ctx context.Context) (*User, 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 *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) {
var (
_node = &User{config: _c.config}
_spec = sqlgraph.NewCreateSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt))
)
if value, ok := _c.mutation.Name(); ok {
_spec.SetField(user.FieldName, field.TypeString, value)
_node.Name = value
}
if value, ok := _c.mutation.Age(); ok {
_spec.SetField(user.FieldAge, field.TypeUint, value)
_node.Age = value
}
if nodes := _c.mutation.TeamsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.TeamsTable,
Columns: user.TeamsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(team.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.TasksIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.TasksTable,
Columns: []string{user.TasksColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// UserCreateBulk is the builder for creating many User entities in bulk.
type UserCreateBulk struct {
config
err error
builders []*UserCreate
}
// Save creates the User entities in the database.
func (_c *UserCreateBulk) Save(ctx context.Context) ([]*User, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*User, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*UserMutation)
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 *UserCreateBulk) SaveX(ctx context.Context) []*User {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *UserCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *UserCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,92 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/privacy/ent/predicate"
"entgo.io/ent/entc/integration/privacy/ent/user"
"entgo.io/ent/schema/field"
)
// UserDelete is the builder for deleting a User entity.
type UserDelete struct {
config
hooks []Hook
mutation *UserMutation
}
// Where appends a list predicates to the UserDelete builder.
func (_d *UserDelete) Where(ps ...predicate.User) *UserDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *UserDelete) 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 *UserDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *UserDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(user.Table, sqlgraph.NewFieldSpec(user.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
}
// UserDeleteOne is the builder for deleting a single User entity.
type UserDeleteOne struct {
_d *UserDelete
}
// Where appends a list predicates to the UserDelete builder.
func (_d *UserDeleteOne) Where(ps ...predicate.User) *UserDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *UserDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{user.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *UserDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,723 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"database/sql/driver"
"errors"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/privacy/ent/predicate"
"entgo.io/ent/entc/integration/privacy/ent/task"
"entgo.io/ent/entc/integration/privacy/ent/team"
"entgo.io/ent/entc/integration/privacy/ent/user"
"entgo.io/ent/schema/field"
)
// UserQuery is the builder for querying User entities.
type UserQuery struct {
config
ctx *QueryContext
order []user.OrderOption
inters []Interceptor
predicates []predicate.User
withTeams *TeamQuery
withTasks *TaskQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the UserQuery builder.
func (_q *UserQuery) Where(ps ...predicate.User) *UserQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *UserQuery) Limit(limit int) *UserQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *UserQuery) Offset(offset int) *UserQuery {
_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 *UserQuery) Unique(unique bool) *UserQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *UserQuery) Order(o ...user.OrderOption) *UserQuery {
_q.order = append(_q.order, o...)
return _q
}
// QueryTeams chains the current query on the "teams" edge.
func (_q *UserQuery) QueryTeams() *TeamQuery {
query := (&TeamClient{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(team.Table, team.FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, user.TeamsTable, user.TeamsPrimaryKey...),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryTasks chains the current query on the "tasks" edge.
func (_q *UserQuery) QueryTasks() *TaskQuery {
query := (&TaskClient{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(task.Table, task.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, user.TasksTable, user.TasksColumn),
)
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) {
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{user.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *UserQuery) FirstX(ctx context.Context) *User {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first User ID from the query.
// Returns a *NotFoundError when no User ID was found.
func (_q *UserQuery) 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{user.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *UserQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single User entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one User entity is found.
// Returns a *NotFoundError when no User entities are found.
func (_q *UserQuery) Only(ctx context.Context) (*User, 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{user.Label}
default:
return nil, &NotSingularError{user.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *UserQuery) OnlyX(ctx context.Context) *User {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only User ID in the query.
// Returns a *NotSingularError when more than one User ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *UserQuery) 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{user.Label}
default:
err = &NotSingularError{user.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *UserQuery) 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 Users.
func (_q *UserQuery) All(ctx context.Context) ([]*User, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*User, *UserQuery]()
return withInterceptors[[]*User](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *UserQuery) AllX(ctx context.Context) []*User {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of User IDs.
func (_q *UserQuery) 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(user.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *UserQuery) 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 *UserQuery) 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[*UserQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *UserQuery) 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 *UserQuery) 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 *UserQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the UserQuery 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 *UserQuery) Clone() *UserQuery {
if _q == nil {
return nil
}
return &UserQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]user.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.User{}, _q.predicates...),
withTeams: _q.withTeams.Clone(),
withTasks: _q.withTasks.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// WithTeams tells the query-builder to eager-load the nodes that are connected to
// the "teams" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *UserQuery) WithTeams(opts ...func(*TeamQuery)) *UserQuery {
query := (&TeamClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withTeams = query
return _q
}
// WithTasks tells the query-builder to eager-load the nodes that are connected to
// the "tasks" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *UserQuery) WithTasks(opts ...func(*TaskQuery)) *UserQuery {
query := (&TaskClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withTasks = 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.User.Query().
// GroupBy(user.FieldName).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *UserQuery) GroupBy(field string, fields ...string) *UserGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &UserGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = user.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.User.Query().
// Select(user.FieldName).
// Scan(ctx, &v)
func (_q *UserQuery) Select(fields ...string) *UserSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &UserSelect{UserQuery: _q}
sbuild.label = user.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a UserSelect configured with the given aggregations.
func (_q *UserQuery) Aggregate(fns ...AggregateFunc) *UserSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *UserQuery) 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 !user.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
}
if user.Policy == nil {
return errors.New("ent: uninitialized user.Policy (forgotten import ent/runtime?)")
}
if err := user.Policy.EvalQuery(ctx, _q); err != nil {
return err
}
return nil
}
func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, error) {
var (
nodes = []*User{}
_spec = _q.querySpec()
loadedTypes = [2]bool{
_q.withTeams != nil,
_q.withTasks != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*User).scanValues(nil, columns)
}
_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 {
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.withTeams; query != nil {
if err := _q.loadTeams(ctx, query, nodes,
func(n *User) { n.Edges.Teams = []*Team{} },
func(n *User, e *Team) { n.Edges.Teams = append(n.Edges.Teams, e) }); err != nil {
return nil, err
}
}
if query := _q.withTasks; query != nil {
if err := _q.loadTasks(ctx, query, nodes,
func(n *User) { n.Edges.Tasks = []*Task{} },
func(n *User, e *Task) { n.Edges.Tasks = append(n.Edges.Tasks, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *UserQuery) loadTeams(ctx context.Context, query *TeamQuery, nodes []*User, init func(*User), assign func(*User, *Team)) 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.TeamsTable)
s.Join(joinT).On(s.C(team.FieldID), joinT.C(user.TeamsPrimaryKey[1]))
s.Where(sql.InValues(joinT.C(user.TeamsPrimaryKey[0]), edgeIDs...))
columns := s.SelectedColumns()
s.Select(joinT.C(user.TeamsPrimaryKey[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[[]*Team](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 "teams" node returned %v`, n.ID)
}
for kn := range nodes {
assign(kn, n)
}
}
return nil
}
func (_q *UserQuery) loadTasks(ctx context.Context, query *TaskQuery, nodes []*User, init func(*User), assign func(*User, *Task)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[int]*User)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.Task(func(s *sql.Selector) {
s.Where(sql.InValues(s.C(user.TasksColumn), fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.user_tasks
if fk == nil {
return fmt.Errorf(`foreign-key "user_tasks" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected referenced foreign-key "user_tasks" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (_q *UserQuery) 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 *UserQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.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, user.FieldID)
for i := range fields {
if fields[i] != user.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 *UserQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(user.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = user.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
}
// UserGroupBy is the group-by builder for User entities.
type UserGroupBy struct {
selector
build *UserQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *UserGroupBy) Aggregate(fns ...AggregateFunc) *UserGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *UserGroupBy) 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[*UserQuery, *UserGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *UserGroupBy) sqlScan(ctx context.Context, root *UserQuery, 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)
}
// UserSelect is the builder for selecting fields of User entities.
type UserSelect struct {
*UserQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *UserSelect) Aggregate(fns ...AggregateFunc) *UserSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *UserSelect) 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[*UserQuery, *UserSelect](ctx, _s.UserQuery, _s, _s.inters, v)
}
func (_s *UserSelect) sqlScan(ctx context.Context, root *UserQuery, 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)
}

View File

@@ -0,0 +1,577 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entc/integration/privacy/ent/predicate"
"entgo.io/ent/entc/integration/privacy/ent/task"
"entgo.io/ent/entc/integration/privacy/ent/team"
"entgo.io/ent/entc/integration/privacy/ent/user"
"entgo.io/ent/schema/field"
)
// UserUpdate is the builder for updating User entities.
type UserUpdate struct {
config
hooks []Hook
mutation *UserMutation
}
// Where appends a list predicates to the UserUpdate builder.
func (_u *UserUpdate) Where(ps ...predicate.User) *UserUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetAge sets the "age" field.
func (_u *UserUpdate) SetAge(v uint) *UserUpdate {
_u.mutation.ResetAge()
_u.mutation.SetAge(v)
return _u
}
// SetNillableAge sets the "age" field if the given value is not nil.
func (_u *UserUpdate) SetNillableAge(v *uint) *UserUpdate {
if v != nil {
_u.SetAge(*v)
}
return _u
}
// AddAge adds value to the "age" field.
func (_u *UserUpdate) AddAge(v int) *UserUpdate {
_u.mutation.AddAge(v)
return _u
}
// ClearAge clears the value of the "age" field.
func (_u *UserUpdate) ClearAge() *UserUpdate {
_u.mutation.ClearAge()
return _u
}
// AddTeamIDs adds the "teams" edge to the Team entity by IDs.
func (_u *UserUpdate) AddTeamIDs(ids ...int) *UserUpdate {
_u.mutation.AddTeamIDs(ids...)
return _u
}
// AddTeams adds the "teams" edges to the Team entity.
func (_u *UserUpdate) AddTeams(v ...*Team) *UserUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddTeamIDs(ids...)
}
// AddTaskIDs adds the "tasks" edge to the Task entity by IDs.
func (_u *UserUpdate) AddTaskIDs(ids ...int) *UserUpdate {
_u.mutation.AddTaskIDs(ids...)
return _u
}
// AddTasks adds the "tasks" edges to the Task entity.
func (_u *UserUpdate) AddTasks(v ...*Task) *UserUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddTaskIDs(ids...)
}
// Mutation returns the UserMutation object of the builder.
func (_u *UserUpdate) Mutation() *UserMutation {
return _u.mutation
}
// ClearTeams clears all "teams" edges to the Team entity.
func (_u *UserUpdate) ClearTeams() *UserUpdate {
_u.mutation.ClearTeams()
return _u
}
// RemoveTeamIDs removes the "teams" edge to Team entities by IDs.
func (_u *UserUpdate) RemoveTeamIDs(ids ...int) *UserUpdate {
_u.mutation.RemoveTeamIDs(ids...)
return _u
}
// RemoveTeams removes "teams" edges to Team entities.
func (_u *UserUpdate) RemoveTeams(v ...*Team) *UserUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveTeamIDs(ids...)
}
// ClearTasks clears all "tasks" edges to the Task entity.
func (_u *UserUpdate) ClearTasks() *UserUpdate {
_u.mutation.ClearTasks()
return _u
}
// RemoveTaskIDs removes the "tasks" edge to Task entities by IDs.
func (_u *UserUpdate) RemoveTaskIDs(ids ...int) *UserUpdate {
_u.mutation.RemoveTaskIDs(ids...)
return _u
}
// RemoveTasks removes "tasks" edges to Task entities.
func (_u *UserUpdate) RemoveTasks(v ...*Task) *UserUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveTaskIDs(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) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *UserUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *UserUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *UserUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
func (_u *UserUpdate) sqlSave(ctx context.Context) (_node int, err error) {
_spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.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.Age(); ok {
_spec.SetField(user.FieldAge, field.TypeUint, value)
}
if value, ok := _u.mutation.AddedAge(); ok {
_spec.AddField(user.FieldAge, field.TypeUint, value)
}
if _u.mutation.AgeCleared() {
_spec.ClearField(user.FieldAge, field.TypeUint)
}
if _u.mutation.TeamsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.TeamsTable,
Columns: user.TeamsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(team.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedTeamsIDs(); len(nodes) > 0 && !_u.mutation.TeamsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.TeamsTable,
Columns: user.TeamsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(team.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.TeamsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.TeamsTable,
Columns: user.TeamsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(team.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.TasksCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.TasksTable,
Columns: []string{user.TasksColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedTasksIDs(); len(nodes) > 0 && !_u.mutation.TasksCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.TasksTable,
Columns: []string{user.TasksColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(task.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.TasksIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.TasksTable,
Columns: []string{user.TasksColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(task.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}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// UserUpdateOne is the builder for updating a single User entity.
type UserUpdateOne struct {
config
fields []string
hooks []Hook
mutation *UserMutation
}
// SetAge sets the "age" field.
func (_u *UserUpdateOne) SetAge(v uint) *UserUpdateOne {
_u.mutation.ResetAge()
_u.mutation.SetAge(v)
return _u
}
// SetNillableAge sets the "age" field if the given value is not nil.
func (_u *UserUpdateOne) SetNillableAge(v *uint) *UserUpdateOne {
if v != nil {
_u.SetAge(*v)
}
return _u
}
// AddAge adds value to the "age" field.
func (_u *UserUpdateOne) AddAge(v int) *UserUpdateOne {
_u.mutation.AddAge(v)
return _u
}
// ClearAge clears the value of the "age" field.
func (_u *UserUpdateOne) ClearAge() *UserUpdateOne {
_u.mutation.ClearAge()
return _u
}
// AddTeamIDs adds the "teams" edge to the Team entity by IDs.
func (_u *UserUpdateOne) AddTeamIDs(ids ...int) *UserUpdateOne {
_u.mutation.AddTeamIDs(ids...)
return _u
}
// AddTeams adds the "teams" edges to the Team entity.
func (_u *UserUpdateOne) AddTeams(v ...*Team) *UserUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddTeamIDs(ids...)
}
// AddTaskIDs adds the "tasks" edge to the Task entity by IDs.
func (_u *UserUpdateOne) AddTaskIDs(ids ...int) *UserUpdateOne {
_u.mutation.AddTaskIDs(ids...)
return _u
}
// AddTasks adds the "tasks" edges to the Task entity.
func (_u *UserUpdateOne) AddTasks(v ...*Task) *UserUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddTaskIDs(ids...)
}
// Mutation returns the UserMutation object of the builder.
func (_u *UserUpdateOne) Mutation() *UserMutation {
return _u.mutation
}
// ClearTeams clears all "teams" edges to the Team entity.
func (_u *UserUpdateOne) ClearTeams() *UserUpdateOne {
_u.mutation.ClearTeams()
return _u
}
// RemoveTeamIDs removes the "teams" edge to Team entities by IDs.
func (_u *UserUpdateOne) RemoveTeamIDs(ids ...int) *UserUpdateOne {
_u.mutation.RemoveTeamIDs(ids...)
return _u
}
// RemoveTeams removes "teams" edges to Team entities.
func (_u *UserUpdateOne) RemoveTeams(v ...*Team) *UserUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveTeamIDs(ids...)
}
// ClearTasks clears all "tasks" edges to the Task entity.
func (_u *UserUpdateOne) ClearTasks() *UserUpdateOne {
_u.mutation.ClearTasks()
return _u
}
// RemoveTaskIDs removes the "tasks" edge to Task entities by IDs.
func (_u *UserUpdateOne) RemoveTaskIDs(ids ...int) *UserUpdateOne {
_u.mutation.RemoveTaskIDs(ids...)
return _u
}
// RemoveTasks removes "tasks" edges to Task entities.
func (_u *UserUpdateOne) RemoveTasks(v ...*Task) *UserUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveTaskIDs(ids...)
}
// Where appends a list predicates to the UserUpdate builder.
func (_u *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne {
_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 *UserUpdateOne) Select(field string, fields ...string) *UserUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated User entity.
func (_u *UserUpdateOne) Save(ctx context.Context) (*User, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *UserUpdateOne) SaveX(ctx context.Context) *User {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *UserUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *UserUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
func (_u *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) {
_spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "User.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, user.FieldID)
for _, f := range fields {
if !user.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != user.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.Age(); ok {
_spec.SetField(user.FieldAge, field.TypeUint, value)
}
if value, ok := _u.mutation.AddedAge(); ok {
_spec.AddField(user.FieldAge, field.TypeUint, value)
}
if _u.mutation.AgeCleared() {
_spec.ClearField(user.FieldAge, field.TypeUint)
}
if _u.mutation.TeamsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.TeamsTable,
Columns: user.TeamsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(team.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedTeamsIDs(); len(nodes) > 0 && !_u.mutation.TeamsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.TeamsTable,
Columns: user.TeamsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(team.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.TeamsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.TeamsTable,
Columns: user.TeamsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(team.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.TasksCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.TasksTable,
Columns: []string{user.TasksColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedTasksIDs(); len(nodes) > 0 && !_u.mutation.TasksCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.TasksTable,
Columns: []string{user.TasksColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(task.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.TasksIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.TasksTable,
Columns: []string{user.TasksColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(task.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
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{user.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

View File

@@ -0,0 +1,82 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package privacy
import (
"context"
"errors"
"testing"
"entgo.io/ent/entc/integration/privacy/ent/enttest"
"entgo.io/ent/entc/integration/privacy/ent/privacy"
"entgo.io/ent/entc/integration/privacy/ent/task"
"entgo.io/ent/entc/integration/privacy/rule"
"entgo.io/ent/entc/integration/privacy/viewer"
_ "github.com/mattn/go-sqlite3"
"github.com/stretchr/testify/require"
)
func TestPrivacyRules(t *testing.T) {
client := enttest.Open(t, "sqlite3",
"file:ent?mode=memory&cache=shared&_fk=1",
)
defer client.Close()
logf := rule.SetMutationLogFunc(func(string, ...any) {
require.FailNow(t, "hook called on privacy deny")
})
ctx := context.Background()
_, err := client.Team.Create().SetName("ent").Save(ctx)
require.True(t, errors.Is(err, privacy.Deny), "policy requires viewer context")
view := viewer.NewContext(ctx, viewer.AppViewer{
Role: viewer.View,
})
_, err = client.Team.CreateBulk(
client.Team.Create().SetName("ent"),
client.Team.Create().SetName("ent-contrib"),
).Save(view)
require.True(t, errors.Is(err, privacy.Deny), "team policy requires admin user")
rule.SetMutationLogFunc(logf)
admin := viewer.NewContext(ctx, viewer.AppViewer{
Role: viewer.Admin,
})
teams := client.Team.CreateBulk(
client.Team.Create().SetName("ent"),
client.Team.Create().SetName("ent-contrib"),
).SaveX(admin)
_, err = client.User.Create().SetName("a8m").AddTeams(teams[0]).Save(view)
require.True(t, errors.Is(err, privacy.Deny), "user creation requires admin user")
a8m := client.User.Create().SetName("a8m").AddTeams(teams[0], teams[1]).SaveX(admin)
nat := client.User.Create().SetName("nati").AddTeams(teams[1]).SaveX(admin)
_, err = client.Task.Create().SetTitle("task 1").AddTeams(teams[0]).SetOwner(a8m).Save(ctx)
require.True(t, errors.Is(err, privacy.Deny), "task creation requires viewer/owner match")
a8mctx := viewer.NewContext(view, &viewer.UserViewer{User: a8m, Role: viewer.View | viewer.Edit})
client.Task.Create().SetTitle("task 1").AddTeams(teams[0]).SetOwner(a8m).SaveX(a8mctx)
_, err = client.Task.Create().SetTitle("task 2").AddTeams(teams[1]).SetOwner(nat).Save(a8mctx)
require.True(t, errors.Is(err, privacy.Deny), "task creation requires viewer/owner match")
natctx := viewer.NewContext(view, &viewer.UserViewer{User: nat, Role: viewer.View | viewer.Edit})
client.Task.Create().SetTitle("task 2").AddTeams(teams[1]).SetOwner(nat).SaveX(natctx)
tasks := client.Task.Query().AllX(a8mctx)
require.Len(t, tasks, 2, "returned tasks from teams 1, 2")
task2 := client.Task.Query().OnlyX(natctx)
require.Equal(t, "task 2", task2.Title, "returned tasks must be from the same team")
task3 := client.Task.Create().SetTitle("multi-team-task (1, 2)").AddTeams(teams...).SetOwner(a8m).SaveX(a8mctx)
_, err = task3.Update().SetStatus(task.StatusClosed).Save(natctx)
require.True(t, errors.Is(err, privacy.Deny), "viewer 2 is not allowed to change the task status")
// DecisionContext returns a new context from the parent with a decision attached to it.
task3.Update().SetStatus(task.StatusClosed).SaveX(privacy.DecisionContext(natctx, privacy.Allow))
task3.Update().SetStatus(task.StatusClosed).SaveX(a8mctx)
// Update description is allowed for other users in the team.
task3.Update().SetDescription("boring description").SaveX(natctx)
task3.Update().SetDescription("boring description").SaveX(a8mctx)
}

View File

@@ -0,0 +1,211 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package rule
import (
"context"
"fmt"
"sync"
"entgo.io/ent/entc/integration/privacy/ent"
"entgo.io/ent/entc/integration/privacy/ent/hook"
"entgo.io/ent/entc/integration/privacy/ent/predicate"
"entgo.io/ent/entc/integration/privacy/ent/privacy"
"entgo.io/ent/entc/integration/privacy/ent/task"
"entgo.io/ent/entc/integration/privacy/ent/team"
"entgo.io/ent/entc/integration/privacy/ent/user"
"entgo.io/ent/entc/integration/privacy/viewer"
)
// DenyUpdateRule is a mutation rule that denies the update-many operation.
func DenyUpdateRule() privacy.MutationRule {
return privacy.DenyMutationOperationRule(ent.OpUpdate)
}
// DenyIfNoViewer is a rule that returns deny decision if the viewer is missing in the context.
func DenyIfNoViewer() privacy.QueryMutationRule {
return privacy.ContextQueryMutationRule(func(ctx context.Context) error {
view := viewer.FromContext(ctx)
if view == nil {
return privacy.Denyf("viewer-context is missing")
}
return privacy.Skip
})
}
// DenyIfNotAdmin is a rule that returns deny decision if the viewer not admin.
func DenyIfNotAdmin() privacy.QueryMutationRule {
return privacy.ContextQueryMutationRule(func(ctx context.Context) error {
view := viewer.FromContext(ctx)
if !view.Admin() {
return privacy.Denyf("viewer-context is not admin")
}
return privacy.Skip
})
}
// AllowIfAdmin is a rule that returns allow decision if the viewer is admin.
func AllowIfAdmin() privacy.QueryMutationRule {
return privacy.ContextQueryMutationRule(func(ctx context.Context) error {
view := viewer.FromContext(ctx)
if view.Admin() {
return privacy.Allow
}
return privacy.Skip
})
}
// AllowUserCreateIfAdmin is a rule that allows user creation only if the viewer is admin.
func AllowUserCreateIfAdmin() privacy.MutationRule {
rule := privacy.UserMutationRuleFunc(func(ctx context.Context, _ *ent.UserMutation) error {
view := viewer.FromContext(ctx)
if view.Admin() {
return privacy.Allow
}
// Skip to the next privacy rule, that may accept or reject this operation.
return privacy.Skip
})
return privacy.OnMutationOperation(rule, ent.OpCreate)
}
// AllowTaskCreateIfOwner is a rule that allows creating task only if the creator is also the user.
func AllowTaskCreateIfOwner() privacy.MutationRule {
rule := privacy.TaskMutationRuleFunc(func(ctx context.Context, m *ent.TaskMutation) error {
view, ok := viewer.FromContext(ctx).(*viewer.UserViewer)
if !ok {
return privacy.Skip
}
id, exists := m.OwnerID()
if exists && view.User.ID == id {
return privacy.Allow
}
// Skip to the next privacy rule, that may accept or reject this operation.
return privacy.Skip
})
return privacy.OnMutationOperation(rule, ent.OpCreate)
}
// FilterTeamRule is a query rule that filters out tasks and users that are not in the team.
func FilterTeamRule() privacy.QueryRule {
type TeamsFilter interface {
WhereHasTeamsWith(...predicate.Team)
}
return privacy.FilterFunc(func(ctx context.Context, f privacy.Filter) error {
view := viewer.FromContext(ctx)
teams, err := view.Teams(ctx)
if err != nil {
return privacy.Denyf("getting team names: %w", err)
}
tf, ok := f.(TeamsFilter)
if !ok {
return privacy.Denyf("unexpected filter type %T", f)
}
tf.WhereHasTeamsWith(team.NameIn(teams...))
return privacy.Skip
})
}
// FilterUsesDep is a filter query rule that uses its injected dependency using type-assertion.
func FilterUsesDep() privacy.QueryRule {
return privacy.FilterFunc(func(ctx context.Context, f privacy.Filter) error {
u, ok := f.(*ent.UserFilter)
if !ok {
return privacy.Denyf("unexpected filter type %T", f)
}
// Access the dependency after the type is resolved.
_ = u.HTTPClient
return privacy.Skip
})
}
// DenyIfStatusChangedByOther is a mutation rule that returns a deny decision if the
// task status was changed by someone that is not the owner of the task, or an admin.
func DenyIfStatusChangedByOther() privacy.MutationRule {
policy := privacy.TaskMutationRuleFunc(func(ctx context.Context, m *ent.TaskMutation) error {
// Skip if the mutation does not change the task status.
if _, exists := m.Status(); !exists {
return privacy.Skip
}
view, ok := viewer.FromContext(ctx).(*viewer.UserViewer)
// Skip if the viewer is an admin (or an app).
if !ok || view.Admin() {
return privacy.Skip
}
id, ok := m.ID()
if !ok {
return fmt.Errorf("missing task id")
}
owner, err := m.Client().User.Query().Where(user.HasTasksWith(task.ID(id))).Only(ctx)
if err != nil {
return err
}
// Deny the mutation, if the viewer is not the owner.
if owner.ID != view.User.ID {
return privacy.Denyf("viewer %d is not allowed to change the task status", view.User.ID)
}
return privacy.Skip
})
return privacy.OnMutationOperation(policy, ent.OpUpdateOne)
}
// AllowIfViewerInTheSameTeam returns allow decision if viewer on the same team as the task.
func AllowIfViewerInTheSameTeam() privacy.MutationRule {
policy := privacy.TaskMutationRuleFunc(func(ctx context.Context, m *ent.TaskMutation) error {
view, ok := viewer.FromContext(ctx).(*viewer.UserViewer)
// Skip if the viewer is an admin (or an app).
if !ok || view.Admin() {
return privacy.Skip
}
teams, err := view.Teams(ctx)
if err != nil {
return privacy.Denyf("getting team names: %w", err)
}
id, ok := m.ID()
if !ok {
return fmt.Errorf("missing task id")
}
// Query should return an error if the viewer
// does not belong to the task namespace/team.
if _, err = m.Client().Task.Query().
Where(
task.ID(id),
task.HasTeamsWith(team.NameIn(teams...)),
).
Only(ctx); err != nil {
return err
}
return privacy.Allow
})
return privacy.OnMutationOperation(policy, ent.OpUpdateOne)
}
var logger = struct {
logf func(string, ...any)
sync.RWMutex
}{
logf: func(string, ...any) {},
}
// SetMutationLogFunc overrides the logging function used by LogPlanetMutationHook.
func SetMutationLogFunc(f func(string, ...any)) func(string, ...any) {
logger.Lock()
defer logger.Unlock()
logf := logger.logf
logger.logf = f
return logf
}
// LogTaskMutationHook returns a hook logging planet mutations.
func LogTaskMutationHook() ent.Hook {
return func(next ent.Mutator) ent.Mutator {
return hook.TaskFunc(func(ctx context.Context, m *ent.TaskMutation) (ent.Value, error) {
value, err := next.Mutate(ctx, m)
logger.RLock()
defer logger.RUnlock()
logger.logf("task mutation: type %s, value %v, err %v", m.Op(), value, err)
return value, err
})
}
}

View File

@@ -0,0 +1,84 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package viewer
import (
"context"
"entgo.io/ent/entc/integration/privacy/ent"
"entgo.io/ent/entc/integration/privacy/ent/team"
)
// Role for viewer actions.
type Role int
// List of roles.
const (
_ Role = 1 << iota
Admin
Edit
View
)
// Viewer describes the query/mutation viewer-context.
type Viewer interface {
Teams(context.Context) ([]string, error) // Team to query (tenant == team).
Admin() bool // If viewer is admin.
Can(Role) bool // If viewer is able to apply role action.
}
// UserViewer describes a user-viewer.
type UserViewer struct {
User *ent.User // Actual user.
Role Role // Attached roles.
}
func (v UserViewer) Teams(ctx context.Context) ([]string, error) {
return v.User.QueryTeams().Select(team.FieldName).Strings(ctx)
}
func (v UserViewer) Can(r Role) bool {
if v.Admin() {
return true
}
return v.Role&r != 0
}
func (v UserViewer) Admin() bool {
return v.Role&Admin != 0
}
// AppViewer describes an app-viewer.
type AppViewer struct {
Role Role // Attached roles.
}
func (v AppViewer) Teams(context.Context) ([]string, error) {
return nil, nil
}
func (v AppViewer) Can(r Role) bool {
if v.Admin() {
return true
}
return v.Role&r != 0
}
func (v AppViewer) Admin() bool {
return v.Role&Admin != 0
}
type ctxKey struct{}
// FromContext returns the Viewer stored in a context.
func FromContext(ctx context.Context) Viewer {
v, _ := ctx.Value(ctxKey{}).(Viewer)
return v
}
// NewContext returns a copy of parent context with the given Viewer attached with it.
func NewContext(parent context.Context, v Viewer) context.Context {
return context.WithValue(parent, ctxKey{}, v)
}