@qrvey/data-persistence 0.5.3 → 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 (29) 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 -20
  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/esm/index.d.mts +11 -2
  18. package/dist/esm/index.mjs +1830 -14
  19. package/dist/esm/index.mjs.map +1 -1
  20. package/dist/types/index.d.ts +11 -2
  21. package/package.json +5 -19
  22. package/dist/esm/chunk-6MOAJFFY.mjs +0 -112
  23. package/dist/esm/chunk-6MOAJFFY.mjs.map +0 -1
  24. package/dist/esm/chunk-DHIGNHXS.mjs +0 -58
  25. package/dist/esm/chunk-DHIGNHXS.mjs.map +0 -1
  26. package/dist/esm/dynamoDbCrud.service-EFYPBZKN.mjs +0 -818
  27. package/dist/esm/dynamoDbCrud.service-EFYPBZKN.mjs.map +0 -1
  28. package/dist/esm/postgreSqlCrud.service-Z6ZT6ITL.mjs +0 -826
  29. package/dist/esm/postgreSqlCrud.service-Z6ZT6ITL.mjs.map +0 -1
@@ -1,826 +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
- 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
- return this.runQuery(query);
438
- }
439
- buildUpdateClausesFormDynamoFunctions(queryFunctions, updateClauses) {
440
- if (queryFunctions.length > 0) {
441
- queryFunctions.forEach((queryFunction) => {
442
- if (typeof queryFunction.value == "object") {
443
- const jsonExpr = this.buildJSONBExpression(
444
- queryFunction.value.jsonExpression,
445
- "jsonb_insert"
446
- );
447
- updateClauses.push(
448
- `${format.ident(queryFunction.path)} = ${jsonExpr}`
449
- );
450
- } else {
451
- updateClauses.push(
452
- `${format.ident(queryFunction.path)} = ${queryFunction.value}`
453
- );
454
- }
455
- });
456
- }
457
- }
458
- setCommonColumnsQueryFunctions(jsonSetExpressionGroup, queryFunctions) {
459
- Object.keys(jsonSetExpressionGroup).forEach((jsonSetExpr) => {
460
- queryFunctions.forEach((queryFunction, index) => {
461
- const columnPath = `"${queryFunction.path}"`;
462
- if (columnPath === jsonSetExpr) {
463
- jsonSetExpressionGroup[jsonSetExpr].push(__spreadProps(__spreadValues({}, queryFunction), {
464
- isCommonColumn: true
465
- }));
466
- delete queryFunctions[index];
467
- }
468
- });
469
- });
470
- }
471
- /**
472
- * @description Builds a jsonb expression like jsonb_insert, or jsonb_set
473
- * @param jsonSetExpressions
474
- * @param functionName
475
- * @returns
476
- */
477
- buildJSONBExpression(jsonSetExpressions, functionName) {
478
- let jsonSetStringExpr = "";
479
- jsonSetExpressions.forEach((expression, index) => {
480
- let _tempFunctionName = functionName;
481
- let { columnName, jsonExpr } = expression;
482
- if (expression.isCommonColumn) {
483
- const jsonExpression = expression.value.jsonExpression[0];
484
- _tempFunctionName = jsonExpression.functionName;
485
- jsonExpr = jsonExpression.jsonExpr;
486
- columnName = jsonExpression.columnName;
487
- }
488
- if (index === 0) {
489
- jsonSetStringExpr = `${_tempFunctionName}(${columnName},${jsonExpr})`;
490
- } else {
491
- jsonSetStringExpr = `${_tempFunctionName}(${jsonSetStringExpr},${jsonExpr})`;
492
- }
493
- });
494
- return jsonSetStringExpr;
495
- }
496
- /**
497
- * @description Serializes a JSON value
498
- * @param value
499
- * @returns
500
- */
501
- serializeJSONValue(value) {
502
- const valueSerialized = typeof value == "object" ? `${JSON.stringify(value).replace(/'/g, "''")}` : value;
503
- return valueSerialized;
504
- }
505
- getJSONBSetExpressionByAction(path, value, options) {
506
- path = path.replace(/\[(\d+)\]/g, ".$1");
507
- const pathSplitted = path.split(".");
508
- const parentPath = pathSplitted[0];
509
- const { createNewColumn, actionName } = options;
510
- const pathSerialized = pathSplitted.slice(1).join(",");
511
- const valueSerialized = `'${JSON.stringify(value).replace(
512
- /'/g,
513
- "''"
514
- )}'`;
515
- if (actionName == DYNAMO_DB_UPDATE_ACTIONS.ADD) {
516
- if (typeof value != "string" && !isNaN(value)) {
517
- const resultExpr = {
518
- jsonExpr: `'{${pathSerialized}}',to_jsonb(COALESCE(("${parentPath}"#>'{${pathSerialized}}')::numeric,0) + ${valueSerialized})`,
519
- columnName: `"${parentPath}"`
520
- };
521
- return resultExpr;
522
- }
523
- }
524
- return {
525
- jsonExpr: `'{${pathSerialized}}',${valueSerialized},${createNewColumn}`,
526
- columnName: `"${parentPath}"`
527
- };
528
- }
529
- getListAppendDefFromValue(queryValue, columnType) {
530
- const regexListAppend = /list_append\(([^)]+)\)/gm;
531
- const listAppendString = "list_append(";
532
- const matchList = queryValue.match(regexListAppend) || [];
533
- const groupResult = matchList[0];
534
- if (groupResult) {
535
- const attributesFromGroup = groupResult.slice(listAppendString.length, -1).split(",");
536
- const attributes = {
537
- originalString: groupResult,
538
- path: attributesFromGroup[0].trim(),
539
- value: attributesFromGroup.slice(1).join(",").trim(),
540
- isDynamoFunction: true,
541
- functionExpr: "",
542
- jsonExpression: [{}]
543
- };
544
- if (columnType == "array") {
545
- attributes["functionExpr"] = this.buildArrayAppendExpr(attributes);
546
- } else {
547
- attributes["jsonExpression"] = this.buildJsonbInsertExpr(attributes);
548
- }
549
- return attributes;
550
- }
551
- return null;
552
- }
553
- buildArrayAppendExpr(params) {
554
- const arrayPath = params.path.split(".");
555
- const columnName = arrayPath.shift();
556
- return `ARRAY_APPEND("${columnName}",${params.value})`;
557
- }
558
- buildJsonbInsertExpr(params) {
559
- const arrayPath = params.path.split(".");
560
- const columnName = arrayPath.shift();
561
- const options = {
562
- isDynamoFunction: params == null ? void 0 : params.isDynamoFunction,
563
- relativePath: arrayPath.length && Array.isArray(arrayPath) ? arrayPath : []
564
- };
565
- const jsonbInsertExpressions = this.getExpressionsByDefinitionForJSONBInsert(
566
- columnName,
567
- params.value,
568
- options
569
- );
570
- return jsonbInsertExpressions;
571
- }
572
- getExpressionsByDefinitionForJSONBInsert(columnName, value, options) {
573
- const jsonbInsertExpressions = [];
574
- let pathToAffect = "0";
575
- if (options.isDynamoFunction == true) {
576
- options.relativePath.push("0");
577
- pathToAffect = options.relativePath.join(",");
578
- }
579
- try {
580
- const parsedValue = JSON.parse(value);
581
- if (Array.isArray(parsedValue)) {
582
- parsedValue.forEach((arrayValue) => {
583
- arrayValue = typeof arrayValue == "string" ? `"${arrayValue}"` : arrayValue;
584
- jsonbInsertExpressions.push({
585
- jsonExpr: `'{${pathToAffect}}','${this.serializeJSONValue(
586
- arrayValue
587
- )}'`,
588
- columnName: `"${columnName}"`,
589
- functionName: "jsonb_insert"
590
- });
591
- });
592
- } else {
593
- jsonbInsertExpressions.push({
594
- jsonExpr: `'{${pathToAffect}}','${this.serializeJSONValue(
595
- parsedValue
596
- )}'`,
597
- columnName: `"${columnName}"`,
598
- functionName: "jsonb_insert"
599
- });
600
- }
601
- } catch (error) {
602
- jsonbInsertExpressions.push({
603
- jsonExpr: `'{${pathToAffect}}','${value}'`,
604
- columnName: `"${columnName}"`,
605
- functionName: "jsonb_insert"
606
- });
607
- }
608
- return jsonbInsertExpressions;
609
- }
610
- getInsertExprFromJsonbDef(queryValue, columnType) {
611
- const listAppendParams = this.getListAppendDefFromValue(
612
- queryValue,
613
- columnType
614
- );
615
- if (listAppendParams != null && (listAppendParams == null ? void 0 : listAppendParams.jsonExpression.length) === 0) {
616
- queryValue = queryValue.replace(
617
- listAppendParams.originalString,
618
- listAppendParams.functionExpr
619
- );
620
- } else {
621
- return listAppendParams;
622
- }
623
- return queryValue;
624
- }
625
- replacePathAndValueByAttributeNames(actions, options, columns, actionName) {
626
- return actions.map((action) => {
627
- action.path = this.replaceExpressionAttributeNames(
628
- action.path,
629
- options
630
- );
631
- if (typeof action.value == "string" && action.value.includes("list_append")) {
632
- action.path = action.path.split(".")[0];
633
- const column = columns[action.path];
634
- action.value = this.replaceExpressionAttributeValuesForDynamoFunctions(
635
- action.value,
636
- options
637
- );
638
- action.value = this.getInsertExprFromJsonbDef(
639
- action.value,
640
- column.type
641
- );
642
- action.dynamoFuncName = "list_append";
643
- } else {
644
- action.value = this.replaceExpressionAttributeValues(
645
- action.value,
646
- options
647
- );
648
- }
649
- action.actionName = actionName;
650
- action.createNewColumn = true;
651
- return action;
652
- });
653
- }
654
- replaceExpressionAttributeValuesForDynamoFunctions(value, options) {
655
- const { expressionAttributeNames, expressionAttributeValues } = options;
656
- const exprAttributeNamesKeys = expressionAttributeNames ? Object.keys(expressionAttributeNames) : [];
657
- const exprAttributeValuesKeys = expressionAttributeValues ? Object.keys(expressionAttributeValues) : [];
658
- if (exprAttributeNamesKeys.length > 0) {
659
- exprAttributeNamesKeys.forEach((exprAttribute) => {
660
- value = value.replace(
661
- exprAttribute,
662
- expressionAttributeNames[exprAttribute]
663
- );
664
- });
665
- }
666
- if (exprAttributeValuesKeys.length > 0) {
667
- exprAttributeValuesKeys.forEach((exprAttribute) => {
668
- const valueSerialized = this.serializeJSONValue(
669
- expressionAttributeValues[exprAttribute]
670
- );
671
- value = value.replace(exprAttribute, `${valueSerialized}`);
672
- });
673
- }
674
- return value;
675
- }
676
- replaceExpressionAttributeNames(path, options) {
677
- const { expressionAttributeNames } = options;
678
- if (expressionAttributeNames) {
679
- Object.keys(expressionAttributeNames).forEach(
680
- (attributeName) => {
681
- const attributeNameValue = expressionAttributeNames[attributeName];
682
- path = path.replace(attributeName, attributeNameValue);
683
- }
684
- );
685
- }
686
- return path;
687
- }
688
- replaceExpressionAttributeValues(value, options) {
689
- const { expressionAttributeValues } = options;
690
- if (expressionAttributeValues[value] != void 0) {
691
- return expressionAttributeValues[value];
692
- }
693
- return value;
694
- }
695
- getValueTypeAsPostgresDefinition(value) {
696
- switch (typeof value) {
697
- case "number":
698
- return "number";
699
- case "boolean":
700
- return "boolean";
701
- case "string":
702
- default:
703
- return "text";
704
- }
705
- }
706
- };
707
-
708
- // src/services/cruds/postgresql/postgreSqlCrud.service.ts
709
- var PostgreSqlCrudService = class extends PostgresqlClientService {
710
- constructor(tableSchema, poolClient) {
711
- super(tableSchema, poolClient);
712
- this.tableSchema = tableSchema;
713
- }
714
- get idColumnName() {
715
- return findIdColumnName(this.tableSchema.columns);
716
- }
717
- normalizeInputData(inputData) {
718
- var _a;
719
- inputData.qvAttributes = {};
720
- for (const key in inputData) {
721
- if (!this.tableSchema.columns[key] && key !== "qvAttributes") {
722
- inputData.qvAttributes[key] = inputData[key];
723
- delete inputData[key];
724
- } else if (Array.isArray(inputData[key]) && ((_a = this.tableSchema.columns[key]) == null ? void 0 : _a.type) !== "array") {
725
- inputData[key] = JSON.stringify(inputData[key]);
726
- }
727
- }
728
- }
729
- getItem(data) {
730
- const schemaColumns = Object.entries(this.tableSchema.columns);
731
- schemaColumns.forEach(([key, value]) => {
732
- if (value.type === "big_number") {
733
- if (data[key])
734
- data[key] = Number(data[key]);
735
- }
736
- });
737
- const resultItem = __spreadValues(__spreadValues({}, data), data.qvAttributes);
738
- delete resultItem["qvAttributes"];
739
- return resultItem;
740
- }
741
- prepareData(data) {
742
- const inputData = __spreadValues({}, data);
743
- this.normalizeInputData(inputData);
744
- return inputData;
745
- }
746
- buildCreateResponseBatch(result) {
747
- const rows = Array.isArray(result == null ? void 0 : result.rows) ? result.rows : [];
748
- return {
749
- items: rows.map((r) => this.getItem(r)),
750
- unprocessedItems: []
751
- };
752
- }
753
- create(data) {
754
- if (Array.isArray(data)) {
755
- const inputDataArray = data.map((item) => this.prepareData(item));
756
- return this.createCommand(inputDataArray).then((result) => {
757
- return this.buildCreateResponseBatch(result);
758
- });
759
- } else {
760
- const inputData = this.prepareData(data);
761
- return this.createCommand([inputData]).then(
762
- (result) => result.rowCount ? this.getItem(result.rows[0]) : null
763
- );
764
- }
765
- }
766
- findItem(findOptions) {
767
- return this.findCommand(findOptions).then((data) => {
768
- return (data == null ? void 0 : data.length) ? this.getItem(data[0]) : null;
769
- });
770
- }
771
- async processQueryResult(findOptions, omitPagination = false) {
772
- const rows = await this.findCommand(findOptions);
773
- const items = rows.map(
774
- (row) => this.getItem(row)
775
- );
776
- const { limit, from } = (findOptions == null ? void 0 : findOptions.pagination) || {};
777
- const hasMoreRecords = items.length && items.length === limit;
778
- const newFrom = limit && hasMoreRecords ? limit + (from || 0) : null;
779
- const result = {
780
- items,
781
- pagination: omitPagination ? null : { limit, from: newFrom },
782
- count: items.length
783
- };
784
- return result;
785
- }
786
- async find(findOptions) {
787
- return this.processQueryResult(findOptions);
788
- }
789
- async findAll(findOptions) {
790
- return this.processQueryResult(findOptions, true);
791
- }
792
- async findCount(findOptions) {
793
- const items = await this.findCommand(__spreadProps(__spreadValues({}, findOptions), {
794
- aggregateFunction: "COUNT" /* COUNT */
795
- }));
796
- const aggFunctionProperty = buildAggFunctionAlias(
797
- "COUNT" /* COUNT */
798
- );
799
- const item = items.length ? items[0] : {};
800
- return item[aggFunctionProperty] || 0;
801
- }
802
- async update(filters, data) {
803
- const savedRecord = await this.findItem({ filters });
804
- const inputData = __spreadValues(__spreadValues({}, savedRecord), data);
805
- await this.updateCommand(filters, this.prepareData(inputData));
806
- return this.getItem(inputData);
807
- }
808
- async remove(filters, options) {
809
- await this.deleteCommand(filters, options == null ? void 0 : options.filterGroups);
810
- }
811
- runQuery(querySentence, values) {
812
- return super.runQuery(querySentence, values);
813
- }
814
- async updateExpressions(filters, actions, options) {
815
- const result = await this.updateExpressionCommand(
816
- filters,
817
- actions,
818
- options
819
- );
820
- return PersistenceErrorWrapper(result);
821
- }
822
- };
823
-
824
- export { PostgreSqlCrudService };
825
- //# sourceMappingURL=out.js.map
826
- //# sourceMappingURL=postgreSqlCrud.service-Z6ZT6ITL.mjs.map