kura_repo_worker (kura v2.31.3)

View Source

CRUD operations, preloading, transactions, and raw queries.

All functions take a repo module as the first argument and execute against its connection pool.

ok = kura_repo_worker:start(MyRepo),
{ok, Users} = kura_repo_worker:all(MyRepo, kura_query:from(my_user)),
{ok, User} = kura_repo_worker:get(MyRepo, my_user, 1),
{ok, Inserted} = kura_repo_worker:insert(MyRepo, Changeset).

Summary

Types

What a failing after_insert/1 or after_update/1 hook returns.

Functions

Run an aggregate function on a query. Supported: count, sum, avg, min, max.

Run an aggregate with a default value when the result is nil/null.

Execute a query and return all matching rows.

Build a log event map from query execution data.

Count all rows matching a query.

Return a default logger function that logs queries via logger:info.

Delete the record referenced by the changeset's data.

Bulk delete all rows matching the query, returning the count of deleted rows.

Check if any record matches the query.

Fetch a single record by primary key.

Fetch a single record matching all key-value clauses.

Insert a record from a changeset. Returns {error, Changeset} with errors on failure.

Insert a record from a changeset with options, such as #{on_conflict => {Target, Action}} for an upsert.

Bulk insert a list of maps in one statement, returning the count of inserted rows.

Bulk insert with options. #{returning => true | [atom()]} returns inserted rows, so an empty list returns {ok, 0, []}. See insert_all/3 for the limits on the entries.

Execute a kura_multi pipeline inside a transaction.

Execute a query and return exactly one result (adds LIMIT 1).

Preload associations on one or more records (standalone, outside of queries).

Execute raw SQL with parameters.

Execute raw SQL as query/3 does. With #{sensitive => true} telemetry and the query log get ~"[redacted]" in place of each parameter, and a failure's code and names without its message or detail. The SQL text is reported as it is, so keep values out of it.

Re-fetch a record from the database by its primary key.

Restore a soft-deleted record by clearing its deleted_at field.

Soft-delete a record by setting deleted_at to the current timestamp. The record remains in the database but is excluded from normal queries.

Start the connection pool for the given repo module.

Execute a function inside a database transaction.

Update a record from a changeset. No-op if there are no changes.

Bulk update all rows matching the query, returning the count of affected rows.

Types

hook_error()

-type hook_error() :: {error, term()}.

What a failing after_insert/1 or after_update/1 hook returns.

write_error()

-type write_error() :: {error, read_only}.

Functions

aggregate/3

