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