import { Alepha, AlephaError, KIND, Middleware, Page, Page as Page$1, PageQuery, PageQuery as PageQuery$1, Primitive, SchemaValidator, Service, Static, StaticEncode, TBigInt, TInteger, TNull, TNumber, TNumberOptions, TObject, TOptional, TPage, TSchema, TString, TStringOptions, TUnion, pageQuerySchema, pageSchema } from "alepha";
import { DateTime, DateTimeProvider } from "alepha/datetime";
import * as drizzle from "drizzle-orm";
import { BuildColumns, BuildExtraConfigColumns, SQL, SQLWrapper, sql } from "drizzle-orm";
import { LockConfig, LockStrength, PgColumn, PgColumnBuilderBase, PgDatabase, PgInsertValue, PgSelectBase, PgSequenceOptions, PgTableExtraConfigValue, PgTableWithColumns, PgTransaction, UpdateDeleteAction } from "drizzle-orm/pg-core";
import { CryptoProvider } from "alepha/crypto";
import * as pg from "drizzle-orm/sqlite-core";
import { SQLiteColumnBuilderBase } from "drizzle-orm/sqlite-core";
import { DatabaseSync } from "node:sqlite";
import { UpdateDeleteAction as UpdateDeleteAction$1 } from "drizzle-orm/pg-core/foreign-keys";
import { PgTransactionConfig } from "drizzle-orm/pg-core/session";
import * as DrizzleKit from "drizzle-kit/api";
import { DrizzleD1Database } from "drizzle-orm/d1";
import { Database } from "bun:sqlite";
import { BunSQLiteDatabase } from "drizzle-orm/bun-sqlite";
export * from "drizzle-orm/pg-core";
//#region ../../src/orm/core/constants/PG_SYMBOLS.d.ts
declare const PG_DEFAULT: unique symbol;
declare const PG_PRIMARY_KEY: unique symbol;
declare const PG_CREATED_AT: unique symbol;
declare const PG_UPDATED_AT: unique symbol;
declare const PG_DELETED_AT: unique symbol;
declare const PG_VERSION: unique symbol;
declare const PG_IDENTITY: unique symbol;
declare const PG_ENUM: unique symbol;
declare const PG_REF: unique symbol;
declare const PG_GENERATED: unique symbol;
declare const PG_ORGANIZATION: unique symbol;
/**
 * @deprecated Use `PG_IDENTITY` instead.
 */
declare const PG_SERIAL: unique symbol;
type PgDefault = typeof PG_DEFAULT;
type PgRef = typeof PG_REF;
type PgPrimaryKey = typeof PG_PRIMARY_KEY;
type PgSymbols = {
  [PG_DEFAULT]: {};
  [PG_PRIMARY_KEY]: {};
  [PG_CREATED_AT]: {};
  [PG_UPDATED_AT]: {};
  [PG_DELETED_AT]: {};
  [PG_VERSION]: {};
  [PG_IDENTITY]: PgIdentityOptions;
  [PG_REF]: PgRefOptions;
  [PG_ENUM]: PgEnumOptions;
  [PG_GENERATED]: PgGeneratedOptions;
  [PG_ORGANIZATION]: PgOrganizationOptions;
  /**
   * @deprecated Use `PG_IDENTITY` instead.
   */
  [PG_SERIAL]: {};
};
type PgSymbolKeys = keyof PgSymbols;
interface PgOrganizationOptions {
  /**
   * Fail-closed tenant scoping. When `true`, the repository (a) refuses any
   * read/write with no resolved tenant instead of falling through to an
   * unfiltered "see/write everything" query, and (b) drops the
   * `OR organizationId IS NULL` "global row" escape — a scoped tenant never
   * sees NULL/global rows. Use for security-sensitive tables. Defaults to
   * `false` (the historic fail-open semantics).
   */
  strict?: boolean;
}
type PgIdentityOptions = {
  mode: "always" | "byDefault";
} & PgSequenceOptions & {
  name?: string;
};
interface PgEnumOptions {
  name?: string;
  description?: string;
}
interface PgGeneratedOptions {
  /**
   * SQL expression for the generated column.
   */
  expression: SQL;
  /**
   * Storage mode for the generated column.
   * - `"stored"` — value is computed on write and stored on disk (default for PostgreSQL).
   * - `"virtual"` — value is computed on read (default for SQLite).
   */
  mode?: "stored" | "virtual";
}
interface PgRefOptions {
  ref: () => {
    name: string;
    entity: EntityPrimitive;
  };
  actions?: {
    onUpdate?: UpdateDeleteAction;
    onDelete?: UpdateDeleteAction;
  };
}
//#endregion
//#region ../../src/orm/core/schemas/insertSchema.d.ts
/**
 * Transforms a TObject schema for insert operations.
 * All default properties at the root level are made optional.
 * Generated columns are excluded entirely.
 *
 * @example
 * Before: { name: string; age: number(default=0); fullName: generated }
 * After:  { name: string; age?: number; }
 */
type TObjectInsert<T extends TObject> = TObject<{ [K in keyof T["shape"] as T["shape"][K] extends {
  [PG_GENERATED]: any;
} ? never : K]: T["shape"][K] extends {
  [PG_DEFAULT]: any;
} | {
  [PG_ORGANIZATION]: any;
} ? TOptional<Extract<T["shape"][K], TSchema>> : T["shape"][K]; }>;
declare const insertSchema: <T extends TObject>(obj: T) => TObjectInsert<T>;
//#endregion
//#region ../../src/orm/core/schemas/updateSchema.d.ts
/**
 * Transforms a TObject schema for update operations.
 * All optional properties at the root level are made nullable (i.e., `T | null`).
 * Generated columns are excluded entirely.
 *
 * @example
 * Before: { name?: string; age: number; fullName: generated }
 * After:  { name?: string | null; age: number; }
 */
type TObjectUpdate<T extends TObject> = TObject<{ [K in keyof T["shape"] as T["shape"][K] extends {
  [PG_GENERATED]: any;
} ? never : K]: T["shape"][K] extends TOptional<infer U extends TSchema> ? TOptional<TUnion<[U, TNull]>> : T["shape"][K]; }>;
declare const updateSchema: <T extends TObject>(schema: T) => TObjectUpdate<T>;
//#endregion
//#region ../../src/orm/core/primitives/$entity.d.ts
/**
 * Creates a database entity primitive that defines table structure using TypeBox schemas.
 *
 * @example
 * ```ts
 * import { z } from "alepha";
 * import { $entity } from "alepha/orm";
 *
 * const userEntity = $entity({
 *   name: "users",
 *   schema: z.object({
 *     id: pg.primaryKey(),
 *     name: z.text(),
 *     email: z.email(),
 *   }),
 * });
 * ```
 */
declare const $entity: {
  <TSchema extends TObject>(options: EntityPrimitiveOptions<TSchema>): EntityPrimitive<TSchema>;
  [KIND]: typeof EntityPrimitive;
};
interface EntityPrimitiveOptions<T extends TObject, Keys = keyof Static<T>> {
  /**
   * The database table name that will be created for this entity.
   * If not provided, name will be inferred from the $repository variable name.
   */
  name: string;
  /**
   * TypeBox schema defining the table structure and column types.
   */
  schema: T;
  /**
   * Database indexes to create for query optimization.
   */
  indexes?: (Keys | {
    /**
     * Single column to index.
     */
    column: Keys;
    /**
     * Whether this should be a unique index (enforces uniqueness constraint).
     */
    unique?: boolean;
    /**
     * Custom name for the index. If not provided, generates name automatically.
     */
    name?: string;
    /**
     * Partial index condition. Only rows matching this SQL expression are indexed.
     */
    where?: SQL;
  } | {
    /**
     * Multiple columns for composite index (order matters for query optimization).
     */
    columns: Keys[];
    /**
     * Whether this should be a unique index (enforces uniqueness constraint).
     */
    unique?: boolean;
    /**
     * Custom name for the index. If not provided, generates name automatically.
     */
    name?: string;
    /**
     * Partial index condition. Only rows matching this SQL expression are indexed.
     */
    where?: SQL;
  } | {
    /**
     * SQL expressions for expression-based indexes.
     *
     * Can include column references and SQL functions like `LOWER()`, `UPPER()`, etc.
     * Columns and expressions can be mixed together.
     *
     * @example
     * ```ts
     * // Case-insensitive unique username per realm
     * indexes: [{
     *   expressions: (self) => [self.realm, sql`LOWER(${self.username})`],
     *   unique: true,
     *   name: "users_realm_username_lower_idx",
     * }]
     * ```
     */
    expressions: (self: Record<Keys & string, any>) => (SQL | any)[];
    /**
     * Whether this should be a unique index (enforces uniqueness constraint).
     */
    unique?: boolean;
    /**
     * Custom name for the index. If not provided, generates name automatically.
     */
    name: string;
    /**
     * Partial index condition. Only rows matching this SQL expression are indexed.
     */
    where?: SQL;
  })[];
  /**
   * Foreign key constraints to maintain referential integrity.
   */
  foreignKeys?: Array<{
    /**
     * Optional name for the foreign key constraint.
     */
    name?: string;
    /**
     * Local columns that reference the foreign table.
     */
    columns: Array<keyof Static<T>>;
    /**
     * Referenced columns in the foreign table.
     * Must be EntityColumn references from other entities.
     */
    foreignColumns: Array<() => EntityColumn<any>>;
  }>;
  /**
   * Additional table constraints for data validation.
   *
   * Constraints enforce business rules at the database level, providing
   * an additional layer of data integrity beyond application validation.
   *
   * **Constraint Types**:
   * - **Unique constraints**: Prevent duplicate values across columns
   * - **Check constraints**: Enforce custom validation rules with SQL expressions
   *
   * @example
   * ```ts
   * constraints: [
   *   {
   *     name: "unique_user_email",
   *     columns: ["email"],
   *     unique: true
   *   },
   *   {
   *     name: "valid_age_range",
   *     columns: ["age"],
   *     check: sql`age >= 0 AND age <= 150`
   *   },
   *   {
   *     name: "unique_user_username_per_tenant",
   *     columns: ["tenantId", "username"],
   *     unique: true
   *   }
   * ]
   * ```
   */
  constraints?: Array<{
    /**
     * Columns involved in this constraint.
     */
    columns: Array<keyof Static<T>>;
    /**
     * Optional name for the constraint.
     */
    name?: string;
    /**
     * Whether this is a unique constraint.
     */
    unique?: boolean | {};
    /**
     * SQL expression for check constraint validation.
     */
    check?: SQL;
  }>;
  /**
   * Advanced Drizzle ORM configuration for complex table setups.
   */
  config?: (self: BuildExtraConfigColumns<string, FromSchema<T>, "pg">) => PgTableExtraConfigValue[];
}
declare class EntityPrimitive<T extends TObject = TObject> {
  readonly options: EntityPrimitiveOptions<T>;
  constructor(options: EntityPrimitiveOptions<T>);
  alias(alias: string): this;
  get cols(): EntityColumns<T>;
  get name(): string;
  get schema(): T;
  protected _insertSchema?: TObjectInsert<T>;
  get insertSchema(): TObjectInsert<T>;
  protected _updateSchema?: TObjectUpdate<T>;
  get updateSchema(): TObjectUpdate<T>;
}
/**
 * Convert a schema to columns.
 */
type FromSchema<T extends TObject> = { [key in keyof T["properties"]]: PgColumnBuilderBase; };
type SchemaToTableConfig<T extends TObject> = {
  name: string;
  schema: string | undefined;
  columns: { [key in keyof T["properties"]]: PgColumn; };
  dialect: string;
};
type EntityColumn<T extends TObject> = {
  name: string;
  entity: EntityPrimitive<T>;
};
type EntityColumns<T extends TObject> = { [key in keyof T["properties"]]: EntityColumn<T>; };
//#endregion
//#region ../../src/orm/core/errors/DbError.d.ts
declare class DbError extends AlephaError {
  name: string;
  constructor(message: string, cause?: unknown);
}
//#endregion
//#region ../../src/orm/core/errors/DbColumnNotFoundError.d.ts
/**
 * Error thrown when a column does not exist.
 *
 * This typically happens when:
 * - Column name is misspelled
 * - Migrations haven't been run
 * - Using wrong schema version
 */
declare class DbColumnNotFoundError extends DbError {
  readonly name = "DbColumnNotFoundError";
  readonly status = 500;
  /**
   * The column that was not found.
   */
  readonly column?: string;
  /**
   * The table where the column was expected.
   */
  readonly table?: string;
  constructor(message: string, cause?: unknown, options?: {
    column?: string;
    table?: string;
  });
  /**
   * Parse a database column not found error and create a DbColumnNotFoundError.
   * Supports both PostgreSQL and SQLite error formats.
   */
  static fromDatabaseError(error: Error): DbColumnNotFoundError;
}
//#endregion
//#region ../../src/orm/core/errors/DbConnectionError.d.ts
/**
 * Error thrown when a database connection fails.
 *
 * This can happen due to:
 * - Connection refused (server not running)
 * - Connection timeout
 * - Authentication failure
 * - Network issues
 * - Database file not found (SQLite)
 */
