NitroSQLite
Integrations

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

Install the driver with Drizzle and Nitro SQLite. Drizzle Kit and the Babel plugin are only needed for migrations.

npm install react-native-nitro-sqlite@nitro-v1 react-native-nitro-sqlite-drizzle@nitro-v1 react-native-nitro-modules@1.0.0-alpha.nightly.138.g43e09c161101 drizzle-orm
npm install --save-dev drizzle-kit babel-plugin-inline-import

The driver supports drizzle-orm 0.45.4 and later 0.x releases.

Create a database

Keep table declarations in a schema module that Drizzle Kit can load without opening a native connection:

db/schema.ts
import { sqliteTable, integer, text } from 'drizzle-orm/sqlite-core'

export const users = sqliteTable('users', {
  id: integer('id').primaryKey(),
  name: text('name').notNull(),
})

Open the connection in a separate module:

db/index.ts
import { open } from 'react-native-nitro-sqlite'
import { drizzle } from 'react-native-nitro-sqlite-drizzle'

export const db = drizzle(open({ name: 'app.sqlite' }))

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().

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

Schema declarations describe your tables to Drizzle. They do not create SQLite tables. Run migrations before inserting or querying rows in a fresh database.

Drizzle Kit generates SQL migration files from your 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'
import migrations from './drizzle/migrations'
import { db } from './db'
import { users } from './db/schema'

await migrate(db, migrations)
await db.insert(users).values({ id: 1, name: 'Ada' }).onConflictDoNothing()
const rows = await db.select().from(users)

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. Unmounting the component or changing the migration bundle leaves earlier migrations queued or running. The hook reports results for its current inputs.

Transactions

Run every query inside a transaction through tx:

import { eq } from 'drizzle-orm'

await db.transaction(async (tx) => {
  await tx.insert(users).values({ id: 2, name: 'Grace' })
  await tx.update(users).set({ name: 'Ada L.' }).where(eq(users.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 every change since that savepoint, including changes from later savepoints. Savepoints cannot isolate callbacks that overlap.

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. To nest further, use the handle supplied to the nested callback:

await db.transaction(async (tx) => {
  await tx.transaction(async (child) => {
    await child.insert(users).values({ id: 3, name: 'Ada' })
    await child.transaction(async (grandchild) => {
      await grandchild.insert(users).values({ id: 4, name: 'Grace' })
    })
  })
  await tx.transaction(async (child) => {
    await child.insert(users).values({ id: 5, name: 'Linus' })
  })
})

Only one nested call can be active on each handle. Overlapping calls, including siblings started with Promise.all(), reject before executing SQL or invoking the second callback. Calls are not queued. A nested callback that calls transaction() through an ancestor handle also rejects instead of waiting on itself. Use sequential await calls for sibling work. Top-level db.transaction() calls still wait for earlier transactions on their connection, and separate connections have separate transaction scopes.

Catch a nested callback's rejection in its parent to continue after a rollback. The driver rolls back and releases that savepoint before rejecting. A savepoint setup or cleanup failure forces the outer transaction to roll back, even if you catch the error. When callback failure and cleanup failure occur together, the error's cause is an AggregateError containing both errors.

If a callback returns or throws with an active nested call, the driver waits for that child to settle, then rejects the parent and rolls back its work. Always await the child yourself. Do not leave transaction promises running after their parent callback finishes, and do not reuse transaction handles after their callbacks finish.

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

Transaction handle lifetime

SQLite savepoints share the outer transaction. A released or rolled-back savepoint no longer defines a child scope. Nitro SQLite rejects queries through a finished Drizzle child handle, including prepared queries created through it, even while the parent transaction remains active. Use the parent handle to continue, or start and await another child transaction.

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