import { Table } from '@uwdata/flechette'; export { Table, tableFromArrays, tableFromIPC, tableToIPC } from '@uwdata/flechette'; /** * Ducklings Workers - Minimal DuckDB for Cloudflare Workers * * This package provides a lightweight DuckDB binding for WebAssembly, * designed for Cloudflare Workers. * * IMPORTANT: In this build, query() and execute() are async and return Promises. * Always use: `await conn.query(...)` or `await conn.execute(...)` * * @packageDocumentation */ /** * DuckDB type constants mapping to the C API type IDs. * @category Types */ declare const DuckDBType: { readonly INVALID: 0; readonly BOOLEAN: 1; readonly TINYINT: 2; readonly SMALLINT: 3; readonly INTEGER: 4; readonly BIGINT: 5; readonly UTINYINT: 6; readonly USMALLINT: 7; readonly UINTEGER: 8; readonly UBIGINT: 9; readonly FLOAT: 10; readonly DOUBLE: 11; readonly TIMESTAMP: 12; readonly DATE: 13; readonly TIME: 14; readonly INTERVAL: 15; readonly HUGEINT: 16; readonly UHUGEINT: 32; readonly VARCHAR: 17; readonly BLOB: 18; readonly DECIMAL: 19; readonly TIMESTAMP_S: 20; readonly TIMESTAMP_MS: 21; readonly TIMESTAMP_NS: 22; readonly ENUM: 23; readonly LIST: 24; readonly STRUCT: 25; readonly MAP: 26; readonly ARRAY: 33; readonly UUID: 27; readonly UNION: 28; readonly BIT: 29; readonly TIME_TZ: 30; readonly TIMESTAMP_TZ: 31; }; /** * Type ID from DuckDB type constants. * @category Types */ type DuckDBTypeId = (typeof DuckDBType)[keyof typeof DuckDBType]; /** * Database access mode. * @category Configuration */ declare enum AccessMode { /** DuckDB determines mode based on context (resolves to READ_WRITE for in-memory) */ AUTOMATIC = "automatic", /** Read-only mode - all write operations are blocked */ READ_ONLY = "read_only", /** Read-write mode - allows both reads and writes */ READ_WRITE = "read_write" } /** * DuckDB configuration options. * @category Configuration */ interface DuckDBConfig { /** * Database access mode. * Use READ_ONLY to prevent any data modification. * @default AccessMode.AUTOMATIC */ accessMode?: AccessMode; /** * Enable external access (file I/O, httpfs, etc.). * Set to false to prevent all external data access. * WARNING: Setting to false will disable httpfs functionality. * @default true */ enableExternalAccess?: boolean; /** * Lock configuration after startup. * Prevents runtime configuration changes via SQL SET commands. * @default true (secure default) */ lockConfiguration?: boolean; /** * Custom configuration options. * Key-value pairs passed directly to duckdb_set_config. * @see https://duckdb.org/docs/configuration/overview */ customConfig?: Record; } /** * Error thrown by DuckDB operations. * @category Types */ declare class DuckDBError extends Error { readonly code?: string; readonly query?: string; constructor(message: string, code?: string, query?: string); } /** * Options for SQL sanitization. * @category Security */ interface SanitizeSqlOptions { /** Allow PRAGMA statements (default: false) */ allowPragma?: boolean; /** Allow COPY ... TO statements (default: false) */ allowCopyTo?: boolean; /** Allow EXPORT DATABASE statements (default: false) */ allowExportDatabase?: boolean; /** Allow duckdb_secrets() function (default: false) */ allowSecretsFunction?: boolean; } /** * Result of SQL sanitization check. * @category Security */ interface SanitizeResult { /** Whether the SQL is considered safe */ safe: boolean; /** The original SQL string */ sql: string; /** Reason why the SQL was blocked (if unsafe) */ reason?: string; /** The pattern that matched (if unsafe) */ matchedPattern?: string; } /** * Checks if a SQL statement contains dangerous patterns. * * This function does not throw - it returns a result object indicating * whether the SQL is safe or not. Use this when you want to handle * unsafe SQL yourself. * * @category Security * @param sql - The SQL statement to check * @param options - Options to selectively allow certain patterns * @returns A SanitizeResult object with safety status * * @example * ```typescript * const result = checkSql("SELECT * FROM duckdb_secrets()"); * if (!result.safe) { * console.log(`Blocked: ${result.reason}`); * } * ``` */ declare function checkSql(sql: string, options?: SanitizeSqlOptions): SanitizeResult; /** * Sanitizes a SQL statement by checking for dangerous patterns. * * This function throws a DuckDBError if the SQL contains dangerous patterns. * Use this in request handlers to automatically reject unsafe queries. * * **Blocked patterns:** * - `duckdb_secrets()` - Exposes database credentials * - `PRAGMA` - Can modify database settings * - `COPY ... TO` - Writes files to disk (COPY FROM is allowed) * - `EXPORT DATABASE` - Exports database to files * * Note: SET commands are blocked separately by `lockConfiguration: true` in DuckDBConfig. * * @category Security * @param sql - The SQL statement to sanitize * @param options - Options to selectively allow certain patterns * @returns The original SQL if safe * @throws DuckDBError with code 'SANITIZE_ERROR' if dangerous patterns detected * * @example * ```typescript * import { sanitizeSql, DuckDBError } from '@ducklings/workers'; * * // In a request handler * try { * const safeSql = sanitizeSql(userInput); * const result = await conn.query(safeSql); * return Response.json({ data: result }); * } catch (e) { * if (e instanceof DuckDBError && e.code === 'SANITIZE_ERROR') { * return Response.json({ error: e.message }, { status: 400 }); * } * throw e; * } * ``` */ declare function sanitizeSql(sql: string, options?: SanitizeSqlOptions): string; /** * Column metadata for query results. * @category Types */ interface ColumnInfo { name: string; type: DuckDBTypeId; alias?: string; } /** * Options for initializing the DuckDB WASM module (workers build). * @category Types */ interface InitOptions { /** * Pre-compiled WebAssembly.Module (required for Cloudflare Workers) * In Workers, import the WASM file directly and pass it here. * * @example * ```typescript * import wasmModule from '@ducklings/workers/wasm'; * await init({ wasmModule }); * ``` */ wasmModule: WebAssembly.Module; /** Optional transport for httpfs requests; fixed for the module lifetime. */ httpFetch?: (url: string, init: RequestInit) => Promise; } /** * Initialize the DuckDB WASM module (workers build with Asyncify). * * This version is optimized for Cloudflare Workers and uses the workers-specific * WASM build that includes Asyncify support for async HTTP operations. * * @category Database * @param options - Initialization options with pre-compiled WASM module * @returns Promise that resolves when initialization is complete * * @example * ```typescript * import { init, DuckDB } from '@ducklings/workers'; * import wasmModule from '@ducklings/workers/wasm'; * * await init({ wasmModule }); * * const db = new DuckDB(); * const conn = db.connect(); * * // httpfs works in CF Workers with this build! * const result = await conn.query("SELECT * FROM 'https://example.com/data.parquet'"); * ``` */ declare function init(options: InitOptions): Promise; /** * Returns the DuckDB library version. * @category Database */ declare function version(): string; /** * A prepared SQL statement with parameter binding. * @category Query Results */ declare class PreparedStatement { private stmtPtr; private closed; private readonly sql; /** @internal */ constructor(stmtPtr: number, _connPtr: number, sql: string); parameterCount(): number; bindBoolean(index: number, value: boolean): this; bindInt32(index: number, value: number): this; bindInt64(index: number, value: bigint | number): this; bindFloat(index: number, value: number): this; bindDouble(index: number, value: number): this; bindString(index: number, value: string): this; bindBlob(index: number, value: Uint8Array): this; bindNull(index: number): this; bindTimestamp(index: number, value: Date): this; bindDate(index: number, value: Date): this; bind(index: number, value: unknown): this; /** * Executes the prepared statement and returns results as an array of objects. * @returns Promise resolving to array of result rows */ run>(): Promise; /** * Executes the prepared statement without returning results. * @returns Promise resolving to number of rows affected */ execute(): Promise; close(): void; } /** * A chunk of data from a streaming query result. * @category Query Results */ declare class DataChunk { private chunkPtr; private destroyed; private readonly columns; /** @internal */ constructor(chunkPtr: number, columns: ColumnInfo[]); get rowCount(): number; get columnCount(): number; getColumnInfo(): ColumnInfo[]; getColumn(columnIndex: number): unknown[]; toArray>(): T[]; private readVectorData; destroy(): void; } /** * A streaming query result that yields data in chunks. * @category Query Results */ declare class StreamingResult implements Iterable { private resultPtr; private closed; private readonly columns; private currentChunkIndex; private readonly totalChunks; /** @internal */ constructor(resultPtr: number, columns: ColumnInfo[]); getColumns(): ColumnInfo[]; get columnCount(): number; get chunkCount(): number; nextChunk(): DataChunk | null; reset(): void; [Symbol.iterator](): Iterator; toArray>(): T[]; /** * Converts the streaming result into a Flechette Arrow Table. * * Reads all remaining chunks and aggregates them into a single Arrow table. * DuckDB column types are mapped to the corresponding Flechette types. * * @returns A Flechette {@link Table} containing all result data * * @example * ```typescript * const stream = conn.queryStreaming('SELECT * FROM large_table'); * const arrowTable = stream.toArrowTable(); * console.log(arrowTable.numRows); * ``` */ toArrowTable(): Table; private getFlechetteType; close(): void; } /** * DuckDB database instance for Cloudflare Workers. * * @category Database * @example * ```typescript * import { init, DuckDB, AccessMode } from '@ducklings/workers'; * import wasmModule from '@ducklings/workers/wasm'; * * await init({ wasmModule }); * * // Default configuration (httpfs enabled, config locked) * const db = new DuckDB(); * * // Or with custom security configuration * const secureDb = new DuckDB({ * accessMode: AccessMode.READ_ONLY, * lockConfiguration: true, * }); * * const conn = db.connect(); * const result = await conn.query('SELECT 42 as answer'); * console.log(result); * * conn.close(); * db.close(); * ``` */ declare class DuckDB { private dbPtr; private closed; /** * Creates a new DuckDB database instance. * * @param config - Optional configuration options */ constructor(config?: DuckDBConfig); /** * Creates a new DuckDB database instance asynchronously. * * @param config - Optional configuration options */ static create(config?: DuckDBConfig): Promise; private getOpenModule; /** * Register an in-memory buffer as a file DuckDB can read by name. * * Useful when the bytes are already in hand — fetched from object storage through a * platform binding, say — and there is no URL DuckDB could `httpfs` instead. Mirrors * `registerFileBuffer` in `@ducklings/browser`, which has had this API all along. * * @param name - File name to register, optionally with directories * @param buffer - The file's contents * * @example * ```typescript * await db.registerFileBuffer('data.csv', new TextEncoder().encode('id\n1\n')); * const rows = await conn.query("SELECT * FROM read_csv('data.csv')"); * ``` */ registerFileBuffer(name: string, buffer: Uint8Array): Promise; /** * Register text as a file, encoded as UTF-8. * * @param name - File name to register * @param text - The file's contents */ registerFileText(name: string, text: string): Promise; /** * Read a registered file back out as bytes. * * The mirror of {@link registerFileBuffer}, and how a query's output leaves the * filesystem — `COPY (…) TO 'x.parquet'`, then this. * * @param name - File name to read * @returns The file's contents * * @example * ```typescript * await conn.query("COPY (SELECT 42 AS answer) TO 'out.parquet' (FORMAT PARQUET)"); * const bytes = await db.copyFileToBuffer('out.parquet'); * ``` */ copyFileToBuffer(name: string): Promise; /** * Remove a file registered with {@link registerFileBuffer}. * * @param name - File name to remove */ dropFile(name: string): Promise; connect(): Connection; close(): void; } /** * A connection to a DuckDB database (async API for Cloudflare Workers). * * All query methods in this class are async and return Promises. * @category Connection */ declare class Connection { private connPtr; private closed; /** @internal */ constructor(connPtr: number); /** * Executes a SQL query and returns the results. * This is async to support httpfs in Cloudflare Workers. * * @param sql - The SQL query to execute * @returns Promise resolving to array of result rows as objects */ query>(sql: string): Promise; private readColumnData; /** * Executes a SQL query and returns results as an Arrow table. * * @param sql - The SQL query to execute * @returns Promise resolving to Arrow Table */ queryArrow(sql: string): Promise; private getFlechetteType; /** * Executes a SQL statement without returning results. * * @param sql - The SQL statement to execute * @returns Promise resolving to number of rows affected */ execute(sql: string): Promise; /** * Creates a prepared statement for the given SQL. * * @param sql - The SQL statement to prepare (use ? for parameters) * @returns A PreparedStatement instance */ prepare(sql: string): PreparedStatement; /** * Prepares SQL asynchronously. * Required when binding may read remote metadata, such as a Parquet schema. */ prepareAsync(sql: string): Promise; beginTransaction(): Promise; commit(): Promise; rollback(): Promise; transaction(fn: () => Promise): Promise; /** * Insert data from an Arrow IPC stream buffer into a table. * * Creates a new table with the given name from the Arrow IPC data. If the table * already exists, the call is a no-op (uses `CREATE TABLE IF NOT EXISTS`). * * **Important:** The IPC stream must not contain dictionary-encoded columns. * Flechette's `tableFromArrays()` defaults to `dictionary(utf8())` for string * columns. Use explicit `utf8()` types to avoid this: * * @param tableName - The name of the table to create * @param ipcBuffer - Arrow IPC stream bytes (use `tableToIPC(table, { format: 'stream' })`) * @throws {@link DuckDBError} If the connection is closed or the IPC data is invalid * * @example * ```typescript * import { tableFromArrays, tableToIPC, utf8 } from '@ducklings/workers'; * * const table = tableFromArrays( * { id: [1, 2, 3], name: ['Alice', 'Bob', 'Charlie'] }, * { types: { name: utf8() } } // Required for string columns * ); * const ipcBuffer = tableToIPC(table, { format: 'stream' }); * await conn.insertArrowFromIPCStream('users', ipcBuffer); * ``` * * @category Data Insertion */ insertArrowFromIPCStream(tableName: string, ipcBuffer: Uint8Array): Promise; close(): void; } export { AccessMode, type ColumnInfo, Connection, DataChunk, DuckDB, type DuckDBConfig, DuckDBError, DuckDBType, type DuckDBTypeId, type InitOptions, PreparedStatement, type SanitizeResult, type SanitizeSqlOptions, StreamingResult, checkSql, init, sanitizeSql, version };