NitroSQLite

Drizzle ORM

Use Drizzle to query a Nitro SQLite connection in React Native or NitroUI.

Drizzle maps TypeScript table definitions to SQL. Its Nitro SQLite driver executes queries asynchronously on an open connection. A join can return two columns named id. The driver reads each value by its position, so each table keeps its own ID.

Install the driver

Install drizzle-orm (0.45.4 or a later 0.x release) alongside the driver and SQLite adapter for your runtime.

RuntimeDriverSQLite adapter
React Nativereact-native-nitro-sqlite-drizzlereact-native-nitro-sqlite
NitroUInitro-sqlite-drizzlenitro-sqlite

Install both from the alpha tag with exact versions. In React Native:

npm install --save-exact react-native-nitro-sqlite@alpha react-native-nitro-sqlite-drizzle@alpha drizzle-orm@0.45.4

In NitroUI:

bun add --exact nitro-sqlite@alpha nitro-sqlite-drizzle@alpha drizzle-orm@0.45.4

Open a database

Choose the imports for your runtime. In React Native:

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

In NitroUI:

import { open } from 'nitro-sqlite'
import { drizzle, migrate } from 'nitro-sqlite-drizzle'

The remaining code works in either runtime. Keep the connection outside components so it survives re-renders.

import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core'

const notes = sqliteTable('notes', {
  id: integer('id').primaryKey(),
  body: text('body').notNull(),
})

const connection = open({ name: 'notes.sqlite' })
const db = drizzle(connection)

Apply migrations and query the database

SQLite needs a table before it can store rows. Pass the Drizzle Kit journal and bundled SQL strings to migrate() at startup. This example includes one migration inline so it runs with either bundler.

await migrate(db, {
  journal: {
    entries: [
      { idx: 0, when: 1735689600000, tag: '0000_notes', breakpoints: true },
    ],
  },
  migrations: {
    m0000: 'CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT NOT NULL)',
  },
})

await db
  .insert(notes)
  .values({ id: 1, body: 'Hello SQLite' })
  .onConflictDoNothing()
const rows = await db.select().from(notes)

The driver records completed migrations in __drizzle_migrations. Calls on the same connection wait for earlier migrations. If a migration fails, its transaction rolls back and the caller can retry. In a component, useMigrations(db, migrations) returns { success, error }.

For transactions, await each statement on the handle passed to the callback. Await nested transactions one at a time. Close the underlying connection when the app has finished using the database.

await db.transaction(async (tx) => {
  await tx.insert(notes).values({ body: 'Another note' })
})
connection.close()

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.

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

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.