import { Pool } from "pg";
import { executePostgresQuery } from "../pg-query-executor.js";
import { ZQLDatabase } from "../zql-database.js";
class NodePgConnection {
  #pool;
  constructor(pool) {
    this.#pool = pool;
  }
  async transaction(fn) {
    const client = this.#pool instanceof Pool ? await this.#pool.connect() : this.#pool;
    try {
      await client.query("BEGIN");
      const result = await fn(new NodePgTransactionInternal(client));
      await client.query("COMMIT");
      return result;
    } catch (error) {
      try {
        await client.query("ROLLBACK");
      } catch {
      }
      throw error;
    } finally {
      if (this.#pool instanceof Pool && "release" in client) {
        client.release();
      }
    }
  }
}
class NodePgTransactionInternal {
  wrappedTransaction;
  constructor(client) {
    this.wrappedTransaction = client;
  }
  runQuery(ast, format, schema, serverSchema) {
    return executePostgresQuery(
      this,
      ast,
      format,
      schema,
      serverSchema
    );
  }
  async query(sql, params) {
    const res = await this.wrappedTransaction.query(sql, params);
    return res.rows;
  }
}
function zeroNodePg(schema, pg) {
  if (typeof pg === "string") {
    pg = new Pool({ connectionString: pg });
  }
  return new ZQLDatabase(new NodePgConnection(pg), schema);
}
export {
  NodePgConnection,
  NodePgTransactionInternal,
  zeroNodePg
};
//# sourceMappingURL=pg.js.map
