or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-features.mddatabase-connections.mdindex.mdquery-building.mdrelational-queries.mdschema-definition.md

database-connections.mddocs/

0

# Database Connections

1

2

Drizzle ORM provides database connection management for multiple database providers with type-safe configuration, connection pooling, transactions, and runtime-specific optimizations.

3

4

## PostgreSQL Connections

5

6

### Node.js PostgreSQL (pg)

7

8

```typescript { .api }

9

function drizzle<TSchema extends Record<string, unknown>>(

10

client: Pool | PoolClient | string,

11

config?: DrizzleConfig<TSchema>

12

): NodePgDatabase<TSchema>;

13

14

interface DrizzleConfig<TSchema extends Record<string, unknown>> {

15

schema?: TSchema;

16

logger?: Logger | boolean;

17

cache?: Cache;

18

casing?: CasingCache;

19

}

20

```

21

22

Usage:

23

24

```typescript

25

import { drizzle } from "drizzle-orm/node-postgres";

26

import { Pool } from "pg";

27

28

// With connection pool

29

const pool = new Pool({

30

connectionString: "postgresql://username:password@localhost:5432/db"

31

});

32

const db = drizzle(pool);

33

34

// With connection string directly

35

const db = drizzle("postgresql://username:password@localhost:5432/db");

36

37

// With schema and configuration

38

const db = drizzle(pool, {

39

schema: { users, posts },

40

logger: true,

41

});

42

```

43

44

### Postgres.js

45

46

```typescript { .api }

47

function drizzle<TSchema extends Record<string, unknown>>(

48

client: Sql<any> | string,

49

config?: DrizzleConfig<TSchema>

50

): PostgresJsDatabase<TSchema>;

51

```

52

53

Usage:

54

55

```typescript

56

import { drizzle } from "drizzle-orm/postgres-js";

57

import postgres from "postgres";

58

59

const sql = postgres("postgresql://username:password@localhost:5432/db");

60

const db = drizzle(sql);

61

```

62

63

### Neon (HTTP)

64

65

```typescript { .api }

66

function drizzle<TSchema extends Record<string, unknown>>(

67

client: NeonHttpClient | string,

68

config?: DrizzleConfig<TSchema>

69

): NeonHttpDatabase<TSchema>;

70

```

71

72

Usage:

73

74

```typescript

75

import { drizzle } from "drizzle-orm/neon-http";

76

import { neon } from "@neondatabase/serverless";

77

78

const sql = neon("postgresql://username:password@hostname/db");

79

const db = drizzle(sql);

80

```

81

82

### Neon (Serverless)

83

84

```typescript { .api }

85

function drizzle<TSchema extends Record<string, unknown>>(

86

client: NeonServerlessClient | string,

87

config?: DrizzleConfig<TSchema>

88

): NeonServerlessDatabase<TSchema>;

89

```

90

91

Usage:

92

93

```typescript

94

import { drizzle } from "drizzle-orm/neon-serverless";

95

import { Pool } from "@neondatabase/serverless";

96

97

const pool = new Pool({ connectionString: "postgresql://..." });

98

const db = drizzle(pool);

99

```

100

101

### Vercel Postgres

102

103

```typescript { .api }

104

function drizzle<TSchema extends Record<string, unknown>>(

105

client: VercelPool | string,

106

config?: DrizzleConfig<TSchema>

107

): VercelPgDatabase<TSchema>;

108

```

109

110

Usage:

111

112

```typescript

113

import { drizzle } from "drizzle-orm/vercel-postgres";

114

import { sql as vercelSql } from "@vercel/postgres";

115

116

const db = drizzle(vercelSql);

117

```

118

119

### AWS RDS Data API (PostgreSQL)

120

121

```typescript { .api }

122

function drizzle<TSchema extends Record<string, unknown>>(

123

config: AwsDataApiPgConfig,

124

drizzleConfig?: DrizzleConfig<TSchema>

125

): AwsDataApiPgDatabase<TSchema>;

126

127

interface AwsDataApiPgConfig {

128

client: RDSDataClient;

129

resourceArn: string;

130

secretArn: string;

131

database: string;

132

}

133

```

