Convert Figma logo to code with AI

Nozbe logoWatermelonDB

🍉 Reactive & asynchronous database for powerful React and React Native apps ⚡️

11,110
623
11,110
283

Top Related Projects

Realm is a mobile database: an alternative to SQLite & key-value stores

Flutter database for super-fast Dart object persistence

12,632

greenDAO is a light & fast ORM solution for Android that maps objects to SQLite databases.

Lightweight, embedded, syncable NoSQL database engine for Android.

SQLCipher is a standalone fork of SQLite that adds 256 bit AES encryption of database files and other security features.

Quick Overview

WatermelonDB is a high-performance reactive database for powerful React and React Native apps. It's designed to build complex, scalable apps with seamless synchronization and real-time updates. WatermelonDB uses a SQLite database under the hood, providing a robust and efficient solution for managing large amounts of data in mobile and web applications.

Pros

  • High performance and scalability, capable of handling large datasets smoothly
  • Built-in support for real-time updates and synchronization
  • Type-safe with full TypeScript support
  • Designed for offline-first applications

Cons

  • Steeper learning curve compared to simpler state management solutions
  • Limited to React and React Native ecosystems
  • Requires additional setup and configuration compared to simpler alternatives
  • May be overkill for small, simple applications

Code Examples

  1. Creating a model:
import { Model } from '@nozbe/watermelondb'

class Post extends Model {
  static table = 'posts'
  static associations = {
    comments: { type: 'has_many', foreignKey: 'post_id' },
  }
}
  1. Querying the database:
const posts = await database.get('posts').query(
  Q.where('status', 'published'),
  Q.sortBy('created_at', Q.desc)
).fetch()
  1. Creating a new record:
await database.write(async () => {
  const newPost = await database.get('posts').create(post => {
    post.title = 'New Post'
    post.body = 'This is the content of the new post.'
  })
})

Getting Started

  1. Install WatermelonDB:
npm install @nozbe/watermelondb
npm install @nozbe/watermelondb-sync-adapter # for sync support
  1. Set up the database:
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' // your custom model

const adapter = new SQLiteAdapter({
  schema,
  migrations,
  jsi: true, // enable JSI for better performance (optional)
  onSetUpError: error => {
    // Database failed to load -- offer the user to reload the app or log out
  }
})

const database = new Database({
  adapter,
  modelClasses: [Post],
})
  1. Use the database in your React components:
import { withDatabase } from '@nozbe/watermelondb/DatabaseProvider'
import withObservables from '@nozbe/with-observables'

const EnhancedComponent = withDatabase(
  withObservables(['database'], ({ database }) => ({
    posts: database.get('posts').query().observe()
  }))(YourComponent)
)

Competitor Comparisons

Realm is a mobile database: an alternative to SQLite & key-value stores

Pros of realm-js

  • Native C++ core provides better performance for large datasets
  • Built-in synchronization capabilities for real-time collaboration
  • Extensive documentation and community support

Cons of realm-js

  • Steeper learning curve due to unique data model and query language
  • Less flexibility in schema migrations compared to WatermelonDB
  • Larger app size due to native libraries

Code Comparison

WatermelonDB:

import { Model } from '@nozbe/watermelondb'

class Post extends Model {
  static table = 'posts'
  static associations = {
    comments: { type: 'has_many', foreignKey: 'post_id' }
  }
}

realm-js:

const Realm = require('realm');

const PostSchema = {
  name: 'Post',
  properties: {
    title: 'string',
    comments: 'Comment[]'
  }
};

const realm = await Realm.open({schema: [PostSchema]});

Both libraries offer reactive data handling and offline-first capabilities. WatermelonDB focuses on simplicity and ease of use, while realm-js provides more advanced features at the cost of complexity. The choice between them depends on specific project requirements and developer preferences.

Flutter database for super-fast Dart object persistence

Pros of ObjectBox

  • Native performance: ObjectBox is built with native code, offering superior speed compared to pure Dart solutions
  • ACID compliance: Ensures data integrity and reliability in database operations
  • Supports relations: Allows for complex data modeling with object relationships

Cons of ObjectBox

  • Limited platform support: Primarily focused on mobile platforms, with less emphasis on web or desktop
  • Steeper learning curve: Requires understanding of ObjectBox-specific concepts and APIs
  • Less flexible querying: Query capabilities may be more limited compared to SQL-based solutions

