elixir-sqlite / ecto_sqlite3

An Ecto SQLite3 adapter.
https://hexdocs.pm/ecto_sqlite3
MIT License
295 stars 44 forks source link

Additional quotes being added to index name? #89

Closed railsmechanic closed 1 year ago

railsmechanic commented 2 years ago

Hi, I already posted this issue in the ecto repository, but @josevalim pointed me to this repository with the guess, that there might be additional quotes added around the index name in the migration.

Issue description

When creating an unique index with a custom expression as shown as in Ecto.Migration docs

create index(:branches, ["(lower(name))"], name: :branches_lower_name_index, unique: true)

and adding the unique_constraint check to the changeset with the name of the unique index

...
|> unique_constraint(:name, name: :branches_lower_name_index)

it raises the following Ecto.ConstraintError

** (Ecto.ConstraintError) constraint error when attempting to insert struct:

    * index 'branches_lower_name_index'_index (unique_constraint)

If you would like to stop this constraint violation from raising an
exception and instead add it as an error to your changeset, please
call `unique_constraint/3` on your changeset with the constraint
`:name` as an option.

The changeset defined the following constraints:

    * branches_lower_name_index (unique_constraint)

    (ecto 3.8.4) lib/ecto/repo/schema.ex:783: anonymous fn/4 in Ecto.Repo.Schema.constraints_to_errors/3
    (elixir 1.13.2) lib/enum.ex:1593: Enum."-map/2-lists^map/1-0-"/2
    (ecto 3.8.4) lib/ecto/repo/schema.ex:768: Ecto.Repo.Schema.constraints_to_errors/3
    (ecto 3.8.4) lib/ecto/repo/schema.ex:749: Ecto.Repo.Schema.apply/4
    (ecto 3.8.4) lib/ecto/repo/schema.ex:367: anonymous fn/15 in Ecto.Repo.Schema.do_insert/4

Please notice the strange name of the index 'branches_lower_name_index'_index

The expected behavior is that an error for the specified field is added to the changeset, instead of raising an Ecto.ConstraintError.

Version information

Many thanks 👍

warmwaffles commented 2 years ago

@railsmechanic I'll take a look at this soon.

railsmechanic commented 2 years ago

Cool, thank you! 👍🏻

warmwaffles commented 2 years ago

@railsmechanic I was able to recreate the issue https://github.com/elixir-sqlite/ecto_sqlite3/compare/index-constraint-name-problem

warmwaffles commented 2 years ago

The funky name is emitted from here

https://github.com/elixir-sqlite/ecto_sqlite3/blob/e3e29edba96e2580a0c1895643e8065081d1dd8e/lib/ecto/adapters/sqlite3/connection.ex#L104-L128

Who'da thought the function name constraint_name_hack/1 would be the culprit 🤣

warmwaffles commented 1 year ago

@railsmechanic I have not forgotten this. Just haven't had time.

railsmechanic commented 1 year ago

@railsmechanic I have not forgotten this. Just haven't had time.

No problem, I also have no time... 👍