Double entries on unique indexes - Ecto

Hello
I have a scenario: User impression to Song.
Three entities there, three tables: User, Impression, Song.
Impression would be the join table:

user_id | impression | song_id
1 | “good” | 352

If I do something like:

def impression_setter(1, "bad", 352) do
  %Impression{user_id: 1, impression: "bad", song_id: 352}
  |> Repo.insert()
end

it should update the row if exists:

user_id | impression | song_id
1 | “bad” | 352

This is how my migration file looks like:

  def change do
    create table(:impressions) do
      add :impression, :string, null: false
      add :song_id, references(:songs, on_delete: :delete_all)
      add :user_id, references(:users, on_delete: :delete_all)

      timestamps()
    end

    create unique_index(:impressions, [:song_id, :user_id])

  end

With this approach, I get unique ID for that impression, and what I need is to have song_id and user_id as a primary key. This is what I have:

id | user_id | impression | song_id

Can someone guide me or direct me to how to solve this?

PS I guess what I need for this problem is to make user_id and song_id primary keys, and I thought that unique index would give me that.

I have fixed it. Basically, there was this on_conflict scenario with my currently set up migration and schema, and here is how I fixed it for the ones who might ask for themselves:

def impression_setter(1, "bad", 352) do
  %Impression{user_id: 1, impression: "bad", song_id: 352}
  |> Repo.insert(on_conflict: [set: [impression: "bad"]],
        conflict_target: [:user_id, :song_id])
end
2 Likes