134

135

### PGlite

136

137

```typescript { .api }

138

function drizzle<TSchema extends Record<string, unknown>>(

139

client: PGliteClient,

140

config?: DrizzleConfig<TSchema>

141

): PgliteDatabase<TSchema>;

142

```

143

144

Usage:

145

146

```typescript

147

import { drizzle } from "drizzle-orm/pglite";

148

import { PGlite } from "@electric-sql/pglite";

149

150

const client = new PGlite();

151

const db = drizzle(client);

152

```

153

154

## MySQL Connections

155

156

### MySQL2

157

158

```typescript { .api }

159

function drizzle<TSchema extends Record<string, unknown>>(

160

client: Connection | Pool | string,

161

config?: DrizzleConfig<TSchema>

162

): MySql2Database<TSchema>;

163

```

164

165

Usage:

166

167

```typescript

168

import { drizzle } from "drizzle-orm/mysql2";

169

import mysql from "mysql2/promise";

170

171

// With connection

172

const connection = await mysql.createConnection({

173

host: "localhost",

174

user: "root",

175

password: "password",

176

database: "test"

177

});

178

const db = drizzle(connection);

179

180

// With connection pool

181

const pool = mysql.createPool({

182

host: "localhost",

183

user: "root",

184

password: "password",

185

database: "test"

186

});

187

const db = drizzle(pool);

188

```

189

190

### PlanetScale Serverless

191

192

```typescript { .api }

193

function drizzle<TSchema extends Record<string, unknown>>(

194

client: PlanetScaleConnection | string,

195

config?: DrizzleConfig<TSchema>

196

): PlanetScaleDatabase<TSchema>;

197

```

198

199

Usage:

200

201

```typescript

202

import { drizzle } from "drizzle-orm/planetscale-serverless";

203

import { connect } from "@planetscale/database";

204

205

const connection = connect({

206

url: process.env.DATABASE_URL

207

});

208

const db = drizzle(connection);

209

```

210

211

### TiDB Serverless

212

213

```typescript { .api }

214

function drizzle<TSchema extends Record<string, unknown>>(

215

client: TiDBServerlessConnection,

216

config?: DrizzleConfig<TSchema>

217

): TiDBServerlessDatabase<TSchema>;

218

```

219

220

## SQLite Connections

221

222

### Better-SQLite3

223

224

```typescript { .api }

225

function drizzle<TSchema extends Record<string, unknown>>(

226

client: BetterSQLite3Database | string,

227

config?: DrizzleConfig<TSchema>

228

): BetterSQLite3Database<TSchema>;

229

```

230

231

Usage:

232

233

```typescript

234

import { drizzle } from "drizzle-orm/better-sqlite3";

235

import Database from "better-sqlite3";

236

237

const sqlite = new Database("sqlite.db");

238

const db = drizzle(sqlite);

239

240

// In-memory database

241

const sqlite = new Database(":memory:");

242

const db = drizzle(sqlite);

243

```

244

245

### Bun SQLite

246

247

```typescript { .api }

248

function drizzle<TSchema extends Record<string, unknown>>(

249

client: BunDatabase,

250

config?: DrizzleConfig<TSchema>

251

): BunSQLiteDatabase<TSchema>;

252

```

253

254

Usage:

255

256

```typescript

257

import { drizzle } from "drizzle-orm/bun-sqlite";

258

import { Database } from "bun:sqlite";

259

260

const sqlite = new Database("sqlite.db");

261

const db = drizzle(sqlite);

262

```

263

264

### LibSQL/Turso

265

266

```typescript { .api }

267

function drizzle<TSchema extends Record<string, unknown>>(

268

client: LibSQLClient,

269

config?: DrizzleConfig<TSchema>

270

): LibSQLDatabase<TSchema>;

271

```

272

273

Usage:

274

275

