UNPKG

alepha

Version:

Easy-to-use modern TypeScript framework for building many kind of applications.

888 lines 34.7 kB
import { Static, TObject } from "alepha"; import { DatabaseProvider, EntityPrimitive, FromSchema, ModelBuilder, SQLLike, SequencePrimitive } from "alepha/orm"; import { BuildExtraConfigColumns } from "drizzle-orm"; import * as pg from "drizzle-orm/pg-core"; import { PgDatabase, PgSchema, PgTableExtraConfigValue } from "drizzle-orm/pg-core"; import { PostgresJsDatabase } from "drizzle-orm/postgres-js"; import postgres from "postgres"; import { BunSQLDatabase } from "drizzle-orm/bun-sql"; import { PgliteDatabase } from "drizzle-orm/pglite"; //#region ../../src/orm/postgres/services/PostgresModelBuilder.d.ts declare class PostgresModelBuilder extends ModelBuilder { protected schemas: Map<string, PgSchema<string>>; /** * Create a primary key column with UUID v7 */ protected getPrimaryKeyUUID(key: string): import("drizzle-orm").HasDefault<pg.PgUUIDBuilderInitial<string>>; protected getPgSchema(name: string): any; 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 PostgreSQL-specific config builder for the table. */ protected getTableConfig(entity: EntityPrimitive, tables: Map<string, unknown>): ((self: BuildExtraConfigColumns<string, any, "pg">) => PgTableExtraConfigValue[]) | undefined; schemaToPgColumns: <T extends TObject>(tableName: string, schema: T, nsp: PgSchema, enums: Map<string, unknown>, tables: Map<string, unknown>) => FromSchema<T>; mapFieldToColumn: (tableName: string, fieldName: string, value: any, nsp: PgSchema, enums: Map<string, any>) => any; /** * Map a string to a PG column. * * @param key The key of the field. * @param value The value of the field. */ mapStringToColumn: (key: string, value: any) => pg.PgCustomColumnBuilder<{ name: string; dataType: 'custom'; columnType: 'PgCustomColumn'; data: Buffer<ArrayBufferLike>; driverParam: unknown; enumValues: undefined; }> | pg.PgDateStringBuilderInitial<string> | pg.PgTextBuilderInitial<string, [string, ...string[]]> | pg.PgTimestampStringBuilderInitial<string> | pg.PgUUIDBuilderInitial<string>; } //#endregion //#region ../../src/orm/postgres/providers/PostgresProvider.d.ts /** * Abstract base class for PostgreSQL database providers. * * Provides shared logic for Node.js and Bun PostgreSQL providers: * - Environment variable handling (DATABASE_URL, POSTGRES_SCHEMA) * - Schema name resolution (with test schema generation) * - SQL execution with error wrapping * - Lifecycle hooks (start with migration lock, stop with test cleanup) * * Subclasses must implement `connect()`, `close()`, and `executeMigrations()`. */ declare abstract class PostgresProvider extends DatabaseProvider { protected readonly env: { DATABASE_URL?: string | undefined; DATABASE_SYNC?: boolean | undefined; }; protected readonly pgEnv: { POSTGRES_SCHEMA?: string | undefined; POOL_MAX?: number | undefined; POOL_IDLE_TIMEOUT?: number | undefined; POOL_CONNECT_TIMEOUT?: number | undefined; }; protected readonly builder: PostgresModelBuilder; readonly dialect = "postgresql"; get name(): string; /** * In testing mode, the schema name will be generated and deleted after the test. */ protected schemaForTesting: string | undefined; get url(): string; /** * Execute a SQL statement. */ execute(statement: SQLLike): Promise<Array<Record<string, unknown>>>; /** * Get Postgres schema used by this provider. */ get schema(): string; abstract get db(): PgDatabase<any>; /** * Establish the database connection. */ abstract connect(): Promise<void>; /** * Close the database connection. */ abstract close(): Promise<void>; protected readonly onStart: import("alepha").HookPrimitive<"start">; protected readonly onStop: import("alepha").HookPrimitive<"stop">; protected migrateLock: import("alepha").PipelinePrimitiveFn<() => Promise<void>>; protected generateTestSchema(): Promise<void>; /** * Drop the current test schema if applicable. */ protected dropTestSchema(): Promise<void>; /** * Remove stale test schemas older than 1 hour. * * Parses the embedded epoch from schema names (format: test_alepha_{epoch}_{random8}) * and drops any that exceed the TTL. This handles schemas left behind by crashed tests, * killed processes, or failed startups where stop() never fired. * * Uses a PG advisory lock so only one concurrent test process performs the cleanup. */ protected cleanupStaleTestSchemas(): Promise<void>; /** * Parse the age in milliseconds from a test schema name. * Format: test_alepha_{epoch_seconds}_{random8} * Returns undefined if the name doesn't match the expected format. */ protected parseTestSchemaAge(name: string, now: number): number | undefined; } //#endregion //#region ../../src/orm/postgres/providers/BunPostgresProvider.d.ts /** * Bun PostgreSQL provider using Drizzle ORM with Bun's native SQL client. * * This provider uses Bun's built-in SQL class for PostgreSQL connections, * which provides excellent performance on the Bun runtime. * * @example * ```ts * // Set DATABASE_URL environment variable * // DATABASE_URL=postgres://user:password@localhost:5432/database * * // Or configure programmatically * alepha.with({ * provide: DatabaseProvider, * use: BunPostgresProvider, * }); * ``` */ declare class BunPostgresProvider extends PostgresProvider { protected client?: Bun.SQL; protected bunDb?: BunSQLDatabase; /** * Get the Drizzle Postgres database instance. */ get db(): PgDatabase<any>; protected executeMigrations(migrationsFolder: string): Promise<void>; connect(): Promise<void>; close(): Promise<void>; } //#endregion //#region ../../src/orm/postgres/providers/CloudflareHyperdriveProvider.d.ts /** * Cloudflare Hyperdrive PostgreSQL provider using Drizzle ORM. * * Connects to an external PostgreSQL database through Cloudflare Hyperdrive, * which provides connection pooling and caching at the edge. * * Creates a fresh connection per request, since Cloudflare Workers * cannot reuse I/O objects across request contexts. * * URL format: hyperdrive://BINDING_NAME */ declare class CloudflareHyperdriveProvider extends DatabaseProvider { protected readonly builder: PostgresModelBuilder; protected readonly env: { DATABASE_URL: string; POSTGRES_SCHEMA?: string | undefined; }; get schema(): string; protected postgresFn?: any; protected drizzleFn?: any; protected bindingName?: string; get name(): string; get driver(): string; readonly dialect = "postgresql"; get url(): string; /** * Get a fresh Drizzle instance per request. * * Reads the current Hyperdrive binding from `cloudflare.env` * and creates a new postgres client each time, avoiding the * "Cannot perform I/O on behalf of a different request" error. */ get db(): PgDatabase<any>; execute(query: SQLLike): Promise<Array<Record<string, unknown>>>; protected readonly onStart: import("alepha").HookPrimitive<"start">; protected executeMigrations(migrationsFolder: string): Promise<void>; } //#endregion //#region ../../src/orm/postgres/providers/NodePostgresProvider.d.ts declare class NodePostgresProvider extends PostgresProvider { static readonly SSL_MODES: readonly ["require", "allow", "prefer", "verify-full"]; protected client?: postgres.Sql; protected pg?: PostgresJsDatabase; /** * Get the Drizzle Postgres database instance. */ get db(): PostgresJsDatabase; protected executeMigrations(migrationsFolder: string): Promise<void>; connect(): Promise<void>; close(): Promise<void>; /** * Map the DATABASE_URL to postgres client options. */ protected getClientOptions(): postgres.Options<any>; protected ssl(url: URL): "require" | "allow" | "prefer" | "verify-full" | undefined; } //#endregion //#region ../../../../node_modules/@electric-sql/pglite/dist/pglite-CpaPhfpC.d.ts type MessageName = 'parseComplete' | 'bindComplete' | 'closeComplete' | 'noData' | 'portalSuspended' | 'replicationStart' | 'emptyQuery' | 'copyDone' | 'copyData' | 'rowDescription' | 'parameterDescription' | 'parameterStatus' | 'backendKeyData' | 'notification' | 'readyForQuery' | 'commandComplete' | 'dataRow' | 'copyInResponse' | 'copyOutResponse' | 'authenticationOk' | 'authenticationMD5Password' | 'authenticationCleartextPassword' | 'authenticationSASL' | 'authenticationSASLContinue' | 'authenticationSASLFinal' | 'error' | 'notice'; type BackendMessage = { name: MessageName; length: number; }; interface NoticeOrError { message: string | undefined; severity: string | undefined; code: string | undefined; detail: string | undefined; hint: string | undefined; position: string | undefined; internalPosition: string | undefined; internalQuery: string | undefined; where: string | undefined; schema: string | undefined; table: string | undefined; column: string | undefined; dataType: string | undefined; constraint: string | undefined; file: string | undefined; line: string | undefined; routine: string | undefined; } declare class NoticeMessage implements BackendMessage, NoticeOrError { readonly length: number; readonly message: string | undefined; constructor(length: number, message: string | undefined); readonly name = "notice"; severity: string | undefined; code: string | undefined; detail: string | undefined; hint: string | undefined; position: string | undefined; internalPosition: string | undefined; internalQuery: string | undefined; where: string | undefined; schema: string | undefined; table: string | undefined; column: string | undefined; dataType: string | undefined; constraint: string | undefined; file: string | undefined; line: string | undefined; routine: string | undefined; } type IDBFS = Emscripten.FileSystemType & { quit: () => void; dbs: Record<string, IDBDatabase>; }; type FS = typeof FS & { filesystems: { MEMFS: Emscripten.FileSystemType; NODEFS: Emscripten.FileSystemType; IDBFS: IDBFS; }; quit: () => void; }; interface PostgresMod extends Omit<EmscriptenModule, 'preInit' | 'preRun' | 'postRun'> { preInit: Array<{ (mod: PostgresMod): void; }>; preRun: Array<{ (mod: PostgresMod): void; }>; postRun: Array<{ (mod: PostgresMod): void; }>; thisProgram: string; stdin: (() => number | null) | null; FS: FS; wasmMemory: WebAssembly.Memory; PROXYFS: Emscripten.FileSystemType; WASM_PREFIX: string; pg_extensions: Record<string, Promise<Blob | null>>; UTF8ToString: (ptr: number, maxBytesToRead?: number) => string; stringToUTF8OnStack: (s: string) => number; _pgl_set_system_fn: (system_fn: number) => void; _pgl_set_popen_fn: (popen_fn: number) => void; _pgl_set_pclose_fn: (pclose_fn: number) => void; _pgl_set_rw_cbs: (read_cb: number, write_cb: number) => void; _pgl_set_pipe_fn: (pipe_fn: number) => number; _pgl_freopen: (filepath: number, mode: number, stream: number) => number; _pgl_pq_flush: () => void; _fopen: (path: number, mode: number) => number; _fclose: (stream: number) => number; _fflush: (stream: number) => void; _pgl_proc_exit: (code: number) => number; addFunction: (cb: (ptr: any, length: number) => void, signature: string) => number; removeFunction: (f: number) => void; callMain: (args?: string[]) => number; _PostgresMainLoopOnce: () => void; _PostgresMainLongJmp: () => void; _PostgresSendReadyForQueryIfNecessary: () => void; _ProcessStartupPacket: (Port: number, ssl_done: boolean, gss_done: boolean) => number; _IsTransactionBlock: () => number; _pgl_setPGliteActive: (newValue: number) => number; _pgl_startPGlite: () => void; _pgl_getMyProcPort: () => number; _pgl_sendConnData: () => void; ENV: any; PGLITE_ENV: any; _emscripten_force_exit: (status: number) => void; _pgl_run_atexit_funcs: () => void; _pq_buffer_remaining_data: () => number; } type DumpTarCompressionOptions = 'none' | 'gzip' | 'auto'; /** * Filesystem interface. * All virtual filesystems that are compatible with PGlite must implement * this interface. */ interface Filesystem { /** * Initiate the filesystem and return the options to pass to the emscripten module. */ init(pg: PGlite, emscriptenOptions: Partial<PostgresMod>): Promise<{ emscriptenOpts: Partial<PostgresMod>; }>; /** * Sync the filesystem to any underlying storage. */ syncToFs(relaxedDurability?: boolean): Promise<void>; /** * Sync the filesystem from any underlying storage. */ initialSyncFs(): Promise<void>; /** * Dump the PGDATA dir from the filesystem to a gzipped tarball. */ dumpTar(dbname: string, compression?: DumpTarCompressionOptions): Promise<File | Blob>; /** * Close the filesystem. */ closeFs(): Promise<void>; } type DebugLevel = 0 | 1 | 2 | 3 | 4 | 5; type RowMode = 'array' | 'object'; interface ParserOptions { [pgType: number]: (value: string) => any; } interface SerializerOptions { [pgType: number]: (value: any) => string; } interface QueryOptions { rowMode?: RowMode; parsers?: ParserOptions; serializers?: SerializerOptions; blob?: Blob | File; onNotice?: (notice: NoticeMessage) => void; paramTypes?: number[]; } interface ExecProtocolOptions { syncToFs?: boolean; throwOnError?: boolean; onNotice?: (notice: NoticeMessage) => void; } interface ExecProtocolOptionsStream { syncToFs?: boolean; onRawData: (data: Uint8Array) => void; } interface ExtensionSetupResult<TNamespace = any> { emscriptenOpts?: any; namespaceObj?: TNamespace; bundlePath?: URL; sharedPreloadLibraries?: string[]; init?: () => Promise<void>; close?: () => Promise<void>; } type ExtensionSetup<TNamespace = any> = (pg: PGliteInterface, emscriptenOpts: any, clientOnly?: boolean) => Promise<ExtensionSetupResult<TNamespace>>; interface Extension<TNamespace = any> { name: string; setup: ExtensionSetup<TNamespace>; } type ExtensionNamespace<T> = T extends Extension<infer TNamespace> ? TNamespace : any; type Extensions = { [namespace: string]: Extension | URL; }; type InitializedExtensions<TExtensions extends Extensions = Extensions> = { [K in keyof TExtensions]: ExtensionNamespace<TExtensions[K]>; }; interface ExecProtocolResult { messages: BackendMessage[]; data: Uint8Array; } interface PGliteOptions<TExtensions extends Extensions = Extensions> { noInitDb?: boolean; dataDir?: string; username?: string; database?: string; fs?: Filesystem; debug?: DebugLevel; relaxedDurability?: boolean; extensions?: TExtensions; loadDataDir?: Blob | File; icuDataDir?: Blob | File; initialMemory?: number; pgliteWasmModule?: WebAssembly.Module; initdbWasmModule?: WebAssembly.Module; fsBundle?: Blob | File; parsers?: ParserOptions; serializers?: SerializerOptions; startParams?: string[]; initDbStartParams?: string[]; postgresqlconf?: string[] | string; } type PGliteInterface<T extends Extensions = Extensions> = InitializedExtensions<T> & { readonly waitReady: Promise<void>; readonly debug: DebugLevel; readonly ready: boolean; readonly closed: boolean; close(): Promise<void>; query<T>(query: string, params?: any[], options?: QueryOptions): Promise<Results<T>>; sql<T>(sqlStrings: TemplateStringsArray, ...params: any[]): Promise<Results<T>>; exec(query: string, options?: QueryOptions): Promise<Array<Results>>; describeQuery(query: string): Promise<DescribeQueryResult>; transaction<T>(callback: (tx: Transaction) => Promise<T>): Promise<T>; execProtocolRaw(message: Uint8Array, options?: ExecProtocolOptions): Promise<Uint8Array>; execProtocolRawStream(message: Uint8Array, options?: ExecProtocolOptionsStream): Promise<void>; execProtocol(message: Uint8Array, options?: ExecProtocolOptions): Promise<ExecProtocolResult>; runExclusive<T>(fn: () => Promise<T>): Promise<T>; listen(channel: string, callback: (payload: string) => void, tx?: Transaction): Promise<(tx?: Transaction) => Promise<void>>; unlisten(channel: string, callback?: (payload: string) => void, tx?: Transaction): Promise<void>; onNotification(callback: (channel: string, payload: string) => void): () => void; offNotification(callback: (channel: string, payload: string) => void): void; dumpDataDir(compression?: DumpTarCompressionOptions): Promise<File | Blob>; refreshArrayTypes(): Promise<void>; }; type PGliteInterfaceExtensions<E> = E extends Extensions ? { [K in keyof E]: E[K] extends Extension ? Awaited<ReturnType<E[K]['setup']>>['namespaceObj'] extends (infer N) ? N extends undefined | null | void ? never : N : never : never; } : Record<string, never>; type Row<T = { [key: string]: any; }> = T; type Results<T = { [key: string]: any; }> = { rows: Row<T>[]; affectedRows?: number; fields: { name: string; dataTypeID: number; }[]; blob?: Blob; }; interface Transaction { query<T>(query: string, params?: any[], options?: QueryOptions): Promise<Results<T>>; sql<T>(sqlStrings: TemplateStringsArray, ...params: any[]): Promise<Results<T>>; exec(query: string, options?: QueryOptions): Promise<Array<Results>>; rollback(): Promise<void>; listen(channel: string, callback: (payload: string) => void): Promise<(tx?: Transaction) => Promise<void>>; get closed(): boolean; } type DescribeQueryResult = { queryParams: { dataTypeID: number; serializer: Serializer; }[]; resultFields: { name: string; dataTypeID: number; parser: Parser; }[]; }; type Parser = (x: string, typeId?: number) => any; type Serializer = (x: any) => string; declare abstract class BasePGlite implements Pick<PGliteInterface, 'query' | 'sql' | 'exec' | 'transaction'> { #private; serializers: Record<number | string, Serializer>; parsers: Record<number | string, Parser>; abstract debug: DebugLevel; /** * Execute a postgres wire protocol message * @param message The postgres wire protocol message to execute * @returns The result of the query */ abstract execProtocol(message: Uint8Array, { syncToFs, onNotice }: ExecProtocolOptions): Promise<ExecProtocolResult>; /** * Execute a postgres wire protocol message * @param message The postgres wire protocol message to execute * @returns The parsed results of the query */ abstract execProtocolStream(message: Uint8Array, { syncToFs, onNotice }: ExecProtocolOptions): Promise<BackendMessage[]>; /** * Execute a postgres wire protocol message directly without wrapping the response. * Only use if `execProtocol()` doesn't suite your needs. * * **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages, * transactions, and notification listeners. Only use if you need to bypass these wrappers and * don't intend to use the above features. * * @param message The postgres wire protocol message to execute * @returns The direct message data response produced by Postgres */ abstract execProtocolRaw(message: Uint8Array, { syncToFs }: ExecProtocolOptions): Promise<Uint8Array>; /** * Execute a postgres wire protocol message directly without wrapping the response. * Only use if `execProtocol()` doesn't suite your needs. * * **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages, * transactions, and notification listeners. Only use if you need to bypass these wrappers and * don't intend to use the above features. * * @param message The postgres wire protocol message to execute * @param options.onRawData Callback to receive streaming data */ abstract execProtocolRawStream(message: Uint8Array, { syncToFs, onRawData }: ExecProtocolOptionsStream): Promise<void>; /** * Sync the database to the filesystem * @returns Promise that resolves when the database is synced to the filesystem */ abstract syncToFs(): Promise<void>; /** * Handle a file attached to the current query * @param file The file to handle */ abstract _handleBlob(blob?: File | Blob): Promise<void>; /** * Get the written file */ abstract _getWrittenBlob(): Promise<File | Blob | undefined>; /** * Cleanup the current file */ abstract _cleanupBlob(): Promise<void>; abstract _checkReady(): Promise<void>; abstract _runExclusiveQuery<T>(fn: () => Promise<T>): Promise<T>; abstract _runExclusiveTransaction<T>(fn: () => Promise<T>): Promise<T>; /** * Listen for notifications on a channel */ abstract listen(channel: string, callback: (payload: string) => void, tx?: Transaction): Promise<(tx?: Transaction) => Promise<void>>; /** * Initialize the array types * The oid if the type of an element and the typarray is the oid of the type of the * array. * We extract these from the database then create the serializers/parsers for * each type. * This should be called at the end of #init() in the implementing class. */ _initArrayTypes({ force }?: { force?: boolean | undefined; }): Promise<void>; /** * Re-syncs the array types from the database * This is useful if you add a new type to the database and want to use it, otherwise pglite won't recognize it. */ refreshArrayTypes(): Promise<void>; /** * Execute a single SQL statement * This uses the "Extended Query" postgres wire protocol message. * @param query The query to execute * @param params Optional parameters for the query * @returns The result of the query */ query<T>(query: string, params?: any[], options?: QueryOptions): Promise<Results<T>>; /** * Execute a single SQL statement like with {@link PGlite.query}, but with a * templated statement where template values will be treated as parameters. * * You can use helpers from `/template` to further format the query with * identifiers, raw SQL, and nested statements. * * This uses the "Extended Query" postgres wire protocol message. * * @param query The query to execute with parameters as template values * @returns The result of the query * * @example * ```ts * const results = await db.sql`SELECT * FROM ${identifier`foo`} WHERE id = ${id}` * ``` */ sql<T>(sqlStrings: TemplateStringsArray, ...params: any[]): Promise<Results<T>>; /** * Execute a SQL query, this can have multiple statements. * This uses the "Simple Query" postgres wire protocol message. * @param query The query to execute * @returns The result of the query */ exec(query: string, options?: QueryOptions): Promise<Array<Results>>; /** * Describe a query * @param query The query to describe * @returns A description of the result types for the query */ describeQuery(query: string, options?: QueryOptions): Promise<DescribeQueryResult>; /** * Execute a transaction * @param callback A callback function that takes a transaction object * @returns The result of the transaction */ transaction<T>(callback: (tx: Transaction) => Promise<T>): Promise<T>; /** * Run a function exclusively, no other transactions or queries will be allowed * while the function is running. * This is useful when working with the execProtocol methods as they are not blocked, * and do not block the locks used by transactions and queries. * @param fn The function to run * @returns The result of the function */ runExclusive<T>(fn: () => Promise<T>): Promise<T>; } declare class PGlite extends BasePGlite implements PGliteInterface, AsyncDisposable { #private; fs?: Filesystem; protected mod?: PostgresMod; private readonly POSTGRES_MAIN_LONGJMP; get ENV(): any; readonly dataDir?: string; readonly waitReady: Promise<void>; readonly debug: DebugLevel; static readonly paths: { readonly PG_ROOT: "/pglite"; readonly PGDATA: string; readonly ICU_DATA_PATH: string; readonly INITDB_EXE_PATH: string; readonly POSTGRES_EXE_PATH: string; }; static readonly DEFAULT_RECV_BUF_SIZE: number; static readonly MAX_BUFFER_SIZE: number; externalCommandStreamFd: number | null; static readonly defaultStartParams: string[]; /** * Create a new PGlite instance * @param dataDir The directory to store the database files * Prefix with idb:// to use indexeddb filesystem in the browser * Use memory:// to use in-memory filesystem * @param options PGlite options */ constructor(dataDir?: string, options?: PGliteOptions); /** * Create a new PGlite instance * @param options PGlite options including the data directory */ constructor(options?: PGliteOptions); /** * Create a new PGlite instance with extensions on the Typescript interface * (The main constructor does enable extensions, however due to the limitations * of Typescript, the extensions are not available on the instance interface) * @param options PGlite options including the data directory * @returns A promise that resolves to the PGlite instance when it's ready. */ static create<O extends PGliteOptions>(options?: O): Promise<PGlite & PGliteInterfaceExtensions<O['extensions']>>; /** * Create a new PGlite instance with extensions on the Typescript interface * (The main constructor does enable extensions, however due to the limitations * of Typescript, the extensions are not available on the instance interface) * @param dataDir The directory to store the database files * Prefix with idb:// to use indexeddb filesystem in the browser * Use memory:// to use in-memory filesystem * @param options PGlite options * @returns A promise that resolves to the PGlite instance when it's ready. */ static create<O extends PGliteOptions>(dataDir?: string, options?: O): Promise<PGlite & PGliteInterfaceExtensions<O['extensions']>>; handleExternalCmd(cmd: string, mode: string): number; /** * The Postgres Emscripten Module */ get Module(): PostgresMod; /** * The ready state of the database */ get ready(): boolean; /** * The closed state of the database */ get closed(): boolean; /** * Close the database * @returns A promise that resolves when the database is closed */ close(): Promise<void>; /** * Close the database when the object exits scope * Stage 3 ECMAScript Explicit Resource Management * https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#using-declarations-and-explicit-resource-management */ [Symbol.asyncDispose](): Promise<void>; /** * Handle a file attached to the current query * @param file The file to handle */ _handleBlob(blob?: File | Blob): Promise<void>; /** * Cleanup the current file */ _cleanupBlob(): Promise<void>; /** * Get the written blob from the current query * @returns The written blob */ _getWrittenBlob(): Promise<Blob | undefined>; /** * Wait for the database to be ready */ _checkReady(): Promise<void>; /** * Execute a postgres wire protocol synchronously * @param message The postgres wire protocol message to execute * @returns The direct message data response produced by Postgres */ execProtocolRawSync(message: Uint8Array): Uint8Array; /** * Execute a postgres wire protocol message directly without wrapping the response. * Only use if `execProtocol()` doesn't suite your needs. * * **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages, * transactions, and notification listeners. Only use if you need to bypass these wrappers and * don't intend to use the above features. * * @param message The postgres wire protocol message to execute * @returns The direct message data response produced by Postgres */ execProtocolRaw(message: Uint8Array, { syncToFs }?: ExecProtocolOptions): Promise<Uint8Array>; /** * Execute a postgres wire protocol message directly without wrapping the response. * Only use if `execProtocol()` doesn't suite your needs. * * **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages, * transactions, and notification listeners. Only use if you need to bypass these wrappers and * don't intend to use the above features. * * @param message The postgres wire protocol message to execute * @param options.onRawData Callback to receive results as streaming data */ execProtocolRawStream(message: Uint8Array, { syncToFs, onRawData }: ExecProtocolOptionsStream): Promise<void>; /** * Execute a postgres wire protocol message * @param message The postgres wire protocol message to execute * @returns The result of the query */ execProtocol(message: Uint8Array, { syncToFs, throwOnError, onNotice }?: ExecProtocolOptions): Promise<ExecProtocolResult>; /** * Execute a postgres wire protocol message * @param message The postgres wire protocol message to execute * @returns The parsed results of the query */ execProtocolStream(message: Uint8Array, { syncToFs, throwOnError, onNotice }?: ExecProtocolOptions): Promise<BackendMessage[]>; /** * Check if the database is in a transaction * @returns True if the database is in a transaction, false otherwise */ isInTransaction(): boolean; /** * Perform any sync operations implemented by the filesystem, this is * run after every query to ensure that the filesystem is synced. */ syncToFs(): Promise<void>; /** * Listen for a notification * @param channel The channel to listen on * @param callback The callback to call when a notification is received */ listen(channel: string, callback: (payload: string) => void, tx?: Transaction): Promise<(tx?: Transaction) => Promise<void>>; /** * Stop listening for a notification * @param channel The channel to stop listening on * @param callback The callback to remove */ unlisten(channel: string, callback?: (payload: string) => void, tx?: Transaction): Promise<void>; /** * Listen to notifications * @param callback The callback to call when a notification is received */ onNotification(callback: (channel: string, payload: string) => void): () => void; /** * Stop listening to notifications * @param callback The callback to remove */ offNotification(callback: (channel: string, payload: string) => void): void; /** * Dump the PGDATA dir from the filesystem to a gzipped tarball. * @param compression The compression options to use - 'gzip', 'auto', 'none' * @returns The tarball as a File object where available, and fallback to a Blob */ dumpDataDir(compression?: DumpTarCompressionOptions): Promise<File | Blob>; /** * Run a function in a mutex that's exclusive to queries * @param fn The query to run * @returns The result of the query */ _runExclusiveQuery<T>(fn: () => Promise<T>): Promise<T>; /** * Run a function in a mutex that's exclusive to transactions * @param fn The function to run * @returns The result of the function */ _runExclusiveTransaction<T>(fn: () => Promise<T>): Promise<T>; clone(): Promise<PGliteInterface>; _runExclusiveListen<T>(fn: () => Promise<T>): Promise<T>; callMain(args: string[]): number; copyToFS(filePath: string, data: Uint8Array, mode?: number): void; } //#endregion //#region ../../src/orm/postgres/providers/PglitePostgresProvider.d.ts interface PgLiteModule { PGlite: typeof PGlite; } declare class PglitePostgresProvider extends DatabaseProvider { static importPglite(): PgLiteModule | undefined; get schema(): string; protected readonly env: { DATABASE_URL?: string | undefined; DATABASE_SYNC?: boolean | undefined; }; protected readonly pgEnv: { POSTGRES_SCHEMA?: string | undefined; POOL_MAX?: number | undefined; POOL_IDLE_TIMEOUT?: number | undefined; POOL_CONNECT_TIMEOUT?: number | undefined; }; protected readonly builder: PostgresModelBuilder; protected client?: PGlite; protected pglite?: PgliteDatabase; get name(): string; get driver(): string; readonly dialect = "postgresql"; get supportsTransactions(): boolean; get url(): string; get db(): PgliteDatabase; execute(statement: 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>; } //#endregion //#region ../../src/orm/postgres/schemas/postgresEnvSchema.d.ts /** * PostgreSQL-specific environment schema. * * Additional env vars for PostgreSQL providers on top of `databaseEnvSchema`. */ declare const postgresEnvSchema: import("zod").ZodObject<{ POSTGRES_SCHEMA: import("zod").ZodOptional<import("zod").ZodString>; POOL_MAX: import("zod").ZodOptional<import("zod").ZodInt>; POOL_IDLE_TIMEOUT: import("zod").ZodOptional<import("zod").ZodInt>; POOL_CONNECT_TIMEOUT: import("zod").ZodOptional<import("zod").ZodInt>; }, import("zod/v4/core").$strip>; declare module "alepha" { interface Env extends Partial<Static<typeof postgresEnvSchema>> {} } //#endregion //#region ../../src/orm/postgres/types/byte.d.ts /** * Postgres bytea type. */ declare const byte: { (): import("drizzle-orm/pg-core").PgCustomColumnBuilder<{ name: ""; dataType: 'custom'; columnType: 'PgCustomColumn'; data: Buffer<ArrayBufferLike>; driverParam: unknown; enumValues: undefined; }>; <TConfig extends Record<string, any> & unknown>(fieldConfig?: TConfig | undefined): import("drizzle-orm/pg-core").PgCustomColumnBuilder<{ name: ""; dataType: 'custom'; columnType: 'PgCustomColumn'; data: Buffer<ArrayBufferLike>; driverParam: unknown; enumValues: undefined; }>; <TName extends string>(dbName: TName, fieldConfig?: unknown): import("drizzle-orm/pg-core").PgCustomColumnBuilder<{ name: TName; dataType: 'custom'; columnType: 'PgCustomColumn'; data: Buffer<ArrayBufferLike>; driverParam: unknown; enumValues: undefined; }>; }; //#endregion //#region ../../src/orm/postgres/index.d.ts declare const AlephaOrmPostgres: import("alepha").Service<import("alepha").Module>; //#endregion export { AlephaOrmPostgres, BunPostgresProvider, CloudflareHyperdriveProvider, NodePostgresProvider, PgLiteModule, PglitePostgresProvider, PostgresModelBuilder, PostgresProvider, byte, postgresEnvSchema }; //# sourceMappingURL=index.d.ts.map