From 94f69b0acb90b90c7339675610e92c9b46caeff9 Mon Sep 17 00:00:00 2001 From: Ariel Mashraki <7413593+a8m@users.noreply.github.com> Date: Sat, 13 Jul 2024 10:41:27 +0300 Subject: [PATCH] doc: explain how to use triggers in migrations (#4138) --- doc/md/hooks.md | 9 +- doc/md/migration/trigger.mdx | 259 +++++ doc/website/sidebars.js | 1 + examples/compositetypes/example_test.go | 2 +- examples/domaintypes/example_test.go | 2 +- examples/enumtypes/example_test.go | 6 +- examples/triggers/README.md | 3 + examples/triggers/atlas.hcl | 15 + examples/triggers/ent/client.go | 483 ++++++++++ examples/triggers/ent/ent.go | 610 ++++++++++++ examples/triggers/ent/enttest/enttest.go | 84 ++ examples/triggers/ent/generate.go | 3 + examples/triggers/ent/hook/hook.go | 211 +++++ examples/triggers/ent/migrate/migrate.go | 64 ++ examples/triggers/ent/migrate/schema.go | 44 + examples/triggers/ent/mutation.go | 884 ++++++++++++++++++ examples/triggers/ent/predicate/predicate.go | 13 + examples/triggers/ent/runtime.go | 9 + examples/triggers/ent/runtime/runtime.go | 9 + examples/triggers/ent/schema/user.go | 39 + examples/triggers/ent/tx.go | 213 +++++ examples/triggers/ent/user.go | 103 ++ examples/triggers/ent/user/user.go | 47 + examples/triggers/ent/user/where.go | 138 +++ examples/triggers/ent/user_create.go | 183 ++++ examples/triggers/ent/user_delete.go | 88 ++ examples/triggers/ent/user_query.go | 527 +++++++++++ examples/triggers/ent/user_update.go | 209 +++++ examples/triggers/ent/userauditlog.go | 136 +++ .../triggers/ent/userauditlog/userauditlog.go | 71 ++ examples/triggers/ent/userauditlog/where.go | 368 ++++++++ examples/triggers/ent/userauditlog_create.go | 232 +++++ examples/triggers/ent/userauditlog_delete.go | 88 ++ examples/triggers/ent/userauditlog_query.go | 527 +++++++++++ examples/triggers/ent/userauditlog_update.go | 347 +++++++ examples/triggers/example_test.go | 61 ++ .../triggers/migrations/20240713061538.sql | 29 + examples/triggers/migrations/atlas.sum | 2 + examples/triggers/schema.sql | 29 + 39 files changed, 6140 insertions(+), 8 deletions(-) create mode 100644 doc/md/migration/trigger.mdx create mode 100644 examples/triggers/README.md create mode 100644 examples/triggers/atlas.hcl create mode 100644 examples/triggers/ent/client.go create mode 100644 examples/triggers/ent/ent.go create mode 100644 examples/triggers/ent/enttest/enttest.go create mode 100644 examples/triggers/ent/generate.go create mode 100644 examples/triggers/ent/hook/hook.go create mode 100644 examples/triggers/ent/migrate/migrate.go create mode 100644 examples/triggers/ent/migrate/schema.go create mode 100644 examples/triggers/ent/mutation.go create mode 100644 examples/triggers/ent/predicate/predicate.go create mode 100644 examples/triggers/ent/runtime.go create mode 100644 examples/triggers/ent/runtime/runtime.go create mode 100644 examples/triggers/ent/schema/user.go create mode 100644 examples/triggers/ent/tx.go create mode 100644 examples/triggers/ent/user.go create mode 100644 examples/triggers/ent/user/user.go create mode 100644 examples/triggers/ent/user/where.go create mode 100644 examples/triggers/ent/user_create.go create mode 100644 examples/triggers/ent/user_delete.go create mode 100644 examples/triggers/ent/user_query.go create mode 100644 examples/triggers/ent/user_update.go create mode 100644 examples/triggers/ent/userauditlog.go create mode 100644 examples/triggers/ent/userauditlog/userauditlog.go create mode 100644 examples/triggers/ent/userauditlog/where.go create mode 100644 examples/triggers/ent/userauditlog_create.go create mode 100644 examples/triggers/ent/userauditlog_delete.go create mode 100644 examples/triggers/ent/userauditlog_query.go create mode 100644 examples/triggers/ent/userauditlog_update.go create mode 100644 examples/triggers/example_test.go create mode 100644 examples/triggers/migrations/20240713061538.sql create mode 100644 examples/triggers/migrations/atlas.sum create mode 100644 examples/triggers/schema.sql diff --git a/doc/md/hooks.md b/doc/md/hooks.md index d3e7b58b2..e7c78491d 100644 --- a/doc/md/hooks.md +++ b/doc/md/hooks.md @@ -18,10 +18,13 @@ There are 5 types of mutations: - `Delete` - Delete all nodes that match a predicate. Each generated node type has its own type of mutation. For example, all [`User` builders](crud.mdx#create-an-entity), share -the same generated `UserMutation` object. +the same generated `UserMutation` object. However, all builder types implement the generic `ent.Mutation` interface. + +:::info Support For Database Triggers +Unlike database triggers, hooks are executed at the application level, not the database level. If you need to execute +specific logic on the database level, use database triggers as explained in the [schema migration guide](/docs/migration/triggers). +::: -However, all builder types implement the generic `ent.Mutation` interface. - ## Hooks Hooks are functions that get an `ent.Mutator` and return a mutator back. diff --git a/doc/md/migration/trigger.mdx b/doc/md/migration/trigger.mdx new file mode 100644 index 000000000..389d22bf5 --- /dev/null +++ b/doc/md/migration/trigger.mdx @@ -0,0 +1,259 @@ +--- +title: Using Database Triggers in Ent Schema +id: trigger +slug: triggers +--- + +import InstallationInstructions from '../components/_installation_instructions.mdx'; + +Triggers are useful tools in relational databases that allow you to execute custom code when specific events occur on a +table. For instance, triggers can automatically populate the audit log table whenever a new mutation is applied to a different table. +This way we ensure that all changes (including those made by other applications) are meticulously recorded, enabling the enforcement +on the database-level and reducing the need for additional code in the applications. + +This guide explains how to attach triggers to your Ent types (objects) and configure the schema migration to manage +both the triggers and the Ent schema as a single migration unit using Atlas. + +:::info [Atlas Pro Feature](https://atlasgo.io/features#pro-plan) +Atlas support for [Triggers](https://atlasgo.io/atlas-schema/hcl#trigger) used in this guide is available exclusively +to Pro users. To use this feature, run: +``` +atlas login +``` +::: + +## Install Atlas + + + +## Login to Atlas + +```shell +$ atlas login a8m +//highlight-next-line-info +You are now connected to "a8m" on Atlas Cloud. +``` + +## Composite Schema + +An `ent/schema` package is mostly used for defining Ent types (objects), their fields, edges and logic. Table triggers +or any other database native objects do not have representation in Ent models. A trigger function can be defined once, +and used in multiple triggers in different tables. + +In order to extend our PostgreSQL schema to include both our Ent types and their triggers, we configure Atlas to +read the state of the schema from a [Composite Schema](https://atlasgo.io/atlas-schema/projects#data-source-composite_schema) +data source. Follow the steps below to configure this for your project: + +1\. Let's define a simple schema with two types (tables): `users` and `user_audit_logs`: + +```go title="ent/schema/user.go" +// User holds the schema definition for the User entity. +type User struct { + ent.Schema +} + +// Fields of the User. +func (User) Fields() []ent.Field { + return []ent.Field{ + field.String("name"), + } +} + +// UserAuditLog holds the schema definition for the UserAuditLog entity. +type UserAuditLog struct { + ent.Schema +} + +// Fields of the UserAuditLog. +func (UserAuditLog) Fields() []ent.Field { + return []ent.Field{ + field.String("operation_type"), + field.String("operation_time"), + field.String("old_value"). + Optional(), + field.String("new_value"). + Optional(), + } +} +``` + +Now, suppose we want to log every change to the `users` table and save it in the `user_audit_logs` table. +To achieve this, we need to create a trigger function on `INSERT`, `UPDATE` and `DELETE` operations and attach it to +the `users` table. + +2\. Next step, we define a trigger function ( `audit_users_changes`) and attach it to the `users` table using the `CREATE TRIGGER` commands: + +```sql title="schema.sql" {23,26,29} +-- Function to audit changes in the users table. +CREATE OR REPLACE FUNCTION audit_users_changes() +RETURNS TRIGGER AS $$ +BEGIN + IF (TG_OP = 'INSERT') THEN + INSERT INTO user_audit_logs(operation_type, operation_time, new_value) + VALUES (TG_OP, CURRENT_TIMESTAMP, row_to_json(NEW)); + RETURN NEW; + ELSIF (TG_OP = 'UPDATE') THEN + INSERT INTO user_audit_logs(operation_type, operation_time, old_value, new_value) + VALUES (TG_OP, CURRENT_TIMESTAMP, row_to_json(OLD), row_to_json(NEW)); + RETURN NEW; + ELSIF (TG_OP = 'DELETE') THEN + INSERT INTO user_audit_logs(operation_type, operation_time, old_value) + VALUES (TG_OP, CURRENT_TIMESTAMP, row_to_json(OLD)); + RETURN OLD; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +-- Trigger for INSERT operations. +CREATE TRIGGER users_insert_audit AFTER INSERT ON users FOR EACH ROW EXECUTE FUNCTION audit_users_changes(); + +-- Trigger for UPDATE operations. +CREATE TRIGGER users_update_audit AFTER UPDATE ON users FOR EACH ROW EXECUTE FUNCTION audit_users_changes(); + +-- Trigger for DELETE operations. +CREATE TRIGGER users_delete_audit AFTER DELETE ON users FOR EACH ROW EXECUTE FUNCTION audit_users_changes(); +``` + + +3\. Lastly, we create a simple `atlas.hcl` config file with a `composite_schema` that includes both our Ent schema and +the custom triggers defined in `schema.sql`: + +```hcl title="atlas.hcl" +data "composite_schema" "app" { + # Load the ent schema first with all tables. + schema "public" { + url = "ent://ent/schema" + } + # Then, load the triggers schema. + schema "public" { + url = "file://schema.sql" + } +} + +env "local" { + src = data.composite_schema.app.url + dev = "docker://postgres/15/dev?search_path=public" +} +``` + +## Usage + +After setting up our composite schema, we can get its representation using the `atlas schema inspect` command, generate +schema migrations for it, apply them to a database, and more. Below are a few commands to get you started with Atlas: + +#### Inspect the Schema + +The `atlas schema inspect` command is commonly used to inspect databases. However, we can also use it to inspect our +`composite_schema` and print the SQL representation of it: + +```shell +atlas schema inspect \ + --env local \ + --url env://src \ + --format '{{ sql . }}' +``` + +The command above prints the following SQL. Note, the `audit_users_changes` function and the triggers are defined after +the `users` and `user_audit_logs` tables: + +```sql +-- Create "user_audit_logs" table +CREATE TABLE "user_audit_logs" ("id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY, "operation_type" character varying NOT NULL, "operation_time" character varying NOT NULL, "old_value" character varying NULL, "new_value" character varying NULL, PRIMARY KEY ("id")); +-- Create "users" table +CREATE TABLE "users" ("id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY, "name" character varying NOT NULL, PRIMARY KEY ("id")); +-- Create "audit_users_changes" function +CREATE FUNCTION "audit_users_changes" () RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF (TG_OP = 'INSERT') THEN + INSERT INTO user_audit_logs(operation_type, operation_time, new_value) + VALUES (TG_OP, CURRENT_TIMESTAMP, row_to_json(NEW)); + RETURN NEW; + ELSIF (TG_OP = 'UPDATE') THEN + INSERT INTO user_audit_logs(operation_type, operation_time, old_value, new_value) + VALUES (TG_OP, CURRENT_TIMESTAMP, row_to_json(OLD), row_to_json(NEW)); + RETURN NEW; + ELSIF (TG_OP = 'DELETE') THEN + INSERT INTO user_audit_logs(operation_type, operation_time, old_value) + VALUES (TG_OP, CURRENT_TIMESTAMP, row_to_json(OLD)); + RETURN OLD; + END IF; + RETURN NULL; +END; +$$; +-- Create trigger "users_delete_audit" +CREATE TRIGGER "users_delete_audit" AFTER DELETE ON "users" FOR EACH ROW EXECUTE FUNCTION "audit_users_changes"(); +-- Create trigger "users_insert_audit" +CREATE TRIGGER "users_insert_audit" AFTER INSERT ON "users" FOR EACH ROW EXECUTE FUNCTION "audit_users_changes"(); +-- Create trigger "users_update_audit" +CREATE TRIGGER "users_update_audit" AFTER UPDATE ON "users" FOR EACH ROW EXECUTE FUNCTION "audit_users_changes"(); +``` + +#### Generate Migrations For the Schema + +To generate a migration for the schema, run the following command: + +```shell +atlas migrate diff \ + --env local +``` + +Note that a new migration file is created with the following content: + +```sql title="migrations/20240712090543.sql" +-- Create "user_audit_logs" table +CREATE TABLE "user_audit_logs" ("id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY, "operation_type" character varying NOT NULL, "operation_time" character varying NOT NULL, "old_value" character varying NULL, "new_value" character varying NULL, PRIMARY KEY ("id")); +-- Create "users" table +CREATE TABLE "users" ("id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY, "name" character varying NOT NULL, PRIMARY KEY ("id")); +-- Create "audit_users_changes" function +CREATE FUNCTION "audit_users_changes" () RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF (TG_OP = 'INSERT') THEN + INSERT INTO user_audit_logs(operation_type, operation_time, new_value) + VALUES (TG_OP, CURRENT_TIMESTAMP, row_to_json(NEW)); + RETURN NEW; + ELSIF (TG_OP = 'UPDATE') THEN + INSERT INTO user_audit_logs(operation_type, operation_time, old_value, new_value) + VALUES (TG_OP, CURRENT_TIMESTAMP, row_to_json(OLD), row_to_json(NEW)); + RETURN NEW; + ELSIF (TG_OP = 'DELETE') THEN + INSERT INTO user_audit_logs(operation_type, operation_time, old_value) + VALUES (TG_OP, CURRENT_TIMESTAMP, row_to_json(OLD)); + RETURN OLD; + END IF; + RETURN NULL; +END; +$$; +-- Create trigger "users_delete_audit" +CREATE TRIGGER "users_delete_audit" AFTER DELETE ON "users" FOR EACH ROW EXECUTE FUNCTION "audit_users_changes"(); +-- Create trigger "users_insert_audit" +CREATE TRIGGER "users_insert_audit" AFTER INSERT ON "users" FOR EACH ROW EXECUTE FUNCTION "audit_users_changes"(); +-- Create trigger "users_update_audit" +CREATE TRIGGER "users_update_audit" AFTER UPDATE ON "users" FOR EACH ROW EXECUTE FUNCTION "audit_users_changes"(); +``` + +#### Apply the Migrations + +To apply the migration generated above to a database, run the following command: + +``` +atlas migrate apply \ + --env local \ + --url "postgres://postgres:pass@localhost:5432/database?search_path=public&sslmode=disable" +``` + +:::info Apply the Schema Directly on the Database + +Sometimes, there is a need to apply the schema directly to the database without generating a migration file. For example, +when experimenting with schema changes, spinning up a database for testing, etc. In such cases, you can use the command +below to apply the schema directly to the database: + +```shell +atlas schema apply \ + --env local \ + --url "postgres://postgres:pass@localhost:5432/database?search_path=public&sslmode=disable" +``` + +::: + +The code for this guide can be found in [GitHub](https://github.com/ent/ent/tree/master/examples/triggers). \ No newline at end of file diff --git a/doc/website/sidebars.js b/doc/website/sidebars.js index af5fa0144..c203f8eba 100644 --- a/doc/website/sidebars.js +++ b/doc/website/sidebars.js @@ -51,6 +51,7 @@ module.exports = { {type: 'doc', id: 'migration/composite', label: 'Composite Types'}, {type: 'doc', id: 'migration/domain', label: 'Domain Types'}, {type: 'doc', id: 'migration/enum', label: 'Enum Types'}, + {type: 'doc', id: 'migration/trigger', label: 'Triggers'}, ], collapsed: false, }, diff --git a/examples/compositetypes/example_test.go b/examples/compositetypes/example_test.go index 78a142b1d..9673ae4d9 100644 --- a/examples/compositetypes/example_test.go +++ b/examples/compositetypes/example_test.go @@ -24,7 +24,7 @@ func TestCompositeTypes(t *testing.T) { t.Skip() } ctx := context.Background() - client, err := ent.Open(dialect.Postgres, "postgres://postgres:pass@:5429/dev?search_path=public&sslmode=disable") + client, err := ent.Open(dialect.Postgres, os.Getenv("DB_URL")) if err != nil { log.Fatalln(err) } diff --git a/examples/domaintypes/example_test.go b/examples/domaintypes/example_test.go index f13d3c661..6e2bedd02 100644 --- a/examples/domaintypes/example_test.go +++ b/examples/domaintypes/example_test.go @@ -22,7 +22,7 @@ func TestDomainTypes(t *testing.T) { t.Skip() } ctx := context.Background() - client, err := ent.Open(dialect.Postgres, "postgres://postgres:pass@:5429/dev?search_path=public&sslmode=disable") + client, err := ent.Open(dialect.Postgres, os.Getenv("DB_URL")) if err != nil { log.Fatalln(err) } diff --git a/examples/enumtypes/example_test.go b/examples/enumtypes/example_test.go index 169ea7ce2..261eff039 100644 --- a/examples/enumtypes/example_test.go +++ b/examples/enumtypes/example_test.go @@ -10,11 +10,11 @@ import ( "os" "testing" + "entgo.io/ent/dialect" + "entgo.io/ent/examples/enumtypes/ent" "entgo.io/ent/examples/enumtypes/ent/user" "ariga.io/atlas-go-sdk/atlasexec" - "entgo.io/ent/dialect" - "entgo.io/ent/examples/enumtypes/ent" _ "github.com/lib/pq" "github.com/stretchr/testify/require" ) @@ -24,7 +24,7 @@ func TestEnumTypes(t *testing.T) { t.Skip() } ctx := context.Background() - client, err := ent.Open(dialect.Postgres, "postgres://postgres:pass@:5429/dev?search_path=public&sslmode=disable") + client, err := ent.Open(dialect.Postgres, os.Getenv("DB_URL")) if err != nil { log.Fatalln(err) } diff --git a/examples/triggers/README.md b/examples/triggers/README.md new file mode 100644 index 000000000..2700b5d84 --- /dev/null +++ b/examples/triggers/README.md @@ -0,0 +1,3 @@ +## Using PostgreSQL Domain Types in Ent Schema + +Read the full guide in \ No newline at end of file diff --git a/examples/triggers/atlas.hcl b/examples/triggers/atlas.hcl new file mode 100644 index 000000000..90c5f559a --- /dev/null +++ b/examples/triggers/atlas.hcl @@ -0,0 +1,15 @@ +data "composite_schema" "app" { + # Load the ent schema first with all tables. + schema "public" { + url = "ent://ent/schema" + } + # Then, load the triggers schema. + schema "public" { + url = "file://schema.sql" + } +} + +env "local" { + src = data.composite_schema.app.url + dev = "docker://postgres/15/dev?search_path=public" +} \ No newline at end of file diff --git a/examples/triggers/ent/client.go b/examples/triggers/ent/client.go new file mode 100644 index 000000000..3a24b9f9e --- /dev/null +++ b/examples/triggers/ent/client.go @@ -0,0 +1,483 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "log" + "reflect" + + "entgo.io/ent" + "entgo.io/ent/examples/triggers/ent/migrate" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/examples/triggers/ent/user" + "entgo.io/ent/examples/triggers/ent/userauditlog" +) + +// 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 + // User is the client for interacting with the User builders. + User *UserClient + // UserAuditLog is the client for interacting with the UserAuditLog builders. + UserAuditLog *UserAuditLogClient +} + +// 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.User = NewUserClient(c.config) + c.UserAuditLog = NewUserAuditLogClient(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, + User: NewUserClient(cfg), + UserAuditLog: NewUserAuditLogClient(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, + User: NewUserClient(cfg), + UserAuditLog: NewUserAuditLogClient(cfg), + }, nil +} + +// Debug returns a new debug-client. It's used to get verbose logging on specific operations. +// +// client.Debug(). +// User. +// 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.User.Use(hooks...) + c.UserAuditLog.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.User.Intercept(interceptors...) + c.UserAuditLog.Intercept(interceptors...) +} + +// Mutate implements the ent.Mutator interface. +func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { + switch m := m.(type) { + case *UserMutation: + return c.User.mutate(ctx, m) + case *UserAuditLogMutation: + return c.UserAuditLog.mutate(ctx, m) + default: + return nil, fmt.Errorf("ent: unknown mutation type %T", m) + } +} + +// 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(u *User) *UserUpdateOne { + mutation := newUserMutation(c.config, OpUpdateOne, withUser(u)) + 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(u *User) *UserDeleteOne { + return c.DeleteOneID(u.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.op = 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 +} + +// Hooks returns the client hooks. +func (c *UserClient) Hooks() []Hook { + return c.hooks.User +} + +// 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()) + } +} + +// UserAuditLogClient is a client for the UserAuditLog schema. +type UserAuditLogClient struct { + config +} + +// NewUserAuditLogClient returns a client for the UserAuditLog from the given config. +func NewUserAuditLogClient(c config) *UserAuditLogClient { + return &UserAuditLogClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `userauditlog.Hooks(f(g(h())))`. +func (c *UserAuditLogClient) Use(hooks ...Hook) { + c.hooks.UserAuditLog = append(c.hooks.UserAuditLog, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `userauditlog.Intercept(f(g(h())))`. +func (c *UserAuditLogClient) Intercept(interceptors ...Interceptor) { + c.inters.UserAuditLog = append(c.inters.UserAuditLog, interceptors...) +} + +// Create returns a builder for creating a UserAuditLog entity. +func (c *UserAuditLogClient) Create() *UserAuditLogCreate { + mutation := newUserAuditLogMutation(c.config, OpCreate) + return &UserAuditLogCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of UserAuditLog entities. +func (c *UserAuditLogClient) CreateBulk(builders ...*UserAuditLogCreate) *UserAuditLogCreateBulk { + return &UserAuditLogCreateBulk{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 *UserAuditLogClient) MapCreateBulk(slice any, setFunc func(*UserAuditLogCreate, int)) *UserAuditLogCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &UserAuditLogCreateBulk{err: fmt.Errorf("calling to UserAuditLogClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*UserAuditLogCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &UserAuditLogCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for UserAuditLog. +func (c *UserAuditLogClient) Update() *UserAuditLogUpdate { + mutation := newUserAuditLogMutation(c.config, OpUpdate) + return &UserAuditLogUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *UserAuditLogClient) UpdateOne(ual *UserAuditLog) *UserAuditLogUpdateOne { + mutation := newUserAuditLogMutation(c.config, OpUpdateOne, withUserAuditLog(ual)) + return &UserAuditLogUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *UserAuditLogClient) UpdateOneID(id int) *UserAuditLogUpdateOne { + mutation := newUserAuditLogMutation(c.config, OpUpdateOne, withUserAuditLogID(id)) + return &UserAuditLogUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for UserAuditLog. +func (c *UserAuditLogClient) Delete() *UserAuditLogDelete { + mutation := newUserAuditLogMutation(c.config, OpDelete) + return &UserAuditLogDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *UserAuditLogClient) DeleteOne(ual *UserAuditLog) *UserAuditLogDeleteOne { + return c.DeleteOneID(ual.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *UserAuditLogClient) DeleteOneID(id int) *UserAuditLogDeleteOne { + builder := c.Delete().Where(userauditlog.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &UserAuditLogDeleteOne{builder} +} + +// Query returns a query builder for UserAuditLog. +func (c *UserAuditLogClient) Query() *UserAuditLogQuery { + return &UserAuditLogQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeUserAuditLog}, + inters: c.Interceptors(), + } +} + +// Get returns a UserAuditLog entity by its id. +func (c *UserAuditLogClient) Get(ctx context.Context, id int) (*UserAuditLog, error) { + return c.Query().Where(userauditlog.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *UserAuditLogClient) GetX(ctx context.Context, id int) *UserAuditLog { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *UserAuditLogClient) Hooks() []Hook { + return c.hooks.UserAuditLog +} + +// Interceptors returns the client interceptors. +func (c *UserAuditLogClient) Interceptors() []Interceptor { + return c.inters.UserAuditLog +} + +func (c *UserAuditLogClient) mutate(ctx context.Context, m *UserAuditLogMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&UserAuditLogCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&UserAuditLogUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&UserAuditLogUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&UserAuditLogDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown UserAuditLog mutation op: %q", m.Op()) + } +} + +// hooks and interceptors per client, for fast access. +type ( + hooks struct { + User, UserAuditLog []ent.Hook + } + inters struct { + User, UserAuditLog []ent.Interceptor + } +) diff --git a/examples/triggers/ent/ent.go b/examples/triggers/ent/ent.go new file mode 100644 index 000000000..6acc683ef --- /dev/null +++ b/examples/triggers/ent/ent.go @@ -0,0 +1,610 @@ +// 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/triggers/ent/user" + "entgo.io/ent/examples/triggers/ent/userauditlog" +) + +// 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 +) + +// columnChecker checks if the column exists in the given table. +func checkColumn(table, column string) error { + initCheck.Do(func() { + columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ + user.Table: user.ValidColumn, + userauditlog.Table: userauditlog.ValidColumn, + }) + }) + return columnCheck(table, column) +} + +// 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) diff --git a/examples/triggers/ent/enttest/enttest.go b/examples/triggers/ent/enttest/enttest.go new file mode 100644 index 000000000..230f6a1bf --- /dev/null +++ b/examples/triggers/ent/enttest/enttest.go @@ -0,0 +1,84 @@ +// Code generated by ent, DO NOT EDIT. + +package enttest + +import ( + "context" + + "entgo.io/ent/examples/triggers/ent" + // required by schema hooks. + _ "entgo.io/ent/examples/triggers/ent/runtime" + + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/examples/triggers/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() + } +} diff --git a/examples/triggers/ent/generate.go b/examples/triggers/ent/generate.go new file mode 100644 index 000000000..8d3fdfdc1 --- /dev/null +++ b/examples/triggers/ent/generate.go @@ -0,0 +1,3 @@ +package ent + +//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate ./schema diff --git a/examples/triggers/ent/hook/hook.go b/examples/triggers/ent/hook/hook.go new file mode 100644 index 000000000..e0bb85b88 --- /dev/null +++ b/examples/triggers/ent/hook/hook.go @@ -0,0 +1,211 @@ +// Code generated by ent, DO NOT EDIT. + +package hook + +import ( + "context" + "fmt" + + "entgo.io/ent/examples/triggers/ent" +) + +// 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) +} + +// The UserAuditLogFunc type is an adapter to allow the use of ordinary +// function as UserAuditLog mutator. +type UserAuditLogFunc func(context.Context, *ent.UserAuditLogMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f UserAuditLogFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.UserAuditLogMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserAuditLogMutation", 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...) +} diff --git a/examples/triggers/ent/migrate/migrate.go b/examples/triggers/ent/migrate/migrate.go new file mode 100644 index 000000000..1956a6bf6 --- /dev/null +++ b/examples/triggers/ent/migrate/migrate.go @@ -0,0 +1,64 @@ +// 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...) +} diff --git a/examples/triggers/ent/migrate/schema.go b/examples/triggers/ent/migrate/schema.go new file mode 100644 index 000000000..a15759eab --- /dev/null +++ b/examples/triggers/ent/migrate/schema.go @@ -0,0 +1,44 @@ +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/schema/field" +) + +var ( + // UsersColumns holds the columns for the "users" table. + UsersColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "name", Type: field.TypeString}, + } + // UsersTable holds the schema information for the "users" table. + UsersTable = &schema.Table{ + Name: "users", + Columns: UsersColumns, + PrimaryKey: []*schema.Column{UsersColumns[0]}, + } + // UserAuditLogsColumns holds the columns for the "user_audit_logs" table. + UserAuditLogsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "operation_type", Type: field.TypeString}, + {Name: "operation_time", Type: field.TypeString}, + {Name: "old_value", Type: field.TypeString, Nullable: true}, + {Name: "new_value", Type: field.TypeString, Nullable: true}, + } + // UserAuditLogsTable holds the schema information for the "user_audit_logs" table. + UserAuditLogsTable = &schema.Table{ + Name: "user_audit_logs", + Columns: UserAuditLogsColumns, + PrimaryKey: []*schema.Column{UserAuditLogsColumns[0]}, + } + // Tables holds all the tables in the schema. + Tables = []*schema.Table{ + UsersTable, + UserAuditLogsTable, + } +) + +func init() { +} diff --git a/examples/triggers/ent/mutation.go b/examples/triggers/ent/mutation.go new file mode 100644 index 000000000..2cab993dc --- /dev/null +++ b/examples/triggers/ent/mutation.go @@ -0,0 +1,884 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "sync" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/examples/triggers/ent/predicate" + "entgo.io/ent/examples/triggers/ent/user" + "entgo.io/ent/examples/triggers/ent/userauditlog" +) + +const ( + // Operation types. + OpCreate = ent.OpCreate + OpDelete = ent.OpDelete + OpDeleteOne = ent.OpDeleteOne + OpUpdate = ent.OpUpdate + OpUpdateOne = ent.OpUpdateOne + + // Node types. + TypeUser = "User" + TypeUserAuditLog = "UserAuditLog" +) + +// UserMutation represents an operation that mutates the User nodes in the graph. +type UserMutation struct { + config + op Op + typ string + id *int + name *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*User, error) + predicates []predicate.User +} + +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{ + config: c, + op: op, + typ: TypeUser, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// 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 +} + +// 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 +} + +// 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) + } +} + +// SetName sets the "name" field. +func (m *UserMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *UserMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// 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 m.id == nil || 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 +} + +// ResetName resets all changes to the "name" field. +func (m *UserMutation) ResetName() { + m.name = nil +} + +// Where appends a list predicates to the UserMutation builder. +func (m *UserMutation) Where(ps ...predicate.User) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the UserMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *UserMutation) 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 *UserMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *UserMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (User). +func (m *UserMutation) 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 *UserMutation) Fields() []string { + fields := make([]string, 0, 1) + if m.name != nil { + fields = append(fields, user.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 *UserMutation) Field(name string) (ent.Value, bool) { + switch name { + case user.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 *UserMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case user.FieldName: + return m.OldName(ctx) + } + 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 *UserMutation) SetField(name string, value ent.Value) error { + switch name { + case user.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 User field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *UserMutation) 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 *UserMutation) 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 *UserMutation) 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 *UserMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *UserMutation) 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 *UserMutation) ClearField(name string) error { + 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 *UserMutation) ResetField(name string) error { + switch name { + case user.FieldName: + m.ResetName() + return nil + } + return fmt.Errorf("unknown User field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *UserMutation) 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 *UserMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *UserMutation) 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 *UserMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *UserMutation) 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 *UserMutation) 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 *UserMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown User unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *UserMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown User edge %s", name) +} + +// UserAuditLogMutation represents an operation that mutates the UserAuditLog nodes in the graph. +type UserAuditLogMutation struct { + config + op Op + typ string + id *int + operation_type *string + operation_time *string + old_value *string + new_value *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*UserAuditLog, error) + predicates []predicate.UserAuditLog +} + +var _ ent.Mutation = (*UserAuditLogMutation)(nil) + +// userauditlogOption allows management of the mutation configuration using functional options. +type userauditlogOption func(*UserAuditLogMutation) + +// newUserAuditLogMutation creates new mutation for the UserAuditLog entity. +func newUserAuditLogMutation(c config, op Op, opts ...userauditlogOption) *UserAuditLogMutation { + m := &UserAuditLogMutation{ + config: c, + op: op, + typ: TypeUserAuditLog, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withUserAuditLogID sets the ID field of the mutation. +func withUserAuditLogID(id int) userauditlogOption { + return func(m *UserAuditLogMutation) { + var ( + err error + once sync.Once + value *UserAuditLog + ) + m.oldValue = func(ctx context.Context) (*UserAuditLog, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().UserAuditLog.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withUserAuditLog sets the old UserAuditLog of the mutation. +func withUserAuditLog(node *UserAuditLog) userauditlogOption { + return func(m *UserAuditLogMutation) { + m.oldValue = func(context.Context) (*UserAuditLog, 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 UserAuditLogMutation) 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 UserAuditLogMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *UserAuditLogMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *UserAuditLogMutation) 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().UserAuditLog.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetOperationType sets the "operation_type" field. +func (m *UserAuditLogMutation) SetOperationType(s string) { + m.operation_type = &s +} + +// OperationType returns the value of the "operation_type" field in the mutation. +func (m *UserAuditLogMutation) OperationType() (r string, exists bool) { + v := m.operation_type + if v == nil { + return + } + return *v, true +} + +// OldOperationType returns the old "operation_type" field's value of the UserAuditLog entity. +// If the UserAuditLog 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 *UserAuditLogMutation) OldOperationType(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOperationType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOperationType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOperationType: %w", err) + } + return oldValue.OperationType, nil +} + +// ResetOperationType resets all changes to the "operation_type" field. +func (m *UserAuditLogMutation) ResetOperationType() { + m.operation_type = nil +} + +// SetOperationTime sets the "operation_time" field. +func (m *UserAuditLogMutation) SetOperationTime(s string) { + m.operation_time = &s +} + +// OperationTime returns the value of the "operation_time" field in the mutation. +func (m *UserAuditLogMutation) OperationTime() (r string, exists bool) { + v := m.operation_time + if v == nil { + return + } + return *v, true +} + +// OldOperationTime returns the old "operation_time" field's value of the UserAuditLog entity. +// If the UserAuditLog 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 *UserAuditLogMutation) OldOperationTime(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOperationTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOperationTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOperationTime: %w", err) + } + return oldValue.OperationTime, nil +} + +// ResetOperationTime resets all changes to the "operation_time" field. +func (m *UserAuditLogMutation) ResetOperationTime() { + m.operation_time = nil +} + +// SetOldValue sets the "old_value" field. +func (m *UserAuditLogMutation) SetOldValue(s string) { + m.old_value = &s +} + +// OldValue returns the value of the "old_value" field in the mutation. +func (m *UserAuditLogMutation) OldValue() (r string, exists bool) { + v := m.old_value + if v == nil { + return + } + return *v, true +} + +// OldOldValue returns the old "old_value" field's value of the UserAuditLog entity. +// If the UserAuditLog 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 *UserAuditLogMutation) OldOldValue(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOldValue is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOldValue requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOldValue: %w", err) + } + return oldValue.OldValue, nil +} + +// ClearOldValue clears the value of the "old_value" field. +func (m *UserAuditLogMutation) ClearOldValue() { + m.old_value = nil + m.clearedFields[userauditlog.FieldOldValue] = struct{}{} +} + +// OldValueCleared returns if the "old_value" field was cleared in this mutation. +func (m *UserAuditLogMutation) OldValueCleared() bool { + _, ok := m.clearedFields[userauditlog.FieldOldValue] + return ok +} + +// ResetOldValue resets all changes to the "old_value" field. +func (m *UserAuditLogMutation) ResetOldValue() { + m.old_value = nil + delete(m.clearedFields, userauditlog.FieldOldValue) +} + +// SetNewValue sets the "new_value" field. +func (m *UserAuditLogMutation) SetNewValue(s string) { + m.new_value = &s +} + +// NewValue returns the value of the "new_value" field in the mutation. +func (m *UserAuditLogMutation) NewValue() (r string, exists bool) { + v := m.new_value + if v == nil { + return + } + return *v, true +} + +// OldNewValue returns the old "new_value" field's value of the UserAuditLog entity. +// If the UserAuditLog 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 *UserAuditLogMutation) OldNewValue(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldNewValue is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldNewValue requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldNewValue: %w", err) + } + return oldValue.NewValue, nil +} + +// ClearNewValue clears the value of the "new_value" field. +func (m *UserAuditLogMutation) ClearNewValue() { + m.new_value = nil + m.clearedFields[userauditlog.FieldNewValue] = struct{}{} +} + +// NewValueCleared returns if the "new_value" field was cleared in this mutation. +func (m *UserAuditLogMutation) NewValueCleared() bool { + _, ok := m.clearedFields[userauditlog.FieldNewValue] + return ok +} + +// ResetNewValue resets all changes to the "new_value" field. +func (m *UserAuditLogMutation) ResetNewValue() { + m.new_value = nil + delete(m.clearedFields, userauditlog.FieldNewValue) +} + +// Where appends a list predicates to the UserAuditLogMutation builder. +func (m *UserAuditLogMutation) Where(ps ...predicate.UserAuditLog) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the UserAuditLogMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *UserAuditLogMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.UserAuditLog, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *UserAuditLogMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *UserAuditLogMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (UserAuditLog). +func (m *UserAuditLogMutation) 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 *UserAuditLogMutation) Fields() []string { + fields := make([]string, 0, 4) + if m.operation_type != nil { + fields = append(fields, userauditlog.FieldOperationType) + } + if m.operation_time != nil { + fields = append(fields, userauditlog.FieldOperationTime) + } + if m.old_value != nil { + fields = append(fields, userauditlog.FieldOldValue) + } + if m.new_value != nil { + fields = append(fields, userauditlog.FieldNewValue) + } + 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 *UserAuditLogMutation) Field(name string) (ent.Value, bool) { + switch name { + case userauditlog.FieldOperationType: + return m.OperationType() + case userauditlog.FieldOperationTime: + return m.OperationTime() + case userauditlog.FieldOldValue: + return m.OldValue() + case userauditlog.FieldNewValue: + return m.NewValue() + } + 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 *UserAuditLogMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case userauditlog.FieldOperationType: + return m.OldOperationType(ctx) + case userauditlog.FieldOperationTime: + return m.OldOperationTime(ctx) + case userauditlog.FieldOldValue: + return m.OldOldValue(ctx) + case userauditlog.FieldNewValue: + return m.OldNewValue(ctx) + } + return nil, fmt.Errorf("unknown UserAuditLog 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 *UserAuditLogMutation) SetField(name string, value ent.Value) error { + switch name { + case userauditlog.FieldOperationType: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOperationType(v) + return nil + case userauditlog.FieldOperationTime: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOperationTime(v) + return nil + case userauditlog.FieldOldValue: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOldValue(v) + return nil + case userauditlog.FieldNewValue: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNewValue(v) + return nil + } + return fmt.Errorf("unknown UserAuditLog field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *UserAuditLogMutation) 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 *UserAuditLogMutation) 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 *UserAuditLogMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown UserAuditLog numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *UserAuditLogMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(userauditlog.FieldOldValue) { + fields = append(fields, userauditlog.FieldOldValue) + } + if m.FieldCleared(userauditlog.FieldNewValue) { + fields = append(fields, userauditlog.FieldNewValue) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *UserAuditLogMutation) 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 *UserAuditLogMutation) ClearField(name string) error { + switch name { + case userauditlog.FieldOldValue: + m.ClearOldValue() + return nil + case userauditlog.FieldNewValue: + m.ClearNewValue() + return nil + } + return fmt.Errorf("unknown UserAuditLog 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 *UserAuditLogMutation) ResetField(name string) error { + switch name { + case userauditlog.FieldOperationType: + m.ResetOperationType() + return nil + case userauditlog.FieldOperationTime: + m.ResetOperationTime() + return nil + case userauditlog.FieldOldValue: + m.ResetOldValue() + return nil + case userauditlog.FieldNewValue: + m.ResetNewValue() + return nil + } + return fmt.Errorf("unknown UserAuditLog field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *UserAuditLogMutation) 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 *UserAuditLogMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *UserAuditLogMutation) 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 *UserAuditLogMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *UserAuditLogMutation) 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 *UserAuditLogMutation) 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 *UserAuditLogMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown UserAuditLog 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 *UserAuditLogMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown UserAuditLog edge %s", name) +} diff --git a/examples/triggers/ent/predicate/predicate.go b/examples/triggers/ent/predicate/predicate.go new file mode 100644 index 000000000..a6b231585 --- /dev/null +++ b/examples/triggers/ent/predicate/predicate.go @@ -0,0 +1,13 @@ +// Code generated by ent, DO NOT EDIT. + +package predicate + +import ( + "entgo.io/ent/dialect/sql" +) + +// User is the predicate function for user builders. +type User func(*sql.Selector) + +// UserAuditLog is the predicate function for userauditlog builders. +type UserAuditLog func(*sql.Selector) diff --git a/examples/triggers/ent/runtime.go b/examples/triggers/ent/runtime.go new file mode 100644 index 000000000..793d053b5 --- /dev/null +++ b/examples/triggers/ent/runtime.go @@ -0,0 +1,9 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +// 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() { +} diff --git a/examples/triggers/ent/runtime/runtime.go b/examples/triggers/ent/runtime/runtime.go new file mode 100644 index 000000000..2da864f4f --- /dev/null +++ b/examples/triggers/ent/runtime/runtime.go @@ -0,0 +1,9 @@ +// Code generated by ent, DO NOT EDIT. + +package runtime + +// The schema-stitching logic is generated in entgo.io/ent/examples/triggers/ent/runtime.go + +const ( + Version = "v0.0.0-00010101000000-000000000000" // Version of ent codegen. +) diff --git a/examples/triggers/ent/schema/user.go b/examples/triggers/ent/schema/user.go new file mode 100644 index 000000000..653521ceb --- /dev/null +++ b/examples/triggers/ent/schema/user.go @@ -0,0 +1,39 @@ +// 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/field" +) + +// User holds the schema definition for the User entity. +type User struct { + ent.Schema +} + +// Fields of the User. +func (User) Fields() []ent.Field { + return []ent.Field{ + field.String("name"), + } +} + +// UserAuditLog holds the schema definition for the UserAuditLog entity. +type UserAuditLog struct { + ent.Schema +} + +// Fields of the UserAuditLog. +func (UserAuditLog) Fields() []ent.Field { + return []ent.Field{ + field.String("operation_type"), + field.String("operation_time"), + field.String("old_value"). + Optional(), + field.String("new_value"). + Optional(), + } +} diff --git a/examples/triggers/ent/tx.go b/examples/triggers/ent/tx.go new file mode 100644 index 000000000..a8f110a0e --- /dev/null +++ b/examples/triggers/ent/tx.go @@ -0,0 +1,213 @@ +// 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 + // User is the client for interacting with the User builders. + User *UserClient + // UserAuditLog is the client for interacting with the UserAuditLog builders. + UserAuditLog *UserAuditLogClient + + // 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.User = NewUserClient(tx.config) + tx.UserAuditLog = NewUserAuditLogClient(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: User.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) diff --git a/examples/triggers/ent/user.go b/examples/triggers/ent/user.go new file mode 100644 index 000000000..9bde6d243 --- /dev/null +++ b/examples/triggers/ent/user.go @@ -0,0 +1,103 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/examples/triggers/ent/user" +) + +// User is the model entity for the User schema. +type User struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*User) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case user.FieldID: + 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 (u *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) + } + u.ID = int(value.Int64) + case user.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + u.Name = value.String + } + default: + u.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 (u *User) Value(name string) (ent.Value, error) { + return u.selectValues.Get(name) +} + +// 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 (u *User) Update() *UserUpdateOne { + return NewUserClient(u.config).UpdateOne(u) +} + +// 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 (u *User) Unwrap() *User { + _tx, ok := u.config.driver.(*txDriver) + if !ok { + panic("ent: User is not a transactional entity") + } + u.config.driver = _tx.drv + return u +} + +// String implements the fmt.Stringer. +func (u *User) String() string { + var builder strings.Builder + builder.WriteString("User(") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("name=") + builder.WriteString(u.Name) + builder.WriteByte(')') + return builder.String() +} + +// Users is a parsable slice of User. +type Users []*User diff --git a/examples/triggers/ent/user/user.go b/examples/triggers/ent/user/user.go new file mode 100644 index 000000000..8f9088fed --- /dev/null +++ b/examples/triggers/ent/user/user.go @@ -0,0 +1,47 @@ +// Code generated by ent, DO NOT EDIT. + +package user + +import ( + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the user type in the database. + Label = "user" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // Table holds the table name of the user in the database. + Table = "users" +) + +// Columns holds all SQL columns for user 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 +} + +// OrderOption defines the ordering options for the User queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} diff --git a/examples/triggers/ent/user/where.go b/examples/triggers/ent/user/where.go new file mode 100644 index 000000000..3db606235 --- /dev/null +++ b/examples/triggers/ent/user/where.go @@ -0,0 +1,138 @@ +// Code generated by ent, DO NOT EDIT. + +package user + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/examples/triggers/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.User { + return predicate.User(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.User { + return predicate.User(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.User { + return predicate.User(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.User { + return predicate.User(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.User { + return predicate.User(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.User { + return predicate.User(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.User { + return predicate.User(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.User { + return predicate.User(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.User { + return predicate.User(sql.FieldLTE(FieldID, id)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.User { + return predicate.User(sql.FieldEQ(FieldName, v)) +} + +// 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)) +} + +// 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)) +} diff --git a/examples/triggers/ent/user_create.go b/examples/triggers/ent/user_create.go new file mode 100644 index 000000000..e190c0a23 --- /dev/null +++ b/examples/triggers/ent/user_create.go @@ -0,0 +1,183 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/triggers/ent/user" + "entgo.io/ent/schema/field" +) + +// UserCreate is the builder for creating a User entity. +type UserCreate struct { + config + mutation *UserMutation + hooks []Hook +} + +// SetName sets the "name" field. +func (uc *UserCreate) SetName(s string) *UserCreate { + uc.mutation.SetName(s) + return uc +} + +// Mutation returns the UserMutation object of the builder. +func (uc *UserCreate) Mutation() *UserMutation { + return uc.mutation +} + +// Save creates the User in the database. +func (uc *UserCreate) Save(ctx context.Context) (*User, error) { + return withHooks(ctx, uc.sqlSave, uc.mutation, uc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (uc *UserCreate) SaveX(ctx context.Context) *User { + v, err := uc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (uc *UserCreate) Exec(ctx context.Context) error { + _, err := uc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (uc *UserCreate) ExecX(ctx context.Context) { + if err := uc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (uc *UserCreate) check() error { + if _, ok := uc.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "User.name"`)} + } + return nil +} + +func (uc *UserCreate) sqlSave(ctx context.Context) (*User, error) { + if err := uc.check(); err != nil { + return nil, err + } + _node, _spec := uc.createSpec() + if err := sqlgraph.CreateNode(ctx, uc.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) + uc.mutation.id = &_node.ID + uc.mutation.done = true + return _node, nil +} + +func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { + var ( + _node = &User{config: uc.config} + _spec = sqlgraph.NewCreateSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) + ) + if value, ok := uc.mutation.Name(); ok { + _spec.SetField(user.FieldName, field.TypeString, value) + _node.Name = value + } + 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 (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { + if ucb.err != nil { + return nil, ucb.err + } + specs := make([]*sqlgraph.CreateSpec, len(ucb.builders)) + nodes := make([]*User, len(ucb.builders)) + mutators := make([]Mutator, len(ucb.builders)) + for i := range ucb.builders { + func(i int, root context.Context) { + builder := ucb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, ucb.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, ucb.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, ucb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (ucb *UserCreateBulk) SaveX(ctx context.Context) []*User { + v, err := ucb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ucb *UserCreateBulk) Exec(ctx context.Context) error { + _, err := ucb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ucb *UserCreateBulk) ExecX(ctx context.Context) { + if err := ucb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/examples/triggers/ent/user_delete.go b/examples/triggers/ent/user_delete.go new file mode 100644 index 000000000..da646f341 --- /dev/null +++ b/examples/triggers/ent/user_delete.go @@ -0,0 +1,88 @@ +// 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/triggers/ent/predicate" + "entgo.io/ent/examples/triggers/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 (ud *UserDelete) Where(ps ...predicate.User) *UserDelete { + ud.mutation.Where(ps...) + return ud +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (ud *UserDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, ud.sqlExec, ud.mutation, ud.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (ud *UserDelete) ExecX(ctx context.Context) int { + n, err := ud.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (ud *UserDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) + if ps := ud.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, ud.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + ud.mutation.done = true + return affected, err +} + +// UserDeleteOne is the builder for deleting a single User entity. +type UserDeleteOne struct { + ud *UserDelete +} + +// Where appends a list predicates to the UserDelete builder. +func (udo *UserDeleteOne) Where(ps ...predicate.User) *UserDeleteOne { + udo.ud.mutation.Where(ps...) + return udo +} + +// Exec executes the deletion query. +func (udo *UserDeleteOne) Exec(ctx context.Context) error { + n, err := udo.ud.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 (udo *UserDeleteOne) ExecX(ctx context.Context) { + if err := udo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/examples/triggers/ent/user_query.go b/examples/triggers/ent/user_query.go new file mode 100644 index 000000000..4a31c5348 --- /dev/null +++ b/examples/triggers/ent/user_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/triggers/ent/predicate" + "entgo.io/ent/examples/triggers/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 + // 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 (uq *UserQuery) Where(ps ...predicate.User) *UserQuery { + uq.predicates = append(uq.predicates, ps...) + return uq +} + +// Limit the number of records to be returned by this query. +func (uq *UserQuery) Limit(limit int) *UserQuery { + uq.ctx.Limit = &limit + return uq +} + +// Offset to start from. +func (uq *UserQuery) Offset(offset int) *UserQuery { + uq.ctx.Offset = &offset + return uq +} + +// 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 (uq *UserQuery) Unique(unique bool) *UserQuery { + uq.ctx.Unique = &unique + return uq +} + +// Order specifies how the records should be ordered. +func (uq *UserQuery) Order(o ...user.OrderOption) *UserQuery { + uq.order = append(uq.order, o...) + return uq +} + +// First returns the first User entity from the query. +// Returns a *NotFoundError when no User was found. +func (uq *UserQuery) First(ctx context.Context) (*User, error) { + nodes, err := uq.Limit(1).All(setContextOp(ctx, uq.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 (uq *UserQuery) FirstX(ctx context.Context) *User { + node, err := uq.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 (uq *UserQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = uq.Limit(1).IDs(setContextOp(ctx, uq.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 (uq *UserQuery) FirstIDX(ctx context.Context) int { + id, err := uq.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 (uq *UserQuery) Only(ctx context.Context) (*User, error) { + nodes, err := uq.Limit(2).All(setContextOp(ctx, uq.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 (uq *UserQuery) OnlyX(ctx context.Context) *User { + node, err := uq.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 (uq *UserQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = uq.Limit(2).IDs(setContextOp(ctx, uq.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 (uq *UserQuery) OnlyIDX(ctx context.Context) int { + id, err := uq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Users. +func (uq *UserQuery) All(ctx context.Context) ([]*User, error) { + ctx = setContextOp(ctx, uq.ctx, ent.OpQueryAll) + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*User, *UserQuery]() + return withInterceptors[[]*User](ctx, uq, qr, uq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (uq *UserQuery) AllX(ctx context.Context) []*User { + nodes, err := uq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of User IDs. +func (uq *UserQuery) IDs(ctx context.Context) (ids []int, err error) { + if uq.ctx.Unique == nil && uq.path != nil { + uq.Unique(true) + } + ctx = setContextOp(ctx, uq.ctx, ent.OpQueryIDs) + if err = uq.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 (uq *UserQuery) IDsX(ctx context.Context) []int { + ids, err := uq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (uq *UserQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, uq.ctx, ent.OpQueryCount) + if err := uq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, uq, querierCount[*UserQuery](), uq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (uq *UserQuery) CountX(ctx context.Context) int { + count, err := uq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (uq *UserQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, uq.ctx, ent.OpQueryExist) + switch _, err := uq.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 (uq *UserQuery) ExistX(ctx context.Context) bool { + exist, err := uq.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 (uq *UserQuery) Clone() *UserQuery { + if uq == nil { + return nil + } + return &UserQuery{ + config: uq.config, + ctx: uq.ctx.Clone(), + order: append([]user.OrderOption{}, uq.order...), + inters: append([]Interceptor{}, uq.inters...), + predicates: append([]predicate.User{}, uq.predicates...), + // clone intermediate query. + sql: uq.sql.Clone(), + path: uq.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.User.Query(). +// GroupBy(user.FieldName). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (uq *UserQuery) GroupBy(field string, fields ...string) *UserGroupBy { + uq.ctx.Fields = append([]string{field}, fields...) + grbuild := &UserGroupBy{build: uq} + grbuild.flds = &uq.ctx.Fields + grbuild.label = user.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// } +// +// client.User.Query(). +// Select(user.FieldName). +// Scan(ctx, &v) +func (uq *UserQuery) Select(fields ...string) *UserSelect { + uq.ctx.Fields = append(uq.ctx.Fields, fields...) + sbuild := &UserSelect{UserQuery: uq} + sbuild.label = user.Label + sbuild.flds, sbuild.scan = &uq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a UserSelect configured with the given aggregations. +func (uq *UserQuery) Aggregate(fns ...AggregateFunc) *UserSelect { + return uq.Select().Aggregate(fns...) +} + +func (uq *UserQuery) prepareQuery(ctx context.Context) error { + for _, inter := range uq.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, uq); err != nil { + return err + } + } + } + for _, f := range uq.ctx.Fields { + if !user.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if uq.path != nil { + prev, err := uq.path(ctx) + if err != nil { + return err + } + uq.sql = prev + } + return nil +} + +func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, error) { + var ( + nodes = []*User{} + _spec = uq.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*User).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &User{config: uq.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, uq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (uq *UserQuery) sqlCount(ctx context.Context) (int, error) { + _spec := uq.querySpec() + _spec.Node.Columns = uq.ctx.Fields + if len(uq.ctx.Fields) > 0 { + _spec.Unique = uq.ctx.Unique != nil && *uq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, uq.driver, _spec) +} + +func (uq *UserQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) + _spec.From = uq.sql + if unique := uq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if uq.path != nil { + _spec.Unique = true + } + if fields := uq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, user.FieldID) + for i := range fields { + if fields[i] != user.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := uq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := uq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := uq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := uq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (uq *UserQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(uq.driver.Dialect()) + t1 := builder.Table(user.Table) + columns := uq.ctx.Fields + if len(columns) == 0 { + columns = user.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if uq.sql != nil { + selector = uq.sql + selector.Select(selector.Columns(columns...)...) + } + if uq.ctx.Unique != nil && *uq.ctx.Unique { + selector.Distinct() + } + for _, p := range uq.predicates { + p(selector) + } + for _, p := range uq.order { + p(selector) + } + if offset := uq.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 := uq.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 (ugb *UserGroupBy) Aggregate(fns ...AggregateFunc) *UserGroupBy { + ugb.fns = append(ugb.fns, fns...) + return ugb +} + +// Scan applies the selector query and scans the result into the given value. +func (ugb *UserGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ugb.build.ctx, ent.OpQueryGroupBy) + if err := ugb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*UserQuery, *UserGroupBy](ctx, ugb.build, ugb, ugb.build.inters, v) +} + +func (ugb *UserGroupBy) sqlScan(ctx context.Context, root *UserQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(ugb.fns)) + for _, fn := range ugb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*ugb.flds)+len(ugb.fns)) + for _, f := range *ugb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*ugb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := ugb.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 (us *UserSelect) Aggregate(fns ...AggregateFunc) *UserSelect { + us.fns = append(us.fns, fns...) + return us +} + +// Scan applies the selector query and scans the result into the given value. +func (us *UserSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, us.ctx, ent.OpQuerySelect) + if err := us.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*UserQuery, *UserSelect](ctx, us.UserQuery, us, us.inters, v) +} + +func (us *UserSelect) sqlScan(ctx context.Context, root *UserQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(us.fns)) + for _, fn := range us.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*us.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 := us.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/examples/triggers/ent/user_update.go b/examples/triggers/ent/user_update.go new file mode 100644 index 000000000..51e4c5aa5 --- /dev/null +++ b/examples/triggers/ent/user_update.go @@ -0,0 +1,209 @@ +// 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/triggers/ent/predicate" + "entgo.io/ent/examples/triggers/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 (uu *UserUpdate) Where(ps ...predicate.User) *UserUpdate { + uu.mutation.Where(ps...) + return uu +} + +// SetName sets the "name" field. +func (uu *UserUpdate) SetName(s string) *UserUpdate { + uu.mutation.SetName(s) + return uu +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (uu *UserUpdate) SetNillableName(s *string) *UserUpdate { + if s != nil { + uu.SetName(*s) + } + return uu +} + +// Mutation returns the UserMutation object of the builder. +func (uu *UserUpdate) Mutation() *UserMutation { + return uu.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (uu *UserUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, uu.sqlSave, uu.mutation, uu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (uu *UserUpdate) SaveX(ctx context.Context) int { + affected, err := uu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (uu *UserUpdate) Exec(ctx context.Context) error { + _, err := uu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (uu *UserUpdate) ExecX(ctx context.Context) { + if err := uu.Exec(ctx); err != nil { + panic(err) + } +} + +func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) + if ps := uu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := uu.mutation.Name(); ok { + _spec.SetField(user.FieldName, field.TypeString, value) + } + if n, err = sqlgraph.UpdateNodes(ctx, uu.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 + } + uu.mutation.done = true + return n, 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 (uuo *UserUpdateOne) SetName(s string) *UserUpdateOne { + uuo.mutation.SetName(s) + return uuo +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (uuo *UserUpdateOne) SetNillableName(s *string) *UserUpdateOne { + if s != nil { + uuo.SetName(*s) + } + return uuo +} + +// Mutation returns the UserMutation object of the builder. +func (uuo *UserUpdateOne) Mutation() *UserMutation { + return uuo.mutation +} + +// Where appends a list predicates to the UserUpdate builder. +func (uuo *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne { + uuo.mutation.Where(ps...) + return uuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (uuo *UserUpdateOne) Select(field string, fields ...string) *UserUpdateOne { + uuo.fields = append([]string{field}, fields...) + return uuo +} + +// Save executes the query and returns the updated User entity. +func (uuo *UserUpdateOne) Save(ctx context.Context) (*User, error) { + return withHooks(ctx, uuo.sqlSave, uuo.mutation, uuo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (uuo *UserUpdateOne) SaveX(ctx context.Context) *User { + node, err := uuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (uuo *UserUpdateOne) Exec(ctx context.Context) error { + _, err := uuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (uuo *UserUpdateOne) ExecX(ctx context.Context) { + if err := uuo.Exec(ctx); err != nil { + panic(err) + } +} + +func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) { + _spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) + id, ok := uuo.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 := uuo.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 := uuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := uuo.mutation.Name(); ok { + _spec.SetField(user.FieldName, field.TypeString, value) + } + _node = &User{config: uuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, uuo.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 + } + uuo.mutation.done = true + return _node, nil +} diff --git a/examples/triggers/ent/userauditlog.go b/examples/triggers/ent/userauditlog.go new file mode 100644 index 000000000..bc865f6f4 --- /dev/null +++ b/examples/triggers/ent/userauditlog.go @@ -0,0 +1,136 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/examples/triggers/ent/userauditlog" +) + +// UserAuditLog is the model entity for the UserAuditLog schema. +type UserAuditLog struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // OperationType holds the value of the "operation_type" field. + OperationType string `json:"operation_type,omitempty"` + // OperationTime holds the value of the "operation_time" field. + OperationTime string `json:"operation_time,omitempty"` + // OldValue holds the value of the "old_value" field. + OldValue string `json:"old_value,omitempty"` + // NewValue holds the value of the "new_value" field. + NewValue string `json:"new_value,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*UserAuditLog) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case userauditlog.FieldID: + values[i] = new(sql.NullInt64) + case userauditlog.FieldOperationType, userauditlog.FieldOperationTime, userauditlog.FieldOldValue, userauditlog.FieldNewValue: + 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 UserAuditLog fields. +func (ual *UserAuditLog) 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 userauditlog.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + ual.ID = int(value.Int64) + case userauditlog.FieldOperationType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field operation_type", values[i]) + } else if value.Valid { + ual.OperationType = value.String + } + case userauditlog.FieldOperationTime: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field operation_time", values[i]) + } else if value.Valid { + ual.OperationTime = value.String + } + case userauditlog.FieldOldValue: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field old_value", values[i]) + } else if value.Valid { + ual.OldValue = value.String + } + case userauditlog.FieldNewValue: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field new_value", values[i]) + } else if value.Valid { + ual.NewValue = value.String + } + default: + ual.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the UserAuditLog. +// This includes values selected through modifiers, order, etc. +func (ual *UserAuditLog) Value(name string) (ent.Value, error) { + return ual.selectValues.Get(name) +} + +// Update returns a builder for updating this UserAuditLog. +// Note that you need to call UserAuditLog.Unwrap() before calling this method if this UserAuditLog +// was returned from a transaction, and the transaction was committed or rolled back. +func (ual *UserAuditLog) Update() *UserAuditLogUpdateOne { + return NewUserAuditLogClient(ual.config).UpdateOne(ual) +} + +// Unwrap unwraps the UserAuditLog 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 (ual *UserAuditLog) Unwrap() *UserAuditLog { + _tx, ok := ual.config.driver.(*txDriver) + if !ok { + panic("ent: UserAuditLog is not a transactional entity") + } + ual.config.driver = _tx.drv + return ual +} + +// String implements the fmt.Stringer. +func (ual *UserAuditLog) String() string { + var builder strings.Builder + builder.WriteString("UserAuditLog(") + builder.WriteString(fmt.Sprintf("id=%v, ", ual.ID)) + builder.WriteString("operation_type=") + builder.WriteString(ual.OperationType) + builder.WriteString(", ") + builder.WriteString("operation_time=") + builder.WriteString(ual.OperationTime) + builder.WriteString(", ") + builder.WriteString("old_value=") + builder.WriteString(ual.OldValue) + builder.WriteString(", ") + builder.WriteString("new_value=") + builder.WriteString(ual.NewValue) + builder.WriteByte(')') + return builder.String() +} + +// UserAuditLogs is a parsable slice of UserAuditLog. +type UserAuditLogs []*UserAuditLog diff --git a/examples/triggers/ent/userauditlog/userauditlog.go b/examples/triggers/ent/userauditlog/userauditlog.go new file mode 100644 index 000000000..86cf24fcf --- /dev/null +++ b/examples/triggers/ent/userauditlog/userauditlog.go @@ -0,0 +1,71 @@ +// Code generated by ent, DO NOT EDIT. + +package userauditlog + +import ( + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the userauditlog type in the database. + Label = "user_audit_log" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldOperationType holds the string denoting the operation_type field in the database. + FieldOperationType = "operation_type" + // FieldOperationTime holds the string denoting the operation_time field in the database. + FieldOperationTime = "operation_time" + // FieldOldValue holds the string denoting the old_value field in the database. + FieldOldValue = "old_value" + // FieldNewValue holds the string denoting the new_value field in the database. + FieldNewValue = "new_value" + // Table holds the table name of the userauditlog in the database. + Table = "user_audit_logs" +) + +// Columns holds all SQL columns for userauditlog fields. +var Columns = []string{ + FieldID, + FieldOperationType, + FieldOperationTime, + FieldOldValue, + FieldNewValue, +} + +// 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 +} + +// OrderOption defines the ordering options for the UserAuditLog 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() +} + +// ByOperationType orders the results by the operation_type field. +func ByOperationType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldOperationType, opts...).ToFunc() +} + +// ByOperationTime orders the results by the operation_time field. +func ByOperationTime(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldOperationTime, opts...).ToFunc() +} + +// ByOldValue orders the results by the old_value field. +func ByOldValue(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldOldValue, opts...).ToFunc() +} + +// ByNewValue orders the results by the new_value field. +func ByNewValue(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldNewValue, opts...).ToFunc() +} diff --git a/examples/triggers/ent/userauditlog/where.go b/examples/triggers/ent/userauditlog/where.go new file mode 100644 index 000000000..303e9e5d5 --- /dev/null +++ b/examples/triggers/ent/userauditlog/where.go @@ -0,0 +1,368 @@ +// Code generated by ent, DO NOT EDIT. + +package userauditlog + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/examples/triggers/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldLTE(FieldID, id)) +} + +// OperationType applies equality check predicate on the "operation_type" field. It's identical to OperationTypeEQ. +func OperationType(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldEQ(FieldOperationType, v)) +} + +// OperationTime applies equality check predicate on the "operation_time" field. It's identical to OperationTimeEQ. +func OperationTime(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldEQ(FieldOperationTime, v)) +} + +// OldValue applies equality check predicate on the "old_value" field. It's identical to OldValueEQ. +func OldValue(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldEQ(FieldOldValue, v)) +} + +// NewValue applies equality check predicate on the "new_value" field. It's identical to NewValueEQ. +func NewValue(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldEQ(FieldNewValue, v)) +} + +// OperationTypeEQ applies the EQ predicate on the "operation_type" field. +func OperationTypeEQ(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldEQ(FieldOperationType, v)) +} + +// OperationTypeNEQ applies the NEQ predicate on the "operation_type" field. +func OperationTypeNEQ(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldNEQ(FieldOperationType, v)) +} + +// OperationTypeIn applies the In predicate on the "operation_type" field. +func OperationTypeIn(vs ...string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldIn(FieldOperationType, vs...)) +} + +// OperationTypeNotIn applies the NotIn predicate on the "operation_type" field. +func OperationTypeNotIn(vs ...string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldNotIn(FieldOperationType, vs...)) +} + +// OperationTypeGT applies the GT predicate on the "operation_type" field. +func OperationTypeGT(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldGT(FieldOperationType, v)) +} + +// OperationTypeGTE applies the GTE predicate on the "operation_type" field. +func OperationTypeGTE(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldGTE(FieldOperationType, v)) +} + +// OperationTypeLT applies the LT predicate on the "operation_type" field. +func OperationTypeLT(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldLT(FieldOperationType, v)) +} + +// OperationTypeLTE applies the LTE predicate on the "operation_type" field. +func OperationTypeLTE(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldLTE(FieldOperationType, v)) +} + +// OperationTypeContains applies the Contains predicate on the "operation_type" field. +func OperationTypeContains(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldContains(FieldOperationType, v)) +} + +// OperationTypeHasPrefix applies the HasPrefix predicate on the "operation_type" field. +func OperationTypeHasPrefix(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldHasPrefix(FieldOperationType, v)) +} + +// OperationTypeHasSuffix applies the HasSuffix predicate on the "operation_type" field. +func OperationTypeHasSuffix(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldHasSuffix(FieldOperationType, v)) +} + +// OperationTypeEqualFold applies the EqualFold predicate on the "operation_type" field. +func OperationTypeEqualFold(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldEqualFold(FieldOperationType, v)) +} + +// OperationTypeContainsFold applies the ContainsFold predicate on the "operation_type" field. +func OperationTypeContainsFold(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldContainsFold(FieldOperationType, v)) +} + +// OperationTimeEQ applies the EQ predicate on the "operation_time" field. +func OperationTimeEQ(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldEQ(FieldOperationTime, v)) +} + +// OperationTimeNEQ applies the NEQ predicate on the "operation_time" field. +func OperationTimeNEQ(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldNEQ(FieldOperationTime, v)) +} + +// OperationTimeIn applies the In predicate on the "operation_time" field. +func OperationTimeIn(vs ...string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldIn(FieldOperationTime, vs...)) +} + +// OperationTimeNotIn applies the NotIn predicate on the "operation_time" field. +func OperationTimeNotIn(vs ...string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldNotIn(FieldOperationTime, vs...)) +} + +// OperationTimeGT applies the GT predicate on the "operation_time" field. +func OperationTimeGT(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldGT(FieldOperationTime, v)) +} + +// OperationTimeGTE applies the GTE predicate on the "operation_time" field. +func OperationTimeGTE(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldGTE(FieldOperationTime, v)) +} + +// OperationTimeLT applies the LT predicate on the "operation_time" field. +func OperationTimeLT(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldLT(FieldOperationTime, v)) +} + +// OperationTimeLTE applies the LTE predicate on the "operation_time" field. +func OperationTimeLTE(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldLTE(FieldOperationTime, v)) +} + +// OperationTimeContains applies the Contains predicate on the "operation_time" field. +func OperationTimeContains(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldContains(FieldOperationTime, v)) +} + +// OperationTimeHasPrefix applies the HasPrefix predicate on the "operation_time" field. +func OperationTimeHasPrefix(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldHasPrefix(FieldOperationTime, v)) +} + +// OperationTimeHasSuffix applies the HasSuffix predicate on the "operation_time" field. +func OperationTimeHasSuffix(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldHasSuffix(FieldOperationTime, v)) +} + +// OperationTimeEqualFold applies the EqualFold predicate on the "operation_time" field. +func OperationTimeEqualFold(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldEqualFold(FieldOperationTime, v)) +} + +// OperationTimeContainsFold applies the ContainsFold predicate on the "operation_time" field. +func OperationTimeContainsFold(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldContainsFold(FieldOperationTime, v)) +} + +// OldValueEQ applies the EQ predicate on the "old_value" field. +func OldValueEQ(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldEQ(FieldOldValue, v)) +} + +// OldValueNEQ applies the NEQ predicate on the "old_value" field. +func OldValueNEQ(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldNEQ(FieldOldValue, v)) +} + +// OldValueIn applies the In predicate on the "old_value" field. +func OldValueIn(vs ...string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldIn(FieldOldValue, vs...)) +} + +// OldValueNotIn applies the NotIn predicate on the "old_value" field. +func OldValueNotIn(vs ...string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldNotIn(FieldOldValue, vs...)) +} + +// OldValueGT applies the GT predicate on the "old_value" field. +func OldValueGT(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldGT(FieldOldValue, v)) +} + +// OldValueGTE applies the GTE predicate on the "old_value" field. +func OldValueGTE(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldGTE(FieldOldValue, v)) +} + +// OldValueLT applies the LT predicate on the "old_value" field. +func OldValueLT(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldLT(FieldOldValue, v)) +} + +// OldValueLTE applies the LTE predicate on the "old_value" field. +func OldValueLTE(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldLTE(FieldOldValue, v)) +} + +// OldValueContains applies the Contains predicate on the "old_value" field. +func OldValueContains(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldContains(FieldOldValue, v)) +} + +// OldValueHasPrefix applies the HasPrefix predicate on the "old_value" field. +func OldValueHasPrefix(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldHasPrefix(FieldOldValue, v)) +} + +// OldValueHasSuffix applies the HasSuffix predicate on the "old_value" field. +func OldValueHasSuffix(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldHasSuffix(FieldOldValue, v)) +} + +// OldValueIsNil applies the IsNil predicate on the "old_value" field. +func OldValueIsNil() predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldIsNull(FieldOldValue)) +} + +// OldValueNotNil applies the NotNil predicate on the "old_value" field. +func OldValueNotNil() predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldNotNull(FieldOldValue)) +} + +// OldValueEqualFold applies the EqualFold predicate on the "old_value" field. +func OldValueEqualFold(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldEqualFold(FieldOldValue, v)) +} + +// OldValueContainsFold applies the ContainsFold predicate on the "old_value" field. +func OldValueContainsFold(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldContainsFold(FieldOldValue, v)) +} + +// NewValueEQ applies the EQ predicate on the "new_value" field. +func NewValueEQ(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldEQ(FieldNewValue, v)) +} + +// NewValueNEQ applies the NEQ predicate on the "new_value" field. +func NewValueNEQ(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldNEQ(FieldNewValue, v)) +} + +// NewValueIn applies the In predicate on the "new_value" field. +func NewValueIn(vs ...string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldIn(FieldNewValue, vs...)) +} + +// NewValueNotIn applies the NotIn predicate on the "new_value" field. +func NewValueNotIn(vs ...string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldNotIn(FieldNewValue, vs...)) +} + +// NewValueGT applies the GT predicate on the "new_value" field. +func NewValueGT(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldGT(FieldNewValue, v)) +} + +// NewValueGTE applies the GTE predicate on the "new_value" field. +func NewValueGTE(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldGTE(FieldNewValue, v)) +} + +// NewValueLT applies the LT predicate on the "new_value" field. +func NewValueLT(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldLT(FieldNewValue, v)) +} + +// NewValueLTE applies the LTE predicate on the "new_value" field. +func NewValueLTE(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldLTE(FieldNewValue, v)) +} + +// NewValueContains applies the Contains predicate on the "new_value" field. +func NewValueContains(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldContains(FieldNewValue, v)) +} + +// NewValueHasPrefix applies the HasPrefix predicate on the "new_value" field. +func NewValueHasPrefix(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldHasPrefix(FieldNewValue, v)) +} + +// NewValueHasSuffix applies the HasSuffix predicate on the "new_value" field. +func NewValueHasSuffix(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldHasSuffix(FieldNewValue, v)) +} + +// NewValueIsNil applies the IsNil predicate on the "new_value" field. +func NewValueIsNil() predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldIsNull(FieldNewValue)) +} + +// NewValueNotNil applies the NotNil predicate on the "new_value" field. +func NewValueNotNil() predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldNotNull(FieldNewValue)) +} + +// NewValueEqualFold applies the EqualFold predicate on the "new_value" field. +func NewValueEqualFold(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldEqualFold(FieldNewValue, v)) +} + +// NewValueContainsFold applies the ContainsFold predicate on the "new_value" field. +func NewValueContainsFold(v string) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.FieldContainsFold(FieldNewValue, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.UserAuditLog) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.UserAuditLog) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.UserAuditLog) predicate.UserAuditLog { + return predicate.UserAuditLog(sql.NotPredicates(p)) +} diff --git a/examples/triggers/ent/userauditlog_create.go b/examples/triggers/ent/userauditlog_create.go new file mode 100644 index 000000000..0d37080f6 --- /dev/null +++ b/examples/triggers/ent/userauditlog_create.go @@ -0,0 +1,232 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/triggers/ent/userauditlog" + "entgo.io/ent/schema/field" +) + +// UserAuditLogCreate is the builder for creating a UserAuditLog entity. +type UserAuditLogCreate struct { + config + mutation *UserAuditLogMutation + hooks []Hook +} + +// SetOperationType sets the "operation_type" field. +func (ualc *UserAuditLogCreate) SetOperationType(s string) *UserAuditLogCreate { + ualc.mutation.SetOperationType(s) + return ualc +} + +// SetOperationTime sets the "operation_time" field. +func (ualc *UserAuditLogCreate) SetOperationTime(s string) *UserAuditLogCreate { + ualc.mutation.SetOperationTime(s) + return ualc +} + +// SetOldValue sets the "old_value" field. +func (ualc *UserAuditLogCreate) SetOldValue(s string) *UserAuditLogCreate { + ualc.mutation.SetOldValue(s) + return ualc +} + +// SetNillableOldValue sets the "old_value" field if the given value is not nil. +func (ualc *UserAuditLogCreate) SetNillableOldValue(s *string) *UserAuditLogCreate { + if s != nil { + ualc.SetOldValue(*s) + } + return ualc +} + +// SetNewValue sets the "new_value" field. +func (ualc *UserAuditLogCreate) SetNewValue(s string) *UserAuditLogCreate { + ualc.mutation.SetNewValue(s) + return ualc +} + +// SetNillableNewValue sets the "new_value" field if the given value is not nil. +func (ualc *UserAuditLogCreate) SetNillableNewValue(s *string) *UserAuditLogCreate { + if s != nil { + ualc.SetNewValue(*s) + } + return ualc +} + +// Mutation returns the UserAuditLogMutation object of the builder. +func (ualc *UserAuditLogCreate) Mutation() *UserAuditLogMutation { + return ualc.mutation +} + +// Save creates the UserAuditLog in the database. +func (ualc *UserAuditLogCreate) Save(ctx context.Context) (*UserAuditLog, error) { + return withHooks(ctx, ualc.sqlSave, ualc.mutation, ualc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (ualc *UserAuditLogCreate) SaveX(ctx context.Context) *UserAuditLog { + v, err := ualc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ualc *UserAuditLogCreate) Exec(ctx context.Context) error { + _, err := ualc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ualc *UserAuditLogCreate) ExecX(ctx context.Context) { + if err := ualc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ualc *UserAuditLogCreate) check() error { + if _, ok := ualc.mutation.OperationType(); !ok { + return &ValidationError{Name: "operation_type", err: errors.New(`ent: missing required field "UserAuditLog.operation_type"`)} + } + if _, ok := ualc.mutation.OperationTime(); !ok { + return &ValidationError{Name: "operation_time", err: errors.New(`ent: missing required field "UserAuditLog.operation_time"`)} + } + return nil +} + +func (ualc *UserAuditLogCreate) sqlSave(ctx context.Context) (*UserAuditLog, error) { + if err := ualc.check(); err != nil { + return nil, err + } + _node, _spec := ualc.createSpec() + if err := sqlgraph.CreateNode(ctx, ualc.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) + ualc.mutation.id = &_node.ID + ualc.mutation.done = true + return _node, nil +} + +func (ualc *UserAuditLogCreate) createSpec() (*UserAuditLog, *sqlgraph.CreateSpec) { + var ( + _node = &UserAuditLog{config: ualc.config} + _spec = sqlgraph.NewCreateSpec(userauditlog.Table, sqlgraph.NewFieldSpec(userauditlog.FieldID, field.TypeInt)) + ) + if value, ok := ualc.mutation.OperationType(); ok { + _spec.SetField(userauditlog.FieldOperationType, field.TypeString, value) + _node.OperationType = value + } + if value, ok := ualc.mutation.OperationTime(); ok { + _spec.SetField(userauditlog.FieldOperationTime, field.TypeString, value) + _node.OperationTime = value + } + if value, ok := ualc.mutation.OldValue(); ok { + _spec.SetField(userauditlog.FieldOldValue, field.TypeString, value) + _node.OldValue = value + } + if value, ok := ualc.mutation.NewValue(); ok { + _spec.SetField(userauditlog.FieldNewValue, field.TypeString, value) + _node.NewValue = value + } + return _node, _spec +} + +// UserAuditLogCreateBulk is the builder for creating many UserAuditLog entities in bulk. +type UserAuditLogCreateBulk struct { + config + err error + builders []*UserAuditLogCreate +} + +// Save creates the UserAuditLog entities in the database. +func (ualcb *UserAuditLogCreateBulk) Save(ctx context.Context) ([]*UserAuditLog, error) { + if ualcb.err != nil { + return nil, ualcb.err + } + specs := make([]*sqlgraph.CreateSpec, len(ualcb.builders)) + nodes := make([]*UserAuditLog, len(ualcb.builders)) + mutators := make([]Mutator, len(ualcb.builders)) + for i := range ualcb.builders { + func(i int, root context.Context) { + builder := ualcb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserAuditLogMutation) + 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, ualcb.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, ualcb.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, ualcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (ualcb *UserAuditLogCreateBulk) SaveX(ctx context.Context) []*UserAuditLog { + v, err := ualcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ualcb *UserAuditLogCreateBulk) Exec(ctx context.Context) error { + _, err := ualcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ualcb *UserAuditLogCreateBulk) ExecX(ctx context.Context) { + if err := ualcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/examples/triggers/ent/userauditlog_delete.go b/examples/triggers/ent/userauditlog_delete.go new file mode 100644 index 000000000..201ca2aef --- /dev/null +++ b/examples/triggers/ent/userauditlog_delete.go @@ -0,0 +1,88 @@ +// 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/triggers/ent/predicate" + "entgo.io/ent/examples/triggers/ent/userauditlog" + "entgo.io/ent/schema/field" +) + +// UserAuditLogDelete is the builder for deleting a UserAuditLog entity. +type UserAuditLogDelete struct { + config + hooks []Hook + mutation *UserAuditLogMutation +} + +// Where appends a list predicates to the UserAuditLogDelete builder. +func (uald *UserAuditLogDelete) Where(ps ...predicate.UserAuditLog) *UserAuditLogDelete { + uald.mutation.Where(ps...) + return uald +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (uald *UserAuditLogDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, uald.sqlExec, uald.mutation, uald.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (uald *UserAuditLogDelete) ExecX(ctx context.Context) int { + n, err := uald.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (uald *UserAuditLogDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(userauditlog.Table, sqlgraph.NewFieldSpec(userauditlog.FieldID, field.TypeInt)) + if ps := uald.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, uald.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + uald.mutation.done = true + return affected, err +} + +// UserAuditLogDeleteOne is the builder for deleting a single UserAuditLog entity. +type UserAuditLogDeleteOne struct { + uald *UserAuditLogDelete +} + +// Where appends a list predicates to the UserAuditLogDelete builder. +func (ualdo *UserAuditLogDeleteOne) Where(ps ...predicate.UserAuditLog) *UserAuditLogDeleteOne { + ualdo.uald.mutation.Where(ps...) + return ualdo +} + +// Exec executes the deletion query. +func (ualdo *UserAuditLogDeleteOne) Exec(ctx context.Context) error { + n, err := ualdo.uald.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{userauditlog.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (ualdo *UserAuditLogDeleteOne) ExecX(ctx context.Context) { + if err := ualdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/examples/triggers/ent/userauditlog_query.go b/examples/triggers/ent/userauditlog_query.go new file mode 100644 index 000000000..b33cc56f1 --- /dev/null +++ b/examples/triggers/ent/userauditlog_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/examples/triggers/ent/predicate" + "entgo.io/ent/examples/triggers/ent/userauditlog" + "entgo.io/ent/schema/field" +) + +// UserAuditLogQuery is the builder for querying UserAuditLog entities. +type UserAuditLogQuery struct { + config + ctx *QueryContext + order []userauditlog.OrderOption + inters []Interceptor + predicates []predicate.UserAuditLog + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the UserAuditLogQuery builder. +func (ualq *UserAuditLogQuery) Where(ps ...predicate.UserAuditLog) *UserAuditLogQuery { + ualq.predicates = append(ualq.predicates, ps...) + return ualq +} + +// Limit the number of records to be returned by this query. +func (ualq *UserAuditLogQuery) Limit(limit int) *UserAuditLogQuery { + ualq.ctx.Limit = &limit + return ualq +} + +// Offset to start from. +func (ualq *UserAuditLogQuery) Offset(offset int) *UserAuditLogQuery { + ualq.ctx.Offset = &offset + return ualq +} + +// 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 (ualq *UserAuditLogQuery) Unique(unique bool) *UserAuditLogQuery { + ualq.ctx.Unique = &unique + return ualq +} + +// Order specifies how the records should be ordered. +func (ualq *UserAuditLogQuery) Order(o ...userauditlog.OrderOption) *UserAuditLogQuery { + ualq.order = append(ualq.order, o...) + return ualq +} + +// First returns the first UserAuditLog entity from the query. +// Returns a *NotFoundError when no UserAuditLog was found. +func (ualq *UserAuditLogQuery) First(ctx context.Context) (*UserAuditLog, error) { + nodes, err := ualq.Limit(1).All(setContextOp(ctx, ualq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{userauditlog.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (ualq *UserAuditLogQuery) FirstX(ctx context.Context) *UserAuditLog { + node, err := ualq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first UserAuditLog ID from the query. +// Returns a *NotFoundError when no UserAuditLog ID was found. +func (ualq *UserAuditLogQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = ualq.Limit(1).IDs(setContextOp(ctx, ualq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{userauditlog.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (ualq *UserAuditLogQuery) FirstIDX(ctx context.Context) int { + id, err := ualq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single UserAuditLog entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one UserAuditLog entity is found. +// Returns a *NotFoundError when no UserAuditLog entities are found. +func (ualq *UserAuditLogQuery) Only(ctx context.Context) (*UserAuditLog, error) { + nodes, err := ualq.Limit(2).All(setContextOp(ctx, ualq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{userauditlog.Label} + default: + return nil, &NotSingularError{userauditlog.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (ualq *UserAuditLogQuery) OnlyX(ctx context.Context) *UserAuditLog { + node, err := ualq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only UserAuditLog ID in the query. +// Returns a *NotSingularError when more than one UserAuditLog ID is found. +// Returns a *NotFoundError when no entities are found. +func (ualq *UserAuditLogQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = ualq.Limit(2).IDs(setContextOp(ctx, ualq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{userauditlog.Label} + default: + err = &NotSingularError{userauditlog.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (ualq *UserAuditLogQuery) OnlyIDX(ctx context.Context) int { + id, err := ualq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of UserAuditLogs. +func (ualq *UserAuditLogQuery) All(ctx context.Context) ([]*UserAuditLog, error) { + ctx = setContextOp(ctx, ualq.ctx, ent.OpQueryAll) + if err := ualq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*UserAuditLog, *UserAuditLogQuery]() + return withInterceptors[[]*UserAuditLog](ctx, ualq, qr, ualq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (ualq *UserAuditLogQuery) AllX(ctx context.Context) []*UserAuditLog { + nodes, err := ualq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of UserAuditLog IDs. +func (ualq *UserAuditLogQuery) IDs(ctx context.Context) (ids []int, err error) { + if ualq.ctx.Unique == nil && ualq.path != nil { + ualq.Unique(true) + } + ctx = setContextOp(ctx, ualq.ctx, ent.OpQueryIDs) + if err = ualq.Select(userauditlog.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (ualq *UserAuditLogQuery) IDsX(ctx context.Context) []int { + ids, err := ualq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (ualq *UserAuditLogQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, ualq.ctx, ent.OpQueryCount) + if err := ualq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, ualq, querierCount[*UserAuditLogQuery](), ualq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (ualq *UserAuditLogQuery) CountX(ctx context.Context) int { + count, err := ualq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (ualq *UserAuditLogQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, ualq.ctx, ent.OpQueryExist) + switch _, err := ualq.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 (ualq *UserAuditLogQuery) ExistX(ctx context.Context) bool { + exist, err := ualq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the UserAuditLogQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (ualq *UserAuditLogQuery) Clone() *UserAuditLogQuery { + if ualq == nil { + return nil + } + return &UserAuditLogQuery{ + config: ualq.config, + ctx: ualq.ctx.Clone(), + order: append([]userauditlog.OrderOption{}, ualq.order...), + inters: append([]Interceptor{}, ualq.inters...), + predicates: append([]predicate.UserAuditLog{}, ualq.predicates...), + // clone intermediate query. + sql: ualq.sql.Clone(), + path: ualq.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 { +// OperationType string `json:"operation_type,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.UserAuditLog.Query(). +// GroupBy(userauditlog.FieldOperationType). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (ualq *UserAuditLogQuery) GroupBy(field string, fields ...string) *UserAuditLogGroupBy { + ualq.ctx.Fields = append([]string{field}, fields...) + grbuild := &UserAuditLogGroupBy{build: ualq} + grbuild.flds = &ualq.ctx.Fields + grbuild.label = userauditlog.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 { +// OperationType string `json:"operation_type,omitempty"` +// } +// +// client.UserAuditLog.Query(). +// Select(userauditlog.FieldOperationType). +// Scan(ctx, &v) +func (ualq *UserAuditLogQuery) Select(fields ...string) *UserAuditLogSelect { + ualq.ctx.Fields = append(ualq.ctx.Fields, fields...) + sbuild := &UserAuditLogSelect{UserAuditLogQuery: ualq} + sbuild.label = userauditlog.Label + sbuild.flds, sbuild.scan = &ualq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a UserAuditLogSelect configured with the given aggregations. +func (ualq *UserAuditLogQuery) Aggregate(fns ...AggregateFunc) *UserAuditLogSelect { + return ualq.Select().Aggregate(fns...) +} + +func (ualq *UserAuditLogQuery) prepareQuery(ctx context.Context) error { + for _, inter := range ualq.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, ualq); err != nil { + return err + } + } + } + for _, f := range ualq.ctx.Fields { + if !userauditlog.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if ualq.path != nil { + prev, err := ualq.path(ctx) + if err != nil { + return err + } + ualq.sql = prev + } + return nil +} + +func (ualq *UserAuditLogQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*UserAuditLog, error) { + var ( + nodes = []*UserAuditLog{} + _spec = ualq.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*UserAuditLog).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &UserAuditLog{config: ualq.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, ualq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (ualq *UserAuditLogQuery) sqlCount(ctx context.Context) (int, error) { + _spec := ualq.querySpec() + _spec.Node.Columns = ualq.ctx.Fields + if len(ualq.ctx.Fields) > 0 { + _spec.Unique = ualq.ctx.Unique != nil && *ualq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, ualq.driver, _spec) +} + +func (ualq *UserAuditLogQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(userauditlog.Table, userauditlog.Columns, sqlgraph.NewFieldSpec(userauditlog.FieldID, field.TypeInt)) + _spec.From = ualq.sql + if unique := ualq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if ualq.path != nil { + _spec.Unique = true + } + if fields := ualq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, userauditlog.FieldID) + for i := range fields { + if fields[i] != userauditlog.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := ualq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := ualq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := ualq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := ualq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (ualq *UserAuditLogQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(ualq.driver.Dialect()) + t1 := builder.Table(userauditlog.Table) + columns := ualq.ctx.Fields + if len(columns) == 0 { + columns = userauditlog.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if ualq.sql != nil { + selector = ualq.sql + selector.Select(selector.Columns(columns...)...) + } + if ualq.ctx.Unique != nil && *ualq.ctx.Unique { + selector.Distinct() + } + for _, p := range ualq.predicates { + p(selector) + } + for _, p := range ualq.order { + p(selector) + } + if offset := ualq.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 := ualq.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// UserAuditLogGroupBy is the group-by builder for UserAuditLog entities. +type UserAuditLogGroupBy struct { + selector + build *UserAuditLogQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (ualgb *UserAuditLogGroupBy) Aggregate(fns ...AggregateFunc) *UserAuditLogGroupBy { + ualgb.fns = append(ualgb.fns, fns...) + return ualgb +} + +// Scan applies the selector query and scans the result into the given value. +func (ualgb *UserAuditLogGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ualgb.build.ctx, ent.OpQueryGroupBy) + if err := ualgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*UserAuditLogQuery, *UserAuditLogGroupBy](ctx, ualgb.build, ualgb, ualgb.build.inters, v) +} + +func (ualgb *UserAuditLogGroupBy) sqlScan(ctx context.Context, root *UserAuditLogQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(ualgb.fns)) + for _, fn := range ualgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*ualgb.flds)+len(ualgb.fns)) + for _, f := range *ualgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*ualgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := ualgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// UserAuditLogSelect is the builder for selecting fields of UserAuditLog entities. +type UserAuditLogSelect struct { + *UserAuditLogQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (uals *UserAuditLogSelect) Aggregate(fns ...AggregateFunc) *UserAuditLogSelect { + uals.fns = append(uals.fns, fns...) + return uals +} + +// Scan applies the selector query and scans the result into the given value. +func (uals *UserAuditLogSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, uals.ctx, ent.OpQuerySelect) + if err := uals.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*UserAuditLogQuery, *UserAuditLogSelect](ctx, uals.UserAuditLogQuery, uals, uals.inters, v) +} + +func (uals *UserAuditLogSelect) sqlScan(ctx context.Context, root *UserAuditLogQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(uals.fns)) + for _, fn := range uals.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*uals.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 := uals.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/examples/triggers/ent/userauditlog_update.go b/examples/triggers/ent/userauditlog_update.go new file mode 100644 index 000000000..6730fc618 --- /dev/null +++ b/examples/triggers/ent/userauditlog_update.go @@ -0,0 +1,347 @@ +// 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/triggers/ent/predicate" + "entgo.io/ent/examples/triggers/ent/userauditlog" + "entgo.io/ent/schema/field" +) + +// UserAuditLogUpdate is the builder for updating UserAuditLog entities. +type UserAuditLogUpdate struct { + config + hooks []Hook + mutation *UserAuditLogMutation +} + +// Where appends a list predicates to the UserAuditLogUpdate builder. +func (ualu *UserAuditLogUpdate) Where(ps ...predicate.UserAuditLog) *UserAuditLogUpdate { + ualu.mutation.Where(ps...) + return ualu +} + +// SetOperationType sets the "operation_type" field. +func (ualu *UserAuditLogUpdate) SetOperationType(s string) *UserAuditLogUpdate { + ualu.mutation.SetOperationType(s) + return ualu +} + +// SetNillableOperationType sets the "operation_type" field if the given value is not nil. +func (ualu *UserAuditLogUpdate) SetNillableOperationType(s *string) *UserAuditLogUpdate { + if s != nil { + ualu.SetOperationType(*s) + } + return ualu +} + +// SetOperationTime sets the "operation_time" field. +func (ualu *UserAuditLogUpdate) SetOperationTime(s string) *UserAuditLogUpdate { + ualu.mutation.SetOperationTime(s) + return ualu +} + +// SetNillableOperationTime sets the "operation_time" field if the given value is not nil. +func (ualu *UserAuditLogUpdate) SetNillableOperationTime(s *string) *UserAuditLogUpdate { + if s != nil { + ualu.SetOperationTime(*s) + } + return ualu +} + +// SetOldValue sets the "old_value" field. +func (ualu *UserAuditLogUpdate) SetOldValue(s string) *UserAuditLogUpdate { + ualu.mutation.SetOldValue(s) + return ualu +} + +// SetNillableOldValue sets the "old_value" field if the given value is not nil. +func (ualu *UserAuditLogUpdate) SetNillableOldValue(s *string) *UserAuditLogUpdate { + if s != nil { + ualu.SetOldValue(*s) + } + return ualu +} + +// ClearOldValue clears the value of the "old_value" field. +func (ualu *UserAuditLogUpdate) ClearOldValue() *UserAuditLogUpdate { + ualu.mutation.ClearOldValue() + return ualu +} + +// SetNewValue sets the "new_value" field. +func (ualu *UserAuditLogUpdate) SetNewValue(s string) *UserAuditLogUpdate { + ualu.mutation.SetNewValue(s) + return ualu +} + +// SetNillableNewValue sets the "new_value" field if the given value is not nil. +func (ualu *UserAuditLogUpdate) SetNillableNewValue(s *string) *UserAuditLogUpdate { + if s != nil { + ualu.SetNewValue(*s) + } + return ualu +} + +// ClearNewValue clears the value of the "new_value" field. +func (ualu *UserAuditLogUpdate) ClearNewValue() *UserAuditLogUpdate { + ualu.mutation.ClearNewValue() + return ualu +} + +// Mutation returns the UserAuditLogMutation object of the builder. +func (ualu *UserAuditLogUpdate) Mutation() *UserAuditLogMutation { + return ualu.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (ualu *UserAuditLogUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, ualu.sqlSave, ualu.mutation, ualu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (ualu *UserAuditLogUpdate) SaveX(ctx context.Context) int { + affected, err := ualu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (ualu *UserAuditLogUpdate) Exec(ctx context.Context) error { + _, err := ualu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ualu *UserAuditLogUpdate) ExecX(ctx context.Context) { + if err := ualu.Exec(ctx); err != nil { + panic(err) + } +} + +func (ualu *UserAuditLogUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := sqlgraph.NewUpdateSpec(userauditlog.Table, userauditlog.Columns, sqlgraph.NewFieldSpec(userauditlog.FieldID, field.TypeInt)) + if ps := ualu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := ualu.mutation.OperationType(); ok { + _spec.SetField(userauditlog.FieldOperationType, field.TypeString, value) + } + if value, ok := ualu.mutation.OperationTime(); ok { + _spec.SetField(userauditlog.FieldOperationTime, field.TypeString, value) + } + if value, ok := ualu.mutation.OldValue(); ok { + _spec.SetField(userauditlog.FieldOldValue, field.TypeString, value) + } + if ualu.mutation.OldValueCleared() { + _spec.ClearField(userauditlog.FieldOldValue, field.TypeString) + } + if value, ok := ualu.mutation.NewValue(); ok { + _spec.SetField(userauditlog.FieldNewValue, field.TypeString, value) + } + if ualu.mutation.NewValueCleared() { + _spec.ClearField(userauditlog.FieldNewValue, field.TypeString) + } + if n, err = sqlgraph.UpdateNodes(ctx, ualu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{userauditlog.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + ualu.mutation.done = true + return n, nil +} + +// UserAuditLogUpdateOne is the builder for updating a single UserAuditLog entity. +type UserAuditLogUpdateOne struct { + config + fields []string + hooks []Hook + mutation *UserAuditLogMutation +} + +// SetOperationType sets the "operation_type" field. +func (ualuo *UserAuditLogUpdateOne) SetOperationType(s string) *UserAuditLogUpdateOne { + ualuo.mutation.SetOperationType(s) + return ualuo +} + +// SetNillableOperationType sets the "operation_type" field if the given value is not nil. +func (ualuo *UserAuditLogUpdateOne) SetNillableOperationType(s *string) *UserAuditLogUpdateOne { + if s != nil { + ualuo.SetOperationType(*s) + } + return ualuo +} + +// SetOperationTime sets the "operation_time" field. +func (ualuo *UserAuditLogUpdateOne) SetOperationTime(s string) *UserAuditLogUpdateOne { + ualuo.mutation.SetOperationTime(s) + return ualuo +} + +// SetNillableOperationTime sets the "operation_time" field if the given value is not nil. +func (ualuo *UserAuditLogUpdateOne) SetNillableOperationTime(s *string) *UserAuditLogUpdateOne { + if s != nil { + ualuo.SetOperationTime(*s) + } + return ualuo +} + +// SetOldValue sets the "old_value" field. +func (ualuo *UserAuditLogUpdateOne) SetOldValue(s string) *UserAuditLogUpdateOne { + ualuo.mutation.SetOldValue(s) + return ualuo +} + +// SetNillableOldValue sets the "old_value" field if the given value is not nil. +func (ualuo *UserAuditLogUpdateOne) SetNillableOldValue(s *string) *UserAuditLogUpdateOne { + if s != nil { + ualuo.SetOldValue(*s) + } + return ualuo +} + +// ClearOldValue clears the value of the "old_value" field. +func (ualuo *UserAuditLogUpdateOne) ClearOldValue() *UserAuditLogUpdateOne { + ualuo.mutation.ClearOldValue() + return ualuo +} + +// SetNewValue sets the "new_value" field. +func (ualuo *UserAuditLogUpdateOne) SetNewValue(s string) *UserAuditLogUpdateOne { + ualuo.mutation.SetNewValue(s) + return ualuo +} + +// SetNillableNewValue sets the "new_value" field if the given value is not nil. +func (ualuo *UserAuditLogUpdateOne) SetNillableNewValue(s *string) *UserAuditLogUpdateOne { + if s != nil { + ualuo.SetNewValue(*s) + } + return ualuo +} + +// ClearNewValue clears the value of the "new_value" field. +func (ualuo *UserAuditLogUpdateOne) ClearNewValue() *UserAuditLogUpdateOne { + ualuo.mutation.ClearNewValue() + return ualuo +} + +// Mutation returns the UserAuditLogMutation object of the builder. +func (ualuo *UserAuditLogUpdateOne) Mutation() *UserAuditLogMutation { + return ualuo.mutation +} + +// Where appends a list predicates to the UserAuditLogUpdate builder. +func (ualuo *UserAuditLogUpdateOne) Where(ps ...predicate.UserAuditLog) *UserAuditLogUpdateOne { + ualuo.mutation.Where(ps...) + return ualuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (ualuo *UserAuditLogUpdateOne) Select(field string, fields ...string) *UserAuditLogUpdateOne { + ualuo.fields = append([]string{field}, fields...) + return ualuo +} + +// Save executes the query and returns the updated UserAuditLog entity. +func (ualuo *UserAuditLogUpdateOne) Save(ctx context.Context) (*UserAuditLog, error) { + return withHooks(ctx, ualuo.sqlSave, ualuo.mutation, ualuo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (ualuo *UserAuditLogUpdateOne) SaveX(ctx context.Context) *UserAuditLog { + node, err := ualuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (ualuo *UserAuditLogUpdateOne) Exec(ctx context.Context) error { + _, err := ualuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ualuo *UserAuditLogUpdateOne) ExecX(ctx context.Context) { + if err := ualuo.Exec(ctx); err != nil { + panic(err) + } +} + +func (ualuo *UserAuditLogUpdateOne) sqlSave(ctx context.Context) (_node *UserAuditLog, err error) { + _spec := sqlgraph.NewUpdateSpec(userauditlog.Table, userauditlog.Columns, sqlgraph.NewFieldSpec(userauditlog.FieldID, field.TypeInt)) + id, ok := ualuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "UserAuditLog.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := ualuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, userauditlog.FieldID) + for _, f := range fields { + if !userauditlog.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != userauditlog.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := ualuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := ualuo.mutation.OperationType(); ok { + _spec.SetField(userauditlog.FieldOperationType, field.TypeString, value) + } + if value, ok := ualuo.mutation.OperationTime(); ok { + _spec.SetField(userauditlog.FieldOperationTime, field.TypeString, value) + } + if value, ok := ualuo.mutation.OldValue(); ok { + _spec.SetField(userauditlog.FieldOldValue, field.TypeString, value) + } + if ualuo.mutation.OldValueCleared() { + _spec.ClearField(userauditlog.FieldOldValue, field.TypeString) + } + if value, ok := ualuo.mutation.NewValue(); ok { + _spec.SetField(userauditlog.FieldNewValue, field.TypeString, value) + } + if ualuo.mutation.NewValueCleared() { + _spec.ClearField(userauditlog.FieldNewValue, field.TypeString) + } + _node = &UserAuditLog{config: ualuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, ualuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{userauditlog.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + ualuo.mutation.done = true + return _node, nil +} diff --git a/examples/triggers/example_test.go b/examples/triggers/example_test.go new file mode 100644 index 000000000..500791bc4 --- /dev/null +++ b/examples/triggers/example_test.go @@ -0,0 +1,61 @@ +// 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 main + +import ( + "context" + "log" + "os" + "testing" + + "entgo.io/ent/dialect" + "entgo.io/ent/examples/triggers/ent" + "entgo.io/ent/examples/triggers/ent/userauditlog" + + "ariga.io/atlas-go-sdk/atlasexec" + _ "github.com/lib/pq" + "github.com/stretchr/testify/require" +) + +func TestTriggersTypes(t *testing.T) { + if os.Getenv("CI") != "" { + t.Skip() + } + ctx := context.Background() + client, err := ent.Open(dialect.Postgres, os.Getenv("DB_URL")) + if err != nil { + log.Fatalln(err) + } + ac, err := atlasexec.NewClient(".", "atlas") + if err != nil { + log.Fatalf("failed to initialize client: %v", err) + } + // Automatically update the database with the desired schema. + // Another option, is to use 'migrate apply' or 'schema apply' manually. + _, err = ac.SchemaApply(ctx, &atlasexec.SchemaApplyParams{ + // URL to your database. For example: + // postgres://postgres:pass@localhost:5432/database?search_path=public&sslmode=disable + URL: os.Getenv("DB_URL"), + Env: "local", + }) + require.NoError(t, err) + t.Cleanup(func() { + client.User.Delete().ExecX(ctx) + client.UserAuditLog.Delete().ExecX(ctx) + }) + client.User.Create().SetName("a8m").ExecX(ctx) + logs := client.UserAuditLog.Query().AllX(ctx) + require.Len(t, logs, 1) + require.Equal(t, "INSERT", logs[0].OperationType) + require.Empty(t, logs[0].OldValue) + require.Contains(t, logs[0].NewValue, "a8m") + + client.User.Update().SetName("Ariel").ExecX(ctx) + logs = client.UserAuditLog.Query().Order(userauditlog.ByID()).AllX(ctx) + require.Len(t, logs, 2) + require.Equal(t, "UPDATE", logs[1].OperationType) + require.Contains(t, logs[1].OldValue, "a8m") + require.Contains(t, logs[1].NewValue, "Ariel") +} diff --git a/examples/triggers/migrations/20240713061538.sql b/examples/triggers/migrations/20240713061538.sql new file mode 100644 index 000000000..f1f56d54f --- /dev/null +++ b/examples/triggers/migrations/20240713061538.sql @@ -0,0 +1,29 @@ +-- Create "user_audit_logs" table +CREATE TABLE "user_audit_logs" ("id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY, "operation_type" character varying NOT NULL, "operation_time" character varying NOT NULL, "old_value" character varying NULL, "new_value" character varying NULL, PRIMARY KEY ("id")); +-- Create "users" table +CREATE TABLE "users" ("id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY, "name" character varying NOT NULL, PRIMARY KEY ("id")); +-- Create "audit_users_changes" function +CREATE FUNCTION "audit_users_changes" () RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF (TG_OP = 'INSERT') THEN + INSERT INTO user_audit_logs(operation_type, operation_time, new_value) + VALUES (TG_OP, CURRENT_TIMESTAMP, row_to_json(NEW)); + RETURN NEW; + ELSIF (TG_OP = 'UPDATE') THEN + INSERT INTO user_audit_logs(operation_type, operation_time, old_value, new_value) + VALUES (TG_OP, CURRENT_TIMESTAMP, row_to_json(OLD), row_to_json(NEW)); + RETURN NEW; + ELSIF (TG_OP = 'DELETE') THEN + INSERT INTO user_audit_logs(operation_type, operation_time, old_value) + VALUES (TG_OP, CURRENT_TIMESTAMP, row_to_json(OLD)); + RETURN OLD; + END IF; + RETURN NULL; +END; +$$; +-- Create trigger "users_delete_audit" +CREATE TRIGGER "users_delete_audit" AFTER DELETE ON "users" FOR EACH ROW EXECUTE FUNCTION "audit_users_changes"(); +-- Create trigger "users_insert_audit" +CREATE TRIGGER "users_insert_audit" AFTER INSERT ON "users" FOR EACH ROW EXECUTE FUNCTION "audit_users_changes"(); +-- Create trigger "users_update_audit" +CREATE TRIGGER "users_update_audit" AFTER UPDATE ON "users" FOR EACH ROW EXECUTE FUNCTION "audit_users_changes"(); diff --git a/examples/triggers/migrations/atlas.sum b/examples/triggers/migrations/atlas.sum new file mode 100644 index 000000000..901c6456c --- /dev/null +++ b/examples/triggers/migrations/atlas.sum @@ -0,0 +1,2 @@ +h1:apbKeEDcQ9pZLC93EvPOVVFRqvAv32edHm3lwAGg4yI= +20240713061538.sql h1:4dwDI6dqxixajNxWj3psnGuqqm51gqkFUtpW2pQualo= diff --git a/examples/triggers/schema.sql b/examples/triggers/schema.sql new file mode 100644 index 000000000..f2bd71998 --- /dev/null +++ b/examples/triggers/schema.sql @@ -0,0 +1,29 @@ +-- Function to audit changes in the users table. +CREATE OR REPLACE FUNCTION audit_users_changes() +RETURNS TRIGGER AS $$ +BEGIN + IF (TG_OP = 'INSERT') THEN + INSERT INTO user_audit_logs(operation_type, operation_time, new_value) + VALUES (TG_OP, CURRENT_TIMESTAMP, row_to_json(NEW)); + RETURN NEW; + ELSIF (TG_OP = 'UPDATE') THEN + INSERT INTO user_audit_logs(operation_type, operation_time, old_value, new_value) + VALUES (TG_OP, CURRENT_TIMESTAMP, row_to_json(OLD), row_to_json(NEW)); + RETURN NEW; + ELSIF (TG_OP = 'DELETE') THEN + INSERT INTO user_audit_logs(operation_type, operation_time, old_value) + VALUES (TG_OP, CURRENT_TIMESTAMP, row_to_json(OLD)); + RETURN OLD; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +-- Trigger for INSERT operations. +CREATE TRIGGER users_insert_audit AFTER INSERT ON users FOR EACH ROW EXECUTE FUNCTION audit_users_changes(); + +-- Trigger for UPDATE operations. +CREATE TRIGGER users_update_audit AFTER UPDATE ON users FOR EACH ROW EXECUTE FUNCTION audit_users_changes(); + +-- Trigger for DELETE operations. +CREATE TRIGGER users_delete_audit AFTER DELETE ON users FOR EACH ROW EXECUTE FUNCTION audit_users_changes();