Today I Learned

hashrocket A Hashrocket project

Execute raw parameterized SQL with Ecto in Elixir

Using SQL directly is a good way to use some of the more interesting parts of SQL that Ecto does not provide a ready abstraction for in its DSL. And parameterization is necessary to avoid SQL injection and just to be able to deal with single quotes correctly. Its fairly straight forward once you find the right module (Ecto.Adapters.SQL) and function (query or query!). Parameters are indicated by $1.

sql = """
  select * from users where name = $1;
"""

results = Ecto.Adapters.SQL.query!(MyApp.Repo, sql, ["chris"])

There is also a stream function on the Ecto.Adapters.SQL module with the same signature as query but the documentation doesn't necessarily state the advantages or situations where it may be useful. More to learn.

See More #elixir TILs
Looking for help? At Hashrocket, we 💜 Elixir! From our many Elixir client projects, to sponsoring the Chicago Elixir Meetup, to the source code for this application, we are invested in this community. Contact us today to talk about your Elixir project.