Packages

A database driver abstraction layer for Gleam

Retired package: Release invalid

Current section

Files

Jump to
common_sql src common_sql.erl
Raw

src/common_sql.erl

-module(common_sql).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch, inline]).
-define(FILEPATH, "src/common_sql.gleam").
-export([connect/2, execute/5, close/2, with_connection/3]).
-export_type([param/0, db_error/0, 'query'/0, driver/1]).
-if(?OTP_RELEASE >= 27).
-define(MODULEDOC(Str), -moduledoc(Str)).
-define(DOC(Str), -doc(Str)).
-else.
-define(MODULEDOC(Str), -compile([])).
-define(DOC(Str), -compile([])).
-endif.
-type param() :: {p_int, integer()} |
{p_string, binary()} |
{p_float, float()} |
{p_bool, boolean()} |
p_null.
-type db_error() :: {query_error, binary()} | {connection_error, binary()}.
-type 'query'() :: {sql, binary()} | {portable, binary()}.
-type driver(DKT) :: {driver,
binary(),
fun((binary()) -> {ok, DKT} | {error, db_error()}),
fun((DKT, 'query'(), list(param())) -> {ok,
list(gleam@dynamic:dynamic_())} |
{error, db_error()}),
fun((DKT) -> nil)}.
-file("src/common_sql.gleam", 48).
?DOC(" Establish a connection using the given driver and connection URL.\n").
-spec connect(driver(DKU), binary()) -> {ok, DKU} | {error, db_error()}.
connect(Driver, Url) ->
(erlang:element(3, Driver))(Url).
-file("src/common_sql.gleam", 54).
?DOC(
" Execute a SQL query, decode each returned row with `decoder`, and collect\n"
" all rows into a `List(a)`. Decoding errors are surfaced as `QueryError`.\n"
).
-spec execute(
driver(DKY),
DKY,
'query'(),
list(param()),
gleam@dynamic@decode:decoder(DLB)
) -> {ok, list(DLB)} | {error, db_error()}.
execute(Driver, Conn, Query, Params, Decoder) ->
gleam@result:'try'(
(erlang:element(4, Driver))(Conn, Query, Params),
fun(Rows) -> _pipe = Rows,
_pipe@2 = gleam@list:map(
_pipe,
fun(Row) -> _pipe@1 = gleam@dynamic@decode:run(Row, Decoder),
gleam@result:map_error(
_pipe@1,
fun(Errors) ->
{query_error, gleam@string:inspect(Errors)}
end
) end
),
gleam@result:all(_pipe@2) end
).
-file("src/common_sql.gleam", 71).
?DOC(" Close a connection using the given driver.\n").
-spec close(driver(DLG), DLG) -> nil.
close(Driver, Conn) ->
(erlang:element(5, Driver))(Conn).
-file("src/common_sql.gleam", 83).
?DOC(
" Open a connection, run `f` with it, then close it — even if `f` returns\n"
" an error. This is the preferred way to use a connection as it guarantees\n"
" the connection is always closed.\n"
"\n"
" ```gleam\n"
" use conn <- sql.with_connection(driver, \"postgres://localhost/mydb\")\n"
" sql.execute(driver, conn, \"SELECT id FROM users\", [], decode.int)\n"
" ```\n"
).
-spec with_connection(
driver(DLI),
binary(),
fun((DLI) -> {ok, DLK} | {error, db_error()})
) -> {ok, DLK} | {error, db_error()}.
with_connection(Driver, Url, F) ->
gleam@result:'try'(
(erlang:element(3, Driver))(Url),
fun(Conn) ->
Result = F(Conn),
(erlang:element(5, Driver))(Conn),
Result
end
).