kura_repo_worker (kura v2.31.3)
View SourceCRUD 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
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
-type hook_error() :: {error, term()}.
What a failing after_insert/1 or after_update/1 hook returns.
-type write_error() :: {error, read_only}.
Functions
-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}).
-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).
-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 a log event map from query execution data.
-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)).
-spec default_logger() -> fun((map()) -> ok).
Return a default logger function that logs queries via logger:info.
-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.
-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.
-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.
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.
-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}.
-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.
-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}.
-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.
-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.
Execute a kura_multi pipeline inside a transaction.
-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).
-spec preload(module(), module(), map() | [map()], [atom() | {atom(), list() | map()}]) -> map() | [map()].
Preload associations on one or more records (standalone, outside of queries).
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.
-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.
Re-fetch a record from the database by its primary key.
-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.
-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 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.
Execute a function inside a database transaction.
-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}.
-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.