NitroSQLite
Guides

Attach databases

Query another database file through a named SQLite schema.

Use db.attach() to query another database file through an existing connection. Its alias becomes a SQLite schema name, which distinguishes its tables from those in the main database. Use it when one query needs data from both files.

Attach and query a database

In NitroSQLite, call attach() on an open connection. The alias becomes the SQLite schema name. Use the same platform root and relative location convention as open().

import { open } from 'react-native-nitro-sqlite'

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

db.attach('archive.sqlite', 'archive', 'databases')

const { results } = db.execute(
  `SELECT main.notes.id, archive.history.note
   FROM main.notes
   JOIN archive.history ON archive.history.note_id = main.notes.id`,
)

db.detach('archive')
db.close()

File paths and aliases

The example assumes the tables and files already exist. SQLite can create the attached file when it is missing, so verify the intended path when opening prepopulated data. attach() and detach() are synchronous connection operations; they fail while the connection queue is busy. A failed attach or detach throws NitroSQLiteError through the connection wrapper.

NitroSQLite binds the filename and schema alias as parameters, including Unicode characters and apostrophes. Aliases can contain spaces or quotes. Quote a schema name as an SQL identifier when using it in a query. Query values still belong in ? parameters.

For compatibility, a complete alias enclosed in double quotes, single quotes, backticks, or square brackets is interpreted as the existing quoted name. For example, db.attach('archive.sqlite', '"sales archive"') and db.attach('archive.sqlite', 'sales archive') both attach the schema sales archive. Either form works with detach() too. Doubled quote characters inside a quoted name are decoded. Square brackets have no escape syntax.

A full pair of quotes is ambiguous with a literal name that includes those quote characters. Legacy quoting takes precedence. To name a schema "archive" including its quote characters, pass the SQL-quoted alias '"""archive"""' to both attach() and detach(). Other raw aliases are preserved, including incomplete quoting. Aliases are never executed as SQL.

Only pass database names and locations you control. Path segments such as .. are not validated. See database lifecycle for the location convention and the generated NitroSQLiteConnection reference for signatures.

On this page