Treasury & Bank Transfer Management System — سامانه مدیریت خزانه‌داری و حواله‌های بانکی

Serialize SQLite financial snapshots inside BEGIN IMMEDIATE to prevent concurrent lost updates

davoodmehraban89 committed Oct 23, 2026 at 10:55 UTC 30204cb96789bbf9a530dabef70a56940d558b0d
1 file changed +6 -3
src/platform/local/sqlite-store.ts
+6 -3
@@ -99,10 +99,13 @@ export class SqliteStore{
99 }
100
101 update(mutator:(data:LocalStoreData)=>LocalStoreData){
102 - const next=mutator(structuredClone(this.snapshot()));
103 - if(next.version!==1) throw new Error('unsupported sqlite schema version');
102 + // Acquire the write lock before reading the snapshot. Otherwise another
103 + // connection can commit between snapshot() and BEGIN IMMEDIATE, causing
104 + // lost payments or audit rows when the rewritten tables are committed.
105 this.db.exec('BEGIN IMMEDIATE');
106 try{
107 + const next=mutator(structuredClone(this.snapshot()));
108 + if(next.version!==1) throw new Error('unsupported sqlite schema version');
109 this.db.prepare("UPDATE meta SET value=? WHERE key='organization_name'").run(next.meta.organizationName);
110 this.db.exec('DELETE FROM audit; DELETE FROM payments; DELETE FROM beneficiaries; DELETE FROM accounts;');
111 const accountStmt=this.db.prepare('INSERT INTO accounts(id,tenant_id,name,iban,bank_name,status) VALUES(?,?,?,?,?,?)');
@@ -114,11 +117,11 @@ export class SqliteStore{
117 const auditStmt=this.db.prepare('INSERT INTO audit(tenant_id,seq,actor,action,entity,at) VALUES(?,?,?,?,?,?)');
118 for(const a of next.audit) auditStmt.run(a.tenantId,a.seq,a.actor,a.action,a.entity,a.at);
119 this.db.exec('COMMIT');
120 + return structuredClone(next);
121 }catch(error){
122 this.db.exec('ROLLBACK');
123 throw error;
124 }
121 - return structuredClone(next);
125 }
126
127 close(){this.db.close()}