Interpolating list of UUIDs into a raw SQL query (can't use fragment)

Viewed 590

I'm having issues interpolating a list of UUIDs to perform an in query.

Ecto.Adapters.SQL.query!(Repo, "
  WHERE
    some_id IN ($1)
", [some_list_of_ids])

This gives me an error ** (ArgumentError) Postgrex expected a binary of 16 bytes, got ["4ca72ee7-61e2-4450-8dac-bdd7cf6b3df9", "83640dcc-9674-462c-881b-0ce2ed8f3fba",.... I still get this error even if I cast the UUIDs to binary with either UUID.string_to_binary!

How can I interpolate this?

1 Answers

Try converting "dashed" UUIDs to binary UUIDs.

This should work:

uuids = [
  "f3c106c3-943f-4270-b129-59a2fda48925",
  "5ead56f1-9b7f-4289-9a8d-236c2812d82a",
  "cf4b7ddc-1369-4d99-b35d-8dae6c9e85d9"
]

binary_uuids = Enum.map uuids, fn uuid -> Ecto.UUID.dump(uuid) |> elem(1) end

query = "select * from accounts where id = ANY($1)"

Ecto.Adapters.SQL.query!(Repo, query, [binary_uuids])
Related