Skip to content

Latest commit

 

History

History
55 lines (42 loc) · 2.19 KB

node-duckdb.connection.execute.md

File metadata and controls

55 lines (42 loc) · 2.19 KB

Node-DuckDB API > Connection > execute

Connection.execute() method

Asynchronously executes the query and returns a Readable stream that wraps the result set.

Signature:

execute<T>(command: string, options?: IExecuteOptions): Promise<Readable>;

Parameters

Parameter Type Description
command string SQL command to execute
options IExecuteOptions optional options object of type IExecuteOptions

Returns:

Promise<Readable>

Example

Streaming results of a DuckDB query into a CSV file:

import { Connection, DuckDB, RowResultFormat } from "node-duckdb";
import { createWriteStream } from "fs";
import { Transform } from "stream";
class ArrayToCsvTransform extends Transform {
  constructor() {
    super({ objectMode: true });
  }
  _transform(chunk: any[], _encoding: string, callback: any) {
    this.push(chunk.join(",") + "\n");
    callback();
  }
}

async function outputToFileAsCsv() {
  const db = new DuckDB();
  const connection = new Connection(db);
  await connection.execute("CREATE TABLE people(id INTEGER, name VARCHAR);");
  await connection.execute("INSERT INTO people VALUES (1, 'Mark'), (2, 'Hannes'), (3, 'Bob');");
  const resultStream = await connection.execute("SELECT * FROM people;", { rowResultFormat: RowResultFormat.Array });
  const transformToCsvStream = new ArrayToCsvTransform();
  const writeStream = createWriteStream("my-people-output");
  resultStream.pipe(transformToCsvStream).pipe(writeStream);
}
outputToFileAsCsv();