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