Current section

Files

Jump to
storch src storch.erl
Raw

src/storch.erl

-module(storch).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]).
-export([migrate/2]).
-export_type([migration/0]).
-type migration() :: {migration, integer(), binary()}.
-spec migrate(list(migration()), sqlight:connection()) -> {ok, nil} |
{error, sqlight:error()}.
migrate(Migrations, Connection) ->
Transaction = (gleam@result:'try'(
sqlight:exec(<<"begin transaction;"/utf8>>, Connection),
fun(_) ->
gleam@result:'try'(
sqlight:exec(
<<"create table if not exists storch_migrations (id integer, applied integer);"/utf8>>,
Connection
),
fun(_) ->
Migrations_decoder = gleam@dynamic:tuple2(
fun gleam@dynamic:int/1,
fun sqlight:decode_bool/1
),
Applications = gleam@list:try_each(
Migrations,
fun(Migration) ->
gleam@result:'try'(
sqlight:'query'(
<<"select id, applied from storch_migrations where id = ?;"/utf8>>,
Connection,
[sqlight:int(erlang:element(2, Migration))],
Migrations_decoder
),
fun(Migrated) ->
Already_applied = case Migrated of
[] ->
false;
[{_, Applied}] ->
Applied;
_ ->
erlang:error(#{gleam_error => panic,
message => <<"Multiple migrations with the same id in the storch migrations table"/utf8>>,
module => <<"storch"/utf8>>,
function => <<"migrate"/utf8>>,
line => 44})
end,
gleam@bool:guard(
Already_applied,
{ok, nil},
fun() ->
gleam@result:'try'(
sqlight:exec(
erlang:element(3, Migration),
Connection
),
fun(_) ->
gleam@result:'try'(
sqlight:'query'(
<<"insert into storch_migrations (id, applied) values (?,?) returning *;"/utf8>>,
Connection,
[sqlight:int(
erlang:element(
2,
Migration
)
),
sqlight:bool(
true
)],
Migrations_decoder
),
fun(_) -> {ok, nil} end
)
end
)
end
)
end
)
end
),
gleam@result:'try'(
Applications,
fun(_) ->
gleam@result:'try'(
sqlight:exec(<<"commit;"/utf8>>, Connection),
fun(_) -> {ok, nil} end
)
end
)
end
)
end
)),
case Transaction of
{ok, _} ->
{ok, nil};
{error, Err} ->
gleam@io:println(<<"error running migration"/utf8>>),
gleam@io:debug(Err),
gleam@io:println(<<"rolling back"/utf8>>),
_ = sqlight:exec(<<"rollback;"/utf8>>, Connection),
{error, Err}
end.