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

    Class DuckDBTerminal

    A browser-based SQL terminal for DuckDB, powered by Ghostty terminal emulator.

    DuckDBTerminal provides a full-featured SQL REPL (Read-Eval-Print Loop) that runs entirely in the browser using DuckDB WASM. It supports:

    • Multi-line SQL statements with syntax highlighting
    • Command history with arrow key navigation
    • Tab completion for SQL keywords, table names, and functions
    • Dot commands (.help, .tables, .schema, etc.)
    • Multiple output formats (table, CSV, JSON)
    • File loading via drag-and-drop or file picker
    • Result pagination for large datasets
    • Custom theming
    • Customizable prompts (via config or .prompt command)
    • Event system for integration with host applications
    const terminal = new DuckDBTerminal({
    container: '#terminal',
    theme: 'dark',
    });
    await terminal.start();
    const terminal = new DuckDBTerminal({
    container: '#terminal',
    prompt: 'SQL> ',
    continuationPrompt: '... ',
    });
    await terminal.start();
    const terminal = new DuckDBTerminal({ container: '#terminal' });

    terminal.on('queryEnd', ({ sql, result, duration }) => {
    console.log(`Query "${sql}" completed in ${duration}ms`);
    });

    terminal.on('error', ({ message, source }) => {
    console.error(`Error from ${source}: ${message}`);
    });

    await terminal.start();
    const terminal = new DuckDBTerminal({ container: '#terminal' });
    await terminal.start();

    const result = await terminal.executeSQL('SELECT * FROM users LIMIT 10;');
    console.log(result.columns); // ['id', 'name', 'email']
    console.log(result.rows); // [[1, 'Alice', 'alice@example.com'], ...]

    Implements

    Index

    Constructors

    Properties

    collectedSQL: string[] = []
    commands: Map<string, Command> = ...
    continuationPrompt: string
    currentPage: number = 0
    currentThemeName: "dark" | "light" | "custom"
    customTheme: Theme | null = null
    database: Database
    debouncedHighlight: () => Promise<void> & { cancel: () => void } = ...
    dragDropCleanup: (() => void) | null = null
    eventListeners: Map<keyof TerminalEvents, Set<TerminalEventListener<any>>> = ...
    history: HistoryStore
    inputBuffer: InputBuffer
    lastQueryResult: QueryResult | null = null
    linkProvider: LinkProvider
    loadedFiles: Map<string, FileInfo> = ...
    outputMode: "table" | "csv" | "json" | "tsv" = 'table'
    pageSize: number = 0
    paginationQuery: string | null = null
    prompt: string
    queryQueue: Promise<QueryResult | null> = ...
    showTimer: boolean = false
    state: TerminalState = 'idle'
    syntaxHighlighting: boolean = true
    terminalAdapter: TerminalAdapter
    totalRows: number = 0

    Methods

    • Clears the terminal screen.

      This removes all content from the terminal display and moves the cursor to the top-left corner.

      Returns void

      terminal.clear();
      terminal.writeln('Screen cleared!');
    • Parameters

      • args: string[]

      Returns Promise<void>

    • Parameters

      • args: string[]

      Returns void

    • Parameters

      • args: string[]

      Returns void

    • Parameters

      • args: string[]

      Returns void

    • Parameters

      • args: string[]

      Returns void

    • Parameters

      • args: string[]

      Returns void

    • Parameters

      • args: string[]

      Returns Promise<void>

    • Parameters

      • args: string[]

      Returns void

    • Parameters

      • args: string[]

      Returns void

    • Copy last query result to clipboard

      Returns Promise<boolean>

    • Cleans up resources and event listeners.

      Call this method when disposing of the terminal to prevent memory leaks. This removes drag-and-drop handlers and clears internal state.

      Returns void

    • Displays a query result in the current output mode.

      Formats and writes the result as table, CSV, TSV, or JSON based on the current outputMode setting.

      Parameters

      • result: QueryResult

        The query result to display

      Returns void

    • Executes a dot command (e.g., .help, .tables, .schema).

      Parses the command and arguments, looks up the handler, and executes it. Emits 'commandExecute' event on execution and 'error' on failure.

      Parameters

      • input: string

        The full command string including arguments

      Returns Promise<void>

    • Executes the current paginated query for the current page.

      Adds LIMIT/OFFSET to the stored query and displays results with pagination controls.

      Returns Promise<QueryResult | null>

      The query result for the current page, or null on error

    • Executes a SQL query and displays the results.

      This method executes the provided SQL statement against the DuckDB database, displays the results in the configured output format (table, CSV, or JSON), and adds the query to the command history.

      For large result sets (when pagination is enabled via .pagesize), the method will automatically paginate the results and enter pagination mode.

      Parameters

      • sql: string

        The SQL statement to execute (should end with a semicolon)

      Returns Promise<QueryResult | null>

      A promise that resolves to the query result, or null if an error occurred

      queryStart - Emitted before query execution begins

      queryEnd - Emitted after query execution completes (success or failure)

      error - Emitted if the query fails

      const result = await terminal.executeSQL('SELECT * FROM users;');
      if (result) {
      console.log(`Retrieved ${result.rowCount} rows in ${result.duration}ms`);
      console.log('Columns:', result.columns);
      console.log('First row:', result.rows[0]);
      }
      await terminal.executeSQL('CREATE TABLE products (id INTEGER, name VARCHAR);');
      await terminal.executeSQL("INSERT INTO products VALUES (1, 'Widget');");
    • Internal

      Internal SQL execution logic.

      Parameters

      • sql: string

        The SQL statement to execute

      Returns Promise<QueryResult | null>

      The query result, or null on error

    • Exits pagination mode and resets pagination state.

      Returns void

    • Finds the longest common prefix among an array of strings.

      Used for auto-completion to expand to the longest unambiguous prefix.

      Parameters

      • strings: string[]

        Array of strings to find common prefix for

      Returns string

      The longest common prefix (case-insensitive comparison)

    • Returns the current theme object for terminal styling.

      Returns Theme

      The custom theme if set, otherwise the built-in theme ('dark' or 'light')

    • Asynchronously highlights SQL using DuckDB's tokenizer.

      Parameters

      • sql: string

        The SQL string to highlight

      Returns Promise<string>

      The highlighted SQL string with ANSI color codes

    • Gets the current theme mode.

      Returns 'dark' or 'light' based on the current theme. For custom themes, this returns 'light' if the theme name is 'light', otherwise 'dark'.

      Returns "dark" | "light"

      The current theme mode: 'dark' or 'light'

      const mode = terminal.getTheme();
      console.log(`Current theme mode: ${mode}`);
    • Navigates to the next command in history (Arrow Down).

      Returns void

    • Navigates to the previous command in history (Arrow Up).

      Returns void

    • Processes a single character of user input.

      Handles special characters (Enter, Backspace, Tab, Ctrl sequences) and regular printable characters including Unicode.

      Parameters

      • char: string

        The single character to process

      Returns void

    • Handles Ctrl+C to cancel current input or multi-line collection.

      Returns void

    • Processes files dropped onto the terminal via drag-and-drop.

      Uses Promise.allSettled to ensure all files are attempted even if some fail.

      Parameters

      • files: File[]

        Array of File objects to load into DuckDB

      Returns Promise<void>

    • Handles the Enter key press.

      For dot commands, executes immediately. For SQL, collects lines until a semicolon terminates the statement, then executes.

      Returns Promise<void>

    • Processes VT100 escape sequences for special keys.

      Handles arrow keys (up/down for history, left/right for cursor), Home, End, and Delete keys.

      Parameters

      • seq: string

        The escape sequence string (e.g., '\x1b[A' for Arrow Up)

      Returns void

    • Handles raw terminal input data.

      Routes input to the appropriate handler based on terminal state (executing, paginating, or normal input mode). Processes escape sequences separately from regular character input.

      Parameters

      • data: string

        The raw input data from the terminal

      Returns void

    • Handles input during pagination mode.

      Supports: [n]ext page, [p]revious page, [q]uit, page number entry, and arrow keys for navigation.

      Parameters

      • data: string

        The input character or escape sequence

      Returns Promise<void>

    • Handles Ctrl+V to paste content from clipboard.

      Inserts text character-by-character, skipping newlines.

      Returns Promise<void>

    • Handles terminal resize events.

      Updates the InputBuffer with the new terminal width and redraws the current input line to ensure proper visual alignment after resize.

      Parameters

      • cols: number

        The new terminal width in columns

      Returns void

    • Handles Tab key for auto-completion.

      Provides suggestions for SQL keywords, table names, and functions. Single match is applied directly; multiple matches are displayed.

      Returns Promise<void>

    • Checks if a character should trigger syntax highlighting redraw.

      Parameters

      • char: string

        The character to check

      Returns boolean

      True if the character is a highlighting trigger (space, semicolon, parentheses, comma)

    • Loads a file into DuckDB's virtual filesystem.

      Registers the file and displays usage hints for supported file types (CSV, Parquet, JSON). Emits a 'fileLoaded' event on success.

      Parameters

      • file: File

        The file to load

      Returns Promise<boolean>

      True if the file was loaded successfully, false otherwise

    • Unsubscribes a listener from a terminal event.

      This is an alternative to using the unsubscribe function returned by on.

      Type Parameters

      Parameters

      Returns void

      const handler = ({ sql }) => console.log(sql);
      terminal.on('queryStart', handler);

      // Later:
      terminal.off('queryStart', handler);
    • Subscribes to a terminal event.

      The terminal emits various events during its lifecycle that you can subscribe to for monitoring, logging, or integrating with your application.

      Type Parameters

      Parameters

      • event: K

        The event name to subscribe to

      • listener: TerminalEventListener<K>

        The callback function to invoke when the event occurs

      Returns () => void

      An unsubscribe function that removes the listener when called

      const unsubscribe = terminal.on('queryEnd', ({ sql, result, duration }) => {
      console.log(`Query completed in ${duration}ms`);
      });

      // Later, to stop listening:
      unsubscribe();
      terminal.on('stateChange', ({ state, previous }) => {
      console.log(`Terminal state: ${previous} -> ${state}`);
      });
    • Redraws the current input line from scratch.

      After a terminal resize, Ghostty re-wraps content and the cursor position becomes unpredictable. The safest approach is to:

      1. Print a newline to ensure we're on a fresh line
      2. Redraw the prompt and content from scratch

      This may result in the old (garbled) content remaining visible above, but the current input will be correctly displayed and functional.

      Parameters

      • _oldCursorPos: { col: number; row: number }

        The cursor position before the change (unused, kept for API stability)

      • _oldEndPos: { col: number; row: number }

        The end position before the change (unused, kept for API stability)

      Returns void

    • Redraws the current input line with syntax highlighting applied.

      This method clears the current line content and rewrites it with color codes for SQL keywords, strings, numbers, etc. Called on delimiter characters (space, semicolon, parentheses, comma) via debouncing.

      Uses DuckDB's internal parser via the poached extension for accurate tokenization.

      Returns Promise<void>

    • Registers all built-in dot commands (.help, .tables, .schema, etc.).

      Called during construction to populate the commands map with handlers for terminal commands.

      Returns void

    • Resolves the container element from the configuration.

      Returns HTMLElement

      The resolved HTML element to attach the terminal to

      Error if the container selector doesn't match any element

    • Internal

      Sets the terminal state and emits a stateChange event.

      Parameters

      • newState: TerminalState

        The new terminal state

      Returns void

    • Sets the terminal color theme.

      You can set a built-in theme ('dark' or 'light') or provide a custom theme object with your own colors. Built-in theme preferences are persisted to localStorage.

      Parameters

      • theme: Theme | "dark" | "light"

        The theme to apply: 'dark', 'light', or a custom Theme object

      Returns void

      themeChange - Emitted after the theme is changed

      terminal.setTheme('light');
      
      terminal.setTheme({
      name: 'my-theme',
      colors: {
      background: '#1a1b26',
      foreground: '#a9b1d6',
      cursor: '#c0caf5',
      // ... other color properties
      },
      });
    • Displays the command prompt (primary or continuation based on state).

      Sets terminal state to 'idle' if not currently collecting multi-line SQL.

      Returns void

    • Initializes and starts the terminal.

      This method performs the following initialization steps:

      1. Resolves the container element
      2. Initializes the terminal adapter (Ghostty), database (DuckDB), and history store in parallel
      3. Sets up input handling and drag-and-drop file loading
      4. Displays the welcome message (if enabled)
      5. Shows the command prompt
      6. Emits the 'ready' event

      Returns Promise<void>

      A promise that resolves when the terminal is fully initialized

      Error if the container element cannot be found

      Error if DuckDB WASM initialization fails

      const terminal = new DuckDBTerminal({ container: '#terminal' });
      await terminal.start();
      console.log('Terminal is ready!');

      ready - Emitted when initialization is complete

    • Writes text to the terminal without a trailing newline.

      Use this method for inline output where you don't want to start a new line. The text is written directly to the terminal without any processing.

      Parameters

      • text: string

        The text to write to the terminal

      Returns void

      terminal.write('Loading');
      terminal.write('...');
      terminal.write(' Done!\n');
    • Writes text to the terminal followed by a newline.

      The text is processed for clickable URLs (if link detection is enabled) and newlines are normalized to CRLF for proper terminal display.

      Parameters

      • text: string

        The text to write to the terminal

      Returns void

      terminal.writeln('Query completed successfully!');
      terminal.writeln('Visit https://duckdb.org for documentation');