-
Notifications
You must be signed in to change notification settings - Fork 0
/
PgPersister.ts
760 lines (676 loc) · 29.3 KB
/
PgPersister.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
// Copyright (c) 2022-2023. Heusala Group Oy. All rights reserved.
// Copyright (c) 2020-2021. Sendanor. All rights reserved.
import { first } from "../../../io/hyperify/core/functions/first";
import { map } from "../../../io/hyperify/core/functions/map";
import { find } from "../../../io/hyperify/core/functions/find";
import { has } from "../../../io/hyperify/core/functions/has";
import { Pool, PoolClient, PoolConfig, QueryResult, types } from "pg";
import { EntityMetadata } from "../../../io/hyperify/core/data/types/EntityMetadata";
import { Persister } from "../../../io/hyperify/core/data/types/Persister";
import { Entity } from "../../../io/hyperify/core/data/Entity";
import { EntityUtils } from "../../../io/hyperify/core/data/utils/EntityUtils";
import { KeyValuePairs } from "../../../io/hyperify/core/data/types/KeyValuePairs";
import { LogService } from "../../../io/hyperify/core/LogService";
import { LogLevel } from "../../../io/hyperify/core/types/LogLevel";
import { isSafeInteger } from "../../../io/hyperify/core/types/Number";
import { PersisterMetadataManager } from "../../../io/hyperify/core/data/persisters/types/PersisterMetadataManager";
import { PersisterMetadataManagerImpl } from "../../../io/hyperify/core/data/persisters/types/PersisterMetadataManagerImpl";
import { PgEntitySelectQueryBuilder } from "../../../io/hyperify/core/data/query/pg/select/PgEntitySelectQueryBuilder";
import { PgQueryUtils } from "../../../io/hyperify/core/data/query/pg/utils/PgQueryUtils";
import { PgOid } from "../../../io/hyperify/core/data/persisters/pg/types/PgOid";
import { PgOidParserUtils } from "../../../io/hyperify/core/data/persisters/pg/utils/PgOidParserUtils";
import { Sort } from "../../../io/hyperify/core/data/Sort";
import { Where } from "../../../io/hyperify/core/data/Where";
import { PgEntityDeleteQueryBuilder } from "../../../io/hyperify/core/data/query/pg/delete/PgEntityDeleteQueryBuilder";
import { isArray } from "../../../io/hyperify/core/types/Array";
import { PgEntityUpdateQueryBuilder } from "../../../io/hyperify/core/data/query/pg/update/PgEntityUpdateQueryBuilder";
import { PgAndChainBuilder } from "../../../io/hyperify/core/data/query/pg/formulas/PgAndChainBuilder";
import { PgEntityInsertQueryBuilder } from "../../../io/hyperify/core/data/query/pg/insert/PgEntityInsertQueryBuilder";
import { PersisterType } from "../../../io/hyperify/core/data/persisters/types/PersisterType";
import { TableFieldInfoCallback, TableFieldInfoResponse } from "../../../io/hyperify/core/data/query/sql/select/EntitySelectQueryBuilder";
import { parseIsoDateStringWithMilliseconds } from "../../../io/hyperify/core/types/Date";
import { PersisterEntityManagerImpl } from "../../../io/hyperify/core/data/persisters/types/PersisterEntityManagerImpl";
import { PersisterEntityManager } from "../../../io/hyperify/core/data/persisters/types/PersisterEntityManager";
import { EntityCallbackUtils } from "../../../io/hyperify/core/data/utils/EntityCallbackUtils";
import { EntityCallbackType } from "../../../io/hyperify/core/data/types/EntityCallbackType";
import { startsWith } from "../../../io/hyperify/core/functions/startsWith";
const LOG = LogService.createLogger('PgPersister');
// FIXME: Make this lazy so that it doesn't happen if the PgPersister has not been used
// This could also be set on Pool only. Better to change there.
types.setTypeParser(PgOid.RECORD as number, PgOidParserUtils.parseRecord);
// Override timestamp conversion to force timestamp to be inserted in UTC
types.setTypeParser(1114, (str) => {
const utcStr = `${str}Z`;
return parseIsoDateStringWithMilliseconds( new Date(utcStr) , true);
});
/**
* This persister implements entity store over PostgreSQL database.
*
* @see {@link Persister}
*/
export class PgPersister implements Persister {
public static setLogLevel (level: LogLevel) {
LOG.setLogLevel(level);
PgEntityInsertQueryBuilder.setLogLevel(level);
EntityUtils.setLogLevel(level);
}
private _pool: Pool | undefined;
private readonly _metadataManager : PersisterMetadataManager;
private readonly _entityManager : PersisterEntityManager;
private readonly _tablePrefix : string;
private readonly _fetchTableInfo : TableFieldInfoCallback;
public constructor (
host: string | undefined = undefined,
user: string | undefined = undefined,
password: string | undefined = undefined,
database: string | undefined = undefined,
ssl : boolean | undefined = undefined,
tablePrefix: string = '',
applicationName: string | undefined = undefined,
connectionTimeoutMillis : number | undefined = undefined,
idleTimeoutMillis : number | undefined = undefined,
maxClients: number = 100,
allowExitOnIdle : boolean | undefined = undefined,
queryTimeout: number | undefined = undefined,
statementTimeout: number | undefined = undefined,
idleInTransactionSessionTimeout: number | undefined = undefined,
port : number | undefined = undefined,
) {
const config : PoolConfig = host && startsWith(host, 'postgresql://') ? ({
connectionString: host
}) : ({
...(host !== undefined ? { host } : {}),
...(user !== undefined ? { user } : {}),
...(password !== undefined ? { password } : {}),
...(database !== undefined ? { database } : {}),
...(port !== undefined ? { port } : {}),
...(ssl !== undefined ? {ssl} : {}),
...(applicationName !== undefined ? {application_name: applicationName} : {}),
...(queryTimeout !== undefined ? {query_timeout: queryTimeout} : {}),
...(statementTimeout !== undefined ? {statement_timeout: statementTimeout} : {}),
...(connectionTimeoutMillis !== undefined ? {connectionTimeoutMillis} : {}),
...(idleInTransactionSessionTimeout !== undefined ? {idle_in_transaction_session_timeout: idleInTransactionSessionTimeout} : {}),
...(idleTimeoutMillis !== undefined ? {idleTimeoutMillis} : {}),
...(maxClients !== undefined ? {max: maxClients} : {}),
...(allowExitOnIdle !== undefined ? {allowExitOnIdle} : {}),
});
this._tablePrefix = tablePrefix;
this._pool = new Pool( config );
this._pool.on('error', (err/*, client*/) => {
LOG.error(`Unexpected error on idle client: `, err);
})
this._metadataManager = new PersisterMetadataManagerImpl();
this._entityManager = PersisterEntityManagerImpl.create();
this._fetchTableInfo = (tableName: string) : TableFieldInfoResponse => {
const mappedMetadata = this._metadataManager.getMetadataByTable(tableName);
if (!mappedMetadata) throw new TypeError(`Could not find metadata for table "${tableName}"`);
const mappedFields = mappedMetadata.fields;
const temporalProperties = mappedMetadata.temporalProperties;
return [mappedFields, temporalProperties];
};
}
/**
* @inheritDoc
* @see {@link Persister.getPersisterType}
*/
public getPersisterType (): PersisterType {
return PersisterType.POSTGRESQL;
}
/**
* @inheritDoc
* @see {@link Persister.destroy}
*/
public destroy () {
if (this._pool) {
this._pool.removeAllListeners('error');
// FIXME: Is there something we should do to tell the pool to destroy itself?
this._pool.end().catch((err) => {
LOG.error(`Error closing pool: ${err}`);
});
this._pool = undefined;
}
}
/**
* @inheritDoc
* @see {@link Persister.setupEntityMetadata}
* @see {@link PersisterMetadataManager.setupEntityMetadata}
*/
public setupEntityMetadata (metadata: EntityMetadata) : void {
this._metadataManager.setupEntityMetadata(metadata);
}
/**
* @inheritDoc
* @see {@link Persister.destroy}
*/
public async count (
metadata : EntityMetadata,
where : Where | undefined
): Promise<number> {
return await this._transaction(
async (connection) => this._count(connection, metadata, where)
);
}
/**
* @inheritDoc
* @see {@link Persister.destroy}
*/
public async existsBy (
metadata : EntityMetadata,
where : Where
): Promise<boolean> {
return await this._transaction(
async (connection) => this._existsBy(connection, metadata, where)
);
}
/**
* @inheritDoc
* @see {@link Persister.destroy}
*/
public async deleteAll (
metadata : EntityMetadata,
where : Where | undefined,
): Promise<void> {
return await this._transaction(
async (connection) => this._deleteAll(connection, metadata, where)
);
}
/**
* @inheritDoc
* @see {@link Persister.findAll}
*/
public async findAll<T extends Entity> (
metadata : EntityMetadata,
where : Where | undefined,
sort : Sort | undefined
): Promise<T[]> {
return await this._transaction(
async (connection) => this._findAll(connection, metadata, where, sort)
);
}
/**
* @inheritDoc
* @see {@link Persister.destroy}
*/
public async findBy<T extends Entity> (
metadata : EntityMetadata,
where : Where,
sort : Sort | undefined
): Promise<T | undefined> {
return await this._transaction(
async (connection) => this._findBy(connection, metadata, where, sort)
);
}
/**
* @inheritDoc
* @see {@link Persister.destroy}
*/
public async insert<T extends Entity> (
metadata : EntityMetadata,
entities : T | readonly T[],
): Promise<T> {
return await this._transaction(
async (connection) => this._insert(connection, metadata, entities)
);
}
/**
* @inheritDoc
* @see {@link Persister.destroy}
*/
public async update<T extends Entity> (
metadata: EntityMetadata,
entity: T,
): Promise<T> {
return await this._transaction(
async (connection) => this._update(connection, metadata, entity)
);
}
protected async _transaction (callback: (connection : PoolClient) => Promise<any>) {
let connection : PoolClient | undefined = undefined;
let returnValue : any = undefined;
try {
connection = await this._getConnection();
await this._beginTransaction(connection);
returnValue = await callback(connection);
await this._commitTransaction(connection);
} catch (err) {
if (connection) {
try {
await this._rollbackTransaction(connection);
} catch (err) {
LOG.warn(`Warning! Failed to rollback transaction: `, err);
}
}
throw err;
} finally {
if (connection) {
try {
connection.release();
} catch (err) {
LOG.warn(`Warning! Failed to release connection: `, err);
}
}
}
return returnValue;
}
protected async _beginTransaction (connection : PoolClient) : Promise<void> {
await connection.query('BEGIN');
}
protected async _commitTransaction (connection : PoolClient) : Promise<void> {
await connection.query('COMMIT');
}
protected async _rollbackTransaction (connection : PoolClient) : Promise<void> {
await connection.query('ROLLBACK');
}
protected async _getConnection () : Promise<PoolClient> {
const pool = this._pool;
if (!pool) throw new TypeError(`The pool was not initialized`);
return pool.connect();
}
/**
* @inheritDoc
* @see {@link Persister.destroy}
*/
private async _count (
connection : PoolClient,
metadata : EntityMetadata,
where : Where | undefined
): Promise<number> {
const {tableName, fields, temporalProperties} = metadata;
const builder = PgEntitySelectQueryBuilder.create();
builder.setTablePrefix(this._tablePrefix);
builder.setTableName(tableName);
builder.includeFormulaByString('COUNT(*)', 'count');
if (where !== undefined) builder.setWhereFromQueryBuilder( builder.buildAnd(where, tableName, fields, temporalProperties) );
const [queryString, queryValues] = builder.build();
LOG.debug(`count: queryString = `, queryString);
LOG.debug(`count: queryValues = `, queryValues);
const result = await this._query(connection, queryString, queryValues);
if (!result) throw new TypeError('Could not get result for PgPersister.countByCondition');
LOG.debug(`count: result = `, result);
const rows = result.rows;
LOG.debug(`count: rows = `, rows);
if (!rows) throw new TypeError('Could not get result rows for PgPersister.countByCondition');
const row = first(rows);
LOG.debug(`count: row = `, row);
if (!row) throw new TypeError('Could not get result row for PgPersister.countByCondition');
const count = row.count;
LOG.debug(`count: count = `, count);
if (!count) throw new TypeError('Could not read count for PgPersister.countByCondition');
const parsedCount = parseInt(count, 10);
if (!isSafeInteger(parsedCount)) throw new TypeError(`Could not read count for PgPersister.countByCondition`);
return parsedCount;
}
/**
* @inheritDoc
* @see {@link Persister.destroy}
*/
private async _existsBy (
connection : PoolClient,
metadata : EntityMetadata,
where : Where
): Promise<boolean> {
const {tableName, fields, temporalProperties} = metadata;
const builder = PgEntitySelectQueryBuilder.create();
builder.setTablePrefix(this._tablePrefix);
builder.setTableName(tableName);
builder.includeFormulaByString('COUNT(*) >= 1', 'exists');
builder.setWhereFromQueryBuilder( builder.buildAnd(where, tableName, fields, temporalProperties) );
const [queryString, queryValues] = builder.build();
const result = await this._query(connection, queryString, queryValues);
if (!result) throw new TypeError('Could not get result for PgPersister.countByCondition');
LOG.debug(`count: result = `, result);
const rows = result.rows;
LOG.debug(`count: rows = `, rows);
if (!rows) throw new TypeError('Could not get result rows for PgPersister.countByCondition');
const row = first(rows);
LOG.debug(`count: row = `, row);
if (!row) throw new TypeError('Could not get result row for PgPersister.countByCondition');
const exists = row.exists;
LOG.debug(`count: exists = `, exists);
return exists;
}
/**
* @inheritDoc
* @see {@link Persister.destroy}
*/
private async _deleteAll<T extends Entity> (
connection : PoolClient,
metadata : EntityMetadata,
where : Where | undefined,
): Promise<void> {
let entities : T[] = [];
const {tableName, fields, temporalProperties, callbacks, idPropertyName } = metadata;
const hasPreRemoveCallbacks = EntityCallbackUtils.hasCallbacks(callbacks, EntityCallbackType.PRE_REMOVE);
const hasPostRemoveCallbacks = EntityCallbackUtils.hasCallbacks(callbacks, EntityCallbackType.POST_REMOVE);
if ( hasPreRemoveCallbacks || hasPostRemoveCallbacks ) {
entities = await this._findAll(connection, metadata, where, undefined);
}
if (hasPreRemoveCallbacks) {
await EntityCallbackUtils.runPreRemoveCallbacks(
entities,
callbacks
);
}
if ( !hasPreRemoveCallbacks && !hasPostRemoveCallbacks ) {
LOG.debug( `deleteAll: tableName = `, tableName );
const builder = new PgEntityDeleteQueryBuilder();
builder.setTablePrefix( this._tablePrefix );
builder.setTableName( tableName );
if ( where !== undefined ) {
LOG.debug( `deleteAll: where = `, where );
builder.setWhereFromQueryBuilder( builder.buildAnd( where, tableName, fields, temporalProperties ) );
}
const [ queryString, queryValues ] = builder.build();
LOG.debug( `deleteAll: queryString = `, queryString );
await this._query( connection, queryString, queryValues );
} else if (entities?.length) {
const builder = new PgEntityDeleteQueryBuilder();
builder.setTablePrefix( this._tablePrefix );
builder.setTableName( tableName );
builder.setWhereFromQueryBuilder(
builder.buildAnd(
Where.propertyListEquals(
idPropertyName,
map(entities, (item) => (item as any)[idPropertyName] )
),
tableName,
fields,
temporalProperties
)
);
const [queryString, queryValues] = builder.build();
await this._query(connection, queryString, queryValues);
if (hasPostRemoveCallbacks) {
await EntityCallbackUtils.runPostRemoveCallbacks(
entities,
callbacks
);
}
}
}
/**
* @inheritDoc
* @see {@link Persister.findAll}
*/
private async _findAll<T extends Entity> (
connection : PoolClient,
metadata : EntityMetadata,
where : Where | undefined,
sort : Sort | undefined
): Promise<T[]> {
LOG.debug(`findAll: `, metadata, where, sort);
const { tableName, fields, oneToManyRelations, manyToOneRelations, temporalProperties, callbacks } = metadata;
LOG.debug(`tableName = "${tableName}"`);
const mainIdColumnName : string = EntityUtils.getIdColumnName(metadata);
const builder = PgEntitySelectQueryBuilder.create();
builder.setTablePrefix(this._tablePrefix);
builder.setTableName(tableName);
if (sort !== undefined) {
builder.setOrderByTableFields(sort, tableName, fields);
}
builder.setGroupByColumn(mainIdColumnName);
builder.includeEntityFields(tableName, fields, temporalProperties);
builder.setOneToManyRelations(oneToManyRelations, this._fetchTableInfo);
builder.setManyToOneRelations(manyToOneRelations, this._fetchTableInfo, fields);
if (where !== undefined) builder.setWhereFromQueryBuilder( builder.buildAnd(where, tableName, fields, temporalProperties) );
const [queryString, queryValues] = builder.build();
const result = await this._query(connection, queryString, queryValues);
const resultEntity = this._toEntityArray(result, metadata);
await EntityCallbackUtils.runPostLoadCallbacks(
resultEntity,
callbacks
);
return resultEntity as unknown as T[];
}
/**
* @inheritDoc
* @see {@link Persister.destroy}
*/
private async _findBy<T extends Entity> (
connection : PoolClient,
metadata : EntityMetadata,
where : Where,
sort : Sort | undefined
): Promise<T | undefined> {
const { tableName, fields, oneToManyRelations, manyToOneRelations, temporalProperties, callbacks } = metadata;
const mainIdColumnName : string = EntityUtils.getIdColumnName(metadata);
const builder = PgEntitySelectQueryBuilder.create();
builder.setTablePrefix(this._tablePrefix);
builder.setTableName(tableName);
if (sort) {
builder.setOrderByTableFields(sort, tableName, fields);
}
builder.setGroupByColumn(mainIdColumnName);
builder.includeEntityFields(tableName, fields, temporalProperties);
builder.setOneToManyRelations(oneToManyRelations, this._fetchTableInfo);
builder.setManyToOneRelations(manyToOneRelations, this._fetchTableInfo, fields);
if (where !== undefined) builder.setWhereFromQueryBuilder( builder.buildAnd(where, tableName, fields, temporalProperties) );
const [queryString, queryValues] = builder.build();
const result = await this._query(connection, queryString, queryValues);
const resultEntity = this._toFirstEntityOrUndefined<T>(result, metadata);
if (resultEntity) {
await EntityCallbackUtils.runPostLoadCallbacks(
[resultEntity],
callbacks
);
}
return resultEntity;
}
/**
* @inheritDoc
* @see {@link Persister.destroy}
*/
private async _insert<T extends Entity> (
connection : PoolClient,
metadata : EntityMetadata,
entities : T | readonly T[],
): Promise<T> {
LOG.debug(`insert: entities = `, entities, metadata);
if ( !isArray(entities) ) {
entities = [entities];
}
if ( entities?.length < 1 ) {
throw new TypeError(`No entities provided. You need to provide at least one entity to insert.`);
}
// Make sure all of our entities have the same metadata
if (!EntityUtils.areEntitiesSameType(entities)) {
throw new TypeError(`Insert can only insert entities of the same time. There were some entities with different metadata than provided.`);
}
const { tableName, fields, temporalProperties, idPropertyName, callbacks } = metadata;
await EntityCallbackUtils.runPrePersistCallbacks(
entities,
callbacks
);
LOG.debug(`insert: table= `, tableName);
const builder = PgEntityInsertQueryBuilder.create();
builder.setTablePrefix(this._tablePrefix);
builder.setTableName(tableName);
builder.appendEntityList(
entities,
fields,
temporalProperties,
[idPropertyName]
);
const [ queryString, values ] = builder.build();
LOG.debug(`insert: query = `, queryString, values);
const result = await this._query(connection, queryString, values);
LOG.debug(`insert: result = `, result);
const resultEntity = this._toFirstEntityOrFail<T>(result, metadata);
await EntityCallbackUtils.runPostLoadCallbacks(
[resultEntity],
callbacks
);
// FIXME: Only single item is returned even if multiple are added {@see https://github.com/heusalagroup/fi.hg.core/issues/72}
await EntityCallbackUtils.runPostPersistCallbacks(
[resultEntity],
callbacks
);
return resultEntity;
}
/**
* @inheritDoc
* @see {@link Persister.destroy}
*/
private async _update<T extends Entity> (
connection : PoolClient,
metadata: EntityMetadata,
entity: T,
): Promise<T> {
const { tableName, fields, temporalProperties, idPropertyName, callbacks } = metadata;
const idField = find(fields, item => item.propertyName === idPropertyName);
if (!idField) throw new TypeError(`Could not find id field using property "${idPropertyName}"`);
const idColumnName = idField.columnName;
if (!idColumnName) throw new TypeError(`Could not find id column using property "${idPropertyName}"`);
const entityId = has(entity, idPropertyName) ? (entity as any)[idPropertyName] : undefined;
if (!entityId) throw new TypeError(`Could not find entity id column using property "${idPropertyName}"`);
const updateFields = this._entityManager.getChangedFields(
entity,
fields
);
if (updateFields.length === 0) {
// FIXME: We probably should call PreUpdate in case that the object
// in the database has changed by someone else?
LOG.debug(`Entity did not any updatable properties changed. Saved nothing.`);
const item : T | undefined = await this._findBy(
connection,
metadata,
Where.propertyEquals(idPropertyName, entityId),
Sort.by(idPropertyName)
);
if (!item) {
throw new TypeError(`Entity was not stored in this persister for ID: ${entityId}`);
}
await EntityCallbackUtils.runPostUpdateCallbacks(
[item],
callbacks
);
return item;
}
await EntityCallbackUtils.runPreUpdateCallbacks(
[entity],
callbacks
);
const builder = PgEntityUpdateQueryBuilder.create();
builder.setTablePrefix(this._tablePrefix);
builder.setTableName(tableName);
builder.appendEntity(
entity,
updateFields,
temporalProperties,
[idPropertyName]
);
const where = PgAndChainBuilder.create();
where.setColumnEquals(this._tablePrefix+tableName, idColumnName, entityId);
builder.setWhereFromQueryBuilder(where);
// builder.setEntities(metadata, entities);
const [ queryString, queryValues ] = builder.build();
const result = await this._query(connection, queryString, queryValues);
const loadedEntity = this._toFirstEntityOrFail<T>(result, metadata);
await EntityCallbackUtils.runPostLoadCallbacks(
[loadedEntity],
callbacks
);
await EntityCallbackUtils.runPostUpdateCallbacks(
[loadedEntity],
callbacks
);
return loadedEntity;
}
/**
* Performs the actual SQL query.
*
* @param connection
* @param query The query as a string with parameter placeholders
* @param values The values for parameter placeholders
* @private
*/
private async _query (
connection : PoolClient,
query: string,
values: readonly any[]
) : Promise<QueryResult> {
query = PgQueryUtils.parametizeQuery(query);
LOG.debug(`Query "${query}" with values: `, values);
try {
// FIXME: The upstream library wants writable array. This might be error.
return await connection.query(query, values as any[]);
} catch (err) {
LOG.debug(`Query failed: `, query, values);
throw TypeError(`Query failed: "${query}": ${err}`);
}
}
/**
* Turns the result set into an array of entities.
*
* @param result
* @param metadata
* @private
*/
private _toEntityArray<T extends Entity> (
result: QueryResult,
metadata: EntityMetadata
) : T[] {
if (!result) throw new TypeError(`Illegal result from query`);
if ( result.fields !== undefined ) LOG.debug(`result.fields = `, result.fields);
if ( result.oid !== undefined ) LOG.debug(`result.oid = `, result.oid);
if ( result.command !== undefined ) LOG.debug(`result.command = `, result.command);
if ( result.rowCount !== undefined ) LOG.debug(`result.rowCount = `, result.rowCount);
if (!result.rows) throw new TypeError(`Illegal result rows from query`);
LOG.debug(`_toEntityArray: result.rows = `, result.rows);
return map(
result.rows,
(row: any) => {
if (!row) throw new TypeError(`Unexpected illegal row: ${row}`);
return this._toEntity<T>(row, metadata);
}
);
}
/**
* Turns the result set into single entity, and returns `undefined` if
* no entity was found.
*
* @param result
* @param metadata
* @private
*/
private _toFirstEntityOrUndefined<T extends Entity> (
result: QueryResult,
metadata: EntityMetadata
) : T | undefined {
if ( !result ) throw new TypeError(`Result was not defined: ${result}`);
if ( result.fields !== undefined ) LOG.debug(`result.fields = `, result.fields);
if ( result.oid !== undefined ) LOG.debug(`result.oid = `, result.oid);
if ( result.command !== undefined ) LOG.debug(`result.command = `, result.command);
if ( result.rowCount !== undefined ) LOG.debug(`result.rowCount = `, result.rowCount);
const rows = result.rows;
if (!rows) throw new TypeError(`Result rows was not defined: ${rows}`);
const row = first(rows);
if (!row) return undefined;
LOG.debug(`_toFirstEntityOrUndefined: row = `, row);
return this._toEntity<T>(row, metadata);
}
/**
* Turns the result set into single entity, and fails if it cannot do that.
*
* @param result
* @param metadata
* @private
*/
private _toFirstEntityOrFail<T extends Entity> (
result: QueryResult,
metadata: EntityMetadata
) : T {
const item = this._toFirstEntityOrUndefined<T>(result, metadata);
if (item === undefined) throw new TypeError(`Result was not found`);
LOG.debug(`_toFirstEntityOrFail: item = `, item);
return item;
}
private _toEntity<T extends Entity> (
row : KeyValuePairs,
metadata : EntityMetadata
) : T {
const entity = EntityUtils.toEntity<T>(row, metadata, this._metadataManager);
this._entityManager.saveLastEntityState(entity);
return entity;
}
}