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