Skip to content

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.

ts
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 read

What each write sends ​

Call (browser client / Moost DB endpoint)ODataResult
insert(row) / POST with an objectPOST to the entity set{ insertedId }: the key value, or the key object
insert(rows) / POST with an arrayone $batch, a changeset per row (below){ insertedCount, insertedIds }
update(patch) / PATCHMERGE (v2) or PATCH (v4) of the changes{ matchedCount, modifiedCount }
replace(row) / PUTPUT of the whole entity{ matchedCount, modifiedCount }
remove(id) / DELETEDELETE 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-EntityId header), 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's returnRepresentation().
  • A missing entity matches nothing on an update or replace ({ matchedCount: 0 }, or 404 with a version token); a delete of one is a 404.
  • 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 MERGE goes out as the real verb. Behind a proxy that refuses it, create the service with merge: "tunnel" (POST with X-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:

ts
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.maxParts allows 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:

OutcomeAnswer
Every row created{ insertedCount, insertedIds }, in request order
Some rows refusedThe 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 refusedThe first row's error and message, every row's entries at that row, no INSERTED entry
The $batch failed as a wholeAs a single POST's failure: nothing is known to have run
json
{
  "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, v2 StoreGeneratedPattern, sap:creatable and sap:updatable false) are never sent. A computed scalar carries @db.default.store next to its @meta.readonly in 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 in insertedId.
  • A GUID the service fills in when left out (Core.ComputedDefaultValue, SAP CAP's cuid keys) 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 ​

WhatBrowser clientServer
A write the set does not allow (not insertable, updatable, deletable)400 NOT_SUPPORTED400 NOT_SUPPORTED
Any write to a draft-enabled set400 NOT_SUPPORTED400 NOT_SUPPORTED
Any write to a set reached only through a navigation400 NOT_SUPPORTED400 NOT_SUPPORTED
A payload the type rejectsClientValidationError, by field400 with the field paths
A value in a @db.rel.store navigationNAV_STORE_WRITENAV_STORE_WRITE
$inc, $dec, $mul400 NOT_SUPPORTED, entry UNSUPPORTED_FIELD_OPERATOR400 NOT_SUPPORTED, the same entry
$insert, $update, $upsert, $remove on a collection400 NOT_SUPPORTED, entry UNSUPPORTED_ARRAY_OPERATORemulated: read, then write the whole collection
Related entities in an update or replaceINVALID_QUERY, entry UNSUPPORTED_DEEP_UPDATEsplit 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_SUPPORTEDan 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:

atscript
@db.column.version
@db.column.version.token
__etag: string

Every 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 as If-Match, without reading first. If someone changed the entity since, the service answers 412, and both hosts answer as Moost DB answers a stale version: the entity is read, and the answer is 409 VERSION_MISMATCH with its current token in currentVersion (db-client's VersionMismatchError), or 404 NOT_FOUND when 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 (a 412 to that * matches nothing when one more read finds the entity gone; found, the service does not take *, and the write fails: 502 STORE_FAILED on the server, a TransportError in 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 is 503 SERIALIZATION_FAILURE, which a caller may retry. A write to a set that declares no version token reads nothing and is sent once: a 412 (or 428) to it, which carried no If-Match, is a precondition the service demands without declaring it, never a change: the server answers 502 STORE_FAILED (entry code PRECONDITION_REQUIRED, a message that says so), the browser client the service's own 412 or 428.

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:

ts
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 init has a session for its writes (see Credentials and Sessions). A write without credentials, or on a space created with sessions: false, has none and is refused: 502 STORE_FAILED, the transport's hint: "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 at 0: raise it in an annotate file, see Relations in writes).
  • Draft editing: draft-enabled sets are read-only. Planned; see Limitations.

DOs and DON'Ts ​

  • Carry the row's __etag into 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 $with expansion carry no token.
  • Give the server's space its credentials in init and leave sessions on — a write without a session fails.
  • Read the INSERTED entries 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 ​

SAP, SAP S/4HANA, SAP Fiori, SAPUI5, SAP BTP and other SAP products and services mentioned herein, as well as their respective logos, are trademarks or registered trademarks of SAP SE (or an SAP affiliate company) in Germany and other countries. Atscript OData is an independent open-source project and is not affiliated with, sponsored or endorsed by SAP SE.
Released under the MIT License.