在底层,SQLite Sync 使用了 设计的高级CRDT(无冲突复制数据类型) 算法和数据结构 专为协作分布式系统 。这意味着:
简单来说,CRDT 使多个用户可以 同时 从任何地方编辑共享数据,并且一切正常。
无论您构建的是移动应用程序、物联网设备还是桌面工具,SQLite Sync 都能简化分布式数据管理,并在分散环境中充分发挥 SQLite 的潜力。
与需要您构建和维护复杂后端的传统同步系统不同, SQLite Sync 包含一个开箱 即用的内置网络层:
同步层与 SQLite Cloud 紧密集成,实现跨设备、跨用户、跨平台的无缝安全数据共享。您可以轻松享受云同步的强大功能,而无需担心复杂性。
得益于底层 SQLite Cloud 基础架构, SQLite Sync 支持行级安全性 (RLS) 定义 - 允许您在行级别 精确的访问控制:
例如:
RLS 的好处 :
SQLite Sync 非常适合跨 Web、移动、桌面和边缘平台构建协作式分布式应用。一些示例用例包括:
有关所有可用函数、其参数和示例的详细信息,请参阅 全面的 API 参考 。
页面下载适合您平台的预构建二进制文件 从官方发布 :
您可以从以下位置下载启用了 SQLite Sync 扩展的 WebAssembly (WASM) 版本的 SQLite: https://www.npmjs.com/package/@sqliteai/sqlite-wasm
您可以 将此存储库作为包依赖项添加到您的 Swift 项目中 的步骤 4 和 5 设置 SQLite 并支持扩展加载 。添加包后,您需要按照本指南 。
以下是如何使用该包的示例:
import CloudSync<>> ... var db: OpaquePointer? sqlite3_open(":memory:", &db) sqlite3_enable_load_extension(db, 1) var errMsg: UnsafeMutablePointer<Int8>? = nil sqlite3_load_extension(db, CloudSync.path, nil, &errMsg) var stmt: OpaquePointer? sqlite3_prepare_v2(db, "SELECT cloudsync_version()", -1, &stmt, nil) defer { sqlite3_finalize(stmt) } sqlite3_step(stmt) log("cloudsync_version(): \(String(cString: sqlite3_column_text(stmt, 0)))") sqlite3_close(db)
加载扩展
-- In SQLite CLI .load ./cloudsync -- In SQL SELECT load_extension('./cloudsync');
入门
以下是开始使用 SQLite Sync 的简单示例:
先决条件
- SQLite Cloud 帐户 注册 :在SQLite Cloud
- SQLite 同步扩展 下载 :从发布版本
SQLite 云设置
- 中创建新项目和数据库 在SQLite Cloud Dashboard
- 从仪表板复制连接字符串和 API 密钥
- 在本地和云数据库中创建具有相同模式的表
- 启用同步:单击 数据库的“OffSync” 按钮,然后选择要同步的每个表
本地数据库设置
# Start SQLite CLI sqlite3 myapp.db
-- Load the extension .load ./cloudsync -- Create a table (primary key MUST be TEXT for global uniqueness) CREATE TABLE IF NOT EXISTS my_data ( id TEXT PRIMARY KEY NOT NULL, value TEXT NOT NULL DEFAULT '', created_at TEXT DEFAULT CURRENT_TIMESTAMP ); -- Initialize table for synchronization SELECT cloudsync_init('my_data'); -- Use your local database normally: read and write data using standard SQL queries -- The CRDT system automatically tracks all changes for synchronization -- Example: Insert data (always use cloudsync_uuid() for globally unique IDs) INSERT INTO my_data (id, value) VALUES (cloudsync_uuid(), 'Hello from device A!'), (cloudsync_uuid(), 'Working offline is seamless!'); -- Example: Update and delete operations work normally UPDATE my_data SET value = 'Updated: Hello from device A!' WHERE value LIKE 'Hello from device A!'; -- View your data SELECT * FROM my_data ORDER BY created_at; -- Configure network connection before using the network sync functions SELECT cloudsync_network_init('sqlitecloud://your-project-id.sqlite.cloud/database.sqlite'); SELECT cloudsync_network_set_apikey('your-api-key-here'); -- Or use token authentication (required for Row-Level Security) -- SELECT cloudsync_network_set_token('your_auth_token'); -- Sync with cloud: send local changes, then check the remote server for new changes -- and, if a package with changes is ready to be downloaded, applies them to the local database SELECT cloudsync_network_sync(); -- Keep calling periodically. The function returns > 0 if data was received -- In production applications, you would typically call this periodically -- rather than manually (e.g., every few seconds) SELECT cloudsync_network_sync(); -- Before closing the database connection SELECT cloudsync_terminate(); -- Close the database connection .quit
-- On another device (or create another database for testing: sqlite3 myapp_2.db) -- Follow the same setup steps: load extension, create table, init sync, configure network -- Load extension and create identical table structure .load ./cloudsync CREATE TABLE IF NOT EXISTS my_data ( id TEXT PRIMARY KEY NOT NULL, value TEXT NOT NULL DEFAULT '', created_at TEXT DEFAULT CURRENT_TIMESTAMP ); SELECT cloudsync_init('my_data'); -- Connect to the same cloud database SELECT cloudsync_network_init('sqlitecloud://your-project-id.sqlite.cloud/database.sqlite'); SELECT cloudsync_network_set_apikey('your-api-key-here'); -- Sync to get data from the first device SELECT cloudsync_network_sync(); -- repeat until data is received (returns > 0) SELECT cloudsync_network_sync(); -- View synchronized data SELECT * FROM my_data ORDER BY created_at; -- Add data from this device to test bidirectional sync INSERT INTO my_data (id, value) VALUES (cloudsync_uuid(), 'Hello from device B!'); -- Sync again to send this device's changes SELECT cloudsync_network_sync(); -- The CRDT system ensures all devices eventually have the same data, -- with automatic conflict resolution and no data loss -- Before closing the database connection SELECT cloudsync_terminate(); -- Close the database connection .quit
完整示例
请参阅 示例 目录以获得全面的演练,其中包括:
同时使用 SQLite-AI:
在为 SQLite Sync 设计数据库模式时,请遵循以下最佳实践以确保最佳的 CRDT 性能和冲突解决:
-- ✅ Recommended: Globally unique TEXT primary key
CREATE TABLE users (
id TEXT PRIMARY KEY NOT NULL, -- Use cloudsync_uuid()
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL
);
-- ❌ Avoid: Auto-incrementing integer primary key
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT, -- Causes conflicts
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL
);
-- ✅ Recommended: Proper constraints and defaults
CREATE TABLE tasks (
id TEXT PRIMARY KEY,
title TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'pending',
priority INTEGER NOT NULL DEFAULT 1,
created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),
assigned_to TEXT -- Nullable for optional assignment
);
使用行级安全性将单租户数据库架构转换为多租户数据库架构时, UNIQUE 约束必须在云数据库的所有租户中保持全局唯一 。对于仅在租户内才应唯一的列,请使用复合 UNIQUE 约束。
-- ❌ Single-tenant: Unique email per database
CREATE TABLE users (
id TEXT PRIMARY KEY,
email TEXT UNIQUE NOT NULL -- Problem: Not unique across tenants
);
-- ✅ Multi-tenant: Composite unique constraint
CREATE TABLE users (
id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL,
email TEXT NOT NULL,
UNIQUE(tenant_id, email) -- Unique email per tenant
);
当使用 SQLite Sync 的外键约束时,请注意与 CRDT 合并算法和行级安全策略的交互可能会导致约束违规。
CRDT 合并算法和默认值
行级安全性和 CASCADE 操作
数据库设计模式
测试和验证
请注意,由于 SQLite Sync 的合并逻辑,某些类型的触发器可能会在同步期间导致错误。
重复操作
逐列处理
许可协议 本项目遵循Elastic License 2.0 。您可以根据许可条款,将其用于非生产用途,包括使用、复制、修改和分发。如需用于生产或托管服务,请 联系 SQLite Cloud, Inc 获取商业许可。