AyeSQL v0.2.1 AyeSQL View Source
Aye /ʌɪ/ exclamation (archaic dialect): said to express assent; yes.
AyeSQL is a small Elixir library for using raw SQL.
Overview
Inspired on Clojure library Yesql, AyeSQL tries to find a middle ground between those two approaches by:
- Keeping the SQL in SQL files.
- Generating Elixir functions for every query.
- Having named parameters and query composability easily.
Using the previous query, we would create a SQL file with the following contents:
-- name: get_day_interval
-- docs: Gets days interval.
SELECT generate_series(
current_date - :days::interval, -- Named parameter :days
current_date - interval '1 day',
interval '1 day'
)::date AS date;
-- name: get_avg_clicks
-- docs: Gets average click count.
WITH computed_dates AS ( :get_day_interval )
SELECT dates.date AS day, count(clicks.id) AS count
FROM computed_date AS dates
LEFT JOIN clicks AS clicks ON date(clicks.inserted_at) = dates.date
WHERE clicks.link_id = :link_id -- Named parameter :link_id
GROUP BY dates.date
ORDER BY dates.date;
In Elixir we would load all the queries in this file by doing the following:
defmodule Queries do
use AyeSQL
defqueries("queries.sql") # File name with relative path to SQL file.
end
And then we could execute the query as follows:
params = %{
link_id: 42,
days: %Postgrex.Interval{secs: 864000} # 10 days
}
{:ok, result} = Queries.get_avg_clicks(params, run?: true)
Link to this section Summary
Link to this section Types
app()
View Source
app() :: :ecto | :postgrex
app() :: :ecto | :postgrex
AyeSQL query runners.
query()
View Source
query() :: AyeSQL.Core.query()
query() :: AyeSQL.Core.query()
AyeSQL query statement.
Link to this section Functions
__using__(options) View Source (macro)
Uses AyeSQL
for loading queries.
The available options are:
app
- The app that will run the query. Defaults to:ecto
, but it can also be:postgrex
.repo
- Database repo name. Used by:ecto
app.conn
- Connection with the database. Used by:postgrex
app.
defqueries(relative) View Source (macro)
Macro to load queries from a file
.
Let's say we have the file sql/my_queries.sql
with the following contents:
-- name: get_user
-- docs: Gets user by username
SELECT *
FROM users
WHERE username = :username;
We can load our queries to Elixir using the macro defqueries/1
as follows:
defmodule Queries do
use AyeSQL
defqueries("sql/my_queries.sql")
end
We can now do the following to get the SQL and the ordered arguments:
iex(1)> Queries.get_user!(%{username: "some_user"})
{"SELECT * FROM user WHERE username = $1", ["some_user"]}
If we would like to execute the previous query directly, the we could do the following:
iex(1)> Queries.get_user!(%{username: "some_user"}, run?: true)
%Postgrex.Result{...}
We can also run the query by composing it with the Queries.run/1
function
generated in the module e.g:
iex(1)> %{username: "some_user"} |> Queries.get_user!() |> Queries.run!()
%Postgrex.Result{...}