@molecule/api-database-motherduck

Provider bond · database · API (Node) · v1.1.3 · Apache-2.0

MotherDuck hosted DuckDB database provider for molecule.dev — the same DuckDB SQL in the cloud, reached with an md: connection string

npm install @molecule/api-database-motherduck

npm · Source on GitHub · Implements @molecule/api-database

How it works

@molecule/api-database-motherduck is a provider bond on the API (Node) side: it implements the database core interface (@molecule/api-database) with a concrete vendor or library behind it.

Your code calls the core; you wire this provider once at startup. Swapping vendors later is one line in that wiring, not a rewrite.

import { setPool, setStore } from '@molecule/api-database'
import { pool, store } from '@molecule/api-database-motherduck'

setPool(pool)
setStore(store)

Works with: @molecule/api-bond, @molecule/api-database, @molecule/api-database-duckdb, @molecule/api-secrets

Secrets: MOTHERDUCK_TOKEN, MOTHERDUCK_DATABASE (optional)

Reference

MotherDuck database provider for molecule.dev — hosted DuckDB in the cloud, reached through the same @duckdb/node-api client with an md: connection string.

MotherDuck is built in partnership with DuckDB's creators and runs DuckDB SQL, so everything true of the @molecule/api-database-duckdb bond is true here — same placeholders, same DataStore, same migrations — with the database living in your MotherDuck account instead of a local file. Pick this bond when several processes or machines need one analytical database, or when the data is already in MotherDuck.

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

Quick Start

import { setPool, setStore } from '@molecule/api-database'
import { pool, store } from '@molecule/api-database-motherduck'

setPool(pool)
setStore(store)

Type

provider

Installation

npm install @molecule/api-database-motherduck @duckdb/node-api @molecule/api-bond @molecule/api-database @molecule/api-database-duckdb @molecule/api-secrets

API

Interfaces

MigrationOptions

Options for the migration runner.

interface MigrationOptions {
  /** Prefix for ledger keys when one database applies SQL from more than one directory. */
  namespace?: string
}

MotherduckConfig

Configuration for a MotherDuck-backed pool.

interface MotherduckConfig {
  /**
   * The `md:` connection string — `md:` (the account's default database) or
   * `md:<database>`. Extra parameters may be appended
   * (`md:my_db?session_name=…`). Defaults to the `MOTHERDUCK_DATABASE` env
   * var, then `md:`.
   */
  connectionString?: string
  /**
   * The MotherDuck token. Read lazily at first use, never at import time.
   * Defaults to the `MOTHERDUCK_TOKEN` env var (the client also auto-reads a
   * lowercase `motherduck_token` env var by itself — either works).
   */
  token?: string
  /**
   * Which env var holds the token (default `MOTHERDUCK_TOKEN`). Only useful
   * for one pool among several.
   */
  tokenEnv?: string
  /**
   * Extra DuckDB settings handed to `DuckDBInstance.fromCache(connectionString,
   * options)` as-is (`session_name`, `dbinstance_inactivity_ttl`,
   * `connection_timeout`, …). The `motherduck_token` entry is set by this bond.
   */
  config?: Record<string, string>
  /**
   * How long (ms) a query, `connect()` or `transaction()` waits for the single
   * connection before failing with an error that says who is holding it.
   * Defaults to 30 000.
   */
  acquireTimeoutMillis?: number
}

ProcessEnv

Environment variables consumed by the MotherDuck database provider.

interface ProcessEnv {
  MOTHERDUCK_TOKEN?: string
  MOTHERDUCK_DATABASE?: string
}

Functions

createStore(pool)

Creates a DataStore backed by a DuckDB DatabasePool.

function createStore(pool: DatabasePool): DataStore
  • pool — The DuckDB DatabasePool to use for queries.

Returns: A DataStore that translates CRUD operations to DuckDB-compatible SQL.

defaultPoolCreated()

Whether the lazy default pool has been created.

Readiness and shutdown wiring must not FORCE a connection.

function defaultPoolCreated(): boolean

Returns: true once the default pool exists.

closeDefaultPool()

Close the lazy default pool, if it was created.

function closeDefaultPool(): Promise<void>

Returns: Resolves once the pool has ended.

runMigrationsOn(pool, migrationsDir, options)

Apply every migration file in migrationsDir to pool, in lexical order — the duckdb bond's applyMigrations, unchanged (same ledger, same translation, same error contract).

function runMigrationsOn(
  pool: MigratablePool,
  migrationsDir: string,
  options?: MigrationOptions,
): Promise<void>
  • pool — The MotherDuck pool to migrate.
  • migrationsDir — Absolute path to the directory of ordered *.sql files.
  • options — Ledger namespace for multi-directory apps.

Returns: Resolves when every file is applied or recorded.

createMigrator(migrationsDir, options)

Returns a runMigrations() bound to a migrations directory and the DEFAULT MotherDuck pool (connection string from MOTHERDUCK_DATABASE).

function createMigrator(migrationsDir: string, options?: MigrationOptions): () => Promise<void>
  • migrationsDir — Absolute path to the directory of ordered *.sql migration files, resolved from the API package directory.
  • options — A stable namespace for a second SQL directory.

