@atscript/db-odata 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Artem Maltsev <artem@maltsev.nl>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,409 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <img src="https://odata.atscript.dev/logo.svg" alt="Atscript" width="120" />
3
+ </p>
2
4
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
5
+ <h1 align="center">@atscript/db-odata</h1>
6
+
7
+ <p align="center">
8
+ Atscript DB adapter that uses an OData v2/v4 service as the database.
9
+ </p>
10
+
11
+ <p align="center">
12
+ Part of Atscript OData. Works with SAP S/4HANA®, SAP Gateway and SAP RAP services, and with any standard OData v2/v4 service.
13
+ </p>
14
+
15
+ <p align="center">
16
+ <a href="https://odata.atscript.dev">Documentation</a>
17
+ </p>
18
+
19
+ ---
20
+
21
+ > Preview release (0.0.x) — APIs may still change between releases. Writes are single-entity; an update or replace detects
22
+ > a conflict when the caller carries the row's version token, and is last-write-wins when it does
23
+ > not (see [Writes](#writes)). The service's operations run through the space and its tables
24
+ > (`callOperation`), which the generated bases of `@atscript/moost-odata` call (see
25
+ > [Operations](https://odata.atscript.dev/guide/operations)).
26
+
27
+ ## Installation
28
+
29
+ ```bash
30
+ pnpm add @atscript/db-odata @atscript/odata @atscript/db @atscript/typescript @uniqu/core
31
+ ```
32
+
33
+ Needs `@atscript/db` 0.1.200 or newer and `@atscript/typescript` 0.2.25 or newer.
34
+
35
+ The models come from the generator of `@atscript/odata`: see the
36
+ [installation guide](https://odata.atscript.dev/guide/installation). Every export is documented in the
37
+ [API reference](https://odata.atscript.dev/api/db-odata).
38
+
39
+ ## Usage
40
+
41
+ `createODataSpace` returns a `DbSpace` (an `ODataSpace`) whose tables are the entity sets of one
42
+ OData service. Typed at build time, live at runtime: the table types are the ones `@atscript/odata`
43
+ generates from the saved `$metadata`, and `space.connect()` reads the live `$metadata` (its
44
+ value-help documents included) and makes the generated module's classes the live declarations.
45
+
46
+ ```ts
47
+ import { createODataSpace } from "@atscript/db-odata";
48
+ import { basicAuth } from "@atscript/moost-odata"; // or any function answering { headers }
49
+ import * as sales from "./odata/sales.as";
50
+ import { model } from "./odata/sales.model.gen";
51
+
52
+ const space = createODataSpace({
53
+ baseUrl: "https://my-gateway.example.com/sap/opu/odata/sap/ZDEMO_ORDERS_SRV",
54
+ query: { "sap-client": "100" },
55
+ model,
56
+ types: sales,
57
+ init: basicAuth({ user: process.env.ODATA_USER!, password: process.env.ODATA_PASSWORD! }),
58
+ });
59
+
60
+ await space.connect(); // the live $metadata, read with the space's init
61
+
62
+ const orders = space.getTable(sales.Order);
63
+
64
+ await orders.findMany({
65
+ filter: { CustomerId: "C0001", OrderDate: { $gte: "2024-01-01" } },
66
+ controls: { $sort: { OrderDate: -1 }, $limit: 20, $with: [{ name: "Items" }] },
67
+ });
68
+ await orders.findById("4500000001");
69
+ await orders.findManyWithCount({ filter: {}, controls: { $skip: 20, $limit: 20 } });
70
+ ```
71
+
72
+ A table reads and writes the entity set its type names in `@db.table`. The tables work with
73
+ everything that takes an atscript-db table, the REST controllers of `@atscript/moost-db` included.
74
+ The generated types name their service as `@db.space`: register the space under that name with
75
+ moost-db's `provideDbSpace`, and declare a controller per entity set by model token; the base
76
+ classes of `@atscript/moost-odata` add the error mapping and offer only the writes the set allows:
77
+
78
+ ```ts
79
+ import { TableController, provideDbSpace } from "@atscript/moost-db";
80
+ import { ODataTableController } from "@atscript/moost-odata";
81
+
82
+ provideDbSpace(space, "sales"); // the types' @db.space
83
+
84
+ @TableController(sales.Order, "api/sales/OrderSet")
85
+ export class OrderSetController extends ODataTableController<typeof sales.Order> {}
86
+
87
+ await space.connect(); // before app.init()
88
+ ```
89
+
90
+ A table of the space (`space.getTable(sales.Order)`) binds as well, and can be created at import.
91
+ Never run schema sync over the space: the service owns its schema. Call `space.connect()` once before
92
+ Moost's `app.init()`, which creates the controllers and reads the tables' structure. `connect()`
93
+ reads with the space's own `init` unless it is given another, and resolves with the same
94
+ connection ever after (`space.connection`, `space.service`). A failed read rejects, and the app
95
+ does not start.
96
+
97
+ - **Drift.** When the live documents differ from the saved ones, the space warns once through its
98
+ `logger` (else `console.warn`): entity sets gone or added, sets allowing fewer writes,
99
+ properties added, removed or changed. `onDrift(drift, message)` replaces the warning.
100
+ - **A set the live service no longer has** keeps its table: every call of it throws a plain
101
+ `Error` before any request, a fault of the server's build (moost-db answers `500`); the
102
+ controller bases of `@atscript/moost-odata` answer it `404` first.
103
+ - **Other options** of the live form: the transport options of `@atscript/odata`, `copies`
104
+ (`annotate X as Y` copies that annotate properties), `name`, `sessions`, `logger`, `onClose`.
105
+ `search: false` is for an OData v4 service that refuses `$search` and declares nothing: its
106
+ sets are then searchable only where the metadata declares it, a `SearchRestrictions` record
107
+ (`/meta` and
108
+ `isSearchable()` say so, and a search is refused before any request).
109
+
110
+ The fixed form `createODataSpace({ service, init })`, over an engine of `createODataService`, reads
111
+ no `$metadata`: for tests and tools. See [Moost Server](https://odata.atscript.dev/guide/server) and
112
+ [Live metadata](https://odata.atscript.dev/guide/live-metadata).
113
+
114
+ The entity sets of the service's value-help services (OData v4 `Common.ValueListReferences`, as
115
+ SAP RAP serves value helps; their types carry `@odata.valueHelpService`) are tables of the same
116
+ space: `space.getTable(sales.CountryVH)` reads the set at the value-help service's own root,
117
+ through `service.valueHelpService(…)`, with the space's `init`. The space reads their documents
118
+ with the live `$metadata`.
119
+
120
+ ### Credentials and sessions
121
+
122
+ The connection to the service is an integration: the server calls it with credentials it was
123
+ given (a technical user), never with those of its own end users. `init` answers them; it is called
124
+ once per table operation, so the reads a write makes (its ETag read, the CSRF token fetch) and the
125
+ write itself carry the same answer. The strategies of `@atscript/moost-odata` (`basicAuth`,
126
+ `bearerAuth`, `staticHeaders`, `callTimeout`, `combineAuth`) build it; any function answering
127
+ `{ headers }` does too.
128
+
129
+ The space keeps the sessions itself, one per credential the calls send (the SHA-256 of a call's
130
+ headers, `Accept-Language` left out): the service's cookies and the CSRF token a write needs. With
131
+ one technical user that is one session; a rotating token starts a new one, and two credentials
132
+ never share a session or a token. Calls without credentials stay stateless.
133
+
134
+ | `sessions` | Meaning |
135
+ | -------------- | ------------------------------------------------------------------------------------------ |
136
+ | not set | `{ ttl: DEFAULT_SESSION_TTL, max: DEFAULT_MAX_SESSIONS }`: 30 minutes after last use, 1000 |
137
+ | `{ ttl, max }` | milliseconds a session is kept after its last use; the most kept (the longest unused goes) |
138
+ | `false` | no session: every call stateless, so writes to an SAP service fail |
139
+
140
+ Keep `ttl` at or below the idle timeout of the service's own sessions. A write the service refuses
141
+ for want of a session (no credentials, or `sessions: false`) fails with a `DbError`
142
+ `STORE_FAILED` whose `cause` has the `hint` `"session-required"` (see [Errors](#errors)).
143
+
144
+ When the models name the language they were saved in (the plugin's `language`), every data call
145
+ also sends `Accept-Language: <language>` unless `init` sets one, so labels and data texts come in
146
+ one language.
147
+
148
+ ### What is supported
149
+
150
+ | Table API | OData |
151
+ | ----------------------------------------- | ------------------------------------------------------------------- |
152
+ | `findById`, `findOne` by the whole key | key read, `EntitySet(key)`; a missing entity is `null` |
153
+ | `findMany`, `findOne` | `$filter`, `$select`, `$orderby`, `$skip`, `$top` |
154
+ | `count` | `/$count` |
155
+ | `findManyWithCount` | one request with `$inlinecount=allpages` (v2) or `$count=true` (v4) |
156
+ | `search`, `searchWithCount` | `search` (v2) or `$search` (v4), where the entity set allows it |
157
+ | `$with` | `$expand` in the same request; see [Relations](#relations) |
158
+ | complex types | nested objects; paths are written `Address.City` |
159
+ | `insertOne`, `insertMany` | `POST`, one per row; see [Writes](#writes) |
160
+ | `updateOne`, `bulkUpdate` | `MERGE` (v2) / `PATCH` (v4) of one entity by key |
161
+ | `replaceOne`, `bulkReplace` | `PUT` of one entity by key |
162
+ | `deleteOne` | `DELETE` of one entity by key |
163
+ | `aggregate` | one `$apply` request (OData v4); see [Aggregation](#aggregation) |
164
+ | `updateMany`, `replaceMany`, `deleteMany` | refused: `ODataNotSupportedError` |
165
+
166
+ - Whether a field can be filtered or sorted by comes from the service metadata and is reported
167
+ through `canFilterField` / `canSortField`, so `/meta` shows it and a request that ignores it is
168
+ refused before the service is called. `filterOps` lists the operators the service allows on a
169
+ field (none where it cannot filter, the operators of a filter restriction where it declares one:
170
+ single-value `$eq`, multi-value `$eq $in`, interval `$eq $gt $gte $lt $lte`); any other operator,
171
+ a lone `$exists` included, is refused the same way. A primary-key or foreign-key field always
172
+ takes `$eq` and `$in`, which the table layer reads it by, even where the service declares it
173
+ non-filterable or single-value.
174
+ - The primary key the table layer appends to every `$sort` is left out of `$orderby` where the
175
+ service cannot sort by it.
176
+ A `$sort` by such a key that the caller asks for is refused like any other field the service
177
+ cannot sort by; that includes the primary-key order `@atscript/moost-db` gives `/pages` when
178
+ the request has no `$sort`.
179
+ - A read without `$limit` follows the paging links of the service to the end. When the service
180
+ cuts it into more pages than the engine follows (`maxPages` of the service), the read fails
181
+ instead of returning a part of the rows.
182
+ - A draft-enabled entity set (`Common.DraftRoot` / `Common.DraftNode`) is read and counted for its
183
+ active entities: a filter with no condition on `IsActiveEntity` of its own gets
184
+ `IsActiveEntity eq true`, so the user's drafts do not show up next to them. A read by key reads
185
+ the key it is given.
186
+
187
+ ### Relations
188
+
189
+ The adapter reads relations inside the read (`supportsWithInRead()`): the relations of `$with`
190
+ ride the request of the rows as `$expand`, and every row comes back with its related rows under
191
+ the navigation name. There is no second read by the keys of the rows, so a relation to an entity
192
+ set that can only be reached through a navigation loads, and the URL does not grow with the
193
+ number of rows. (A filter an entity set declares mandatory is advisory: reads are sent without
194
+ it, and a service that needs it answers `400`, `INVALID_QUERY` with its message.)
195
+
196
+ ```ts
197
+ await orders.findMany({
198
+ filter: { CustomerId: "C0001" },
199
+ controls: {
200
+ $select: ["OrderId", "OrderDate"],
201
+ $with: [{ name: "Items", filter: { Product: "HT-1000" }, controls: { $select: ["ItemNo"] } }],
202
+ },
203
+ });
204
+ // v4: Orders?$filter=CustomerId eq 'C0001'&$select=OrderId,OrderDate
205
+ // &$expand=Items($filter=Product eq 'HT-1000';$select=ItemNo,OrderId)
206
+ ```
207
+
208
+ - **Every part of an entry reaches the service**: the relation's filter (the client's and any a
209
+ controller conjoins into the entry, such as a row scope in `validateControls`), its `$select`,
210
+ its `$sort` and its nested `$with`. The related rows are cut back to their selection and their
211
+ key, at every depth, as atscript-db's relation loader keeps the key on other adapters (the
212
+ service always sends it). Nothing in an entry is dropped: what the service cannot express is
213
+ refused.
214
+ - **A filter that can never match** (an empty `$in`, say a controller's scope for a user with no
215
+ values) leaves the relation out of the request: every row has it empty, `[]` or `null`, as
216
+ atscript-db answers it on other adapters. Nothing like `$filter=false` is sent.
217
+ - **OData v2** has no options inside an expansion except the selection (written `Nav/Property` in
218
+ the root `$select`). A filter or a sort of a relation, a scope added by a controller included, is
219
+ refused with a `DbError` `NOT_SUPPORTED` before any request; moost-db answers `400`.
220
+ - **No paging inside `$with`.** The table layer refuses `$skip` and `$limit` in a `$with` entry
221
+ (`NOT_SUPPORTED`).
222
+ - **One service.** A relation is read only to a table of the same service (`sharesStoreWith`).
223
+ - **Navigations without a foreign key** (`@db.rel.store`, which the generator emits where the
224
+ service declares no usable referential constraint) are read the same way. The table layer
225
+ refuses a value in one on every write; only relations with foreign keys (`@db.rel.to` /
226
+ `.from`) give a foreign key to a value help.
227
+ - Related rows carry no version token: the adapter reads no ETag of an expanded entity (read the
228
+ row itself for its token).
229
+
230
+ ### Aggregation
231
+
232
+ `table.aggregate()` (moost-db's `/query` with `$groupBy`) is one OData v4 `$apply` request, on an
233
+ entity set the service declares `$apply` for (`Aggregation.ApplySupported` on the set, its type or
234
+ the container, as RAP writes it):
235
+
236
+ ```ts
237
+ await lineItems.aggregate({
238
+ filter: { CompanyCode: "1000" },
239
+ controls: {
240
+ $groupBy: ["CompanyCode", "Currency"],
241
+ $select: ["CompanyCode", "Currency", { $fn: "sum", $field: "Amount", $as: "total" }],
242
+ $sort: { total: -1 },
243
+ $limit: 10,
244
+ },
245
+ });
246
+ // LineItems?$apply=filter(CompanyCode eq '1000')/groupby((CompanyCode,Currency),
247
+ // aggregate(Amount with sum as total))&$orderby=total desc&$top=10
248
+ // → [{ CompanyCode: "1000", Currency: "EUR", total: "1500.25" }, …]
249
+ ```
250
+
251
+ - **Functions** (`aggregateFns()`, `/meta.aggregateFns`): `sum`, `avg`, `min`, `max` on an SAP
252
+ service (RAP answers `$count` and `countdistinct` with `501`); on any other also `count(*)`
253
+ (`$count as …`) and `countDistinct`. `count` of a field has no `$apply` form.
254
+ - **`$having`** is a `filter()` after the grouping, **`$sort`**, **`$skip`** / **`$limit`** apply
255
+ to the groups, and **`$count`** answers `[{ count }]`, the number of groups
256
+ (`$top=0&$count=true`). `$groupBy: []` is one row over every matching row. A grouping without
257
+ aggregates gives the distinct values of a field (atscript-ui's distinct-values picker).
258
+ - **Rows**: the grouped fields (a member of a complex property nested, as in reads) and every
259
+ aggregate under its alias, decimals as strings. An alias the service could take for a property
260
+ (RAP refuses those, "already used") is sent under another name and comes back under yours.
261
+ - **Refused before any request** (`ODataNotSupportedError` for `aggregate`, `400` over HTTP, the
262
+ entry's `path` at the field or control): an entity set without `$apply` (every set on OData v2);
263
+ `sum` / `avg` of what is no number; a path through a navigation; `$search`. The table layer
264
+ refuses an amount aggregated without its currency (or unit) in `$groupBy`.
265
+ - **Left to the service**: which properties it lets you group by or aggregate, and an amount
266
+ compared in `$having` without its currency (RAP answers `400`, which reaches the caller as
267
+ `INVALID_QUERY` with its message).
268
+ - **Not supported**: calendar buckets, expressions, `first` / `last`, conditional aggregates,
269
+ field lists and two-level aggregates (the table layer refuses them, as the adapter does not
270
+ declare them); OData v2 analytical sets (`sap:semantics="aggregate"`), which aggregate by the
271
+ dimensions and measures of a `$select` with no function to choose.
272
+
273
+ ### Writes
274
+
275
+ Every write addresses one entity by its key, as OData writes it:
276
+
277
+ | Adapter method | OData |
278
+ | ----------------------------------------- | ---------------------------------------------------------------------- |
279
+ | `insertOne`, `insertMany` | `POST` to the entity set, one request per row |
280
+ | `updateOne` | `MERGE` (v2) or `PATCH` (v4) to `Set(key)` with the changed properties |
281
+ | `replaceOne` | `PUT` to `Set(key)` with the whole entity |
282
+ | `deleteOne` | `DELETE` of `Set(key)` |
283
+ | `updateMany`, `replaceMany`, `deleteMany` | refused (`ODataNotSupportedError`): there is no write by query |
284
+
285
+ - **By key only.** The table layer addresses a row by its primary key, which arrives as a filter;
286
+ a filter that is not exactly an equality on every key property is refused (a row scope added to
287
+ a delete, for instance). Writes by a filter are refused.
288
+ - **The inserted key** is the one the service reports (from the returned entity, else from the
289
+ `Location` / `OData-EntityId` header), else the one the row carried. A key the service computes
290
+ (`Core.Computed`, v2 `StoreGeneratedPattern="Identity"`, `sap:creatable="false"` with
291
+ `sap:updatable="false"`) is never sent.
292
+ - **What the service maintains is not sent**: computed properties in any write, immutable ones in
293
+ an update or replace, update-only ones in a create. They are left out of the request, so a row
294
+ that was read can be written back as it is. An update made only of such properties sends
295
+ nothing and reports `modifiedCount: 0`.
296
+ - **What the service computes** (`Core.Computed`, `StoreGeneratedPattern`, v2 `sap:creatable` and
297
+ `sap:updatable` false) carries `@db.default.store` in the generated type when it is a scalar:
298
+ the service fills it, so the table layer's insert validation does not demand it and an insert
299
+ leaves it out (the adapter lists `store` in `nativeDefaultFns()`). A value given anyway is not
300
+ sent. A computed key comes back in `insertedId` from the service's answer: no placeholder
301
+ needed. A computed complex value or collection gets no default.
302
+ - **A GUID with a computed default** (`Core.ComputedDefaultValue`, SAP CAP's `cuid` keys)
303
+ carries `@db.default.uuid`: the table layer generates one when the row leaves it out, and it is
304
+ sent, as a key given by the caller is; the service takes it.
305
+ - **Complex values** in an update replace the stored value: the members a value leaves out are sent
306
+ as `null`, because OData merges a complex value into the stored one. A patch with
307
+ `@db.patch.strategy "merge"` is sent as a merge into the stored value.
308
+ - **Collections** are written as a whole (a plain array, or `$replace`): OData has no operator
309
+ for part of a collection. The array operators `$insert`, `$upsert`, `$update` and `$remove` are
310
+ emulated by the table layer, which reads the entity and writes the whole collection back. Nothing
311
+ keeps a concurrent change of the collection from being overwritten in between: last write wins,
312
+ as for every write.
313
+ - **Field operators** (`$inc`, `$mul`) and an integer version (`$cas` with a number) are refused:
314
+ OData has neither. A version token is compared (see [ETags](#etags-the-version-token)).
315
+ - **What the entity set allows.** A set that is not insertable, updatable or deletable (`sap:creatable`,
316
+ `Capabilities.InsertRestrictions`, …) refuses that write, and a set that is draft-enabled, can only
317
+ be reached through a navigation, or holds the parameters of a parameterized view
318
+ refuses every write, with `ODataNotSupportedError` before any request. The rule and its messages
319
+ are `writeRefusal` of `@atscript/odata`, which the browser client follows too; `allowedWrites` says
320
+ the same in advance. The refusal names the adapter method that was called (a single insert
321
+ reaches the adapter as `insertMany`).
322
+ - **A missing entity** matches nothing: `{ matchedCount: 0 }` for an update or replace,
323
+ `{ deletedCount: 0 }` for a delete.
324
+ - **No transactions.** `insertMany` of several rows sends one `$batch`, each row in a changeset of
325
+ its own (row after row with the space's `batch: false`): the rows after a refused one still run.
326
+ When rows are refused, the error is the first refused row's (its code), with the paths of every
327
+ refused row's entries naming it (`[1].City`, `[1]` for a message about the row as a whole) and an
328
+ entry `{ path: "[j]", code: "INSERTED", params: { insertedId } }` for each row created. `bulkUpdate` and `bulkReplace` write row by row as well, but the table layer calls the
329
+ adapter for each row without saying which, so their errors name no row. Nested writes are split
330
+ by the table layer into one write per row and table (OData deep insert is not used).
331
+
332
+ #### ETags: the version token
333
+
334
+ An entity set that declares optimistic concurrency (`Core.OptimisticConcurrency`, also with an
335
+ empty property list except on an SAP service, whose entities carry no ETag then, or v2
336
+ `ConcurrencyMode="Fixed"`) gets a version token from the generator:
337
+ `__etag: string` with `@db.column.version @db.column.version.token`, a field the service does
338
+ not have. Every read fills it with the entity's ETag (`__metadata.etag`, `@odata.etag`, or the
339
+ `ETag` header of a single read); it is never sent to the service, and cannot be filtered or sorted
340
+ by. (A set whose entity type has a property named `__etag` gets no token; the generator reports
341
+ it.)
342
+
343
+ - **With the token, real conflict detection.** An update or replace whose `$cas` carries the
344
+ token (`{ __etag: "<ETag>" }`; moost-db lifts the `__etag` of a request body into it) is sent
345
+ with it as `If-Match`, and nothing is read first. A `412` (someone changed the entity since the
346
+ caller's read) answers `{ matchedCount: 0 }`, which moost-db turns into its `409`
347
+ `VERSION_MISMATCH` with the entity's current token (or `404` when the entity is gone). A write
348
+ with nothing to send compares the token with the entity's.
349
+ - **Without the token, last write wins.** An update or replace without `$cas`, and every delete,
350
+ overwrites whatever changed since the caller read the entity. The service still requires
351
+ `If-Match`, so the adapter reads the entity right before the write and sends that ETag (`*`
352
+ for an entity that comes without one; a `412` to `*` matches nothing when one more read finds
353
+ the entity gone, and is `STORE_FAILED` when it finds it: the service does not take `*`). A `412`
354
+ (a change in the moment between that read and the write) has the ETag read and the write sent
355
+ again, three attempts in all; then the write fails with `SERIALIZATION_FAILURE` (moost-db `503`).
356
+
357
+ Sets without the declaration have no token and are written without `If-Match`. A token in the
358
+ row of an insert is not sent. The table layer refuses a patch that carries `$cas` and writes no
359
+ column (a versioned touch).
360
+
361
+ ### Errors
362
+
363
+ | Situation | Error |
364
+ | ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
365
+ | a read OData cannot express, or the service metadata forbids | `DbError` `INVALID_QUERY` with the path |
366
+ | a filter or sort of a relation on OData v2 | `DbError` `NOT_SUPPORTED` with the relation's path |
367
+ | the service answers `400` | `DbError` `INVALID_QUERY` with its messages, by field (see below) |
368
+ | a read needs more pages than the engine follows | `DbError` `INVALID_QUERY` on `$limit` |
369
+ | a write the entity set does not allow, a draft-enabled set, a write by filter or not by key, field operators | `ODataNotSupportedError`: a `DbError` `NOT_SUPPORTED` |
370
+ | a grouped read the entity set cannot answer (see [Aggregation](#aggregation)) | `ODataNotSupportedError` for `aggregate`: a `DbError` `NOT_SUPPORTED` |
371
+ | a payload the engine refuses (unknown property, bad value) | `DbError` `INVALID_QUERY`, entry `code` of the engine (`UNKNOWN_PROPERTY`, `INVALID_VALUE`, …) |
372
+ | the service answers `412` to a write with the caller's token | not an error: nothing matched (moost-db answers `409` with the current token) |
373
+ | the service answers `412` on each of three attempts (changed since the ETag was read) | `DbError` `SERIALIZATION_FAILURE` (retryable) |
374
+ | the service answers `409` | `DbError` `CONFLICT` with its messages, by field (see below) |
375
+ | a write by key answers `404` | not an error: nothing matched |
376
+ | the service answers `501` (not implemented: a method, function or query option) | `DbError` `NOT_SUPPORTED` with its messages, by field |
377
+ | the service answers another `5xx`, `401`, `403`, `428` or another status, a collection read `404`, no usable answer | `DbError` `STORE_FAILED` |
378
+ | a write without credentials, or with `sessions: false`, fails its CSRF check | `DbError` `STORE_FAILED`, the `cause`'s `hint` `"session-required"` |
379
+ | the service's gateway answers `504`, or the call is aborted or times out | `DbError` `STORE_TIMEOUT` |
380
+ | the service answers `429` | `DbError` `STORE_THROTTLED`, `params.retryAfter` (seconds) when it named a wait |
381
+ | a call of a table whose entity set the live service no longer has | a plain `Error`, before any request |
382
+
383
+ The original error is the `cause`. `@atscript/moost-db` answers a `DbError` `INVALID_QUERY` or
384
+ `NOT_SUPPORTED` with `400`, `CONFLICT` with `409`, `SERIALIZATION_FAILURE` with `503`, and the
385
+ store-failure codes `STORE_FAILED`, `STORE_TIMEOUT`, `STORE_THROTTLED` with `502`, `504` and `429`
386
+ (with `Retry-After`), on any controller, and logs every `5xx` with its cause. A store failure's
387
+ message is generic; what the service said stays in the cause. An `ODataNotSupportedError` is a
388
+ `DbError` with atscript-db's code `NOT_SUPPORTED`, one entry coded `NOT_SUPPORTED` without
389
+ `params`, and the adapter method as `operation`. The `DbError`s come from `dbFailureOf` of
390
+ `@atscript/odata`, the one mapping the browser client answers with too, and from `toDbError` for
391
+ what only a server answers so (its own credentials, connection and session). A `404` on a key read
392
+ is not an error (the entity is `null`); on a collection read it means the service or the entity set
393
+ is not where it was configured.
394
+
395
+ The messages of a `400` or `409` follow `messageEntries` of `@atscript/odata`, the rule the browser
396
+ client follows too, on v2 and v4: the service's leading message is the error's `message`, and an
397
+ entry of `errors` at its field when its target names one, else at `""` with the service's code when
398
+ it has one no detail repeats (`dbFailureOf`); every message with a target is an entry at
399
+ the field path it maps to (with the service's code); a detail without a target is an entry at `""`
400
+ unless it repeats the leading message; a pseudo target like SAP CAP's `/#TRANSIENT#` counts as
401
+ none.
402
+
403
+ ## License
404
+
405
+ MIT
406
+
407
+ ---
408
+
409
+ SAP, SAP S/4HANA and the other SAP products named here are trademarks or registered trademarks of SAP SE (or an SAP affiliate company) in Germany and other countries. Atscript OData is not affiliated with or endorsed by SAP SE.