dwyl / dwyl/learn-postgresql

Partial index aka conditional index

Open
#89 0 comments 1 reaction 0 assignees View on GitHub
Dominant language
JavaScript
Stars
346
Forks
37
PR merge metrics
No merged PRs in 30d

Description

You can create a unique index with constraints. This should be declared in a changeset to capture the propgation of the error from the database

Example: given an "event_id", you want at most one record with status="owner"
```
[evt, user, status]
[1, 1, owner] <- ok
[1, 2, owner] <- not allowed
[1, 2, pending] <- ok
[1, 3, pending] <- ok
```

```elixir
# migration
create unique_index(:event_participants, [:event_id],
where: "status = 'owner'",
name: :unique_owner
)
```
```elixir
# schema
def changeset(%__MODULE__{} = event_participants, attrs) do
event_participants
[...]
|> unique_constraint([:event_id], where: "status = 'owner'", name: :unique_owner)
end
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.