MCPcopy Create free account
hub / github.com/Seb-C/kiss-orm / PgSqlDatabase

Class PgSqlDatabase

src/Databases/PgSqlDatabase.ts:9–76  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

7const sql = SqlQuery.createFromTemplateString;
8
9export default class PgSqlDatabase implements DatabaseInterface {
10 public readonly connection: Pool|ClientBase;
11
12 constructor(connection: PoolConfig|Pool|ClientBase) {
13 if (connection instanceof Pool || connection instanceof Client) {
14 this.connection = connection;
15 } else {
16 this.connection = new Pool(<PoolConfig>connection);
17 }
18 }
19
20 async disconnect() {
21 if (this.connection instanceof Pool) {
22 await this.connection.end();
23 }
24 }
25
26 indexToPlaceholder (i: number): string {
27 return '$' + (i + 1);
28 }
29
30 async query(query: SqlQuery): Promise<any[]> {
31 const compiledQuery = query.compile(this.indexToPlaceholder, formatIdentifier);
32 const result = await this.connection.query(compiledQuery.sql, <any[]><any>compiledQuery.params);
33
34 return result.rows;
35 }
36
37 async sequence<T>(
38 sequence: (sequenceDb: PgSqlDatabase) => Promise<T>,
39 ): Promise<T> {
40 if (!(this.connection instanceof Pool)) {
41 // Already in a sequence, so another call changes nothing but works for conveniency
42 return sequence(this);
43 }
44
45 const client = <PoolClient>(await this.connection.connect());
46
47 try {
48 const result = await sequence(
49 new PgSqlDatabase(<ClientBase>client)
50 );
51 client.release();
52 return result;
53 } catch (error) {
54 client.release();
55 throw error;
56 }
57 }
58
59 async migrate(migrations: { [key: string]: SqlQuery }) {
60 await migrate(this, migrations);
61 }
62
63 async insertAndGet(standardInsertQuery: SqlQuery): Promise<number[]|string[]|any[]> {
64 return this.query(sql`
65 ${standardInsertQuery}
66 RETURNING *;

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected