

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Postgres
incomplete
2: Drizzle ORM
incomplete
3: Drizzle Queries
incomplete
4: Reset
incomplete
5: List Users
incomplete
This lesson's interactive features are locked, please to keep using them
Drizzle is a ORM and migration tool written in TypeScript. Its API and syntax is very similar to SQL, making it a perfect fit for this project (we wanna stay close to the raw SQL).
A migration is just a set of changes to your database table. You can have as many migrations as needed as your requirements change over time. For example, one migration might create a new table, one might delete a column, and one might add 2 new columns.
An "up" migration moves the state of the database from its current schema to the schema that you want. So, to get a "blank" database to the state it needs to be ready to run your application, you run all the "up" migrations.
If something breaks, you can run one of the "down" migrations to revert the database to a previous state. "Down" migrations are also used if you need to reset a local testing database to a known state.
npm i drizzle-orm postgres
npm i -D drizzle-kit
import { pgTable, timestamp, uuid, text } from "drizzle-orm/pg-core";
export const users = pgTable("users", {
id: uuid("id").primaryKey().defaultRandom().notNull(),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedAt: timestamp("updated_at")
.notNull()
.defaultNow()
.$onUpdate(() => new Date()),
name: text("name").notNull().unique(),
});
The $onUpdate function sets the updatedAt field to a default value whenever the row is updated.
protocol://username:password@host:port/database
Here are examples:
postgres://wagslane:@localhost:5432/gatorpostgres://postgres:postgres@localhost:5432/gatorTest your connection string by running psql, for example:
psql "postgres://wagslane:@localhost:5432/gator"
It should connect you to the gator database directly. If it's working, great. exit out of psql and save the connection string.
protocol://username:password@host:port/database?sslmode=disable
Your application code needs to know to not try to use SSL locally.
import { defineConfig } from "drizzle-kit";
export default defineConfig({
schema: "src/<path_to_schema>",
out: "src/<path_to_generated_files>",
dialect: "postgresql",
dbCredentials: {
url: "your_connection_string",
},
});
You can use the readConfig function to read the connection string from the .gatorconfig.json file instead of hard-coding it.
I created a src/lib/db directory to hold all of my database-related files. You can do the same, or put them wherever you like.
npx drizzle-kit generate
npx drizzle-kit migrate
Submit the CLI tests.
package.json to make running drizzle-kit easier. For example:{
"scripts": {
"generate": "drizzle-kit generate",
"migrate": "drizzle-kit migrate"
}
}