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.

1
npm i drizzle-orm postgres
2
npm i -D drizzle-kit
2

Create your models

Create a schema.ts file and define your models.

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

Connect

Connect to your database using the Connection Pooler.

From the project Connect panel, copy the URI from the "Shared Pooler" option and save it as the DATABASE_URL environment variable. Remember to replace the password placeholder with your actual database password.

In local SUPABASE_DB_URL require to be adapted to work with Docker resolver

1
import 'dotenv/config'
2
3
import { drizzle } from 'drizzle-orm/postgres-js'
4
import postgres from 'postgres'
5
6
let connectionString = process.env.DATABASE_URL
7
if (host.includes('postgres:postgres@supabase_db_')) {
8
const url = URL.parse(host)!
9
url.hostname = url.hostname.split('_')[1]
10
connectionString = url.href
11
}
12
13
// Disable prefetch as it is not supported for "Transaction" pool mode
14
export const client = postgres(connectionString, { prepare: false })
15
export const db = drizzle(client);