Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add working merge functionality (#186)
Leendert de Borste82faeba4030
diff --git a/src/AliasVault.Client/Main/Pages/Sync/StatusMessages/Merging.razor b/src/AliasVault.Client/Main/Pages/Sync/StatusMessages/Merging.razorindex e45d7ae32..a32d148c1 100644--- a/src/AliasVault.Client/Main/Pages/Sync/StatusMessages/Merging.razor+++ b/src/AliasVault.Client/Main/Pages/Sync/StatusMessages/Merging.razor@@ -5,7 +5,7 @@<div class="text-center"><div class="space-y-4"><BoldLoadingIndicator />- <h2 class="text-xl font-semibold text-gray-900 dark:text-white">Merging required</h2>+ <h2 class="text-xl font-semibold text-gray-900 dark:text-white">Vault merge in progress</h2><p class="text-sm text-gray-500 dark:text-gray-400">A merge is required because another client has made changes to the vault since you last synced.</p>diff --git a/src/AliasVault.Client/Services/Database/DbMergeUtility.cs b/src/AliasVault.Client/Services/Database/DbMergeUtility.csindex 9a2dace9a..55391d6f6 100644--- a/src/AliasVault.Client/Services/Database/DbMergeUtility.cs+++ b/src/AliasVault.Client/Services/Database/DbMergeUtility.cs@@ -47,55 +47,93 @@ public static class DbMergeUtilityusing var baseCommand = baseConnection.CreateCommand();using var sourceCommand = sourceConnection.CreateCommand();- // Check if the table has UpdatedAt and IsDeleted columnsbaseCommand.CommandText = $"PRAGMA table_info({tableName})";var columns = new List<string>();+ bool hasId = false;+ bool hasUpdatedAt = false;+ bool hasIsDeleted = false;+using (var reader = await baseCommand.ExecuteReaderAsync()){while (await reader.ReadAsync()){- columns.Add(reader.GetString(1));+ string columnName = reader.GetString(1);+ columns.Add(columnName);+ if (columnName == "Id")+ {+ hasId = true;+ }+ else if (columnName == "UpdatedAt")+ {+ hasUpdatedAt = true;+ }+ else if (columnName == "IsDeleted")+ {+ hasIsDeleted = true;+ }}}- bool hasUpdatedAt = columns.Contains("UpdatedAt");- bool hasIsDeleted = columns.Contains("IsDeleted");+ // Check if the table has Id, UpdatedAt and IsDeleted columns.+ if (!hasId || !hasUpdatedAt || !hasIsDeleted)+ {+ return;+ }- // Get all records from the source table+ // Get all records from the source table.sourceCommand.CommandText = $"SELECT * FROM {tableName}";using var sourceReader = await sourceCommand.ExecuteReaderAsync();+ Console.WriteLine($"Got records for {tableName}.");+while (await sourceReader.ReadAsync()){- var id = sourceReader.GetValue(0); // Assuming the first column is always the ID+ var id = sourceReader.GetValue(0);var updatedAt = hasUpdatedAt ? sourceReader.GetDateTime(columns.IndexOf("UpdatedAt")) : DateTime.MinValue;var isDeleted = hasIsDeleted && sourceReader.GetBoolean(columns.IndexOf("IsDeleted"));- // Check if the record exists in the base table- baseCommand.CommandText = $"SELECT * FROM {tableName} WHERE Id = @Id";+ // Check if the record exists in the base table.+ baseCommand.CommandText = $"SELECT UpdatedAt FROM {tableName} WHERE Id = @Id";baseCommand.Parameters.Clear();baseCommand.Parameters.AddWithValue("@Id", id);- using var baseReader = await baseCommand.ExecuteReaderAsync();- if (await baseReader.ReadAsync())+ Console.WriteLine($"Checking if record exists in {tableName}.");++ var existingRecord = await baseCommand.ExecuteScalarAsync();+ if (existingRecord != null){- // Record exists, compare UpdatedAt+ Console.WriteLine($"Record exists in {tableName}.");++ // Record exists, compare UpdatedAt if it exists.if (hasUpdatedAt){- var baseUpdatedAt = baseReader.GetDateTime(columns.IndexOf("UpdatedAt"));+ Console.WriteLine($"Comparing UpdatedAt in {tableName}.");+ Console.WriteLine($"UpdatedAt: {existingRecord}");+ var baseUpdatedAt = DateTime.Parse((string)existingRecord);if (updatedAt > baseUpdatedAt){- // Source record is newer, update the base record+ // Source record is newer, update the base record.await UpdateRecord(baseConnection, tableName, sourceReader, columns);}+ else+ {+ Console.WriteLine($"Base record is newer, skipping {tableName}.");+ }+ }+ else+ {+ // If UpdatedAt doesn't exist, always update.+ await UpdateRecord(baseConnection, tableName, sourceReader, columns);}}else{- // Record doesn't exist in base, add it+ // Record doesn't exist in base, add it.await InsertRecord(baseConnection, tableName, sourceReader, columns);}}++ Console.WriteLine($"Merged {tableName}.");}/// <summary>diff --git a/src/AliasVault.Client/Services/Database/DbService.cs b/src/AliasVault.Client/Services/Database/DbService.csindex d354ae7d8..0589276ef 100644--- a/src/AliasVault.Client/Services/Database/DbService.cs+++ b/src/AliasVault.Client/Services/Database/DbService.cs@@ -127,15 +127,41 @@ public sealed class DbService : IDisposable// Get all table names from the base databasevar tables = await DbMergeUtility.GetTableNames(baseConnection);+ // Disable foreign key checks on the base connection+ await using (var command = baseConnection.CreateCommand())+ {+ command.CommandText = "PRAGMA foreign_keys = OFF;";+ await command.ExecuteNonQueryAsync();+ }+// Merge each database into the base+ var i = 0;foreach (var connection in sqlConnections){+ i++;foreach (var table in tables){await DbMergeUtility.MergeTable(baseConnection, connection, table);}}+ // Re-enable foreign key checks and verify integrity+ await using (var command = baseConnection.CreateCommand())+ {+ command.CommandText = "PRAGMA foreign_keys = ON;";+ await command.ExecuteNonQueryAsync();++ // Verify foreign key integrity+ command.CommandText = "PRAGMA foreign_key_check;";+ using var reader = await command.ExecuteReaderAsync();+ if (await reader.ReadAsync())+ {+ // Foreign key violation detected+ _state.UpdateState(DbServiceState.DatabaseStatus.MergeFailed, "Foreign key violation detected after merge.");+ return false;+ }+ }+// Set the merged database as the current database_sqlConnection.Close();_sqlConnection = baseConnection;@@ -149,10 +175,15 @@ public sealed class DbService : IDisposable}await _dbContext.Database.MigrateAsync();+ _vaultRevisionNumber = vaultsToMerge.Vaults.Max(v => v.CurrentRevisionNumber);+_isSuccessfullyInitialized = true;await _settingsService.InitializeAsync(this);_state.UpdateState(DbServiceState.DatabaseStatus.Ready);+ // Save the newly merged database to the server.+ await SaveDatabaseAsync();+return true;}catch (Exception ex)