A native, high-performance TypeScript reimplementation of the JustyBase.NetezzaDriver.
It allows for direct connection to IBM Netezza / PureData System for Analytics databases without the need for ODBC drivers or external dependencies.
- Pure TypeScript: No native bindings, no ODBC/CLI required.
- High Performance: one growable read buffer per connection, discarded rows skipped by length, with offline replay benchmarks in
PERFORMANCE.md. - pg-style
query():connection.query()/pool.query()return bufferedQueryResult(rows,rowCount,fields). - ADO.NET Style API: Familiar Connection/Command/Reader pattern when you need streaming readers.
- Connection strings:
netezza:///nz://URIs viaparseConnectionStringornew NzConnection(uri). - Connection Pool: Built-in
NzPoolwith configurable limits, timeouts, and idle management. - Structured errors: Backend failures throw
NzDatabaseErrorwith SQLSTATE / severity / detail when present. - Security & Audit: SSL/TLS, MD5/SHA256 authentication, and Guardium audit metadata.
- Strongly Typed: Full TypeScript support; dual CJS + ESM builds.
npm install @justybase/netezza-driverRequires Node.js >= 22.0.0.
The package root has everything. Subpaths let a consumer import only what it needs; every subpath resolves in both ESM and CommonJS, and re-exports the same objects as the root (one module instance, no duplicated code):
| Specifier | Exports |
|---|---|
@justybase/netezza-driver |
the complete public API |
@justybase/netezza-driver/pool |
NzPool, NzPoolConfig, PoolHealthCheckResult |
@justybase/netezza-driver/metadata |
NzMetadata, catalog interfaces, DDL builders |
@justybase/netezza-driver/types |
NzDate, NzTime, NzTimestamp, value parsers |
@justybase/netezza-driver/errors |
NzDatabaseError, NzTimeoutError, NzProtocolError |
import { NzPool } from '@justybase/netezza-driver/pool';
import { NzMetadata } from '@justybase/netezza-driver/metadata';
import { NzDatabaseError } from '@justybase/netezza-driver/errors';Deep imports into dist/ are not supported; use these specifiers instead.
4.0.0 is a major release because a few behaviours are now stricter:
| Change | What to do |
|---|---|
| Config is validated in the constructor | Pass a real port (1–65535) and finite connectionTimeout / commandTimeout. 0 still disables a deadline. |
securityLevel / sslmode must be valid |
Fix typos such as requier; they now throw instead of falling back to plaintext. |
release() no longer throws on a second call |
Remove the try/catch workaround; a double release is a no-op. |
| ESM declarations are separate from CJS | If you deep-import from dist/cjs, switch to @justybase/netezza-driver; exports is the supported entry point. |
Everything else in the public API keeps working. See
CHANGELOG.md for the full list.
The repository includes a standalone Electron SQL Editor example that demonstrates this driver in a small desktop application. It keeps all Netezza communication in Electron's main process and showcases connections, schema browsing, SQL completion, multiple result sets, filtering/grouping, CSV/XLSX/XLSB import and export, and query cancellation.
The example has its own dependencies and build workflow; it is not included in the published driver package. The Electron workflow builds unsigned macOS (x64/arm64), Linux (x64), and Windows (x64) installers and archives as separate GitHub Actions artifacts.
import { NzConnection } from '@justybase/netezza-driver';
async function example() {
// Object config or connection string
const connection = new NzConnection({
host: 'your-nz-host',
database: 'system',
user: 'admin',
password: 'password',
// port: 5480, // default
});
// const connection = new NzConnection('netezza://admin:password@your-nz-host:5480/system');
await connection.connect();
try {
const result = await connection.query(
'SELECT TABLENAME FROM _V_TABLE WHERE TABLENAME = $1 LIMIT 5',
['DIMDATE']
);
for (const row of result.rows) {
console.log(row.TABLENAME);
}
console.log('rowCount:', result.rowCount);
} finally {
await connection.close();
}
}query() is generic: pass your row shape as the type argument and result.rows
becomes T[] instead of Record<string, unknown>[]. This works on both
connection.query<T>() and pool.query<T>().
interface TableRow {
TABLENAME: string;
ROWS: number;
}
const result = await connection.query<TableRow>(
'SELECT TABLENAME, ROWS FROM _V_TABLE WHERE TABLENAME = $1 LIMIT 5',
['DIMDATE']
);
// result.rows is TableRow[] — fully typed, no casts needed
for (const row of result.rows) {
console.log(row.TABLENAME, row.ROWS);
}Without a type argument the rows stay QueryResultRow
(Record<string, unknown>), preserving the default strict-but-unknown contract.
The streaming API is typed the same way: executeReader<T>() on a connection or
NzCommand returns an NzDataReader<T> whose getRowObject() and async
iteration are typed.
const reader = await connection
.createCommand('SELECT TABLENAME FROM _V_TABLE LIMIT 5')
.executeReader<{ TABLENAME: string }>();
try {
for await (const row of reader) {
console.log(row.TABLENAME); // string
}
} finally {
await reader.close();
}getRowObject() also accepts a per-call type argument, so you can type an
individual row even on a reader created without a type parameter:
const row = reader.getRowObject<{ TABLENAME: string }>();Netezza’s simple-query path used by this driver does not expose server-side bind/prepared parameters. $1, $2, … placeholders are escaped client-side and interpolated into the SQL text before send (escapeLiteral / substituteParameters). Prefer primitives (null, boolean, number, bigint, string, Date, Buffer); unsupported object shapes are rejected.
import { parseConnectionString, NzConnection } from '@justybase/netezza-driver';
const config = parseConnectionString(
'netezza://admin:secret@host:5480/JUST_DATA?sslmode=require&appName=myapp'
);
const connection = new NzConnection(config);
// or: new NzConnection('nz://admin:secret@host/JUST_DATA');The handshake identifies the connection as a Node.js client by default
(clientType = 15). For compatibility with systems that require another
client identity, set clientType in the object configuration:
import { ClientTypeId, NzConnection } from '@justybase/netezza-driver';
const connection = new NzConnection({
host: 'your-nz-host',
database: 'JUST_DATA',
user: 'admin',
password: 'password',
clientType: ClientTypeId.Node, // 15, default
// clientType: ClientTypeId.SqlDotnet, // 11, compatibility fallback
});Known identifiers are available as ClientTypeId: Invalid (-1), None
(0), Sql (1), SqlOdbc (2), SqlJdbc (3), Load (4), Client (5),
Bnr (6), Reclaim (7), Unknown (8), SqlOledb (9), Internal (10),
SqlDotnet (11), SqlGolang (12), SqlPython (13), Unknown2 (14), and
Node (15). Other signed 16-bit values can also be supplied for server-
specific or future client types. This option is available in object
configuration; connection-string query parameters do not change it.
Two independent deadlines are supported:
| Option | Where | Default | Meaning |
|---|---|---|---|
connectionTimeout |
config / ?connectionTimeout= |
10 s |
socket + handshake, also used for the cancel request |
commandTimeout |
config / ?commandTimeout= / NzCommand.commandTimeout |
30 s |
execute() / executeReader() startup |
0 disables a deadline. Invalid values are rejected in the constructor instead
of silently disabling it. A command that exceeds its deadline rejects with
NzTimeoutError (code NZ_TIMEOUT) and the driver sends a cancel request in
the background; the connection stays usable.
const connection = new NzConnection({
// ...
connectionTimeout: 15, // seconds, 0 = no deadline
commandTimeout: 120,
});
connection.commandTimeout = 60; // default for new commands
connection.createCommand('SELECT 1').commandTimeout = 5; // per commandA statement batch (SELECT 1; SELECT 2) produces several result sets. The
reader exposes the first one; nextResult() advances to the next row-returning
result and returns false when there are none left:
const reader = await connection.createCommand('SELECT 1 AS a; SELECT 2 AS b').executeReader();
do {
while (await reader.read()) {
console.log(reader.getRowObject());
}
} while (await reader.nextResult());
await reader.close();close() is always required (or for await, which closes automatically); it
drains the unread protocol bytes up to ReadyForQuery so the connection can be
reused. If the drain hits a protocol fault, close() rethrows it rather than
pretending the session is healthy.
Failed queries and authentication errors throw NzDatabaseError (extends Error) with optional severity, code (SQLSTATE), detail, hint, and raw payload fields.
import { NzDatabaseError } from '@justybase/netezza-driver';
try {
await connection.query('SELECT * FROM no_such_table');
} catch (err) {
if (err instanceof NzDatabaseError) {
console.error(err.code, err.message, err.detail);
}
throw err;
}Three error classes are exported, so callers can react to the category without matching message text:
| Class | code |
Meaning |
|---|---|---|
NzDatabaseError |
SQLSTATE when sent | The server rejected the SQL or the login |
NzProtocolError |
— | The byte stream is out of sync; the connection requires a reconnect |
NzTimeoutError |
NZ_TIMEOUT |
A command, connect or cancel exceeded its deadline |
import { isNzTimeoutError, NzProtocolError } from '@justybase/netezza-driver';
try {
await connection.query(sql);
} catch (err) {
if (isNzTimeoutError(err)) {
// the connection is still usable; the command was cancelled
} else if (err instanceof NzProtocolError) {
// discard the connection, a pool will open a new one on the next checkout
}
}securityLevel selects the TLS policy sent in the handshake. It is validated,
so a misspelling fails immediately instead of silently leaving the session
unencrypted:
import { SecurityLevel } from '@justybase/netezza-driver';
const connection = new NzConnection({
// ...
securityLevel: SecurityLevel.OnlySecuredSession,
});The accepted values are PreferredUnsecured (default), OnlyUnsecuredSession,
PreferredSecuredSession and OnlySecuredSession, matched case-insensitively.
OnlyUnsecuredSession is enforced: if the server refuses a plaintext session the
connect fails instead of silently upgrading to TLS.
With a connection string, ?sslmode= accepts the libpq spellings, and the
certificate policy follows libpq:
sslmode |
TLS | Certificate chain | Hostname |
|---|---|---|---|
disable |
never | — | — |
allow / prefer |
preferred | verified | not checked |
require |
required | not checked | not checked |
verify-ca |
required | verified | not checked |
verify-full |
required | verified | verified |
An unknown sslmode is an error rather than a silent fallback, and
verify-ca/verify-full combined with rejectUnauthorized=false is rejected:
those modes promise chain validation, so disabling it is a contradiction rather
than a preference. rejectUnauthorized accepts true/false in any case
(yes/no, on/off, 1/0); anything else is an error instead of being
read as false.
import { NzPool } from '@justybase/netezza-driver';
const pool = new NzPool({
host: 'your-nz-host',
database: 'system',
user: 'admin',
password: 'password',
max: 10,
idleTimeoutMillis: 30000,
});
async function runQuery() {
const result = await pool.query('SELECT 1 AS n');
console.log(result.rows[0].n);
}pool.transaction() takes a connection, opens a transaction, commits on
success and rolls back when the callback throws. It releases the connection in
every outcome, so it cannot leak a checkout:
const orderId = await pool.transaction(async (conn) => {
await conn.execute('INSERT INTO orders (id) VALUES ($1)', [1]);
await conn.execute('INSERT INTO lines (order_id) VALUES ($1)', [1]);
return 1;
});
// Committed. On a throw, both inserts are rolled back and the error is rethrown.A successful rollback leaves the session clean, so a business-level error from the callback does not destroy a healthy connection. Only a failure that leaves the protocol or transaction state unknown removes it.
pool.healthCheck() probes a pooled connection with SELECT 1. It never
throws for a failed probe; it reports the failure and discards that connection,
so a dead session is not handed to the next checkout:
const { ok, latencyMs, error } = await pool.healthCheck();
if (!ok) logger.warn('pool probe failed', latencyMs, error?.message);A checked-out connection that is released while an explicit transaction is
still open is rolled back before it can be handed to the next caller, so an
uncommitted transaction (and its uncommitted data) never leaks into another
checkout. This is controlled by rollbackOnRelease (default true):
const pool = new NzPool({
// ...
rollbackOnRelease: true, // default
});
const { client, release } = await pool.connect();
try {
await client.beginTransaction();
await client.execute("INSERT INTO t VALUES (1)");
await client.commit();
} finally {
// If the commit above did not run, the pool rolls the transaction back
// here before returning the connection to the idle queue.
release();
}The transaction state is tracked from the statements the driver sends
(BEGIN / START TRANSACTION open it, COMMIT / ROLLBACK / END / ABORT
close it). A failed COMMIT/ROLLBACK keeps the transaction marked open so the
pool still rolls it back on release.
Only a statement-initial keyword counts, and the scan blanks out everything
whose content is not SQL syntax first — string literals, quoted identifiers,
dollar-quoted bodies, AS BEGIN_PROC ... END_PROC bodies and comments. So
INSERT INTO t VALUES ('a;COMMIT') or a procedure body containing END;
cannot be mistaken for a transaction boundary. Netezza neither reports the state
in ReadyForQuery nor errors on a ROLLBACK outside a transaction (it returns
a notice), so a defensive rollback is harmless; the scan is a lexer rather than
a full SQL parser, and any mistracking errs towards the harmless extra
ROLLBACK. Open transactions through pool.query() are not supported at all -
use pool.transaction() or pool.connect() when you need one.
release(err) keeps its meaning: passing an error destroys the connection. The
only behaviour change is which failures pool.query() / pool.executeNonQuery()
consider fatal. A SQL-level failure (NzDatabaseError, e.g. an unknown table)
leaves a healthy session that is returned to the pool, while protocol faults
(NzProtocolError) and socket failures still destroy the connection.
When you need streaming readers, cancellation, or fine-grained command control, use Connection / Command / Reader:
import { NzConnection } from '@justybase/netezza-driver';
async function example() {
const connection = new NzConnection({
host: 'your-nz-host',
database: 'system',
user: 'admin',
password: 'password',
});
await connection.connect();
try {
const reader = await connection
.createCommand('SELECT TABLENAME FROM _V_TABLE ORDER BY TABLENAME LIMIT 5')
.executeReader();
try {
while (await reader.read()) {
console.log(`Found table: ${reader.getString(0)}`);
}
} finally {
await reader.close();
}
} finally {
await connection.close();
}
}The connection.meta helper exposes catalog methods for schemas, databases, tables, columns, views, procedures, functions, synonyms, sessions, sequences, users, groups, query history, keys, comments and owners. It reconstructs DDL for tables, views, procedures, external tables and synonyms.
const ddl = await connection.meta.getTableDdl('DIMDATE', 'ADMIN');
const columns = await connection.meta.getDetailedColumns('DIMDATE', 'ADMIN');
const results = await connection.meta.getTablesDdl('ADMIN', undefined, ['DIMDATE']);Batch DDL results include an error for each object that could not be reconstructed. Pass a full signature for an overloaded procedure.
The handshake reports an application name, OS user and client hostname. They are
detected from the process by default (script name, USERNAME/USER,
os.hostname()), and are only sent when the server negotiates handshake version
4 or 6; version 2/3/5 does not carry these fields at all.
const connection = new NzConnection({
// ... basic connection info
appName: 'MyDataService',
osUser: 'service-account',
clientHostName: 'worker-node-1',
});An explicit empty string is honoured and sent as-is, without falling back to the detected value:
const connection = new NzConnection({
// ...
osUser: '', // sent as an empty field, not as the real OS login
});Set clientMetadata: false (or ?clientMetadata=false in a connection string)
to blank all three fields at once. Fields set explicitly in the config still win:
const connection = new NzConnection({
// ...
clientMetadata: false, // appName/osUser/clientHostName all become ''
appName: 'MyDataService', // ... except this one
});Note that the server derives _V_SESSION.CLIENT_HOST from reverse DNS, not from
clientHostName, so that column is populated regardless. Some servers also read
the OS login from a SQL literal such as 'OS Username: <value>' for certain
client types; the driver never sends such a statement.
This driver exposes both a pg-style buffered query() API and ADO.NET-inspired connection/command/reader abstractions. The design mirrors common C# database client patterns for streaming use cases.
Important: this project is an independent TypeScript implementation and does not reuse code from the node-netezza package. The functional and architectural inspiration comes from the C# implementation referenced above.
The primary live compatibility reference is the C# JustyBase.NetezzaDriver; node-netezza is only an optional comparison in tools/examples/performance_test.js.
The shared corpus lives in the multi-driver workspace at ../conformance
(a sibling of this repository, not part of the published package), so these
commands only work from that workspace checkout. It provisions its own
CONFORMANCE schema on a live appliance and runs the same case corpus against
Node, Rust, C# and Python.
..\conformance\run-all.ps1 -Profile smoke -Bootstrap
..\conformance\run-all.ps1 -Profile full -BootstrapThis driver is executed by tools/conformance/runner.js. The report contains
the case matrix, known divergences and JUnit XML. Build the driver first
(npm run build). Host and credentials come only from NZ_DEV_HOST and the
other NZ_DEV_* variables; there is no hard-coded lab address or password.
Repository CI runs formatting checks, Biome lint, TypeScript typechecks and
compile-time type tests, and offline unit tests on Node 22.x and 24.x. Live
Netezza smoke/full suites stay local. The published package engines field
requires >=22.0.0.
| Variable | Purpose |
|---|---|
NZ_DEV_HOST |
Netezza host (required for integration tests unless lab defaults) |
NZ_DEV_PASSWORD |
Password (required unless lab defaults) |
NZ_DEV_PORT |
Port (default 5480) |
NZ_DEV_DATABASE |
Database (default JUST_DATA) |
NZ_DEV_USER |
User (default admin) |
NZ_USE_LAB_DEFAULTS |
Set to 1 to allow hardcoded lab defaults when host/password are unset |
NZ_SSL_CERT_PATH |
Optional trusted cert for SSL tests |
NZ_LOCAL_TMP_DIR |
Optional temp dir for external-table tests / examples |
See .env.example for a copy-paste template.
The appliance names the import/export file when it drives an external-table operation, and the driver opens that path on the client. Point the driver at a directory you are willing to expose:
const connection = new NzConnection({
// ...
externalTableDirectory: 'C:\\nz-extab', // import/export files
externalTableLogDirectory: 'C:\\nz-extab\\logs', // .nzlog/.nzbad/.nzstats
});A path outside those directories fails the command instead of being opened. If the options are unset the previous behaviour is kept, which allows any path the server names — set them for any deployment where the appliance is not fully trusted.
# Windows (PowerShell)
$env:NZ_DEV_HOST="127.0.0.1"
$env:NZ_DEV_PASSWORD="your_password"
# Linux/macOS
export NZ_DEV_HOST=127.0.0.1
export NZ_DEV_PASSWORD=your_passwordnpm run test:unitThe offline suite needs no database. It covers the protocol framing and length validation, both row decoders (text and DBOS), numeric/temporal/type conversions, SQL parameter substitution, connection-string and TLS policy, transaction tracking, pool lifecycle, the reader's result boundaries, timeouts, cancel deadlines, metadata/DDL reconstruction and external-table handling, plus byte-exact replay fixtures for the three shared benchmarks.
Compile-time type tests in tests/types/ guard the generic
query<T>() / executeReader<T>() typings (and the typed rows they return),
and published-dts.test-d.ts compiles
against dist/cjs/index.d.ts, so the packaged declarations are checked too:
npm run typecheck:typesCI also enforces a coverage threshold (jest.config.js, coverageThreshold)
and verifies the tarball contents with npm run verify:package.
Requires a live Netezza server and NZ_DEV_HOST + NZ_DEV_PASSWORD (or NZ_USE_LAB_DEFAULTS=1).
npm test
# or
npm run test:smokeThe live compatibility tests compare this driver with
JustyBase.NetezzaDriver 1.7.2, without requiring ODBC or native bindings:
dotnet --version
npm run test:reference # smoke: 16 queries, one C# process
npm run test:reference:full # full: ~700 queries ported from the old ODBC suiteThe reference runner targets .NET 10 and emits typed JSON values, so large
BIGINT and NUMERIC values are compared without JavaScript number rounding.
Batch mode (--batch) reuses a single C# process and connection for many
queries. Comparison is strict (column names + values) with a closed list of
representation equivalences in tests/helpers/csharpReference.js (float32
print format, 28-digit decimal limit, empty-string vs null quirk of the C#
driver, read-time timestamp skew); skipped queries live in knownDivergences
in tests/CSharpComparison.test.js.
The full suite needs a live server plus dotnet and stays local-only — it is
excluded from npm run test:full and from CI. The legacy ODBC comparison
suites were removed; C# is the sole live compatibility reference.
npm run test:fullnpm run check # format + lint (Biome) + typecheck + type tests
npm run lint # Biome lint (errors fail the build)
npm run typecheck # tsc --noEmit on the CJS and ESM configs
npm run typecheck:types # compile-time type tests (tests/types)npm run test:debug
npx jest tests/BasicTests.test.js --config jest.config.js --runInBandUse the public metadata methods on NzDataReader when you need server type information.
const reader = await connection
.createCommand(`
SELECT
'AA'::NVARCHAR(32) AS NVC,
CURRENT_DATE AS CD
FROM JUST_DATA..DIMACCOUNT
LIMIT 1
`)
.executeReader();
const metadata = reader.getColumnMetadata(0);
console.log(metadata.typeName); // NVARCHAR
console.log(metadata.declaredTypeName); // NVARCHAR(32)
console.log(metadata.providerType); // 2530For compatibility, getTypeName() continues to return canonical base names such as VARCHAR, NVARCHAR, NCHAR, DATE, and TIMESTAMPTZ. Use getDeclaredTypeName() or getColumnMetadata() when you also need declared lengths like VARCHAR(32).
Starting in 2.0.0, loose text-protocol queries and table-backed binary queries use the same JavaScript value contract whenever the server provides a known type OID.
The main mappings are BOOL -> boolean, BYTEINT/INT2/INT4/OID -> number, INT8 -> bigint, DATE/TIMESTAMP/TIMESTAMPTZ/ABSTIME -> Date, TIME -> TimeValue, and NUMERIC -> number | string using the existing precision-preserving rule.
Each result set keeps one decoded value per distinct cell in every column, so
repeated strings, numeric text, dates, times and timestamps are returned as the
same object/primitive without decoding again. The cache is bounded per column
and switches itself off for high-cardinality columns. Set valueCache: false
in the connection config to opt out.
DATE and TIMESTAMP cells are NzDate/NzTimestamp: immutable Date
subclasses that keep instanceof Date and every read method, but throw on
mutators such as setTime. TIME cells are immutable NzTime objects with the
same toString() shape as before. Copy a temporal value with
new Date(row.date) when you need a mutable object.
Repeated numeric values are strings only when the precision rule already
required a string; the primitive number form is unaffected.
npm run buildProduces dual packages under dist/cjs (CommonJS) and dist/esm (ES modules).
Optional API docs:
npm run docs