Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Partial index aka conditional index #89

Open
ndrean opened this issue Oct 13, 2022 · 0 comments
Open

Partial index aka conditional index #89

ndrean opened this issue Oct 13, 2022 · 0 comments

Comments

@ndrean
Copy link

ndrean commented Oct 13, 2022

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

https://dba.stackexchange.com/questions/317508/postgres-create-unique-index-with-conditional/317510?noredirect=1#comment618954_317510

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
# migration
create unique_index(:event_participants, [:event_id],
             where: "status = 'owner'",
             name: :unique_owner
)
# schema
def changeset(%__MODULE__{} = event_participants, attrs) do
    event_participants
   [...]
   |> unique_constraint([:event_id], where: "status = 'owner'", name: :unique_owner)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant