Skip to content

Commit

Permalink
Allow setting custom node ids
Browse files Browse the repository at this point in the history
  • Loading branch information
cachapa committed Mar 5, 2024
1 parent 9502060 commit a637d08
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 6 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 3.0.1

- Allow setting custom node ids

## 3.0.0+1

- Fix missing `query` method in transactions
Expand Down
26 changes: 21 additions & 5 deletions lib/src/sql_crdt.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,18 @@ abstract class SqlCrdt extends Crdt {
SqlCrdt(this._db);

/// Initialize this CRDT
Future<void> init() async {
// Read the canonical time from database, or generate a new node id if empty
canonicalTime = await _getLastModified() ?? Hlc.zero(generateNodeId());
///
/// Use [nodeId] to set an explicit id, or leave it empty to autogenerate a
/// random one.
/// If you set a custom id, make sure it's unique accross your system, as
/// collisions will break the CRDT in subtle ways.
///
/// Setting the node id on init only works for empty CRDTs.
/// See [resetNodeId] and [generateNodeId].
Future<void> init([String? nodeId]) async {
nodeId ??= generateNodeId();
// Read the canonical time from database, or start from scratch
canonicalTime = await _getLastModified() ?? Hlc.zero(nodeId);
}

/// Returns all the user tables in this database.
Expand Down Expand Up @@ -201,9 +210,16 @@ abstract class SqlCrdt extends Crdt {
/// account without resetting the database - id avoids synchronization issues
/// where the existing entries do not get correctly propagated to the new
/// user id.
Future<void> resetNodeId() async {
///
/// Use [newNodeId] to set an explicit id, or leave it empty to autogenerate a
/// random one.
/// If you set a custom id, make sure it's unique accross your system, as
/// collisions will break the CRDT in subtle ways.
///
/// See [init] and [generateNodeId].
Future<void> resetNodeId([String? newNodeId]) async {
final oldNodeId = canonicalTime.nodeId;
final newNodeId = generateNodeId();
newNodeId ??= generateNodeId();
await _db.executeBatch(
(txn) async {
for (final table in await getTables()) {
Expand Down
2 changes: 1 addition & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: sql_crdt
description: Base package for Conflict-free Replicated Data Types (CRDTs) using SQL databases
version: 3.0.0+1
version: 3.0.1
homepage: https://github.com/cachapa/sql_crdt
repository: https://github.com/cachapa/sql_crdt
issue_tracker: https://github.com/cachapa/sql_crdt/issues
Expand Down

0 comments on commit a637d08

Please sign in to comment.