---
title: L8 - Drivers
description: Handle database connections and execute queries
icon: cable
---

**Location:** `src/drivers/`

## Why This Layer Exists

Different database clients have different APIs:

```typescript
// node-postgres
const result = await client.query(sql, params);

// PGlite (embedded)
const result = await db.exec(sql, params);

// mysql2
const [rows] = await connection.execute(sql, params);

// better-sqlite3
const rows = db.prepare(sql).all(...params);
```

Drivers abstract these differences behind a common interface.

## Driver Interface

Drivers extend the abstract `Driver` base class (see `src/drivers/driver.ts`). It is generic over the underlying client and transaction handle, carries its dialect's facts (a SQL driver's are its SQL adapter), and manages lazy connection, transaction queuing, and error mapping. Subclasses implement five methods and provide their typed result parser:

```typescript
abstract class Driver<TClient, TTransaction> {
  readonly dialect: Dialect;                    // "postgresql" | "mysql" | "sqlite" | "surrealql"
  readonly driverName: string;
  abstract readonly adapter: EngineFacts;       // what the engine asks of every driver; a SQL driver's is its DatabaseAdapter
  readonly backend?: QueryBackend;              // what writes its statements where the database reads no SQL (SurrealDB)
  abstract readonly result: DriverResultParser; // physical-to-logical result codecs
  readonly supportsTransactions: boolean;       // false for batch-only clients (D1 binding, Neon HTTP)
  readonly supportsBatch: boolean;              // true for atomic-batch APIs (D1, Neon HTTP)

  // Subclasses implement:
  protected abstract initClient(): Promise<TClient>;
  protected abstract closeClient(client: TClient | TTransaction): Promise<void>;
  protected abstract execute<T>(client, sql, params, context?): Promise<QueryResult<T>>;
  protected abstract executeRaw<T>(client, sql, params, context?): Promise<QueryResult<T>>;
  protected abstract transaction<T>(client, fn: (tx: TTransaction) => Promise<T>, context?): Promise<T>;
}
```

A custom SQLite driver can reuse the stock field-aware parser:

```typescript
import { Driver, sqliteResultParser } from "viborm/driver";

class CustomSQLiteDriver extends Driver<CustomClient, CustomTransaction> {
  readonly result = sqliteResultParser;
  // Implement the adapter and provider methods shown above.
}
```

The parser is required for typed SQLite booleans, integers, dates, JSON and
other physical representations. Raw execution returns physical provider values.

Its `adapter` is a `SQLiteAdapter` (from `viborm/adapters`) whose options state
what the transport refuses. Each one defaults to plain SQLite; set only what
your platform differs on:

| Option | Set it when | Example |
|---|---|---|
| `temporaryObjects: false` | the transport refuses `CREATE TEMP TABLE` (`SQLITE_AUTH`) | D1, Durable Objects |
| `deepExpressions: false` | SQLite was compiled with a small expression depth ("Expression tree is too large") | D1, Durable Objects (depth 100) |
| `sharedRelationBodies: true` | the transport bounds statement text and repeated relation filters reach it | D1 (100 KB) |
| `compoundSelectTerms: n` | a compound `SELECT` admits at most `n` terms | D1 (5) |
| `relationsPerStatement: n` | the planner bounds the relations one statement references | D1 (256) |
| `countsCascadedChanges: true` | the affected-row count includes rows a cascade changed | D1 |

`sharedRelationBodies` trades CPU for text: measured on a Durable Object with a
large permissions policy, `can` costs about 40 % more with it. Leave it off
unless statements reach the text limit. Also declare
`maxBindParametersPerStatement` when the platform bounds bound values (100 on
D1 and Durable Objects): VibORM then splits or refuses an oversized statement
before it reaches the database.

Declare `readonly sqliteMigrationCapability = SQLITE_MIGRATION_CAPABILITY` (from
`viborm/driver`) to use migrations; see
[SQLite migrations](/docs/migration/drivers/sqlite#driver-admission). For a
Durable Object's storage, use [`viborm/durable-object`](/docs/drivers/sqlite/durable-object),
which declares the Durable Object capability and implements its migration frame.

## Available Drivers

| Driver | Entry Point | Client | Use Case |
|--------|-------------|--------|----------|
| `PgDriver` | `viborm/pg` | node-postgres | PostgreSQL servers |
| `PostgresDriver` | `viborm/postgres` | postgres.js | PostgreSQL servers |
| `PGliteDriver` | `viborm/pglite` | PGlite | Embedded PostgreSQL |
| `NeonHTTPDriver` | `viborm/neon-http` | Neon HTTP | Serverless PostgreSQL |
| `BunSQLDriver` | `viborm/bun-sql` | Bun SQL | PostgreSQL from Bun |
| `MySQL2Driver` | `viborm/mysql2` | mysql2 | MySQL servers |
| `PlanetScaleDriver` | `viborm/planetscale` | PlanetScale | Serverless MySQL |
| `SQLite3Driver` | `viborm/sqlite3` | better-sqlite3 | SQLite files |
| `LibSQLDriver` | `viborm/libsql` | libSQL | Turso / libSQL |
| `BunSQLiteDriver` | `viborm/bun-sqlite` | bun:sqlite | SQLite from Bun |
| `D1Driver` | `viborm/d1` | D1 binding | Cloudflare Workers |
| `createDurableObjectDriver` | `viborm/durable-object` | `ctx.storage` | Cloudflare Durable Objects |

## What Drivers Handle

### Connection Management

Drivers connect lazily and accept either an existing client or connection options. For example, `PostgresDriver` (postgres.js):

```typescript
const driver = new PostgresDriver({
  databaseUrl: "postgres://...",  // or options: { host, port, database, ... }
  // client: existingPostgresJsInstance,
  // pgvector: true,
  // postgis: true,
});
```

### Parameterization

Drivers ensure queries use parameterized values:

```typescript
// Adapter-built SQL fragment composed by the query engine
sql`SELECT * FROM users WHERE id = ${userId}`

// Driver separates template and values
query: "SELECT * FROM users WHERE id = $1"
params: [userId]
```

### Result Transformation

Some databases return results in different formats. Drivers normalize this:

```typescript
// MySQL returns [rows, fields]
// PostgreSQL returns { rows, rowCount }
// Drivers return just the rows
```

### Error Handling

Database-specific errors are normalized into typed VibORM errors (see `src/drivers/error-mapping.ts`):

```typescript
// PostgreSQL: error code "23505"
// MySQL: errno 1062 / "ER_DUP_ENTRY"
// SQLite: "SQLITE_CONSTRAINT_UNIQUE"
// Driver: throws UniqueConstraintError
```

Provider recognition stops at this boundary. The driver maps provider codes,
constraint names, and assertion markers. The query engine can then combine a
typed unique failure with the structural `racePin` on a write; it does not parse
provider SQL or error text itself.

### Fragment Execution

Drivers do not interpret `PlanningFragment`, `OperationFragment`, relation
programs, or guards. `OperationExecutor` lowers those concepts into the surface
the driver owns:

- one statement for a structural direct candidate;
- ordered statements inside a transaction;
- one atomic `BatchQuery[]` envelope for a batch-capable driver.

Adapter `batchRefs` lower produced-value references for atomic batches. Drivers
execute the resulting batch and return normalized results in the same order.

## Connection to Other Layers

- **L6 (Query Engine)**: Query engine lowers portable fragments to driver statements or batches
- **L7 (Adapters)**: Adapters determine SQL dialect, drivers execute it
- **L9 (Client)**: Client uses driver through query engine
