TURSO_DATABASE_URL과 TURSO_AUTH_TOKEN 값을 모르는 경우, LibSQL Driver SDK 튜토리얼을 참조하세요.
여기에서 확인한 후, 모든 값을 생성하여 .env 파일에 추가하고 돌아오세요.
Drizzle과 Turso Cloud 시작하기
Basic file structure
This is the basic file structure of the project. In the src/db directory, we have table definition in schema.ts. In drizzle folder there are sql migration file and snapshots.
📦 <project root>
├ 📂 drizzle
├ 📂 src
│ ├ 📂 db
│ │ └ 📜 schema.ts
│ └ 📜 index.ts
├ 📜 .env
├ 📜 drizzle.config.ts
├ 📜 package.json
└ 📜 tsconfig.jsonStep 1 - 필수 패키지 설치
npm i drizzle-orm @libsql/client dotenv
npm i -D drizzle-kit tsx
Step 2 - 연결 변수 설정
프로젝트 루트에 .env 파일을 생성하고 Turso 데이터베이스 URL과 인증 토큰을 추가합니다:
TURSO_DATABASE_URL=
TURSO_AUTH_TOKEN=Step 3 - Drizzle ORM을 데이터베이스에 연결
Drizzle은 모든 @libsql/client 드라이버 변형을 기본적으로 지원합니다:
@libsql/client | defaults to node import, automatically changes to web if target or platform is set for bundler, e.g. esbuild --platform=browser |
@libsql/client/node | node compatible module, supports :memory:, file, wss, http and turso connection protocols |
@libsql/client/web | module for fullstack web frameworks like next, nuxt, astro, etc. |
@libsql/client/http | module for http and https connection protocols |
@libsql/client/ws | module for ws and wss connection protocols |
@libsql/client/sqlite3 | module for :memory: and file connection protocols |
@libsql/client-wasm | Separate experimental package for WASM |
import { drizzle } from 'drizzle-orm/libsql';
const db = drizzle({ connection: {
url: process.env.DATABASE_URL,
authToken: process.env.DATABASE_AUTH_TOKEN
}});src 디렉토리에 index.ts 파일을 생성하고 연결을 초기화합니다:
import 'dotenv/config';
import { drizzle } from 'drizzle-orm/libsql';
// libsql 연결 옵션의 모든 속성을 지정할 수 있습니다
const db = drizzle({
connection: {
url: process.env.TURSO_DATABASE_URL!,
authToken: process.env.TURSO_AUTH_TOKEN!
}
});기존 드라이버를 제공해야 하는 경우:
import 'dotenv/config';
import { drizzle } from 'drizzle-orm/libsql';
import { createClient } from '@libsql/client';
const client = createClient({
url: process.env.TURSO_DATABASE_URL!,
authToken: process.env.TURSO_AUTH_TOKEN!
});
const db = drizzle({ client });Step 4 - 테이블 생성
Create a schema.ts file in the src/db directory and declare your table:
import { int, sqliteTable, text } from "drizzle-orm/sqlite-core";
export const usersTable = sqliteTable("users_table", {
id: int().primaryKey({ autoIncrement: true }),
name: text().notNull(),
age: int().notNull(),
email: text().notNull().unique(),
});Step 5 - Drizzle 설정 파일 구성
Drizzle config - Drizzle Kit에서 사용하는 설정 파일로, 데이터베이스 연결, 마이그레이션 폴더, 스키마 파일에 대한 모든 정보를 포함합니다.
프로젝트 루트에 drizzle.config.ts 파일을 생성하고 다음 내용을 추가합니다:
import 'dotenv/config';
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
out: './drizzle',
schema: './src/db/schema.ts',
dialect: 'turso',
dbCredentials: {
url: process.env.TURSO_DATABASE_URL,
authToken: process.env.TURSO_AUTH_TOKEN,
},
});Step 6 - 데이터베이스에 변경사항 적용
You can directly apply changes to your database using the drizzle-kit push command. This is a convenient method for quickly testing new schema designs or modifications in a local development environment, allowing for rapid iterations without the need to manage migration files:
npx drizzle-kit pushRead more about the push command in documentation.
Alternatively, you can generate migrations using the drizzle-kit generate command and then apply them using the drizzle-kit migrate command:
Generate migrations:
npx drizzle-kit generateApply migrations:
npx drizzle-kit migrateRead more about migration process in documentation.
Step 7 - 데이터베이스 시딩 및 쿼리
Let’s update the src/index.ts file with queries to create, read, update, and delete users
import 'dotenv/config';
import { eq } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/libsql';
import { usersTable } from './db/schema';
async function main() {
const db = drizzle({
connection: {
url: process.env.TURSO_DATABASE_URL!,
authToken: process.env.TURSO_AUTH_TOKEN!
}
});
const user: typeof usersTable.$inferInsert = {
name: 'John',
age: 30,
email: 'john@example.com',
};
await db.insert(usersTable).values(user);
console.log('New user created!')
const users = await db.select().from(usersTable);
console.log('Getting all users from the database: ', users)
/*
const users: {
id: number;
name: string;
age: number;
email: string;
}[]
*/
await db
.update(usersTable)
.set({
age: 31,
})
.where(eq(usersTable.email, user.email));
console.log('User info updated!')
await db.delete(usersTable).where(eq(usersTable.email, user.email));
console.log('User deleted!')
}
main();Step 8 - index.ts 파일 실행
To run any TypeScript files, you have several options, but let’s stick with one: using tsx
You’ve already installed tsx, so we can run our queries now
Run index.ts script
npx tsx src/index.ts
We suggest using bun to run TypeScript files. With bun, such scripts can be executed without issues or additional
settings, regardless of whether your project is configured with CommonJS (CJS), ECMAScript Modules (ESM), or any other module format.
To run a script with bun, use the following command:
bun src/index.tsIf you don’t have bun installed, check the Bun installation docs