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,698 @@
// 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/examples/privacytenant/ent/migrate"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/examples/privacytenant/ent/group"
"entgo.io/ent/examples/privacytenant/ent/tenant"
"entgo.io/ent/examples/privacytenant/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
// Group is the client for interacting with the Group builders.
Group *GroupClient
// Tenant is the client for interacting with the Tenant builders.
Tenant *TenantClient
// 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.Group = NewGroupClient(c.config)
c.Tenant = NewTenantClient(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
}
// 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
}
}
// 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,
Group: NewGroupClient(cfg),
Tenant: NewTenantClient(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,
Group: NewGroupClient(cfg),
Tenant: NewTenantClient(cfg),
User: NewUserClient(cfg),
}, nil
}
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
//
// client.Debug().
// Group.
// 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.Group.Use(hooks...)
c.Tenant.Use(hooks...)
c.User.Use(hooks...)
}
// Intercept adds the query interceptors to all the entity clients.
// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`.
func (c *Client) Intercept(interceptors ...Interceptor) {
c.Group.Intercept(interceptors...)
c.Tenant.Intercept(interceptors...)
c.User.Intercept(interceptors...)
}
// Mutate implements the ent.Mutator interface.
func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
switch m := m.(type) {
case *GroupMutation:
return c.Group.mutate(ctx, m)
case *TenantMutation:
return c.Tenant.mutate(ctx, m)
case *UserMutation:
return c.User.mutate(ctx, m)
default:
return nil, fmt.Errorf("ent: unknown mutation type %T", m)
}
}
// GroupClient is a client for the Group schema.
type GroupClient struct {
config
}
// NewGroupClient returns a client for the Group from the given config.
func NewGroupClient(c config) *GroupClient {
return &GroupClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `group.Hooks(f(g(h())))`.
func (c *GroupClient) Use(hooks ...Hook) {
c.hooks.Group = append(c.hooks.Group, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `group.Intercept(f(g(h())))`.
func (c *GroupClient) Intercept(interceptors ...Interceptor) {
c.inters.Group = append(c.inters.Group, interceptors...)
}
// Create returns a builder for creating a Group entity.
func (c *GroupClient) Create() *GroupCreate {
mutation := newGroupMutation(c.config, OpCreate)
return &GroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Group entities.
func (c *GroupClient) CreateBulk(builders ...*GroupCreate) *GroupCreateBulk {
return &GroupCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *GroupClient) MapCreateBulk(slice any, setFunc func(*GroupCreate, int)) *GroupCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &GroupCreateBulk{err: fmt.Errorf("calling to GroupClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*GroupCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &GroupCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Group.
func (c *GroupClient) Update() *GroupUpdate {
mutation := newGroupMutation(c.config, OpUpdate)
return &GroupUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *GroupClient) UpdateOne(_m *Group) *GroupUpdateOne {
mutation := newGroupMutation(c.config, OpUpdateOne, withGroup(_m))
return &GroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *GroupClient) UpdateOneID(id int) *GroupUpdateOne {
mutation := newGroupMutation(c.config, OpUpdateOne, withGroupID(id))
return &GroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Group.
func (c *GroupClient) Delete() *GroupDelete {
mutation := newGroupMutation(c.config, OpDelete)
return &GroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *GroupClient) DeleteOne(_m *Group) *GroupDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *GroupClient) DeleteOneID(id int) *GroupDeleteOne {
builder := c.Delete().Where(group.ID(id))
builder.mutation.id = &id
builder.mutation.SetOp(OpDeleteOne)
return &GroupDeleteOne{builder}
}
// Query returns a query builder for Group.
func (c *GroupClient) Query() *GroupQuery {
return &GroupQuery{
config: c.config,
ctx: &QueryContext{Type: TypeGroup},
inters: c.Interceptors(),
}
}
// Get returns a Group entity by its id.
func (c *GroupClient) Get(ctx context.Context, id int) (*Group, error) {
return c.Query().Where(group.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *GroupClient) GetX(ctx context.Context, id int) *Group {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryTenant queries the tenant edge of a Group.
func (c *GroupClient) QueryTenant(_m *Group) *TenantQuery {
query := (&TenantClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, id),
sqlgraph.To(tenant.Table, tenant.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, group.TenantTable, group.TenantColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryUsers queries the users edge of a Group.
func (c *GroupClient) QueryUsers(_m *Group) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, group.UsersTable, group.UsersPrimaryKey...),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *GroupClient) Hooks() []Hook {
hooks := c.hooks.Group
return append(hooks[:len(hooks):len(hooks)], group.Hooks[:]...)
}
// Interceptors returns the client interceptors.
func (c *GroupClient) Interceptors() []Interceptor {
return c.inters.Group
}
func (c *GroupClient) mutate(ctx context.Context, m *GroupMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&GroupCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&GroupUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&GroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&GroupDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Group mutation op: %q", m.Op())
}
}
// TenantClient is a client for the Tenant schema.
type TenantClient struct {
config
}
// NewTenantClient returns a client for the Tenant from the given config.
func NewTenantClient(c config) *TenantClient {
return &TenantClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `tenant.Hooks(f(g(h())))`.
func (c *TenantClient) Use(hooks ...Hook) {
c.hooks.Tenant = append(c.hooks.Tenant, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `tenant.Intercept(f(g(h())))`.
func (c *TenantClient) Intercept(interceptors ...Interceptor) {
c.inters.Tenant = append(c.inters.Tenant, interceptors...)
}
// Create returns a builder for creating a Tenant entity.
func (c *TenantClient) Create() *TenantCreate {
mutation := newTenantMutation(c.config, OpCreate)
return &TenantCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Tenant entities.
func (c *TenantClient) CreateBulk(builders ...*TenantCreate) *TenantCreateBulk {
return &TenantCreateBulk{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 *TenantClient) MapCreateBulk(slice any, setFunc func(*TenantCreate, int)) *TenantCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &TenantCreateBulk{err: fmt.Errorf("calling to TenantClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*TenantCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &TenantCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Tenant.
func (c *TenantClient) Update() *TenantUpdate {
mutation := newTenantMutation(c.config, OpUpdate)
return &TenantUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *TenantClient) UpdateOne(_m *Tenant) *TenantUpdateOne {
mutation := newTenantMutation(c.config, OpUpdateOne, withTenant(_m))
return &TenantUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *TenantClient) UpdateOneID(id int) *TenantUpdateOne {
mutation := newTenantMutation(c.config, OpUpdateOne, withTenantID(id))
return &TenantUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Tenant.
func (c *TenantClient) Delete() *TenantDelete {
mutation := newTenantMutation(c.config, OpDelete)
return &TenantDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *TenantClient) DeleteOne(_m *Tenant) *TenantDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *TenantClient) DeleteOneID(id int) *TenantDeleteOne {
builder := c.Delete().Where(tenant.ID(id))
builder.mutation.id = &id
builder.mutation.SetOp(OpDeleteOne)
return &TenantDeleteOne{builder}
}
// Query returns a query builder for Tenant.
func (c *TenantClient) Query() *TenantQuery {
return &TenantQuery{
config: c.config,
ctx: &QueryContext{Type: TypeTenant},
inters: c.Interceptors(),
}
}
// Get returns a Tenant entity by its id.
func (c *TenantClient) Get(ctx context.Context, id int) (*Tenant, error) {
return c.Query().Where(tenant.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *TenantClient) GetX(ctx context.Context, id int) *Tenant {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// Hooks returns the client hooks.
func (c *TenantClient) Hooks() []Hook {
hooks := c.hooks.Tenant
return append(hooks[:len(hooks):len(hooks)], tenant.Hooks[:]...)
}
// Interceptors returns the client interceptors.
func (c *TenantClient) Interceptors() []Interceptor {
return c.inters.Tenant
}
func (c *TenantClient) mutate(ctx context.Context, m *TenantMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&TenantCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&TenantUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&TenantUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&TenantDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Tenant 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
}
// QueryTenant queries the tenant edge of a User.
func (c *UserClient) QueryTenant(_m *User) *TenantQuery {
query := (&TenantClient{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(tenant.Table, tenant.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, user.TenantTable, user.TenantColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryGroups queries the groups edge of a User.
func (c *UserClient) QueryGroups(_m *User) *GroupQuery {
query := (&GroupClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, id),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, user.GroupsTable, user.GroupsPrimaryKey...),
)
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 {
Group, Tenant, User []ent.Hook
}
inters struct {
Group, Tenant, 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/examples/privacytenant/ent/group"
"entgo.io/ent/examples/privacytenant/ent/tenant"
"entgo.io/ent/examples/privacytenant/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{
group.Table: group.ValidColumn,
tenant.Table: tenant.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,330 @@
// 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/examples/privacytenant/ent/group"
"entgo.io/ent/examples/privacytenant/ent/predicate"
"entgo.io/ent/examples/privacytenant/ent/tenant"
"entgo.io/ent/examples/privacytenant/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: group.Table,
Columns: group.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: group.FieldID,
},
},
Type: "Group",
Fields: map[string]*sqlgraph.FieldSpec{
group.FieldTenantID: {Type: field.TypeInt, Column: group.FieldTenantID},
group.FieldName: {Type: field.TypeString, Column: group.FieldName},
},
}
graph.Nodes[1] = &sqlgraph.Node{
NodeSpec: sqlgraph.NodeSpec{
Table: tenant.Table,
Columns: tenant.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: tenant.FieldID,
},
},
Type: "Tenant",
Fields: map[string]*sqlgraph.FieldSpec{
tenant.FieldName: {Type: field.TypeString, Column: tenant.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.FieldTenantID: {Type: field.TypeInt, Column: user.FieldTenantID},
user.FieldName: {Type: field.TypeString, Column: user.FieldName},
user.FieldFoods: {Type: field.TypeJSON, Column: user.FieldFoods},
},
}
graph.MustAddE(
"tenant",
&sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: group.TenantTable,
Columns: []string{group.TenantColumn},
Bidi: false,
},
"Group",
"Tenant",
)
graph.MustAddE(
"users",
&sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
Bidi: false,
},
"Group",
"User",
)
graph.MustAddE(
"tenant",
&sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: user.TenantTable,
Columns: []string{user.TenantColumn},
Bidi: false,
},
"User",
"Tenant",
)
graph.MustAddE(
"groups",
&sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.GroupsTable,
Columns: user.GroupsPrimaryKey,
Bidi: false,
},
"User",
"Group",
)
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 *GroupQuery) addPredicate(pred func(s *sql.Selector)) {
_q.predicates = append(_q.predicates, pred)
}
// Filter returns a Filter implementation to apply filters on the GroupQuery builder.
func (_q *GroupQuery) Filter() *GroupFilter {
return &GroupFilter{config: _q.config, predicateAdder: _q}
}
// addPredicate implements the predicateAdder interface.
func (m *GroupMutation) addPredicate(pred func(s *sql.Selector)) {
m.Where(pred)
}
// Filter returns an entql.Where implementation to apply filters on the GroupMutation builder.
func (m *GroupMutation) Filter() *GroupFilter {
return &GroupFilter{config: m.config, predicateAdder: m}
}
// GroupFilter provides a generic filtering capability at runtime for GroupQuery.
type GroupFilter struct {
predicateAdder
config
}
// Where applies the entql predicate on the query filter.
func (f *GroupFilter) 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 *GroupFilter) WhereID(p entql.IntP) {
f.Where(p.Field(group.FieldID))
}
// WhereTenantID applies the entql int predicate on the tenant_id field.
func (f *GroupFilter) WhereTenantID(p entql.IntP) {
f.Where(p.Field(group.FieldTenantID))
}
// WhereName applies the entql string predicate on the name field.
func (f *GroupFilter) WhereName(p entql.StringP) {
f.Where(p.Field(group.FieldName))
}
// WhereHasTenant applies a predicate to check if query has an edge tenant.
func (f *GroupFilter) WhereHasTenant() {
f.Where(entql.HasEdge("tenant"))
}
// WhereHasTenantWith applies a predicate to check if query has an edge tenant with a given conditions (other predicates).
func (f *GroupFilter) WhereHasTenantWith(preds ...predicate.Tenant) {
f.Where(entql.HasEdgeWith("tenant", 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 *GroupFilter) 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 *GroupFilter) 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 *TenantQuery) addPredicate(pred func(s *sql.Selector)) {
_q.predicates = append(_q.predicates, pred)
}
// Filter returns a Filter implementation to apply filters on the TenantQuery builder.
func (_q *TenantQuery) Filter() *TenantFilter {
return &TenantFilter{config: _q.config, predicateAdder: _q}
}
// addPredicate implements the predicateAdder interface.
func (m *TenantMutation) addPredicate(pred func(s *sql.Selector)) {
m.Where(pred)
}
// Filter returns an entql.Where implementation to apply filters on the TenantMutation builder.
func (m *TenantMutation) Filter() *TenantFilter {
return &TenantFilter{config: m.config, predicateAdder: m}
}
// TenantFilter provides a generic filtering capability at runtime for TenantQuery.
type TenantFilter struct {
predicateAdder
config
}
// Where applies the entql predicate on the query filter.
func (f *TenantFilter) 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 *TenantFilter) WhereID(p entql.IntP) {
f.Where(p.Field(tenant.FieldID))
}
// WhereName applies the entql string predicate on the name field.
func (f *TenantFilter) WhereName(p entql.StringP) {
f.Where(p.Field(tenant.FieldName))
}
// 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))
}
// WhereTenantID applies the entql int predicate on the tenant_id field.
func (f *UserFilter) WhereTenantID(p entql.IntP) {
f.Where(p.Field(user.FieldTenantID))
}
// WhereName applies the entql string predicate on the name field.
func (f *UserFilter) WhereName(p entql.StringP) {
f.Where(p.Field(user.FieldName))
}
// WhereFoods applies the entql json.RawMessage predicate on the foods field.
func (f *UserFilter) WhereFoods(p entql.BytesP) {
f.Where(p.Field(user.FieldFoods))
}
// WhereHasTenant applies a predicate to check if query has an edge tenant.
func (f *UserFilter) WhereHasTenant() {
f.Where(entql.HasEdge("tenant"))
}
// WhereHasTenantWith applies a predicate to check if query has an edge tenant with a given conditions (other predicates).
func (f *UserFilter) WhereHasTenantWith(preds ...predicate.Tenant) {
f.Where(entql.HasEdgeWith("tenant", sqlgraph.WrapFunc(func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})))
}
// WhereHasGroups applies a predicate to check if query has an edge groups.
func (f *UserFilter) WhereHasGroups() {
f.Where(entql.HasEdge("groups"))
}
// WhereHasGroupsWith applies a predicate to check if query has an edge groups with a given conditions (other predicates).
func (f *UserFilter) WhereHasGroupsWith(preds ...predicate.Group) {
f.Where(entql.HasEdgeWith("groups", 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/examples/privacytenant/ent"
// required by schema hooks.
_ "entgo.io/ent/examples/privacytenant/ent/runtime"
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/examples/privacytenant/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 entgo.io/ent/cmd/ent generate --feature privacy,entql,schema/snapshot --header "// Copyright 2019-present Facebook Inc. All rights reserved.\n// This source code is licensed under the Apache 2.0 license found\n// in the LICENSE file in the root directory of this source tree.\n\n// Code generated by ent, DO NOT EDIT." ./schema

View File

@@ -0,0 +1,163 @@
// 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/examples/privacytenant/ent/group"
"entgo.io/ent/examples/privacytenant/ent/tenant"
)
// Group is the model entity for the Group schema.
type Group struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// TenantID holds the value of the "tenant_id" field.
TenantID int `json:"tenant_id,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the GroupQuery when eager-loading is set.
Edges GroupEdges `json:"edges"`
selectValues sql.SelectValues
}
// GroupEdges holds the relations/edges for other nodes in the graph.
type GroupEdges struct {
// Tenant holds the value of the tenant edge.
Tenant *Tenant `json:"tenant,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
}
// TenantOrErr returns the Tenant value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e GroupEdges) TenantOrErr() (*Tenant, error) {
if e.Tenant != nil {
return e.Tenant, nil
} else if e.loadedTypes[0] {
return nil, &NotFoundError{label: tenant.Label}
}
return nil, &NotLoadedError{edge: "tenant"}
}
// UsersOrErr returns the Users value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) UsersOrErr() ([]*User, error) {
if e.loadedTypes[1] {
return e.Users, nil
}
return nil, &NotLoadedError{edge: "users"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Group) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case group.FieldID, group.FieldTenantID:
values[i] = new(sql.NullInt64)
case group.FieldName:
values[i] = new(sql.NullString)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Group fields.
func (_m *Group) assignValues(columns []string, values []any) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case group.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
_m.ID = int(value.Int64)
case group.FieldTenantID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field tenant_id", values[i])
} else if value.Valid {
_m.TenantID = int(value.Int64)
}
case group.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
_m.Name = value.String
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Group.
// This includes values selected through modifiers, order, etc.
func (_m *Group) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryTenant queries the "tenant" edge of the Group entity.
func (_m *Group) QueryTenant() *TenantQuery {
return NewGroupClient(_m.config).QueryTenant(_m)
}
// QueryUsers queries the "users" edge of the Group entity.
func (_m *Group) QueryUsers() *UserQuery {
return NewGroupClient(_m.config).QueryUsers(_m)
}
// Update returns a builder for updating this Group.
// Note that you need to call Group.Unwrap() before calling this method if this Group
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Group) Update() *GroupUpdateOne {
return NewGroupClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Group entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (_m *Group) Unwrap() *Group {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: Group is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Group) String() string {
var builder strings.Builder
builder.WriteString("Group(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("tenant_id=")
builder.WriteString(fmt.Sprintf("%v", _m.TenantID))
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(_m.Name)
builder.WriteByte(')')
return builder.String()
}
// Groups is a parsable slice of Group.
type Groups []*Group

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 group
import (
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the group type in the database.
Label = "group"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldTenantID holds the string denoting the tenant_id field in the database.
FieldTenantID = "tenant_id"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// EdgeTenant holds the string denoting the tenant edge name in mutations.
EdgeTenant = "tenant"
// EdgeUsers holds the string denoting the users edge name in mutations.
EdgeUsers = "users"
// Table holds the table name of the group in the database.
Table = "groups"
// TenantTable is the table that holds the tenant relation/edge.
TenantTable = "groups"
// TenantInverseTable is the table name for the Tenant entity.
// It exists in this package in order to avoid circular dependency with the "tenant" package.
TenantInverseTable = "tenants"
// TenantColumn is the table column denoting the tenant relation/edge.
TenantColumn = "tenant_id"
// UsersTable is the table that holds the users relation/edge. The primary key declared below.
UsersTable = "user_groups"
// 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 group fields.
var Columns = []string{
FieldID,
FieldTenantID,
FieldName,
}
var (
// UsersPrimaryKey and UsersColumn2 are the table columns denoting the
// primary key for the users relation (M2M).
UsersPrimaryKey = []string{"user_id", "group_id"}
)
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
// 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/examples/privacytenant/ent/runtime"
var (
Hooks [1]ent.Hook
Policy ent.Policy
// DefaultName holds the default value on creation for the "name" field.
DefaultName string
)
// OrderOption defines the ordering options for the Group queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByTenantID orders the results by the tenant_id field.
func ByTenantID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldTenantID, opts...).ToFunc()
}
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, opts...).ToFunc()
}
// ByTenantField orders the results by tenant field.
func ByTenantField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newTenantStep(), sql.OrderByField(field, opts...))
}
}
// 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 newTenantStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(TenantInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, TenantTable, TenantColumn),
)
}
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,410 @@
// 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 group
import (
"context"
"fmt"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/examples/privacytenant/ent/predicate"
)
// Mutation represents an operation that mutates the Group nodes in the graph.
type Mutation struct {
op ent.Op
typ string
name *string
clearedFields map[string]struct{}
tenant *int
clearedtenant bool
users map[int]struct{}
removedusers map[int]struct{}
clearedusers bool
predicates []predicate.Group
}
// NewMutation creates a new Mutation for the Group entity.
func NewMutation(op ent.Op) *Mutation {
return &Mutation{
op: op,
typ: "Group",
clearedFields: make(map[string]struct{}),
}
}
// Predicates returns the list of predicates set on the mutation.
func (m *Mutation) Predicates() []predicate.Group {
return m.predicates
}
// SetTenantID sets the "tenant_id" field.
func (m *Mutation) SetTenantID(i int) {
m.tenant = &i
}
// TenantID returns the value of the "tenant_id" field in the mutation.
func (m *Mutation) TenantID() (r int, exists bool) {
v := m.tenant
if v == nil {
return
}
return *v, true
}
// ResetTenantID resets all changes to the "tenant_id" field.
func (m *Mutation) ResetTenantID() {
m.tenant = nil
}
// 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
}
// ClearTenant clears the "tenant" edge to the Tenant entity.
func (m *Mutation) ClearTenant() {
m.clearedtenant = true
m.clearedFields[FieldTenantID] = struct{}{}
}
// TenantCleared reports if the "tenant" edge to the Tenant entity was cleared.
func (m *Mutation) TenantCleared() bool {
return m.clearedtenant
}
// TenantIDs returns the "tenant" edge IDs in the mutation.
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
// TenantID instead. It exists only for internal usage by the builders.
func (m *Mutation) TenantIDs() (ids []int) {
if id := m.tenant; id != nil {
ids = append(ids, *id)
}
return
}
// ResetTenant resets all changes to the "tenant" edge.
func (m *Mutation) ResetTenant() {
m.tenant = nil
m.clearedtenant = false
}
// 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.Group) {
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.Group, 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 (Group).
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.tenant != nil {
fields = append(fields, FieldTenantID)
}
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 FieldTenantID:
return m.TenantID()
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 Group 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 FieldTenantID:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetTenantID(v)
return nil
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 Group field %s", name)
}
// AddedFields returns all numeric fields that were incremented/decremented during
// this mutation.
func (m *Mutation) AddedFields() []string {
var fields []string
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 {
}
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 Group 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 Group 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 FieldTenantID:
m.ResetTenantID()
return nil
case FieldName:
m.ResetName()
return nil
}
return fmt.Errorf("unknown Group 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.tenant != nil {
edges = append(edges, EdgeTenant)
}
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 EdgeTenant:
if id := m.tenant; id != nil {
return []ent.Value{*id}
}
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.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 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.clearedtenant {
edges = append(edges, EdgeTenant)
}
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 EdgeTenant:
return m.clearedtenant
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 {
case EdgeTenant:
m.ClearTenant()
return nil
}
return fmt.Errorf("unknown Group 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 EdgeTenant:
m.ResetTenant()
return nil
case EdgeUsers:
m.ResetUsers()
return nil
}
return fmt.Errorf("unknown Group edge %s", name)
}

