Cast_embed followed by unique_constraint doesn't detect uniqueness errors

Hi, I have an ecto schema whose changeset function is in the following structure

def changeset(post, attrs) do
    |> cast(attrs, @fields)
    |> cast_embed(:blog)
    |> unique_constraint([:name])
    |> validate_required(@fields)

When there is a duplicate name and also some error in blog cast_embed, it should return errors from cast_embed and unique_constraint error but it only returns cast_embed error. How to get all errors?

It shouldn’t and here’s why:

The unique constraint can’t be validated unless the command is sent to the database. Your application won’t know if there’s a duplicate entry in the database table without doing so. If there’s an error with anything else the command won’t be sent to the database because there is a problem and it shouldn’t be attempted.

As @joey_the_snake mentioned, unique_constraint/3 only adds the error if your changest hits the database. You can however add an unsafe_validate_unique/4 to optimistically check for duplicate entries before insertion and add an error to the changeset if a duplicate is found. This is useful to show the user early on that the operation can’t succeed (and will probably catch most of the cases, the rest will be caught by unique_constraint/3)