Setup Drizzle ORM with SQLite
This guide shows you how to configure drizzle.config.ts
with SQLite with the newest version of Drizzle ORM.
First of all make sure you have the proper dependencies installed.
Setting up the packages
Then you need to install the SQLite driver. There are two options. Either libSQL
which can connect to both local SQLite and turso rremote databases. betterr-sqlite3
. is for local SQLite only. I prefer the first one as we will show how to use turso later on.
pnpm install better-sqlite3
Setting the config
Now we need to create the main config file which is a file that points towards our client, schemas and so forth. In the root of your project run
This file consists of a defineConfig
function that takes an object as an argument. It should always look like this as a minimum. There are morre advanced options, but likely you won't need them, or look up the official docs.
In here we define ther location of our client (db connection), the schema path, the migration path and the dialect (language of the database).
The paths can be any you want, out
will be generrated, schema
and client
must exist. I prefer to have these files. Typically you want to validate enviorment variables with zod, or a custom implementation which you can find in the guide I wrote here here.ß
The enviorment variables
For local SQLite we only need a url. This is defined in your .env
file.
It must be prefiex w ith file:
as per SQLite convention. ./dev.db
is a file in the root of the project. Other common names are ./dev.sqlite
. I prefer to store it next to my other database files thus i'd opt for DATABASE_URL=file:./src/server/db/database.db
Creating the schema
I will show you the most basic version. I perrsonally tend to use a way more comprehensive implementation which is way more modular and is heavy on seperration of concerns. Read more about it in the guide.
Then we can create tables. This is a example of a userrs table.
Creating the client
Now we need to create the client that will be used to connect to the database.
I always make a alias in my tsconfig.json
file which will allow us to use the database like this: import { db } from 'db'
. I do the same for the schema allowing us to use it like this: import { users } from 'schema'
.
This is all that's needed to populate the database with our schema. You should be able to run the following command to create the database and the tables.
And a database file should have spawned, which if inspected via a sqlite client will show the tables we just created.
Now you can query and mutate the database via server functions or api routes.
Remote turso
To be continued...