Press n or j to go to the next uncovered block, b, p or k for the previous block.
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 | 2x 2x 2x 2x 2x 2x 67x 67x 67x 29x 29x 29x 38x 38x 38x 2x 82x 82x 82x 82x 82x 82x 82x 82x 82x 67x 67x 243x 243x 243x 243x 243x 243x 2x 10x 10x 82x 82x 4x 2x 25x 25x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 4x 4x 4x 4x 3x 3x 4x 4x 4x 4x 4x 6x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 5x 5x 5x 5x 12x 5x 14x 5x 12x 4x 4x 4x 4x 4x 4x 8x 5x 5x 5x 4x 4x 12x 5x 5x 5x 6x 6x 4x 4x 22x 22x 20x 20x 20x 20x 28x 22x 22x 22x 25x 22x 171x 2x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 3x 6x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 2x 2x 2x 2x 5x 5x 3x 3x 5x 5x 5x 5x 5x 5x 7x 5x 5x 5x 4x 8x 5x 5x 5x 5x 5x 5x 5x 5x 8x 5x 5x 5x 8x 5x 2x 2x 45x 2x 10x 10x 10x 10x 10x 10x 10x 10x 25x 50x 2x | /* * Deepkit Framework * Copyright (C) 2021 Deepkit UG, Marc J. Schmidt * * This program is free software: you can redistribute it and/or modify * it under the terms of the MIT License. * * You should have received a copy of the MIT License along with this program. */ import { DefaultPlatform, SqlBuilder, SQLConnection, SQLConnectionPool, SQLDatabaseAdapter, SQLDatabaseQuery, SQLDatabaseQueryFactory, SQLPersistence, SQLQueryModel, SQLQueryResolver, SQLStatement } from '@deepkit/sql'; import {Changes, DatabasePersistenceChangeSet, DatabaseSession, DeleteResult, Entity, PatchResult} from '@deepkit/orm'; import {PostgresPlatform} from './postgres-platform'; import {ClassSchema, getClassSchema, getPropertyXtoClassFunction, PropertySchema, resolvePropertySchema} from '@deepkit/type'; import type {Pool, PoolClient, PoolConfig} from 'pg'; import pg from 'pg'; import {asyncOperation, ClassType, empty} from '@deepkit/core'; export class PostgresStatement extends SQLStatement { protected released = false; constructor(protected sql: string, protected client: PoolClient) { super(); } async get(params: any[] = []) { return asyncOperation<any>((resolve, reject) => { this.client.query(this.sql, params).then((res) => { resolve(res.rows[0]); }).catch(reject); }); } async all(params: any[] = []) { return asyncOperation<any>((resolve, reject) => { this.client.query(this.sql, params).then((res) => { resolve(res.rows); }).catch(reject); }); } release() { } } export class PostgresConnection extends SQLConnection { protected changes: number = 0; public lastReturningRows: any[] = []; protected connection?: PoolClient = undefined; constructor( connectionPool: PostgresConnectionPool, protected getConnection: () => Promise<PoolClient> ) { super(connectionPool); } release() { super.release(); Eif (this.connection) { this.connection.release(); this.connection = undefined; } } async prepare(sql: string) { if (!this.connection) this.connection = await this.getConnection(); return new PostgresStatement(sql, this.connection); } async run(sql: string, params: any[] = []) { await asyncOperation(async (resolve, reject) => { if (!this.connection) this.connection = await this.getConnection(); this.connection.query(sql, params).then((res) => { this.lastReturningRows = res.rows; this.changes = res.rowCount; resolve(undefined); }, reject); }); } async getChanges(): Promise<number> { return this.changes; } } export class PostgresConnectionPool extends SQLConnectionPool { constructor(protected pool: Pool) { super(); } getConnection(): PostgresConnection { this.activeConnections++; return new PostgresConnection(this, () => this.pool.connect()); } } function typeSafeDefaultValue(property: PropertySchema): any { Eif (property.type === 'number') return 0; if (property.type === 'boolean') return false; if (property.type === 'date') return new Date; return null; } export class PostgresPersistence extends SQLPersistence { constructor(protected platform: DefaultPlatform, protected connection: PostgresConnection) { super(platform, connection); } async update<T extends Entity>(classSchema: ClassSchema<T>, changeSets: DatabasePersistenceChangeSet<T>[]): Promise<void> { const scopeSerializer = this.platform.serializer.for(classSchema); const tableName = this.platform.getTableIdentifier(classSchema); const pkName = classSchema.getPrimaryField().name; const pkField = this.platform.quoteIdentifier(pkName); const values: { [name: string]: any[] } = {}; const setNames: string[] = []; const aggregateSelects: { [name: string]: { id: any, sql: string }[] } = {}; const requiredFields: { [name: string]: 1 } = {}; const assignReturning: { [name: string]: { item: any, names: string[] } } = {}; const setReturning: { [name: string]: 1 } = {}; for (const changeSet of changeSets) { const where: string[] = []; const pk = scopeSerializer.partialSerialize(changeSet.primaryKey); for (const i in pk) { Iif (!pk.hasOwnProperty(i)) continue; where.push(`${this.platform.quoteIdentifier(i)} = ${this.platform.quoteValue(pk[i])}`); requiredFields[i] = 1; } if (!values[pkName]) values[pkName] = []; values[pkName].push(this.platform.quoteValue(changeSet.primaryKey[pkName])); const fieldAddedToValues: { [name: string]: 1 } = {}; const id = changeSet.primaryKey[pkName]; if (changeSet.changes.$set) { const value = scopeSerializer.partialSerialize(changeSet.changes.$set); for (const i in value) { Iif (!value.hasOwnProperty(i)) continue; if (!values[i]) { values[i] = []; setNames.push(`${this.platform.quoteIdentifier(i)} = _b.${this.platform.quoteIdentifier(i)}`); } requiredFields[i] = 1; fieldAddedToValues[i] = 1; let v = value[i]; //special postgres check to avoid an error like: /// column "deletedAt" is of type timestamp without time zone but expression is of type text Iif (v === undefined || v === null) { if (classSchema.getProperty(i).type === 'date') { values[i].push('null::timestamp'); } else { values[i].push('null'); } } else { values[i].push(this.platform.quoteValue(v)); } } } if (changeSet.changes.$inc) { for (const i in changeSet.changes.$inc) { Iif (!changeSet.changes.$inc.hasOwnProperty(i)) continue; const value = changeSet.changes.$inc[i]; Eif (!aggregateSelects[i]) aggregateSelects[i] = []; Eif (!values[i]) { values[i] = []; setNames.push(`${this.platform.quoteIdentifier(i)} = _b.${this.platform.quoteIdentifier(i)}`); } Eif (!assignReturning[id]) { assignReturning[id] = { item: changeSet.item, names: [] }; } assignReturning[id].names.push(i); setReturning[i] = 1; aggregateSelects[i].push({ id: changeSet.primaryKey[pkName], sql: `_origin.${this.platform.quoteIdentifier(i)} + ${this.platform.quoteValue(value)}` }); requiredFields[i] = 1; Eif (!fieldAddedToValues[i]) { fieldAddedToValues[i] = 1; values[i].push(this.platform.quoteValue(typeSafeDefaultValue(classSchema.getProperty(i)))); } } } } const selects: string[] = []; const valuesValues: string[] = []; const valuesNames: string[] = []; for (const i in values) { valuesNames.push(i); } for (let i = 0; i < values[pkName].length; i++) { valuesValues.push('(' + valuesNames.map(name => values[name][i]).join(',') + ')'); } for (const i in requiredFields) { if (aggregateSelects[i]) { const select: string[] = []; select.push('CASE'); for (const item of aggregateSelects[i]) { select.push(`WHEN _.${pkField} = ${item.id} THEN ${item.sql}`); } select.push(`ELSE _.${this.platform.quoteIdentifier(i)} END as ${this.platform.quoteIdentifier(i)}`); selects.push(select.join(' ')); } else { selects.push('_.' + this.platform.quoteIdentifier(i)); } } const returningSelect: string[] = []; returningSelect.push(tableName + '.' + pkField); if (!empty(setReturning)) { for (const i in setReturning) { returningSelect.push(tableName + '.' + this.platform.quoteIdentifier(i)); } } const escapedValuesNames = valuesNames.map(v => this.platform.quoteIdentifier(v)); const sql = ` WITH _b(${escapedValuesNames.join(', ')}) AS ( SELECT ${selects.join(', ')} FROM (VALUES ${valuesValues.join(', ')}) as _(${escapedValuesNames.join(', ')}) INNER JOIN ${tableName} as _origin ON (_origin.${pkField} = _.${pkField}) ) UPDATE ${tableName} SET ${setNames.join(', ')} FROM _b WHERE ${tableName}.${pkField} = _b.${pkField} RETURNING ${returningSelect.join(', ')}; `; const result = await this.connection.execAndReturnAll(sql); for (const returning of result) { const r = assignReturning[returning[pkName]]; if (!r) continue; for (const name of r.names) { r.item[name] = returning[name]; } } } protected async populateAutoIncrementFields<T>(classSchema: ClassSchema<T>, items: T[]) { const autoIncrement = classSchema.getAutoIncrementField(); if (!autoIncrement) return; //We adjusted the INSERT SQL with additional RETURNING which returns all generated //auto-increment values. We read the result and simply assign the value. const name = autoIncrement.name; const insertedRows = this.connection.lastReturningRows; Iif (!insertedRows.length) return; for (let i = 0; i < items.length; i++) { items[i][name] = insertedRows[i][name]; } } protected getInsertSQL(classSchema: ClassSchema, fields: string[], values: string[]): string { const autoIncrement = classSchema.getAutoIncrementField(); const returning = autoIncrement ? ` RETURNING ${this.platform.quoteIdentifier(autoIncrement.name)}` : ''; return `INSERT INTO ${this.platform.getTableIdentifier(classSchema)} (${fields.join(', ')}) VALUES (${values.join('), (')}) ${returning}`; } protected placeholderPosition: number = 1; protected resetPlaceholderSymbol() { this.placeholderPosition = 1; } protected getPlaceholderSymbol() { return '$' + this.placeholderPosition++; } } export class PostgresSQLQueryResolver<T extends Entity> extends SQLQueryResolver<T> { async delete(model: SQLQueryModel<T>, deleteResult: DeleteResult<T>): Promise<void> { const primaryKey = this.classSchema.getPrimaryField(); const pkField = this.platform.quoteIdentifier(primaryKey.name); const primaryKeyConverted = getPropertyXtoClassFunction(primaryKey, this.platform.serializer); const sqlBuilder = new SqlBuilder(this.platform); const select = sqlBuilder.select(this.classSchema, model, { select: [pkField] }); const tableName = this.platform.getTableIdentifier(this.classSchema); const connection = this.connectionPool.getConnection(); try { const sql = ` WITH _ AS (${select.sql}) DELETE FROM ${tableName} USING _ WHERE ${tableName}.${pkField} = _.${pkField} RETURNING ${tableName}.${pkField} `; const rows = await connection.execAndReturnAll(sql, select.params); deleteResult.modified = rows.length; for (const row of rows) { deleteResult.primaryKeys.push(primaryKeyConverted(row[primaryKey.name])); } } finally { connection.release(); } } async patch(model: SQLQueryModel<T>, changes: Changes<T>, patchResult: PatchResult<T>): Promise<void> { const select: string[] = []; const tableName = this.platform.getTableIdentifier(this.classSchema); const primaryKey = this.classSchema.getPrimaryField(); const pkField = this.platform.quoteIdentifier(primaryKey.name); const primaryKeyConverted = getPropertyXtoClassFunction(primaryKey, this.platform.serializer); select.push(pkField); const fieldsSet: { [name: string]: 1 } = {}; const aggregateFields: { [name: string]: { converted: (v: any) => any } } = {}; const scopeSerializer = this.platform.serializer.for(this.classSchema); const $set = changes.$set ? scopeSerializer.partialSerialize(changes.$set) : undefined; const set: string[] = []; if ($set) for (const i in $set) { Iif (!$set.hasOwnProperty(i)) continue; Iif ($set[i] === undefined || $set[i] === null) { set.push(`${this.platform.quoteIdentifier(i)} = NULL`); } else { fieldsSet[i] = 1; select.push(`${this.platform.quoteValue($set[i])} as ${this.platform.quoteIdentifier(i)}`); } } Iif (changes.$unset) for (const i in changes.$unset) { if (!changes.$unset.hasOwnProperty(i)) continue; fieldsSet[i] = 1; select.push(`NULL as ${this.platform.quoteIdentifier(i)}`); } for (const i of model.returning) { aggregateFields[i] = { converted: getPropertyXtoClassFunction(resolvePropertySchema(this.classSchema, i), this.platform.serializer) }; select.push(`(${this.platform.quoteIdentifier(i)} ) as ${this.platform.quoteIdentifier(i)}`); } if (changes.$inc) for (const i in changes.$inc) { Iif (!changes.$inc.hasOwnProperty(i)) continue; fieldsSet[i] = 1; aggregateFields[i] = { converted: getPropertyXtoClassFunction(resolvePropertySchema(this.classSchema, i), this.platform.serializer) }; select.push(`(${this.platform.quoteIdentifier(i)} + ${this.platform.quoteValue(changes.$inc[i])}) as ${this.platform.quoteIdentifier(i)}`); } for (const i in fieldsSet) { set.push(`${this.platform.quoteIdentifier(i)} = _b.${this.platform.quoteIdentifier(i)}`); } const returningSelect: string[] = []; returningSelect.push(tableName + '.' + pkField); if (!empty(aggregateFields)) { for (const i in aggregateFields) { returningSelect.push(tableName + '.' + this.platform.quoteIdentifier(i)); } } const sqlBuilder = new SqlBuilder(this.platform); const selectSQL = sqlBuilder.select(this.classSchema, model, { select }); const sql = ` WITH _b AS (${selectSQL.sql}) UPDATE ${tableName} SET ${set.join(', ')} FROM _b WHERE ${tableName}.${pkField} = _b.${pkField} RETURNING ${returningSelect.join(', ')} `; const connection = this.connectionPool.getConnection(); try { const result = await connection.execAndReturnAll(sql, selectSQL.params); patchResult.modified = result.length; for (const i in aggregateFields) { patchResult.returning[i] = []; } for (const returning of result) { patchResult.primaryKeys.push(primaryKeyConverted(returning[primaryKey.name])); for (const i in aggregateFields) { patchResult.returning[i].push(aggregateFields[i].converted(returning[i])); } } } finally { connection.release(); } } } export class PostgresSQLDatabaseQuery<T> extends SQLDatabaseQuery<T> { } export class PostgresSQLDatabaseQueryFactory extends SQLDatabaseQueryFactory { createQuery<T extends Entity>(classType: ClassType<T> | ClassSchema<T>): PostgresSQLDatabaseQuery<T> { return new PostgresSQLDatabaseQuery(getClassSchema(classType), this.databaseSession, new PostgresSQLQueryResolver(this.connectionPool, this.platform, getClassSchema(classType), this.databaseSession) ); } } export class PostgresDatabaseAdapter extends SQLDatabaseAdapter { protected pool = new pg.Pool(this.options); public connectionPool = new PostgresConnectionPool(this.pool); public platform = new PostgresPlatform(); constructor(protected options: PoolConfig) { super(); pg.types.setTypeParser(1700, parseFloat); pg.types.setTypeParser(20, parseInt); } getName(): string { return 'postgres'; } getSchemaName(): string { //todo extract schema name from connection options. This acts as default when a table has no schemaName defined. return ''; } createPersistence(): SQLPersistence { return new PostgresPersistence(this.platform, this.connectionPool.getConnection()); } queryFactory(databaseSession: DatabaseSession<any>): SQLDatabaseQueryFactory { return new PostgresSQLDatabaseQueryFactory(this.connectionPool, this.platform, databaseSession); } disconnect(force?: boolean): void { this.pool.end().catch(console.error); } } |