declare class DbConnectionError extends DbError {
  readonly name = "DbConnectionError";
  readonly status = 503;
  /**
   * The type of connection error.
   */
  readonly errorType?: "refused" | "timeout" | "auth" | "not_found" | "locked" | "unknown";
  /**
   * Whether this error is retryable.
   * Connection errors are often transient and can be retried.
   */
  readonly retryable: boolean;
  constructor(message: string, cause?: unknown, options?: {
    errorType?: DbConnectionError["errorType"];
    retryable?: boolean;
  });
  /**
   * Parse a database connection error message and create a DbConnectionError.
   * Supports both PostgreSQL and SQLite error formats.
   */
  static fromDatabaseError(error: Error): DbConnectionError;
}
//#endregion
//#region ../../src/orm/core/errors/DbDeadlockError.d.ts
/**
 * Error thrown when a deadlock is detected.
 *
 * This happens when two or more transactions are waiting for each other
 * to release locks. The database automatically aborts one transaction
 * to resolve the deadlock.
 *
 * This error is useful for implementing retry logic.
 */
declare class DbDeadlockError extends DbError {
  readonly name = "DbDeadlockError";
  readonly status = 409;
  /**
   * Whether this error is retryable.
   * Deadlocks are typically safe to retry.
   */
  readonly retryable = true;
  /**
   * Parse a database deadlock error message and create a DbDeadlockError.
   * Supports PostgreSQL. SQLite doesn't have true deadlocks (uses SQLITE_BUSY instead).
   */
  static fromDatabaseError(error: Error): DbDeadlockError;
}
//#endregion
//#region ../../src/orm/core/errors/DbEntityNotFoundError.d.ts
declare class DbEntityNotFoundError extends DbError {
  readonly name = "DbEntityNotFoundError";
  readonly status = 404;
  constructor(entityName: string);
}
//#endregion
//#region ../../src/orm/core/errors/DbForeignKeyError.d.ts
/**
 * Error thrown when a foreign key constraint is violated.
 *
 * This typically happens when trying to delete an entity that is
 * referenced by another entity.
 */
declare class DbForeignKeyError extends DbError {
  readonly name = "DbForeignKeyError";
  readonly status = 409;
  /**
   * The table that references the entity being deleted.
   */
  readonly referencingTable?: string;
  /**
   * The constraint name that was violated.
   */
  readonly constraintName?: string;
  constructor(message: string, cause?: unknown, options?: {
    referencingTable?: string;
    constraintName?: string;
  });
  /**
   * Parse a database foreign key error message and create a DbForeignKeyError.
   * Supports both PostgreSQL and SQLite error formats.
   */
  static fromDatabaseError(error: Error, tableName: string): DbForeignKeyError;
}
//#endregion
//#region ../../src/orm/core/errors/DbNotNullError.d.ts
/**
 * Error thrown when a NOT NULL constraint is violated.
 *
 * This happens when inserting or updating a NULL value into a column
 * that has a NOT NULL constraint.
 */
declare class DbNotNullError extends DbError {
  readonly name = "DbNotNullError";
  readonly status = 400;
  /**
   * The column that violated the NOT NULL constraint.
   */
  readonly column?: string;
  /**
   * The table containing the column.
   */
  readonly table?: string;
  constructor(message: string, cause?: unknown, options?: {
    column?: string;
    table?: string;
  });
  /**
   * Parse a database NOT NULL error message and create a DbNotNullError.
   * Supports both PostgreSQL and SQLite error formats.
   */
  static fromDatabaseError(error: Error, tableName: string): DbNotNullError;
}
//#endregion
//#region ../../src/orm/core/errors/DbTableNotFoundError.d.ts
/**
 * Error thrown when a table does not exist.
 *
 * This typically happens when:
 * - Migrations haven't been run
 * - Table name is misspelled
 * - Wrong database/schema is being used
 */
declare class DbTableNotFoundError extends DbError {
  readonly name = "DbTableNotFoundError";
  readonly status = 500;
  /**
   * The table that was not found.
   */
  readonly table?: string;
  constructor(message: string, cause?: unknown, options?: {
    table?: string;
  });
  /**
   * Parse a database table not found error and create a DbTableNotFoundError.
   * Supports both PostgreSQL and SQLite error formats.
   */
  static fromDatabaseError(error: Error): DbTableNotFoundError;
}
//#endregion
//#region ../../src/orm/core/helpers/pgAttr.d.ts
/**
 * Decorates a typebox schema with a Postgres attribute.
 *
 * > It's just a fancy way to add Symbols to a field.
 *
 * @example
 * ```ts
 * import { z } from "alepha";
 * import { PG_UPDATED_AT } from "../constants/PG_SYMBOLS";
 *
 * export const updatedAtSchema = pgAttr(
 *   z.datetime(), PG_UPDATED_AT,
 * );
 * ```
 */
declare const pgAttr: <T extends TSchema, Attr extends PgSymbolKeys>(type: T, attr: Attr, value?: PgSymbols[Attr]) => PgAttr<T, Attr>;
/**
 * Retrieves the fields of a schema that have a specific attribute.
 */
declare const getAttrFields: (schema: TObject, name: PgSymbolKeys) => PgAttrField[];
/**
 * Type representation.
 */
type PgAttr<T extends TSchema, TAttr extends PgSymbolKeys> = T & { [K in TAttr]: PgSymbols[K]; };
interface PgAttrField {
  key: string;
  type: TSchema;
  data: any;
  nested?: any[];
  one?: boolean;
}
//#endregion
//#region ../../src/orm/core/interfaces/FilterOperators.d.ts
interface FilterOperators<TValue> {
  /**
   * Test that two values are equal.
   *
   * Remember that the SQL standard dictates that
   * two NULL values are not equal, so if you want to test
   * whether a value is null, you may want to use
   * `isNull` instead.
   *
   * ## Examples
   *
   * ```ts
   * // Select cars made by Ford
   * db.select().from(cars)
   *   .where(eq(cars.make, 'Ford'))
   * ```
   *
   * @see isNull for a way to test equality to NULL.
   */
  eq?: TValue;
  /**
   * Test that two values are not equal.
   *
   * Remember that the SQL standard dictates that
   * two NULL values are not equal, so if you want to test
   * whether a value is not null, you may want to use
   * `isNotNull` instead.
   *
   * ## Examples
   *
   * ```ts
   * // Select cars not made by Ford
   * db.select().from(cars)
   *   .where(ne(cars.make, 'Ford'))
   * ```
   *
   * @see isNotNull for a way to test whether a value is not null.
   */
  ne?: TValue;
  /**
   * Test that the first expression passed is greater than
   * the second expression.
   *
   * ## Examples
   *
   * ```ts
   * // Select cars made after 2000.
   * db.select().from(cars)
   *   .where(gt(cars.year, 2000))
   * ```
   *
   * @see gte for greater-than-or-equal
   */
  gt?: TValue;
  /**
   * Test that the first expression passed is greater than
   * or equal to the second expression. Use `gt` to
   * test whether an expression is strictly greater
   * than another.
   *
   * ## Examples
   *
   * ```ts
   * // Select cars made on or after 2000.
   * db.select().from(cars)
   *   .where(gte(cars.year, 2000))
   * ```
   *
   * @see gt for a strictly greater-than condition
   */
  gte?: TValue;
  /**
   * Test that the first expression passed is less than
   * the second expression.
   *
   * ## Examples
   *
   * ```ts
   * // Select cars made before 2000.
   * db.select().from(cars)
   *   .where(lt(cars.year, 2000))
   * ```
   *
   * @see lte for greater-than-or-equal
   */
  lt?: TValue;
  /**
   * Test that the first expression passed is less than
   * or equal to the second expression.
   *
   * ## Examples
   *
   * ```ts
   * // Select cars made before 2000.
   * db.select().from(cars)
   *   .where(lte(cars.year, 2000))
   * ```
   *
   * @see lt for a strictly less-than condition
   */
  lte?: TValue;
  /**
   * Test whether the first parameter, a column or expression,
   * has a value from a list passed as the second argument.
   *
   * ## Throws
   *
   * The argument passed in the second array can't be empty:
   * if an empty is provided, this method will throw.
   *
   * ## Examples
   *
   * ```ts
   * // Select cars made by Ford or GM.
   * db.select().from(cars)
   *   .where(inArray(cars.make, ['Ford', 'GM']))
   * ```
   *
   * @see notInArray for the inverse of this test
   */
  inArray?: TValue[];
  /**
   * Test whether the first parameter, a column or expression,
   * has a value that is not present in a list passed as the
   * second argument.
   *
   * ## Throws
   *
   * The argument passed in the second array can't be empty:
   * if an empty is provided, this method will throw.
   *
   * ## Examples
   *
   * ```ts
   * // Select cars made by any company except Ford or GM.
   * db.select().from(cars)
   *   .where(notInArray(cars.make, ['Ford', 'GM']))
   * ```
   *
   * @see inArray for the inverse of this test
   */
  notInArray?: TValue[];
  /**
   * Test whether an expression is not NULL. By the SQL standard,
   * NULL is neither equal nor not equal to itself, so
   * it's recommended to use `isNull` and `notIsNull` for
   * comparisons to NULL.
   *
   * ## Examples
   *
   * ```ts
   * // Select cars that have been discontinued.
   * db.select().from(cars)
   *   .where(isNotNull(cars.discontinuedAt))
   * ```
   *
   * @see isNull for the inverse of this test
   */
  isNotNull?: true;
  /**
   * Test whether an expression is NULL. By the SQL standard,
   * NULL is neither equal nor not equal to itself, so
   * it's recommended to use `isNull` and `notIsNull` for
   * comparisons to NULL.
   *
   * ## Examples
   *
   * ```ts
   * // Select cars that have no discontinuedAt date.
   * db.select().from(cars)
   *   .where(isNull(cars.discontinuedAt))
   * ```
   *
   * @see isNotNull for the inverse of this test
   */
  isNull?: true;
  /**
   * Test whether an expression is between two values. This
   * is an easier way to express range tests, which would be
   * expressed mathematically as `x <= a <= y` but in SQL
   * would have to be like `a >= x AND a <= y`.
   *
   * Between is inclusive of the endpoints: if `column`
   * is equal to `min` or `max`, it will be TRUE.
   *
   * ## Examples
   *
   * ```ts
   * // Select cars made between 1990 and 2000
   * db.select().from(cars)
   *   .where(between(cars.year, 1990, 2000))
   * ```
   *
   * @see notBetween for the inverse of this test
   */
  between?: [number, number];
  /**
   * Test whether an expression is not between two values.
   *
   * This, like `between`, includes its endpoints, so if
   * the `column` is equal to `min` or `max`, in this case
   * it will evaluate to FALSE.
   *
   * ## Examples
   *
   * ```ts
   * // Exclude cars made in the 1970s
   * db.select().from(cars)
   *   .where(notBetween(cars.year, 1970, 1979))
   * ```
   *
   * @see between for the inverse of this test
   */
  notBetween?: [number, number];
  /**
   * Compare a column to a pattern, which can include `%` and `_`
   * characters to match multiple variations. Including `%`
   * in the pattern matches zero or more characters, and including
   * `_` will match a single character.
   *
   * ## Examples
   *
   * ```ts
   * // Select all cars with 'Turbo' in their names.
   * db.select().from(cars)
   *   .where(like(cars.name, '%Turbo%'))
   * ```
   *
   * @see ilike for a case-insensitive version of this condition
   */
  like?: string;
  /**
   * The inverse of like - this tests that a given column
   * does not match a pattern, which can include `%` and `_`
   * characters to match multiple variations. Including `%`
   * in the pattern matches zero or more characters, and including
   * `_` will match a single character.
   *
   * ## Examples
   *
   * ```ts
   * // Select all cars that don't have "ROver" in their name.
   * db.select().from(cars)
   *   .where(notLike(cars.name, '%Rover%'))
   * ```
   *
   * @see like for the inverse condition
   * @see notIlike for a case-insensitive version of this condition
   */
  notLike?: string;
  /**
   * Case-insensitively compare a column to a pattern,
   * which can include `%` and `_`
   * characters to match multiple variations. Including `%`
   * in the pattern matches zero or more characters, and including
   * `_` will match a single character.
   *
   * Unlike like, this performs a case-insensitive comparison.
   *
   * ## Examples
   *
   * ```ts
   * // Select all cars with 'Turbo' in their names.
   * db.select().from(cars)
   *   .where(ilike(cars.name, '%Turbo%'))
   * ```
   *
   * @see like for a case-sensitive version of this condition
   */
  ilike?: string;
  /**
   * The inverse of ilike - this case-insensitively tests that a given column
   * does not match a pattern, which can include `%` and `_`
   * characters to match multiple variations. Including `%`
   * in the pattern matches zero or more characters, and including
   * `_` will match a single character.
   *
   * ## Examples
   *
   * ```ts
   * // Select all cars that don't have "Rover" in their name.
   * db.select().from(cars)
   *   .where(notLike(cars.name, '%Rover%'))
   * ```
   *
   * @see ilike for the inverse condition
   * @see notLike for a case-sensitive version of this condition
   */
  notIlike?: string;
  /**
   * Syntactic sugar for case-insensitive substring matching.
   * Automatically wraps the value with `%` wildcards on both sides.
   *
   * Equivalent to: `ilike: '%value%'`
   *
   * ## Examples
   *
   * ```ts
   * // Select all cars with "Turbo" anywhere in their name.
   * db.select().from(cars)
   *   .where({ name: { contains: 'Turbo' } })
   * // Same as: .where(ilike(cars.name, '%Turbo%'))
   * ```
   *
   * @see ilike for manual pattern matching
   * @see startsWith for prefix matching
   * @see endsWith for suffix matching
   */
  contains?: string;
  /**
   * Syntactic sugar for case-insensitive prefix matching.
   * Automatically appends a `%` wildcard to the end of the value.
   *
   * Equivalent to: `ilike: 'value%'`
   *
   * ## Examples
   *
   * ```ts
   * // Select all cars whose names start with "Ford".
   * db.select().from(cars)
   *   .where({ name: { startsWith: 'Ford' } })
   * // Same as: .where(ilike(cars.name, 'Ford%'))
   * ```
   *
   * @see ilike for manual pattern matching
   * @see contains for substring matching
   * @see endsWith for suffix matching
   */
  startsWith?: string;
  /**
   * Syntactic sugar for case-insensitive suffix matching.
   * Automatically prepends a `%` wildcard to the beginning of the value.
   *
   * Equivalent to: `ilike: '%value'`
   *
   * ## Examples
   *
   * ```ts
   * // Select all cars whose names end with "Turbo".
   * db.select().from(cars)
   *   .where({ name: { endsWith: 'Turbo' } })
   * // Same as: .where(ilike(cars.name, '%Turbo'))
   * ```
   *
   * @see ilike for manual pattern matching
   * @see contains for substring matching
   * @see startsWith for prefix matching
   */
  endsWith?: string;
  /**
   * Test that a column or expression contains all elements of
   * the list passed as the second argument.
   *
   * ## Throws
   *
   * The argument passed in the second array can't be empty:
   * if an empty is provided, this method will throw.
   *
   * ## Examples
   *
   * ```ts
   * // Select posts where its tags contain "Typescript" and "ORM".
   * db.select().from(posts)
   *   .where(arrayContains(posts.tags, ['Typescript', 'ORM']))
   * ```
   *
   * @see arrayContained to find if an array contains all elements of a column or expression
   * @see arrayOverlaps to find if a column or expression contains any elements of an array
   */
  arrayContains?: TValue;
  /**
   * Test that the list passed as the second argument contains
   * all elements of a column or expression.
   *
   * ## Throws
   *
   * The argument passed in the second array can't be empty:
   * if an empty is provided, this method will throw.
   *
   * ## Examples
   *
   * ```ts
   * // Select posts where its tags contain "Typescript", "ORM" or both,
   * // but filtering posts that have additional tags.
   * db.select().from(posts)
   *   .where(arrayContained(posts.tags, ['Typescript', 'ORM']))
   * ```
   *
   * @see arrayContains to find if a column or expression contains all elements of an array
   * @see arrayOverlaps to find if a column or expression contains any elements of an array
   */
  arrayContained?: TValue;
  /**
   * Test that a column or expression contains any elements of
   * the list passed as the second argument.
   *
   * ## Throws
   *
   * The argument passed in the second array can't be empty:
   * if an empty is provided, this method will throw.
   *
   * ## Examples
   *
   * ```ts
   * // Select posts where its tags contain "Typescript", "ORM" or both.
   * db.select().from(posts)
   *   .where(arrayOverlaps(posts.tags, ['Typescript', 'ORM']))
   * ```
   *
   * @see arrayContains to find if a column or expression contains all elements of an array
   * @see arrayContained to find if an array contains all elements of a column or expression
   */
  arrayOverlaps?: TValue;
}
//#endregion
//#region ../../src/orm/core/interfaces/PgQuery.d.ts
/**
 * Order direction for sorting
 */
