@farming-labs/orm-dynamodb 0.0.37
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/dist/index.cjs +1064 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +29 -0
- package/dist/index.d.ts +29 -0
- package/dist/index.js +1053 -0
- package/dist/index.js.map +1 -0
- package/package.json +35 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1053 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { randomUUID } from "crypto";
|
|
3
|
+
import {
|
|
4
|
+
DeleteCommand,
|
|
5
|
+
GetCommand,
|
|
6
|
+
PutCommand,
|
|
7
|
+
ScanCommand,
|
|
8
|
+
TransactWriteCommand,
|
|
9
|
+
DynamoDBDocumentClient
|
|
10
|
+
} from "@aws-sdk/lib-dynamodb";
|
|
11
|
+
import {
|
|
12
|
+
createDriverHandle,
|
|
13
|
+
createManifest,
|
|
14
|
+
equalValues,
|
|
15
|
+
isOperatorFilterObject,
|
|
16
|
+
mergeUniqueLookupCreateData,
|
|
17
|
+
requireUniqueLookup,
|
|
18
|
+
validateUniqueLookupUpdateData
|
|
19
|
+
} from "@farming-labs/orm";
|
|
20
|
+
var ormPrimaryKey = "__orm_pk";
|
|
21
|
+
var ormKindKey = "__orm_kind";
|
|
22
|
+
var ormTargetKey = "__orm_target";
|
|
23
|
+
var ormRecordKind = "record";
|
|
24
|
+
var ormUniqueKind = "unique";
|
|
25
|
+
var manifestCache = /* @__PURE__ */ new WeakMap();
|
|
26
|
+
function getManifest(schema) {
|
|
27
|
+
const cached = manifestCache.get(schema);
|
|
28
|
+
if (cached) return cached;
|
|
29
|
+
const next = createManifest(schema);
|
|
30
|
+
manifestCache.set(schema, next);
|
|
31
|
+
return next;
|
|
32
|
+
}
|
|
33
|
+
function isRecord(value) {
|
|
34
|
+
return !!value && typeof value === "object";
|
|
35
|
+
}
|
|
36
|
+
function normalizeDecimalString(value) {
|
|
37
|
+
const trimmed = value.trim();
|
|
38
|
+
const match = /^(-?\d+)(?:\.(\d+))?$/.exec(trimmed);
|
|
39
|
+
if (!match) {
|
|
40
|
+
return trimmed;
|
|
41
|
+
}
|
|
42
|
+
const [, integerPart, fractionalPart] = match;
|
|
43
|
+
if (!fractionalPart) {
|
|
44
|
+
return integerPart;
|
|
45
|
+
}
|
|
46
|
+
const normalizedFraction = fractionalPart.replace(/0+$/g, "");
|
|
47
|
+
return normalizedFraction.length ? `${integerPart}.${normalizedFraction}` : integerPart;
|
|
48
|
+
}
|
|
49
|
+
function isDocumentClientLike(client) {
|
|
50
|
+
const constructorName = client?.constructor?.name ?? "";
|
|
51
|
+
return constructorName.includes("DocumentClient") || isRecord(client.config) && "translateConfig" in client.config;
|
|
52
|
+
}
|
|
53
|
+
function createDocumentClient(client, override) {
|
|
54
|
+
if (override) return override;
|
|
55
|
+
if (isDocumentClientLike(client)) {
|
|
56
|
+
return client;
|
|
57
|
+
}
|
|
58
|
+
return DynamoDBDocumentClient.from(client, {
|
|
59
|
+
marshallOptions: {
|
|
60
|
+
removeUndefinedValues: true
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
function applyDefault(value, field) {
|
|
65
|
+
if (value !== void 0) return value;
|
|
66
|
+
if (field.generated === "id") return randomUUID();
|
|
67
|
+
if (field.generated === "now") return /* @__PURE__ */ new Date();
|
|
68
|
+
if (typeof field.defaultValue === "function") {
|
|
69
|
+
return field.defaultValue();
|
|
70
|
+
}
|
|
71
|
+
return field.defaultValue;
|
|
72
|
+
}
|
|
73
|
+
function isComparable(value) {
|
|
74
|
+
return value instanceof Date || typeof value === "number" || typeof value === "string" || typeof value === "bigint";
|
|
75
|
+
}
|
|
76
|
+
function evaluateFilter(value, filter) {
|
|
77
|
+
if (!isOperatorFilterObject(filter)) {
|
|
78
|
+
return equalValues(value, filter);
|
|
79
|
+
}
|
|
80
|
+
if ("eq" in filter && !equalValues(value, filter.eq)) return false;
|
|
81
|
+
if ("not" in filter && equalValues(value, filter.not)) return false;
|
|
82
|
+
if ("in" in filter) {
|
|
83
|
+
const values = Array.isArray(filter.in) ? filter.in : [];
|
|
84
|
+
if (!values.some((candidate) => equalValues(candidate, value))) return false;
|
|
85
|
+
}
|
|
86
|
+
if ("contains" in filter) {
|
|
87
|
+
if (typeof value !== "string" || typeof filter.contains !== "string") return false;
|
|
88
|
+
if (!value.includes(filter.contains)) return false;
|
|
89
|
+
}
|
|
90
|
+
if ("gt" in filter) {
|
|
91
|
+
if (!isComparable(value) || value <= filter.gt) return false;
|
|
92
|
+
}
|
|
93
|
+
if ("gte" in filter) {
|
|
94
|
+
if (!isComparable(value) || value < filter.gte) return false;
|
|
95
|
+
}
|
|
96
|
+
if ("lt" in filter) {
|
|
97
|
+
if (!isComparable(value) || value >= filter.lt) return false;
|
|
98
|
+
}
|
|
99
|
+
if ("lte" in filter) {
|
|
100
|
+
if (!isComparable(value) || value > filter.lte) return false;
|
|
101
|
+
}
|
|
102
|
+
return true;
|
|
103
|
+
}
|
|
104
|
+
function sortRows(rows, orderBy) {
|
|
105
|
+
if (!orderBy) return rows;
|
|
106
|
+
const entries = Object.entries(orderBy);
|
|
107
|
+
if (!entries.length) return rows;
|
|
108
|
+
return [...rows].sort((left, right) => {
|
|
109
|
+
for (const [field, direction] of entries) {
|
|
110
|
+
const a = left.data[field];
|
|
111
|
+
const b = right.data[field];
|
|
112
|
+
if (equalValues(a, b)) continue;
|
|
113
|
+
if (a === void 0) return direction === "asc" ? -1 : 1;
|
|
114
|
+
if (b === void 0) return direction === "asc" ? 1 : -1;
|
|
115
|
+
if (a == null) return direction === "asc" ? -1 : 1;
|
|
116
|
+
if (b == null) return direction === "asc" ? 1 : -1;
|
|
117
|
+
if (a < b) return direction === "asc" ? -1 : 1;
|
|
118
|
+
if (a > b) return direction === "asc" ? 1 : -1;
|
|
119
|
+
}
|
|
120
|
+
return 0;
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
function pageRows(rows, skip, take) {
|
|
124
|
+
const start = skip ?? 0;
|
|
125
|
+
const end = take === void 0 ? void 0 : start + take;
|
|
126
|
+
return rows.slice(start, end);
|
|
127
|
+
}
|
|
128
|
+
function dynamodbConstraintError(target) {
|
|
129
|
+
const fields = Array.isArray(target) ? target.join(", ") : target ?? "unique fields";
|
|
130
|
+
const error = new Error(`DynamoDB unique constraint violation on ${fields}.`);
|
|
131
|
+
Object.assign(error, {
|
|
132
|
+
code: "ConditionalCheckFailedException",
|
|
133
|
+
target
|
|
134
|
+
});
|
|
135
|
+
return error;
|
|
136
|
+
}
|
|
137
|
+
function isUnsupportedTransactionWrite(error) {
|
|
138
|
+
if (!isRecord(error)) return false;
|
|
139
|
+
return error.name === "UnknownOperationException" || error.code === "UnknownOperationException" || String(error.message ?? "").includes("UnknownOperation");
|
|
140
|
+
}
|
|
141
|
+
function recordPk(docId) {
|
|
142
|
+
return `record#${docId}`;
|
|
143
|
+
}
|
|
144
|
+
function getStoredItemPk(item) {
|
|
145
|
+
const value = item[ormPrimaryKey];
|
|
146
|
+
return typeof value === "string" ? value : void 0;
|
|
147
|
+
}
|
|
148
|
+
function normalizeDynamoDbDocumentClient(client, documentClient) {
|
|
149
|
+
return createDocumentClient(client, documentClient);
|
|
150
|
+
}
|
|
151
|
+
function createDynamoDbDriverInternal(config) {
|
|
152
|
+
const documentClient = createDocumentClient(config.client, config.documentClient);
|
|
153
|
+
function getSupportedManifest(schema) {
|
|
154
|
+
const manifest = getManifest(schema);
|
|
155
|
+
for (const model of Object.values(manifest.models)) {
|
|
156
|
+
if (model.schema) {
|
|
157
|
+
throw new Error(
|
|
158
|
+
`The DynamoDB runtime does not support schema-qualified tables for model "${model.name}". Use flat table names instead.`
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
const idField = model.fields.id;
|
|
162
|
+
if (idField?.kind === "id" && idField.idType === "integer" && idField.generated === "increment") {
|
|
163
|
+
throw new Error(
|
|
164
|
+
`The DynamoDB runtime does not support generated integer ids for model "${model.name}". Use manual numeric ids or a string id instead.`
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return manifest;
|
|
169
|
+
}
|
|
170
|
+
function getTableName(schema, modelName) {
|
|
171
|
+
const manifest = getSupportedManifest(schema);
|
|
172
|
+
return config.tables?.[modelName] ?? manifest.models[modelName].table;
|
|
173
|
+
}
|
|
174
|
+
function fieldTransform(modelName, fieldName) {
|
|
175
|
+
return config.transforms?.[modelName]?.[fieldName];
|
|
176
|
+
}
|
|
177
|
+
function encodeValue(modelName, field, value) {
|
|
178
|
+
if (value === void 0) return value;
|
|
179
|
+
if (value === null) return null;
|
|
180
|
+
const transform = fieldTransform(modelName, field.name);
|
|
181
|
+
if (transform?.encode) {
|
|
182
|
+
return transform.encode(value);
|
|
183
|
+
}
|
|
184
|
+
if (field.kind === "id" && field.idType === "integer") {
|
|
185
|
+
return Number(value);
|
|
186
|
+
}
|
|
187
|
+
if (field.kind === "enum") {
|
|
188
|
+
return String(value);
|
|
189
|
+
}
|
|
190
|
+
if (field.kind === "boolean") {
|
|
191
|
+
return Boolean(value);
|
|
192
|
+
}
|
|
193
|
+
if (field.kind === "integer") {
|
|
194
|
+
return Number(value);
|
|
195
|
+
}
|
|
196
|
+
if (field.kind === "bigint") {
|
|
197
|
+
return typeof value === "bigint" ? value.toString() : BigInt(value).toString();
|
|
198
|
+
}
|
|
199
|
+
if (field.kind === "decimal") {
|
|
200
|
+
return typeof value === "string" ? normalizeDecimalString(value) : String(value);
|
|
201
|
+
}
|
|
202
|
+
if (field.kind === "datetime") {
|
|
203
|
+
if (value instanceof Date) return value.toISOString();
|
|
204
|
+
return new Date(value).toISOString();
|
|
205
|
+
}
|
|
206
|
+
return value;
|
|
207
|
+
}
|
|
208
|
+
function decodeValue(modelName, field, value, docId) {
|
|
209
|
+
const transform = fieldTransform(modelName, field.name);
|
|
210
|
+
if (transform?.decode) {
|
|
211
|
+
return transform.decode(value);
|
|
212
|
+
}
|
|
213
|
+
if (value === void 0 && field.kind === "id" && docId !== void 0) {
|
|
214
|
+
if (field.idType === "integer") {
|
|
215
|
+
const numeric = Number(docId);
|
|
216
|
+
return Number.isFinite(numeric) ? numeric : void 0;
|
|
217
|
+
}
|
|
218
|
+
return docId;
|
|
219
|
+
}
|
|
220
|
+
if (value === void 0 || value === null) return value ?? null;
|
|
221
|
+
if (field.kind === "id" && field.idType === "integer") {
|
|
222
|
+
return Number(value);
|
|
223
|
+
}
|
|
224
|
+
if (field.kind === "enum") {
|
|
225
|
+
return String(value);
|
|
226
|
+
}
|
|
227
|
+
if (field.kind === "boolean") {
|
|
228
|
+
return Boolean(value);
|
|
229
|
+
}
|
|
230
|
+
if (field.kind === "integer") {
|
|
231
|
+
return Number(value);
|
|
232
|
+
}
|
|
233
|
+
if (field.kind === "bigint") {
|
|
234
|
+
return typeof value === "bigint" ? value : BigInt(value);
|
|
235
|
+
}
|
|
236
|
+
if (field.kind === "decimal") {
|
|
237
|
+
return normalizeDecimalString(String(value));
|
|
238
|
+
}
|
|
239
|
+
if (field.kind === "datetime") {
|
|
240
|
+
return value instanceof Date ? value : new Date(value);
|
|
241
|
+
}
|
|
242
|
+
return value;
|
|
243
|
+
}
|
|
244
|
+
function buildStoredRow(model, data) {
|
|
245
|
+
const stored = {};
|
|
246
|
+
const decoded = {};
|
|
247
|
+
for (const field of Object.values(model.fields)) {
|
|
248
|
+
const value = applyDefault(data[field.name], field);
|
|
249
|
+
if (value === void 0) continue;
|
|
250
|
+
const encoded = encodeValue(model.name, field, value);
|
|
251
|
+
stored[field.column] = encoded;
|
|
252
|
+
decoded[field.name] = decodeValue(model.name, field, encoded);
|
|
253
|
+
}
|
|
254
|
+
const idField = model.fields.id;
|
|
255
|
+
if (!idField) {
|
|
256
|
+
return {
|
|
257
|
+
docId: randomUUID(),
|
|
258
|
+
stored,
|
|
259
|
+
decoded
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
let idValue = decoded[idField.name];
|
|
263
|
+
if (idValue === void 0 || idValue === null) {
|
|
264
|
+
if (idField.idType === "integer") {
|
|
265
|
+
throw new Error(
|
|
266
|
+
`The DynamoDB runtime requires an explicit numeric id for model "${model.name}" when using manual integer ids.`
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
idValue = randomUUID();
|
|
270
|
+
const encodedId = encodeValue(model.name, idField, idValue);
|
|
271
|
+
stored[idField.column] = encodedId;
|
|
272
|
+
decoded[idField.name] = decodeValue(model.name, idField, encodedId);
|
|
273
|
+
idValue = decoded[idField.name];
|
|
274
|
+
}
|
|
275
|
+
return {
|
|
276
|
+
docId: String(idValue),
|
|
277
|
+
stored,
|
|
278
|
+
decoded
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
function buildUpdatedRow(model, current, data) {
|
|
282
|
+
const stored = {
|
|
283
|
+
...current.stored
|
|
284
|
+
};
|
|
285
|
+
const decoded = {
|
|
286
|
+
...current.data
|
|
287
|
+
};
|
|
288
|
+
for (const [fieldName, value] of Object.entries(data)) {
|
|
289
|
+
if (value === void 0) continue;
|
|
290
|
+
const field = model.fields[fieldName];
|
|
291
|
+
if (!field) {
|
|
292
|
+
throw new Error(`Unknown field "${fieldName}" on model "${model.name}".`);
|
|
293
|
+
}
|
|
294
|
+
if (field.name === "id" && !equalValues(current.data.id, value)) {
|
|
295
|
+
throw new Error(
|
|
296
|
+
`The DynamoDB runtime does not support updating the id field for model "${model.name}".`
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
const encoded = encodeValue(model.name, field, value);
|
|
300
|
+
stored[field.column] = encoded;
|
|
301
|
+
decoded[field.name] = decodeValue(model.name, field, encoded);
|
|
302
|
+
}
|
|
303
|
+
return {
|
|
304
|
+
docId: current.docId,
|
|
305
|
+
stored,
|
|
306
|
+
decoded
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
async function scanAllItems(tableName) {
|
|
310
|
+
const items = [];
|
|
311
|
+
let exclusiveStartKey;
|
|
312
|
+
do {
|
|
313
|
+
const result = await documentClient.send(
|
|
314
|
+
new ScanCommand({
|
|
315
|
+
TableName: tableName,
|
|
316
|
+
ExclusiveStartKey: exclusiveStartKey
|
|
317
|
+
})
|
|
318
|
+
);
|
|
319
|
+
items.push(...result.Items ?? []);
|
|
320
|
+
exclusiveStartKey = result.LastEvaluatedKey;
|
|
321
|
+
} while (exclusiveStartKey);
|
|
322
|
+
return items;
|
|
323
|
+
}
|
|
324
|
+
async function loadRowByPk(model, tableName, pk) {
|
|
325
|
+
const result = await documentClient.send(
|
|
326
|
+
new GetCommand({
|
|
327
|
+
TableName: tableName,
|
|
328
|
+
Key: {
|
|
329
|
+
[ormPrimaryKey]: pk
|
|
330
|
+
}
|
|
331
|
+
})
|
|
332
|
+
);
|
|
333
|
+
const stored = result.Item;
|
|
334
|
+
if (!stored || stored[ormKindKey] !== ormRecordKind) {
|
|
335
|
+
return null;
|
|
336
|
+
}
|
|
337
|
+
const decoded = {};
|
|
338
|
+
const docId = pk.slice("record#".length);
|
|
339
|
+
for (const field of Object.values(model.fields)) {
|
|
340
|
+
decoded[field.name] = decodeValue(model.name, field, stored[field.column], docId);
|
|
341
|
+
}
|
|
342
|
+
return {
|
|
343
|
+
docId,
|
|
344
|
+
pk,
|
|
345
|
+
data: decoded,
|
|
346
|
+
stored
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
async function loadRows(schema, modelName) {
|
|
350
|
+
const model = getSupportedManifest(schema).models[modelName];
|
|
351
|
+
const tableName = getTableName(schema, modelName);
|
|
352
|
+
const items = await scanAllItems(tableName);
|
|
353
|
+
return items.filter((item) => item[ormKindKey] === ormRecordKind).map((stored) => {
|
|
354
|
+
const pk = getStoredItemPk(stored) ?? "";
|
|
355
|
+
const docId = pk.slice("record#".length);
|
|
356
|
+
const decoded = {};
|
|
357
|
+
for (const field of Object.values(model.fields)) {
|
|
358
|
+
decoded[field.name] = decodeValue(model.name, field, stored[field.column], docId);
|
|
359
|
+
}
|
|
360
|
+
return {
|
|
361
|
+
docId,
|
|
362
|
+
pk,
|
|
363
|
+
data: decoded,
|
|
364
|
+
stored
|
|
365
|
+
};
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
function normalizeFilterValue(model, fieldName, value) {
|
|
369
|
+
const field = model.fields[fieldName];
|
|
370
|
+
if (!field || value === void 0 || value === null) {
|
|
371
|
+
return value;
|
|
372
|
+
}
|
|
373
|
+
return decodeValue(model.name, field, encodeValue(model.name, field, value));
|
|
374
|
+
}
|
|
375
|
+
function evaluateModelFilter(model, fieldName, value, filter) {
|
|
376
|
+
if (!isOperatorFilterObject(filter)) {
|
|
377
|
+
return equalValues(value, normalizeFilterValue(model, fieldName, filter));
|
|
378
|
+
}
|
|
379
|
+
const normalized = {
|
|
380
|
+
...filter.eq !== void 0 ? { eq: normalizeFilterValue(model, fieldName, filter.eq) } : {},
|
|
381
|
+
...filter.not !== void 0 ? { not: normalizeFilterValue(model, fieldName, filter.not) } : {},
|
|
382
|
+
...filter.in !== void 0 ? {
|
|
383
|
+
in: (Array.isArray(filter.in) ? filter.in : []).map(
|
|
384
|
+
(entry) => normalizeFilterValue(model, fieldName, entry)
|
|
385
|
+
)
|
|
386
|
+
} : {},
|
|
387
|
+
...filter.contains !== void 0 ? { contains: String(filter.contains) } : {},
|
|
388
|
+
...filter.gt !== void 0 ? { gt: normalizeFilterValue(model, fieldName, filter.gt) } : {},
|
|
389
|
+
...filter.gte !== void 0 ? { gte: normalizeFilterValue(model, fieldName, filter.gte) } : {},
|
|
390
|
+
...filter.lt !== void 0 ? { lt: normalizeFilterValue(model, fieldName, filter.lt) } : {},
|
|
391
|
+
...filter.lte !== void 0 ? { lte: normalizeFilterValue(model, fieldName, filter.lte) } : {}
|
|
392
|
+
};
|
|
393
|
+
return evaluateFilter(value, normalized);
|
|
394
|
+
}
|
|
395
|
+
function matchesModelWhere(model, record, where) {
|
|
396
|
+
if (!where) return true;
|
|
397
|
+
if (where.AND && !where.AND.every((clause) => matchesModelWhere(model, record, clause))) {
|
|
398
|
+
return false;
|
|
399
|
+
}
|
|
400
|
+
if (where.OR && !where.OR.some((clause) => matchesModelWhere(model, record, clause))) {
|
|
401
|
+
return false;
|
|
402
|
+
}
|
|
403
|
+
if (where.NOT && matchesModelWhere(model, record, where.NOT)) {
|
|
404
|
+
return false;
|
|
405
|
+
}
|
|
406
|
+
for (const [key, filter] of Object.entries(where)) {
|
|
407
|
+
if (key === "AND" || key === "OR" || key === "NOT") continue;
|
|
408
|
+
if (!evaluateModelFilter(model, key, record[key], filter)) return false;
|
|
409
|
+
}
|
|
410
|
+
return true;
|
|
411
|
+
}
|
|
412
|
+
function applyModelQuery(model, rows, args = {}) {
|
|
413
|
+
const filtered = rows.filter((row) => matchesModelWhere(model, row.data, args.where));
|
|
414
|
+
const sorted = sortRows(filtered, args.orderBy);
|
|
415
|
+
return pageRows(sorted, args.skip, args.take);
|
|
416
|
+
}
|
|
417
|
+
function serializeUniqueValue(model, fieldName, value) {
|
|
418
|
+
const field = model.fields[fieldName];
|
|
419
|
+
const normalized = decodeValue(model.name, field, encodeValue(model.name, field, value));
|
|
420
|
+
if (normalized instanceof Date) {
|
|
421
|
+
return normalized.toISOString();
|
|
422
|
+
}
|
|
423
|
+
if (typeof normalized === "bigint") {
|
|
424
|
+
return normalized.toString();
|
|
425
|
+
}
|
|
426
|
+
return JSON.stringify(normalized);
|
|
427
|
+
}
|
|
428
|
+
function uniqueLockPk(model, fields, row) {
|
|
429
|
+
const values = fields.map((fieldName) => row[fieldName]);
|
|
430
|
+
if (values.some((value) => value === void 0 || value === null)) {
|
|
431
|
+
return null;
|
|
432
|
+
}
|
|
433
|
+
const encodedValues = fields.map(
|
|
434
|
+
(fieldName) => encodeURIComponent(serializeUniqueValue(model, fieldName, row[fieldName]))
|
|
435
|
+
);
|
|
436
|
+
return `unique#${model.name}#${fields.join("+")}#${encodedValues.join("#")}`;
|
|
437
|
+
}
|
|
438
|
+
function uniqueLocksForRow(model, row, docId) {
|
|
439
|
+
const target = recordPk(docId);
|
|
440
|
+
const locks = [];
|
|
441
|
+
for (const field of Object.values(model.fields)) {
|
|
442
|
+
if (!field.unique) continue;
|
|
443
|
+
const pk = uniqueLockPk(model, [field.name], row);
|
|
444
|
+
if (!pk) continue;
|
|
445
|
+
locks.push({
|
|
446
|
+
pk,
|
|
447
|
+
target,
|
|
448
|
+
fields: [field.name]
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
for (const constraint of model.constraints.unique) {
|
|
452
|
+
const pk = uniqueLockPk(model, [...constraint.fields], row);
|
|
453
|
+
if (!pk) continue;
|
|
454
|
+
locks.push({
|
|
455
|
+
pk,
|
|
456
|
+
target,
|
|
457
|
+
fields: [...constraint.fields]
|
|
458
|
+
});
|
|
459
|
+
}
|
|
460
|
+
return locks;
|
|
461
|
+
}
|
|
462
|
+
async function loadUniqueRow(schema, modelName, where) {
|
|
463
|
+
const manifest = getSupportedManifest(schema);
|
|
464
|
+
const model = manifest.models[modelName];
|
|
465
|
+
const lookup = requireUniqueLookup(model, where, "FindUnique");
|
|
466
|
+
const tableName = getTableName(schema, modelName);
|
|
467
|
+
if (lookup.kind === "id") {
|
|
468
|
+
return loadRowByPk(model, tableName, recordPk(String(lookup.values[lookup.fields[0].name])));
|
|
469
|
+
}
|
|
470
|
+
const normalizedLookupRow = Object.fromEntries(
|
|
471
|
+
lookup.fields.map((field) => [
|
|
472
|
+
field.name,
|
|
473
|
+
decodeValue(model.name, field, encodeValue(model.name, field, lookup.values[field.name]))
|
|
474
|
+
])
|
|
475
|
+
);
|
|
476
|
+
const lockPk = uniqueLockPk(
|
|
477
|
+
model,
|
|
478
|
+
lookup.fields.map((field) => field.name),
|
|
479
|
+
normalizedLookupRow
|
|
480
|
+
);
|
|
481
|
+
if (!lockPk) {
|
|
482
|
+
return null;
|
|
483
|
+
}
|
|
484
|
+
const lockResult = await documentClient.send(
|
|
485
|
+
new GetCommand({
|
|
486
|
+
TableName: tableName,
|
|
487
|
+
Key: {
|
|
488
|
+
[ormPrimaryKey]: lockPk
|
|
489
|
+
}
|
|
490
|
+
})
|
|
491
|
+
);
|
|
492
|
+
const target = typeof lockResult.Item?.[ormTargetKey] === "string" ? lockResult.Item[ormTargetKey] : void 0;
|
|
493
|
+
if (!target) {
|
|
494
|
+
return null;
|
|
495
|
+
}
|
|
496
|
+
return loadRowByPk(model, tableName, target);
|
|
497
|
+
}
|
|
498
|
+
function findUniqueConflict(model, candidate, existingRows, ignoreDocIds = /* @__PURE__ */ new Set()) {
|
|
499
|
+
const idField = model.fields.id;
|
|
500
|
+
for (const row of existingRows) {
|
|
501
|
+
if (ignoreDocIds.has(row.docId)) continue;
|
|
502
|
+
if (idField && candidate[idField.name] !== void 0 && candidate[idField.name] !== null && row.data[idField.name] !== void 0 && row.data[idField.name] !== null && equalValues(candidate[idField.name], row.data[idField.name])) {
|
|
503
|
+
return [idField.name];
|
|
504
|
+
}
|
|
505
|
+
for (const field of Object.values(model.fields)) {
|
|
506
|
+
if (!field.unique) continue;
|
|
507
|
+
if (candidate[field.name] === void 0 || candidate[field.name] === null) continue;
|
|
508
|
+
if (row.data[field.name] === void 0 || row.data[field.name] === null) continue;
|
|
509
|
+
if (equalValues(candidate[field.name], row.data[field.name])) {
|
|
510
|
+
return [field.name];
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
for (const constraint of model.constraints.unique) {
|
|
514
|
+
if (!constraint.fields.every(
|
|
515
|
+
(fieldName) => candidate[fieldName] !== void 0 && candidate[fieldName] !== null && row.data[fieldName] !== void 0 && row.data[fieldName] !== null
|
|
516
|
+
)) {
|
|
517
|
+
continue;
|
|
518
|
+
}
|
|
519
|
+
if (constraint.fields.every(
|
|
520
|
+
(fieldName) => equalValues(candidate[fieldName], row.data[fieldName])
|
|
521
|
+
)) {
|
|
522
|
+
return [...constraint.fields];
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
return null;
|
|
527
|
+
}
|
|
528
|
+
function buildRecordItem(row) {
|
|
529
|
+
return {
|
|
530
|
+
[ormPrimaryKey]: recordPk(row.docId),
|
|
531
|
+
[ormKindKey]: ormRecordKind,
|
|
532
|
+
...row.stored
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
function putRecordCreateItem(tableName, row) {
|
|
536
|
+
return {
|
|
537
|
+
Put: {
|
|
538
|
+
TableName: tableName,
|
|
539
|
+
Item: buildRecordItem(row),
|
|
540
|
+
ConditionExpression: "attribute_not_exists(#pk)",
|
|
541
|
+
ExpressionAttributeNames: {
|
|
542
|
+
"#pk": ormPrimaryKey
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
function putRecordUpdateItem(tableName, row) {
|
|
548
|
+
return {
|
|
549
|
+
Put: {
|
|
550
|
+
TableName: tableName,
|
|
551
|
+
Item: buildRecordItem(row)
|
|
552
|
+
}
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
function putUniqueItem(tableName, lock) {
|
|
556
|
+
return {
|
|
557
|
+
Put: {
|
|
558
|
+
TableName: tableName,
|
|
559
|
+
Item: {
|
|
560
|
+
[ormPrimaryKey]: lock.pk,
|
|
561
|
+
[ormKindKey]: ormUniqueKind,
|
|
562
|
+
[ormTargetKey]: lock.target
|
|
563
|
+
},
|
|
564
|
+
ConditionExpression: "attribute_not_exists(#pk)",
|
|
565
|
+
ExpressionAttributeNames: {
|
|
566
|
+
"#pk": ormPrimaryKey
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
function deleteItem(tableName, pk) {
|
|
572
|
+
return {
|
|
573
|
+
Delete: {
|
|
574
|
+
TableName: tableName,
|
|
575
|
+
Key: {
|
|
576
|
+
[ormPrimaryKey]: pk
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
async function putRecordSequential(tableName, row, conditionallyCreate) {
|
|
582
|
+
await documentClient.send(
|
|
583
|
+
new PutCommand({
|
|
584
|
+
TableName: tableName,
|
|
585
|
+
Item: buildRecordItem(row),
|
|
586
|
+
...conditionallyCreate ? {
|
|
587
|
+
ConditionExpression: "attribute_not_exists(#pk)",
|
|
588
|
+
ExpressionAttributeNames: {
|
|
589
|
+
"#pk": ormPrimaryKey
|
|
590
|
+
}
|
|
591
|
+
} : {}
|
|
592
|
+
})
|
|
593
|
+
);
|
|
594
|
+
}
|
|
595
|
+
async function putUniqueSequential(tableName, lock) {
|
|
596
|
+
await documentClient.send(
|
|
597
|
+
new PutCommand({
|
|
598
|
+
TableName: tableName,
|
|
599
|
+
Item: {
|
|
600
|
+
[ormPrimaryKey]: lock.pk,
|
|
601
|
+
[ormKindKey]: ormUniqueKind,
|
|
602
|
+
[ormTargetKey]: lock.target
|
|
603
|
+
},
|
|
604
|
+
ConditionExpression: "attribute_not_exists(#pk)",
|
|
605
|
+
ExpressionAttributeNames: {
|
|
606
|
+
"#pk": ormPrimaryKey
|
|
607
|
+
}
|
|
608
|
+
})
|
|
609
|
+
);
|
|
610
|
+
}
|
|
611
|
+
async function deleteSequential(tableName, pk) {
|
|
612
|
+
await documentClient.send(
|
|
613
|
+
new DeleteCommand({
|
|
614
|
+
TableName: tableName,
|
|
615
|
+
Key: {
|
|
616
|
+
[ormPrimaryKey]: pk
|
|
617
|
+
}
|
|
618
|
+
})
|
|
619
|
+
);
|
|
620
|
+
}
|
|
621
|
+
async function acquireUniqueLocksSequential(tableName, locks) {
|
|
622
|
+
const acquired = [];
|
|
623
|
+
try {
|
|
624
|
+
for (const lock of locks) {
|
|
625
|
+
await putUniqueSequential(tableName, lock);
|
|
626
|
+
acquired.push(lock);
|
|
627
|
+
}
|
|
628
|
+
} catch (error) {
|
|
629
|
+
await releaseUniqueLocksSequential(tableName, acquired);
|
|
630
|
+
throw error;
|
|
631
|
+
}
|
|
632
|
+
return acquired;
|
|
633
|
+
}
|
|
634
|
+
async function releaseUniqueLocksSequential(tableName, locks) {
|
|
635
|
+
for (const lock of [...locks].reverse()) {
|
|
636
|
+
try {
|
|
637
|
+
await deleteSequential(tableName, lock.pk);
|
|
638
|
+
} catch {
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
async function createRecordWithLocks(tableName, row, model) {
|
|
643
|
+
const locks = uniqueLocksForRow(model, row.decoded, row.docId);
|
|
644
|
+
const transactItems = [
|
|
645
|
+
putRecordCreateItem(tableName, row),
|
|
646
|
+
...locks.map((lock) => putUniqueItem(tableName, lock))
|
|
647
|
+
];
|
|
648
|
+
try {
|
|
649
|
+
await documentClient.send(
|
|
650
|
+
new TransactWriteCommand({
|
|
651
|
+
TransactItems: transactItems
|
|
652
|
+
})
|
|
653
|
+
);
|
|
654
|
+
} catch (error) {
|
|
655
|
+
if (!isUnsupportedTransactionWrite(error)) {
|
|
656
|
+
throw error;
|
|
657
|
+
}
|
|
658
|
+
const acquiredLocks = await acquireUniqueLocksSequential(tableName, locks);
|
|
659
|
+
try {
|
|
660
|
+
await putRecordSequential(tableName, row, true);
|
|
661
|
+
} catch (recordError) {
|
|
662
|
+
await releaseUniqueLocksSequential(tableName, acquiredLocks);
|
|
663
|
+
throw recordError;
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
async function updateRecordWithLocks(tableName, model, current, next) {
|
|
668
|
+
const currentLocks = new Map(
|
|
669
|
+
uniqueLocksForRow(model, current.data, current.docId).map((lock) => [lock.pk, lock])
|
|
670
|
+
);
|
|
671
|
+
const nextLocks = new Map(
|
|
672
|
+
uniqueLocksForRow(model, next.decoded, next.docId).map((lock) => [lock.pk, lock])
|
|
673
|
+
);
|
|
674
|
+
const deleteOps = [...currentLocks.keys()].filter((pk) => !nextLocks.has(pk)).map((pk) => deleteItem(tableName, pk));
|
|
675
|
+
const putOps = [...nextLocks.entries()].filter(([pk]) => !currentLocks.has(pk)).map(([, lock]) => putUniqueItem(tableName, lock));
|
|
676
|
+
try {
|
|
677
|
+
await documentClient.send(
|
|
678
|
+
new TransactWriteCommand({
|
|
679
|
+
TransactItems: [putRecordUpdateItem(tableName, next), ...deleteOps, ...putOps]
|
|
680
|
+
})
|
|
681
|
+
);
|
|
682
|
+
} catch (error) {
|
|
683
|
+
if (!isUnsupportedTransactionWrite(error)) {
|
|
684
|
+
throw error;
|
|
685
|
+
}
|
|
686
|
+
const addedLocks = [...nextLocks.values()].filter((lock) => !currentLocks.has(lock.pk));
|
|
687
|
+
const acquiredLocks = await acquireUniqueLocksSequential(tableName, addedLocks);
|
|
688
|
+
try {
|
|
689
|
+
await putRecordSequential(tableName, next, false);
|
|
690
|
+
} catch (recordError) {
|
|
691
|
+
await releaseUniqueLocksSequential(tableName, acquiredLocks);
|
|
692
|
+
throw recordError;
|
|
693
|
+
}
|
|
694
|
+
for (const operation of deleteOps) {
|
|
695
|
+
await deleteSequential(tableName, operation.Delete.Key[ormPrimaryKey]);
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
async function deleteRecordWithLocks(tableName, model, current) {
|
|
700
|
+
const locks = uniqueLocksForRow(model, current.data, current.docId);
|
|
701
|
+
try {
|
|
702
|
+
await documentClient.send(
|
|
703
|
+
new TransactWriteCommand({
|
|
704
|
+
TransactItems: [
|
|
705
|
+
deleteItem(tableName, current.pk),
|
|
706
|
+
...locks.map((lock) => deleteItem(tableName, lock.pk))
|
|
707
|
+
]
|
|
708
|
+
})
|
|
709
|
+
);
|
|
710
|
+
} catch (error) {
|
|
711
|
+
if (!isUnsupportedTransactionWrite(error)) {
|
|
712
|
+
throw error;
|
|
713
|
+
}
|
|
714
|
+
await deleteSequential(tableName, current.pk);
|
|
715
|
+
for (const lock of locks) {
|
|
716
|
+
await deleteSequential(tableName, lock.pk);
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
async function projectRow(schema, modelName, row, select) {
|
|
721
|
+
const modelDefinition = schema.models[modelName];
|
|
722
|
+
const output = {};
|
|
723
|
+
if (!select) {
|
|
724
|
+
for (const fieldName of Object.keys(modelDefinition.fields)) {
|
|
725
|
+
output[fieldName] = row[fieldName];
|
|
726
|
+
}
|
|
727
|
+
return output;
|
|
728
|
+
}
|
|
729
|
+
for (const [key, value] of Object.entries(select)) {
|
|
730
|
+
if (value !== true && value === void 0) continue;
|
|
731
|
+
if (key in modelDefinition.fields && value === true) {
|
|
732
|
+
output[key] = row[key];
|
|
733
|
+
continue;
|
|
734
|
+
}
|
|
735
|
+
if (key in modelDefinition.relations) {
|
|
736
|
+
output[key] = await resolveRelation(
|
|
737
|
+
schema,
|
|
738
|
+
modelName,
|
|
739
|
+
key,
|
|
740
|
+
row,
|
|
741
|
+
value
|
|
742
|
+
);
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
return output;
|
|
746
|
+
}
|
|
747
|
+
async function resolveRelation(schema, modelName, relationName, row, value) {
|
|
748
|
+
const relation = schema.models[modelName].relations[relationName];
|
|
749
|
+
const relationArgs = value === true ? {} : value;
|
|
750
|
+
if (relation.kind === "belongsTo") {
|
|
751
|
+
const foreignValue = row[relation.foreignKey];
|
|
752
|
+
const targetRows2 = (await loadRows(schema, relation.target)).filter(
|
|
753
|
+
(item) => equalValues(item.data.id, foreignValue)
|
|
754
|
+
);
|
|
755
|
+
const target = applyModelQuery(
|
|
756
|
+
relationTargetManifest(schema, relation.target),
|
|
757
|
+
targetRows2,
|
|
758
|
+
relationArgs
|
|
759
|
+
)[0];
|
|
760
|
+
return target ? projectRow(
|
|
761
|
+
schema,
|
|
762
|
+
relation.target,
|
|
763
|
+
target.data,
|
|
764
|
+
relationArgs.select
|
|
765
|
+
) : null;
|
|
766
|
+
}
|
|
767
|
+
if (relation.kind === "hasOne") {
|
|
768
|
+
const targetRows2 = (await loadRows(schema, relation.target)).filter(
|
|
769
|
+
(item) => equalValues(item.data[relation.foreignKey], row.id)
|
|
770
|
+
);
|
|
771
|
+
const target = applyModelQuery(
|
|
772
|
+
relationTargetManifest(schema, relation.target),
|
|
773
|
+
targetRows2,
|
|
774
|
+
relationArgs
|
|
775
|
+
)[0];
|
|
776
|
+
return target ? projectRow(
|
|
777
|
+
schema,
|
|
778
|
+
relation.target,
|
|
779
|
+
target.data,
|
|
780
|
+
relationArgs.select
|
|
781
|
+
) : null;
|
|
782
|
+
}
|
|
783
|
+
if (relation.kind === "hasMany") {
|
|
784
|
+
const targetRows2 = (await loadRows(schema, relation.target)).filter(
|
|
785
|
+
(item) => equalValues(item.data[relation.foreignKey], row.id)
|
|
786
|
+
);
|
|
787
|
+
const matchedRows2 = applyModelQuery(
|
|
788
|
+
relationTargetManifest(schema, relation.target),
|
|
789
|
+
targetRows2,
|
|
790
|
+
relationArgs
|
|
791
|
+
);
|
|
792
|
+
return Promise.all(
|
|
793
|
+
matchedRows2.map(
|
|
794
|
+
(item) => projectRow(schema, relation.target, item.data, relationArgs.select)
|
|
795
|
+
)
|
|
796
|
+
);
|
|
797
|
+
}
|
|
798
|
+
const throughRows = (await loadRows(schema, relation.through)).filter(
|
|
799
|
+
(item) => equalValues(item.data[relation.from], row.id)
|
|
800
|
+
);
|
|
801
|
+
const targetIds = throughRows.map((item) => item.data[relation.to]);
|
|
802
|
+
const targetRows = (await loadRows(schema, relation.target)).filter(
|
|
803
|
+
(item) => targetIds.some((targetId) => equalValues(targetId, item.data.id))
|
|
804
|
+
);
|
|
805
|
+
const matchedRows = applyModelQuery(
|
|
806
|
+
relationTargetManifest(schema, relation.target),
|
|
807
|
+
targetRows,
|
|
808
|
+
relationArgs
|
|
809
|
+
);
|
|
810
|
+
return Promise.all(
|
|
811
|
+
matchedRows.map(
|
|
812
|
+
(item) => projectRow(schema, relation.target, item.data, relationArgs.select)
|
|
813
|
+
)
|
|
814
|
+
);
|
|
815
|
+
}
|
|
816
|
+
function relationTargetManifest(schema, modelName) {
|
|
817
|
+
return getSupportedManifest(schema).models[modelName];
|
|
818
|
+
}
|
|
819
|
+
let driver;
|
|
820
|
+
driver = {
|
|
821
|
+
handle: createDriverHandle({
|
|
822
|
+
kind: "dynamodb",
|
|
823
|
+
client: {
|
|
824
|
+
client: config.client,
|
|
825
|
+
documentClient,
|
|
826
|
+
tables: config.tables
|
|
827
|
+
},
|
|
828
|
+
capabilities: {
|
|
829
|
+
supportsNumericIds: true,
|
|
830
|
+
numericIds: "manual",
|
|
831
|
+
supportsJSON: true,
|
|
832
|
+
supportsDates: true,
|
|
833
|
+
supportsBooleans: true,
|
|
834
|
+
supportsTransactions: false,
|
|
835
|
+
supportsSchemaNamespaces: false,
|
|
836
|
+
supportsTransactionalDDL: false,
|
|
837
|
+
supportsJoin: false,
|
|
838
|
+
nativeRelationLoading: "none",
|
|
839
|
+
textComparison: "case-sensitive",
|
|
840
|
+
textMatching: {
|
|
841
|
+
equality: "case-sensitive",
|
|
842
|
+
contains: "case-sensitive",
|
|
843
|
+
ordering: "case-sensitive"
|
|
844
|
+
},
|
|
845
|
+
upsert: "emulated",
|
|
846
|
+
returning: {
|
|
847
|
+
create: true,
|
|
848
|
+
update: true,
|
|
849
|
+
delete: false
|
|
850
|
+
},
|
|
851
|
+
returningMode: {
|
|
852
|
+
create: "record",
|
|
853
|
+
update: "record",
|
|
854
|
+
delete: "none"
|
|
855
|
+
},
|
|
856
|
+
nativeRelations: {
|
|
857
|
+
singularChains: false,
|
|
858
|
+
hasMany: false,
|
|
859
|
+
manyToMany: false,
|
|
860
|
+
filtered: false,
|
|
861
|
+
ordered: false,
|
|
862
|
+
paginated: false
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
}),
|
|
866
|
+
async findMany(schema, modelName, args) {
|
|
867
|
+
const model = getSupportedManifest(schema).models[modelName];
|
|
868
|
+
const rows = applyModelQuery(model, await loadRows(schema, modelName), args);
|
|
869
|
+
return Promise.all(rows.map((row) => projectRow(schema, modelName, row.data, args.select)));
|
|
870
|
+
},
|
|
871
|
+
async findFirst(schema, modelName, args) {
|
|
872
|
+
const model = getSupportedManifest(schema).models[modelName];
|
|
873
|
+
const row = applyModelQuery(model, await loadRows(schema, modelName), args)[0];
|
|
874
|
+
if (!row) return null;
|
|
875
|
+
return projectRow(schema, modelName, row.data, args.select);
|
|
876
|
+
},
|
|
877
|
+
async findUnique(schema, modelName, args) {
|
|
878
|
+
const model = getSupportedManifest(schema).models[modelName];
|
|
879
|
+
const row = await loadUniqueRow(schema, modelName, args.where);
|
|
880
|
+
if (!row || !matchesModelWhere(model, row.data, args.where)) {
|
|
881
|
+
return null;
|
|
882
|
+
}
|
|
883
|
+
return projectRow(schema, modelName, row.data, args.select);
|
|
884
|
+
},
|
|
885
|
+
async count(schema, modelName, args) {
|
|
886
|
+
const model = getSupportedManifest(schema).models[modelName];
|
|
887
|
+
return applyModelQuery(model, await loadRows(schema, modelName), args).length;
|
|
888
|
+
},
|
|
889
|
+
async create(schema, modelName, args) {
|
|
890
|
+
const model = getSupportedManifest(schema).models[modelName];
|
|
891
|
+
const existingRows = await loadRows(schema, modelName);
|
|
892
|
+
const built = buildStoredRow(model, args.data);
|
|
893
|
+
const conflict = findUniqueConflict(model, built.decoded, existingRows);
|
|
894
|
+
if (conflict) {
|
|
895
|
+
throw dynamodbConstraintError(conflict);
|
|
896
|
+
}
|
|
897
|
+
await createRecordWithLocks(getTableName(schema, modelName), built, model);
|
|
898
|
+
return projectRow(schema, modelName, built.decoded, args.select);
|
|
899
|
+
},
|
|
900
|
+
async createMany(schema, modelName, args) {
|
|
901
|
+
const model = getSupportedManifest(schema).models[modelName];
|
|
902
|
+
const existingRows = await loadRows(schema, modelName);
|
|
903
|
+
const created = [];
|
|
904
|
+
for (const entry of args.data) {
|
|
905
|
+
const built = buildStoredRow(model, entry);
|
|
906
|
+
const conflict = findUniqueConflict(model, built.decoded, [
|
|
907
|
+
...existingRows,
|
|
908
|
+
...created.map((row) => ({
|
|
909
|
+
docId: row.docId,
|
|
910
|
+
pk: recordPk(row.docId),
|
|
911
|
+
data: row.decoded,
|
|
912
|
+
stored: row.stored
|
|
913
|
+
}))
|
|
914
|
+
]);
|
|
915
|
+
if (conflict) {
|
|
916
|
+
throw dynamodbConstraintError(conflict);
|
|
917
|
+
}
|
|
918
|
+
created.push(built);
|
|
919
|
+
}
|
|
920
|
+
for (const row of created) {
|
|
921
|
+
await createRecordWithLocks(getTableName(schema, modelName), row, model);
|
|
922
|
+
}
|
|
923
|
+
return Promise.all(
|
|
924
|
+
created.map((row) => projectRow(schema, modelName, row.decoded, args.select))
|
|
925
|
+
);
|
|
926
|
+
},
|
|
927
|
+
async update(schema, modelName, args) {
|
|
928
|
+
const model = getSupportedManifest(schema).models[modelName];
|
|
929
|
+
const rows = await loadRows(schema, modelName);
|
|
930
|
+
const current = applyModelQuery(model, rows, {
|
|
931
|
+
where: args.where,
|
|
932
|
+
take: 1
|
|
933
|
+
})[0];
|
|
934
|
+
if (!current) return null;
|
|
935
|
+
const next = buildUpdatedRow(model, current, args.data);
|
|
936
|
+
const conflict = findUniqueConflict(model, next.decoded, rows, /* @__PURE__ */ new Set([current.docId]));
|
|
937
|
+
if (conflict) {
|
|
938
|
+
throw dynamodbConstraintError(conflict);
|
|
939
|
+
}
|
|
940
|
+
await updateRecordWithLocks(getTableName(schema, modelName), model, current, next);
|
|
941
|
+
return projectRow(schema, modelName, next.decoded, args.select);
|
|
942
|
+
},
|
|
943
|
+
async updateMany(schema, modelName, args) {
|
|
944
|
+
const model = getSupportedManifest(schema).models[modelName];
|
|
945
|
+
const rows = await loadRows(schema, modelName);
|
|
946
|
+
const matched = applyModelQuery(model, rows, {
|
|
947
|
+
where: args.where
|
|
948
|
+
});
|
|
949
|
+
if (!matched.length) return 0;
|
|
950
|
+
const nextRows = matched.map(
|
|
951
|
+
(row) => buildUpdatedRow(model, row, args.data)
|
|
952
|
+
);
|
|
953
|
+
const keepIds = new Set(matched.map((row) => row.docId));
|
|
954
|
+
const remaining = rows.filter((row) => !keepIds.has(row.docId));
|
|
955
|
+
const pending = [];
|
|
956
|
+
for (const next of nextRows) {
|
|
957
|
+
const conflict = findUniqueConflict(model, next.decoded, [...remaining, ...pending]);
|
|
958
|
+
if (conflict) {
|
|
959
|
+
throw dynamodbConstraintError(conflict);
|
|
960
|
+
}
|
|
961
|
+
pending.push({
|
|
962
|
+
docId: next.docId,
|
|
963
|
+
pk: recordPk(next.docId),
|
|
964
|
+
data: next.decoded,
|
|
965
|
+
stored: next.stored
|
|
966
|
+
});
|
|
967
|
+
}
|
|
968
|
+
for (let index = 0; index < matched.length; index += 1) {
|
|
969
|
+
await updateRecordWithLocks(
|
|
970
|
+
getTableName(schema, modelName),
|
|
971
|
+
model,
|
|
972
|
+
matched[index],
|
|
973
|
+
nextRows[index]
|
|
974
|
+
);
|
|
975
|
+
}
|
|
976
|
+
return nextRows.length;
|
|
977
|
+
},
|
|
978
|
+
async upsert(schema, modelName, args) {
|
|
979
|
+
const model = getSupportedManifest(schema).models[modelName];
|
|
980
|
+
const lookup = requireUniqueLookup(model, args.where, "Upsert");
|
|
981
|
+
validateUniqueLookupUpdateData(
|
|
982
|
+
model,
|
|
983
|
+
args.update,
|
|
984
|
+
lookup,
|
|
985
|
+
"Upsert"
|
|
986
|
+
);
|
|
987
|
+
const current = await loadUniqueRow(schema, modelName, args.where);
|
|
988
|
+
if (current && matchesModelWhere(model, current.data, args.where)) {
|
|
989
|
+
const rows2 = await loadRows(schema, modelName);
|
|
990
|
+
const next = buildUpdatedRow(
|
|
991
|
+
model,
|
|
992
|
+
current,
|
|
993
|
+
args.update
|
|
994
|
+
);
|
|
995
|
+
const conflict2 = findUniqueConflict(model, next.decoded, rows2, /* @__PURE__ */ new Set([current.docId]));
|
|
996
|
+
if (conflict2) {
|
|
997
|
+
throw dynamodbConstraintError(conflict2);
|
|
998
|
+
}
|
|
999
|
+
await updateRecordWithLocks(getTableName(schema, modelName), model, current, next);
|
|
1000
|
+
return projectRow(schema, modelName, next.decoded, args.select);
|
|
1001
|
+
}
|
|
1002
|
+
const created = buildStoredRow(
|
|
1003
|
+
model,
|
|
1004
|
+
mergeUniqueLookupCreateData(
|
|
1005
|
+
model,
|
|
1006
|
+
args.create,
|
|
1007
|
+
lookup,
|
|
1008
|
+
"Upsert"
|
|
1009
|
+
)
|
|
1010
|
+
);
|
|
1011
|
+
const rows = await loadRows(schema, modelName);
|
|
1012
|
+
const conflict = findUniqueConflict(model, created.decoded, rows);
|
|
1013
|
+
if (conflict) {
|
|
1014
|
+
throw dynamodbConstraintError(conflict);
|
|
1015
|
+
}
|
|
1016
|
+
await createRecordWithLocks(getTableName(schema, modelName), created, model);
|
|
1017
|
+
return projectRow(schema, modelName, created.decoded, args.select);
|
|
1018
|
+
},
|
|
1019
|
+
async delete(schema, modelName, args) {
|
|
1020
|
+
const model = getSupportedManifest(schema).models[modelName];
|
|
1021
|
+
const row = applyModelQuery(model, await loadRows(schema, modelName), {
|
|
1022
|
+
where: args.where,
|
|
1023
|
+
take: 1
|
|
1024
|
+
})[0];
|
|
1025
|
+
if (!row) return 0;
|
|
1026
|
+
await deleteRecordWithLocks(getTableName(schema, modelName), model, row);
|
|
1027
|
+
return 1;
|
|
1028
|
+
},
|
|
1029
|
+
async deleteMany(schema, modelName, args) {
|
|
1030
|
+
const model = getSupportedManifest(schema).models[modelName];
|
|
1031
|
+
const rows = applyModelQuery(model, await loadRows(schema, modelName), {
|
|
1032
|
+
where: args.where
|
|
1033
|
+
});
|
|
1034
|
+
for (const row of rows) {
|
|
1035
|
+
await deleteRecordWithLocks(getTableName(schema, modelName), model, row);
|
|
1036
|
+
}
|
|
1037
|
+
return rows.length;
|
|
1038
|
+
},
|
|
1039
|
+
async transaction(schema, run) {
|
|
1040
|
+
getSupportedManifest(schema);
|
|
1041
|
+
return run(driver);
|
|
1042
|
+
}
|
|
1043
|
+
};
|
|
1044
|
+
return driver;
|
|
1045
|
+
}
|
|
1046
|
+
function createDynamodbDriver(config) {
|
|
1047
|
+
return createDynamoDbDriverInternal(config);
|
|
1048
|
+
}
|
|
1049
|
+
export {
|
|
1050
|
+
createDynamodbDriver,
|
|
1051
|
+
normalizeDynamoDbDocumentClient
|
|
1052
|
+
};
|
|
1053
|
+
//# sourceMappingURL=index.js.map
|