Code Comparison

ObjectBox:

@Entity()
class Person {
  int id;
  String name;
  int age;

  Person({this.id = 0, required this.name, required this.age});
}

WatermelonDB:

class Person extends Model {
  static table = 'persons'

  @field('name') name
  @field('age') age
}

Both libraries offer simple ways to define database models, but ObjectBox uses Dart annotations while WatermelonDB uses JavaScript decorators. ObjectBox's approach is more tightly integrated with Dart's type system, while WatermelonDB's syntax is more concise and JavaScript-like.

ObjectBox provides native performance and ACID compliance, making it suitable for high-performance mobile apps. However, WatermelonDB offers broader platform support and may be easier to learn for developers familiar with JavaScript and React Native ecosystems.

12,632

greenDAO is a light & fast ORM solution for Android that maps objects to SQLite databases.

Pros of greenDAO

  • Mature and well-established ORM for Android development
  • Supports database encryption out of the box
  • Offers a powerful query builder for complex database operations

Cons of greenDAO

  • Limited to Android platform, not suitable for cross-platform development
  • Requires more boilerplate code compared to modern alternatives
  • Less active development and community support in recent years

Code Comparison

greenDAO:

@Entity
public class User {
    @Id private Long id;
    private String name;
    private int age;
}

WatermelonDB:

class User extends Model {
  static table = 'users'
  static columns = {
    name: 'string',
    age: 'number'
  }
}

Key Differences

  • WatermelonDB is designed for cross-platform mobile development (React Native, iOS, Android), while greenDAO is Android-specific
  • WatermelonDB uses a more modern, declarative syntax compared to greenDAO's annotation-based approach
  • greenDAO generates code at compile-time, while WatermelonDB uses runtime introspection
  • WatermelonDB focuses on offline-first architecture and synchronization, which is not a primary feature of greenDAO

Both libraries aim to simplify database operations in mobile apps, but they cater to different ecosystems and development philosophies.

Lightweight, embedded, syncable NoSQL database engine for Android.

Pros of Couchbase Lite Android

  • Full-featured NoSQL database with support for complex queries and indexing
  • Built-in synchronization capabilities with Couchbase Server
  • Mature ecosystem with extensive documentation and enterprise support

Cons of Couchbase Lite Android

  • Larger footprint and potentially higher resource usage
  • Steeper learning curve due to more complex API and features
  • May be overkill for simpler mobile app database needs

Code Comparison

WatermelonDB:

const post = await database.collections.get('posts').create(record => {
  record.title = 'New Post'
  record.body = 'Lorem ipsum...'
})

Couchbase Lite Android:

MutableDocument doc = new MutableDocument()
    .setString("type", "post")
    .setString("title", "New Post")
    .setString("body", "Lorem ipsum...");
collection.save(doc);

WatermelonDB focuses on a more declarative, React-friendly API, while Couchbase Lite Android offers a lower-level, more flexible approach. WatermelonDB is designed specifically for React Native and web applications, whereas Couchbase Lite Android is a general-purpose mobile database solution with broader use cases and platform support.

SQLCipher is a standalone fork of SQLite that adds 256 bit AES encryption of database files and other security features.

Pros of SQLCipher

  • Strong encryption: Provides 256-bit AES encryption for SQLite databases
  • Cross-platform compatibility: Works on various operating systems and devices
  • Mature and well-established: Widely used in enterprise and government applications

Cons of SQLCipher

  • Lower-level API: Requires more manual management of database operations
  • Limited built-in features: Lacks advanced ORM capabilities and reactive programming support
  • Performance overhead: Encryption and decryption processes can impact performance

Code Comparison

SQLCipher:

PRAGMA key = 'encryption_key';
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);
INSERT INTO users (name) VALUES ('John Doe');

WatermelonDB:

const user = await database.collections.get('users').create(record => {
  record.name = 'John Doe'
})

Summary

SQLCipher focuses on providing robust encryption for SQLite databases, offering strong security features and cross-platform compatibility. It's well-suited for applications requiring high-level data protection. WatermelonDB, on the other hand, provides a more developer-friendly API with built-in ORM capabilities and reactive programming support, making it easier to work with complex data structures and real-time updates. The choice between the two depends on the specific requirements of your project, particularly regarding security needs and development workflow preferences.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

