Drizzle Kit
When we design tables in our code, the tables don’t actually exist in the database. Therefore, we need Drizzle Kit to synchronize the table structure from our code to the database.
Configuration
We create a configuration file /drizzle.config.ts
for Drizzle Kit.
You can modify the highlighted lines above to specify the database you want to use. Once the configuration is created, we need to write a script that uses Drizzle Kit to generate the synchronization SQL statements and execute them every time the script is run.
Migration
Drizzle Kit supports two modes: push mode and generate mode. Generally, we use the push mode during development and the generate mode when deploying to a server.
Push Mode
Push mode: directly adjusts the database to match the local table structure. Tables and fields that have been removed will not be deleted.
The above code assumes that you are using MySQL. If you are using PostgreSQL, replace mysql
with pg
in the code.
Generate Mode
Generate mode: analyzes the differences between the current table structure and the table structure from the last run, and generates SQL files for the differences.
Generate mode is safer because you can explicitly track every change made to the database to prevent unforeseen consequences caused by human errors.
The above code assumes that you are using MySQL. If you are using PostgreSQL, adjust the parts related to MySQL in the code.
Running Drizzle Kit
Once you’re done, you can give it a try. Go ahead and run it! Before running, make sure you have at least one table created.
If you find it cumbersome to enter the command every time, you can add this command to the Milkio menubar in the bottom-left corner of VS Code.
Deployment
Usually, the database used in local development is different from the one used in the actual server. Therefore, when you update your server code, remember to run bun run ./drizzle.migrate.push.ts
to keep the database up to date.
Drizzle Studio
Drizzle Kit comes with Drizzle Studio, a bundled database browser that allows you to start it locally with a single command.
If you find it cumbersome to enter the command every time, you can add this command to the Milkio menubar in the bottom-left corner of VS Code.