### Basic Query Builder Usage Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/supastash-query-builder.md Demonstrates how to start a query, select data, apply a filter, and execute the operation. This is a fundamental example of the chainable query builder. ```typescript await supastash.from("users").select().eq("status", "active").run(); ``` ```typescript await supastash.from("orders").run(); ``` -------------------------------- ### Troubleshooting Examples Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/sync-log-utils.md Code examples demonstrating how to use sync log utilities for troubleshooting common sync issues. ```APIDOC ## Troubleshooting Examples ### Check current sync status ```typescript // Check current sync status const status = await getSyncLog("users"); console.log("Last sync:", status?.last_synced_at); ``` ### Force resync ```typescript // Force resync await resetSyncLog("users", undefined, "last_synced_at"); ``` ### Verify sync log exists ```typescript // Verify sync log exists const log = await getSyncLog("users"); if (!log) { console.log("No sync log found - first sync will be full"); } ``` ### Check for filter mismatches ```typescript // Check for filter mismatches console.log("Current filter key:", log?.filter_key); ``` ### Clear and resync ```typescript // Clear and resync await clearLocalSyncLog("users"); await pullData("users"); ``` ``` -------------------------------- ### Configure Supastash at App Startup Source: https://github.com/0xzekea/supastash/blob/main/src/shared/docs/configuration.md Call `configureSupastash()` once at your app's startup, typically in a dedicated setup file. This example demonstrates setting up the database name, Supabase client, Expo SQLite client, and defining a local schema for users. ```typescript import { configureSupastash, defineLocalSchema } from "supastash"; import { supabase } from "./supabase"; import { openDatabaseAsync } from "expo-sqlite"; configureSupastash({ dbName: "supastash_db", supabaseClient: supabase, sqliteClient: { openDatabaseAsync }, sqliteClientType: "expo", debugMode: true, onSchemaInit: async () => { defineLocalSchema("users", { id: "TEXT PRIMARY KEY", name: "TEXT", email: "TEXT", created_at: "TIMESTAMP DEFAULT CURRENT_TIMESTAMP", updated_at: "TIMESTAMP DEFAULT CURRENT_TIMESTAMP", }); }, }); ``` -------------------------------- ### Full Supastash Query Example Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/supastash-filters.md A comprehensive example demonstrating the chaining of multiple filters, limit, and execution. ```typescript const { data, error } = await supastash .from("products") .select() .eq("category", "electronics") .gte("price", 100) .lte("price", 999) .in("brand", ["Sony", "Samsung", "Apple"]) .is("in_stock", true) .limit(25) .run(); ``` ```sql SELECT * FROM products WHERE category = 'electronics' AND price >= 100 AND price <= 999 AND brand IN ('Sony', 'Samsung', 'Apple') AND in_stock IS TRUE LIMIT 25; ``` -------------------------------- ### Install Supastash Package Source: https://github.com/0xzekea/supastash/blob/main/README.md Install the main Supastash package using npm. ```bash npm install supastash ``` -------------------------------- ### Example 1: Custom RPC for Push Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/sync-calls.md Demonstrates how to use `registerSyncCall` to implement a custom RPC for the 'sales' table's push operation. ```APIDOC ## Example: Custom RPC for Push ### Description This example shows how to override the default push behavior for the 'sales' table by registering a custom `push` function that calls a Supabase RPC endpoint. ### Code ```ts import { registerSyncCall } from "supastash/core/sync/registerSyncCall"; import { supabase } from "@/lib/supabase"; registerSyncCall("sales", { async push(rows) { const { error } = await supabase.rpc("batch_sync", { target_table: "sales", payload: rows, columns: Object.keys(rows[0] ?? {}), }); if (error) { console.error("[Supastash] RPC push failed:", error); // Implement your retry logic here // For example, return false if the push failed and needs to be retried: // if (failed) return false; } return true; // Indicate success, rows will be marked as synced }, }); ``` ### Notes - The `push` function must return `true` on success and `false` on failure to indicate whether a retry is needed. ``` -------------------------------- ### Install Required Peer Dependencies Source: https://github.com/0xzekea/supastash/blob/main/src/shared/docs/getting-started.md Manually install the essential peer dependencies for Supastash. ```bash npm install @supabase/supabase-js @react-native-community/netinfo react react-native ``` -------------------------------- ### Install Classic SQLite Adapter for Bare React Native Source: https://github.com/0xzekea/supastash/blob/main/src/shared/docs/getting-started.md Install the react-native-sqlite-storage adapter as a classic SQLite option for bare React Native projects. ```bash # Or classic SQLite option npm install react-native-sqlite-storage ``` -------------------------------- ### Install React Native Nitro SQLite Adapter Source: https://github.com/0xzekea/supastash/blob/main/README.md Install 'react-native-nitro-sqlite' for potentially better performance in bare React Native projects. ```bash # Bare RN with better speed npm install react-native-nitro-sqlite ``` -------------------------------- ### Install Classic React Native SQLite Storage Adapter Source: https://github.com/0xzekea/supastash/blob/main/README.md Install 'react-native-sqlite-storage' for classic SQLite support in React Native (currently in beta). ```bash # Classic RN SQLite (beta) npm install react-native-sqlite-storage ``` -------------------------------- ### Install Required Peer Dependencies Source: https://github.com/0xzekea/supastash/blob/main/README.md Install the necessary peer dependencies for Supastash, including Supabase JS, NetInfo, React, and React Native. ```bash npm install @supabase/supabase-js \ @react-native-community/netinfo \ react \ react-native ``` -------------------------------- ### Initializing Supastash in App Entry Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/useSupastash-hook.md Example of how to use the useSupastash hook in your application's entry layout file (e.g., _layout.tsx or App.tsx) to manage Supastash initialization and sync. ```typescript // _layout.tsx or App.tsx (entry layout) const { dbReady, startSync, stopSync } = useSupastash(); if (!dbReady) return null; ``` -------------------------------- ### Install Expo SQLite Adapter Source: https://github.com/0xzekea/supastash/blob/main/README.md Install the 'expo-sqlite' package if you are using Expo for your React Native project. ```bash # Expo (most common) npm install expo-sqlite ``` -------------------------------- ### Usage Example for Applying Triggers to Multiple Tables Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/replication-mode.md This SQL query demonstrates how to use the `apply_arrival_trigger_to_tables` function to attach the arrival trigger to the 'orders' and 'order_items' tables. ```sql SELECT apply_arrival_trigger_to_tables( ARRAY['orders', 'order_items'] ); ``` -------------------------------- ### Configure Supastash Source: https://github.com/0xzekea/supastash/blob/main/src/shared/docs/getting-started.md Configure Supastash with your Supabase client, database name, SQLite client, and schema initialization. This should be done early in your application, for example, in `lib/supastash.ts`. ```typescript // lib/supastash.ts import { configureSupastash, defineLocalSchema } from "supastash"; import { supabase } from "./supabase"; import { openDatabaseAsync } from "expo-sqlite"; configureSupastash({ supabaseClient: supabase, dbName: "supastash_db", sqliteClient: { openDatabaseAsync }, sqliteClientType: "expo", // or "rn-nitro" or "rn-storage" onSchemaInit: () => { // Define your local schema here. You can include this is a separate file, then call it here. defineLocalSchema( "users", { id: "TEXT PRIMARY KEY", name: "TEXT", email: "TEXT", created_at: "TIMESTAMP DEFAULT CURRENT_TIMESTAMP", updated_at: "TIMESTAMP DEFAULT CURRENT_TIMESTAMP", }, true ); }, debugMode: true, // useful for logging syncEngine: { push: true, pull: false, // ⚠️ Pull sync is disabled by default. It will pull unfiltered data from the server. Enable RLS if you want to pull filtered data. }, }); ``` -------------------------------- ### Configure Supastash with Local Schema Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/configuration.md Call configureSupastash once at app startup before using any hooks. This example sets up the database name, Supabase client, SQLite client, and defines a local schema for users. ```typescript import { configureSupastash, defineLocalSchema } from "supastash"; import { supabase } from "./supabase"; import { openDatabaseAsync } from "expo-sqlite"; configureSupastash({ dbName: "supastash_db", supabaseClient: supabase, sqliteClient: { openDatabaseAsync }, sqliteClientType: "expo", debugMode: true, onSchemaInit: async () => { defineLocalSchema("users", { id: "TEXT PRIMARY KEY", name: "TEXT", email: "TEXT", created_at: "TIMESTAMP DEFAULT CURRENT_TIMESTAMP", updated_at: "TIMESTAMP DEFAULT CURRENT_TIMESTAMP", }); }, // Recommended hardening for name<=20/barcode flows syncPolicy: { nonRetryableCodes: new Set([ "23505", "23502", "23514", "23P01", "22001", "22P02", ]), onNonRetryable: "accept-server", }, }); ``` -------------------------------- ### Column Definition Examples Source: https://github.com/0xzekea/supastash/blob/main/src/shared/docs/schema-management.md Columns are defined using string templates that combine SQL types and modifiers. Multiple modifiers can be combined. ```typescript { id: "TEXT PRIMARY KEY", quantity: "INTEGER NOT NULL", price: "REAL", active: "INTEGER DEFAULT 1", created_at: "TEXT DEFAULT CURRENT_TIMESTAMP" } ``` ```typescript "name": "TEXT NOT NULL UNIQUE" ``` -------------------------------- ### Component Usage: Refresh Table Source: https://github.com/0xzekea/supastash/blob/main/src/shared/docs/data-access.md Example of how to use `refreshTable` within a component, for instance, after a sync operation completes. ```typescript import { refreshTable } from "supastash/utils/sync/refreshTables"; function onSyncComplete() { refreshTable("messages"); } ``` -------------------------------- ### Example 2: Pull + Mark Messages as Delivered Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/sync-calls.md Illustrates using `registerSyncCall` to handle data pulling for the 'messages' table and marking messages as delivered via an RPC. ```APIDOC ## Example: Pull + Mark Messages as Delivered ### Description This example demonstrates registering a custom `pull` function for the 'messages' table. It fetches new messages, upserts them locally, and then calls an RPC to mark them as delivered. ### Code ```ts import { registerSyncCall } from "supastash/core/sync/registerSyncCall"; import { supastash } from "supastash"; // Assuming supastash client is imported import { supabase } from "@/lib/supabase"; // Assuming supabase client is imported registerSyncCall("messages", { async pull(payload) { // Your custom logic to process the pulled data // .. // Add payload to local db const { data, error } = await supastash .from("messages") .upsert(payload) .syncMode("localOnly") .run(); if (error) throw error; // Example: mark received messages as delivered using an RPC const deliveredIds = data.map((m) => m.id); await supabase.rpc("mark_messages_delivered", { ids: deliveredIds }); console.log(`Pulled ${data.length} new messages`); }, }); ``` ### Notes - The `pull` function is responsible for handling incoming data and any necessary side effects, such as updating local records or triggering other actions. ``` -------------------------------- ### Test Supastash Pull Sync RPC Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/batch-pull-sync.md Verify the `supastash_pull_sync` function directly from the Supabase SQL editor. This example demonstrates how to specify tables, JSON filters, and the sync cursor column. ```sql SELECT public.supastash_pull_sync( ARRAY['bikers'], '{ "bikers": [ { "col": "city", "op": "eq", "val": "e9673fbe-490d-4158-b578-cee6c9a4da0a" }, { "col": "deleted_at", "op": "is_null" }, { "or": [ { "col": "is_active", "op": "eq", "val": "true" }, { "col": "bike_id", "op": "is_not_null" } ] } ] }'::jsonb, 'arrived_at' -- or 'updated_at' for client-side replication ); ``` -------------------------------- ### Simple Filter Example Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/batch-pull-sync.md A basic filter structure with a column, operator, and value. ```json { col: "shop_id", op: "eq", val: shopId } ``` -------------------------------- ### Advanced useSupastashData with Filters, Lazy Loading, and Callbacks Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/useSupastashData.md This example showcases advanced configuration for useSupastashData. It includes conditional fetching based on userId, lazy loading requiring manual triggering, batched updates, filtering by user_id, grouping by status and user_id, and custom callbacks for insert, update, and delete events. The data fetching is initiated via a useEffect hook when lazy loading is enabled. ```tsx const { data, dataMap, trigger, cancel, groupedBy } = useSupastashData( "orders", { shouldFetch: !!userId, // Only fetch if user is available lazy: true, // Wait for manual trigger flushIntervalMs: 200, // Reduce render frequency filter: { column: "user_id", operator: "eq", value: userId, }, extraMapKeys: ["status", "user_id"], onInsert: (order) => console.log("Inserted:", order), onUpdate: (order) => console.log("Updated:", order), onDelete: (order) => console.log("Deleted:", order), } ); useEffect(() => { trigger(); // Only needed if lazy: true }, []); ``` -------------------------------- ### Use SupatashData Hook Source: https://github.com/0xzekea/supastash/blob/main/README.md Example of using the `useSupatashData` hook to fetch orders data, filtered by user ID. Ensure the 'supastash' library is imported. ```tsx import { useSupatashData } from "supastash"; const { data: orders } = useSupatashData("orders", { filter: { column: "user_id", operator: "eq", value: userId }, }); ``` -------------------------------- ### Configure Supastash with RN Storage SQLite Source: https://github.com/0xzekea/supastash/blob/main/src/shared/docs/configuration.md Example of configuring Supastash with the 'rn-storage' SQLite client type. This is a legacy option but widely supported. Ensure `configureSupastash()` is called before any hook or sync action. ```typescript sqliteClientType: "rn-storage", sqliteClient: { openDatabase } ``` -------------------------------- ### Configure Supastash with Expo SQLite Source: https://github.com/0xzekea/supastash/blob/main/src/shared/docs/configuration.md Example of configuring Supastash with the 'expo' SQLite client type. Ensure `configureSupastash()` is called before any hook or sync action. ```typescript sqliteClientType: "expo", sqliteClient: { openDatabaseAsync } ``` -------------------------------- ### Subscribe to Supastash Refresh Event Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/zustand.md Example of subscribing to a specific table's refresh event using `supastashEventBus.on`. ```typescript supastashEventBus.on("supastash:refreshZustand:sales", hydrateSales); ``` -------------------------------- ### Filtered and Configured useSupastashData Usage Source: https://github.com/0xzekea/supastash/blob/main/src/shared/docs/data-access.md This example demonstrates using the hook with advanced options like filtering, lazy loading, and custom callbacks for realtime events. The `trigger` function must be called if `lazy` mode is enabled. ```tsx const { data, dataMap, trigger, cancel } = useSupastashData("orders", { filter: { column: "user_id", operator: "eq", value: userId, }, shouldFetch: !!userId, flushIntervalMs: 200, lazy: true, realtime: true, onInsert: (item) => console.log("Inserted:", item), onUpdate: (item) => console.log("Updated:", item), onDelete: (item) => console.log("Deleted:", item), }); useEffect(() => { trigger(); // required if lazy mode is enabled }, []); ``` -------------------------------- ### Soft Delete a Task Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/delete-query.md This example demonstrates how to soft-delete a task by its ID. The row will be marked with a `deleted_at` timestamp locally and queued for syncing. ```typescript await supastash.from("tasks").delete().eq("id", "task_1").run(); ``` -------------------------------- ### Configure Supastash with RN Nitro SQLite Source: https://github.com/0xzekea/supastash/blob/main/src/shared/docs/configuration.md Example of configuring Supastash with the 'rn-nitro' SQLite client type. This is suitable for performance-critical applications. Ensure `configureSupastash()` is called before any hook or sync action. ```typescript sqliteClientType: "rn-nitro", sqliteClient: { open } ``` -------------------------------- ### Zustand Store with Hydration Function Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/zustand.md An example of a Zustand store that includes a `hydrateSales` async function to fetch and update sales data. It demonstrates fetching data from a 'sales' table and setting the store's state. ```typescript import { create } from "zustand"; const prevLimit = 100; export const useSalesStore = create((set) => ({ sales: [], hydrateSales: async (newLimit = prevLimit) => { const { data: sales } = await supastash .from("sales") .select("*") .is("deleted_at", null) .limit(newLimit) .run(); if (sales) set({ sales }); }, })); ``` -------------------------------- ### Get Supastash Database Instance Source: https://github.com/0xzekea/supastash/blob/main/src/shared/docs/schema-management.md Retrieves the active SQLite database instance for local-first operations. It lazily initializes the connection once using the configured adapter. ```typescript const db = await getSupastashDb(); const users = await db.getAllAsync("SELECT * FROM users"); await db.withTransaction(async (tx) => { await tx.runAsync( `INSERT INTO orders (id, customer_name, total_amount, created_at) VALUES (?, ?, ?, ?)`, ["1", "John Udoka", 250.0, new Date().toISOString()] ); await tx.runAsync( `INSERT INTO order_items (id, order_id, product_name, quantity, price) VALUES (?, ?, ?, ?, ?)`, ["10", "1", "Premium Shirt", 2, 125.0] ); }); ``` -------------------------------- ### Get All User Tables Source: https://github.com/0xzekea/supastash/blob/main/src/shared/docs/schema-management.md Fetches a list of all user-defined tables in the local SQLite database, excluding internal Supastash tables. Useful for dynamic tooling or debugging. ```typescript const tables = await getAllTables(); console.log(tables); // ["users", "orders", "transactions"] ``` -------------------------------- ### Access Grouped Data with extraMapKeys Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/useSupastashData.md After configuring `extraMapKeys`, you can directly access grouped data using the `groupedBy` object. This example shows how to retrieve all orders for a specific user. ```typescript const userOrders = groupedBy.user_id.get(user.id) ?? []; ``` -------------------------------- ### Basic Query with Supastash Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/getSupastashDb.md Demonstrates how to perform a basic INSERT operation using the `runAsync` method after obtaining the database connection. ```typescript const db = await getSupastashDb(); await db.runAsync( `INSERT INTO orders (id, customer_name, total_amount, created_at)` `VALUES (?, ?, ?, ?)`, ["1", "John Doe", 150, new Date().toISOString()] ); ``` -------------------------------- ### Initialize Supastash in App Entry Point Source: https://github.com/0xzekea/supastash/blob/main/README.md Import the Supastash configuration file once in your application's entry point (e.g., App.tsx or _layout.tsx) to trigger initialization. Use the useSupatash hook to check for database readiness. ```ts // App.tsx or _layout.tsx import "@/lib/supastash"; // triggers init import { useSupatash } from "supastash"; export default function App() { const { dbReady } = useSupatash(); if (!dbReady) return null; return ; } ``` -------------------------------- ### configureSupastash Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/configuration.md Initializes Supastash. This function must be called once to set up the Supastash instance with the provided configuration. ```APIDOC ## configureSupastash(config: SupastashConfig & { sqliteClientType: T }) ### Description Initializes Supastash. Must be called once. ### Parameters #### Core options - **dbName** (string) - Optional - Name of local SQLite DB. Defaults to "supastash_db". - **supabaseClient** (SupabaseClient | null) - Required - A configured Supabase client. - **sqliteClient** (adapter for chosen engine) - Required - Shape depends on `sqliteClientType`. - **sqliteClientType** ("expo" | "rn-storage" | "rn-nitro" | null) - Required - Selects SQLite engine. - **platform** ("native" | "desktop") - Optional - Runtime platform. Controls which adapters (DB, storage, lifecycle) are used. Defaults to "native". - **onSchemaInit** (() => Promise) - Optional - Hook to define local schema with `defineLocalSchema`. Runs once after DB creation. - **debugMode** (boolean) - Optional - Verbose logs for sync/DB. Defaults to `true`. - **listeners** (number) - Optional - Max event listeners. Defaults to `250`. - **networkAdapter** ({ fetch: () => Promise<{ isConnected: boolean | null }> } | null) - Optional - Custom network connectivity adapter. Pass `NetInfo` from `@react-native-community/netinfo` on React Native for reliable detection. - **hasEnabledSimpleNullHandling** (boolean) - Optional - Suppresses the simple null handling warning for Nitro SQLite. Only set if you've explicitly opted in to simple null mode. Defaults to `false`. - **supastashMode** ("live" | "ghost") - Optional - "ghost" disables all network activity (no sync, no realtime, no retries). Useful for demo, testing, or sandbox environments. Defaults to "live". - **pushRPCPath** (string) - Optional - Path to your custom batch-sync RPC for push operations. ``` -------------------------------- ### Initialize Supastash and Wait for DB Ready Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/getting-started.md Import and use the `useSupatash` hook to check if the database is ready before rendering your application. This prevents rendering issues before data is available. ```typescript import { useSupatash } from "supastash"; const { dbReady } = useSupatash(); if (!dbReady) return null; return ; ``` -------------------------------- ### OR Group Filter Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/batch-pull-sync.md Example of an OR group combining multiple filter conditions. ```json { or: [ { col: "is_active", op: "eq", val: "true" }, { col: "brand_id", op: "is_not_null" }, ], } ``` -------------------------------- ### Basic useSupastashLiteQuery Usage Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/useSupastashLiteQuery.md Demonstrates how to use useSupastashLiteQuery to fetch paginated data and integrate it with a FlatList for infinite scrolling and manual refresh. ```tsx const { data, loadMore, refresh, isLoading, hasMore } = useSupastashLiteQuery("orders", { sqlFilter: [{ column: "shop_id", operator: "eq", value: activeShopId }], pageSize: 30, orderBy: "created_at", orderDesc: true, }); item.id} renderItem={({ item }) => } onEndReached={loadMore} onRefresh={refresh} refreshing={isLoading} ListFooterComponent={hasMore && isLoading ? : null} />; ``` -------------------------------- ### Enable Sync Engine with useSupatash Hook Source: https://github.com/0xzekea/supastash/blob/main/src/shared/docs/getting-started.md Use the `useSupatash` hook before rendering the rest of your app to prepare the sync engine. Ensure `dbReady` is true before proceeding. ```typescript import { useSupatash } from "supastash"; const { dbReady } = useSupatash(); if (!dbReady) return null; return ; ``` -------------------------------- ### Initialize Supastash in App Entry Point Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/getting-started.md Import the Supastash configuration file once in your application's entry point (e.g., App.tsx or _layout.tsx) to trigger initialization. ```typescript // App.tsx or _layout.tsx import "@/lib/supastash"; // Triggers initialization export default function App() { return ; // or your app shell } ``` -------------------------------- ### Using .cacheFirst() Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/select-query.md Attempts to resolve the query from the local SQLite database first. If no usable result is found locally, it automatically falls back to fetching from the remote Supabase instance. ```APIDOC ## SELECT with Cache First Fetch Policy ### Description Attempts to resolve the query from the local SQLite database first. If no usable result is found locally, it automatically falls back to fetching from the remote Supabase instance. This provides fast local reads with a safe remote fallback. ### Method SELECT (Implicit) ### Endpoint N/A (Local Database Operation with Remote Fallback) ### Parameters #### Columns - `columns` (string) - Comma-separated string of column names to select, or `*` for all columns. #### Filters - Supports standard operators like `.eq()`, `.gt()`, `.in()`, etc. ### Chained Methods - `.cacheFirst()` - Enables the cache-first fetch policy. ### Request Example ```ts const result = await supastash .from("orders") .select("id, amount") .eq("status", "pending") .cacheFirst() .run(); ``` ### Response #### Success Response - `data` (array | object | null) - The query result, fetched either from local cache or remote. #### Response Example ```json { "data": [ { "id": "a1", "amount": 500 }, ... ], "error": null, "success": true } ``` ``` -------------------------------- ### Switching to and from Ghost Mode Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/supastash-runtime-modes.md Use `reinitializeSupastash` to switch between 'ghost' and 'live' modes. This is essential for executing tutorial or demo flows in isolation and then returning to the main application state. ```typescript await reinitializeSupastash("ghost"); // Explicitly initialize tutorial-only schema and data await createGhostTables(); await seedTutorialData(); // User interacts with tutorial data safely // No network access // No remote sync // No risk of affecting live data // Exit tutorial and return to Live Mode await reinitializeSupastash("live"); ``` -------------------------------- ### Delete with Filter Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/delete-query.md All `.delete()` calls require at least one filter to prevent accidental data loss. This example shows a delete operation scoped by `project_id`. ```typescript .delete().eq("project_id", "proj_123") ``` -------------------------------- ### Cache First Strategy (.cacheFirst) Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/supastash-filters.md Available on .select() only. Prioritizes fetching data from the local SQLite database, falling back to Supabase if no usable result is found. ```typescript await supastash .from("products") .select() .eq("id", productId) .cacheFirst() .run(); ``` -------------------------------- ### PostgreSQL Update Trigger Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/sync-log-utils.md Example of a PostgreSQL trigger function to automatically update the `updated_at` column on row updates. This ensures consistency for all mutations, even those outside Supastash. ```sql -- Example trigger for PostgreSQL CREATE OR REPLACE FUNCTION update_updated_at_column() RETURNS TRIGGER AS $$ BEGIN NEW.updated_at = NOW(); RETURN NEW; END; $$ LANGUAGE plpgsql; CREATE TRIGGER update_users_updated_at BEFORE UPDATE ON users FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); ``` -------------------------------- ### Insert with Default Sync Mode (Local First) Source: https://github.com/0xzekea/supastash/blob/main/src/shared/docs/insert-query.md This snippet shows a basic insert operation using the default 'localFirst' sync mode, where data is written locally and queued for remote synchronization. ```typescript await supastash .from("orders") .insert({ amount: 500 }) .run(); ``` -------------------------------- ### Troubleshoot Data Not Appearing Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/sync-log-utils.md Verify if a sync log exists for the table using `getSyncLog`. If no log is found, the next sync will be a full one. Also, check the `filter_key` in the sync log for potential mismatches that might prevent data from appearing. ```typescript // Verify sync log exists const log = await getSyncLog("users"); if (!log) { console.log("No sync log found - first sync will be full"); } // Check for filter mismatches console.log("Current filter key:", log?.filter_key); ``` -------------------------------- ### Execute Query (.run) Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/supastash-filters.md Executes the constructed query against the database. Equivalent to .execute() or .go(). ```typescript const { data, error, success } = await supastash .from("orders") .select() .eq("user_id", currentUser.id) .lte("total", 500) .limit(20) .run(); ``` -------------------------------- ### Direct Supabase Query with Supastash Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/getting-started.md Use the `supastash.from()` wrapper for direct Supabase access, ensuring it respects your Supastash configuration. This is useful for making one-off queries. ```typescript import { supastash } from "supastash"; const { data, error } = await supastash.from("orders").select("*").run(); ``` -------------------------------- ### Upsert Operation Failing Due to Missing ID Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/upsert-query.md This example demonstrates an invalid upsert operation where the 'id' field is missing. Supastash requires an 'id' for every item to perform upserts. ```typescript await supastash.from("products").upsert({ name: "Invalid" }); // ❌ no id ``` -------------------------------- ### Select with Filters and Limit Source: https://github.com/0xzekea/supastash/blob/main/src/shared/docs/select-query.md Demonstrates selecting specific columns, applying an equality filter, and limiting the number of returned rows. ```typescript await supastash .from("tasks") .select("id, title") .eq("assigned_to", "user_1") .limit(10) .run(); ``` -------------------------------- ### Perform Server Queries with supastash Query Builder Source: https://github.com/0xzekea/supastash/blob/main/src/shared/docs/getting-started.md Use the `supastash` query builder, a wrapper around `supabase.from(...)`, for one-off server queries that align with Supastash's local-first philosophy. ```typescript import { supastash } from "supastash"; const { data, error } = await supastash.from("orders").select("*").run(); if (error) console.error(error); return {JSON.stringify(data)}; ``` -------------------------------- ### Register Custom Pull Handler for Messages Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/sync-calls.md This example registers a custom pull handler for the 'messages' table. It upserts incoming messages locally and then uses a Supabase RPC to mark them as delivered based on their IDs. ```typescript registerSyncCall("messages", { async pull(payload) { // Your logic // .. // Add payload to local db const { data, error } = await supastash .from("messages") .upsert(payload) .syncMode("localOnly") .run(); if (error) throw error; // Example: mark received messages as delivered const deliveredIds = data.map((m) => m.id); await supabase.rpc("mark_messages_delivered", { ids: deliveredIds }); console.log(`Pulled ${data.length} new messages`); }, }); ``` -------------------------------- ### Basic Data Fetching with useSupastashData Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/useSupastashData.md This snippet demonstrates the fundamental usage of the useSupastashData hook to load all records from a specified table ('orders'). It returns the data as both an array and a map keyed by 'id'. ```tsx const { data, dataMap } = useSupastashData("orders"); ``` -------------------------------- ### Define Table Filters with useSupastashFilters Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/useSupastashFilters.md Use this hook to specify filtering rules for tables. Each rule consists of a column, an operator, and a value to match. This example filters 'orders' by 'shop_id' and 'status', and 'inventory' by 'location_id'. ```typescript useSupastashFilters({ orders: [ { column: "shop_id", operator: "eq", value: currentShopId }, { column: "status", operator: "in", value: ["pending", "completed"] }, ], inventory: [ { column: "location_id", operator: "eq", value: selectedLocationId }, ], }); ``` -------------------------------- ### Simplified useSupastashData Usage Source: https://github.com/0xzekea/supastash/blob/main/src/shared/docs/data-access.md This is the basic way to use the hook to fetch all records from a specified table. It returns the data as an array and a map. ```tsx const { data, dataMap } = useSupastashData("orders"); ``` -------------------------------- ### Get Sync Log for a Table Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/sync-log-utils.md Retrieves the stored sync status for a specific table. Returns null if the table has no entry. Useful for debugging sync status, building custom dashboards, or monitoring sync health. ```typescript const log = await getSyncLog("users"); ``` ```typescript { table_name: "users", last_synced_at: "2024-06-01T10:00:00.000Z", last_synced_at_pk: "00000000-0000-0000-0000-000000000000", last_deleted_at: "2024-06-01T10:00:00.000Z", filter_key: "abc123", filter_json: "[...]", updated_at: "2024-06-01T10:00:00.000Z" } ``` -------------------------------- ### getSupastashDb() Source: https://github.com/0xzekea/supastash/blob/main/src/shared/docs/schema-management.md Returns the active SQLite database instance for local-first operations. It lazily initializes the connection once using the configured adapter. ```APIDOC ## `await getSupastashDb()` ### Description Returns the active SQLite database instance that Supastash uses to perform all local-first operations — such as reads, writes, and sync tracking. It **lazily initializes** the database connection only once (singleton pattern), using the adapter specified in your Supastash configuration. ### API Methods | Method | Description | | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `runAsync(sql, params?)` | Executes a single statement (e.g., `INSERT`, `UPDATE`, `DELETE`) Returns `Promise`. | | `getAllAsync(sql, params?)` | Fetches **all rows** from a `SELECT` query Returns `Promise`. | | `getFirstAsync(sql, params?)` | Fetches **first row only** (or `null` if none) from a `SELECT` query Returns `Promise`. | | `execAsync(statements)` | Executes multiple SQL statements separated by `;` (used in schema creation) Returns `Promise`. | | `withTransaction(fn)` | Executes multiple operations inside a single SQLite transaction. Automatically commits on success and rolls back if an error is thrown. Nested transactions are not supported. Returns `Promise`. ### Example Usage ```ts const db = await getSupastashDb(); const users = await db.getAllAsync("SELECT * FROM users"); await db.withTransaction(async (tx) => { await tx.runAsync( `INSERT INTO orders (id, customer_name, total_amount, created_at)` `VALUES (?, ?, ?, ?)`, ["1", "John Udoka", 250.0, new Date().toISOString()] ); await tx.runAsync( `INSERT INTO order_items (id, order_id, product_name, quantity, price)` `VALUES (?, ?, ?, ?, ?)`, ["10", "1", "Premium Shirt", 2, 125.0] ); }); ``` ``` -------------------------------- ### Trigger Manual Sync for All Tables Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/sync-flows.md Use `syncAllTables` to synchronize all Supastash tables. This is useful for app resume or manual "Sync Now" actions. ```ts import { syncAllTables } from "supastash"; import { AppState } from "react-native"; useEffect(() => { const sub = AppState.addEventListener("change", async (state) => { if (state === "active") { await syncAllTables(); // sync everything when app becomes active } }); return () => sub.remove(); }, []); ``` -------------------------------- ### Show Push Sync Progress Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/useSupastashSyncStatus.md Calculate and display the push sync progress percentage based on completed tables versus the total number of tables. This requires access to `syncInfo.push`. ```tsx const progress = Math.round( (syncInfo.push.tablesCompleted / syncInfo.push.numberOfTables) * 100 ); Push Sync Progress: {progress}%; ``` -------------------------------- ### Advanced Querying with Supastash Source: https://github.com/0xzekea/supastash/blob/main/README.md Demonstrates advanced querying using the Supastash client, including update operations with different sync modes. Available sync modes are 'localFirst', 'localOnly', and 'remoteOnly'. ```ts await supastash .from("orders") .update({ status: "delivered" }) .syncMode("localFirst") // localOnly, remoteOnly also available .run(); ``` -------------------------------- ### Basic Filter Usage Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/supastash-filters.md Demonstrates chaining multiple filters for a query. Filters are combined with AND logic. ```typescript await supastash .from("users") .select() .eq("status", "active") .gte("age", 18) .run(); ``` -------------------------------- ### Configure Supastash Listener Limit Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/zustand.md Shows how to configure Supastash to increase the maximum number of listeners, which can be useful if encountering `MaxListenersExceededWarning` when subscribing to many events. ```typescript configureSupastash({ // ...other config listeners: 500, // increase from default 250 }); ``` -------------------------------- ### Register Table Filters with useSupastashFilters Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/getting-started.md Call this hook at startup if you are pulling data (using `pull: true`) to ensure only scoped rows are pulled from Supabase. This prevents unnecessary or insecure full-table syncs and validates your filters. ```typescript useSupastashFilters({ orders: [{ column: "shop_id", operator: "eq", value: activeShopId }], inventory: [ { column: "location_id", operator: "eq", value: selectedLocation }, ], }); ``` -------------------------------- ### Import Refresh Utilities Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/manual-refreshes.md Import the necessary functions for refreshing table data from Supastash utilities. ```typescript import { refreshTable, refreshAllTables, } from "supastash/utils/sync/refreshTables"; ``` -------------------------------- ### Using cacheFirst() for Data Retrieval Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/fetchPolicy.md Use `cacheFirst()` to prioritize local data. If data is not found locally, it fetches from the remote database and caches it. This is ideal for data that doesn't require real-time updates. ```typescript const { data, error } = await supastash .from("orders") .select("*") .eq("status", "completed") .cacheFirst() // 👇 The magic happens here .run(); // If "completed orders" are already in SQLite, // this returns in ~5ms instead of ~200ms+. ``` -------------------------------- ### Fetch Data with useSupastashData Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/getting-started.md Use this hook for fetching and syncing local data with Supabase in realtime. It utilizes a global cache and automatically keeps state synced, making it ideal for dashboards and live data. ```typescript const { data, dataMap, groupedBy } = useSupastashData("orders", { filter: { column: "user_id", operator: "eq", value: userId }, extraMapKeys: ["status"], }); ``` -------------------------------- ### Reinitialize Supastash to Switch Modes Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/supastash-runtime-modes.md Use this function to switch between 'live' and 'ghost' runtime modes. This process involves a full reinitialization of Supastash services. ```typescript await reinitializeSupastash(mode: 'live' | 'ghost') ``` -------------------------------- ### Configure Supastash with Expo SQLite Source: https://github.com/0xzekea/supastash/blob/main/README.md Configure Supastash with Supabase client, database name, Expo SQLite adapter, and define the local schema for users. Includes debug mode and sync engine settings. ```ts // lib/supastash.ts import { configureSupastash, defineLocalSchema } from "supastash"; import { supabase } from "./supabase"; import { openDatabaseAsync } from "expo-sqlite"; // or your adapter import * as NetInfo from "@react-native-community/netinfo"; // react-native only configureSupastash({ supabaseClient: supabase, dbName: "supastash_db", sqliteClient: { openDatabaseAsync }, sqliteClientType: "expo", networkAdapter: NetInfo, onSchemaInit: () => { defineLocalSchema("users", { id: "TEXT PRIMARY KEY", name: "TEXT", email: "TEXT", created_at: "TEXT NOT NULL", updated_at: "TEXT NOT NULL", }); }, debugMode: true, syncEngine: { push: true, pull: false, // enable this if using filters or RLS }, excludeTables: { push: ["daily_reminders"], pull: ["daily_reminders"], }, }); ``` -------------------------------- ### Define Filters for Pull Syncing Source: https://github.com/0xzekea/supastash/blob/main/README.md Configure filters for tables like 'orders' and 'inventory' when using 'pull: true' in the sync engine to ensure efficient data synchronization based on specific criteria like 'shop_id' or 'location'. ```ts useSupastashFilters({ orders: [{ column: "shop_id", operator: "eq", value: activeShopId }], inventory: [{ column: "location_id", operator: "eq", value: location }], }); ``` -------------------------------- ### Fetch Orders with Realtime Sync Source: https://github.com/0xzekea/supastash/blob/main/README.md Use the 'useSupastashData' hook to fetch 'orders' data, applying a filter for the current 'userId'. Enables realtime updates to keep the UI synchronized automatically. ```ts const { data, groupedBy } = useSupastashData("orders", { filter: { column: "user_id", operator: "eq", value: userId }, extraMapKeys: ["status"], realtime: true, // Default: true }); ``` -------------------------------- ### Test Batch Schema Fetch Function Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/batch-pull-sync.md Execute the `get_table_schemas` function in your SQL editor with an array of table names to test its functionality and verify the returned JSONB structure. ```sql SELECT public.get_table_schemas( ARRAY['inventory', 'customers', 'orders'] ); ``` -------------------------------- ### Create Function to Apply Triggers to Multiple Tables Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/replication-mode.md This SQL function automates the process of attaching the `set_arrived_at` trigger to a list of specified tables. ```sql CREATE OR REPLACE FUNCTION apply_arrival_trigger_to_tables(table_names text[]) RETURNS void AS $$ DECLARE t text; BEGIN FOREACH t IN ARRAY table_names LOOP EXECUTE format( 'CREATE TRIGGER set_arrived_at BEFORE INSERT OR UPDATE ON public.%I FOR EACH ROW EXECUTE FUNCTION enforce_server_arrival_timestamp();', t ); END LOOP; END; $$ LANGUAGE plpgsql; ``` -------------------------------- ### Enable Batch Pull Sync Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/batch-pull-sync.md Set the `useBatchPullSync` flag to `true` in your Supastash configuration to enable batch synchronization. This routes existing sync functions through the batch path. ```typescript configureSupastash({ // ... your existing config useBatchPullSync: true, }); ``` -------------------------------- ### Configure Supastash Replication Mode Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/replication-mode.md Set the replication mode during Supastash configuration. Choose between 'client-side' (legacy) or 'server-side' (recommended). ```typescript configureSupastash({ replicationMode: "client-side", // or "server-side" }); ``` -------------------------------- ### Import NetInfo for React Native Source: https://github.com/0xzekea/supastash/blob/main/README.md Import NetInfo from '@react-native-community/netinfo' when using it as a network adapter in React Native applications. ```ts import * as NetInfo from "@react-native-community/netinfo"; // React Native only ``` -------------------------------- ### getAllTables() Source: https://github.com/0xzekea/supastash/blob/main/src/shared/docs/schema-management.md Retrieves a list of all user-defined tables in the local SQLite database, excluding internal Supastash tables. ```APIDOC ### `getAllTables(): Promise` Returns a list of all user-defined tables in the local SQLite database, **excluding** internal tables used by Supastash. #### Example ```ts const tables = await getAllTables(); console.log(tables); // ["users", "orders", "transactions"] ``` #### Return - `string[]` – array of table names (excluding system/internal). - `null` – if no user tables are found. ``` -------------------------------- ### Allow Schema Reflection in Supabase Source: https://github.com/0xzekea/supastash/blob/main/README.md Run this SQL in Supabase to allow schema reflection. This function is necessary for Supastash to inspect your table schemas. ```sql create or replace function get_table_schema(table_name text) returns table(column_name text, data_type text, is_nullable text) security definer as $$ select column_name, data_type, is_nullable from information_schema.columns where table_schema = 'public' and table_name = $1; $$ language sql; grant execute on function get_table_schema(text) to anon, authenticated; ``` -------------------------------- ### Enable RLS Support with get_table_schema Function Source: https://github.com/0xzekea/supastash/blob/main/src/shared/docs/getting-started.md Run this SQL function in Supabase SQL Editor to enable Supastash to fetch column metadata, which is required for syncing, especially when RLS is enabled. ```sql create or replace function get_table_schema(table_name text) returns table( column_name text, data_type text, is_nullable text ) security definer as $$ select column_name, data_type, is_nullable from information_schema.columns where table_schema = 'public' and table_name = $1; $$ language sql; grant execute on function get_table_schema(text) to anon, authenticated; ``` -------------------------------- ### syncAllTables Source: https://github.com/0xzekea/supastash/blob/main/docs-site/docs/sync-flows.md Triggers a manual sync for all Supastash tables, regardless of polling cycles. This is great for situations like app resume, manual “Sync Now” buttons, or recovery after a failed background sync. ```APIDOC ## `syncAllTables(): Promise` ### Description Triggers a manual sync for all Supastash tables, bypassing regular polling cycles. This function is ideal for scenarios such as synchronizing data when an application resumes, implementing a "Sync Now" button, or recovering from background sync failures. ### Method `syncAllTables` ### Response #### Success Response - Returns a `Promise` that resolves when all table syncs are complete. ### Example: Sync on App Resume ```ts import { syncAllTables } from "supastash"; import { AppState } from "react-native"; useEffect(() => { const sub = AppState.addEventListener("change", async (state) => { if (state === "active") { await syncAllTables(); // sync everything when app becomes active } }); return () => sub.remove(); }, []); ``` ```