11
votes

I’m playing with Elixir&Ecto stuff. I’d like to create custom SQL query, which uses some postgres–specific powers (in this case: it searches postgres array).

Here’s what I’m trying to do:

iex(5)> query = from g in MyModel, where: "'sample_tag' = ANY(tags)", select: g    #Ecto.Query<from g in MyModel, where: "'sample_tag' = ANY(tags)", select: g>
iex(6)> Repo.all(query)                                                        [debug] SELECT g0."id", g0."name", g0."description", g0."image_file_name", g0."image_file_size", g0."image_updated_at", g0."image_content_type" FROM "my_model" AS g0 WHERE ('''sample_tag'' = ANY(tags)') [] (0.9ms)

unfortunaltely, it’s being escaped (so it should produce sth. like this: )

SELECT g0."id", g0."name", g0."description", g0."image_file_name", g0."image_file_size", g0."image_updated_at", g0."image_content_type" FROM "my_mode." AS g0 WHERE ('sample_tag' = ANY(tags))

How can I achieve that?

2

2 Answers

18
votes

You can use fragments to send expressions to the DB:

from g in MyModel,
  where: fragment("? = ANY(?)", "sample_tag", g.tags)
6
votes

You can run sql via Ecto using

Ecto.Adapters.SQL.query(Repo, "sql here")

There is a third param, for prepared statements.