```typescript

276

import { drizzle } from "drizzle-orm/libsql";

277

import { createClient } from "@libsql/client";

278

279

// Local SQLite file

280

const client = createClient({ url: "file:local.db" });

281

const db = drizzle(client);

282

283

// Turso

284

const client = createClient({

285

url: "libsql://your-database.turso.io",

286

authToken: "your-auth-token"

287

});

288

const db = drizzle(client);

289

```

290

291

### Cloudflare D1

292

293

```typescript { .api }

294

function drizzle<TSchema extends Record<string, unknown>>(

295

client: D1Database,

296

config?: DrizzleConfig<TSchema>

297

): D1Database<TSchema>;

298

```

299

300

Usage:

301

302

```typescript

303

import { drizzle } from "drizzle-orm/d1";

304

305

// In Cloudflare Workers

306

export default {

307

async fetch(request: Request, env: Env) {

308

const db = drizzle(env.DB);

309

// Use db...

310

},

311

};

312

```

313

314

### SQL.js (Browser SQLite)

315

316

```typescript { .api }

317

function drizzle<TSchema extends Record<string, unknown>>(

318

client: SqlJsDatabase,

319

config?: DrizzleConfig<TSchema>

320

): SqlJsDatabase<TSchema>;

321

```

322

323

Usage:

324

325

```typescript

326

import { drizzle } from "drizzle-orm/sql-js";

327

import initSqlJs from "sql.js";

328

329

const SQL = await initSqlJs();

330

const sqlite = new SQL.Database();

331

const db = drizzle(sqlite);

332

```

333

334

### Expo SQLite

335

336

```typescript { .api }

337

function drizzle<TSchema extends Record<string, unknown>>(

338

client: ExpoSQLiteDatabase,

339

config?: DrizzleConfig<TSchema>

340

): ExpoSQLiteDatabase<TSchema>;

341

```

342

343

Usage:

344

345

```typescript

346

import { drizzle } from "drizzle-orm/expo-sqlite";

347

import { openDatabaseSync } from "expo-sqlite";

348

349

const expo = openDatabaseSync("db.db");

350

const db = drizzle(expo);

351

```

352

353

### React Native op-sqlite

354

355

```typescript { .api }

356

function drizzle<TSchema extends Record<string, unknown>>(

357

client: OPSQLiteConnection,

358

config?: DrizzleConfig<TSchema>

359

): OPSQLiteDatabase<TSchema>;

360

```

361

362

Usage:

363

364

```typescript

365

import { drizzle } from "drizzle-orm/op-sqlite";

366

import { open } from "@op-engineering/op-sqlite";

367

368

const db = open({

369

name: "myDB.sqlite",

370

});

371

const drizzleDb = drizzle(db);

372

```

373

374

## Configuration Options

375

376

### DrizzleConfig Interface

377

378

```typescript { .api }

379

interface DrizzleConfig<TSchema extends Record<string, unknown>> {

380

schema?: TSchema;

381

logger?: Logger | boolean;

382

cache?: Cache;

383

casing?: CasingCache;

384

}

385

```

386

387

### Schema Configuration

388

389

```typescript

390

// With relational schema

391

const db = drizzle(client, {

392

schema: { users, posts, usersRelations, postsRelations }

393

});

394

```

395

396

### Logging Configuration

397

398

```typescript { .api }

399

interface Logger {

400

logQuery(query: string, params: unknown[]): void;

401

}

402

403

class DefaultLogger implements Logger {

404

logQuery(query: string, params: unknown[]): void;

405

}

406

```

407

408

Usage:

409

410

```typescript

411

// Enable default logging

412

const db = drizzle(client, { logger: true });

413

414

// Custom logger

415

const db = drizzle(client, {

416

logger: {

417

logQuery: (query, params) => {

418

console.log("Query:", query, "Params:", params);

419

}

420

}

421

});

422

```

423

424

### Caching Configuration

425

426

```typescript { .api }

427

interface Cache {

428

get<T>(key: string): Promise<T | null>;

429

set(key: string, value: unknown, ttl?: number): Promise<void>;

430

delete(key: string): Promise<void>;

431

clear(): Promise<void>;

432

onMutate?: () => Promise<void>;

433

}

434

```

