MikroORM
Store and query MikroORM entities in a local Nitro SQLite database.
SQLite stores tables in a file on the device. MikroORM maps entities to those tables, tracks changes to the entities you load, and writes pending changes when you call flush(). The Nitro SQLite driver executes those queries asynchronously on a dedicated native connection.
Install the driver
Use matching MikroORM packages. This setup uses MikroORM 7.2.13 and Kysely 0.29.9.
npm install react-native-nitro-sqlite react-native-nitro-sqlite-mikro-orm @mikro-orm/core@7.2.13 @mikro-orm/sql@7.2.13 kysely@0.29.9 bufferUse @mikro-orm/sql for the shared SQLite platform. The @mikro-orm/sqlite package requires the Node.js better-sqlite3 addon.
Configure Metro and Babel
The driver ships two build-time helpers. The Metro resolver selects MikroORM's browser stubs for filesystem access. The Babel plugin handles MikroORM's computed imports and leaves Unicode property escapes for Hermes.
In a bare React Native app, add the resolver to metro.config.js.
const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config')
const { resolveRequest } = require('react-native-nitro-sqlite-mikro-orm/metro')
module.exports = mergeConfig(getDefaultConfig(__dirname), {
resolver: { resolveRequest },
})Add babelPlugin to the plugins in babel.config.js.
const { babelPlugin } = require('react-native-nitro-sqlite-mikro-orm/metro')
module.exports = {
presets: ['module:@react-native/babel-preset'],
plugins: [babelPlugin],
}Keep your app's existing presets and plugins. Restart Metro with a clear cache after changing either file.
Set up the JavaScript Buffer implementation before importing your ORM code. For example, add this to an initialization module and import it first from the app entry point.
import { Buffer } from 'buffer'
globalThis.Buffer ??= BufferStore and read an entity
A file name in dbName selects the database in the app's SQLite directory. The driver accepts Nitro SQLite's location, readOnly, and encryptionKey options in driverOptions.
import { defineEntity, MikroORM, p } from '@mikro-orm/sql'
import { NitroSQLiteDriver } from 'react-native-nitro-sqlite-mikro-orm'
const Note = defineEntity({
name: 'Note',
properties: {
id: p.integer().primary(),
title: p.string(),
},
})
const orm = new MikroORM({
driver: NitroSQLiteDriver,
dbName: 'notes.db',
entities: [Note],
})
try {
// Create or update the schema for this example.
await orm.schema.update()
const writer = orm.em.fork()
const note = writer.create(Note, { title: 'Packing list' })
await writer.flush()
const reader = orm.em.fork()
const saved = await reader.findOneOrFail(Note, note.id)
console.log(saved.title)
} finally {
await orm.close()
}For a long-lived database, create the ORM once and close it after its queries and transactions finish. Use an entity manager fork for each independent unit of work.
Read large result sets
The driver loads all rows returned by a query into memory. MikroORM's em.stream() and qb.stream() are unsupported. To process a large table, fetch one page at a time. For the Note entity above, use the last ID from the previous page and stop when a page is empty.
const page = await reader.find(
Note,
{ id: { $gt: lastId } },
{ orderBy: { id: 'asc' }, limit: 100, disableIdentityMap: true },
)Disabling the identity map keeps the entity manager from retaining earlier pages.
Wait for a database lock
SQLite allows one writer at a time. If several connections write to the same file, set a busy timeout on each connection that should wait for a lock. This example lets SQLite retry for up to five seconds before returning a busy error. MikroORM runs the hook again after reconnecting.
import { CompiledQuery, type DatabaseConnection } from 'kysely'
const orm = new MikroORM({
driver: NitroSQLiteDriver,
dbName: 'notes.db',
entities: [Note],
onCreateConnection: async (connection) => {
const db = connection as DatabaseConnection
await db.executeQuery(CompiledQuery.raw('PRAGMA busy_timeout = 5000'))
},
})Use transactions and manage the schema
SQLite transactions commit a group of writes together or roll them back together. Pass the transaction callback's entity manager to every function that does database work inside the transaction. Pass the nested callback's manager when you use a nested transaction. On Hermes, MikroORM's fallback for AsyncLocalStorage does not propagate across await.
List entity objects or classes directly in entities and use the synchronous ORM constructor. Keep filesystem discovery, generated migration files, and CLI tools in your development environment. To migrate an installed app, ship migration SQL with the app and run it on the device before using the new schema. See the transactions guide.