XUtils

eql

Erlang with SQL or not.


eql Hex.pm


Erlang with SQL, inspired by yesql.


description

Suppose we have a database with a list of users, in Erlang we can use simple ORM (boss_db, texas), SQL builders (sqerl, mekao) or write SQL queries in Erlang code like this:

get_users(Conn) ->
    pgsql:squery(Conn, "SELECT * FROM users;").

Or something like that. yesql proposes to write SQL queries by your hands, but do it comfortably. Because most of ORM and SQL builders adds some accidental complexity to your software, ORM or builder should parse your code into SQL and then your RDBMS should parse SQL, also write a complex query in ORM - is pure hell, sometimes. That’s why you should use pure SQL with some handy features, like that:

-- Get all users from database
-- :get_all_users
SELECT *
FROM users;

-- Just some description here
-- :get_user_by_id
SELECT *
FROM users
WHERE id = ?

-- Just some description here
-- :get_by_id
SELECT *
FROM :table
WHERE id = ?

In Erlang you can use these queries like functions:

> {ok, Queries} = eql:compile("queries/user.sql"). % with path to your queries file
> {ok, Q1} = eql:get_query(get_all_users, Queries).
> {ok, Q2} = proplists:get_value(get_user_by_id, Queries).
> {ok, Q3} = eql:get_query(get_by_id, Queries, [{table, "some_table"}]).
> Q1.
%> <<"SELECT * FROM users;">>
> Q2.
%> <<"SELECT * FROM users WHERE id = ?">>
> Q3.
%> [<<"SELECT * FROM ">>,"some_table",<<" WHERE id = ?">>]

Note: The named parameters like :table in the example above are not sanitized, so can be dangerous.



Articles

  • coming soon...