Functions and transactions
Give clients named operations. The function signature describes the input and result, and the body defines the transaction.
Choose a function kind
| Declaration | Behavior |
|---|---|
fn | Can read or compute. A private pure helper can be called by another function. |
write fn | May insert, update, or delete. A failed invocation rolls back its tentative writes. |
gen fn | Uses yield to emit values one at a time through an Iterator<T>. |
Add export to expose a callable operation. An exported function must access the database, directly or through a helper, or meet a supported authorization effect such as token issuance. Qualify cross-namespace names with ::.
Group writes in one call
export write fn add(id: UInt8, book: UInt8, body: Text) -> () {
Note.insert({
id: id,
book: book,
body: body,
});
}Each ordinary invocation runs as a transaction. Calls to other DBL functions from its body share that transaction and see its earlier writes. Results are released after commit. On contention the database can rerun the whole attempt.
Patch and remove
export write fn rename(id: UInt8, body: Text) -> () {
Note.update(id, {
body: body,
});
}
export write fn remove(id: UInt8) -> () {
Note.delete(id);
}A patch preserves omitted fields. A single-row update or delete requires a matching row. Use upsert for separate create and update paths, or insertMany, updateMany, and deleteMany for list inputs. Bulk updates and deletes skip missing keys. returning: true asks for affected records.
Locals, loops, and streams
let binds a value. Add mut to allow local mutation. A for loop consumes iterable values. Use return for the final result or yield for an item in a generator.
export gen fn titles(book: UInt8) -> Iterator<Text> {
for entry in Note.by_book.scan(prefix: (book)) {
yield entry.0;
}
}A generator body is evaluated on demand. Consuming the same iterator twice continues from its current position. Stop early if only the first few entries are needed. For a bounded result in an ordinary read function, see range scans.