%% generate tags start %% #software-engineering %% generate tags end %% #software-engineering/database #software-engineering/database/turso #software-engineering/sqlite ## How to Start? install turso cli ``` brew install tursodatabase/tap/turso ``` create first database ``` turso auth login turso db create ``` ## Define Database Schema Using Drizzle > [!info] see more > [Step 3: Configuring Drizzle | Turso](https://docs.turso.tech/tutorials/e-commerce-store-codelab/step-03-configuring-drizzle#previewing-the-turso-database-using-drizzle) 1. use bun to create a project 2. install drizzle, you can check [Turso - DrizzleORM](https://orm.drizzle.team/docs/quick-sqlite/turso) ```sh bun add drizzle-orm @libsql/client bun add -D drizzle-kit ``` ```ts import { drizzle } from 'drizzle-orm/libsql'; import { createClient } from '@libsql/client'; const client = createClient({ url: 'DATABASE_URL', authToken: 'DATABASE_AUTH_TOKEN' }); const db = drizzle(client); const result = await db.select().from(users).all() ``` 4. create the database schema, see [SQLite column types - DrizzleORM](https://orm.drizzle.team/docs/column-types/sqlite) The above code shows the Drizzle database schema for our app including the indexes and relations for some of the tables 5. Add the following SQL generation script inside `package.json`. ```json "generate": "drizzle-kit generate:sqlite --out ./drizzle/migrations --breakpoints --schema=./drizzle/schema.ts" ``` 6. write a migration script ```ts import { migrate } from "drizzle-orm/libsql/migrator"; import { drizzle } from "drizzle-orm/libsql"; import { createClient } from "@libsql/client"; export const client = createClient({ url: process.env.TURSO_DB_URL as string, authToken: process.env.TURSO_DB_AUTH_TOKEN as string, }); export const db = drizzle(client); async function main() { try { await migrate(db, { migrationsFolder: "drizzle/migrations", }); console.log("Tables migrated!"); process.exit(0); } catch (error) { console.error("Error performing migration: ", error); process.exit(1); } } main(); ``` ```json // package.json "migrate": "bun run drizzle/migrate", ``` 7. preview database ```ts import type { Config } from "drizzle-kit"; export default { schema: "./drizzle/schema.ts", out: "./drizzle/migrations", driver: "turso", dbCredentials: { url: process.env.TURSO_DB_URL as string, authToken: process.env.TURSO_DB_AUTH_TOKEN as string, }, } satisfies Config; ``` ```json // package.json "studio": "drizzle-kit studio --port 3333" ``` ## How to Feed a Sqlite File into Turso (seeding)? you need to create a `seed.ts`, see [app-the-mug-store/drizzle/seed.ts at master · turso-extended/app-the-mug-store (github.com)](https://github.com/turso-extended/app-the-mug-store/blob/master/drizzle/seed.ts) ```json // package.json "db:seed": "tsx drizzle/seed" ``` <iframe src="https://demo.mathesar.org/shares/tables/51b54122-cf44-4be7-9848-e3a5c8b4c87a/" width=“100px” height=“100%”></iframe>