import pg from "pg";
import { CockroachDatabase } from "../cockroach-core/db.js";
import { CockroachDialect } from "../cockroach-core/dialect.js";
import { entityKind } from "../entity.js";
import { DefaultLogger } from "../logger.js";
import {
  createTableRelationsHelpers,
  extractTablesRelationalConfig
} from "../relations.js";
import { isConfig } from "../utils.js";
import { NodeCockroachSession } from "./session.js";
class NodeCockroachDriver {
  constructor(client, dialect, options = {}) {
    this.client = client;
    this.dialect = dialect;
    this.options = options;
  }
  static [entityKind] = "NodeCockroachDriver";
  createSession(schema) {
    return new NodeCockroachSession(this.client, this.dialect, schema, { logger: this.options.logger });
  }
}
class NodeCockroachDatabase extends CockroachDatabase {
  static [entityKind] = "NodeCockroachDatabase";
}
function construct(client, config = {}) {
  const dialect = new CockroachDialect({ casing: config.casing });
  let logger;
  if (config.logger === true) {
    logger = new DefaultLogger();
  } else if (config.logger !== false) {
    logger = config.logger;
  }
  let schema;
  if (config.schema) {
    const tablesConfig = extractTablesRelationalConfig(
      config.schema,
      createTableRelationsHelpers
    );
    schema = {
      fullSchema: config.schema,
      schema: tablesConfig.tables,
      tableNamesMap: tablesConfig.tableNamesMap
    };
  }
  const driver = new NodeCockroachDriver(client, dialect, { logger });
  const session = driver.createSession(schema);
  const db = new NodeCockroachDatabase(dialect, session, schema);
  db.$client = client;
  return db;
}
function drizzle(...params) {
  if (typeof params[0] === "string") {
    const instance = new pg.Pool({
      connectionString: params[0]
    });
    return construct(instance, params[1]);
  }
  if (isConfig(params[0])) {
    const { connection, client, ...drizzleConfig } = params[0];
    if (client) return construct(client, drizzleConfig);
    const instance = typeof connection === "string" ? new pg.Pool({
      connectionString: connection
    }) : new pg.Pool(connection);
    return construct(instance, drizzleConfig);
  }
  return construct(params[0], params[1]);
}
((drizzle2) => {
  function mock(config) {
    return construct({}, config);
  }
  drizzle2.mock = mock;
})(drizzle || (drizzle = {}));
export {
  NodeCockroachDatabase,
  NodeCockroachDriver,
  drizzle
};
//# sourceMappingURL=driver.js.map