Current section

Files

Jump to
based_pg src based_pg.erl
Raw

src/based_pg.erl

-module(based_pg).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]).
-export([with_connection/2]).
-export_type([config/0]).
-type config() :: {config, binary(), integer(), binary(), binary(), binary()}.
-spec connect(config()) -> gleam@pgo:connection().
connect(Config) ->
{config, Host, Port, Database, User, Password} = Config,
Conn = gleam_pgo_ffi:connect(
erlang:setelement(
9,
erlang:setelement(
6,
erlang:setelement(
5,
erlang:setelement(
4,
erlang:setelement(
3,
erlang:setelement(
2,
gleam@pgo:default_config(),
Host
),
Port
),
Database
),
User
),
{some, Password}
),
5
)
),
Conn.
-spec to_pgo_values(list(based:value())) -> list(gleam@pgo:value()).
to_pgo_values(Values) ->
_pipe = Values,
gleam@list:map(_pipe, fun(Value) -> case Value of
{string, Val} ->
gleam_pgo_ffi:coerce(Val);
{int, Val@1} ->
gleam_pgo_ffi:coerce(Val@1);
{float, Val@2} ->
gleam_pgo_ffi:coerce(Val@2);
{bool, Val@3} ->
gleam_pgo_ffi:coerce(Val@3);
null ->
gleam_pgo_ffi:null()
end end).
-spec execute(based:'query'(GUB), gleam@pgo:connection()) -> {ok,
based:returned(GUB)} |
{error, nil}.
execute(Query, Conn) ->
{'query', Sql, Args, Maybe_decoder} = Query,
Values = to_pgo_values(Args),
Execution = case Maybe_decoder of
{some, Decoder} ->
_pipe = gleam@pgo:execute(Sql, Conn, Values, Decoder),
gleam@result:map(
_pipe,
fun(Ret) ->
{returned, erlang:element(2, Ret), erlang:element(3, Ret)}
end
);
_ ->
_pipe@1 = gleam@pgo:execute(
Sql,
Conn,
Values,
fun gleam@dynamic:dynamic/1
),
gleam@result:replace(_pipe@1, {returned, 0, []})
end,
_pipe@2 = Execution,
gleam@result:replace_error(_pipe@2, nil).
-spec with_connection(
config(),
fun((based:db(any(), gleam@pgo:connection())) -> GUA)
) -> GUA.
with_connection(Config, Callback) ->
Conn = connect(Config),
Result = begin
_pipe = {db, Conn, fun execute/2},
Callback(_pipe)
end,
gleam_pgo_ffi:disconnect(Conn),
Result.