# 本機同步伺服器

> 將 Turso CLI 作為本機同步伺服器，無需 Turso Cloud 即可進行開發與測試。
> Canonical HTML: https://tursodb.cn/zh-tw/docs/sync/local-sync-server/
> Upstream Source (MIT): https://docs.turso.tech/sync/local-sync-server
> Language: zh-TW

---
`tursodb` CLI 內建了可在本機執行的同步伺服器，讓您完全在個人電腦上開發與測試同步工作流程，無需註冊 Turso Cloud 帳號。

<div class="doc-callout doc-callout-info"><div class="doc-callout-title">注意</div><div class="doc-callout-body">

本機同步伺服器實作了與 Turso Cloud 完全相同的同步協定，因此您的應用程式碼在兩種環境下可以一致運作。

</div></div>


## 啟動伺服器

傳入 `--sync-server` 與監聽位址即可啟動同步伺服器。資料庫路徑參數用於指定伺服器的資料儲存位置：

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

此指令會啟動一個監聽 `8080` 連接埠的同步伺服器，並以 `./server.db` 作為底層資料庫檔案。

## 連線用戶端

將同步用戶端指向 `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",
)
```

```go Go
package main

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

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

連線完成後，所有同步操作（`push`、`pull`、`checkpoint`、`stats`）的用法皆與[使用指南](/zh-tw/docs/sync/usage/)所述完全一致。

## 範例：完整的本機同步流程

以下範例將帶您走過完整流程：啟動伺服器、從一個用戶端寫入資料，並將其同步至另一個用戶端。

**1. 啟動同步伺服器**

開啟終端機並啟動伺服器：

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

**2. 從用戶端 A 寫入並推送**

```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)
```

**3. 從用戶端 B 拉取變更**

```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")
```
