---
url: /reference/sqlite.md
---

# @signaldb/sqlite

## createSQLiteAdapter (`default`)

```js
import { AsyncDataAdapter, Collection } from '@signaldb/core'
import createSQLiteAdapter from '@signaldb/sqlite'

const dataAdapter = new AsyncDataAdapter({
  storage: name => createSQLiteAdapter(driver, name),
})

const Todos = new Collection('todos', dataAdapter, {
  indices: ['listId'],
})
```

```ts
createSQLiteAdapter<T, I extends string | number = string>(
  driver: SQLiteDriver,
  tableName: string,
): StorageAdapter<T, I>
```

Persists a collection in SQLite. It works with any SQLite library: you connect
it through a small [`SQLiteDriver`](#sqlitedriver), so the package does not
depend on any of them.

* `driver`: The connection to use. Create one driver and share it between all
  collections, so their writes are queued behind each other (see
  [Transactions](#transactions)).
* `tableName`: The table the collection is stored in. Passing the collection's
  name, as in `name => createSQLiteAdapter(driver, name)`, is usually what you
  want. Any name is allowed; it is quoted as an identifier.

## `SQLiteDriver`

```ts
type SQLiteValue = string | number | null

type SQLiteDriver = {
  execute: (sql: string, parameters: SQLiteValue[]) => Promise<unknown>
  select: <R>(sql: string, parameters: SQLiteValue[]) => Promise<R[]>
}
```

* `execute` runs a statement that returns no rows.
* `select` runs a query and returns its rows as objects keyed by column name.

Both receive SQL with `?` placeholders and the values to bind to them. Mapping
your library onto this is usually a few lines.

### expo-sqlite

```ts
import { openDatabaseSync } from 'expo-sqlite'
import type { SQLiteDriver, SQLiteValue } from '@signaldb/sqlite'

const database = openDatabaseSync('app.db')

const driver: SQLiteDriver = {
  execute: (sql, parameters) => database.runAsync(sql, parameters),
  select: <R>(sql: string, parameters: SQLiteValue[]) => database.getAllAsync<R>(sql, parameters),
}
```

### op-sqlite

```ts
import { open } from '@op-engineering/op-sqlite'
import type { SQLiteDriver } from '@signaldb/sqlite'

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

const driver: SQLiteDriver = {
  execute: (sql, parameters) => database.execute(sql, parameters),
  select: async (sql, parameters) => (await database.execute(sql, parameters)).rows as any[],
}
```

### node:sqlite

```ts
import { DatabaseSync } from 'node:sqlite'
import type { SQLiteDriver } from '@signaldb/sqlite'

const database = new DatabaseSync('app.db')

const driver: SQLiteDriver = {
  execute: async (sql, parameters) => database.prepare(sql).run(...parameters),
  select: async (sql, parameters) => database.prepare(sql).all(...parameters) as any[],
}
```

## How a collection is stored

Each collection uses three tables:

| Table | Holds |
| --- | --- |
| `<tableName>` | One row per document: its `id` and the document as JSON. |
| `<tableName>__index` | One row per indexed field and document: the field, the [index key](/reference/core/createstorageadapter/#index-keys) and the id. |
| `<tableName>__indexed_fields` | The fields that are indexed. |

The adapter creates them in `setup` if they don't exist yet.

* **Documents are stored as JSON.** Values JSON cannot represent come back
  differently: a `Date` comes back as an ISO string, `undefined` fields are
  dropped.
* **Ids keep their type.** A numeric id comes back as a number, a string id as
  a string.
* **Indices survive a restart.** An index is built once, when it is first
  created, and kept up to date on every write after that. When the app starts
  again, `createIndex` finds the field in `<tableName>__indexed_fields` and does
  nothing. An index that a collection no longer declares stays and keeps being
  updated until you call `dropIndex`.

## Transactions

Every `insert`, `replace`, `remove` and `removeAll` runs in its own
transaction, so a batch is written completely or not at all. A batch that
fails (for example an `insert` of an id that already exists) is rolled back
and rejects; the writes queued after it continue.

SQLite runs one transaction per connection at a time. The adapter therefore
queues all writes per driver, across all collections that share it, and every
read waits for the writes queued before it. Statements that other code sends
through the same connection while a transaction is open become part of that
transaction, so write to the adapter's tables only through SignalDB.

## Queries

The adapter implements the optional
[`query`](/reference/core/createstorageadapter/#answering-queries-with-query)
method, which the [`AsyncDataAdapter`](/reference/core/asyncdataadapter/),
the [`AutoFetchDataAdapter`](/reference/core/autofetchdataadapter/) and the
[`WorkerDataAdapterHost`](/reference/core/workerdataadapter/) use:

* An equality on `id` (`{ id: 'abc' }`) reads only that row.
* An equality on an indexed field with a string, number or boolean value
  (`{ listId: 'abc' }`) reads only the rows the index names.
* Everything else reads the whole table and is filtered by SignalDB.

Sorting, `skip`/`limit` and projection always happen in SignalDB. SQLite
compares text by its UTF-8 bytes and JavaScript by UTF-16 code units, so an
order produced in SQL would not always match the one SignalDB produces.

So declare an index for every field your selectors filter on. A query that no
index covers reads every row of the table.