View File

@@ -0,0 +1,214 @@
// 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 group
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/examples/privacytenant/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Group {
return predicate.Group(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Group {
return predicate.Group(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Group {
return predicate.Group(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldID, id))
}
// TenantID applies equality check predicate on the "tenant_id" field. It's identical to TenantIDEQ.
func TenantID(v int) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldTenantID, v))
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldName, v))
}
// TenantIDEQ applies the EQ predicate on the "tenant_id" field.
func TenantIDEQ(v int) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldTenantID, v))
}
// TenantIDNEQ applies the NEQ predicate on the "tenant_id" field.
func TenantIDNEQ(v int) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldTenantID, v))
}
// TenantIDIn applies the In predicate on the "tenant_id" field.
func TenantIDIn(vs ...int) predicate.Group {
return predicate.Group(sql.FieldIn(FieldTenantID, vs...))
}
// TenantIDNotIn applies the NotIn predicate on the "tenant_id" field.
func TenantIDNotIn(vs ...int) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldTenantID, vs...))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldName, v))
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldName, v))
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldIn(FieldName, vs...))
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldName, vs...))
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.Group {
return predicate.Group(sql.FieldGT(FieldName, v))
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldName, v))
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.Group {
return predicate.Group(sql.FieldLT(FieldName, v))
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldName, v))
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.Group {
return predicate.Group(sql.FieldContains(FieldName, v))
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.Group {
return predicate.Group(sql.FieldHasPrefix(FieldName, v))
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.Group {
return predicate.Group(sql.FieldHasSuffix(FieldName, v))
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.Group {
return predicate.Group(sql.FieldEqualFold(FieldName, v))
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.Group {
return predicate.Group(sql.FieldContainsFold(FieldName, v))
}
// HasTenant applies the HasEdge predicate on the "tenant" edge.
func HasTenant() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, TenantTable, TenantColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasTenantWith applies the HasEdge predicate on the "tenant" edge with a given conditions (other predicates).
func HasTenantWith(preds ...predicate.Tenant) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := newTenantStep()
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.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, UsersTable, UsersPrimaryKey...),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasUsersWith applies the HasEdge predicate on the "users" edge with a given conditions (other predicates).
func HasUsersWith(preds ...predicate.User) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := newUsersStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Group) predicate.Group {
return predicate.Group(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Group) predicate.Group {
return predicate.Group(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Group) predicate.Group {
return predicate.Group(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,275 @@
// 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/examples/privacytenant/ent/group"
"entgo.io/ent/examples/privacytenant/ent/tenant"
"entgo.io/ent/examples/privacytenant/ent/user"
"entgo.io/ent/schema/field"
)
// GroupCreate is the builder for creating a Group entity.
type GroupCreate struct {
config
mutation *GroupMutation
hooks []Hook
}
// SetTenantID sets the "tenant_id" field.
func (_c *GroupCreate) SetTenantID(v int) *GroupCreate {
_c.mutation.SetTenantID(v)
return _c
}
// SetName sets the "name" field.
func (_c *GroupCreate) SetName(v string) *GroupCreate {
_c.mutation.SetName(v)
return _c
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_c *GroupCreate) SetNillableName(v *string) *GroupCreate {
if v != nil {
_c.SetName(*v)
}
return _c
}
// SetTenant sets the "tenant" edge to the Tenant entity.
func (_c *GroupCreate) SetTenant(v *Tenant) *GroupCreate {
return _c.SetTenantID(v.ID)
}
// AddUserIDs adds the "users" edge to the User entity by IDs.
func (_c *GroupCreate) AddUserIDs(ids ...int) *GroupCreate {
_c.mutation.AddUserIDs(ids...)
return _c
}
// AddUsers adds the "users" edges to the User entity.
func (_c *GroupCreate) AddUsers(v ...*User) *GroupCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddUserIDs(ids...)
}
// Mutation returns the GroupMutation object of the builder.
func (_c *GroupCreate) Mutation() *GroupMutation {
return _c.mutation
}
// Save creates the Group in the database.
func (_c *GroupCreate) Save(ctx context.Context) (*Group, error) {
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 *GroupCreate) SaveX(ctx context.Context) *Group {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *GroupCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *GroupCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_c *GroupCreate) defaults() error {
if _, ok := _c.mutation.Name(); !ok {
v := group.DefaultName
_c.mutation.SetName(v)
}
return nil
}
// check runs all checks and user-defined validators on the builder.
func (_c *GroupCreate) check() error {
if _, ok := _c.mutation.TenantID(); !ok {
return &ValidationError{Name: "tenant_id", err: errors.New(`ent: missing required field "Group.tenant_id"`)}
}
if _, ok := _c.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Group.name"`)}
}
if len(_c.mutation.TenantIDs()) == 0 {
return &ValidationError{Name: "tenant", err: errors.New(`ent: missing required edge "Group.tenant"`)}
}
return nil
}
func (_c *GroupCreate) sqlSave(ctx context.Context) (*Group, error) {
if err := _c.check(); err != nil {
return nil, err
}
_node, _spec := _c.createSpec()
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
_c.mutation.id = &_node.ID
_c.mutation.done = true
return _node, nil
}
func (_c *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
var (
_node = &Group{config: _c.config}
_spec = sqlgraph.NewCreateSpec(group.Table, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt))
)
if value, ok := _c.mutation.Name(); ok {
_spec.SetField(group.FieldName, field.TypeString, value)
_node.Name = value
}
if nodes := _c.mutation.TenantIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: group.TenantTable,
Columns: []string{group.TenantColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(tenant.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.TenantID = nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.UsersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// GroupCreateBulk is the builder for creating many Group entities in bulk.
type GroupCreateBulk struct {
config
err error
builders []*GroupCreate
}
// Save creates the Group entities in the database.
func (_c *GroupCreateBulk) Save(ctx context.Context) ([]*Group, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*Group, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*GroupMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (_c *GroupCreateBulk) SaveX(ctx context.Context) []*Group {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *GroupCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *GroupCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}

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/examples/privacytenant/ent/group"
"entgo.io/ent/examples/privacytenant/ent/predicate"
"entgo.io/ent/schema/field"
)
// GroupDelete is the builder for deleting a Group entity.
type GroupDelete struct {
config
hooks []Hook
mutation *GroupMutation
}
// Where appends a list predicates to the GroupDelete builder.
func (_d *GroupDelete) Where(ps ...predicate.Group) *GroupDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *GroupDelete) Exec(ctx context.Context) (int, error) {
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *GroupDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *GroupDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(group.Table, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt))
if ps := _d.mutation.Predicates(); len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
_d.mutation.done = true
return affected, err
}
// GroupDeleteOne is the builder for deleting a single Group entity.
type GroupDeleteOne struct {
_d *GroupDelete
}
// Where appends a list predicates to the GroupDelete builder.
func (_d *GroupDeleteOne) Where(ps ...predicate.Group) *GroupDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *GroupDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{group.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *GroupDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

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/examples/privacytenant/ent/group"
"entgo.io/ent/examples/privacytenant/ent/predicate"
"entgo.io/ent/examples/privacytenant/ent/tenant"
"entgo.io/ent/examples/privacytenant/ent/user"
"entgo.io/ent/schema/field"
)
// GroupQuery is the builder for querying Group entities.
type GroupQuery struct {
config
ctx *QueryContext
order []group.OrderOption
inters []Interceptor
predicates []predicate.Group
withTenant *TenantQuery
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 GroupQuery builder.
func (_q *GroupQuery) Where(ps ...predicate.Group) *GroupQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *GroupQuery) Limit(limit int) *GroupQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *GroupQuery) Offset(offset int) *GroupQuery {
_q.ctx.Offset = &offset
return _q
}
// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (_q *GroupQuery) Unique(unique bool) *GroupQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *GroupQuery) Order(o ...group.OrderOption) *GroupQuery {
_q.order = append(_q.order, o...)
return _q
}
// QueryTenant chains the current query on the "tenant" edge.
func (_q *GroupQuery) QueryTenant() *TenantQuery {
query := (&TenantClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, selector),
sqlgraph.To(tenant.Table, tenant.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, group.TenantTable, group.TenantColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryUsers chains the current query on the "users" edge.
func (_q *GroupQuery) QueryUsers() *UserQuery {
query := (&UserClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, group.UsersTable, group.UsersPrimaryKey...),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Group entity from the query.
// Returns a *NotFoundError when no Group was found.
func (_q *GroupQuery) First(ctx context.Context) (*Group, error) {
nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{group.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *GroupQuery) FirstX(ctx context.Context) *Group {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Group ID from the query.
// Returns a *NotFoundError when no Group ID was found.
func (_q *GroupQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{group.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *GroupQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Group entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Group entity is found.
// Returns a *NotFoundError when no Group entities are found.
func (_q *GroupQuery) Only(ctx context.Context) (*Group, error) {
nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{group.Label}
default:
return nil, &NotSingularError{group.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *GroupQuery) OnlyX(ctx context.Context) *Group {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Group ID in the query.
// Returns a *NotSingularError when more than one Group ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *GroupQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{group.Label}
default:
err = &NotSingularError{group.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *GroupQuery) OnlyIDX(ctx context.Context) int {
id, err := _q.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Groups.
func (_q *GroupQuery) All(ctx context.Context) ([]*Group, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Group, *GroupQuery]()
return withInterceptors[[]*Group](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *GroupQuery) AllX(ctx context.Context) []*Group {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Group IDs.
func (_q *GroupQuery) IDs(ctx context.Context) (ids []int, err error) {
if _q.ctx.Unique == nil && _q.path != nil {
_q.Unique(true)
}
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
if err = _q.Select(group.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *GroupQuery) IDsX(ctx context.Context) []int {
ids, err := _q.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (_q *GroupQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)
if err := _q.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, _q, querierCount[*GroupQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *GroupQuery) CountX(ctx context.Context) int {
count, err := _q.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (_q *GroupQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
switch _, err := _q.FirstID(ctx); {
case IsNotFound(err):
return false, nil
case err != nil:
return false, fmt.Errorf("ent: check existence: %w", err)
default:
return true, nil
}
}
// ExistX is like Exist, but panics if an error occurs.
func (_q *GroupQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the GroupQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (_q *GroupQuery) Clone() *GroupQuery {
if _q == nil {
return nil
}
return &GroupQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]group.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Group{}, _q.predicates...),
withTenant: _q.withTenant.Clone(),
withUsers: _q.withUsers.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// WithTenant tells the query-builder to eager-load the nodes that are connected to
// the "tenant" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *GroupQuery) WithTenant(opts ...func(*TenantQuery)) *GroupQuery {
query := (&TenantClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withTenant = 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 *GroupQuery) WithUsers(opts ...func(*UserQuery)) *GroupQuery {
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 {
// TenantID int `json:"tenant_id,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Group.Query().
// GroupBy(group.FieldTenantID).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *GroupQuery) GroupBy(field string, fields ...string) *GroupGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &GroupGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = group.Label
grbuild.scan = grbuild.Scan
return grbuild
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// TenantID int `json:"tenant_id,omitempty"`
// }
//
// client.Group.Query().
// Select(group.FieldTenantID).
// Scan(ctx, &v)
func (_q *GroupQuery) Select(fields ...string) *GroupSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &GroupSelect{GroupQuery: _q}
sbuild.label = group.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a GroupSelect configured with the given aggregations.
func (_q *GroupQuery) Aggregate(fns ...AggregateFunc) *GroupSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *GroupQuery) prepareQuery(ctx context.Context) error {
for _, inter := range _q.inters {
if inter == nil {
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
}
if trv, ok := inter.(Traverser); ok {
if err := trv.Traverse(ctx, _q); err != nil {
return err
}
}
}
for _, f := range _q.ctx.Fields {
if !group.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if _q.path != nil {
prev, err := _q.path(ctx)
if err != nil {
return err
}
_q.sql = prev
}
if group.Policy == nil {
return errors.New("ent: uninitialized group.Policy (forgotten import ent/runtime?)")
}
if err := group.Policy.EvalQuery(ctx, _q); err != nil {
return err
}
return nil
}
func (_q *GroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Group, error) {
var (
nodes = []*Group{}
_spec = _q.querySpec()
loadedTypes = [2]bool{
_q.withTenant != nil,
_q.withUsers != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Group).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Group{config: _q.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := _q.withTenant; query != nil {
if err := _q.loadTenant(ctx, query, nodes, nil,
func(n *Group, e *Tenant) { n.Edges.Tenant = e }); err != nil {
return nil, err
}
}
if query := _q.withUsers; query != nil {
if err := _q.loadUsers(ctx, query, nodes,
func(n *Group) { n.Edges.Users = []*User{} },
func(n *Group, e *User) { n.Edges.Users = append(n.Edges.Users, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *GroupQuery) loadTenant(ctx context.Context, query *TenantQuery, nodes []*Group, init func(*Group), assign func(*Group, *Tenant)) error {
ids := make([]int, 0, len(nodes))
nodeids := make(map[int][]*Group)
for i := range nodes {
fk := nodes[i].TenantID
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(tenant.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 "tenant_id" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *GroupQuery) loadUsers(ctx context.Context, query *UserQuery, nodes []*Group, init func(*Group), assign func(*Group, *User)) error {
edgeIDs := make([]driver.Value, len(nodes))
byID := make(map[int]*Group)
nids := make(map[int]map[*Group]struct{})
for i, node := range nodes {
edgeIDs[i] = node.ID
byID[node.ID] = node
if init != nil {
init(node)
}
}
query.Where(func(s *sql.Selector) {
joinT := sql.Table(group.UsersTable)
s.Join(joinT).On(s.C(user.FieldID), joinT.C(group.UsersPrimaryKey[0]))
s.Where(sql.InValues(joinT.C(group.UsersPrimaryKey[1]), edgeIDs...))
columns := s.SelectedColumns()
s.Select(joinT.C(group.UsersPrimaryKey[1]))
s.AppendSelect(columns...)
s.SetDistinct(false)
})
if err := query.prepareQuery(ctx); err != nil {
return err
}
qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) {
assign := spec.Assign
values := spec.ScanValues
spec.ScanValues = func(columns []string) ([]any, error) {
values, err := values(columns[1:])
if err != nil {
return nil, err
}
return append([]any{new(sql.NullInt64)}, values...), nil
}
spec.Assign = func(columns []string, values []any) error {
outValue := int(values[0].(*sql.NullInt64).Int64)
inValue := int(values[1].(*sql.NullInt64).Int64)
if nids[inValue] == nil {
nids[inValue] = map[*Group]struct{}{byID[outValue]: {}}
return assign(columns[1:], values[1:])
}
nids[inValue][byID[outValue]] = struct{}{}
return nil
}
})
})
neighbors, err := withInterceptors[[]*User](ctx, query, qr, query.inters)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nids[n.ID]
if !ok {
return fmt.Errorf(`unexpected "users" node returned %v`, n.ID)
}
for kn := range nodes {
assign(kn, n)
}
}
return nil
}
func (_q *GroupQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *GroupQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(group.Table, group.Columns, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt))
_spec.From = _q.sql
if unique := _q.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if _q.path != nil {
_spec.Unique = true
}
if fields := _q.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, group.FieldID)
for i := range fields {
if fields[i] != group.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
if _q.withTenant != nil {
_spec.Node.AddColumnOnce(group.FieldTenantID)
}
}
if ps := _q.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := _q.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := _q.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := _q.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (_q *GroupQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(group.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = group.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// GroupGroupBy is the group-by builder for Group entities.
type GroupGroupBy struct {
selector
build *GroupQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *GroupGroupBy) Aggregate(fns ...AggregateFunc) *GroupGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *GroupGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)
if err := _g.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*GroupQuery, *GroupGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *GroupGroupBy) sqlScan(ctx context.Context, root *GroupQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(_g.fns))
for _, fn := range _g.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*_g.flds)+len(_g.fns))
for _, f := range *_g.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*_g.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// GroupSelect is the builder for selecting fields of Group entities.
type GroupSelect struct {
*GroupQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *GroupSelect) Aggregate(fns ...AggregateFunc) *GroupSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *GroupSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)
if err := _s.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*GroupQuery, *GroupSelect](ctx, _s.GroupQuery, _s, _s.inters, v)
}
func (_s *GroupSelect) sqlScan(ctx context.Context, root *GroupQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(_s.fns))
for _, fn := range _s.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*_s.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

View File

@@ -0,0 +1,398 @@
// 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/examples/privacytenant/ent/group"
"entgo.io/ent/examples/privacytenant/ent/predicate"
"entgo.io/ent/examples/privacytenant/ent/user"
"entgo.io/ent/schema/field"
)
// GroupUpdate is the builder for updating Group entities.
type GroupUpdate struct {
config
hooks []Hook
mutation *GroupMutation
}
// Where appends a list predicates to the GroupUpdate builder.
func (_u *GroupUpdate) Where(ps ...predicate.Group) *GroupUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetName sets the "name" field.
func (_u *GroupUpdate) SetName(v string) *GroupUpdate {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *GroupUpdate) SetNillableName(v *string) *GroupUpdate {
if v != nil {
_u.SetName(*v)
}
return _u
}
// AddUserIDs adds the "users" edge to the User entity by IDs.
func (_u *GroupUpdate) AddUserIDs(ids ...int) *GroupUpdate {
_u.mutation.AddUserIDs(ids...)
return _u
}
// AddUsers adds the "users" edges to the User entity.
func (_u *GroupUpdate) AddUsers(v ...*User) *GroupUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddUserIDs(ids...)
}
// Mutation returns the GroupMutation object of the builder.
func (_u *GroupUpdate) Mutation() *GroupMutation {
return _u.mutation
}
// ClearUsers clears all "users" edges to the User entity.
func (_u *GroupUpdate) ClearUsers() *GroupUpdate {
_u.mutation.ClearUsers()
return _u
}
// RemoveUserIDs removes the "users" edge to User entities by IDs.
func (_u *GroupUpdate) RemoveUserIDs(ids ...int) *GroupUpdate {
_u.mutation.RemoveUserIDs(ids...)
return _u
}
// RemoveUsers removes "users" edges to User entities.
func (_u *GroupUpdate) RemoveUsers(v ...*User) *GroupUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveUserIDs(ids...)
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *GroupUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *GroupUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *GroupUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *GroupUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *GroupUpdate) check() error {
if _u.mutation.TenantCleared() && len(_u.mutation.TenantIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "Group.tenant"`)
}
return nil
}
func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(group.Table, group.Columns, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt))
if ps := _u.mutation.Predicates(); len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Name(); ok {
_spec.SetField(group.FieldName, field.TypeString, value)
}
if _u.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedUsersIDs(); len(nodes) > 0 && !_u.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.UsersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{group.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// GroupUpdateOne is the builder for updating a single Group entity.
type GroupUpdateOne struct {
config
fields []string
hooks []Hook
mutation *GroupMutation
}
// SetName sets the "name" field.
func (_u *GroupUpdateOne) SetName(v string) *GroupUpdateOne {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *GroupUpdateOne) SetNillableName(v *string) *GroupUpdateOne {
if v != nil {
_u.SetName(*v)
}
return _u
}
// AddUserIDs adds the "users" edge to the User entity by IDs.
func (_u *GroupUpdateOne) AddUserIDs(ids ...int) *GroupUpdateOne {
_u.mutation.AddUserIDs(ids...)
return _u
}
// AddUsers adds the "users" edges to the User entity.
func (_u *GroupUpdateOne) AddUsers(v ...*User) *GroupUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddUserIDs(ids...)
}
// Mutation returns the GroupMutation object of the builder.
func (_u *GroupUpdateOne) Mutation() *GroupMutation {
return _u.mutation
}
// ClearUsers clears all "users" edges to the User entity.
func (_u *GroupUpdateOne) ClearUsers() *GroupUpdateOne {
_u.mutation.ClearUsers()
return _u
}
// RemoveUserIDs removes the "users" edge to User entities by IDs.
func (_u *GroupUpdateOne) RemoveUserIDs(ids ...int) *GroupUpdateOne {
_u.mutation.RemoveUserIDs(ids...)
return _u
}
// RemoveUsers removes "users" edges to User entities.
func (_u *GroupUpdateOne) RemoveUsers(v ...*User) *GroupUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveUserIDs(ids...)
}
// Where appends a list predicates to the GroupUpdate builder.
func (_u *GroupUpdateOne) Where(ps ...predicate.Group) *GroupUpdateOne {
_u.mutation.Where(ps...)
return _u
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (_u *GroupUpdateOne) Select(field string, fields ...string) *GroupUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated Group entity.
func (_u *GroupUpdateOne) Save(ctx context.Context) (*Group, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *GroupUpdateOne) SaveX(ctx context.Context) *Group {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *GroupUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *GroupUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *GroupUpdateOne) check() error {
if _u.mutation.TenantCleared() && len(_u.mutation.TenantIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "Group.tenant"`)
}
return nil
}
func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(group.Table, group.Columns, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Group.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := _u.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, group.FieldID)
for _, f := range fields {
if !group.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != group.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := _u.mutation.Predicates(); len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Name(); ok {
_spec.SetField(group.FieldName, field.TypeString, value)
}
if _u.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedUsersIDs(); len(nodes) > 0 && !_u.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.UsersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: group.UsersTable,
Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &Group{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{group.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

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/examples/privacytenant/ent"
)
// The GroupFunc type is an adapter to allow the use of ordinary
// function as Group mutator.
type GroupFunc func(context.Context, *ent.GroupMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f GroupFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.GroupMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GroupMutation", m)
}
// The TenantFunc type is an adapter to allow the use of ordinary
// function as Tenant mutator.
type TenantFunc func(context.Context, *ent.TenantMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f TenantFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.TenantMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.TenantMutation", 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...)
}

View File

@@ -0,0 +1,13 @@
// 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.
//go:build tools
// +build tools
// Package internal holds a loadable version of the latest schema.
package internal
const Schema = "{\"Schema\":\"entgo.io/ent/examples/privacytenant/ent/schema\",\"Package\":\"entgo.io/ent/examples/privacytenant/ent\",\"Schemas\":[{\"name\":\"Group\",\"config\":{\"Table\":\"\"},\"edges\":[{\"name\":\"tenant\",\"type\":\"Tenant\",\"field\":\"tenant_id\",\"unique\":true,\"required\":true,\"immutable\":true},{\"name\":\"users\",\"type\":\"User\",\"ref_name\":\"groups\",\"inverse\":true}],\"fields\":[{\"name\":\"tenant_id\",\"type\":{\"Type\":12,\"Ident\":\"\",\"PkgPath\":\"\",\"PkgName\":\"\",\"Nillable\":false,\"RType\":null},\"immutable\":true,\"position\":{\"Index\":0,\"MixedIn\":true,\"MixinIndex\":1}},{\"name\":\"name\",\"type\":{\"Type\":7,\"Ident\":\"\",\"PkgPath\":\"\",\"PkgName\":\"\",\"Nillable\":false,\"RType\":null},\"default\":true,\"default_value\":\"Unknown\",\"default_kind\":24,\"position\":{\"Index\":0,\"MixedIn\":false,\"MixinIndex\":0}}],\"policy\":[{\"Index\":0,\"MixedIn\":true,\"MixinIndex\":0},{\"Index\":0,\"MixedIn\":true,\"MixinIndex\":1},{\"Index\":0,\"MixedIn\":false,\"MixinIndex\":0}]},{\"name\":\"Tenant\",\"config\":{\"Table\":\"\"},\"fields\":[{\"name\":\"name\",\"type\":{\"Type\":7,\"Ident\":\"\",\"PkgPath\":\"\",\"PkgName\":\"\",\"Nillable\":false,\"RType\":null},\"validators\":1,\"position\":{\"Index\":0,\"MixedIn\":false,\"MixinIndex\":0}}],\"policy\":[{\"Index\":0,\"MixedIn\":true,\"MixinIndex\":0},{\"Index\":0,\"MixedIn\":false,\"MixinIndex\":0}]},{\"name\":\"User\",\"config\":{\"Table\":\"\"},\"edges\":[{\"name\":\"tenant\",\"type\":\"Tenant\",\"field\":\"tenant_id\",\"unique\":true,\"required\":true,\"immutable\":true},{\"name\":\"groups\",\"type\":\"Group\"}],\"fields\":[{\"name\":\"tenant_id\",\"type\":{\"Type\":12,\"Ident\":\"\",\"PkgPath\":\"\",\"PkgName\":\"\",\"Nillable\":false,\"RType\":null},\"immutable\":true,\"position\":{\"Index\":0,\"MixedIn\":true,\"MixinIndex\":1}},{\"name\":\"name\",\"type\":{\"Type\":7,\"Ident\":\"\",\"PkgPath\":\"\",\"PkgName\":\"\",\"Nillable\":false,\"RType\":null},\"default\":true,\"default_value\":\"Unknown\",\"default_kind\":24,\"position\":{\"Index\":0,\"MixedIn\":false,\"MixinIndex\":0}},{\"name\":\"foods\",\"type\":{\"Type\":3,\"Ident\":\"[]string\",\"PkgPath\":\"\",\"PkgName\":\"\",\"Nillable\":true,\"RType\":{\"Name\":\"\",\"Ident\":\"[]string\",\"Kind\":23,\"PkgPath\":\"\",\"Methods\":{}}},\"optional\":true,\"position\":{\"Index\":1,\"MixedIn\":false,\"MixinIndex\":0}}],\"policy\":[{\"Index\":0,\"MixedIn\":true,\"MixinIndex\":0},{\"Index\":0,\"MixedIn\":true,\"MixinIndex\":1}]}],\"Features\":[\"privacy\",\"entql\",\"schema/snapshot\"]}"

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,106 @@
// 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/sql/schema"
"entgo.io/ent/schema/field"
)
var (
// GroupsColumns holds the columns for the "groups" table.
GroupsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "name", Type: field.TypeString, Default: "Unknown"},
{Name: "tenant_id", Type: field.TypeInt},
}
// GroupsTable holds the schema information for the "groups" table.
GroupsTable = &schema.Table{
Name: "groups",
Columns: GroupsColumns,
PrimaryKey: []*schema.Column{GroupsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "groups_tenants_tenant",
Columns: []*schema.Column{GroupsColumns[2]},
RefColumns: []*schema.Column{TenantsColumns[0]},
OnDelete: schema.NoAction,
},
},
}
// TenantsColumns holds the columns for the "tenants" table.
TenantsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "name", Type: field.TypeString},
}
// TenantsTable holds the schema information for the "tenants" table.
TenantsTable = &schema.Table{
Name: "tenants",
Columns: TenantsColumns,
PrimaryKey: []*schema.Column{TenantsColumns[0]},
}
// UsersColumns holds the columns for the "users" table.
UsersColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "name", Type: field.TypeString, Default: "Unknown"},
{Name: "foods", Type: field.TypeJSON, Nullable: true},
{Name: "tenant_id", Type: field.TypeInt},
}
// UsersTable holds the schema information for the "users" table.
UsersTable = &schema.Table{
Name: "users",
Columns: UsersColumns,
PrimaryKey: []*schema.Column{UsersColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "users_tenants_tenant",
Columns: []*schema.Column{UsersColumns[3]},
RefColumns: []*schema.Column{TenantsColumns[0]},
OnDelete: schema.NoAction,
},
},
}
// UserGroupsColumns holds the columns for the "user_groups" table.
UserGroupsColumns = []*schema.Column{
{Name: "user_id", Type: field.TypeInt},
{Name: "group_id", Type: field.TypeInt},
}
// UserGroupsTable holds the schema information for the "user_groups" table.
UserGroupsTable = &schema.Table{
Name: "user_groups",
Columns: UserGroupsColumns,
PrimaryKey: []*schema.Column{UserGroupsColumns[0], UserGroupsColumns[1]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "user_groups_user_id",
Columns: []*schema.Column{UserGroupsColumns[0]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.Cascade,
},
{
Symbol: "user_groups_group_id",
Columns: []*schema.Column{UserGroupsColumns[1]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.Cascade,
},
},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
GroupsTable,
TenantsTable,
UsersTable,
UserGroupsTable,
}
)
func init() {
GroupsTable.ForeignKeys[0].RefTable = TenantsTable
UsersTable.ForeignKeys[0].RefTable = TenantsTable
UserGroupsTable.ForeignKeys[0].RefTable = UsersTable
UserGroupsTable.ForeignKeys[1].RefTable = GroupsTable
}

View File

@@ -0,0 +1,489 @@
// 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/examples/privacytenant/ent/group"
"entgo.io/ent/examples/privacytenant/ent/tenant"
"entgo.io/ent/examples/privacytenant/ent/user"
)
const (
// Operation types.
OpCreate = ent.OpCreate
OpDelete = ent.OpDelete
OpDeleteOne = ent.OpDeleteOne
OpUpdate = ent.OpUpdate
OpUpdateOne = ent.OpUpdateOne
// Node types.
TypeGroup = "Group"
TypeTenant = "Tenant"
TypeUser = "User"
)
// GroupMutation represents an operation that mutates the Group nodes in the graph.
type GroupMutation struct {
group.Mutation
config
id *int
done bool
oldValue func(context.Context) (*Group, error)
}
var _ ent.Mutation = (*GroupMutation)(nil)
// groupOption allows management of the mutation configuration using functional options.
type groupOption func(*GroupMutation)
// newGroupMutation creates new mutation for the Group entity.
func newGroupMutation(c config, op Op, opts ...groupOption) *GroupMutation {
m := &GroupMutation{
Mutation: *group.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 *GroupMutation) ID() (id int, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// withGroupID sets the ID field of the mutation.
func withGroupID(id int) groupOption {
return func(m *GroupMutation) {
var (
err error
once sync.Once
value *Group
)
m.oldValue = func(ctx context.Context) (*Group, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().Group.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withGroup sets the old Group of the mutation.
func withGroup(node *Group) groupOption {
return func(m *GroupMutation) {
m.oldValue = func(context.Context) (*Group, 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 GroupMutation) 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 GroupMutation) 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 *GroupMutation) 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().Group.Query().Where(m.Predicates()...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.Op())
}
}
// OldTenantID returns the old "tenant_id" field's value of the Group entity.
// If the Group 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 *GroupMutation) OldTenantID(ctx context.Context) (v int, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldTenantID is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldTenantID requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldTenantID: %w", err)
}
return oldValue.TenantID, nil
}
// OldName returns the old "name" field's value of the Group entity.
// If the Group 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 *GroupMutation) 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 *GroupMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case group.FieldTenantID:
return m.OldTenantID(ctx)
case group.FieldName:
return m.OldName(ctx)
}
return nil, fmt.Errorf("unknown Group field %s", name)
}
// TenantMutation represents an operation that mutates the Tenant nodes in the graph.
type TenantMutation struct {
tenant.Mutation
config
id *int
done bool
oldValue func(context.Context) (*Tenant, error)
}
var _ ent.Mutation = (*TenantMutation)(nil)
// tenantOption allows management of the mutation configuration using functional options.
type tenantOption func(*TenantMutation)
// newTenantMutation creates new mutation for the Tenant entity.
func newTenantMutation(c config, op Op, opts ...tenantOption) *TenantMutation {
m := &TenantMutation{
Mutation: *tenant.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 *TenantMutation) ID() (id int, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// withTenantID sets the ID field of the mutation.
func withTenantID(id int) tenantOption {
return func(m *TenantMutation) {
var (
err error
once sync.Once
value *Tenant
)
m.oldValue = func(ctx context.Context) (*Tenant, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().Tenant.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withTenant sets the old Tenant of the mutation.
func withTenant(node *Tenant) tenantOption {
return func(m *TenantMutation) {
m.oldValue = func(context.Context) (*Tenant, 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 TenantMutation) 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 TenantMutation) 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 *TenantMutation) 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().Tenant.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 Tenant entity.
// If the Tenant 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 *TenantMutation) 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 *TenantMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case tenant.FieldName:
return m.OldName(ctx)
}
return nil, fmt.Errorf("unknown Tenant 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())
}
}
// OldTenantID returns the old "tenant_id" 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) OldTenantID(ctx context.Context) (v int, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldTenantID is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldTenantID requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldTenantID: %w", err)
}
return oldValue.TenantID, nil
}
// 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
}
// OldFoods returns the old "foods" 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) OldFoods(ctx context.Context) (v []string, err error) {
if !m.Op().Is(OpUpdateOne) {
return v, errors.New("OldFoods is only allowed on UpdateOne operations")
}
if _, exists := m.ID(); !exists || m.oldValue == nil {
return v, errors.New("OldFoods requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldFoods: %w", err)
}
return oldValue.Foods, 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.FieldTenantID:
return m.OldTenantID(ctx)
case user.FieldName:
return m.OldName(ctx)
case user.FieldFoods:
return m.OldFoods(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"
)
// Group is the predicate function for group builders.
type Group func(*sql.Selector)
// Tenant is the predicate function for tenant builders.
type Tenant 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/examples/privacytenant/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 GroupQueryRuleFunc type is an adapter to allow the use of ordinary
// functions as a query rule.
type GroupQueryRuleFunc func(context.Context, *ent.GroupQuery) error
// EvalQuery return f(ctx, q).
func (f GroupQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.GroupQuery); ok {
return f(ctx, q)
}
return Denyf("ent/privacy: unexpected query type %T, expect *ent.GroupQuery", q)
}
// The GroupMutationRuleFunc type is an adapter to allow the use of ordinary
// functions as a mutation rule.
type GroupMutationRuleFunc func(context.Context, *ent.GroupMutation) error
// EvalMutation calls f(ctx, m).
func (f GroupMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error {
if m, ok := m.(*ent.GroupMutation); ok {
return f(ctx, m)
}
return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.GroupMutation", m)
}
// The TenantQueryRuleFunc type is an adapter to allow the use of ordinary
// functions as a query rule.
type TenantQueryRuleFunc func(context.Context, *ent.TenantQuery) error
// EvalQuery return f(ctx, q).
func (f TenantQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.TenantQuery); ok {
return f(ctx, q)
}
return Denyf("ent/privacy: unexpected query type %T, expect *ent.TenantQuery", q)
}
// The TenantMutationRuleFunc type is an adapter to allow the use of ordinary
// functions as a mutation rule.
type TenantMutationRuleFunc func(context.Context, *ent.TenantMutation) error
// EvalMutation calls f(ctx, m).
func (f TenantMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error {
if m, ok := m.(*ent.TenantMutation); ok {
return f(ctx, m)
}
return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.TenantMutation", 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.GroupQuery:
return q.Filter(), nil
case *ent.TenantQuery:
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.GroupMutation:
return m.Filter(), nil
case *ent.TenantMutation:
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/examples/privacytenant/ent/runtime/runtime.go

View File

@@ -0,0 +1,77 @@
// 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/examples/privacytenant/ent/group"
"entgo.io/ent/examples/privacytenant/ent/schema"
"entgo.io/ent/examples/privacytenant/ent/tenant"
"entgo.io/ent/examples/privacytenant/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() {
groupMixin := schema.Group{}.Mixin()
group.Policy = privacy.NewPolicies(groupMixin[0], groupMixin[1], schema.Group{})
group.Hooks[0] = func(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if err := group.Policy.EvalMutation(ctx, m); err != nil {
return nil, err
}
return next.Mutate(ctx, m)
})
}
groupFields := schema.Group{}.Fields()
_ = groupFields
// groupDescName is the schema descriptor for name field.
groupDescName := groupFields[0].Descriptor()
// group.DefaultName holds the default value on creation for the name field.
group.DefaultName = groupDescName.Default.(string)
tenantMixin := schema.Tenant{}.Mixin()
tenant.Policy = privacy.NewPolicies(tenantMixin[0], schema.Tenant{})
tenant.Hooks[0] = func(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if err := tenant.Policy.EvalMutation(ctx, m); err != nil {
return nil, err
}
return next.Mutate(ctx, m)
})
}
tenantFields := schema.Tenant{}.Fields()
_ = tenantFields
// tenantDescName is the schema descriptor for name field.
tenantDescName := tenantFields[0].Descriptor()
// tenant.NameValidator is a validator for the "name" field. It is called by the builders before save.
tenant.NameValidator = tenantDescName.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.DefaultName holds the default value on creation for the name field.
user.DefaultName = userDescName.Default.(string)
}
const (
Version = "v0.0.0-00010101000000-000000000000" // Version of ent codegen.
)

