NusaDB

Documentation / Clients and protocol

Clients and protocol

The official drivers and how to use them, connection settings, TLS and authentication, and the protocol behaviour a client sees.

Wire protocol

NusaDB has its own wire protocol. A client built for another database engine sends a handshake the server does not recognise, gets no reply, and times out. No server setting changes this.

The SQL dialect is independent of the protocol. Queries written for other engines usually run unchanged over a NusaDB connection, so porting an application mostly means changing its driver and connection settings.

Official clients

Every driver speaks the protocol directly with no native dependencies, binds parameters as $1, $2, ..., and returns typed values (an INT column arrives as the host language's integer, NUMERIC as a decimal, TIMESTAMPTZ as a datetime, JSON parsed).

ClientInstallNotes
nusadb-cliin the container image and every releaseinteractive shell and batch runner
Pythonpip install nusadb (0.1.2 on PyPI); extras nusadb[sqlalchemy], nusadb[asyncio], nusadb[django]DB-API 2.0 and an asyncio API, SQLAlchemy dialects, a Django backend
Node.jsnpm install nusadbPromise-based, TypeScript typings
Gogo get github.com/nusadb/godatabase/sql driver, registered as nusadb
Rustcargo add nusadb (0.1.2 on crates.io)sync and async (Tokio), connection pool, ORM, tls feature
Rubygem install nusadbnative client
PHPcomposer require nusadb/nusadbPDO-style API in pure PHP
Javacom.nusadb:nusadb-jdbc:0.3.0 (Maven Central)JDBC, pure Java, Java 17+; also on Central: nusadb-bom, the Hibernate dialects nusadb-hibernate5 and nusadb-hibernate6, and nusadb-spring-boot-starter
.NET (ADO.NET)not yet publishedpackage NusaDb for net8.0; not on NuGet yet
Names in older container images

The shell is nusadb-cli and the bootstrap superuser is nusadb-root. Images published before these names were introduced use nusa-cli and nusa-root.

Python:

python
import nusadb

conn = nusadb.connect(host="127.0.0.1", port=5678, user="app", password="change-me",
                      database="nusadb")
cur = conn.cursor()
cur.execute("INSERT INTO customers (email, country) VALUES ($1, $2) RETURNING id",
            ["dewi@example.com", "ID"])
print(cur.fetchone())                       # (4,)
cur.execute("SELECT email FROM customers WHERE country = $1", ["ID"])
for (email,) in cur:
    print(email)
conn.close()

Node.js:

js
const { connect } = require('nusadb');

const conn = await connect({ host: '127.0.0.1', port: 5678, user: 'app',
                             password: 'change-me', database: 'nusadb' });
const res = await conn.query('SELECT id, email FROM customers WHERE country = $1', ['ID']);
console.log(res.rows);          // [[1, 'ana@example.com'], [2, 'budi@example.com']]
console.log(res.columnTypes);   // ['INT', 'TEXT']
await conn.close();

Go:

go
import (
    "database/sql"
    _ "github.com/nusadb/go"
)

db, err := sql.Open("nusadb", "nusadb://app:change-me@127.0.0.1:5678/nusadb")
var email string
err = db.QueryRow("SELECT email FROM customers WHERE id = $1", 1).Scan(&email)

Java:

java
// pom.xml: <dependency><groupId>com.nusadb</groupId>
//          <artifactId>nusadb-jdbc</artifactId><version>0.3.0</version></dependency>
import java.sql.*;

String url = "jdbc:nusadb://app:change-me@127.0.0.1:5678/nusadb";
try (Connection conn = DriverManager.getConnection(url);
     PreparedStatement ps = conn.prepareStatement("SELECT email FROM customers WHERE country = $1")) {
    ps.setString(1, "ID");
    try (ResultSet rs = ps.executeQuery()) {
        while (rs.next()) System.out.println(rs.getString("email"));
    }
}

Rust:

rust
use nusadb::Connection;

let mut conn = Connection::connect("nusadb://app:change-me@127.0.0.1:5678/nusadb")?;
let rows = conn.query_params("SELECT id, email FROM customers WHERE country = $1", &[&"ID"])?;

What the Python and Rust drivers cover

Both drivers follow the server closely. As of 0.1.2:

FeaturePython 0.1.2Rust 0.1.2
Protocolasks for 1.3; an older server answers at its own version1.3, and older servers
Parameters$1, :1, and %s / %(name)s; each value declares its type$1; each value binds as its Rust type
Value typesranges as nusadb.Range, INET / CIDR as ipaddress values, VECTOR as a list of floats; MACADDR, BIT, geometric, full-text and XML keep their textIpAddr, IpNet, Cidr, MacAddr, BitString, Range<T>; geometric, full-text and XML as tagged text; arrays decode at their element type
Composite typesCompositeInfo, register_composite, parse_recordcomposite_type, Record, FromRecord
Batches and pipelinesexecutemany pipelined 256 per round trip; conn.pipeline()execute_many pipelined in chunks of 256; Pipeline and run_pipeline
Server-side cursorsnamed cursors, scrollable and withholddeclare_cursor with scroll and hold options
Binary resultsconnect(binary=True), or per cursor or statementConfig::binary_results, query_binary
COPYPython rows in and out, text or binaryrows in and out, text or binary
Building SQL safelynusadb.sqlnusadb::sql
Automatic prepareafter five runs with parameters (prepare_threshold)after five runs of query_params (prepare_threshold)
Noticesconn.notices, add_notice_handlernotices(), set_notice_handler
Two-phase committhe DB-API tpc_* methodsTransaction::prepare, commit_prepared, rollback_prepared, prepared_transactions
FrameworksSQLAlchemy 2.0, blocking and asyncio; Django 4.2 (nusadb.django)the crate's own ORM and query builder

The Python package's Django backend is set as the database engine:

python
DATABASES = {
    "default": {
        "ENGINE": "nusadb.django",
        "NAME": "app",
        "USER": "app",
        "PASSWORD": os.environ["DB_PASSWORD"],
        "HOST": "db.example",
        "PORT": "5678",
    }
}

Django's tests get their own database through CREATE DATABASE, so USER needs the CREATEDB attribute (or is nusadb-root). Each package's README lists its full API and its known limits.

Every driver uses prepared statements: the statement is parsed once and run with values for $1..$n, and the server caches the plan. The SQL spellings PREPARE / EXECUTE / DEALLOCATE also work on any connection, which is how nusadb-cli binds parameters. They, and the cursor statements DECLARE, FETCH, MOVE and CLOSE, work through the extended query protocol too, whatever the row limit and result formats: a FETCH or EXECUTE is described with its columns and honours both like any other query, and a DECLARE may take $n parameters.

Errors and retries

Every failed statement carries a five-character SQLSTATE, and the drivers expose it. Branch on the code, not on the message. Class 40 (40001, 40P01) means run the whole transaction again; 25P02 means the transaction is aborted and must be rolled back first; 55006 means a prepared transaction holds the table; 42501 is a missing grant. The retry loop is described under transactions, and the full table of codes is in the SQL reference.

Connection settings

SettingDefaultNotes
Host and port127.0.0.1:5678one connection targets one database
Databasenusadbcross-database queries are refused; CREATE DATABASE makes another
Usernusadb-rootthe bootstrap superuser
Passwordfrom NUSADB_PASSWORD (shell) or the driver's optionrequired once the server lists any --auth-user
TLSoffon the server with a certificate and key, on the same port

TLS and authentication

TLS runs on the same port: the server offers it when a certificate and key are configured, and a plaintext client is then refused. There is no system trust store, so the client names the certificate to trust with --tls-ca.

shell
nusadb-cli --host db.internal:5678 --user app --tls --tls-ca /etc/nusadb/ca.crt
nusadb-cli --host 10.0.0.5:5678 --tls --tls-ca ca.crt --tls-domain db.internal
Self-signed certificates

A certificate generated with the common one-line command is marked as a certificate authority, and is rejected when presented as a server certificate. Create a separate CA and sign the server certificate with it, or generate a leaf certificate that is not marked as a CA.

Hostname verification is applied, and a mismatch reports which names the certificate covers. For mutual TLS, the server takes a client CA and then requires every client to present a certificate signed by it.

Authentication is SCRAM-SHA-256. The password is never sent: the exchange proves that the client knows the password and that the server holds its stored verifier. A wrong password and an unknown user return the same authentication failure, so the error cannot be used to discover which usernames exist. Who may connect is the server's --auth-user list; what they may do is decided by SQL roles and grants, described under configuration.

Notifications

LISTEN channel subscribes a connection; NOTIFY channel, 'payload' from any connection in the same database reaches every listener, at commit when issued inside a transaction. A listener receives notifications between its own statements, which is how the drivers surface them.

Notices

From protocol 1.3, a statement may send notices besides its result: DROP TABLE IF EXISTS of a table that is not there, CREATE TABLE IF NOT EXISTS of one that is, a procedure's RAISE NOTICE. Each carries a severity (NOTICE, WARNING or INFO), a SQLSTATE (00000 when nothing is wrong, 01000 for a RAISE WARNING, otherwise the code the statement would have failed with had it not been told to skip) and a message. A statement's notices arrive just before its own completion or error. One statement sends at most 1000; past that one closing WARNING says how many were dropped. A notice is never an error. A client that asks for an older protocol version receives none.

Bulk transfer

COPY moves rows in a single streaming exchange rather than a round trip per row, in both directions, in text, CSV or binary format. The shell forms read from the command's standard input and write to its standard output, so they work in pipelines. See getting started.

Several statements in one query

A simple query may hold several statements separated by ;. The server parses all of them first and runs nothing if one fails to parse, then runs them in order, each sending its own result; the first statement that fails stops the rest.

  • Outside a transaction block the statements run in one implicit transaction, committed after the last one succeeds, so either all of it takes effect or none of it does.
  • A BEGIN in the string turns that into an ordinary transaction block, which stays open after the query until a COMMIT or ROLLBACK. A COMMIT or ROLLBACK in the string ends the implicit transaction at that point.
  • SAVEPOINT needs a transaction block, so in an implicit transaction it fails with 25P01; PREPARE TRANSACTION likewise.
  • CREATE DATABASE, DROP DATABASE, CHECKPOINT, COMMIT PREPARED and ROLLBACK PREPARED cannot run inside a transaction block, so send them on their own.
  • COPY cannot be one of several statements (0A000), and the extended query protocol takes exactly one statement.

Connections and pooling

The server handles connections on a thread pool rather than one process per connection, so a moderate number of idle connections is cheap. The default cap is 25 concurrent connections and excess connections queue rather than fail; --reject-excess-connections turns the queue into an immediate 53300 so a pool can back off. Raise --max-connections on a larger host. An external connection pooler is optional.

Writing your own client

The protocol is documented in full in the wire protocol reference: framing, the start-up and SCRAM exchange, simple and extended queries, COPY in text and binary, notices, cancellation, and the text and binary form of every type. The current version is 1.3. A client names the version it speaks at start-up and the server uses the lower of the two. Each minor version adds something only for a client that asks for it: 1.1 typed column descriptions, 1.2 the element type of an array column, 1.3 notices. A client that asks for an older version receives only that version's messages.