type OrderDirection = "asc" | "desc";
/**
 * Single order by clause with column and direction
 */
interface OrderByClause<T> {
  column: keyof T;
  direction?: OrderDirection;
}
/**
 * Order by parameter - supports 3 modes:
 * 1. String: orderBy: "name" (defaults to ASC)
 * 2. Single object: orderBy: { column: "name", direction: "desc" }
 * 3. Array: orderBy: [{ column: "name", direction: "asc" }, { column: "age", direction: "desc" }]
 */
type OrderBy<T> = keyof T | OrderByClause<T> | Array<OrderByClause<T>>;
/**
 * Generic query interface for PostgreSQL entities
 */
interface PgQuery<T extends TObject = TObject> {
  distinct?: (keyof Static<T>)[];
  columns?: (keyof Static<T>)[];
  where?: PgQueryWhereOrSQL<T>;
  limit?: number;
  offset?: number;
  orderBy?: OrderBy<Static<T>>;
  groupBy?: (keyof Static<T>)[];
}
type PgStatic<T extends TObject, Relations extends PgRelationMap<T>> = Static<T> & { [K in keyof Relations]: Static<Relations[K]["join"]["schema"]> & (Relations[K]["with"] extends PgRelationMap<TObject> ? PgStatic<Relations[K]["join"]["schema"], Relations[K]["with"]> : {}); };
interface PgQueryRelations<T extends TObject = TObject, Relations extends PgRelationMap<T> | undefined = undefined> extends PgQuery<T> {
  with?: Relations;
  where?: PgQueryWhereOrSQL<T, Relations>;
}
type PgRelationMap<Base extends TObject> = Record<string, PgRelation<Base>>;
type PgRelation<Base extends TObject> = {
  type?: "left" | "inner" | "right";
  join: {
    schema: TObject;
    name: string;
  };
  on: SQLWrapper | readonly [keyof Static<Base>, {
    name: string;
  }];
  with?: PgRelationMap<TObject>;
};
//#endregion
//#region ../../src/orm/core/interfaces/PgQueryWhere.d.ts
type PgQueryWhere<T extends TObject, Relations extends PgRelationMap<TObject> | undefined = undefined> = (PgQueryWhereOperators<T> & PgQueryWhereConditions<T>) | (PgQueryWhereRelations<Relations> & PgQueryWhereOperators<T> & PgQueryWhereConditions<T, Relations>);
type PgQueryWhereOrSQL<T extends TObject, Relations extends PgRelationMap<TObject> | undefined = undefined> = SQLWrapper | PgQueryWhere<T, Relations>;
type PgQueryWhereOperators<T extends TObject> = { [Key in keyof Static<T>]?: FilterOperators<Static<T>[Key]> | Static<T>[Key]; };
type PgQueryWhereConditions<T extends TObject, Relations extends PgRelationMap<TObject> | undefined = undefined> = {
  /**
   * Combine a list of conditions with the `and` operator. Conditions
   * that are equal `undefined` are automatically ignored.
   *
   * ## Examples
   *
   * ```ts
   * db.select().from(cars)
   *   .where(
   *     and(
   *       eq(cars.make, 'Volvo'),
   *       eq(cars.year, 1950),
   *     )
   *   )
   * ```
   */
  and?: Array<PgQueryWhereOrSQL<T, Relations>>;
  /**
   * Combine a list of conditions with the `or` operator. Conditions
   * that are equal `undefined` are automatically ignored.
   *
   * ## Examples
   *
   * ```ts
   * db.select().from(cars)
   *   .where(
   *     or(
   *       eq(cars.make, 'GM'),
   *       eq(cars.make, 'Ford'),
   *     )
   *   )
   * ```
   */
  or?: Array<PgQueryWhereOrSQL<T, Relations>>;
  /**
   * Negate the meaning of an expression using the `not` keyword.
   *
   * ## Examples
   *
   * ```ts
   * // Select cars _not_ made by GM or Ford.
   * db.select().from(cars)
   *   .where(not(inArray(cars.make, ['GM', 'Ford'])))
   * ```
   */
  not?: PgQueryWhereOrSQL<T, Relations>;
  /**
   * Test whether a subquery evaluates to have any rows.
   *
   * ## Examples
   *
   * ```ts
   * // Users whose `homeCity` column has a match in a cities
   * // table.
   * db
   *   .select()
   *   .from(users)
   *   .where(
   *     exists(db.select()
   *       .from(cities)
   *       .where(eq(users.homeCity, cities.id))),
   *   );
   * ```
   *
   * @see notExists for the inverse of this test
   */
  exists?: SQLWrapper;
  /**
   * Test whether a subquery evaluates to have no rows.
   *
   * @see exists for the inverse of this test
   */
  notExists?: SQLWrapper;
};
type PgQueryWhereRelations<Relations extends PgRelationMap<TObject> | undefined = undefined> = Relations extends PgRelationMap<TObject> ? { [K in keyof Relations]?: PgQueryWhere<Relations[K]["join"]["schema"], Relations[K]["with"]>; } : {};
//#endregion
//#region ../../src/orm/core/interfaces/AggregateQuery.d.ts
type AggregateOp = "count" | "sum" | "avg" | "min" | "max";
/**
 * Select definition for aggregate queries.
 * - `true` means select the column value as-is (used for groupBy columns).
 * - `{ sum: true, avg: true, ... }` means compute those aggregations.
 */
type AggregateColumnSelect = true | Partial<Record<AggregateOp, true>>;
type AggregateSelect<T extends TObject> = { [K in keyof Static<T>]?: AggregateColumnSelect; };
/**
 * Maps a single column's select definition to its result type.
 * - `true` → original column type
 * - `{ sum: true, avg: true }` → `{ sum: number; avg: number }`
 */
type AggregateColumnResult<TValue, TSelect> = TSelect extends true ? TValue : { [Op in AggregateOp as TSelect extends Record<Op, true> ? Op : never]: number; };
/**
 * Result type for an aggregate query.
 */
type AggregateResult<T extends TObject, S extends AggregateSelect<T>> = { [K in keyof S & keyof Static<T>]: AggregateColumnResult<Static<T>[K], NonNullable<S[K]>>; };
/**
 * HAVING clause for aggregate queries.
 * Only applies to columns with aggregate operations (not `true`).
 */
type AggregateHaving<T extends TObject, S extends AggregateSelect<T>> = { [K in keyof S & keyof Static<T>]?: S[K] extends true ? never : { [Op in AggregateOp as S[K] extends Record<Op, true> ? Op : never]?: {
  gt?: number;
  gte?: number;
  lt?: number;
  lte?: number;
  eq?: number;
  ne?: number;
}; }; };
/**
 * Full aggregate query definition.
 */
