From 2abe483c6daa853fc15d3e10e59f8c302951d514 Mon Sep 17 00:00:00 2001 From: Dani Palou Date: Fri, 9 Aug 2024 14:43:43 +0200 Subject: [PATCH] MOBILE-4640 db: Fix bug when updating primary key in memory database Before this fix, the record was updated but the key was still the old primary key, so the new record wasn't found when using getOneByPrimaryKey. --- .../classes/database/eager-database-table.ts | 4 ++-- .../database/inmemory-database-table.ts | 20 +++++++++++++++++++ .../classes/database/lazy-database-table.ts | 4 ++-- 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/core/classes/database/eager-database-table.ts b/src/core/classes/database/eager-database-table.ts index 3bfbf6e8d..5820dd34f 100644 --- a/src/core/classes/database/eager-database-table.ts +++ b/src/core/classes/database/eager-database-table.ts @@ -172,7 +172,7 @@ export class CoreEagerDatabaseTable< continue; } - Object.assign(record, updates); + this.updateMemoryRecord(record, updates, this.records); } } @@ -187,7 +187,7 @@ export class CoreEagerDatabaseTable< continue; } - Object.assign(record, updates); + this.updateMemoryRecord(record, updates, this.records); } } diff --git a/src/core/classes/database/inmemory-database-table.ts b/src/core/classes/database/inmemory-database-table.ts index 7f01ad912..b3af85408 100644 --- a/src/core/classes/database/inmemory-database-table.ts +++ b/src/core/classes/database/inmemory-database-table.ts @@ -96,4 +96,24 @@ export abstract class CoreInMemoryDatabaseTable< return rowId; } + /** + * Update a record in memory. + * + * @param record Record to update. + * @param updates New values. + * @param records Records object. + */ + protected updateMemoryRecord(record: DBRecord, updates: Partial, records: Record): void { + const previousPrimaryKey = this.serializePrimaryKey(this.getPrimaryKeyFromRecord(record)); + + Object.assign(record, updates); + + const newPrimaryKey = this.serializePrimaryKey(this.getPrimaryKeyFromRecord(record)); + + if (newPrimaryKey !== previousPrimaryKey) { + delete records[previousPrimaryKey]; + records[newPrimaryKey] = record; + } + } + } diff --git a/src/core/classes/database/lazy-database-table.ts b/src/core/classes/database/lazy-database-table.ts index a745e29f4..d06aafc1c 100644 --- a/src/core/classes/database/lazy-database-table.ts +++ b/src/core/classes/database/lazy-database-table.ts @@ -156,7 +156,7 @@ export class CoreLazyDatabaseTable< continue; } - Object.assign(record, updates); + this.updateMemoryRecord(record, updates, this.records); } } @@ -171,7 +171,7 @@ export class CoreLazyDatabaseTable< continue; } - Object.assign(record, updates); + this.updateMemoryRecord(record, updates, this.records); } }