From 337c128ec931206cf442406810d987aa65e0141f Mon Sep 17 00:00:00 2001 From: Spoffy Date: Wed, 15 Jan 2025 08:25:23 +0000 Subject: [PATCH] Adds a comment explaining why UNIQUE constraint is caught. --- app/server/lib/DocStorage.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/app/server/lib/DocStorage.ts b/app/server/lib/DocStorage.ts index c6b4d1c607..7d1791b9c4 100644 --- a/app/server/lib/DocStorage.ts +++ b/app/server/lib/DocStorage.ts @@ -1885,8 +1885,13 @@ export class DocStorage implements ISQLiteDB, OnDemandStorage { } private async _addBasicFileRecord(db: SQLiteDB, fileIdent: string): Promise { + // Try to insert a new record with the given ident. It'll fail the UNIQUE constraint if exists. + // Catching the violation is the simplest and most reliable way of doing this. + // If this function runs multiple times in parallel (which can happen), nothing guarantees the + // order that multiple `db.run` or `db.get` statements will run in (not even .execTransaction). + // This means it's not safe to check then insert - we just have to try the insert and see if it + // fails. try { - // Try to insert a new record with the given ident. It'll fail UNIQUE constraint if exists. await db.run('INSERT INTO _gristsys_Files (ident, data, storageId) VALUES (?)', fileIdent); } catch(err) { // If UNIQUE constraint failed, this ident must already exist.