# `Ash.Resource.Change.Builtins`
[🔗](https://github.com/ash-project/ash/blob/v3.17.0/lib/ash/resource/change/builtins.ex#L5)

Built in changes that are available to all resources

The functions in this module are imported by default in the actions section.

# `after_action`
*macro* 

Directly attach an `after_action` function to the current change.

See `Ash.Changeset.after_action/3` for more information.

Provide the option `prepend?: true` to place the hook before all other hooks instead of after.

## Example

    change after_action(fn changeset, record, _context ->
      Logger.debug("Successfully executed action #{changeset.action.name} on #{inspect(changeset.resource)}")
      {:ok, record}
    end)

# `after_transaction`
*macro* 

Directly attach an `after_transaction` function to the current change.

See `Ash.Changeset.after_transaction/3` for more information.

Provide the option `prepend?: true` to place the hook before all other hooks instead of after.

## Example

    change after_transaction(fn
      changeset, {:ok, record}, _context ->
        Logger.debug("Successfully executed transaction for action #{changeset.action.name} on #{inspect(changeset.resource)}")
        {:ok, record}
      changeset, {:error, reason}, _context ->
        Logger.debug("Failed to execute transaction for action #{changeset.action.name} on #{inspect(changeset.resource)}, reason: #{inspect(reason)}")
        {:error, reason}
    end)

# `atomic_set`

```elixir
@spec atomic_set(attribute :: atom(), expr :: Ash.Expr.t(), opts :: Keyword.t()) ::
  Ash.Resource.Change.ref()
```

Sets an attribute using an expression evaluated in the data layer during create.

The expression cannot use `atomic_ref/1` since there is no existing row to reference.

For updating existing records, use `atomic_update/3` instead.

When used on update actions, this behaves the same as `atomic_update/3`.

## Options

* `:cast_atomic?` - set to `false` to ignore atomic type casting logic. Defaults to `true`.

## Examples

    # Set timestamp at database level during create
    change atomic_set(:created_at, expr(now()))

    # Use a database function
    change atomic_set(:uuid, expr(fragment("gen_random_uuid()")))

## Custom Changes

To implement similar behavior in a custom change, return `{:atomic_set, atomics}`
from the `c:Ash.Resource.Change.atomic/3` callback:

    def atomic(_changeset, _opts, _context) do
      {:atomic_set, %{created_at: expr(now())}}
    end

For upserts where you need both insert and update values, return a list:

    def atomic(_changeset, _opts, _context) do
      [
        {:atomic_set, %{created_at: expr(now())}},
        {:atomic, %{updated_at: expr(now())}}
      ]
    end

# `atomic_update`

```elixir
@spec atomic_update(attribute :: atom(), expr :: Ash.Expr.t(), opts :: Keyword.t()) ::
  Ash.Resource.Change.ref()
```

Updates an attribute using an expression evaluated at the database level.

This is used to update values during the UPDATE phase (for updates or the ON CONFLICT
clause of upserts). The expression can use `atomic_ref/1` to reference existing values.

For setting values during create (INSERT phase), use `atomic_set/3` instead.

> #### Cannot be used on create actions {: .warning}
>
> `atomic_update/3` cannot be used on create actions because there is no existing row
> to update. Use `atomic_set/3` for creates.

## Options

* `:cast_atomic?` - set to `false` to ignore atomic type casting logic. Defaults to `true`.

## Examples

    # Increment counter during update
    change atomic_update(:view_count, expr(view_count + 1))

    # Update timestamp on modification
    change atomic_update(:updated_at, expr(now()))

## Custom Changes

To implement similar behavior in a custom change, return `{:atomic, atomics}`
from the `c:Ash.Resource.Change.atomic/3` callback:

    def atomic(_changeset, _opts, _context) do
      {:atomic, %{view_count: expr(view_count + 1)}}
    end

# `before_action`
*macro* 

Directly attach a `before_action` function to the current change.

See `Ash.Changeset.before_action/3` for more information.

Provide the option `prepend?: true` to place the hook before all other hooks instead of after.

## Example

    change before_action(fn changeset, _context ->
      Logger.debug("About to execute #{changeset.action.name} on #{inspect(changeset.resource)}")

      changeset
    end)

# `before_transaction`
*macro* 

Directly attach a `before_transaction` function to the current change.

See `Ash.Changeset.before_transaction/3` for more information.

Provide the option `prepend?: true` to place the hook before all other hooks instead of after.

## Example

    change before_transaction(fn changeset, _context ->
      Logger.debug("About to execute transaction for #{changeset.action.name} on #{inspect(changeset.resource)}")

      changeset
    end)

# `cascade_destroy`

Cascade this resource's destroy action to a related resource's destroy action.

Adds an after-action hook that explicitly calls destroy on any records related
via the named relationship.  It will optimise for bulk destroys where
possible.

> #### Beware database constraints {: .warning}
>
> Think carefully before using this change with data layers which enforce
> referential integrity (ie PostgreSQL and SQLite) and you may need to defer
> constraints for the relationship in question.
>
> See also:
>   1. [`postgres.references.reference.deferrable` DSL](https://hexdocs.pm/ash_postgres/dsl-ashpostgres-datalayer.html#postgres-references-reference-deferrable)
>   2. [`sqlite.references.reference.deferrable` DSL](https://hexdocs.pm/ash_sqlite/dsl-ashsqlite-datalayer.html#sqlite-references-reference-deferrable)
>   3. [PostgreSQL's `SET CONSTRAINTS` documentation](https://www.postgresql.org/docs/current/sql-set-constraints.html)
>   4. [SQLite's `PRAGMA defer_foreign_keys` documentation](https://www.sqlite.org/pragma.html#pragma_defer_foreign_keys)

> #### Cascading notifications {: .tip}
>
> By default notifications are disabled for the related destroy. This is to avoid potentially sending a **lot** of notifications for high-cardinality relationships.

## Options

* `:relationship` (`t:atom/0`) - Required. The name of the relationship to work on

* `:action` (`t:atom/0`) - The name of the destroy action to call on the related resource. Uses the primary destroy by default.

* `:read_action` (`t:atom/0`) - The name of the read action to call on the related resource to find results to be destroyed

* `:return_notifications?` (`t:boolean/0`) - Return notifications for all destroyed records? The default value is `false`.

* `:after_action?` (`t:boolean/0`) - If true, cascade destroys are done in after_action hooks. If false, they run as before_action hooks. Defaults to true for atomic action compatibility The default value is `true`.

* `:domain` (`Ash.Domain`) - 

## Example

    change cascade_destroy(:relationship)

# `cascade_update`

  Cascade a resource's update action to a related resource's update action.

  Adds an after-action hook that explicitly calls update on any records related
  via the named relationship.  It will optimise for bulk updates where
  possible.

  Allows you to copy fields from the arguments or changes to the destination,
  this way you can cascade a bunch of changes downstream.

> #### Beware database constraints {: .warning}
>
> Think carefully before using this change with data layers which enforce
> referential integrity (ie PostgreSQL and SQLite) and you may need to defer
> constraints for the relationship in question.
>
> See also:
>   1. [`postgres.references.reference.deferrable` DSL](https://hexdocs.pm/ash_postgres/dsl-ashpostgres-datalayer.html#postgres-references-reference-deferrable)
>   2. [`sqlite.references.reference.deferrable` DSL](https://hexdocs.pm/ash_sqlite/dsl-ashsqlite-datalayer.html#sqlite-references-reference-deferrable)
>   3. [PostgreSQL's `SET CONSTRAINTS` documentation](https://www.postgresql.org/docs/current/sql-set-constraints.html)
>   4. [SQLite's `PRAGMA defer_foreign_keys` documentation](https://www.sqlite.org/pragma.html#pragma_defer_foreign_keys)

> #### Cascading notifications {: .tip}
>
> By default notifications are disabled for the related updates. This is to avoid potentially sending a **lot** of notifications for high-cardinality relationships.

## Options

* `:relationship` (`t:atom/0`) - Required. The name of the relationship to work on

* `:action` (`t:atom/0`) - The name of the update action to call on the related resource. Uses the primary update by default.

* `:copy_inputs` (list of `t:atom/0`) - A list of fields to copy & pass on to the downstream update. The source action cannot be atomic. The default value is `[]`.

* `:read_action` (`t:atom/0`) - The name of the read action to call on the related resource to find results to be updated

* `:return_notifications?` (`t:boolean/0`) - Return notifications for all updated records? The default value is `false`.

* `:domain` (`Ash.Domain`) - 

## Example

    change cascade_update(:relationship1)
    change cascade_update(:relationship2, copy_inputs: [:field1, :field2])

# `debug_log`

```elixir
@spec debug_log(label :: String.t() | nil) :: Ash.Resource.Change.ref()
```

# `ensure_selected`

```elixir
@spec ensure_selected(select :: atom() | [atom()]) :: Ash.Resource.Change.ref()
```

Passes the provided value into `Ash.Changeset.ensure_selected/2`

If the value is not already selected, this makes sure it is. Does not deselect anything else.

## Example

    change ensure_selected([:necessary_field])

# `filter`

```elixir
@spec filter(expr :: Ash.Expr.t()) :: Ash.Resource.Change.ref()
```

Applies a filter to the changeset. Has no effect for create actions.

This ensures that only things matching the provided filter are updated or destroyed.

# `get_and_lock`

Re-fetches the record being updated and locks it with the given type.

This happens in a `before_action` hook (so that it is done as part of the transaction).

If your resource has global validations (in the top level `validations` block), you may
want to add `delay_global_validations? true` to your action to ensure they happen on the
locked record.

## Options

- `:skip_atomic?` - set to `true` to skip in the case that the update is done atomically. Defaults to `false`.

# `get_and_lock_for_update`

```elixir
@spec get_and_lock_for_update(opts :: Keyword.t()) :: Ash.Resource.Change.ref()
```

Re-fetches the record being updated and locks it for update.

Only usable with data layers that support locking `:for_update`.

This happens in a `before_action` hook (so that it is done as part of the transaction).

If your resource has global validations (in the top level `validations` block), you may
want to add `delay_global_validations? true` to your action to ensure they happen on the
locked record.

## Options

- `:skip_atomic?` - set to `true` to skip in the case that the update is done atomically. Defaults to `false`.

# `increment`

```elixir
@spec increment(attribute :: atom(), opts :: Keyword.t()) :: Ash.Resource.Change.ref()
```

Increments an attribute's value by the amount specified, which defaults to 1.

Options:

* `:amount` - Defaults to 1
* `:overflow_limit` - Defaults to `nil`. If the value is over the overflow limit it will roll-over to the amount being incremented by (for common database limit support)

# `load`

```elixir
@spec load(load :: term()) :: Ash.Resource.Change.ref()
```

Passes the provided value into `Ash.load` after the action has completed.

## Example

    change load(:comments)
    change load([:friend_count, :friends])

# `manage_relationship`

```elixir
@spec manage_relationship(
  argument :: atom(),
  relationship_name :: atom() | nil,
  opts :: Keyword.t()
) :: Ash.Resource.Change.ref()
```

Calls `Ash.Changeset.manage_relationship/4` with the changeset and relationship provided, using the value provided for the named argument.

If relationship_name is not specified, it is assumed to be the same as the argument.

For information on the available options, see `Ash.Changeset.manage_relationship/4`.

## Examples

    change manage_relationship(:comments, type: :append)
    change manage_relationship(:remove_comments, :comments, type: :remove)

# `optimistic_lock`

Apply an "optimistic lock" on a record being updated or destroyed.

See `Ash.Resource.Change.OptimisticLock` for more.

# `prevent_change`

```elixir
@spec prevent_change(attribute :: atom()) :: Ash.Resource.Change.ref()
```

Clears a change off of the changeset before the action runs.

Does not fail if it is being changed, but ensures it is cleared just before the action.

Can be useful if a change is only used in validations but shouldn't ultimately be written to the data layer.

## Examples

    change prevent_change(:email)

# `relate_actor`

```elixir
@spec relate_actor(relationship :: atom(), opts :: Keyword.t()) ::
  Ash.Resource.Change.ref()
```

Relates the actor to the data being changed, as the provided relationship.

## Options

* `:allow_nil?` (`t:boolean/0`) - Whether or not to allow the actor to be nil, in which case nothing will happen. The default value is `false`.

* `:field` (`t:atom/0`) - The field of the actor to set the relationship to

## Examples

    change relate_actor(:owner, allow_nil?: true)

# `select`

```elixir
@spec select(select :: atom() | [atom()]) :: Ash.Resource.Change.ref()
```

Passes the provided value into `Ash.Changeset.select/3`

Keep in mind, this will *limit* the fields that are selected. You may want `ensure_selected/1` if you
want to make sure that something is selected, without deselecting anything else.

Selecting in changesets does not actually do a select in the data layer. It nils out any
fields that were not selected after completing the action. This can be useful if you are writing
policies that have to do with specific fields being selected.

## Example

    change select([:name])

# `set_attribute`

```elixir
@spec set_attribute(
  attribute :: atom(),
  (-&gt; term()) | {:_arg, :status} | term(),
  opts :: Keyword.t()
) :: Ash.Resource.Change.ref()
```

Sets the attribute to the value provided.

If a zero argument function is provided, it is called to determine the value.

Use `arg(:argument_name)` to use the value of the given argument.

## Options

* `:set_when_nil?` (`t:boolean/0`) - When false, decline setting the attribute if it is nil. The default value is `true`.

* `:new?` (`t:boolean/0`) - When true, sets the attribute to the value provided if the attribute is not already being changed. The default value is `false`.

## Examples

    change set_attribute(:active, false)
    change set_attribute(:opened_at, &DateTime.utc_now/0)
    change set_attribute(:status, arg(:status))
    change set_attribute(:encrypted_data, arg(:data), set_when_nil?: false)

# `set_context`

```elixir
@spec set_context(context :: map() | mfa()) :: Ash.Resource.Change.ref()
```

Merges the given query context.

If an MFA is provided, it will be called with the changeset.
The MFA should return `{:ok, context_to_be_merged}` or `{:error, term}`

## Examples

    change set_context(%{something_used_internally: true})
    change set_context({MyApp.Context, :set_context, []})

# `set_new_attribute`

```elixir
@spec set_new_attribute(
  relationship :: atom(),
  (-&gt; term()) | {:_arg, :status} | term()
) ::
  Ash.Resource.Change.ref()
```

Sets the attribute to the value provided if the attribute is not already being changed.

If a zero argument function is provided, it is called to determine the value.

Use `arg(:argument_name)` to use the value of the given argument.

## Examples

    change set_new_attribute(:active, false)
    change set_new_attribute(:opened_at, &DateTime.utc_now/0)
    change set_new_attribute(:status, arg(:status))

# `update_change`
*macro* 

Updates an existing attribute change by applying a function to it.

The update function gets called with the value already cast to the correct type, and only gets called
on valid changesets, so the value is guaranteed to have passed validations and constraints.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