Returns: A no-arg runMigrations() that connects to MotherDuck and applies every migration file in lexical order.

chooseConnectionString(config)

Resolve the md: connection string: config, then MOTHERDUCK_DATABASE, then md:.

function chooseConnectionString(config?: MotherduckConfig): string
  • config — Pool configuration.

Returns: The connection string.

resolveToken(config)

Resolve the token from config or the env var, lazily — never at import time. undefined when the caller must fall back to the client's own auto-read of a lowercase motherduck_token env var.

function resolveToken(config?: MotherduckConfig): string | undefined
  • config — Pool configuration.

Returns: The token, or undefined when nothing is set.

createPool(config)

Creates a DatabasePool backed by MotherDuck.

The connection opens on first use, not here, so creating a pool is free and synchronous. The instance is opened through DuckDBInstance.fromCache — mandatory per MotherDuck's docs: the Node client does NOT cache instances by default, and every bare create('md:…') re-fetches the catalog.

function createPool(config?: MotherduckConfig): DatabasePool
  • config — Connection string, token and wait timeout.

Returns: A pool over one long-lived MotherDuck connection.

Constants

sqlCapabilities

What the MotherDuck bond supports from PostgreSQL-dialect migrations.

Identical to the DuckDB bond: the engine is the same, so a referential action (ON DELETE/ON UPDATE CASCADE, SET NULL, SET DEFAULT) is unsupported and partial indexes are translated without changing behaviour.

const sqlCapabilities: SqlCapabilities

pool

The MotherDuck connection pool instance.

const pool: DatabasePool

store

Default DataStore proxy backed by the lazily-initialized default pool.

const store: DataStore

DEFAULT_TOKEN_ENV

The env var this bond reads the token from by default.

const DEFAULT_TOKEN_ENV: 'MOTHERDUCK_TOKEN'

databaseMotherduckSecretDefinitions

Secret definitions required by the MotherDuck database bond.

const databaseMotherduckSecretDefinitions: SecretDefinition[]

Core Interface

Implements @molecule/api-database interface.

Bond Wiring

Setup function to register this provider with the core interface:

import { setPool, setStore } from '@molecule/api-database'
import { pool, store } from '@molecule/api-database-motherduck'

export function setupDatabaseMotherduck(): void {
  setPool(pool)
  setStore(store)
}

Injection Notes

Requirements

Peer dependencies:

  • @molecule/api-bond ^1.0.1
  • @molecule/api-database ^1.2.0
  • @molecule/api-database-duckdb ^1.0.0
  • @molecule/api-secrets ^1.0.1

Environment Variables

  • MOTHERDUCK_TOKEN (required) — MotherDuck token
  • MOTHERDUCK_DATABASE (optional) — MotherDuck database — default: md:
    • Setup: The md: connection string: "md:" for the default database, or "md:my_db".
    • Example: md:my_db

Runtime Dependencies

  • @duckdb/node-api
  • @molecule/api-bond
  • @molecule/api-database
  • @molecule/api-database-duckdb
  • @molecule/api-secrets

Configure via environment variables: MOTHERDUCK_TOKEN (required — create it in the MotherDuck UI under Settings → "+ Create token"; the client also auto-reads a lowercase motherduck_token env var by itself) and MOTHERDUCK_DATABASE (the md: connection string; default md: for the account's default database, md:my_db for a named one).

  • A missing token fails with the tagged config error (config.notConfigured, HTTP 503) naming where to create one — not an opaque vendor 401. The token is read at first use, never at import time.
  • Instances are cached (DuckDBInstance.fromCache), mandatory. The Node client does not cache md: instances by default and every bare create() re-fetches the remote catalog; this bond always goes through the cache, so repeated pools on one connection string share one instance.
  • One connection, serialized like the duckdb bond. Every statement runs on one long-lived connection behind a FIFO queue — MotherDuck itself recommends long-lived connections. A transaction() holds the queue for its whole BEGIN → … → COMMIT/ROLLBACK lifetime.
  • MotherDuck runs DuckDB SQL, not PostgreSQL SQL. Local files and attachments, INSTALL/LOAD, SET, and temp tables are NOT available through md: — read_parquet('s3://…') and https:// paths work; a local ./data.parquet does not (the file is on YOUR disk, not MotherDuck's).
  • JSON columns read as JSON TEXT through raw query() (the duckdb bond's caveat — DuckDB's JSON type is VARCHAR underneath); the DataStore CRUD helpers parse JSON-typed columns for you.
  • Migrations: the duckdb bond's runner on this pool — same ledger (_molecule_migrations), same Postgres-dialect translation and the same limits: partial indexes are translated without changing behaviour, while an ON DELETE/ON UPDATE referential action throws UnsupportedSqlFeatureError (DuckDB cannot reproduce it, so the generator's compatibility preflight refuses that resource/database pair — see sqlCapabilities).
  • pool.end() closes this pool's connection. The cached instance stays alive for the process (MotherDuck's dbinstance_inactivity_ttl, default 15 minutes, retires idle instances server-side).