import { executePostgresQuery } from "../pg-query-executor.js";
import { ZQLDatabase } from "../zql-database.js";
class DrizzleConnection {
  #drizzle;
  constructor(drizzle) {
    this.#drizzle = drizzle;
  }
  transaction(fn) {
    return this.#drizzle.transaction(
      (drizzleTx) => fn(
        new DrizzleInternalTransaction(
          drizzleTx
        )
      )
    );
  }
}
class DrizzleInternalTransaction {
  wrappedTransaction;
  constructor(drizzleTx) {
    this.wrappedTransaction = drizzleTx;
  }
  runQuery(ast, format, schema, serverSchema) {
    return executePostgresQuery(
      this,
      ast,
      format,
      schema,
      serverSchema
    );
  }
  async query(sql, params) {
    const prepared = this.wrappedTransaction._.session.prepareQuery(
      { sql, params },
      void 0,
      void 0,
      false
    );
    const result = await prepared.execute();
    return toIterableRows(result);
  }
}
function isIterable(value) {
  return (
    // oxlint-disable-next-line eqeqeq
    value != null && typeof value[Symbol.iterator] === "function"
  );
}
function toIterableRows(result) {
  if (result === null || result === void 0) {
    return [];
  }
  if (Array.isArray(result)) {
    return result;
  }
  if (isIterable(result)) {
    return result;
  }
  if (typeof result === "object") {
    const rows = result.rows;
    if (rows === null || rows === void 0) {
      return [];
    }
    if (Array.isArray(rows)) {
      return rows;
    }
    if (isIterable(rows)) {
      return rows;
    }
  }
  throw new TypeError("Drizzle query result is not iterable");
}
function zeroDrizzle(schema, client) {
  return new ZQLDatabase(
    new DrizzleConnection(client),
    schema
  );
}
export {
  DrizzleConnection,
  toIterableRows,
  zeroDrizzle
};
//# sourceMappingURL=drizzle.js.map
