cardinal

Reading and writing records

Cardinal.DB, the record API app code uses instead of SQL.

App code reads and writes through Cardinal.DB. Apps send no raw SQL. Filters compile to parametrized SQL inside the platform, and every call checks the ctx user's permissions.

Read

{:ok, rows} =
  Cardinal.DB.get_list(ctx, "GL Entry",
    fields: ["posting_date"],
    filters: [["cost_center", "=", "Main - AC"], ["is_cancelled", "=", false]],
    order_by: "posting_date desc",
    limit: 1
  )
FunctionReturns
get_doc(ctx, rectype, name, opts)The record with its child rows. for_update: true locks the row
get_list(ctx, rectype, opts)Rows. opts: fields, filters, or_filters, order_by, limit, offset, group_by, distinct
get_value(ctx, rectype, match, field)One field of a record
exists(ctx, rectype, match){:ok, true} or {:ok, false}
count(ctx, rectype, opts){:ok, n}
new_doc(ctx, rectype, values)An unsaved record with its defaults
copy_doc(ctx, rectype, rec)The unsaved record a Duplicate starts from, without name, audit columns, no_copy fields or Passwords

Filters are [[field, operator, value], ...] or a map, %{"status" => "Open"}. A single's record is named after its RecType: get_doc(ctx, "FCRM Settings", "FCRM Settings").

Write

{:ok, rec, effects} = Cardinal.DB.insert(ctx, "CRM Task", %{"title" => "Call Acme", "status" => "Todo"})
{:ok, rec, more} = Cardinal.DB.save(ctx, "CRM Task", Map.put(rec, "status", "Done"))
FunctionDoes
insert, save, deleteRun the full lifecycle and its hooks
submit, cancel, amend, discardMove the docstatus
set_value(ctx, rectype, name, values, opts)Writes fields through a save. skip_hooks: true skips the controllers, as Frappe's db_set
rename(ctx, rectype, old, new, opts)Renames and rewrites every Link. merge: true merges into new
delete_many(ctx, rectype, filters)Bulk delete with no hooks or link checks. Needs an as_system ctx
lock(ctx, rectype, match)Locks matching rows FOR UPDATE in name order until the transaction ends, so two writers cannot deadlock
replace_rows(ctx, rectype, match, rows)The only writer of an index RecType
get_password(ctx, rectype, name, field)A Password field's plaintext. as_system ctx only

insert/4 takes ignore_mandatory: true under as_system, as a tree's root needs. cancel/4 takes ignore_links: true.

Writes return {:ok, rec, effects}. Errors include {:invalid, errors}, :not_found, :timestamp_mismatch, {:forbidden, message} and {:link_exists, ...}. A failed write rolls back to its own savepoint, so the transaction can go on.

Transactions

The request, the job or the test owns the transaction. Code inside it never commits. Outside one, such as in a txn: false worker or an API route, open one with Cardinal.DB.transaction/2:

Cardinal.DB.transaction(ctx, fn ctx ->
  with {:ok, rec, effects} <- Cardinal.DB.insert(ctx, "Gate Item", %{"item_name" => "Bolt"}),
       do: {:after_commit, rec, effects}
end)

{:after_commit, value, effects} commits, then runs the effects. {:error, reason} rolls back. Any other value commits. The answer is {:ok, value} or {:error, reason}.

Savepoints

Cardinal.DB.savepoint(ctx, fun, opts) runs fun so that an error or a raise rolls back only its own writes. Use it for one item of a batch:

for name <- names do
  Cardinal.DB.savepoint(ctx, fn -> post(ctx, name) end, lock_timeout: 2_000)
end

lock_timeout: and statement_timeout: (milliseconds) apply inside the savepoint only.

CRM's lost-deal RPC reads a status, locks the deal, then saves it:

crm/lib/rpc/pipeline.ex
with {:ok, [%{"name" => lost} | _]} <-
       DB.get_list(ctx, status_rt,
         fields: ["name"],
         filters: [["type", "=", "Lost"]],
         order_by: "position asc"
       ),
     {:ok, rec} <- DB.get_doc(ctx, rectype, name, for_update: true),
     {:ok, saved, fx} <- DB.save(ctx, rectype, Map.put(rec, "status", lost)) do
  {:ok, saved["name"], fx}
end

Acting as the system

Cardinal.DB.as_system(ctx) skips permission checks, for hooks that write on the platform's behalf. Apps may call it only in controller hooks, and each call site must be listed. See Permissions. Cardinal.DB.system?(ctx) tells whether a ctx is one.

Cardinal.DB.at(ctx, instant) makes a system ctx act at a past time: dates, creation, modified and naming's date parts read instant. Seed uses it to write history. It raises on any other ctx.

On this page