import postgres from 'postgres';
import { ZQLDatabase } from "../zql-database.js";
export class PostgresJSConnection {
    #pg;
    constructor(pg) {
        this.#pg = pg;
    }
    transaction(fn) {
        return this.#pg.begin(pgTx => fn(new PostgresJsTransactionInternal(pgTx)));
    }
}
export class PostgresJsTransactionInternal {
    wrappedTransaction;
    constructor(pgTx) {
        this.wrappedTransaction = pgTx;
    }
    query(sql, params) {
        return this.wrappedTransaction.unsafe(sql, params);
    }
}
/**
 * Wrap a `postgres` client for Zero ZQL.
 *
 * Provides ZQL querying plus access to the underlying postgres.js transaction.
 * Use {@link PostgresJsTransaction} to type your server mutator transaction.
 *
 * @param schema - Zero schema.
 * @param pg - `postgres` client or connection string.
 *
 * @example
 * ```ts
 * import postgres from 'postgres';
 *
 * const sql = postgres(process.env.ZERO_UPSTREAM_DB!);
 * const zql = zeroPostgresJS(schema, sql);
 *
 * // Define the server mutator transaction type using the helper
 * type ServerTx = ServerTransaction<
 *   Schema,
 *   PostgresJsTransaction
 * >;
 *
 * async function createUser(
 *   tx: ServerTx,
 *   {id, name}: {id: string; name: string},
 * ) {
 *   await tx.dbTransaction.wrappedTransaction
 *     .unsafe('INSERT INTO "user" (id, name) VALUES ($1, $2)', [id, name]);
 * }
 * ```
 */
export function zeroPostgresJS(schema, pg) {
    if (typeof pg === 'string') {
        pg = postgres(pg);
    }
    return new ZQLDatabase(new PostgresJSConnection(pg), schema);
}
//# sourceMappingURL=postgresjs.js.map