import pg from 'pg';
import { getConnection } from './database/get_connection';

export class Postgres {
  client: pg.PoolClient | null = null;
  public static async new(pool: pg.Pool) {
    const pg = new Postgres();
    pg.client = await pool.connect();
    return pg;
  }

  async query(query: string, params: any[] = []) {
    return (await this.client!.query(query, params));
  }

  async release() {
    await this.client!.release(true);
  }

  async begin() {
    await this.client!.query('begin');
  }

  async commit() {
    await this.client!.query('commit');
  }

  async rollback() {
    await this.client!.query('rollback');
  }
}

export default async (
  pool: pg.Pool
) => { return await Postgres.new(pool); };

import { building } from '$app/environment';
import init from '$lib/server/database/init_db';
if (!building) await init(await Postgres.new(getConnection()));