View File

@@ -0,0 +1,56 @@
// 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/examples/privacytenant/ent/privacy"
"entgo.io/ent/examples/privacytenant/rule"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
)
// Group holds the schema definition for the Group entity.
type Group struct {
ent.Schema
}
// Mixin of the User schema.
func (Group) Mixin() []ent.Mixin {
return []ent.Mixin{
BaseMixin{},
TenantMixin{},
}
}
// Fields of the User.
func (Group) Fields() []ent.Field {
return []ent.Field{
field.String("name").
Default("Unknown"),
}
}
// Edges of the Group.
func (Group) Edges() []ent.Edge {
return []ent.Edge{
edge.From("users", User.Type).
Ref("groups"),
}
}
// Policy defines the privacy policy of the Group.
func (Group) Policy() ent.Policy {
return privacy.Policy{
Mutation: privacy.MutationPolicy{
// Limit DenyMismatchedTenants only for
// Create operations
privacy.OnMutationOperation(
rule.DenyMismatchedTenants(),
ent.OpCreate,
),
},
}
}

View File

@@ -0,0 +1,64 @@
// 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/examples/privacytenant/ent/privacy"
"entgo.io/ent/examples/privacytenant/rule"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/mixin"
)
// BaseMixin for all schemas in the graph.
type BaseMixin struct {
mixin.Schema
}
// Policy defines the privacy policy of the BaseMixin.
func (BaseMixin) Policy() ent.Policy {
return privacy.Policy{
Query: privacy.QueryPolicy{
// Deny any operation in case there is no "viewer context".
rule.DenyIfNoViewer(),
// Allow admins to query any information.
rule.AllowIfAdmin(),
},
Mutation: privacy.MutationPolicy{
// Deny any operation in case there is no "viewer context".
rule.DenyIfNoViewer(),
},
}
}
// TenantMixin for embedding the tenant info in different schemas.
type TenantMixin struct {
mixin.Schema
}
// Fields for all schemas that embed TenantMixin.
func (TenantMixin) Fields() []ent.Field {
return []ent.Field{
field.Int("tenant_id").
Immutable(),
}
}
// Edges for all schemas that embed TenantMixin.
func (TenantMixin) Edges() []ent.Edge {
return []ent.Edge{
edge.To("tenant", Tenant.Type).
Field("tenant_id").
Unique().
Required().
Immutable(),
}
}
// Policy for all schemas that embed TenantMixin.
func (TenantMixin) Policy() ent.Policy {
return rule.FilterTenantRule()
}

View File

@@ -0,0 +1,44 @@
// 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/examples/privacytenant/ent/privacy"
"entgo.io/ent/examples/privacytenant/rule"
"entgo.io/ent/schema/field"
)
// Tenant holds the schema definition for the Tenant entity.
type Tenant struct {
ent.Schema
}
// Mixin of the Tenant schema.
func (Tenant) Mixin() []ent.Mixin {
return []ent.Mixin{
BaseMixin{},
}
}
// Fields of the Tenant.
func (Tenant) Fields() []ent.Field {
return []ent.Field{
field.String("name").
NotEmpty(),
}
}
// Policy defines the privacy policy of the User.
func (Tenant) Policy() ent.Policy {
return privacy.Policy{
Mutation: privacy.MutationPolicy{
// For Tenant type, we only allow admin users to mutate
// the tenant information and deny otherwise.
rule.AllowIfAdmin(),
privacy.AlwaysDenyRule(),
},
}
}

View File

@@ -0,0 +1,47 @@
// 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/schema/edge"
"entgo.io/ent/schema/field"
)
// User holds the schema definition for the User entity.
type User struct {
ent.Schema
}
// Mixin of the User schema.
func (User) Mixin() []ent.Mixin {
return []ent.Mixin{
BaseMixin{},
TenantMixin{},
}
}
// Fields of the User.
func (User) Fields() []ent.Field {
return []ent.Field{
field.String("name").
Default("Unknown"),
field.Strings("foods").
Optional(),
}
}
// Edges of the User.
func (User) Edges() []ent.Edge {
return []ent.Edge{
edge.To("groups", Group.Type),
}
}
// Policy defines the privacy policy of the User.
func (User) Policy() ent.Policy {
// Privacy policy defined in the BaseMixin and TenantMixin.
return nil
}

