You can create new Supabase project in the dashboard or by following this link.
Setup connection string variable
Navigate to Database Settings and copy the URI from the Connection String section. Make sure to use connection pooling. Remember to replace the password placeholder with your actual database password.
Add DATABASE_URL variable to your .env or .env.local file.
Read more about Connection Pooler and pooling modes in the documentation.
Connect Drizzle ORM to your database
Create a index.ts file in the src/db directory and set up your database configuration:
Create tables
Create a schema.ts file in the src/db directory and declare your tables:
Setup Drizzle config file
Drizzle config - a configuration file that is used by Drizzle Kit and contains all the information about your database connection, migration folder and schema files.
Create a drizzle.config.ts file in the root of your project and add the following content:
Applying changes to the database
You can generate migrations using drizzle-kit generate command and then run them using the drizzle-kit migrate command.
Generate migrations:
These migrations are stored in the supabase/migrations directory, as specified in your drizzle.config.ts. This directory will contain the SQL files necessary to update your database schema and a meta folder for storing snapshots of the schema at different migration stages.
For tables that already exist, manually review the generated migration files from npx drizzle-kit generate and comment out or adjust any unsafe pure create statements (e.g., CREATE SCHEMA "auth";) while ensuring safe conditional creates (e.g., CREATE TABLE IF NOT EXISTS "auth"."users") are properly handled.
Push command is good for situations where you need to quickly test new schema designs or changes in a local development environment, allowing for fast iterations without the overhead of managing migration files.
To apply migrations using the Supabase CLI you should follow these steps:
Generate migrations using Drizzle Kit:
Initialize the local Supabase project:
Link it to your remote project:
Push changes to the database:
Basic file structure
This is the basic file structure of the project. In the src/db directory, we have database-related files including connection in index.ts and schema definitions in schema.ts.
Query examples
For instance, we create src/db/queries folder and separate files for each operation: insert, select, update, delete.