435

436

Usage:

437

438

```typescript

439

// Custom cache implementation

440

const cache: Cache = {

441

async get(key) { /* implementation */ },

442

async set(key, value, ttl) { /* implementation */ },

443

async delete(key) { /* implementation */ },

444

async clear() { /* implementation */ },

445

};

446

447

const db = drizzle(client, { cache });

448

```

449

450

## Transaction Support

451

452

```typescript { .api }

453

interface Database {

454

transaction<T>(

455

transaction: (tx: Transaction) => Promise<T>

456

): Promise<T>;

457

}

458

```

459

460

Usage:

461

462

```typescript

463

await db.transaction(async (tx) => {

464

await tx.insert(users).values({ name: "John" });

465

await tx.insert(posts).values({ title: "Hello", authorId: 1 });

466

});

467

```

468

469

## Connection Pooling

470

471

Most drivers support connection pooling automatically:

472

473

```typescript

474

// PostgreSQL with pg

475

import { Pool } from "pg";

476

const pool = new Pool({

477

connectionString: "postgresql://...",

478

max: 20,

479

idleTimeoutMillis: 30000,

480

connectionTimeoutMillis: 2000,

481

});

482

483

// MySQL with mysql2

484

import mysql from "mysql2/promise";

485

const pool = mysql.createPool({

486

host: "localhost",

487

user: "root",

488

password: "password",

489

database: "test",

490

waitForConnections: true,

491

connectionLimit: 10,

492

queueLimit: 0

493

});

494

```

495

496

## Environment-Specific Drivers

497

498

### Edge Runtime Compatible

499

- `drizzle-orm/neon-http`

500

- `drizzle-orm/planetscale-serverless`

501

- `drizzle-orm/d1`

502

503

### Node.js Specific

504

- `drizzle-orm/node-postgres`

505

- `drizzle-orm/mysql2`

506

- `drizzle-orm/better-sqlite3`

507

508

### Browser Compatible

509

- `drizzle-orm/sql-js`

510

511

### Mobile (React Native/Expo)

512

- `drizzle-orm/expo-sqlite`

513

- `drizzle-orm/op-sqlite`

514

515

### Runtime Agnostic

516

- `drizzle-orm/postgres-js`

517

- `drizzle-orm/libsql`

518

519

## Types

520

521

