# 使用指南

> 了解如何在 TypeScript、Python 與 Go 中啟用並使用 Turso 同步功能。
> Canonical HTML: https://tursodb.cn/zh-tw/docs/sync/usage/
> Upstream Source (MIT): https://docs.turso.tech/sync/usage
> Language: zh-TW

---
本指南說明如何設定 Turso 資料庫，並在您的應用程式中使用同步功能。

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

本篇範例使用 Turso Cloud 來同步本機 Turso 資料庫，並假設您已擁有 Turso Cloud 帳號。

</div></div>


**1. 設定 Turso Cloud 資料庫**

* 依照[快速入門](/zh-tw/docs/quickstart/)安裝 CLI 並建立資料庫

* 取得資料庫 URL（`turso://...`）：

```
turso db show <db>
```

* 為您的應用程式建立認證權杖：

```
turso db tokens create <db>
```

**2. 建立支援同步的基礎連線**

啟用同步功能需要三個必要項目：

* 本機路徑（Local path）：本機已同步 tursodb 檔案的儲存位置
* 遠端 URL（Remote URL）：您的 Turso Cloud 資料庫網址（`turso://...`）
* 認證權杖（Auth token）：用來驗證請求身分的 Turso Cloud 權杖

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

const db = await connect({
  path: './app.db',                               // local path
  url: 'turso://...',                            // remote URL (generated with turso db show <db-name> --url)
  authToken: process.env.TURSO_AUTH_TOKEN,        // authentication token (generated with turso db tokens create <db-name>)
  // longPollTimeoutMs: 10_000,                   // optional: server waits before replying to pull
  // bootstrapIfEmpty: false,                     // set to false to avoid bootstrapping on first run
});
```

```py Python
import os
import turso.sync

conn = turso.sync.connect(
    path="./app.db",                                  # local path
    remote_url="turso://...",                        # remote URL (generated with turso db show <db-name> --url)
    auth_token=os.environ["TURSO_AUTH_TOKEN"],        # authentication token (generated with turso db tokens create <db-name>)
    # long_poll_timeout_ms=10_000,                    # optional: server waits before replying to pull
    # bootstrap_if_empty=False,                       # set to false to avoid bootstrapping on first run
)
```

```go Go
package main

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

db, err := turso.NewTursoSyncDb(ctx, turso.TursoSyncDbConfig{
  Path:              "./app.db",                    // local path
  RemoteUrl:         "turso://...",                // remote URL (generated with turso db show <db-name> --url)
  AuthToken:         os.Getenv("TURSO_AUTH_TOKEN"), // authentication token (generated with turso db tokens create <db-name>)
  // LongPollTimeoutMs: 10_000,                     // optional: server waits before replying to pull
  // BootstrapIfEmpty: new(bool),                   // *bool; point at false to avoid bootstrapping on first run
})
```

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

首次執行時，本機資料庫會自動從遠端進行初始載入（Bootstrap），因此初次連線時必須能夠連上遠端伺服器。

如果您將 `bootstrap_if_empty` 設為 `false`，本機資料庫則會以空資料庫啟動。之後隨時可以透過明確呼叫 `pull()` 來載入或更新資料。

</div></div>


**3. 推送變更（Push）**

Push 會將您的本機變更傳送至 Turso Cloud 伺服器。在底層實作中，系統會傳送邏輯陳述式，發生衝突時採取「最後推送優先（last push wins）」策略。若已提交的寫入交易與尚未結束的寫入交易有重疊，其推送可能會延遲。若要確保所有已提交的交易皆立即推送，請在呼叫 push 時確認沒有尚未關閉的寫入交易。

```ts TypeScript
await db.exec("CREATE TABLE IF NOT EXISTS notes(id TEXT PRIMARY KEY, body TEXT)");
await db.exec("INSERT INTO notes VALUES ('n1', 'hello')");

await db.push();
```

```py Python
conn.execute("CREATE TABLE IF NOT EXISTS notes(id TEXT PRIMARY KEY, body TEXT)")
conn.commit()
conn.execute("INSERT INTO notes VALUES ('n1', 'hello')")
conn.commit()

conn.push()
```

```go Go
// create *sql.DB instance
conn, err := db.Connect(ctx)
if err != nil {
  return err
}

_, err = conn.ExecContext(ctx, "CREATE TABLE IF NOT EXISTS notes(id TEXT PRIMARY KEY, body TEXT)")
if err != nil {
  return err
}
_, err = conn.ExecContext(ctx, "INSERT INTO notes VALUES ('n1', 'hello')")
if err != nil {
  return err
}

