src/rally_runtime@test_db.erl

-module(rally_runtime@test_db).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch, inline]).
-define(FILEPATH, "src/rally_runtime/test_db.gleam").
-export([setup/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.

-file("src/rally_runtime/test_db.gleam", 23).
-spec template_db(binary()) -> {ok, sqlight:connection()} | {error, nil}.
template_db(Migrations_dir) ->
    Cache_key = <<"rally_test_template:"/utf8, Migrations_dir/binary>>,
    case rally_runtime_test_db_ffi:pt_get(Cache_key, {error, nil}) of
        {ok, Conn} ->
            {ok, Conn};

        {error, nil} ->
            gleam@result:'try'(case sqlight:open(<<":memory:"/utf8>>) of
                    {ok, Conn@1} ->
                        {ok, Conn@1};

                    _ ->
                        {error, nil}
                end, fun(Conn@2) ->
                    gleam@result:'try'(
                        case rally_runtime@migrate:run(Conn@2, Migrations_dir) of
                            {ok, _} ->
                                {ok, nil};

                            _ ->
                                {error, nil}
                        end,
                        fun(_) ->
                            rally_runtime_test_db_ffi:pt_put(
                                Cache_key,
                                {ok, Conn@2}
                            ),
                            {ok, Conn@2}
                        end
                    )
                end)
    end.

-file("src/rally_runtime/test_db.gleam", 46).
?DOC(
    " Open a fresh in-memory database with migrations already applied.\n"
    " The first call runs migrations into a template db cached via\n"
    " persistent_term. Subsequent calls clone it via SQLite's backup\n"
    " API (page-level copy), avoiding re-running migrations per test.\n"
).
-spec setup(binary()) -> {ok, sqlight:connection()} | {error, nil}.
setup(Migrations_dir) ->
    gleam@result:'try'(
        template_db(Migrations_dir),
        fun(Conn) -> rally_runtime_test_db_ffi:clone_db(Conn) end
    ).