Skip to content

Unique Index Constraint Name Mismatch in ecto_libsql #32

@ocean

Description

@ocean

Bug Report: Unique Index Constraint Name Mismatch in ecto_libsql

Description

When using unique_constraint/3 with a custom index name in ecto_libsql, the constraint name reported by the database doesn't match the name specified in the schema, causing constraint errors to be raised as exceptions instead of being converted to changeset errors.

Steps to Reproduce

  1. Create a migration that drops and recreates a unique index with a specific name:
drop index(:users, [:email])
create unique_index(:users, [:email])
  1. In the schema, define a unique constraint with the explicit name:
unique_constraint(:email, name: "users_email_index")
  1. Attempt to insert a duplicate record. The constraint error is raised as an exception instead of being added to the changeset.

Expected Behavior

The constraint error should be caught and converted to a changeset error with the message "has already been taken".

Actual Behavior

An Ecto.ConstraintError is raised with the message:

constraint error when attempting to insert struct:
* "index" (unique_constraint)

The changeset defined the following constraints:
* "users_email_index" (unique_constraint)

The database reports the constraint name as "index" but the changeset expects "users_email_index", causing the mismatch.

Root Cause

It appears that ecto_libsql is reporting the constraint name as "index" for unique indexes instead of using the actual index name when reporting SQLite constraint violations.

Suggested Fix

When reporting unique index constraint violations from SQLite, ecto_libsql should extract and use the actual index name from the SQLite error or metadata, rather than using a generic name like "index".

Workaround

For now, users can either:

  1. Avoid using custom index names and rely on Ecto's default naming conventions
  2. Catch the Ecto.ConstraintError exception explicitly in their code

Environment

  • ecto_libsql version: 0.4+
  • Ecto version: 3.13
  • Phoenix version: 1.8
  • Elixir version: 1.19+

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions