ash-project / ash-project/ash_postgres

Add a way to persist a calculation for a resource

Open
#383 0 comments 2 reactions 0 assignees View on GitHub
enhancement
Dominant language
Elixir
Stars
189
Forks
168
Avg merge
13h 1m
Merged PRs (30d)
22

Description

**Is your feature request related to a problem? Please describe.**
When defining generated attributes for a resource, I often see people needing to manually edit the migration to use ALTER TABLE to explicitly add the column with the SQL statement used to populate the column.

**Describe the solution you'd like**
A way to in an Ash resource to define an attribute that is generated, specify the raw SQL statement to populate the field, and have the generated migration use the Ecto syntax for configuring such a column shown [here](https://hexdocs.pm/ecto_sql/Ecto.Migration.html#add/3-examples)

**Describe alternatives you've considered**
Continue manually changing migrations or replace generated attribute with calculations that are not persisted in a column

**Express the feature either with a change to resource syntax, or with a change to the resource interface**

## Idea 1 - `generate_with` attribute option

### Using calculation

```elixir
attributes do
attribute :generated_foo, :string, generate_with: :full_name
end

calculations do
calculate :full_name, :string, expr(first_name <> " " <> last_name)
end
```

### Using raw SQL

```elixir
attributes do
attribute :generated_foo, :string, generate_with: expr(fragment("? || ' ' || ?", first_name, last_name))
end
```

## Idea 2 - `persist` calculation option

```elixir
calculations do
calculate :full_name, :string, expr(first_name <> " " <> last_name)

persist? true
end
```

**Additional context**
Link to the start of the conversation in the Elixir Discord server that lead to this proposal: [message](https://discord.com/channels/269508806759809042/828361963826184252/1283098684724351039)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.