This example shows how to use the Drizzle ORM with the Open Source libSQL server and the Turso managed offering.
Establish environment settings for the local server:
cp .env.example .env
The contents of .env
now refer to a SQLite database file in the current
directory:
DATABASE_URL=file:local.db
Install modules required by the local server:
pnpm i
Start the local HTTP server on port 3000, which will create the database and perform a migration to add two tables:
pnpm start
Make a request to add a new row to the users
table:
curl --request POST \
--url http://localhost:3000/users \
--header 'Content-Type: application/json' \
--data '{
"name": "John Doe",
"email": "john@test.com"
}'
Fetch all the users as JSON:
curl --url http://localhost:3000/users
Stop the server with ctrl-C.
You must have the Turso CLI installed and authenticated to create and manage a Turso database.
Create a new database:
turso db create drizzle-example
Run this command to get the database URL:
turso db show drizzle-example --url
Edit .env and copy the database URL into the DATABASE_URL value:
DATABASE_URL=libsql://[your-database]-[your-github].turso.io
For Turso, an authentication token is required in order for the libSQL TypeScript client library to connect. Run this command to generate a new non-expiring token:
turso db tokens create drizzle-example -e none
Add a new line to .env and add the value to a new variable called
DATABASE_AUTH_TOKEN
:
DATABASE_AUTH_TOKEN=[your-auth-token]
Start the server again, this time connecting to Turso instead of using a local file:
pnpm start
Repeat the curl commands above to add a new row to users and fetch it.
Check that the row exists in Turso using the Turso CLI shell:
turso db shell drizzle-example "select * from users"
src/index.ts
- the main entry pointsrc/schema.ts
- defines the database schemamigrations
- contains the SQL migrations generated with Drizzle Kitsrc/env.ts
- loads, validates and exports the environment variablessrc/server.ts
- the server definitionsrc/utils.ts
- utility functions
pnpm generate
- generate a new migration based on schema changes
Migrations are run automatically when the server starts.