FIXED: Ecto 3.9 schemaless unsafe_validate_unique - possible bug?

Hello.

schemaless
|> cast(params, [:some_field])
|> unsafe_validate_unique(:some_field, Repo, query: Query.base(), message: "dublicate some field")

I see that in changelogs [Ecto.Changeset] Raise when schemaless changeset or embedded schema is used in unsafe_validate_unique/4. but i dont understand reasoning. Why wouldn’t unsafe_validate_unique validation be allowed if query base is provided?

I sthis considered a bug, or it will stay this way and i need to create custom validation for this.

My 5 cents would be that for UNSAFE_validation_unique passing custom query base should be an option.

What table are you going to check for conflicts with that schemaless changeset?

Previously i was passing query as option (..., query: Query.base(), ...), that had table with some specific where clauses and joins to make sure uniqueness is constrained only within specific scope.

docs prior ecto v3.8: Ecto.Changeset — Ecto v3.8.4

Query option: the base query to use for the check. Defaults to the schema of the changeset. If the primary key is set, a clause will be added to exclude the changeset row itself from the check.

Interestingly enough in ecto v3.9 query option still is exists: Ecto.Changeset — Ecto v3.9.0

but now custom source can be provided only for schemas (that already have source) if necessary, but not for schemaless. I would expect that for schemaless query option should be required tho.

You’d need a primary_key option too then, no?

Why wouldn’t you create a normal schema?

I think this is a case of someone running into unsafe_validate_unique not working on embedded schemas without a custom query. The handling of that got improved, but went a bit too far, as using a custom :query might be a legitimate usecase. I’d open an issue and see if the added error can be loosened a bit.

1 Like

allow to use unsafe_validate_unique with schemaless changeset if query option is provided · Issue #4012 · elixir-ecto/ecto · GitHub will try to fix it myself :slight_smile: :hand_with_index_finger_and_thumb_crossed:

Fixed: allow to use unsafe_validate_unique with schemaless changeset if query option is provided · Issue #4012 · elixir-ecto/ecto · GitHub

1 Like