@qrvey/data-persistence 0.5.7 → 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 (45) hide show
  1. package/dist/cjs/helpers/crudHelpers.js +3 -4
  2. package/dist/cjs/helpers/crudHelpers.js.map +1 -1
  3. package/dist/cjs/helpers/errorHelper.js +1 -2
  4. package/dist/cjs/helpers/errorHelper.js.map +1 -1
  5. package/dist/cjs/helpers/queryHelpers.js +2 -2
  6. package/dist/cjs/helpers/queryHelpers.js.map +1 -1
  7. package/dist/cjs/helpers/tableHelper.js +4 -5
  8. package/dist/cjs/helpers/tableHelper.js.map +1 -1
  9. package/dist/cjs/index.js +3 -1
  10. package/dist/cjs/index.js.map +1 -1
  11. package/dist/cjs/services/crud.service.js +2 -2
  12. package/dist/cjs/services/crud.service.js.map +1 -1
  13. package/dist/cjs/services/crudFactory.service.js +5 -34
  14. package/dist/cjs/services/crudFactory.service.js.map +1 -1
  15. package/dist/cjs/services/cruds/dynamodb/dynamoDbCrud.service.js +6 -7
  16. package/dist/cjs/services/cruds/dynamodb/dynamoDbCrud.service.js.map +1 -1
  17. package/dist/cjs/services/cruds/dynamodb/queryBuilder.service.js.map +1 -1
  18. package/dist/cjs/services/cruds/dynamodb/queryBuilderCondition.service.js.map +1 -1
  19. package/dist/cjs/services/cruds/index.js +19 -0
  20. package/dist/cjs/services/cruds/index.js.map +1 -0
  21. package/dist/cjs/services/cruds/postgresql/connection.service.js.map +1 -1
  22. package/dist/cjs/services/cruds/postgresql/postgreSqlClient.service.js +21 -21
  23. package/dist/cjs/services/cruds/postgresql/postgreSqlClient.service.js.map +1 -1
  24. package/dist/cjs/services/cruds/postgresql/postgreSqlCrud.service.js +4 -2
  25. package/dist/cjs/services/cruds/postgresql/postgreSqlCrud.service.js.map +1 -1
  26. package/dist/cjs/services/cruds/postgresql/query.service.js +2 -2
  27. package/dist/cjs/services/cruds/postgresql/query.service.js.map +1 -1
  28. package/dist/cjs/services/dbPool.service.js +1 -2
  29. package/dist/cjs/services/dbPool.service.js.map +1 -1
  30. package/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -0
  31. package/dist/cjs/utils/constants.js +2 -2
  32. package/dist/cjs/utils/constants.js.map +1 -1
  33. package/dist/esm/index.d.mts +4 -3
  34. package/dist/esm/index.mjs +1802 -18
  35. package/dist/esm/index.mjs.map +1 -1
  36. package/dist/types/index.d.ts +4 -3
  37. package/package.json +11 -25
  38. package/dist/esm/chunk-6MOAJFFY.mjs +0 -112
  39. package/dist/esm/chunk-6MOAJFFY.mjs.map +0 -1
  40. package/dist/esm/chunk-DHIGNHXS.mjs +0 -58
  41. package/dist/esm/chunk-DHIGNHXS.mjs.map +0 -1
  42. package/dist/esm/dynamoDbCrud.service-J7ZOB5QW.mjs +0 -822
  43. package/dist/esm/dynamoDbCrud.service-J7ZOB5QW.mjs.map +0 -1
  44. package/dist/esm/postgreSqlCrud.service-JGJELA6R.mjs +0 -866
  45. package/dist/esm/postgreSqlCrud.service-JGJELA6R.mjs.map +0 -1
