diff --git a/lib/core/src/persist/sync.rs b/lib/core/src/persist/sync.rs index edb95e7e4..cc211103c 100644 --- a/lib/core/src/persist/sync.rs +++ b/lib/core/src/persist/sync.rs @@ -96,18 +96,19 @@ impl Persister { Ok(sync_settings) } + fn set_sync_setting_stmt(con: &Connection) -> rusqlite::Result { + con.prepare("INSERT OR REPLACE INTO sync_settings(key, value) VALUES(:key, :value)") + } + pub(crate) fn set_sync_settings(&self, map: HashMap<&'static str, String>) -> Result<()> { let mut con = self.get_connection()?; let tx = con.transaction_with_behavior(TransactionBehavior::Immediate)?; for (key, value) in map { - tx.execute( - "INSERT OR REPLACE INTO sync_settings(key, value) VALUES(:key, :value)", - named_params! { - ":key": key, - ":value": value, - }, - )?; + Self::set_sync_setting_stmt(&tx)?.execute(named_params! { + ":key": key, + ":value": value, + })?; } tx.commit()?; @@ -115,6 +116,52 @@ impl Persister { Ok(()) } + pub(crate) fn set_new_remote(&self, remote_url: String) -> Result<()> { + let mut con = self.get_connection()?; + let tx = con.transaction_with_behavior(TransactionBehavior::Immediate)?; + + tx.execute("DELETE FROM sync_state", [])?; + tx.execute("DELETE FROM sync_incoming", [])?; + tx.execute("DELETE FROM sync_outgoing", [])?; + + let swap_tables = HashMap::from([ + ("receive_swaps", RecordType::Receive), + ("send_swaps", RecordType::Send), + ("chain_swaps", RecordType::Chain), + ]); + for (table_name, record_type) in swap_tables { + let mut stmt = tx.prepare(&format!("SELECT id FROM {table_name}"))?; + let mut rows = stmt.query([])?; + + while let Some(row) = rows.next()? { + let data_id: String = row.get(0)?; + let record_id = Record::get_id_from_record_type(record_type, &data_id); + + tx.execute( + " + INSERT INTO sync_outgoing(record_id, data_id, record_type, commit_time) + VALUES(:record_id, :data_id, :record_type, :commit_time) + ", + named_params! { + ":record_id": record_id, + ":data_id": data_id, + ":record_type": record_type, + ":commit_time": utils::now(), + }, + )?; + } + } + + Self::set_sync_setting_stmt(&tx)?.execute(named_params! { + ":key": "remote_url", + ":value": remote_url + })?; + + tx.commit()?; + + Ok(()) + } + pub(crate) fn get_incoming_records(&self) -> Result> { let con = self.get_connection()?; diff --git a/lib/core/src/sync/mod.rs b/lib/core/src/sync/mod.rs index b334d75f6..8a600d6dd 100644 --- a/lib/core/src/sync/mod.rs +++ b/lib/core/src/sync/mod.rs @@ -43,6 +43,18 @@ impl SyncService { } } + fn check_remote_change(&self) -> Result<()> { + match self + .persister + .get_sync_settings()? + .remote_url + .is_some_and(|url| url == self.remote_url) + { + true => Ok(()), + false => self.persister.set_new_remote(self.remote_url.clone()), + } + } + pub(crate) async fn run(self: Arc, mut shutdown: watch::Receiver<()>) -> Result<()> { self.client.connect(self.remote_url.clone()).await?;