同步使用指南
介绍如何在 TypeScript、Python 和 Go 中启用并使用 Turso 数据同步功能。
本指南介绍如何配置 Turso 数据库,并在应用程序中使用数据同步能力。
本文示例通过 Turso Cloud 同步本地 Turso 数据库,前提是你已经拥有 Turso Cloud 账号。
1. 配置 Turso Cloud 数据库
-
按照快速开始安装 CLI 并创建一个云端数据库
-
获取数据库 URL(
turso://...):
turso db show <db>
- 为应用生成访问令牌(Token):
turso db tokens create <db>
2. 建立启用同步的基础连接
启用同步需要以下三项核心配置:
- 本地路径(Local path):本地同步后的 tursodb 文件存储位置
- 远端 URL(Remote URL):你的 Turso Cloud 数据库地址(
turso://...) - 认证令牌(Auth token):用于鉴权的 Turso Cloud 令牌
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
});
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
)
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
})
首次运行时,本地数据库会自动从远端拉取初始化数据(bootstrap),因此初次连接时必须能够访问远端服务。
如果你将 bootstrap_if_empty 设为 false,本地数据库将以空库启动。之后你可以随时显式调用 pull() 来完成初始化或同步更新。
3. 推送变更(Push)
push 会将本地变更发送到 Turso Cloud 服务端。底层传输的是逻辑变更语句,发生冲突时采用“后推送覆盖先推送(last push wins)”策略。如果某些已提交的写事务与当前仍未结束的写事务存在重叠,其推送可能会被延迟。为确保所有已提交事务都能及时推送,请保证调用 push 时没有未关闭的写事务。
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();
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()
// 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仍可能返回有变更,这是因为服务端可能下发了冲突解决产生的帧。
// Returns true if anything changed locally
const changed = await db.pull();
console.info('pulled changes:', changed);
changed = conn.pull()
print("pulled changes:", changed)
changed, err := db.Pull(ctx)
if err != nil {
return err
}
log.Println("pulled changes:", changed)
5. 检查点压缩(Checkpoint)
checkpoint 用于压缩本地 WAL 日志,在保留同步状态的同时控制本地磁盘空间占用。
await db.checkpoint();
conn.checkpoint()
if err := db.Checkpoint(ctx); err != nil {
return err
}
6. 查看同步统计信息(Stats)
stats 用于观测同步状态与资源使用情况(包括 WAL 大小、最近推送/拉取时间、网络收发流量、版本号等)。
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,
});
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,
})
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()。所有变更都会安全保存在本地数据库文件中,直到完成同步。
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);
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)
// 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 嵌入式副本 中的 offline: true 选项。使用 Turso Sync 时,所有读写操作默认都在本地完成,由你通过显式调用 push() 和 pull() 来掌控同步时机。