View File

@@ -0,0 +1,29 @@
{{/* The line below tells Intellij/GoLand to enable the autocompletion based on the *gen.Graph type. */}}
{{/* gotype: entgo.io/ent/entc/gen.Graph */}}
{{/* An example privacy rule that is appended to the generated privacy package. For more info: https://entgo.io/docs/privacy#template-based */}}
{{ define "privacy/additional/privacy" }}
// FilterTenantRule is a query/mutation rule that filters out entities that are not in the tenant.
func FilterTenantRule() QueryMutationRule {
// TenantsFilter is an interface to wrap WhereTenantID()
// predicate that is used by both `Group` and `User` schemas.
type TenantsFilter interface {
WhereTenantID(entql.IntP)
}
return FilterFunc(func(ctx context.Context, f Filter) error {
view := viewer.FromContext(ctx)
tid, ok := view.Tenant()
if !ok {
return Denyf("missing tenant information in viewer")
}
tf, ok := f.(TenantsFilter)
if !ok {
return Denyf("unexpected filter type %T", f)
}
// Make sure that a tenant reads only entities that have an edge to it.
tf.WhereTenantID(entql.IntEQ(tid))
// Skip to the next privacy rule (equivalent to return nil).
return Skip
})
}
{{ end }}

View File

@@ -0,0 +1,107 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/examples/privacytenant/ent/tenant"
)
// Tenant is the model entity for the Tenant schema.
type Tenant 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"`
selectValues sql.SelectValues
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Tenant) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case tenant.FieldID:
values[i] = new(sql.NullInt64)
case tenant.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 Tenant fields.
func (_m *Tenant) 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 tenant.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 tenant.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 Tenant.
// This includes values selected through modifiers, order, etc.
func (_m *Tenant) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// Update returns a builder for updating this Tenant.
// Note that you need to call Tenant.Unwrap() before calling this method if this Tenant
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Tenant) Update() *TenantUpdateOne {
return NewTenantClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Tenant 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 *Tenant) Unwrap() *Tenant {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: Tenant is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Tenant) String() string {
var builder strings.Builder
builder.WriteString("Tenant(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("name=")
builder.WriteString(_m.Name)
builder.WriteByte(')')
return builder.String()
}
// Tenants is a parsable slice of Tenant.
type Tenants []*Tenant

View File

@@ -0,0 +1,233 @@
// 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 tenant
import (
"context"
"fmt"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/examples/privacytenant/ent/predicate"
)
// Mutation represents an operation that mutates the Tenant nodes in the graph.
type Mutation struct {
op ent.Op
typ string
name *string
clearedFields map[string]struct{}
predicates []predicate.Tenant
}
// NewMutation creates a new Mutation for the Tenant entity.
func NewMutation(op ent.Op) *Mutation {
return &Mutation{
op: op,
typ: "Tenant",
clearedFields: make(map[string]struct{}),
}
}
// Predicates returns the list of predicates set on the mutation.
func (m *Mutation) Predicates() []predicate.Tenant {
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
}
// Where appends a list predicates to the Mutation builder.
func (m *Mutation) Where(ps ...predicate.Tenant) {
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.Tenant, 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 (Tenant).
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 Tenant 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 Tenant 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 Tenant 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 Tenant 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 Tenant field %s", name)
}
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *Mutation) AddedEdges() []string {
edges := make([]string, 0, 0)
return edges
}
// AddedIDs returns all IDs (to other nodes) that were added for the given edge
// name in this mutation.
func (m *Mutation) AddedIDs(name string) []ent.Value {
return nil
}
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *Mutation) RemovedEdges() []string {
edges := make([]string, 0, 0)
return edges
}
// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
// the given name in this mutation.
func (m *Mutation) RemovedIDs(name string) []ent.Value {
return nil
}
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *Mutation) ClearedEdges() []string {
edges := make([]string, 0, 0)
return edges
}
// EdgeCleared returns a boolean which indicates if the edge with the given name
// was cleared in this mutation.
func (m *Mutation) EdgeCleared(name string) bool {
return false
}
// ClearEdge clears the value of the edge with the given name. It returns an error
// if that edge is not defined in the schema.
func (m *Mutation) ClearEdge(name string) error {
return fmt.Errorf("unknown Tenant 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 {
return fmt.Errorf("unknown Tenant edge %s", name)
}

View File

@@ -0,0 +1,64 @@
// 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 tenant
import (
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
)
const (
// Label holds the string label denoting the tenant type in the database.
Label = "tenant"
// 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"
// Table holds the table name of the tenant in the database.
Table = "tenants"
)
// Columns holds all SQL columns for tenant fields.
var Columns = []string{
FieldID,
FieldName,
}
// 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/examples/privacytenant/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 Tenant 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()
}