interface AggregateQuery<T extends TObject, S extends AggregateSelect<T>> {
  /**
   * Columns and aggregate operations to select.
   */
  select: S;
  /**
   * WHERE clause to filter rows before aggregation.
   */
  where?: PgQueryWhereOrSQL<T>;
  /**
   * Columns to group by.
   */
  groupBy?: (keyof Static<T>)[];
  /**
   * HAVING clause to filter groups after aggregation.
   */
  having?: AggregateHaving<T, S>;
  /**
   * Order results. Supports dot notation for aggregate columns (e.g. "amount.sum").
   */
  orderBy?: string | {
    column: string;
    direction: "asc" | "desc";
  } | Array<{
    column: string;
    direction: "asc" | "desc";
  }>;
  /**
   * Limit the number of results.
   */
  limit?: number;
  /**
   * Offset for pagination.
   */
  offset?: number;
}
//#endregion
//#region ../../src/orm/core/providers/DatabaseTypeProvider.d.ts
declare class DatabaseTypeProvider {
  readonly attr: typeof pgAttr;
  /**
   * Creates a primary key with an identity column.
   */
  readonly identityPrimaryKey: (identity?: PgIdentityOptions) => PgAttr<PgAttr<PgAttr<import("zod").ZodInt, typeof PG_PRIMARY_KEY>, typeof PG_IDENTITY>, typeof PG_DEFAULT>;
  /**
   * Creates a primary key with a big identity column. (default)
   */
  readonly bigIdentityPrimaryKey: (identity?: PgIdentityOptions) => PgAttr<PgAttr<PgAttr<import("zod").ZodInt, typeof PG_PRIMARY_KEY>, typeof PG_IDENTITY>, typeof PG_DEFAULT>;
  /**
   * Creates a primary key with a UUID column.
   */
  readonly uuidPrimaryKey: () => PgAttr<PgAttr<import("zod").ZodString, typeof PG_PRIMARY_KEY>, typeof PG_DEFAULT>;
  /**
   * Creates a primary key for a given type. Supports:
   * - `t.integer()` -> PG INT (default)
   * - `t.bigint()` -> PG BIGINT
   * - `t.uuid()` -> PG UUID
   */
  primaryKey(): PgAttr<PgAttr<TInteger, PgPrimaryKey>, PgDefault>;
  primaryKey(type: TString, options?: TStringOptions): PgAttr<PgAttr<TString, PgPrimaryKey>, PgDefault>;
  primaryKey(type: TInteger, options?: TNumberOptions, identity?: PgIdentityOptions): PgAttr<PgAttr<TInteger, PgPrimaryKey>, PgDefault>;
  primaryKey(type: TNumber, options?: TNumberOptions, identity?: PgIdentityOptions): PgAttr<PgAttr<TNumber, PgPrimaryKey>, PgDefault>;
  primaryKey(type: TBigInt, options?: TNumberOptions, identity?: PgIdentityOptions): PgAttr<PgAttr<TBigInt, PgPrimaryKey>, PgDefault>;
  /**
   * Wrap a schema with "default" attribute.
   * This is used to set a default value for a column in the database.
   */
  readonly default: <T extends TSchema>(type: T, value?: Static<T>) => PgAttr<T, PgDefault>;
  /**
   * Creates a column 'version'.
   *
   * This is used to track the version of a row in the database.
   *
   * You can use it for optimistic concurrency control (OCC) with {@link RepositoryPrimitive#save}.
   *
   * @see {@link RepositoryPrimitive#save}
   * @see {@link PgVersionMismatchError}
   */
  readonly version: () => PgAttr<PgAttr<import("zod").ZodInt, typeof PG_VERSION>, typeof PG_DEFAULT>;
  /**
   * Creates a column Created At. So just a datetime column with a default value of the current timestamp.
   */
  readonly createdAt: () => PgAttr<PgAttr<import("zod").ZodString, typeof PG_CREATED_AT>, typeof PG_DEFAULT>;
  /**
   * Creates a column Updated At. Like createdAt, but it is updated on every update of the row.
   */
  readonly updatedAt: () => PgAttr<PgAttr<import("zod").ZodString, typeof PG_UPDATED_AT>, typeof PG_DEFAULT>;
  /**
   * Creates a column Deleted At for soft delete functionality.
   * This is used to mark rows as deleted without actually removing them from the database.
   * The column is nullable - NULL means not deleted, timestamp means deleted.
   */
  readonly deletedAt: () => PgAttr<import("zod").ZodOptional<import("zod").ZodString>, typeof PG_DELETED_AT>;
  /**
   * Creates an organization column for multi-tenant row scoping.
   *
   * When present, queries are automatically filtered by the current user's organization.
   * On create, the column is auto-stamped with the current user's organization.
   *
   * @param options.nullable - When `false`, the column is NOT NULL in the database and
   *   the ORM rejects inserts that arrive without an organization context.
   *   Defaults to `true` (nullable) — unless `strict` is set, which flips the
   *   default to non-nullable. NULL rows are visible to every tenant (the
   *   historic "global row" semantics) only when the column is nullable AND
   *   not strict.
   * @param options.strict - Fail-closed tenant scoping for security-sensitive
   *   tables. Refuses reads/writes with no resolved tenant (instead of a
   *   fail-open "see/write everything") and drops the `OR org IS NULL` escape
   *   so a scoped tenant never sees global rows. Defaults to `false`.
   */
  readonly organization: (options?: {
    nullable?: boolean;
    strict?: boolean;
  }) => PgAttr<import("zod").ZodOptional<import("zod").ZodString> | import("zod").ZodString, typeof PG_ORGANIZATION>;
  /**
   * Creates a reference to another table or schema. Basically a foreign key.
   */
  readonly ref: <T extends TSchema>(type: T, ref: () => any, actions?: {
    onUpdate?: UpdateDeleteAction$1;
    onDelete?: UpdateDeleteAction$1;
  }) => PgAttr<T, PgRef>;
  /**
   * Creates a page schema for a given object schema.
   * It's used by {@link Repository#paginate} method.
   */
  readonly page: <T extends TObject>(resource: T) => TPage<T>;
}
/**
 * Wrapper of TypeProvider (`t`) for database types.
 *
 * Use `db` for improve TypeBox schema definitions with database-specific attributes.
 *
 * @example
 * ```ts
 * import { t } from "alepha";
 * import { db } from "alepha/orm";
 *
 * const userSchema = t.object({
 *   id: db.primaryKey(t.uuid()),
 *   email: t.email(),
 *   createdAt: db.createdAt(),
 * });
 * ```
 */
declare const db: DatabaseTypeProvider;
//#endregion
//#region ../../src/orm/core/schemas/legacyIdSchema.d.ts
/**
 * @deprecated Use `pg.primaryKey()` instead.
 */
declare const legacyIdSchema: PgAttr<PgAttr<PgAttr<import("zod").ZodInt, typeof PG_PRIMARY_KEY>, typeof PG_SERIAL>, typeof PG_DEFAULT>;
//#endregion
//#region ../../src/orm/core/entities/alephaSequences.d.ts
/**
 * Storage table for the {@link SequenceProvider}.
 *
 * Each row represents one counter, identified by `(name, scope)`:
 * - `name` is the sequence primitive name (defaulted from its property key).
 * - `scope` is an arbitrary string passed by the caller, defaulted to "default"
 *   for the global, unscoped form. Use this column to namespace per-tenant /
 *   per-campaign / per-anything counters off the same primitive.
 * - `value` is the current counter value. Incremented atomically by
 *   `SequenceProvider.advance()` through an `INSERT ... ON CONFLICT DO UPDATE`
 *   on `(name, scope)` — works identically on Postgres, SQLite, and D1.
 */
declare const alephaSequences: EntityPrimitive<import("zod").ZodObject<{
  id: PgAttr<PgAttr<import("zod").ZodString, typeof PG_PRIMARY_KEY>, typeof PG_DEFAULT>;
  createdAt: PgAttr<PgAttr<import("zod").ZodString, typeof PG_CREATED_AT>, typeof PG_DEFAULT>;
  updatedAt: PgAttr<PgAttr<import("zod").ZodString, typeof PG_UPDATED_AT>, typeof PG_DEFAULT>;
  name: import("zod").ZodString;
  scope: import("zod").ZodString;
  value: import("zod").ZodInt;
}, import("zod/v4/core").$strip>>;
type AlephaSequence = Static<typeof alephaSequences.schema>;
//#endregion
//#region ../../src/orm/core/errors/DbConflictError.d.ts
declare class DbConflictError extends DbError {
  readonly name = "DbConflictError";
  readonly status = 409;
}
//#endregion
//#region ../../src/orm/core/errors/DbMigrationError.d.ts
declare class DbMigrationError extends DbError {
  readonly name = "DbMigrationError";
  constructor(cause?: unknown);
}
//#endregion
//#region ../../src/orm/core/errors/DbVersionMismatchError.d.ts
/**
 * Error thrown when there is a version mismatch.
 * It's thrown by {@link Repository#save} when the updated entity version does not match the one in the database.
 * This is used for optimistic concurrency control.
 */
declare class DbVersionMismatchError extends DbError {
  readonly name = "DbVersionMismatchError";
  constructor(table: string, id: any);
}
//#endregion
//#region ../../src/orm/core/providers/DbCacheProvider.d.ts
/**
 * Database query cache using a simple in-memory Map.
 *
 * Uses `{tableName}:{cacheKey}` as the storage key.
 * Provides per-table invalidation for write-through cache busting.
 *
 * This is intentionally self-contained (no external cache dependencies)
 * so the ORM module does not force `AlephaCache` on all consumers.
 */
declare class DbCacheProvider {
  protected readonly dateTime: DateTimeProvider;
  protected readonly store: Map<string, {
    value: unknown;
    expiresAt?: number;
  }>;
  protected storeKey(tableName: string, cacheKey: string): string;
  /**
   * Get a cached query result.
   */
  get<T>(tableName: string, cacheKey: string): Promise<T | undefined>;
  /**
   * Store a query result in the cache.
   */
  set<T>(tableName: string, cacheKey: string, value: T, ttl?: number): Promise<void>;
  /**
   * Invalidate all cached queries for a table.
   */
  invalidateTable(tableName: string): Promise<void>;
}
//#endregion
//#region ../../src/orm/core/services/ModelBuilder.d.ts
/**
 * Database-specific table configuration functions
 */
interface TableConfigBuilders<TConfig> {
  index: (name: string) => {
    on: (...columns: any[]) => TConfig;
  };
  uniqueIndex: (name: string) => {
    on: (...columns: any[]) => TConfig;
  };
  unique: (name: string) => {
    on: (...columns: any[]) => TConfig;
  };
  check: (name: string, sql: SQL) => TConfig;
  foreignKey: (config: {
    name: string;
    columns: any[];
    foreignColumns: any[];
  }) => TConfig;
}
/**
 * Abstract base class for transforming Alepha Primitives (Entity, Sequence, etc...)
 * into drizzle models (tables, enums, sequences, etc...).
 */
