### Install PowerSync Agent Skills Source: https://docs.powersync.com/tools/ai-tools Run this command to install PowerSync-specific agent skills for AI assistants. Follow the prompts to complete the setup. ```bash npx skills add powersync-ja/agent-skills ``` -------------------------------- ### Instantiate PowerSync Database with Tokio Source: https://docs.powersync.com/intro/setup-guide This example demonstrates how to instantiate the PowerSync database using the Tokio runtime. Ensure you call `PowerSyncEnvironment::powersync_auto_extension()` and spawn async tasks appropriately before connecting. This setup is suitable for applications using Tokio. ```rust use std::sync::Arc; use isahc::config::Configurable; use isahc::HttpClient as IsahcClient; use powersync_sdk::Client as PowerSyncClient; use powersync_sdk::PowerSyncDatabase; use powersync_sdk::PowerSyncEnvironment; fn app_schema() -> &'static str { "CREATE TABLE users (id TEXT PRIMARY KEY, name TEXT)" } fn open_pool() -> Result> { ConnectionPool::open("powersync.db") } #[tokio::main] async fn main() { PowerSyncEnvironment::powersync_auto_extension() .expect("could not load PowerSync core extension"); let pool = open_pool().expect("open pool"); let client = Arc::new(IsahcClient::new()); let env = PowerSyncEnvironment::custom( client.clone(), pool, Box::new(PowerSyncEnvironment::tokio_timer()), ); let db = PowerSyncDatabase::new(env, app_schema()); db.async_tasks().spawn_with_tokio(); // Connect with a backend connector in the next step. } ``` -------------------------------- ### Install OP-SQLite Adapter (pnpm) Source: https://docs.powersync.com/client-sdks/reference/react-native-and-expo Install the recommended OP-SQLite adapter and its peer dependency with pnpm. ```bash pnpm expo install @powersync/op-sqlite @op-engineering/op-sqlite ``` -------------------------------- ### Install OP-SQLite Adapter (npm) Source: https://docs.powersync.com/client-sdks/reference/react-native-and-expo Install the recommended OP-SQLite adapter and its peer dependency with npm. ```bash npx expo install @powersync/op-sqlite @op-engineering/op-sqlite ``` -------------------------------- ### Install OP-SQLite Adapter (yarn) Source: https://docs.powersync.com/client-sdks/reference/react-native-and-expo Install the recommended OP-SQLite adapter and its peer dependency with yarn. ```bash yarn expo add @powersync/op-sqlite @op-engineering/op-sqlite ``` -------------------------------- ### Initialize PowerSync Database and Create Collection Source: https://docs.powersync.com/client-sdks/frameworks/tanstack Define your application schema, initialize the PowerSync database, and create a TanStack DB collection. This example uses TypeScript and demonstrates schema definition and collection setup. ```typescript // Other SDKs are also supported import { Schema, Table, column } from '@powersync/web'; import { createCollection } from '@tanstack/react-db'; import { powerSyncCollectionOptions } from '@tanstack/powersync-db-collection'; // Define schema and init PowerSync database const APP_SCHEMA = new Schema({ documents: new Table({ name: column.text, author: column.text, created_at: column.text, archived: column.integer }) }); const db = new PowerSyncDatabase({ database: { dbFilename: 'app.sqlite' }, schema: APP_SCHEMA }); // Optional: db.connect(connector) for backend sync // Create a TanStack DB collection (types inferred from table) const documentsCollection = createCollection( powerSyncCollectionOptions({ database: db, table: APP_SCHEMA.props.documents }) ); ``` -------------------------------- ### Install and Run Diagnostics App Locally Source: https://docs.powersync.com/tools/diagnostics-client Commands to install dependencies, build packages, and start the local development server for the PowerSync Diagnostics App. The app will be available on http://localhost:5173. ```bash pnpm install pnpm build:packages ``` ```bash pnpm dev ``` -------------------------------- ### Install PowerSync Capacitor Package Source: https://docs.powersync.com/client-sdks/reference/capacitor-api Install the PowerSync SDK for Capacitor using npm. ```bash npm install @powersync/capacitor ``` -------------------------------- ### Install and Initialize PowerSync CLI for Cloud Source: https://docs.powersync.com/intro/setup-guide Install the PowerSync CLI globally using npm, log in, and then initialize a cloud configuration. This sets up the necessary configuration files for a cloud instance. ```bash npm install -g powersync powersync login powersync init cloud ``` -------------------------------- ### Complete Powersync Stream Configuration Example Source: https://docs.powersync.com/sync/streams/queries A comprehensive example demonstrating global reference data, user-specific items with field transformations, and on-demand item details with subscription parameters and auth checks. ```yaml config: edition: 3 streams: # Global reference data (no parameters, auto-subscribed) categories: auto_subscribe: true query: SELECT id, name, CAST(sort_order AS TEXT) AS sort_order FROM categories # User's own items with transformed fields (auth parameter, auto-subscribed) my_items: auto_subscribe: true query: | SELECT id, name, metadata ->> 'status' AS status, unixepoch(created_at) AS created_at, base64(thumbnail) AS thumbnail FROM items WHERE owner_id = auth.user_id() # On-demand item details (subscription parameter with auth check) item_comments: query: | SELECT * FROM comments WHERE item_id = subscription.parameter('item_id') AND item_id IN (SELECT id FROM items WHERE owner_id = auth.user_id()) ``` -------------------------------- ### Complete Example with Global and Stream-Level CTEs Source: https://docs.powersync.com/sync/streams/ctes This example demonstrates a full configuration using both global CTEs (shared across all streams) and stream-level CTEs (specific to a single stream). It shows how to manage data access and organization. ```yaml config: edition: 3 # Global CTE - shared across all streams with: accessible_projects: | SELECT id FROM projects WHERE org_id IN (SELECT org_id FROM org_memberships WHERE user_id = auth.user_id()) OR id IN (SELECT project_id FROM project_shares WHERE shared_with = auth.user_id()) streams: # Organization-level data (auto-sync) - stream-level CTE + global CTE org_and_projects: auto_subscribe: true with: user_orgs: | SELECT org_id FROM org_memberships WHERE user_id = auth.user_id() queries: - SELECT * FROM organizations WHERE id IN user_orgs - SELECT * FROM projects WHERE id IN accessible_projects # Project details (on-demand) - uses only the global CTE project_details: queries: - | SELECT * FROM tasks WHERE project_id = subscription.parameter('project_id') AND project_id IN accessible_projects - | SELECT * FROM files WHERE project_id = subscription.parameter('project_id') AND project_id IN accessible_projects ``` -------------------------------- ### Install PowerSync CLI Globally Source: https://docs.powersync.com/tools/cli Install the PowerSync CLI globally using npm for command-line access. ```bash npm install -g powersync ``` -------------------------------- ### Swift FTS Setup Snippet Source: https://docs.powersync.com/client-sdks/full-text-search A placeholder indicating where FTS setup is handled in a Swift implementation. Refer to the linked file for the actual FTS setup code. ```swift // See https://github.com/powersync-ja/powersync-swift/blob/main/Demo/PowerSyncExample/PowerSync/SystemManager.swift#L89 ``` -------------------------------- ### Create New Expo App and Install PowerSync Source: https://docs.powersync.com/client-sdks/frameworks/expo-go-support Steps to create a new Expo application, navigate to its directory, and install the necessary PowerSync dependencies. ```bash npx create-expo-app@latest my-app ``` ```bash cd my-app && npm run ios ``` ```bash npm install @powersync/react-native @powersync/adapter-sql-js ``` -------------------------------- ### Clone and Install Demo App Dependencies Source: https://docs.powersync.com/integrations/neon Clone the PowerSync JS repository, install dependencies, build packages, and navigate to the React Neon TanStack Query Notes demo directory. ```bash git clone https://github.com/powersync-ja/powersync-js.git cd powersync-js pnpm install pnpm build:packages cd demos/react-neon-tanstack-query-notes ``` -------------------------------- ### Install and Initialize PowerSync CLI for Self-Hosted Source: https://docs.powersync.com/intro/setup-guide Install the PowerSync CLI and initialize a self-hosted configuration. This command scaffolds the configuration directory and generates a Docker Compose stack for local development. ```bash npm install -g powersync powersync init self-hosted powersync docker configure --database postgres --storage postgres ``` -------------------------------- ### Install React Native Quick SQLite Adapter (npm) Source: https://docs.powersync.com/client-sdks/reference/react-native-and-expo Install the React Native Quick SQLite adapter with npm. ```bash npx expo install @journeyapps/react-native-quick-sqlite ``` -------------------------------- ### Install Peer Dependencies with npm Source: https://docs.powersync.com/client-sdks/reference/capacitor Install the required peer dependencies for the PowerSync Capacitor SDK using npm. ```bash npm install @capacitor-community/sqlite @powersync/web @journeyapps/wa-sqlite ``` -------------------------------- ### Install Peer Dependencies with pnpm Source: https://docs.powersync.com/client-sdks/reference/capacitor Install the required peer dependencies for the PowerSync Capacitor SDK using pnpm. ```bash pnpm install @capacitor-community/sqlite @powersync/web @journeyapps/wa-sqlite ``` -------------------------------- ### Install React Native Quick SQLite Adapter (yarn) Source: https://docs.powersync.com/client-sdks/reference/react-native-and-expo Install the React Native Quick SQLite adapter with yarn. ```bash yarn expo add @journeyapps/react-native-quick-sqlite ``` -------------------------------- ### Install PowerSync Dependencies Source: https://docs.powersync.com/client-sdks/frameworks/next-js Install the PowerSync Web SDK, its peer dependency @journeyapps/wa-sqlite, and the @powersync/react package for easier integration. ```shell npm install @powersync/web @journeyapps/wa-sqlite @powersync/react ``` ```shell yarn add @powersync/web @journeyapps/wa-sqlite @powersync/react ``` ```shell pnpm install @powersync/web @journeyapps/wa-sqlite @powersync/react ``` -------------------------------- ### Install React Native Quick SQLite Adapter (pnpm) Source: https://docs.powersync.com/client-sdks/reference/react-native-and-expo Install the React Native Quick SQLite adapter with pnpm. ```bash pnpm expo install @journeyapps/react-native-quick-sqlite ``` -------------------------------- ### .NET IPFS Storage Adapter Example Source: https://docs.powersync.com/client-sdks/advanced/attachments Provides a C# implementation of an IPFS storage adapter for Powersync. This example shows how to upload files to IPFS, store their CIDs in a backend, and retrieve them for download or deletion. ```csharp // Example: IPFS remote storage public sealed class IPFSStorageAdapter(HttpClient http) : IRemoteStorageAdapter { public async Task UploadFileAsync(Stream fileData, Attachment attachment) { // Upload the file to IPFS via your backend using var content = new StreamContent(fileData); var resp = await http.PostAsync("/api/ipfs/add", content); resp.EnsureSuccessStatusCode(); var cid = await resp.Content.ReadAsStringAsync(); // Store the CID so it can be retrieved for downloads await http.PostAsJsonAsync("/api/ipfs-cids", new { attachmentId = attachment.Id, cid }); } public async Task DownloadFileAsync(Attachment attachment) { // Retrieve the CID from your backend var cid = await http.GetStringAsync($"/api/ipfs-cids/{attachment.Id}"); return await http.GetStreamAsync($"/api/ipfs/cat/{cid}"); } public async Task DeleteFileAsync(Attachment attachment) { // IPFS is immutable; unpin and remove the record from your backend var resp = await http.DeleteAsync($"/api/ipfs-cids/{attachment.Id}"); if (resp.StatusCode != HttpStatusCode.NotFound) resp.EnsureSuccessStatusCode(); } } ``` -------------------------------- ### Start PowerSync Service (Self-Hosted Docker) Source: https://docs.powersync.com/intro/setup-guide Start the PowerSync Service using Docker Compose after configuring it for self-hosting. Use `powersync status` to verify that the service is running. ```bash powersync docker start ``` -------------------------------- ### Start Docker Compose Stack Source: https://docs.powersync.com/tools/local-development This command starts the Docker Compose stack defined in your `docker-compose.yaml` file, bringing up all the configured services for local PowerSync development. ```bash docker compose up ``` -------------------------------- ### Complete Backend Example with Express and PostgreSQL Source: https://docs.powersync.com/handling-writes/custom-conflict-resolution A full Node.js backend example using Express and PostgreSQL to handle batched operations with custom logic for different tables. Includes transaction management and error handling. ```javascript import express from 'express'; import { Pool } from 'pg'; const app = express(); const pool = new Pool({ connectionString: process.env.DATABASE_URL }); app.post('/api/data', async (req, res) => { const { batch } = req.body; const userId = req.user.id; // From auth middleware const db = await pool.connect(); try { await db.query('BEGIN'); for (const operation of batch) { // Choose strategy based on table if (operation.table === 'orders') { await handleOrderOperation(db, operation, userId); } else if (operation.table === 'tasks') { await handleTaskOperation(db, operation, userId); } else { // Default handling await handleGenericOperation(db, operation); } } await db.query('COMMIT'); res.json({ success: true }); } catch (error) { await db.query('ROLLBACK'); console.error('Operation failed:', error); res.status(500).json({ error: error.message }); } finally { db.release(); } }); async function handleOrderOperation(db, op, userId) { if (op.op === 'PUT') { // Use business rule validation (Strategy 4) const result = await validateOrderUpdate(db, op); if (result.conflict) { throw new Error(result.message); } } else if (op.op === 'PATCH') { await handleOrderPatch(db, op, userId); } else if (op.op === 'DELETE') { await handleOrderDelete(db, op); } } async function handleTaskOperation(db, op, userId) { if (op.op === 'PUT' || op.op === 'PATCH') { // Use timestamp detection with conflict recording (Strategy 1 + 5) const result = await handleUpdateWithConflictRecording(db, op, userId); if (result.conflict && result.conflict !== 'recorded') { console.warn('Conflict detected:', result); } } else if (op.op === 'DELETE') { await db.query('DELETE FROM tasks WHERE id = $1', [op.id]); } } async function handleGenericOperation(db, op) { // Default last-write-wins if (op.op === 'PUT') { const fields = Object.keys(op.opData); const values = Object.values(op.opData); const placeholders = fields.map((_, i) => `$${i + 1}`).join(', '); const updates = fields.map((f, i) => `${f} = $${i + 1}`).join(', '); await db.query( `INSERT INTO ${op.table} (id, ${fields.join(', ')})\n VALUES ($${fields.length + 1}, ${placeholders})\n ON CONFLICT (id) DO UPDATE SET ${updates}`, [...values, op.id] ); } else if (op.op === 'PATCH') { const fields = Object.keys(op.opData); const values = Object.values(op.opData); const updates = fields.map((f, i) => `${f} = $${i + 1}`).join(', '); await db.query( `UPDATE ${op.table} SET ${updates} WHERE id = $${fields.length + 1}`, [...values, op.id] ); } else if (op.op === 'DELETE') { await db.query(`DELETE FROM ${op.table} WHERE id = $1`, [op.id]); } } app.listen(3000, () => { console.log('Backend listening on port 3000'); }); ``` -------------------------------- ### Manual JWKS URI Example Source: https://docs.powersync.com/configuration/auth/supabase-auth Example of a JWKS URI for manual configuration, typically used when PowerSync cannot auto-detect your Supabase project, such as with local development. ```text http://localhost:54321/auth/v1/.well-known/jwks.json ``` -------------------------------- ### Install PowerSync Web SDK and Dependencies Source: https://docs.powersync.com/client-sdks/reference/javascript-web-api Commands to install the core PowerSync web package and its required peer dependency, WA-SQLite, using npm. ```bash npm install @powersync/web npm install @journeyapps/wa-sqlite ``` -------------------------------- ### PowerSync CLI Command Mapping: Init and Instance Setup Source: https://docs.powersync.com/tools/cli Maps the previous 'npx powersync init' and 'powersync instance set' commands to their new equivalents for authentication and instance linking. ```bash powersync login ``` ```bash powersync init cloud ``` ```bash powersync pull instance --project-id=... --instance-id=... ``` ```bash powersync link cloud --instance-id= --project-id= ``` -------------------------------- ### Install Powersync Attachment Storage for React Native Source: https://docs.powersync.com/client-sdks/advanced/attachments Install the necessary package for attachment storage in React Native projects. Expo projects require additional setup with expo-file-system, while bare React Native projects need @dr.pogodin/react-native-fs. ```bash # Built into @powersync/web, @powersync/node, and @powersync/react-native. # React Native requires an additional storage adapter: # npm install @powersync/attachments-storage-react-native # Expo projects (v54+) also require: # npm install expo-file-system # Bare React Native projects also require: # npm install @dr.pogodin/react-native-fs ``` -------------------------------- ### Setup PowerSync with Drizzle Source: https://docs.powersync.com/client-sdks/orms/js/drizzle Wrap your PowerSync database with Drizzle to use Drizzle's query API. This example shows defining Drizzle schema and relations, then initializing PowerSync and wrapping it. ```javascript import { wrapPowerSyncWithDrizzle } from '@powersync/drizzle-driver'; import { PowerSyncDatabase } from '@powersync/web'; import { relations } from 'drizzle-orm'; import { index, integer, sqliteTable, text } from 'drizzle-orm/sqlite-core'; import { AppSchema } from './schema'; export const lists = sqliteTable('lists', { id: text('id'), name: text('name') }); export const todos = sqliteTable('todos', { id: text('id'), description: text('description'), list_id: text('list_id'), created_at: text('created_at') }); export const listsRelations = relations(lists, ({ one, many }) => ({ todos: many(todos) })); export const todosRelations = relations(todos, ({ one, many }) => ({ list: one(lists, { fields: [todos.list_id], references: [lists.id] }) })); export const drizzleSchema = { lists, todos, listsRelations, todosRelations }; // As an alternative to manually defining a PowerSync schema, generate the local PowerSync schema from the Drizzle schema with the `DrizzleAppSchema` constructor: // import { DrizzleAppSchema } from '@powersync/drizzle-driver'; // export const AppSchema = new DrizzleAppSchema(drizzleSchema); // // This is optional, but recommended, since you will only need to maintain one schema on the client-side // Read on to learn more. export const powerSyncDb = new PowerSyncDatabase({ database: { dbFilename: 'test.sqlite' }, schema: AppSchema }); // This is the DB you will use in queries export const db = wrapPowerSyncWithDrizzle(powerSyncDb, { schema: drizzleSchema }); ``` -------------------------------- ### Initialize Self-Hosted Instance and Link CLI Source: https://docs.powersync.com/tools/cli Scaffold a self-hosted PowerSync instance, configure its service file, link the CLI to the running API, and check the status. ```bash powersync init self-hosted # Edit powersync/service.yaml with instance details and api.tokens powersync link self-hosted --api-url https://powersync.example.com powersync status ``` -------------------------------- ### Start Serverpod Backend Source: https://docs.powersync.com/integrations/serverpod Run the Serverpod backend using the provided command. ```bash dart run bin/main.dart ``` -------------------------------- ### Log in and Initialize Cloud Instance Source: https://docs.powersync.com/tools/cli Use these commands to log in to your PowerSync account and scaffold a new cloud instance. ```bash powersync login powersync init cloud ``` -------------------------------- ### Install PowerSync Nuxt Dependencies Source: https://docs.powersync.com/client-sdks/frameworks/nuxt Install the Nuxt PowerSync module using npm or pnpm. For pnpm, ensure peer dependencies are installed explicitly. ```shell npm install @powersync/nuxt ``` ```shell pnpm add @powersync/nuxt @powersync/vue @powersync/web ``` -------------------------------- ### Run the Demo App Source: https://docs.powersync.com/integrations/neon Start the development server for the demo application using pnpm. This command is used to run the local development environment. ```bash pnpm dev ``` -------------------------------- ### Install PowerSync Tauri Plugin with pnpm Source: https://docs.powersync.com/intro/setup-guide Install the PowerSync Tauri plugin using pnpm. Note that this package is only available under the @powersync/ scope and cannot be installed with `tauri add`. ```bash pnpm install @powersync/tauri-plugin ``` -------------------------------- ### Setup Web Assets Source: https://docs.powersync.com/client-sdks/frameworks/flutter-web-support Run this command in your application's root folder to download necessary web assets like sqlite3.wasm and worker scripts. ```bash dart run powersync:setup_web ``` -------------------------------- ### Install PowerSync Node.js Package Source: https://docs.powersync.com/client-sdks/reference/node-api Installs the PowerSync Node.js SDK and the better-sqlite3 driver. Both packages include install scripts for compiling or downloading necessary binaries. ```bash npm install @powersync/node better-sqlite3 ``` -------------------------------- ### Initialize and Start PowerSync Docker Source: https://docs.powersync.com/tools/cli Initializes a self-hosted PowerSync instance and configures Docker for local development. Use this to set up your local PowerSync service. ```bash powersync init self-hosted powersync docker configure # links to the local API automatically powersync docker start ``` -------------------------------- ### Connector Implementation Example Source: https://docs.powersync.com/client-sdks/reference/node An example implementation of the `PowerSyncBackendConnector` interface in TypeScript for a Node.js environment. ```APIDOC ## Connector Implementation Example ### Description This example demonstrates how to implement the `PowerSyncBackendConnector` interface. It includes placeholder logic for `fetchCredentials` and `uploadData`. ### Class `Connector` ### Constructor Initializes the connector, typically setting up a connection client for server communication. ```javascript constructor() { // set up a connection to your server for uploads this.serverConnectionClient = TODO; } ``` ### Methods #### `fetchCredentials()` ```javascript async fetchCredentials() { // Implement fetchCredentials to obtain a JWT from your authentication service. // See https://docs.powersync.com/configuration/auth/overview return { endpoint: '[Your PowerSync instance URL or self-hosted endpoint]', // Use a development token (see Authentication Setup https://docs.powersync.com/configuration/auth/development-tokens) to get up and running quickly token: 'An authentication token' }; } ``` #### `uploadData(database)` ```javascript async uploadData(database) { // Implement uploadData to send local changes to your backend service. // You can omit this method if you only want to sync data from the database to the client // See example implementation here: https://docs.powersync.com/client-sdks/reference/javascript-web#3-integrate-with-your-backend } ``` ``` -------------------------------- ### Run Postinstall Script Source: https://docs.powersync.com/client-sdks/frameworks/next-js Execute the postinstall script to copy the pre-bundled worker files to public/@powersync/. ```shell npm run postinstall ``` ```shell yarn postinstall ``` ```shell pnpm postinstall ``` -------------------------------- ### Run the Demo App Source: https://docs.powersync.com/integrations/supabase Ensure Melos is installed, then bootstrap the project and run the Flutter application. ```bash # Ensure you have [melos](https://melos.invertase.dev/~melos-latest/getting-started) installed. melos bootstrap flutter run ``` -------------------------------- ### Link and Create Cloud Instance Source: https://docs.powersync.com/tools/cli Link your local CLI to a new cloud instance, specifying project and optionally organization IDs. ```bash powersync link cloud --create --project-id= ``` -------------------------------- ### Instantiate PowerSync Database (Common SDK) Source: https://docs.powersync.com/client-sdks/reference/dotnet Use this snippet to initialize the PowerSync database with basic options for the Common SDK. Ensure you have the necessary PowerSync.Common.Client namespace imported. ```csharp using PowerSync.Common.Client; class Demo { static async Task Main() { var db = new PowerSyncDatabase(new PowerSyncDatabaseOptions { Database = new SQLOpenOptions { DbFilename = "tododemo.db" }, Schema = AppSchema.PowerSyncSchema, }); await db.Init(); } } ``` -------------------------------- ### Install wa-sqlite Peer Dependency (pnpm) Source: https://docs.powersync.com/client-sdks/reference/javascript-web Install the required @journeyapps/wa-sqlite peer dependency using pnpm. ```bash pnpm install @journeyapps/wa-sqlite ``` -------------------------------- ### Install wa-sqlite Peer Dependency (yarn) Source: https://docs.powersync.com/client-sdks/reference/javascript-web Install the required @journeyapps/wa-sqlite peer dependency using yarn. ```bash yarn add @journeyapps/wa-sqlite ``` -------------------------------- ### Install wa-sqlite Peer Dependency (npm) Source: https://docs.powersync.com/client-sdks/reference/javascript-web Install the required @journeyapps/wa-sqlite peer dependency using npm. ```bash npm install @journeyapps/wa-sqlite ``` -------------------------------- ### Install Kysely Driver Source: https://docs.powersync.com/client-sdks/frameworks/nuxt Install the `@powersync/kysely-driver` package to enable type-safe query building with Kysely ORM. ```shell npm install @powersync/kysely-driver ``` ```shell pnpm add @powersync/kysely-driver ``` -------------------------------- ### Tasks Query After Restructuring with Subscription Parameters Source: https://docs.powersync.com/debugging/troubleshooting This is the 'After' example. It uses subscription parameters to create buckets per active client subscription, reducing the bucket count to one per active subscription (e.g., 3 projects open = 3 buckets). ```powersync streams: project_tasks: with: user_projects: SELECT id FROM projects WHERE org_id IN (SELECT org_id FROM org_membership WHERE user_id = auth.user_id()) query: SELECT * FROM tasks WHERE project_id = subscription.parameter('project_id') AND project_id IN user_projects ``` -------------------------------- ### smol Runtime Setup Source: https://docs.powersync.com/client-sdks/reference/rust Configures PowerSync with reqwest client, a connection pool, and async_io timer, then spawns tasks using smol's executor. ```Rust use powersync::PowerSyncDatabase; async fn start_app() { let pool = open_pool().expect("open pool"); let env = PowerSyncEnvironment::custom( reqwest::Client::new(), pool, // Use the async_io crate to implement timers in PowerSync PowerSyncEnvironment::async_io_timer(), ); let db = PowerSyncDatabase::new(env, schema::app_schema()); // TODO: Use a custom multi-threaded executor instead of the default let tasks = db.async_tasks().spawn_with(smol::spawn); for task in tasks { // The task will automatically stop once the database is dropped, but we // want to keep it running until then. task.detach(); } } fn main() { PowerSyncEnvironment::powersync_auto_extension() .expect("could not load PowerSync core extension"); smol::block_on(start_app()); } ``` -------------------------------- ### Install SQL.js Adapter in Existing App Source: https://docs.powersync.com/client-sdks/frameworks/expo-go-support Install the SQL.js adapter for PowerSync into an existing Expo application. ```bash npm install @powersync/adapter-sql-js ``` -------------------------------- ### Install SQLite Peer Dependency Source: https://docs.powersync.com/client-sdks/reference/react-native-api Installs the required SQLite peer dependency for the PowerSync React Native SDK. By default, it uses `@journeyapps/react-native-quick-sqlite`. Ensure this or an alternative SQLite implementation is installed. ```bash npx expo install @journeyapps/react-native-quick-sqlite ``` -------------------------------- ### Install Peer Dependencies with yarn Source: https://docs.powersync.com/client-sdks/reference/capacitor Install the required peer dependencies for the PowerSync Capacitor SDK using yarn. ```bash yarn add @capacitor-community/sqlite @powersync/web @journeyapps/wa-sqlite ``` -------------------------------- ### Set up Self-Hosted Postgres for PowerSync with Docker Source: https://docs.powersync.com/intro/setup-guide Creates a Docker network, runs a Postgres instance with logical replication enabled, and configures a PowerSync user and publication. This is for self-hosting PowerSync with a Postgres source. ```bash # 1. Create a Docker network (if not already created) # This allows various PowerSync containers to communicate with each other docker network create powersync-network # 2. Run Postgres source database with logical replication enabled (required for PowerSync) docker run -d \ --name powersync-postgres \ --network powersync-network \ -e POSTGRES_PASSWORD="my_secure_password" \ -p 5432:5432 \ postgres:18 \ postgres -c wal_level=logical # 3. Configure PowerSync user and publication # This creates a PowerSync database user/role with replication privileges and read-only access to your tables # Read-only (SELECT) access is also granted to all future tables (to cater for schema additions) # It also creates a publication to replicate tables. The publication must be named "powersync" docker exec -it powersync-postgres psql -U postgres -c " CREATE ROLE powersync_role WITH REPLICATION BYPASSRLS LOGIN PASSWORD 'myhighlyrandompassword'; GRANT SELECT ON ALL TABLES IN SCHEMA public TO powersync_role; ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO powersync_role; CREATE PUBLICATION powersync FOR ALL TABLES;" ``` -------------------------------- ### Create Directory for PowerSync Service Config Source: https://docs.powersync.com/intro/setup-guide Create a new directory and navigate into it to set up the configuration files for a manual self-hosted PowerSync Service instance. ```bash mkdir powersync-service && cd powersync-service ``` -------------------------------- ### Install TanStackDB-PowerSync Collection (pnpm) Source: https://docs.powersync.com/client-sdks/frameworks/tanstack Install the necessary packages for using TanStack DB with PowerSync via pnpm. ```bash pnpm install @tanstack/powersync-db-collection @powersync/web @journeyapps/wa-sqlite ``` -------------------------------- ### Install TanStackDB-PowerSync Collection (yarn) Source: https://docs.powersync.com/client-sdks/frameworks/tanstack Install the necessary packages for using TanStack DB with PowerSync via yarn. ```bash yarn add @tanstack/powersync-db-collection @powersync/web @journeyapps/wa-sqlite ``` -------------------------------- ### Install PowerSync Web SDK (npm) Source: https://docs.powersync.com/client-sdks/reference/javascript-web Use this command to add the PowerSync Web NPM package to your project using npm. ```bash npm install @powersync/web ``` -------------------------------- ### Install TanStackDB-PowerSync Collection (npm) Source: https://docs.powersync.com/client-sdks/frameworks/tanstack Install the necessary packages for using TanStack DB with PowerSync via npm. ```bash npm install @tanstack/powersync-db-collection @powersync/web @journeyapps/wa-sqlite ``` -------------------------------- ### Manual JWKS Configuration Example Source: https://docs.powersync.com/installation/authentication-setup/supabase-auth Configure PowerSync with a manual JWKS URI and JWT Audience when auto-detection is not possible, such as with self-hosted Supabase instances. ```yaml client_auth: supabase: false jwks_uri: "http://localhost:54321/auth/v1/.well-known/jwks.json" jwt_audience: "authenticated" ``` -------------------------------- ### Instantiate PowerSync for Rust Source: https://docs.powersync.com/intro/setup-guide Prepare to instantiate the PowerSync database for Rust applications. This snippet outlines the initial setup steps required before opening a connection pool. ```rust // 1. Process setup: register PowerSync extension early (e.g. in main()). // 2. Open a connection pool, create env, then database. Spawn async tasks // before connecting (see Connect step). Requires powersync with tokio feature. use powersync::{ConnectionPool, PowerSyncDatabase, error::PowerSyncError}; use powersync::env::PowerSyncEnvironment; use std::sync::Arc; use http_client::IsahcClient; fn open_pool() -> Result { ``` -------------------------------- ### Instantiate PowerSync for .NET - Common Source: https://docs.powersync.com/intro/setup-guide Instantiate the PowerSync database for common .NET applications. This example shows basic initialization with schema and database options. ```csharp using PowerSync.Common.Client; class Demo { static async Task Main() { var db = new PowerSyncDatabase(new PowerSyncDatabaseOptions { Database = new SQLOpenOptions { DbFilename = "tododemo.db" }, Schema = AppSchema.PowerSyncSchema, }); await db.Init(); } } ``` -------------------------------- ### Install Specific PowerSync Version Source: https://docs.powersync.com/client-sdks/reference/dotnet Use the --version flag to install a specific version of the PowerSync.Common NuGet package. ```bash dotnet add package PowerSync.Common --version ``` -------------------------------- ### Run JavaScript Web App Source: https://docs.powersync.com/integrations/supabase/guide Command to start the development server for the JavaScript Web demo app. ```bash # In `demos/react-supabase-todolist`: pnpm dev ``` -------------------------------- ### Tasks Query Before Restructuring Source: https://docs.powersync.com/debugging/troubleshooting This is the 'Before' example showing a subquery that returns all user projects, leading to 50 buckets for 50 projects. ```powersync streams: project_tasks: with: user_projects: SELECT id FROM projects WHERE org_id IN (SELECT org_id FROM org_membership WHERE user_id = auth.user_id()) query: SELECT * FROM tasks WHERE project_id IN user_projects ``` -------------------------------- ### Powersync Attachment Queue Installation (.NET) Source: https://docs.powersync.com/client-sdks/advanced/attachments The PowerSync.Common package (v0.1.2+) includes attachment queue functionality, requiring no additional installation. ```csharp # Built into PowerSync.Common (v0.1.2+). No additional installation needed. ``` -------------------------------- ### Install better-sqlite3 Peer Dependency Source: https://docs.powersync.com/client-sdks/reference/node Install the recommended 'better-sqlite3' package as a peer dependency for the PowerSync SDK. This is required for database operations. ```bash npm install better-sqlite3 ``` ```bash yarn add better-sqlite3 ``` ```bash pnpm install better-sqlite3 ``` -------------------------------- ### Instantiate PowerSync Database (MAUI SDK) Source: https://docs.powersync.com/client-sdks/reference/dotnet This snippet demonstrates initializing the PowerSync database for MAUI applications, ensuring the database file is stored in a platform-appropriate location using a factory pattern. It requires imports from PowerSync.Common.Client, PowerSync.Common.MDSQLite, and PowerSync.Maui.SQLite. ```csharp using PowerSync.Common.Client; using PowerSync.Common.MDSQLite; using PowerSync.Maui.SQLite; class Demo { static async Task Main() { // Ensures the DB file is stored in a platform appropriate location var dbPath = Path.Combine(FileSystem.AppDataDirectory, "maui-example.db"); var factory = new MAUISQLiteDBOpenFactory(new MDSQLiteOpenFactoryOptions() { DbFilename = dbPath }); var Db = new PowerSyncDatabase(new PowerSyncDatabaseOptions() { Database = factory, // Supply a factory Schema = AppSchema.PowerSyncSchema, }); await db.Init(); } } ``` -------------------------------- ### Run Swift App Source: https://docs.powersync.com/integrations/supabase/guide Instructions for running the Swift app using Xcode. ```bash # Run the app using XCode. ```