Barrel
EN GitHub

Créer une branche, comparer, fusionner, restaurer

Ce projet essaie une modification sur une branche d’une base de données avant de toucher l’original. Il écrit une petite liste de prix, augmente un prix sur la base principale, crée une branche, modifie, ajoute et supprime sur la branche, compare les deux avec la même requête BQL et l’historique des versions, fusionne la branche, puis ouvre une seconde branche de la base principale telle qu’elle était avant toute modification (restauration à un instant donné). Utilisez-le quand une exécution d’agent, une migration ou une modification en masse doit être relue avant d’être appliquée.

Prérequis

  • Erlang/OTP 26 ou plus récent (cette exécution a utilisé OTP 29) et rebar3.
  • Un compilateur C et CMake pour les dépendances natives (la première compilation prend quelques minutes).

Exécuter

./run.sh

run.sh compile le projet, supprime ./data, puis exécute branch_experiment:main/0 une fois.

Ce que montre l’exemple

  • barrel:changes(Db, first) renvoie le curseur du dernier changement : gardez-le pour revenir plus tard à ce point.
  • barrel:branch/2 crée maintenant une branche de la base. Les écritures sur la branche ne touchent pas le parent tant que vous ne fusionnez pas.
  • barrel:doc_versions/2 et barrel:version_body/3 listent les versions d’un document et lisent chacune d’elles.
  • barrel:merge/1 écrit les modifications de la branche dans le parent et renvoie un rapport.
  • barrel:branch(Db, Name, #{at => Cursor}) ouvre une branche du passé.
  • Une branche d’une branche est refusée : {error, cannot_branch_a_branch}.

Notes

  • La filiation n’a qu’un niveau, et un instant plus ancien que l’historique conservé échoue avec pitr_window_exceeded (la conservation par défaut est de 30 jours).
  • Cette base n’a pas de stockage vectoriel. Sur une base en mode enregistrement, une branche reconstruit son index à partir des embeddings stockés ; la branche d’une base simple ne porte aucun vecteur.

Sortie attendue

La table des prix à chaque étape, les versions d’un document et le rapport de fusion. La sortie d’une exécution réelle se trouve dans expected.txt.

Télécharger Le dossier sur GitHub, avec tous les fichiers ci-dessous.

Code source

src/branch_experiment.erl
%% Try a change on a branch, compare it with the parent, merge it,
%% then open a branch of the past (point-in-time recovery).
-module(branch_experiment).
-export([main/0]).

-define(Q, <<"SELECT id, price FROM plans ORDER BY id">>).

main() ->
    try run() of
        ok -> halt(0)
    catch C:R:S ->
        io:format(standard_error, "~p:~p~n~p~n", [C, R, S]),
        halt(1)
    end.

run() ->
    {ok, _} = application:ensure_all_started(barrel),
    {ok, Db} = barrel:open(<<"pricing">>, #{vectordb => none}),
    _ = barrel:put_docs(Db, [plan(<<"free">>, 0),
                             plan(<<"pro">>, 20),
                             plan(<<"team">>, 50)]),
    %% The changes cursor after the first writes: a point in time.
    {ok, _, T1} = barrel:changes(Db, first),
    table("main, initial", Db),

    %% Later, on main: pro goes up.
    ok = set_price(Db, <<"plan:pro">>, 25),
    table("main, pro raised to 25", Db),

    %% A branch shares the parent's history up to now.
    {ok, Exp} = barrel:branch(Db, <<"pricing_exp">>),
    ok = set_price(Exp, <<"plan:team">>, 45),
    {ok, _} = barrel:put_doc(Exp, plan(<<"edu">>, 5)),
    {ok, Free} = barrel:get_doc(Exp, <<"plan:free">>),
    {ok, _} = barrel:delete_doc(Exp, <<"plan:free">>,
                                #{rev => maps:get(<<"_rev">>, Free)}),
    io:format("~nbranches of pricing: ~p~n",
              [barrel_docdb:list_branches(<<"pricing">>)]),

    %% Compare: the same query on both sides.
    table("branch", Exp),
    table("main, unchanged", Db),
    {ok, Versions} = barrel:doc_versions(Exp, <<"plan:team">>),
    io:format("~nplan:team versions on the branch:~n"),
    [begin
         {ok, B} = barrel:version_body(Exp, <<"plan:team">>, V),
         io:format("  ~s price ~p~n", [S, maps:get(<<"price">>, B)])
     end || #{status := S, version := V} <- Versions],

    %% Merge the branch back into main.
    {ok, Report} = barrel:merge(Exp),
    io:format("~nmerge: ~kp~n",
              [maps:with([docs_read, docs_written, failed], Report)]),
    table("main, after merge", Db),

    %% Point-in-time: a branch of main as it was at T1.
    {ok, Past} = barrel:branch(Db, <<"pricing_t1">>, #{at => T1}),
    table("branch at the first cursor", Past),

    %% Branches are one level deep.
    io:format("~nbranch of a branch: ~p~n",
              [barrel:branch(Exp, <<"nested">>)]),

    ok = barrel:delete(Exp),
    ok = barrel:delete(Past),
    ok = barrel:close(Db),
    ok.

plan(Name, Price) ->
    #{<<"id">> => <<"plan:", Name/binary>>, <<"type">> => <<"plan">>,
      <<"price">> => Price}.

set_price(Db, Id, Price) ->
    {ok, Doc} = barrel:get_doc(Db, Id),
    {ok, _} = barrel:put_doc(Db, Doc#{<<"price">> => Price}),
    ok.

table(Title, Db) ->
    {ok, Rows, _} = barrel:query(Db, ?Q),
    io:format("~n~s:~n", [Title]),
    [io:format("  ~-10s ~p~n", [Id, P])
     || #{<<"id">> := Id, <<"price">> := P} <- Rows],
    ok.
rebar.config
{erl_opts, [debug_info]}.
{deps, [{barrel, "~> 1.12"}]}.
run.sh
#!/bin/sh
# Build, then run main/0 once on a fresh data directory.
set -e
cd "$(dirname "$0")"
rebar3 compile >&2
rm -rf data
exec erl -noshell -config config/sys \
  -pa _build/default/lib/*/ebin _build/default/checkouts/*/ebin \
  -eval 'branch_experiment:main()'

Sortie attendue

Le fichier expected.txt de l’exemple, issu d’une exécution réelle. Les révisions, identifiants, jetons et horodatages changent à chaque exécution ; scripts/verify-examples.sh les masque avant de comparer.

expected.txt

main, initial:
  plan:free  0
  plan:pro   20
  plan:team  50

main, pro raised to 25:
  plan:free  0
  plan:pro   25
  plan:team  50

branches of pricing: [<<"pricing_exp">>]

branch:
  plan:edu   5
  plan:pro   25
  plan:team  45

main, unchanged:
  plan:free  0
  plan:pro   25
  plan:team  50

plan:team versions on the branch:
  current price 45
  superseded price 50

merge: #{docs_read => 3,docs_written => 3,failed => []}

main, after merge:
  plan:edu   5
  plan:pro   25
  plan:team  45

branch at the first cursor:
  plan:free  0
  plan:pro   20
  plan:team  50

branch of a branch: {error,cannot_branch_a_branch}

Haut et bas pour se déplacerEntrée pour ouvrir