@qrvey/data-persistence 0.5.8 → 0.5.9-bundled

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.
Files changed (29) hide show
  1. package/dist/cjs/index.js +3 -1
  2. package/dist/cjs/index.js.map +1 -1
  3. package/dist/cjs/services/crud.service.js +2 -2
  4. package/dist/cjs/services/crud.service.js.map +1 -1
  5. package/dist/cjs/services/crudFactory.service.js +5 -44
  6. package/dist/cjs/services/crudFactory.service.js.map +1 -1
  7. package/dist/cjs/services/cruds/dynamodb/dynamoDbCrud.service.js +6 -7
  8. package/dist/cjs/services/cruds/dynamodb/dynamoDbCrud.service.js.map +1 -1
  9. package/dist/cjs/services/cruds/index.js +19 -0
  10. package/dist/cjs/services/cruds/index.js.map +1 -0
  11. package/dist/cjs/services/cruds/postgresql/postgreSqlClient.service.js +21 -21
  12. package/dist/cjs/services/cruds/postgresql/postgreSqlClient.service.js.map +1 -1
  13. package/dist/cjs/services/cruds/postgresql/postgreSqlCrud.service.js +4 -2
  14. package/dist/cjs/services/cruds/postgresql/postgreSqlCrud.service.js.map +1 -1
  15. package/dist/cjs/services/cruds/postgresql/query.service.js +2 -2
  16. package/dist/cjs/services/cruds/postgresql/query.service.js.map +1 -1
  17. package/dist/esm/index.d.mts +3 -2
  18. package/dist/esm/index.mjs +1799 -14
  19. package/dist/esm/index.mjs.map +1 -1
  20. package/dist/types/index.d.ts +3 -2
  21. package/package.json +5 -19
  22. package/dist/esm/chunk-2H6RO6ZL.mjs +0 -56
  23. package/dist/esm/chunk-2H6RO6ZL.mjs.map +0 -1
  24. package/dist/esm/chunk-2OYWEFNZ.mjs +0 -105
  25. package/dist/esm/chunk-2OYWEFNZ.mjs.map +0 -1
  26. package/dist/esm/dynamoDbCrud.service-NRSGRPDQ.mjs +0 -796
  27. package/dist/esm/dynamoDbCrud.service-NRSGRPDQ.mjs.map +0 -1
  28. package/dist/esm/postgreSqlCrud.service-AD2CHR2Z.mjs +0 -857
  29. package/dist/esm/postgreSqlCrud.service-AD2CHR2Z.mjs.map +0 -1
@@ -1,5 +1,110 @@
1
- import { FILTER_LOGIC_OPERATORS, CONNECTION_CLOSING_MODES, __spreadValues, __objRest, isMultiPlatformMode, __spreadProps } from './chunk-2OYWEFNZ.mjs';
2
- import { Pool } from 'pg';
1
+ import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
2
+ import { DynamoDBDocumentClient, GetCommand, QueryCommand, ScanCommand, PutCommand, UpdateCommand, DeleteCommand, BatchWriteCommand } from '@aws-sdk/lib-dynamodb';
3
+ import { literal, ident, format } from '@scaleleap/pg-format';
4
+ import { Pool, Client } from 'pg';
5
+ export { Pool } from 'pg';
6
+
7
+ var __defProp = Object.defineProperty;
8
+ var __defProps = Object.defineProperties;
9
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
10
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
13
+ var __typeError = (msg) => {
14
+ throw TypeError(msg);
15
+ };
16
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
17
+ var __spreadValues = (a, b) => {
18
+ for (var prop in b || (b = {}))
19
+ if (__hasOwnProp.call(b, prop))
20
+ __defNormalProp(a, prop, b[prop]);
21
+ if (__getOwnPropSymbols)
22
+ for (var prop of __getOwnPropSymbols(b)) {
23
+ if (__propIsEnum.call(b, prop))
24
+ __defNormalProp(a, prop, b[prop]);
25
+ }
26
+ return a;
27
+ };
28
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
29
+ var __objRest = (source, exclude) => {
30
+ var target = {};
31
+ for (var prop in source)
32
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
33
+ target[prop] = source[prop];
34
+ if (source != null && __getOwnPropSymbols)
35
+ for (var prop of __getOwnPropSymbols(source)) {
36
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
37
+ target[prop] = source[prop];
38
+ }
39
+ return target;
40
+ };
41
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
42
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
43
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
44
+
45
+ // src/utils/constants.ts
46
+ var FILTER_OPERATOR_MAP = {
47
+ CONTAINS: "contains",
48
+ NOT_CONTAINS: "notContains",
49
+ EQUAL: "eq",
50
+ STARTS_WITH: "beginsWith",
51
+ NOT_EQUAL: "notEq",
52
+ IN: "in",
53
+ GREATER_THAN: "gt",
54
+ GT: "gt",
55
+ GREATER_THAN_EQUAL: "gte",
56
+ GTE: "gte",
57
+ LESS_THAN: "lt",
58
+ LT: "lt",
59
+ LESS_THAN_EQUAL: "lte",
60
+ LTE: "lte",
61
+ EXIST: "attribute_exists",
62
+ NOT_EXIST: "attribute_not_exists",
63
+ BETWEEN: "between"
64
+ };
65
+ var DYNAMODB_OPERATORS = {
66
+ EQUAL: "EQUAL"
67
+ };
68
+ var CONNECTION_CLOSING_MODES = /* @__PURE__ */ ((CONNECTION_CLOSING_MODES2) => {
69
+ CONNECTION_CLOSING_MODES2["AUTO"] = "AUTO";
70
+ CONNECTION_CLOSING_MODES2["MANUAL"] = "MANUAL";
71
+ return CONNECTION_CLOSING_MODES2;
72
+ })(CONNECTION_CLOSING_MODES || {});
73
+ var FILTER_LOGIC_OPERATORS = /* @__PURE__ */ ((FILTER_LOGIC_OPERATORS2) => {
74
+ FILTER_LOGIC_OPERATORS2["AND"] = "AND";
75
+ FILTER_LOGIC_OPERATORS2["OR"] = "OR";
76
+ return FILTER_LOGIC_OPERATORS2;
77
+ })(FILTER_LOGIC_OPERATORS || {});
78
+ var POSTGRES_FILTER_OPERATOR_MAP = {
79
+ EQUAL: "=",
80
+ NOT_EQUAL: "<>",
81
+ GREATER_THAN: ">",
82
+ GT: ">",
83
+ GTE: ">=",
84
+ GREATER_THAN_EQUAL: ">=",
85
+ LTE: "<=",
86
+ LESS_THAN_EQUAL: "<=",
87
+ LESS_THAN: "<",
88
+ LT: "<",
89
+ IN: "IN",
90
+ STARTS_WITH: "LIKE",
91
+ CONTAINS: "LIKE",
92
+ NOT_CONTAINS: "NOT LIKE",
93
+ BETWEEN: "BETWEEN",
94
+ EXIST: "IS NOT NULL",
95
+ NOT_EXIST: "IS NULL"
96
+ };
97
+ var DEFAULT_PG_SCHEMA = "public";
98
+ var DYNAMO_DB_UPDATE_ACTIONS = {
99
+ SET: "SET",
100
+ ADD: "ADD",
101
+ DELETE: "DELETE",
102
+ REMOVE: "REMOVE"
103
+ };
104
+ function isMultiPlatformMode() {
105
+ var _a;
106
+ return ((_a = process.env.PLATFORM_TYPE) == null ? void 0 : _a.toLowerCase()) === "container";
107
+ }
3
108
 
4
109
  // src/helpers/crudHelpers.ts
5
110
  function buildFilter(attribute, value, operator = "EQUAL", relativePath = void 0) {
@@ -22,21 +127,1701 @@ function buildSort(column, direction = "ASC" /* ASC */) {
22
127
  direction
23
128
  };
24
129
  }
