Writes and Concurrency
Both hosts write one entity at a time, by its key, where the entity set allows it. A write carries the row's version token when the caller has it, which makes it a conditional write; without one, the last write wins. This page covers what a write sends, what it refuses, version tokens and CSRF.
const orders = getDefaultClientFactory()("/odata/sales/OrderSet"); // or "/api/sales/OrderSet"
const { insertedId } = await orders.insert({ CustomerId: "C0001", Country: "DE" });
const row = await orders.one(insertedId); // carries __etag
await orders.update({ ...row, Country: "FR" }); // If-Match: the ETag of that readWhat each write sends
| Call (browser client / Moost DB endpoint) | OData | Result |
|---|---|---|
insert(row) / POST with an object | POST to the entity set | { insertedId }: the key value, or the key object |
insert(rows) / POST with an array | one $batch, a changeset per row (below) | { insertedCount, insertedIds } |
update(patch) / PATCH | MERGE (v2) or PATCH (v4) of the changes | { matchedCount, modifiedCount } |
replace(row) / PUT | PUT of the whole entity | { matchedCount, modifiedCount } |
remove(id) / DELETE | DELETE by key | { deletedCount }; a missing entity is a 404 |
- By key only. A patch carries the key properties and the changed members, as an Atscript UI form's
getPatch()plus the row's key gives it: the key goes into the URL, the rest into the body. There is no write by filter. - The inserted key is the one the service reports (from the returned entity, else the
Location/OData-EntityIdheader), else the one the row carried. insert(row, { returning: true })in the browser client answers the entity the service returned. On a Moost server the controller decides with Moost DB'sreturnRepresentation().- A missing entity matches nothing on an update or replace (
{ matchedCount: 0 }, or404with a version token); a delete of one is a404. - An array write is not a transaction: when a row fails, the rows before it stay written, and for an insert the rows after it too (see Several rows at once). On the server an array update or replace names no row yet.
- OData v2
MERGEgoes out as the real verb. Behind a proxy that refuses it, create the service withmerge: "tunnel"(POSTwithX-HTTP-Method: MERGE).
Several rows at once
An array insert goes out as one OData $batch, each row in a changeset of its own, on both hosts:
await orders.insert([first, second, third]); // POST $batch: three changesets of one POST each- Not atomic: a row the service refuses rolls nothing else back, and the rows after it still run (on OData v4 the batch asks the service to continue past a failure). A changeset of one row works on every backend, also the classic SAP Gateway® services that refuse a changeset of several operations.
- One CSRF token, one round trip, as many rows as
batch.maxPartsallows per$batch(100 by default; more rows go out as several). - One row is one plain
POST, its failure its own.
What it answers keeps Atscript DB's insertMany contract:
| Outcome | Answer |
|---|---|
| Every row created | { insertedCount, insertedIds }, in request order |
| Some rows refused | The first refused row's error (its status and code), message "2 of 3 rows were created; the row at [1] failed": each refused row's entries at that row ([1].label), and for each row created { path: "[j]", code: "INSERTED", params: { insertedId } } |
| Every row refused | The first row's error and message, every row's entries at that row, no INSERTED entry |
The $batch failed as a whole | As a single POST's failure: nothing is known to have run |
{
"statusCode": 400,
"code": "INVALID_QUERY",
"message": "2 of 3 rows were created; the row at [1] failed",
"errors": [
{
"path": "[0]",
"message": "The row at [0] was created",
"code": "INSERTED",
"params": { "insertedId": "4500000001" }
},
{ "path": "[1].Country", "message": "Country DX does not exist", "code": "ZSD/012" },
{
"path": "[2]",
"message": "The row at [2] was created",
"code": "INSERTED",
"params": { "insertedId": "4500000003" }
}
]
}Without $batch (the space's or the registration's batch: false, { batch: false } on the call in the browser, a service whose $metadata says it has none or that answers a $batch 404, 405 or 501) the rows go one POST after the other, on past a refused one, with the same answers. An array insert never joins a batch of createBatch(): it sends one of its own.
What the service maintains is not sent
- Computed properties (
Core.Computed, v2StoreGeneratedPattern,sap:creatableandsap:updatablefalse) are never sent. A computed scalar carries@db.default.storenext to its@meta.readonlyin the generated type: a create form shows it read-only, and neither the form, the client's preflight nor the server's validation demands it. A key the service assigns comes back ininsertedId. - A GUID the service fills in when left out (
Core.ComputedDefaultValue, SAP CAP'scuidkeys) carries@db.default.uuid: a create without it gets one from the table layer (server) or leaves it to the service (browser), and a given one is sent. - Immutable properties are dropped from an update or replace, update-only ones from a create. They carry no annotation, so a form offers them in both modes; a change the service would refuse is dropped.
A row that was read can therefore be written back as it is. An update made only of such properties sends nothing and reports modifiedCount: 0.
On OData v4, an entity of a type that takes part in inheritance (it has a base type, or another entity type derives from it) is sent with its type as @odata.type ("#Namespace.Type", the entity set's type), in a create, an update, a replace and for each related row of a deep insert: some services refuse such a payload without it ("Type information must be specified for types that take part in inheritance"). A service takes the base type for a row of a derived type too. v2 payloads carry no type.
Refused before any request
| What | Browser client | Server |
|---|---|---|
| A write the set does not allow (not insertable, updatable, deletable) | 400 NOT_SUPPORTED | 400 NOT_SUPPORTED |
| Any write to a draft-enabled set | 400 NOT_SUPPORTED | 400 NOT_SUPPORTED |
| Any write to a set reached only through a navigation | 400 NOT_SUPPORTED | 400 NOT_SUPPORTED |
| A payload the type rejects | ClientValidationError, by field | 400 with the field paths |
A value in a @db.rel.store navigation | NAV_STORE_WRITE | NAV_STORE_WRITE |
$inc, $dec, $mul | 400 NOT_SUPPORTED, entry UNSUPPORTED_FIELD_OPERATOR | 400 NOT_SUPPORTED, the same entry |
$insert, $update, $upsert, $remove on a collection | 400 NOT_SUPPORTED, entry UNSUPPORTED_ARRAY_OPERATOR | emulated: read, then write the whole collection |
| Related entities in an update or replace | INVALID_QUERY, entry UNSUPPORTED_DEEP_UPDATE | split into one write per table |
A $cas that is not the set's version token (an integer version, a set without a token) | 400 NOT_SUPPORTED, entry CAS_NOT_SUPPORTED | an integer version: the same; a set without a token: 400 INVALID_QUERY at $cas (Atscript DB: the table has no @db.column.version) |
The browser client answers a write the set does not allow with the body a Moost server answers: 400 NOT_SUPPORTED, one entry at "" with the reason ("OrderSet does not allow deleting entities"). It also refuses onConflict: "ignore" (400 INVALID_QUERY, entry UNSUPPORTED_CONTROL on $onConflict). The rule of which writes a set allows is one function, writeRefusal of @atscript/odata, used by both hosts on the live $metadata: crud in the metadata of both lists the same writes, and Atscript UI shows no button that cannot work. A write the live service stopped allowing is refused the same way (see Moost Server).
Collections are written as a whole (a plain array, or $replace): OData has no operator for part of one. A complex value in an update on the server replaces the stored value, the members it leaves out sent as null, unless the patch uses @db.patch.strategy "merge".
Version tokens
An entity set that declares optimistic concurrency (Core.OptimisticConcurrency, or v2 ConcurrencyMode="Fixed") gets a version token in its generated type:
@db.column.version
@db.column.version.token
__etag: stringEvery row either host reads carries the entity's ETag there, /meta names the field versionColumn, and it is never sent to the service as data, nor filtered or sorted by.
- With the token, conflicts are detected. An update or replace that carries it (the row as read, or
$cas: { __etag }) is sent with it asIf-Match, without reading first. If someone changed the entity since, the service answers412, and both hosts answer as Moost DB answers a stale version: the entity is read, and the answer is409VERSION_MISMATCHwith its current token incurrentVersion(db-client'sVersionMismatchError), or404NOT_FOUNDwhen it is gone. In an array write, such a row counts{ matchedCount: 0 }instead. - Without it, the last write wins. An update or replace without the token, and every delete, overwrites whatever changed since the caller read the row. The service still requires
If-Match, so the host reads the entity's current ETag right before the write and sends that,*for an entity that comes without one (a412to that*matches nothing when one more read finds the entity gone; found, the service does not take*, and the write fails:502STORE_FAILEDon the server, aTransportErrorin the browser). When the entity changes in the moment between that read and the write (412), the host reads it again and sends the write again, three attempts in all; then the answer is503SERIALIZATION_FAILURE, which a caller may retry. A write to a set that declares no version token reads nothing and is sent once: a412(or428) to it, which carried noIf-Match, is a precondition the service demands without declaring it, never a change: the server answers502STORE_FAILED(entry codePRECONDITION_REQUIRED, a message that says so), the browser client the service's own412or428.
Sets without the declaration have no token and are written without If-Match. A token in the row of an insert is not sent. Related rows read through $with carry no token.
An Atscript UI edit form sends the token of the row it loaded, so its save detects conflicts. Build it with the versionColumn of /meta and handle the mismatch:
import { VersionMismatchError } from "@atscript/db-client";
import { createFormDef, deserializeServedType, getDefaultClientFactory } from "@atscript/ui";
const orders = getDefaultClientFactory()(url);
const meta = await orders.meta();
const def = createFormDef(deserializeServedType(meta.type), {
mode: "edit",
versionColumn: meta.versionColumn,
});
const record = await orders.one(id);
async function save(data: unknown) {
try {
await orders.update(data as Record<string, unknown>);
} catch (error) {
if (error instanceof VersionMismatchError) {
// Changed since it was opened: reload, or show the user what changed.
} else throw error;
}
}The full pattern, with the reload, is in Atscript UI's edit forms with optimistic concurrency.
See it live
Open coffee 17 in the browser app in two tabs and save both: the second save is refused, and the form reads the row again with your edits kept. Code: RecordForm.vue.
CSRF tokens
Every write to a service with CSRF protection (SAP Gateway® and RAP services have it) needs a token. The transport handles it: it fetches one with a HEAD request on the service root before the first unsafe request, reuses it for three minutes, and fetches a new one and retries once when the service answers 403 with x-csrf-token: required. A service without CSRF protection costs no extra round trip per write: one that answers the HEAD without a token is not asked again for three minutes, one that answers it 404, 405 or 501 (it has no token endpoint, as most non-SAP services) not for ten minutes, unless a write is refused for want of a token, which fetches one at once.
The token is bound to the service's session cookie, so it lives in a session:
- Browser client: every call has a session, one per service by default, and the cookies are the browser's. Nothing to do.
- Moost server (Node): the transport keeps cookies only in a session the host supplies. The space keeps one per credential its calls send, so a space with credentials in
inithas a session for its writes (see Credentials and Sessions). A write without credentials, or on a space created withsessions: false, has none and is refused:502STORE_FAILED, the transport'shint: "session-required"and its remedy in the logged cause.
Turn the handling off with csrf: false in the registration or the space for a service without CSRF protection, or tune how long a token is reused with csrf: { ttl }.
Not possible
- Writes by filter (
updateMany,replaceMany,deleteMany). - Field operators (
$inc,$mul) and integer versions. - Transactions: multi-row and nested writes cannot roll back.
- OData deep insert on the server (nested rows are written one by one, and only as deep as the type's
@db.depth.limit, which a generated type leaves at0: raise it in anannotatefile, see Relations in writes). - Draft editing: draft-enabled sets are read-only. Planned; see Limitations.
DOs and DON'Ts
- Carry the row's
__etaginto updates (an edit form does it for you) — without it the last write wins. - Read a row by its key before editing it — rows from a
$withexpansion carry no token. - Give the server's space its credentials in
initand leavesessionson — a write without a session fails. - Read the
INSERTEDentries of a failed array insert — the rows they name were created, before and after the refused one; don't treat an array write as atomic. - Leave computed, immutable and update-only fields in the row — the hosts drop them; don't strip them by hand.
See also
- Errors: how a refusal of the service reaches the form.
writeRefusal,allowedWrites: the write rule for your own code.- Atscript DB optimistic concurrency:
$casand version columns.