Remote / Declared writes
Concurrent increments and decrements
Use increment or decrement to adjust numeric columns atomically in SQL (stock = stock + ?) without lost updates:
ts
const Restock = Mutation.write(
'Restock',
Write.update(
Entity.input(
Product,
Schema.Struct({ id: Schema.String, revision: Schema.Number, quantity: Schema.Int }),
{ quantity: Entity.unmapped },
),
{ id: 'id', expect: 'revision', increment: { stock: 'quantity' } },
),
)Increments require a non-nullable numeric field distinct from id, revision, and set fields, and RemoteServer.write enforces one of two retry protections:
- Optimistic revision (
expect: 'revision'): Concurrent increments conflict and retries of applied writes returnConflict. - Write ledger (no
expect, likeSellabove): Concurrent increments both succeed and retries return the ledgered result by operation ID.
Use decrement with a when precondition reading { row, input } to ensure stock never drops below zero:
ts
const SellInStock = Mutation.update('SellInStock', Product, {
input: { quantity: Schema.Int },
decrement: { stock: 'quantity' },
when: ({ row, input }) => Expr.lte(input.quantity, row.stock),
})Mutation.update expands to the same Mutation.write / Write.update structure with decrement compiled as negated addition (-quantity).