@qrvey/data-persistence 0.5.4-beta → 0.5.4-bundled

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