import type { Column, ColumnBaseConfig, ColumnDataType, DrizzleConfig, ExtractTablesWithRelations, Relation, Relations, SQL, TableRelationalConfig, } from 'drizzle-orm' import type { LibSQLDatabase } from 'drizzle-orm/libsql' import type { NodePgDatabase, NodePgQueryResultHKT } from 'drizzle-orm/node-postgres' import type { PgColumn, PgTable, PgTransaction, Precision, UpdateDeleteAction, } from 'drizzle-orm/pg-core' import type { SQLiteColumn, SQLiteTable, SQLiteTransaction } from 'drizzle-orm/sqlite-core' import type { Result } from 'drizzle-orm/sqlite-core/session' import type { BaseDatabaseAdapter, FlattenedField, MigrationData, Operator, Payload, PayloadRequest, } from 'payload' import type { BuildQueryJoinAliases } from './queries/buildQuery.js' export { BuildQueryJoinAliases } import type { ResultSet } from '@libsql/client' import type { DrizzleSnapshotJSON } from 'drizzle-kit/api' import type { SQLiteRaw } from 'drizzle-orm/sqlite-core/query-builders/raw' import type { QueryResult } from 'pg' import type { DrizzleResolvedOperator, Operators } from './queries/operatorMap.js' export type PostgresDB = NodePgDatabase> export type SQLiteDB = LibSQLDatabase< Record & Record > export type GenericPgColumn = PgColumn< ColumnBaseConfig, Record > export type GenericColumns = { [x: string]: T } type GenericPgTable = PgTable<{ columns: GenericColumns dialect: string name: string schema: undefined }> type GenericSQLiteTable = SQLiteTable<{ columns: GenericColumns dialect: string name: string schema: undefined }> export type GenericColumn = GenericPgColumn | SQLiteColumn export type GenericTable = GenericPgTable | GenericSQLiteTable export type GenericRelation = Relations>> export type TransactionSQLite = SQLiteTransaction< 'async', Result<'async', unknown>, Record, { tsName: TableRelationalConfig } > export type TransactionPg = PgTransaction< NodePgQueryResultHKT, Record, ExtractTablesWithRelations> > export type DrizzleTransaction = TransactionPg | TransactionSQLite export type CountDistinct = (args: { column?: PgColumn | SQLiteColumn db: DrizzleTransaction | LibSQLDatabase | PostgresDB joins: BuildQueryJoinAliases tableName: string where: SQL }) => Promise export type DeleteWhere = (args: { db: DrizzleTransaction | LibSQLDatabase | PostgresDB tableName: string where: SQL }) => Promise export type DropDatabase = (args: { adapter: DrizzleAdapter }) => Promise export type Execute = (args: { db?: DrizzleTransaction | LibSQLDatabase | PostgresDB drizzle?: LibSQLDatabase | PostgresDB raw?: string sql?: SQL }) => | Promise>> | SQLiteRaw> | SQLiteRaw export type Insert = (args: { db: DrizzleTransaction | LibSQLDatabase | PostgresDB onConflictDoUpdate?: unknown tableName: string values: Record | Record[] }) => Promise[]> export type RequireDrizzleKit = () => Promise<{ generateDrizzleJson: ( args: Record, ) => DrizzleSnapshotJSON | Promise generateMigration: (prev: DrizzleSnapshotJSON, cur: DrizzleSnapshotJSON) => Promise pushSchema: ( schema: Record, drizzle: DrizzleAdapter['drizzle'], filterSchema?: string[], tablesFilter?: string[], extensionsFilter?: string[], ) => Promise<{ apply; hasDataLoss; warnings }> upSnapshot?: (snapshot: Record) => DrizzleSnapshotJSON }> export type Migration = { down: ({ db, payload, req, }: { db?: DrizzleTransaction | LibSQLDatabase> | PostgresDB payload: Payload req: PayloadRequest }) => Promise up: ({ db, payload, req, }: { db?: DrizzleTransaction | LibSQLDatabase | PostgresDB payload: Payload req: PayloadRequest }) => Promise } & MigrationData export type CreateJSONQueryArgs = { column?: Column | string operator: string pathSegments: string[] rawColumn?: SQL table?: string treatAsArray?: string[] treatRootAsArray?: boolean value: boolean | number | number[] | string | string[] } /** * Abstract relation link */ export type RawRelation = | { fields: { name: string; table: string }[] references: string[] relationName?: string to: string type: 'one' } | { relationName?: string to: string type: 'many' } /** * Abstract SQL table that later gets converted by database specific implementation to Drizzle */ export type RawTable = { columns: Record foreignKeys?: Record indexes?: Record name: string } /** * Abstract SQL foreign key that later gets converted by database specific implementation to Drizzle */ export type RawForeignKey = { columns: string[] foreignColumns: { name: string; table: string }[] name: string onDelete?: UpdateDeleteAction onUpdate?: UpdateDeleteAction } /** * Abstract SQL index that later gets converted by database specific implementation to Drizzle */ export type RawIndex = { name: string on: string | string[] unique?: boolean } /** * Abstract SQL column that later gets converted by database specific implementation to Drizzle */ export type BaseRawColumn = { default?: any name: string notNull?: boolean primaryKey?: boolean reference?: { name: string onDelete: UpdateDeleteAction table: string } } /** * Postgres: native timestamp type * SQLite: text column, defaultNow achieved through strftime('%Y-%m-%dT%H:%M:%fZ', 'now'). withTimezone/precision have no any effect. */ export type TimestampRawColumn = { defaultNow?: boolean mode: 'date' | 'string' precision: Precision type: 'timestamp' withTimezone?: boolean } & BaseRawColumn /** * Postgres: native UUID type and db lavel defaultRandom * SQLite: text type and defaultRandom in the app level */ export type UUIDRawColumn = { defaultRandom?: boolean /** App-side UUID v7 default (Postgres & SQLite); mutually exclusive with defaultRandom in practice */ defaultV7?: boolean type: 'uuid' } & BaseRawColumn /** * Accepts either `locale: true` to have options from locales or `options` string array * Postgres: native enums * SQLite: text column with checks. */ export type EnumRawColumn = ( | { enumName: string options: string[] type: 'enum' } | { locale: true type: 'enum' } ) & BaseRawColumn export type IntegerRawColumn = { /** * SQLite only. * Enable [AUTOINCREMENT](https://www.sqlite.org/autoinc.html) for primary key to ensure that the same ID cannot be reused from previously deleted rows. */ autoIncrement?: boolean type: 'integer' } & BaseRawColumn export type VectorRawColumn = { dimensions?: number type: 'vector' } & BaseRawColumn export type HalfVecRawColumn = { dimensions?: number type: 'halfvec' } & BaseRawColumn export type SparseVecRawColumn = { dimensions?: number type: 'sparsevec' } & BaseRawColumn export type BinaryVecRawColumn = { dimensions?: number type: 'bit' } & BaseRawColumn export type RawColumn = | ({ type: 'boolean' | 'geometry' | 'jsonb' | 'numeric' | 'serial' | 'text' | 'varchar' } & BaseRawColumn) | BinaryVecRawColumn | EnumRawColumn | HalfVecRawColumn | IntegerRawColumn | SparseVecRawColumn | TimestampRawColumn | UUIDRawColumn | VectorRawColumn export type IDType = 'integer' | 'numeric' | 'text' | 'uuid' | 'varchar' export type SetColumnID = (args: { adapter: DrizzleAdapter columns: Record fields: FlattenedField[] }) => IDType export type ColumnToCodeConverter = (args: { adapter: DrizzleAdapter addEnum: (name: string, options: string[]) => void addImport: (from: string, name: string) => void circularEdges?: Set column: RawColumn locales?: string[] tableKey: string }) => string export type BuildDrizzleTable = (args: { adapter: T locales: string[] rawTable: RawTable }) => void export type BlocksToJsonBlockToMigrate = { data: Record | Record[] fieldAccessor: (number | string)[] } export interface BaseBlocksToJsonEntityToMigrate { blocks: BlocksToJsonBlockToMigrate[] originalData: Record } export interface CollectionOrVersionBlocksToJsonEntityToMigrate extends BaseBlocksToJsonEntityToMigrate { id: number | string slug: string type: 'collection' | 'collectionVersion' | 'globalVersion' } export interface GlobalBlocksToJsonEntityToMigrate extends BaseBlocksToJsonEntityToMigrate { slug: string type: 'global' } export type BlocksToJsonEntityToMigrate = | CollectionOrVersionBlocksToJsonEntityToMigrate | GlobalBlocksToJsonEntityToMigrate export interface BlocksToJsonMigrator { collectAndSaveEntitiesToBatches( req: PayloadRequest, options?: { batchSize?: number }, ): Promise getMigrationStatements(): Promise<{ statements: string writeDrizzleSnapshot(filePath: string): void }> migrateEntitiesFromTempFolder( req: PayloadRequest, options?: { clearBatches?: boolean }, ): Promise setTempFolder(tempFolderPath: string): void updatePayloadConfigFile(): Promise } /** * The information passed to a query-operator handler for one user-facing leaf comparison. */ export type DrizzleOperatorHandlerContext = { adapter: DrizzleAdapter column: Column | SQL field: FlattenedField locale?: string /** The operator supplied by the Payload query, before any adapter conversions. */ originalOperator: Operator path: string /** The operator actually sent to the database after Payload's existing conversions. */ resolvedOperator: DrizzleResolvedOperator storage: 'column' value: unknown } /** * Transforms the column and/or value of a matching operator before the default (or replacement) * comparison runs. Multiple matching transform handlers compose in configuration order. */ export type DrizzleOperandTransformHandler = { build?: never /** Restricts the handler to these Payload field types. Omit to match every field type. */ fieldTypes?: FlattenedField['type'][] name: string operators: DrizzleResolvedOperator[] transformOperands: (context: DrizzleOperatorHandlerContext) => { column: Column | SQL value: unknown } } /** * Replaces the default comparison for a matching operator entirely. Runs after every matching * `transformOperands` handler has already run. */ export type DrizzleOperatorReplacementHandler = { build: (context: DrizzleOperatorHandlerContext) => SQL /** Restricts the handler to these Payload field types. Omit to match every field type. */ fieldTypes?: FlattenedField['type'][] name: string operators: DrizzleResolvedOperator[] transformOperands?: never } export type DrizzleOperatorHandler = | DrizzleOperandTransformHandler | DrizzleOperatorReplacementHandler export type DrizzleQueryConfig = { operatorHandlers?: DrizzleOperatorHandler[] } export interface DrizzleAdapter extends BaseDatabaseAdapter { blocksAsJSON?: boolean blocksToJsonMigrator?: BlocksToJsonMigrator convertPathToJSONTraversal?: (incomingSegments: string[]) => string countDistinct: CountDistinct createJSONQuery: (args: CreateJSONQueryArgs) => string defaultDrizzleSnapshot: Record deleteWhere: DeleteWhere drizzle: LibSQLDatabase | PostgresDB dropDatabase: DropDatabase enums?: never | Record execute: Execute features: { json?: boolean } /** * An object keyed on each table, with a key value pair where the constraint name is the key, followed by the dot-notation field name * Used for returning properly formed errors from unique fields */ fieldConstraints: Record> foreignKeys: Set idType: 'serial' | 'uuid' | 'uuidv7' indexes: Set initializing: Promise insert: Insert /** * Timestamp (ms) of the last write operation. When read replicas are configured, * reads within `readReplicasAfterWriteInterval` ms of this timestamp are routed to the * primary to guarantee read-after-write consistency. */ lastWriteTimestamp?: number limitedBoundParameters?: boolean localesSuffix?: string logger: DrizzleConfig['logger'] operatorHandlers: DrizzleOperatorHandler[] operators: Operators /** * When read replicas are configured, holds the unwrapped primary drizzle instance * (before withReplicas wrapping). Used for reads that are part of write operations * to avoid replication lag. */ primaryDrizzle?: PostgresDB push: boolean rawRelations: Record> rawTables: Record /** * How long (ms) after a write to route reads to the primary instead of a * read replica. Avoids stale reads caused by replication lag. * @default 2000 */ readReplicasAfterWriteInterval: number rejectInitializing: () => void relations: Record relationshipsSuffix?: string requireDrizzleKit: RequireDrizzleKit resolveInitializing: () => void schema: Record schemaName?: string sessions: { [id: string]: { db: DrizzleTransaction reject: () => Promise resolve: () => Promise } } tableNameMap: Map tables: Record transactionOptions: unknown versionsSuffix?: string } export type RelationMap = Map< string, { localized: boolean relationName?: string target: string type: 'many' | 'one' } >