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

Local Sync Server

원문 보기 위키 갱신

Turso Cloud 없이도 개발과 테스트를 할 수 있게 Turso CLI를 로컬 동기화 서버로 쓰는 방법이에요. 머신 안에서 동기화 워크플로 전체를 돌려 볼 수 있어요.

출처: 문서

본문

tursodb CLI에는 로컬에서 실행할 수 있는 내장 동기화 서버가 들어 있어요. 덕분에 Turso Cloud 계정 없이도 동기화 워크플로를 머신 안에서 개발하고 테스트할 수 있어요.

로컬 동기화 서버는 Turso Cloud와 동일한 동기화 프로토콜을 구현해요. 그래서 애플리케이션 코드는 두 환경에서 똑같이 동작해요.

Starting the server

--sync-server 플래그에 주소를 붙여서 동기화 서버를 시작해요. 데이터베이스 인자는 서버가 데이터를 저장할 위치를 지정해요.

tursodb ./server.db --sync-server 0.0.0.0:8080

이 명령은 ./server.db를 기반으로 포트 8080에서 수신하는 동기화 서버를 시작해요.

Connecting clients

동기화 클라이언트가 http://localhost:8080을 바라보게 하면 돼요. 로컬 서버에는 인증 토큰이 필요 없어요.

```ts TypeScript import { connect } from '@tursodatabase/sync';

const db = await connect({ path: './local-replica.db', url: 'http://localhost:8080', });


```py Python
import turso.sync

conn = turso.sync.connect(
    path="./local-replica.db",
    remote_url="http://localhost:8080",
)
package main

import (
\tturso "turso.tech/database/tursogo"
)

db, err := turso.NewTursoSyncDb(ctx, turso.TursoSyncDbConfig{
    Path:      "./local-replica.db",
    RemoteUrl: "http://localhost:8080",
})

연결하고 나면 모든 동기화 연산(push, pull, checkpoint, stats)이 Usage 가이드에서 설명한 것과 정확히 동일하게 동작해요.

Example: full local sync workflow

이 예제는 완전한 워크플로를 안내해요. 서버를 시작하고, 한 클라이언트에서 데이터를 쓰고, 다른 클라이언트로 동기화하는 과정이에요.

터미널을 열고 서버를 시작해요.
```bash
tursodb ./server.db --sync-server 0.0.0.0:8080
```
```ts TypeScript import { connect } from '@tursodatabase/sync';
  const clientA = await connect({
    path: './client-a.db',
    url: 'http://localhost:8080',
  });

  await clientA.exec("CREATE TABLE IF NOT EXISTS notes (id TEXT PRIMARY KEY, body TEXT)");
  await clientA.exec("INSERT INTO notes VALUES ('n1', 'hello from client A')");

  await clientA.push();
  ```

  ```py Python
  import turso.sync

  client_a = turso.sync.connect(
      path="./client-a.db",
      remote_url="http://localhost:8080",
  )

  client_a.execute("CREATE TABLE IF NOT EXISTS notes (id TEXT PRIMARY KEY, body TEXT)")
  client_a.commit()
  client_a.execute("INSERT INTO notes VALUES ('n1', 'hello from client A')")
  client_a.commit()

  client_a.push()
  ```

  ```go Go
  clientA, err := turso.NewTursoSyncDb(ctx, turso.TursoSyncDbConfig{
      Path:      "./client-a.db",
      RemoteUrl: "http://localhost:8080",
  })
  if err != nil {
      return err
  }
  connA, _ := clientA.Connect(ctx)

  connA.ExecContext(ctx, "CREATE TABLE IF NOT EXISTS notes (id TEXT PRIMARY KEY, body TEXT)")
  connA.ExecContext(ctx, "INSERT INTO notes VALUES ('n1', 'hello from client A')")

  clientA.Push(ctx)
  ```
</CodeGroup>
```ts TypeScript import { connect } from '@tursodatabase/sync';
  const clientB = await connect({
    path: './client-b.db',
    url: 'http://localhost:8080',
  });

  const changed = await clientB.pull();
  console.log('changes pulled:', changed);

  const rows = await clientB.query("SELECT * FROM notes");
  console.log(rows);
  // [{ id: 'n1', body: 'hello from client A' }]
  ```

  ```py Python
  import turso.sync

  client_b = turso.sync.connect(
      path="./client-b.db",
      remote_url="http://localhost:8080",
  )

  changed = client_b.pull()
  print("changes pulled:", changed)

  rows = client_b.execute("SELECT * FROM notes").fetchall()
  print(rows)
  # [('n1', 'hello from client A')]
  ```

  ```go Go
  clientB, err := turso.NewTursoSyncDb(ctx, turso.TursoSyncDbConfig{
      Path:      "./client-b.db",
      RemoteUrl: "http://localhost:8080",
  })
  if err != nil {
      return err
  }

  changed, _ := clientB.Pull(ctx)
  log.Println("changes pulled:", changed)

  connB, _ := clientB.Connect(ctx)
  rows, _ := connB.QueryContext(ctx, "SELECT * FROM notes")
  ```
</CodeGroup>

더 알아보기 (Learn more)