130
+ var AWS_REGION = process.env.AWS_DEFAULT_REGION;
131
+ var DynamoDbClientService = class {
132
+ constructor(tableName) {
133
+ if (!tableName)
134
+ throw new Error(
135
+ 'The "tableName" is required to use a DynamoDbClientService.'
136
+ );
137
+ this.tableName = tableName;
138
+ const client = new DynamoDBClient({ region: AWS_REGION });
139
+ this.dynamoDBClient = DynamoDBDocumentClient.from(client, {
140
+ marshallOptions: {
141
+ removeUndefinedValues: true
142
+ }
143
+ });
144
+ }
145
+ /**
146
+ * Get an item by key
147
+ * @param {Object} keyObject - Ex: { jobId: 1234 }
148
+ * @param {GetCommandInput} options
149
+ */
150
+ async getByKey(keyObject, options = {}) {
151
+ const params = __spreadValues({
152
+ TableName: this.tableName,
153
+ Key: keyObject
154
+ }, options);
155
+ const result = await this.dynamoDBClient.send(new GetCommand(params));
156
+ return result.Item;
157
+ }
158
+ /**
159
+ * Query a table
160
+ * @param {QueryCommandInput} options
161
+ */
162
+ async query(options = {}) {
163
+ const params = __spreadValues({
164
+ TableName: this.tableName
165
+ }, options);
166
+ const result = await this.dynamoDBClient.send(new QueryCommand(params));
167
+ if (result.$metadata) delete result.$metadata;
168
+ return result;
169
+ }
170
+ /**
171
+ * Scan a table
172
+ * @param {ScanInput} options
173
+ */
174
+ async scan(input) {
175
+ const params = __spreadProps(__spreadValues({}, input), {
176
+ TableName: this.tableName
177
+ });
178
+ const command = new ScanCommand(params);
179
+ const response = await this.dynamoDBClient.send(command);
180
+ if (response.$metadata) delete response.$metadata;
181
+ return response;
182
+ }
183
+ /**
184
+ * Create/Replace a item object
185
+ * To take care:
186
+ * - https://stackoverflow.com/questions/43667229/difference-between-dynamodb-putitem-vs-updateitem
187
+ * @param {Object} input
188
+ */
189
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
190
+ async put(input) {
191
+ const params = {
192
+ TableName: this.tableName,
193
+ Item: input,
194
+ ReturnValues: "NONE"
195
+ };
196
+ return await this.dynamoDBClient.send(new PutCommand(params));
197
+ }
198
+ /**
199
+ * Update a item object
200
+ * To take care:
201
+ * - https://stackoverflow.com/questions/43667229/difference-between-dynamodb-putitem-vs-updateitem
202
+ * @param {Object} keyObject - Ex: { jobId: 1234 }
203
+ * @param {UpdateCommandInput} updateObject
204
+ */
205
+ async update(keyObject, options = {}) {
206
+ const params = __spreadValues({
207
+ TableName: this.tableName,
208
+ Key: keyObject,
209
+ ReturnValues: "NONE"
210
+ }, options);
211
+ return await this.dynamoDBClient.send(new UpdateCommand(params));
212
+ }
213
+ /**
214
+ * Delete/Remove an item object
215
+ */
216
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
217
+ async remove(keyObject) {
218
+ const params = {
219
+ TableName: this.tableName,
220
+ Key: keyObject,
221
+ ReturnValues: "NONE"
222
+ };
223
+ return await this.dynamoDBClient.send(new DeleteCommand(params));
224
+ }
225
+ batchWrittenPut(data) {
226
+ const putRequests = data.map((item) => ({
227
+ PutRequest: {
228
+ Item: item
229
+ }
230
+ }));
231
+ const params = {
232
+ RequestItems: {
233
+ [this.tableName]: putRequests
234
+ }
235
+ };
236
+ const insertCommand = new BatchWriteCommand(params);
237
+ return this.dynamoDBClient.send(insertCommand);
238
+ }
239
+ buildDeleteRequestKeys(filters) {
240
+ const deleteRequestKeys = {};
241
+ filters.forEach((filter) => {
242
+ deleteRequestKeys[filter.attribute] = filter.value;
243
+ });
244
+ return deleteRequestKeys;
245
+ }
246
+ async batchRemove(filterGroups) {
247
+ if (!(filterGroups == null ? void 0 : filterGroups.length)) return;
248
+ const deleteRequests = filterGroups.map((filterGroup) => ({
249
+ DeleteRequest: {
250
+ Key: this.buildDeleteRequestKeys(filterGroup)
251
+ }
252
+ }));
253
+ const params = {
254
+ RequestItems: {
255
+ [this.tableName]: deleteRequests
256
+ }
257
+ };
258
+ await this.dynamoDBClient.send(new BatchWriteCommand(params));
259
+ }
260
+ async updateExpressions(keyObject, options = {}) {
261
+ const params = __spreadValues({
262
+ TableName: this.tableName,
263
+ Key: keyObject
264
+ }, options);
265
+ return await this.dynamoDBClient.send(new UpdateCommand(params));
266
+ }
267
+ };
268
+
269
+ // src/helpers/queryHelpers.ts
270
+ function buildAggFunctionAlias(aggregateFunction) {
271
+ return `AGG_FN_${aggregateFunction}`;
272
+ }
273
+
274
+ // src/services/cruds/dynamodb/queryBuilderCondition.service.ts
275
+ var QueryBuilderConditionService = class {
276
+ constructor(query) {
277
+ this.tempKey = "";
278
+ this.tempLogicOperator = null;
279
+ this.wheres = [];
280
+ this.filters = [];
281
+ this.updates = [];
282
+ this.attributeNames = {};
283
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
284
+ this.attributeValues = {};
285
+ this.query = query;
286
+ this.command = {};
287
+ }
288
+ get() {
289
+ this.build();
290
+ return this.command;
291
+ }
292
+ setKey(key) {
293
+ this.tempKey = key;
294
+ return this;
295
+ }
296
+ setTmpLogicOp(logicOp) {
297
+ this.tempLogicOperator = logicOp;
298
+ return this;
299
+ }
300
+ setConfig(config) {
301
+ this.config = config;
302
+ return this;
303
+ }
304
+ from(methodName) {
305
+ this.queryFrom = methodName;
306
+ return this;
307
+ }
308
+ eq(keyValue) {
309
+ const { key, value } = this.generateKeyValue(keyValue);
310
+ let expression = `${key} = ${value}`;
311
+ if (this.tempLogicOperator)
312
+ expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
313
+ this.setExpression(expression);
314
+ return this.query;
315
+ }
316
+ notEq(keyValue) {
317
+ const { key, value } = this.generateKeyValue(keyValue);
318
+ let expression = `${key} <> ${value}`;
319
+ if (this.tempLogicOperator)
320
+ expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
321
+ this.setExpression(expression);
322
+ return this.query;
323
+ }
324
+ contains(keyValue) {
325
+ const { key, value } = this.generateKeyValue(keyValue);
326
+ let expression = `contains(${key}, ${value})`;
327
+ if (this.tempLogicOperator)
328
+ expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
329
+ this.setExpression(expression);
330
+ return this.query;
331
+ }
332
+ notContains(keyValue) {
333
+ const { key, value } = this.generateKeyValue(keyValue);
334
+ let expression = `NOT contains(${key}, ${value})`;
335
+ if (this.tempLogicOperator)
336
+ expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
337
+ this.setExpression(expression);
338
+ return this.query;
339
+ }
340
+ in(keyValue) {
341
+ const keyValues = Array.isArray(keyValue) ? keyValue : [keyValue];
342
+ const { key, value } = this.generateKeyValue(keyValues);
343
+ let expression = `${key} IN (${value})`;
344
+ if (this.tempLogicOperator)
345
+ expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
346
+ this.setExpression(expression);
347
+ return this.query;
348
+ }
349
+ beginsWith(keyValue) {
350
+ const { key, value } = this.generateKeyValue(keyValue);
351
+ let expression = `begins_with(${key}, ${value})`;
352
+ if (this.tempLogicOperator)
353
+ expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
354
+ this.setExpression(expression);
355
+ return this.query;
356
+ }
357
+ project(keyValue) {
358
+ const key = `#${keyValue}`;
359
+ this.attributeNames[key] = keyValue;
360
+ return key;
361
+ }
362
+ gt(keyValue) {
363
+ const { key, value } = this.generateKeyValue(keyValue);
364
+ let expression = `${key} > ${value}`;
365
+ if (this.tempLogicOperator)
366
+ expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
367
+ this.setExpression(expression);
368
+ return this.query;
369
+ }
370
+ gte(keyValue) {
371
+ const { key, value } = this.generateKeyValue(keyValue);
372
+ let expression = `${key} >= ${value}`;
373
+ if (this.tempLogicOperator)
374
+ expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
375
+ this.setExpression(expression);
376
+ return this.query;
377
+ }
378
+ lte(keyValue) {
379
+ const { key, value } = this.generateKeyValue(keyValue);
380
+ let expression = `${key} <= ${value}`;
381
+ if (this.tempLogicOperator)
382
+ expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
383
+ this.setExpression(expression);
384
+ return this.query;
385
+ }
386
+ lt(keyValue) {
387
+ const { key, value } = this.generateKeyValue(keyValue);
388
+ let expression = `${key} < ${value}`;
389
+ if (this.tempLogicOperator)
390
+ expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
391
+ this.setExpression(expression);
392
+ return this.query;
393
+ }
394
+ attribute_exists(keyValue) {
395
+ const { key } = this.generateKeyValue(keyValue, null, true);
396
+ let expression = `attribute_exists(${key})`;
397
+ if (this.tempLogicOperator)
398
+ expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
399
+ this.setExpression(expression);
400
+ return this.query;
401
+ }
402
+ attribute_not_exists(keyValue) {
403
+ const { key } = this.generateKeyValue(keyValue, null, true);
404
+ let expression = `attribute_not_exists(${key})`;
405
+ if (this.tempLogicOperator)
406
+ expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
407
+ this.setExpression(expression);
408
+ return this.query;
409
+ }
410
+ between(keyValues) {
411
+ const isValidValues = Array.isArray(keyValues) && (keyValues == null ? void 0 : keyValues.length) === 2;
412
+ if (!isValidValues)
413
+ throw new Error(
414
+ "The value for between filter operator should be an Array with 2 values."
415
+ );
416
+ const { key, value } = this.generateKeyValue(keyValues, " AND");
417
+ let expression = `${key} between ${value}`;
418
+ if (this.tempLogicOperator)
419
+ expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
420
+ this.setExpression(expression);
421
+ return this.query;
422
+ }
423
+ setExpression(expression) {
424
+ switch (this.queryFrom) {
425
+ case "filter" /* filter */:
426
+ this.filters.push(expression);
427
+ break;
428
+ case "update" /* update */:
429
+ this.updates.push(expression);
430
+ break;
431
+ default:
432
+ this.wheres.push(expression);
433
+ break;
434
+ }
435
+ }
436
+ generateKeyValue(value, separatorCharacter = ",", omitAttributeValues = false) {
437
+ const keyExpression = `#${this.tempKey}1`;
438
+ this.attributeNames[keyExpression] = this.tempKey;
439
+ if (Array.isArray(value)) {
440
+ const valueExpressions = value.map((val, index) => {
441
+ let valueExpression = `:${this.tempKey}${index + 1}1`;
442
+ for (const [i] of Object.entries(this.attributeValues)) {
443
+ if (i === valueExpression) valueExpression += "1";
444
+ }
445
+ this.attributeValues[valueExpression] = val;
446
+ return valueExpression;
447
+ });
448
+ return {
449
+ key: keyExpression,
450
+ value: valueExpressions.join(`${separatorCharacter} `)
451
+ };
452
+ } else {
453
+ let valueExpression = `:${this.tempKey}1`;
454
+ if (valueExpression in this.attributeValues) {
455
+ for (const [index] of Object.entries(this.attributeValues)) {
456
+ if (index === valueExpression) valueExpression += "1";
457
+ }
458
+ }
459
+ if (!omitAttributeValues)
460
+ this.attributeValues[valueExpression] = value;
461
+ return { key: keyExpression, value: valueExpression };
462
+ }
463
+ }
464
+ build() {
465
+ var _a;
466
+ if (this.wheres.length > 0) {
467
+ const keyConditionExpression = this.wheres.join(" AND ");
468
+ this.command["KeyConditionExpression"] = keyConditionExpression;
469
+ }
470
+ if (this.filters.length > 0) {
471
+ let filterExpression = "";
472
+ (_a = this.filters) == null ? void 0 : _a.forEach((filter, index) => {
473
+ var _a2, _b;
474
+ if (filter == null ? void 0 : filter.logicOperator) {
475
+ if ((_a2 = filter == null ? void 0 : filter.config) == null ? void 0 : _a2.openExpression) {
476
+ filterExpression = filterExpression.replace(/\s+(AND|OR)\s*$/, ` ${filter.config.parentKey} (`);
477
+ if (filterExpression === "") filterExpression += "(";
478
+ filterExpression += `${filter.expression} ${filter.logicOperator} `;
479
+ } else if ((_b = filter == null ? void 0 : filter.config) == null ? void 0 : _b.closeExpression) {
480
+ filterExpression += `${filter.expression}) ${filter.config.parentKey} `;
481
+ } else {
482
+ filterExpression += `${filter.expression} ${filter.logicOperator} `;
483
+ }
484
+ }
485
+ });
486
+ filterExpression = filterExpression.replace(/\s+(AND|OR)\s*$/, "");
487
+ this.command["FilterExpression"] = filterExpression;
488
+ }
489
+ if (this.updates.length > 0) {
490
+ const filterExpression = this.updates.join(", ");
491
+ this.command["UpdateExpression"] = `SET ${filterExpression}`;
492
+ }
493
+ if (Object.values(this.attributeNames).length > 0)
494
+ this.command["ExpressionAttributeNames"] = this.attributeNames;
495
+ if (Object.values(this.attributeValues).length > 0)
496
+ this.command["ExpressionAttributeValues"] = this.attributeValues;
497
+ }
498
+ };
499
+
500
+ // src/services/cruds/dynamodb/queryBuilder.service.ts
501
+ var QueryBuilderService = class {
502
+ constructor(useScan = false) {
503
+ this.useScan = useScan;
504
+ this.command = {};
505
+ this.condition = new QueryBuilderConditionService(this);
506
+ }
507
+ get() {
508
+ const condition = this.condition.get();
509
+ return __spreadValues(__spreadValues({}, this.command), condition);
510
+ }
511
+ limit(num) {
512
+ this.command.Limit = num;
513
+ return this;
514
+ }
515
+ usingIndex(indexName) {
516
+ this.command.IndexName = indexName;
517
+ return this;
518
+ }
519
+ ascending() {
520
+ if (!this.useScan) this.command.ScanIndexForward = true;
521
+ return this;
522
+ }
523
+ descending() {
524
+ if (!this.useScan) this.command.ScanIndexForward = false;
525
+ return this;
526
+ }
527
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
528
+ startKey(lastEvaluatedKey) {
529
+ this.command.ExclusiveStartKey = lastEvaluatedKey;
530
+ return this;
531
+ }
532
+ projection(fields = []) {
533
+ if (!fields.length) return this;
534
+ const expression = [];
535
+ fields.forEach((field) => {
536
+ const key = this.condition.project(field);
537
+ expression.push(key);
538
+ });
539
+ this.command.ProjectionExpression = expression.join(",");
540
+ return this;
541
+ }
542
+ where(keyName) {
543
+ this.condition.setKey(keyName).setTmpLogicOp(null).from("where" /* where */);
544
+ return this.condition;
545
+ }
546
+ filter(keyName, logicOperator = "AND", config) {
547
+ this.condition.setKey(keyName).setTmpLogicOp(logicOperator).setConfig(config).from("filter" /* filter */);
548
+ return this.condition;
549
+ }
550
+ update(attribute) {
551
+ for (const [key, value] of Object.entries(attribute)) {
552
+ this.condition.setKey(key).from("update" /* update */);
553
+ this.condition.eq(value);
554
+ }
555
+ return this;
556
+ }
557
+ consistentRead(consistentRead) {
558
+ this.command.ConsistentRead = consistentRead;
559
+ return this;
560
+ }
561
+ count() {
562
+ this.command.Select = "COUNT" /* COUNT */;
563
+ return this;
564
+ }
565
+ };
566
+
567
+ // src/helpers/tableHelper.ts
568
+ function getTableColumnNames(columns) {
569
+ return Object.keys(columns);
570
+ }
571
+ function findIdColumnName(columns) {
572
+ return getTableColumnNames(columns).find(
573
+ (columnName) => columns[columnName].columnId === true
574
+ );
575
+ }
576
+ function getTableName(table, property = "name") {
577
+ if (!table) throw new Error("missing table property");
578
+ if (typeof table === "string") return table;
579
+ const { name, alias } = table;
580
+ return property === "alias" && alias ? alias : name;
581
+ }
582
+ function getPrimaryKeyColumns(columns) {
583
+ return getTableColumnNames(columns).filter(
584
+ (columnName) => columns[columnName].primary === true
585
+ );
586
+ }
587
+
588
+ // src/error/NoRecordsAffectedException.ts
589
+ var NoRecordsAffectedException = class extends Error {
590
+ constructor() {
591
+ super("No records affected by update");
592
+ this.name = "NoRecordsAffectedException";
593
+ }
594
+ };
595
+
596
+ // src/helpers/errorHelper.ts
597
+ function PersistenceErrorWrapper(queryResult) {
598
+ const dynamoNoRecordsAffectedExceptions = [
599
+ "ConditionalCheckFailedException"
600
+ ];
601
+ if (queryResult instanceof Error) {
602
+ if (queryResult.name && dynamoNoRecordsAffectedExceptions.includes(queryResult.name)) {
603
+ throw new NoRecordsAffectedException();
604
+ } else {
605
+ throw queryResult;
606
+ }
607
+ } else {
608
+ if (queryResult.rowCount === 0) {
609
+ throw new NoRecordsAffectedException();
610
+ }
611
+ }
612
+ return queryResult;
613
+ }
614
+
615
+ // src/services/cruds/dynamodb/dynamoDbCrud.service.ts
616
+ var _DynamoDbCrudService_instances, prepareAndExecuteUpdateExpression_fn, buildUpdateExpressionQuery_fn, getKeyObjectForUpdateExpression_fn, getUpdateExpressionOptions_fn, extractUpdateExpressionAttributesAndNames_fn;
617
+ var DynamoDbCrudService = class {
618
+ constructor(tableSchema) {
619
+ this.tableSchema = tableSchema;
620
+ __privateAdd(this, _DynamoDbCrudService_instances);
621
+ this.dynamoDbClientService = new DynamoDbClientService(this.tableName);
622
+ }
623
+ get tableName() {
624
+ return getTableName(this.tableSchema.table);
625
+ }
626
+ get idColumnName() {
627
+ return findIdColumnName(this.tableSchema.columns);
628
+ }
629
+ get defaultPrimaryKeys() {
630
+ return getPrimaryKeyColumns(this.tableSchema.columns);
631
+ }
632
+ async create(data) {
633
+ var _a;
634
+ if (Array.isArray(data)) {
635
+ const response = await this.dynamoDbClientService.batchWrittenPut(data);
636
+ return {
637
+ unprocessedItems: (_a = response.UnprocessedItems) != null ? _a : []
638
+ };
639
+ } else {
640
+ await this.dynamoDbClientService.put(data);
641
+ return data;
642
+ }
643
+ }
644
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars
645
+ runQuery(queryCommand) {
646
+ throw new Error("Method not implemented.");
647
+ }
648
+ find(options = {}) {
649
+ var _a, _b, _c, _d;
650
+ const query = new QueryBuilderService(options.useScan);
651
+ if ((_a = options.index) == null ? void 0 : _a.indexName)
652
+ query.usingIndex((_b = options.index) == null ? void 0 : _b.indexName);
653
+ this.applySorting(query, options.sorting, (_c = options.index) == null ? void 0 : _c.indexName);
654
+ this.applyPagination(query, options.pagination);
655
+ if (options.consistentRead)
656
+ query.consistentRead(options.consistentRead);
657
+ if (options.fields) query.projection(options.fields);
658
+ this.applyFilters(query, options);
659
+ if (options.aggregateFunction === "COUNT" /* COUNT */)
660
+ query.count();
661
+ return this.fetchResults(
662
+ query.get(),
663
+ (_d = options.pagination) == null ? void 0 : _d.limit,
664
+ options.useScan
665
+ ).then((res) => {
666
+ var _a2, _b2;
667
+ const pagination = {};
668
+ if (res.lastEvaluatedKey) pagination.from = res.lastEvaluatedKey;
669
+ if ((_a2 = options.pagination) == null ? void 0 : _a2.limit)
670
+ pagination.limit = (_b2 = options.pagination) == null ? void 0 : _b2.limit;
671
+ return {
672
+ items: res.items,
673
+ pagination,
674
+ count: res.count
675
+ };
676
+ });
677
+ }
678
+ async fetchResults(command, limit = 100, useScan = false) {
679
+ var _a, _b;
680
+ let results = [];
681
+ let lastEvaluatedKey = {};
682
+ let rowsCount = 0;
683
+ do {
684
+ const result = await this.fetchBatch(
685
+ command,
686
+ useScan,
687
+ lastEvaluatedKey
688
+ );
689
+ const rows = (_a = result.Items) != null ? _a : [];
690
+ results = results.concat(rows);
691
+ lastEvaluatedKey = (_b = result.LastEvaluatedKey) != null ? _b : {};
692
+ rowsCount += result.Count || rows.length;
693
+ } while (rowsCount < limit && this.isNotEmptyObject(lastEvaluatedKey));
694
+ const encryptedLastEvaluatedKey = this.isNotEmptyObject(
695
+ lastEvaluatedKey
696
+ ) ? this.encryptPaginationKey(lastEvaluatedKey) : null;
697
+ return {
698
+ items: results,
699
+ lastEvaluatedKey: encryptedLastEvaluatedKey,
700
+ count: rowsCount
701
+ };
702
+ }
703
+ async fetchBatch(command, useScan, lastEvaluatedKey) {
704
+ var _a, _b, _c;
705
+ if (this.isNotEmptyObject(lastEvaluatedKey))
706
+ command.ExclusiveStartKey = lastEvaluatedKey;
707
+ const result = await (useScan ? this.dynamoDbClientService.scan(command) : this.dynamoDbClientService.query(command));
708
+ if (command.Select !== "COUNT" /* COUNT */) {
709
+ command.Limit = ((_a = command.Limit) != null ? _a : 0) - ((_c = (_b = result.Items) == null ? void 0 : _b.length) != null ? _c : 0);
710
+ }
711
+ return result;
712
+ }
713
+ applyPagination(query, pagination) {
714
+ if (pagination == null ? void 0 : pagination.limit) query.limit(pagination.limit);
715
+ if (pagination == null ? void 0 : pagination.from)
716
+ query.startKey(this.decryptPaginationKey(pagination.from));
717
+ }
718
+ async findAll(options = {}, allResults = [], rowsCount = 0) {
719
+ const { items, pagination, count } = await this.find(options);
720
+ allResults.push(...items);
721
+ rowsCount += count;
722
+ if (pagination == null ? void 0 : pagination.from)
723
+ await this.findAll(__spreadProps(__spreadValues({}, options), { pagination }), allResults);
724
+ return {
725
+ items: allResults,
726
+ pagination: null,
727
+ count: rowsCount
728
+ };
729
+ }
730
+ async findCount(options = {}) {
731
+ var _a;
732
+ const findOptions = __spreadProps(__spreadValues({}, options), {
733
+ aggregateFunction: "COUNT" /* COUNT */
734
+ });
735
+ if ((_a = options.pagination) == null ? void 0 : _a.from) {
736
+ return this.find(findOptions).then((res) => res.count);
737
+ } else {
738
+ return this.findAll(findOptions).then((res) => res.count);
739
+ }
740
+ }
741
+ buildFindItemQuery(options) {
742
+ var _a;
743
+ const query = new QueryBuilderService();
744
+ if ((_a = options.index) == null ? void 0 : _a.indexName) query.usingIndex(options.index.indexName);
745
+ this.applyFilters(query, options);
746
+ query.projection(options.fields);
747
+ query.limit(1);
748
+ return query;
749
+ }
750
+ findItem(options) {
751
+ const query = this.buildFindItemQuery(options);
752
+ return this.dynamoDbClientService.query(query.get()).then((result) => {
753
+ var _a;
754
+ if ((_a = result.Items) == null ? void 0 : _a.length) return result.Items[0];
755
+ if (options.throwErrorIfNull) throw new Error("NOT_FOUND");
756
+ return null;
757
+ });
758
+ }
759
+ applyWhereFilter(query, filter) {
760
+ var _a, _b;
761
+ const operator = FILTER_OPERATOR_MAP[(_b = (_a = filter.operator) == null ? void 0 : _a.toUpperCase()) != null ? _b : DYNAMODB_OPERATORS.EQUAL];
762
+ query.where(filter.attribute)[operator](filter.value);
763
+ }
764
+ applyFilterFilter(query, filter, logicOperator = "AND", config) {
765
+ var _a, _b;
766
+ const operator = FILTER_OPERATOR_MAP[(_b = (_a = filter.operator) == null ? void 0 : _a.toUpperCase()) != null ? _b : DYNAMODB_OPERATORS.EQUAL];
767
+ query.filter(filter.attribute, logicOperator, config)[operator](filter.value);
768
+ }
769
+ applyFilters(query, options) {
770
+ if (Array.isArray(options.filters)) {
771
+ this.applySimpleFilters(query, options);
772
+ } else {
773
+ this.applyCompoundFilters(query, options);
774
+ }
775
+ }
776
+ applySimpleFilters(query, options) {
777
+ var _a, _b;
778
+ const queryIndexColumns = (_b = (_a = options.index) == null ? void 0 : _a.columns) != null ? _b : [];
779
+ const defaultWhereProperties = this.defaultPrimaryKeys;
780
+ const whereProperties = (queryIndexColumns == null ? void 0 : queryIndexColumns.length) ? queryIndexColumns : defaultWhereProperties;
781
+ const filters = options.filters;
782
+ filters.forEach((filter) => {
783
+ const isWhereProperty = whereProperties.includes(filter.attribute);
784
+ isWhereProperty && !options.useScan ? this.applyWhereFilter(query, filter) : this.applyFilterFilter(query, filter);
785
+ });
786
+ }
787
+ applyCompoundFilters(query, options) {
788
+ if (!options.filters) return;
789
+ this.buildFilterExpression(query, options);
790
+ }
791
+ buildFilterExpression(query, options, parentKey) {
792
+ var _a;
793
+ const compositeFilters = options.filters;
794
+ const queryIndexColumns = ((_a = options.index) == null ? void 0 : _a.columns) || [];
795
+ const defaultWhereProperties = this.defaultPrimaryKeys;
796
+ const whereProperties = (queryIndexColumns == null ? void 0 : queryIndexColumns.length) ? queryIndexColumns : defaultWhereProperties;
797
+ for (const [key, value] of Object.entries(compositeFilters)) {
798
+ value.forEach(
799
+ (filter, index) => {
800
+ const isCompositeFilter = "OR" in filter || "AND" in filter;
801
+ if (isCompositeFilter) {
802
+ const newOptions = __spreadProps(__spreadValues({}, options), {
803
+ filters: filter
804
+ });
805
+ this.buildFilterExpression(query, newOptions, key);
806
+ } else {
807
+ const simpleFilter = filter;
808
+ const isWhereProperty = whereProperties.includes(
809
+ simpleFilter.attribute
810
+ );
811
+ let config;
812
+ if (parentKey) {
813
+ config = {
814
+ parentKey,
815
+ openExpression: index === 0,
816
+ closeExpression: index === value.length - 1
817
+ };
818
+ }
819
+ isWhereProperty && !options.useScan ? this.applyWhereFilter(query, simpleFilter) : this.applyFilterFilter(
820
+ query,
821
+ simpleFilter,
822
+ key,
823
+ config
824
+ );
825
+ }
826
+ }
827
+ );
828
+ }
829
+ }
830
+ applySorting(query, sorting, sortIndex) {
831
+ if (sorting == null ? void 0 : sorting.length) {
832
+ if (sortIndex) query.usingIndex(sortIndex);
833
+ if (sorting[0].direction === "DESC") {
834
+ query.descending();
835
+ } else {
836
+ query.ascending();
837
+ }
838
+ }
839
+ }
840
+ isNotEmptyObject(obj) {
841
+ return obj !== null && typeof obj === "object" && Object.keys(obj).length > 0;
842
+ }
843
+ encryptPaginationKey(key) {
844
+ const jsonKey = JSON.stringify(key);
845
+ return Buffer.from(jsonKey).toString("base64");
846
+ }
847
+ decryptPaginationKey(encodedKey) {
848
+ const decodedKey = Buffer.from(encodedKey, "base64").toString("utf-8");
849
+ return JSON.parse(decodedKey);
850
+ }
851
+ async update(filters, data, { skipFindItems = false }) {
852
+ const savedRecord = skipFindItems ? {} : await this.findItem({
853
+ filters
854
+ });
855
+ const newData = __spreadValues(__spreadValues({}, savedRecord), data);
856
+ await this.dynamoDbClientService.put(newData);
857
+ return newData;
858
+ }
859
+ async remove(filters, options) {
860
+ if (options == null ? void 0 : options.filterGroups) {
861
+ await this.dynamoDbClientService.batchRemove(
862
+ filters
863
+ );
864
+ } else {
865
+ const key = filters.reduce((obj, item) => {
866
+ const property = item.attribute;
867
+ obj[property] = item.value;
868
+ return obj;
869
+ }, {});
870
+ await this.dynamoDbClientService.remove(key);
871
+ }
872
+ }
873
+ async updateExpressions(filters, actions, options) {
874
+ try {
875
+ return await __privateMethod(this, _DynamoDbCrudService_instances, prepareAndExecuteUpdateExpression_fn).call(this, filters, actions, options);
876
+ } catch (error) {
877
+ PersistenceErrorWrapper(error);
878
+ }
879
+ }
880
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
881
+ runRawQuery(query, params) {
882
+ throw new Error("Method not implemented.");
883
+ }
884
+ };
885
+ _DynamoDbCrudService_instances = new WeakSet();
886
+ prepareAndExecuteUpdateExpression_fn = async function(filters, actions, options) {
887
+ const queryObject = __privateMethod(this, _DynamoDbCrudService_instances, buildUpdateExpressionQuery_fn).call(this, { filters }).get();
888
+ const primaryKeys = this.defaultPrimaryKeys;
889
+ const keyObject = __privateMethod(this, _DynamoDbCrudService_instances, getKeyObjectForUpdateExpression_fn).call(this, queryObject, primaryKeys);
890
+ const updateExpressions = [];
891
+ Object.keys(actions).forEach((action) => {
892
+ const actionUpdateExpression = __privateMethod(this, _DynamoDbCrudService_instances, extractUpdateExpressionAttributesAndNames_fn).call(this, actions, action);
893
+ updateExpressions.push(actionUpdateExpression);
894
+ });
895
+ const dbParams = __spreadValues({
896
+ UpdateExpression: updateExpressions.join(" ")
897
+ }, __privateMethod(this, _DynamoDbCrudService_instances, getUpdateExpressionOptions_fn).call(this, options));
898
+ const { ExpressionAttributeValues, ExpressionAttributeNames } = queryObject;
899
+ if (Object.keys(ExpressionAttributeValues).length > 0) {
900
+ dbParams["ExpressionAttributeValues"] = __spreadValues(__spreadValues({}, ExpressionAttributeValues), dbParams.ExpressionAttributeValues);
901
+ }
902
+ if (Object.keys(ExpressionAttributeNames).length > 0) {
903
+ dbParams["ExpressionAttributeNames"] = __spreadValues(__spreadValues({}, ExpressionAttributeNames), dbParams.ExpressionAttributeNames);
904
+ }
905
+ if (queryObject.FilterExpression)
906
+ dbParams["ConditionExpression"] = queryObject.FilterExpression;
907
+ return this.dynamoDbClientService.updateExpressions(
908
+ keyObject,
909
+ dbParams
910
+ );
911
+ };
912
+ buildUpdateExpressionQuery_fn = function(options) {
913
+ var _a;
914
+ const query = new QueryBuilderService();
915
+ if ((_a = options.index) == null ? void 0 : _a.indexName) query.usingIndex(options.index.indexName);
916
+ this.applyFilters(query, options);
917
+ return query;
918
+ };
919
+ getKeyObjectForUpdateExpression_fn = function(queryObject, primaryKeys) {
920
+ const keyObject = {};
921
+ Object.keys(queryObject.ExpressionAttributeNames).forEach(
922
+ (attribute) => {
923
+ const sanitizedAttribute = attribute.replace("#", "").replace("1", "");
924
+ if (primaryKeys.includes(sanitizedAttribute)) {
925
+ const valueName = `:${sanitizedAttribute}1`;
926
+ keyObject[sanitizedAttribute] = queryObject.ExpressionAttributeValues[valueName];
927
+ delete queryObject.ExpressionAttributeValues[valueName];
928
+ delete queryObject.ExpressionAttributeNames[attribute];
929
+ }
930
+ }
931
+ );
932
+ return keyObject;
933
+ };
934
+ getUpdateExpressionOptions_fn = function(options) {
935
+ const updateExprOptions = {
936
+ ReturnValues: options.returnValues
937
+ };
938
+ if (options.expressionAttributeNames)
939
+ updateExprOptions.ExpressionAttributeNames = options.expressionAttributeNames;
940
+ if (options.expressionAttributeValues)
941
+ updateExprOptions.ExpressionAttributeValues = options.expressionAttributeValues;
942
+ return updateExprOptions;
943
+ };
944
+ extractUpdateExpressionAttributesAndNames_fn = function(actions, actionType) {
945
+ const actionUpdateExpressions = [];
946
+ actions[actionType].forEach((action) => {
947
+ switch (actionType) {
948
+ case DYNAMO_DB_UPDATE_ACTIONS.DELETE:
949
+ case DYNAMO_DB_UPDATE_ACTIONS.REMOVE:
950
+ actionUpdateExpressions.push(`${action.path}`);
951
+ break;
952
+ case DYNAMO_DB_UPDATE_ACTIONS.ADD:
953
+ case DYNAMO_DB_UPDATE_ACTIONS.SET:
954
+ {
955
+ let operator = "";
956
+ if (actionType == DYNAMO_DB_UPDATE_ACTIONS.SET)
957
+ operator = "=";
958
+ actionUpdateExpressions.push(
959
+ `${action.path} ${operator}${action.value}`
960
+ );
961
+ }
962
+ break;
963
+ }
964
+ });
965
+ const actionUpdateExpression = `${actionType} ${actionUpdateExpressions.join(
966
+ ", "
967
+ )}`;
968
+ return actionUpdateExpression;
969
+ };
970
+ var ConnectionService = class {
971
+ get connectionString() {
972
+ const connectionString = process.env.MULTIPLATFORM_PG_CONNECTION_STRING || "";
973
+ if (!connectionString) {
974
+ throw new Error(
975
+ "MULTIPLATFORM_PG_CONNECTION_STRING environment variable must be configured"
976
+ );
977
+ }
978
+ return connectionString;
979
+ }
980
+ async getClient() {
981
+ const client = new Client({
982
+ connectionString: this.connectionString
983
+ });
984
+ await client.connect();
985
+ return client;
986
+ }
987
+ releaseClient(client) {
988
+ try {
989
+ client.end();
990
+ } catch (e) {
991
+ console.log("Error releasing client");
992
+ }
993
+ }
994
+ };
995
+
996
+ // src/services/cruds/postgresql/query.service.ts
997
+ var QueryService = class {
998
+ constructor(pool) {
999
+ this.pool = pool;
1000
+ this.connectionService = new ConnectionService();
1001
+ }
1002
+ async runQuery(queryText, values) {
1003
+ const client = await (this.pool ? this.pool.connect() : this.connectionService.getClient());
1004
+ try {
1005
+ if (process.env.NODE_ENV === "development")
1006
+ console.info("[data-persistence] Query as Text:", queryText);
1007
+ const result = await client.query(queryText, values);
1008
+ return result;
1009
+ } finally {
1010
+ if (this.pool) {
1011
+ await client.release();
1012
+ } else {
1013
+ this.connectionService.releaseClient(client);
1014
+ }
1015
+ }
1016
+ }
1017
+ };
1018
+
1019
+ // src/services/cruds/postgresql/postgreSqlClient.service.ts
1020
+ var PostgresqlClientService = class extends QueryService {
1021
+ constructor(tableSchema, poolClient) {
1022
+ super(poolClient);
1023
+ this.isCompositeFilter = function(value) {
1024
+ return "OR" in value || "AND" in value;
1025
+ };
1026
+ this.crudSchema = tableSchema;
1027
+ }
1028
+ get dbSchema() {
1029
+ return this.crudSchema.schema || DEFAULT_PG_SCHEMA;
1030
+ }
1031
+ get tableName() {
1032
+ return getTableName(this.crudSchema.table, "alias") || getTableName(this.crudSchema.table);
1033
+ }
1034
+ get isTemporalTable() {
1035
+ var _a;
1036
+ return (_a = this.crudSchema) == null ? void 0 : _a.isTemporalTable;
1037
+ }
1038
+ getWildcardValue(operator, value) {
1039
+ if (operator === "CONTAINS" /* CONTAINS */ || operator === "NOT_CONTAINS" /* NOT_CONTAINS */) {
1040
+ return "%" + value + "%";
1041
+ } else if (operator === "STARTS_WITH" /* STARTS_WITH */) {
1042
+ return value + "%";
1043
+ } else {
1044
+ return value;
1045
+ }
1046
+ }
1047
+ buildClause(operator, attribute, relativePath, value) {
1048
+ var _a;
1049
+ const formattedValue = literal(value);
1050
+ operator = operator ? operator.toUpperCase() : "EQUAL" /* EQUAL */;
1051
+ const postgresOperator = POSTGRES_FILTER_OPERATOR_MAP[operator];
1052
+ if (!postgresOperator)
1053
+ throw new Error(`Unsupported filter operator: ${operator}`);
1054
+ let property;
1055
+ const filterProperty = ident(attribute);
1056
+ const columnExists = !!this.crudSchema.columns[attribute];
1057
+ const columnType = columnExists && ((_a = this.crudSchema.columns[attribute]) == null ? void 0 : _a.type);
1058
+ if (relativePath != void 0) {
1059
+ const attributePath = relativePath.split(".").join(",");
1060
+ property = `("${attribute}" #> '{${attributePath}}')`;
1061
+ if (value != null) {
1062
+ const comparisonValueType = this.getValueTypeAsPostgresDefinition(value);
1063
+ property += `::${comparisonValueType}`;
1064
+ }
1065
+ } else {
1066
+ property = columnExists ? filterProperty : `("qvAttributes" ->> '${attribute}')`;
1067
+ }
1068
+ if (operator === "IN" /* IN */) {
1069
+ const formattedValues = Array.isArray(value) ? value.map(literal) : [formattedValue];
1070
+ return `${property} ${postgresOperator} (${formattedValues.join(
1071
+ ", "
1072
+ )})`;
1073
+ }
1074
+ if (operator === "BETWEEN" /* BETWEEN */) {
1075
+ return `${property} ${postgresOperator} ${value[0]} AND ${value[1]}`;
1076
+ }
1077
+ if (operator === "NOT_EQUAL" /* NOT_EQUAL */ && value !== null) {
1078
+ return `(${property} ${postgresOperator} ${literal(
1079
+ value
1080
+ )} OR ${property} IS NULL)`;
1081
+ }
1082
+ if (operator === "NOT_EXIST" /* NOT_EXIST */ || operator === "EXIST" /* EXIST */) {
1083
+ return `${property} ${postgresOperator}`;
1084
+ }
1085
+ if ((operator === "CONTAINS" /* CONTAINS */ || operator === "NOT_CONTAINS" /* NOT_CONTAINS */) && columnType === "array") {
1086
+ const filterValue = typeof value === "number" ? value : `'${value}'`;
1087
+ let filterString = `${filterValue} = ANY(${property})`;
1088
+ if (operator === "NOT_CONTAINS" /* NOT_CONTAINS */) {
1089
+ if (value === null) {
1090
+ filterString = `(NOT (${filterString}))`;
1091
+ } else {
1092
+ filterString = `(NOT (${filterString}) or ${property} IS NULL)`;
1093
+ }
1094
+ }
1095
+ return filterString;
1096
+ }
1097
+ const wildcardValue = this.getWildcardValue(operator, value);
1098
+ return `${property} ${postgresOperator} ${literal(wildcardValue)}`;
1099
+ }
1100
+ buildFilterClause(filters, logicOperator) {
1101
+ if (Array.isArray(filters)) {
1102
+ const filterClauses = filters.map((filter) => {
1103
+ return this.buildClause(
1104
+ filter.operator,
1105
+ filter.attribute,
1106
+ filter.relativePath,
1107
+ filter.value
1108
+ );
1109
+ });
1110
+ return filterClauses.join(
1111
+ ` ${logicOperator != null ? logicOperator : "AND" /* AND */} `
1112
+ );
1113
+ } else {
1114
+ return this.buildQueryByClause(filters);
1115
+ }
1116
+ }
1117
+ buildQueryByClause(filters) {
1118
+ let filterClauses = "";
1119
+ let isFirstFilter = true;
1120
+ for (const [key, value] of Object.entries(filters)) {
1121
+ if (!isFirstFilter) {
1122
+ filterClauses += key === "AND" ? " AND " : " OR ";
1123
+ }
1124
+ if (this.isCompositeFilter(value)) {
1125
+ filterClauses += "(";
1126
+ filterClauses += this.buildQueryByClause(
1127
+ value
1128
+ );
1129
+ filterClauses += ")";
1130
+ } else {
1131
+ value.forEach((filter) => {
1132
+ let clause = "";
1133
+ if (this.isCompositeFilter(filter)) {
1134
+ clause = `(${this.buildQueryByClause(
1135
+ filter
1136
+ )})`;
1137
+ } else {
1138
+ clause = this.buildClause(
1139
+ filter.operator,
1140
+ filter.attribute,
1141
+ filter.relativePath,
1142
+ filter.value
1143
+ );
1144
+ }
1145
+ filterClauses += `${clause} ${key} `;
1146
+ });
1147
+ }
1148
+ isFirstFilter = false;
1149
+ }
1150
+ filterClauses = filterClauses.replace(/\s+(AND|OR)\s*$/, "");
1151
+ return filterClauses;
1152
+ }
1153
+ formatOrderByItem(sort) {
1154
+ return `${ident(sort.column)} ${sort.direction || "ASC" /* ASC */}`;
1155
+ }
1156
+ buildOrderByClause(querySorting) {
1157
+ try {
1158
+ return querySorting.map(this.formatOrderByItem).join(", ");
1159
+ } catch (error) {
1160
+ return "";
1161
+ }
1162
+ }
1163
+ formatArray(array) {
1164
+ const isNumberArray = typeof array[0] === "number";
1165
+ if (isNumberArray) {
1166
+ return `{${array.join(",")}}`;
1167
+ } else {
1168
+ return `{${array.map((val) => `"${val}"`).join(",")}}`;
1169
+ }
1170
+ }
1171
+ formatValue(value) {
1172
+ if (Array.isArray(value)) {
1173
+ if (!(value == null ? void 0 : value.length)) return "{}";
1174
+ const isNumberArray = typeof value[0] === "number";
1175
+ if (isNumberArray) {
1176
+ return `{${value.join(",")}}`;
1177
+ } else {
1178
+ return `{${value.map((val) => `"${val}"`).join(",")}}`;
1179
+ }
1180
+ }
1181
+ return value;
1182
+ }
1183
+ async createCommand(data) {
1184
+ const keys = Object.keys(data[0]);
1185
+ const values = data.map(
1186
+ (item) => keys.map((key) => this.formatValue(item[key]))
1187
+ );
1188
+ const query = format(
1189
+ `INSERT INTO ${ident(this.dbSchema)}.${ident(
1190
+ this.tableName
1191
+ )} (%I) VALUES %L RETURNING *;`,
1192
+ keys,
1193
+ values
1194
+ );
1195
+ return this.runQuery(query);
1196
+ }
1197
+ isValidFiltersInput(filters) {
1198
+ const isValidArrayFilters = Array.isArray(filters) && (filters == null ? void 0 : filters.length) > 0;
1199
+ const isValidCompositeFilters = this.isCompositeFilter(filters);
1200
+ return isValidArrayFilters || isValidCompositeFilters;
1201
+ }
1202
+ replaceFilterTokensInQuery(query, filters) {
1203
+ if (!filters) return query;
1204
+ if (this.isValidFiltersInput(filters)) {
1205
+ const filterClause = this.buildFilterClause(filters);
1206
+ return query.replace(/{{filters}}/g, filterClause);
1207
+ }
1208
+ }
1209
+ addFiltersToQuery(query, filters) {
1210
+ if (!filters) return query;
1211
+ if (this.isValidFiltersInput(filters))
1212
+ query += ` WHERE ${this.buildFilterClause(filters)}`;
1213
+ return query;
1214
+ }
1215
+ addOrderByToQuery(query, orderBy) {
1216
+ if (orderBy) query += ` ORDER BY ${this.buildOrderByClause(orderBy)}`;
1217
+ return query;
1218
+ }
1219
+ addPaginationToQuery(query, pagination) {
1220
+ if (pagination) {
1221
+ const { limit, from } = pagination;
1222
+ if (limit) query += ` LIMIT ${limit}`;
1223
+ if (from) query += ` OFFSET ${from}`;
1224
+ }
1225
+ return query;
1226
+ }
1227
+ getSelectClause(aggregateFunction, fields = []) {
1228
+ if (aggregateFunction)
1229
+ return `CAST(${aggregateFunction}(1) AS INTEGER) AS "${buildAggFunctionAlias(
1230
+ aggregateFunction
1231
+ )}"`;
1232
+ if (!(fields == null ? void 0 : fields.length)) return "*";
1233
+ return this.parseFields(fields).join(", ");
1234
+ }
1235
+ parseFields(fields) {
1236
+ const columnsFromSchema = Object.keys(
1237
+ this.crudSchema.columns
1238
+ );
1239
+ const attributes = fields.filter((field) => columnsFromSchema.indexOf(field) !== -1).map((field) => `"${field}"`);
1240
+ fields.filter((field) => columnsFromSchema.indexOf(field) === -1).forEach((field) => {
1241
+ attributes.push(`"qvAttributes" ->> '${field}' as "${field}"`);
1242
+ });
1243
+ return attributes;
1244
+ }
1245
+ resolveWithQueries(rawWith) {
1246
+ const withQueries = rawWith.map(({ alias, query, filters }) => {
1247
+ const withQuery = this.replaceFilterTokensInQuery(query, filters);
1248
+ return `${alias} AS (${withQuery})`;
1249
+ });
1250
+ return withQueries;
1251
+ }
1252
+ getRawWithClause(rawWith) {
1253
+ let rawWithClause = "";
1254
+ if (rawWith == null ? void 0 : rawWith.length) {
1255
+ const withQueries = this.resolveWithQueries(rawWith);
1256
+ rawWithClause = "WITH " + withQueries.join(",\n");
1257
+ }
1258
+ return rawWithClause;
1259
+ }
1260
+ getQueryFrom() {
1261
+ return this.isTemporalTable ? ident(this.tableName) : `${ident(this.dbSchema)}.${ident(this.tableName)}`;
1262
+ }
1263
+ async findCommand(options = {}) {
1264
+ const rawWithClause = this.getRawWithClause(options.rawWith);
1265
+ let query = `SELECT ${this.getSelectClause(
1266
+ options.aggregateFunction,
1267
+ options.fields
1268
+ )} FROM ${this.getQueryFrom()}`;
1269
+ query = this.addFiltersToQuery(query, options.filters);
1270
+ if (!options.aggregateFunction) {
1271
+ query = this.addOrderByToQuery(query, options.sorting);
1272
+ query = this.addPaginationToQuery(query, options.pagination);
1273
+ }
1274
+ if (rawWithClause) {
1275
+ query = `${rawWithClause} ${query}`;
1276
+ }
1277
+ return (await this.runQuery(query)).rows;
1278
+ }
1279
+ sanitizeValue(value) {
1280
+ if (Array.isArray(value)) {
1281
+ if (value.length === 0) ;
1282
+ const formattedArray = value.map((item) => {
1283
+ if (typeof item === "string") {
1284
+ return `'${item}'`;
1285
+ } else if (typeof item === "object") {
1286
+ return JSON.stringify(item);
1287
+ } else {
1288
+ return item;
1289
+ }
1290
+ }).join(",");
1291
+ return JSON.stringify(formattedArray);
1292
+ } else {
1293
+ return literal(value);
1294
+ }
1295
+ }
1296
+ async updateCommand(filters, data) {
1297
+ let query = `UPDATE ${ident(this.dbSchema)}.${ident(
1298
+ this.tableName
1299
+ )} SET`;
1300
+ const updateClauses = Object.entries(data).map(([key, value]) => {
1301
+ const dbValue = literal(this.formatValue(value));
1302
+ return `${ident(key)} = ${dbValue}`;
1303
+ });
1304
+ query += ` ${updateClauses.join(", ")}`;
1305
+ query += " WHERE ";
1306
+ query += this.buildFilterClause(filters);
1307
+ return this.runQuery(query);
1308
+ }
1309
+ buildFilterClauseForFilterGroups(filterGroups) {
1310
+ const filterClauses = filterGroups.map((filterGroup) => {
1311
+ return `(${this.buildFilterClause(filterGroup)})`;
1312
+ });
1313
+ return filterClauses.join(" OR ");
1314
+ }
1315
+ async deleteCommand(filters, useFilterGroups = false) {
1316
+ let query = `DELETE FROM ${ident(this.dbSchema)}.${ident(
1317
+ this.tableName
1318
+ )}`;
1319
+ if (filters) {
1320
+ query += " WHERE ";
1321
+ if (useFilterGroups) {
1322
+ query += this.buildFilterClauseForFilterGroups(
1323
+ filters
1324
+ );
1325
+ } else {
1326
+ query += this.buildFilterClause(
1327
+ filters
1328
+ );
1329
+ }
1330
+ }
1331
+ return this.runQuery(query);
1332
+ }
1333
+ query(queryText, values) {
1334
+ return this.runQuery(queryText, values);
1335
+ }
1336
+ async updateExpressionCommand(filters, actions, options = {}) {
1337
+ let query = `UPDATE ${ident(this.dbSchema)}.${ident(
1338
+ this.tableName
1339
+ )} SET`;
1340
+ const set = actions.SET || [];
1341
+ const add = actions.ADD || [];
1342
+ const columns = this.crudSchema.columns;
1343
+ const setValues = this.replacePathAndValueByAttributeNames(
1344
+ set,
1345
+ options,
1346
+ columns,
1347
+ DYNAMO_DB_UPDATE_ACTIONS.SET
1348
+ );
1349
+ const addValues = this.replacePathAndValueByAttributeNames(
1350
+ add,
1351
+ options,
1352
+ columns,
1353
+ DYNAMO_DB_UPDATE_ACTIONS.ADD
1354
+ );
1355
+ const setValuesAndAddValues = setValues.concat(addValues);
1356
+ const updateClauses = [];
1357
+ const jsonSetExpressionGroup = {};
1358
+ const queryFunctions = [];
1359
+ setValuesAndAddValues.forEach((expression) => {
1360
+ const { path, value, createNewColumn, actionName, dynamoFuncName } = expression;
1361
+ if (dynamoFuncName) {
1362
+ queryFunctions.push({ path, value, dynamoFuncName });
1363
+ }
1364
+ if (path.includes(".") && !dynamoFuncName) {
1365
+ const jsonExpr = this.getJSONBSetExpressionByAction(
1366
+ path,
1367
+ value,
1368
+ {
1369
+ createNewColumn,
1370
+ actionName
1371
+ }
1372
+ );
1373
+ const columnName = jsonExpr.columnName;
1374
+ if (!jsonSetExpressionGroup[columnName]) {
1375
+ jsonSetExpressionGroup[columnName] = [jsonExpr];
1376
+ } else {
1377
+ jsonSetExpressionGroup[columnName].push(jsonExpr);
1378
+ }
1379
+ } else if (!dynamoFuncName) {
1380
+ let expValue;
1381
+ const column = this.crudSchema.columns[path];
1382
+ if ((column == null ? void 0 : column.type) == void 0)
1383
+ throw `Column type definition for column: (${path}) must be in the CrudSchema`;
1384
+ let formattedValue;
1385
+ switch (column.type) {
1386
+ case "object":
1387
+ {
1388
+ const valueSerialized = `${JSON.stringify(
1389
+ value
1390
+ ).replace(/'/g, "''")}`;
1391
+ expValue = `'${valueSerialized}'::jsonb`;
1392
+ }
1393
+ break;
1394
+ case "array":
1395
+ formattedValue = literal(value);
1396
+ expValue = `ARRAY[${formattedValue}]`;
1397
+ break;
1398
+ default:
1399
+ formattedValue = literal(value);
1400
+ expValue = formattedValue;
1401
+ break;
1402
+ }
1403
+ this.crudSchema.columns;
1404
+ updateClauses.push(`${ident(path)} = ${expValue}`);
1405
+ }
1406
+ });
1407
+ this.setCommonColumnsQueryFunctions(
1408
+ jsonSetExpressionGroup,
1409
+ queryFunctions
1410
+ );
1411
+ if (Object.keys(jsonSetExpressionGroup).length > 0) {
1412
+ Object.keys(jsonSetExpressionGroup).forEach((groupIndex) => {
1413
+ const jsonSetExpression = this.buildJSONBExpression(
1414
+ jsonSetExpressionGroup[groupIndex],
1415
+ "jsonb_set"
1416
+ );
1417
+ updateClauses.push(`${groupIndex} = ${jsonSetExpression}`);
1418
+ });
1419
+ }
1420
+ this.buildUpdateClausesFormDynamoFunctions(
1421
+ queryFunctions,
1422
+ updateClauses
1423
+ );
1424
+ query += ` ${updateClauses.join(", ")}`;
1425
+ query += " WHERE ";
1426
+ query += this.buildFilterClause(filters);
1427
+ return this.runQuery(query);
1428
+ }
1429
+ buildUpdateClausesFormDynamoFunctions(queryFunctions, updateClauses) {
1430
+ if (queryFunctions.length > 0) {
1431
+ queryFunctions.forEach((queryFunction) => {
1432
+ if (typeof queryFunction.value == "object") {
1433
+ const jsonExpr = this.buildJSONBExpression(
1434
+ queryFunction.value.jsonExpression,
1435
+ "jsonb_insert"
1436
+ );
1437
+ updateClauses.push(
1438
+ `${ident(queryFunction.path)} = ${jsonExpr}`
1439
+ );
1440
+ } else {
1441
+ updateClauses.push(
1442
+ `${ident(queryFunction.path)} = ${queryFunction.value}`
1443
+ );
1444
+ }
1445
+ });
1446
+ }
1447
+ }
1448
+ setCommonColumnsQueryFunctions(jsonSetExpressionGroup, queryFunctions) {
1449
+ Object.keys(jsonSetExpressionGroup).forEach((jsonSetExpr) => {
1450
+ queryFunctions.forEach((queryFunction, index) => {
1451
+ const columnPath = `"${queryFunction.path}"`;
1452
+ if (columnPath === jsonSetExpr) {
1453
+ jsonSetExpressionGroup[jsonSetExpr].push(__spreadProps(__spreadValues({}, queryFunction), {
1454
+ isCommonColumn: true
1455
+ }));
1456
+ delete queryFunctions[index];
1457
+ }
1458
+ });
1459
+ });
1460
+ }
1461
+ /**
1462
+ * @description Builds a jsonb expression like jsonb_insert, or jsonb_set
1463
+ * @param jsonSetExpressions
1464
+ * @param functionName
1465
+ * @returns
1466
+ */
1467
+ buildJSONBExpression(jsonSetExpressions, functionName) {
1468
+ let jsonSetStringExpr = "";
1469
+ jsonSetExpressions.forEach((expression, index) => {
1470
+ let _tempFunctionName = functionName;
1471
+ let { columnName, jsonExpr } = expression;
1472
+ if (expression.isCommonColumn) {
1473
+ const jsonExpression = expression.value.jsonExpression[0];
1474
+ _tempFunctionName = jsonExpression.functionName;
1475
+ jsonExpr = jsonExpression.jsonExpr;
1476
+ columnName = jsonExpression.columnName;
1477
+ }
1478
+ if (index === 0) {
1479
+ jsonSetStringExpr = `${_tempFunctionName}(${columnName},${jsonExpr})`;
1480
+ } else {
1481
+ jsonSetStringExpr = `${_tempFunctionName}(${jsonSetStringExpr},${jsonExpr})`;
1482
+ }
1483
+ });
1484
+ return jsonSetStringExpr;
1485
+ }
1486
+ /**
1487
+ * @description Serializes a JSON value
1488
+ * @param value
1489
+ * @returns
1490
+ */
1491
+ serializeJSONValue(value) {
1492
+ const valueSerialized = typeof value == "object" ? `${JSON.stringify(value).replace(/'/g, "''")}` : value;
1493
+ return valueSerialized;
1494
+ }
1495
+ getJSONBSetExpressionByAction(path, value, options) {
1496
+ path = path.replace(/\[(\d+)\]/g, ".$1");
1497
+ const pathSplitted = path.split(".");
1498
+ const parentPath = pathSplitted[0];
1499
+ const { createNewColumn, actionName } = options;
1500
+ const pathSerialized = pathSplitted.slice(1).join(",");
1501
+ const valueSerialized = `'${JSON.stringify(value).replace(
1502
+ /'/g,
1503
+ "''"
1504
+ )}'`;
1505
+ if (actionName == DYNAMO_DB_UPDATE_ACTIONS.ADD) {
1506
+ if (typeof value != "string" && !isNaN(value)) {
1507
+ const resultExpr = {
1508
+ jsonExpr: `'{${pathSerialized}}',to_jsonb(COALESCE(("${parentPath}"#>'{${pathSerialized}}')::numeric,0) + ${valueSerialized})`,
1509
+ columnName: `"${parentPath}"`
1510
+ };
1511
+ return resultExpr;
1512
+ }
1513
+ }
1514
+ return {
1515
+ jsonExpr: `'{${pathSerialized}}',${valueSerialized},${createNewColumn}`,
1516
+ columnName: `"${parentPath}"`
1517
+ };
1518
+ }
1519
+ getListAppendDefFromValue(queryValue, columnType) {
1520
+ const regexListAppend = /list_append\(([^)]+)\)/gm;
1521
+ const listAppendString = "list_append(";
1522
+ const matchList = queryValue.match(regexListAppend) || [];
1523
+ const groupResult = matchList[0];
1524
+ if (groupResult) {
1525
+ const attributesFromGroup = groupResult.slice(listAppendString.length, -1).split(",");
1526
+ const attributes = {
1527
+ originalString: groupResult,
1528
+ path: attributesFromGroup[0].trim(),
1529
+ value: attributesFromGroup.slice(1).join(",").trim(),
1530
+ isDynamoFunction: true,
1531
+ functionExpr: "",
1532
+ jsonExpression: [{}]
1533
+ };
1534
+ if (columnType == "array") {
1535
+ attributes["functionExpr"] = this.buildArrayAppendExpr(attributes);
1536
+ } else {
1537
+ attributes["jsonExpression"] = this.buildJsonbInsertExpr(attributes);
1538
+ }
1539
+ return attributes;
1540
+ }
1541
+ return null;
1542
+ }
1543
+ buildArrayAppendExpr(params) {
1544
+ const arrayPath = params.path.split(".");
1545
+ const columnName = arrayPath.shift();
1546
+ return `ARRAY_APPEND("${columnName}",${params.value})`;
1547
+ }
1548
+ buildJsonbInsertExpr(params) {
1549
+ const arrayPath = params.path.split(".");
1550
+ const columnName = arrayPath.shift();
1551
+ const options = {
1552
+ isDynamoFunction: params == null ? void 0 : params.isDynamoFunction,
1553
+ relativePath: arrayPath.length && Array.isArray(arrayPath) ? arrayPath : []
1554
+ };
1555
+ const jsonbInsertExpressions = this.getExpressionsByDefinitionForJSONBInsert(
1556
+ columnName,
1557
+ params.value,
1558
+ options
1559
+ );
1560
+ return jsonbInsertExpressions;
1561
+ }
1562
+ getExpressionsByDefinitionForJSONBInsert(columnName, value, options) {
1563
+ const jsonbInsertExpressions = [];
1564
+ let pathToAffect = "0";
1565
+ if (options.isDynamoFunction == true) {
1566
+ options.relativePath.push("0");
1567
+ pathToAffect = options.relativePath.join(",");
1568
+ }
1569
+ try {
1570
+ const parsedValue = JSON.parse(value);
1571
+ if (Array.isArray(parsedValue)) {
1572
+ parsedValue.forEach((arrayValue) => {
1573
+ arrayValue = typeof arrayValue == "string" ? `"${arrayValue}"` : arrayValue;
1574
+ jsonbInsertExpressions.push({
1575
+ jsonExpr: `'{${pathToAffect}}','${this.serializeJSONValue(
1576
+ arrayValue
1577
+ )}'`,
1578
+ columnName: `"${columnName}"`,
1579
+ functionName: "jsonb_insert"
1580
+ });
1581
+ });
1582
+ } else {
1583
+ jsonbInsertExpressions.push({
1584
+ jsonExpr: `'{${pathToAffect}}','${this.serializeJSONValue(
1585
+ parsedValue
1586
+ )}'`,
1587
+ columnName: `"${columnName}"`,
1588
+ functionName: "jsonb_insert"
1589
+ });
1590
+ }
1591
+ } catch (error) {
1592
+ jsonbInsertExpressions.push({
1593
+ jsonExpr: `'{${pathToAffect}}','${value}'`,
1594
+ columnName: `"${columnName}"`,
1595
+ functionName: "jsonb_insert"
1596
+ });
1597
+ }
1598
+ return jsonbInsertExpressions;
1599
+ }
1600
+ getInsertExprFromJsonbDef(queryValue, columnType) {
1601
+ const listAppendParams = this.getListAppendDefFromValue(
1602
+ queryValue,
1603
+ columnType
1604
+ );
1605
+ if (listAppendParams != null && (listAppendParams == null ? void 0 : listAppendParams.jsonExpression.length) === 0) {
1606
+ queryValue = queryValue.replace(
1607
+ listAppendParams.originalString,
1608
+ listAppendParams.functionExpr
1609
+ );
1610
+ } else {
1611
+ return listAppendParams;
1612
+ }
1613
+ return queryValue;
1614
+ }
1615
+ replacePathAndValueByAttributeNames(actions, options, columns, actionName) {
1616
+ return actions.map((action) => {
1617
+ action.path = this.replaceExpressionAttributeNames(
1618
+ action.path,
1619
+ options
1620
+ );
1621
+ if (typeof action.value == "string" && action.value.includes("list_append")) {
1622
+ action.path = action.path.split(".")[0];
1623
+ const column = columns[action.path];
1624
+ action.value = this.replaceExpressionAttributeValuesForDynamoFunctions(
1625
+ action.value,
1626
+ options
1627
+ );
1628
+ action.value = this.getInsertExprFromJsonbDef(
1629
+ action.value,
1630
+ column.type
1631
+ );
1632
+ action.dynamoFuncName = "list_append";
1633
+ } else {
1634
+ action.value = this.replaceExpressionAttributeValues(
1635
+ action.value,
1636
+ options
1637
+ );
1638
+ }
1639
+ action.actionName = actionName;
1640
+ action.createNewColumn = true;
1641
+ return action;
1642
+ });
1643
+ }
1644
+ replaceExpressionAttributeValuesForDynamoFunctions(value, options) {
1645
+ const { expressionAttributeNames, expressionAttributeValues } = options;
1646
+ const exprAttributeNamesKeys = expressionAttributeNames ? Object.keys(expressionAttributeNames) : [];
1647
+ const exprAttributeValuesKeys = expressionAttributeValues ? Object.keys(expressionAttributeValues) : [];
1648
+ if (exprAttributeNamesKeys.length > 0) {
1649
+ exprAttributeNamesKeys.forEach((exprAttribute) => {
1650
+ value = value.replace(
1651
+ exprAttribute,
1652
+ expressionAttributeNames[exprAttribute]
1653
+ );
1654
+ });
1655
+ }
1656
+ if (exprAttributeValuesKeys.length > 0) {
1657
+ exprAttributeValuesKeys.forEach((exprAttribute) => {
1658
+ const valueSerialized = this.serializeJSONValue(
1659
+ expressionAttributeValues[exprAttribute]
1660
+ );
1661
+ value = value.replace(exprAttribute, `${valueSerialized}`);
1662
+ });
1663
+ }
1664
+ return value;
1665
+ }
1666
+ replaceExpressionAttributeNames(path, options) {
1667
+ const { expressionAttributeNames } = options;
1668
+ if (expressionAttributeNames) {
1669
+ Object.keys(expressionAttributeNames).forEach(
1670
+ (attributeName) => {
1671
+ const attributeNameValue = expressionAttributeNames[attributeName];
1672
+ path = path.replace(attributeName, attributeNameValue);
1673
+ }
1674
+ );
1675
+ }
1676
+ return path;
1677
+ }
1678
+ replaceExpressionAttributeValues(value, options) {
1679
+ const { expressionAttributeValues } = options;
1680
+ if (expressionAttributeValues[value] != void 0) {
1681
+ return expressionAttributeValues[value];
1682
+ }
1683
+ return value;
1684
+ }
1685
+ getValueTypeAsPostgresDefinition(value) {
1686
+ switch (typeof value) {
1687
+ case "number":
1688
+ return "number";
1689
+ case "boolean":
1690
+ return "boolean";
1691
+ case "string":
1692
+ default:
1693
+ return "text";
1694
+ }
1695
+ }
1696
+ };
1697
+
1698
+ // src/services/cruds/postgresql/postgreSqlCrud.service.ts
1699
+ var PostgreSqlCrudService = class extends PostgresqlClientService {
1700
+ constructor(tableSchema, poolClient) {
1701
+ super(tableSchema, poolClient);
1702
+ this.tableSchema = tableSchema;
1703
+ }
1704
+ get idColumnName() {
1705
+ return findIdColumnName(this.tableSchema.columns);
1706
+ }
1707
+ normalizeInputData(inputData) {
1708
+ var _a;
1709
+ inputData.qvAttributes = {};
1710
+ for (const key in inputData) {
1711
+ if (!this.tableSchema.columns[key] && key !== "qvAttributes") {
1712
+ inputData.qvAttributes[key] = inputData[key];
1713
+ delete inputData[key];
1714
+ } else if (Array.isArray(inputData[key]) && ((_a = this.tableSchema.columns[key]) == null ? void 0 : _a.type) !== "array") {
1715
+ inputData[key] = JSON.stringify(inputData[key]);
1716
+ }
1717
+ }
1718
+ }
1719
+ getItem(data) {
1720
+ const schemaColumns = Object.entries(this.tableSchema.columns);
1721
+ schemaColumns.forEach(([key, value]) => {
1722
+ if (value.type === "big_number") {
1723
+ if (data[key]) data[key] = Number(data[key]);
1724
+ }
1725
+ });
1726
+ const resultItem = __spreadValues(__spreadValues({}, data), data.qvAttributes);
1727
+ delete resultItem["qvAttributes"];
1728
+ return resultItem;
1729
+ }
1730
+ prepareData(data) {
1731
+ const inputData = __spreadValues({}, data);
1732
+ this.normalizeInputData(inputData);
1733
+ return inputData;
1734
+ }
1735
+ buildCreateResponseBatch(result) {
1736
+ const rows = Array.isArray(result == null ? void 0 : result.rows) ? result.rows : [];
1737
+ return {
1738
+ items: rows.map((r) => this.getItem(r)),
1739
+ unprocessedItems: []
1740
+ };
1741
+ }
1742
+ create(data) {
1743
+ if (Array.isArray(data)) {
1744
+ const inputDataArray = data.map((item) => this.prepareData(item));
1745
+ return this.createCommand(inputDataArray).then((result) => {
1746
+ return this.buildCreateResponseBatch(result);
1747
+ });
1748
+ } else {
1749
+ const inputData = this.prepareData(data);
1750
+ return this.createCommand([inputData]).then(
1751
+ (result) => result.rowCount ? this.getItem(result.rows[0]) : null
1752
+ );
1753
+ }
1754
+ }
1755
+ findItem(findOptions) {
1756
+ return this.findCommand(findOptions).then((data) => {
1757
+ return (data == null ? void 0 : data.length) ? this.getItem(data[0]) : null;
1758
+ });
1759
+ }
1760
+ async processQueryResult(findOptions, omitPagination = false) {
1761
+ const rows = await this.findCommand(findOptions);
1762
+ const items = rows.map(
1763
+ (row) => this.getItem(row)
1764
+ );
1765
+ const { limit, from } = (findOptions == null ? void 0 : findOptions.pagination) || {};
1766
+ const hasMoreRecords = items.length && items.length === limit;
1767
+ const newFrom = limit && hasMoreRecords ? limit + (from || 0) : null;
1768
+ const result = {
1769
+ items,
1770
+ pagination: omitPagination ? null : { limit, from: newFrom },
1771
+ count: items.length
1772
+ };
1773
+ return result;
1774
+ }
1775
+ async find(findOptions) {
1776
+ return this.processQueryResult(findOptions);
1777
+ }
1778
+ async findAll(findOptions) {
1779
+ return this.processQueryResult(findOptions, true);
1780
+ }
1781
+ async findCount(findOptions) {
1782
+ const items = await this.findCommand(__spreadProps(__spreadValues({}, findOptions), {
1783
+ aggregateFunction: "COUNT" /* COUNT */
1784
+ }));
1785
+ const aggFunctionProperty = buildAggFunctionAlias(
1786
+ "COUNT" /* COUNT */
1787
+ );
1788
+ const item = items.length ? items[0] : {};
1789
+ return item[aggFunctionProperty] || 0;
1790
+ }
1791
+ async update(filters, data, options = {}) {
1792
+ const savedRecord = options.skipFindItems ? {} : await this.findItem({ filters });
1793
+ const inputData = __spreadValues(__spreadValues({}, savedRecord), data);
1794
+ await this.updateCommand(filters, this.prepareData(inputData));
1795
+ return this.getItem(inputData);
1796
+ }
1797
+ async remove(filters, options) {
1798
+ await this.deleteCommand(filters, options == null ? void 0 : options.filterGroups);
1799
+ }
1800
+ runQuery(querySentence, values) {
1801
+ return super.runQuery(querySentence, values);
1802
+ }
1803
+ async updateExpressions(filters, actions, options) {
1804
+ const result = await this.updateExpressionCommand(
1805
+ filters,
1806
+ actions,
1807
+ options
1808
+ );
1809
+ return PersistenceErrorWrapper(result);
1810
+ }
1811
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1812
+ runRawQuery(query, params) {
1813
+ throw super.runQuery(query, params);
1814
+ }
1815
+ };
25
1816
 
