You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
daton/orm/src/db/PostgresConnection.ts

51 lines
1.6 KiB

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'
export default class PostgresConnection extends Connection {
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)
const result = await this._client.query(query)
let base_i = 0
const cols = collect(result?.rowDescription?.columns || []).sortBy('index').map(col => {
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()
}
}