Ducklings API Documentation
    Preparing search index...

    A connection to a DuckDB database.

    Connections are used to execute queries and manage transactions. All operations are async as they communicate with a Web Worker.

    const conn = await db.connect();

    // Query returns array of objects
    const rows = await conn.query('SELECT * FROM range(10)');

    // Query returns Arrow Table
    const table = await conn.queryArrow('SELECT * FROM range(1000)');

    // Streaming for large results
    const stream = await conn.queryStreaming('SELECT * FROM large_table');
    for await (const chunk of stream) {
    console.log(chunk.rowCount);
    }

    await conn.close();
    Index

    Data Insertion

    • Insert data from an Arrow IPC stream buffer into a table.

      Creates a new table with the given name from the Arrow IPC data. If the table already exists, the call is a no-op (uses CREATE TABLE IF NOT EXISTS).

      Important: The IPC stream must not contain dictionary-encoded columns. Flechette's tableFromArrays() defaults to dictionary(utf8()) for string columns. Use explicit utf8() types to avoid this.

      Parameters

      • tableName: string

        The name of the table to create

      • ipcBuffer: Uint8Array

        Arrow IPC stream bytes (use tableToIPC(table, { format: 'stream' }))

      Returns Promise<void>

      When the connection is closed or the IPC data is invalid

      import { tableFromArrays, tableToIPC, utf8 } from '@ducklings/browser';

      const table = tableFromArrays(
      { id: [1, 2, 3], name: ['Alice', 'Bob', 'Charlie'] },
      { types: { name: utf8() } } // Required for string columns
      );
      const ipcBuffer = tableToIPC(table, { format: 'stream' });
      await conn.insertArrowFromIPCStream('users', ipcBuffer);

    Other

    • Begins a new transaction.

      Returns Promise<void>

      await conn.beginTransaction();
      try {
      await conn.execute('INSERT INTO users (name) VALUES ($1)', ['Alice']);
      await conn.execute('UPDATE balances SET amount = amount - 100 WHERE user = $1', ['Alice']);
      await conn.commit();
      } catch (e) {
      await conn.rollback();
      throw e;
      }
    • Executes a SQL statement and returns the number of affected rows.

      Use this for INSERT, UPDATE, DELETE, or other statements where you don't need to read result rows.

      Parameters

      • sql: string

        The SQL statement to execute

      Returns Promise<number>

      Promise resolving to the number of rows affected

      const deleted = await conn.execute('DELETE FROM users WHERE inactive = true');
      console.log(`Deleted ${deleted} users`);
    • Insert data from a CSV file.

      Parameters

      • tableName: string

        The name of the table to insert into

      • path: string

        The virtual file path of the CSV

      • Optionaloptions: CSVInsertOptions

        Optional CSV parsing options

      Returns Promise<void>

      await db.registerFileBuffer('data.csv', csvData);
      await conn.insertCSVFromPath('my_table', 'data.csv', { header: true });
    • Insert data from a JSON file.

      Parameters

      • tableName: string

        The name of the table to insert into

      • path: string

        The virtual file path of the JSON

      • Optionaloptions: JSONInsertOptions

        Optional JSON parsing options

      Returns Promise<void>

      await db.registerFileBuffer('data.json', jsonData);
      await conn.insertJSONFromPath('my_table', 'data.json');
    • Prepares a SQL statement for execution.

      Prepared statements are more secure (prevent SQL injection) and can be more efficient when executing the same query multiple times with different parameters.

      Parameters

      • sql: string

        The SQL statement with parameter placeholders (?)

      Returns Promise<PreparedStatement>

      Promise resolving to a PreparedStatement instance

      const stmt = await conn.prepare('SELECT * FROM users WHERE id = ?');
      stmt.bindInt32(1, 42);
      const rows = await stmt.run();
      await stmt.close();
    • Executes a SQL query and returns the results as an array of objects.

      Type Parameters

      • T = Record<string, unknown>

      Parameters

      • sql: string

        The SQL query to execute

      Returns Promise<T[]>

      Promise resolving to array of result rows as objects

      const rows = await conn.query<{ id: number; name: string }>(
      'SELECT * FROM users WHERE active = true'
      );
      for (const row of rows) {
      console.log(row.id, row.name);
      }
    • Executes a SQL query and returns results as a Flechette Arrow Table.

      This method is more efficient for large result sets and provides proper Arrow/columnar data representation.

      Parameters

      • sql: string

        The SQL query to execute

      Returns Promise<Table<TypeMap>>

      Promise resolving to Arrow Table with query results

      const table = await conn.queryArrow('SELECT * FROM range(1000000)');
      console.log(table.numRows);
    • Executes a SQL query and returns a streaming result.

      This method is more memory-efficient for large result sets as it processes data in chunks rather than loading everything at once.

      Parameters

      • sql: string

        The SQL query to execute

      Returns Promise<StreamingResult>

      Promise resolving to AsyncStreamingResult that can be iterated over

      const stream = await conn.queryStreaming('SELECT * FROM large_table');
      for await (const chunk of stream) {
      console.log(`Processing ${chunk.rowCount} rows`);
      for (const row of chunk.toArray()) {
      processRow(row);
      }
      }
      await stream.close();
    • Execute a function within a transaction.

      The transaction is automatically committed on success or rolled back on error.

      Type Parameters

      • T

      Parameters

      • fn: () => Promise<T>

        The function to execute within the transaction

      Returns Promise<T>

      Promise resolving to the function's return value

      const result = await conn.transaction(async () => {
      await conn.execute('INSERT INTO users (name) VALUES ($1)', ['Alice']);
      return await conn.query('SELECT * FROM users WHERE name = $1', ['Alice']);
      });