View File

@@ -0,0 +1,142 @@
// 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 tenant
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/examples/privacytenant/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Tenant {
return predicate.Tenant(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Tenant {
return predicate.Tenant(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Tenant {
return predicate.Tenant(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Tenant {
return predicate.Tenant(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Tenant {
return predicate.Tenant(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Tenant {
return predicate.Tenant(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Tenant {
return predicate.Tenant(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Tenant {
return predicate.Tenant(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Tenant {
return predicate.Tenant(sql.FieldLTE(FieldID, id))
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Tenant {
return predicate.Tenant(sql.FieldEQ(FieldName, v))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Tenant {
return predicate.Tenant(sql.FieldEQ(FieldName, v))
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.Tenant {
return predicate.Tenant(sql.FieldNEQ(FieldName, v))
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.Tenant {
return predicate.Tenant(sql.FieldIn(FieldName, vs...))
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.Tenant {
return predicate.Tenant(sql.FieldNotIn(FieldName, vs...))
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.Tenant {
return predicate.Tenant(sql.FieldGT(FieldName, v))
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.Tenant {
return predicate.Tenant(sql.FieldGTE(FieldName, v))
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.Tenant {
return predicate.Tenant(sql.FieldLT(FieldName, v))
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.Tenant {
return predicate.Tenant(sql.FieldLTE(FieldName, v))
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.Tenant {
return predicate.Tenant(sql.FieldContains(FieldName, v))
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.Tenant {
return predicate.Tenant(sql.FieldHasPrefix(FieldName, v))
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.Tenant {
return predicate.Tenant(sql.FieldHasSuffix(FieldName, v))
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.Tenant {
return predicate.Tenant(sql.FieldEqualFold(FieldName, v))
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.Tenant {
return predicate.Tenant(sql.FieldContainsFold(FieldName, v))
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Tenant) predicate.Tenant {
return predicate.Tenant(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Tenant) predicate.Tenant {
return predicate.Tenant(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Tenant) predicate.Tenant {
return predicate.Tenant(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,192 @@
// 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/examples/privacytenant/ent/tenant"
"entgo.io/ent/schema/field"
)
// TenantCreate is the builder for creating a Tenant entity.
type TenantCreate struct {
config
mutation *TenantMutation
hooks []Hook
}
// SetName sets the "name" field.
func (_c *TenantCreate) SetName(v string) *TenantCreate {
_c.mutation.SetName(v)
return _c
}
// Mutation returns the TenantMutation object of the builder.
func (_c *TenantCreate) Mutation() *TenantMutation {
return _c.mutation
}
// Save creates the Tenant in the database.
func (_c *TenantCreate) Save(ctx context.Context) (*Tenant, error) {
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *TenantCreate) SaveX(ctx context.Context) *Tenant {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *TenantCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *TenantCreate) 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 *TenantCreate) check() error {
if _, ok := _c.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Tenant.name"`)}
}
if v, ok := _c.mutation.Name(); ok {
if err := tenant.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Tenant.name": %w`, err)}
}
}
return nil
}
func (_c *TenantCreate) sqlSave(ctx context.Context) (*Tenant, 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 *TenantCreate) createSpec() (*Tenant, *sqlgraph.CreateSpec) {
var (
_node = &Tenant{config: _c.config}
_spec = sqlgraph.NewCreateSpec(tenant.Table, sqlgraph.NewFieldSpec(tenant.FieldID, field.TypeInt))
)
if value, ok := _c.mutation.Name(); ok {
_spec.SetField(tenant.FieldName, field.TypeString, value)
_node.Name = value
}
return _node, _spec
}
// TenantCreateBulk is the builder for creating many Tenant entities in bulk.
type TenantCreateBulk struct {
config
err error
builders []*TenantCreate
}
// Save creates the Tenant entities in the database.
func (_c *TenantCreateBulk) Save(ctx context.Context) ([]*Tenant, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*Tenant, 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.(*TenantMutation)
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 *TenantCreateBulk) SaveX(ctx context.Context) []*Tenant {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *TenantCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *TenantCreateBulk) 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/examples/privacytenant/ent/predicate"
"entgo.io/ent/examples/privacytenant/ent/tenant"
"entgo.io/ent/schema/field"
)
// TenantDelete is the builder for deleting a Tenant entity.
type TenantDelete struct {
config
hooks []Hook
mutation *TenantMutation
}
// Where appends a list predicates to the TenantDelete builder.
func (_d *TenantDelete) Where(ps ...predicate.Tenant) *TenantDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *TenantDelete) 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 *TenantDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *TenantDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(tenant.Table, sqlgraph.NewFieldSpec(tenant.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
}
// TenantDeleteOne is the builder for deleting a single Tenant entity.
type TenantDeleteOne struct {
_d *TenantDelete
}
// Where appends a list predicates to the TenantDelete builder.
func (_d *TenantDeleteOne) Where(ps ...predicate.Tenant) *TenantDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *TenantDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{tenant.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *TenantDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,538 @@
// 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"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/examples/privacytenant/ent/predicate"
"entgo.io/ent/examples/privacytenant/ent/tenant"
"entgo.io/ent/schema/field"
)
// TenantQuery is the builder for querying Tenant entities.
type TenantQuery struct {
config
ctx *QueryContext
order []tenant.OrderOption
inters []Interceptor
predicates []predicate.Tenant
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the TenantQuery builder.
func (_q *TenantQuery) Where(ps ...predicate.Tenant) *TenantQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *TenantQuery) Limit(limit int) *TenantQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *TenantQuery) Offset(offset int) *TenantQuery {
_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 *TenantQuery) Unique(unique bool) *TenantQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *TenantQuery) Order(o ...tenant.OrderOption) *TenantQuery {
_q.order = append(_q.order, o...)
return _q
}
// First returns the first Tenant entity from the query.
// Returns a *NotFoundError when no Tenant was found.
func (_q *TenantQuery) First(ctx context.Context) (*Tenant, 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{tenant.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *TenantQuery) FirstX(ctx context.Context) *Tenant {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Tenant ID from the query.
// Returns a *NotFoundError when no Tenant ID was found.
func (_q *TenantQuery) 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{tenant.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *TenantQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Tenant entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Tenant entity is found.
// Returns a *NotFoundError when no Tenant entities are found.
func (_q *TenantQuery) Only(ctx context.Context) (*Tenant, 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{tenant.Label}
default:
return nil, &NotSingularError{tenant.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *TenantQuery) OnlyX(ctx context.Context) *Tenant {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Tenant ID in the query.
// Returns a *NotSingularError when more than one Tenant ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *TenantQuery) 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{tenant.Label}
default:
err = &NotSingularError{tenant.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *TenantQuery) 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 Tenants.
func (_q *TenantQuery) All(ctx context.Context) ([]*Tenant, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Tenant, *TenantQuery]()
return withInterceptors[[]*Tenant](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *TenantQuery) AllX(ctx context.Context) []*Tenant {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Tenant IDs.
func (_q *TenantQuery) 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(tenant.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *TenantQuery) 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 *TenantQuery) 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[*TenantQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *TenantQuery) 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 *TenantQuery) 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 *TenantQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the TenantQuery 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 *TenantQuery) Clone() *TenantQuery {
if _q == nil {
return nil
}
return &TenantQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]tenant.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Tenant{}, _q.predicates...),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// 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.Tenant.Query().
// GroupBy(tenant.FieldName).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *TenantQuery) GroupBy(field string, fields ...string) *TenantGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &TenantGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = tenant.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.Tenant.Query().
// Select(tenant.FieldName).
// Scan(ctx, &v)
func (_q *TenantQuery) Select(fields ...string) *TenantSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &TenantSelect{TenantQuery: _q}
sbuild.label = tenant.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a TenantSelect configured with the given aggregations.
func (_q *TenantQuery) Aggregate(fns ...AggregateFunc) *TenantSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *TenantQuery) 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 !tenant.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 tenant.Policy == nil {
return errors.New("ent: uninitialized tenant.Policy (forgotten import ent/runtime?)")
}
if err := tenant.Policy.EvalQuery(ctx, _q); err != nil {
return err
}
return nil
}
func (_q *TenantQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Tenant, error) {
var (
nodes = []*Tenant{}
_spec = _q.querySpec()
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Tenant).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Tenant{config: _q.config}
nodes = append(nodes, node)
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
}
return nodes, nil
}
func (_q *TenantQuery) 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 *TenantQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(tenant.Table, tenant.Columns, sqlgraph.NewFieldSpec(tenant.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, tenant.FieldID)
for i := range fields {
if fields[i] != tenant.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 *TenantQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(tenant.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = tenant.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
}
// TenantGroupBy is the group-by builder for Tenant entities.
type TenantGroupBy struct {
selector
build *TenantQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *TenantGroupBy) Aggregate(fns ...AggregateFunc) *TenantGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *TenantGroupBy) 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[*TenantQuery, *TenantGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *TenantGroupBy) sqlScan(ctx context.Context, root *TenantQuery, 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)
}
// TenantSelect is the builder for selecting fields of Tenant entities.
type TenantSelect struct {
*TenantQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *TenantSelect) Aggregate(fns ...AggregateFunc) *TenantSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *TenantSelect) 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[*TenantQuery, *TenantSelect](ctx, _s.TenantQuery, _s, _s.inters, v)
}
func (_s *TenantSelect) sqlScan(ctx context.Context, root *TenantQuery, 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,239 @@
// 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/examples/privacytenant/ent/predicate"
"entgo.io/ent/examples/privacytenant/ent/tenant"
"entgo.io/ent/schema/field"
)
// TenantUpdate is the builder for updating Tenant entities.
type TenantUpdate struct {
config
hooks []Hook
mutation *TenantMutation
}
// Where appends a list predicates to the TenantUpdate builder.
func (_u *TenantUpdate) Where(ps ...predicate.Tenant) *TenantUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetName sets the "name" field.
func (_u *TenantUpdate) SetName(v string) *TenantUpdate {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *TenantUpdate) SetNillableName(v *string) *TenantUpdate {
if v != nil {
_u.SetName(*v)
}
return _u
}
// Mutation returns the TenantMutation object of the builder.
func (_u *TenantUpdate) Mutation() *TenantMutation {
return _u.mutation
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *TenantUpdate) 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 *TenantUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *TenantUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *TenantUpdate) 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 *TenantUpdate) check() error {
if v, ok := _u.mutation.Name(); ok {
if err := tenant.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Tenant.name": %w`, err)}
}
}
return nil
}
func (_u *TenantUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(tenant.Table, tenant.Columns, sqlgraph.NewFieldSpec(tenant.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(tenant.FieldName, field.TypeString, value)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{tenant.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// TenantUpdateOne is the builder for updating a single Tenant entity.
type TenantUpdateOne struct {
config
fields []string
hooks []Hook
mutation *TenantMutation
}
// SetName sets the "name" field.
func (_u *TenantUpdateOne) SetName(v string) *TenantUpdateOne {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *TenantUpdateOne) SetNillableName(v *string) *TenantUpdateOne {
if v != nil {
_u.SetName(*v)
}
return _u
}
// Mutation returns the TenantMutation object of the builder.
func (_u *TenantUpdateOne) Mutation() *TenantMutation {
return _u.mutation
}
// Where appends a list predicates to the TenantUpdate builder.
func (_u *TenantUpdateOne) Where(ps ...predicate.Tenant) *TenantUpdateOne {
_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 *TenantUpdateOne) Select(field string, fields ...string) *TenantUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated Tenant entity.
func (_u *TenantUpdateOne) Save(ctx context.Context) (*Tenant, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *TenantUpdateOne) SaveX(ctx context.Context) *Tenant {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *TenantUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *TenantUpdateOne) 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 *TenantUpdateOne) check() error {
if v, ok := _u.mutation.Name(); ok {
if err := tenant.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Tenant.name": %w`, err)}
}
}
return nil
}
func (_u *TenantUpdateOne) sqlSave(ctx context.Context) (_node *Tenant, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(tenant.Table, tenant.Columns, sqlgraph.NewFieldSpec(tenant.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Tenant.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, tenant.FieldID)
for _, f := range fields {
if !tenant.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != tenant.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(tenant.FieldName, field.TypeString, value)
}
_node = &Tenant{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{tenant.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
// Group is the client for interacting with the Group builders.
Group *GroupClient
// Tenant is the client for interacting with the Tenant builders.
Tenant *TenantClient
// 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.Group = NewGroupClient(tx.config)
tx.Tenant = NewTenantClient(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: Group.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,179 @@
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"encoding/json"
"fmt"
"strings"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/examples/privacytenant/ent/tenant"
"entgo.io/ent/examples/privacytenant/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"`
// TenantID holds the value of the "tenant_id" field.
TenantID int `json:"tenant_id,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// Foods holds the value of the "foods" field.
Foods []string `json:"foods,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 {
// Tenant holds the value of the tenant edge.
Tenant *Tenant `json:"tenant,omitempty"`
// Groups holds the value of the groups edge.
Groups []*Group `json:"groups,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// TenantOrErr returns the Tenant value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e UserEdges) TenantOrErr() (*Tenant, error) {
if e.Tenant != nil {
return e.Tenant, nil
} else if e.loadedTypes[0] {
return nil, &NotFoundError{label: tenant.Label}
}
return nil, &NotLoadedError{edge: "tenant"}
}
// GroupsOrErr returns the Groups value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) GroupsOrErr() ([]*Group, error) {
if e.loadedTypes[1] {
return e.Groups, nil
}
return nil, &NotLoadedError{edge: "groups"}
}
// 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.FieldFoods:
values[i] = new([]byte)
case user.FieldID, user.FieldTenantID:
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.FieldTenantID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field tenant_id", values[i])
} else if value.Valid {
_m.TenantID = 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.FieldFoods:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field foods", values[i])
} else if value != nil && len(*value) > 0 {
if err := json.Unmarshal(*value, &_m.Foods); err != nil {
return fmt.Errorf("unmarshal field foods: %w", err)
}
}
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)
}
// QueryTenant queries the "tenant" edge of the User entity.
func (_m *User) QueryTenant() *TenantQuery {
return NewUserClient(_m.config).QueryTenant(_m)
}
// QueryGroups queries the "groups" edge of the User entity.
func (_m *User) QueryGroups() *GroupQuery {
return NewUserClient(_m.config).QueryGroups(_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("tenant_id=")
builder.WriteString(fmt.Sprintf("%v", _m.TenantID))
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(_m.Name)
builder.WriteString(", ")
builder.WriteString("foods=")
builder.WriteString(fmt.Sprintf("%v", _m.Foods))
builder.WriteByte(')')
return builder.String()
}
// Users is a parsable slice of User.
type Users []*User

View File

@@ -0,0 +1,484 @@
// 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/examples/privacytenant/ent/predicate"
)
// Mutation represents an operation that mutates the User nodes in the graph.
type Mutation struct {
op ent.Op
typ string
name *string
foods *[]string
appendfoods []string
clearedFields map[string]struct{}
tenant *int
clearedtenant bool
groups map[int]struct{}
removedgroups map[int]struct{}
clearedgroups 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
}
// SetTenantID sets the "tenant_id" field.
func (m *Mutation) SetTenantID(i int) {
m.tenant = &i
}
// TenantID returns the value of the "tenant_id" field in the mutation.
func (m *Mutation) TenantID() (r int, exists bool) {
v := m.tenant
if v == nil {
return
}
return *v, true
}
// ResetTenantID resets all changes to the "tenant_id" field.
func (m *Mutation) ResetTenantID() {
m.tenant = nil
}
// 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
}
// SetFoods sets the "foods" field.
func (m *Mutation) SetFoods(s []string) {
m.foods = &s
m.appendfoods = nil
}
// Foods returns the value of the "foods" field in the mutation.
func (m *Mutation) Foods() (r []string, exists bool) {
v := m.foods
if v == nil {
return
}
return *v, true
}
// AppendFoods adds s to the "foods" field.
func (m *Mutation) AppendFoods(s []string) {
m.appendfoods = append(m.appendfoods, s...)
}
// AppendedFoods returns the list of values that were appended to the "foods" field in this mutation.
func (m *Mutation) AppendedFoods() ([]string, bool) {
if len(m.appendfoods) == 0 {
return nil, false
}
return m.appendfoods, true
}
// ClearFoods clears the value of the "foods" field.
func (m *Mutation) ClearFoods() {
m.foods = nil
m.appendfoods = nil
m.clearedFields[FieldFoods] = struct{}{}
}
// FoodsCleared returns if the "foods" field was cleared in this mutation.
func (m *Mutation) FoodsCleared() bool {
_, ok := m.clearedFields[FieldFoods]
return ok
}
// ResetFoods resets all changes to the "foods" field.
func (m *Mutation) ResetFoods() {
m.foods = nil
m.appendfoods = nil
delete(m.clearedFields, FieldFoods)
}
// ClearTenant clears the "tenant" edge to the Tenant entity.
func (m *Mutation) ClearTenant() {
m.clearedtenant = true
m.clearedFields[FieldTenantID] = struct{}{}
}
// TenantCleared reports if the "tenant" edge to the Tenant entity was cleared.
func (m *Mutation) TenantCleared() bool {
return m.clearedtenant
}
// TenantIDs returns the "tenant" edge IDs in the mutation.
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
// TenantID instead. It exists only for internal usage by the builders.
func (m *Mutation) TenantIDs() (ids []int) {
if id := m.tenant; id != nil {
ids = append(ids, *id)
}
return
}
// ResetTenant resets all changes to the "tenant" edge.
func (m *Mutation) ResetTenant() {
m.tenant = nil
m.clearedtenant = false
}
// AddGroupIDs adds the "groups" edge to the Group entity by ids.
func (m *Mutation) AddGroupIDs(ids ...int) {
if m.groups == nil {
m.groups = make(map[int]struct{})
}
for i := range ids {
m.groups[ids[i]] = struct{}{}
}
}
// ClearGroups clears the "groups" edge to the Group entity.
func (m *Mutation) ClearGroups() {
m.clearedgroups = true
}
// GroupsCleared reports if the "groups" edge to the Group entity was cleared.
func (m *Mutation) GroupsCleared() bool {
return m.clearedgroups
}
// RemoveGroupIDs removes the "groups" edge to the Group entity by IDs.
func (m *Mutation) RemoveGroupIDs(ids ...int) {
if m.removedgroups == nil {
m.removedgroups = make(map[int]struct{})
}
for i := range ids {
delete(m.groups, ids[i])
m.removedgroups[ids[i]] = struct{}{}
}
}
// RemovedGroups returns the removed IDs of the "groups" edge to the Group entity.
func (m *Mutation) RemovedGroupsIDs() (ids []int) {
for id := range m.removedgroups {
ids = append(ids, id)
}
return
}
// GroupsIDs returns the "groups" edge IDs in the mutation.
func (m *Mutation) GroupsIDs() (ids []int) {
for id := range m.groups {
ids = append(ids, id)
}
return
}
// ResetGroups resets all changes to the "groups" edge.
func (m *Mutation) ResetGroups() {
m.groups = nil
m.clearedgroups = false
m.removedgroups = 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, 3)
if m.tenant != nil {
fields = append(fields, FieldTenantID)
}
if m.name != nil {
fields = append(fields, FieldName)
}
if m.foods != nil {
fields = append(fields, FieldFoods)
}
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 FieldTenantID:
return m.TenantID()
case FieldName:
return m.Name()
case FieldFoods:
return m.Foods()
}
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 FieldTenantID:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetTenantID(v)
return nil
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 FieldFoods:
v, ok := value.([]string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetFoods(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
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 {
}
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 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(FieldFoods) {
fields = append(fields, FieldFoods)
}
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 FieldFoods:
m.ClearFoods()
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 FieldTenantID:
m.ResetTenantID()
return nil
case FieldName:
m.ResetName()
return nil
case FieldFoods:
m.ResetFoods()
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.tenant != nil {
edges = append(edges, EdgeTenant)
}
if m.groups != nil {
edges = append(edges, EdgeGroups)
}
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 EdgeTenant:
if id := m.tenant; id != nil {
return []ent.Value{*id}
}
case EdgeGroups:
ids := make([]ent.Value, 0, len(m.groups))
for id := range m.groups {
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.removedgroups != nil {
edges = append(edges, EdgeGroups)
}
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 EdgeGroups:
ids := make([]ent.Value, 0, len(m.removedgroups))
for id := range m.removedgroups {
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.clearedtenant {
edges = append(edges, EdgeTenant)
}
if m.clearedgroups {
edges = append(edges, EdgeGroups)
}
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 EdgeTenant:
return m.clearedtenant
case EdgeGroups:
return m.clearedgroups
}
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 EdgeTenant:
m.ClearTenant()
return nil
}
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 EdgeTenant:
m.ResetTenant()
return nil
case EdgeGroups:
m.ResetGroups()
return nil
}
return fmt.Errorf("unknown User edge %s", name)
}

View File

@@ -0,0 +1,133 @@
// 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"
// FieldTenantID holds the string denoting the tenant_id field in the database.
FieldTenantID = "tenant_id"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldFoods holds the string denoting the foods field in the database.
FieldFoods = "foods"
// EdgeTenant holds the string denoting the tenant edge name in mutations.
EdgeTenant = "tenant"
// EdgeGroups holds the string denoting the groups edge name in mutations.
EdgeGroups = "groups"
// Table holds the table name of the user in the database.
Table = "users"
// TenantTable is the table that holds the tenant relation/edge.
TenantTable = "users"
// TenantInverseTable is the table name for the Tenant entity.
// It exists in this package in order to avoid circular dependency with the "tenant" package.
TenantInverseTable = "tenants"
// TenantColumn is the table column denoting the tenant relation/edge.
TenantColumn = "tenant_id"
// GroupsTable is the table that holds the groups relation/edge. The primary key declared below.
GroupsTable = "user_groups"
// GroupsInverseTable is the table name for the Group entity.
// It exists in this package in order to avoid circular dependency with the "group" package.
GroupsInverseTable = "groups"
)
// Columns holds all SQL columns for user fields.
var Columns = []string{
FieldID,
FieldTenantID,
FieldName,
FieldFoods,
}
var (
// GroupsPrimaryKey and GroupsColumn2 are the table columns denoting the
// primary key for the groups relation (M2M).
GroupsPrimaryKey = []string{"user_id", "group_id"}
)
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
// 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/examples/privacytenant/ent/runtime"
var (
Hooks [1]ent.Hook
Policy ent.Policy
// DefaultName holds the default value on creation for the "name" field.
DefaultName string
)
// 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()
}
// ByTenantID orders the results by the tenant_id field.
func ByTenantID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldTenantID, opts...).ToFunc()
}
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, opts...).ToFunc()
}
// ByTenantField orders the results by tenant field.
func ByTenantField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newTenantStep(), sql.OrderByField(field, opts...))
}
}
// ByGroupsCount orders the results by groups count.
func ByGroupsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newGroupsStep(), opts...)
}
}
// ByGroups orders the results by groups terms.
func ByGroups(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newGroupsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
func newTenantStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(TenantInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, TenantTable, TenantColumn),
)
}
func newGroupsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(GroupsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, GroupsTable, GroupsPrimaryKey...),
)
}

View File

@@ -0,0 +1,224 @@
// 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/examples/privacytenant/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))
}
// TenantID applies equality check predicate on the "tenant_id" field. It's identical to TenantIDEQ.
func TenantID(v int) predicate.User {
return predicate.User(sql.FieldEQ(FieldTenantID, v))
}
// 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))
}
// TenantIDEQ applies the EQ predicate on the "tenant_id" field.
func TenantIDEQ(v int) predicate.User {
return predicate.User(sql.FieldEQ(FieldTenantID, v))
}
// TenantIDNEQ applies the NEQ predicate on the "tenant_id" field.
func TenantIDNEQ(v int) predicate.User {
return predicate.User(sql.FieldNEQ(FieldTenantID, v))
}
// TenantIDIn applies the In predicate on the "tenant_id" field.
func TenantIDIn(vs ...int) predicate.User {
return predicate.User(sql.FieldIn(FieldTenantID, vs...))
}
// TenantIDNotIn applies the NotIn predicate on the "tenant_id" field.
func TenantIDNotIn(vs ...int) predicate.User {
return predicate.User(sql.FieldNotIn(FieldTenantID, vs...))
}
// 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))
}
// FoodsIsNil applies the IsNil predicate on the "foods" field.
func FoodsIsNil() predicate.User {
return predicate.User(sql.FieldIsNull(FieldFoods))
}
// FoodsNotNil applies the NotNil predicate on the "foods" field.
func FoodsNotNil() predicate.User {
return predicate.User(sql.FieldNotNull(FieldFoods))
}
// HasTenant applies the HasEdge predicate on the "tenant" edge.
func HasTenant() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, TenantTable, TenantColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasTenantWith applies the HasEdge predicate on the "tenant" edge with a given conditions (other predicates).
func HasTenantWith(preds ...predicate.Tenant) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newTenantStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasGroups applies the HasEdge predicate on the "groups" edge.
func HasGroups() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, GroupsTable, GroupsPrimaryKey...),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasGroupsWith applies the HasEdge predicate on the "groups" edge with a given conditions (other predicates).
func HasGroupsWith(preds ...predicate.Group) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newGroupsStep()
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,285 @@
// 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/examples/privacytenant/ent/group"
"entgo.io/ent/examples/privacytenant/ent/tenant"
"entgo.io/ent/examples/privacytenant/ent/user"
"entgo.io/ent/schema/field"
)
// UserCreate is the builder for creating a User entity.
type UserCreate struct {
config
mutation *UserMutation
hooks []Hook
}
// SetTenantID sets the "tenant_id" field.
func (_c *UserCreate) SetTenantID(v int) *UserCreate {
_c.mutation.SetTenantID(v)
return _c
}
// SetName sets the "name" field.
func (_c *UserCreate) SetName(v string) *UserCreate {
_c.mutation.SetName(v)
return _c
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_c *UserCreate) SetNillableName(v *string) *UserCreate {
if v != nil {
_c.SetName(*v)
}
return _c
}
// SetFoods sets the "foods" field.
func (_c *UserCreate) SetFoods(v []string) *UserCreate {
_c.mutation.SetFoods(v)
return _c
}
// SetTenant sets the "tenant" edge to the Tenant entity.
func (_c *UserCreate) SetTenant(v *Tenant) *UserCreate {
return _c.SetTenantID(v.ID)
}
// AddGroupIDs adds the "groups" edge to the Group entity by IDs.
func (_c *UserCreate) AddGroupIDs(ids ...int) *UserCreate {
_c.mutation.AddGroupIDs(ids...)
return _c
}
// AddGroups adds the "groups" edges to the Group entity.
func (_c *UserCreate) AddGroups(v ...*Group) *UserCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddGroupIDs(ids...)
}
// Mutation returns the UserMutation object of the builder.
func (_c *UserCreate) Mutation() *UserMutation {
return _c.mutation
}
// Save creates the User in the database.
func (_c *UserCreate) Save(ctx context.Context) (*User, 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 *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)
}
}
// defaults sets the default values of the builder before save.
func (_c *UserCreate) defaults() error {
if _, ok := _c.mutation.Name(); !ok {
v := user.DefaultName
_c.mutation.SetName(v)
}
return nil
}
// check runs all checks and user-defined validators on the builder.
func (_c *UserCreate) check() error {
if _, ok := _c.mutation.TenantID(); !ok {
return &ValidationError{Name: "tenant_id", err: errors.New(`ent: missing required field "User.tenant_id"`)}
}
if _, ok := _c.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "User.name"`)}
}
if len(_c.mutation.TenantIDs()) == 0 {
return &ValidationError{Name: "tenant", err: errors.New(`ent: missing required edge "User.tenant"`)}
}
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.Foods(); ok {
_spec.SetField(user.FieldFoods, field.TypeJSON, value)
_node.Foods = value
}
if nodes := _c.mutation.TenantIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: user.TenantTable,
Columns: []string{user.TenantColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(tenant.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.TenantID = nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.GroupsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.GroupsTable,
Columns: user.GroupsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// 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]
builder.defaults()
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/examples/privacytenant/ent/predicate"
"entgo.io/ent/examples/privacytenant/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/examples/privacytenant/ent/group"
"entgo.io/ent/examples/privacytenant/ent/predicate"
"entgo.io/ent/examples/privacytenant/ent/tenant"
"entgo.io/ent/examples/privacytenant/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
withTenant *TenantQuery
withGroups *GroupQuery
// 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
}
// QueryTenant chains the current query on the "tenant" edge.
func (_q *UserQuery) QueryTenant() *TenantQuery {
query := (&TenantClient{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(tenant.Table, tenant.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, user.TenantTable, user.TenantColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryGroups chains the current query on the "groups" edge.
func (_q *UserQuery) QueryGroups() *GroupQuery {
query := (&GroupClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, selector),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, user.GroupsTable, user.GroupsPrimaryKey...),
)
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...),
withTenant: _q.withTenant.Clone(),
withGroups: _q.withGroups.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// WithTenant tells the query-builder to eager-load the nodes that are connected to
// the "tenant" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *UserQuery) WithTenant(opts ...func(*TenantQuery)) *UserQuery {
query := (&TenantClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withTenant = query
return _q
}
// WithGroups tells the query-builder to eager-load the nodes that are connected to
// the "groups" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *UserQuery) WithGroups(opts ...func(*GroupQuery)) *UserQuery {
query := (&GroupClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withGroups = 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 {
// TenantID int `json:"tenant_id,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.User.Query().
// GroupBy(user.FieldTenantID).
// 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 {
// TenantID int `json:"tenant_id,omitempty"`
// }
//
// client.User.Query().
// Select(user.FieldTenantID).
// 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.withTenant != nil,
_q.withGroups != 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.withTenant; query != nil {
if err := _q.loadTenant(ctx, query, nodes, nil,
func(n *User, e *Tenant) { n.Edges.Tenant = e }); err != nil {
return nil, err
}
}
if query := _q.withGroups; query != nil {
if err := _q.loadGroups(ctx, query, nodes,
func(n *User) { n.Edges.Groups = []*Group{} },
func(n *User, e *Group) { n.Edges.Groups = append(n.Edges.Groups, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *UserQuery) loadTenant(ctx context.Context, query *TenantQuery, nodes []*User, init func(*User), assign func(*User, *Tenant)) error {
ids := make([]int, 0, len(nodes))
nodeids := make(map[int][]*User)
for i := range nodes {
fk := nodes[i].TenantID
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(tenant.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 "tenant_id" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *UserQuery) loadGroups(ctx context.Context, query *GroupQuery, nodes []*User, init func(*User), assign func(*User, *Group)) error {
edgeIDs := make([]driver.Value, len(nodes))
byID := make(map[int]*User)
nids := make(map[int]map[*User]struct{})
for i, node := range nodes {
edgeIDs[i] = node.ID
byID[node.ID] = node
if init != nil {
init(node)
}
}
query.Where(func(s *sql.Selector) {
joinT := sql.Table(user.GroupsTable)
s.Join(joinT).On(s.C(group.FieldID), joinT.C(user.GroupsPrimaryKey[1]))
s.Where(sql.InValues(joinT.C(user.GroupsPrimaryKey[0]), edgeIDs...))
columns := s.SelectedColumns()
s.Select(joinT.C(user.GroupsPrimaryKey[0]))
s.AppendSelect(columns...)
s.SetDistinct(false)
})
if err := query.prepareQuery(ctx); err != nil {
return err
}
qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) {
assign := spec.Assign
values := spec.ScanValues
spec.ScanValues = func(columns []string) ([]any, error) {
values, err := values(columns[1:])
if err != nil {
return nil, err
}
return append([]any{new(sql.NullInt64)}, values...), nil
}
spec.Assign = func(columns []string, values []any) error {
outValue := int(values[0].(*sql.NullInt64).Int64)
inValue := int(values[1].(*sql.NullInt64).Int64)
if nids[inValue] == nil {
nids[inValue] = map[*User]struct{}{byID[outValue]: {}}
return assign(columns[1:], values[1:])
}
nids[inValue][byID[outValue]] = struct{}{}
return nil
}
})
})
neighbors, err := withInterceptors[[]*Group](ctx, query, qr, query.inters)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nids[n.ID]
if !ok {
return fmt.Errorf(`unexpected "groups" node returned %v`, n.ID)
}
for kn := range nodes {
assign(kn, n)
}
}
return nil
}
func (_q *UserQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Columns = _q.ctx.Fields
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 _q.withTenant != nil {
_spec.Node.AddColumnOnce(user.FieldTenantID)
}
}
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,457 @@
// 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/dialect/sql/sqljson"
"entgo.io/ent/examples/privacytenant/ent/group"
"entgo.io/ent/examples/privacytenant/ent/predicate"
"entgo.io/ent/examples/privacytenant/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
}
// SetName sets the "name" field.
func (_u *UserUpdate) SetName(v string) *UserUpdate {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *UserUpdate) SetNillableName(v *string) *UserUpdate {
if v != nil {
_u.SetName(*v)
}
return _u
}
// SetFoods sets the "foods" field.
func (_u *UserUpdate) SetFoods(v []string) *UserUpdate {
_u.mutation.SetFoods(v)
return _u
}
// AppendFoods appends value to the "foods" field.
func (_u *UserUpdate) AppendFoods(v []string) *UserUpdate {
_u.mutation.AppendFoods(v)
return _u
}
// ClearFoods clears the value of the "foods" field.
func (_u *UserUpdate) ClearFoods() *UserUpdate {
_u.mutation.ClearFoods()
return _u
}
// AddGroupIDs adds the "groups" edge to the Group entity by IDs.
func (_u *UserUpdate) AddGroupIDs(ids ...int) *UserUpdate {
_u.mutation.AddGroupIDs(ids...)
return _u
}
// AddGroups adds the "groups" edges to the Group entity.
func (_u *UserUpdate) AddGroups(v ...*Group) *UserUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddGroupIDs(ids...)
}
// Mutation returns the UserMutation object of the builder.
func (_u *UserUpdate) Mutation() *UserMutation {
return _u.mutation
}
// ClearGroups clears all "groups" edges to the Group entity.
func (_u *UserUpdate) ClearGroups() *UserUpdate {
_u.mutation.ClearGroups()
return _u
}
// RemoveGroupIDs removes the "groups" edge to Group entities by IDs.
func (_u *UserUpdate) RemoveGroupIDs(ids ...int) *UserUpdate {
_u.mutation.RemoveGroupIDs(ids...)
return _u
}
// RemoveGroups removes "groups" edges to Group entities.
func (_u *UserUpdate) RemoveGroups(v ...*Group) *UserUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveGroupIDs(ids...)
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *UserUpdate) Save(ctx context.Context) (int, error) {
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)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *UserUpdate) check() error {
if _u.mutation.TenantCleared() && len(_u.mutation.TenantIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "User.tenant"`)
}
return nil
}
func (_u *UserUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_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.Name(); ok {
_spec.SetField(user.FieldName, field.TypeString, value)
}
if value, ok := _u.mutation.Foods(); ok {
_spec.SetField(user.FieldFoods, field.TypeJSON, value)
}
if value, ok := _u.mutation.AppendedFoods(); ok {
_spec.AddModifier(func(u *sql.UpdateBuilder) {
sqljson.Append(u, user.FieldFoods, value)
})
}
if _u.mutation.FoodsCleared() {
_spec.ClearField(user.FieldFoods, field.TypeJSON)
}
if _u.mutation.GroupsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.GroupsTable,
Columns: user.GroupsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedGroupsIDs(); len(nodes) > 0 && !_u.mutation.GroupsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.GroupsTable,
Columns: user.GroupsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.GroupsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.GroupsTable,
Columns: user.GroupsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{user.Label}
} 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
}
// SetName sets the "name" field.
func (_u *UserUpdateOne) SetName(v string) *UserUpdateOne {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *UserUpdateOne) SetNillableName(v *string) *UserUpdateOne {
if v != nil {
_u.SetName(*v)
}
return _u
}
// SetFoods sets the "foods" field.
func (_u *UserUpdateOne) SetFoods(v []string) *UserUpdateOne {
_u.mutation.SetFoods(v)
return _u
}
// AppendFoods appends value to the "foods" field.
func (_u *UserUpdateOne) AppendFoods(v []string) *UserUpdateOne {
_u.mutation.AppendFoods(v)
return _u
}
// ClearFoods clears the value of the "foods" field.
func (_u *UserUpdateOne) ClearFoods() *UserUpdateOne {
_u.mutation.ClearFoods()
return _u
}
// AddGroupIDs adds the "groups" edge to the Group entity by IDs.
func (_u *UserUpdateOne) AddGroupIDs(ids ...int) *UserUpdateOne {
_u.mutation.AddGroupIDs(ids...)
return _u
}
// AddGroups adds the "groups" edges to the Group entity.
func (_u *UserUpdateOne) AddGroups(v ...*Group) *UserUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddGroupIDs(ids...)
}
// Mutation returns the UserMutation object of the builder.
func (_u *UserUpdateOne) Mutation() *UserMutation {
return _u.mutation
}
// ClearGroups clears all "groups" edges to the Group entity.
func (_u *UserUpdateOne) ClearGroups() *UserUpdateOne {
_u.mutation.ClearGroups()
return _u
}
// RemoveGroupIDs removes the "groups" edge to Group entities by IDs.
func (_u *UserUpdateOne) RemoveGroupIDs(ids ...int) *UserUpdateOne {
_u.mutation.RemoveGroupIDs(ids...)
return _u
}
// RemoveGroups removes "groups" edges to Group entities.
func (_u *UserUpdateOne) RemoveGroups(v ...*Group) *UserUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveGroupIDs(ids...)
}
// Where appends a list predicates to the UserUpdate builder.
func (_u *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne {
_u.mutation.Where(ps...)
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)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *UserUpdateOne) check() error {
if _u.mutation.TenantCleared() && len(_u.mutation.TenantIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "User.tenant"`)
}
return nil
}
func (_u *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_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.Name(); ok {
_spec.SetField(user.FieldName, field.TypeString, value)
}
if value, ok := _u.mutation.Foods(); ok {
_spec.SetField(user.FieldFoods, field.TypeJSON, value)
}
if value, ok := _u.mutation.AppendedFoods(); ok {
_spec.AddModifier(func(u *sql.UpdateBuilder) {
sqljson.Append(u, user.FieldFoods, value)
})
}
if _u.mutation.FoodsCleared() {
_spec.ClearField(user.FieldFoods, field.TypeJSON)
}
if _u.mutation.GroupsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.GroupsTable,
Columns: user.GroupsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedGroupsIDs(); len(nodes) > 0 && !_u.mutation.GroupsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.GroupsTable,
Columns: user.GroupsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.GroupsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.GroupsTable,
Columns: user.GroupsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &User{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
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
}