2020-07-06 14:53:03 +00:00
|
|
|
import { Connection, ConnectionNotReadyError } from './Connection.ts'
|
|
|
|
import { Client } from '../../../lib/src/external/db.ts'
|
|
|
|
import {collect, Collection} from '../../../lib/src/collection/Collection.ts'
|
|
|
|
import { QueryResult, QueryRow } from './types.ts'
|
|
|
|
import { logger } from '../../../lib/src/service/logging/global.ts'
|
|
|
|
|
2020-08-17 14:44:23 +00:00
|
|
|
/**
|
|
|
|
* Database connection class for PostgreSQL connections.
|
|
|
|
* @extends Connection
|
|
|
|
*/
|
2020-07-06 14:53:03 +00:00
|
|
|
export default class PostgresConnection extends Connection {
|
2020-08-17 14:44:23 +00:00
|
|
|
/**
|
|
|
|
* The underlying PostgreSQL client.
|
|
|
|
* @type Client
|
|
|
|
*/
|
2020-07-06 14:53:03 +00:00
|
|
|
private _client?: Client
|
|
|
|
|
|
|
|
public async init() {
|
|
|
|
this._client = new Client(this.config)
|
|
|
|
|
|
|
|
logger.info(`Opening PostgreSQL database for connection: ${this.name}`)
|
|
|
|
await this._client.connect()
|
|
|
|
}
|
|
|
|
|
|
|
|
public async query(query: string) {
|
|
|
|
if ( !this._client ) throw new ConnectionNotReadyError(this.name)
|
2020-07-28 00:48:44 +00:00
|
|
|
logger.verbose(`Executing query: \n${query}`)
|
2020-07-06 14:53:03 +00:00
|
|
|
const result = await this._client.query(query)
|
|
|
|
|
|
|
|
let base_i = 0
|
2020-07-27 14:41:04 +00:00
|
|
|
const cols = collect(result?.rowDescription?.columns || []).map(col => {
|
2020-07-06 14:53:03 +00:00
|
|
|
col.index = base_i
|
|
|
|
base_i += 1
|
|
|
|
return col
|
|
|
|
})
|
|
|
|
|
|
|
|
const rows = new Collection<QueryRow>()
|
|
|
|
for ( const row of result.rows ) {
|
|
|
|
const row_obj: { [key: string]: any } = {}
|
|
|
|
for ( const col of cols ) {
|
|
|
|
// @ts-ignore
|
|
|
|
row_obj[col.name] = row[col.index]
|
|
|
|
}
|
|
|
|
rows.push(row_obj)
|
|
|
|
}
|
|
|
|
|
|
|
|
logger.verbose(`Query result returned ${result.rowCount} row(s).`)
|
|
|
|
return {
|
|
|
|
rows,
|
|
|
|
row_count: result.rowCount,
|
|
|
|
} as QueryResult
|
|
|
|
}
|
|
|
|
|
|
|
|
public async close() {
|
|
|
|
if ( this._client )
|
|
|
|
await this._client.end()
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|