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