@probitas/client-sql-duckdb
DuckDB client for Probitas scenario testing framework.
This package provides a DuckDB client designed for integration testing, with analytical query capabilities and Parquet/CSV file support.
Features
- Query Execution: Parameterized queries with type-safe results
- Transactions: Full transaction support
- File Formats: Native support for Parquet, CSV, and JSON files
- In-Memory Databases: Perfect for isolated test scenarios
- Analytical Queries: Optimized for OLAP workloads
- Resource Management: Implements
AsyncDisposablefor proper cleanup
Installation
deno add jsr:@probitas/client-sql-duckdb
Quick Start
import { createDuckDbClient } from "@probitas/client-sql-duckdb";
// In-memory database for testing
const client = await createDuckDbClient({
path: ":memory:",
});
// Query from Parquet files
const result = await client.query<{ id: number; name: string }>(
"SELECT id, name FROM read_parquet('data/*.parquet') WHERE active = ?",
[true]
);
console.log(result.rows);
// Analytical queries
const stats = await client.query(`
SELECT
date_trunc('month', created_at) as month,
COUNT(*) as count,
AVG(amount) as avg_amount
FROM transactions
GROUP BY 1
ORDER BY 1
`);
await client.close();
Transactions
import { createDuckDbClient } from "@probitas/client-sql-duckdb";
import type { SqlTransaction } from "@probitas/client-sql";
const client = await createDuckDbClient({ path: ":memory:" });
await client.transaction(async (tx: SqlTransaction) => {
await tx.query("INSERT INTO accounts (id, balance) VALUES (?, ?)", [1, 100]);
await tx.query("INSERT INTO accounts (id, balance) VALUES (?, ?)", [2, 200]);
// Automatically committed if no error, rolled back on exception
});
await client.close();
Using with using Statement
import { createDuckDbClient } from "@probitas/client-sql-duckdb";
await using client = await createDuckDbClient({ path: ":memory:" });
const result = await client.query("SELECT 42 as answer");
// Client automatically closed when block exits
Related Packages
| Package | Description |
|---|---|
| `@probitas/client-sql` | Common SQL types and utilities |
| `@probitas/client-sql-postgres` | PostgreSQL client |
| `@probitas/client-sql-mysql` | MySQL client |
| `@probitas/client-sql-sqlite` | SQLite client |
Links
Installation
deno add jsr:@probitas/client-sql-duckdbClasses
#CatalogError
class CatalogError extends DuckDbErrorDuckDbErrorError thrown for catalog errors (table not found, etc.).
| Name | Description |
|---|---|
name | — |
duckdbKind | — |
Constructor
new CatalogError(message: string, options?: DuckDbErrorOptions)Properties
- readonly
namestring - readonly
duckdbKind"catalog"
#ConstraintError
class ConstraintError extends SqlErrorSqlErrorError thrown when a constraint violation occurs.
| Name | Description |
|---|---|
name | — |
kind | — |
constraint | — |
Constructor
new ConstraintError(
message: string,
constraint: string,
options?: SqlErrorOptions,
)Properties
- readonly
namestring - readonly
kind"constraint" - readonly
constraintstring
#DeadlockError
class DeadlockError extends SqlErrorSqlErrorError thrown when a deadlock is detected.
Constructor
new DeadlockError(message: string, options?: SqlErrorOptions)Properties
- readonly
namestring - readonly
kind"deadlock"
#DuckDbError
class DuckDbError extends SqlErrorSqlErrorBase error class for DuckDB-specific errors. Extends SqlError with DuckDB-specific properties.
Constructor
new DuckDbError(message: string, options?: DuckDbErrorOptions)Properties
- readonly
namestring - readonly
errorType?string
#DuckDbTransactionImpl
class DuckDbTransactionImpl implements SqlTransactionSqlTransaction| Name | Description |
|---|---|
begin() | Begin a new transaction. |
query() | — |
queryOne() | — |
commit() | — |
rollback() | — |
Constructor
new DuckDbTransactionImpl(conn: DuckDBConnection)Methods
static begin(): unknownBegin a new transaction.
query(): unknownqueryOne(): unknowncommit(): unknownrollback(): unknown#IoError
class IoError extends DuckDbErrorDuckDbErrorError thrown for IO-related errors (file not found, permission denied, etc.).
| Name | Description |
|---|---|
name | — |
duckdbKind | — |
Constructor
new IoError(message: string, options?: DuckDbErrorOptions)Properties
- readonly
namestring - readonly
duckdbKind"io"
#QuerySyntaxError
class QuerySyntaxError extends SqlErrorSqlErrorError thrown when a SQL query has syntax errors.
Constructor
new QuerySyntaxError(message: string, options?: SqlErrorOptions)Properties
- readonly
namestring - readonly
kind"query"
#SqlConnectionError
class SqlConnectionError extends SqlErrorSqlErrorError thrown when a connection or network-level error occurs.
This includes:
- Connection refused (server not running)
- Authentication failure
- Connection timeout
- Pool exhaustion
- TLS handshake failure
- DNS resolution failure
Constructor
new SqlConnectionError(message: string, options?: SqlErrorOptions)Properties
- readonly
namestring - readonly
kind"connection"
#SqlError
class SqlError extends ClientErrorClientErrorBase error class for SQL-specific errors. Extends ClientError with SQL-specific properties.
Constructor
new SqlError(message: string, kind: SqlErrorKind, options?: SqlErrorOptions)Properties
- readonly
namestring - readonly
sqlStatestring | null
Interfaces
#DuckDbClient
interface DuckDbClient extends AsyncDisposableDuckDB client interface.
| Name | Description |
|---|---|
config | The client configuration. |
dialect | The SQL dialect identifier. |
query() | Execute a SQL query. |
queryOne() | Execute a query and return the first row or undefined. |
transaction() | Execute a function within a transaction. |
queryParquet() | Query a Parquet file directly. |
queryCsv() | Query a CSV file directly. |
close() | Close the database connection. |
Properties
The client configuration.
- readonly
dialect"duckdb"The SQL dialect identifier.
Methods
query<T = Record<string, any>>(
sql: string,
params?: unknown[],
options?: SqlQueryOptions,
): Promise<SqlQueryResult<T>>Execute a SQL query.
Parameters
sqlstring- SQL query string
params?unknown[]- Optional query parameters
options?SqlQueryOptions- Optional query options
queryOne<T = Record<string, any>>(
sql: string,
params?: unknown[],
options?: SqlQueryOptions,
): Promise<T | undefined>Execute a query and return the first row or undefined.
Parameters
sqlstring- SQL query string
params?unknown[]- Optional query parameters
options?SqlQueryOptions- Optional query options
transaction<T>(
fn: (tx: SqlTransaction) => unknown,
options?: SqlTransactionOptions | DuckDbTransactionOptions,
): Promise<T>Execute a function within a transaction. Automatically commits on success or rolls back on error.
Parameters
fn(tx: SqlTransaction) => unknown- Function to execute within transaction
- Transaction options
queryParquet<T = Record<string, any>>(path: string): Promise<SqlQueryResult<T>>Query a Parquet file directly. DuckDB can read Parquet files without importing them.
Parameters
pathstring- Path to the Parquet file
queryCsv<T = Record<string, any>>(path: string): Promise<SqlQueryResult<T>>Query a CSV file directly. DuckDB can read CSV files without importing them.
Parameters
pathstring- Path to the CSV file
close(): Promise<void>Close the database connection.
#DuckDbClientConfig
interface DuckDbClientConfig extends CommonOptionsConfiguration for creating a DuckDB client.
| Name | Description |
|---|---|
path | Database file path. |
readonly | Open the database in read-only mode. |
throwOnError | Whether to throw an error for query failures. |
Properties
- readonly
path?stringDatabase file path. Use
:memory:or omit for an in-memory database. - readonly
readonly?booleanOpen the database in read-only mode.
- readonly
throwOnError?booleanWhether to throw an error for query failures. When false, failures are returned as SqlQueryResultError or SqlQueryResultFailure. Can be overridden per-query via SqlQueryOptions.
#DuckDbErrorOptions
interface DuckDbErrorOptions extends SqlErrorOptionsOptions for DuckDbError constructor.
| Name | Description |
|---|---|
errorType | DuckDB error type if available. |
Properties
- readonly
errorType?stringDuckDB error type if available.
#DuckDbTransactionOptions
interface DuckDbTransactionOptions extends SqlTransactionOptionsDuckDB-specific transaction options.
#SqlErrorOptions
interface SqlErrorOptions extends ErrorOptionsOptions for SqlError constructor.
| Name | Description |
|---|---|
sqlState | SQL State code (e.g., "23505" for unique violation) |
Properties
- readonly
sqlState?stringSQL State code (e.g., "23505" for unique violation)
#SqlQueryOptions
interface SqlQueryOptions extends CommonOptionsOptions for individual SQL queries.
| Name | Description |
|---|---|
throwOnError | Whether to throw an error for query failures. |
Properties
- readonly
throwOnError?booleanWhether to throw an error for query failures. When false, failures are returned as SqlQueryResultError or SqlQueryResultFailure.
#SqlQueryResultError
interface SqlQueryResultError<T = any> extends SqlQueryResultBase<T>SQL query result for query errors (syntax errors, constraint violations, etc.).
Server received and processed the query, but it failed due to a SQL error.
| Name | Description |
|---|---|
processed | Server processed the query. |
ok | Query failed. |
error | Error describing the SQL error. |
rows | Empty rows for failed queries. |
rowCount | Zero affected rows for failed queries. |
lastInsertId | No lastInsertId for failed queries. |
warnings | No warnings for failed queries. |
Properties
- readonly
processedtrueServer processed the query.
- readonly
okfalseQuery failed.
Error describing the SQL error.
- readonly
rowsreadonly never[]Empty rows for failed queries.
- readonly
rowCount0Zero affected rows for failed queries.
- readonly
lastInsertIdnullNo lastInsertId for failed queries.
- readonly
warningsnullNo warnings for failed queries.
#SqlQueryResultFailure
interface SqlQueryResultFailure<T = any> extends SqlQueryResultBase<T>SQL query result for connection failures (network errors, timeouts, etc.).
Query could not be processed by the server (connection refused, timeout, pool exhausted, authentication failure, etc.).
| Name | Description |
|---|---|
processed | Server did not process the query. |
ok | Query failed. |
error | Error describing the failure. |
rows | No rows (query didn't reach server). |
rowCount | No row count (query didn't reach server). |
lastInsertId | No lastInsertId (query didn't reach server). |
warnings | No warnings (query didn't reach server). |
Properties
- readonly
processedfalseServer did not process the query.
- readonly
okfalseQuery failed.
Error describing the failure.
- readonly
rowsnullNo rows (query didn't reach server).
- readonly
rowCountnullNo row count (query didn't reach server).
- readonly
lastInsertIdnullNo lastInsertId (query didn't reach server).
- readonly
warningsnullNo warnings (query didn't reach server).
#SqlQueryResultSuccess
interface SqlQueryResultSuccess<T = any> extends SqlQueryResultBase<T>SQL query result for successful queries.
The query was executed successfully and returned results.
| Name | Description |
|---|---|
processed | Server processed the query. |
ok | Query succeeded. |
error | No error for successful queries. |
rows | Query result rows. |
rowCount | Number of affected rows. |
lastInsertId | Last inserted ID (for INSERT statements). |
warnings | Warning messages from the database. |
Properties
- readonly
processedtrueServer processed the query.
- readonly
oktrueQuery succeeded.
- readonly
errornullNo error for successful queries.
- readonly
rowsreadonly T[]Query result rows.
- readonly
rowCountnumberNumber of affected rows.
- readonly
lastInsertIdbigint | string | nullLast inserted ID (for INSERT statements).
- readonly
warningsunknown | nullWarning messages from the database.
#SqlQueryResultSuccessParams
interface SqlQueryResultSuccessParams<T = any>Parameters for creating a SqlQueryResultSuccess.
| Name | Description |
|---|---|
rows | The result rows |
rowCount | Number of affected rows (for INSERT/UPDATE/DELETE) |
duration | Query execution duration in milliseconds |
lastInsertId | Last inserted ID (for INSERT statements) |
warnings | Warning messages from the database |
Properties
- readonly
rowsreadonly T[]The result rows
- readonly
rowCountnumberNumber of affected rows (for INSERT/UPDATE/DELETE)
- readonly
durationnumberQuery execution duration in milliseconds
- readonly
lastInsertId?bigint | stringLast inserted ID (for INSERT statements)
- readonly
warnings?readonly string[]Warning messages from the database
#SqlTransaction
interface SqlTransactionSQL transaction interface. Implementations should provide actual database-specific transaction handling.
| Name | Description |
|---|---|
query() | Execute a query within the transaction. |
queryOne() | Execute a query and return the first row or undefined. |
commit() | Commit the transaction. |
rollback() | Rollback the transaction. |
Methods
query<T = Record<string, any>>(
sql: string,
params?: unknown[],
options?: SqlQueryOptions,
): Promise<SqlQueryResult<T>>Execute a query within the transaction.
Parameters
sqlstring- SQL query string
params?unknown[]- Optional query parameters
options?SqlQueryOptions- Optional query options
queryOne<T = Record<string, any>>(
sql: string,
params?: unknown[],
options?: SqlQueryOptions,
): Promise<T | undefined>Execute a query and return the first row or undefined.
Parameters
sqlstring- SQL query string
params?unknown[]- Optional query parameters
options?SqlQueryOptions- Optional query options
commit(): Promise<void>Commit the transaction.
rollback(): Promise<void>Rollback the transaction.
#SqlTransactionOptions
interface SqlTransactionOptionsOptions for starting a transaction.
| Name | Description |
|---|---|
isolationLevel | Isolation level for the transaction |
Properties
Isolation level for the transaction
Functions
#convertDuckDbError
function convertDuckDbError(error: unknown): SqlErrorConvert a DuckDB error to the appropriate error class.
DuckDB errors are classified based on message content analysis.
Parameters
errorunknown
#createDuckDbClient
async function createDuckDbClient(
config: DuckDbClientConfig,
): Promise<DuckDbClient>Create a new DuckDB client instance.
The client provides parameterized queries, transaction support, and DuckDB-specific features like direct Parquet and CSV file querying.
Parameters
configDuckDbClientConfig- DuckDB client configuration
Returns
Promise<DuckDbClient> — A promise resolving to a new DuckDB client instance
Examples
Using in-memory database (default)
import { createDuckDbClient } from "@probitas/client-sql-duckdb";
const client = await createDuckDbClient({});
const result = await client.query("SELECT 42 as answer");
if (result.ok) {
console.log(result.rows[0]); // { answer: 42 }
}
await client.close();
Using file-based database
import { createDuckDbClient } from "@probitas/client-sql-duckdb";
const client = await createDuckDbClient({
path: "./data.duckdb",
});
await client.close();
Query Parquet files directly
import { createDuckDbClient } from "@probitas/client-sql-duckdb";
const client = await createDuckDbClient({ path: ":memory:" });
// Query directly from Parquet
const result = await client.queryParquet<{ id: number; value: string }>(
"./data/events.parquet"
);
await client.close();
Query CSV files directly
import { createDuckDbClient } from "@probitas/client-sql-duckdb";
const client = await createDuckDbClient({ path: ":memory:" });
const result = await client.queryCsv<{ name: string; age: number }>(
"./data/users.csv"
);
await client.close();
Transaction with auto-commit/rollback
import { createDuckDbClient } from "@probitas/client-sql-duckdb";
import type { SqlTransaction } from "@probitas/client-sql";
const client = await createDuckDbClient({ path: ":memory:" });
await client.transaction(async (tx: SqlTransaction) => {
await tx.query("INSERT INTO users VALUES ($1, $2)", [1, "Alice"]);
await tx.query("INSERT INTO users VALUES ($1, $2)", [2, "Bob"]);
});
await client.close();
Using await using for automatic cleanup
import { createDuckDbClient } from "@probitas/client-sql-duckdb";
await using client = await createDuckDbClient({});
const result = await client.query("SELECT 1");
// Client automatically closed when scope exits
#isConnectionError
function isConnectionError(error: unknown): booleanCheck if an error is a connection-level error. These are errors that indicate the database cannot be accessed at all, not errors that occur during query execution.
Parameters
errorunknown
Types
#DuckDbErrorKind
type DuckDbErrorKind = "io" | "catalog" | "parser" | "binder"DuckDB-specific error kinds.
#SqlErrorKind
type SqlErrorKind = "query" | "constraint" | "deadlock" | "connection" | "unknown"SQL-specific error kinds.
#SqlFailureError
type SqlFailureError = SqlConnectionError | AbortError | TimeoutErrorError types that indicate the operation was not processed. These are errors that occur before the query reaches the SQL server.
#SqlIsolationLevel
type SqlIsolationLevel = "read_uncommitted" | "read_committed" | "repeatable_read" | "serializable"Transaction isolation level.
#SqlOperationError
type SqlOperationError = QuerySyntaxError | ConstraintError | DeadlockError | SqlErrorError types that indicate an operation was processed by the server. These errors occur after the query reaches the SQL server.
#SqlQueryResult
type SqlQueryResult<T = any> = SqlQueryResultSuccess<T> | SqlQueryResultError<T> | SqlQueryResultFailure<T>SQL query result union type representing all possible result states.
- Success:
processed: true, ok: true, error: null - Error:
processed: true, ok: false, error: SqlError - Failure:
processed: false, ok: false, error: SqlConnectionError
