Skip to content

Node.js driver

View as Markdown

node-coradb (@coradb/node-coradb) is the Node.js driver for CoraDB. It is written in 100% JavaScript, implements the CoraDB broker protocol itself and needs no native compilation; its only runtime dependency is luxon, for time-zone values. TypeScript definitions are included (index.d.ts).

  • Promise-first API with server-side value binding: sql(), stream(), cursor(), prepare(), executeMulti(), transaction().
  • Every call takes a time limit (timeoutMs) and an AbortSignal; a running statement is cancelled on the server.
  • All data types, including LOBs, ENUM, JSON, time-zone types and the collections SET, MULTISET and LIST (read as arrays).
  • Alternative hosts and connection retries, request queueing, generated keys, query plans.
  • The classic callback API of node-cubrid is still available.

Requires Node.js 20 or newer.

npm install @coradb/node-coradb
const CoraDB = require('@coradb/node-coradb');
// or: import CoraDB from '@coradb/node-coradb';
const conn = CoraDB.createConnection({
host: 'localhost', // or 'host:port', or ['db1:33000', 'db2:33000'] tried in order
port: 33000,
user: 'dba',
password: '',
database: 'e-commerce',
connectionTimeout: 10000, // ms
requestTimeoutMs: 30000, // default time limit for every call
});

The connection opens on the first request (or call await conn.connect()), and requests made on one connection run one after the other, in order. Close it with await conn.close().

Option Default Meaning
host / hosts localhost Broker host, host:port, or an array of them tried in order.
port 33000 Broker port for hosts without one.
user / password PUBLIC / empty Credentials.
database — Database name.
connectionTimeout 0 (none) Connect timeout in milliseconds.
maxConnectionRetryCount 1 Retries when connecting fails.
requestTimeoutMs 0 (none) Default timeoutMs of every call.
queryTimeout 0 (none) Server-side time limit of each statement, in milliseconds.
logger none An object with debug and info methods.

All options are described in the API reference.

sql() runs one statement, binds the ? values on the server and returns all rows as objects:

const { rows } = await conn.sql(
'SELECT name, unit_price FROM product WHERE unit_price > ? ORDER BY unit_price DESC LIMIT 3',
[90]);
// rows: [{ name: 'Côte de Blaye', unit_price: 263.5 }, { name: 'Thüringer Rostbratwurst', unit_price: 123.79 }, { name: 'Lando Gym Jacket', unit_price: 99 }]
Result field Content
rows The rows, as { column: value } objects (or arrays with { rowsAs: 'arrays' })
columns { name, type, table, nullable, precision, scale } for each column
rowCount Number of rows returned
affectedRows Rows changed by INSERT, UPDATE, DELETE …

A graph query is just another statement. Use aliases (or rowsAs: 'arrays') when two columns would have the same name:

const { rows } = await conn.sql(`
SELECT b.name AS brand, COUNT(cu) AS followers
FROM MATCH (cu:customer)-[:follows]->(b:brand)
GROUP BY b.name ORDER BY followers DESC LIMIT ?`, [3]);
// [{ brand: 'Nike', followers: 209 }, { brand: 'Adidas', followers: 132 }, { brand: 'Puma', followers: 94 }]

Values are bound with a type taken from the JavaScript value (string → VARCHAR, integer → INT or BIGINT, other number → DOUBLE, Date → DATETIME, Buffer → VARBIT, null → NULL). Give the type yourself when needed:

await conn.sql('UPDATE product SET unit_price = ? WHERE id = ?',
[{ type: 'numeric', value: '52.90' }, 1379]);
// one row at a time, fetched a batch at a time
for await (const row of conn.stream('SELECT * FROM order_items WHERE quantity > ?', [2])) {
process(row); // leaving the loop early closes the result
}
// paging under your control
const cursor = await conn.cursor('SELECT id, order_date FROM orders ORDER BY id');
console.log(cursor.total); // 2910
let batch = await cursor.next();
while (batch.length) { show(batch); batch = await cursor.next(); }
const stmt = await conn.prepare('UPDATE product SET units_in_stock = units_in_stock + ? WHERE id = ?');
for (const { id, qty } of deliveries) {
await stmt.run([qty, id]);
}
await stmt.close();

transaction() turns auto-commit off, runs the function, commits when it resolves and rolls back when it throws:

await conn.transaction(async (c) => {
await c.sql(`INSERT INTO orders (id, customer_id, order_date, shipping_cost, ship_address)
VALUES (?, ?, SYSDATE, ?, ?)`, [9001, 5, 4.9, 'Storgatan 1, Luleå']);
await c.sql(`INSERT INTO order_items (order_id, product_id, quantity, discount_pct)
VALUES (?, ?, ?, 0)`, [9001, 1379, 2]);
});

For manual control use setAutoCommitMode(false), then commit() or rollback() (beginTransaction() / endTransaction() still work but are deprecated). Changing the auto-commit mode commits pending work, as JDBC does.

await conn.sql(sql, params, { timeoutMs: 5000 }); // this call only
const controller = new AbortController();
const p = conn.sql(sql, params, { signal: controller.signal });
controller.abort(); // p rejects with an AbortError

When the time runs out, the running statement is cancelled through the broker and the connection stays usable. conn.setQueryTimeout(ms) sets a limit enforced by the server itself.

Every failure is a CoraDB.CoraDBError with:

  • code: the server's (negative) error number, or a driver code such as TIMEOUT, INVALID_PARAMETER, STATEMENT_CLOSED;
  • statement: the SQL text, when known;
  • retryable: true for transient errors (deadlock victim, lock timeout, no CAS free) — also CoraDB.isRetryable(err).
try {
await conn.sql('INSERT INTO countries (code, name) VALUES (?, ?)', ['FRA', 'France']);
} catch (err) {
if (err instanceof CoraDB.CoraDBError) console.error(err.code, err.message);
else throw err; // socket errors (ECONNREFUSED, ...) pass through as Node reports them
}

A failed batch rejects with CoraDB.CoraDBBatchError, which lists each failed statement.

node-coradb started as node-cubrid 11.0.0 and keeps its API, so moving an application is mostly a rename:

  1. npm uninstall node-cubrid && npm install @coradb/node-coradb (Node.js 20+; moment-timezone is replaced by luxon).
  2. Rename: require('node-cubrid') → require('@coradb/node-coradb'), createCUBRIDConnection() → createCoraDBConnection() (or createConnection()), CUBRIDDataType / CUBRIDSchemaType / CUBRIDIsolationLevel … → CoraDBDataType / CoraDBSchemaType / CoraDBIsolationLevel …, CUBRID_STMT_* → CORADB_STMT_*.
  3. Delete your own declare module 'node-cubrid' type shims: the package ships its types.
  4. Check the behaviours that changed on purpose:
    • execute(), batchExecuteNoQuery() and executeWithTypedParams() now resolve with the number of changed rows.
    • BIGINT and NUMERIC values that a JavaScript number cannot hold exactly come back as strings; SMALLINT is signed; zero dates are null; collections are arrays; strings are decoded in the column's charset.
    • Every rejection is a CoraDBError; CAS error codes use the current numbering (-10007, not -1007).
    • Changing the auto-commit mode commits pending work; after a lost connection with auto-commit off, requests fail with TRANSACTION_LOST until you roll back.
    • Values written into the SQL text are escaped by doubling quotes only; prefer sql() with bound values.

The complete API — the everyday API, connection options, the classic query() / execute() / fetch() methods, batches, schema information, LOBs, query plans and cancelling — is in the Node.js driver API reference.