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

    Class Database

    Index

    Constructors

    Properties

    conn: AsyncDuckDBConnection | null = null
    db: AsyncDuckDB | null = null
    initialized: boolean = false
    options: DatabaseOptions
    poachedLoaded: boolean = false
    worker: Worker | null = null

    Methods

    • 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);');
      
    • 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' }]
    • 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 poached extension is loaded.

      Returns boolean

      True if the poached extension is available

    • 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');");
    • 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"
      }