Sirannon encodes large integers and binary values as tagged JSON objects. The client SDK decodes them into bigint and binary arrays, while another language can decode the same objects through its JSON library.
JavaScript's JSON parser otherwise rounds integers outside its safe number range. JSON also has no binary value type, so both kinds of value need an explicit representation.
Stand up a ledger
Save the complete values.ts below and install the server peer from getting started. The example creates an isolated temporary database and enables SQL on a loopback-only server for the demonstration.
For a deployed service, use authenticated registered operations. Keep the example process open while trying the Python and Go clients, then send a shutdown signal to close it and remove its temporary files.
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { Sirannon } from '@delali/sirannon-db'
import { SirannonClient } from '@delali/sirannon-db/client'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
import { createServer } from '@delali/sirannon-db/server'
const directory = await mkdtemp(join(tmpdir(), 'sirannon-values-'))
const sirannon = new Sirannon({ driver: betterSqlite3() })
const server = createServer(sirannon, { host: '127.0.0.1', port: 9876, acceptSql: true })
const client = new SirannonClient('http://127.0.0.1:9876', { transport: 'http' })
const stopped = Promise.withResolvers<void>()
process.once('SIGINT', stopped.resolve)
process.once('SIGTERM', stopped.resolve)
try {
const ledger = await sirannon.open('ledger', join(directory, 'ledger.db'))
await ledger.execute(`CREATE TABLE transfers (
id INTEGER PRIMARY KEY, reference INTEGER NOT NULL, checksum BLOB NOT NULL, amount INTEGER NOT NULL
)`)
await server.listen()
const db = client.database('ledger')
await db.execute('INSERT INTO transfers (reference, checksum, amount) VALUES (?, ?, ?)', [
9007199254740993n, Buffer.from([0xde, 0xad, 0xbe, 0xef]), 250,
])
const rows = await db.query<{ reference: bigint; checksum: Buffer; amount: number }>(
'SELECT reference, checksum, amount FROM transfers')
const row = rows[0]
if (!row || row.reference !== 9007199254740993n || !Buffer.isBuffer(row.checksum)) {
throw new Error('The SDK did not return the expected native value types')
}
const response = await fetch('http://127.0.0.1:9876/db/ledger/query', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ sql: 'SELECT reference, checksum, amount FROM transfers' }),
signal: AbortSignal.timeout(30_000),
})
if (!response.ok) throw new Error(`Query failed with HTTP ${response.status}`)
console.log(JSON.stringify(await response.json(), (key: string, value: unknown): unknown =>
typeof value === 'number' ? Number(value.toFixed(2)) : value, 2))
await stopped.promise
} finally {
client.close()
try {
await server.close()
} finally {
try {
await sirannon.shutdown()
} finally {
await rm(directory, { recursive: true, force: true })
}
}
}Write and read through the client SDK
The SDK wraps 9007199254740993n as an integer envelope and the checksum as a binary envelope. It decodes the returned reference into the same exact bigint and the checksum into a Node Buffer.
In a browser, the binary value becomes a Uint8Array. Both Buffer and Uint8Array work as bind parameters. An integer within JavaScript's safe range returns as a number.
Look at the raw JSON
The example's plain HTTP request bypasses SDK decoding. Its JSON response contains __sirannon_int for the reference, __sirannon_blob for the checksum, and the ordinary number 250 for the amount.
The integer payload is 9007199254740993. The binary payload is DEADBEEF, with two hexadecimal digits per byte.
The envelope rules
An envelope has exactly one key, __sirannon_int or __sirannon_blob, with a string value. A stored text value resembling an envelope remains a JSON string, so it remains distinct from the tagged object.
- An integer payload contains an optional minus sign followed by one to nineteen decimal digits, with no whitespace, plus sign, or exponent.
- Sirannon emits plain JSON numbers for integers from -9007199254740991 through 9007199254740991 and wraps larger magnitudes.
- Sirannon emits uppercase hexadecimal for binary payloads, while the decoder accepts either letter case. An empty payload represents an empty BLOB.
- The protocol uses envelopes in result cells, change-event
rowandoldRowvalues, bind parameters, batch parameters, and subscription filter values. - A malformed envelope in request parameters produces HTTP
INVALID_REQUESTwith status 400 or WebSocketINVALID_MESSAGE.
Decode without the SDK
This complete Python client uses the standard library. It validates tagged payloads and converts them into an arbitrary-precision integer or bytes. urlopen() raises an error for an unsuccessful HTTP response, and its timeout bounds the network wait.
import json
import re
from urllib import request
def decode_value(value):
if not isinstance(value, dict) or len(value) != 1:
return value
if '__sirannon_int' in value:
payload = value['__sirannon_int']
if not isinstance(payload, str) or not re.fullmatch(r'-?[0-9]{1,19}', payload):
raise ValueError('Invalid tagged integer')
return int(payload)
if '__sirannon_blob' in value:
payload = value['__sirannon_blob']
if not isinstance(payload, str) or len(payload) % 2 or not re.fullmatch(r'[0-9a-fA-F]*', payload):
raise ValueError('Invalid tagged binary value')
return bytes.fromhex(payload)
return value
query = request.Request(
'http://127.0.0.1:9876/db/ledger/query',
data=json.dumps({'sql': 'SELECT reference, checksum, amount FROM transfers'}).encode(),
headers={'content-type': 'application/json'},
)
with request.urlopen(query, timeout=30) as response:
payload = json.load(response)
rows = [{column: decode_value(value) for column, value in row.items()} for row in payload['rows']]
if not rows:
raise RuntimeError('The ledger returned no transfer')
print(rows[0])The Go client also uses the standard library. UseNumber() preserves ordinary JSON numbers for explicit conversion, while ParseInt() converts the tagged reference to SQLite's signed 64-bit range.
package main
import (
"bytes"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"regexp"
"strconv"
"time"
)
var integerPayload = regexp.MustCompile(`^-?[0-9]{1,19}$`)
func decodeValue(value any) (any, error) {
envelope, ok := value.(map[string]any)
if !ok || len(envelope) != 1 {
return value, nil
}
if raw, exists := envelope["__sirannon_int"]; exists {
payload, ok := raw.(string)
if !ok || !integerPayload.MatchString(payload) {
return nil, fmt.Errorf("invalid tagged integer")
}
return strconv.ParseInt(payload, 10, 64)
}
if raw, exists := envelope["__sirannon_blob"]; exists {
payload, ok := raw.(string)
if !ok {
return nil, fmt.Errorf("invalid tagged binary value")
}
return hex.DecodeString(payload)
}
return value, nil
}
func main() {
body := []byte(`{"sql":"SELECT reference, checksum, amount FROM transfers"}`)
client := &http.Client{Timeout: 30 * time.Second}
response, err := client.Post("http://127.0.0.1:9876/db/ledger/query", "application/json", bytes.NewReader(body))
if err != nil {
panic(err)
}
defer response.Body.Close()
if response.StatusCode < 200 || response.StatusCode >= 300 {
panic(fmt.Errorf("query failed with HTTP %s", response.Status))
}
var payload struct {
Rows []map[string]any `json:"rows"`
}
decoder := json.NewDecoder(response.Body)
decoder.UseNumber()
if err := decoder.Decode(&payload); err != nil {
panic(err)
}
if len(payload.Rows) == 0 {
panic("the ledger returned no transfer")
}
row := payload.Rows[0]
for column, value := range row {
decoded, err := decodeValue(value)
if err != nil {
panic(err)
}
row[column] = decoded
}
fmt.Println(row["reference"], row["checksum"], row["amount"])
}Apply the same rules in reverse when sending parameters without the SDK. Wrap an integer outside the safe range and every binary value before JSON serialisation.
Sirannon binds booleans as SQLite integers, 1 for true and 0 for false. Empty binary arrays remain empty BLOBs. The browser driver preserves embedded NUL characters in text and copies returned BLOB bytes before advancing the statement.
Integer fidelity covers driver limits, including Expo's unsafe-integer restrictions. Subscription resumption describes the cursor and epoch fields alongside encoded change-event rows.