WatermelonDB

A reactive database framework

Build powerful React and React Native apps that scale from hundreds to tens of thousands of records and remain fast ⚡️

MIT License npm Gurubase

WatermelonDB
⚡️Launch your app instantly no matter how much data you have
📈Highly scalable from hundreds to tens of thousands of records
😎Lazy loaded. Only load data when you need it
🔄Offline-first. Sync with your own backend
📱Multiplatform. iOS, Android, Windows, web, and Node.js
⚛️Optimized for React. Easily plug data into components
🧰Framework-agnostic. Use JS API to plug into other UI frameworks
⏱Fast. And getting faster with every release!
✅Proven. Powers Nozbe since 2017 (and many others)
✨Reactive. (Optional) RxJS API
🔗Relational. Built on rock-solid SQLite foundation
⚠️Static typing with Flow or TypeScript

Why Watermelon?

WatermelonDB is a new way of dealing with user data in React Native and React web apps.

It's optimized for building complex applications in React Native, and the number one goal is real-world performance. In simple words, your app must launch fast.

For simple apps, using Redux or MobX with a persistence adapter is the easiest way to go. But when you start scaling to thousands or tens of thousands of database records, your app will now be slow to launch (especially on slower Android devices). Loading a full database into JavaScript is expensive!

Watermelon fixes it by being lazy. Nothing is loaded until it's requested. And since all querying is performed directly on the rock-solid SQLite database on a separate native thread, most queries resolve in an instant.

But unlike using SQLite directly, Watermelon is fully observable. So whenever you change a record, all UI that depends on it will automatically re-render. For example, completing a task in a to-do app will re-render the task component, the list (to reorder), and all relevant task counters. Learn more.

React Native EU: Next-generation React Databases

📺 Next-generation React databases
(a talk about WatermelonDB)

Usage

Quick (over-simplified) example: an app with posts and comments.

First, you define Models:

class Post extends Model {
  @field('name') name
  @field('body') body
  @children('comments') comments
}

class Comment extends Model {
  @field('body') body
  @field('author') author
}

Then, you connect components to the data:

const Comment = ({ comment }) => (
  <View style={styles.commentBox}>
    <Text>{comment.body} — by {comment.author}</Text>
  </View>
)

// This is how you make your app reactive! ✨
const enhance = withObservables(['comment'], ({ comment }) => ({
  comment,
}))
const EnhancedComment = enhance(Comment)

And now you can render the whole Post:

const Post = ({ post, comments }) => (
  <View>
    <Text>{post.name}</Text>
    <Text>Comments:</Text>
    {comments.map(comment =>
      <EnhancedComment key={comment.id} comment={comment} />
    )}
  </View>
)

const enhance = withObservables(['post'], ({ post }) => ({
  post,
  comments: post.comments
}))

The result is fully reactive! Whenever a post or comment is added, changed, or removed, the right components will automatically re-render on screen. Doesn't matter if a change occurred in a totally different part of the app, it all just works out of the box!

➡️ Learn more: see full documentation

Who uses WatermelonDB

Nozbe Teams
CAPMO
Mattermost
Rocket Chat
Steady
Aerobotics
Smash Appz
HaloGo
SportsRecruits
Chatable
Todorant
Blast Workout
Dayful
Learn The Words

Does your company or app use 🍉? Open a pull request and add your logo/icon with link here!

Contributing

We need you

WatermelonDB is an open-source project and it needs your help to thrive!

If there's a missing feature, a bug, or other improvement you'd like, we encourage you to contribute! Feel free to open an issue to get some guidance and see Contributing guide for details about project setup, testing, etc.

If you're just getting started, see good first issues that are easy to contribute to. If you make a non-trivial contribution, email me, and I'll send you a nice 🍉 sticker!

If you make or are considering making an app using WatermelonDB, please let us know!

Author and license

WatermelonDB was created by @Nozbe.

WatermelonDB's main author and maintainer is Radek Pietruszewski (website ⋅ 𝕏 (Twitter))

See all contributors.

WatermelonDB is available under the MIT license. See the LICENSE file for more info.

NPM DownloadsLast 30 Days