mardi 15 mars 2016

Sync SQLite3 database with iCloud

This question ha been asked a number of times before, but I have been unable to find a full answer. I need to store data in my app using an sqlite3 database and core data is not an option. I want to synchronise the data across devices using iCloud, and the best approach to this seems to be to send SQL transaction logs to iCloud and use them to keep device up to date. The process I've come up with so far is as follows:

  • All database altering queries (INSERT, UPDATE, DELETE) once executed are stored in a transactions array, each element of which contains the sql query and the timestamp it was carried out
  • The database contains a table for logging the point in the transactions array that the app last got to (including the filename of the transactions file stored on iCloud)
  • Transactions array saved to device-unique file on iCloud
  • When syncing:
    1. Get array of transactions files from iCloud
    2. Create empty array of transactions to be committed
    3. For each file:
      • Check database for last position got to in transaction file
      • If none, start from beginning of file
      • Add each transaction from that point to the array of transactions to be committed
      • Update database with new last position of transaction file so the synced transactions are not repeated
    4. Sort the array of transactions to be committed by transaction timestamp
    5. Execute the commands in the array of transactions to be committed

I am confident that I can get this working in terms of pulling the data down to each device and carrying out the commands to update each local copy. The only problem I envisage is if two devices insert a record to the same table while both offline and then sync. For example:

  1. Device 1 and device 2 both have synchronised copies of the database, with four records each in the table "table1"
  2. Device 1 inserts value "foo" to table "table1" with PK 5
  3. Device 2 inserts value "bar" to table "table1" with PK 5
  4. Device 1 downloads transaction log for device 2 and inserts value "bar" to ID 6
  5. Device 2 downloads transaction log for device 1 and inserts value "foo" to ID 6

We now have a situation where the primary keys for these records are inverted on each device, which will break links to tables which rely on the primary key for linking.

I'm still trying to research a solution to this but in the meantime if anybody has an suggestions I would be extremely grateful!

Aucun commentaire:

Enregistrer un commentaire