Model synced data
A synced table gets edits from many devices, so the way you model it decides what users see after a merge. Synced tables have rules, and serverpod generate checks most of them. A few patterns, covered in the sections below, also keep edits from being lost, mixed, or duplicated.
Rules for synced tables
Serverpod adds a spaceId field to every synced table. The field records which space owns the row.
The serverpod generate command reports any synced table model that breaks these rules:
| Rule | What to do |
|---|---|
| The id is a UUID | Leave id out and Serverpod adds one, or declare id: UuidValue?, defaultPersist=random_v7. The id is generated wherever the row is created, so a row created offline has its id right away. |
| Relations connect only synced tables | To point at a row in a table that doesn't sync, store its id in a plain field without relation. Give the field the same type as that table's id. |
| Required relations are deferred | Add deferred to every relation with a non-nullable foreign key, because a merge can add a child row before its parent. |
| Unique indexes are per space | List spaceId in the index's fields, as in fields: spaceId, name. An index made only of nullable foreign keys to synced tables can leave it out, such as the index of a one-to-one relation. |
| Unique indexes have a field offline sync can replace | Include a String, a nullable field, or a UuidValue without a relation. When two rows conflict, offline sync gives the losing row a replacement value in that field. |
| One-to-one relations are optional | Make the foreign key nullable. |
| Every field reaches every member's device | Keep secrets and server-only data in tables that don't sync, because synced fields can't use scope=serverOnly. |
Two more rules apply, but serverpod generate doesn't check them:
- Unique indexes can't include JSON fields. That covers
List,Map,Set, and nested model fields. The server and the app throw aStateErrorwhen they first use the database. - Relations can't reach another space. A parent in another space counts as missing, so the child is handled as Relations after a merge describes. To link to a row in another space, store its id in a plain
UuidValuefield withoutrelation. Look it up with a second query, which can come back empty.
Design for concurrent edits
Each column merges on its own, and the newest write wins. When two devices change the same column, only the newer change survives. The following patterns stop a merge from losing a change, or from mixing two changes into a wrong value:
| To store | Use | Why |
|---|---|---|
| A list that several devices add to, such as a recipe's ingredients | Child rows with a relation, not a List field | A List field is one value, so one device's additions are lost. |
| An order that users rearrange | A double position on each row, sorted by position and then by id. Give a moved row a value between its new neighbors. | With int positions, a move rewrites many rows, so a move from one device can be lost. |
| A count, such as likes | One row per contributor, counted when you read | When two devices add 1 at the same time, one addition is lost. |
| One choice among many, such as a default address | One nullable reference on the row that owns the choice, such as defaultAddressId on a customer | A flag on each row can mix two devices' picks into two defaults. |
| Values that only make sense together, such as an amount and its currency | One nested model field | Separate columns can mix the amount from one device with the currency from another. |
Avoid duplicate rows
Two devices can create the same thing while offline. Each copy gets its own random id, so the merge keeps both as separate rows. The following patterns turn the copies into one row, or let a person resolve them:
| To store | Use | Why |
|---|---|---|
Something two devices might create at once, such as a tag named urgent | An id derived from the data, as in Derive ids from the data | Both devices create the same id, so the merge keeps one row. |
| A name that must not repeat, such as a list's title | A unique index | The row that set the name first keeps it. The other row reads <name>__conflict__<rowId> until someone renames it. |
Derive ids from the data
Derive the id from the data that makes the row unique, such as a tag's name or the two rows a link connects:
UuidValue tagId(UuidValue spaceUuid, String name) =>
const Uuid().v5obj(spaceUuid.uuid, 'tag:${name.trim().toLowerCase()}');
Three rules keep derived ids working:
- Derive ids only from data that identifies one thing. Rows with the same id merge into one row, so two different tasks that share a title, such as "Buy milk", would become one.
- Build the id from the space's UUID. An id can belong to only one space. If two spaces derive the same id, the second row is rejected, and the device that synced it can't sync until the row is fixed. Troubleshooting shows how to find the row.
- Insert with
ignoreConflicts: trueto skip rows that already exist. Another device may have created the row already. The insert also restores the row if a user deleted it.
Choose onDelete for each relation
Sometimes one device deletes a parent row while another device adds a child row to it. The merge gives the same result as deleting the parent in a database that already has the new child, so the relation's onDelete action decides it:
| Relationship | onDelete | Result after the merge |
|---|---|---|
| A child owned by its parent, such as a task in a project | Cascade | The child is hidden with the parent, and comes back if the parent is restored. |
| A child that must keep its parent, such as a line on an invoice | Restrict, NoAction, or none | The delete is undone, and the parent reappears with the child. If the children that blocked it are deleted later, the parent is hidden again. |
| An optional link, such as an assignee | SetNull, with a nullable foreign key | The child stays, and its foreign key reads null. The foreign key points to the parent again if the parent is restored. |
| A child that falls back to a default parent, such as a note that moves to an Inbox folder | SetDefault | The child's foreign key reads its default value while the row it points to is visible in the same space. Otherwise the delete is undone. |
Deletes on a single device follow normal database rules, as Delete rows describes.
Values your code can't write
Offline sync uses these values for rows that lose a unique value to another row, or give one up:
- Text in a unique column that ends in
__conflict__,__hidden__, or__park__followed by a UUID - A version 8 UUID in a non-nullable unique
UuidValuefield without a relation
If your code writes one of these values, for example by copying a title like Groceries__conflict__<rowId> to a new row, the write throws OfflineSyncReservedValueException. You can still save a row that holds one of these values, as long as you don't change that value.
Related
- Offline sync: how merges behave and the rules every write follows.
- How merges work: what a merge does with each kind of change.
- Share data with spaces: putting data for different groups of users in separate spaces.
- Relations and Indexing: relations and unique indexes in general.