```typescript { .api }

522

// Core database configuration types

523

interface DrizzleConfig<TSchema extends Record<string, unknown>> {

524

schema?: TSchema;

525

logger?: Logger | boolean;

526

cache?: Cache;

527

casing?: any;

528

}

529

530

interface Logger {

531

logQuery(query: string, params: unknown[]): void;

532

}

533

534

interface Cache {

535

get<T>(key: string): Promise<T | null>;

536

set(key: string, value: unknown, ttl?: number): Promise<void>;

537

delete(key: string): Promise<void>;

538

clear(): Promise<void>;

539

onMutate?: () => Promise<void>;

540

}

541

542

// Database client types

543

type NodePgClient = any; // pg.Pool | pg.Client

544

type MySqlClient = any; // mysql2.Connection | mysql2.Pool

545

type SQLiteClient = any; // Database instance

546

type NeonHttpClient = any;

547

type NeonServerlessClient = any;

548

type VercelPool = any;

549

type PlanetScaleConnection = any;

550

type TiDBServerlessConnection = any;

551

type LibSQLClient = any;

552

type D1Database = any;

553

type SqlJsDatabase = any;

554

type ExpoSQLiteDatabase = any;

555

type OPSQLiteConnection = any;

556

type BunDatabase = any;

557

type PGliteClient = any;

558

type BetterSQLite3Database = any;

559

560

// Query result types

561

interface QueryResultHKT {

562

readonly hkt: any;

563

}

564

565

interface NodePgQueryResultHKT extends QueryResultHKT {}

566

interface MySql2QueryResultHKT extends QueryResultHKT {}

567

interface BetterSQLite3QueryResultHKT extends QueryResultHKT {}

568

569

// Database instance types

570

type NodePgDatabase<TSchema extends Record<string, unknown> = Record<string, never>> = PgDatabase<NodePgQueryResultHKT, TSchema>;

571

type MySql2Database<TSchema extends Record<string, unknown> = Record<string, never>> = MySqlDatabase<MySql2QueryResultHKT, TSchema>;

572

type BetterSQLite3Database<TSchema extends Record<string, unknown> = Record<string, never>> = SQLiteDatabase<BetterSQLite3QueryResultHKT, TSchema>;

573

type PostgresJsDatabase<TSchema extends Record<string, unknown> = Record<string, never>> = PgDatabase<any, TSchema>;

574

type NeonHttpDatabase<TSchema extends Record<string, unknown> = Record<string, never>> = PgDatabase<any, TSchema>;

575

type NeonServerlessDatabase<TSchema extends Record<string, unknown> = Record<string, never>> = PgDatabase<any, TSchema>;

576

type VercelPgDatabase<TSchema extends Record<string, unknown> = Record<string, never>> = PgDatabase<any, TSchema>;

577

type AwsDataApiPgDatabase<TSchema extends Record<string, unknown> = Record<string, never>> = PgDatabase<any, TSchema>;

578

type PgliteDatabase<TSchema extends Record<string, unknown> = Record<string, never>> = PgDatabase<any, TSchema>;

579

type PlanetScaleDatabase<TSchema extends Record<string, unknown> = Record<string, never>> = MySqlDatabase<any, TSchema>;

580

type TiDBServerlessDatabase<TSchema extends Record<string, unknown> = Record<string, never>> = MySqlDatabase<any, TSchema>;

581

type BunSQLiteDatabase<TSchema extends Record<string, unknown> = Record<string, never>> = SQLiteDatabase<any, TSchema>;

582

type LibSQLDatabase<TSchema extends Record<string, unknown> = Record<string, never>> = SQLiteDatabase<any, TSchema>;

583

type D1SQLiteDatabase<TSchema extends Record<string, unknown> = Record<string, never>> = SQLiteDatabase<any, TSchema>;

584

585

// Base database interfaces

586

interface PgDatabase<TQueryResult extends QueryResultHKT, TSchema extends Record<string, unknown>> {

587

select(): any;

588

insert<T extends any>(table: T): any;

589

update<T extends any>(table: T): any;

590

delete<T extends any>(table: T): any;

591

query: TSchema extends Record<string, never> ? never : any;

592

transaction<T>(transaction: (tx: any) => Promise<T>): Promise<T>;

593

}

594

595

interface MySqlDatabase<TQueryResult extends QueryResultHKT, TSchema extends Record<string, unknown>> {

596

select(): any;

597

insert<T extends any>(table: T): any;

598

update<T extends any>(table: T): any;

599

delete<T extends any>(table: T): any;

600

query: TSchema extends Record<string, never> ? never : any;

601

transaction<T>(transaction: (tx: any) => Promise<T>): Promise<T>;

602

}

603

604

interface SQLiteDatabase<TQueryResult extends QueryResultHKT, TSchema extends Record<string, unknown>> {

605

select(): any;

606

insert<T extends any>(table: T): any;

607

update<T extends any>(table: T): any;

608

delete<T extends any>(table: T): any;

609

query: TSchema extends Record<string, never> ? never : any;

610

transaction<T>(transaction: (tx: any) => Promise<T>): Promise<T>;

611

}

612

613

// AWS Data API config

614

interface AwsDataApiPgConfig {

615

client: any; // RDSDataClient

616

resourceArn: string;

617

secretArn: string;

618

database: string;

619

}

620

621

// Transaction interface

622

interface Transaction {

623

select(): any;

624

insert<T extends any>(table: T): any;

625

update<T extends any>(table: T): any;

626

delete<T extends any>(table: T): any;

627

}

628

```