NitroSQLite

Drizzle ORM

Use Drizzle ORM with Nitro SQLite through the react-native-nitro-sqlite-drizzle driver.

react-native-nitro-sqlite-drizzle runs Drizzle ORM queries on a Nitro SQLite connection. Pass an open connection to drizzle() and query it with Drizzle's API. Every query is asynchronous.

Install

Use the Drizzle quick start to install the driver, open a database, and run a query. The driver supports drizzle-orm 0.45.4 and later 0.x releases.

Create a database

A Drizzle table declaration describes columns to the query builder. SQLite needs the corresponding table in the database file. The quick start creates it with SQL. For versioned schema changes, use the migrations below.

Create db once, outside your components. drizzle(connection, config) accepts Drizzle's schema, logger, and casing options. db.$client is the connection passed to drizzle(). Close it after outstanding work finishes.

SQLite stores binary values as BLOBs. When you pass a Buffer or another typed-array view through Drizzle, the driver binds its bytes as an ArrayBuffer, preserving the view's byte range.

Migrations

Start the first generated migration on a fresh database. The quick start creates the notes table directly, so Drizzle has no migration record for it and would try to create it again.

Install the development tools for generating and bundling migrations.

npm install --save-dev drizzle-kit babel-plugin-inline-import

Put the table declarations in db/schema.ts so Drizzle Kit can load them in Node without opening a native connection. Drizzle Kit generates SQL migration files from that schema. Set driver: 'expo' so it also writes a migrations.js file that bundles them for React Native:

drizzle.config.ts
import { defineConfig } from 'drizzle-kit'

export default defineConfig({
  schema: './db/schema.ts',
  out: './drizzle',
  dialect: 'sqlite',
  driver: 'expo',
})

Run npx drizzle-kit generate after each schema change.

migrations.js imports .sql files. Add the Babel plugin so they load as strings:

babel.config.js
module.exports = {
  presets: ['module:@react-native/babel-preset'],
  plugins: [['inline-import', { extensions: ['.sql'] }]],
}

Add sql to Metro's source extensions:

metro.config.js
const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config')

const defaultConfig = getDefaultConfig(__dirname)

module.exports = mergeConfig(defaultConfig, {
  resolver: { sourceExts: [...defaultConfig.resolver.sourceExts, 'sql'] },
})

Run the migrations when the app starts with useMigrations. It applies the migrations this database has not run yet, in one transaction, and records them in the __drizzle_migrations table:

import { Text } from 'react-native'
import { useMigrations } from 'react-native-nitro-sqlite-drizzle'
import migrations from './drizzle/migrations'
import { db } from './db'

export function App() {
  const { success, error } = useMigrations(db, migrations)

  if (error) return <Text>Migration failed: {error.message}</Text>
  if (!success) return <Text>Migrating...</Text>
  return <Text>Ready</Text>
}

To run migrations outside a component, such as in startup code or a test, call migrate and await it:

import { migrate } from 'react-native-nitro-sqlite-drizzle'

await migrate(db, migrations)

Calls using the same connection wait for earlier migration calls before checking which migrations are pending. React Strict Mode can replay useMigrations without applying the same migration twice. If a migration fails, its transaction rolls back and a later call can retry it.

Changing the database or migration bundle returns pending state on the first render with the new inputs. Earlier queued or running migrations still finish after an input change or unmount, but their results do not replace the state for the current inputs.

Transactions

Run every query inside a transaction through tx:

import { eq } from 'drizzle-orm'

await db.transaction(async (tx) => {
  await tx.insert(notes).values({ title: 'Passport' })
  await tx.update(notes).set({ title: 'Packed' }).where(eq(notes.id, 1))
})

A transaction holds the connection until its callback finishes. A query awaited through db inside the callback, including a query prepared from db, waits for the transaction and never completes.

Nested transactions

SQLite savepoints form a stack inside one transaction. Releasing a savepoint keeps its changes inside the outer transaction. Rolling back to a savepoint undoes changes since that savepoint. Savepoints cannot isolate overlapping callbacks.

Nested tx.transaction() calls use savepoints. Await each nested call before starting another on the same handle, using its parent handle for queries, or returning from the parent callback. Use the child handle to nest further:

await db.transaction(async (tx) => {
  await tx.transaction(async (child) => {
    await child.insert(notes).values({ title: 'Passport' })
    await child.transaction(async (grandchild) => {
      await grandchild.insert(notes).values({ title: 'Tickets' })
    })
  })
  await tx.transaction(async (child) => {
    await child.insert(notes).values({ title: 'Packed' })
  })
})

Overlapping nested calls on the same handle reject before executing SQL or invoking the second callback. This includes siblings started with Promise.all() and nested calls made through an ancestor handle. Top-level transactions still wait for earlier transactions on their connection. Separate connections have separate scopes.

Catch a nested callback's rejection in its parent to continue after a rollback. The driver rolls back and releases the savepoint before rejecting. Savepoint setup or cleanup failures force the outer transaction to roll back, even if caught. When callback and cleanup both fail, the error's cause is an AggregateError containing both errors.

If a callback returns or throws with an active child, the driver rejects the parent and rolls back its work without waiting for that child. The child's handle finishes with the parent, so its later queries and its nested call reject. Always await the child yourself.

Queries through a finished child handle reject after either release or rollback, including prepared queries created through that handle. This applies while its parent remains active. Continue through the parent or start and await another child.

tx.rollback() rolls back the transaction and rejects it with a SQLiteError whose message is Rollback. The behavior option of db.transaction() is ignored: transactions start with BEGIN. See transactions for how Nitro SQLite runs them.

If a statement implicitly rolls back the entire SQLite transaction, later queries and nested transactions reject before running SQL. Catching a default ABORT constraint error keeps the transaction active and allows further queries and nested transactions. See constraint errors and implicit rollback.

On this page