Drizzle ORM - PostgreSQL (original) (raw)

Drizzle has native support for PostgreSQL connections with the node-postgres and postgres.js drivers.

There are a few differences between the node-postgres and postgres.js drivers that we discovered while using both and integrating them with the Drizzle ORM. For example:

node-postgres

Step 1 - Install packages

npm i drizzle-orm pg
npm i -D drizzle-kit @types/pg
yarn add drizzle-orm pg
yarn add -D drizzle-kit @types/pg
pnpm add drizzle-orm pg
pnpm add -D drizzle-kit @types/pg
bun add drizzle-orm pg
bun add -D drizzle-kit @types/pg

Step 2 - Initialize the driver and make a query

node-postgres

node-postgres with config

// Make sure to install the 'pg' package 
import { drizzle } from 'drizzle-orm/node-postgres';

const db = drizzle(process.env.DATABASE_URL);
 
const result = await db.execute('select 1');
// Make sure to install the 'pg' package 
import { drizzle } from 'drizzle-orm/node-postgres';

// You can specify any property from the node-postgres connection options
const db = drizzle({ 
  connection: { 
    connectionString: process.env.DATABASE_URL,
    ssl: true
  }
});
 
const result = await db.execute('select 1');

If you need to provide your existing driver:

// Make sure to install the 'pg' package 
import { pgTable, serial, text, varchar } from "drizzle-orm/pg-core";
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 });
 
const result = await db.execute('select 1');

postgres.js

Step 1 - Install packages

npm i drizzle-orm postgres
npm i -D drizzle-kit
yarn add drizzle-orm postgres
yarn add -D drizzle-kit
pnpm add drizzle-orm postgres
pnpm add -D drizzle-kit
bun add drizzle-orm postgres
bun add -D drizzle-kit

Step 2 - Initialize the driver and make a query

postgres.js

postgres.js with config

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

const db = drizzle(process.env.DATABASE_URL);

const result = await db.execute('select 1');
import { drizzle } from 'drizzle-orm/postgres-js';

// You can specify any property from the postgres-js connection options
const db = drizzle({ 
  connection: { 
    url: process.env.DATABASE_URL, 
    ssl: true 
  }
});

const result = await db.execute('select 1');

If you need to provide your existing driver:

// Make sure to install the 'postgres' package
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';

const queryClient = postgres(process.env.DATABASE_URL);
const db = drizzle({ client: queryClient });

const result = await db.execute('select 1');

What’s next?