@twin.org/entity-storage-connector-postgresql 0.0.1-next.21

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.
@@ -0,0 +1,556 @@
1
+ 'use strict';
2
+
3
+ var core = require('@twin.org/core');
4
+ var entity = require('@twin.org/entity');
5
+ var loggingModels = require('@twin.org/logging-models');
6
+ var postgres = require('postgres');
7
+
8
+ // Copyright 2024 IOTA Stiftung.
9
+ // SPDX-License-Identifier: Apache-2.0.
10
+ /**
11
+ * Class for performing entity storage operations using ql.
12
+ */
13
+ class PostgreSqlEntityStorageConnector {
14
+ /**
15
+ * Limit the number of entities when finding.
16
+ * @internal
17
+ */
18
+ static _PAGE_SIZE = 40;
19
+ /**
20
+ * Runtime name for the class.
21
+ */
22
+ CLASS_NAME = "PostgreSqlEntityStorageConnector";
23
+ /**
24
+ * The schema for the entity.
25
+ * @internal
26
+ */
27
+ _entitySchema;
28
+ /**
29
+ * The configuration for the connector.
30
+ * @internal
31
+ */
32
+ _config;
33
+ /**
34
+ * The configuration for the connector.
35
+ * @internal
36
+ */
37
+ _connection;
38
+ /**
39
+ * Create a new instance of PostgreSqlEntityStorageConnector.
40
+ * @param options The options for the connector.
41
+ */
42
+ constructor(options) {
43
+ core.Guards.object(this.CLASS_NAME, "options", options);
44
+ core.Guards.stringValue(this.CLASS_NAME, "options.entitySchema", options.entitySchema);
45
+ core.Guards.object(this.CLASS_NAME, "options.config", options.config);
46
+ core.Guards.stringValue(this.CLASS_NAME, "options.config.host", options.config.host);
47
+ core.Guards.stringValue(this.CLASS_NAME, "options.config.user", options.config.user);
48
+ core.Guards.stringValue(this.CLASS_NAME, "options.config.password", options.config.password);
49
+ core.Guards.stringValue(this.CLASS_NAME, "options.config.database", options.config.database);
50
+ core.Guards.stringValue(this.CLASS_NAME, "options.config.tableName", options.config.tableName);
51
+ this._entitySchema = entity.EntitySchemaFactory.get(options.entitySchema);
52
+ this._config = options.config;
53
+ }
54
+ /**
55
+ * Initialize the PostgreSql environment.
56
+ * @param nodeLoggingConnectorType Optional type of the logging connector.
57
+ * @returns A promise that resolves to a boolean indicating success.
58
+ */
59
+ async bootstrap(nodeLoggingConnectorType) {
60
+ const nodeLogging = loggingModels.LoggingConnectorFactory.getIfExists(nodeLoggingConnectorType ?? "node-logging");
61
+ try {
62
+ const dbConnection = await this.createConnection();
63
+ await nodeLogging?.log({
64
+ level: "info",
65
+ source: this.CLASS_NAME,
66
+ ts: Date.now(),
67
+ message: "databaseCreating",
68
+ data: {
69
+ database: this._config.database
70
+ }
71
+ });
72
+ const res = await dbConnection.unsafe(`SELECT datname FROM pg_catalog.pg_database WHERE datname = '${this._config.database}'`);
73
+ if (res.length === 0) {
74
+ await dbConnection.unsafe(`CREATE DATABASE "${this._config.database}";`);
75
+ }
76
+ await nodeLogging?.log({
77
+ level: "info",
78
+ source: this.CLASS_NAME,
79
+ ts: Date.now(),
80
+ message: "databaseExists",
81
+ data: {
82
+ database: this._config.database
83
+ }
84
+ });
85
+ const tableExistsQuery = `SELECT to_regclass('${this._config.tableName}')`;
86
+ const tableExistsResult = await dbConnection.unsafe(tableExistsQuery);
87
+ if (!tableExistsResult[0].to_regclass) {
88
+ const createTableQuery = `CREATE TABLE IF NOT EXISTS ${this._config.tableName} (${this.mapPostgreSqlProperties(this._entitySchema)})`;
89
+ await dbConnection.unsafe(createTableQuery);
90
+ }
91
+ await nodeLogging?.log({
92
+ level: "info",
93
+ source: this.CLASS_NAME,
94
+ ts: Date.now(),
95
+ message: "tableExists",
96
+ data: {
97
+ table: this._config.tableName
98
+ }
99
+ });
100
+ }
101
+ catch (error) {
102
+ const errors = error instanceof AggregateError ? error.errors : [error];
103
+ for (const err of errors) {
104
+ await nodeLogging?.log({
105
+ level: "error",
106
+ source: this.CLASS_NAME,
107
+ ts: Date.now(),
108
+ message: "databaseCreateFailed",
109
+ error: core.BaseError.fromError(err),
110
+ data: {
111
+ database: this._config.database
112
+ }
113
+ });
114
+ }
115
+ return false;
116
+ }
117
+ return true;
118
+ }
119
+ /**
120
+ * Get the schema for the entities.
121
+ * @returns The schema for the entities.
122
+ */
123
+ getSchema() {
124
+ return this._entitySchema;
125
+ }
126
+ /**
127
+ * Get an entity from PostgreSql.
128
+ * @param id The id of the entity to get, or the index value if secondaryIndex is set.
129
+ * @param secondaryIndex Get the item using a secondary index.
130
+ * @param conditions The optional conditions to match for the entities.
131
+ * @returns The object if it can be found or undefined.
132
+ */
133
+ async get(id, secondaryIndex, conditions) {
134
+ core.Guards.stringValue(this.CLASS_NAME, "id", id);
135
+ try {
136
+ const dbConnection = await this.createConnection();
137
+ const whereClauses = [];
138
+ const values = [];
139
+ if (secondaryIndex) {
140
+ whereClauses.push(`"${String(secondaryIndex)}" = $1`);
141
+ values.push(id);
142
+ }
143
+ else {
144
+ const primaryKey = entity.EntitySchemaHelper.getPrimaryKey(this.getSchema());
145
+ whereClauses.push(`"${primaryKey.property}" = $1`);
146
+ values.push(id);
147
+ }
148
+ if (conditions) {
149
+ for (const condition of conditions) {
150
+ whereClauses.push(`"${String(condition.property)}" = $${values.length + 1}`);
151
+ values.push(condition.value);
152
+ }
153
+ }
154
+ const query = `SELECT * FROM "${this._config.tableName}" WHERE ${whereClauses.join(" AND ")} LIMIT 1`;
155
+ const rows = await dbConnection.unsafe(query, values);
156
+ if (Array.isArray(rows) && rows.length === 1) {
157
+ if (this._entitySchema.properties) {
158
+ for (const prop of this._entitySchema.properties) {
159
+ const row = rows[0];
160
+ let propColumn = prop.property;
161
+ propColumn = propColumn.toLowerCase();
162
+ if ((prop.type === entity.EntitySchemaPropertyType.Object ||
163
+ prop.type === entity.EntitySchemaPropertyType.Array) &&
164
+ typeof row[propColumn] === "string") {
165
+ const rowValue = JSON.parse(rows[0][propColumn]);
166
+ delete rows[0][propColumn];
167
+ rows[0][prop.property] = rowValue;
168
+ }
169
+ if (row[propColumn] === null) {
170
+ rows[0][prop.property] = undefined;
171
+ }
172
+ }
173
+ }
174
+ return rows[0];
175
+ }
176
+ }
177
+ catch (err) {
178
+ throw new core.GeneralError(this.CLASS_NAME, "getFailed", {
179
+ id
180
+ }, err);
181
+ }
182
+ return undefined;
183
+ }
184
+ /**
185
+ * Set an entity.
186
+ * @param entity The entity to set.
187
+ * @param conditions The optional conditions to match for the entities.
188
+ * @returns The id of the entity.
189
+ */
190
+ async set(entity$1, conditions) {
191
+ core.Guards.object(this.CLASS_NAME, "entity", entity$1);
192
+ // Validate that the entity matches the schema
193
+ this.entitySqlVerification(entity$1);
194
+ const primaryKey = entity.EntitySchemaHelper.getPrimaryKey(this.getSchema());
195
+ const id = entity$1[primaryKey.property];
196
+ try {
197
+ if (core.Is.arrayValue(conditions)) {
198
+ const itemData = await this.get(id);
199
+ if (core.Is.notEmpty(itemData) && !this.verifyConditions(conditions, itemData)) {
200
+ return;
201
+ }
202
+ }
203
+ const columns = Object.keys(entity$1)
204
+ .map(key => `"${key}"`)
205
+ .join(", ");
206
+ // eslint-disable-next-line no-confusing-arrow
207
+ const values = Object.values(entity$1).map(value => value === undefined ? null : value);
208
+ const placeholders = values.map((_, index) => `$${index + 1}`).join(", ");
209
+ const dbConnection = await this.createConnection();
210
+ await dbConnection.unsafe(`INSERT INTO "${this._config.tableName}" (${columns}) VALUES (${placeholders}) ON CONFLICT ("${primaryKey.property}") DO UPDATE SET ${columns
211
+ .split(", ")
212
+ .map(col => `${col} = EXCLUDED.${col}`)
213
+ .join(", ")};`, values);
214
+ }
215
+ catch (err) {
216
+ throw new core.GeneralError(this.CLASS_NAME, "setFailed", {
217
+ id
218
+ }, err);
219
+ }
220
+ }
221
+ /**
222
+ * Remove the entity.
223
+ * @param id The id of the entity to remove.
224
+ * @param conditions The optional conditions to match for the entities.
225
+ * @returns Nothing.
226
+ */
227
+ async remove(id, conditions) {
228
+ core.Guards.stringValue(this.CLASS_NAME, "id", id);
229
+ try {
230
+ const dbConnection = await this.createConnection();
231
+ const itemData = await this.get(id);
232
+ if (core.Is.notEmpty(itemData)) {
233
+ const values = [id];
234
+ let whereClauses = [];
235
+ if (core.Is.arrayValue(conditions)) {
236
+ whereClauses = conditions.map(condition => {
237
+ values.push(condition.value);
238
+ return `"${String(condition.property)}" = $${values.length}`;
239
+ });
240
+ }
241
+ const primaryKey = entity.EntitySchemaHelper.getPrimaryKey(this.getSchema());
242
+ const query = `DELETE FROM "${this._config.tableName}" WHERE "${primaryKey.property}" = $1${whereClauses.length > 0 ? ` AND ${whereClauses.join(" AND ")}` : ""}`;
243
+ await dbConnection.unsafe(query, values);
244
+ }
245
+ }
246
+ catch (err) {
247
+ throw new core.GeneralError(this.CLASS_NAME, "removeFailed", {
248
+ id
249
+ }, err);
250
+ }
251
+ }
252
+ /**
253
+ * Find all the entities which match the conditions.
254
+ * @param conditions The conditions to match for the entities.
255
+ * @param sortProperties The optional sort order.
256
+ * @param properties The optional properties to return, defaults to all.
257
+ * @param cursor The cursor to request the next page of entities.
258
+ * @param pageSize The suggested number of entities to return in each chunk, in some scenarios can return a different amount.
259
+ * @returns All the entities for the storage matching the conditions,
260
+ * and a cursor which can be used to request more entities.
261
+ */
262
+ async query(conditions, sortProperties, properties, cursor, pageSize) {
263
+ const sql = "";
264
+ try {
265
+ const returnSize = pageSize ?? PostgreSqlEntityStorageConnector._PAGE_SIZE;
266
+ let orderByClause = "";
267
+ if (Array.isArray(sortProperties)) {
268
+ const orderClauses = [];
269
+ for (const sortProperty of sortProperties) {
270
+ const direction = sortProperty.sortDirection === entity.SortDirection.Ascending ? "ASC" : "DESC";
271
+ orderClauses.push(`"${String(sortProperty.property)}" ${direction}`);
272
+ }
273
+ orderByClause = `ORDER BY ${orderClauses.join(", ")}`;
274
+ }
275
+ const whereClauses = [];
276
+ const values = [];
277
+ if (conditions) {
278
+ this.buildQueryParameters("", conditions, whereClauses, values);
279
+ }
280
+ const query = `SELECT ${properties ? properties.map(p => `"${String(p)}"`).join(", ") : "*"} FROM "${this._config.tableName}" ${whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : ""} ${orderByClause} LIMIT ${returnSize} OFFSET ${cursor ? Number(cursor) : 0}::integer`;
281
+ const dbConnection = await this.createConnection();
282
+ const rows = await dbConnection.unsafe(query, values);
283
+ if (this._entitySchema.properties) {
284
+ for (const row of rows) {
285
+ for (const prop of this._entitySchema.properties) {
286
+ let propColumn = prop.property;
287
+ propColumn = propColumn.toLowerCase();
288
+ if ((prop.type === entity.EntitySchemaPropertyType.Object ||
289
+ prop.type === entity.EntitySchemaPropertyType.Array) &&
290
+ typeof row[propColumn] === "string") {
291
+ const rowValue = JSON.parse(row[propColumn]);
292
+ delete row[propColumn];
293
+ row[prop.property] = rowValue;
294
+ }
295
+ if (row[propColumn] === null) {
296
+ row[prop.property] = undefined;
297
+ }
298
+ }
299
+ }
300
+ }
301
+ return {
302
+ entities: rows,
303
+ cursor: Array.isArray(rows) && rows.length === returnSize
304
+ ? String((cursor ? Number(cursor) : 0) + returnSize)
305
+ : undefined
306
+ };
307
+ }
308
+ catch (err) {
309
+ throw new core.GeneralError(this.CLASS_NAME, "queryFailed", { sql }, err);
310
+ }
311
+ }
312
+ /**
313
+ * Drop the table.
314
+ * @returns Nothing.
315
+ */
316
+ async tableDrop() {
317
+ try {
318
+ const dbConnection = await this.createConnection();
319
+ await dbConnection.unsafe(`DROP TABLE ${this._config.tableName};`);
320
+ }
321
+ catch {
322
+ // Ignore errors
323
+ }
324
+ }
325
+ /**
326
+ * Create a new DB connection.
327
+ * @returns The PostgreSql connection.
328
+ * @internal
329
+ */
330
+ async createConnection() {
331
+ if (this._connection) {
332
+ return this._connection;
333
+ }
334
+ const newConnection = await postgres(this.createConnectionConfig());
335
+ this._connection = newConnection;
336
+ return newConnection;
337
+ }
338
+ /**
339
+ * Create a new DB connection configuration.
340
+ * @returns The PostgreSql connection configuration.
341
+ * @internal
342
+ */
343
+ createConnectionConfig() {
344
+ return {
345
+ host: this._config.host,
346
+ port: this._config.port ?? 5432,
347
+ user: this._config.user,
348
+ password: this._config.password
349
+ };
350
+ }
351
+ /**
352
+ * Create an SQL condition clause.
353
+ * @param objectPath The path for the nested object.
354
+ * @param condition The conditions to create the query from.
355
+ * @param whereClauses The where clauses to use in the query.
356
+ * @param values The values to use in the query.
357
+ * @internal
358
+ */
359
+ buildQueryParameters(objectPath, condition, whereClauses, values) {
360
+ if (core.Is.undefined(condition)) {
361
+ return;
362
+ }
363
+ if ("conditions" in condition) {
364
+ if (condition.conditions.length === 0) {
365
+ return;
366
+ }
367
+ const joinConditions = condition.conditions.map(c => {
368
+ const subWhereClauses = [];
369
+ const subValues = [];
370
+ this.buildQueryParameters(objectPath, c, subWhereClauses, subValues);
371
+ values.push(...subValues);
372
+ return subWhereClauses.join(" AND ");
373
+ });
374
+ const logicalOperator = this.mapConditionalOperator(condition.logicalOperator);
375
+ const queryClause = joinConditions.filter(j => j.length > 0).join(` ${logicalOperator} `);
376
+ if (queryClause.length > 0) {
377
+ whereClauses.push(`(${queryClause})`);
378
+ }
379
+ return;
380
+ }
381
+ const schemaProp = this._entitySchema.properties?.find(p => p.property === condition.property);
382
+ const comparison = this.mapComparisonOperator(objectPath, condition, schemaProp?.type, values);
383
+ whereClauses.push(comparison);
384
+ }
385
+ /**
386
+ * Map the framework comparison operators to those in MySQL.
387
+ * @param objectPath The prefix to use for the condition.
388
+ * @param comparator The operator to map.
389
+ * @param type The type of the property.
390
+ * @param values The values to use in the query.
391
+ * @returns The comparison expression.
392
+ * @throws GeneralError if the comparison operator is not supported.
393
+ * @internal
394
+ */
395
+ mapComparisonOperator(objectPath, comparator, type, values) {
396
+ let prop = objectPath;
397
+ if (prop.length > 0) {
398
+ prop += ".";
399
+ }
400
+ prop += comparator.property;
401
+ if (comparator.comparison === entity.ComparisonOperator.In) {
402
+ const inValues = Array.isArray(comparator.value) ? comparator.value : [comparator.value];
403
+ values.push(...inValues.map(val => this.propertyToDbValue(val, type)));
404
+ const placeholders = inValues
405
+ .map((_, index) => `$${values.length - inValues.length + index + 1}`)
406
+ .join(", ");
407
+ return `"${prop}" IN (${placeholders})`;
408
+ }
409
+ const dbValue = this.propertyToDbValue(comparator.value, type);
410
+ values.push(dbValue);
411
+ if (comparator.property.split(".").length > 1) {
412
+ const jsonPath = comparator.property
413
+ .split(".")
414
+ .slice(1)
415
+ .map((p, i, arr) => (i === arr.length - 1 ? `->> '${p}'` : `-> '${p}'`))
416
+ .join("");
417
+ return `("${comparator.property.split(".")[0]}"::jsonb ${jsonPath}) = $${values.length}`;
418
+ }
419
+ else if (comparator.comparison === entity.ComparisonOperator.Equals) {
420
+ return `"${prop}" = $${values.length}`;
421
+ }
422
+ else if (comparator.comparison === entity.ComparisonOperator.NotEquals) {
423
+ return `"${prop}" <> $${values.length}`;
424
+ }
425
+ else if (comparator.comparison === entity.ComparisonOperator.GreaterThan) {
426
+ return `"${prop}" > $${values.length}`;
427
+ }
428
+ else if (comparator.comparison === entity.ComparisonOperator.LessThan) {
429
+ return `"${prop}" < $${values.length}`;
430
+ }
431
+ else if (comparator.comparison === entity.ComparisonOperator.GreaterThanOrEqual) {
432
+ return `"${prop}" >= $${values.length}`;
433
+ }
434
+ else if (comparator.comparison === entity.ComparisonOperator.LessThanOrEqual) {
435
+ return `"${prop}" <= $${values.length}`;
436
+ }
437
+ else if (comparator.comparison === entity.ComparisonOperator.Includes) {
438
+ return `EXISTS (SELECT 1 FROM jsonb_array_elements("${prop}") elem WHERE elem @> $${values.length}::jsonb)`;
439
+ }
440
+ throw new core.GeneralError(this.CLASS_NAME, "comparisonNotSupported", {
441
+ comparison: comparator.comparison
442
+ });
443
+ }
444
+ /**
445
+ * Format a value to insert into DB.
446
+ * @param value The value to format.
447
+ * @param type The type for the property.
448
+ * @returns The value after conversion.
449
+ * @internal
450
+ */
451
+ propertyToDbValue(value, type) {
452
+ if (type === "string") {
453
+ return String(value);
454
+ }
455
+ else if (type === "number") {
456
+ return Number(value);
457
+ }
458
+ else if (type === "boolean") {
459
+ return Boolean(value);
460
+ }
461
+ else if (type === "array") {
462
+ return value;
463
+ }
464
+ if (core.Is.object(value)) {
465
+ return JSON.stringify(value);
466
+ }
467
+ return value;
468
+ }
469
+ /**
470
+ * Map the framework conditional operators to those in MySQL.
471
+ * @param operator The operator to map.
472
+ * @returns The conditional operator.
473
+ * @throws GeneralError if the conditional operator is not supported.
474
+ * @internal
475
+ */
476
+ mapConditionalOperator(operator) {
477
+ if ((operator ?? entity.LogicalOperator.And) === entity.LogicalOperator.And) {
478
+ return "AND";
479
+ }
480
+ else if (operator === entity.LogicalOperator.Or) {
481
+ return "OR";
482
+ }
483
+ throw new core.GeneralError(this.CLASS_NAME, "conditionalNotSupported", { operator });
484
+ }
485
+ /**
486
+ * Verify the conditions for the entity.
487
+ * @param conditions The conditions to verify.
488
+ * @internal
489
+ */
490
+ verifyConditions(conditions, obj) {
491
+ return conditions.every(condition => core.ObjectHelper.propertyGet(obj, condition.property) === condition.value);
492
+ }
493
+ /**
494
+ * Map entity schema properties to SQL properties.
495
+ * @param entitySchema The schema of the entity.
496
+ * @returns The SQL properties as a string.
497
+ * @throws GeneralError if the entity properties do not exist.
498
+ */
499
+ mapPostgreSqlProperties(entitySchema) {
500
+ const sqlTypeMap = {
501
+ [entity.EntitySchemaPropertyType.String]: "TEXT",
502
+ [entity.EntitySchemaPropertyType.Number]: "REAL",
503
+ [entity.EntitySchemaPropertyType.Integer]: "INTEGER",
504
+ [entity.EntitySchemaPropertyType.Object]: "JSONB",
505
+ [entity.EntitySchemaPropertyType.Array]: "JSONB",
506
+ [entity.EntitySchemaPropertyType.Boolean]: "BOOLEAN"
507
+ };
508
+ if (!entitySchema.properties) {
509
+ throw new core.GeneralError(this.CLASS_NAME, "entitySchemaPropertiesUndefined");
510
+ }
511
+ const primaryKeys = [];
512
+ const columnDefinitions = entitySchema.properties
513
+ .map(prop => {
514
+ const sqlType = sqlTypeMap[prop.type] || "TEXT";
515
+ const columnName = String(prop.property);
516
+ const nullable = prop.optional ? " NULL" : " NOT NULL";
517
+ if (prop.isPrimary) {
518
+ primaryKeys.push(columnName);
519
+ }
520
+ return `"${columnName}" ${sqlType}${nullable}`;
521
+ })
522
+ .join(", ");
523
+ const primaryKeyDefinition = primaryKeys.length > 0 ? `, PRIMARY KEY (${primaryKeys.join(", ")})` : "";
524
+ return columnDefinitions + primaryKeyDefinition;
525
+ }
526
+ /**
527
+ * Validate that the entity matches the schema.
528
+ * @param entity The entity to validate.
529
+ * @throws GeneralError if the entity schema properties are undefined or if the entity does not match the schema.
530
+ */
531
+ entitySqlVerification(entity) {
532
+ // Validate that the entity matches the schema
533
+ if (!this._entitySchema.properties) {
534
+ throw new core.GeneralError(this.CLASS_NAME, "entitySchemaPropertiesUndefined");
535
+ }
536
+ for (const prop of this._entitySchema.properties) {
537
+ const value = entity[prop.property];
538
+ if (value === undefined || value === null) {
539
+ if (!prop.optional) {
540
+ throw new core.GeneralError(this.CLASS_NAME, "invalidEntity", {
541
+ entity,
542
+ entitySchema: this._entitySchema
543
+ });
544
+ }
545
+ }
546
+ else if (typeof value !== prop.type && (prop.type !== "array" || !core.Is.array(value))) {
547
+ throw new core.GeneralError(this.CLASS_NAME, "invalidEntity", {
548
+ entity,
549
+ entitySchema: this._entitySchema
550
+ });
551
+ }
552
+ }
553
+ }
554
+ }
555
+
556
+ exports.PostgreSqlEntityStorageConnector = PostgreSqlEntityStorageConnector;