barrel_design

View Source

Barrel views keep a list current as documents change: which invoices are open, and how much each customer owes. The application reads the list whenever a dashboard opens, and can wait for a recent payment to be included before issuing a statement.

A design is a named, versioned collection of views installed in a barrel_docdb database. Each view selects documents with a BQL condition and turns each one into ordered key/value rows, from document paths or from a WebAssembly map, totalled with _sum, _count or a Wasm reducer at read time. Use it when an application asks for the same categorized lists and totals over and over. Designs can be published to other nodes as signed statements that each node admits under its own trust policy.

The app is optional and needs Erlang/OTP 29 (its runtime, erlang_wasm 0.14.0, requires it). Build and test it from the repository root:

# from the repository root
rebar3 as design compile
rebar3 as design ct --dir apps/barrel_design/test

Start with Your first view: open invoices for one customer and their total, with no toolchain. Install a design and read a category total:

Db = <<"billing">>,   %% the database of "Your first view", with its two invoices
Design = #{name => <<"receivables">>, version => 1,
           views => #{<<"open_by_customer">> => #{
               select => <<"SELECT * FROM db WHERE type = 'invoice' AND status = 'open'">>,
               key => [#{path => [<<"customer">>], type => text, category => true},
                       #{path => [<<"due_on">>], type => text}],
               value => #{sum => [<<"line_cents">>]}, reduce => '_sum'}}},
{ok, #{outcome := installed}} = barrel_design:install(Db, Design, #{}),
{ok, [#{key := [<<"Ada">>], value := 2550}], _} =
    barrel_design:query(Db, {<<"receivables">>, <<"open_by_customer">>},
                        #{key_prefix => [<<"Ada">>], group_level => 1}).

Optionally, try a Wasm map on sample documents without installing anything. In a shell started from the repository root:

%% from the repository root
{ok, _} = application:ensure_all_started(barrel_design),
View = #{select => <<"SELECT * FROM db WHERE type = 'sale'">>,
         map => #{fields => [{[<<"customer">>], text}, {[<<"cents">>], i64}]},
         key => #{type => text}, value => #{type => i64}, reduce => '_sum'},
{ok, Wat} = file:read_file("apps/barrel_design/test/guests/by_customer.wat"),
{ok, [#{id := <<"a">>, rows := [#{key := <<"Ada">>, value := 1250}]}] = Results} =
    barrel_design:preview({wat, Wat}, View,
        [#{<<"id">> => <<"a">>, <<"type">> => <<"sale">>,
           <<"customer">> => <<"Ada">>, <<"cents">> => 1250}]).

The test guests in test/guests rebuild, from the repository root, with make -C apps/barrel_design/test/guests (wasm-tools 1.256.0, Zig 0.17.1, the pinned Rust toolchain for make -C apps/barrel_design/test/guests rust).