francois

francois

How to run a SELECT WHERE column IN (...) query?

Hi all!

I don’t know what to do to make Ecto happy to run the following query:

 sql = "" <>
   "SELECT chat_user_notification_keys.key " <>
   "FROM chat_user_rooms " <>
   "JOIN chat_user_notification_keys ON chat_user_notification_keys.user_id = chat_user_rooms.user_id " <>
   "JOIN users                       ON users.id = chat_user_rooms.user_id " <>
   "JOIN chat_rooms                  ON chat_rooms.id = chat_user_rooms.room_id " <>
   "WHERE chat_rooms.id_ref = $1::text::uuid " <>
   "  AND users.slug NOT IN ($2)"

 case Ecto.Adapters.SQL.query(BusChatWeb.Repo, sql, [room_id, user_slugs_who_are_present]) do
   {:ok, %{num_rows: num_keys, rows: keys}} ->
     case num_keys do
       0 -> # ...
       _ -> # ...
     end
 end

Currently, I get the following error message:

** (ArgumentError) Postgrex expected a binary, got []. Please make sure the value you are passing matches the definition in your table or in your query or convert the value accordingly.
[debug] QUERY ERROR db=9.9ms
SELECT chat_user_notification_keys.key FROM chat_user_rooms JOIN chat_user_notification_keys ON chat_user_notification_keys.user_id = chat_user_rooms.user_id JOIN users                       ON users.id = chat_user_rooms.user_id JOIN chat_rooms                  ON    chat_rooms.id = chat_user_rooms.room_id WHERE chat_rooms.id_ref = $1::text::uuid   AND users.slug NOT IN ($2) ["afe13f89-7819-43d9-9bb8-b4ba38a2ddac", []]
            (ecto) /Users/francois/Projects/chat_web/deps/postgrex/lib/postgrex/type_module.ex:717: Ecto.Adapters.Postgres.TypeModule.encode_params/3
        (postgrex) lib/postgrex/query.ex:45: DBConnection.Query.Postgrex.Query.encode/3
    (db_connection) lib/db_connection.ex:1071: DBConnection.describe_run/5
    (db_connection) lib/db_connection.ex:1142: anonymous fn/4 in DBConnection.run_meter/5
    (db_connection) lib/db_connection.ex:1199: DBConnection.run_begin/3
    (db_connection) lib/db_connection.ex:584: DBConnection.prepare_execute/4
            (ecto) lib/ecto/adapters/postgres/connection.ex:93: Ecto.Adapters.Postgres.Connection.execute/4
            (ecto) lib/ecto/adapters/sql.ex:243: Ecto.Adapters.SQL.sql_call/6
        (chat_web) lib/chat_web/repo.ex:117: ChatWeb.Repo.find_notifiable_keys/2

The problem is related to the $2 parameter: it’s a list in Elixir-land. How can I convert/cast a list to something Ecto will be happy?

Thanks!

Most Liked

francois

francois

Thanks @OvermindDL1. The UUIDs are coming straight from the UI layer. I kept them as strings, because that makes it easy to inspect the value from anywhere in the stack.

I finally found a solution to my problem by reusing the ANY operator. My original SQL query is now:

-- as before
  AND NOT users.slug = ANY ($2::text[])

This works and satisfies me.

Thanks!

zambal

zambal

You need to dump the string UUID first to a binary like this:

{:ok, bin} = Ecto.UUID.load(room_id)

Now you can use the binary UUID directly in your query like this:

where: chat_rooms.id_ref == ^bin

Note that if you use an Ecto schema, you don’t need to do all this manual casting and dumping.

Where Next?

Popular in Questions Top

lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

Other popular topics Top

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
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
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

We're in Beta

About us Mission Statement