Transactions
A transaction keeps a group of changes together. When the block ends, they're all saved. If anything inside fails, none of them are, and the error carries on:
<import package="KScript.Data" />
<model name="Account">
<field name="owner" type="string" />
<field name="balance" type="number" default="0" />
</model>
<do>$db->create_table(Account)</do>
<do>Account->create(owner: 'Ada', balance: 100)</do>
<do>Account->create(owner: 'Ben')</do>
<fn name="transfer" params="from: int, to: int, amount: number">
<transaction>
<do>Account->where(id: $from)->decrement(balance, by: $amount)</do>
<do>Account->where(id: $to)->increment(balance, by: $amount)</do>
<if Account->find($from).balance < 0>
<throw value="Conflict(message: 'Not enough money')" />
</if>
</transaction>
</fn>
<for each="amount" in="[30, 500]">
<try>
<do>@transfer(1, 2, $amount)</do>
<catch type="Conflict" as="err">
<echo value="$err.message" />
</catch>
</try>
</for>
<echo value="Account->pluck(balance)" />import KScript.Data
model Account {
owner: string
balance: number = 0
}
$db->create_table(Account)
Account->create(owner: 'Ada', balance: 100)
Account->create(owner: 'Ben')
fn transfer(from: int, to: int, amount: number) {
transaction {
Account->where(id: $from)->decrement(balance, by: $amount)
Account->where(id: $to)->increment(balance, by: $amount)
if Account->find($from).balance < 0 {
throw Conflict(message: 'Not enough money')
}
}
}
for amount in [30, 500] {
try {
@transfer(1, 2, $amount)
} catch Conflict as err {
echo $err.message
}
}
echo Account->pluck(balance)If you'd rather wrap a function, $db->transaction(fn() => ...) does the same and returns what the function returns. A transaction inside another becomes a savepoint, so only its own changes are undone. Pass retries: 3 to try again when the database is busy.
Inside a transaction, ->lock_for_update() locks the rows a query reads, and ->skip_locked() skips rows another transaction has locked. Both lock rows on Postgres, MySQL and MariaDB. SQLite locks the whole database for a transaction's writes instead, so they change nothing there.