### Setup and usage snippets: install, headers, Vite config, basic query, Worker with IndexedDB Source: https://oliphaunt.dev/docs/sdk/wasix-typescript This group contains the essential setup snippets for the WASIX TypeScript SDK. It includes the npm install command, the required HTTP response headers for browser isolation, a Vite configuration that excludes the SDK packages from prebundling and sets the required headers, a basic query example using the root import, and a Worker-based example using IndexedDB for persistent storage. The snippets are presented together as the steps to prepare the environment and run the first query. ```bash npm install @oliphaunt/wasix-ts ``` ```http Cross-Origin-Opener-Policy: same-origin Cross-Origin-Embedder-Policy: require-corp ``` ```typescript import { defineConfig } from 'vite'; export default defineConfig({ optimizeDeps: { exclude: ['@oliphaunt/wasix-ts', '@oliphaunt/liboliphaunt-wasix'], }, worker: { format: 'es' }, server: { headers: { 'Cross-Origin-Opener-Policy': 'same-origin', 'Cross-Origin-Embedder-Policy': 'require-corp', }, }, }); ``` ```typescript import Oliphaunt from '@oliphaunt/wasix-ts'; const db = await Oliphaunt.open(); try { const result = await db.query('SELECT $1::int4 AS answer', [42]); console.log(result.rows[0]?.answer); // 42 } finally { await db.close(); } ``` ```typescript import OliphauntWorker from '@oliphaunt/wasix-ts/worker'; import { indexedDB } from '@oliphaunt/wasix-ts/storage/indexed-db'; const db = await OliphauntWorker.open({ storage: indexedDB('notes') }); ``` -------------------------------- ### Install @oliphaunt/ts with Bun Source: https://oliphaunt.dev/docs/sdk/typescript Install the package using Bun's package manager. ```bash bun add @oliphaunt/ts ``` -------------------------------- ### Start OliphauntServer with DatabaseStorage Source: https://oliphaunt.dev/docs/sdk/wasix-rust/runtime Builds and starts an OliphauntServer using directory-based storage, prints the connection string, and closes the server. The endpoint serves one connected client at a time; close the client before closing the server. ```rust use oliphaunt_pgwire_server::{DatabaseStorage, OliphauntServer}; let mut server = OliphauntServer::builder() .storage(DatabaseStorage::Directory("./data/server".into())) .start()?; println!("{}", server.connection_string()); // Connect one client. Close it before closing the server. server.close()?; ``` -------------------------------- ### Install CLI and dump to file Source: https://oliphaunt.dev/docs/sdk/wasix-rust/dump-restore Installs the CLI with the tools feature and runs oliphaunt-wasix-dump to write a SQL dump to a file. Close other owners of the root first. Use --database and --username only for identities already present in the database. ```bash cargo install oliphaunt-wasix --features tools oliphaunt-wasix-dump --directory ./data/notes > notes.sql ``` -------------------------------- ### Start AsyncOliphauntServer for PostgreSQL driver or ORM Source: https://oliphaunt.dev/docs/learn/tauri Start an AsyncOliphauntServer to provide a connection URL for independent sessions. Retain the server handle, not just its URL. ```rust use oliphaunt::AsyncOliphauntServer; async fn start_server(app_data: PathBuf) -> oliphaunt::Result { AsyncOliphauntServer::builder() .storage(DatabaseStorage::Directory(app_data.join("postgres"))) .start() .await } ``` -------------------------------- ### Start a server for ORM or connection pool Source: https://oliphaunt.dev/docs/sdk/rust/guide Starts a server and returns a handle that must be kept alive. The server lifecycle handle does not run SQL itself. Close clients before closing server. Use `AsyncOliphauntServer` for async server ownership. ```rust use oliphaunt::OliphauntServer; let mut server = OliphauntServer::builder() .storage(DatabaseStorage::Directory("./app-data/server.oliphaunt".into())) .start()?; println!("{}", server.connection_string()); // Connect a PostgreSQL driver here. Close clients before closing server. server.close()?; ``` -------------------------------- ### Install @oliphaunt/wasix-tools Source: https://oliphaunt.dev/docs/sdk/wasix-typescript/guide Install the optional tools package for logical PostgreSQL operations. ```bash npm install @oliphaunt/wasix-tools ``` -------------------------------- ### Install and use pgtap extension Source: https://oliphaunt.dev/docs/sdk/wasix-typescript/guide Install the @oliphaunt/extension-pgtap-wasix package and pass its descriptor to Oliphaunt.open. The SDK does not run application migrations or CREATE EXTENSION automatically; include the selected extension packages when deploying. ```bash npm install @oliphaunt/extension-pgtap-wasix ``` -------------------------------- ### Install @oliphaunt/ts with npm Source: https://oliphaunt.dev/docs/sdk/typescript Install the package for Node.js or other npm-compatible runtimes. Supports Node.js 22.13 through 24.x. ```bash npm install @oliphaunt/ts ``` -------------------------------- ### Open database in broker mode Source: https://oliphaunt.dev/docs/sdk/rust/guide Starts a database in broker mode, moving the database into a helper process. Direct mode runs in your process. ```rust let mut db = Oliphaunt::builder() .storage(DatabaseStorage::Directory("./app-data/main.oliphaunt".into())) .broker() .open()?; ``` -------------------------------- ### Run first query with synchronous Oliphaunt Source: https://oliphaunt.dev/docs/sdk/rust Creates src/main.rs with a complete synchronous example. Opens the default database, runs a query with a bound parameter, retrieves the result, and prints the answer. The default database uses disposable temporary storage; choose a persistent directory before saving application data. Run with cargo run. ```rust use oliphaunt::Oliphaunt; fn main() -> Result<(), Box> { let mut db = Oliphaunt::open()?; let result = db.sql("SELECT $1::int4 AS answer").bind(42_i32).query()?; let answer: i32 = result.rows()[0].try_get("answer")?; println!("{answer}"); // 42 db.close()?; Ok(()) } ``` -------------------------------- ### Prepare a managed root with Rust SDK Source: https://oliphaunt.dev/docs/sdk/c-abi/guide Run this separate Rust program using the Rust SDK to create persistent storage before calling oliphaunt_init. After the process exits, pass ./data/example/pgdata to the C example; the surrounding root also contains .oliphaunt.json which must be retained. ```rust use oliphaunt::{DatabaseStorage, Oliphaunt}; fn main() -> oliphaunt::Result<()> { let mut db = Oliphaunt::builder() .storage(DatabaseStorage::Directory("./data/example".into())) .direct() .open()?; db.close() } ``` -------------------------------- ### Install @oliphaunt/react-native and seed package Source: https://oliphaunt.dev/docs/sdk/react-native Install the React Native package and the iOS seed package. The seed package provides the initial empty database for iOS; the plugin selects matching initialization resources on Android. ```bash npm install @oliphaunt/react-native @oliphaunt/seed-native-ios-datum64-standard ``` -------------------------------- ### Export and import SQL with pg_dump and psql Source: https://oliphaunt.dev/docs/sdk/wasix-rust/dump-restore Complete example that exports a database using pg_dump and restores it into another in-memory database using psql. pg_dump returns UTF-8 SQL that may contain COPY data and psql commands, so it must be passed to psql, not execute. Tools reset session state and cannot run inside a callback transaction. ```rust use oliphaunt_wasix::{Oliphaunt, tools}; fn main() -> Result<(), Box> { let mut source = Oliphaunt::open()?; source.execute("CREATE TABLE notes (body text NOT NULL)")?; source.execute("INSERT INTO notes VALUES ('First note')")?; let sql = source.pg_dump(tools::PgDumpOptions::new())?; source.close()?; let mut target = Oliphaunt::open()?; target.psql(tools::PsqlOptions::new().script(sql))?; let rows = target.query("SELECT body FROM notes")?; let body: String = rows.rows()[0].try_get("body")?; assert_eq!(body, "First note"); target.close()?; Ok(()) } ``` -------------------------------- ### Open persistent storage with applicationData Source: https://oliphaunt.dev/docs/sdk/react-native Use this storage configuration instead of the disposable example. Direct mode stays bound to its first root for the lifetime of the process; closing does not let the same process switch roots. Let the platform SDK choose an app-private directory by name. ```typescript const db = await Oliphaunt.open({ storage: { kind: 'applicationData', name: 'main' }, }); ``` -------------------------------- ### Persist data with Directory storage Source: https://oliphaunt.dev/docs/sdk/kotlin Use this storage configuration instead of the disposable example. Direct mode stays bound to its first root for the lifetime of the process; closing does not let the same process switch roots. Directory accepts java.io.File, not a path string. ```kotlin val db = Oliphaunt.open( context = context.applicationContext, config = OliphauntConfig( storage = DatabaseStorage.Directory(context.filesDir.resolve("main.oliphaunt")), ), ) ``` -------------------------------- ### Open and query with liboliphaunt in C (example.c) Source: https://oliphaunt.dev/docs/sdk/c-abi Save as example.c. The argument is the pgdata path inside your prepared root. runtime_dir and module_dir use release-layout discovery unless you set explicit paths. The response is binary protocol data, not a string or decoded row; parse backend messages to read the result and detect PostgreSQL ErrorResponse messages. ```c #include #include #include int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "Usage: %s /path/to/root/pgdata\n", argv[0]); return 2; } OliphauntHandle *handle = NULL; OliphauntErrorCapture error = {0}; OliphauntConfig config = { .abi_version = OLIPHAUNT_ABI_VERSION, .pgdata = argv[1], .username = "postgres", .database = "postgres", }; if (oliphaunt_init_with_error(&config, &handle, &error) != 0) { fprintf(stderr, "%s\n", error.message); return 1; } OliphauntResponse response = {0}; const char *sql = "SELECT 42::int4 AS answer"; int32_t status = oliphaunt_exec_simple_query_with_error( handle, sql, strlen(sql), &response, &error); if (status != 0) fprintf(stderr, "%s\n", error.message); else printf("Received %zu PostgreSQL protocol bytes\n", response.len); oliphaunt_free_response(&response); int32_t closed = oliphaunt_close(handle); return status != 0 || closed != 0; } ``` -------------------------------- ### Install native extension package Source: https://oliphaunt.dev/docs/sdk/react-native/architecture Install the native extension packages your app uses before plugin or manual setup. The Expo plugin discovers installed extension packages. ```bash npm install @oliphaunt/extension-vector ``` -------------------------------- ### Run first query with @oliphaunt/ts Source: https://oliphaunt.dev/docs/sdk/typescript Opens a database, runs a parameterized query, prints the result, and closes the database. Save as main.mjs for Node/Bun or main.ts for Deno. ```javascript import { Oliphaunt } from '@oliphaunt/ts'; const db = await Oliphaunt.open(); try { const result = await db.query('SELECT $1::int4 AS answer', [42]); console.log(result.rows[0]?.answer); // 42 } finally { await db.close(); } ``` -------------------------------- ### Oliphaunt.open(config?) Source: https://oliphaunt.dev/docs/sdk/react-native/api-reference Opens a database and returns a promise resolving to an OliphauntDatabase instance. Configuration accepts storage, startupGUCs, username, database, extensions, and broker options. ```APIDOC ## Oliphaunt.open(config?) ### Description Opens a database and returns a promise resolving to an OliphauntDatabase instance. ### Method open ### Parameters #### Config - **storage** (object) - Optional - Storage configuration. Values: `{ kind: 'temporaryDirectory' }` (default, disposable), `{ kind: 'directory', path: string }` (persistent explicit path), `{ kind: 'applicationData', name: string }` (persistent platform-resolved app-data path). - **startupGUCs** (object) - Optional - Startup configuration parameters. - **username** (string) - Optional - Username for authentication. - **database** (string) - Optional - Database name. - **extensions** (NativeExtension[]) - Optional - Typed native extension descriptors. - **broker** (object) - Optional - Timeouts for a broker build. Fields: `startupTimeoutMs` (positive integer), `operationTimeoutMs` (positive integer). ### Returns Promise ### Example ```typescript const db = await Oliphaunt.open({ storage: { kind: 'temporaryDirectory' } }); ``` ``` -------------------------------- ### Install oliphaunt-wasix with cargo add Source: https://oliphaunt.dev/docs/sdk/wasix-rust Adds the oliphaunt-wasix crate as a dependency. Requires Rust 1.93 or later. ```bash cargo add oliphaunt-wasix ``` -------------------------------- ### OliphauntBroker.open(context, config, options) Source: https://oliphaunt.dev/docs/sdk/kotlin/api-reference Returns the same database interface from a separate process. Use application-data names for persistent broker storage. ```APIDOC ## OliphauntBroker.open(context, config, options) ### Description Returns the same database interface from a separate process. Use application-data names for persistent broker storage. ### Method Suspend function ### Parameters - **context** (Context) - Required - Android context. - **config** (OliphauntConfig) - Optional - Configuration object. - **options** (BrokerOptions) - Optional - Broker-specific options. ``` -------------------------------- ### Install Oliphaunt plugin and library in app/build.gradle.kts Source: https://oliphaunt.dev/docs/sdk/kotlin Add the Oliphaunt plugin and library dependency. Replace with your selected Kotlin SDK version. Requires mavenCentral() in settings.gradle.kts. ```kotlin plugins { id("com.android.application") id("dev.oliphaunt.android") version "" } dependencies { implementation("dev.oliphaunt:oliphaunt-android:") } ``` -------------------------------- ### Create a notes table with identity column and timestamp Source: https://oliphaunt.dev/docs/learn/sqlite-upgrade SQL to create a PostgreSQL table with an identity column for generated IDs and a timestamptz column for creation time. Use this as a starting point when porting a small schema. ```sql CREATE TABLE notes ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, body text NOT NULL, created_at timestamptz NOT NULL DEFAULT now() ); ``` -------------------------------- ### Run first query with Oliphaunt::open Source: https://oliphaunt.dev/docs/sdk/wasix-rust Complete src/main.rs that opens an in-memory database, runs a parameterized query, and prints the result. The default database uses a memory filesystem and is discarded on close. ```rust use oliphaunt_wasix::Oliphaunt; fn main() -> Result<(), Box> { let mut db = Oliphaunt::open()?; let result = db.sql("SELECT $1::int4 AS answer").bind(42_i32).query()?; let answer: i32 = result.rows()[0].try_get("answer")?; println!("{answer}"); // 42 db.close()?; Ok(()) } ``` -------------------------------- ### Backup and restore database Source: https://oliphaunt.dev/docs/sdk/rust/guide Creates a native backup, closes the database, restores into a new or empty root, and reopens in broker mode. The restored handle uses broker mode because direct mode remains bound to its original root for the lifetime of the process. Reapply required extension selections when opening restored data. ```rust let archive = db.backup()?; db.close()?; Oliphaunt::restore("./app-data/restored.oliphaunt", &archive)?; let mut restored = Oliphaunt::builder() .storage(DatabaseStorage::Directory("./app-data/restored.oliphaunt".into())) .broker() .open()?; restored.close()?; ``` -------------------------------- ### Add oliphaunt with cargo add Source: https://oliphaunt.dev/docs/sdk/rust Adds the oliphaunt crate to Cargo.toml. Requires Rust 1.93 or later. The crate includes the matching native runtime for supported desktop targets, so no environment variables or separate runtime download are needed for the default setup. ```bash cargo add oliphaunt ``` -------------------------------- ### Oliphaunt.open(context, config, runtimeDirectory, resourceRoot) Source: https://oliphaunt.dev/docs/sdk/kotlin/api-reference Suspends and returns an OliphauntDatabase. Only context is required; resource overrides are optional File values. ```APIDOC ## Oliphaunt.open(context, config, runtimeDirectory, resourceRoot) ### Description Suspends and returns an OliphauntDatabase. Only context is required; resource overrides are optional File values. ### Method Suspend function ### Parameters - **context** (Context) - Required - Android context. - **config** (OliphauntConfig) - Optional - Configuration object. - **runtimeDirectory** (File?) - Optional - Runtime directory override. - **resourceRoot** (File?) - Optional - Resource root override. ### Returns OliphauntDatabase ``` -------------------------------- ### Generate Swift extension package with Bun Source: https://oliphaunt.dev/docs/sdk/swift/guide Install Bun, then obtain the Swift extension generator from the Oliphaunt source package matching your Swift dependency. Download the matching `vector` Swift extension carrier JSON from its release. The output directory must not already exist. ```bash bun /path/to/oliphaunt/src/native/sdks/swift/tools/render-extension-products.mts \ --extension-carrier /path/to/vector-swift-extension-carrier.json \ --extensions vector \ --output-dir ./OliphauntExtensions ``` -------------------------------- ### Add an extension Source: https://oliphaunt.dev/docs/sdk/react-native/guide Steps to add an extension: install the package, configure the Expo plugin, rebuild, and open the database with the extension descriptor. The plugin packages selected extension resources and dependencies. Extension changes require a native rebuild; a JavaScript update alone cannot add them. ```bash ```bash npm install @oliphaunt/extension-vector ``` ``` ```json ```json { "expo": { "plugins": [["@oliphaunt/react-native", { "extensions": ["vector"] }]] } } ``` ``` ```javascript ```javascript import vector from '@oliphaunt/extension-vector'; const db = await Oliphaunt.open({ storage: { kind: 'applicationData', name: 'main' }, extensions: [vector], }); await db.execute('CREATE EXTENSION IF NOT EXISTS vector'); ``` ``` -------------------------------- ### Backup and restore database Source: https://oliphaunt.dev/docs/sdk/typescript/guide Create a physical backup as a Uint8Array, close the database, and restore to a new or empty directory. The restored handle uses broker mode because direct mode remains bound to its original root for the process lifetime. Restore does not replace a nonempty database. ```typescript const archive = await db.backup(); await db.close(); await Oliphaunt.restore( { kind: 'directory', path: './app-data/restored.oliphaunt' }, archive, ); const restored = await Oliphaunt.open({ topology: 'broker', storage: { kind: 'directory', path: './app-data/restored.oliphaunt' }, }); try { console.log((await restored.query('SELECT count(*) FROM notes')).rows); } finally { await restored.close(); } ``` -------------------------------- ### Oliphaunt::open() Source: https://oliphaunt.dev/docs/sdk/wasix-rust/api-reference Opens a synchronous database instance using in-memory storage by default. Use the builder to specify persistent storage and other options. ```APIDOC ## Oliphaunt::open() ### Description Opens a synchronous database instance using `DatabaseStorage::Memory` by default. ### Method `open` ### Parameters None ### Returns `Oliphaunt` instance ### Notes - Uses `DatabaseStorage::Memory` by default. - Use `.builder().storage(DatabaseStorage::Directory(path)).open()` to persist data. - Builders accept `startup_guc`, `startup_gucs`, `username`, `database`, and typed `extension` selections. ``` -------------------------------- ### Import and enable vector extension Source: https://oliphaunt.dev/docs/sdk/typescript/guide Import the vector extension descriptor and open a database with it. Then execute CREATE EXTENSION IF NOT EXISTS vector to enable it. ```typescript import vector from '@oliphaunt/extension-vector'; const db = await Oliphaunt.open({ extensions: [vector] }); await db.execute('CREATE EXTENSION IF NOT EXISTS vector'); ``` -------------------------------- ### Back up and restore Source: https://oliphaunt.dev/docs/sdk/react-native/guide Back up and restore database data. Direct mode stays bound to one database root and configuration for the lifetime of the process. Restore requires new or empty persistent storage, cannot target temporary storage, and must be used on the next launch. Reapply required extensions when opening the restored database. ```javascript ```javascript const archive = await db.backup(); await db.close(); await Oliphaunt.restore( { kind: 'applicationData', name: 'restored' }, archive, ); ``` ``` ```javascript ```javascript const restored = await Oliphaunt.open({ storage: { kind: 'applicationData', name: 'restored' }, }); await restored.close(); ``` ``` -------------------------------- ### Oliphaunt::builder() Source: https://oliphaunt.dev/docs/sdk/rust/api-reference Configures storage and selects direct().open() or broker().open(). This is a synchronous method that blocks the caller. ```APIDOC ## Oliphaunt::builder() ### Description Configures storage and selects direct().open() or broker().open(). This is a synchronous method that blocks the caller. ### Method builder ### Endpoint Oliphaunt::builder() ### Parameters None ### Response Returns a builder object. ``` -------------------------------- ### Run Deno with native loading and storage permissions Source: https://oliphaunt.dev/docs/sdk/wasix-typescript/guide Deno needs local npm module resolution. Set "nodeModulesDir": "auto" in deno.json, use npm: import prefixes, and grant native loading and storage permissions. The Worker placement does not require process-spawn permission. ```bash deno run --allow-ffi --allow-read --allow-write --allow-env main.ts ``` -------------------------------- ### OliphauntDatabase.open(configuration:) Source: https://oliphaunt.dev/docs/sdk/swift/api-reference Opens a database with the given configuration, returning an actor that exposes async throws database operations. ```APIDOC ## OliphauntDatabase.open(configuration:) ### Description Opens a database with the given configuration, returning an actor that exposes async throws database operations. ### Method open ### Parameters #### Configuration - **storage** (OliphauntDatabaseStorage) - Optional - Defaults to `.temporaryDirectory`. Persistent storage can be `.directory(URL)` using a file URL, or `.applicationData(name:)`. - **startupGUCs** ([OliphauntStartupGUC]) - Optional - Defaults to empty. Construct a startup setting with `OliphauntStartupGUC("name", "value")`. - **username** (String?) - Optional - Optional string; fresh roots use `postgres`. - **database** (String?) - Optional - Optional string; fresh roots use `postgres`. - **extensions** ([OliphauntExtension]) - Optional - Defaults to empty, typed extension selections. ### Response Returns a database instance. ``` -------------------------------- ### Select and enable extension with Oliphaunt::builder Source: https://oliphaunt.dev/docs/sdk/wasix-rust/guide Selects the pgtap extension before opening, then enables it with SQL. Reopen persistent databases with the same required extension selection. ```rust use oliphaunt_wasix::Oliphaunt; let mut db = Oliphaunt::builder() .extension(oliphaunt_extension_pgtap::PGTAP) .open()?; db.execute("CREATE EXTENSION IF NOT EXISTS pgtap")?; ``` -------------------------------- ### Backup and restore database with archive bytes Source: https://oliphaunt.dev/docs/sdk/swift/guide Use archive bytes for export, not a live directory copy. Prepare the restored data, then use it on the next launch. Restore rejects nonempty destinations. ```swift let archive = try await db.backup() try await db.close() try await OliphauntDatabase.restore(destination: restoredURL, bytes: archive) ``` -------------------------------- ### oliphaunt_init Source: https://oliphaunt.dev/docs/sdk/c-abi/api-reference Opens a direct logical lease. This function initializes the native handle for subsequent operations. ```APIDOC ## oliphaunt_init ### Description Opens a direct logical lease. ### Function `oliphaunt_init` ### Parameters - `config` (OliphauntConfig) - Required - Configuration struct with ABI version, pgdata, resource paths, identity, flags, and startup arguments. ### Returns - `OliphauntHandle` - Opaque native handle for the opened lease. ### Notes - The handle must not be inspected or freed directly. - Use `oliphaunt_free_response` for response ownership release. ``` -------------------------------- ### backup() Source: https://oliphaunt.dev/docs/sdk/swift/api-reference Returns a backup of the database as Data. ```APIDOC ## backup() ### Description Returns a backup of the database as Data. ### Method backup ### Response Returns Data. ``` -------------------------------- ### Oliphaunt::open() Source: https://oliphaunt.dev/docs/sdk/rust/api-reference Creates a temporary direct database. This is a synchronous method that blocks the caller. ```APIDOC ## Oliphaunt::open() ### Description Creates a temporary direct database. This is a synchronous method that blocks the caller. ### Method open ### Endpoint Oliphaunt::open() ### Parameters None ### Response Returns an Oliphaunt instance. ``` -------------------------------- ### oliphaunt_init_with_error Source: https://oliphaunt.dev/docs/sdk/c-abi Initializes an Oliphaunt handle from a prepared managed root's pgdata path. The root must already be prepared via a native SDK. ```APIDOC ## oliphaunt_init_with_error ### Description Initializes an Oliphaunt handle from a prepared managed root's pgdata path. The root must already be prepared via a native SDK. ### Method C function ### Signature `int32_t oliphaunt_init_with_error(const OliphauntConfig *config, OliphauntHandle **handle, OliphauntErrorCapture *error)` ### Parameters - **config** (const OliphauntConfig*) - Required - Pointer to a configuration struct with fields: `abi_version`, `pgdata`, `username`, `database`. - **handle** (OliphauntHandle**) - Required - Output pointer to receive the initialized handle. - **error** (OliphauntErrorCapture*) - Required - Pointer to an error capture struct. ### Return Value - **int32_t** - 0 on success, non-zero on failure. ### Example ```c OliphauntHandle *handle = NULL; OliphauntErrorCapture error = {0}; OliphauntConfig config = { .abi_version = OLIPHAUNT_ABI_VERSION, .pgdata = argv[1], .username = "postgres", .database = "postgres", }; if (oliphaunt_init_with_error(&config, &handle, &error) != 0) { fprintf(stderr, "%s\n", error.message); return 1; } ``` ``` -------------------------------- ### Run first query with OliphauntDatabase.open() Source: https://oliphaunt.dev/docs/sdk/swift Call this function from an async context, such as a SwiftUI .task. It uses disposable storage and closes after reading a parameterized query result. ```swift import Oliphaunt func firstQuery() async throws { let db = try await OliphauntDatabase.open() do { let result = try await db.query( "SELECT $1::int4 AS answer", parameters: [.int32(42)] ) let answer: Int32? = try result.rows[0].value(named: "answer") print(answer ?? 0) // 42 } catch { try? await db.close() throw error } try await db.close() } ``` -------------------------------- ### Create table and query data Source: https://oliphaunt.dev/docs/sdk/typescript/guide Create the `notes` table before running the insert and read. Use parameters for values; do not interpolate user input into SQL. Use `query` when you need rows, `execute` when you need command metadata, and `exec` for a trusted SQL script containing multiple statements. ```typescript await db.execute(` CREATE TABLE IF NOT EXISTS notes ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, body text NOT NULL ) `); const inserted = await db.query( 'INSERT INTO notes (body) VALUES ($1) RETURNING id', ['First note'], ); const notes = await db.query('SELECT id, body FROM notes ORDER BY id'); console.log(notes.rows); ``` -------------------------------- ### Run Deno script with required permissions Source: https://oliphaunt.dev/docs/sdk/typescript Allow native libraries, database files, environment variables, and the initdb process when running a Deno script. ```bash deno run --allow-ffi --allow-env --allow-read --allow-write --allow-run main.ts ``` -------------------------------- ### Back up and restore with db.backup and Oliphaunt::restore Source: https://oliphaunt.dev/docs/sdk/wasix-rust/guide Creates a backup archive, closes the database, and restores it to a new or empty destination. Use a compatible WASIX runtime for physical restore and ship required extensions separately. ```rust let archive = db.backup()?; db.close()?; oliphaunt_wasix::Oliphaunt::restore("./data/restored", archive)?; ``` -------------------------------- ### pg_dump(PgDumpOptions) and psql(PsqlOptions) Source: https://oliphaunt.dev/docs/sdk/wasix-rust/api-reference With the `tools` feature, database handles expose pg_dump and psql tools. Output is UTF-8 text. ```APIDOC ## pg_dump(PgDumpOptions) ### Description Runs pg_dump with the given options. Output is UTF-8 text. ### Method `pg_dump` ### Parameters - `PgDumpOptions` - Required - Options for pg_dump ### Notes - Requires the `tools` feature. - Exclusively uses and resets the session. ## psql(PsqlOptions) ### Description Runs psql with the given options. Output is UTF-8 text. ### Method `psql` ### Parameters - `PsqlOptions` - Required - Options for psql ### Notes - Requires the `tools` feature. - Exclusively uses and resets the session. ``` -------------------------------- ### Run first query with Oliphaunt.open() Source: https://oliphaunt.dev/docs/sdk/react-native Call this function from application initialization or a user action, not during React rendering. Opens a database, runs a parameterized query, logs the result, and closes the database. ```typescript import Oliphaunt from '@oliphaunt/react-native'; export async function firstQuery() { const db = await Oliphaunt.open(); try { const result = await db.query('SELECT $1::int4 AS answer', [42]); console.log(result.rows[0]?.answer); // 42 } finally { await db.close(); } } ``` -------------------------------- ### backup() Source: https://oliphaunt.dev/docs/sdk/kotlin/api-reference Returns a ByteArray backup of the database. ```APIDOC ## backup() ### Description Returns a ByteArray backup of the database. ### Method Suspend function ### Returns ByteArray ``` -------------------------------- ### Oliphaunt::builder() Source: https://oliphaunt.dev/docs/sdk/wasix-rust/api-reference Returns a builder for configuring and opening an Oliphaunt instance with custom storage and startup options. ```APIDOC ## Oliphaunt::builder() ### Description Returns a builder for configuring and opening an Oliphaunt instance. ### Method `builder` ### Parameters None ### Returns Builder object ### Builder Options - `storage(DatabaseStorage)` - Set storage (e.g., `DatabaseStorage::Directory(path)`) - `startup_guc` - Set a startup GUC - `startup_gucs` - Set multiple startup GUCs - `username` - Set username - `database` - Set database name - `extension` - Select typed extension ### Example ```rust Oliphaunt::builder() .storage(DatabaseStorage::Directory(path)) .open() ``` ``` -------------------------------- ### Open restored database on subsequent launch Source: https://oliphaunt.dev/docs/sdk/swift/guide On a subsequent application launch, open the restored destination. Reapply the original database's required extension selection when reopening. Physical backups require a compatible native runtime. ```swift let restored = try await OliphauntDatabase.open( configuration: OliphauntConfiguration(storage: .directory(restoredURL)) ) try await restored.close() ``` -------------------------------- ### Back up and restore database Source: https://oliphaunt.dev/docs/sdk/wasix-typescript/guide Creates a backup archive, closes the database, restores it to a new directory, and reopens it. Restore requires new or empty persistent storage and a compatible WASIX physical archive. Reapply required extensions when opening restored data. ```javascript const archive = await db.backup(); await db.close(); await Oliphaunt.restore(directory('./data/restored'), archive); const restored = await Oliphaunt.open({ storage: directory('./data/restored') }); await restored.close(); ``` -------------------------------- ### Use pgDump and psql from @oliphaunt/wasix-tools Source: https://oliphaunt.dev/docs/sdk/wasix-typescript/guide Dump a database with pgDump and restore it into a Worker handle with psql. pgDump supports root, direct, and Worker handles; psql requires a Worker handle in browsers. Tools exclusively use and reset the session, so reapply session settings and prepared statements after a tool run. ```typescript import OliphauntWorker from '@oliphaunt/wasix-ts/worker'; import { pgDump, psql } from '@oliphaunt/wasix-tools'; const sql = await pgDump(db); const target = await OliphauntWorker.open(); try { await psql(target, { script: sql }); } finally { await target.close(); } ``` -------------------------------- ### backup() and Oliphaunt::restore(destination, bytes) Source: https://oliphaunt.dev/docs/sdk/wasix-rust/api-reference Backup returns archive bytes; restore restores to new or empty persistent storage. ```APIDOC ## backup() ### Description Returns archive bytes of the database. ### Method `backup` ### Parameters None ### Returns Archive bytes ## Oliphaunt::restore(destination, bytes) ### Description Restores a database from archive bytes to a new or empty persistent storage. ### Method `restore` ### Parameters - `destination` - Required - Destination storage - `bytes` - Required - Archive bytes ### Notes - `AsyncOliphaunt` offers async versions. ``` -------------------------------- ### Restore a physical backup Source: https://oliphaunt.dev/docs/sdk/wasix-rust/dump-restore Creates a backup, closes the source database, and restores it to a new location. The destination must be absent or empty; restore does not replace a nonempty root. ```rust let archive = db.backup()?; db.close()?; Oliphaunt::restore("./data/restored", archive)?; ``` -------------------------------- ### execute(sql, parameters?, options?) Source: https://oliphaunt.dev/docs/sdk/react-native/api-reference Executes a command and returns command metadata. ```APIDOC ## execute(sql, parameters?, options?) ### Description Executes a command and returns command metadata. ### Method execute ### Parameters - **sql** (string) - Required - SQL statement. - **parameters** (array) - Optional - Query parameters. - **options** (object) - Optional - Query options. ### Returns Command metadata. ### Example ```typescript const meta = await db.execute('INSERT INTO users (name) VALUES ($1)', ['Alice']); ``` ``` -------------------------------- ### Query application data with db.execute and db.query Source: https://oliphaunt.dev/docs/sdk/wasix-rust/guide Creates a table, inserts a row with bound parameters, and queries it back. Use bound parameters for values and match Rust result types to PostgreSQL column types, using Option for nullable values. ```rust db.execute("CREATE TABLE IF NOT EXISTS notes (body text NOT NULL)")?; db.execute_with_params("INSERT INTO notes (body) VALUES ($1)", ["First note"])?; let result = db.query("SELECT body FROM notes")?; let body: String = result.rows()[0].try_get("body")?; ``` -------------------------------- ### AsyncOliphaunt async open methods Source: https://oliphaunt.dev/docs/sdk/rust/api-reference AsyncOliphaunt exposes corresponding async open methods for creating databases asynchronously. ```APIDOC ## AsyncOliphaunt async open methods ### Description AsyncOliphaunt exposes corresponding async open methods for creating databases asynchronously. ### Method async open ### Endpoint AsyncOliphaunt::open() and AsyncOliphaunt::builder() ### Parameters None ### Response Returns an AsyncOliphaunt instance. ``` -------------------------------- ### Build native app for Android with Expo Source: https://oliphaunt.dev/docs/sdk/react-native Run the Android native build using Expo. Use this command to build the native app for Android. ```bash npx expo run:android ``` -------------------------------- ### Open persistent application storage with AsyncOliphaunt Source: https://oliphaunt.dev/docs/learn/tauri Use AsyncOliphaunt to open a database in the application-data directory and create a table. This avoids blocking Tauri's async executor. ```rust use oliphaunt::{AsyncOliphaunt, DatabaseStorage}; use std::path::PathBuf; struct AppDatabase(AsyncOliphaunt); async fn open_database(app_data: PathBuf) -> oliphaunt::Result { let db = AsyncOliphaunt::builder() .storage(DatabaseStorage::Directory(app_data.join("postgres"))) .direct() .open() .await?; db.execute("CREATE TABLE IF NOT EXISTS notes (body text NOT NULL)").await?; Ok(db) } ``` ```rust use tauri::Manager; // Add this setup callback to your existing tauri::Builder. .setup(|app| { let app_data = app.path().app_data_dir()?; let db = tauri::async_runtime::block_on(open_database(app_data))?; app.manage(AppDatabase(db)); Ok(()) }) ``` -------------------------------- ### Enable vector extension and create embeddings table Source: https://oliphaunt.dev/docs/reference/extensions After packaging and selecting the 'vector' extension, run these SQL statements to enable it and create a table with a vector column. ```sql CREATE EXTENSION IF NOT EXISTS vector; CREATE TABLE embeddings (id bigint PRIMARY KEY, embedding vector(3)); ``` -------------------------------- ### Back up and restore database Source: https://oliphaunt.dev/docs/sdk/kotlin/guide Backs up the database to a byte array, closes the handle, and restores to a new destination. Direct mode stays bound to one database root and configuration for the lifetime of the process. Restore requires a new or empty destination. ```kotlin val archive: ByteArray = db.backup() db.close() val destination = context.filesDir.resolve("restored.oliphaunt") Oliphaunt.restore(context, destination, archive) ```