# Database

> Browse tables, edit rows and run SQL against your app's SQLite databases, or against a PostgreSQL, MySQL, MariaDB or SQLite database the desktop app connects to. Your app's databases are off until you pass them.

The Database panel lists the tables in a database, pages through their rows, and runs SQL. It works with the SQLite databases in your app, and with PostgreSQL, MySQL, MariaDB and SQLite databases the desktop app connects to directly.

[Using Database in the desktop app](/docs/desktop/database/)

## Setup

* In your app

  **Accepts** `false | Record<string, DatabaseAdapter>` Opt-in

  Pass each database to `init()` with the adapter for its driver: `expoSqliteAdapter` for `expo-sqlite` and `opSqliteAdapter` for `@op-engineering/op-sqlite`.

  *index.ts*

  ```ts
  import { open } from '@op-engineering/op-sqlite';
  import { expoSqliteAdapter, init, opSqliteAdapter } from '@xerlock/client';
  import * as SQLite from 'expo-sqlite';

  init({
    database: {
      main: expoSqliteAdapter(SQLite.openDatabaseAsync('app.db')),
      cache: opSqliteAdapter(open({ name: 'cache.db' })),
    },
  });
  ```

  Each key is the name the panel shows. An adapter takes the database handle, a promise of one, or a function that returns either.

* Direct connection

  Nothing goes in your app. Add the connection in the desktop app, as described in [Adding a connection](#adding-a-connection).

### Opening the database on first use

For an app database, pass a function instead of a handle to open it the first time the panel asks for it, not when `init()` runs. If the function throws or rejects, the next request calls it again.

*index.ts*

```ts
import { expoSqliteAdapter, init } from '@xerlock/client';
import * as SQLite from 'expo-sqlite';

let db: SQLite.SQLiteDatabase | null = null;

init({
  database: {
    main: expoSqliteAdapter(() => (db ??= SQLite.openDatabaseSync('app.db'))),
  },
});
```

### Custom adapters

To use another SQLite driver, pass an object with an `execute` function. It runs the SQL the panel sends, with any parameters, and returns the column names and rows. The panel sends SQLite SQL, such as `PRAGMA table_info` and `rowid`, so the driver must be SQLite.

*index.ts*

```ts
import { init, type DatabaseAdapter } from '@xerlock/client';

type MyDriver = {
  run(
    sql: string,
    params: unknown[],
  ): Promise<{ columns: string[]; rows: unknown[][]; changes: number }>;
};

declare const myDriver: MyDriver;

const customAdapter: DatabaseAdapter = {
  execute: async (sql, params = []) => {
    const result = await myDriver.run(sql, [...params]);
    return { columns: result.columns, rows: result.rows, rowsAffected: result.changes };
  },
};

init({
  database: { custom: customAdapter },
});
```

Show the full example

| Member                                                                               | Description                                                                                              |
| ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------- |
| `execute(sql: string, params?: readonly SqlValue[]): Promise<DatabaseExecuteOutput>` | Runs `sql` with the given bound params and resolves to its columns, rows and, for a write, rowsAffected. |

### Shapes

The SDK doesn’t depend on `expo-sqlite` or `@op-engineering/op-sqlite`. Any handle with these shapes works:

| Member                                                        | Description                   |
| ------------------------------------------------------------- | ----------------------------- |
| `prepareAsync(sql: string): Promise<ExpoSQLiteStatementLike>` | Prepares `sql` for execution. |

| Member                                                                                   | Description                                                                                                           |
| ---------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `execute(sql: string, params?: SqlDriverValue[]): Promise<OpSQLiteExecuteResult>`        | Runs `sql` with the given bound params and resolves to its rows, rowsAffected and (optionally) column names.          |
| `executeRaw?(sql: string, params?: SqlDriverValue[]): Promise<OpSQLiteRawExecuteResult>` | Same as `execute`, but resolves to value arrays instead of row objects, preserving duplicate column names from joins. |

### Turning it off

Leave out `database`, or pass `false`.

In release builds the adapters do nothing, but a handle or promise you pass is still opened by your own code. Pass a function if the database is only opened for Xerlock.

## Limits and Troubleshooting

* **The panel says “No databases yet”**: pass `database` to `init()`, or add a connection.
