### Connect to DuckDB Instance (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Establishes a connection to a DuckDB instance. This example demonstrates creating a connection using the default instance, which is suitable for most application-level needs. ```javascript import { DuckDBConnection } from '@duckdb/node-api'; const connection = await DuckDBConnection.create(); ``` -------------------------------- ### Extract and Prepare SQL Statements with Parameters Source: https://duckdb.org/docs/stable/clients/node_neo/overview Shows how to extract multiple SQL statements from a single string and prepare them for execution. This example demonstrates binding integer parameters to prepared statements and running them. It's useful for executing sequences of SQL commands dynamically. ```javascript const extractedStatements = await connection.extractStatements(` create or replace table numbers as from range(?); from numbers where range < ?; drop table numbers; `); const parameterValues = [10, 7]; const statementCount = extractedStatements.count; for (let stmtIndex = 0; stmtIndex < statementCount; stmtIndex++) { const prepared = await extractedStatements.prepare(stmtIndex); let parameterCount = prepared.parameterCount; for (let paramIndex = 1; paramIndex <= parameterCount; paramIndex++) { prepared.bindInteger(paramIndex, parameterValues.shift()); } const result = await prepared.run(); // ... } ``` -------------------------------- ### Get Basic Information Source: https://duckdb.org/docs/stable/clients/node_neo/overview Retrieve the version of the DuckDB Node.js client and descriptions of its configuration options. ```APIDOC ## Get Basic Information ### Description This endpoint provides methods to get the current version of the DuckDB Node.js client and a description of available configuration options. ### Method GET ### Endpoint N/A (These are static methods of the `duckdb` module) ### Parameters None ### Request Example ```javascript import duckdb from '@duckdb/node-api'; console.log(duckdb.version()); console.log(duckdb.configurationOptionDescriptions()); ``` ### Response #### Success Response (200) - **version()**: (string) - The current version of the DuckDB Node.js client. - **configurationOptionDescriptions()**: (object) - An object containing descriptions for configuration options. #### Response Example ```json { "version": "1.4.4", "configurationOptions": { "threads": "Number of threads to use for query execution." // ... other options } } ``` ``` -------------------------------- ### Control Asynchronous Task Evaluation with Pending Results Source: https://duckdb.org/docs/stable/clients/node_neo/overview Demonstrates how to manage the execution of long-running asynchronous tasks using `DuckDBPendingResultState`. The example prepares a query, starts it asynchronously, and polls its state until the result is ready, allowing for non-blocking operations. ```javascript import { DuckDBPendingResultState } from '@duckdb/node-api'; async function sleep(ms) { return new Promise((resolve) => { setTimeout(resolve, ms); }); } const prepared = await connection.prepare('from range(10_000_000)'); const pending = prepared.start(); while (pending.runTask() !== DuckDBPendingResultState.RESULT_READY) { console.log('not ready'); await sleep(1); } console.log('ready'); const result = await pending.getResult(); // ... ``` -------------------------------- ### Get DuckDB Version and Configuration Info (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Retrieves the current version of the DuckDB Node.js client and a description of its configuration options. This is useful for debugging and understanding the client's capabilities. ```javascript import duckdb from '@duckdb/node-api'; console.log(duckdb.version()); console.log(duckdb.configurationOptionDescriptions()); ``` -------------------------------- ### Append Data Chunk to DuckDB Table Source: https://duckdb.org/docs/stable/clients/node_neo/overview Illustrates appending data to a DuckDB table using a `DuckDBDataChunk`. This method is more efficient for larger datasets as it allows appending data in batches. The example shows how to create a chunk and set its columns or rows before appending. ```javascript await connection.run( `create or replace table target_table(i integer, v varchar)` ); const appender = await connection.createAppender('target_table'); const chunk = DuckDBDataChunk.create([INTEGER, VARCHAR]); chunk.setColumns([ [42, 123, 17], ['duck', 'mallad', 'goose'], ]); // OR: // chunk.setRows([ // [42, 'duck'], // [123, 'mallard'], // [17, 'goose'], // ]); appender.appendDataChunk(chunk); appender.flushSync(); ``` -------------------------------- ### Pending Results (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Shows how to handle asynchronous SQL query execution using pending results in the DuckDB Node.js client. This allows for non-blocking operations, where query execution can be started and results retrieved later, optionally in a streaming fashion. ```javascript // Create a pending result. const pending = await connection.start(sql); const pending = await connection.start(sql, values); const pending = await connection.start(sql, values, types); // Create a pending, streaming result. const pending = await connection.startStream(sql); const pending = await connection.startStream(sql, values); const pending = await connection.startStream(sql, values, types); // Create a pending result from a prepared statement. const pending = await prepared.start(); const pending = await prepared.startStream(); while (pending.runTask() !== DuckDBPendingResultState.RESULT_READY) { // optionally sleep or do other work between tasks } // Retrieve the result. If not yet READY, will run until it is. const result = await pending.getResult(); const reader = await pending.read(); const reader = await pending.readAll(); const reader = await pending.readUntil(targetRowCount); ``` -------------------------------- ### Get Chunk Data as Rows (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview This snippet illustrates how to extract row data from a DuckDB chunk. It shows methods for getting rows as arrays, row objects, and columns. ```javascript const rows = chunk.getRows(); const rowObjects = chunk.getRowObjects(result.deduplicatedColumnNames()); const columns = chunk.getColumns(); const columnsObject = chunk.getColumnsObject(result.deduplicatedColumnNames()); ``` -------------------------------- ### Get Result Data in Various Forms (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Retrieve query results in multiple formats: as an array of row arrays, an array of row objects, an array of column arrays, or an object mapping column names to arrays of column values. This provides flexibility in how result data is consumed. ```javascript const reader = await connection.runAndReadAll( 'from range(3) select range::int as i, 10 + i as n' ); const rows = reader.getRows(); // [ [0, 10], [1, 11], [2, 12] ] const rowObjects = reader.getRowObjects(); // [ { i: 0, n: 10 }, { i: 1, n: 11 }, { i: 2, n: 12 } ] const columns = reader.getColumns(); // [ [0, 1, 2], [10, 11, 12] ] const columnsObject = reader.getColumnsObject(); // { i: [0, 1, 2], n: [10, 11, 12] } ``` -------------------------------- ### Get Chunk Data Value by Value (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview This code demonstrates how to access individual values within a DuckDB chunk by iterating through columns and then through items within each column vector. This provides granular access to the data. ```javascript const columns = []; const columnCount = chunk.columnCount; for (let columnIndex = 0; columnIndex < columnCount; columnIndex++) { const columnValues = []; const columnVector = chunk.getColumnVector(columnIndex); const itemCount = columnVector.itemCount; for (let itemIndex = 0; itemIndex < itemCount; itemIndex++) { const value = columnVector.getItem(itemIndex); columnValues.push(value); } columns.push(columnValues); } ``` -------------------------------- ### Prepared Statements (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Illustrates how to use prepared statements with the DuckDB Node.js client for efficient and secure SQL execution. This involves preparing a statement, binding parameters, and then executing it using methods similar to direct connection execution. ```javascript // Prepare a possibly-parametered SQL statement to run later. const prepared = await connection.prepare(sql); // Bind values to the parameters. prepared.bind(values); prepared.bind(values, types); // Run the prepared statement. These mirror the methods on the connection. const result = prepared.run(); const reader = prepared.runAndRead(); const reader = prepared.runAndReadAll(); const reader = prepared.runAndReadUntil(targetRowCount); const result = prepared.stream(); const reader = prepared.streamAndRead(); const reader = prepared.streamAndReadAll(); const reader = prepared.streamAndReadUntil(targetRowCount); ``` -------------------------------- ### Create DuckDB Instance (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Demonstrates various ways to create a DuckDB instance, including in-memory databases, file-based databases, and instances with specific configuration options like thread count. ```javascript import { DuckDBInstance } from '@duckdb/node-api'; // Create with an in-memory database: const instance = await DuckDBInstance.create(':memory:'); // Equivalent to the above: const instance = await DuckDBInstance.create(); // Read from and write to a database file, which is created if needed: const instance = await DuckDBInstance.create('my_duckdb.db'); // Set configuration options: const instance = await DuckDBInstance.create('my_duckdb.db', { threads: '4' }); ``` -------------------------------- ### Parameterize SQL Queries (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Demonstrates how to parameterize SQL queries using positional or named placeholders, improving security and performance. It covers binding various data types and handling type inference. ```javascript const prepared = await connection.prepare('select $1, $2, $3'); prepared.bindVarchar(1, 'duck'); prepared.bindInteger(2, 42); prepared.bindList(3, listValue([10, 11, 12]), LIST(INTEGER)); const result = await prepared.run(); // Or using named parameters: const prepared = await connection.prepare('select $a, $b, $c'); prepared.bind({ 'a': 'duck', 'b': 42, 'c': listValue([10, 11, 12]), }, { 'a': VARCHAR, 'b': INTEGER, 'c': LIST(INTEGER), }); const result = await prepared.run(); // Or directly in run: const result = await connection.run('select $a, $b, $c', { 'a': 'duck', 'b': 42, 'c': listValue([10, 11, 12]), }, { 'a': VARCHAR, 'b': INTEGER, 'c': LIST(INTEGER), }); // Unspecified types will be inferred: const result = await connection.run('select $a, $b, $c', { 'a': 'duck', 'b': 42, 'c': listValue([10, 11, 12]), }); ``` -------------------------------- ### Use DuckDB Instance Cache (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Illustrates how to use an instance cache to manage multiple DuckDB instances within the same process, preventing issues with attaching the same database multiple times. It shows both the default cache and explicit cache creation. ```javascript import { DuckDBInstanceCache } from '@duckdb/node-api'; // Using the default instance cache: const instance = await DuckDBInstance.fromCache('my_duckdb.db'); // Creating and using an explicit instance cache: const cache = new DuckDBInstanceCache(); const instance = await cache.getOrCreateInstance('my_duckdb.db'); ``` -------------------------------- ### Connect to a DuckDB Instance (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Establishes a connection to an already created DuckDB instance. This is a prerequisite for running SQL queries against that specific instance. ```javascript const connection = await instance.connect(); ``` -------------------------------- ### Run SQL Queries Source: https://duckdb.org/docs/stable/clients/node_neo/overview Execute SQL queries against the connected DuckDB instance, with support for parameterization and streaming results. ```APIDOC ## Run SQL Queries ### Description This section covers executing SQL queries using the DuckDB Node.js client, including running simple queries, parameterized queries, and streaming results. ### Run SQL #### Method `async run(query: string, params?: any, types?: any)` #### Description Executes a given SQL query. Parameters can be provided for prepared statements. #### Parameters - **query** (string) - The SQL query to execute. - **params** (any) - Optional. An object or array of parameters for the query. - **types** (any) - Optional. An object or array specifying the types of the parameters. #### Request Example ```javascript // Simple query const result = await connection.run('SELECT 42 AS number'); // Query with parameters const resultWithParams = await connection.run('SELECT $a, $b', { a: 1, b: 'hello' }); // Query with specified types const resultWithTypes = await connection.run('SELECT $a, $b', { a: 1, b: 'hello' }, { a: 'INTEGER', b: 'VARCHAR' }); ``` ### Prepare and Run SQL #### Method `async prepare(query: string)` #### Description Prepares an SQL query for execution, allowing for parameter binding. #### Parameters - **query** (string) - The SQL query to prepare. #### Request Example ```javascript // Prepare a statement const prepared = await connection.prepare('SELECT $1, $2'); // Bind parameters prepared.bindVarchar(1, 'duck'); prepared.bindInteger(2, 42); // Run the prepared statement const result = await prepared.run(); // Alternative binding using an object const preparedNamed = await connection.prepare('SELECT $a, $b'); preparedNamed.bind({ 'a': 'duck', 'b': 42 }, { 'a': 'VARCHAR', 'b': 'INTEGER' }); const resultNamed = await preparedNamed.run(); ``` ### Stream Results #### Method `async stream(query: string)` #### Description Executes an SQL query and returns a stream of results. Results are evaluated lazily as rows are read. #### Parameters - **query** (string) - The SQL query to execute. #### Request Example ```javascript const resultStream = await connection.stream('FROM range(10000)'); // Process the stream... ``` ### Specifying Values #### Description Values for various data types can be represented using JavaScript primitives (`boolean`, `number`, `bigint`, `string`, `null`). For specific types like `ARRAY`, `DATE`, `DECIMAL`, `LIST`, `MAP`, `STRUCT`, `TIMESTAMP`, etc., special functions must be used (e.g., `arrayValue()`, `dateValue()`, `listValue()`). #### Example Functions - `arrayValue(values)` - `bitValue(value)` - `blobValue(value)` - `dateValue(value)` - `decimalValue(value)` - `intervalValue(value)` - `listValue(values, type)` - `mapValue(entries, keyType, valueType)` - `structValue(fields)` - `timeValue(value)` - `timeTZValue(value)` - `timestampValue(value)` - `timestampTZValue(value)` - `timestampSecondsValue(value)` - `timestampMillisValue(value)` - `timestampNanosValue(value)` - `unionValue(tag, value)` - `uuidValue(value)` #### Request Example (Parameterization with specific types) ```javascript import { listValue, LIST, INTEGER } from '@duckdb/node-api'; const prepared = await connection.prepare('SELECT $1'); prepared.bind(1, listValue([10, 11, 12]), LIST(INTEGER)); const result = await prepared.run(); ``` ``` -------------------------------- ### Execute SQL Queries (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Demonstrates various methods to execute SQL queries with the DuckDB Node.js client. These methods include running queries to completion, retrieving data via readers, and creating streaming results. They support optional parameter binding with values and types. ```javascript const result = await connection.run(sql); const result = await connection.run(sql, values); const result = await connection.run(sql, values, types); const reader = await connection.runAndRead(sql); const reader = await connection.runAndRead(sql, values); const reader = await connection.runAndRead(sql, values, types); const reader = await connection.runAndReadAll(sql); const reader = await connection.runAndReadAll(sql, values); const reader = await connection.runAndReadAll(sql, values, types); const reader = await connection.runAndReadUntil(sql, targetRowCount); const reader = await connection.runAndReadAll(sql, targetRowCount, values); const reader = await connection.runAndReadAll(sql, targetRowCount, values, types); const result = await connection.stream(sql); const result = await connection.stream(sql, values); const result = await connection.stream(sql, values, types); const reader = await connection.streamAndRead(sql); const reader = await connection.streamAndRead(sql, values); const reader = await connection.streamAndRead(sql, values, types); const reader = await connection.streamAndReadAll(sql); const reader = await connection.streamAndReadAll(sql, values); const reader = await connection.streamAndReadAll(sql, values, types); const reader = await connection.streamAndReadUntil(sql, targetRowCount); const reader = await connection.streamAndReadUntil(sql, targetRowCount, values); const reader = await connection.streamAndReadUntil(sql, targetRowCount, values, types); ``` -------------------------------- ### Connect to DuckDB Source: https://duckdb.org/docs/stable/clients/node_neo/overview Establish a connection to a DuckDB instance, either in-memory or file-based. ```APIDOC ## Connect to DuckDB ### Description This section details how to create and connect to DuckDB instances, including options for in-memory databases, file-based databases, and configuration settings. ### Create Instance #### Method `static async create(path?: string | Options)` #### Description Creates a new DuckDB instance. If `path` is omitted or `':memory:'`, an in-memory database is created. If a string path is provided, a file-based database is created or opened at that path. An `Options` object can be provided to set configuration options. #### Parameters - **path** (string | Options) - Optional. The path to the database file or an options object. - **threads** (string) - Optional. Number of threads to use. #### Request Example ```javascript import { DuckDBInstance } from '@duckdb/node-api'; // In-memory database (default) const instanceInMemory = await DuckDBInstance.create(); // File-based database const instanceFile = await DuckDBInstance.create('my_duckdb.db'); // With configuration options const instanceWithOptions = await DuckDBInstance.create('my_duckdb.db', { threads: '4' }); ``` ### Instance Cache #### Method `static async fromCache(path: string)` #### Description Retrieves an existing DuckDB instance from the cache or creates a new one if it doesn't exist. This ensures that multiple calls with the same path return the same instance. #### Parameters - **path** (string) - The path to the database file. #### Request Example ```javascript import { DuckDBInstance } from '@duckdb/node-api'; const instance = await DuckDBInstance.fromCache('my_duckdb.db'); ``` ### Explicit Instance Cache #### Method `new DuckDBInstanceCache()` #### Description Creates a new, explicit instance cache. This allows for more granular control over instance management. #### Request Example ```javascript import { DuckDBInstanceCache } from '@duckdb/node-api'; const cache = new DuckDBInstanceCache(); const instance = await cache.getOrCreateInstance('my_duckdb.db'); ``` ### Connect to Instance #### Method `async connect()` #### Description Establishes a connection to the DuckDB instance. #### Request Example ```javascript const connection = await instance.connect(); ``` ### Disconnect #### Method `disconnectSync()` or `closeSync()` #### Description Explicitly disconnects the connection. Connections are typically disconnected automatically when their reference is dropped, but explicit disconnection is also supported. #### Request Example ```javascript connection.disconnectSync(); // or connection.closeSync(); ``` ``` -------------------------------- ### Append Data Row by Row to DuckDB Table Source: https://duckdb.org/docs/stable/clients/node_neo/overview Demonstrates appending data to a DuckDB table row by row using the `createAppender` method. It shows how to append integers and strings for each row and flush the data. This method is suitable for smaller datasets or when data arrives sequentially. ```javascript await connection.run( `create or replace table target_table(i integer, v varchar)` ); const appender = await connection.createAppender('target_table'); appender.appendInteger(42); appender.appendVarchar('duck'); appender.endRow(); appender.appendInteger(123); appender.appendVarchar('mallard'); appender.endRow(); appender.flushSync(); appender.appendInteger(17); appender.appendVarchar('goose'); appender.endRow(); appender.closeSync(); // also flushes ``` -------------------------------- ### Read All Result Data at Once (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Execute a query and read all of its results into memory. This method is suitable for smaller result sets where loading all data at once is feasible. The data can be accessed as rows or columns. ```javascript const reader = await connection.runAndReadAll('from test_all_types()'); const rows = reader.getRows(); // OR: const columns = reader.getColumns(); ``` -------------------------------- ### Run SQL Query (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Executes a SQL query against an active DuckDB connection and retrieves the results. This is the fundamental operation for interacting with the database. ```javascript const result = await connection.run('from test_all_types()'); ``` -------------------------------- ### Stream and Read Result Data Up To a Limit (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Execute a query and stream results, reading up to a specified number of rows. This method reads data in chunks (defaulting to 2048 rows) and is efficient for large datasets where only a portion of the data is needed initially. ```javascript const reader = await connection.streamAndReadUntil( 'from range(5000)', 1000 ); const rows = reader.getRows(); // rows.length === 2048. (Rows are read in chunks of 2048.) ``` -------------------------------- ### Read Result Data Incrementally (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Execute a query and read results incrementally. This allows for fine-grained control over data fetching, enabling the application to process data as it becomes available. The `readUntil` method fetches data in chunks. ```javascript const reader = await connection.streamAndRead('from range(5000)'); reader.readUntil(2000); // reader.currentRowCount === 2048 (Rows are read in chunks of 2048.) // reader.done === false reader.readUntil(4000); // reader.currentRowCount === 4096 // reader.done === false reader.readUntil(6000); // reader.currentRowCount === 5000 // reader.done === true ``` -------------------------------- ### Retrieve Data Using a Reader (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Retrieve data sequentially using a reader object. This is efficient for large result sets as it allows processing rows incrementally. Data can be accessed synchronously after reading a portion of the rows. ```javascript // First, (asynchronously) read some rows: await reader.readAll(); // or: await reader.readUntil(targetRowCount); // Then, (synchronously) get result data for the rows read: const columns = reader.getColumns(); const columnsJson = reader.getColumnsJson(); const columnsObject = reader.getColumnsObject(); const columnsObjectJson = reader.getColumnsObjectJson(); const rows = reader.getRows(); const rowsJson = reader.getRowsJson(); const rowObjects = reader.getRowObjects(); const rowObjectsJson = reader.getRowObjectsJson(); // Individual values can also be read directly: const value = reader.value(columnIndex, rowIndex); ``` -------------------------------- ### Stream DuckDB Query Results (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Shows how to stream query results from DuckDB, which evaluates lazily as rows are read. This is efficient for large result sets, as it avoids loading all data into memory at once. ```javascript const result = await connection.stream('from range(10_000)'); ``` -------------------------------- ### Fetch and Process Data Chunks (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Fetch and process data in chunks from a result object. This provides fine-grained control over data retrieval and manipulation, suitable for memory-constrained environments or custom processing logic. Data can be accessed by column, row, or visited element by element. ```javascript // If desired, one or more chunks can be fetched from a result: const chunk = await result.fetchChunk(); const chunks = await result.fetchAllChunks(); // And then data can be retrieved from each chunk: const columnValues = chunk.getColumnValues(columnIndex); const columns = chunk.getColumns(); const rowValues = chunk.getRowValues(rowIndex); const rows = chunk.getRows(); // Or, values can be visited: chunk.visitColumnValues(columnIndex, (value, rowIndex, columnIndex, type) => { /* ... */ } ); chunk.visitColumns((column, columnIndex, type) => { /* ... */ }); chunk.visitColumnMajor( (value, rowIndex, columnIndex, type) => { /* ... */ } ); chunk.visitRowValues(rowIndex, (value, rowIndex, columnIndex, type) => { /* ... */ } ); chunk.visitRows((row, rowIndex) => { /* ... */ }); chunk.visitRowMajor( (value, rowIndex, columnIndex, type) => { /* ... */ } ); // Or converted: // The `converter` argument implements `DuckDBValueConverter`, // which has the single method convertValue(value, type). const columnValues = chunk.convertColumnValues(columnIndex, converter); const columns = chunk.convertColumns(converter); const rowValues = chunk.convertRowValues(rowIndex, converter); const rows = chunk.convertRows(converter); ``` -------------------------------- ### Inspect Result Metadata (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Retrieve column names and their corresponding data types from a query result. This is useful for understanding the structure of the returned data before processing it. ```javascript const columnNames = result.columnNames(); const columnTypes = result.columnTypes(); ``` -------------------------------- ### DuckDB Node.js (Neo) Client API Source: https://duckdb.org/docs/stable/clients/node_neo/overview This section provides an overview of the main features and functionalities of the DuckDB Node.js (Neo) client, including its differences from the older duckdb-node package and its roadmap. ```APIDOC ## DuckDB Node.js (Neo) Client API ### Description This API provides a high-level interface for using DuckDB in Node.js applications. It offers native Promise support, efficient handling of all DuckDB data types, and wraps released DuckDB binaries. ### Features - Native support for Promises. - DuckDB-specific API, not based on SQLite Node API. - Lossless & efficient support for values of all DuckDB data types. - Wraps released DuckDB binaries instead of rebuilding DuckDB. - Built on DuckDB's C API, exposing more functionality. ### Roadmap Some features are not yet complete, including binding MAP and UNION data types, appending default values row-by-row, user-defined types & functions, profiling info, table description, and APIs for Arrow. Refer to the GitHub issues list for the most up-to-date roadmap. ### Supported Platforms - Linux arm64 - Linux x64 - Mac OS X (Darwin) arm64 (Apple Silicon) - Mac OS X (Darwin) x64 (Intel) - Windows (Win32) x64 ``` -------------------------------- ### Retrieve All Result Data Asynchronously (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Asynchronously retrieve all data from a result object in various formats. This method is suitable when the entire result set needs to be loaded into memory at once. It provides access to columns and rows as arrays, JSON, or objects. ```javascript const columns = await result.getColumns(); const columnsJson = await result.getColumnsJson(); const columnsObject = await result.getColumnsObject(); const columnsObjectJson = await result.getColumnsObjectJson(); const rows = await result.getRows(); const rowsJson = await result.getRowsJson(); const rowObjects = await result.getRowObjects(); const rowObjectsJson = await result.getRowObjectsJson(); ``` -------------------------------- ### Fetch All Chunks from DuckDB Result (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview This code snippet demonstrates how to fetch all chunks from a DuckDB query result in a Node.js environment. It utilizes the `fetchAllChunks()` method provided by the client API. ```javascript const chunks = await result.fetchAllChunks(); ``` -------------------------------- ### Convert Query Results to JSON Columns (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Retrieves query results as an array of JSON-serializable columns. Each column is an array containing all values for that specific column across all rows. This is useful for column-oriented processing. ```javascript const reader = await connection.runAndReadAll( 'from test_all_types() select bigint, date, interval limit 2' ); const columns = reader.getColumnsJson(); // [ ... ] ``` ```javascript const reader = await connection.runAndReadAll( 'from test_all_types() select int_array, struct, map, "union" limit 2' ); const columns = reader.getColumnsJson(); // [ ... ] ``` -------------------------------- ### Fetch Chunks One by One (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview This snippet shows how to iteratively fetch chunks from a DuckDB result until no more rows are available. It's useful for processing large datasets in a streaming fashion, preventing memory overload. ```javascript const chunks = []; while (true) { const chunk = await result.fetchChunk(); // Last chunk will have zero rows. if (chunk.rowCount === 0) { break; } chunks.push(chunk); } ``` -------------------------------- ### Convert Query Results to JSON Column Objects (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Retrieves query results as a JSON-serializable object where keys are column names and values are arrays of column data. This provides a convenient way to access data by column name. ```javascript const reader = await connection.runAndReadAll( 'from test_all_types() select bigint, date, interval limit 2' ); const columnsObject = reader.getColumnsObjectJson(); // { ... } ``` ```javascript const reader = await connection.runAndReadAll( 'from test_all_types() select int_array, struct, map, "union" limit 2' ); const columnsObject = reader.getColumnsObjectJson(); // { ... } ``` -------------------------------- ### Convert DuckDB Data Type to String (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview This code snippet demonstrates how to convert a DuckDB data type object into its string representation using the `toString()` method. The resulting string is both human-readable and can be interpreted by DuckDB. ```javascript const typeString = columnType.toString(); ``` -------------------------------- ### Disconnect from DuckDB (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Shows how to explicitly disconnect from a DuckDB connection. While connections are often garbage collected, explicit disconnection can be useful for managing resources. ```javascript connection.disconnectSync(); // or, equivalently: connection.closeSync(); ``` -------------------------------- ### Access Materialized Chunks by Index (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview For materialized (non-streaming) results, this code demonstrates how to access individual chunks using their index. It retrieves the total row count and chunk count to iterate through all available chunks. ```javascript const rowCount = result.rowCount; const chunkCount = result.chunkCount; for (let i = 0; i < chunkCount; i++) { const chunk = result.getChunk(i); // ... } ``` -------------------------------- ### Convert Column Names and Types to JSON (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Serializes the names and detailed type information of query result columns into a JSON object. This is useful for introspection and understanding the schema of the returned data. ```javascript const reader = await connection.runAndReadAll( 'from test_all_types() select int_array, struct, map, "union" limit 2' ); const columnNamesAndTypes = reader.columnNamesAndTypesJson(); // { ... } ``` -------------------------------- ### Convert Query Results to JSON Rows (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Retrieves query results as an array of JSON-serializable rows. Each row is an array of values. This method is useful for obtaining data that can be directly parsed by JSON.stringify. ```javascript const reader = await connection.runAndReadAll( 'from test_all_types() select bigint, date, interval limit 2' ); const rows = reader.getRowsJson(); // [ ... ] ``` ```javascript const reader = await connection.runAndReadAll( 'from test_all_types() select int_array, struct, map, "union" limit 2' ); const rows = reader.getRowsJson(); // [ ... ] ``` -------------------------------- ### Convert Query Results to JSON Row Objects (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview Retrieves query results as an array of JSON-serializable row objects. Each object maps column names to their corresponding values. This format is convenient for direct use in applications that expect key-value pairs. ```javascript const reader = await connection.runAndReadAll( 'from test_all_types() select bigint, date, interval limit 2' ); const rowObjects = reader.getRowObjectsJson(); // [ ... ] ``` ```javascript const reader = await connection.runAndReadAll( 'from test_all_types() select int_array, struct, map, "union" limit 2' ); const rowObjects = reader.getRowObjectsJson(); // [ ... ] ``` -------------------------------- ### Inspect DuckDB Data Values in Node.js Source: https://duckdb.org/docs/stable/clients/node_neo/overview This snippet demonstrates how to inspect various DuckDB data types when using the Node.js client. It covers ARRAY, BIT, BLOB, DATE, DECIMAL, INTERVAL, LIST, MAP, STRUCT, TIMESTAMP variations, TIME variations, UNION, and UUID types, showing how to access their underlying values and string representations. ```typescript import { DuckDBTypeId } from '@duckdb/node-api'; if (columnType.typeId === DuckDBTypeId.ARRAY) { const arrayItems = columnValue.items; // array of values const arrayString = columnValue.toString(); } if (columnType.typeId === DuckDBTypeId.BIT) { const bools = columnValue.toBools(); // array of booleans const bits = columnValue.toBits(); // array of 0s and 1s const bitString = columnValue.toString(); // string of '0's and '1's } if (columnType.typeId === DuckDBTypeId.BLOB) { const blobBytes = columnValue.bytes; // Uint8Array const blobString = columnValue.toString(); } if (columnType.typeId === DuckDBTypeId.DATE) { const dateDays = columnValue.days; const dateString = columnValue.toString(); const { year, month, day } = columnValue.toParts(); } if (columnType.typeId === DuckDBTypeId.DECIMAL) { const decimalWidth = columnValue.width; const decimalScale = columnValue.scale; // Scaled-up value. Represented number is value/(10^scale). const decimalValue = columnValue.value; // bigint const decimalString = columnValue.toString(); const decimalDouble = columnValue.toDouble(); } if (columnType.typeId === DuckDBTypeId.INTERVAL) { const intervalMonths = columnValue.months; const intervalDays = columnValue.days; const intervalMicros = columnValue.micros; // bigint const intervalString = columnValue.toString(); } if (columnType.typeId === DuckDBTypeId.LIST) { const listItems = columnValue.items; // array of values const listString = columnValue.toString(); } if (columnType.typeId === DuckDBTypeId.MAP) { const mapEntries = columnValue.entries; // array of { key, value } const mapString = columnValue.toString(); } if (columnType.typeId === DuckDBTypeId.STRUCT) { // { name1: value1, name2: value2, ... } const structEntries = columnValue.entries; const structString = columnValue.toString(); } if (columnType.typeId === DuckDBTypeId.TIMESTAMP_MS) { const timestampMillis = columnValue.milliseconds; // bigint const timestampMillisString = columnValue.toString(); } if (columnType.typeId === DuckDBTypeId.TIMESTAMP_NS) { const timestampNanos = columnValue.nanoseconds; // bigint const timestampNanosString = columnValue.toString(); } if (columnType.typeId === DuckDBTypeId.TIMESTAMP_S) { const timestampSecs = columnValue.seconds; // bigint const timestampSecsString = columnValue.toString(); } if (columnType.typeId === DuckDBTypeId.TIMESTAMP_TZ) { const timestampTZMicros = columnValue.micros; // bigint const timestampTZString = columnValue.toString(); const { date: { year, month, day }, time: { hour, min, sec, micros }, } = columnValue.toParts(); } if (columnType.typeId === DuckDBTypeId.TIMESTAMP) { const timestampMicros = columnValue.micros; // bigint const timestampString = columnValue.toString(); const { date: { year, month, day }, time: { hour, min, sec, micros }, } = columnValue.toParts(); } if (columnType.typeId === DuckDBTypeId.TIME_TZ) { const timeTZMicros = columnValue.micros; // bigint const timeTZOffset = columnValue.offset; const timeTZString = columnValue.toString(); const { time: { hour, min, sec, micros }, offset, } = columnValue.toParts(); } if (columnType.typeId === DuckDBTypeId.TIME) { const timeMicros = columnValue.micros; // bigint const timeString = columnValue.toString(); const { hour, min, sec, micros } = columnValue.toParts(); } if (columnType.typeId === DuckDBTypeId.UNION) { const unionTag = columnValue.tag; const unionValue = columnValue.value; const unionValueString = columnValue.toString(); } if (columnType.typeId === DuckDBTypeId.UUID) { const uuidHugeint = columnValue.hugeint; // bigint const uuidString = columnValue.toString(); } // other possible values are: null, boolean, number, bigint, or string ``` -------------------------------- ### Inspect DuckDB Data Types (Node.js) Source: https://duckdb.org/docs/stable/clients/node_neo/overview This snippet shows how to inspect various DuckDB data types using the `DuckDBTypeId` enum. It covers common types like ARRAY, DECIMAL, ENUM, LIST, MAP, STRUCT, and UNION, extracting specific properties for each. ```javascript import { DuckDBTypeId } from '@duckdb/node-api'; if (columnType.typeId === DuckDBTypeId.ARRAY) { const arrayValueType = columnType.valueType; const arrayLength = columnType.length; } if (columnType.typeId === DuckDBTypeId.DECIMAL) { const decimalWidth = columnType.width; const decimalScale = columnType.scale; } if (columnType.typeId === DuckDBTypeId.ENUM) { const enumValues = columnType.values; } if (columnType.typeId === DuckDBTypeId.LIST) { const listValueType = columnType.valueType; } if (columnType.typeId === DuckDBTypeId.MAP) { const mapKeyType = columnType.keyType; const mapValueType = columnType.valueType; } if (columnType.typeId === DuckDBTypeId.STRUCT) { const structEntryNames = columnType.names; const structEntryTypes = columnType.valueTypes; } if (columnType.typeId === DuckDBTypeId.UNION) { const unionMemberTags = columnType.memberTags; const unionMemberTypes = columnType.memberTypes; } // For the JSON type (https://duckdb.org/docs/data/json/json_type) if (columnType.alias === 'JSON') { const json = JSON.parse(columnValue); } ``` -------------------------------- ### Set Timezone Offset for TIMESTAMP_TZ in Node.js Source: https://duckdb.org/docs/stable/clients/node_neo/overview This snippet shows how to change the default timezone offset used for converting TIMESTAMP_TZ values to strings in the DuckDB Node.js client. It demonstrates setting a fixed offset and dynamically setting it based on DuckDB's current timezone setting. ```typescript import { DuckDBTimestampTZValue } from '@duckdb/node-api'; // Set a fixed timezone offset (e.g., PST) DuckDBTimestampTZValue.timezoneOffsetInMinutes = -8 * 60; const pst = DuckDBTimestampTZValue.Epoch.toString(); // Expected output: 1969-12-31 16:00:00-08 // Set another fixed timezone offset (e.g., CET) DuckDBTimestampTZValue.timezoneOffsetInMinutes = +1 * 60; const cet = DuckDBTimestampTZValue.Epoch.toString(); // Expected output: 1970-01-01 01:00:00+01 // Dynamically set timezone offset to match DuckDB's TimeZone setting // Assuming 'connection' is an established DuckDB connection object // const reader = await connection.runAndReadAll( // `select (timezone(current_timestamp) / 60)::int` // ); // DuckDBTimestampTZValue.timezoneOffsetInMinutes = // reader.getColumns()[0][0]; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.