Yesql

Yesql is an Elixir library for using SQL.

Rationale

You're writing Elixir You need to write some SQL.

One option is to use Ecto, which provides a sophisticated DSL for generating database queries at runtime. This can be convenient for simple use, but its abstraction only works with the simplest and common database features. Because of this either the abstraction breaks down and we start passing raw strings to Repo.query and fragment, or we will neglect these database features altogether.

So what's the solution? Keep the SQL as SQL. Have one file with your query:

SELECT *
FROM users
WHERE country_code = :country_code

...and then read that file to turn it into a regular Elixir function at compile time:

defmodule Query do
use Yesql, driver: Postgrex, conn: MyApp.ConnectionPool
Yesql.defquery("some/where/select_users_by_country.sql")
end
# A function with the name `users_by_country/1` has been created.
# Let's use it:
iex> Query.users_by_country(country_code: "gbr")
{:ok, [%{name: "Louis", country_code: "gbr"}]}

By keeping the SQL and Elixir separate you get:

When Should I Not Use Yesql?

When you need your SQL to work with many different kinds of database at once. If you want one complex query to be transparently translated into different dialects for MySQL, Oracle, Postgres etc., then you genuinely do need an abstraction layer on top of SQL.

Alternatives

We've talked about Ecto, but how does Yesql compare to $OTHER_LIBRARY?

eql

eql is an Erlang library with similar inspiration and goals.

Development & Testing

createdb yesql_test
mix deps.get
mix test

Other Languages

Yesql rips off is inspired by Kris Jenkins' Clojure Yesql. Similar libraries can be found for many languages:

LanguageProject
C#JaSql
ClojureYeSPARQL
ClojureYesql
Erlangeql
GoDotSql
Gogoyesql
JavaScriptPreql
JavaScriptsqlt
PHPYepSQL
PythonAnosql
Rubyyayql

License

Copyright © 2018 Louis Pilfold. All Rights Reserved.