0

I am trying to insert into the postgres using Elixir Ecto.Adapters.SQL.query, the query consists of array of tags which are strings. However it does inset into postgres, but not as a list of strings, but a single string. i.e. if tags contains ["abc","xyz"], it inserts in postgres as abcdef and not as array.

Important to mention, i am not using schema or migrations. Simple raw queries.

Map that needs to be inserted in postgres

  response_map=  %{"description" => "des33", "id" => 158,
  "inserted_at" => "2017-06-09T10:19:03.904572", "tags" => ["abc","xyz"],
  "title" => "test 1", "updated_at" => "2017-06-09T10:19:03.904578"}

Code that i use

%{"description" => desc, "id" => id, "title" => title, "tags" =>  tags}=response_map
Ecto.Adapters.SQL.query!(Repo,"insert into test values ('#{id}','#{title}','#{desc}','#{tags}')") 
4
  • Does Ecto.Adapters.SQL.query know about Postgres array types? This is a Postgres specific feature, and if the query builder / SQL client doesn't know about this, it won't know how to treat it correctly. Commented Jun 9, 2017 at 10:25
  • @HoriaComan so what do you think, how should i insert an array, Commented Jun 9, 2017 at 10:26
  • IDK, that's up to you. You could make tags be a json/jsonb type, of the form { "tags": [ list of tags ] }. If you send it a serialized JSON object postgres will be smart enough to transform it into a JSON field, rather than leave it as a string. Commented Jun 9, 2017 at 10:28
  • Ecto supports PostgreSQL Arrays just fine. :) Commented Jun 9, 2017 at 10:28

1 Answer 1

0

You should never use string interpolation in queries. You're opening yourself to SQL injection attacks. Use parameterized queries and you'll fix the SQL injection as well as make this work with arrays:

Ecto.Adapters.SQL.query!(Repo, "insert into test values ($1, $2, $3, $4)", [id, title, desc, tags]) 
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you, but this is what i am getting after the above code (ArgumentError) Postgrex expected a binary, got ["abc", "xyz"]. Please make sure the value you are passing matches the definition in your t able or in your query or convert the value accordingly.
What is the type of the fourth column in PostgreSQL? It should be an Array.
Can you post the output of running \d test from psql connected to your database? (That should print the schema of the table.) I just tested this and it works for me when the column is of type text[].
tags | character varying(255)[]
Can you add the complete output to the question?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.