@twin.org/entity-storage-connector-mysql 0.0.1-next.18

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