### Setup Python Virtual Environment and Dependencies Source: https://github.com/tursodatabase/libsql/blob/main/libsql-sqlite3/benchmark/README.md Install `numpy` and other required Python packages for benchmark scripts by setting up a virtual environment and installing from `requirements.txt`. ```sh $> python -m venv .env $> source .env/bin/activate $> pip install -r requirements.txt ``` -------------------------------- ### Install and Verify sqld with Homebrew Source: https://context7.com/tursodatabase/libsql/llms.txt Use these commands to install the `sqld` server via Homebrew on macOS or Linux, and then verify the installation by checking its help output. ```bash brew tap libsql/sqld brew install sqld sqld --help ``` -------------------------------- ### Install sqld with Homebrew Source: https://github.com/tursodatabase/libsql/blob/main/docs/BUILD-RUN.md Install the `sqld` binary using Homebrew after adding its tap. This places the executable in your PATH. ```bash brew install sqld ``` -------------------------------- ### Install Emscripten SDK on Linux Source: https://github.com/tursodatabase/libsql/blob/main/libsql-sqlite3/ext/wasm/README.md Install the Emscripten SDK by cloning the repository, installing the latest tools, and activating the SDK. This process is typically a one-time setup for the build environment. ```bash # Clone the emscripten repository: $ sudo apt install git $ git clone https://github.com/emscripten-core/emsdk.git $ cd emsdk # Download and install the latest SDK tools: $ ./emsdk install latest # Make the "latest" SDK "active" for the current user: $ ./emsdk activate latest ``` -------------------------------- ### Install bottomless-cli for Replication Management Source: https://github.com/tursodatabase/libsql/blob/main/libsql-server/README.md Install the `bottomless-cli` tool via Cargo to inspect and manage `sqld`'s replicated snapshots. ```bash RUSTFLAGS='--cfg uuid_unstable' cargo install bottomless-cli ``` -------------------------------- ### Basic Rusqlite Usage Example Source: https://github.com/tursodatabase/libsql/blob/main/vendored/rusqlite/README.md This example demonstrates how to open an in-memory SQLite database, create a table, insert a new record, and then query the data, mapping rows to a custom Rust struct. ```rust use rusqlite::{Connection, Result}; #[derive(Debug)] struct Person { id: i32, name: String, data: Option>, } fn main() -> Result<()> { let conn = Connection::open_in_memory()?; conn.execute( "CREATE TABLE person ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, data BLOB )", (), // empty list of parameters. )?; let me = Person { id: 0, name: "Steven".to_string(), data: None, }; conn.execute( "INSERT INTO person (name, data) VALUES (?1, ?2)", (&me.name, &me.data), )?; let mut stmt = conn.prepare("SELECT id, name, data FROM person")?; let person_iter = stmt.query_map([], |row| { Ok(Person { id: row.get(0)?, name: row.get(1)?, data: row.get(2)?, }) })?; for person in person_iter { println!("Found person {:?}", person.unwrap()); } Ok(()) } ``` -------------------------------- ### WAL Synchronization Example Source: https://github.com/tursodatabase/libsql/blob/main/libsql-sqlite3/doc/libsql_extensions.md Complete example demonstrating how to synchronize WAL frames from a primary database to a backup database using the libSQL WAL API functions. ```APIDOC ## WAL Synchronization Example ### Description This example demonstrates how to synchronize WAL (Write-Ahead Logging) frames from a primary database to a backup database using the libSQL WAL API. ### Usage Pattern ```c static void sync_db(sqlite3 *db_primary, sqlite3 *db_backup){ unsigned int max_frame; // Get the number of frames in the primary database WAL libsql_wal_frame_count(db_primary, &max_frame); // Begin WAL insertion on the backup database libsql_wal_insert_begin(db_backup); // Iterate through all frames and copy them for(int i=1; i<=max_frame; i++){ char frame[4096+24]; // Retrieve frame from primary database libsql_wal_get_frame(db_primary, i, frame, sizeof(frame)); // Insert frame into backup database int conflict; libsql_wal_insert_frame(db_backup, i, frame, sizeof(frame), &conflict); } // End WAL insertion on the backup database libsql_wal_insert_end(db_backup); } ``` ### Key Points - Frame size is typically 4096 bytes plus 24 bytes for the frame header - Frames are 1-indexed (starting from frame 1) - The conflict parameter in libsql_wal_insert_frame detects insertion conflicts - Always pair libsql_wal_insert_begin with libsql_wal_insert_end ``` -------------------------------- ### Verify sqld Installation via Homebrew Source: https://github.com/tursodatabase/libsql/blob/main/docs/BUILD-RUN.md Check the installed `sqld` binary's functionality by displaying its help message. ```bash sqld --help ``` -------------------------------- ### Complete Lemon Parser Usage Example in C Source: https://github.com/tursodatabase/libsql/blob/main/libsql-sqlite3/doc/lemon.html This example demonstrates a full parsing workflow, including tokenizer creation, parser allocation, token processing, and parser deallocation, returning a parse tree. ```c ParseTree *ParseFile(const char *zFilename){ Tokenizer *pTokenizer; void *pParser; Token sToken; int hTokenId; ParserState sState; pTokenizer = TokenizerCreate(zFilename); pParser = ParseAlloc( malloc ); InitParserState(&sState); while( GetNextToken(pTokenizer, &hTokenId, &sToken) ){ Parse(pParser, hTokenId, sToken, &sState); } Parse(pParser, 0, sToken, &sState); ParseFree(pParser, free ); TokenizerFree(pTokenizer); return sState.treeRoot; } ``` -------------------------------- ### Install Library Target Source: https://github.com/tursodatabase/libsql/blob/main/libsql-ffi/bundled/SQLite3MultipleCiphers/CMakeLists.txt This command defines the installation rules for the library target, including destinations for archives, libraries, public headers, and runtimes. ```CMake INSTALL(TARGETS ${SQLITE3MC_TARGET} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib PUBLIC_HEADER DESTINATION include/${CMAKE_PROJECT_NAME} RUNTIME DESTINATION bin ) ``` -------------------------------- ### Launch libSQL Replica Instance with Docker Source: https://github.com/tursodatabase/libsql/blob/main/docs/DOCKER.md Start a replica libSQL server instance, linking it to a primary instance via SQLD_PRIMARY_URL and exposing port 8081. ```console docker run --name some-sqld-replica -p 8081:8080 -ti \ -e SQLD_NODE=replica \ -e SQLD_PRIMARY_URL=https://: \ ghcr.io/tursodatabase/libsql-server:latest ``` -------------------------------- ### Launch a Primary sqld Server with TLS Source: https://github.com/tursodatabase/libsql/blob/main/docs/USER_GUIDE.md Start a `sqld` instance configured as a primary server, listening for HTTP and gRPC connections with TLS enabled using generated certificates. ```console sqld \ --http-listen-addr 127.0.0.1:8081 \ --grpc-listen-addr 127.0.0.1:5001 \ --grpc-tls \ --grpc-ca-cert-file ca_cert.pem \ --grpc-cert-file server_cert.pem \ --grpc-key-file server_key.pem ``` -------------------------------- ### Launch a Replica sqld Server with TLS Source: https://github.com/tursodatabase/libsql/blob/main/docs/USER_GUIDE.md Start a `sqld` instance configured as a replica, connecting to a primary server via gRPC with TLS using client-specific certificates. ```console sqld \ --http-listen-addr 127.0.0.1:8082 \ --primary-grpc-url https://127.0.0.1:5001 \ --primary-grpc-tls \ --primary-grpc-ca-cert-file ca_cert.pem \ --primary-grpc-cert-file client_cert.pem \ --primary-grpc-key-file client_key.pem ``` -------------------------------- ### Initialize pgbench Database Schema Source: https://github.com/tursodatabase/libsql/blob/main/libsql-server/perf/pgbench/README.md Load the pgbench schema into a PostgreSQL database running on localhost. Execute this setup step before running performance tests. ```console psql -h 127.0.0.1 -p 5432 < pg_bench_schema.sql ``` -------------------------------- ### Start sqld with S3 Bottomless Replication Source: https://github.com/tursodatabase/libsql/blob/main/libsql-server/README.md Launch `sqld` with HTTP enabled and continuous replication to S3-compatible storage, requiring compilation with the `-F bottomless` flag. ```bash sqld --http-listen-addr=127.0.0.1:8000 --enable-bottomless-replication ``` -------------------------------- ### Launch libSQL Primary Instance with Docker Source: https://github.com/tursodatabase/libsql/blob/main/docs/DOCKER.md Use this command to start a primary libSQL server instance in a Docker container, exposing port 8080. ```console docker run --name some-sqld -p 8080:8080 -ti \ -e SQLD_NODE=primary \ ghcr.io/tursodatabase/libsql-server:latest ``` -------------------------------- ### Build and Run LibSQL WASM for Node.js Source: https://github.com/tursodatabase/libsql/blob/main/bindings/wasm/README.md Use `wasm-pack` to build the WebAssembly bindings for Node.js, then execute a JavaScript example. ```console wasm-pack build --target nodejs node example.js ``` -------------------------------- ### Example libSQL Fiddle Commands Source: https://github.com/tursodatabase/libsql/blob/main/libsql-sqlite3/ext/wasm/fiddle/index.html Illustrates basic sqlite3 shell commands and SQL statements for use within the libSQL Fiddle, including setting null value display and header output. ```sqlite3 -- ================================================== -- -- Use ctrl-enter or shift-enter to execute sqlite3 -- -- shell commands and SQL. -- -- If a subset of the text is currently selected, -- -- only that part is executed. -- -- ================================================== .nullvalue NULL .headers on ``` -------------------------------- ### sqld Log Output for Snapshot Generation Source: https://github.com/tursodatabase/libsql/blob/main/docs/USER_GUIDE.md This example shows the console output when `sqld` successfully creates an incremental snapshot and invokes the specified `snapshot.sh` script. ```console 2023-08-11T08:21:04.183564Z INFO sqld::replication::snapshot: snapshot `e126f594-90f4-45be-9350-bc8a01160de9-0-2.snap` successfully created Generated incremental snapshot data.sqld/dbs/default/snapshots/e126f594-90f4-45be-9350-bc8a01160de9-0-2.snap ``` -------------------------------- ### Write to Replica Server Source: https://github.com/tursodatabase/libsql/blob/main/docs/USER_GUIDE.md Example of performing a write operation (CREATE TABLE, INSERT) on a `sqld` replica server. The replica will delegate the write to the primary. ```console curl -d '{"statements": ["CREATE TABLE IF NOT EXISTS users (username)", "INSERT INTO users VALUES (\"alice\")"]}' 127.0.0.1:8082 ``` -------------------------------- ### libSQL Server Docker Compose Configuration Source: https://github.com/tursodatabase/libsql/blob/main/docs/DOCKER.md Example Docker Compose configuration for local development, setting up a libSQL server with port mappings and data persistence. ```yaml services: db: image: ghcr.io/tursodatabase/libsql-server:latest platform: linux/amd64 ports: - "8080:8080" - "5001:5001" # environment: # - SQLD_NODE=primary volumes: - ./data/libsql:/var/lib/sqld ``` -------------------------------- ### Web Worker Setup and Message Handling for SQLite3 Demo Source: https://github.com/tursodatabase/libsql/blob/main/libsql-sqlite3/ext/wasm/demo-123-worker.html Initializes a Web Worker for a SQLite3 demo, defines a logging utility, and sets up a message handler to display worker output in the HTML document. ```javascript (function(){ const logHtml = function(cssClass,...args){ const ln = document.createElement('div'); if(cssClass) ln.classList.add(cssClass); ln.append(document.createTextNode(args.join(' '))); document.body.append(ln); }; const w = new Worker("demo-123.js?sqlite3.dir=jswasm" /* Note the URL argument on that name. See the notes in demo-123.js (search for "importScripts") for why we need that. */); w.onmessage = function({data}){ switch(data.type){ case 'log': logHtml(data.payload.cssClass, ...data.payload.args); break; default: logHtml('error',"Unhandled message:",data.type); }; }; })(); ``` -------------------------------- ### Build and run sqld server Source: https://context7.com/tursodatabase/libsql/llms.txt Compile the sqld server binary and launch it with HTTP listening on localhost:8080. ```bash cargo build -p libsql-server ./target/debug/sqld --http-listen-addr 127.0.0.1:8080 ``` -------------------------------- ### Install cargo-afl Source: https://github.com/tursodatabase/libsql/blob/main/tools/fuzz/README.md Installs the `cargo-afl` tool, which is required for fuzz testing Rust projects. ```bash cargo install cargo-afl ``` -------------------------------- ### Install Bottomless CLI Source: https://github.com/tursodatabase/libsql/blob/main/bottomless/README.md Installs the 'bottomless-cli' as a standalone executable using Cargo. The 'RUSTFLAGS' are necessary for 'uuid_unstable' feature. ```sh RUSTFLAGS="--cfg uuid_unstable" cargo install bottomless-cli ``` -------------------------------- ### Build `libsql-sqlite3` and Run `bruteforce` Benchmark Source: https://github.com/tursodatabase/libsql/blob/main/libsql-sqlite3/benchmark/README.md Demonstrates how to build the `libsql-sqlite3` library to generate necessary `.libs` and then execute the `bruteforce` benchmark tool. ```sh $> basename $(pwd) libsql-sqlite3 $> make # this command will generate libs in the .libs directory $> cd benchmark $> make bruteforce open queries file at bruteforce.sql open sqlite db at 'test.db' executed simple statement: 'PRAGMA journal_mode=WAL;' executed simple statement: 'CREATE TABLE x ( id INTEGER PRIMARY KEY, embedding FLOAT32(64) );' prepared statement: 'INSERT INTO x VALUES (?, vector(?));' inserts (bruteforce.sql): insert: 46.27 micros (avg.), 1000 (count) size : 0.2695 MB reads : 1.00 (avg.), 1000 (total) writes: 1.00 (avg.), 1000 (total) prepared statement: 'SELECT id FROM x ORDER BY vector_distance_cos(embedding, vector(?)) LIMIT ?;' search (bruteforce.sql): select: 329.32 micros (avg.), 1000 (count) size : 0.2695 MB reads : 2000.00 (avg.), 2000000 (total) ``` -------------------------------- ### Set grammar start symbol with %start_symbol Source: https://github.com/tursodatabase/libsql/blob/main/libsql-sqlite3/doc/lemon.html Override the default start symbol (first non-terminal in grammar file) with a different non-terminal. ```lemon %start_symbol prog ``` -------------------------------- ### Deploying sqld to Fly.io Source: https://github.com/tursodatabase/libsql/blob/main/docs/USER_GUIDE.md Use this command to initialize and deploy a new `sqld` application on Fly.io, leveraging an existing `fly.toml` configuration. ```console flyctl launch ``` -------------------------------- ### Configure Bottomless environment variables Source: https://context7.com/tursodatabase/libsql/llms.txt Set up storage endpoint, bucket, and AWS credentials for Bottomless S3-backed WAL replication. ```bash export LIBSQL_BOTTOMLESS_ENDPOINT='http://localhost:9000' export LIBSQL_BOTTOMLESS_BUCKET='my-db-backups' export AWS_ACCESS_KEY_ID='minioadmin' export AWS_SECRET_ACCESS_KEY='minioadmin' ``` -------------------------------- ### Install SQLite3MC Shell Executable with CMake Source: https://github.com/tursodatabase/libsql/blob/main/libsql-ffi/bundled/SQLite3MultipleCiphers/CMakeLists.txt Installs the compiled shell executable to the bin directory and archive/library files to their respective destinations. Use this to deploy the built shell target. ```cmake INSTALL(TARGETS ${SQLITE3MC_SHELL_TARGET} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib PUBLIC_HEADER DESTINATION include/${CMAKE_PROJECT_NAME} RUNTIME DESTINATION bin ) ``` -------------------------------- ### Detailed Steps for 'mdevtest' Execution Source: https://github.com/tursodatabase/libsql/blob/main/libsql-sqlite3/doc/testrunner.md Illustrates the sequence of commands that the 'mdevtest' command effectively executes, involving configure, make, and testfixture for different build configurations. ```bash $TOP/configure --enable-all --enable-debug make fuzztest make testfixture ./testfixture $TOP/test/testrunner.tcl veryquick # Then, after removing files created by the tests above: $TOP/configure --enable-all OPTS="-O0" make fuzztest make testfixture ./testfixture $TOP/test/testrunner.tcl veryquick ``` -------------------------------- ### Check `sqld` Health and Version via HTTP API Source: https://context7.com/tursodatabase/libsql/llms.txt Use the `GET /health` endpoint for readiness checks and `GET /version` to retrieve the `sqld` server version string. These are useful for load balancers and monitoring. ```bash # Health check — returns HTTP 200 if server is up curl -s -o /dev/null -w "%{\nhttp_code}" http://127.0.0.1:8080/health ``` ```bash # Version endpoint — returns server version string curl -s http://127.0.0.1:8080/version ``` -------------------------------- ### GET /version Source: https://github.com/tursodatabase/libsql/blob/main/docs/http_api.md Returns the server's version. ```APIDOC ## GET /version ### Description Returns the server's version. ### Method GET ### Endpoint /version ### Response #### Success Response (200) Returns the server's version. The exact format of the response body is not specified, but it typically contains a version string. ``` -------------------------------- ### Embedded hex database example with SQLite CLI Source: https://github.com/tursodatabase/libsql/blob/main/libsql-sqlite3/tool/dbtotxt.md Complete example showing how to embed a hex-formatted database directly in a script. The database definition includes page headers, table schema, and data, followed by SQL queries to verify the loaded database. ```sql .open --hexdb | size 8192 pagesize 4096 filename x9.db | page 1 offset 0 | 0: 53 51 4c 69 74 65 20 66 6f 72 6d 61 74 20 33 00 SQLite format 3. | 16: 10 00 01 01 00 40 20 20 00 00 00 04 00 00 00 02 .....@ ........ | 32: 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 04 ................ | 48: 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 ................ | 80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 04 ................ | 96: 00 2e 30 38 0d 00 00 00 01 0f c0 00 0f c0 00 00 ..08............ | 4032: 3e 01 06 17 11 11 01 69 74 61 62 6c 65 74 31 74 >......itablet1t | 4048: 31 02 43 52 45 41 54 45 20 54 41 42 4c 45 20 74 1.CREATE TABLE t | 4064: 31 28 78 2c 79 20 44 45 46 41 55 4c 54 20 78 27 1(x,y DEFAULT x' | 4080: 66 66 27 2c 7a 20 44 45 46 41 55 4c 54 20 30 29 ff',z DEFAULT 0) | page 2 offset 4096 | 0: 0d 08 14 00 04 00 10 00 0e 05 0a 0f 04 15 00 10 ................ | 16: 88 02 03 05 90 04 0e 08 00 00 00 00 00 00 00 00 ................ | 1040: 00 00 00 00 ff 87 7c 02 05 8f 78 0e 08 00 00 00 ......|...x..... | 2064: 00 00 00 ff 0c 0a 01 fb 00 00 00 00 00 00 00 00 ................ | 2560: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 83 ................ | 2576: 78 01 05 87 70 0e 08 00 00 00 00 00 00 00 00 00 x...p........... | 3072: 00 00 00 00 00 00 00 00 00 ff 00 00 01 fb 00 00 ................ | 3584: 00 00 00 00 00 83 78 00 05 87 70 0e 08 00 00 00 ......x...p..... | 4080: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ff ................ | end x9.db SELECT rowid FROM t1; PRAGMA integrity_check; ``` -------------------------------- ### Initialize Preselected Flags and URL Parameters Source: https://github.com/tursodatabase/libsql/blob/main/libsql-sqlite3/ext/wasm/speedtest1-worker.html Sets up default preselected flags and processes URL parameters to configure the benchmark. Automatically adds --memdb flag if no VFS is specified via URL parameters. ```JavaScript const preselectedFlags = [ '--big-transactions', '--singlethread' ]; if(urlParams.has('flags')){ preselectedFlags.push(...urlParams.get('flags').split(',')); } if(!urlParams.get('vfs')){ preselectedFlags.push('--memdb'); } ``` -------------------------------- ### GET /health Source: https://github.com/tursodatabase/libsql/blob/main/docs/http_api.md The health route returns an HTTP 200 (OK) if the server is up and running. ```APIDOC ## GET /health ### Description The health route returns an HTTP 200 (OK) if the server is up and running. ### Method GET ### Endpoint /health ### Response #### Success Response (200) Returns an HTTP 200 OK status code if the server is healthy. No specific body content is defined. ``` -------------------------------- ### HTTP GET Version Route Source: https://github.com/tursodatabase/libsql/blob/main/docs/http_api.md Endpoint to retrieve the server's current version information. ```HTTP GET /version ``` -------------------------------- ### Launch libsql interactive shell Source: https://context7.com/tursodatabase/libsql/llms.txt Start the interactive libsql shell for executing SQL queries directly. ```bash cd libsql-sqlite3 && ./libsql ``` -------------------------------- ### Clone and build libsql from source Source: https://context7.com/tursodatabase/libsql/llms.txt Clone the libsql repository and build the SQLite-compatible C library and shell. ```bash git clone https://github.com/tursodatabase/libsql.git cd libsql cargo xtask build ``` -------------------------------- ### HTTP GET Health Check Route Source: https://github.com/tursodatabase/libsql/blob/main/docs/http_api.md Endpoint to check if the server is operational, returning HTTP 200 on success. ```HTTP GET /health ``` -------------------------------- ### Run `benchtest` with SQL Queries Source: https://github.com/tursodatabase/libsql/blob/main/libsql-sqlite3/benchmark/README.md Execute `benchtest` to run SQL queries from a file against a specified database, demonstrating basic insert and search operations with performance metrics. ```sh $> LD_LIBRARY_PATH=../.libs/ ./benchtest queries.sql data.db open queries file at queries.sql open sqlite db at 'data.db' executed simple statement: 'CREATE TABLE t ( id INTEGER PRIMARY KEY, emb FLOAT32(4) );' executed simple statement: 'CREATE INDEX t_idx ON t ( libsql_vector_idx(emb) );' prepared statement: 'INSERT INTO t VALUES ( ?, vector(?) );' inserts (queries.sql): insert: 710.25 micros (avg.), 4 (count) size : 0.2695 MB reads : 1.00 (avg.), 4 (total) writes: 1.00 (avg.), 4 (total) prepared statement: 'SELECT * FROM vector_top_k('t_idx', vector(?), ?);' search (queries.sql): select: 63.25 micros (avg.), 4 (count) size : 0.2695 MB reads : 1.00 (avg.), 4 (total) writes: 1.00 (avg.), 4 (total) ``` -------------------------------- ### Set Target Public Header Properties Source: https://github.com/tursodatabase/libsql/blob/main/libsql-ffi/bundled/SQLite3MultipleCiphers/CMakeLists.txt This command sets the PUBLIC_HEADER property for the library target, specifying which headers should be installed. ```CMake set_target_properties(${SQLITE3MC_TARGET} PROPERTIES PUBLIC_HEADER "${SQLITE3MC_PUBLIC_HEADERS}") ``` -------------------------------- ### Set up libSQL static library environment variable Source: https://github.com/tursodatabase/libsql/blob/main/libsql/DEVELOPING.md Configure the LIBSQL_STATIC_LIB_DIR environment variable to point to the compiled static libraries directory before building. ```sh export LIBSQL_STATIC_LIB_DIR=$(pwd)/../../.libs ``` -------------------------------- ### libsql_wal_insert_end Source: https://github.com/tursodatabase/libsql/blob/main/libsql-sqlite3/doc/libsql_extensions.md Ends a WAL insertion transaction. This function must be called after all frames have been inserted to complete the transaction started by libsql_wal_insert_begin. ```APIDOC ## libsql_wal_insert_end ### Description Ends a WAL insertion transaction. This function must be called after all frames have been inserted to complete the transaction started by libsql_wal_insert_begin. ### Function Signature ```c int libsql_wal_insert_end(sqlite3 *db) ``` ### Parameters - **db** (sqlite3*) - Required - Pointer to the SQLite database connection ### Return Value - **int** - SQLITE_OK on success, or an appropriate SQLite error code ``` -------------------------------- ### JSON Query with Positional Parameters Source: https://github.com/tursodatabase/libsql/blob/main/docs/http_api.md Example of a query using positional parameters, where values are provided as an array in the `params` field. ```json { "q": "SELECT * FROM users WHERE name = ?", "params": ["adhoc"] } ``` -------------------------------- ### JSON Query with Named Parameters Source: https://github.com/tursodatabase/libsql/blob/main/docs/http_api.md Example of a query using named parameters, where parameters are mapped by name in the `params` object. ```json { "q": "SELECT * FROM users WHERE name = :name AND age = &age AND height > @height AND address = $address", "params": { ":name": "adhoc", "age" : "18", "@height" : "170", "$address" : "very nice place" } } ``` -------------------------------- ### Basic libSQL Shell Interaction Source: https://github.com/tursodatabase/libsql/blob/main/libsql-shell/README.md This snippet demonstrates how to start the libSQL shell and perform basic SQL operations, including creating a table, inserting various data types (integer, blob, float, string, null), and querying the data with functions like `length()` and `hex()`. ```console $ ./libsql libSQL version 0.2.0 Connected to a transient in-memory database. libsql> create table test(id, v); libsql> insert into test values(42, zeroblob(12)); libsql> insert into test values(3.14, 'hello'); libsql> insert into test values(null, null); libsql> select id, v, length(v), hex(v) from test; id | v | length(v) | hex(v) ------+--------------------+-----------+-------------------------- 42 | 0xAAAAAAAAAAAAAAAA | 12 | 000000000000000000000000 3.14 | hello | 5 | 68656C6C6F null | null | null | libsql> ``` -------------------------------- ### Run 'full' Test Suite Source: https://github.com/tursodatabase/libsql/blob/main/libsql-sqlite3/doc/testrunner.md Execute the complete 'full' test suite using the testfixture. ```bash ./testfixture $TESTDIR/testrunner.tcl full ``` -------------------------------- ### Define Trusted SQLite Extensions Source: https://github.com/tursodatabase/libsql/blob/main/libsql-server/README.md Example `trusted.lst` file specifying SHA256 checksums for SQLite extensions to be preloaded by `sqld`. ```console cat trusted.lst 04cd193d2547ff99d672fbfc6dcd7e0b220869a1ab867a9bb325f7374d168533 vector0.so 74f9029cbf6e31b155c097a273e08517eb4e56f2300dede65c801407b01eb248 vss0.so 5bbbe0f80dd7721162157f852bd5f364348eb504f9799ae521f832d44c13a3a1 crypto.so 731a8cbe150351fed02944a00ca586fc60d8f3814e4f83efbe60fcef62d4332b fuzzy.so 1dbe9e4e58c4b994a119f1b507d07eb7a4311a80b96482c979b3bc0defd485fb math.so 511bf71b0621977bd9575d71e90adf6d02967008e460066a33aed8720957fecb stats.so ae7fff8412e4e66e7f22b9af620bd24074bc9c77da6746221a9aba9d2b38d6a6 text.so 9ed6e7f4738c2223e194c7a80525d87f323df269c04d155a769d733e0ab3b4d0 unicode.so 19106ded4fd3fd4986a5111433d062a73bcf9557e07fa6d9154e088523e02bb0 uuid.so ``` -------------------------------- ### Build SQLite3 WASM (from ext/wasm) Source: https://github.com/tursodatabase/libsql/blob/main/libsql-sqlite3/ext/wasm/README.md Build the SQLite3 WebAssembly components by navigating to the `ext/wasm` directory and running `make`. This is an alternative build method to `make fiddle`. ```bash $ cd ext/wasm $ make ``` -------------------------------- ### Update Emscripten SDK Source: https://github.com/tursodatabase/libsql/blob/main/libsql-sqlite3/ext/wasm/README.md Update an existing Emscripten SDK installation by pulling the latest changes from the repository and reactivating the SDK tools. ```bash $ git pull $ ./emsdk install latest $ ./emsdk activate latest ``` -------------------------------- ### Build sqld Docker Image from Source Source: https://github.com/tursodatabase/libsql/blob/main/docs/BUILD-RUN.md Build a Docker image for `sqld` from the cloned repository, tagging it as `libsql/sqld:latest`. ```bash docker build -t libsql/sqld:latest . ``` -------------------------------- ### Example JSON Response from sqld Query Source: https://github.com/tursodatabase/libsql/blob/main/docs/USER_GUIDE.md This JSON output represents the expected response from the `SELECT` statement executed against the `sqld` database. ```json [{ "b": 2, "a": 1, "c": 3 }] ``` -------------------------------- ### GET v3-protobuf Source: https://github.com/tursodatabase/libsql/blob/main/docs/HRANA_3_SPEC.md Checks if the server supports version 3 of Hrana over HTTP with Protobuf encoding. A 2xx response indicates support. ```APIDOC ## GET v3-protobuf ### Description Checks if the server supports version 3 of Hrana over HTTP with Protobuf encoding. A 2xx response indicates support. ### Method GET ### Endpoint v3-protobuf ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Request Example (None) ### Response #### Success Response (2xx) The server returns a 2xx status code if version 3 with Protobuf encoding is supported. No specific response body is defined. #### Response Example (None) ``` -------------------------------- ### Build Bottomless libSQL Extension (Release) Source: https://github.com/tursodatabase/libsql/blob/main/bottomless/README.md Builds the Bottomless libSQL extension in release mode. Replace '/path/to/your/libsql/directory' with the actual path to your libSQL source. ```shell LIBSQL_DIR=/path/to/your/libsql/directory make release ``` -------------------------------- ### GET v3 Source: https://github.com/tursodatabase/libsql/blob/main/docs/HRANA_3_SPEC.md Checks if the server supports version 3 of Hrana over HTTP with JSON encoding. A 2xx response indicates support. ```APIDOC ## GET v3 ### Description Checks if the server supports version 3 of Hrana over HTTP with JSON encoding. A 2xx response indicates support. ### Method GET ### Endpoint v3 ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Request Example (None) ### Response #### Success Response (2xx) The server returns a 2xx status code if version 3 with JSON encoding is supported. No specific response body is defined. #### Response Example (None) ``` -------------------------------- ### Use Prepared Statements for Efficient SQL in LibSQL Rust Source: https://context7.com/tursodatabase/libsql/llms.txt Illustrates how to pre-compile SQL statements using `prepare` for reuse, improving performance for frequently executed queries. Shows both `execute` and `query` on prepared statements. ```rust use libsql::Builder; #[tokio::main] async fn main() -> Result<(), Box> { let db = Builder::new_local(":memory:").build().await?; let conn = db.connect()?; conn.execute("CREATE TABLE kv (key TEXT PRIMARY KEY, value TEXT)", ()).await?; let insert = conn.prepare("INSERT OR REPLACE INTO kv VALUES (?1, ?2)").await?; for (k, v) in [("color", "blue"), ("size", "medium"), ("weight", "light")] { insert.execute([k, v]).await?; } let select = conn.prepare("SELECT value FROM kv WHERE key = ?1").await?; let mut rows = select.query(["color"]).await?; if let Some(row) = rows.next().await? { println!("color = {}", row.get::(0)?); } // Output: color = blue Ok(()) } ``` -------------------------------- ### Checking testrunner.tcl status Source: https://github.com/tursodatabase/libsql/blob/main/libsql-sqlite3/doc/testrunner.md Run this command in the directory containing 'testrunner.db' to get a succinct report on the state of a running 'testrunner.tcl' script. ```bash ./testfixture $(TESTDIR)/testrunner.tcl status ``` -------------------------------- ### Set TCL directory environment variable Source: https://github.com/tursodatabase/libsql/blob/main/libsql-sqlite3/doc/compile-for-windows.md Set the TCLDIR environment variable to point to the TCL installation directory before running the SQLite makefile. ```cmd set TCLDIR=c:\Tcl ``` -------------------------------- ### Run 'all' Tests (Full + Permutations) Source: https://github.com/tursodatabase/libsql/blob/main/libsql-sqlite3/doc/testrunner.md Execute all available tests, including the full suite and various permutations. ```bash ./testfixture $TESTDIR/testrunner.tcl all ``` -------------------------------- ### Read from Primary Server Source: https://github.com/tursodatabase/libsql/blob/main/docs/USER_GUIDE.md Example of performing a read operation (SELECT) on a `sqld` primary server to verify data written via a replica. ```console curl -d '{"statements": ["SELECT * FROM users"]}' 127.0.0.1:8081 ``` -------------------------------- ### Run sqld from Rust Source Build Source: https://github.com/tursodatabase/libsql/blob/main/docs/BUILD-RUN.md Launch the `sqld` server directly from the compiled binary, using default settings for data persistence and client connections. ```bash ./target/debug/sqld ``` -------------------------------- ### GET /health - Health Check Source: https://context7.com/tursodatabase/libsql/llms.txt Health probe endpoint for load balancers and readiness checks. Returns HTTP 200 if the server is operational. ```APIDOC ## GET /health ### Description Health probe endpoint for load balancers and readiness checks. Returns HTTP 200 if the server is operational. ### Method GET ### Endpoint /health ### Response #### Success Response (200) Server is healthy and operational. #### Response Example ``` 200 OK ``` ``` -------------------------------- ### Run libSQL Rust benchmarks Source: https://github.com/tursodatabase/libsql/blob/main/libsql/DEVELOPING.md Execute the benchmark suite to measure performance. ```sh cargo bench ```