Delete ignores constraints

I’m using two tables, Products and Categories, where Product belongs_to Category and Category has_many Products. When attempting to delete a Category, I check the associations with Ecto.Changeset.no_assoc_constraint(:products). The resulting changeset correctly contains the following constraint:

[
  %{
    constraint: "products_category_id_fkey",
    error_message: "are still associated with this entry",
    error_type: :no_assoc,
    field: :products,
    match: :exact,
    type: :foreign_key
  }
]

Here is the problem: when using Repo.delete(changeset), I see the exception (Ecto.ConstraintError) constraint error when attempting to delete struct instead of the changeset with a constraint error. Why so? (I’m using Sqlite3)
Thanks!

It seems like it might be an sqlite issue. If you look at the integration test helpers they are skipping the tests for this constraint because the database doesn’t return enough information: ecto_sqlite3/test_helper.exs at main · elixir-sqlite/ecto_sqlite3 · GitHub

And you can see the no_assoc_constraint tests use this tag: ecto/repo.exs at master · elixir-ecto/ecto · GitHub.

I’m not entirely sure if this means they don’t support the changeset errors though. It could just be they don’t support the way the tests are being done.

If you post a simple reproducible example that fails it would help find the issue.

1 Like

An issue with Sqlite was something I suspected. I’ll check the constraint by preloading and counting the categories: it’s a bit of a hack, but it’ll do the job, I guess. Thanks!