Drizzle is a lightweight, type-safe ORM which supports a variety database drivers out of the box! It’s type-safety will make your dev experience 100x better with the power of code completions and intellisense build into modern editors.
Table of contents
Open Table of contents
Before We Start
In this post we will be using pnpm as the preferred package manager and mysql2 as the db driver. You can choose these differently according to your needs.
Also, it is assumed that you have a working typescript environment at your disposal before starting with drizzle setup.
Here’s the basic tsconfig we will be using for this project. Two things to watch for are the path aliases and the include folders.
Steps to Follow
Installing Dependencies
Install drizzle-orm
and the driver package for preferred database dialect, which is mysql2
for mysql. Then install drizzle-kit
as a dev-dependency.
Install dotenv
for loading .env files & zod
for env validation and typings.
This step is OPTIONAL but if you skip this step you will have to handle ENV Variables on your own.
Setting up ENV Variables
We will export all parsed ENV vars from a single file called env.ts
TipURI Format for mysql is as follows:
mysql://${username}:${password}@${host}:${port}/${db_name}
Writing Table Schemas
There are many ways of structuring our schema files. For this post we will use the approach that will help us easily integrate into drizzle migrations and db queries functionality with full type-safety. You can read about other approaches here.
We will store all the schema files inside src/db/schema
folder and then export then with a barrel file. For example:
and the barrel file,
Database Client
This client will be used to perform operations on our db with full type-safety.
This is why we needed a barrel file, Because the drizzle function expects a schema value to provide type completions when using db.query for something like this.
Handling Migrations
For generating migrations we need to first setup a drizzle.config.ts file at the root of our project.
We can use the following command to generate the migrations.
Then we need to write a custom script to call the migration function for mysql2.
Finally, we can use the following command to apply the migrations to our database.
You can install
tsx
as a dev dependency to run typescript files directly.
Useful Package JSON Script
drizzle-kit provides much more functionality then what we just used. Still I am sharing a snippet of what my package.json commonly looks in a drizzle project.