### start() Method Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunqlserver.md Example of starting the HTTP server. ```typescript server.start(); // → [BunQLServer] Listening on http://0.0.0.0:3000 ``` -------------------------------- ### Complete Server Setup Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunqlserver.md Full TypeScript example demonstrating the setup of a BunQLServer with database connection, port, host, CORS, and authentication. ```typescript import { BunQL } from "@nds-stack/bunql"; import { BunQLServer } from "@nds-stack/bunql/server"; const db = new BunQL("./app.db", { wal: true, busyTimeout: 5000, }); const server = new BunQLServer(db, { port: 3000, host: "0.0.0.0", cors: true, auth: { apiKey: process.env.API_KEY || "dev-key" }, }); server.start(); // Graceful shutdown process.on("SIGTERM", async () => { server.stop(); await db.close(); process.exit(0); }); ``` -------------------------------- ### BunQLServer Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/configuration.md An example of how to instantiate and start a BunQLServer with custom options. ```typescript const server = new BunQLServer(db, { port: 8080, host: "127.0.0.1", cors: true, auth: { apiKey: "secret-key-123" }, }); server.start(); ``` -------------------------------- ### Complete Search Setup Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/fts5-helper.md A comprehensive example showing how to set up FTS5, insert documents, perform searches with snippets, and optimize the index using BunQL. ```typescript import { BunQL } from "@nds-stack/bunql"; const db = new BunQL("./blog.db"); // Initialize search db.fts.create("posts", ["title", "content"], { tokenize: "porter", prefix: [2, 4], }); // Insert documents db.fts.insert("posts", { title: "SQLite Performance Tips", content: "Learn how to optimize your SQLite queries...", }); db.fts.insert("posts", { title: "Getting Started with FTS5", content: "FTS5 is a full-text search extension...", }); // Search with snippets const results = db.fts.search("posts", "SQLite OR FTS5", { limit: 10, snippet: { startTag: "", endTag: "", maxTokens: 64, }, }); results.forEach((result) => { console.log(`${result.title} (rank: ${result.rank})`); if (result.snippet) { console.log(` Snippet: ${result.snippet}`); } }); // Optimize index db.fts.optimize("posts"); ``` -------------------------------- ### Quick Start Example Source: https://github.com/nds-stack/bunql/blob/main/README.md Demonstrates basic usage of BunQL for inserting data, querying with a cached prepared statement, and performing a transaction. ```typescript const db = new BunQL("./app.db"); // Writes are synchronous — just like raw bun:sqlite db.run("INSERT INTO users (name) VALUES (?)", ["Alice"]); // Read — cached prepared statement const users = db.query<{ id: number; name: string }>("SELECT * FROM users"); // Transaction — async with auto-rollback await db.transaction(async (tx) => { tx.run("UPDATE accounts SET balance = balance - 100 WHERE id = 1"); tx.run("UPDATE accounts SET balance = balance + 100 WHERE id = 2"); }); ``` -------------------------------- ### Example Server Setup with CORS Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/endpoints.md Demonstrates how to configure a BunQL server with CORS enabled. ```typescript const server = new BunQLServer(db, { port: 3000, cors: true, auth: { apiKey: "secret" }, }); ``` -------------------------------- ### BunQLServer Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunqlserver.md Example of how to import and initialize BunQLServer. ```typescript import { BunQL} from "@nds-stack/bunql"; import { BunQLServer} from "@nds-stack/bunql/server"; const db = new BunQL("./app.db"); const server = new BunQLServer(db, { port: 3000, cors: true, auth: { apiKey: "secret-key-here" }, }); server.start(); // → Listening on http://0.0.0.0:3000 ``` -------------------------------- ### create() Method Examples Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/fts5-helper.md Examples of creating FTS5 tables with different configurations. ```typescript // Basic FTS5 table db.fts.create("docs", ["title", "body"]); // With porter stemmer db.fts.create("articles", ["title", "content"], { tokenize: "porter", prefix: [2, 4], }); // External content (unindexed storage) db.fts.create("indexed_docs", ["title"], { content: "docs_content", }); ``` -------------------------------- ### Complete Configuration Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/configuration.md A comprehensive example demonstrating various configuration options for BunQL. ```typescript import { BunQL } from "@nds-stack/bunql"; const db = new BunQL("./app.db", { // Database wal: true, readonly: false, busyTimeout: 5000, synchronous: "NORMAL", cacheSize: -8000, // 8MB foreignKeys: true, readerPool: 3, slowQueryThreshold: 100, // Retry retry: { maxRetries: 5, baseDelay: 50, maxDelay: 1000, jitter: true, }, // PRAGMA pragma: { autoVacuum: "INCREMENTAL", }, // Hooks hooks: { beforeWrite: (sql) => console.log(`[WRITE] ${sql}`), afterWrite: (sql, _, ms) => console.log(` ${ms.toFixed(1)}ms`), beforeTransaction: () => console.log("[TX] BEGIN"), afterTransaction: (ms, ok) => { console.log(`[TX] ${ok ? "COMMIT" : "ROLLBACK"} (${ms}ms)`) }, }, // Events events: { onBusy: (attempt, delay) => { console.warn(`[BUSY] retry ${attempt + 1} in ${delay}ms`); }, onDrain: () => console.log("[QUEUE] drained"), onError: (err) => console.error("[ERROR]", err), onSlowQuery: (sql, ms) => { console.warn(`[SLOW] ${ms}ms: ${sql.slice(0, 60)}`); }, }, // Logger logger: console, // Maintenance maintenance: { checkpoint: { enabled: true, intervalMs: 60000, pagesThreshold: 1000, mode: "TRUNCATE", }, vacuum: { enabled: true, intervalMs: 300000, mode: "incremental", pagesPerStep: 100, }, backup: { enabled: true, intervalMs: 86400000, path: "./backups/", }, }, }); ``` -------------------------------- ### StatementCache get() Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/internal-utilities.md Example of using the get() method to retrieve a cached or new prepared statement. ```typescript const stmt = cache.get("SELECT * FROM users WHERE id = ?"); const user = stmt.get(1); ``` -------------------------------- ### BunQLServer Constructor Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunqlserver.md Example of creating a BunQLServer instance with custom options. ```typescript const server = new BunQLServer(db, { port: 8080, host: "127.0.0.1", cors: true, auth: { apiKey: "prod-secret" }, }); ``` -------------------------------- ### Authentication Header Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunqlserver.md Example of the required 'x-api-key' header for authenticated requests. ```text x-api-key: key ``` -------------------------------- ### Server Configuration Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/types.md An example of creating and configuring a BunQLServer instance. ```typescript const server = new BunQLServer(db, { port: 8080, host: "127.0.0.1", cors: true, auth: { apiKey: "secret" }, }); ``` -------------------------------- ### GET /health Endpoint Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunqlserver.md Example cURL command to check the health of the server. ```bash curl http://localhost:3000/health ``` -------------------------------- ### POST /exec Endpoint Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunqlserver.md Example cURL command to execute multi-statement SQL. ```bash curl -X POST http://localhost:3000/exec \ -H "Content-Type: application/json" \ -H "x-api-key: secret-key" \ -d '{"sql": "CREATE TABLE IF NOT EXISTS logs (id INTEGER PRIMARY KEY, msg TEXT);"}' ``` -------------------------------- ### vacuum() example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunql-class.md Example usage of the vacuum method with incremental option. ```typescript const result = await db.vacuum({ incremental: true, pagesPerStep: 100 }); console.log(`Reclaimed ${result.pagesReclaimed} pages`); ``` -------------------------------- ### url Getter Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunqlserver.md Example of checking the server URL. ```typescript if (server.url) { console.log(`Server running at ${server.url}`); } ``` -------------------------------- ### BunQLHooks Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/types.md Example of using BunQLHooks. ```typescript const db = new BunQL("./app.db", { hooks: { beforeWrite: (sql) => console.log(`Executing: ${sql}`), afterWrite: (sql, _, ms) => console.log(` took ${ms}ms`), afterTransaction: (ms, success) => { console.log(`Transaction ${success ? "committed" : "rolled back"} in ${ms}ms`); }, }, }); ``` -------------------------------- ### POST /query Endpoint Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunqlserver.md Example cURL command to execute a SELECT query. ```bash curl -X POST http://localhost:3000/query \ -H "Content-Type: application/json" \ -H "x-api-key: secret-key" \ -d '{"sql": "SELECT * FROM users WHERE id = ?", "params": [1]}' ``` -------------------------------- ### Client Library Usage Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunqlserver.md TypeScript example demonstrating how to use the query and run functions to interact with the BunQL server. ```typescript // Usage const users = await query("SELECT * FROM users WHERE age > ?", [18]); const result = await run("INSERT INTO logs (msg) VALUES (?)", ["hello"]); ``` -------------------------------- ### POST /run Endpoint Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunqlserver.md Example cURL command to execute an INSERT, UPDATE, or DELETE statement. ```bash curl -X POST http://localhost:3000/run \ -H "Content-Type: application/json" \ -H "x-api-key: secret-key" \ -d '{"sql": "UPDATE users SET age = ? WHERE id = ?", "params": [30, 1]}' ``` -------------------------------- ### Installation Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/README.md Install BunQL using Bun's package manager. ```bash bun add @nds-stack/bunql ``` -------------------------------- ### EventHandlers Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/types.md Example of using EventHandlers. ```typescript const db = new BunQL("./app.db", { slowQueryThreshold: 100, events: { onBusy: (attempt, delay) => { console.warn(`SQLITE_BUSY (attempt ${attempt}, retry in ${delay}ms)`); }, onSlowQuery: (sql, ms) => { console.warn(`Slow query (${ms.toFixed(1)}ms): ${sql}`); }, onDrain: () => console.log("Write queue flushed"), }, }); ``` -------------------------------- ### BatchOperation Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/types.md Example of using BatchOperation. ```typescript const operations: BatchOperation[] = [ { sql: "INSERT INTO users (name) VALUES (?)", params: ["Alice"] }, { sql: "INSERT INTO users (name) VALUES (?)", params: ["Bob"] }, { sql: "UPDATE counters SET total = total + 2" }, ]; await db.batch(operations); ``` -------------------------------- ### RunResult Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/types.md Example usage of RunResult. ```typescript const result = await db.run( "INSERT INTO users (name) VALUES (?)", ["Alice"] ); console.log(result.changes); // 1 console.log(result.lastInsertRowid); // 1 (the new user's id) ``` -------------------------------- ### insert() Method Examples Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/fts5-helper.md Examples of inserting documents into an FTS5 table. ```typescript db.fts.insert("articles", { title: "Getting Started with SQLite", body: "SQLite is an excellent embedded database for web applications.", }); // Multiple inserts (note: not batched, use transaction for performance) const docs = [ { title: "FTS5 Basics", body: "FTS5 is a powerful..." }, { title: "Advanced FTS5", body: "Learn query syntax..." }, ]; for (const doc of docs) { db.fts.insert("articles", doc); } ``` -------------------------------- ### BunQL Constructor with Environment Variables Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/configuration.md Example of initializing BunQL, passing options explicitly or from process.env. ```typescript const db = new BunQL("./app.db", { busyTimeout: parseInt(process.env.DB_BUSY_TIMEOUT || "5000", 10), readerPool: parseInt(process.env.DB_READER_POOL || "0", 10), synchronous: (process.env.DB_SYNC || "NORMAL") as "OFF" | "NORMAL" | "FULL" | "EXTRA", }); ``` -------------------------------- ### BackupResult Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/types.md Example usage of BackupResult. ```typescript const result = await db.backup("./backup.db"); console.log(`Backup: ${result.size} bytes in ${result.durationMs}ms`); ``` -------------------------------- ### POST /batch Endpoint Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunqlserver.md Example cURL command to execute multiple write operations in a single atomic transaction. ```bash curl -X POST http://localhost:3000/batch \ -H "Content-Type: application/json" \ -H "x-api-key: secret-key" \ -d '{ "operations": [ {"sql": "INSERT INTO logs (msg) VALUES (?)", "params": ["event-1"]}, {"sql": "INSERT INTO logs (msg) VALUES (?)", "params": ["event-2"]} ] }' ``` -------------------------------- ### stop() Method Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunqlserver.md Example of stopping the HTTP server. ```typescript server.stop(); // → [BunQLServer] Stopped ``` -------------------------------- ### Logger Configuration Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/types.md An example showing how to provide a custom logger implementation to BunQL. ```typescript const db = new BunQL("./app.db", { logger: { log: (...args) => myLogger.info(args), warn: (...args) => myLogger.warn(args), error: (...args) => myLogger.error(args), info: (...args) => myLogger.info(args), debug: (...args) => myLogger.debug(args), }, }); ``` -------------------------------- ### Maintenance Configuration Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/types.md An example demonstrating how to configure maintenance settings when initializing a BunQL instance. ```typescript const db = new BunQL("./app.db", { maintenance: { checkpoint: { enabled: true, intervalMs: 60000, pagesThreshold: 1000, mode: "TRUNCATE", }, vacuum: { enabled: true, intervalMs: 300000, mode: "incremental", pagesPerStep: 100, }, backup: { enabled: true, intervalMs: 86400000, // daily path: "./backups/", }, }, }); ``` -------------------------------- ### close() example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunql-class.md Example of using the close method on SIGTERM signal. ```typescript process.on("SIGTERM", async () => { await db.close(); process.exit(0); }); ``` -------------------------------- ### WalStatus Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/types.md Example usage of WalStatus. ```typescript const status = await db.walStatus(); if (status.checkpointRequired) { await db.checkpoint("TRUNCATE"); } ``` -------------------------------- ### prepare() Method Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/transaction-context.md Example demonstrating the use of prepare() to create a reusable statement within a transaction for batch inserts. ```typescript await db.transaction(async (tx) => { const insertStmt = tx.prepare<{ id: number }, [string]>( "INSERT INTO logs (message) VALUES (?)" ); const results = []; for (let i = 0; i < 100; i++) { results.push(await insertStmt.run(`event-${i}`)); } insertStmt.finalize(); }); ``` -------------------------------- ### POST /run Endpoint Example (Insert) Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/endpoints.md Example cURL command for inserting data. ```bash curl -X POST http://localhost:3000/run \ -H "Content-Type: application/json" \ -H "x-api-key: secret" \ -d '{ "sql": "INSERT INTO users (name) VALUES (?)", "params": ["Charlie"] }' # → { "changes": 1, "lastInsertRowid": 6, "durationMs": 0.5 } ``` -------------------------------- ### Statement Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/types.md Example usage of Statement. ```typescript type User = { id: number; name: string }; const stmt = db.prepare( "SELECT * FROM users WHERE name = ?" ); const alice: User | undefined = stmt.get("Alice"); const all: User[] = stmt.all("Bob"); await stmt.run("UpdatedName"); stmt.finalize(); ``` -------------------------------- ### POST /transaction Response Example (200 OK) Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunqlserver.md Example JSON response body for a successful transaction. ```json [ [{ "balance": 1000 }], { "changes": 1, "lastInsertRowid": null, "durationMs": 0.2 }, { "changes": 1, "lastInsertRowid": null, "durationMs": 0.1 } ] ``` -------------------------------- ### CheckpointResult Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/types.md Example usage of CheckpointResult. ```typescript const result = await db.checkpoint("TRUNCATE"); console.log(`Checkpointed ${result.pagesCheckpointed} pages`); ``` -------------------------------- ### Metrics Access Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/types.md Example of accessing and logging BunQL metrics. ```typescript const m = db.metrics; console.log(`Queue: ${m.queue.currentSize} pending`); console.log(`Writes: ${m.writes.total} total, ${m.writes.failed} failed`); console.log(`Hit rate: ${(m.writes.retried / m.writes.total * 100).toFixed(1)}% retried`); ``` -------------------------------- ### BunQLServer Initialization with Authentication Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunqlserver.md TypeScript example of initializing BunQLServer with an API key for authentication. ```typescript const server = new BunQLServer(db, { port: 3000, auth: { apiKey: "my-secret-key-123" }, }); ``` -------------------------------- ### POST /run Endpoint Example (Update) Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/endpoints.md Example cURL command for updating data. ```bash curl -X POST http://localhost:3000/run \ -H "Content-Type: application/json" \ -H "x-api-key: secret" \ -d '{ "sql": "UPDATE users SET age = ? WHERE id = ?", "params": [30, 1] }' # → { "changes": 1, "lastInsertRowid": null, "durationMs": 0.3 } ``` -------------------------------- ### FTS5 Query Syntax Examples Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/fts5-helper.md Examples demonstrating various FTS5 query syntaxes including single term, AND, OR, NOT, phrase, and prefix searches. ```typescript db.fts.search("articles", "sqlite"); // Single term db.fts.search("articles", "sqlite database"); // Both terms db.fts.search("articles", "sqlite AND fast"); // Explicit AND db.fts.search("articles", "sql OR python"); // OR db.fts.search("articles", "NOT database"); // NOT db.fts.search("articles", '"full text search"'); // Phrase db.fts.search("articles", "sql*"); // Prefix (if enabled) ``` -------------------------------- ### run() Method Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/transaction-context.md Example of using the run() method within a transaction to perform INSERT and UPDATE operations, logging the results. ```typescript await db.transaction(async (tx) => { const r1 = await tx.run("INSERT INTO accounts (balance) VALUES (?)", [1000]); console.log(r1.lastInsertRowid); // ID of new account const r2 = await tx.run( "UPDATE accounts SET balance = balance - 100 WHERE id = ?", [r1.lastInsertRowid] ); console.log(r2.changes); // 1 }); ``` -------------------------------- ### StatementCache Constructor Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/internal-utilities.md Example of creating a new StatementCache instance. ```typescript import { Database } from "bun:sqlite"; const db = new Database("./app.db"); const cache = new StatementCache(db, 50); ``` -------------------------------- ### search() examples Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/fts5-helper.md Examples demonstrating various ways to use the search function, including simple searches, searches with snippets and pagination, boolean queries, phrase queries, and prefix searches. ```typescript // Simple search const results = db.fts.search("articles", "sqlite"); // → [{ rowid: 1, title: "...", body: "...", rank: -1.5 }, ...] // With snippets and pagination const page1 = db.fts.search("articles", "database OR sql", { limit: 10, offset: 0, snippet: { startTag: "", endTag: "", maxTokens: 32 }, }); // Boolean query const results = db.fts.search("docs", "python AND NOT java"); // Phrase query const results = db.fts.search("docs", '"machine learning"'); // Prefix search (if table has prefix option) const results = db.fts.search("docs", "sql*"); ``` -------------------------------- ### POST /transaction Request Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunqlserver.md Example JSON request body for executing mixed SELECT and write operations in a single transaction. ```json { "operations": [ { "sql": "SELECT balance FROM accounts WHERE id = ?", "params": [1] }, { "sql": "UPDATE accounts SET balance = balance - 100 WHERE id = ?", "params": [1] }, { "sql": "UPDATE accounts SET balance = balance + 100 WHERE id = ?", "params": [2] } ] } ``` -------------------------------- ### POST /batch cURL Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/endpoints.md Example cURL command to execute a batch operation. ```bash curl -X POST http://localhost:3000/batch \ -H "Content-Type: application/json" \ -H "x-api-key: secret" \ -d '{ "operations": [ {"sql": "INSERT INTO logs (msg) VALUES (?)", "params": ["event-1"]}, {"sql": "INSERT INTO logs (msg) VALUES (?)", "params": ["event-2"]}, {"sql": "INSERT INTO logs (msg) VALUES (?)", "params": ["event-3"]} ] }' # → [ # {"changes": 1, "lastInsertRowid": 1, "durationMs": 0.4}, # {"changes": 1, "lastInsertRowid": 2, "durationMs": 0.3}, # {"changes": 1, "lastInsertRowid": 3, "durationMs": 0.2} # ] ``` -------------------------------- ### POST /exec Endpoint Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/endpoints.md Example cURL command for executing multi-statement SQL to create a table. ```bash curl -X POST http://localhost:3000/exec \ -H "Content-Type: application/json" \ -H "x-api-key: secret" \ -d '{ "sql": "CREATE TABLE IF NOT EXISTS audit (id INTEGER PRIMARY KEY, action TEXT, ts DATETIME DEFAULT CURRENT_TIMESTAMP);" }' ``` -------------------------------- ### onBusy and onRetry Event Handlers Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/internal-utilities.md Demonstrates setting up onBusy and onRetry event handlers for retry policies. ```typescript const policy = new RetryPolicy(); policy.onBusy = (attempt, delay) => { console.log(`Busy, retrying in ${delay}ms`); }; policy.onRetry = (attempt, delay, error) => { console.log(`Retry ${attempt + 1}: ${error.message}`); }; ``` -------------------------------- ### Enable WAL (Write-Ahead Log) Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/configuration.md Example of enabling WAL mode for concurrent access and improved performance. ```typescript const db = new BunQL("./app.db", { wal: true }); ``` -------------------------------- ### Retry Configuration Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/types.md Example of configuring retry behavior for BunQL. ```typescript const db = new BunQL("./app.db", { retry: { maxRetries: 10, baseDelay: 100, maxDelay: 5000, jitter: true, }, }); ``` -------------------------------- ### update() Method Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/fts5-helper.md Example of updating a document in an FTS5 table. ```typescript db.fts.update("articles", 5, { title: "Updated Title", body: "Updated content here...", }); ``` -------------------------------- ### Creating a Database Instance Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/README.md Example of creating a new BunQL database instance with specified options. ```typescript import { BunQL } from "@nds-stack/bunql"; const db = new BunQL("./app.db", { wal: true, busyTimeout: 5000, synchronous: "NORMAL", retry: { maxRetries: 5, baseDelay: 50 }, }); ``` -------------------------------- ### Browser Request Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/endpoints.md An example of how to make a POST request to a BunQL endpoint from a browser, including necessary headers and body. ```javascript const response = await fetch("http://localhost:3000/query", { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": "secret", }, body: JSON.stringify({ sql: "SELECT * FROM users", }), }); const result = await response.json(); ``` -------------------------------- ### raw getter example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunql-class.md Example usage of the raw getter for PRAGMA commands and VACUUM. ```typescript db.raw.run("PRAGMA cache_size=-8000"); db.raw.run("PRAGMA synchronous=FULL"); db.raw.exec("VACUUM"); ``` -------------------------------- ### Set Cache Size Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/configuration.md Example of configuring the SQLite cache size. ```typescript const db = new BunQL("./app.db", { cacheSize: -8000 }); // 8MB ``` -------------------------------- ### Configure Reader Pool Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/configuration.md Example of setting up a reader pool for parallel reads. ```typescript const db = new BunQL("./app.db", { wal: true, readerPool: 3, // 3 read-only connections }); ``` -------------------------------- ### POST /exec Request Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/endpoints.md Example JSON payload for executing multi-statement SQL. ```json { "sql": "CREATE TABLE IF NOT EXISTS logs (id INTEGER PRIMARY KEY, msg TEXT); INSERT INTO logs (msg) VALUES ('startup');" } ``` -------------------------------- ### batch() Method Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/transaction-context.md Example showcasing the batch() method for executing multiple write operations sequentially within a transaction. ```typescript await db.transaction(async (tx) => { const results = await tx.batch([ { sql: "INSERT INTO users (name) VALUES (?)", params: ["Alice"] }, { sql: "INSERT INTO users (name) VALUES (?)", params: ["Bob"] }, { sql: "UPDATE counters SET total = total + 2" }, ]); console.log(results); // Array of 3 RunResult objects }); ``` -------------------------------- ### drop() Method Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/fts5-helper.md Example of dropping an FTS5 virtual table. ```typescript db.fts.drop("articles"); ``` -------------------------------- ### Open Database in Read-Only Mode Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/configuration.md Example of opening a database in read-only mode. ```typescript const db = new BunQL("./app.db", { readonly: true }); // await db.run(...) → throws error // db.query(...) → works ``` -------------------------------- ### FTS5 Table Creation Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/types.md An example of creating an FTS5 table with custom tokenization and prefix search options. ```typescript db.fts.create("articles", ["title", "body"], { tokenize: "porter", prefix: [2, 4], // Enable 2-char and 4-char prefix search }); ``` -------------------------------- ### Set Synchronous Mode Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/configuration.md Example of setting the synchronous PRAGMA mode. ```typescript const db = new BunQL("./app.db", { synchronous: "NORMAL", // Default, good for WAL }); ``` -------------------------------- ### POST /query Request Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/endpoints.md Example JSON payload for executing a SELECT query. ```json { "sql": "SELECT * FROM users WHERE name = ? AND age > ?", "params": ["Alice", 18] } ``` -------------------------------- ### Enable Foreign Keys Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/configuration.md Example of enabling foreign key constraint enforcement. ```typescript const db = new BunQL("./app.db", { foreignKeys: true }); ``` -------------------------------- ### Vacuum Operation Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/types.md Example of performing a vacuum operation and logging the result. ```typescript const result = await db.vacuum({ incremental: true }); console.log(`Reclaimed ${result.pagesReclaimed} pages`); ``` -------------------------------- ### Authentication Header Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/endpoints.md Example of how to include the API key in the request header for authenticated endpoints. ```bash curl -X POST http://localhost:3000/query \ -H "x-api-key: secret-key" \ -H "Content-Type: application/json" \ -d '{"sql": "SELECT 1"}' ``` -------------------------------- ### POST /query Endpoint Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/endpoints.md Example cURL command for executing a SELECT query with parameters and authentication. ```bash curl -X POST http://localhost:3000/query \ -H "Content-Type: application/json" \ -H "x-api-key: secret" \ -d '{ "sql": "SELECT id, name FROM users WHERE age > ?", "params": [18] }' ``` -------------------------------- ### metrics getter example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunql-class.md Example usage of the metrics getter to log operation statistics. ```typescript const m = db.metrics; console.log(`Writes: ${m.writes.total}, Failed: ${m.writes.failed}, Retried: ${m.writes.retried}`); console.log(`Queue: ${m.queue.currentSize}/${m.queue.peakSize}`); ``` -------------------------------- ### hooks.beforeTransaction Lifecycle Hook Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/configuration.md Callback executed before starting a transaction. ```typescript beforeTransaction?: () => void ``` ```typescript const db = new BunQL("./app.db", { hooks: { beforeTransaction: () => { console.log("[TX] beginning"); metrics.increment("db_transactions_started"); }, }, }); ``` -------------------------------- ### Cache Stats Access Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/types.md Example of accessing and logging cache statistics. ```typescript const stats = db.cacheStats; console.log(`Cache: ${stats.size} statements, ${(stats.hitRate * 100).toFixed(1)}% hit rate`); ``` -------------------------------- ### BunQLServer Initialization with CORS Enabled Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunqlserver.md TypeScript example of initializing BunQLServer with CORS enabled. ```typescript const server = new BunQLServer(db, { port: 3000, cors: true }); ``` -------------------------------- ### query() Method Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/transaction-context.md Example of using the query() method within a transaction to fetch users and then update their verified status. ```typescript await db.transaction(async (tx) => { const users = tx.query<{ id: number; name: string }>( "SELECT * FROM users WHERE name LIKE ?", ["%Alice%"] ); for (const user of users) { await tx.run("UPDATE users SET verified = 1 WHERE id = ?", [user.id]); } }); ``` -------------------------------- ### POST /transaction cURL Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunqlserver.md cURL command to execute a transaction with INSERT and UPDATE operations. ```bash curl -X POST http://localhost:3000/transaction \ -H "Content-Type: application/json" \ -H "x-api-key: secret-key" \ -d '{ "operations": [ {"sql": "INSERT INTO audit (action) VALUES (?)", "params": ["user_created"]}, {"sql": "UPDATE stats SET total_users = total_users + 1"} ] }' ``` -------------------------------- ### rank() function signature and example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/fts5-helper.md Signature and example for the rank function, used to get the relevance score for a specific document. ```typescript rank(table: string, query: string, id: number): number const rank = db.fts.rank("articles", "sqlite", 5); console.log(`Document 5 relevance: ${rank}`); // e.g., -2.5 ``` -------------------------------- ### TransactionContext Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/transaction-context.md Demonstrates basic usage of the transaction context with INSERT, UPDATE, and query operations. ```typescript import { BunQL } from "@nds-stack/bunql"; const db = new BunQL("./app.db"); await db.transaction(async (tx) => { // All operations here are atomic await tx.run("INSERT INTO users (name) VALUES (?)", ["Alice"]); await tx.run("UPDATE logs SET count = count + 1"); const user = tx.query("SELECT * FROM users WHERE name = ?", ["Alice"]); }); ``` -------------------------------- ### Example - Failed to Open Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/errors.md Demonstrates catching a ConnectionError when attempting to open a database with an invalid path. ```typescript import { ConnectionError } from "@nds-stack/bunql"; try { const db = new BunQL("/invalid/path/app.db"); } catch (err) { if (err instanceof ConnectionError) { console.error("Cannot open database:", err.message); console.error("Cause:", err.cause?.message); // System error } } ``` -------------------------------- ### Log Slow Queries Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/configuration.md Example of configuring a slow query threshold and an event handler. ```typescript const db = new BunQL("./app.db", { slowQueryThreshold: 100, // Log queries > 100ms events: { onSlowQuery: (sql, ms) => { console.warn(`Slow query (${ms}ms): ${sql}`); }, }, }); ``` -------------------------------- ### POST /run Request Example (Insert) Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/endpoints.md Example JSON payload for inserting data using the /run endpoint. ```json { "sql": "INSERT INTO users (name, age) VALUES (?, ?)", "params": ["Bob", 28] } ``` -------------------------------- ### Checkpoint Operation Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/types.md An example of performing a manual WAL checkpoint with a specified mode. ```typescript await db.checkpoint("TRUNCATE"); ``` -------------------------------- ### POST /batch Response Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/endpoints.md Example JSON response for a successful POST /batch request, showing results for each operation. ```json [ { "changes": 1, "lastInsertRowid": 1, "durationMs": 0.5 }, { "changes": 1, "lastInsertRowid": 2, "durationMs": 0.3 }, { "changes": 1, "lastInsertRowid": null, "durationMs": 0.2 } ] ``` -------------------------------- ### rebuild() function signature and example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/fts5-helper.md Signature and example for the rebuild function, used to rebuild the FTS5 index. ```typescript rebuild(table: string): void // After bulk updates via raw SQL db.raw.run("UPDATE articles SET body = 'new content' WHERE id = 1"); // Rebuild index db.fts.rebuild("articles"); ``` -------------------------------- ### getDelay() Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/internal-utilities.md Demonstrates how getDelay() calculates delays with base delay, max delay, and jitter. ```typescript const policy = new RetryPolicy({ baseDelay: 50, maxDelay: 1000, jitter: true, }); console.log(policy.getDelay(0)); // ~50ms console.log(policy.getDelay(1)); // ~100ms console.log(policy.getDelay(2)); // ~200ms console.log(policy.getDelay(5)); // ~1000ms (capped) ``` -------------------------------- ### POST /batch Request Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/endpoints.md Example JSON request body for the POST /batch endpoint, demonstrating multiple insert and update operations. ```json { "operations": [ { "sql": "INSERT INTO users (name) VALUES (?)", "params": ["Alice"] }, { "sql": "INSERT INTO users (name) VALUES (?)", "params": ["Bob"] }, { "sql": "UPDATE counters SET total = total + 2" } ] } ``` -------------------------------- ### QueryResult Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/types.md Example usage of QueryResult. ```typescript const result = db.query<{ id: number; name: string }>( "SELECT id, name FROM users" ); result.rows.forEach(row => { console.log(row.id, row.name); }); ``` -------------------------------- ### Client Library Example: Run Function Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunqlserver.md TypeScript function using fetch to execute a write operation (e.g., INSERT, UPDATE) against the BunQL server. ```typescript async function run(sql: string, params?: unknown[]) { const response = await fetch("http://localhost:3000/run", { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": "secret-key", }, body: JSON.stringify({ sql, params }), }); if (!response.ok) { throw new Error(`Run failed: ${response.statusText}`); } return response.json(); } ``` -------------------------------- ### Set Busy Timeout Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/configuration.md Example of setting a custom busy timeout for SQLite. ```typescript const db = new BunQL("./app.db", { busyTimeout: 10000 }); // 10s ``` -------------------------------- ### Configure Retry Base Delay Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/configuration.md Example of setting a custom initial delay for exponential backoff retries. ```typescript const db = new BunQL("./app.db", { retry: { baseDelay: 25 }, // Start at 25ms }); ``` -------------------------------- ### FTS5 Full-Text Search Setup and Usage Source: https://github.com/nds-stack/bunql/blob/main/README.md Demonstrates how to set up, insert data into, search, and maintain FTS5 indexes using BunQL. ```typescript import { BunQL } from "@nds-stack/bunql"; const db = new BunQL("./app.db"); // Setup (synchronous — no await needed) db.fts.create("articles", ["title", "body"]); // Insert db.fts.insert("articles", { title: "Hello SQLite", body: "SQLite FTS5 is a powerful full-text search engine", }); // Search with ranking + snippet const results = db.fts.search("articles", "sqlite", { limit: 10, snippet: { startTag: "", endTag: "" }, }); // Index maintenance (synchronous) db.fts.optimize("articles"); db.fts.rebuild("articles"); db.fts.drop("articles"); ``` -------------------------------- ### Server-Side (BunQLServer) Source: https://github.com/nds-stack/bunql/blob/main/README.md Example of setting up a BunQLServer to provide an HTTP bridge for database access, ensuring serialized writes. ```typescript import { BunQL } from "@nds-stack/bunql"; import { BunQLServer } from "@nds-stack/bunql/server"; const db = new BunQL("./app.db"); const server = new BunQLServer(db, { port: 3000, secret: "my-api-key" }); server.start(); // → HTTP endpoint: http://localhost:3000 — serialized through one BunQL instance ``` -------------------------------- ### StatementCache clear() Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/internal-utilities.md Example of clearing all statements from the cache. ```typescript cache.clear(); ``` -------------------------------- ### backup() method Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunql-class.md Creates an online backup of the database using the 'VACUUM INTO' command. This operation is safe for concurrent reads and includes path validation to prevent security vulnerabilities. ```typescript async backup(path: string): Promise ``` ```typescript const result = await db.backup("./backups/app-2026-05-28.db"); console.log(`Backup complete: ${result.size} bytes in ${result.durationMs}ms`); ``` -------------------------------- ### StatementCache remove() Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/internal-utilities.md Example of removing a specific statement from the cache. ```typescript cache.remove("SELECT * FROM users WHERE id = ?"); ``` -------------------------------- ### Error Handling Example Source: https://github.com/nds-stack/bunql/blob/main/README.md Demonstrates how to catch and handle specific BunQL errors like BusyError and ConnectionError. ```typescript import { BunQL, BusyError, ConnectionError } from "@nds-stack/bunql"; try { await db.run("INSERT INTO logs (msg) VALUES (?)", ["hello"]); } catch (err) { if (err instanceof BusyError) { console.error("Database busy after retries:", err.cause); // Retry later or fail gracefully } else if (err instanceof ConnectionError) { console.error("Broken connection:", err.message); } else { throw err; // Unexpected error — re-throw } } ``` -------------------------------- ### BunQL Constructor Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/configuration.md Constructor signature for BunQL. ```typescript new BunQL(path: string, options?: BunQLOptions) ``` -------------------------------- ### Multiple Processes (External Access) Source: https://github.com/nds-stack/bunql/blob/main/README.md Example of configuring BunQL for scenarios with external processes accessing the same SQLite file, including retry options and busy timeout. ```typescript const db = new BunQL("./app.db", { retry: { maxRetries: 10, baseDelay: 100 }, // Higher tolerance for external contention busyTimeout: 10000, // SQLite-level busy timeout }); ``` -------------------------------- ### Reader pool requires WAL mode Source: https://github.com/nds-stack/bunql/blob/main/README.md Configuration example showing that the reader pool requires WAL mode to be enabled. ```typescript const db = new BunQL("./app.db", { wal: true, // required when readerPool > 0 readerPool: 3, }); ``` -------------------------------- ### delete() Method Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/fts5-helper.md Example of deleting a document from an FTS5 table by its rowid. ```typescript db.fts.delete("articles", 5); // Delete document with rowid=5 ``` -------------------------------- ### FTS Search Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/types.md Example of performing a full-text search and processing the results. ```typescript interface Article extends FTSResult { rowid: number; title: string; body: string; snippet?: string; } const results = db.fts.search
("articles", "sqlite", { snippet: true, }); results.forEach(r => { console.log(`${r.title} (rank: ${r.rank})`); if (r.snippet) console.log(` ${r.snippet}`); }); ``` -------------------------------- ### Client Library Example: Query Function Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunqlserver.md TypeScript function using fetch to execute a SELECT query against the BunQL server. ```typescript async function query(sql: string, params?: unknown[]) { const response = await fetch("http://localhost:3000/query", { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": "secret-key", }, body: JSON.stringify({ sql, params }), }); if (!response.ok) { throw new Error(`Query failed: ${response.statusText}`); } return response.json(); } ``` -------------------------------- ### POST /transaction cURL Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/endpoints.md Example cURL command to execute a transaction with mixed operations. ```bash curl -X POST http://localhost:3000/transaction \ -H "Content-Type: application/json" \ -H "x-api-key: secret" \ -d '{ "operations": [ {"sql": "SELECT balance FROM accounts WHERE id = ?", "params": [1]}, {"sql": "UPDATE accounts SET balance = balance - 50 WHERE id = ?", "params": [1]}, {"sql": "UPDATE accounts SET balance = balance + 50 WHERE id = ?", "params": [2]} ] }' # → [ # [{"balance": 1000}], # {"changes": 1, "lastInsertRowid": null, "durationMs": 0.2}, # {"changes": 1, "lastInsertRowid": null, "durationMs": 0.1} # ] ``` -------------------------------- ### Constructor Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunql-class.md Creates a new BunQL instance connected to the SQLite database at `path`. Initializes the write queue, statement cache, retry policy, and optional reader pool. All writes are automatically queued and serialized. Reads execute in parallel and bypass the queue. ```typescript import { BunQL } from "@nds-stack/bunql"; const db = new BunQL("./app.db", { wal: true, busyTimeout: 5000, synchronous: "NORMAL", }); ``` -------------------------------- ### File Organization Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/INDEX.md Directory structure for the BunQL project, showing the location of various documentation files. ```bash output/ ├── README.md # Start here ├── INDEX.md # This file ├── configuration.md # All constructor options ├── types.md # Type definitions reference ├── errors.md # Error handling guide ├── endpoints.md # HTTP API reference └── api-reference/ ├── bunql-class.md # Main BunQL API ├── transaction-context.md # Transaction methods ├── fts5-helper.md # Full-text search API ├── bunqlserver.md # HTTP server class └── internal-utilities.md # WriteQueue, RetryPolicy, etc. ``` -------------------------------- ### prepare() method Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/bunql-class.md Prepares and caches a SQL statement for reuse. Allows fetching rows, executing writes, and manual finalization. ```typescript prepare( sql: string ): Statement ``` ```typescript const stmt = db.prepare<{ id: number; name: string }, [string]>( "SELECT * FROM users WHERE name = ?" ); const alice = stmt.get("Alice"); // Synchronous const all = stmt.all("Bob"); // Synchronous await stmt.run("NewName", [123]); // Asynchronous, queued stmt.finalize(); // Close and remove from cache ``` -------------------------------- ### optimize() function signature and example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/fts5-helper.md Signature and example for the optimize function, used to optimize the FTS5 index. ```typescript optimize(table: string): void db.fts.optimize("articles"); ``` -------------------------------- ### BunQLServer Constructor Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/configuration.md The constructor for the BunQLServer class. ```typescript new BunQLServer(bunql: BunQL, options?: ServerOptions) ``` -------------------------------- ### POST /batch Error Response Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/endpoints.md Example JSON error response for a failed POST /batch request. ```json { "error": "UNIQUE constraint failed: users.id" } ``` -------------------------------- ### FTS5Helper Usage Example Source: https://github.com/nds-stack/bunql/blob/main/_autodocs/api-reference/fts5-helper.md Demonstrates creating an FTS5 virtual table, inserting a document, and performing a ranked search with snippets and highlighting. ```typescript import { BunQL } from "@nds-stack/bunql"; const db = new BunQL("./app.db"); // Create FTS5 virtual table db.fts.create("articles", ["title", "body"]); // Insert document db.fts.insert("articles", { title: "Hello SQLite", body: "SQLite is a powerful embedded database", }); // Search with ranking and snippets const results = db.fts.search("articles", "sqlite", { limit: 10, snippet: { startTag: "", endTag: "" }, }); console.log(results); // [{ rowid: 1, title: "...", body: "...", snippet: "...", rank: -1.5 }] ```