Skip to content

Commit 1951d6a

Browse files
fix(db): add SQLite file validation and backup for non-SQLite file #592 (#601)
1 parent 29084be commit 1951d6a

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

src/main/db/index.ts

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,24 @@ import fs from 'fs-extra'
77
import { store } from '../store'
88

99
const DB_NAME = 'massCode.db'
10-
// const BACKUP_DB_NAME = 'massCode-backup.db'
11-
// const MANUAL_BACKUP_DB_NAME = 'massCode-manual-backup.db'
1210
const isDev = process.env.NODE_ENV === 'development'
1311

1412
let db: Database.Database | null = null
1513
let backupTimer: NodeJS.Timeout | null = null
1614

15+
function isSqliteFile(dbPath: string): boolean {
16+
try {
17+
if (!fs.existsSync(dbPath))
18+
return false
19+
20+
const buffer = fs.readFileSync(dbPath).subarray(0, 16)
21+
return buffer.toString('ascii') === 'SQLite format 3\x00'
22+
}
23+
catch {
24+
return false
25+
}
26+
}
27+
1728
function tableExists(db: Database.Database, table: string): boolean {
1829
const row = db
1930
.prepare(
@@ -33,6 +44,14 @@ export function useDB() {
3344

3445
const dbPath = `${store.preferences.get('storagePath')}/${DB_NAME}`
3546

47+
if (fs.existsSync(dbPath) && !isSqliteFile(dbPath)) {
48+
const backupPath = `${dbPath}.old`
49+
try {
50+
fs.moveSync(dbPath, backupPath)
51+
}
52+
catch {}
53+
}
54+
3655
try {
3756
db = new Database(dbPath, {
3857
// eslint-disable-next-line no-console

0 commit comments

Comments
 (0)