This tutorial demonstrates how to use Drizzle ORM with Turso.
This guide assumes familiarity with:
You should have installed Drizzle ORM and Drizzle kit. You can do this by running the following command:
npm
yarn
pnpm
bun
You should have installed dotenv package for managing environment variables. Read more about this package here
npm
yarn
pnpm
bun
You should have installed @libsql/client package. Read more about this package here.
npm
yarn
pnpm
bun
You should have installed Turso CLI. Check documentation for more information
Turso is a SQLite-compatible database built on libSQL, the Open Contribution fork of SQLite. It enables scaling to hundreds of thousands of databases per organization and supports replication to any location, including your own servers, for microsecond-latency access. You can read more about Turso’s concepts here.
Drizzle ORM natively supports libSQL driver, we embrace SQL dialects and dialect specific drivers and syntax and mirror most popular SQLite-like all, get, values and run query methods syntax.
Create new database by running the turso db create <DATABASE_NAME> command:
To see information about the database, run the following command:
Create an authentication token
To create an authentication token for your database, run the following command:
Learn more about this command and its options in the documentation.
Update environment variables
Update your .env or .env.local file with connection url and authentication token.
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 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.
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.
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.