Database

Drizzle


Connecting with Drizzle

Drizzle ORM is a TypeScript ORM for SQL databases designed with maximum type safety in mind. You can use their ORM to connect to your database.

1

Install

Install Drizzle and related dependencies.


_10
npm i drizzle-orm postgres
_10
npm i -D drizzle-kit

2

Create your models

Create a schema.ts file and define your models.

schema.ts

_10
import { pgTable, serial, text, varchar } from "drizzle-orm/pg-core";
_10
_10
export const users = pgTable('users', {
_10
id: serial('id').primaryKey(),
_10
fullName: text('full_name'),
_10
phone: varchar('phone', { length: 256 }),
_10
});

3

Connect

Connect to your database using the Connection Pooler.

In your Database Settings, make sure Use connection pooler is checked, then copy the URI and save it as the DATABASE_URL environment variable. Remember to replace the password placeholder with your actual database password.

db.ts

_10
import 'dotenv/config'
_10
_10
import { drizzle } from 'drizzle-orm/postgres-js'
_10
import postgres from 'postgres'
_10
_10
const connectionString = process.env.DATABASE_URL
_10
_10
// Disable prefetch as it is not supported for "Transaction" pool mode
_10
export const client = postgres(connectionString, { prepare: false })
_10
export const db = drizzle(client);