On April 8th, 2024, the free Hobby database of PlanetScale plan would no longer be available.
So I started to find an alternative. After the comparison of other serverless databases in the market,
I decided to choose Turso as the database for the next project, Amazing Endemic Species.
Moreover, I used Primsa as an Object-Relational Mapping (ORM) tool applied in my Next.js projects last year.
However, I did not like its unique syntax of API design and the level of abstraction.
Until I found Drizzle ORM, whose philosophy is "If you know SQL, you know Drizzle ORM",
which offers a higher level abstraction from SQL and can be used to read nested relations.
In this article, I will introduce how to use Turso with Drizzle ORM in Next.js.
You should have installed Drizzle ORM and Drizzle kit. You can do this by running the following command:
Setup Turso
Install the Turso CLI
Turso CLI will help manage the database, create replicas in other regions, and connect to the database shell.
You can install it by following the command:
And check the version of Turso CLI.
Signup or login to Turso
Create a Database in Turso
I create a database with the name aes:
And show the information about the aes database with following command:
Connect with the database with following command:
Setup Turso Database
Turso is a SQLite-compatible database built on libSQL, the Open Contribution fork of SQLite.
It is easy to set up a local database for the development process.
Create db Folder for Connecting Turso Database
Update environment variables
Create a .env file in the root directory with the connection url and authentication token and
get database name and token from the following command:
Then Paste the connection url and authentication token in .env as below:
Setup Drizzle config file
Create a drizzle.config.ts file in the root of the project and add the following content:
Connect Drizzle ORM to Turso
For connecting Turso database, I write the following code into db/index.ts as below:
Create tables in Turso database
The code below is a demonstration of creating a aes table in aes database
Generate the Migration
Generate migration based on you Drizzle schema.
This will generate a migration SQL file:
Push the Schema to Turso Database
drizzle-kit push lets you push the schema changes directly to the aes database
After that, you will see the schema of aes table in Turso database.
Let's stop here for today and continue adding more later.