TypeScript SDK
The ParticleDB TypeScript SDK provides a PG wire client (connection pool, typed queries, transactions), a gRPC client, and a streaming client (WebSocket / SSE). It includes helpers for vector search, KV operations, RAG pipelines, and AI functions.
Installation
Section titled “Installation”npm install particledbnpm install particledb @grpc/grpc-js @grpc/proto-loaderQuick Start
Section titled “Quick Start”import { ParticleDB } from 'particledb';
const db = new ParticleDB({ host: 'localhost', port: 5432, user: 'particledb', database: 'particledb',});
// SQL queries with typed resultsconst { rows } = await db.query<{ id: number; name: string }>( 'SELECT id, name FROM users WHERE id = $1', [1]);
// Single row lookupconst user = await db.queryOne<{ id: number; name: string }>( 'SELECT * FROM users WHERE id = $1', [42]);
// DML with affected row countconst affected = await db.execute( 'UPDATE users SET active = true WHERE id = $1', [42]);
await db.close();Connection
Section titled “Connection”// Config objectconst db = new ParticleDB({ host: 'localhost', port: 5432, user: 'particledb', password: 'secret', database: 'mydb', poolSize: 20, ssl: true,});
// Connection stringconst db = await ParticleDB.connect('postgresql://user:pass@host:5432/mydb');Transactions
Section titled “Transactions”const result = await db.transaction(async (tx) => { await tx.execute('INSERT INTO accounts (id, balance) VALUES ($1, $2)', [1, 100]); await tx.execute('UPDATE accounts SET balance = balance - $1 WHERE id = $2', [50, 2]); return 'done';});// Automatically commits on success, rolls back on errorVector Search
Section titled “Vector Search”// Similarity searchconst results = await db.vector.search('documents', 'embedding', [0.1, 0.2, 0.3], { k: 5, filter: "category = 'science'",});
for (const { row, distance } of results) { console.log(`${row.title}: distance=${distance}`);}
// Insert with vectorawait db.vector.insert( 'documents', { title: 'My Doc', category: 'science' }, 'embedding', [0.1, 0.2, 0.3]);
// Create vector indexawait db.vector.createIndex('documents', 'embedding', 'hnsw', { m: 16, ef_construction: 200,});Key-Value Store
Section titled “Key-Value Store”Redis-compatible key-value operations:
await db.kv.set('session:123', '{"user":"alice"}', 3600); // with TTLconst val = await db.kv.get('session:123');
await db.kv.mset({ key1: 'val1', key2: 'val2' });const vals = await db.kv.mget(['key1', 'key2']);
await db.kv.incr('counter', 1);const exists = await db.kv.exists('session:123');const keys = await db.kv.keys('session:*');await db.kv.delete('session:123');RAG (Retrieval-Augmented Generation)
Section titled “RAG (Retrieval-Augmented Generation)”// Query with a named pipelineconst answer = await db.rag.query('What is ParticleDB?', { pipeline: 'docs_pipeline',});
// Query with inline configconst answer2 = await db.rag.query('What is ParticleDB?', { table: 'documents', vectorCol: 'embedding', textCol: 'content', k: 5,});
// Create a reusable pipelineawait db.rag.createPipeline('docs_pipeline', { table: 'documents', vectorCol: 'embedding', textCol: 'content', k: 5, mode: 'simple',});AI Functions
Section titled “AI Functions”// Embeddingsconst embedding = await db.ai.embed('Hello world');const embeddings = await db.ai.embedBatch(['Hello', 'World']);
// Text generationconst response = await db.ai.generate('Explain vector databases');
// Classificationconst label = await db.ai.classify('Great product!', ['positive', 'negative', 'neutral']);
// Summarizationconst summary = await db.ai.summarize(longArticle);Streaming (WebSocket / SSE)
Section titled “Streaming (WebSocket / SSE)”Real-time streaming client for CDC events, pub/sub, and row-by-row query results.
import { StreamingClient } from 'particledb';
// Connect via WebSocket (default)const stream = new StreamingClient({ host: 'localhost', httpPort: 4000, transport: 'websocket', // or 'sse'});await stream.connect();
// Subscribe to CDC events on a tableconst unsub = stream.subscribe('cdc_users', (event) => { console.log(`${event.event} on ${event.table}: ${event.payload}`);});
// Stream query results row-by-rowfor await (const row of stream.streamQuery('SELECT * FROM large_table')) { console.log(row);}
// Auto-reconnect with exponential backoffconst stream2 = new StreamingClient({ autoReconnect: true, maxReconnectAttempts: 10, reconnectBaseDelay: 1000,});
unsub();await stream.close();SSE Transport
Section titled “SSE Transport”Server-Sent Events work in any environment with fetch and EventSource:
const stream = new StreamingClient({ host: 'localhost', httpPort: 4000, transport: 'sse', ssl: true,});await stream.connect();
stream.subscribe('cdc_orders', (event) => { console.log('Order changed:', event.payload);});gRPC Client
Section titled “gRPC Client”Direct gRPC client for the particledb.v1.ParticleDB service.
import { GrpcClient } from 'particledb';
const client = new GrpcClient({ host: 'localhost', port: 26257,});
// Execute SQLconst result = await client.executeSQL('SELECT * FROM users WHERE id = 1');console.log(result.rows);
// Batch executionconst batch = await client.batchExecute([ "INSERT INTO events (id, name) VALUES (1, 'click')", "INSERT INTO events (id, name) VALUES (2, 'view')", 'SELECT COUNT(*) AS total FROM events',]);
// Server-streaming queryfor await (const row of client.streamQuery('SELECT * FROM large_table')) { console.log(row.id, row.name);}
// CDC subscriptionfor await (const event of client.subscribe('users', ['INSERT', 'DELETE'])) { console.log(`${event.event} on ${event.table}: ${event.payload}`);}
// Bulk insert (client-streaming)const ins = await client.streamInsert('events', ['id', 'name'], [ [1, 'click'], [2, 'view'],]);console.log(`Inserted ${ins.rowsInserted} rows`);
// Health checkconst health = await client.health();console.log(health.status); // "OK"
// TLS / Mutual TLSimport { readFileSync } from 'fs';
const secureClient = new GrpcClient({ host: 'prod.particledb.io', port: 26257, ssl: true, rootCert: readFileSync('/path/to/ca.pem'), clientCert: readFileSync('/path/to/client.pem'), clientKey: readFileSync('/path/to/client-key.pem'),});
await client.close();API Reference
Section titled “API Reference”ParticleDB
Section titled “ParticleDB”| Method | Description |
|---|---|
new ParticleDB(config?) | Create client with config object |
ParticleDB.connect(url) | Create client from connection string |
query<T>(sql, params?) | Execute query, return typed rows |
queryOne<T>(sql, params?) | Execute query, return first row or null |
execute(sql, params?) | Execute DML, return affected row count |
stream<T>(sql, params?) | Stream results as async iterable |
transaction(fn) | Execute function in a transaction |
close() | Close connection pool |
Accessors
Section titled “Accessors”| Property | Type | Description |
|---|---|---|
db.vector | VectorOps | Vector search operations |
db.kv | KVOps | Key-value operations |
db.rag | RAGOps | RAG query operations |
db.ai | AIOps | AI function operations |
StreamingClient
Section titled “StreamingClient”| Method | Description |
|---|---|
new StreamingClient(config?) | Create streaming client |
connect() | Open WebSocket or SSE connection |
subscribe(channel, callback) | Subscribe to CDC/pub-sub events; returns unsubscribe fn |
streamQuery(sql, params?) | Stream query results as async iterable |
onEvent(type, handler) | Register event handler; returns unsubscribe fn |
isConnected | Whether the connection is open |
close() | Disconnect and release resources |
GrpcClient
Section titled “GrpcClient”| Method | Description |
|---|---|
new GrpcClient(config?) | Create gRPC client |
executeSQL(sql, params?) | Execute single SQL statement |
query(sql, params?) | Convenience alias for executeSQL |
streamQuery(sql, params?) | Stream query results as async iterable |
batchExecute(sqls) | Execute multiple statements in one round-trip |
subscribe(table, events?) | Subscribe to CDC events (async iterable) |
streamInsert(table, cols, rows) | Bulk insert via client-streaming |
health() | Server health check |
close() | Close gRPC channel |
Next Steps
Section titled “Next Steps”- SQL Reference — Full SQL syntax supported by ParticleDB
- Vector Search — Vector search SQL syntax
- Browser/WebSocket SDK — For browser-only use cases