2021-06-03 03:36:25 +00:00
|
|
|
import {Connection, ConnectionNotReadyError} from './Connection'
|
|
|
|
import {Client} from 'pg'
|
|
|
|
import {Inject} from '../../di'
|
|
|
|
import {QueryResult} from '../types'
|
|
|
|
import {collect} from '../../util'
|
|
|
|
import {SQLDialect} from '../dialect/SQLDialect'
|
|
|
|
import {PostgreSQLDialect} from '../dialect/PostgreSQLDialect'
|
|
|
|
import {Logging} from '../../service/Logging'
|
2021-06-02 01:59:40 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Type interface representing the config for a PostgreSQL connection.
|
|
|
|
*/
|
|
|
|
export interface PostgresConnectionConfig {
|
|
|
|
user: string,
|
|
|
|
host: string,
|
|
|
|
database: string,
|
|
|
|
password?: string,
|
|
|
|
port?: string,
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* An implementation of a database Connection for dealing with PostgreSQL servers.
|
|
|
|
*/
|
|
|
|
export class PostgresConnection extends Connection {
|
|
|
|
@Inject()
|
|
|
|
protected readonly logging!: Logging
|
|
|
|
|
|
|
|
/** The `pg` database client. */
|
|
|
|
protected client?: Client
|
|
|
|
|
|
|
|
public dialect(): SQLDialect {
|
|
|
|
return <PostgreSQLDialect> this.app().make(PostgreSQLDialect)
|
|
|
|
}
|
|
|
|
|
2021-06-03 03:36:25 +00:00
|
|
|
public async init(): Promise<void> {
|
2021-06-02 01:59:40 +00:00
|
|
|
this.logging.debug(`Initializing PostgreSQL connection ${this.name}...`)
|
|
|
|
this.client = new Client(this.config)
|
|
|
|
await this.client.connect()
|
|
|
|
}
|
|
|
|
|
2021-06-03 03:36:25 +00:00
|
|
|
public async close(): Promise<void> {
|
2021-06-02 01:59:40 +00:00
|
|
|
this.logging.debug(`Closing PostgreSQL connection ${this.name}...`)
|
|
|
|
if ( this.client ) {
|
|
|
|
await this.client.end()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public async query(query: string): Promise<QueryResult> {
|
2021-06-03 03:36:25 +00:00
|
|
|
if ( !this.client ) {
|
|
|
|
throw new ConnectionNotReadyError(this.name, { config: JSON.stringify(this.config) })
|
|
|
|
}
|
|
|
|
this.logging.verbose(`Executing query in connection ${this.name}: \n${query.split('\n').map(x => ' ' + x)
|
|
|
|
.join('\n')}`)
|
2021-06-02 01:59:40 +00:00
|
|
|
|
|
|
|
try {
|
|
|
|
const result = await this.client.query(query)
|
2021-06-05 13:36:35 +00:00
|
|
|
await this.queryExecuted(query)
|
2021-06-02 01:59:40 +00:00
|
|
|
|
|
|
|
return {
|
|
|
|
rows: collect(result.rows),
|
|
|
|
rowCount: result.rowCount,
|
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
throw this.app().errorWrapContext(e, {
|
|
|
|
query,
|
|
|
|
connection: this.name,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|