Quick start

Lets build a quick start app with PostgreSQL + postgresjs and run our first migration.

The first thing we need to do is to install drizzle-orm and drizzle-kit:

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

Lets declare our schema.ts:

πŸ“¦ <project root>
 β”œ ...
 β”œ πŸ“‚ src
 β”‚ β”” πŸ“œ schema.ts
 β”” πŸ“œ package.json
schema.ts
import { serial, text, timestamp, pgTable } from "drizzle-orm/pg-core";

export const user = pgTable("user", {
  id: serial("id"),
  name: text("name"),
  email: text("email"),
  password: text("password"),
  role: text("role").$type<"admin" | "customer">(),
  createdAt: timestamp("created_at"),
  updatedAt: timestamp("updated_at"),
});

Now lets add drizzle configuration file:

πŸ“¦ <project root>
 β”œ ...
 β”œ πŸ“‚ src
 β”œ πŸ“œ drizzle.config.ts
 β”” πŸ“œ package.json
import type { Config } from "drizzle-kit";

export default {
  schema: "./src/schema.ts",
  out: "./drizzle",
} satisfies Config;

Add generate command to package.json and run our first migrations generation:

package.json
{
  "name": "first time?",
  "version": "0.0.1",
  "scripts": {
    "generate": "drizzle-kit generate:pg"
  }, 
}
terminal
$ npm run generate
...

[βœ“] Your SQL migration file ➜ drizzle/0000_pale_mister_fear.sql πŸš€

Done! We now have our first SQL migration file πŸ₯³

πŸ“¦ <project root>
 β”œ πŸ“‚ drizzle
 β”‚ β”œ πŸ“‚ _meta
 β”‚ β”” πŸ“œ 0000_pale_mister_fear.sql
 β”œ πŸ“‚ src
 β”œ πŸ“œ drizzle.config.ts
 β”” πŸ“œ package.json

Now lets run our first migration to the database:

πŸ“¦ <project root>
 β”œ πŸ“‚ drizzle
 β”œ πŸ“‚ src
 β”‚ β”œ πŸ“œ schema.ts
 β”‚ β”” πŸ“œ index.ts
 β”œ πŸ“œ drizzle.config.ts
 β”” πŸ“œ package.json
index.ts
import { drizzle } from "drizzle-orm/postgres-js";
import { migrate } from "drizzle-orm/postgres-js/migrator";
import postgres from "postgres";

const connectionString = "..."
const sql = postgres(connectionString, { max: 1 })
const db = drizzle(sql);

await migrate(db, { migrationsFolder: "drizzle" });

await sql.end();

That’s it, folks!

My personal congratulations πŸŽ‰