### Install narrowdb-server Source: https://github.com/lassejlv/narrowdb/blob/main/crates/server/README.md Install the server binary using cargo. ```bash cargo install narrowdb-server ``` -------------------------------- ### CLI Example: Benchmark Source: https://github.com/lassejlv/narrowdb/blob/main/docs.md Example of running a benchmark with a specified number of rows. ```bash # Benchmark with 5 million rows narrowdb bench logs.db 5000000 ``` -------------------------------- ### Quick start with CLI Source: https://github.com/lassejlv/narrowdb/blob/main/README.md Build the project and execute SQL commands directly against a database file. ```bash cargo build --release # Create a table and insert data narrowdb exec logs.db "CREATE TABLE logs (ts TIMESTAMP, level TEXT, service TEXT, status INT, duration REAL);" narrowdb exec logs.db "INSERT INTO logs VALUES (1, 'info', 'api', 200, 12.0), (2, 'error', 'api', 500, 120.0);" # Query with filters, aggregation, and ordering narrowdb exec logs.db "SELECT service, COUNT(*) AS errors FROM logs WHERE level = 'error' GROUP BY service ORDER BY errors DESC LIMIT 5;" ``` -------------------------------- ### CLI Example: Create Table Source: https://github.com/lassejlv/narrowdb/blob/main/docs.md Example of creating a table named 'logs' using the CLI. ```bash # Create a table narrowdb exec logs.db "CREATE TABLE logs (ts TIMESTAMP, level TEXT, service TEXT, status INT, duration REAL);" ``` -------------------------------- ### Run narrowdb-server Source: https://github.com/lassejlv/narrowdb/blob/main/crates/server/README.md Start the server by specifying the database file path and optional configuration flags. ```bash narrowdb-server [options] ``` ```bash narrowdb-server ./logs.narrowdb --listen 0.0.0.0:5433 --user admin --password s3cret ``` -------------------------------- ### Running the TCP server Source: https://github.com/lassejlv/narrowdb/blob/main/README.md Start the server crate to enable PostgreSQL wire protocol access. ```bash cargo run -p narrowdb-server -- ./logs.narrowdb --listen 127.0.0.1:5433 --user narrowdb --password secret ``` -------------------------------- ### CLI Example: Query with Aggregation Source: https://github.com/lassejlv/narrowdb/blob/main/docs.md Example of querying logs, filtering by level, aggregating, and ordering results. ```bash # Query with filters, aggregation, and ordering narrowdb exec logs.db "SELECT service, COUNT(*) AS errors FROM logs WHERE level = 'error' GROUP BY service ORDER BY errors DESC LIMIT 5;" ``` -------------------------------- ### TCP Server: Running with Arguments Source: https://github.com/lassejlv/narrowdb/blob/main/docs.md Start the NarrowDB TCP server with database file, listen address, user, and password. ```bash cargo run -p narrowdb-server -- ./logs.narrowdb \ --listen 127.0.0.1:5433 \ --user narrowdb \ --password secret ``` -------------------------------- ### CLI Example: Table-less Expressions Source: https://github.com/lassejlv/narrowdb/blob/main/docs.md Example of evaluating expressions without a table context. ```bash # Table-less expressions narrowdb exec logs.db "SELECT 2 + 3 * 4;" ``` -------------------------------- ### CLI Example: Insert Rows Source: https://github.com/lassejlv/narrowdb/blob/main/docs.md Example of inserting rows into the 'logs' table using the CLI. ```bash # Insert rows narrowdb exec logs.db "INSERT INTO logs VALUES (1, 'info', 'api', 200, 12.0), (2, 'error', 'api', 500, 120.0);" ``` -------------------------------- ### TCP Server: Running with Environment Variables Source: https://github.com/lassejlv/narrowdb/blob/main/docs.md Start the NarrowDB TCP server using environment variables for configuration. ```bash NARROWDB_LISTEN=0.0.0.0:5433 \ NARROWDB_USER=narrowdb \ NARROWDB_PASSWORD=secret \ narrowdb-server ./logs.narrowdb ``` -------------------------------- ### CLI Example: Arithmetic Expressions Source: https://github.com/lassejlv/narrowdb/blob/main/docs.md Example of using arithmetic expressions in a SELECT statement. ```bash # Arithmetic expressions in SELECT narrowdb exec logs.db "SELECT duration * 1.1 AS padded FROM logs WHERE status >= 500;" ``` -------------------------------- ### Example SQL for TCP server Source: https://github.com/lassejlv/narrowdb/blob/main/README.md Standard SQL commands compatible with the PostgreSQL wire protocol implementation. ```sql CREATE TABLE logs (ts TIMESTAMP, service TEXT, status INT); INSERT INTO logs VALUES (1, 'api', 200); SELECT * FROM logs; ``` -------------------------------- ### SQL WHERE Clause Examples Source: https://github.com/lassejlv/narrowdb/blob/main/docs.md Demonstrates various operators for filtering data in SQL queries. Ensure correct syntax for each operator. ```sql WHERE status >= 500 AND level = 'error' AND ts >= 1700000000 ``` ```sql WHERE level = 'error' ``` ```sql WHERE level != 'info' ``` ```sql WHERE duration >= 100.0 ``` ```sql WHERE service IS NULL ``` ```sql WHERE service IS NOT NULL ``` -------------------------------- ### Start NarrowDB TCP Server Source: https://context7.com/lassejlv/narrowdb/llms.txt Run NarrowDB as a standalone TCP server using the PostgreSQL wire protocol. Connect with any PostgreSQL client. Configuration can be done via command-line arguments or environment variables. ```bash # Start the server cargo run -p narrowdb-server -- ./logs.db \ --listen 127.0.0.1:5433 \ --user narrowdb \ --password secret \ --row-group-size 16384 \ --sync-on-flush true # Or use environment variables NARROWDB_LISTEN=0.0.0.0:5433 \ NARROWDB_USER=admin \ NARROWDB_PASSWORD=mysecret \ narrowdb-server ./logs.db ``` -------------------------------- ### Columnar Batch Ingestion Example Source: https://github.com/lassejlv/narrowdb/blob/main/docs.md Illustrates how to ingest data using `ColumnarBatch` for high-throughput scenarios. Ensure all columns have the same number of rows and match the table schema. ```rust BatchColumn::Int64 => Vec, BatchColumn::Float64 => Vec, BatchColumn::Bool => Vec, BatchColumn::String => Vec, BatchColumn::Timestamp => Vec ``` -------------------------------- ### Execute Single SQL Statement and Get One Result in NarrowDB Source: https://context7.com/lassejlv/narrowdb/llms.txt Shows how to execute a single SQL statement using `execute_one` and access the result, specifically retrieving a single value from the first row and first column. ```rust // Execute single statement and get one result let result = db.execute_one("SELECT COUNT(*) AS total FROM users;")?; println!("Total users: {:?}", result.rows[0][0]); // Int64(2) ``` -------------------------------- ### Build NarrowDB from Source Source: https://github.com/lassejlv/narrowdb/blob/main/docs.md Clone the repository and build the release binary. ```bash git clone https://github.com/lassejlv/narrowdb.git cd narrowdb cargo build --release ``` -------------------------------- ### Execute SQL and Process Query Results in NarrowDB Source: https://context7.com/lassejlv/narrowdb/llms.txt Demonstrates opening a database, creating a table, inserting data, executing a SELECT query, and iterating through the results. Shows how to access column names and row values, handling different data types like String, Int64, Float64, Bool, and Null. ```rust use narrowdb::{NarrowDb, DbOptions, Value}; let db = NarrowDb::open("app.db", DbOptions::default())?; db.execute_sql("CREATE TABLE users (id INT, name TEXT, score REAL);")?; db.execute_sql("INSERT INTO users VALUES (1, 'Alice', 95.5), (2, 'Bob', 87.0);")?; let results = db.execute_sql("SELECT name, score FROM users WHERE score > 90;")?; for result in results { // Column names as Vec println!("Columns: {:?}", result.columns); // ["name", "score"] // Rows as Vec> for row in result.rows { for value in row { match value { Value::String(s) => println!("String: {}", s), Value::Int64(i) => println!("Int: {}", i), Value::Float64(f) => println!("Float: {}", f.into_inner()), Value::Bool(b) => println!("Bool: {}", b), Value::Null => println!("NULL") } } } } ``` -------------------------------- ### Build and Run with Docker Source: https://github.com/lassejlv/narrowdb/blob/main/crates/server/README.md Commands for building the Docker image and running the container with persistent storage and environment configuration. ```bash docker build -f crates/server/Dockerfile -t narrowdb-server . ``` ```bash docker run -v narrowdb-data:/data -p 5433:5433 narrowdb-server ``` ```bash docker run -v narrowdb-data:/data -p 5433:5433 \ -e NARROWDB_USER=admin \ -e NARROWDB_PASSWORD=s3cret \ narrowdb-server ``` -------------------------------- ### Connect to narrowdb-server Source: https://github.com/lassejlv/narrowdb/blob/main/crates/server/README.md Use standard PostgreSQL clients like psql to connect to the running server instance. ```bash PGPASSWORD=s3cret psql "host=127.0.0.1 port=5433 user=admin dbname=logs" ``` -------------------------------- ### Build and Execute SQL with NarrowDB CLI Source: https://context7.com/lassejlv/narrowdb/llms.txt Build the NarrowDB command-line interface and execute SQL commands against a database file. ```bash # Build the CLI cargo build --release # Execute SQL against a database file narrowdb exec logs.db "CREATE TABLE logs (ts TIMESTAMP, level TEXT, service TEXT, status INT);" narrowdb exec logs.db "INSERT INTO logs VALUES (1, 'info', 'api', 200), (2, 'error', 'api', 500);" narrowdb exec logs.db "SELECT service, COUNT(*) AS errors FROM logs WHERE level = 'error' GROUP BY service ORDER BY errors DESC LIMIT 5;" ``` -------------------------------- ### Open a NarrowDB database Source: https://context7.com/lassejlv/narrowdb/llms.txt Initializes a database connection using default or custom configuration options. ```rust use narrowdb::{NarrowDb, DbOptions}; // Open with default options (16K row group size, fsync enabled) let db = NarrowDb::open("logs.db", DbOptions::default())?; // Open with custom options for high-throughput ingestion let db = NarrowDb::open("logs.db", DbOptions { row_group_size: 32_768, // Larger row groups for better compression sync_on_flush: false, // Disable fsync for faster writes auto_flush_interval: None, // Manual flush control })?; ``` -------------------------------- ### Use Aggregate Functions in SQL Source: https://context7.com/lassejlv/narrowdb/llms.txt Shows how to use COUNT, SUM, AVG, MIN, and MAX functions with optional GROUP BY clauses. ```rust use narrowdb::{NarrowDb, DbOptions}; let db = NarrowDb::open("sales.db", DbOptions::default())?; db.execute_sql("CREATE TABLE sales (region TEXT, product TEXT, amount REAL, quantity INT);")?; db.execute_sql("INSERT INTO sales VALUES ('west', 'widget', 100.0, 10), ('west', 'gadget', 250.0, 5), ('east', 'widget', 150.0, 15), ('east', 'gadget', 300.0, 8);")?; // COUNT with and without column let results = db.execute_sql("SELECT COUNT(*) AS total_rows FROM sales;")?; let results = db.execute_sql("SELECT COUNT(amount) AS non_null_amounts FROM sales;")?; // SUM and AVG let results = db.execute_sql( "SELECT region, SUM(amount) AS revenue, AVG(quantity) AS avg_qty FROM sales GROUP BY region;" )?; // MIN and MAX let results = db.execute_sql( "SELECT product, MIN(amount) AS min_sale, MAX(amount) AS max_sale FROM sales GROUP BY product;" )?; ``` -------------------------------- ### Run NarrowDB Benchmarks Source: https://context7.com/lassejlv/narrowdb/llms.txt Execute built-in benchmarks for NarrowDB from the command line, with options to specify the number of rows. ```bash # Run built-in benchmark (default 1M rows) narrowdb bench benchmark.db # Benchmark with 5 million rows narrowdb bench benchmark.db 5000000 ``` -------------------------------- ### Connecting via psql Source: https://github.com/lassejlv/narrowdb/blob/main/README.md Connect to the running narrowdb server using the standard psql client. ```bash PGPASSWORD=secret psql "host=127.0.0.1 port=5433 user=narrowdb dbname=logs" ``` -------------------------------- ### Create tables using SQL Source: https://context7.com/lassejlv/narrowdb/llms.txt Defines table schemas using standard SQL syntax, supporting various data types. ```rust use narrowdb::{NarrowDb, DbOptions}; let db = NarrowDb::open("app.db", DbOptions::default())?; // Create table using SQL db.execute_sql("CREATE TABLE logs ( ts TIMESTAMP, level TEXT, service TEXT, status INT, duration REAL );")?; // Create table only if it doesn't exist db.execute_sql("CREATE TABLE IF NOT EXISTS events ( id INT, event_type TEXT, payload TEXT );")?; ``` -------------------------------- ### Library Usage: Basic Operations Source: https://github.com/lassejlv/narrowdb/blob/main/docs.md Open a database, create a table, insert data, and query results using the NarrowDB Rust library. ```rust use narrowdb::{NarrowDb, DbOptions, Value}; fn main() -> anyhow::Result<()> { let mut db = NarrowDb::open("my.db", DbOptions::default())?; db.execute_sql("CREATE TABLE logs (ts TIMESTAMP, level TEXT, service TEXT, status INT);")?; db.execute_sql("INSERT INTO logs VALUES (1, 'info', 'api', 200), (2, 'error', 'api', 500);")?; let results = db.execute_sql( "SELECT service, COUNT(*) AS total FROM logs GROUP BY service;" )?; for result in results { println!("Columns: {:?}", result.columns); for row in &result.rows { println!("{:?}", row); } } Ok(()) } ``` -------------------------------- ### Execute SELECT Queries in Rust Source: https://context7.com/lassejlv/narrowdb/llms.txt Demonstrates basic SELECT queries with filtering, aggregation, grouping, and sorting using the NarrowDB execute_sql method. ```rust use narrowdb::{NarrowDb, DbOptions}; let db = NarrowDb::open("logs.db", DbOptions::default())?; db.execute_sql("CREATE TABLE logs (ts TIMESTAMP, level TEXT, service TEXT, status INT, duration REAL);")?; db.execute_sql("INSERT INTO logs VALUES (1, 'info', 'api', 200, 12.0), (2, 'error', 'api', 500, 120.0), (3, 'error', 'worker', 503, 250.0), (4, 'info', 'worker', 200, 8.0);")?; // Simple SELECT with filter let results = db.execute_sql("SELECT service, status FROM logs WHERE status >= 500;")?; // Returns: [["api", 500], ["worker", 503]] // SELECT with aggregation and GROUP BY let results = db.execute_sql( "SELECT service, COUNT(*) AS total, AVG(duration) AS avg_duration FROM logs WHERE level = 'error' GROUP BY service ORDER BY total DESC LIMIT 10;" )?; for result in results { println!("Columns: {:?}", result.columns); // ["service", "total", "avg_duration"] for row in result.rows { println!("{:?}", row); // [String("api"), Int64(1), Float64(120.0)] } } // SELECT * wildcard let results = db.execute_sql("SELECT * FROM logs WHERE level = 'info';")?; ``` -------------------------------- ### Connect to NarrowDB TCP Server with psql Source: https://context7.com/lassejlv/narrowdb/llms.txt Connect to a running NarrowDB TCP server using the psql client and execute SQL commands. ```bash # Connect with psql PGPASSWORD=secret psql "host=127.0.0.1 port=5433 user=narrowdb dbname=logs" # Execute SQL CREATE TABLE logs (ts TIMESTAMP, service TEXT, status INT); INSERT INTO logs VALUES (1700000000, 'api', 200), (1700000001, 'worker', 503); SELECT service, COUNT(*) FROM logs WHERE status >= 500 GROUP BY service; ``` -------------------------------- ### Using narrowdb as a Rust library Source: https://github.com/lassejlv/narrowdb/blob/main/README.md Open a database, execute SQL, and insert rows programmatically. ```rust use narrowdb::{NarrowDb, DbOptions, Schema, ColumnDef, DataType, Value}; let mut db = NarrowDb::open("my.db", DbOptions::default())?; db.execute_sql("CREATE TABLE logs (ts TIMESTAMP, msg TEXT);")?; db.insert_rows("logs", vec![vec![Value::Int64(1), Value::String("hello".into())]])?; let results = db.execute_sql("SELECT * FROM logs;")?; ``` -------------------------------- ### SQL Reference: CREATE TABLE Source: https://github.com/lassejlv/narrowdb/blob/main/docs.md Syntax for creating a new table in NarrowDB. ```sql CREATE TABLE table_name ( column1 TYPE, column2 TYPE, ... ); ``` -------------------------------- ### Execute SQL via CLI Source: https://github.com/lassejlv/narrowdb/blob/main/docs.md Use the narrowdb CLI to execute SQL commands against a database file. ```bash # Execute SQL against a database file narrowdb exec ``` ```bash # Run built-in benchmark narrowdb bench [rows] ``` -------------------------------- ### Execute SQL Queries Source: https://github.com/lassejlv/narrowdb/blob/main/crates/server/README.md Run standard SQL commands against the connected narrowdb-server. ```sql CREATE TABLE logs (ts TIMESTAMP, service TEXT, status INT); INSERT INTO logs VALUES (1, 'api', 200); SELECT * FROM logs WHERE status = 200; ``` -------------------------------- ### Library dependency configuration Source: https://github.com/lassejlv/narrowdb/blob/main/README.md Add narrowdb to your Cargo.toml file to use it as a library. ```toml [dependencies] narrowdb = "0.1" ``` -------------------------------- ### Add NarrowDB Dependency Source: https://github.com/lassejlv/narrowdb/blob/main/docs.md Add this to your Cargo.toml to include NarrowDB as a dependency. ```toml [dependencies] narrowdb = "0.2" ``` -------------------------------- ### NarrowDB Data Types Reference and Usage Source: https://context7.com/lassejlv/narrowdb/llms.txt Map SQL type names to internal storage types and Rust equivalents. All types support NULL values. Demonstrates creating a table with various types and inserting data. ```rust // SQL Type Names -> Internal Type -> Rust Equivalent // INT, INTEGER, BIGINT -> Int64 -> i64 // REAL, FLOAT, DOUBLE -> Float64 -> f64 // BOOL, BOOLEAN -> Bool -> bool // TEXT, STRING, VARCHAR -> String -> String // TIMESTAMP, DATETIME -> Timestamp -> i64 (epoch) use narrowdb::{NarrowDb, DbOptions}; let db = NarrowDb::open("types.db", DbOptions::default())?; db.execute_sql("CREATE TABLE all_types ( id INTEGER, score DOUBLE, active BOOLEAN, name VARCHAR, created_at DATETIME );")?; db.execute_sql("INSERT INTO all_types VALUES (1, 95.5, true, 'Alice', 1700000000), (2, NULL, false, 'Bob', 1700000001);")?; ``` -------------------------------- ### SQL Reference: SELECT Source: https://github.com/lassejlv/narrowdb/blob/main/docs.md Basic syntax for selecting data from a table. ```sql SELECT projections FROM table_name [WHERE filters] [GROUP BY columns] [ORDER BY column [ASC|DESC]] [LIMIT n]; ``` -------------------------------- ### Perform Arithmetic Expressions in SELECT Source: https://context7.com/lassejlv/narrowdb/llms.txt Illustrates performing arithmetic operations on columns and literals within SQL projections. ```rust use narrowdb::{NarrowDb, DbOptions}; let db = NarrowDb::open("products.db", DbOptions::default())?; db.execute_sql("CREATE TABLE products (name TEXT, price REAL, quantity INT, tax_rate REAL);")?; db.execute_sql("INSERT INTO products VALUES ('widget', 10.0, 5, 0.08), ('gadget', 25.0, 3, 0.10), ('gizmo', 7.5, 10, 0.05);")?; // Column * literal let results = db.execute_sql("SELECT name, price * 1.1 AS price_with_markup FROM products;")?; // Column * column let results = db.execute_sql("SELECT name, price * quantity AS total_value FROM products;")?; // Complex expression let results = db.execute_sql( "SELECT name, (price * quantity) * (1 + tax_rate) AS total_with_tax FROM products;" )?; // Table-less arithmetic expressions let results = db.execute_sql("SELECT 2 + 3 * 4 AS result;")?; // Returns 14 let results = db.execute_sql("SELECT 10 % 3 AS remainder;")?; // Returns 1 ``` -------------------------------- ### Insert rows via SQL Source: https://context7.com/lassejlv/narrowdb/llms.txt Executes SQL INSERT statements to add data to existing tables. ```rust use narrowdb::{NarrowDb, DbOptions}; let db = NarrowDb::open("app.db", DbOptions::default())?; db.execute_sql("CREATE TABLE logs (ts TIMESTAMP, level TEXT, service TEXT, status INT);")?; // Insert single row db.execute_sql("INSERT INTO logs VALUES (1700000000, 'info', 'api', 200);")?; // Insert multiple rows in one statement db.execute_sql("INSERT INTO logs VALUES (1700000001, 'error', 'api', 500), (1700000002, 'info', 'worker', 200), (1700000003, 'error', 'worker', 503);")?; ``` -------------------------------- ### Library Usage: Row-by-Row Insertion Source: https://github.com/lassejlv/narrowdb/blob/main/docs.md Insert a single row into a table using the `insert_row` method. ```rust use narrowdb::{NarrowDb, DbOptions, Value}; let mut db = NarrowDb::open("my.db", DbOptions::default())?; db.insert_row("logs", vec![ Value::Int64(1), Value::String("info".into()), Value::String("api".into()), Value::Int64(200), ])?; ``` -------------------------------- ### SQL Reference: INSERT Source: https://github.com/lassejlv/narrowdb/blob/main/docs.md Syntax for inserting rows into a table. ```sql INSERT INTO table_name VALUES (val1, val2, ...), (val1, val2, ...); ``` -------------------------------- ### Flush Data to Disk in NarrowDB Source: https://context7.com/lassejlv/narrowdb/llms.txt Manually trigger data persistence to disk for specific tables or all tables. SELECT queries automatically flush the target table for consistency. ```rust use narrowdb::{NarrowDb, DbOptions}; let db = NarrowDb::open("app.db", DbOptions::default())?; db.execute_sql("CREATE TABLE events (ts TIMESTAMP, data TEXT);")?; // Insert some rows (buffered in memory) db.execute_sql("INSERT INTO events VALUES (1, 'event1'), (2, 'event2');")?; // Flush a specific table to disk db.flush_table("events")?; // Or flush all tables at once db.flush_all()?; // Note: SELECT queries automatically flush the target table first // to ensure consistency ``` -------------------------------- ### Library Usage: Columnar Batch Insertion Source: https://github.com/lassejlv/narrowdb/blob/main/docs.md Insert data in batches using the `insert_columnar_batch` method for high throughput. ```rust use narrowdb::{NarrowDb, DbOptions, ColumnarBatch, BatchColumn}; let mut db = NarrowDb::open("my.db", DbOptions::default())?; let batch = ColumnarBatch::new(vec![ BatchColumn::Timestamp(vec![1, 2, 3]), BatchColumn::String(vec!["info".into(), "error".into(), "info".into()]), BatchColumn::String(vec!["api".into(), "api".into(), "worker".into()]), BatchColumn::Int64(vec![200, 500, 200]), ])?; db.insert_columnar_batch("logs", batch)?; ``` -------------------------------- ### Perform columnar batch ingestion Source: https://context7.com/lassejlv/narrowdb/llms.txt Optimizes ingestion throughput by providing data as typed vectors in columnar batches. ```rust use narrowdb::{NarrowDb, DbOptions, ColumnarBatch, BatchColumn}; let db = NarrowDb::open("events.db", DbOptions::default())?; db.execute_sql("CREATE TABLE events (ts TIMESTAMP, service TEXT, status INT, latency REAL);")?; // Create a columnar batch with 1000 rows let batch = ColumnarBatch::new(vec![ BatchColumn::Timestamp(vec![1700000000, 1700000001, 1700000002]), BatchColumn::String(vec!["api".into(), "worker".into(), "api".into()]), BatchColumn::Int64(vec![200, 503, 200]), BatchColumn::Float64(vec![12.5, 250.0, 8.3]), ])?; // Insert the batch - automatically flushes when row_group_size is reached db.insert_columnar_batch("events", batch)?; // Force flush remaining data to disk db.flush_all()?; ``` -------------------------------- ### Library Usage: Flushing Data Source: https://github.com/lassejlv/narrowdb/blob/main/docs.md Manually flush data to disk for a specific table or all tables. ```rust db.flush_table("logs")?; // Flush one table ``` ```rust db.flush_all()?; // Flush all tables ``` -------------------------------- ### Filter Data with WHERE Clauses Source: https://context7.com/lassejlv/narrowdb/llms.txt Covers the use of comparison operators and NULL checks for filtering query results. ```rust use narrowdb::{NarrowDb, DbOptions}; let db = NarrowDb::open("logs.db", DbOptions::default())?; db.execute_sql("CREATE TABLE logs (ts TIMESTAMP, level TEXT, status INT, duration REAL);")?; db.execute_sql("INSERT INTO logs VALUES (1, 'info', 200, 12.0), (2, 'error', 500, 120.0), (3, 'warn', 404, 45.0);")?; // Equality and comparison filters let results = db.execute_sql("SELECT * FROM logs WHERE level = 'error';")?; let results = db.execute_sql("SELECT * FROM logs WHERE status >= 400 AND status < 500;")?; let results = db.execute_sql("SELECT * FROM logs WHERE duration > 50.0;")?; // Not equal let results = db.execute_sql("SELECT * FROM logs WHERE level != 'info';")?; let results = db.execute_sql("SELECT * FROM logs WHERE level <> 'info';")?; // NULL handling let results = db.execute_sql("SELECT * FROM logs WHERE duration IS NOT NULL;")?; ``` -------------------------------- ### Table-less SELECT Statements Source: https://github.com/lassejlv/narrowdb/blob/main/docs.md Perform arithmetic operations without referencing a table. Useful for quick calculations or testing expressions. ```sql SELECT 1 + 2; ``` ```sql SELECT 5 * (3 - 2) AS result; ``` ```sql SELECT 10 % 3; ``` -------------------------------- ### Insert rows programmatically Source: https://context7.com/lassejlv/narrowdb/llms.txt Uses the Rust API with Value enums for type-safe data insertion. ```rust use narrowdb::{NarrowDb, DbOptions, Value}; let db = NarrowDb::open("app.db", DbOptions::default())?; db.execute_sql("CREATE TABLE metrics (ts TIMESTAMP, name TEXT, value REAL);")?; // Insert single row db.insert_row("metrics", vec![ Value::Int64(1700000000), Value::String("cpu_usage".into()), Value::Float64(ordered_float::OrderedFloat(45.5)), ])?; // Insert multiple rows at once db.insert_rows("metrics", vec![ vec![Value::Int64(1700000001), Value::String("memory_mb".into()), Value::Float64(ordered_float::OrderedFloat(2048.0))], vec![Value::Int64(1700000002), Value::String("disk_io".into()), Value::Float64(ordered_float::OrderedFloat(150.7))], ]); ``` -------------------------------- ### Concurrent Read-Only Queries in NarrowDB Source: https://context7.com/lassejlv/narrowdb/llms.txt Execute read-only queries under a shared lock for concurrent access. Unflushed rows are not visible; call flush_all() first if needed. ```rust use narrowdb::{NarrowDb, DbOptions}; use std::sync::Arc; use std::thread; let db = Arc::new(NarrowDb::open("shared.db", DbOptions::default())?); db.execute_sql("CREATE TABLE data (id INT, value TEXT);")?; db.execute_sql("INSERT INTO data VALUES (1, 'a'), (2, 'b');")?; db.flush_all()?; // Multiple threads can query concurrently let db_clone = Arc::clone(&db); let handle = thread::spawn(move || { // query() uses a read lock - multiple can run in parallel let results = db_clone.query("SELECT * FROM data WHERE id = 1;").unwrap(); results }); let results = db.query("SELECT * FROM data WHERE id = 2;")?; let other_results = handle.join().unwrap(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.