ericteubert

ericteubert

Unique Index with multiple columns

I have a unqiue index over three columns where one is computed ([:file_id, :request_id, "(accessed_at::date)"]) and I can’t figure out how to use :conflict_target on insert correctly.

The Ecto docs made me understand that a unique_index creates a constraint so I could use conflict_target: {:constraint, :downloads_daily_unique_request_index} but that doesn’t seem to be the case.

Here’s my abbreviated setup:

# Migration
defmodule DemoApp.Repo.Migrations.CreateDownloads do
  use Ecto.Migration

  def change do
    create table(:downloads) do
      add :request_id, :string
      add :accessed_at, :utc_datetime
      add :file_id, references(:audio_files, on_delete: :nothing)

      timestamps()
    end

    create unique_index(
             :downloads,
             [:file_id, :request_id, "(accessed_at::date)"],
             name: :downloads_daily_unique_request_index
           )
  end
end
# Schema
defmodule DemoApp.Tracking.Download do
  use Ecto.Schema

  # ...

  schema "downloads" do
    field :request_id, :string
    field :accessed_at, :utc_datetime

    belongs_to :file, AudioFile

    timestamps()
  end

  @doc false
  def changeset(download, attrs) do
    download
    |> cast(attrs, [
      :request_id,
      :accessed_at
    ])
    |> validate_required([
      :request_id,
      :accessed_at
    ])
    |> unique_constraint(
      :request_id,
      name: :downloads_daily_unique_request_index
    )
  end
end

There doesn’t seem to be a constraint setup in the database:

Download.changeset(%Download{}, %{request_id: "fooxyz", accessed_at: DateTime.utc_now()})
|> Ecto.Changeset.put_assoc(:file, file)
|> Repo.insert(
  on_conflict: :nothing,
  conflict_target: {:constraint, :downloads_daily_unique_request_index}
)

** (Postgrex.Error) ERROR 42704 (undefined_object) constraint “downloads_daily_unique_request_index” for table “downloads” does not exist
query: INSERT INTO “downloads” (“accessed_at”,“file_id”,“request_id”,“inserted_at”,“updated_at”) VALUES ($1,$2,$3,$4,$5) ON CONFLICT ON CONSTRAINT “downloads_daily_unique_request_index” DO NOTHING RETURNING “id”

Listing the columns does not work because one of them is calculated:

Download.changeset(%Download{}, %{request_id: "fooxyz", accessed_at: DateTime.utc_now()})
|> Ecto.Changeset.put_assoc(:file, file)
|> Repo.insert(
  on_conflict: :nothing,
  conflict_target: [:file_id, :request_id, "accessed_at::date"]
)

** (Postgrex.Error) ERROR 42703 (undefined_column) column “accessed_at::date” does not exist

What am I missing?

Thanks!

Marked As Solved

al2o3cr

al2o3cr

Dunno if it works outside of Ecto.Query.from, but you might try adding import Ecto.Query to make fragment visible.

FWIW, the Postgres docs mention that the conflict target can be omitted for ON CONFLICT ... DO NOTHING cases.

Also Liked

ericteubert

ericteubert

:man_facepalming: Of course! All I care about is that no duplicates are inserted and that’s ensured by the index itself. Thanks!

Where Next?

Popular in Questions Top

Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: <h1>Create Post</h1> <%= ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New

Other popular topics Top

Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43622 214
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52341 488
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

We're in Beta

About us Mission Statement