declare abstract class ModelBuilder {
  /**
   * Build a table from an entity primitive.
   */
  abstract buildTable(entity: EntityPrimitive, options: {
    tables: Map<string, unknown>;
    enums: Map<string, unknown>;
    schemas: Map<string, unknown>;
    schema: string;
  }): void;
  /**
   * Build a sequence from a sequence primitive.
   */
  abstract buildSequence(sequence: SequencePrimitive, options: {
    sequences: Map<string, unknown>;
    schema: string;
  }): void;
  /**
   * Convert camelCase to snake_case for column names.
   */
  protected toColumnName(str: string): string;
  /**
   * Build the table configuration function for any database.
   * This includes indexes, foreign keys, constraints, and custom config.
   *
   * @param entity - The entity primitive
   * @param builders - Database-specific builder functions
   * @param tableResolver - Function to resolve entity references to table columns
   * @param customConfigHandler - Optional handler for custom config
   */
  protected buildTableConfig<TConfig, TSelf>(entity: EntityPrimitive, builders: TableConfigBuilders<TConfig>, tableResolver?: (entityName: string) => any, customConfigHandler?: (config: any, self: TSelf) => TConfig[]): ((self: TSelf) => TConfig[]) | undefined;
}
//#endregion
//#region ../../src/orm/core/providers/DrizzleKitProvider.d.ts
declare class DrizzleKitProvider {
  protected readonly log: import("alepha/logger").Logger;
  protected readonly dateTime: DateTimeProvider;
  protected readonly alepha: Alepha;
  /**
   * Push-based synchronization using Drizzle Kit's introspection API.
   *
   * Reads the actual database state, diffs against current entity definitions,
   * and applies changes. No stored snapshots — no drift, no corruption.
   *
   * - SQLite: uses `pushSQLiteSchema` (requires sync driver — node:sqlite shim or bun-sqlite)
   * - PostgreSQL: uses `pushSchema` with schema filters
   *
   * Does nothing in production mode — use file-based migrations instead.
   */
  synchronize(provider: DatabaseProvider): Promise<void>;
  /**
   * Generate SQL migration statements by diffing two schema states.
   *
   * Used by tests (schema validation) and CLI (`alepha db migrations generate`).
   * Not part of the push sync flow.
   *
   * When `withoutSchema` is true, models are rebuilt without schema qualifiers
   * so the generated SQL is portable across different PostgreSQL schemas.
   */
  generateMigration(provider: DatabaseProvider, prevSnapshot?: any, options?: {
    withoutSchema?: boolean;
  }): Promise<{
    statements: string[];
    models: Record<string, unknown>;
    snapshot?: any;
  }>;
  /**
   * Load all tables, enums, sequences, etc. from the provider's repositories.
   */
  getModels(provider: DatabaseProvider): Record<string, unknown>;
  /**
   * Build schema-free models for migration generation.
   *
   * Rebuilds all entities with `schema = "public"` so Drizzle produces
   * SQL without schema qualifiers (e.g. `CREATE TABLE "users"` instead
   * of `CREATE TABLE "myschema"."users"`).
   *
   * The actual schema is applied at migration execution time via `search_path`.
   */
  getModelsWithoutSchema(provider: DatabaseProvider): Record<string, unknown>;
  /**
   * Preview schema push without executing any statements.
   *
   * Returns the SQL statements that would be executed, warnings, and
   * whether data loss would occur. Does NOT execute any SQL.
   */
  dryRunPush(provider: DatabaseProvider): Promise<{
    statements: string[];
    warnings: string[];
    hasDataLoss: boolean;
  }>;
  protected pushSqlite(kit: typeof DrizzleKit, models: Record<string, unknown>, provider: DatabaseProvider): Promise<void>;
  /**
   * Push schema changes to PostgreSQL using Drizzle Kit's pushSchema with schema filters.
   */
  protected pushPostgres(kit: typeof DrizzleKit, models: Record<string, unknown>, provider: DatabaseProvider): Promise<void>;
  /**
   * Execute a list of SQL statements against the provider.
   */
  protected executeStatements(statements: string[], provider: DatabaseProvider): Promise<void>;
  /**
   * Execute SQL statements, ignoring "already exists" errors.
   *
   * Used by the fallback migration path where push may have partially
   * applied changes before erroring, leaving some objects already created.
   */
  protected executeStatementsLenient(statements: string[], provider: DatabaseProvider): Promise<void>;
  protected createSchemaIfNotExists(provider: DatabaseProvider, schemaName: string): Promise<void>;
  /**
   * Wrap a Drizzle PgDatabase instance for compatibility with Drizzle Kit.
   *
   * Drizzle Kit's pushSchema expects execute() to return { rows: T[] }
   * (node-postgres/pg format), but postgres.js returns a Result that
   * extends Array directly — no .rows property.
   */
  protected wrapDbForDrizzleKit(db: any): any;
  /**
   * Try to load the official Drizzle Kit API.
   */
  importDrizzleKit(): typeof DrizzleKit;
}
//#endregion
//#region ../../src/orm/core/providers/drivers/DatabaseProvider.d.ts
type SQLLike = SQLWrapper | string;
declare abstract class DatabaseProvider {
  protected readonly alepha: Alepha;
  protected readonly dateTime: DateTimeProvider;
  protected readonly log: import("alepha/logger").Logger;
  protected abstract readonly builder: ModelBuilder;
  protected readonly kit: DrizzleKitProvider;
  abstract readonly db: PgDatabase<any>;
  abstract readonly dialect: "postgresql" | "sqlite";
  abstract readonly url: string;
  readonly enums: Map<string, unknown>;
  readonly tables: Map<string, unknown>;
  readonly sequences: Map<string, unknown>;
  readonly schemas: Map<string, unknown>;
  protected readonly entityPrimitives: EntityPrimitive[];
  protected readonly sequencePrimitives: SequencePrimitive[];
  get name(): string;
  get driver(): string;
  /**
   * Whether this driver supports SQL-level transactions (BEGIN/COMMIT/ROLLBACK).
   *
   * Drivers that do not (e.g. PGlite, Cloudflare D1) should override to `false`.
   */
  get supportsTransactions(): boolean;
  /**
   * Raw database connection handle (e.g. DatabaseSync, bun:sqlite Database).
   * Override in providers that expose native connections for introspection.
   */
  get nativeConnection(): unknown;
  get schema(): string;
  /**
   * Migration tracking table name, scoped by schema.
   *
   * Returns `migrations_{schema}` so that multiple schemas sharing the same
   * database each get their own migration history (e.g. `migrations_lore`,
   * `migrations_public`).
   */
  get migrationsTable(): string;
  /**
   * Log a database query with structured metadata for devtools inspection.
   */
  protected logQuery(sql: string, params: unknown[], duration: number, rowCount: number, error?: string): void;
  protected parseOperation(sql: string): string;
  table<T extends TObject>(entity: EntityPrimitive<T>): PgTableWithColumns<SchemaToTableConfig<T>>;
  registerEntity(entity: EntityPrimitive): void;
  registerSequence(sequence: SequencePrimitive): void;
  /**
   * Rebuild all models into fresh maps using a different schema.
   *
   * When called with `"public"`, produces schema-free models suitable for
   * migration generation (no schema qualifiers in the SQL output).
   */
  rebuildModels(targetSchema: string): {
    tables: Map<string, unknown>;
    enums: Map<string, unknown>;
    sequences: Map<string, unknown>;
    schemas: Map<string, unknown>;
  };
  /**
   * Run a function inside a database transaction with implicit tx propagation.
   *
   * The transaction object is stored in `alepha.store` so that all Repository
   * operations within `fn` automatically participate in the transaction without
   * explicit `{ tx }` drilling.
   *
   * Nesting is safe — if already inside a `transactional()` block, the inner
   * call reuses the outer transaction (no nested PG transactions / savepoints).
   */
  transactional<R>(fn: () => Promise<R>, config?: PgTransactionConfig): Promise<R>;
  abstract execute(statement: SQLLike): Promise<Record<string, unknown>[]>;
  run<T extends TObject>(statement: SQLLike, schema: T): Promise<Array<Static<T>>>;
  /**
   * Get migrations folder path - can be overridden
   */
  protected getMigrationsFolder(): string;
  /**
   * Migration orchestration.
   *
   * - Production: file-based migrations from the migrations folder
   * - Dev / Test: push-based sync (introspects actual DB, no snapshots)
   * - Serverless: skipped (migrations should be applied during deployment)
   */
  migrate(): Promise<void>;
  /**
   * Provider-specific migration execution
   * MUST be implemented by each provider
   */
  protected abstract executeMigrations(migrationsFolder: string): Promise<void>;
  /**
   * For testing purposes, generate a unique schema name.
   *
   * Format: `test_alepha_{epoch_seconds}_{random8}`
   * Example: `test_alepha_1739871618_k3m9x2p1`
   */
  protected generateTestSchemaName(): string;
}
//#endregion
//#region ../../src/orm/core/services/QueryManager.d.ts
declare class QueryManager {
  protected readonly alepha: Alepha;
  /**
   * Convert a query object to a SQL query.
   */
  toSQL(query: PgQueryWhereOrSQL<TObject>, options: {
    schema: TObject;
    col: (key: string) => PgColumn;
    joins?: PgJoin[];
    dialect: "postgresql" | "sqlite";
  }): SQL | undefined;
  /**
   * Check if an object has any filter operator properties.
   */
  protected hasFilterOperatorProperties(obj: any): boolean;
  /**
   * Map a filter operator to a SQL query.
   */
  mapOperatorToSql(operator: FilterOperators<any> | any, column: PgColumn, columnSchema?: TObject, columnName?: string, dialect?: "postgresql" | "sqlite"): SQL | undefined;
  /**
   * Parse pagination sort string to orderBy format.
   * Format: "firstName,-lastName" -> [{ column: "firstName", direction: "asc" }, { column: "lastName", direction: "desc" }]
   * - Columns separated by comma
   * - Prefix with '-' for DESC direction
   *
   * @param sort Pagination sort string
   * @returns OrderBy array or single object
   */
  parsePaginationSort(sort: string): Array<{
    column: string;
    direction: "asc" | "desc";
  }> | {
    column: string;
    direction: "asc" | "desc";
  };
  /**
   * Normalize orderBy parameter to array format.
   * Supports 3 modes:
   * 1. String: "name" -> [{ column: "name", direction: "asc" }]
   * 2. Object: { column: "name", direction: "desc" } -> [{ column: "name", direction: "desc" }]
   * 3. Array: [{ column: "name" }, { column: "age", direction: "desc" }] -> normalized array
   *
   * @param orderBy The orderBy parameter
   * @returns Normalized array of order by clauses
   */
  normalizeOrderBy(orderBy: any): Array<{
    column: string;
    direction: "asc" | "desc";
  }>;
  /**
   * Create a pagination object.
   *
   * @deprecated Use `createPagination` from alepha instead.
   * This method now delegates to the framework-level helper.
   *
   * @param entities The entities to paginate.
   * @param limit The limit of the pagination.
   * @param offset The offset of the pagination.
   * @param sort Optional sort metadata to include in response.
   */
  createPagination<T>(entities: T[], limit?: number, offset?: number, sort?: Array<{
    column: string;
    direction: "asc" | "desc";
  }>): import("alepha").Page<T>;
}
interface PgJoin {
  table: string;
  schema: TObject;
  key: string;
  col: (key: string) => PgColumn;
  parent?: string;
}
//#endregion
//#region ../../src/orm/core/services/PgRelationManager.d.ts
declare class PgRelationManager {
  protected readonly schemaValidator: SchemaValidator;
  /**
   * Recursively build joins for the query builder based on the relations map
   */
  buildJoins(provider: DatabaseProvider, builder: PgSelectBase<any, any, any>, joins: Array<PgJoin>, withRelations: PgRelationMap<TObject>, table: PgTableWithColumns<any>, parentKey?: string): void;
  /**
   * Map a row with its joined relations based on the joins definition
   */
  mapRowWithJoins(record: Record<string, unknown>, row: Record<string, unknown>, schema: TObject, joins: PgJoin[], parentKey?: string): Record<string, unknown>;
  /**
   * Check if all values in an object are null (indicates a left join with no match)
   */
  protected isAllNull(obj: unknown): boolean;
  /**
   * Build a schema that includes all join properties recursively
   */
  buildSchemaWithJoins(baseSchema: TObject, joins: PgJoin[], parentPath?: string): TObject;
}
//#endregion
//#region ../../src/orm/core/services/Repository.d.ts
declare abstract class Repository<T extends TObject> {
  readonly entity: EntityPrimitive<T>;
  readonly provider: DatabaseProvider;
  protected readonly log: import("alepha/logger").Logger;
  protected readonly relationManager: PgRelationManager;
  protected readonly queryManager: QueryManager;
  protected readonly dateTimeProvider: DateTimeProvider;
  protected readonly dbCache: DbCacheProvider;
  protected readonly alepha: Alepha;
  static of<T extends TObject>(entity: EntityPrimitive<T>, provider?: typeof DatabaseProvider): new () => Repository<T>;
  constructor(entity: EntityPrimitive<T>, provider?: typeof DatabaseProvider);
  /**
   * Represents the primary key of the table.
   * - Key is the name of the primary key column.
   * - Type is the type (TypeBox) of the primary key column.
   *
   * ID is mandatory. If the table does not have a primary key, it will throw an error.
   */
  get id(): {
    type: TSchema;
    key: keyof T["properties"];
    col: PgColumn;
  };
  /**
   * Get Drizzle table object.
   */
  get table(): PgTableWithColumns<SchemaToTableConfig<T>>;
  /**
   * Get SQL table name. (from Drizzle table object)
   */
  get tableName(): string;
  /**
   * Getter for the database connection from the database provider.
   *
   * Automatically picks up a transaction from `alepha.store` if one was set
   * by `DatabaseProvider.transactional()`, so that all repository operations
   * inside a `transactional()` block participate in the same transaction.
   */
  protected get db(): PgDatabase<any>;
  /**
   * Execute a SQL query.
   *
   * This method allows executing raw SQL queries against the database.
   * This is by far the easiest way to run custom queries that are not covered by the repository's built-in methods!
   *
   * You must use the `sql` tagged template function from Drizzle ORM to create the query. https://orm.drizzle.team/docs/sql
   *
   * @example
   * ```ts
   * class App {
   *   repository = $repository({ ... });
   *   async getAdults() {
   *     const users = repository.table; // Drizzle table object
   *     await repository.query(sql`SELECT * FROM ${users} WHERE ${users.age} > ${18}`);
   *     // or better
   *     await repository.query((users) => sql`SELECT * FROM ${users} WHERE ${users.age} > ${18}`);
   *   }
   * }
   * ```
   */
  query<R extends TObject = T>(query: SQLLike | ((table: PgTableWithColumns<SchemaToTableConfig<T>>, db: PgDatabase<any>) => SQLLike), schema?: R): Promise<Static<R>[]>;
  protected columnNameMap?: Map<string, string>;
  /**
   * Map raw database fields to entity fields. (handles column name differences)
   */
  protected mapRawFieldsToEntity(row: Record<string, unknown>): any;
  /**
   * Get a Drizzle column from the table by his name.
   */
  protected col(name: keyof StaticEncode<T>): PgColumn;
  /**
   * Run a transaction.
   */
  transaction<T>(transaction: (tx: PgTransaction<any, Record<string, any>, any>) => Promise<T>, config?: PgTransactionConfig): Promise<T>;
  /**
   * Start a SELECT query on the table.
   */
  protected rawSelect(opts?: StatementOptions): import("drizzle-orm/pg-core").PgSelectBase<string, Record<string, PgColumn<import("drizzle-orm").ColumnBaseConfig<import("drizzle-orm").ColumnDataType, string>, {}, {}>>, "single", Record<string, "not-null">, false, never, {
    [x: string]: unknown;
  }[], {
    [x: string]: PgColumn<import("drizzle-orm").ColumnBaseConfig<import("drizzle-orm").ColumnDataType, string>, {}, {}>;
  }>;
  /**
   * Start a SELECT DISTINCT query on the table.
   */
  protected rawSelectDistinct(opts?: StatementOptions, columns?: (keyof Static<T>)[]): import("drizzle-orm/pg-core").PgSelectBase<string, Record<string, any>, "partial", Record<string, "not-null">, false, never, {
    [x: string]: any;
  }[], {
    [x: string]: any;
  }>;
  /**
   * Start an INSERT query on the table.
   */
  protected rawInsert(opts?: StatementOptions): import("drizzle-orm/pg-core").PgInsertBuilder<PgTableWithColumns<SchemaToTableConfig<T>>, any, false>;
  /**
   * Start an UPDATE query on the table.
   */
  protected rawUpdate(opts?: StatementOptions): import("drizzle-orm/pg-core").PgUpdateBuilder<PgTableWithColumns<SchemaToTableConfig<T>>, any>;
  /**
   * Start a DELETE query on the table.
   */
  protected rawDelete(opts?: StatementOptions): import("drizzle-orm/pg-core").PgDeleteBase<PgTableWithColumns<SchemaToTableConfig<T>>, any, undefined, undefined, false, never>;
  /**
   * Create a Drizzle `select` query based on a JSON query object.
   *
   * > This method is the base for `find`, `findOne`, `findById`, and `paginate`.
   */
  findMany<R extends PgRelationMap<T>>(query?: PgQueryRelations<T, R>, opts?: StatementOptions): Promise<PgStatic<T, R>[]>;
  /**
   * Find a single entity. Returns `undefined` if not found.
   */
  findOne<R extends PgRelationMap<T>>(query: Pick<PgQueryRelations<T, R>, "with" | "where">, opts?: StatementOptions): Promise<PgStatic<T, R> | undefined>;
  /**
   * Find a single entity. Throws `DbEntityNotFoundError` if not found.
   */
  getOne<R extends PgRelationMap<T>>(query: Pick<PgQueryRelations<T, R>, "with" | "where">, opts?: StatementOptions): Promise<PgStatic<T, R>>;
  /**
   * Find entities with pagination.
   *
   * It uses the same parameters as `find()`, but adds pagination metadata to the response.
   *
   * > Pagination CAN also do a count query to get the total number of elements.
   */
  paginate<R extends PgRelationMap<T>>(pagination?: PageQuery$1, query?: Omit<PgQueryRelations<T, R>, "where"> & {
    where?: PgQueryWhere<T>;
  }, opts?: StatementOptions & {
    count?: boolean;
  }): Promise<Page$1<PgStatic<T, R>>>;
  /**
   * Find an entity by ID. Returns `undefined` if not found.
   *
   * Pass `with` to eager-load relations on the result — same `with` map
   * shape as `findOne` / `paginate`. Without `with`, returns the plain
   * row.
   *
   * @example
   * ```ts
   * const session = await sessions.findById(id, {
   *   with: { user: { join: users, on: ["userId", users.cols.id] as const } },
   * });
   * session?.user?.email;
   * ```
   */
  findById<R extends PgRelationMap<T>>(id: string | number, opts?: StatementOptions & {
    with?: R;
  }): Promise<PgStatic<T, R> | undefined>;
  /**
   * Find an entity by ID. Throws `DbEntityNotFoundError` if not found.
   *
   * Pass `with` to eager-load relations — see {@link findById}.
   */
  getById<R extends PgRelationMap<T>>(id: string | number, opts?: StatementOptions & {
    with?: R;
  }): Promise<PgStatic<T, R>>;
  /**
   * Helper to create a type-safe query object.
   */
  createQuery(): PgQuery<T>;
  /**
   * Helper to create a type-safe where clause.
   */
  createQueryWhere(): PgQueryWhere<T>;
  /**
   * Create an entity.
   *
   * @param data The entity to create.
   * @param opts The options for creating the entity.
   * @returns The ID of the created entity.
   */
  create(data: Static<TObjectInsert<T>>, opts?: StatementOptions): Promise<Static<T>>;
  /**
   * Create many entities.
   *
   * Inserts are batched in chunks of 1000 to avoid hitting database limits.
   *
   * @param values The entities to create.
   * @param opts The statement options.
   * @returns The created entities.
   */
  createMany(values: Array<Static<TObjectInsert<T>>>, opts?: StatementOptions & {
    batchSize?: number;
  }): Promise<Static<T>[]>;
  /**
   * Insert or update an entity.
   *
   * If a row with the same conflict target already exists, it updates that row.
   * Otherwise, it inserts a new row.
   *
   * @param data The entity data to insert.
   * @param opts.target The column(s) to detect conflicts on. Defaults to the primary key.
   * @param opts.set The fields to update on conflict. Defaults to the insert data (minus conflict target columns).
   * @returns The created or updated entity.
   *
   * @example
   * ```ts
   * // Simple upsert on primary key
   * await repo.upsert({ id: "abc", name: "Alice", role: "admin" });
   *
   * // Upsert on a unique column
   * await repo.upsert(
   *   { email: "alice@example.com", name: "Alice" },
   *   { target: ["email"] },
   * );
   *
   * // Upsert with custom update fields
   * await repo.upsert(
   *   { id: "abc", name: "Alice", role: "admin" },
   *   { set: { role: "admin" } },
   * );
   * ```
   */
  upsert(data: Static<TObjectInsert<T>>, opts?: StatementOptions & {
    target?: Array<keyof Static<T>>;
    set?: WithSQL<Static<TObjectUpdate<T>>>;
  }): Promise<Static<T>>;
  /**
   * Find an entity and update it.
   */
  updateOne(where: PgQueryWhereOrSQL<T>, data: WithSQL<Static<TObjectUpdate<T>>>, opts?: StatementOptions): Promise<Static<T>>;
  /**
   * Save a given entity.
   *
   * @example
   * ```ts
   * const entity = await repository.findById(1);
   * entity.name = "New Name"; // update a field
   * delete entity.description; // delete a field
   * await repository.save(entity);
   * ```
   *
   * Difference with `updateById/updateOne`:
   *
   * - requires the entity to be fetched first (whole object is expected)
   * - check pg.version() if present -> optimistic locking
   * - validate entity against schema
   * - undefined values will be set to null, not ignored!
   *
   * @see {@link DbVersionMismatchError}
   */
  save(entity: Static<T>, opts?: StatementOptions): Promise<void>;
  /**
   * Find an entity by ID and update it.
   */
  updateById(id: string | number, data: WithSQL<Static<TObjectUpdate<T>>>, opts?: StatementOptions): Promise<Static<T>>;
  /**
   * Find many entities and update all of them.
   */
  updateMany(where: PgQueryWhereOrSQL<T>, data: WithSQL<Static<TObjectUpdate<T>>>, opts?: StatementOptions): Promise<Array<number | string>>;
  /**
   * Find many and delete all of them.
   * @returns Array of deleted entity IDs
   */
  deleteMany(where?: PgQueryWhereOrSQL<T>, opts?: StatementOptions): Promise<Array<number | string>>;
  /**
   * Delete all entities.
   * @returns Array of deleted entity IDs
   */
  clear(opts?: StatementOptions): Promise<Array<number | string>>;
  /**
   * Delete the given entity.
   *
   * You must fetch the entity first in order to delete it.
   * @returns Array containing the deleted entity ID
   */
  destroy(entity: Static<T>, opts?: StatementOptions): Promise<Array<number | string>>;
  /**
   * Find an entity and delete it.
   * @returns Array of deleted entity IDs (should contain at most one ID)
   */
  deleteOne(where?: PgQueryWhereOrSQL<T>, opts?: StatementOptions): Promise<Array<number | string>>;
  /**
   * Find an entity by ID and delete it.
   * @returns Array containing the deleted entity ID
   * @throws DbEntityNotFoundError if the entity is not found
   */
  deleteById(id: string | number, opts?: StatementOptions): Promise<Array<number | string>>;
  /**
   * Count entities.
   */
  count(where?: PgQueryWhereOrSQL<T>, opts?: StatementOptions): Promise<number>;
  /**
   * Execute an aggregate query with type-safe select, groupBy, and having.
   *
   * @example
   * ```ts
   * const result = await repo.aggregate({
   *   select: { category: true, amount: { sum: true, avg: true } },
   *   groupBy: ["category"],
   *   having: { amount: { sum: { gt: 100 } } },
   *   orderBy: { column: "amount.sum", direction: "desc" },
   * });
   * // result: Array<{ category: string; amount: { sum: number; avg: number } }>
   * ```
   */
  aggregate<S extends AggregateSelect<T>>(query: AggregateQuery<T, S>, opts?: StatementOptions): Promise<AggregateResult<T, S>[]>;
  protected errorPatterns: {
    conflict: string[];
    foreignKey: string[];
    notNull: string[];
    deadlock: string[];
    tableNotFound: string[];
    columnNotFound: string[];
  };
  protected handleError(error: unknown, message: string): DbError;
  protected withDeletedAt(where: PgQueryWhereOrSQL<T>, opts?: {
    force?: boolean;
  }): PgQueryWhereOrSQL<T>;
  protected deletedAt(): PgAttrField | undefined;
  protected withOrganization(where: PgQueryWhereOrSQL<T>): PgQueryWhereOrSQL<T>;
  protected stampOrganization(data: any): void;
  /**
   * Resolve the value used for `PG_ORGANIZATION` scoping.
   *
   * Priority:
   * 1. Request-bound tenant (`currentTenantAtom`) — set by an app-level
   *    middleware from the request `Host`. Lets cross-tenant users (admins,
   *    agency operators) be scoped to the tenant they are acting in rather
   *    than the one they belong to.
   * 2. Authenticated user's `organization` — the legacy single-tenant case.
   */
  protected resolveOrganizationValue(): string | undefined;
  protected organizationField(): PgAttrField | undefined;
  /**
   * Convert something to valid Pg Insert Value.
   */
  protected cast(data: any, insert: boolean): PgInsertValue<PgTableWithColumns<SchemaToTableConfig<T>>>;
  /**
   * Transform a row from the database into a clean entity.
   */
  protected clean<T extends TObject>(row: Record<string, unknown>, schema: T): Static<T>;
  /**
   * Clean a row with joins recursively
   */
  protected cleanWithJoins<T extends TObject>(row: Record<string, unknown>, schema: T, joins: PgJoin[], parentPath?: string): Static<T>;
  /**
   * Build a cache key from method name and query parameters.
   */
  protected buildCacheKey(method: string, query: any): string;
  /**
   * Convert a where clause to SQL.
   */
  protected toSQL(where: PgQueryWhereOrSQL<T>, joins?: PgJoin[]): SQL | undefined;
  /**
   * Get the where clause for an ID.
   *
   * @param id The ID to get the where clause for.
   * @returns The where clause for the ID.
   */
  protected getWhereId(id: string | number): PgQueryWhere<T>;
  /**
   * Find a primary key in the schema.
   */
  protected getPrimaryKey(schema: TObject): {
    key: string;
    col: PgColumn<import("drizzle-orm").ColumnBaseConfig<import("drizzle-orm").ColumnDataType, string>, {}, {}>;
    type: import("alepha").ZType;
  };
}
/**
 * The options for a statement.
 */