if err := db.Push(ctx); err != nil {
	return err
}
```

**4. 拉取變更（Pull）**

Pull 會從遠端擷取變更並套用至本機資料庫，並回傳一個布林值以表示本機是否有任何變動。

* 若希望伺服器等待變更再回應以避免空白回覆，可設定 `long_poll_timeout_ms` / `LongPollTimeoutMs`。
* 即使您剛才才執行過推送，後續的 pull 仍可能因伺服器端的衝突解決框架（frames）而回傳資料有所變動。

```ts TypeScript
// Returns true if anything changed locally
const changed = await db.pull();
console.info('pulled changes:', changed);
```

```py Python
changed = conn.pull()
print("pulled changes:", changed)
```

```go Go
changed, err := db.Pull(ctx)
if err != nil {
	return err
}
log.Println("pulled changes:", changed)
```

**5. 檢查點（Checkpoint）**

Checkpoint 會壓縮本機 WAL 檔案，在保留同步狀態的同時有效控制本機磁碟空間佔用。

```ts TypeScript
await db.checkpoint();
```

```py Python
conn.checkpoint()
```

```go Go
if err := db.Checkpoint(ctx); err != nil {
	return err
}
```

**6. 統計資訊（Stats）**

統計資訊可協助您觀測同步行為與資源使用狀況（包括 WAL 大小、最近推送／拉取時間、網路流量、修訂版本等）。

```ts TypeScript
const s = await db.stats();
console.info({
  cdcOperations: s.cdcOperations,
  mainWalSize: s.mainWalSize,
  revertWalSize: s.revertWalSize,
  networkReceivedBytes: s.networkReceivedBytes,
  networkSentBytes: s.networkSentBytes,
  lastPullUnixTime: s.lastPullUnixTime,
  lastPushUnixTime: s.lastPushUnixTime,
  revision: s.revision,
});
```

```py Python
s = conn.stats()
print({
    "cdc_operations": s.cdc_operations,
    "main_wal_size": s.main_wal_size,
    "revert_wal_size": s.revert_wal_size,
    "network_received_bytes": s.network_received_bytes,
    "network_sent_bytes": s.network_sent_bytes,
    "last_pull_unix_time": s.last_pull_unix_time,
    "last_push_unix_time": s.last_push_unix_time,
    "revision": s.revision,
})
```

```go Go
s, err := db.Stats(ctx)
if err != nil {
	return err
}
log.Printf("stats: cdc=%v, main=%d revert=%d rx=%d tx=%d pull=%d push=%d revision=%s",
  s.CdcOperations,
  s.MainWalSize,
  s.RevertWalSize,
  s.NetworkReceivedBytes,
  s.NetworkSentBytes,
  s.LastPullUnixTime,
  s.LastPushUnixTime,
  s.Revision,
)
```

## 離線優先寫入

若您的應用程式需要在無網路連線時接受寫入操作，可以先寫入本機，待網路恢復後再呼叫 `push()`。在完成同步之前，所有變更都會安全地保存在本機資料庫檔案中。

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

// bootstrapIfEmpty: false lets the app start offline without
// needing to reach the remote on first launch
const db = await connect({
  path: './local.db',
  url: process.env.TURSO_URL!,
  authToken: process.env.TURSO_AUTH_TOKEN!,
  bootstrapIfEmpty: false,
});

async function syncWhenOnline(db) {
  try {
    await db.push();
  } catch (e) {
    // No connectivity — changes are safe in the local file
    // and will sync on the next push() call
  }
}

// On app launch, pull the latest state if online
try {
  await db.pull();
} catch (e) {
  // Offline — local data is still available for reads and writes
}

// On a timer or connectivity event
await syncWhenOnline(db);
```

```py Python
import os
import turso.sync

# bootstrap_if_empty=False lets the app start offline without
# needing to reach the remote on first launch
conn = turso.sync.connect(
    path="./local.db",
    remote_url=os.environ["TURSO_URL"],
    auth_token=os.environ["TURSO_AUTH_TOKEN"],
    bootstrap_if_empty=False,
)

def sync_when_online(conn):
    try:
        conn.push()
    except Exception:
        # No connectivity — changes are safe in the local file
        # and will sync on the next push() call
        pass

# On app launch, pull the latest state if online
try:
    conn.pull()
except Exception:
    # Offline — local data is still available for reads and writes
    pass

# On a timer or connectivity event
sync_when_online(conn)
```

```go Go
// BootstrapIfEmpty pointing at false lets the app start offline
// without needing to reach the remote on first launch
noBootstrap := false
db, err := turso.NewTursoSyncDb(ctx, turso.TursoSyncDbConfig{
	Path:             "./local.db",
	RemoteUrl:        os.Getenv("TURSO_URL"),
	AuthToken:        os.Getenv("TURSO_AUTH_TOKEN"),
	BootstrapIfEmpty: &noBootstrap,
})

func syncWhenOnline(ctx context.Context, db *turso.TursoSyncDb) {
	if err := db.Push(ctx); err != nil {
		// No connectivity — changes are safe in the local file
		// and will sync on the next Push() call
		log.Println("push deferred:", err)
	}
}

// On app launch, pull the latest state if online
if _, err := db.Pull(ctx); err != nil {
	// Offline — local data is still available for reads and writes
	log.Println("pull deferred:", err)
}

// On a timer or connectivity event
syncWhenOnline(ctx, db)
```

這是 [`@libsql/client` 嵌入式副本](/zh-tw/docs/features/embedded-replicas/introduction/)中 `offline: true` 旗標的現代替代方案。使用 Turso Sync 時，所有讀寫預設皆於本機完成，並由您透過明確呼叫 `push()` 與 `pull()` 來掌控同步時機。
