You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Schema changes with CloudKit sync: downgrade/re-upgrade, and columns added later with a default
#591
Hi! Thank you for SQLiteData — we're moving a multiplatform SwiftUI app (iPhone, iPad, Mac) from SwiftData to it, mainly for CloudKit sharing, and the sharing work in our lab has been excellent.
We're on sqlite-data 1.13.0 (e72164c), GRDB 7.12.0, Xcode 27.2 / macOS 27.2, with SyncEngine syncing a private database and shares. While planning how our schema will grow after the first release, we ran into two behaviours and would like to know whether they're expected, and what you'd recommend.
1. An older build opening a store a newer build migrated
Steps (failing test below):
Build N+1 migrates the store (ALTER TABLE … ADD COLUMN; also a new child table) and starts its SyncEngine.
Build N opens the same file (a TestFlight tester going back to the App Store build, or a developer switching builds). Its migrator has nothing to do; it caches record types from sqlite_master, so it now caches the table with the new column. It receives a record carrying the new field: the value is kept in _lastKnownServerRecordAllFields but not written to the row; a child record of the new table gets SyncMetadata only.
Build N+1 starts again. updateLocalFromSchemaChange sees no changed table and replays nothing, so the column stays at its default and the child row is never inserted.
A later server change to that field is fetched, but the stale default is read as a newer local edit (isRowValueModified), so the row never catches up.
The next local edit of any other column sends the default with a new modification time, overwriting the value for every device.
The plain upgrade (an older build that never opened a migrated file) works, with or without an edit on the older build before updating.
Questions: Is opening a newer-schema store with an older build something SQLiteData aims to support? If not, is there a recommended pattern? What we built in our lab: a local, never-synced storeInfo table with highestSchemaVersion, read on a plain read-only connection before attaching the metadatabase, migrating or starting the engine; if the store is newer than the build, we open it read-only with no SyncEngine. That passes our test for a nullable column. Does that look right to you, or would you suggest something better (or is something like it planned upstream)?
2. A column added after v1 with NOT NULL … DEFAULT, no downgrade involved
With a column added in a later version as NOT NULL ON CONFLICT REPLACE DEFAULT 0 (the form used in SchemaChangeTests), we saw in our lab that a value another device sets after this device upgraded is not applied here, and this device's next edit of the row writes the default back to the server. A nullable column with no default behaves correctly, so our rule is now: every column added after the first version is nullable with no default (defaults computed in Swift), and new tables are fine.
Questions: Is that the rule you'd recommend, or are we using the default-column form wrong? We saw the 1.5.0 fix for schema migrations and NOT NULL columns (#365); is our case a different one?
(Separately, we're following #244 on leaving some fields unencrypted — our use case is the same read-only CloudKit JS web view.)
Failing test for question 1
In Tests/SQLiteDataTests/CloudKitTests/, next to SchemaChangeTests:
#if canImport(CloudKit)importCloudKitimportCustomDumpimportFoundationimportSQLiteDataimportTestingextensionBaseCloudKitTests{finalclassDowngradeThenUpgradeTests:BaseCloudKitTests, @uncheckedSendable{@available(iOS17,macOS14,tvOS17,watchOS10,*)@TestfuncnewColumnAfterDowngradeAndUpgrade()asyncthrows{tryawaituserDatabase.userWrite{dbintrydb.seed{RemindersList(id:1,title:"Personal")}}tryawaitsyncEngine.processPendingRecordZoneChanges(scope:.private)
// 1. Newer build: migrate, start (caches the new record types).
syncEngine.stop()tryawaituserDatabase.userWrite{dbintry #sql(""" ALTER TABLE "remindersLists" ADD COLUMN "position" INTEGER NOT NULL ON CONFLICT REPLACE DEFAULT 0""").execute(db)}letnewTables:[anySynchronizableTable]=syncEngine.tables.filter{$0.base!=RemindersList.self}+[SynchronizedTable(for:ListWithPosition.self)]letnewer=tryawaitSyncEngine(container:syncEngine.container,userDatabase:syncEngine.userDatabase,tables:newTables,privateTables:syncEngine.privateTables)newer.stop()
// 2. Older build on the same file receives the new field.
letolder=tryawaitSyncEngine(container:syncEngine.container,userDatabase:syncEngine.userDatabase,tables:syncEngine.tables,privateTables:syncEngine.privateTables)tryawaitwithDependencies{$0.currentTime.now+=60}operation:{letrecord=tryolder.private.database.record(for:RemindersList.recordID(for:1))record.setValue(7,forKey:"position",at:now)tryawaitolder.modifyRecords(scope:.private,saving:[record]).notify()}older.stop()
// 3. Newer build again.
letrelaunched=tryawaitSyncEngine(container:syncEngine.container,userDatabase:syncEngine.userDatabase,tables:newTables,privateTables:syncEngine.privateTables)defer{_=relaunched}tryawaituserDatabase.read{dbin
// ❌ position is 0
try #expect(ListWithPosition.find(1).fetchOne(db)?.position==7)}
// 4. A later server change to the field is fetched.
tryawaitwithDependencies{$0.currentTime.now+=180}operation:{letrecord=tryrelaunched.private.database.record(for:RemindersList.recordID(for:1))record.setValue(8,forKey:"position",at:now)tryawaitrelaunched.modifyRecords(scope:.private,saving:[record]).notify()}tryawaituserDatabase.read{dbin
// ❌ still 0
try #expect(ListWithPosition.find(1).fetchOne(db)?.position==8)}
// 5. A title-only edit on this device.
tryawaitwithDependencies{$0.currentTime.now+=240}operation:{tryawaituserDatabase.userWrite{dbintryListWithPosition.find(1).update{$0.title="Edited"}.execute(db)}tryawaitrelaunched.processPendingRecordZoneChanges(scope:.private)}letserver=tryrelaunched.private.database.record(for:RemindersList.recordID(for:1))
// ❌ 0: the server's 8 is overwritten
#expect(server.encryptedValues["position"]as?Int64==8)}}}@Table("remindersLists")privatestructListWithPosition:Equatable,Identifiable{letid:Intvartitle=""varposition=0}#endif
If it helps, two ideas from reading the code (you'll know better): compare cached record types against the running engine's own Table columns rather than sqlite_master, or let updateLocalFromSchemaChange fill columns that still hold their default while _lastKnownServerRecordAllFields has a value.
Both behaviors are expected given how SyncEngine currently checks schemas (sqlite_master vs. lastKnownServerRecord). Your two workarounds are the exact patterns to use.
1. Why NOT NULL DEFAULT 0 breaks sync when added in v2+ (Question 2)
When a device upgrades first, SQLite fills the new column with 0, while lastKnownServerRecord["position"] is still nil. Because 0 != nil, SyncEngine (isRowValueModified in CloudKit+StructuredQueries.swift) thinks 0 is a newer local edit and ignores incoming server values (8), eventually pushing 0 back to CloudKit.
❌ Before (causes 0 != nil false local-edit conflict):
// Migration
try #sql("ALTER TABLE \"remindersLists\" ADD COLUMN \"position\" INTEGER NOT NULL ON CONFLICT REPLACE DEFAULT 0").execute(db)@Table("remindersLists")structRemindersList:Identifiable{letid:Intvartitle=""varposition=0}
✅ After (works cleanly across all upgrade orders):
Make columns added after v1 nullable (DEFAULT NULL) in SQLite so nil == nil matches lastKnownServerRecord, and expose a non-optional helper in Swift:
2. Older build opening a store migrated by a newer build (Question 1)
SyncEngine.start() reads currentRecordTypes from sqlite_master (SQLiteSchema), not from the running Swift @Table struct. Once Build $N+1$ alters the table, sqlite_master.sql never changes again—so after Build $N$ runs, Build $N+1$ doesn't know it needs to replay _lastKnownServerRecordAllFields.
✅ Recommended Guard (check user_version before starting SyncEngine):
Your highestSchemaVersion check is the right approach. You can also use SQLite's built-in PRAGMA user_version before attaching SyncEngine:
letappSchemaVersion=2letdbVersion=tryawaituserDatabase.read{dbintryInt.fetchOne(db,sql:"PRAGMA user_version")??0}ifdbVersion>appSchemaVersion{
// Store was migrated by a newer app build -> do NOT start SyncEngine on this older build
}else{
// Safe to run migrations, bump PRAGMA user_version, and start SyncEngine
}
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
Hi! Thank you for SQLiteData — we're moving a multiplatform SwiftUI app (iPhone, iPad, Mac) from SwiftData to it, mainly for CloudKit sharing, and the sharing work in our lab has been excellent.
We're on sqlite-data 1.13.0 (
e72164c), GRDB 7.12.0, Xcode 27.2 / macOS 27.2, withSyncEnginesyncing a private database and shares. While planning how our schema will grow after the first release, we ran into two behaviours and would like to know whether they're expected, and what you'd recommend.1. An older build opening a store a newer build migrated
Steps (failing test below):
ALTER TABLE … ADD COLUMN; also a new child table) and starts itsSyncEngine.sqlite_master, so it now caches the table with the new column. It receives a record carrying the new field: the value is kept in_lastKnownServerRecordAllFieldsbut not written to the row; a child record of the new table getsSyncMetadataonly.updateLocalFromSchemaChangesees no changed table and replays nothing, so the column stays at its default and the child row is never inserted.isRowValueModified), so the row never catches up.The plain upgrade (an older build that never opened a migrated file) works, with or without an edit on the older build before updating.
Questions: Is opening a newer-schema store with an older build something SQLiteData aims to support? If not, is there a recommended pattern? What we built in our lab: a local, never-synced
storeInfotable withhighestSchemaVersion, read on a plain read-only connection before attaching the metadatabase, migrating or starting the engine; if the store is newer than the build, we open it read-only with noSyncEngine. That passes our test for a nullable column. Does that look right to you, or would you suggest something better (or is something like it planned upstream)?2. A column added after v1 with
NOT NULL … DEFAULT, no downgrade involvedWith a column added in a later version as
NOT NULL ON CONFLICT REPLACE DEFAULT 0(the form used inSchemaChangeTests), we saw in our lab that a value another device sets after this device upgraded is not applied here, and this device's next edit of the row writes the default back to the server. A nullable column with no default behaves correctly, so our rule is now: every column added after the first version is nullable with no default (defaults computed in Swift), and new tables are fine.Questions: Is that the rule you'd recommend, or are we using the default-column form wrong? We saw the 1.5.0 fix for schema migrations and NOT NULL columns (#365); is our case a different one?
(Separately, we're following #244 on leaving some fields unencrypted — our use case is the same read-only CloudKit JS web view.)
Failing test for question 1
In
Tests/SQLiteDataTests/CloudKitTests/, next toSchemaChangeTests:If it helps, two ideas from reading the code (you'll know better): compare cached record types against the running engine's own
Tablecolumns rather thansqlite_master, or letupdateLocalFromSchemaChangefill columns that still hold their default while_lastKnownServerRecordAllFieldshas a value.Thanks for any guidance!
All reactions