interface StatementOptions {
  /**
   * Transaction to use.
   *
   * - `undefined` — auto-detect from `alepha.store` (implicit transactional context)
   * - `PgTransaction` — use this specific transaction (explicit)
   * - `null` — force no transaction, bypass implicit context
   */
  tx?: PgTransaction<any, Record<string, any>> | null;
  /**
   * Lock strength.
   */
  for?: LockStrength | {
    config: LockConfig;
    strength: LockStrength;
  };
  /**
   * If true, ignore soft delete.
   */
  force?: boolean;
  /**
   * Force the current time.
   */
  now?: DateTime | string;
  /**
   * Cache configuration for query results.
   *
   * When set, results are stored in an in-memory cache keyed by query parameters.
   * Any write to this table automatically invalidates all cached queries.
   *
   * @example
   * ```ts
   * await repo.findMany(query, { cache: { ttl: 60_000 } });
   * ```
   */
  cache?: {
    /**
     * Time-to-live in milliseconds.
     */
    ttl?: number;
    /**
     * Custom cache key. If not provided, a key is derived from the query.
     */
    key?: string;
  };
}
type WithSQL<T> = { [P in keyof T]?: T[P] | SQL; };
//#endregion
//#region ../../src/orm/core/primitives/$repository.d.ts
/**
 * Get the repository for the given entity.
 */
declare const $repository: <T extends TObject>(entity: EntityPrimitive<T>) => Repository<T>;
//#endregion
//#region ../../src/orm/core/primitives/$seed.d.ts
interface SeedOptions {
  /**
   * Seed handler, executed inside a database transaction.
   *
   * If the handler throws, the transaction is rolled back automatically.
   */
  handler: (ctx: {
    alepha: Alepha;
    db: DatabaseProvider;
  }) => any;
}
/**
 * Activate seed mode: a convenience wrapper around `$mode` that runs the handler
 * inside a database transaction.
 *
 * When `SEED=true` (or `MODE=SEED`) is set, the owning class becomes `alepha.target`,
 * the graph is pruned, and the handler runs inside `db.transactional()`.
 * After completion (or error), the app stops automatically.
 *
 * Returns `true` if seed mode is active, `false` otherwise.
 *
 * @example
 * ```ts
 * import { $seed } from "alepha/orm";
 * import { $repository } from "alepha/orm";
 *
 * class AppSeed {
 *   users = $repository(userEntity);
 *
 *   seed = $seed({
 *     handler: async () => {
 *       await this.users.create({ name: "John Doe" });
 *     },
 *   });
 * }
 * ```
 *
 * ```bash
 * SEED=true node app.js
 * ```
 */
declare const $seed: (args: SeedOptions) => boolean;
//#endregion
//#region ../../src/orm/core/primitives/$transactional.d.ts
interface TransactionalOptions {
  /**
   * PostgreSQL transaction configuration (isolation level, access mode, etc.).
   */
  config?: PgTransactionConfig;
}
/**
 * Middleware that wraps handler execution in a database transaction.
 *
 * All Repository operations inside the handler automatically participate in
 * the transaction — no explicit `{ tx }` drilling required.
 *
 * Nesting is safe: if the handler is already inside a `transactional()` block,
 * the outer transaction is reused.
 *
 * ```typescript
 * class OrderService {
 *   createOrder = $action({
 *     use: [$transactional()],
 *     handler: async ({ body }) => {
 *       await this.orders.create(body);      // auto-uses tx
 *       await this.audit.create({ ... });     // auto-uses tx
 *       // throw → auto rollback, return → auto commit
 *     },
 *   });
 * }
 * ```
 */
declare const $transactional: (options?: TransactionalOptions) => Middleware;
//#endregion
//#region ../../src/orm/core/providers/drivers/CloudflareD1Provider.d.ts
/**
 * D1Database interface matching Cloudflare's D1 API.
 */
interface D1Database {
  prepare(query: string): D1PreparedStatement;
  batch<T = unknown>(statements: D1PreparedStatement[]): Promise<T[]>;
  exec(query: string): Promise<D1ExecResult>;
  dump(): Promise<ArrayBuffer>;
}
interface D1PreparedStatement {
  bind(...values: unknown[]): D1PreparedStatement;
  first<T = unknown>(colName?: string): Promise<T | null>;
  run(): Promise<D1Result>;
  all<T = unknown>(): Promise<D1Result<T>>;
  raw<T = unknown>(): Promise<T[]>;
}
interface D1Result<T = unknown> {
  results: T[];
  success: boolean;
  meta: {
    duration: number;
    changes: number;
    last_row_id: number;
    served_by: string;
    internal_stats: unknown;
  };
}
interface D1ExecResult {
  count: number;
  duration: number;
}
/**
 * Cloudflare D1 SQLite provider using Drizzle ORM.
 */
