(customDbPath?: string)
| 12 | let currentDbPath: string | null = null |
| 13 | |
| 14 | export function useDB(customDbPath?: string) { |
| 15 | const dbPath |
| 16 | = customDbPath || `${store.preferences.get('storage.rootPath')}/${DB_NAME}` |
| 17 | |
| 18 | if (db && currentDbPath === dbPath) |
| 19 | return db |
| 20 | |
| 21 | if (db) { |
| 22 | db.close() |
| 23 | db = null |
| 24 | currentDbPath = null |
| 25 | } |
| 26 | |
| 27 | const dbDir = path.dirname(dbPath) |
| 28 | |
| 29 | if (!fs.existsSync(dbDir)) { |
| 30 | fs.mkdirSync(dbDir, { recursive: true }) |
| 31 | } |
| 32 | |
| 33 | try { |
| 34 | db = new Database(dbPath, { |
| 35 | // eslint-disable-next-line no-console |
| 36 | verbose: isDev ? console.log : undefined, |
| 37 | }) |
| 38 | currentDbPath = dbPath |
| 39 | |
| 40 | db.pragma('journal_mode = WAL') |
| 41 | db.pragma('foreign_keys = ON') |
| 42 | |
| 43 | db.function('unicode_lower', (str: unknown) => { |
| 44 | if (typeof str !== 'string') |
| 45 | return str |
| 46 | return str.toLowerCase() |
| 47 | }) |
| 48 | |
| 49 | db.exec(` |
| 50 | CREATE TABLE IF NOT EXISTS folders ( |
| 51 | id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 52 | name TEXT NOT NULL, |
| 53 | defaultLanguage TEXT NOT NULL, |
| 54 | parentId INTEGER, |
| 55 | isOpen INTEGER NOT NULL, |
| 56 | orderIndex INTEGER NOT NULL DEFAULT 0, |
| 57 | icon TEXT, |
| 58 | createdAt INTEGER NOT NULL, |
| 59 | updatedAt INTEGER NOT NULL, |
| 60 | FOREIGN KEY(parentId) REFERENCES folders(id) |
| 61 | ) |
| 62 | `) |
| 63 | |
| 64 | db.exec(` |
| 65 | CREATE TABLE IF NOT EXISTS snippets ( |
| 66 | id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 67 | name TEXT NOT NULL, |
| 68 | description TEXT, |
| 69 | folderId INTEGER, |
| 70 | isDeleted INTEGER NOT NULL, |
| 71 | isFavorites INTEGER NOT NULL, |
no test coverage detected