import pg from 'pg';

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 savepoint(name: string) {
    await this.client!.query(`savepoint ${name}`);
  }

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

  async rollbackTo(name: string) {
    await this.client!.query(`rollback to ${name}`);
  }

  async releaseSavepoint(name: string) {
    await this.client!.query(`release savepoint ${name}`);
  }
}

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