@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,857 +0,0 @@
1
- import { findIdColumnName, buildAggFunctionAlias, PersistenceErrorWrapper, getTableName } from './chunk-2H6RO6ZL.mjs';
2
- import { __spreadValues, __spreadProps, DEFAULT_PG_SCHEMA, POSTGRES_FILTER_OPERATOR_MAP, DYNAMO_DB_UPDATE_ACTIONS } from './chunk-2OYWEFNZ.mjs';
3
- import format from 'pg-format';
4
- import { Client } from 'pg';
5
-
6
- var ConnectionService = class {
7
- get connectionString() {
8
- const connectionString = process.env.MULTIPLATFORM_PG_CONNECTION_STRING || "";
9
- if (!connectionString) {
10
- throw new Error(
11
- "MULTIPLATFORM_PG_CONNECTION_STRING environment variable must be configured"
12
- );
13
- }
14
- return connectionString;
15
- }
16
- async getClient() {
17
- const client = new Client({
18
- connectionString: this.connectionString
19
- });
20
- await client.connect();
21
- return client;
22
- }
23
- releaseClient(client) {
24
- try {
25
- client.end();
26
- } catch (e) {
27
- console.log("Error releasing client");
28
- }
29
- }
30
- };
31
-
32
- // src/services/cruds/postgresql/query.service.ts
33
- var QueryService = class {
34
- constructor(pool) {
35
- this.pool = pool;
36
- this.connectionService = new ConnectionService();
37
- }
38
- async runQuery(queryText, values) {
39
- const client = await (this.pool ? this.pool.connect() : this.connectionService.getClient());
40
- try {
41
- if (process.env.NODE_ENV === "debugging")
42
- console.log("queryText:::", queryText);
43
- const result = await client.query(queryText, values);
44
- return result;
45
- } finally {
46
- if (this.pool) {
47
- await client.release();
48
- } else {
49
- this.connectionService.releaseClient(client);
50
- }
51
- }
52
- }
53
- };
54
-
55
- // src/services/cruds/postgresql/postgreSqlClient.service.ts
56
- var PostgresqlClientService = class extends QueryService {
57
- constructor(tableSchema, poolClient) {
58
- super(poolClient);
59
- this.isCompositeFilter = function(value) {
60
- return "OR" in value || "AND" in value;
61
- };
62
- this.crudSchema = tableSchema;
63
- }
64
- get dbSchema() {
65
- return this.crudSchema.schema || DEFAULT_PG_SCHEMA;
66
- }
67
- get tableName() {
68
- return getTableName(this.crudSchema.table, "alias") || getTableName(this.crudSchema.table);
69
- }
70
- get isTemporalTable() {
71
- var _a;
72
- return (_a = this.crudSchema) == null ? void 0 : _a.isTemporalTable;
73
- }
74
- getWildcardValue(operator, value) {
75
- if (operator === "CONTAINS" /* CONTAINS */ || operator === "NOT_CONTAINS" /* NOT_CONTAINS */) {
76
- return "%" + value + "%";
77
- } else if (operator === "STARTS_WITH" /* STARTS_WITH */) {
78
- return value + "%";
79
- } else {
80
- return value;
81
- }
82
- }
83
- buildClause(operator, attribute, relativePath, value) {
84
- var _a;
85
- const formattedValue = format.literal(value);
86
- operator = operator ? operator.toUpperCase() : "EQUAL" /* EQUAL */;
87
- const postgresOperator = POSTGRES_FILTER_OPERATOR_MAP[operator];
88
- if (!postgresOperator)
89
- throw new Error(`Unsupported filter operator: ${operator}`);
90
- let property;
91
- const filterProperty = format.ident(attribute);
92
- const columnExists = !!this.crudSchema.columns[attribute];
93
- const columnType = columnExists && ((_a = this.crudSchema.columns[attribute]) == null ? void 0 : _a.type);
94
- if (relativePath != void 0) {
95
- const attributePath = relativePath.split(".").join(",");
96
- property = `("${attribute}" #> '{${attributePath}}')`;
97
- if (value != null) {
98
- const comparisonValueType = this.getValueTypeAsPostgresDefinition(value);
99
- property += `::${comparisonValueType}`;
100
- }
101
- } else {
102
- property = columnExists ? filterProperty : `("qvAttributes" ->> '${attribute}')`;
103
- }
104
- if (operator === "IN" /* IN */) {
105
- const formattedValues = Array.isArray(value) ? value.map(format.literal) : [formattedValue];
106
- return `${property} ${postgresOperator} (${formattedValues.join(
107
- ", "
108
- )})`;
109
- }
110
- if (operator === "BETWEEN" /* BETWEEN */) {
111
- return `${property} ${postgresOperator} ${value[0]} AND ${value[1]}`;
112
- }
113
- if (operator === "NOT_EQUAL" /* NOT_EQUAL */ && value !== null) {
114
- return `(${property} ${postgresOperator} ${format.literal(
115
- value
116
- )} OR ${property} IS NULL)`;
117
- }
118
- if (operator === "NOT_EXIST" /* NOT_EXIST */ || operator === "EXIST" /* EXIST */) {
119
- return `${property} ${postgresOperator}`;
120
- }
121
- if ((operator === "CONTAINS" /* CONTAINS */ || operator === "NOT_CONTAINS" /* NOT_CONTAINS */) && columnType === "array") {
122
- const filterValue = typeof value === "number" ? value : `'${value}'`;
123
- let filterString = `${filterValue} = ANY(${property})`;
124
- if (operator === "NOT_CONTAINS" /* NOT_CONTAINS */) {
125
- if (value === null) {
126
- filterString = `(NOT (${filterString}))`;
127
- } else {
128
- filterString = `(NOT (${filterString}) or ${property} IS NULL)`;
129
- }
130
- }
131
- return filterString;
132
- }
133
- const wildcardValue = this.getWildcardValue(operator, value);
134
- return `${property} ${postgresOperator} ${format.literal(
135
- wildcardValue
136
- )}`;
137
- }
138
- buildFilterClause(filters, logicOperator) {
139
- if (Array.isArray(filters)) {
140
- const filterClauses = filters.map((filter) => {
141
- return this.buildClause(
142
- filter.operator,
143
- filter.attribute,
144
- filter.relativePath,
145
- filter.value
146
- );
147
- });
148
- return filterClauses.join(
149
- ` ${logicOperator != null ? logicOperator : "AND" /* AND */} `
150
- );
151
- } else {
152
- return this.buildQueryByClause(filters);
153
- }
154
- }
155
- buildQueryByClause(filters) {
156
- let filterClauses = "";
157
- let isFirstFilter = true;
158
- for (const [key, value] of Object.entries(filters)) {
159
- if (!isFirstFilter) {
160
- filterClauses += key === "AND" ? " AND " : " OR ";
161
- }
162
- if (this.isCompositeFilter(value)) {
163
- filterClauses += "(";
164
- filterClauses += this.buildQueryByClause(
165
- value
166
- );
167
- filterClauses += ")";
168
- } else {
169
- value.forEach((filter) => {
170
- let clause = "";
171
- if (this.isCompositeFilter(filter)) {
172
- clause = `(${this.buildQueryByClause(
173
- filter
174
- )})`;
175
- } else {
176
- clause = this.buildClause(
177
- filter.operator,
178
- filter.attribute,
179
- filter.relativePath,
180
- filter.value
181
- );
182
- }
183
- filterClauses += `${clause} ${key} `;
184
- });
185
- }
186
- isFirstFilter = false;
187
- }
188
- filterClauses = filterClauses.replace(/\s+(AND|OR)\s*$/, "");
189
- return filterClauses;
190
- }
191
- formatOrderByItem(sort) {
192
- return `${format.ident(sort.column)} ${sort.direction || "ASC" /* ASC */}`;
193
- }
194
- buildOrderByClause(querySorting) {
195
- try {
196
- return querySorting.map(this.formatOrderByItem).join(", ");
197
- } catch (error) {
198
- return "";
199
- }
200
- }
201
- formatArray(array) {
202
- const isNumberArray = typeof array[0] === "number";
203
- if (isNumberArray) {
204
- return `{${array.join(",")}}`;
205
- } else {
206
- return `{${array.map((val) => `"${val}"`).join(",")}}`;
207
- }
208
- }
209
- formatValue(value) {
210
- if (Array.isArray(value)) {
211
- if (!(value == null ? void 0 : value.length)) return "{}";
212
- const isNumberArray = typeof value[0] === "number";
213
- if (isNumberArray) {
214
- return `{${value.join(",")}}`;
215
- } else {
216
- return `{${value.map((val) => `"${val}"`).join(",")}}`;
217
- }
218
- }
219
- return value;
220
- }
221
- async createCommand(data) {
222
- const keys = Object.keys(data[0]);
223
- const values = data.map(
224
- (item) => keys.map((key) => this.formatValue(item[key]))
225
- );
226
- const query = format(
227
- `INSERT INTO ${format.ident(this.dbSchema)}.${format.ident(
228
- this.tableName
229
- )} (%I) VALUES %L RETURNING *;`,
230
- keys,
231
- values
232
- );
233
- return this.runQuery(query);
234
- }
235
- isValidFiltersInput(filters) {
236
- const isValidArrayFilters = Array.isArray(filters) && (filters == null ? void 0 : filters.length) > 0;
237
- const isValidCompositeFilters = this.isCompositeFilter(filters);
238
- return isValidArrayFilters || isValidCompositeFilters;
239
- }
240
- replaceFilterTokensInQuery(query, filters) {
241
- if (!filters) return query;
242
- if (this.isValidFiltersInput(filters)) {
243
- const filterClause = this.buildFilterClause(filters);
244
- return query.replace(/{{filters}}/g, filterClause);
245
- }
246
- }
247
- addFiltersToQuery(query, filters) {
248
- if (!filters) return query;
249
- if (this.isValidFiltersInput(filters))
250
- query += ` WHERE ${this.buildFilterClause(filters)}`;
251
- return query;
252
- }
253
- addOrderByToQuery(query, orderBy) {
254
- if (orderBy) query += ` ORDER BY ${this.buildOrderByClause(orderBy)}`;
255
- return query;
256
- }
257
- addPaginationToQuery(query, pagination) {
258
- if (pagination) {
259
- const { limit, from } = pagination;
260
- if (limit) query += ` LIMIT ${limit}`;
261
- if (from) query += ` OFFSET ${from}`;
262
- }
263
- return query;
264
- }
265
- getSelectClause(aggregateFunction, fields = []) {
266
- if (aggregateFunction)
267
- return `CAST(${aggregateFunction}(1) AS INTEGER) AS "${buildAggFunctionAlias(
268
- aggregateFunction
269
- )}"`;
270
- if (!(fields == null ? void 0 : fields.length)) return "*";
271
- return this.parseFields(fields).join(", ");
272
- }
273
- parseFields(fields) {
274
- const columnsFromSchema = Object.keys(
275
- this.crudSchema.columns
276
- );
277
- const attributes = fields.filter((field) => columnsFromSchema.indexOf(field) !== -1).map((field) => `"${field}"`);
278
- fields.filter((field) => columnsFromSchema.indexOf(field) === -1).forEach((field) => {
279
- attributes.push(`"qvAttributes" ->> '${field}' as "${field}"`);
280
- });
281
- return attributes;
282
- }
283
- resolveWithQueries(rawWith) {
284
- const withQueries = rawWith.map(({ alias, query, filters }) => {
285
- const withQuery = this.replaceFilterTokensInQuery(query, filters);
286
- return `${alias} AS (${withQuery})`;
287
- });
288
- return withQueries;
289
- }
290
- getRawWithClause(rawWith) {
291
- let rawWithClause = "";
292
- if (rawWith == null ? void 0 : rawWith.length) {
293
- const withQueries = this.resolveWithQueries(rawWith);
294
- rawWithClause = "WITH " + withQueries.join(",\n");
295
- }
296
- return rawWithClause;
297
- }
298
- getQueryFrom() {
299
- return this.isTemporalTable ? format.ident(this.tableName) : `${format.ident(this.dbSchema)}.${format.ident(this.tableName)}`;
300
- }
301
- async findCommand(options = {}) {
302
- const rawWithClause = this.getRawWithClause(options.rawWith);
303
- let query = `SELECT ${this.getSelectClause(
304
- options.aggregateFunction,
305
- options.fields
306
- )} FROM ${this.getQueryFrom()}`;
307
- query = this.addFiltersToQuery(query, options.filters);
308
- if (!options.aggregateFunction) {
309
- query = this.addOrderByToQuery(query, options.sorting);
310
- query = this.addPaginationToQuery(query, options.pagination);
311
- }
312
- if (rawWithClause) {
313
- query = `${rawWithClause} ${query}`;
314
- }
315
- return (await this.runQuery(query)).rows;
316
- }
317
- sanitizeValue(value) {
318
- if (Array.isArray(value)) {
319
- if (value.length === 0) ;
320
- const formattedArray = value.map((item) => {
321
- if (typeof item === "string") {
322
- return `'${item}'`;
323
- } else if (typeof item === "object") {
324
- return JSON.stringify(item);
325
- } else {
326
- return item;
327
- }
328
- }).join(",");
329
- return JSON.stringify(formattedArray);
330
- } else {
331
- return format.literal(value);
332
- }
333
- }
334
- async updateCommand(filters, data) {
335
- let query = `UPDATE ${format.ident(this.dbSchema)}.${format.ident(
336
- this.tableName
337
- )} SET`;
338
- const updateClauses = Object.entries(data).map(([key, value]) => {
339
- const dbValue = format.literal(this.formatValue(value));
340
- return `${format.ident(key)} = ${dbValue}`;
341
- });
342
- query += ` ${updateClauses.join(", ")}`;
343
- query += " WHERE ";
344
- query += this.buildFilterClause(filters);
345
- return this.runQuery(query);
346
- }
347
- buildFilterClauseForFilterGroups(filterGroups) {
348
- const filterClauses = filterGroups.map((filterGroup) => {
349
- return `(${this.buildFilterClause(filterGroup)})`;
350
- });
351
- return filterClauses.join(" OR ");
352
- }
353
- async deleteCommand(filters, useFilterGroups = false) {
354
- let query = `DELETE FROM ${format.ident(this.dbSchema)}.${format.ident(
355
- this.tableName
356
- )}`;
357
- if (filters) {
358
- query += " WHERE ";
359
- if (useFilterGroups) {
360
- query += this.buildFilterClauseForFilterGroups(
361
- filters
362
- );
363
- } else {
364
- query += this.buildFilterClause(
365
- filters
366
- );
367
- }
368
- }
369
- return this.runQuery(query);
370
- }
371
- query(queryText, values) {
372
- return this.runQuery(queryText, values);
373
- }
374
- async updateExpressionCommand(filters, actions, options = {}) {
375
- let query = `UPDATE ${format.ident(this.dbSchema)}.${format.ident(
376
- this.tableName
377
- )} SET`;
378
- const set = actions.SET || [];
379
- const add = actions.ADD || [];
380
- const columns = this.crudSchema.columns;
381
- const setValues = this.replacePathAndValueByAttributeNames(
382
- set,
383
- options,
384
- columns,
385
- DYNAMO_DB_UPDATE_ACTIONS.SET
386
- );
387
- const addValues = this.replacePathAndValueByAttributeNames(
388
- add,
389
- options,
390
- columns,
391
- DYNAMO_DB_UPDATE_ACTIONS.ADD
392
- );
393
- const setValuesAndAddValues = setValues.concat(addValues);
394
- const updateClauses = [];
395
- const jsonSetExpressionGroup = {};
396
- const queryFunctions = [];
397
- setValuesAndAddValues.forEach((expression) => {
398
- const { path, value, createNewColumn, actionName, dynamoFuncName } = expression;
399
- if (dynamoFuncName) {
400
- queryFunctions.push({ path, value, dynamoFuncName });
401
- }
402
- if (path.includes(".") && !dynamoFuncName) {
403
- const jsonExpr = this.getJSONBSetExpressionByAction(
404
- path,
405
- value,
406
- {
407
- createNewColumn,
408
- actionName
409
- }
410
- );
411
- const columnName = jsonExpr.columnName;
412
- if (!jsonSetExpressionGroup[columnName]) {
413
- jsonSetExpressionGroup[columnName] = [jsonExpr];
414
- } else {
415
- jsonSetExpressionGroup[columnName].push(jsonExpr);
416
- }
417
- } else if (!dynamoFuncName) {
418
- let expValue;
419
- const column = this.crudSchema.columns[path];
420
- if ((column == null ? void 0 : column.type) == void 0)
421
- throw `Column type definition for column: (${path}) must be in the CrudSchema`;
422
- let formattedValue;
423
- switch (column.type) {
424
- case "object":
425
- {
426
- const valueSerialized = `${JSON.stringify(
427
- value
428
- ).replace(/'/g, "''")}`;
429
- expValue = `'${valueSerialized}'::jsonb`;
430
- }
431
- break;
432
- case "array":
433
- formattedValue = format.literal(value);
434
- expValue = `ARRAY[${formattedValue}]`;
435
- break;
436
- default:
437
- formattedValue = format.literal(value);
438
- expValue = formattedValue;
439
- break;
440
- }
441
- this.crudSchema.columns;
442
- updateClauses.push(`${format.ident(path)} = ${expValue}`);
443
- }
444
- });
445
- this.setCommonColumnsQueryFunctions(
446
- jsonSetExpressionGroup,
447
- queryFunctions
448
- );
449
- if (Object.keys(jsonSetExpressionGroup).length > 0) {
450
- Object.keys(jsonSetExpressionGroup).forEach((groupIndex) => {
451
- const jsonSetExpression = this.buildJSONBExpression(
452
- jsonSetExpressionGroup[groupIndex],
453
- "jsonb_set"
454
- );
455
- updateClauses.push(`${groupIndex} = ${jsonSetExpression}`);
456
- });
457
- }
458
- this.buildUpdateClausesFormDynamoFunctions(
459
- queryFunctions,
460
- updateClauses
461
- );
462
- query += ` ${updateClauses.join(", ")}`;
463
- query += " WHERE ";
464
- query += this.buildFilterClause(filters);
465
- return this.runQuery(query);
466
- }
467
- buildUpdateClausesFormDynamoFunctions(queryFunctions, updateClauses) {
468
- if (queryFunctions.length > 0) {
469
- queryFunctions.forEach((queryFunction) => {
470
- if (typeof queryFunction.value == "object") {
471
- const jsonExpr = this.buildJSONBExpression(
472
- queryFunction.value.jsonExpression,
473
- "jsonb_insert"
474
- );
475
- updateClauses.push(
476
- `${format.ident(queryFunction.path)} = ${jsonExpr}`
477
- );
478
- } else {
479
- updateClauses.push(
480
- `${format.ident(queryFunction.path)} = ${queryFunction.value}`
481
- );
482
- }
483
- });
484
- }
485
- }
486
- setCommonColumnsQueryFunctions(jsonSetExpressionGroup, queryFunctions) {
487
- Object.keys(jsonSetExpressionGroup).forEach((jsonSetExpr) => {
488
- queryFunctions.forEach((queryFunction, index) => {
489
- const columnPath = `"${queryFunction.path}"`;
490
- if (columnPath === jsonSetExpr) {
491
- jsonSetExpressionGroup[jsonSetExpr].push(__spreadProps(__spreadValues({}, queryFunction), {
492
- isCommonColumn: true
493
- }));
494
- delete queryFunctions[index];
495
- }
496
- });
497
- });
498
- }
499
- /**
500
- * @description Builds a jsonb expression like jsonb_insert, or jsonb_set
501
- * @param jsonSetExpressions
502
- * @param functionName
503
- * @returns
504
- */
505
- buildJSONBExpression(jsonSetExpressions, functionName) {
506
- let jsonSetStringExpr = "";
507
- jsonSetExpressions.forEach((expression, index) => {
508
- let _tempFunctionName = functionName;
509
- let { columnName, jsonExpr } = expression;
510
- if (expression.isCommonColumn) {
511
- const jsonExpression = expression.value.jsonExpression[0];
512
- _tempFunctionName = jsonExpression.functionName;
513
- jsonExpr = jsonExpression.jsonExpr;
514
- columnName = jsonExpression.columnName;
515
- }
516
- if (index === 0) {
517
- jsonSetStringExpr = `${_tempFunctionName}(${columnName},${jsonExpr})`;
518
- } else {
519
- jsonSetStringExpr = `${_tempFunctionName}(${jsonSetStringExpr},${jsonExpr})`;
520
- }
521
- });
522
- return jsonSetStringExpr;
523
- }
524
- /**
525
- * @description Serializes a JSON value
526
- * @param value
527
- * @returns
528
- */
529
- serializeJSONValue(value) {
530
- const valueSerialized = typeof value == "object" ? `${JSON.stringify(value).replace(/'/g, "''")}` : value;
531
- return valueSerialized;
532
- }
533
- getJSONBSetExpressionByAction(path, value, options) {
534
- path = path.replace(/\[(\d+)\]/g, ".$1");
535
- const pathSplitted = path.split(".");
536
- const parentPath = pathSplitted[0];
537
- const { createNewColumn, actionName } = options;
538
- const pathSerialized = pathSplitted.slice(1).join(",");
539
- const valueSerialized = `'${JSON.stringify(value).replace(
540
- /'/g,
541
- "''"
542
- )}'`;
543
- if (actionName == DYNAMO_DB_UPDATE_ACTIONS.ADD) {
544
- if (typeof value != "string" && !isNaN(value)) {
545
- const resultExpr = {
546
- jsonExpr: `'{${pathSerialized}}',to_jsonb(COALESCE(("${parentPath}"#>'{${pathSerialized}}')::numeric,0) + ${valueSerialized})`,
547
- columnName: `"${parentPath}"`
548
- };
549
- return resultExpr;
550
- }
551
- }
552
- return {
553
- jsonExpr: `'{${pathSerialized}}',${valueSerialized},${createNewColumn}`,
554
- columnName: `"${parentPath}"`
555
- };
556
- }
557
- getListAppendDefFromValue(queryValue, columnType) {
558
- const regexListAppend = /list_append\(([^)]+)\)/gm;
559
- const listAppendString = "list_append(";
560
- const matchList = queryValue.match(regexListAppend) || [];
561
- const groupResult = matchList[0];
562
- if (groupResult) {
563
- const attributesFromGroup = groupResult.slice(listAppendString.length, -1).split(",");
564
- const attributes = {
565
- originalString: groupResult,
566
- path: attributesFromGroup[0].trim(),
567
- value: attributesFromGroup.slice(1).join(",").trim(),
568
- isDynamoFunction: true,
569
- functionExpr: "",
570
- jsonExpression: [{}]
571
- };
572
- if (columnType == "array") {
573
- attributes["functionExpr"] = this.buildArrayAppendExpr(attributes);
574
- } else {
575
- attributes["jsonExpression"] = this.buildJsonbInsertExpr(attributes);
576
- }
577
- return attributes;
578
- }
579
- return null;
580
- }
581
- buildArrayAppendExpr(params) {
582
- const arrayPath = params.path.split(".");
583
- const columnName = arrayPath.shift();
584
- return `ARRAY_APPEND("${columnName}",${params.value})`;
585
- }
586
- buildJsonbInsertExpr(params) {
587
- const arrayPath = params.path.split(".");
588
- const columnName = arrayPath.shift();
589
- const options = {
590
- isDynamoFunction: params == null ? void 0 : params.isDynamoFunction,
591
- relativePath: arrayPath.length && Array.isArray(arrayPath) ? arrayPath : []
592
- };
593
- const jsonbInsertExpressions = this.getExpressionsByDefinitionForJSONBInsert(
594
- columnName,
595
- params.value,
596
- options
597
- );
598
- return jsonbInsertExpressions;
599
- }
600
- getExpressionsByDefinitionForJSONBInsert(columnName, value, options) {
601
- const jsonbInsertExpressions = [];
602
- let pathToAffect = "0";
603
- if (options.isDynamoFunction == true) {
604
- options.relativePath.push("0");
605
- pathToAffect = options.relativePath.join(",");
606
- }
607
- try {
608
- const parsedValue = JSON.parse(value);
609
- if (Array.isArray(parsedValue)) {
610
- parsedValue.forEach((arrayValue) => {
611
- arrayValue = typeof arrayValue == "string" ? `"${arrayValue}"` : arrayValue;
612
- jsonbInsertExpressions.push({
613
- jsonExpr: `'{${pathToAffect}}','${this.serializeJSONValue(
614
- arrayValue
615
- )}'`,
616
- columnName: `"${columnName}"`,
617
- functionName: "jsonb_insert"
618
- });
619
- });
620
- } else {
621
- jsonbInsertExpressions.push({
622
- jsonExpr: `'{${pathToAffect}}','${this.serializeJSONValue(
623
- parsedValue
624
- )}'`,
625
- columnName: `"${columnName}"`,
626
- functionName: "jsonb_insert"
627
- });
628
- }
629
- } catch (error) {
630
- jsonbInsertExpressions.push({
631
- jsonExpr: `'{${pathToAffect}}','${value}'`,
632
- columnName: `"${columnName}"`,
633
- functionName: "jsonb_insert"
634
- });
635
- }
636
- return jsonbInsertExpressions;
637
- }
638
- getInsertExprFromJsonbDef(queryValue, columnType) {
639
- const listAppendParams = this.getListAppendDefFromValue(
640
- queryValue,
641
- columnType
642
- );
643
- if (listAppendParams != null && (listAppendParams == null ? void 0 : listAppendParams.jsonExpression.length) === 0) {
644
- queryValue = queryValue.replace(
645
- listAppendParams.originalString,
646
- listAppendParams.functionExpr
647
- );
648
- } else {
649
- return listAppendParams;
650
- }
651
- return queryValue;
652
- }
653
- replacePathAndValueByAttributeNames(actions, options, columns, actionName) {
654
- return actions.map((action) => {
655
- action.path = this.replaceExpressionAttributeNames(
656
- action.path,
657
- options
658
- );
659
- if (typeof action.value == "string" && action.value.includes("list_append")) {
660
- action.path = action.path.split(".")[0];
661
- const column = columns[action.path];
662
- action.value = this.replaceExpressionAttributeValuesForDynamoFunctions(
663
- action.value,
664
- options
665
- );
666
- action.value = this.getInsertExprFromJsonbDef(
667
- action.value,
668
- column.type
669
- );
670
- action.dynamoFuncName = "list_append";
671
- } else {
672
- action.value = this.replaceExpressionAttributeValues(
673
- action.value,
674
- options
675
- );
676
- }
677
- action.actionName = actionName;
678
- action.createNewColumn = true;
679
- return action;
680
- });
681
- }
682
- replaceExpressionAttributeValuesForDynamoFunctions(value, options) {
683
- const { expressionAttributeNames, expressionAttributeValues } = options;
684
- const exprAttributeNamesKeys = expressionAttributeNames ? Object.keys(expressionAttributeNames) : [];
685
- const exprAttributeValuesKeys = expressionAttributeValues ? Object.keys(expressionAttributeValues) : [];
686
- if (exprAttributeNamesKeys.length > 0) {
687
- exprAttributeNamesKeys.forEach((exprAttribute) => {
688
- value = value.replace(
689
- exprAttribute,
690
- expressionAttributeNames[exprAttribute]
691
- );
692
- });
693
- }
694
- if (exprAttributeValuesKeys.length > 0) {
695
- exprAttributeValuesKeys.forEach((exprAttribute) => {
696
- const valueSerialized = this.serializeJSONValue(
697
- expressionAttributeValues[exprAttribute]
698
- );
699
- value = value.replace(exprAttribute, `${valueSerialized}`);
700
- });
701
- }
702
- return value;
703
- }
704
- replaceExpressionAttributeNames(path, options) {
705
- const { expressionAttributeNames } = options;
706
- if (expressionAttributeNames) {
707
- Object.keys(expressionAttributeNames).forEach(
708
- (attributeName) => {
709
- const attributeNameValue = expressionAttributeNames[attributeName];
710
- path = path.replace(attributeName, attributeNameValue);
711
- }
712
- );
713
- }
714
- return path;
715
- }
716
- replaceExpressionAttributeValues(value, options) {
717
- const { expressionAttributeValues } = options;
718
- if (expressionAttributeValues[value] != void 0) {
719
- return expressionAttributeValues[value];
720
- }
721
- return value;
722
- }
723
- getValueTypeAsPostgresDefinition(value) {
724
- switch (typeof value) {
725
- case "number":
726
- return "number";
727
- case "boolean":
728
- return "boolean";
729
- case "string":
730
- default:
731
- return "text";
732
- }
733
- }
734
- };
735
-
736
- // src/services/cruds/postgresql/postgreSqlCrud.service.ts
737
- var PostgreSqlCrudService = class extends PostgresqlClientService {
738
- constructor(tableSchema, poolClient) {
739
- super(tableSchema, poolClient);
740
- this.tableSchema = tableSchema;
741
- }
742
- get idColumnName() {
743
- return findIdColumnName(this.tableSchema.columns);
744
- }
745
- normalizeInputData(inputData) {
746
- var _a;
747
- inputData.qvAttributes = {};
748
- for (const key in inputData) {
749
- if (!this.tableSchema.columns[key] && key !== "qvAttributes") {
750
- inputData.qvAttributes[key] = inputData[key];
751
- delete inputData[key];
752
- } else if (Array.isArray(inputData[key]) && ((_a = this.tableSchema.columns[key]) == null ? void 0 : _a.type) !== "array") {
753
- inputData[key] = JSON.stringify(inputData[key]);
754
- }
755
- }
756
- }
757
- getItem(data) {
758
- const schemaColumns = Object.entries(this.tableSchema.columns);
759
- schemaColumns.forEach(([key, value]) => {
760
- if (value.type === "big_number") {
761
- if (data[key]) data[key] = Number(data[key]);
762
- }
763
- });
764
- const resultItem = __spreadValues(__spreadValues({}, data), data.qvAttributes);
765
- delete resultItem["qvAttributes"];
766
- return resultItem;
767
- }
768
- prepareData(data) {
769
- const inputData = __spreadValues({}, data);
770
- this.normalizeInputData(inputData);
771
- return inputData;
772
- }
773
- buildCreateResponseBatch(result) {
774
- const rows = Array.isArray(result == null ? void 0 : result.rows) ? result.rows : [];
775
- return {
776
- items: rows.map((r) => this.getItem(r)),
777
- unprocessedItems: []
778
- };
779
- }
780
- create(data) {
781
- if (Array.isArray(data)) {
782
- const inputDataArray = data.map((item) => this.prepareData(item));
783
- return this.createCommand(inputDataArray).then((result) => {
784
- return this.buildCreateResponseBatch(result);
785
- });
786
- } else {
787
- const inputData = this.prepareData(data);
788
- return this.createCommand([inputData]).then(
789
- (result) => result.rowCount ? this.getItem(result.rows[0]) : null
790
- );
791
- }
792
- }
793
- findItem(findOptions) {
794
- return this.findCommand(findOptions).then((data) => {
795
- return (data == null ? void 0 : data.length) ? this.getItem(data[0]) : null;
796
- });
797
- }
798
- async processQueryResult(findOptions, omitPagination = false) {
799
- const rows = await this.findCommand(findOptions);
800
- const items = rows.map(
801
- (row) => this.getItem(row)
802
- );
803
- const { limit, from } = (findOptions == null ? void 0 : findOptions.pagination) || {};
804
- const hasMoreRecords = items.length && items.length === limit;
805
- const newFrom = limit && hasMoreRecords ? limit + (from || 0) : null;
806
- const result = {
807
- items,
808
- pagination: omitPagination ? null : { limit, from: newFrom },
809
- count: items.length
810
- };
811
- return result;
812
- }
813
- async find(findOptions) {
814
- return this.processQueryResult(findOptions);
815
- }
816
- async findAll(findOptions) {
817
- return this.processQueryResult(findOptions, true);
818
- }
819
- async findCount(findOptions) {
820
- const items = await this.findCommand(__spreadProps(__spreadValues({}, findOptions), {
821
- aggregateFunction: "COUNT" /* COUNT */
822
- }));
823
- const aggFunctionProperty = buildAggFunctionAlias(
824
- "COUNT" /* COUNT */
825
- );
826
- const item = items.length ? items[0] : {};
827
- return item[aggFunctionProperty] || 0;
828
- }
829
- async update(filters, data) {
830
- const savedRecord = await this.findItem({ filters });
831
- const inputData = __spreadValues(__spreadValues({}, savedRecord), data);
832
- await this.updateCommand(filters, this.prepareData(inputData));
833
- return this.getItem(inputData);
834
- }
835
- async remove(filters, options) {
836
- await this.deleteCommand(filters, options == null ? void 0 : options.filterGroups);
837
- }
838
- runQuery(querySentence, values) {
839
- return super.runQuery(querySentence, values);
840
- }
841
- async updateExpressions(filters, actions, options) {
842
- const result = await this.updateExpressionCommand(
843
- filters,
844
- actions,
845
- options
846
- );
847
- return PersistenceErrorWrapper(result);
848
- }
849
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
850
- runRawQuery(query, params) {
851
- throw super.runQuery(query, params);
852
- }
853
- };
854
-
855
- export { PostgreSqlCrudService };
856
- //# sourceMappingURL=postgreSqlCrud.service-AD2CHR2Z.mjs.map
857
- //# sourceMappingURL=postgreSqlCrud.service-AD2CHR2Z.mjs.map