declare class CloudflareD1Provider extends DatabaseProvider {
  protected readonly builder: SqliteModelBuilder;
  protected readonly env: {
    DATABASE_URL: string;
  };
  protected d1?: D1Database;
  protected drizzleDb?: DrizzleD1Database;
  get name(): string;
  get driver(): string;
  readonly dialect = "sqlite";
  get url(): string;
  get db(): PgDatabase<any>;
  execute(query: SQLLike): Promise<Array<Record<string, unknown>>>;
  /**
   * D1 does not support SQL-level transactions (BEGIN/COMMIT/ROLLBACK).
   * It rejects these statements and requires the JS `batch()` API for atomic
   * multi-statement operations instead.
   *
   * @see https://developers.cloudflare.com/d1/worker-api/d1-database/#batch-statements
   * @see https://github.com/drizzle-team/drizzle-orm/issues/2463
   */
  get supportsTransactions(): boolean;
  protected readonly onStart: import("alepha").HookPrimitive<"start">;
  protected executeMigrations(migrationsFolder: string): Promise<void>;
  /**
   * D1 doesn't support push-based schema sync.
   * Always use file-based migrations regardless of environment.
   */
  migrate(): Promise<void>;
}
//#endregion
//#region ../../src/orm/core/providers/RepositoryProvider.d.ts
declare class RepositoryProvider {
  protected readonly alepha: Alepha;
  protected readonly registry: Map<EntityPrimitive<any>, Service<Repository<any>>>;
  getRepositories(provider?: DatabaseProvider): Repository<TObject>[];
  getRepository<T extends TObject>(entity: EntityPrimitive<T>): Repository<T>;
  createClassRepository<T extends TObject>(entity: EntityPrimitive<T>): Service<Repository<T>>;
}
//#endregion
//#region ../../src/orm/core/schemas/databaseEnvSchema.d.ts
/**
 * Base database environment schema.
 *
 * Defines the `DATABASE_URL` connection string used by all ORM providers
 * to determine the database driver and connection target.
 *
 * Supported URL formats:
 * - `sqlite://:memory:` or `sqlite://./path/to/db` — SQLite (Node.js or Bun)
 * - `postgres://user:password@host:port/database` — PostgreSQL (Node.js or Bun)
 * - `pglite://:memory:` or `pglite://./path` — PGlite (embedded Postgres)
 * - `d1://BINDING_NAME` — Cloudflare D1
 * - `hyperdrive://BINDING_NAME` — Cloudflare Hyperdrive
 */
declare const databaseEnvSchema: import("zod").ZodObject<{
  DATABASE_URL: import("zod").ZodOptional<import("zod").ZodString>;
  DATABASE_SYNC: import("zod").ZodOptional<import("zod").ZodBoolean>;
}, import("zod/v4/core").$strip>;
declare module "alepha" {
  interface Env extends Partial<Static<typeof databaseEnvSchema>> {}
}
//#endregion
//#region ../../src/orm/core/types/schema.d.ts
/**
 * Postgres schema type.
 */
declare const schema: <TDocument extends TSchema>(name: string, document: TDocument) => import("drizzle-orm").$Type<import("drizzle-orm/pg-core").PgCustomColumnBuilder<{
  name: string;
  dataType: 'custom';
  columnType: 'PgCustomColumn';
  data: Static<TDocument>;
  driverParam: string;
  enumValues: undefined;
}>, Static<TDocument>>;
//#endregion
//#region ../../src/orm/core/providers/SequenceProvider.d.ts
/**
 * Portable, scoped numeric sequence provider — works identically on Postgres,
 * SQLite, and Cloudflare D1.
 *
 * Implementation: a single `alepha_sequences` table holds one row per
 * `(name, scope)` pair. Every call to {@link advance} runs an
 * `INSERT ... ON CONFLICT (name, scope) DO UPDATE SET value = value + step`
 * with `RETURNING value`, which is atomic on every supported driver:
 *
 * - **Postgres**: row-level lock on `ON CONFLICT DO UPDATE`.
 * - **SQLite / D1**: writes are serialized, atomic by construction.
 *
 * The repository pattern is the same one used by `DatabaseCacheProvider.incr()`
 * — see that file for the proof-of-design.
 *
 * Callers never instantiate this directly. They declare a {@link SequencePrimitive}
 * via `$sequence()` and call `.next(scope?)` on the primitive — this provider is
 * the engine behind that call.
 */
declare class SequenceProvider {
  protected readonly repository: Repository<import("zod").ZodObject<{
    id: PgAttr<PgAttr<import("zod").ZodString, typeof PG_PRIMARY_KEY>, typeof PG_DEFAULT>;
    createdAt: PgAttr<PgAttr<import("zod").ZodString, typeof PG_CREATED_AT>, typeof PG_DEFAULT>;
    updatedAt: PgAttr<PgAttr<import("zod").ZodString, typeof PG_UPDATED_AT>, typeof PG_DEFAULT>;
    name: import("zod").ZodString;
    scope: import("zod").ZodString;
    value: import("zod").ZodInt;
  }, import("zod/v4/core").$strip>>;
  protected readonly crypto: CryptoProvider;
  /**
   * Atomically advance the counter for `(name, scope)` and return the new value.
   *
   * If the row doesn't exist yet, it's inserted with `value = start` and that
   * value is returned. Subsequent calls increment by `step`.
   *
   * Scope defaults to "default" — pass any string to namespace per
   * tenant / campaign / parent entity / etc.
   */
  advance(name: string, scope?: string, opts?: {
    startWith?: number;
    incrementBy?: number;
  }): Promise<number>;
  /**
   * Read the current value without advancing it. Returns `null` if the
   * `(name, scope)` pair has never been advanced.
   */
  peek(name: string, scope?: string): Promise<number | null>;
  /**
   * Reset the counter for `(name, scope)` to an explicit value. Creates the row
   * if it doesn't exist.
   *
   * Mostly useful in tests and ops scripts — production code should rarely call
   * this, since it can produce duplicate IDs if anything still holds a previously
   * advanced value.
   */
  reset(name: string, scope: string | undefined, value: number): Promise<void>;
}
//#endregion
//#region ../../src/orm/core/primitives/$sequence.d.ts
/**
 * Declare a portable, scoped numeric sequence.
 *
 * Works identically on Postgres, SQLite, and Cloudflare D1 — backed by the
 * shared `alepha_sequences` table managed by {@link SequenceProvider}.
 *
 * @example
 * ```ts
 * class Quests {
 *   // Sequence name defaults to the property key — here "shortId".
 *   shortId = $sequence();
 *
 *   async create(campaignId: number, data: ...) {
 *     // Global counter — same primitive, one shared "default" scope.
 *     const n = await this.shortId.next();
 *
 *     // Scoped counter — one independent sequence per campaign.
 *     const perCampaign = await this.shortId.next(String(campaignId));
 *   }
 * }
 * ```
 *
 * @see {@link SequenceProvider}
 */
declare const $sequence: {
  (options?: SequencePrimitiveOptions): SequencePrimitive;
  [KIND]: typeof SequencePrimitive;
};
interface SequencePrimitiveOptions {
  /**
   * Sequence name. Defaults to the primitive's property key. Two primitives
   * sharing the same name share the same counter table rows, which is rarely
   * what you want — prefer letting the property key drive the name.
   */
  name?: string;
  /**
   * Starting value used on the very first `.next()` for a `(name, scope)` pair.
   * Defaults to `1`.
   */
  startWith?: number;
  /**
   * Amount added on every call to `.next()`. Defaults to `1`.
   */
  incrementBy?: number;
}
declare class SequencePrimitive extends Primitive<SequencePrimitiveOptions> {
  protected readonly provider: SequenceProvider;
  get name(): string;
  /**
   * Atomically advance the counter and return the new value.
   *
   * Scope defaults to "default". Pass any string to keep an independent counter
   * per tenant / campaign / parent entity / etc.
   *
   * **Transaction semantics:** when called inside a `$transactional` block, the
   * increment participates in that transaction — commit advances the counter,
   * rollback unwinds it. This is intentionally different from PG-native
   * `nextval()` (which leaves gaps on rollback). It means a failed insert that
   * consumed a `shortId` returns the value to the pool instead of burning it.
   */
  next(scope?: string): Promise<number>;
  /**
   * Read the current value without advancing it. Returns `null` if the
   * `(name, scope)` pair has never been advanced.
   */
  current(scope?: string): Promise<number | null>;
  /**
   * Reset the counter for the given scope to an explicit value. Creates the row
   * if it doesn't exist. Mostly useful in tests and ops scripts.
   */
  reset(value: number, scope?: string): Promise<void>;
}
//#endregion
//#region ../../src/orm/core/services/SqliteModelBuilder.d.ts
declare class SqliteModelBuilder extends ModelBuilder {
  buildTable(entity: EntityPrimitive<any>, options: {
    tables: Map<string, unknown>;
    enums: Map<string, unknown>;
    schemas: Map<string, unknown>;
    schema: string;
  }): void;
  buildSequence(sequence: SequencePrimitive, options: {
    sequences: Map<string, unknown>;
    schema: string;
  }): void;
  /**
   * Get SQLite-specific config builder for the table.
   */
  protected getTableConfig(entity: EntityPrimitive, tables: Map<string, unknown>): ((self: BuildColumns<string, any, "sqlite">) => any) | undefined;
  schemaToSqliteColumns: <T extends TObject>(tableName: string, schema: T, enums: Map<string, unknown>, tables: Map<string, unknown>) => SchemaToSqliteBuilder<T>;
  mapFieldToSqliteColumn: (tableName: string, fieldName: string, value: any, enums: Map<string, any>) => pg.SQLiteCustomColumnBuilder<{
    name: string;
    dataType: 'custom';
    columnType: 'SQLiteCustomColumn';
    data: string;
    driverParam: number;
    enumValues: undefined;
  }> | pg.SQLiteCustomColumnBuilder<{
    name: string;
    dataType: 'custom';
    columnType: 'SQLiteCustomColumn';
    data: boolean;
    driverParam: number;
    enumValues: undefined;
  }> | pg.SQLiteIntegerBuilderInitial<string> | pg.SQLiteRealBuilderInitial<string> | pg.SQLiteTextBuilderInitial<string, [string, ...string[]], number | undefined> | import("drizzle-orm").$Type<pg.SQLiteCustomColumnBuilder<{
    name: string;
    dataType: 'custom';
    columnType: 'SQLiteCustomColumn';
    data: any;
    driverParam: string;
    enumValues: undefined;
  }>, any> | import("drizzle-orm").$Type<pg.SQLiteCustomColumnBuilder<{
    name: string;
    dataType: 'custom';
    columnType: 'SQLiteCustomColumn';
    data: unknown[];
    driverParam: string;
    enumValues: undefined;
  }>, unknown[]> | import("drizzle-orm").$Type<pg.SQLiteCustomColumnBuilder<{
    name: string;
    dataType: 'custom';
    columnType: 'SQLiteCustomColumn';
    data: Record<string, unknown>;
    driverParam: string;
    enumValues: undefined;
  }>, Record<string, unknown>> | import("drizzle-orm").$Type<pg.SQLiteCustomColumnBuilder<{
    name: string;
    dataType: 'custom';
    columnType: 'SQLiteCustomColumn';
    data: Record<string | number | symbol, unknown>;
    driverParam: string;
    enumValues: undefined;
  }>, Record<string | number | symbol, unknown>>;
  mapStringToSqliteColumn: (key: string, value: any) => pg.SQLiteCustomColumnBuilder<{
    name: string;
    dataType: 'custom';
    columnType: 'SQLiteCustomColumn';
    data: string;
    driverParam: number;
    enumValues: undefined;
  }> | pg.SQLiteTextBuilderInitial<string, [string, ...string[]], number | undefined> | import("drizzle-orm").$Type<pg.SQLiteCustomColumnBuilder<{
    name: string;
    dataType: 'custom';
    columnType: 'SQLiteCustomColumn';
    data: any;
    driverParam: string;
    enumValues: undefined;
  }>, any>;
  sqliteJson: <TDocument extends TSchema>(name: string, document: TDocument) => import("drizzle-orm").$Type<pg.SQLiteCustomColumnBuilder<{
    name: string;
    dataType: 'custom';
    columnType: 'SQLiteCustomColumn';
    data: Static<TDocument>;
    driverParam: string;
    enumValues: undefined;
  }>, Static<TDocument>>;
  sqliteDateTime: {
    <TConfig extends Record<string, any> & unknown>(fieldConfig: TConfig): pg.SQLiteCustomColumnBuilder<{
      name: "";
      dataType: 'custom';
      columnType: 'SQLiteCustomColumn';
      data: string;
      driverParam: number;
      enumValues: undefined;
    }>;
    <TName extends string>(dbName: TName, fieldConfig: unknown): pg.SQLiteCustomColumnBuilder<{
      name: TName;
      dataType: 'custom';
      columnType: 'SQLiteCustomColumn';
      data: string;
      driverParam: number;
      enumValues: undefined;
    }>;
  };
  sqliteBool: {
    <TConfig extends Record<string, any> & unknown>(fieldConfig: TConfig): pg.SQLiteCustomColumnBuilder<{
      name: "";
      dataType: 'custom';
      columnType: 'SQLiteCustomColumn';
      data: boolean;
      driverParam: number;
      enumValues: undefined;
    }>;
    <TName extends string>(dbName: TName, fieldConfig: unknown): pg.SQLiteCustomColumnBuilder<{
      name: TName;
      dataType: 'custom';
      columnType: 'SQLiteCustomColumn';
      data: boolean;
      driverParam: number;
      enumValues: undefined;
    }>;
  };
  sqliteDate: {
    <TConfig extends Record<string, any> & unknown>(fieldConfig: TConfig): pg.SQLiteCustomColumnBuilder<{
      name: "";
      dataType: 'custom';
      columnType: 'SQLiteCustomColumn';
      data: string;
      driverParam: number;
      enumValues: undefined;
    }>;
    <TName extends string>(dbName: TName, fieldConfig: unknown): pg.SQLiteCustomColumnBuilder<{
      name: TName;
      dataType: 'custom';
      columnType: 'SQLiteCustomColumn';
      data: string;
      driverParam: number;
      enumValues: undefined;
    }>;
  };
}
type SchemaToSqliteBuilder<T extends TObject> = { [key in keyof T["properties"]]: SQLiteColumnBuilderBase; };
//#endregion
//#region ../../src/orm/core/providers/drivers/NodeSqliteProvider.d.ts
/**
 * Configuration options for the Node.js SQLite database provider.
 */