26
1817
  // src/services/crudFactory.service.ts
27
1818
  var CrudFactory = class {
28
- static async databaseClientService(crudSchema, pool) {
1819
+ static databaseClientService(crudSchema, pool) {
29
1820
  var _a;
30
1821
  const isMultiPlatformMode2 = ((_a = process.env.PLATFORM_TYPE) == null ? void 0 : _a.toLowerCase()) === "container";
31
- let DatabaseCrudService;
32
- if (isMultiPlatformMode2) {
33
- const module = await import('./postgreSqlCrud.service-AD2CHR2Z.mjs');
34
- DatabaseCrudService = module.PostgreSqlCrudService;
35
- } else {
36
- const module = await import('./dynamoDbCrud.service-NRSGRPDQ.mjs');
37
- DatabaseCrudService = module.DynamoDbCrudService;
38
- }
39
- return new DatabaseCrudService(crudSchema, pool);
1822
+ if (isMultiPlatformMode2)
1823
+ return new PostgreSqlCrudService(crudSchema, pool);
1824
+ return new DynamoDbCrudService(crudSchema);
40
1825
  }
41
1826
  };
42
1827
 
@@ -85,9 +1870,9 @@ var CrudService = class {
85
1870
  (crudService) => crudService.findItem(options)
86
1871
  );
87
1872
  }
88
- update(filters, data) {
1873
+ update(filters, data, options = {}) {
89
1874
  return this.getCrudServiceInstance().then(
90
- (crudService) => crudService.update(filters, data, {})
1875
+ (crudService) => crudService.update(filters, data, options)
91
1876
  );
92
1877
  }
93
1878
  remove(filters, options = {}) {