### Web Babel Setup for WatermelonDB Source: https://github.com/nozbe/watermelondb/blob/master/docs-website/docs/docs/Installation.mdx Installs necessary Babel plugins for decorators, static class properties, and async/await, which are recommended for using WatermelonDB effectively on the web. This assumes Babel 7 is already in use and ES6 syntax is supported. ```bash yarn add --dev @babel/plugin-proposal-decorators yarn add --dev @babel/plugin-proposal-class-properties yarn add --dev @babel/plugin-transform-runtime ``` ```bash # (or with npm:) npm install -D @babel/plugin-proposal-decorators npm install -D @babel/plugin-proposal-class-properties npm install -D @babel/plugin-transform-runtime ``` -------------------------------- ### Install WatermelonDB Package with Yarn/NPM Source: https://github.com/nozbe/watermelondb/blob/master/docs-website/docs/docs/Installation.mdx Add the WatermelonDB package to your project using either Yarn or NPM package managers. This is the initial step required before platform-specific setup. ```bash yarn add @nozbe/watermelondb ``` ```bash npm install @nozbe/watermelondb ``` -------------------------------- ### Install Website Dependencies (Yarn) Source: https://github.com/nozbe/watermelondb/blob/master/docs-website/README.md Installs the necessary project dependencies using Yarn. This is the first step before running any other commands. ```bash $ yarn ``` -------------------------------- ### Start Local Development Server (Yarn) Source: https://github.com/nozbe/watermelondb/blob/master/docs-website/README.md Starts a local development server for the website. Changes are reflected live without requiring a server restart. Opens the site in a browser. ```bash $ yarn start ``` -------------------------------- ### Install better-sqlite3 for NodeJS SQLite Setup Source: https://github.com/nozbe/watermelondb/blob/master/docs-website/docs/docs/Installation.mdx Install the 'better-sqlite3' package as a development dependency to enable WatermelonDB's SQLite functionality within a NodeJS environment. This is required for server-side operations or shared code that utilizes SQLite. ```sh yarn add --dev better-sqlite3 ``` ```sh npm install -D better-sqlite3 ``` -------------------------------- ### Android JSI Installation for WatermelonDB Source: https://github.com/nozbe/watermelondb/blob/master/docs-website/docs/docs/Installation.mdx Configures WatermelonDB for high-performance, synchronous JSI operation on Android. This involves adding the JSI module to `settings.gradle` and `build.gradle`, and potentially configuring `packagingOptions` and Proguard rules. It also includes JSI package registration for both Java and Kotlin. ```gradle include ':watermelondb-jsi' project(':watermelondb-jsi').projectDir = new File(rootProject.projectDir, '../node_modules/@nozbe/watermelondb/native/android-jsi') ``` ```gradle // ... android { // ... packagingOptions { pickFirst '**/libc++_shared.so' // ⬅️ This (if missing) } } dependencies { // ... implementation project(':watermelondb-jsi') // ⬅️ This! } ``` ```bash # ... -keep class com.nozbe.watermelondb.** { *; } ``` ```java // ... import com.nozbe.watermelondb.jsi.WatermelonDBJSIPackage; // ⬅️ This! // ... @Override protected List getPackages() { return Arrays.asList( // new MyReactNativePackage(), new WatermelonDBJSIPackage() // ⬅️ Here! ); } ``` ```kotlin // ... import com.nozbe.watermelondb.jsi.WatermelonDBJSIPackage // ⬅️ This! // ... override val reactNativeHost: ReactNativeHost = object : DefaultReactNativeHost(this) { override fun getPackages(): List { return PackageList(this).packages.apply { // Packages that cannot be autolinked yet can be added manually here, for example: // add(new MyReactNativePackage()); add(WatermelonDBJSIPackage()) } } } ``` -------------------------------- ### Start TestChat Python Server Source: https://github.com/nozbe/watermelondb/blob/master/native/iosTest/Pods/SocketRocket/README.md Launch the TestChat server using Python. This requires activating a virtual environment and installing the Tornado library. The server broadcasts messages to connected clients. ```bash source .env/bin/activate pip install git+https://github.com/tornadoweb/tornado.git python TestChatServer/py/chatroom.py ``` -------------------------------- ### Initialize LokiJSAdapter for Web Applications Source: https://github.com/nozbe/watermelondb/blob/master/docs-website/docs/docs/Setup.md Configure and initialize the LokiJSAdapter for web-based WatermelonDB applications using IndexedDB storage. Supports optional web workers and incremental IndexedDB for efficient storage management. Includes comprehensive error handlers for quota exceeded errors, setup failures, and multi-tab synchronization events. ```javascript import LokiJSAdapter from '@nozbe/watermelondb/adapters/lokijs' const adapter = new LokiJSAdapter({ schema, // (You might want to comment out migrations for development purposes -- see Migrations documentation) migrations, useWebWorker: false, useIncrementalIndexedDB: true, // dbName: 'myapp', // optional db name // --- Optional, but recommended event handlers: onQuotaExceededError: (error) => { // Browser ran out of disk space -- offer the user to reload the app or log out }, onSetUpError: (error) => { // Database failed to load -- offer the user to reload the app or log out }, extraIncrementalIDBOptions: { onDidOverwrite: () => { // Called when this adapter is forced to overwrite contents of IndexedDB. // This happens if there's another open tab of the same app that's making changes. // Try to synchronize the app now, and if user is offline, alert them that if they close this // tab, some data may be lost }, onversionchange: () => { // database was deleted in another browser tab (user logged out), so we must make sure we delete // it in this tab as well - usually best to just refresh the page if (checkIfUserIsLoggedIn()) { window.location.reload() } }, } }) // The rest is the same! ``` -------------------------------- ### Setup Migrations in WatermelonDB Source: https://github.com/nozbe/watermelondb/blob/master/docs-website/docs/docs/Advanced/Migrations.md Initializes the migration configuration for WatermelonDB by importing `schemaMigrations` and defining an empty migrations array. This setup is then passed to the database adapter. ```javascript // app/model/migrations.js import { schemaMigrations } from '@nozbe/watermelondb/Schema/migrations' export default schemaMigrations({ migrations: [ // We'll add migration definitions here later ], }) ``` ```javascript // index.js import migrations from 'model/migrations' const adapter = new SQLiteAdapter({ schema: mySchema, migrations, }) ``` -------------------------------- ### Start TestChat Go Server Source: https://github.com/nozbe/watermelondb/blob/master/native/iosTest/Pods/SocketRocket/README.md Initiate the TestChat server using a Go implementation. Navigate to the Go server directory and execute the chatroom.go script. This provides an alternative server for the demo application. ```bash cd TestChatServer/go go run chatroom.go ``` -------------------------------- ### Vite Babel Configuration (Non-React) for WatermelonDB Source: https://github.com/nozbe/watermelondb/blob/master/docs-website/docs/docs/Installation.mdx Set up a non-React Vite project to work with WatermelonDB by using the vite-plugin-babel and configuring the necessary Babel plugins. This allows for decorators, class properties, and runtime transformations in non-React Vite environments. ```javascript import { defineConfig } from 'vite'; import babel from 'vite-plugin-babel'; export default defineConfig({ plugins: [ babel({ babelConfig: { babelrc: false, configFile: false, plugins: [ ["@babel/plugin-proposal-decorators", { "legacy": true }], ["@babel/plugin-proposal-class-properties", { "loose": true }], [ "@babel/plugin-transform-runtime", { "helpers": true, "regenerator": true } ] ], }, }), ] }); ``` -------------------------------- ### Install Babel Decorator Plugin for React Native Source: https://github.com/nozbe/watermelondb/blob/master/docs-website/docs/docs/Installation.mdx Install the Babel plugin for decorator support, which is required for WatermelonDB to work properly in React Native projects. Choose either Yarn or NPM. ```bash yarn add --dev @babel/plugin-proposal-decorators ``` ```bash npm install -D @babel/plugin-proposal-decorators ``` -------------------------------- ### Advanced WatermelonDB Turbo Sync Setup (JavaScript) Source: https://context7.com/nozbe/watermelondb/llms.txt This snippet illustrates the setup for Turbo Sync, an optimized synchronization method designed for initial or login syncs, requiring a SQLite database with a JSI adapter. It uses the `unsafeTurbo: true` option and expects `syncJson` (a JSON string of changes) from the `pullChanges` function for native processing. Optional callbacks `onDidPullChanges` and `onWillApplyRemoteChanges` are provided for post-pull processing and UI updates before applying changes. ```javascript // Advanced: Turbo sync for initial/login sync (requires SQLite with JSI) async function syncWithTurbo() { await synchronize({ database, unsafeTurbo: true, // Only for initial sync, requires SQLite JSI adapter pullChanges: async ({ lastPulledAt, schemaVersion, migration }) => { const response = await fetch(`https://api.example.com/sync?turbo=true`) // Return syncJson or syncJsonId for native processing const { syncJson, timestamp } = await response.json() return { syncJson, // JSON string of changes processed natively timestamp } }, pushChanges: async ({ changes, lastPulledAt }) => { await fetch('https://api.example.com/sync', { method: 'POST', body: JSON.stringify({ changes, lastPulledAt }) }) }, onDidPullChanges: async (result) => { // Called after pullChanges, useful for post-processing console.log('Pull changes completed') }, onWillApplyRemoteChanges: async ({ remoteChangeCount }) => { // Called before applying changes, useful for showing UI console.log(`Applying ${remoteChangeCount} remote changes`) } }) } ``` -------------------------------- ### Initialize WatermelonDB Database (JavaScript) Source: https://context7.com/nozbe/watermelondb/llms.txt Sets up a WatermelonDB database instance with schema, migrations, and adapter registration. Supports both SQLite for native platforms and LokiJS for web. Handles schema definition, migration steps, and error callbacks for adapter setup. ```javascript import { Database } from '@nozbe/watermelondb' import SQLiteAdapter from '@nozbe/watermelondb/adapters/sqlite' import LokiJSAdapter from '@nozbe/watermelondb/adapters/lokijs' import { appSchema, tableSchema } from '@nozbe/watermelondb' import { schemaMigrations } from '@nozbe/watermelondb/Schema/migrations' import Post from './model/Post' import Comment from './model/Comment' // Define schema const schema = appSchema({ version: 1, tables: [ tableSchema({ name: 'posts', columns: [ { name: 'title', type: 'string' }, { name: 'body', type: 'string' }, { name: 'is_starred', type: 'boolean' }, { name: 'created_at', type: 'number' }, { name: 'updated_at', type: 'number' } ] }), tableSchema({ name: 'comments', columns: [ { name: 'body', type: 'string' }, { name: 'author', type: 'string' }, { name: 'post_id', type: 'string', isIndexed: true }, { name: 'created_at', type: 'number' } ] }) ] }) // Define migrations const migrations = schemaMigrations({ migrations: [ { toVersion: 2, steps: [ { type: 'add_columns', table: 'posts', columns: [ { name: 'is_pinned', type: 'boolean' } ] } ] } ] }) // For React Native (iOS/Android/Node.js) - SQLite const adapter = new SQLiteAdapter({ schema, migrations, jsi: true, onSetUpError: error => { console.error('Database setup failed:', error) } }) // For Web - LokiJS const webAdapter = new LokiJSAdapter({ schema, migrations, useWebWorker: false, useIncrementalIndexedDB: true, onQuotaExceededError: (error) => { console.error('Disk space exceeded:', error) }, onSetUpError: (error) => { console.error('Database setup failed:', error) } }) // Create database instance const database = new Database({ adapter: adapter, // Use adapter for native, webAdapter for web modelClasses: [Post, Comment] }) export default database ``` -------------------------------- ### Install SocketRocket with Carthage Source: https://github.com/nozbe/watermelondb/blob/master/native/iosTest/Pods/SocketRocket/README.md Integrate SocketRocket using Carthage by adding the repository to your Cartfile and running 'carthage update'. Carthage is another dependency manager that builds frameworks. ```text github "facebook/SocketRocket" ``` -------------------------------- ### Basic WatermelonDB Synchronization Setup (JavaScript) Source: https://context7.com/nozbe/watermelondb/llms.txt This snippet demonstrates the fundamental setup for synchronizing data with a remote backend using WatermelonDB's `synchronize` function. It defines asynchronous functions for pulling changes from a server based on a timestamp and pushing local changes back to the server. It also includes optional configurations for migration handling, sending created records as updated, custom conflict resolution, and logging. ```javascript import { synchronize } from '@nozbe/watermelondb/sync' import database from './database' // Basic synchronization setup async function syncDatabase() { try { await synchronize({ database, pullChanges: async ({ lastPulledAt, schemaVersion, migration }) => { // Fetch changes from server since lastPulledAt timestamp const response = await fetch(`https://api.example.com/sync?last_pulled_at=${lastPulledAt}&schema_version=${schemaVersion}`) if (!response.ok) { throw new Error('Sync pull failed') } const { changes, timestamp } = await response.json() // changes format: // { // posts: { created: [...], updated: [...], deleted: ['id1', 'id2'] }, // comments: { created: [...], updated: [...], deleted: [...] } // } return { changes, timestamp } }, pushChanges: async ({ changes, lastPulledAt }) => { // Send local changes to server const response = await fetch('https://api.example.com/sync', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ changes, lastPulledAt }) }) if (!response.ok) { throw new Error('Sync push failed') } // Optionally return rejected IDs const { experimentalRejectedIds } = await response.json() return { experimentalRejectedIds } }, // Optional: handle migration syncs migrationsEnabledAtVersion: 1, // Optional: send created records as updated (useful for server-generated IDs) sendCreatedAsUpdated: false, // Optional: custom conflict resolution conflictResolver: (table, local, remote, resolved) => { // Default behavior: server wins // Custom: return your own resolved object if (table === 'posts') { // Keep local isStarred value even if server has different value return { ...resolved, is_starred: local.is_starred } } return resolved }, // Optional: logging log: { startedAt: new Date(), finishedAt: new Date(), remoteChangeCount: 0, localChangeCount: 0 } }) console.log('Sync completed successfully') } catch (error) { console.error('Sync failed:', error) throw error } } ``` -------------------------------- ### Run SocketRocket Tests from Command Line Source: https://github.com/nozbe/watermelondb/blob/master/native/iosTest/Pods/SocketRocket/README.md Execute automated tests for SocketRocket using make commands. 'make test' runs the short tests, while 'make test_all' includes performance tests. Ensure dependencies are installed first. ```bash make test ``` ```bash make test_all ``` -------------------------------- ### Configure Babel for ES6 Decorators Source: https://github.com/nozbe/watermelondb/blob/master/docs-website/docs/docs/Installation.mdx Update the .babelrc configuration file to enable ES6 decorator support with the metro-react-native-babel-preset and the decorators plugin in legacy mode. ```json { "presets": ["module:metro-react-native-babel-preset"], "plugins": [["@babel/plugin-proposal-decorators", { "legacy": true }]] } ``` -------------------------------- ### Vite React Babel Configuration for WatermelonDB Source: https://github.com/nozbe/watermelondb/blob/master/docs-website/docs/docs/Installation.mdx Configure your Vite project to support WatermelonDB by adding specific Babel plugins within the React plugin configuration in vite.config.js. This enables decorators, class properties, and runtime transformations for React applications using Vite. ```javascript import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [ react({ babel: { plugins: [ ["@babel/plugin-proposal-decorators", { "legacy": true }], ["@babel/plugin-proposal-class-properties", { "loose": true }], [ "@babel/plugin-transform-runtime", { "helpers": true, "regenerator": true } ] ], } }), ] }); ``` -------------------------------- ### Initialize SQLiteAdapter for React Native and NodeJS Source: https://github.com/nozbe/watermelondb/blob/master/docs-website/docs/docs/Setup.md Configure and initialize the SQLiteAdapter for React Native (iOS/Android) and NodeJS environments. The adapter manages database connection, applies migrations, handles errors, and supports JSI mode for better performance on iOS. Includes error handlers for database setup failures and optional configuration for development. ```javascript import { Platform } from 'react-native' import { Database } from '@nozbe/watermelondb' import SQLiteAdapter from '@nozbe/watermelondb/adapters/sqlite' import schema from './model/schema' import migrations from './model/migrations' // import Post from './model/Post' // ⬅️ You'll import your Models here // First, create the adapter to the underlying database: const adapter = new SQLiteAdapter({ schema, // (You might want to comment it out for development purposes -- see Migrations documentation) migrations, // (optional database name or file system path) // dbName: 'myapp', // (recommended option, should work flawlessly out of the box on iOS. On Android, // additional installation steps have to be taken - disable if you run into issues...) jsi: true, /* Platform.OS === 'ios' */ // (optional, but you should implement this method) onSetUpError: error => { // Database failed to load -- offer the user to reload the app or log out } }) // Then, make a Watermelon database from it! const database = new Database({ adapter, modelClasses: [ // Post, // ⬅️ You'll add Models to Watermelon here ], }) ``` -------------------------------- ### Create WatermelonDB App Schema Source: https://github.com/nozbe/watermelondb/blob/master/docs-website/docs/docs/Setup.md Initialize the app schema by importing schema utilities from WatermelonDB and defining tables. This creates the base schema structure that defines your database tables and their versions. The schema is required for database initialization and subsequent migration definitions. ```javascript import { appSchema, tableSchema } from '@nozbe/watermelondb' export default appSchema({ version: 1, tables: [ // We'll add tableSchemas here later ] }) ``` -------------------------------- ### Configure CocoaPods Dependencies for iOS in Podfile Source: https://github.com/nozbe/watermelondb/blob/master/docs-website/docs/docs/Installation.mdx Add WatermelonDB and its native dependencies (simdjson) to the iOS project's Podfile for CocoaPods dependency management. Uncomment the WatermelonDB pod line if auto-linking fails. ```ruby # Uncomment this line if you're not using auto-linking or if auto-linking causes trouble # pod 'WatermelonDB', path: '../node_modules/@nozbe/watermelondb' # WatermelonDB dependency, should not be needed on modern React Native # (please file an issue if this causes issues for you) # pod 'React-jsi', path: '../node_modules/react-native/ReactCommon/jsi', modular_headers: true # WatermelonDB dependency pod 'simdjson', path: '../node_modules/@nozbe/simdjson', modular_headers: true ``` -------------------------------- ### Webpack Babel Configuration for WatermelonDB Source: https://github.com/nozbe/watermelondb/blob/master/docs-website/docs/docs/Installation.mdx Add ES7 support to your Webpack project's .babelrc file by including necessary Babel plugins for decorators, class properties, and runtime transformations. This configuration is essential for using modern JavaScript features required by WatermelonDB. ```json { "plugins": [ ["@babel/plugin-proposal-decorators", { "legacy": true }], ["@babel/plugin-proposal-class-properties", { "loose": true }], [ "@babel/plugin-transform-runtime", { "helpers": true, "regenerator": true } ] ] } ``` -------------------------------- ### Create WatermelonDB Schema Migrations Source: https://github.com/nozbe/watermelondb/blob/master/docs-website/docs/docs/Setup.md Define database migrations using schemaMigrations from WatermelonDB. Migrations handle schema version updates and data transformations when your database structure changes. This file tracks all migration definitions needed for database evolution. ```javascript import { schemaMigrations } from '@nozbe/watermelondb/Schema/migrations' export default schemaMigrations({ migrations: [ // We'll add migration definitions here later ], }) ``` -------------------------------- ### Install SocketRocket with CocoaPods Source: https://github.com/nozbe/watermelondb/blob/master/native/iosTest/Pods/SocketRocket/README.md Use CocoaPods to integrate SocketRocket into your project by adding 'SocketRocket' to your Podfile and running 'pod install'. This is a common dependency management method for iOS projects. ```ruby pod 'SocketRocket' ``` -------------------------------- ### Android Manual Linking for WatermelonDB Source: https://github.com/nozbe/watermelondb/blob/master/docs-website/docs/docs/Installation.mdx Manually links the WatermelonDB library in an Android React Native project. This is typically only needed for older React Native versions or when autolinking is disabled. It involves modifying `settings.gradle`, `build.gradle`, and `MainApplication.java` files to include the WatermelonDB package. ```gradle include ':watermelondb' project(':watermelondb').projectDir = new File(rootProject.projectDir, '../node_modules/@nozbe/watermelondb/native/android') ``` ```gradle // ... dependencies { // ... implementation project(':watermelondb') // ⬅️ This! } ``` ```java // ... import com.nozbe.watermelondb.WatermelonDBPackage; // ⬅️ This! // ... @Override protected List getPackages() { return Arrays.asList( new MainReactPackage(), new WatermelonDBPackage() // ⬅️ Here! ); } ``` -------------------------------- ### React: Basic DatabaseProvider and Hooks Usage Source: https://context7.com/nozbe/watermelondb/llms.txt Demonstrates wrapping the application with `DatabaseProvider` and using the `useDatabase` hook to access the database instance for creating new records. This is the foundational setup for using WatermelonDB in React. ```javascript import React, { useState } from 'react' import { View, Text, FlatList, Button } from 'react-native' import { Q } from '@nozbe/watermelondb' import { DatabaseProvider, withObservables, useDatabase, compose } from '@nozbe/watermelondb/react' import database from './database' // 1. Wrap your app with DatabaseProvider function App() { return ( ) } // 2. Using hooks - useDatabase function CreatePostButton() { const database = useDatabase() const handleCreatePost = async () => { await database.write(async () => { await database.get('posts').create(post => { post.title = 'New Post' post.body = 'Created from React' post.isStarred = false }) }) } return