declare const nodeSqliteOptions: import("alepha").Atom<import("zod").ZodObject<{
  path: import("zod").ZodOptional<import("zod").ZodString>;
}, import("zod/v4/core").$strip>, "alepha.postgres.node-sqlite.options">;
type NodeSqliteProviderOptions = Static<typeof nodeSqliteOptions.schema>;
declare module "alepha" {
  interface State {
    [nodeSqliteOptions.key]: NodeSqliteProviderOptions;
  }
}
/**
 * Node.js SQLite provider using `node:sqlite` (DatabaseSync).
 *
 * Uses drizzle-orm's `BetterSQLiteSession` (sync driver) with a shimmed
 * `node:sqlite` DatabaseSync — no native `better-sqlite3` package required.
 *
 * The session and migrator sub-modules of `drizzle-orm/better-sqlite3` are
 * imported directly, bypassing `driver.cjs` which has a top-level
 * `require("better-sqlite3")`.
 */
declare class NodeSqliteProvider extends DatabaseProvider {
  protected readonly env: {
    DATABASE_URL?: string | undefined;
    DATABASE_SYNC?: boolean | undefined;
  };
  protected readonly builder: SqliteModelBuilder;
  protected readonly options: Readonly<{
    path?: string | undefined;
  }>;
  protected sqlite: DatabaseSync;
  protected drizzleDb: any;
  get name(): string;
  readonly dialect = "sqlite";
  get url(): string;
  get db(): PgDatabase<any>;
  get nativeConnection(): unknown;
  /**
   * SQLite transaction override.
   *
   * The base class uses `this.db.transaction()` which goes through drizzle's
   * better-sqlite3 driver. That driver wraps a synchronous `BEGIN`/`COMMIT`
   * around the callback, so async callbacks commit before the work finishes.
   *
   * This override uses direct `BEGIN`/`COMMIT`/`ROLLBACK` on the native
   * connection with proper `await`, making async transactions safe.
   */
  transactional<R>(fn: () => Promise<R>): Promise<R>;
  execute(query: SQLLike): Promise<Array<Record<string, unknown>>>;
  protected readonly onStart: import("alepha").HookPrimitive<"start">;
  /**
   * Shim `node:sqlite` DatabaseSync to be compatible with the `better-sqlite3`
   * Drizzle driver. DatabaseSync lacks `stmt.raw()` and `db.transaction()`.
   */
  protected shimDatabaseSync(): void;
  /**
   * For SELECT queries with JOINs, add unique positional aliases to each column
   * so that `Object.values()` preserves all values even when column names collide.
   *
   * Only rewrites when the query is a SELECT containing a JOIN keyword and the
   * column list has duplicate base names.
   */
  protected static aliasSelectColumns(sql: string): string;
  /**
   * Initialize Drizzle using the sync session from `drizzle-orm/better-sqlite3/session`
   * directly, bypassing `drizzle-orm/better-sqlite3/driver` which has a top-level
   * `require("better-sqlite3")`. The shimmed `node:sqlite` DatabaseSync is fully
   * compatible with the sync session — no native `better-sqlite3` package required.
   */
  protected initDrizzle(): void;
  protected executeMigrations(migrationsFolder: string): Promise<void>;
}
//#endregion
//#region ../../src/orm/core/modes/DbMigrationMode.d.ts
/**
 * Built-in migration mode.
 *
 * When `MIGRATE=true` (or `MODE=MIGRATE`) is set, runs database migrations
 * via `DatabaseProvider.migrate()`, then stops the process.
 *
 * Auto-registered by `AlephaOrm` — any app using the ORM module gets
 * `MIGRATE=true node app.js` for free.
 *
 * @example
 * ```bash
 * MIGRATE=true node app.js    # runs migrations, then exits
 * MODE=MIGRATE node app.js    # same effect
 * ```
 */
declare class DbMigrationMode {
  protected db: DatabaseProvider;
  protected mode: boolean;
}
//#endregion
//#region ../../src/orm/core/providers/drivers/BunSqliteProvider.d.ts
/**
 * Configuration options for the Bun SQLite database provider.
 */
declare const bunSqliteOptions: import("alepha").Atom<import("zod").ZodObject<{
  path: import("zod").ZodOptional<import("zod").ZodString>;
}, import("zod/v4/core").$strip>, "alepha.postgres.bun-sqlite.options">;
type BunSqliteProviderOptions = Static<typeof bunSqliteOptions.schema>;
declare module "alepha" {
  interface State {
    [bunSqliteOptions.key]: BunSqliteProviderOptions;
  }
}
/**
 * Bun SQLite provider using Drizzle ORM with Bun's native SQLite client.
 *
 * This provider uses Bun's built-in `bun:sqlite` for SQLite connections,
 * which provides excellent performance on the Bun runtime.
 *
 * @example
 * ```ts
 * // Set DATABASE_URL environment variable
 * // DATABASE_URL=sqlite://./my-database.db
 *
 * // Or configure programmatically
 * alepha.with({
 *   provide: DatabaseProvider,
 *   use: BunSqliteProvider,
 * });
 *
 * // Or use options atom
 * alepha.store.mut(bunSqliteOptions, (old) => ({
 *   ...old,
 *   path: ":memory:",
 * }));
 * ```
 */
declare class BunSqliteProvider extends DatabaseProvider {
  protected readonly env: {
    DATABASE_URL?: string | undefined;
    DATABASE_SYNC?: boolean | undefined;
  };
  protected readonly builder: SqliteModelBuilder;
  protected readonly options: Readonly<{
    path?: string | undefined;
  }>;
  protected sqlite?: Database;
  protected bunDb?: BunSQLiteDatabase;
  get name(): string;
  readonly dialect = "sqlite";
  get url(): string;
  get db(): PgDatabase<any>;
  get nativeConnection(): unknown;
  execute(query: SQLLike): Promise<Array<Record<string, unknown>>>;
  protected readonly onStart: import("alepha").HookPrimitive<"start">;
  protected readonly onStop: import("alepha").HookPrimitive<"stop">;
  protected executeMigrations(migrationsFolder: string): Promise<void>;
}
declare namespace index_d_exports {
  export { $entity, $repository, $seed, $sequence, $transactional, AggregateColumnResult, AggregateColumnSelect, AggregateHaving, AggregateOp, AggregateQuery, AggregateResult, AggregateSelect, AlephaOrm, AlephaSequence, BunSqliteProvider, BunSqliteProviderOptions, CloudflareD1Provider, D1Database, D1ExecResult, D1PreparedStatement, D1Result, DatabaseProvider, DatabaseTypeProvider, DbCacheProvider, DbColumnNotFoundError, DbConflictError, DbConnectionError, DbDeadlockError, DbEntityNotFoundError, DbError, DbForeignKeyError, DbMigrationError, DbMigrationMode, DbNotNullError, DbTableNotFoundError, DbVersionMismatchError, DrizzleKitProvider, EntityColumn, EntityColumns, EntityPrimitive, EntityPrimitiveOptions, FilterOperators, FromSchema, ModelBuilder, NodeSqliteProvider, NodeSqliteProviderOptions, OrderBy, OrderByClause, OrderDirection, PG_CREATED_AT, PG_DEFAULT, PG_DELETED_AT, PG_ENUM, PG_GENERATED, PG_IDENTITY, PG_ORGANIZATION, PG_PRIMARY_KEY, PG_REF, PG_SERIAL, PG_UPDATED_AT, PG_VERSION, Page, PageQuery, PgAttr, PgAttrField, PgDefault, PgEnumOptions, PgGeneratedOptions, PgIdentityOptions, PgOrganizationOptions, PgPrimaryKey, PgQuery, PgQueryRelations, PgQueryWhere, PgQueryWhereOrSQL, PgRef, PgRefOptions, PgRelation, PgRelationMap, PgStatic, PgSymbolKeys, PgSymbols, Repository, RepositoryProvider, SQLLike, SchemaToTableConfig, SeedOptions, SequencePrimitive, SequencePrimitiveOptions, SequenceProvider, SqliteProvider, StatementOptions, TObjectInsert, TObjectUpdate, TableConfigBuilders, TransactionalOptions, alephaSequences, bunSqliteOptions, databaseEnvSchema, db, drizzle, getAttrFields, insertSchema, legacyIdSchema, nodeSqliteOptions, pageQuerySchema, pageSchema, pgAttr, schema, sql, updateSchema };
}
declare module "alepha" {
  interface State {
    "alepha.orm.tx"?: PgTransaction<any>;
  }
  interface Hooks {
    /**
     * Fires before creating an entity in the repository.
     */
    "repository:create:before": {
      tableName: string;
      data: any;
    };
    /**
     * Fires after creating an entity in the repository.
     */
    "repository:create:after": {
      tableName: string;
      data: any;
      entity: any;
    };
    /**
     * Fires before updating entities in the repository.
     */
    "repository:update:before": {
      tableName: string;
      where: any;
      data: any;
    };
    /**
     * Fires after updating entities in the repository.
     */
    "repository:update:after": {
      tableName: string;
      where: any;
      data: any;
      entities: any[];
    };
    /**
     * Fires before deleting entities from the repository.
     */
    "repository:delete:before": {
      tableName: string;
      where: any;
    };
    /**
     * Fires after deleting entities from the repository.
     */
    "repository:delete:after": {
      tableName: string;
      where: any;
      ids: Array<string | number>;
    };
    /**
     * Fires before reading entities from the repository.
     */
    "repository:read:before": {
      tableName: string;
      query: any;
    };
    /**
     * Fires after reading entities from the repository.
     */
    "repository:read:after": {
      tableName: string;
      query: any;
      entities: any[];
    };
  }
}
declare const SqliteProvider: typeof NodeSqliteProvider;
declare const AlephaOrm: import("alepha").Service<import("alepha").Module>;
//#endregion
export { $entity, $repository, $seed, $sequence, $transactional, AggregateColumnResult, AggregateColumnSelect, AggregateHaving, AggregateOp, AggregateQuery, AggregateResult, AggregateSelect, AlephaOrm, AlephaSequence, BunSqliteProvider, BunSqliteProviderOptions, CloudflareD1Provider, D1Database, D1ExecResult, D1PreparedStatement, D1Result, DatabaseProvider, DatabaseTypeProvider, DbCacheProvider, DbColumnNotFoundError, DbConflictError, DbConnectionError, DbDeadlockError, DbEntityNotFoundError, DbError, DbForeignKeyError, DbMigrationError, DbMigrationMode, DbNotNullError, DbTableNotFoundError, DbVersionMismatchError, DrizzleKitProvider, EntityColumn, EntityColumns, EntityPrimitive, EntityPrimitiveOptions, FilterOperators, FromSchema, ModelBuilder, NodeSqliteProvider, NodeSqliteProviderOptions, OrderBy, OrderByClause, OrderDirection, PG_CREATED_AT, PG_DEFAULT, PG_DELETED_AT, PG_ENUM, PG_GENERATED, PG_IDENTITY, PG_ORGANIZATION, PG_PRIMARY_KEY, PG_REF, PG_SERIAL, PG_UPDATED_AT, PG_VERSION, type Page, type PageQuery, PgAttr, PgAttrField, PgDefault, PgEnumOptions, PgGeneratedOptions, PgIdentityOptions, PgOrganizationOptions, PgPrimaryKey, PgQuery, PgQueryRelations, PgQueryWhere, PgQueryWhereOrSQL, PgRef, PgRefOptions, PgRelation, PgRelationMap, PgStatic, PgSymbolKeys, PgSymbols, Repository, RepositoryProvider, SQLLike, SchemaToTableConfig, SeedOptions, SequencePrimitive, SequencePrimitiveOptions, SequenceProvider, SqliteProvider, StatementOptions, TObjectInsert, TObjectUpdate, TableConfigBuilders, TransactionalOptions, alephaSequences, bunSqliteOptions, databaseEnvSchema, db, drizzle, getAttrFields, insertSchema, legacyIdSchema, nodeSqliteOptions, pageQuerySchema, pageSchema, pgAttr, schema, sql, updateSchema };
//# sourceMappingURL=index.d.ts.map