DuckDB Terminal - v0.8.4
    Preparing search index...

    Class Database

    Index
    activeSentQuery: symbol | null = null
    conn: AsyncDuckDBConnection | null = null
    connectionQueue: Promise<void> = ...

    Tail of the connection work queue; see Database.withConnection.

    db: AsyncDuckDB | null = null
    initialized: boolean = false
    initialSettings: Map<string, DatabaseSettingValue> | null = null
    options: NormalizedDatabaseOptions
    poachedLoaded: boolean = false
    worker: Worker | null = null
    • Cancels the query currently being consumed through DuckDB's pending-query API.

      Returns Promise<boolean>

      Whether DuckDB accepted a cancellation request

    • Check whether a statement can be safely wrapped as a paginated subquery. Preparing a zero-row wrapper validates the shape without scanning the result.

      Parameters

      • sql: string

      Returns Promise<boolean>

    • Closes the database connection and releases resources.

      This method:

      1. Closes the database connection
      2. Terminates the DuckDB instance
      3. Terminates the Web Worker

      After calling this method, init must be called again before executing any queries.

      Returns Promise<void>

      A promise that resolves when cleanup is complete

      await db.close();
      console.log('Database closed:', !db.isReady());
    • Removes a file from DuckDB's virtual filesystem.

      Parameters

      • filename: string

        The filename to remove

      Returns Promise<void>

      Error if the database is not initialized

      await db.dropFile('data.csv');
      
    • Executes a SQL query and returns the results.

      Parameters

      • sql: string

        The SQL statement to execute

      Returns Promise<QueryResult>

      A promise that resolves to the query result containing columns, rows, row count, and duration

      Error if the database is not initialized

      Error if the SQL query is invalid or fails

      const result = await db.executeQuery('SELECT * FROM users WHERE age > 18;');
      console.log('Columns:', result.columns); // ['id', 'name', 'age']
      console.log('Rows:', result.rows); // [[1, 'Alice', 25], [2, 'Bob', 30]]
      console.log('Duration:', result.duration); // 5.23 (milliseconds)
      await db.executeQuery('CREATE TABLE products (id INTEGER, name VARCHAR);');
      
    • Executes a query while retaining at most maxRows rows.

      One additional row is consumed to determine whether the result was truncated. If it was, the remaining DuckDB stream is cancelled.

      Parameters

      • sql: string
      • maxRows: number

      Returns Promise<QueryResult>

    • Gets CREATE TABLE statements for all tables and views in the database.

      This method queries the database catalog and generates DDL statements that describe the schema, useful for providing context to AI assistants.

      Returns Promise<string>

      A promise that resolves to a string containing all CREATE TABLE statements, or an empty string if no tables exist

      const ddl = await db.getAllDDL();
      console.log(ddl);
      // CREATE TABLE users (id INTEGER, name VARCHAR, email VARCHAR);
      // CREATE TABLE orders (id INTEGER, user_id INTEGER, total DECIMAL);
    • Gets auto-completion suggestions for the current input.

      Provides suggestions for:

      • SQL keywords (SELECT, FROM, WHERE, etc.)
      • Table names from the current database
      • Common SQL functions

      Parameters

      • text: string

        The current input text

      • cursorPosition: number

        The cursor position within the text

      Returns Promise<CompletionSuggestion[]>

      A promise that resolves to an array of completion suggestions

      const suggestions = await db.getCompletions('SEL', 3);
      console.log(suggestions);
      // [{ value: 'SELECT', type: 'keyword' }]
    • Return the exact row count when a statement can be used as a subquery. A null result means the statement should use bounded, non-pageable output.

      Parameters

      • sql: string

      Returns Promise<number | null>

    • Gets a list of all tables in the database.

      Queries all attached databases and returns tables with their qualified names when multiple databases are present, or just the table name when only the default 'memory' database exists.

      Returns Promise<string[]>

      A promise that resolves to an array of table names (qualified if multiple databases)

      // Single database
      const tables = await db.getTables();
      console.log('Tables:', tables); // ['users', 'products', 'orders']

      // With attached database
      const tables = await db.getTables();
      console.log('Tables:', tables); // ['users', 'mydb.products']
    • Gets the schema (column definitions) for a specific table.

      Parameters

      • tableName: string

        The name of the table to get the schema for

      Returns Promise<{ name: string; type: string }[]>

      A promise that resolves to an array of column definitions

      const schema = await db.getTableSchema('users');
      console.log(schema);
      // [
      // { name: 'id', type: 'INTEGER' },
      // { name: 'name', type: 'VARCHAR' },
      // { name: 'email', type: 'VARCHAR' }
      // ]
    • Initializes the DuckDB database.

      This method performs the following setup:

      1. Downloads the appropriate DuckDB WASM bundle
      2. Creates a Web Worker for database operations
      3. Instantiates the DuckDB instance
      4. Opens the database (in-memory or OPFS-backed)
      5. Creates a connection for query execution

      Returns Promise<void>

      A promise that resolves when initialization is complete

      Error if initialization fails (network issues, WASM loading, etc.)

      const db = new Database();
      await db.init();
      console.log('Database ready:', db.isReady());
    • Checks if the database is initialized and ready for queries.

      Returns boolean

      True if the database is ready, false otherwise

      if (db.isReady()) {
      const result = await db.executeQuery('SELECT 1;');
      }
    • Loads the poached extension for SQL tokenization.

      The poached extension provides tokenize_sql() which uses DuckDB's internal parser for accurate SQL syntax highlighting.

      Returns Promise<boolean>

      A promise that resolves to true if loaded successfully, false otherwise

    • Registers a file in DuckDB's virtual filesystem.

      This allows you to load external files (CSV, Parquet, JSON) into DuckDB and query them using functions like read_csv(), read_parquet(), etc.

      Parameters

      • filename: string

        The virtual filename to register (e.g., 'data.csv')

      • data: Uint8Array

        The file contents as a Uint8Array

      Returns Promise<void>

      Error if the database is not initialized

      // Load a CSV file
      const response = await fetch('https://example.com/data.csv');
      const data = new Uint8Array(await response.arrayBuffer());
      await db.registerFile('data.csv', data);

      // Query the file
      const result = await db.executeQuery("SELECT * FROM read_csv('data.csv');");
    • Releases a result that was not read to the end (truncated, cancelled, or failed while streaming). DuckDB-Wasm keeps such a result open on the connection and refuses to prepare statements until it is gone ("connection has an open result"), which broke pagination checks and the AI write guard after a truncated result. Cancelling does not release it; starting another query does.

      Parameters

      • conn: AsyncDuckDBConnection

      Returns Promise<void>

    • Parameters

      • batch: Pick<arrow.RecordBatch, "numRows" | "getChildAt">
      • columnCount: number
      • maxRows: number = Number.POSITIVE_INFINITY

      Returns unknown[][]

    • Parameters

      • conn: AsyncDuckDBConnection
      • sql: string

      Returns Promise<{ queryToken: symbol; reader: AsyncRecordBatchStreamReader }>

    • Starts a DuckDB worker and instantiates DuckDB in it. With withoutOPFS, the worker has no navigator.storage.getDirectory(), so DuckDB does not mount its OPFS scratch file system.

      Parameters

      • bundle: DuckDBBundle
      • withoutOPFS: boolean

      Returns Promise<AsyncDuckDB>

    • Tokenizes SQL using DuckDB's internal parser via the poached extension.

      Returns token positions and categories for syntax highlighting. Categories include: KEYWORD, IDENTIFIER, OPERATOR, NUMERIC_CONSTANT, STRING_CONSTANT, COMMENT, ERROR

      Parameters

      • sql: string

        The SQL string to tokenize

      Returns Promise<SQLToken[] | null>

      A promise that resolves to an array of tokens, or null if tokenization fails

      const tokens = await db.tokenizeSQL('SELECT * FROM users');
      // [
      // { position: 0, category: 'KEYWORD' }, // SELECT
      // { position: 7, category: 'OPERATOR' }, // *
      // { position: 9, category: 'KEYWORD' }, // FROM
      // { position: 14, category: 'IDENTIFIER' } // users
      // ]
    • Validates SQL and returns error information if invalid.

      This combines is_valid_sql() and sql_error_message() in a single query for efficiency. Returns validation result and error details in one call.

      Parameters

      • sql: string

        The SQL string to validate

      Returns Promise<{ error?: SQLError; isValid: boolean } | undefined>

      A promise that resolves to an object with isValid boolean and optional error with details, or undefined if extension unavailable

      const result = await db.validateSQL('SELECT * FROM users WHERE');
      if (result && !result.isValid) {
      console.log(result.error?.exceptionMessage); // "syntax error at end of input"
      }
    • Runs connection work one operation at a time.

      DuckDB-Wasm keys sent queries, result-chunk fetches, and cancellation by connection rather than by query, so a statement started while another result is still being read takes over that connection's result. Each operation therefore holds the connection until its result is fully consumed. cancelActiveQuery deliberately bypasses this queue.

      Type Parameters

      • T

      Parameters

      • operation: (conn: AsyncDuckDBConnection) => Promise<T>

      Returns Promise<T>