Search code examples
elixirphoenix-frameworkecto

Phoenix/Elixir/Ecto - unique_constraint not working with name option


What I expected to happen: When trying to insert a persona with an already existing username, for the call to Repo.insert to return me the changeset with the error in the details.

What is happening: Ecto is raising a hard exception

I am getting the following error in my Phoenix project.

** (exit) an exception was raised:
    ** (Ecto.ConstraintError) constraint error when attempting to insert struct:

    * personas_username_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 has not defined any constraint.

So I followed its advice and added the name of the unique index in my database, personas_username_index. This unique index definitely exists in the real underlying database.

Here is my schema:

defmodule Poaster.Persona do
  use Ecto.Schema
  import Ecto.Changeset
  alias Poaster.User

  schema "personas" do
    belongs_to :user, User
    field :background_image_url, :string
    field :bio, :string
    field :name, :string
    field :profile_image_url, :string
    field :username, :string

    timestamps()
  end

  @doc false
  def changeset(persona, attrs) do
    persona
    |> cast(attrs, [:username, :name, :bio, :profile_image_url, :background_image_url, :user])
    |> validate_required([:username])
    |> unique_constraint(:username, name: :personas_username_index)
  end
end

And here is my controller code:

def create(conn, %{"username" => username}) do
    # First attempt
    # result = Ecto.build_assoc(conn.assigns[:signed_user], :personas, %{ username: username })
    # IO.inspect(result)
    # result = Repo.insert(result)
    # IO.inspect(result)

    user = conn.assigns[:signed_user]
    result = Repo.insert(%Persona{username: username, user: user})


    case result do
      {:ok, persona} ->
        conn
          |> put_status(:created)
          |> json(persona_data(persona))

      {:error, _changeset} ->
        conn
          |> put_status(:internal_server_error)
          |> json(%{
              success: false,
              error: %{
                detail: "There was an error saving your username!"
              }
            })
    end
  end

  defp persona_data(persona) do
    %{
      id: persona.id,
      background_image_url: persona.background_image_url,
      bio: persona.bio,
      inserted_at: persona.inserted_at,
      name: persona.name,
      profile_image_url: persona.profile_image_url,
      updated_at: persona.updated_at,
      username: persona.username
    }
  end

Migration file:

defmodule Poaster.Repo.Migrations.CreatePersonas do
  use Ecto.Migration

  def change do
    create table(:personas) do
      add :username, :string, null: false
      add :name, :string
      add :bio, :string
      add :profile_image_url, :string
      add :background_image_url, :string
      add :user_id, references(:users, on_delete: :nothing), null: false

      timestamps()
    end

    create unique_index(:personas, [:username])
    create index(:personas, [:user_id])
  end
end


Solution

  • I think that you are supposed to insert a changeset, not the schema directly, in order to be able to catch the error, as described in the docs:

    https://hexdocs.pm/ecto/Ecto.Changeset.html#unique_constraint/3-complex-constraints

    You are calling unique_constraint/3 in your Persona.changeset/2 function, but you are not calling Persona.changeset/2 in your controller code.

    I believe that you should replace the following line:

    result = Repo.insert(%Persona{username: username, user: user}
    

    by:

    result = %Persona{}
      |> Persona.changeset(%{username: username, user: user})
      |> Repo.insert()
    

    Or rather, it is probably more idiomatic to have a create_persona/1 function defined in the context that does this, and invoke this function from your controller (at least this is how the generator is organizing it).