Database connection with Drizzle
Drizzle ORM runs SQL queries on your database via database drivers .
import { drizzle } from "drizzle-orm/node-postgres"
import { users } from "./schema"
const db = drizzle ( process . env . DATABASE_URL );
const usersCount = await db .$count (users);
ββββββββββββββββββββββββ
β db.$count(users) β <--- drizzle query
ββββββββββββββββββββββββ
β Κ
select count(*) from users -β β
β β- [{ count: 0 }]
v β
βββββββββββββββββββββββ
β node-postgres β <--- database driver
βββββββββββββββββββββββ
β Κ
01101000 01100101 01111001 -β β
β β- 01110011 01110101 01110000
v β
ββββββββββββββββββββββ
β Database β
ββββββββββββββββββββββ
import { pgTable , integer , text } from "drizzle-orm" ;
export const users = pgTable ( "users" , {
id : integer ( "id" ) .generateAlwaysAsIdentity () ,
name : text ( "name" ) ,
})
Under the hood Drizzle will create a node-postgres driver instance which you can access via db.$client
if necessary
import { drizzle } from "drizzle-orm/node-postgres"
const db = drizzle ( process . env . DATABASE_URL );
const pool = db .$client;
// above is equivalent to
import { drizzle } from "drizzle-orm/node-postgres" ;
import { Pool } from "pg" ;
const pool = new Pool ({
connectionString : process . env . DATABASE_URL ,
});
const db = drizzle ({ client : pool });
Drizzle is by design natively compatible with every edge or serverless runtime, whenever youβd need access to a serverless database - weβve got you covered
Neon HTTP
Neon with websockets
Vercel Postgres
PlanetScale HTTP
Cloudflare d1
import { drizzle } from "drizzle-orm/neon-http" ;
const db = drizzle ( process . env . DATABASE_URL );
import { drizzle } from "drizzle-orm/neon-serverless" ;
const db = drizzle ( process . env . DATABASE_URL );
import { drizzle } from "drizzle-orm/vercel-postgres" ;
const db = drizzle ();
import { drizzle } from "drizzle-orm/planetscale" ;
const db = drizzle ( process . env . DATABASE_URL );
import { drizzle } from "drizzle-orm/d1" ;
const db = drizzle ({ connection : env . DB });
And yes, we do support runtime specific drivers like Bun SQLite or Expo SQLite :
import { drizzle } from "drizzle-orm/bun-sqlite"
const db = drizzle (); // <--- will create an in-memory db
const db = drizzle ( "./sqlite.db" );
import { drizzle } from "drizzle-orm/expo-sqlite" ;
import { openDatabaseSync } from "expo-sqlite/next" ;
const expo = openDatabaseSync ( "db.db" );
const db = drizzle (expo);
Database connection URL
Just in case if youβre not familiar with database connection URL concept
postgresql://alex:[email protected] /dbname
ββββ βββββββββ βββββββββββββββββββββββββββββββββββββββββββββββ ββββββ
Κ Κ Κ Κ
role -β β β- hostname β- database
β
β- password
Next steps
Feel free to check out per-driver documentations