### INSTALL extension from URL
Source: https://github.com/duckdb/duckdb-wasm/blob/main/README.md
Defers fetching the extension to the first LOAD instruction. INSTALL x FROM community; shorthands are also supported.
```sql
INSTALL extension_name FROM 'https://repository.endpoint.org';
```
--------------------------------
### React DuckDB setup with DuckDBPlatform, DuckDBProvider, and DuckDBConnectionProvider
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/react-duckdb.md
This example shows how to initialize DuckDB in a React application. It imports the necessary modules and components, creates an App component that uses the useDuckDBConnection hook to check connection status, and exports a Root component that wraps the App with the required providers. The DuckDBPlatform is configured with a ConsoleLogger and bundles from getJsDelivrBundles, and the DuckDBProvider uses an in-memory database path.
```tsx
import React from 'react';
import * as duckdb from '@duckdb/duckdb-wasm';
import { DuckDBPlatform, DuckDBProvider, DuckDBConnectionProvider, useDuckDBConnection } from '@duckdb/react-duckdb';
const App = () => {
const conn = useDuckDBConnection(); // connection id 0
return
{conn ? 'connected' : 'connecting...'}
;
};
export const Root = () => (
);
```
--------------------------------
### Usage examples
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/async-duckdb.md
Basic lifecycle, error handling, and file registration examples for AsyncDuckDB.
```APIDOC
## Usage examples
### Basic lifecycle
```ts
import * as duckdb from '@duckdb/duckdb-wasm';
const JSDELIVR_BUNDLES = duckdb.getJsDelivrBundles();
const bundle = await duckdb.selectBundle(JSDELIVR_BUNDLES);
const worker_url = URL.createObjectURL(
new Blob([`importScripts("${bundle.mainWorker!}");`], { type: 'text/javascript' }),
);
const worker = new Worker(worker_url);
const logger = new duckdb.ConsoleLogger();
const db = new duckdb.AsyncDuckDB(logger, worker);
await db.instantiate(bundle.mainModule, bundle.pthreadWorker);
URL.revokeObjectURL(worker_url);
await db.open({ path: ':memory:' });
const conn = await db.connect();
const table = await conn.query(`SELECT count(*)::INTEGER v FROM generate_series(0, 100)`);
console.log(table.toArray());
await conn.close();
await db.terminate();
```
### Error handling
```ts
try {
await db.open({ path: ':memory:' });
const conn = await db.connect();
await conn.query(`SELECT * FROM missing_table`);
} catch (e: any) {
// e.name / e.message / e.stack mirror the original worker error
console.error(`query failed: ${e.message}`);
} finally {
await db.terminate();
}
```
### File registration with transfer buffers
```ts
const csvBytes = new TextEncoder().encode('1,foo\n2,bar\n');
await db.registerFileBuffer('data.csv', csvBytes); // transfers buffer.buffer
await db.registerFileHandle('local.parquet', file, duckdb.DuckDBDataProtocol.BROWSER_FILEREADER, true);
const conn = await db.connect();
await conn.insertCSVFromPath('data.csv', { name: 't', header: false, delimiter: ',' });
```
```
--------------------------------
### S3 helper usage example
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/utils.md
Demonstrates how to use getHTTPUrl and addS3Headers to perform an authenticated GET request for an S3 file.
```ts
import { getHTTPUrl, addS3Headers } from '@duckdb/duckdb-wasm/src/utils/s3_helper';
const s3: S3Config = { region: 'eu-west-1', accessKeyId: 'AK', secretAccessKey: 'SK', sessionToken: 'tok' };
const xhr = new XMLHttpRequest();
xhr.open('GET', getHTTPUrl(s3, 's3://bucket/path/file.parquet'), false);
addS3Headers(xhr, s3, 's3://bucket/path/file.parquet', 'GET');
xhr.send(null);
```
--------------------------------
### Load, autoload, and install DuckDB extensions
Source: https://github.com/duckdb/duckdb-wasm/blob/main/README.md
Shows how to explicitly load extensions with LOAD, trigger autoloading via DESCRIBE FROM read_parquet (which autoloads JSON), and register extensions with INSTALL from community or custom URLs before loading them.
```sql
--- Excplicitly load extensions
LOAD icu;
--- Or have them autoloaded when using relevant functions or settings
DESCRIBE FROM read_parquet('https://blobs.duckdb.org/stations.parquet'); -- (this autoloads JSON)
--- Or register extensions
INSTALL h3 FROM community;
INSTALL sqlite_scanner FROM 'https://extensions.duckdb.org';
INSTALL quack FROM 'https://community-extensions.duckdb.org';
--- And then load them
LOAD h3;
LOAD sqlite_scanner;
LOAD quack;
```
--------------------------------
### AsyncDuckDBConnection usage example
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/async-connection.md
Shows how to connect, run a materialized query with query(), stream results with send(), and close the connection. The example uses generate_series and logs row counts.
```typescript
import * as arrow from 'apache-arrow';
const conn = await db.connect();
// Materialized
const table = await conn.query<{ v: arrow.Int32 }>(`SELECT * FROM generate_series(1, 100) t(v)`);
console.log(table.numRows);
// Streamed, with typed schema
const reader = await conn.send<{ v: arrow.Int32 }>(`SELECT * FROM generate_series(1, 100000) t(v)`, true);
for await (const batch of reader) {
console.log('batch rows:', batch.numRows);
}
await conn.close();
```
--------------------------------
### PreparedStatement usage example
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/duckdb-connection.md
Demonstrates preparing a statement, executing it via query() for materialized results or send() for streaming, and closing resources.
```ts
const conn = bindings.connect();
const stmt = conn.prepare<{ v: arrow.Int32 }>(`SELECT v + ? FROM generate_series(0, 10000) AS t(v)`);
try {
const all = stmt.query(234).toArray(); // materialized
for await (const batch of stmt.send(234)) { /* streamed */ }
} finally {
stmt.close();
conn.close(); // closing the connection releases its statements as well
}
```
--------------------------------
### Open and reset example
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/duckdb-bindings.md
Opens an in-memory database with AUTOMATIC access mode, runs queries, then resets the database.
```typescript
bindings.open({ path: ':memory:', accessMode: duckdb.DuckDBAccessMode.AUTOMATIC });
// ... run queries ...
bindings.reset();
```
--------------------------------
### Example usage of arrowToSQLType and arrowToSQLField
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/json-typedef.md
Example usage of arrowToSQLType and arrowToSQLField with various Arrow types. Shows expected outputs and error handling for unsupported types. Requires deep import from the internal module.
```typescript
// (internal API — shown for reference)
import { arrowToSQLType, arrowToSQLField } from '@duckdb/duckdb-wasm/src/json_typedef';
import * as arrow from 'apache-arrow';
arrowToSQLType(new arrow.Int32()); // { sqlType: 'int32' }
arrowToSQLType(new arrow.Utf8()); // { sqlType: 'utf8' }
arrowToSQLField('col1', new arrow.Float64()); // { sqlType: 'float64', name: 'col1' }
try {
arrowToSQLType(new arrow.Unknown());
} catch (e) {
console.log(e.message); // "unsupported arrow type: ..."
}
```
--------------------------------
### Query execution usage example
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/duckdb-bindings.md
Shows how to run a simple query and use the streaming path with send(). The streaming path iterates over arrow.RecordBatch objects.
```TypeScript
const conn = bindings.connect();
const table = conn.query(`SELECT 42::INTEGER AS v`);
console.log(table.toArray());
// streaming path
const stream = conn.send(`SELECT * FROM generate_series(1, 100000)`, true);
for await (const batch of stream) { /* arrow.RecordBatch */ }
```
--------------------------------
### Usage: Load bundles and platform features
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/platform.md
Shows how to import the library, get CDN bundles, fetch platform features, and select a bundle. Also demonstrates manually configuring bundles for Node.js with local file paths.
```TypeScript
import * as duckdb from '@duckdb/duckdb-wasm';
const bundles = duckdb.getJsDelivrBundles(); // CDN URLs, no coi
const features = await duckdb.getPlatformFeatures(); // capability flags
const bundle = await duckdb.selectBundle(bundles); // coi > eh > mvp
if (features.wasmExceptions) console.log('modern wasm runtime');
// Serving workers manually: node example
const DUCKDB_DIST = path.dirname(require.resolve('@duckdb/duckdb-wasm'));
const cfg: duckdb.DuckDBBundles = {
mvp: { mainModule: path.join(DUCKDB_DIST, 'duckdb-mvp.wasm'),
mainWorker: path.join(DUCKDB_DIST, 'duckdb-node-mvp.worker.cjs') },
eh: { mainModule: path.join(DUCKDB_DIST, 'duckdb-eh.wasm'),
mainWorker: path.join(DUCKDB_DIST, 'duckdb-node-eh.worker.cjs') },
};
```
--------------------------------
### AsyncPreparedStatement Usage Example
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/async-connection.md
Demonstrates preparing a statement, executing a materialized query, and streaming results using AsyncPreparedStatement.
```ts
const stmt = await conn.prepare<{ v: arrow.Int32 }>(`SELECT v + ? FROM generate_series(0, 10000) AS t(v)`);
try {
console.log((await stmt.query(234)).toArray());
for await (const batch of await stmt.send(234)) { /* ... */ }
} finally {
await stmt.close();
await conn.close();
}
```
--------------------------------
### Build duckdb-wasm from source
Source: https://github.com/duckdb/duckdb-wasm/blob/main/README.md
Clone the duckdb-wasm repository, initialize and update its submodules, apply patches, and start a local development server. Run these commands in order from a terminal.
```shell
git clone https://github.com/duckdb/duckdb-wasm.git
cd duckdb-wasm
git submodule init
git submodule update
make apply_patches
make serve
```
--------------------------------
### AsyncDuckDB.startPendingQuery(conn, text, allowStreamResult?)
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/async-duckdb.md
Starts a pending query. Returns a Uint8Array or null if streaming is allowed.
```APIDOC
## AsyncDuckDB.startPendingQuery(conn, text, allowStreamResult?)
### Description
Starts a pending query. Returns a Uint8Array or null if streaming is allowed.
### Method
startPendingQuery
### Parameters
- **conn** (ConnectionID) - Required - Connection ID
- **text** (string) - Required - SQL query text
- **allowStreamResult** (boolean) - Optional - Whether to allow streaming result
### Returns
Promise
```
--------------------------------
### Initialize DuckDB-WASM and run a query in the browser
Source: https://github.com/duckdb/duckdb-wasm/blob/main/examples/bare-browser/index.html
Imports the DuckDB-WASM module, selects a bundle with MVP and EH variants, creates a worker, instantiates the database, runs a count query, and cleans up. Use this as a starting point for browser-based DuckDB-WASM applications.
```javascript
import * as duckdb from './duckdb-browser.mjs';
(async () => {
try {
const DUCKDB_CONFIG = await duckdb.selectBundle({
mvp: {
mainModule: './duckdb.wasm',
mainWorker: './duckdb-browser.worker.js',
},
eh: {
mainModule: './duckdb-eh.wasm',
mainWorker: './duckdb-browser-eh.worker.js',
},
});
const logger = new duckdb.ConsoleLogger();
const worker = new Worker(DUCKDB_CONFIG.mainWorker);
const db = new duckdb.AsyncDuckDB(logger, worker);
await db.instantiate(DUCKDB_CONFIG.mainModule, DUCKDB_CONFIG.pthreadWorker);
const conn = await db.connect();
await conn.query(`SELECT count(*)::INTEGER as v FROM generate_series(0, 100) t(v)`);
await conn.close();
await db.terminate();
await worker.terminate();
} catch (e) {
console.error(e);
}
})();
```
--------------------------------
### Concrete DuckDB Class Implementation
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/bindings-variants.md
Example of a concrete DuckDB class implementation in bindings_browser_mvp.ts, showing how it instantiates the DuckDBWasm wrapper.
```ts
// bindings_browser_mvp.ts
export class DuckDB extends DuckDBBrowserBindings {
public constructor(
logger: Logger,
runtime: DuckDBRuntime,
mainModuleURL: string,
pthreadWorkerURL: string | null = null,
) { super(logger, runtime, mainModuleURL, pthreadWorkerURL); }
protected instantiateImpl(moduleOverrides: Partial): Promise {
return DuckDBWasm({
...moduleOverrides,
instantiateWasm: this.instantiateWasm.bind(this),
locateFile: this.locateFile.bind(this),
});
}
}
```
--------------------------------
### Usage example: custom logger and ConsoleLogger with AsyncDuckDB
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/logging.md
Shows how to use the logging module: create a custom logger to silence output, or use ConsoleLogger with a specific level (e.g., WARNING). Pass the logger to AsyncDuckDB and instantiate it; note that AsyncDuckDBConnection.query() emits LogOrigin.ASYNC_DUCKDB / LogTopic.QUERY / LogEvent.RUN entries.
```typescript
import * as duckdb from '@duckdb/duckdb-wasm';
// Silence: use a custom logger
const logger: duckdb.Logger = { log: (entry) => console.log(duckdb.getLogOriginLabel(entry.origin), entry.value) };
// Console logging at WARNING and above
const warnLogger = new duckdb.ConsoleLogger(duckdb.LogLevel.WARNING);
const db = new duckdb.AsyncDuckDB(warnLogger, worker);
await db.instantiate(bundle.mainModule, bundle.pthreadWorker);
// AsyncDuckDBConnection.query() emits LogOrigin.ASYNC_DUCKDB / LogTopic.QUERY / LogEvent.RUN entries
```
--------------------------------
### Materialized Query Example
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/duckdb-connection.md
Demonstrates executing a query that returns a materialized table. The result is processed synchronously using the query method.
```ts
import * as arrow from 'apache-arrow';
const conn = bindings.connect();
try {
const table = conn.query<{ v: arrow.Int32 }>(`SELECT * FROM generate_series(1, 100) t(v)`);
for (const row of table.toArray()) console.log(row);
} finally {
conn.close();
}
```
--------------------------------
### Insert Parquet Files from Various Sources
Source: https://github.com/duckdb/duckdb-wasm/blob/main/packages/duckdb-wasm/README.md
Registers Parquet files from a user-picked file, a URL, and a fetched buffer. The example shows three registration methods: registerFileHandle, registerFileURL, and registerFileBuffer.
```TypeScript
// ..., from Parquet files
const pickedFile: File = letUserPickFile();
await db.registerFileHandle('local.parquet', pickedFile, DuckDBDataProtocol.BROWSER_FILEREADER, true);
await db.registerFileURL('remote.parquet', 'https://origin/remote.parquet', DuckDBDataProtocol.HTTP, false);
const res = await fetch('https://origin/remote.parquet');
await db.registerFileBuffer('buffer.parquet', new Uint8Array(await res.arrayBuffer()));
```
--------------------------------
### Initialize DuckDB with full-featured configuration
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/configuration.md
Demonstrates opening a database with OPFS, HTTP tuning, and lossless Arrow conversion settings.
```ts
await db.open({
path: 'opfs://my/db.duckdb',
accessMode: duckdb.DuckDBAccessMode.READ_WRITE,
maximumThreads: 4,
useDirectIO: true,
allowUnsignedExtensions: true,
arrowLosslessConversion: true,
customUserAgent: 'my-app/1.0',
query: { castBigIntToDouble: false, castDecimalToDouble: false },
filesystem: { allowFullHTTPReads: true, forceFullHTTPReads: false },
opfs: { fileHandling: 'auto' },
});
```
--------------------------------
### Custom runtime example
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/runtimes.md
Example of supplying a custom runtime to createDuckDB. It spreads DEFAULT_RUNTIME and overrides testPlatformFeature and getDefaultDataProtocol. The custom runtime is passed as the third argument to createDuckDB.
```ts
import { DuckDBRuntime, DEFAULT_RUNTIME } from '@duckdb/duckdb-wasm';
const myRuntime: DuckDBRuntime = {
...DEFAULT_RUNTIME,
testPlatformFeature: (_mod, feature) => feature === 7,
getDefaultDataProtocol: () => 0,
};
const bindings = await createDuckDB(bundles, logger, myRuntime);
```
--------------------------------
### Basic AsyncDuckDB lifecycle
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/async-duckdb.md
Demonstrates the standard lifecycle of an AsyncDuckDB instance, including bundle selection, worker initialization, database connection, and query execution.
```ts
import * as duckdb from '@duckdb/duckdb-wasm';
const JSDELIVR_BUNDLES = duckdb.getJsDelivrBundles();
const bundle = await duckdb.selectBundle(JSDELIVR_BUNDLES);
const worker_url = URL.createObjectURL(
new Blob([`importScripts("${bundle.mainWorker!}");`], { type: 'text/javascript' }),
);
const worker = new Worker(worker_url);
const logger = new duckdb.ConsoleLogger();
const db = new duckdb.AsyncDuckDB(logger, worker);
await db.instantiate(bundle.mainModule, bundle.pthreadWorker);
URL.revokeObjectURL(worker_url);
await db.open({ path: ':memory:' });
const conn = await db.connect();
const table = await conn.query(`SELECT count(*)::INTEGER v FROM generate_series(0, 100)`);
console.log(table.toArray());
await conn.close();
await db.terminate();
```
--------------------------------
### class PreparedStatement
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/duckdb-connection.md
Represents a prepared SQL statement. Provides methods to close the statement, execute the query and get a materialized Arrow table, or send the query and get a stream of record batches.
```APIDOC
## class PreparedStatement
### Description
Represents a prepared SQL statement. Provides methods to close the statement, execute the query and get a materialized Arrow table, or send the query and get a stream of record batches.
### Constructor
- `constructor(bindings: DuckDBBindings, connectionId: number, statementId: number)` - Creates a new PreparedStatement. `bindings` is the DuckDB bindings, `connectionId` is the connection ID, `statementId` is the statement ID.
### Methods
#### close()
- **Signature**: `close(): void`
- **Description**: Closes the prepared statement, releasing resources. Calls `bindings.closePrepared(connectionId, statementId)`.
#### query(...params)
- **Signature**: `query(...params: any[]): arrow.Table`
- **Description**: Executes the prepared statement with the given positional bind values and returns a materialized Arrow table. The bind values are JSON-serialized by the bindings layer.
- **Parameters**:
- `...params` (any[]) - Positional bind values referenced by `?` markers in the SQL text.
- **Returns**: `arrow.Table` - Materialized Arrow IPC file reader wrapped in a Table.
#### send(...params)
- **Signature**: `send(...params: any[]): arrow.RecordBatchStreamReader`
- **Description**: Executes the prepared statement with the given positional bind values and returns a stream of record batches. The bind values are JSON-serialized by the bindings layer.
- **Parameters**:
- `...params` (any[]) - Positional bind values referenced by `?` markers in the SQL text.
- **Returns**: `arrow.RecordBatchStreamReader` - Header + `ResultStreamIterator` as a stream.
### Example
ts
const conn = bindings.connect();
const stmt = conn.prepare<{ v: arrow.Int32 }>(`SELECT v + ? FROM generate_series(0, 10000) AS t(v)`);
try {
const all = stmt.query(234).toArray(); // materialized
for await (const batch of stmt.send(234)) { /* streamed */ }
} finally {
stmt.close();
conn.close(); // closing the connection releases its statements as well
}
```
--------------------------------
### Registering a custom worker dispatcher
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/worker-dispatcher.md
An illustrative example of how to register an AsyncDuckDBDispatcher on globalThis.onmessage within a worker script.
```ts
// my-worker.js — registers a dispatcher on globalThis.onmessage
import { AsyncDuckDBDispatcher } from '@duckdb/duckdb-wasm';
// In practice the shipped workers wire `instantiate`/`postMessage` to
// BROWSER_RUNTIME/NODE_RUNTIME and DuckDB(MVP|EH|COI).
globalThis.onmessage = async (event) => {
await myDispatcher.onMessage(event.data);
};
```
--------------------------------
### DuckDBBindingsBase.instantiate
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/duckdb-bindings.md
Downloads/compiles the Wasm module, runs onRuntimeInitialized and stores itself on globalThis.DUCKDB_BINDINGS. If the instance is already open it returns immediately.
```APIDOC
## instantiate(onProgress)
### Description
Downloads/compiles the Wasm module, runs `onRuntimeInitialized` and stores itself on `globalThis.DUCKDB_BINDINGS`. If the instance is already open (`_instance != null`) it returns immediately. Progress callbacks registered while an instantiation is in flight are appended and awaited. Returns the instance itself.
### Method
async
### Parameters
- `onProgress` (function) - Optional - Called with `InstantiationProgress { startedAt, updatedAt, bytesTotal, bytesLoaded }` periodically during module download.
### Returns
`Promise` - The instance itself.
### Throws
Any error produced by the underlying `DuckDBWasm({...})` instantiation (network failures, Wasm parse/instantiation errors).
### Example
```ts
import * as duckdb from '@duckdb/duckdb-wasm/dist/duckdb-browser-blocking';
import { BROWSER_RUNTIME } from '@duckdb/duckdb-wasm/dist/duckdb-browser-blocking';
import { getJsDelivrBundles } from '@duckdb/duckdb-wasm';
const bundles = getJsDelivrBundles();
const bindings = await duckdb.createDuckDB(bundles, new duckdb.ConsoleLogger(), BROWSER_RUNTIME);
await bindings.instantiate((p) => console.log(`${p.bytesLoaded}/${p.bytesTotal} bytes`));
bindings.open({ path: ':memory:' });
```
```
--------------------------------
### DuckDB-Wasm File Registration and Management
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/duckdb-bindings-file-api.md
Demonstrates initializing the DuckDB-Wasm browser runtime, registering files from different sources, executing SQL queries, and performing filesystem operations.
```ts
import * as arrow from 'apache-arrow';
import { BROWSER_RUNTIME } from '@duckdb/duckdb-wasm';
// Blocking entry point for the browser
import { createDuckDB, ConsoleLogger, DuckDBConnection, DuckDBDataProtocol } from '@duckdb/duckdb-wasm/dist/duckdb-browser-blocking';
import { getJsDelivrBundles } from '@duckdb/duckdb-wasm';
const bindings = await createDuckDB(getJsDelivrBundles(), new ConsoleLogger(), BROWSER_RUNTIME);
await bindings.instantiate();
bindings.open({ path: ':memory:' });
// Text / buffer / URL registration
bindings.registerFileText('data.csv', '1|foo\n2|bar\n');
bindings.registerFileBuffer('data.parquet', new Uint8Array(await (await fetch('/data.parquet')).arrayBuffer()));
bindings.registerFileURL('remote.parquet', 'https://origin/remote.parquet', DuckDBDataProtocol.HTTP, false);
// Browser File object (HTML5 file reader)
const picked: File = fileInput.files![0];
bindings.registerFileHandle('local.parquet', picked, DuckDBDataProtocol.BROWSER_FILEREADER, true);
// Use from SQL
const conn: DuckDBConnection = bindings.connect();
await conn.query(`CREATE TABLE t AS SELECT * FROM read_csv('data.csv')`);
// Filesystem helpers
const infos = bindings.globFiles('/data/');
bindings.copyFileToBuffer('data.csv');
bindings.dropFile('data.csv');
bindings.dropFiles(['data.parquet', 'remote.parquet']);
// Statistics
bindings.collectFileStatistics('local.parquet', true);
const stats = bindings.exportFileStatistics('local.parquet');
console.log('cold reads:', stats.totalFileReadsCold);
```
--------------------------------
### AsyncDuckDB.instantiate(mainModuleURL, pthreadWorkerURL?, progress?)
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/async-duckdb.md
Instantiates the DuckDB module. Takes the main module URL, optional pthread worker URL, and a progress callback.
```APIDOC
## AsyncDuckDB.instantiate(mainModuleURL, pthreadWorkerURL?, progress?)
### Description
Instantiates the DuckDB module. Takes the main module URL, optional pthread worker URL, and a progress callback.
### Method
instantiate
### Parameters
- **mainModuleURL** (string) - Required - URL of the main module
- **pthreadWorkerURL** (string | null) - Optional - URL of the pthread worker
- **progress** (function) - Optional - Progress callback receiving InstantiationProgress
### Returns
Promise
```
--------------------------------
### Scalar UDF usage example
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/duckdb-bindings.md
Creates a scalar function 'inc' that increments an integer, then uses it in a SQL query.
```TypeScript
import * as arrow from 'apache-arrow';
conn.createScalarFunction('inc', new arrow.Int32(), (x: number) => x + 1);
conn.query(`SELECT inc(v) FROM (VALUES (1), (2)) t(v)`);
```
--------------------------------
### AsyncDuckDB.open(config)
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/async-duckdb.md
Opens a database with the given configuration.
```APIDOC
## AsyncDuckDB.open(config)
### Description
Opens a database with the given configuration.
### Method
open
### Parameters
- **config** (DuckDBConfig) - Required - Configuration for the database
### Returns
Promise
```
--------------------------------
### instantiate method signature
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/duckdb-bindings.md
Downloads/compiles the Wasm module, runs onRuntimeInitialized, and stores itself on globalThis.DUCKDB_BINDINGS. Returns immediately if already open.
```typescript
public async instantiate(onProgress: (progress: InstantiationProgress) => void = _ => {}): Promise
```
--------------------------------
### Progress, tokens, and WebFile interfaces
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/types.md
Defines interfaces for progress reporting, tokenization, and file handling. `InstantiationProgress` is used by `instantiate(onProgress)` and `AsyncDuckDB.instantiate(progress)`; `ScriptTokens` is returned by `bindings.tokenize(text)`; `WebFile` is returned by `globFiles(path)`.
```ts
// src/bindings/progress.ts
export interface InstantiationProgress { startedAt: Date; updatedAt: Date; bytesTotal: number; bytesLoaded: number; }
export type InstantiationProgressHandler = (p: InstantiationProgress) => void;
// src/bindings/tokens.ts
export interface ScriptTokens { offsets: number[]; types: TokenType[]; }
// src/bindings/web_file.ts
export interface WebFile {
fileName: string;
dataProtocol: DuckDBDataProtocol;
fileId?: number;
fileSize?: number;
dataUrl?: string;
dataNativeFd?: number;
collectStatistics?: boolean;
reliableHeadRequests?: boolean;
allowFullHttpReads?: boolean;
}
```
--------------------------------
### registerOPFSFileName signature
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/duckdb-bindings-file-api.md
If file starts with 'opfs://', forwards to prepareFileHandle with BROWSER_FSACCESS; otherwise throws Error('Not an OPFS file name: ' + file).
```typescript
public async registerOPFSFileName(file: string): Promise
```
--------------------------------
### Instantiate with static served files
Source: https://github.com/duckdb/duckdb-wasm/blob/main/packages/duckdb-wasm/README.md
Manually defines DuckDBBundles with placeholder paths for statically served files. Requires downloading the dist files from the CDN and adjusting paths. Uses selectBundle() and instantiates AsyncDuckDB.
```ts
import * as duckdb from '@duckdb/duckdb-wasm';
const MANUAL_BUNDLES: duckdb.DuckDBBundles = {
mvp: {
mainModule: 'change/me/../duckdb-mvp.wasm',
mainWorker: 'change/me/../duckdb-browser-mvp.worker.js',
},
eh: {
mainModule: 'change/m/../duckdb-eh.wasm',
mainWorker: 'change/m/../duckdb-browser-eh.worker.js',
},
};
// Select a bundle based on browser checks
const bundle = await duckdb.selectBundle(MANUAL_BUNDLES);
// Instantiate the asynchronous version of DuckDB-wasm
const worker = new Worker(bundle.mainWorker!);
const logger = new duckdb.ConsoleLogger();
const db = new duckdb.AsyncDuckDB(logger, worker);
await db.instantiate(bundle.mainModule, bundle.pthreadWorker);
```
--------------------------------
### OPFS auto file handling
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/async-duckdb.md
Describes how runQuery and startPendingQuery handle OPFS files automatically when the database path starts with opfs:// and config.opfs.fileHandling is set to auto.
```APIDOC
## OPFS auto file handling
### Description
runQuery and startPendingQuery consult shouldOPFSFileHandling(): when the configured database path starts with opfs:// and config.opfs?.fileHandling === "auto", the SQL text is scanned for 'opfs://...' literals (searchOPFSFiles), each match is registered via registerOPFSFileName before execution, and all of them are dropped again in a finally block. Registration failure throws Error("File Not found:" + file). fileHandling: "manual" or a non-OPFS path skips this entirely.
```
--------------------------------
### instantiate
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/async-duckdb.md
Registers a progress callback and sends an INSTANTIATE request to the worker to instantiate the Wasm module. The worker responds with INSTANTIATE_PROGRESS messages while downloading, and progress callbacks are reset when the request completes.
```APIDOC
## instantiate
### Description
Registers the progress callback and sends an INSTANTIATE request [mainModuleURL, pthreadWorkerURL] to the worker. The worker instantiates the Wasm module and answers INSTANTIATE_PROGRESS messages while downloading. Progress callbacks are reset when the request completes.
### Method
async
### Signature
```ts
public async instantiate(
mainModuleURL: string,
pthreadWorkerURL: string | null = null,
progress: (progress: InstantiationProgress) => void = _p => {},
): Promise
```
### Parameters
- **mainModuleURL** (string) - Required - The URL of the main Wasm module.
- **pthreadWorkerURL** (string | null) - Optional - The URL of the pthread worker, defaults to null.
- **progress** (function) - Optional - Callback receiving InstantiationProgress, defaults to a no-op.
### Returns
Promise - Resolves when instantiation completes.
```
--------------------------------
### Version constants: Package version parts
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/platform.md
Exports package name and version constants derived from config, with major, minor, and patch parts. Example values are shown in comments.
```TypeScript
// src/version.ts
export const PACKAGE_NAME = config.name; // "@duckdb/duckdb-wasm"
export const PACKAGE_VERSION = config.version; // "1.11.0"
export const PACKAGE_VERSION_MAJOR = VERSION_PARTS[0]; // "1"
export const PACKAGE_VERSION_MINOR = VERSION_PARTS[1]; // "11"
export const PACKAGE_VERSION_PATCH = VERSION_PARTS[2]; // "0"
```
--------------------------------
### AsyncDuckDBConnection.prepare()
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/async-connection.md
Prepares a SQL statement and returns an AsyncPreparedStatement handle.
```APIDOC
## AsyncDuckDBConnection.prepare()
### Description
Prepares a SQL statement and returns an AsyncPreparedStatement handle.
### Parameters
- **text** (string) - Required - The SQL statement to prepare.
### Returns
- **Promise>** - A prepared statement handle.
### Example
```ts
const stmt = await conn.prepare('SELECT * FROM my_table WHERE id = ?');
```
```
--------------------------------
### Insert Data from a JavaScript Array
Source: https://github.com/duckdb/duckdb-wasm/blob/main/packages/duckdb-wasm/README.md
Encodes a JavaScript array as JSON, registers it as a file buffer, and inserts it with schema and name options. The example uses TextEncoder to convert the array to a buffer.
```TypeScript
// ... from a Javascript array
const myArray = [
{
name: 'Dan',
age: 32,
numberOfPets: 3
}
];
const encoder = new TextEncoder();
const buffer = encoder.encode(myArray);
await db.registerFileBuffer(myTableName, buffer);
await c.insertJSONFromPath(myTableName, {
schema: 'main',
name: 'foo',
});
```
--------------------------------
### AsyncDuckDB.createPrepared(conn, text)
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/async-duckdb.md
Creates a prepared statement and returns its ID.
```APIDOC
## AsyncDuckDB.createPrepared(conn, text)
### Description
Creates a prepared statement and returns its ID.
### Method
createPrepared
### Parameters
- **conn** (number) - Required - Connection ID
- **text** (string) - Required - SQL text
### Returns
Promise
```
--------------------------------
### Insert JSON Data in Row-Major and Column-Major Formats
Source: https://github.com/duckdb/duckdb-wasm/blob/main/packages/duckdb-wasm/README.md
Registers JSON files in both row-major and column-major formats and inserts them with typed options. The example shows two separate registerFileText calls and two insertJSONFromPath calls.
```TypeScript
// ..., from JSON documents in row-major format
await db.registerFileText(
'rows.json',
`[
{ "col1": 1, "col2": "foo" },
{ "col1": 2, "col2": "bar" },
]`,
);
// ... or column-major format
await db.registerFileText(
'columns.json',
`{
"col1": [1, 2],
"col2": ["foo", "bar"]
}`,
);
// ... with typed insert options
await c.insertJSONFromPath('rows.json', { name: 'rows' });
await c.insertJSONFromPath('columns.json', { name: 'columns' });
```
--------------------------------
### prepareFileHandleAsync signature
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/duckdb-bindings-file-api.md
Resolves a handle for BROWSER_FSACCESS protocol. Returns FileSystemSyncAccessHandle as-is, attempts createSyncAccessHandle for FileSystemFileHandle, or uses navigator.storage.getDirectory() for named handles. Rethrows errors with the name appended.
```typescript
public async prepareFileHandleAsync(
name: string,
handle: HandleType,
protocol: DuckDBDataProtocol,
directIO: boolean,
): Promise
```
--------------------------------
### AsyncDuckDB.runPrepared(conn, statement, params)
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/async-duckdb.md
Runs a prepared statement with the given parameters.
```APIDOC
## AsyncDuckDB.runPrepared(conn, statement, params)
### Description
Runs a prepared statement with the given parameters.
### Method
runPrepared
### Parameters
- **conn** (number) - Required - Connection ID
- **statement** (number) - Required - Statement ID
- **params** (any[]) - Required - Parameters for the statement
### Returns
Promise
```
--------------------------------
### AsyncDuckDB.connect()
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/async-duckdb.md
Creates a new AsyncDuckDBConnection.
```APIDOC
## AsyncDuckDB.connect()
### Description
Creates a new AsyncDuckDBConnection.
### Method
connect
### Parameters
None
### Returns
Promise
```
--------------------------------
### Initialize DuckDB-Wasm instance
Source: https://github.com/duckdb/duckdb-wasm/blob/main/examples/plain-html/index.html
The getDb function handles bundle selection, worker instantiation, and asynchronous database initialization. It caches the database instance on the window object to prevent redundant initializations.
```javascript
const getDb = async () => { const duckdb = window.duckdbduckdbWasm; // @ts-ignore if (window._db) return window._db; const JSDELIVR_BUNDLES = duckdb.getJsDelivrBundles(); // Select a bundle based on browser checks const bundle = await duckdb.selectBundle(JSDELIVR_BUNDLES); const worker_url = URL.createObjectURL( new Blob([`importScripts("${bundle.mainWorker}");`], { type: "text/javascript", }) ); // Instantiate the asynchronous version of DuckDB-wasm const worker = new Worker(worker_url); // const logger = null //new duckdb.ConsoleLogger(); const logger = new duckdb.ConsoleLogger(); const db = new duckdb.AsyncDuckDB(logger, worker); await db.instantiate(bundle.mainModule, bundle.pthreadWorker); URL.revokeObjectURL(worker_url); window._db = db; return db; };
```
--------------------------------
### prepareFileHandle and prepareDBFileHandle signatures
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/duckdb-bindings-file-api.md
Both delegate to runtime methods when protocol is BROWSER_FSACCESS and the runtime implements the optional callback, re-registering returned PreparedDBFileHandle whose getSize() is truthy. For other protocols they throw unsupported protocol errors.
```typescript
public async prepareFileHandle(fileName: string, protocol: DuckDBDataProtocol): Promise
public async prepareDBFileHandle(path: string, protocol: DuckDBDataProtocol): Promise
```
--------------------------------
### AsyncDuckDBConnection.bindings (getter)
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/async-connection.md
Returns the underlying AsyncDuckDB instance.
```APIDOC
## AsyncDuckDBConnection.bindings (getter)
### Description
Returns the underlying AsyncDuckDB instance.
### Returns
- **AsyncDuckDB** - The underlying AsyncDuckDB instance.
### Example
```ts
const bindings = conn.bindings;
```
```
--------------------------------
### Instantiate with browser-blocking bundle
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/duckdb-bindings.md
Creates DuckDB bindings using the browser-blocking bundle, instantiates with progress logging, and opens an in-memory database.
```typescript
import * as duckdb from '@duckdb/duckdb-wasm/dist/duckdb-browser-blocking';
import { BROWSER_RUNTIME } from '@duckdb/duckdb-wasm/dist/duckdb-browser-blocking';
import { getJsDelivrBundles } from '@duckdb/duckdb-wasm';
const bundles = getJsDelivrBundles();
const bindings = await duckdb.createDuckDB(bundles, new duckdb.ConsoleLogger(), BROWSER_RUNTIME);
await bindings.instantiate((p) => console.log(`${p.bytesLoaded}/${p.bytesTotal} bytes`));
bindings.open({ path: ':memory:' });
```
--------------------------------
### DuckDBBindingsBase.open
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/duckdb-bindings.md
Serializes the config to JSON and calls the C function duckdb_web_open to open a database.
```APIDOC
## open(config)
### Description
Serializes the config to JSON and calls the C function `duckdb_web_open` to open a database.
### Method
void
### Parameters
- `config` (DuckDBConfig) - Required - See `configuration.md`.
### Throws
`Error` with the C-side message when the native call returns a status ≠ `StatusCode.SUCCESS`.
### Example
```ts
bindings.open({ path: ':memory:', accessMode: duckdb.DuckDBAccessMode.AUTOMATIC });
```
```
--------------------------------
### Prepared statement methods
Source: https://github.com/duckdb/duckdb-wasm/blob/main/_autodocs/api-reference/duckdb-bindings.md
Methods for creating, closing, and running prepared statements. createPrepared returns a numeric statement id; runPrepared returns an Arrow IPC file buffer; sendPrepared returns the stream header buffer. All throw Error on non-SUCCESS.
```TypeScript
public createPrepared(conn: number, text: string): number
public closePrepared(conn: number, statement: number): void
public runPrepared(conn: number, statement: number, params: any[]): Uint8Array
public sendPrepared(conn: number, statement: number, params: any[]): Uint8Array
```