alexdesousa / ayesql

Library for using raw SQL in Elixir
MIT License
138 stars 14 forks source link

Feature/inner queries #12

Closed alexdesousa closed 4 years ago

alexdesousa commented 4 years ago

This PR adds subqueries with local scope e.g:

-- name: ascending
ASC

-- name: descending
DESC

-- name: by_age
age :order_direction

-- name: by_name
name :order_direction

-- name: get_adults
-- docs: Gets adults.
SELECT name, age
  FROM person
 WHERE age >= 18
ORDER BY :order_by

Then our code in elixir would be:

iex> order_by = [
...>   by_name: [order_direction: :ascending],
...>   by_age: [order_direction: :descending]
...> ]
iex> Queries.get_adults(order_by: {:inner, order_by, ", "})
{:ok,
  [
    %{name: "Alice", age: 42},
    %{name: "Bob", age: 21},
    ...
  ]
}

Note: If you're using this level of composability, consider using Ecto if it fits your problem or stack.