@@ -1,866 +0,0 @@
1
- import { findIdColumnName, buildAggFunctionAlias, PersistenceErrorWrapper, getTableName } from './chunk-DHIGNHXS.mjs';
2
- import { __spreadValues, __spreadProps, DEFAULT_PG_SCHEMA, POSTGRES_FILTER_OPERATOR_MAP, DYNAMO_DB_UPDATE_ACTIONS } from './chunk-6MOAJFFY.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))
212
- return "{}";
213
- const isNumberArray = typeof value[0] === "number";
214
- if (isNumberArray) {
215
- return `{${value.join(",")}}`;
216
- } else {
217
- return `{${value.map((val) => `"${val}"`).join(",")}}`;
218
- }
219
- }
220
- return value;
221
- }
222
- async createCommand(data) {
223
- const keys = Object.keys(data[0]);
224
- const values = data.map(
225
- (item) => keys.map((key) => this.formatValue(item[key]))
226
- );
227
- const query = format(
228
- `INSERT INTO ${format.ident(this.dbSchema)}.${format.ident(
229
- this.tableName
230
- )} (%I) VALUES %L RETURNING *;`,
231
- keys,
232
- values
233
- );
234
- return this.runQuery(query);
235
- }
236
- isValidFiltersInput(filters) {
237
- const isValidArrayFilters = Array.isArray(filters) && (filters == null ? void 0 : filters.length) > 0;
238
- const isValidCompositeFilters = this.isCompositeFilter(filters);
239
- return isValidArrayFilters || isValidCompositeFilters;
240
- }
241
- replaceFilterTokensInQuery(query, filters) {
242
- if (!filters)
243
- return query;
244
- if (this.isValidFiltersInput(filters)) {
245
- const filterClause = this.buildFilterClause(filters);
246
- return query.replace(/{{filters}}/g, filterClause);
247
- }
248
- }
249
- addFiltersToQuery(query, filters) {
250
- if (!filters)
251
- return query;
252
- if (this.isValidFiltersInput(filters))
253
- query += ` WHERE ${this.buildFilterClause(filters)}`;
254
- return query;
255
- }
256
- addOrderByToQuery(query, orderBy) {
257
- if (orderBy)
258
- query += ` ORDER BY ${this.buildOrderByClause(orderBy)}`;
259
- return query;
260
- }
261
- addPaginationToQuery(query, pagination) {
262
- if (pagination) {
263
- const { limit, from } = pagination;
264
- if (limit)
265
- query += ` LIMIT ${limit}`;
266
- if (from)
267
- query += ` OFFSET ${from}`;
268
- }
269
- return query;
270
- }
271
- getSelectClause(aggregateFunction, fields = []) {
272
- if (aggregateFunction)
273
- return `CAST(${aggregateFunction}(1) AS INTEGER) AS "${buildAggFunctionAlias(
274
- aggregateFunction
275
- )}"`;
276
- if (!(fields == null ? void 0 : fields.length))
277
- return "*";
278
- return this.parseFields(fields).join(", ");
279
- }
280
- parseFields(fields) {
281
- const columnsFromSchema = Object.keys(
282
- this.crudSchema.columns
283
- );
284
- const attributes = fields.filter((field) => columnsFromSchema.indexOf(field) !== -1).map((field) => `"${field}"`);
285
- fields.filter((field) => columnsFromSchema.indexOf(field) === -1).forEach((field) => {
286
- attributes.push(`"qvAttributes" ->> '${field}' as "${field}"`);
287
- });
288
- return attributes;
289
- }
290
- resolveWithQueries(rawWith) {
291
- const withQueries = rawWith.map(({ alias, query, filters }) => {
292
- const withQuery = this.replaceFilterTokensInQuery(query, filters);
293
- return `${alias} AS (${withQuery})`;
294
- });
295
- return withQueries;
296
- }
297
- getRawWithClause(rawWith) {
298
- let rawWithClause = "";
299
- if (rawWith == null ? void 0 : rawWith.length) {
300
- const withQueries = this.resolveWithQueries(rawWith);
301
- rawWithClause = "WITH " + withQueries.join(",\n");
302
- }
303
- return rawWithClause;
304
- }
305
- getQueryFrom() {
306
- return this.isTemporalTable ? format.ident(this.tableName) : `${format.ident(this.dbSchema)}.${format.ident(this.tableName)}`;
307
- }
308
- async findCommand(options = {}) {
309
- const rawWithClause = this.getRawWithClause(options.rawWith);
310
- let query = `SELECT ${this.getSelectClause(
311
- options.aggregateFunction,
312
- options.fields
313
- )} FROM ${this.getQueryFrom()}`;
314
- query = this.addFiltersToQuery(query, options.filters);
315
- if (!options.aggregateFunction) {
316
- query = this.addOrderByToQuery(query, options.sorting);
317
- query = this.addPaginationToQuery(query, options.pagination);
318
- }
319
- if (rawWithClause) {
320
- query = `${rawWithClause} ${query}`;
321
- }
322
- return (await this.runQuery(query)).rows;
323
- }
324
- sanitizeValue(value) {
325
- if (Array.isArray(value)) {
326
- if (value.length === 0)
327
- ;
328
- const formattedArray = value.map((item) => {
329
- if (typeof item === "string") {
330
- return `'${item}'`;
331
- } else if (typeof item === "object") {
332
- return JSON.stringify(item);
333
- } else {
334
- return item;
335
- }
336
- }).join(",");
337
- return JSON.stringify(formattedArray);
338
- } else {
339
- return format.literal(value);
340
- }
341
- }
342
- async updateCommand(filters, data) {
343
- let query = `UPDATE ${format.ident(this.dbSchema)}.${format.ident(
344
- this.tableName
345
- )} SET`;
346
- const updateClauses = Object.entries(data).map(([key, value]) => {
347
- const dbValue = format.literal(this.formatValue(value));
348
- return `${format.ident(key)} = ${dbValue}`;
349
- });
350
- query += ` ${updateClauses.join(", ")}`;
351
- query += " WHERE ";
352
- query += this.buildFilterClause(filters);
353
- return this.runQuery(query);
354
- }
355
- buildFilterClauseForFilterGroups(filterGroups) {
356
- const filterClauses = filterGroups.map((filterGroup) => {
357
- return `(${this.buildFilterClause(filterGroup)})`;
358
- });
359
- return filterClauses.join(" OR ");
360
- }
361
- async deleteCommand(filters, useFilterGroups = false) {
362
- let query = `DELETE FROM ${format.ident(this.dbSchema)}.${format.ident(
363
- this.tableName
364
- )}`;
365
- if (filters) {
366
- query += " WHERE ";
367
- if (useFilterGroups) {
368
- query += this.buildFilterClauseForFilterGroups(
369
- filters
370
- );
371
- } else {
372
- query += this.buildFilterClause(
373
- filters
374
- );
375
- }
376
- }
377
- return this.runQuery(query);
378
- }
379
- query(queryText, values) {
380
- return this.runQuery(queryText, values);
381
- }
382
- async updateExpressionCommand(filters, actions, options = {}) {
383
- let query = `UPDATE ${format.ident(this.dbSchema)}.${format.ident(
384
- this.tableName
385
- )} SET`;
386
- const set = actions.SET || [];
387
- const add = actions.ADD || [];
388
- const columns = this.crudSchema.columns;
389
- const setValues = this.replacePathAndValueByAttributeNames(
390
- set,
391
- options,
392
- columns,
393
- DYNAMO_DB_UPDATE_ACTIONS.SET
394
- );
395
- const addValues = this.replacePathAndValueByAttributeNames(
396
- add,
397
- options,
398
- columns,
399
- DYNAMO_DB_UPDATE_ACTIONS.ADD
400
- );
401
- const setValuesAndAddValues = setValues.concat(addValues);
402
- const updateClauses = [];
403
- const jsonSetExpressionGroup = {};
404
- const queryFunctions = [];
405
- setValuesAndAddValues.forEach((expression) => {
406
- const { path, value, createNewColumn, actionName, dynamoFuncName } = expression;
407
- if (dynamoFuncName) {
408
- queryFunctions.push({ path, value, dynamoFuncName });
409
- }
410
- if (path.includes(".") && !dynamoFuncName) {
411
- const jsonExpr = this.getJSONBSetExpressionByAction(
412
- path,
413
- value,
414
- {
415
- createNewColumn,
416
- actionName
417
- }
418
- );
419
- const columnName = jsonExpr.columnName;
420
- if (!jsonSetExpressionGroup[columnName]) {
421
- jsonSetExpressionGroup[columnName] = [jsonExpr];
422
- } else {
423
- jsonSetExpressionGroup[columnName].push(jsonExpr);
424
- }
425
- } else if (!dynamoFuncName) {
426
- let expValue;
427
- const column = this.crudSchema.columns[path];
428
- if ((column == null ? void 0 : column.type) == void 0)
429
- throw `Column type definition for column: (${path}) must be in the CrudSchema`;
430
- let formattedValue;
431
- switch (column.type) {
432
- case "object":
433
- {
434
- const valueSerialized = `${JSON.stringify(
435
- value
436
- ).replace(/'/g, "''")}`;
437
- expValue = `'${valueSerialized}'::jsonb`;
438
- }
439
- break;
440
- case "array":
441
- formattedValue = format.literal(value);
442
- expValue = `ARRAY[${formattedValue}]`;
443
- break;
444
- default:
445
- formattedValue = format.literal(value);
446
- expValue = formattedValue;
447
- break;
448
- }
449
- this.crudSchema.columns;
450
- updateClauses.push(`${format.ident(path)} = ${expValue}`);
451
- }
452
- });
453
- this.setCommonColumnsQueryFunctions(
454
- jsonSetExpressionGroup,
455
- queryFunctions
456
- );
457
- if (Object.keys(jsonSetExpressionGroup).length > 0) {
458
- Object.keys(jsonSetExpressionGroup).forEach((groupIndex) => {
459
- const jsonSetExpression = this.buildJSONBExpression(
460
- jsonSetExpressionGroup[groupIndex],
461
- "jsonb_set"
462
- );
463
- updateClauses.push(`${groupIndex} = ${jsonSetExpression}`);
464
- });
465
- }
466
- this.buildUpdateClausesFormDynamoFunctions(
467
- queryFunctions,
468
- updateClauses
469
- );
470
- query += ` ${updateClauses.join(", ")}`;
471
- query += " WHERE ";
472
- query += this.buildFilterClause(filters);
473
- return this.runQuery(query);
474
- }
475
- buildUpdateClausesFormDynamoFunctions(queryFunctions, updateClauses) {
476
- if (queryFunctions.length > 0) {
477
- queryFunctions.forEach((queryFunction) => {
478
- if (typeof queryFunction.value == "object") {
479
- const jsonExpr = this.buildJSONBExpression(
480
- queryFunction.value.jsonExpression,
481
- "jsonb_insert"
482
- );
483
- updateClauses.push(
484
- `${format.ident(queryFunction.path)} = ${jsonExpr}`
485
- );
486
- } else {
487
- updateClauses.push(
488
- `${format.ident(queryFunction.path)} = ${queryFunction.value}`
489
- );
490
- }
491
- });
492
- }
493
- }
494
- setCommonColumnsQueryFunctions(jsonSetExpressionGroup, queryFunctions) {
495
- Object.keys(jsonSetExpressionGroup).forEach((jsonSetExpr) => {
496
- queryFunctions.forEach((queryFunction, index) => {
497
- const columnPath = `"${queryFunction.path}"`;
498
- if (columnPath === jsonSetExpr) {
499
- jsonSetExpressionGroup[jsonSetExpr].push(__spreadProps(__spreadValues({}, queryFunction), {
500
- isCommonColumn: true
501
- }));
502
- delete queryFunctions[index];
503
- }
504
- });
505
- });
506
- }
507
- /**
508
- * @description Builds a jsonb expression like jsonb_insert, or jsonb_set
509
- * @param jsonSetExpressions
510
- * @param functionName
511
- * @returns
512
- */
513
- buildJSONBExpression(jsonSetExpressions, functionName) {
514
- let jsonSetStringExpr = "";
515
- jsonSetExpressions.forEach((expression, index) => {
516
- let _tempFunctionName = functionName;
517
- let { columnName, jsonExpr } = expression;
518
- if (expression.isCommonColumn) {
519
- const jsonExpression = expression.value.jsonExpression[0];
520
- _tempFunctionName = jsonExpression.functionName;
521
- jsonExpr = jsonExpression.jsonExpr;
522
- columnName = jsonExpression.columnName;
523
- }
524
- if (index === 0) {
525
- jsonSetStringExpr = `${_tempFunctionName}(${columnName},${jsonExpr})`;
526
- } else {
527
- jsonSetStringExpr = `${_tempFunctionName}(${jsonSetStringExpr},${jsonExpr})`;
528
- }
529
- });
530
- return jsonSetStringExpr;
531
- }
532
- /**
533
- * @description Serializes a JSON value
534
- * @param value
535
- * @returns
536
- */
537
- serializeJSONValue(value) {
538
- const valueSerialized = typeof value == "object" ? `${JSON.stringify(value).replace(/'/g, "''")}` : value;
539
- return valueSerialized;
540
- }
541
- getJSONBSetExpressionByAction(path, value, options) {
542
- path = path.replace(/\[(\d+)\]/g, ".$1");
543
- const pathSplitted = path.split(".");
544
- const parentPath = pathSplitted[0];
545
- const { createNewColumn, actionName } = options;
546
- const pathSerialized = pathSplitted.slice(1).join(",");
547
- const valueSerialized = `'${JSON.stringify(value).replace(
548
- /'/g,
549
- "''"
550
- )}'`;
551
- if (actionName == DYNAMO_DB_UPDATE_ACTIONS.ADD) {
552
- if (typeof value != "string" && !isNaN(value)) {
553
- const resultExpr = {
554
- jsonExpr: `'{${pathSerialized}}',to_jsonb(COALESCE(("${parentPath}"#>'{${pathSerialized}}')::numeric,0) + ${valueSerialized})`,
555
- columnName: `"${parentPath}"`
556
- };
557
- return resultExpr;
558
- }
559
- }
560
- return {
561
- jsonExpr: `'{${pathSerialized}}',${valueSerialized},${createNewColumn}`,
562
- columnName: `"${parentPath}"`
563
- };
564
- }
565
- getListAppendDefFromValue(queryValue, columnType) {
566
- const regexListAppend = /list_append\(([^)]+)\)/gm;
567
- const listAppendString = "list_append(";
568
- const matchList = queryValue.match(regexListAppend) || [];
569
- const groupResult = matchList[0];
570
- if (groupResult) {
571
- const attributesFromGroup = groupResult.slice(listAppendString.length, -1).split(",");
572
- const attributes = {
573
- originalString: groupResult,
574
- path: attributesFromGroup[0].trim(),
575
- value: attributesFromGroup.slice(1).join(",").trim(),
576
- isDynamoFunction: true,
577
- functionExpr: "",
578
- jsonExpression: [{}]
579
- };
580
- if (columnType == "array") {
581
- attributes["functionExpr"] = this.buildArrayAppendExpr(attributes);
582
- } else {
583
- attributes["jsonExpression"] = this.buildJsonbInsertExpr(attributes);
584
- }
585
- return attributes;
586
- }
587
- return null;
588
- }
589
- buildArrayAppendExpr(params) {
590
- const arrayPath = params.path.split(".");
591
- const columnName = arrayPath.shift();
592
- return `ARRAY_APPEND("${columnName}",${params.value})`;
593
- }
594
- buildJsonbInsertExpr(params) {
595
- const arrayPath = params.path.split(".");
596
- const columnName = arrayPath.shift();
597
- const options = {
598
- isDynamoFunction: params == null ? void 0 : params.isDynamoFunction,
599
- relativePath: arrayPath.length && Array.isArray(arrayPath) ? arrayPath : []
600
- };
601
- const jsonbInsertExpressions = this.getExpressionsByDefinitionForJSONBInsert(
602
- columnName,
603
- params.value,
604
- options
605
- );
606
- return jsonbInsertExpressions;
607
- }
608
- getExpressionsByDefinitionForJSONBInsert(columnName, value, options) {
609
- const jsonbInsertExpressions = [];
610
- let pathToAffect = "0";
611
- if (options.isDynamoFunction == true) {
612
- options.relativePath.push("0");
613
- pathToAffect = options.relativePath.join(",");
614
- }
615
- try {
616
- const parsedValue = JSON.parse(value);
617
- if (Array.isArray(parsedValue)) {
618
- parsedValue.forEach((arrayValue) => {
619
- arrayValue = typeof arrayValue == "string" ? `"${arrayValue}"` : arrayValue;
620
- jsonbInsertExpressions.push({
621
- jsonExpr: `'{${pathToAffect}}','${this.serializeJSONValue(
622
- arrayValue
623
- )}'`,
624
- columnName: `"${columnName}"`,
625
- functionName: "jsonb_insert"
626
- });
627
- });
628
- } else {
629
- jsonbInsertExpressions.push({
630
- jsonExpr: `'{${pathToAffect}}','${this.serializeJSONValue(
631
- parsedValue
632
- )}'`,
633
- columnName: `"${columnName}"`,
634
- functionName: "jsonb_insert"
635
- });
636
- }
637
- } catch (error) {
638
- jsonbInsertExpressions.push({
639
- jsonExpr: `'{${pathToAffect}}','${value}'`,
640
- columnName: `"${columnName}"`,
641
- functionName: "jsonb_insert"
642
- });
643
- }
644
- return jsonbInsertExpressions;
645
- }
646
- getInsertExprFromJsonbDef(queryValue, columnType) {
647
- const listAppendParams = this.getListAppendDefFromValue(
648
- queryValue,
649
- columnType
650
- );
651
- if (listAppendParams != null && (listAppendParams == null ? void 0 : listAppendParams.jsonExpression.length) === 0) {
652
- queryValue = queryValue.replace(
653
- listAppendParams.originalString,
654
- listAppendParams.functionExpr
655
- );
656
- } else {
657
- return listAppendParams;
658
- }
659
- return queryValue;
660
- }
661
- replacePathAndValueByAttributeNames(actions, options, columns, actionName) {
662
- return actions.map((action) => {
663
- action.path = this.replaceExpressionAttributeNames(
664
- action.path,
665
- options
666
- );
667
- if (typeof action.value == "string" && action.value.includes("list_append")) {
668
- action.path = action.path.split(".")[0];
669
- const column = columns[action.path];
670
- action.value = this.replaceExpressionAttributeValuesForDynamoFunctions(
671
- action.value,
672
- options
673
- );
674
- action.value = this.getInsertExprFromJsonbDef(
675
- action.value,
676
- column.type
677
- );
678
- action.dynamoFuncName = "list_append";
679
- } else {
680
- action.value = this.replaceExpressionAttributeValues(
681
- action.value,
682
- options
683
- );
684
- }
685
- action.actionName = actionName;
686
- action.createNewColumn = true;
687
- return action;
688
- });
689
- }
690
- replaceExpressionAttributeValuesForDynamoFunctions(value, options) {
691
- const { expressionAttributeNames, expressionAttributeValues } = options;
692
- const exprAttributeNamesKeys = expressionAttributeNames ? Object.keys(expressionAttributeNames) : [];
693
- const exprAttributeValuesKeys = expressionAttributeValues ? Object.keys(expressionAttributeValues) : [];
694
- if (exprAttributeNamesKeys.length > 0) {
695
- exprAttributeNamesKeys.forEach((exprAttribute) => {
696
- value = value.replace(
697
- exprAttribute,
698
- expressionAttributeNames[exprAttribute]
699
- );
700
- });
701
- }
702
- if (exprAttributeValuesKeys.length > 0) {
703
- exprAttributeValuesKeys.forEach((exprAttribute) => {
704
- const valueSerialized = this.serializeJSONValue(
705
- expressionAttributeValues[exprAttribute]
706
- );
707
- value = value.replace(exprAttribute, `${valueSerialized}`);
708
- });
709
- }
710
- return value;
711
- }
712
- replaceExpressionAttributeNames(path, options) {
713
- const { expressionAttributeNames } = options;
714
- if (expressionAttributeNames) {
715
- Object.keys(expressionAttributeNames).forEach(
716
- (attributeName) => {
717
- const attributeNameValue = expressionAttributeNames[attributeName];
718
- path = path.replace(attributeName, attributeNameValue);
719
- }
720
- );
721
- }
722
- return path;
723
- }
724
- replaceExpressionAttributeValues(value, options) {
725
- const { expressionAttributeValues } = options;
726
- if (expressionAttributeValues[value] != void 0) {
727
- return expressionAttributeValues[value];
728
- }
729
- return value;
730
- }
731
- getValueTypeAsPostgresDefinition(value) {
732
- switch (typeof value) {
733
- case "number":
734
- return "number";
735
- case "boolean":
736
- return "boolean";
737
- case "string":
738
- default:
739
- return "text";
740
- }
741
- }
742
- };
743
-
744
- // src/services/cruds/postgresql/postgreSqlCrud.service.ts
745
- var PostgreSqlCrudService = class extends PostgresqlClientService {
746
- constructor(tableSchema, poolClient) {
747
- super(tableSchema, poolClient);
748
- this.tableSchema = tableSchema;
749
- }
750
- get idColumnName() {
751
- return findIdColumnName(this.tableSchema.columns);
752
- }
753
- normalizeInputData(inputData) {
754
- var _a;
755
- inputData.qvAttributes = {};
756
- for (const key in inputData) {
757
- if (!this.tableSchema.columns[key] && key !== "qvAttributes") {
758
- inputData.qvAttributes[key] = inputData[key];
759
- delete inputData[key];
760
- } else if (Array.isArray(inputData[key]) && ((_a = this.tableSchema.columns[key]) == null ? void 0 : _a.type) !== "array") {
761
- inputData[key] = JSON.stringify(inputData[key]);
762
- }
763
- }
764
- }
765
- getItem(data) {
766
- const schemaColumns = Object.entries(this.tableSchema.columns);
767
- schemaColumns.forEach(([key, value]) => {
768
- if (value.type === "big_number") {
769
- if (data[key])
770
- data[key] = Number(data[key]);
771
- }
772
- });
773
- const resultItem = __spreadValues(__spreadValues({}, data), data.qvAttributes);
774
- delete resultItem["qvAttributes"];
775
- return resultItem;
776
- }
777
- prepareData(data) {
778
- const inputData = __spreadValues({}, data);
779
- this.normalizeInputData(inputData);
780
- return inputData;
781
- }
782
- buildCreateResponseBatch(result) {
783
- const rows = Array.isArray(result == null ? void 0 : result.rows) ? result.rows : [];
784
- return {
785
- items: rows.map((r) => this.getItem(r)),
786
- unprocessedItems: []
787
- };
788
- }
789
- create(data) {
790
- if (Array.isArray(data)) {
791
- const inputDataArray = data.map((item) => this.prepareData(item));
792
- return this.createCommand(inputDataArray).then((result) => {
793
- return this.buildCreateResponseBatch(result);
794
- });
795
- } else {
796
- const inputData = this.prepareData(data);
797
- return this.createCommand([inputData]).then(
798
- (result) => result.rowCount ? this.getItem(result.rows[0]) : null
799
- );
800
- }
801
- }
802
- findItem(findOptions) {
803
- return this.findCommand(findOptions).then((data) => {
804
- return (data == null ? void 0 : data.length) ? this.getItem(data[0]) : null;
805
- });
806
- }
807
- async processQueryResult(findOptions, omitPagination = false) {
808
- const rows = await this.findCommand(findOptions);
809
- const items = rows.map(
810
- (row) => this.getItem(row)
811
- );
812
- const { limit, from } = (findOptions == null ? void 0 : findOptions.pagination) || {};
813
- const hasMoreRecords = items.length && items.length === limit;
814
- const newFrom = limit && hasMoreRecords ? limit + (from || 0) : null;
815
- const result = {
816
- items,
817
- pagination: omitPagination ? null : { limit, from: newFrom },
818
- count: items.length
819
- };
820
- return result;
821
- }
822
- async find(findOptions) {
823
- return this.processQueryResult(findOptions);
824
- }
825
- async findAll(findOptions) {
826
- return this.processQueryResult(findOptions, true);
827
- }
828
- async findCount(findOptions) {
829
- const items = await this.findCommand(__spreadProps(__spreadValues({}, findOptions), {
830
- aggregateFunction: "COUNT" /* COUNT */
831
- }));
832
- const aggFunctionProperty = buildAggFunctionAlias(
833
- "COUNT" /* COUNT */
834
- );
835
- const item = items.length ? items[0] : {};
836
- return item[aggFunctionProperty] || 0;
837
- }
838
- async update(filters, data) {
839
- const savedRecord = await this.findItem({ filters });
840
- const inputData = __spreadValues(__spreadValues({}, savedRecord), data);
841
- await this.updateCommand(filters, this.prepareData(inputData));
842
- return this.getItem(inputData);
843
- }
844
- async remove(filters, options) {
845
- await this.deleteCommand(filters, options == null ? void 0 : options.filterGroups);
846
- }
847
- runQuery(querySentence, values) {
848
- return super.runQuery(querySentence, values);
849
- }
850
- async updateExpressions(filters, actions, options) {
851
- const result = await this.updateExpressionCommand(
852
- filters,
853
- actions,
854
- options
855
- );
856
- return PersistenceErrorWrapper(result);
857
- }
858
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
859
- runRawQuery(query, params) {
860
- throw super.runQuery(query, params);
861
- }
862
- };
863
-
864
- export { PostgreSqlCrudService };
865
- //# sourceMappingURL=out.js.map
866
- //# sourceMappingURL=postgreSqlCrud.service-JGJELA6R.mjs.map