본문 바로가기
WIKI 기술 지식 베이스

Turso 퀵스타트

원문 보기 위키 갱신

Turso 퀵스타트 (Flutter / Dart)

Flutter나 Dart 프로젝트에서 libSQL 클라이언트를 쓰면 몇 단계 만에 Turso 데이터베이스와 연결할 수 있어요. 이 퀵스타트는 자격 증명 확인부터 설치, 연결, 쿼리 실행, 선택적인 로컬 동기화까지 차례대로 안내해요.

출처: 문서

본문

이 Flutter/Dart 퀵스타트에서 배울 내용은 다음과 같아요:

  • 데이터베이스 자격 증명(credential) 가져오기
  • Flutter/Dart libSQL 클라이언트 설치하기
  • 로컬 또는 원격 Turso 데이터베이스에 연결하기
  • SQL로 쿼리 실행하기
  • 로컬 데이터베이스에 변경 사항 동기화하기 (선택)

참고: 이 SDK는 커뮤니티에서 유지보수하는 패키지라서 Turso의 공식 지원을 받지 않거나 최신 기능이 반영되지 않았을 수 있어요. 도움과 피드백이 필요하면 Discord의 #libsql-dart 채널을 찾아 주세요.

단계별 진행

1. 데이터베이스 자격 증명 가져오기

계속하려면 기존 데이터베이스가 필요해요. 없다면 먼저 데이터베이스를 만들어 주세요. 데이터베이스 URL과 인증 토큰을 확보한 뒤에는 환경 변수로 저장해 두는 편이 좋아요.

2. libsql_dart 설치하기

flutter pub add libsql_dart

3. 초기화하기

LibsqlClient 생성자를 사용해 로컬 또는 원격 데이터베이스에 연결해요. 연결 방식은 상황에 맞게 고르면 돼요.

Embedded Replicas (임베디드 레플리카)

final dir = await getApplicationCacheDirectory();
final path = '${dir.path}/local.db';

final client = LibsqlClient(path)
  ..authToken = '<TOKEN>'
  ..syncUrl = '<TURSO_OR_LIBSQL_URL>'
  ..syncIntervalSeconds = 5
  ..readYourWrites = true;

Local only (로컬 전용)

final dir = await getApplicationCacheDirectory();
final path = '${dir.path}/local.db';

final client = LibsqlClient(path);
final client = LibsqlClient(":memory:");

Remote only (원격 전용)

final client = LibsqlClient('<TURSO_OR_LIBSQL_URL>')
  ..authToken = '<TOKEN>';

4. 연결하기

await client.connect();

5. 실행하기

await client.execute("create table if not exists customers (id integer primary key, name text);");
await client.query("insert into customers(name) values ('John Doe')");
print(await client.query("select * from customers"));
await client.batch("""insert into customers (name) values ('Jane Doe'); insert into customers (name) values ('Jake Doe');""");
final statement = await client
	.prepare("select * from customers where id = ?");

await statement.query(positional: [1])
final tx = await client.transaction();

await tx
	.execute("update customers set name = 'John Noe' where id = 1");
await tx
	.execute("update customers set name = 'Jane Noe' where id = 2");
print(await tx
	.query("select * from customers where id = ?", positional: [1]));

await tx.commit();

값에 플레이스홀더를 쓰고 싶다면 아래처럼 하면 돼요:

final statement = await client
  .prepare("select * from customers where id = ?");

await statement.query(positional: [1])
final statement = await client
	.prepare("select * from customers where id = :id");

await statement.query(named: {"id": 1})

6. 동기화하기 (Embedded Replicas 전용)

임베디드 레플리카를 사용할 때는 커넥터에서 sync()를 호출해 로컬 데이터베이스를 기본(primary) 데이터베이스와 동기화해야 해요.

await client.sync();

더 알아보기 (Learn more)