### Initialize PowerSync Cloud Instance via CLI Source: https://github.com/powersync-ja/powersync-docs/blob/main/intro/setup-guide.mdx Install the PowerSync CLI, log in, and scaffold a cloud configuration. Then, link your local setup to a cloud instance by providing your project ID. ```bash npm install -g powersync powersync login powersync init cloud ``` ```bash powersync link cloud --create --project-id= ``` -------------------------------- ### Example SQL for Initial Data Setup Source: https://github.com/powersync-ja/powersync-docs/blob/main/maintenance-ops/compacting-buckets.mdx This SQL sequence demonstrates inserting a rarely changed row alongside many frequently changing rows, illustrating a scenario where defragmentation becomes necessary. ```sql INSERT INTO lists(name) VALUES('a'); INSERT INTO lists (name) SELECT 'b' FROM generate_series(1, 50000); DELETE FROM lists WHERE name = 'b'; ``` -------------------------------- ### Install PowerSync Agent Skills Source: https://github.com/powersync-ja/powersync-docs/blob/main/tools/ai-tools.mdx Run this command in your terminal to install the PowerSync agent skills. Follow the prompts to complete the setup. ```bash npx skills add powersync-ja/agent-skills ``` -------------------------------- ### .NET Installation Source: https://github.com/powersync-ja/powersync-docs/blob/main/intro/setup-guide.mdx Install the PowerSync SDK for .NET applications. ```csharp dotnet add package PowerSync.Client ``` -------------------------------- ### Setup PowerSync Database with Drizzle Source: https://github.com/powersync-ja/powersync-docs/blob/main/client-sdks/orms/js/drizzle.mdx Initialize the PowerSync database and wrap it with Drizzle for querying. This example demonstrates defining Drizzle tables, relations, and integrating with PowerSync. ```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 }); ``` -------------------------------- ### Node.js Installation Source: https://github.com/powersync-ja/powersync-docs/blob/main/intro/setup-guide.mdx Install the PowerSync SDK for Node.js applications. ```bash npm install @powersync/node ``` -------------------------------- ### JavaScript/Web Installation Source: https://github.com/powersync-ja/powersync-docs/blob/main/intro/setup-guide.mdx Install the PowerSync SDK for JavaScript and web applications. ```bash npm install @powersync/web ``` -------------------------------- ### Flutter Installation Source: https://github.com/powersync-ja/powersync-docs/blob/main/intro/setup-guide.mdx Install the PowerSync SDK for Flutter applications. ```bash flutter pub add powersync ``` -------------------------------- ### Capacitor Installation Source: https://github.com/powersync-ja/powersync-docs/blob/main/intro/setup-guide.mdx Install the PowerSync SDK for Capacitor applications. ```bash npm install @powersync/capacitor npx cap sync ``` -------------------------------- ### Install Melos and Bootstrap Project Source: https://github.com/powersync-ja/powersync-docs/blob/main/integrations/supabase/guide.mdx Ensure Melos is installed and then bootstrap the project. ```bash melos bootstrap flutter run ``` -------------------------------- ### Rust Installation Source: https://github.com/powersync-ja/powersync-docs/blob/main/intro/setup-guide.mdx Install the PowerSync SDK for Rust applications. ```rust [dependencies] powersync-client = "0.1.0" ``` -------------------------------- ### Client Parameters Sync Rules Example Source: https://github.com/powersync-ja/powersync-docs/blob/main/sync/streams/migration.mdx Sync Rules example demonstrating the use of global client parameters to pass dynamic values. ```yaml bucket_definitions: posts: parameters: SELECT (request.parameters() ->> 'current_page') as page_number data: - SELECT * FROM posts WHERE page_number = bucket.page_number ``` -------------------------------- ### Install SQL.js Adapter for Existing App Source: https://github.com/powersync-ja/powersync-docs/blob/main/client-sdks/frameworks/expo-go-support.mdx Install the SQL.js adapter for PowerSync in an existing application. ```bash npm install @powersync/adapter-sql-js ``` -------------------------------- ### Tauri Installation Source: https://github.com/powersync-ja/powersync-docs/blob/main/intro/setup-guide.mdx Install the PowerSync SDK for Tauri applications. ```bash npm install @powersync/tauri ``` -------------------------------- ### Start Serverpod Backend Source: https://github.com/powersync-ja/powersync-docs/blob/main/integrations/serverpod.mdx Command to start the Serverpod backend. Ensure your Serverpod backend and PowerSync are running before connecting clients. ```bash dart run bin/main.dart ``` -------------------------------- ### Install PowerSync SDK Source: https://github.com/powersync-ja/powersync-docs/blob/main/client-sdks/reference/dotnet.mdx Install the PowerSync SDK using the NuGet package manager. ```csharp dotnet add package PowerSync.Common ``` -------------------------------- ### Install Dependencies Source: https://github.com/powersync-ja/powersync-docs/blob/main/CONTRIBUTING.md Enable Corepack and install project dependencies using pnpm. ```bash corepack enable pnpm install ``` -------------------------------- ### React Native Installation Source: https://github.com/powersync-ja/powersync-docs/blob/main/intro/setup-guide.mdx Install the PowerSync SDK for React Native applications. ```bash npm install @powersync/react-native npx pod-install ``` -------------------------------- ### Kotlin Installation Source: https://github.com/powersync-ja/powersync-docs/blob/main/intro/setup-guide.mdx Install the PowerSync SDK for Kotlin (Android) applications. ```kotlin implementation("com.powersync:powersync-android:0.1.0") ``` -------------------------------- ### Swift Installation Source: https://github.com/powersync-ja/powersync-docs/blob/main/intro/setup-guide.mdx Install the PowerSync SDK for Swift (iOS) applications. ```swift Package.dependencies.append(.package(url: "https://github.com/powersync-com/powersync-swift", from: "0.1.0")) ``` -------------------------------- ### Install PowerSync.Common for Desktop/Server Source: https://github.com/powersync-ja/powersync-docs/blob/main/snippets/dotnet/installation.mdx Installs the PowerSync.Common NuGet package, which is required for desktop, server, and binary use-cases, including WPF applications. ```bash dotnet add package PowerSync.Common ``` -------------------------------- ### Install React Native Quick SQLite Adapter Source: https://github.com/powersync-ja/powersync-docs/blob/main/snippets/react-native/installation.mdx Installs the battle-tested React Native Quick SQLite adapter for PowerSync. ```bash npx expo install @journeyapps/react-native-quick-sqlite ``` ```bash yarn expo add @journeyapps/react-native-quick-sqlite ``` ```bash pnpm expo install @journeyapps/react-native-quick-sqlite ``` -------------------------------- ### Install PowerSync CLI Globally Source: https://github.com/powersync-ja/powersync-docs/blob/main/tools/cli.mdx Install the PowerSync CLI globally using npm for command-line access. ```bash npm install -g powersync ``` -------------------------------- ### Sync Streams Example: User Lists Source: https://github.com/powersync-ja/powersync-docs/blob/main/architecture/powersync-service.mdx This example demonstrates how Sync Streams implicitly create buckets based on stream definitions and queries. No direct bucket management is required. ```yaml streams: user_lists: auto_subscribe: true query: SELECT * FROM lists WHERE owner_id = auth.user_id() ``` -------------------------------- ### Complete Backend Example with PostgreSQL (Node.js + Express) Source: https://github.com/powersync-ja/powersync-docs/blob/main/handling-writes/custom-conflict-resolution.mdx A full backend example using Express and PostgreSQL to handle batched operations, with specific strategies for 'orders' and 'tasks' tables, and a generic fallback. ```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'); }); ``` -------------------------------- ### Start Docker Compose Stack Source: https://github.com/powersync-ja/powersync-docs/blob/main/tools/local-development.mdx This command starts the Docker Compose stack defined in your `docker-compose.yaml` file, bringing up all the defined services including PowerSync, PostgreSQL, and MongoDB. ```bash docker compose up ``` -------------------------------- ### Data with Subqueries Sync Rules Example Source: https://github.com/powersync-ja/powersync-docs/blob/main/sync/streams/migration.mdx Sync Rules example for data with subqueries, using bucket parameters to link related data. ```yaml bucket_definitions: owned_lists: parameters: | SELECT id as list_id FROM lists WHERE owner_id = request.user_id() data: - SELECT * FROM lists WHERE lists.id = bucket.list_id - SELECT * FROM todos WHERE todos.list_id = bucket.list_id ``` -------------------------------- ### Complete Example with Global and Stream-Level CTEs Source: https://github.com/powersync-ja/powersync-docs/blob/main/sync/streams/ctes.mdx This example demonstrates a full configuration using both global CTEs for shared logic and stream-level CTEs for stream-specific needs. Global CTEs are defined at the top level and accessible by all streams, while stream-level CTEs are local to a specific stream. ```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 ``` -------------------------------- ### Sync Rules Example with Time Parameter Source: https://github.com/powersync-ja/powersync-docs/blob/main/sync/advanced/sync-data-by-time.mdx This example shows a legacy Sync Rules configuration attempting to filter data based on a 'start_at' parameter. Similar to Sync Streams, range operators are not supported for parameters. ```yaml bucket_definitions: issues_after_start_date: parameters: SELECT request.parameters() ->> 'start_at' as start_at data: SELECT * FROM issues WHERE updated_at > bucket.start_date ``` -------------------------------- ### Create PowerSync Service (Basic Setup) Source: https://github.com/powersync-ja/powersync-docs/blob/main/maintenance-ops/self-hosting/aws-ecs.mdx This command deploys a single instance running both replication and API processes. It is not recommended for production due to potential sync rule lock errors during updates. ```bash aws ecs create-service \ --cluster powersync-cluster \ --service-name powersync-service \ --task-definition powersync-service \ --desired-count 1 \ --launch-type FARGATE \ --network-configuration "awsvpcConfiguration={ subnets=[$PRIVATE_SUBNET_1,$PRIVATE_SUBNET_2], securityGroups=[$ECS_SG], assignPublicIp=DISABLED }" \ --load-balancers "targetGroupArn=$TG_ARN,containerName=powersync,containerPort=8080" \ --health-check-grace-period-seconds 120 \ --deployment-configuration "minimumHealthyPercent=0,maximumPercent=100" ``` -------------------------------- ### Install .NET Attachment Dependencies Source: https://github.com/powersync-ja/powersync-docs/blob/main/client-sdks/advanced/attachments.mdx The PowerSync .NET SDK includes attachment support starting from version 0.1.2. No additional installation is needed. ```bash # Built into PowerSync.Common (v0.1.2+). No additional installation needed. ``` -------------------------------- ### Install Kotlin Attachment Dependencies Source: https://github.com/powersync-ja/powersync-docs/blob/main/client-sdks/advanced/attachments.mdx The PowerSync Kotlin SDK includes attachment support starting from version 1.0.0. No additional installation is needed. ```kotlin // Built into the PowerSync Kotlin SDK (v1.0.0+). No additional installation needed. ``` -------------------------------- ### Sync Capacitor Project Source: https://github.com/powersync-ja/powersync-docs/blob/main/snippets/capacitor/installation.mdx After installing packages, run this command to sync your Capacitor project. ```bash npx cap sync ``` -------------------------------- ### Install Swift Attachment Dependencies Source: https://github.com/powersync-ja/powersync-docs/blob/main/client-sdks/advanced/attachments.mdx The PowerSync Swift SDK includes attachment support starting from version 1.0.0. No additional installation is needed. ```swift // Built into the PowerSync Swift SDK (v1.0.0+). No additional installation needed. ``` -------------------------------- ### Start Local Docs Server Source: https://github.com/powersync-ja/powersync-docs/blob/main/CONTRIBUTING.md Run the local development server to preview documentation changes. ```bash pnpm dev ``` -------------------------------- ### Install Dart/Flutter Attachment Dependencies Source: https://github.com/powersync-ja/powersync-docs/blob/main/client-sdks/advanced/attachments.mdx The PowerSync Dart/Flutter SDK includes attachment support starting from version 1.16.0. No additional installation is needed. ```bash # Built into the powersync package (v1.16.0+). No additional installation needed. ``` -------------------------------- ### Initialize and Start Local Docker Environment Source: https://github.com/powersync-ja/powersync-docs/blob/main/tools/cli.mdx Use these commands to set up a self-hosted PowerSync service and its dependencies in a local Docker environment for development. ```bash powersync init self-hosted powersync docker configure powersync docker start ``` -------------------------------- ### Watch Query in Swift Source: https://github.com/powersync-ja/powersync-docs/blob/main/client-sdks/usage-examples.mdx Example of watching a query in Swift. Requires PowerSync SDK setup. ```swift import PowerSync func watchQuery() { let powersync = PowerSync.shared let subscription = powersync.watchQuery("SELECT id, name FROM users WHERE id = ?", parameters: [userId]) subscription.stream.sink { print("Users updated: \($0)") } } ``` -------------------------------- ### Clone Flutter Demo App Source: https://github.com/powersync-ja/powersync-docs/blob/main/integrations/supabase/guide.mdx Clone the PowerSync Dart demo app for Flutter to get started. ```bash git clone https://github.com/powersync-ja/powersync.dart.git cd powersync.dart/demos/supabase-todolist/ ``` -------------------------------- ### Complete Stream Configuration Example Source: https://github.com/powersync-ja/powersync-docs/blob/main/sync/streams/queries.mdx A comprehensive configuration demonstrating global reference data, user-specific items with field transformations, and on-demand item details with authentication 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()) ``` -------------------------------- ### Log in and Initialize Cloud Instance Source: https://github.com/powersync-ja/powersync-docs/blob/main/tools/cli.mdx Logs into PowerSync and scaffolds a new cloud instance configuration. ```bash powersync login powersync init cloud ``` -------------------------------- ### Set up Postgres Source Database with Docker Source: https://github.com/powersync-ja/powersync-docs/blob/main/intro/setup-guide.mdx This Docker command sequence sets up a self-hosted Postgres instance, enables logical replication, creates a PowerSync user with appropriate permissions, and establishes the 'powersync' publication. It also creates a Docker network for container communication. ```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;" ``` -------------------------------- ### Initialize PowerSync Database Source: https://github.com/powersync-ja/powersync-docs/blob/main/snippets/sdk-instantiate-db-examples.mdx Sets up the PowerSync environment with a database pool and client, then initializes the database instance. ```rust 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. } ``` -------------------------------- ### Watch Multiple Attachment Types with UNION (TypeScript) Source: https://github.com/powersync-ja/powersync-docs/blob/main/client-sdks/advanced/attachments.mdx Example of watching user photos, documents, and videos using a UNION query. Assumes tables store file extensions. Initializes and starts the AttachmentQueue. ```typescript // Example: Watching users.photo_id, documents.document_id, and videos.video_id // Assuming your tables store file extensions const attachmentQueue = new AttachmentQueue({ db: db, localStorage, remoteStorage, watchAttachments: (onUpdate) => { db.watch( `SELECT photo_id as id, photo_file_extension as file_extension FROM users WHERE photo_id IS NOT NULL UNION ALL SELECT document_id as id, document_file_extension as file_extension FROM documents WHERE document_id IS NOT NULL UNION ALL SELECT video_id as id, video_file_extension as file_extension FROM videos WHERE video_id IS NOT NULL`, [], { onResult: async (result) => { const attachments = result.rows?._array.map(row => ({ id: row.id, fileExtension: row.file_extension })) ?? []; await onUpdate(attachments); } } ); }, // ... other options }); await attachmentQueue.startSync(); ``` -------------------------------- ### Watch Multiple Attachment Types with UNION (Kotlin) Source: https://github.com/powersync-ja/powersync-docs/blob/main/client-sdks/advanced/attachments.mdx Kotlin example for watching user photos, documents, and videos using a UNION query. Assumes tables store file extensions. Initializes and starts the AttachmentQueue. ```kotlin // Example: Watching users.photo_id, documents.document_id, and videos.video_id // Assuming your tables store file extensions val attachmentQueue = AttachmentQueue( db = db, remoteStorage = remoteStorage, attachmentsDirectory = attachmentsDirectory, localStorage = localStorage, watchAttachments = { db.watch( sql = """ SELECT photo_id as id, photo_file_extension as file_extension FROM users WHERE photo_id IS NOT NULL UNION ALL SELECT document_id as id, document_file_extension as file_extension FROM documents WHERE document_id IS NOT NULL UNION ALL SELECT video_id as id, video_file_extension as file_extension FROM videos WHERE video_id IS NOT NULL """, parameters = null ) { cursor -> WatchedAttachmentItem( id = cursor.getString("id"), fileExtension = cursor.getString("file_extension") ) } }, // ... other options ) attachmentQueue.startSync() ``` -------------------------------- ### Watch Multiple Attachment Types with UNION (Swift) Source: https://github.com/powersync-ja/powersync-docs/blob/main/client-sdks/advanced/attachments.mdx Swift example for watching user photos, documents, and videos using a UNION query. Assumes tables store file extensions. Initializes and starts the AttachmentQueue. ```swift // Example: Watching users.photo_id, documents.document_id, and videos.video_id // Assuming your tables store file extensions let attachmentQueue = AttachmentQueue( db: db, remoteStorage: remoteStorage, attachmentsDirectory: try getAttachmentsDirectoryPath(), watchAttachments: { try db.watch( sql: """ SELECT photo_id as id, photo_file_extension as file_extension FROM users WHERE photo_id IS NOT NULL UNION ALL SELECT document_id as id, document_file_extension as file_extension FROM documents WHERE document_id IS NOT NULL UNION ALL SELECT video_id as id, video_file_extension as file_extension FROM videos WHERE video_id IS NOT NULL """, parameters: [], mapper: { cursor in try WatchedAttachmentItem( id: cursor.getString(name: "id"), fileExtension: cursor.getString(name: "file_extension") ) } ) }, // ... other options ) try await attachmentQueue.startSync() ``` -------------------------------- ### Initialize PowerSync and Attachments Setup Source: https://github.com/powersync-ja/powersync-docs/blob/main/integrations/flutterflow/attachments.mdx Call `initializePowerSync` to create the PowerSync database, followed by `setUpAttachments` to create the attachments queue. This order is crucial as `setUpAttachments` depends on the database being ready. ```dart initializePowerSync(); setUpAttachments(); ``` -------------------------------- ### Watch Multiple Attachment Types with UNION (Flutter) Source: https://github.com/powersync-ja/powersync-docs/blob/main/client-sdks/advanced/attachments.mdx Flutter example for watching user photos, documents, and videos using a UNION query. Assumes tables store file extensions. Initializes and starts the AttachmentQueue. ```dart // Example: Watching users.photo_id, documents.document_id, and videos.video_id // Assuming your tables store file extensions attachmentQueue = AttachmentQueue( db: db, remoteStorage: SignedUrlStorageAdapter(), localStorage: await getLocalStorage(), watchAttachments: () => db.watch(''' SELECT photo_id as id, photo_file_extension as file_extension FROM users WHERE photo_id IS NOT NULL UNION ALL SELECT document_id as id, document_file_extension as file_extension FROM documents WHERE document_id IS NOT NULL UNION ALL SELECT video_id as id, video_file_extension as file_extension FROM videos WHERE video_id IS NOT NULL ''').map( (results) => [ for (final row in results) WatchedAttachmentItem( id: row['id'] as String, fileExtension: row['file_extension'] as String, ) ], ), // ... other options ); await attachmentQueue.startSync(); ``` -------------------------------- ### Setup Web Assets for PowerSync Source: https://github.com/powersync-ja/powersync-docs/blob/main/client-sdks/frameworks/flutter-web-support.mdx Run this command in your application's root folder to download necessary WASM and worker assets for web support. ```bash dart run powersync:setup_web ``` -------------------------------- ### Run JavaScript Web Demo App Source: https://github.com/powersync-ja/powersync-docs/blob/main/integrations/supabase/guide.mdx Instructions to run the JavaScript web demo app. ```bash # In `demos/react-supabase-todolist`: pnpm dev ``` -------------------------------- ### MySQL Configuration and User Setup Source: https://github.com/powersync-ja/powersync-docs/blob/main/intro/setup-guide.mdx Configure binary logging and create a user with replication privileges for MySQL. Ensure your MySQL version is 5.7 or greater. ```sql -- Configure binary logging -- Add to MySQL option file (my.cnf or my.ini): server_id= log_bin=ON enforce_gtid_consistency=ON gtid_mode=ON binlog_format=ROW -- Create a user with necessary privileges CREATE USER 'repl_user'@'%' IDENTIFIED BY ''; -- Grant replication client privilege GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'repl_user'@'%'; -- Grant select access to the specific database GRANT SELECT ON .* TO 'repl_user'@'%'; -- Apply changes FLUSH PRIVILEGES; ``` -------------------------------- ### Initialize PowerSync Cloud Configuration Source: https://github.com/powersync-ja/powersync-docs/blob/main/tools/cli.mdx Scaffolds a new configuration directory for a PowerSync Cloud instance. ```bash powersync init cloud ``` -------------------------------- ### Install Peer Dependencies Source: https://github.com/powersync-ja/powersync-docs/blob/main/snippets/javascript-web/installation.mdx Install the required @journeyapps/wa-sqlite peer dependency. ```bash npm install @journeyapps/wa-sqlite ``` ```bash yarn add @journeyapps/wa-sqlite ``` ```bash pnpm install @journeyapps/wa-sqlite ``` -------------------------------- ### Create PowerSync Cloud Instance Source: https://github.com/powersync-ja/powersync-docs/blob/main/integrations/flutterflow/guide.mdx Initializes a PowerSync cloud instance, which acts as the backend for your local-first application. ```bash powersync-cli create-cloud-instance --name "your-instance-name" ``` -------------------------------- ### Install PowerSync Dependencies Source: https://github.com/powersync-ja/powersync-docs/blob/main/client-sdks/frameworks/nuxt.mdx Install the necessary PowerSync packages for your Nuxt project. For npm users, peer dependencies are handled automatically. For pnpm, ensure you install `@powersync/vue` and `@powersync/web` explicitly. ```shell npm install @powersync/nuxt ``` ```shell pnpm add @powersync/nuxt @powersync/vue @powersync/web ``` -------------------------------- ### Run Swift App Source: https://github.com/powersync-ja/powersync-docs/blob/main/integrations/supabase/guide.mdx Instructions to run the app using XCode. ```bash # Run the app using XCode. ``` -------------------------------- ### Instantiate PowerSync Database (Common SDK) Source: https://github.com/powersync-ja/powersync-docs/blob/main/client-sdks/reference/dotnet.mdx Initialize the PowerSync database for the Common .NET SDK. This setup streams changes from your backend and allows local data access. ```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(); } } ``` -------------------------------- ### Initialize PowerSync Self-Hosted Instance via CLI Source: https://github.com/powersync-ja/powersync-docs/blob/main/intro/setup-guide.mdx Install the PowerSync CLI and scaffold a self-hosted configuration. This command sets up Docker Compose with a Postgres instance for both the source database and storage. ```bash npm install -g powersync powersync init self-hosted powersync docker configure --database postgres --storage postgres ``` -------------------------------- ### Connector Implementation Example Source: https://github.com/powersync-ja/powersync-docs/blob/main/client-sdks/reference/node.mdx An example implementation of the `PowerSyncBackendConnector` interface for a Node.js application. ```APIDOC ## Connector Implementation Example ### Description This code snippet demonstrates how to implement the `PowerSyncBackendConnector` interface in a Node.js environment. It includes placeholder logic for fetching credentials and uploading data. ### Code ```javascript import { UpdateType } from '@powersync/node'; export class Connector implements PowerSyncBackendConnector { constructor() { // Initialize connection to your server for uploads this.serverConnectionClient = TODO; } async fetchCredentials() { // Implement fetchCredentials to obtain a JWT from your authentication service. // Refer to https://docs.powersync.com/configuration/auth/overview for details. return { endpoint: '[Your PowerSync instance URL or self-hosted endpoint]', // Use a development token for quick setup: https://docs.powersync.com/configuration/auth/development-tokens token: 'An authentication token' }; } async uploadData(database) { // Implement uploadData to send local changes to your backend service. // Omit this method if only syncing data from the database to the client. // See example implementation: https://docs.powersync.com/client-sdks/reference/javascript-web#3-integrate-with-your-backend } } ``` ``` -------------------------------- ### Install PowerSync Dependencies Source: https://github.com/powersync-ja/powersync-docs/blob/main/client-sdks/frameworks/expo-go-support.mdx Install the necessary PowerSync packages for React Native and the SQL.js adapter. ```bash npm install @powersync/react-native @powersync/adapter-sql-js ``` -------------------------------- ### Install PowerSync Web SDK Source: https://github.com/powersync-ja/powersync-docs/blob/main/snippets/javascript-web/installation.mdx Use these commands to add the PowerSync Web NPM package to your project. ```bash npm install @powersync/web ``` ```bash yarn add @powersync/web ``` ```bash pnpm install @powersync/web ``` -------------------------------- ### Start PowerSync Service Source: https://github.com/powersync-ja/powersync-docs/blob/main/integrations/serverpod.mdx Use Docker Compose to start the PowerSync service in detached mode. ```bash docker compose up --detach ``` -------------------------------- ### Install TanStackDB-PowerSync Collection Source: https://github.com/powersync-ja/powersync-docs/blob/main/client-sdks/frameworks/tanstack.mdx Install the necessary packages for TanStackDB-PowerSync integration with PowerSync web SDK and WA-SQLite. ```bash npm install @tanstack/powersync-db-collection @powersync/web @journeyapps/wa-sqlite ``` ```bash yarn add @tanstack/powersync-db-collection @powersync/web @journeyapps/wa-sqlite ``` ```bash pnpm install @tanstack/powersync-db-collection @powersync/web @journeyapps/wa-sqlite ``` -------------------------------- ### Initialize PowerSync Database in Swift Source: https://github.com/powersync-ja/powersync-docs/blob/main/snippets/sdk-instantiate-db-examples.mdx Basic initialization for Swift applications. ```swift import PowerSync let db = PowerSyncDatabase( schema: AppSchema, dbFilename: "powersync.sqlite" ) ``` -------------------------------- ### Install Kysely Driver Source: https://github.com/powersync-ja/powersync-docs/blob/main/client-sdks/frameworks/nuxt.mdx 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 ``` -------------------------------- ### Install Peer Dependencies with pnpm Source: https://github.com/powersync-ja/powersync-docs/blob/main/snippets/capacitor/installation.mdx Install the required peer dependencies for the PowerSync Capacitor SDK using pnpm. ```bash pnpm install @capacitor-community/sqlite @powersync/web @journeyapps/wa-sqlite ``` -------------------------------- ### Create Serverpod Project Source: https://github.com/powersync-ja/powersync-docs/blob/main/integrations/serverpod.mdx Use the Serverpod CLI to create a new Serverpod project. This command initializes a new project named 'notes'. ```bash # If you haven't already, dart pub global activate serverpod_cli serverpod create notes ``` -------------------------------- ### Open PowerSync Config Studio Source: https://github.com/powersync-ja/powersync-docs/blob/main/tools/cli.mdx Launches the Config Studio, an integrated editor for managing PowerSync configurations. ```bash powersync edit config ``` -------------------------------- ### Install Peer Dependencies with yarn Source: https://github.com/powersync-ja/powersync-docs/blob/main/snippets/capacitor/installation.mdx Install the required peer dependencies for the PowerSync Capacitor SDK using yarn. ```bash yarn add @capacitor-community/sqlite @powersync/web @journeyapps/wa-sqlite ``` -------------------------------- ### Configure Postgres for PowerSync (General) Source: https://github.com/powersync-ja/powersync-docs/blob/main/intro/setup-guide.mdx Use these SQL commands to enable logical replication, create a dedicated user with replication and read-only privileges, and set up a 'powersync' publication for all tables. This is the general setup for a self-hosted Postgres instance. ```sql -- 1. Enable logical replication (requires restart) ALTER SYSTEM SET wal_level = logical; -- 2. Create PowerSync database user/role with replication privileges and read-only access to your tables CREATE ROLE powersync_role WITH REPLICATION BYPASSRLS LOGIN PASSWORD 'myhighlyrandompassword'; -- Set up permissions for the newly created role -- Read-only (SELECT) access is required GRANT SELECT ON ALL TABLES IN SCHEMA public TO powersync_role; -- Optionally, grant SELECT on all future tables (to cater for schema additions) ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO powersync_role; -- 3. Create a publication to replicate tables. The publication must be named "powersync" CREATE PUBLICATION powersync FOR ALL TABLES; ```