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