-spec aggregate(module(),
                #kura_query{from :: atom() | module() | binary() | undefined,
                            select :: [atom() | term()] | {exprs, [term()]},
                            wheres :: [term()],
                            joins :: [term()],
                            order_bys :: [term()],
                            group_bys :: [atom()],
                            havings :: [term()],
                            limit :: non_neg_integer() | undefined,
                            offset :: non_neg_integer() | undefined,
                            distinct :: boolean() | [atom()],
                            lock :: kura_query:lock() | binary() | undefined,
                            prefix :: binary() | undefined,
                            preloads :: [atom() | {atom(), list() | map()}],
                            ctes :: [{binary(), #kura_query{}}],
                            combinations :: [{union | union_all | intersect | except, #kura_query{}}],
                            include_deleted :: boolean()},
                count | {count | sum | avg | min | max, atom()}) ->
                   {ok, term()} | {error, term()}.

Run an aggregate function on a query. Supported: count, sum, avg, min, max.

The query is scoped as all/2 scopes it: soft-deleted rows are left out unless the query asks for them with kura_query:with_deleted/1, and the current tenant applies.

{ok, 42} = kura_repo_worker:aggregate(MyRepo, Q, count).
{ok, 150.5} = kura_repo_worker:aggregate(MyRepo, Q, {sum, score}).

aggregate(RepoMod, Query, Agg, Default)

-spec aggregate(module(),
                #kura_query{from :: atom() | module() | binary() | undefined,
                            select :: [atom() | term()] | {exprs, [term()]},
                            wheres :: [term()],
                            joins :: [term()],
                            order_bys :: [term()],
                            group_bys :: [atom()],
                            havings :: [term()],
                            limit :: non_neg_integer() | undefined,
                            offset :: non_neg_integer() | undefined,
                            distinct :: boolean() | [atom()],
                            lock :: kura_query:lock() | binary() | undefined,
                            prefix :: binary() | undefined,
                            preloads :: [atom() | {atom(), list() | map()}],
                            ctes :: [{binary(), #kura_query{}}],
                            combinations :: [{union | union_all | intersect | except, #kura_query{}}],
                            include_deleted :: boolean()},
                count | {count | sum | avg | min | max, atom()},
                term()) ->
                   {ok, term()} | {error, term()}.

Run an aggregate with a default value when the result is nil/null.

{ok, 0} = kura_repo_worker:aggregate(MyRepo, Q, {sum, score}, 0).

all(RepoMod, Query)

-spec all(module(),
          #kura_query{from :: atom() | module() | binary() | undefined,
                      select :: [atom() | term()] | {exprs, [term()]},
                      wheres :: [term()],
                      joins :: [term()],
                      order_bys :: [term()],
                      group_bys :: [atom()],
                      havings :: [term()],
                      limit :: non_neg_integer() | undefined,
                      offset :: non_neg_integer() | undefined,
                      distinct :: boolean() | [atom()],
                      lock :: kura_query:lock() | binary() | undefined,
                      prefix :: binary() | undefined,
                      preloads :: [atom() | {atom(), list() | map()}],
                      ctes :: [{binary(), #kura_query{}}],
                      combinations :: [{union | union_all | intersect | except, #kura_query{}}],
                      include_deleted :: boolean()}) ->
             {ok, [map()]} | {error, term()}.

Execute a query and return all matching rows.

build_log_event(Repo, SQL, Params, Result, DurationUs)

-spec build_log_event(module(), iodata(), [term()], term(), integer()) -> map().

Build a log event map from query execution data.

build_telemetry_metadata(RepoMod, SQL, Params, Result)

count(RepoMod, Query)

-spec count(module(),
            #kura_query{from :: atom() | module() | binary() | undefined,
                        select :: [atom() | term()] | {exprs, [term()]},
                        wheres :: [term()],
                        joins :: [term()],
                        order_bys :: [term()],
                        group_bys :: [atom()],
                        havings :: [term()],
                        limit :: non_neg_integer() | undefined,
                        offset :: non_neg_integer() | undefined,
                        distinct :: boolean() | [atom()],
                        lock :: kura_query:lock() | binary() | undefined,
                        prefix :: binary() | undefined,
                        preloads :: [atom() | {atom(), list() | map()}],
                        ctes :: [{binary(), #kura_query{}}],
                        combinations :: [{union | union_all | intersect | except, #kura_query{}}],
                        include_deleted :: boolean()}) ->
               {ok, non_neg_integer()} | {error, term()}.

Count all rows matching a query.

{ok, 42} = kura_repo_worker:count(MyRepo, kura_query:from(my_schema)).

default_logger()

-spec default_logger() -> fun((map()) -> ok).

Return a default logger function that logs queries via logger:info.

delete(RepoMod, CS)

-spec delete(module(),
             #kura_changeset{valid :: boolean(),
                             schema :: module() | undefined,
                             data :: map(),
                             params :: map(),
                             changes :: map(),
                             errors :: [{atom(), binary()}],
                             types :: #{atom() => kura_types:kura_type()},
                             required :: [atom()],
                             action :: atom() | undefined,
                             constraints ::
                                 [#kura_constraint{type :: unique | foreign_key | check | exclusion,
                                                   constraint :: binary(),
                                                   field :: atom(),
                                                   message :: binary()}],
                             assoc_changes :: #{atom() => #kura_changeset{} | [#kura_changeset{}]},
                             prepare :: [fun((#kura_changeset{}) -> #kura_changeset{})],
                             optimistic_lock :: atom() | undefined}) ->
                {ok, map()} | {error, term()}.

Delete the record referenced by the changeset's data.

delete_all(RepoMod, Query)

-spec delete_all(module(),
                 #kura_query{from :: atom() | module() | binary() | undefined,
                             select :: [atom() | term()] | {exprs, [term()]},
                             wheres :: [term()],
                             joins :: [term()],
                             order_bys :: [term()],
                             group_bys :: [atom()],
                             havings :: [term()],
                             limit :: non_neg_integer() | undefined,
                             offset :: non_neg_integer() | undefined,
                             distinct :: boolean() | [atom()],
                             lock :: kura_query:lock() | binary() | undefined,
                             prefix :: binary() | undefined,
                             preloads :: [atom() | {atom(), list() | map()}],
                             ctes :: [{binary(), #kura_query{}}],
                             combinations :: [{union | union_all | intersect | except, #kura_query{}}],
                             include_deleted :: boolean()}) ->
                    {ok, non_neg_integer()} | {error, term()}.

Bulk delete all rows matching the query, returning the count of deleted rows.

Raises {kura, {unsupported_in_bulk_write, Clause}} for the same clauses as update_all/3: Clause is the first of joins, order_bys, group_bys, havings, limit, offset, distinct, ctes and combinations, in that order, that the query sets.

exists(RepoMod, Query)

-spec exists(module(),
             #kura_query{from :: atom() | module() | binary() | undefined,
                         select :: [atom() | term()] | {exprs, [term()]},
                         wheres :: [term()],
                         joins :: [term()],
                         order_bys :: [term()],
                         group_bys :: [atom()],
                         havings :: [term()],
                         limit :: non_neg_integer() | undefined,
                         offset :: non_neg_integer() | undefined,
                         distinct :: boolean() | [atom()],
                         lock :: kura_query:lock() | binary() | undefined,
                         prefix :: binary() | undefined,
                         preloads :: [atom() | {atom(), list() | map()}],
                         ctes :: [{binary(), #kura_query{}}],
                         combinations :: [{union | union_all | intersect | except, #kura_query{}}],
                         include_deleted :: boolean()}) ->
                {ok, boolean()} | {error, term()}.

Check if any record matches the query.

extract_source(SQL)

get(RepoMod, SchemaMod, Spec)

-spec get(module(), module(), term()) -> {ok, map()} | {error, not_found} | {error, term()}.

Fetch a single record by primary key.

For a single-key schema pass the bare key value; for a composite-key schema pass a #{field => value} map covering every key column. A map-valued single key must be wrapped as #{KeyField => Map}, since a bare map is read as a composite key spec.

get_by(RepoMod, SchemaMod, Clauses)

-spec get_by(module(), module(), [{atom(), term()}]) ->
                {ok, map()} | {error, not_found} | {error, term()}.

Fetch a single record matching all key-value clauses.

Each clause is an equality and its value is always bound, so an atom taken from a request cannot turn into an operator: {status, is_not_nil} compares status with the atom rather than testing for NULL. For a NULL test use one/2 with kura_query:where/2 and {Field, is_nil}.

insert(RepoMod, CS)

-spec insert(module(),
             #kura_changeset{valid :: boolean(),
                             schema :: module() | undefined,
                             data :: map(),
                             params :: map(),
                             changes :: map(),
                             errors :: [{atom(), binary()}],
                             types :: #{atom() => kura_types:kura_type()},
                             required :: [atom()],
                             action :: atom() | undefined,
                             constraints ::
                                 [#kura_constraint{type :: unique | foreign_key | check | exclusion,
                                                   constraint :: binary(),
                                                   field :: atom(),
                                                   message :: binary()}],
                             assoc_changes :: #{atom() => #kura_changeset{} | [#kura_changeset{}]},
                             prepare :: [fun((#kura_changeset{}) -> #kura_changeset{})],
                             optimistic_lock :: atom() | undefined}) ->
                {ok, map()} |
                {error,
                 #kura_changeset{valid :: boolean(),
                                 schema :: module() | undefined,
                                 data :: map(),
                                 params :: map(),
                                 changes :: map(),
                                 errors :: [{atom(), binary()}],
                                 types :: #{atom() => kura_types:kura_type()},
                                 required :: [atom()],
                                 action :: atom() | undefined,
                                 constraints ::
                                     [#kura_constraint{type :: unique | foreign_key | check | exclusion,
                                                       constraint :: binary(),
                                                       field :: atom(),
                                                       message :: binary()}],
                                 assoc_changes :: #{atom() => #kura_changeset{} | [#kura_changeset{}]},
                                 prepare :: [fun((#kura_changeset{}) -> #kura_changeset{})],
                                 optimistic_lock :: atom() | undefined}} |
                hook_error() |
                write_error().

Insert a record from a changeset. Returns {error, Changeset} with errors on failure.

insert(RepoMod, CS, Opts)

-spec insert(module(),
             #kura_changeset{valid :: boolean(),
                             schema :: module() | undefined,
                             data :: map(),
                             params :: map(),
                             changes :: map(),
                             errors :: [{atom(), binary()}],
                             types :: #{atom() => kura_types:kura_type()},
                             required :: [atom()],
                             action :: atom() | undefined,
                             constraints ::
                                 [#kura_constraint{type :: unique | foreign_key | check | exclusion,
                                                   constraint :: binary(),
                                                   field :: atom(),
                                                   message :: binary()}],
                             assoc_changes :: #{atom() => #kura_changeset{} | [#kura_changeset{}]},
                             prepare :: [fun((#kura_changeset{}) -> #kura_changeset{})],
                             optimistic_lock :: atom() | undefined},
             map()) ->
                {ok, map()} |
                {error,
                 #kura_changeset{valid :: boolean(),
                                 schema :: module() | undefined,
                                 data :: map(),
                                 params :: map(),
                                 changes :: map(),
                                 errors :: [{atom(), binary()}],
                                 types :: #{atom() => kura_types:kura_type()},
                                 required :: [atom()],
                                 action :: atom() | undefined,
                                 constraints ::
                                     [#kura_constraint{type :: unique | foreign_key | check | exclusion,
                                                       constraint :: binary(),
                                                       field :: atom(),
                                                       message :: binary()}],
                                 assoc_changes :: #{atom() => #kura_changeset{} | [#kura_changeset{}]},
                                 prepare :: [fun((#kura_changeset{}) -> #kura_changeset{})],
                                 optimistic_lock :: atom() | undefined}} |
                hook_error() |
                write_error().

Insert a record from a changeset with options, such as #{on_conflict => {Target, Action}} for an upsert.

Runs the same pipeline as insert/2: prepare_changes/2 functions, before_insert/1 and after_insert/1, and the changeset's associations, in one transaction when there are any.

after_insert/1 runs whenever the statement returns a row, so on an upsert it also runs when the conflict updated an existing row. When the conflict leaves the row as it was (nothing, or a row the tenant guard refuses), no row comes back: the result is the changeset's data with its changes applied, after_insert/1 does not run and no association is written.

A changeset with associations takes no on_conflict action but nothing, since an upsert that updates a row would insert its children again: it raises {kura, on_conflict_with_assocs}.

insert_all(RepoMod, SchemaMod, Entries)

-spec insert_all(module(), module(), [map()]) -> {ok, non_neg_integer()} | {error, term()}.

Bulk insert a list of maps in one statement, returning the count of inserted rows.

An empty list inserts nothing and returns {ok, 0} without a statement.

Every entry must set the same fields. The statement has one column list, so an entry with a field the others lack, or without one they have, returns {error, {entries_differ, Fields, EntryFields}} and nothing is written.

A statement holds a limited number of bound values, 65535 on PostgreSQL, and each entry binds one per field. A list over the limit raises {kura, {too_many_parameters, Count, Max}}. Split the list and insert the parts inside one transaction.

insert_all(RepoMod, SchemaMod, Entries, Opts)

-spec insert_all(module(), module(), [map()], map()) ->
                    {ok, non_neg_integer()} | {ok, non_neg_integer(), [map()]} | {error, term()}.

Bulk insert with options. #{returning => true | [atom()]} returns inserted rows, so an empty list returns {ok, 0, []}. See insert_all/3 for the limits on the entries.

multi(RepoMod, Multi)

-spec multi(module(), kura_multi:t()) -> {ok, map()} | {error, atom(), term(), map()}.

Execute a kura_multi pipeline inside a transaction.

one(RepoMod, Query)

-spec one(module(),
          #kura_query{from :: atom() | module() | binary() | undefined,
                      select :: [atom() | term()] | {exprs, [term()]},
                      wheres :: [term()],
                      joins :: [term()],
                      order_bys :: [term()],
                      group_bys :: [atom()],
                      havings :: [term()],
                      limit :: non_neg_integer() | undefined,
                      offset :: non_neg_integer() | undefined,
                      distinct :: boolean() | [atom()],
                      lock :: kura_query:lock() | binary() | undefined,
                      prefix :: binary() | undefined,
                      preloads :: [atom() | {atom(), list() | map()}],
                      ctes :: [{binary(), #kura_query{}}],
                      combinations :: [{union | union_all | intersect | except, #kura_query{}}],
                      include_deleted :: boolean()}) ->
             {ok, map()} | {error, not_found} | {error, term()}.

Execute a query and return exactly one result (adds LIMIT 1).

pgo_query(RepoMod, SQL, Params)

preload(RepoMod, Schema, Records, Assocs)

-spec preload(module(), module(), map() | [map()], [atom() | {atom(), list() | map()}]) ->
                 map() | [map()].

Preload associations on one or more records (standalone, outside of queries).

query(RepoMod, SQL, Params)

-spec query(module(), iodata(), [term()]) -> {ok, list()} | {error, term()}.

Execute raw SQL with parameters.

Rows come back as the driver decodes them: no schema is involved, so no field type is applied. A jsonb column arrives as its JSON text, and an enum column as a binary. Decode such a column yourself (json:decode/1), extract the value in SQL (metadata->>'key'), or read through a schema query, which loads every column through its field type.

Params are reported to telemetry and the query log as they are: kura cannot tell which of them is sensitive. Use query/4 when one is.

query(RepoMod, SQL, Params, Opts)

-spec query(module(), iodata(), [term()], #{sensitive => boolean()}) -> {ok, list()} | {error, term()}.

Execute raw SQL as query/3 does. With #{sensitive => true} telemetry and the query log get ~"[redacted]" in place of each parameter, and a failure's code and names without its message or detail. The SQL text is reported as it is, so keep values out of it.

reload(RepoMod, SchemaMod, Record)

-spec reload(module(), module(), map()) -> {ok, map()} | {error, term()}.

Re-fetch a record from the database by its primary key.

restore/2

-spec restore(module(),
              #kura_changeset{valid :: boolean(),
                              schema :: module() | undefined,
                              data :: map(),
                              params :: map(),
                              changes :: map(),
                              errors :: [{atom(), binary()}],
                              types :: #{atom() => kura_types:kura_type()},
                              required :: [atom()],
                              action :: atom() | undefined,
                              constraints ::
                                  [#kura_constraint{type :: unique | foreign_key | check | exclusion,
                                                    constraint :: binary(),
                                                    field :: atom(),
                                                    message :: binary()}],
                              assoc_changes :: #{atom() => #kura_changeset{} | [#kura_changeset{}]},
                              prepare :: [fun((#kura_changeset{}) -> #kura_changeset{})],
                              optimistic_lock :: atom() | undefined}) ->
                 {ok, map()} | {error, term()}.

Restore a soft-deleted record by clearing its deleted_at field.

soft_delete/2

-spec soft_delete(module(),
                  #kura_changeset{valid :: boolean(),
                                  schema :: module() | undefined,
                                  data :: map(),
                                  params :: map(),
                                  changes :: map(),
                                  errors :: [{atom(), binary()}],
                                  types :: #{atom() => kura_types:kura_type()},
                                  required :: [atom()],
                                  action :: atom() | undefined,
                                  constraints ::
                                      [#kura_constraint{type :: unique | foreign_key | check | exclusion,
                                                        constraint :: binary(),
                                                        field :: atom(),
                                                        message :: binary()}],
                                  assoc_changes :: #{atom() => #kura_changeset{} | [#kura_changeset{}]},
                                  prepare :: [fun((#kura_changeset{}) -> #kura_changeset{})],
                                  optimistic_lock :: atom() | undefined}) ->
                     {ok, map()} | {error, term()}.

Soft-delete a record by setting deleted_at to the current timestamp. The record remains in the database but is excluded from normal queries.

Returns {error, not_soft_deletable} if the schema has no deleted_at field.

start(RepoMod)

-spec start(module()) -> ok | {error, term()}.

Start the connection pool for the given repo module.

The repo's config is read as kura_repo:config/1 returns it, init/1 applied, and the pool is named by its pool key, as at application boot. The connection settings in it go to its pool_module, which maps them onto its own options and defaults; kura's own settings are kept back. Returns {error, Reason} when the pool does not start, with any secret in Reason replaced by redacted. A pool module that raises instead makes this raise {pool_start_failed, RepoMod, {Class, Redacted}}. A repo init/1 that raises returns {error, {init_failed, {Class, Shape}}}, keeping only the shape of its reason; see kura_db:start_pool/1. A pool name another repo's running pool already has returns {error, {pool_owned_by, Owner}}.

Queries then use the settings the pool was started with, without calling init/1 again. Calling start/1 again on a running pool returns ok and re-reads them. When they changed, storing them replaces a persistent_term, which triggers a global garbage collection over every process, so refresh on a config change, not per request. Settings that are unchanged cost nothing.

A running pool keeps the connection settings it was started with: calling start/1 again after changing the credentials returns ok and changes nothing in the pool. Call kura_db:stop_pool/1 and then start/1 to apply new credentials.

transaction(RepoMod, Fun)

-spec transaction(module(), fun(() -> term())) -> term().

Execute a function inside a database transaction.

update(RepoMod, CS)

-spec update(module(),
             #kura_changeset{valid :: boolean(),
                             schema :: module() | undefined,
                             data :: map(),
                             params :: map(),
                             changes :: map(),
                             errors :: [{atom(), binary()}],
                             types :: #{atom() => kura_types:kura_type()},
                             required :: [atom()],
                             action :: atom() | undefined,
                             constraints ::
                                 [#kura_constraint{type :: unique | foreign_key | check | exclusion,
                                                   constraint :: binary(),
                                                   field :: atom(),
                                                   message :: binary()}],
                             assoc_changes :: #{atom() => #kura_changeset{} | [#kura_changeset{}]},
                             prepare :: [fun((#kura_changeset{}) -> #kura_changeset{})],
                             optimistic_lock :: atom() | undefined}) ->
                {ok, map()} |
                {error,
                 #kura_changeset{valid :: boolean(),
                                 schema :: module() | undefined,
                                 data :: map(),
                                 params :: map(),
                                 changes :: map(),
                                 errors :: [{atom(), binary()}],
                                 types :: #{atom() => kura_types:kura_type()},
                                 required :: [atom()],
                                 action :: atom() | undefined,
                                 constraints ::
                                     [#kura_constraint{type :: unique | foreign_key | check | exclusion,
                                                       constraint :: binary(),
                                                       field :: atom(),
                                                       message :: binary()}],
                                 assoc_changes :: #{atom() => #kura_changeset{} | [#kura_changeset{}]},
                                 prepare :: [fun((#kura_changeset{}) -> #kura_changeset{})],
                                 optimistic_lock :: atom() | undefined}} |
                {error, stale} |
                hook_error() |
                write_error().

Update a record from a changeset. No-op if there are no changes.

With kura_changeset:optimistic_lock/2 set, a row whose lock field no longer matches returns {error, stale}.

update_all(RepoMod, Query, Updates)

-spec update_all(module(),
                 #kura_query{from :: atom() | module() | binary() | undefined,
                             select :: [atom() | term()] | {exprs, [term()]},
                             wheres :: [term()],
                             joins :: [term()],
                             order_bys :: [term()],
                             group_bys :: [atom()],
                             havings :: [term()],
                             limit :: non_neg_integer() | undefined,
                             offset :: non_neg_integer() | undefined,
                             distinct :: boolean() | [atom()],
                             lock :: kura_query:lock() | binary() | undefined,
                             prefix :: binary() | undefined,
                             preloads :: [atom() | {atom(), list() | map()}],
                             ctes :: [{binary(), #kura_query{}}],
                             combinations :: [{union | union_all | intersect | except, #kura_query{}}],
                             include_deleted :: boolean()},
                 map()) ->
                    {ok, non_neg_integer()} | {error, term()}.

Bulk update all rows matching the query, returning the count of affected rows.

The statement is built from the query's from, its where conditions and its prefix. A query with a join, an order_by, a group_by, a having, a limit, an offset, a distinct, a CTE or a combination raises {kura, {unsupported_in_bulk_write, Clause}}, since the write would otherwise ignore the clause and touch rows the query does not select. Clause is the first of joins, order_bys, group_bys, havings, limit, offset, distinct, ctes and combinations, in that order, that the query sets.