-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.js
More file actions
529 lines (472 loc) · 18 KB
/
Copy pathdatabase.js
File metadata and controls
529 lines (472 loc) · 18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
/**
* @fileoverview Database IPC handlers for DevSnippet
* Provides all communication between the renderer process and SQLite database.
* Implements full-text search (FTS5), snippet CRUD, folder management, and WikiLink resolution.
* @module ipc/database
*/
import { ipcMain, BrowserWindow } from 'electron'
import { propagateRename } from '../database/refactor'
/**
* Notifies all renderer windows that database data has changed.
* Triggers a UI refresh in all open windows via IPC event broadcast.
*
* @private
* @returns {void}
*
* @example
* // After saving a snippet
* preparedStatements.save.run(snippet)
* notifyDataChanged() // All windows refresh their UI
*/
const notifyDataChanged = () => {
BrowserWindow.getAllWindows().forEach((win) => {
if (!win.isDestroyed()) {
win.webContents.send('db:data-changed')
}
})
}
/**
* Transforms a raw database row into a frontend-friendly format.
* Converts CSV tags to arrays and normalizes boolean fields.
*
* @private
* @param {Object|null} row - Raw database row from better-sqlite3
* @param {string} row.tags - Comma-separated tag string (e.g., "react,hooks")
* @param {number} row.is_draft - SQLite boolean (0 or 1)
* @param {number} row.is_favorite - SQLite boolean (0 or 1)
* @returns {Object|null} Transformed row or null if input is null
*
* @example
* const raw = { tags: 'react,hooks', is_draft: 1, is_favorite: 0 }
* const transformed = transformRow(raw)
* // { tags: ['react', 'hooks'], is_draft: true, is_favorite: 0 }
*/
const transformRow = (row) => {
if (!row) return row
return {
...row,
tags: row.tags ? row.tags.split(',').filter(Boolean) : [],
is_draft: !!row.is_draft,
is_favorite: row.is_favorite ? 1 : 0
}
}
/**
* Registers all database IPC handlers with the Electron main process.
* Sets up bidirectional communication between renderer (React) and SQLite database.
*
* **Registered Channels:**
* - `db:getSnippets` - Fetch all or paginated snippets
* - `db:getSnippetById` - Get single snippet by ID
* - `db:saveSnippet` - Create or update snippet
* - `db:searchSnippets` - Full-text search (FTS5)
* - `db:deleteSnippet` - Soft delete snippet
* - `db:getFolders` - Get folder hierarchy
* - ... (and many more, see inline documentation)
*
* @public
* @param {import('better-sqlite3').Database} db - SQLite database instance
* @param {Object} preparedStatements - Pre-compiled SQL statements for performance
* @param {import('better-sqlite3').Statement} preparedStatements.getMetadata - Get snippet metadata only
* @param {import('better-sqlite3').Statement} preparedStatements.getAll - Get full snippet content
* @param {import('better-sqlite3').Statement} preparedStatements.getById - Get snippet by ID
* @param {import('better-sqlite3').Statement} preparedStatements.save - Save/update snippet
* @param {import('better-sqlite3').Statement} preparedStatements.softDelete - Soft delete snippet
* @returns {void}
*
* @example
* // In main/index.js
* import Database from 'better-sqlite3'
* import { registerDatabaseHandlers } from './ipc/database.js'
*
* const db = new Database('app.db')
* const preparedStatements = {
* getMetadata: db.prepare('SELECT id, title FROM snippets'),
* // ... other statements
* }
* registerDatabaseHandlers(db, preparedStatements)
*/
export const registerDatabaseHandlers = (db, preparedStatements) => {
/**
* IPC Handler: Get all snippets or paginated subset
*
* @channel db:getSnippets
* @param {Object} options - Query options
* @param {number} [options.limit] - Maximum snippets to return
* @param {number} [options.offset] - Starting position for pagination
* @param {boolean} [options.metadataOnly=true] - Fetch only metadata (no full `code`)
* @returns {Object[]} Array of snippet objects
*
* @performance Target: < 20ms for 10,000 snippets (metadata only)
*
* @example
* // Renderer process
* const snippets = await window.api.getSnippets({ limit: 50, offset: 0 })
*/
ipcMain.handle('db:getSnippets', (event, options = {}) => {
const { limit, offset, metadataOnly = true } = options
// Choose the statement based on whether we want full text or just metadata
const stmt = metadataOnly ? preparedStatements.getMetadata : preparedStatements.getAll
if (limit !== undefined && offset !== undefined) {
if (metadataOnly) {
return preparedStatements.getMetadataPaginated.all(limit, offset).map(transformRow)
}
// Fallback for full-paginated if needed (can be added later)
return db.prepare(`${stmt.source} LIMIT ? OFFSET ?`).all(limit, offset).map(transformRow)
}
return stmt.all().map(transformRow)
})
/**
* IPC Handler: Get single snippet by unique ID (full content)
*
* @channel db:getSnippetById
* @param {string} id - Snippet UUID
* @returns {Object|null} Snippet object or null if not found
*
* @performance Target: < 5ms (indexed lookup)
*
* @example
* const snippet = await window.api.getSnippetById('abc-123-def')
*/
ipcMain.handle('db:getSnippetById', (event, id) => {
return transformRow(preparedStatements.getById.get(id))
})
/**
* IPC Handler: Get snippet by title (case-insensitive)
* Used for WikiLink resolution: [[My Note]] -> snippet lookup
*
* @channel db:getSnippetByTitle
* @param {string} title - Snippet title to search for
* @returns {Object|null} Snippet object or null if not found
*
* @performance Target: < 5ms (assumes index on `title COLLATE NOCASE`)
*
* @example
* // WikiLink click handler
* const linked = await window.api.getSnippetByTitle('React Hooks Guide')
*/
ipcMain.handle('db:getSnippetByTitle', (event, title) => {
if (!title) return null
const row = db
.prepare('SELECT * FROM snippets WHERE title = ? COLLATE NOCASE AND is_deleted = 0')
.get(title.trim())
return transformRow(row)
})
// Full-text search using FTS5 with robust LIKE fallback
ipcMain.handle('db:searchSnippets', (event, query, limit = 250) => {
if (!query || query.trim().length === 0) {
return preparedStatements.getMetadata.all()
}
const trimmedQuery = query.trim()
const terms = trimmedQuery.split(/\s+/).filter(Boolean)
// 🚀 OPTIMIZATION: Use LIKE for short single-word queries (up to 3 chars)
if (trimmedQuery.length < 4 && terms.length === 1) {
const pattern = `%${trimmedQuery}%`
const results = db
.prepare(
`
SELECT id, title, code, language, timestamp, type, tags, is_draft, is_pinned, is_favorite, sort_index,
CASE WHEN (code_draft IS NOT NULL AND code_draft != '' AND code_draft != code) THEN 1 ELSE 0 END as is_modified
FROM snippets
WHERE (title LIKE ? OR tags LIKE ? OR code LIKE ?) AND is_deleted = 0
ORDER BY is_pinned DESC, timestamp DESC
LIMIT ?
`
)
.all(pattern, pattern, pattern, limit)
return results.map(transformRow)
}
try {
// Construct a robust FTS query: "term1"* AND "term2"* ...
const ftsQuery = terms.map((term) => `"${term.replace(/"/g, '""')}"*`).join(' AND ')
const results = db
.prepare(
`
SELECT s.id, s.title, s.code, s.language, s.timestamp, s.type, s.tags, s.is_draft, s.is_pinned, s.is_favorite, s.sort_index,
CASE WHEN (s.code_draft IS NOT NULL AND s.code_draft != '' AND s.code_draft != s.code) THEN 1 ELSE 0 END as is_modified,
snippet(snippets_fts, 1, '__MARK__', '__/MARK__', '...', 20) as match_context
FROM (
SELECT rowid, rank
FROM snippets_fts
WHERE snippets_fts MATCH ?
ORDER BY bm25(snippets_fts, 10.0, 1.0, 5.0)
LIMIT ?
) as fts
JOIN snippets s ON s.rowid = fts.rowid
JOIN snippets_fts ON snippets_fts.rowid = fts.rowid
WHERE s.is_deleted = 0
ORDER BY fts.rank
`
)
.all(ftsQuery, limit)
// Fallback if FTS is empty
if (results.length === 0) throw new Error('No FTS')
return results.map(transformRow)
} catch (e) {
// Final Fallback: Multi-term LIKE (All terms must exist in Title OR Code OR Tags)
let queryStr = `
SELECT id, title, code, language, timestamp, type, tags, is_draft, is_pinned, is_favorite, sort_index,
CASE WHEN (code_draft IS NOT NULL AND code_draft != '' AND code_draft != code) THEN 1 ELSE 0 END as is_modified
FROM snippets
WHERE is_deleted = 0
`
const params = []
terms.forEach((term) => {
queryStr += ` AND (title LIKE ? OR code LIKE ? OR tags LIKE ?)`
const p = `%${term}%`
params.push(p, p, p)
})
queryStr += ` ORDER BY is_pinned DESC, timestamp DESC LIMIT ?`
params.push(limit)
const results = db.prepare(queryStr).all(...params)
return results.map(transformRow)
}
})
// Save snippet
ipcMain.handle('db:saveSnippet', (event, snippet) => {
try {
// 🟢 WIKILINK REFACTORING LOGIC
// Before saving, check if we are renaming an existing snippet.
// If the title changed, we need to update all inbound links [[Old Title]] -> [[New Title]].
const oldSnippet = preparedStatements.getById.get(snippet.id)
const isRename =
oldSnippet &&
snippet.title &&
oldSnippet.title !== snippet.title &&
oldSnippet.title.trim() !== '' &&
!snippet.is_draft // Only propagate if the new version is not a draft (though usually renaming happens on permanent titles)
// PRO-TIP: Prevent duplicate titles to keep the library clean
// We skip empty titles to allow multiple "New Drafts"
if (snippet.title && snippet.title.trim()) {
const folderId = snippet.folder_id || null
const existing = db
.prepare(
'SELECT id FROM snippets WHERE title = ? COLLATE NOCASE AND id != ? AND (folder_id IS ?) AND is_draft = 0 AND is_deleted = 0'
)
.get(snippet.title.trim(), snippet.id, folderId)
if (existing) {
throw new Error('DUPLICATE_TITLE')
}
}
const dbPayload = {
id: snippet.id,
title: snippet.title || '',
code: snippet.code || '',
language: snippet.language || 'markdown',
timestamp: snippet.timestamp || Date.now(),
type: snippet.type || 'snippet',
tags: Array.isArray(snippet.tags) ? snippet.tags.join(',') : snippet.tags || '',
is_draft: snippet.is_draft ? 1 : 0,
is_favorite: snippet.is_favorite ? 1 : 0,
is_pinned: snippet.is_pinned ? 1 : 0,
sort_index: snippet.sort_index ?? null,
folder_id: snippet.folder_id ?? null
}
// Execute Save and Propagation within a single atomic transaction
db.transaction(() => {
preparedStatements.save.run(dbPayload)
if (isRename && !snippet.is_draft) {
propagateRename(db, oldSnippet.title, snippet.title)
}
})()
notifyDataChanged()
return true
} catch (err) {
console.error('Failed to save snippet to DB:', err)
throw err
}
})
// Delete snippet (Soft Delete)
ipcMain.handle('db:deleteSnippet', (event, id) => {
// preparedStatements.delete is now permanentDelete, we use softDelete
preparedStatements.softDelete.run(Date.now(), id)
notifyDataChanged()
return true
})
// Restore snippet
ipcMain.handle('db:restoreSnippet', (event, id) => {
preparedStatements.restore.run(id)
notifyDataChanged()
return true
})
// Permanent Delete
ipcMain.handle('db:permanentDeleteSnippet', (event, id) => {
preparedStatements.permanentDelete.run(id)
notifyDataChanged()
return true
})
// Save snippet draft (Silent sync for 'Modified' status dots)
ipcMain.handle('db:saveSnippetDraft', (event, payload) => {
const { id, code_draft, language } = payload
const stmt = db.prepare(
'UPDATE snippets SET code_draft = ?, language = COALESCE(?, language) WHERE id = ?'
)
stmt.run(code_draft, language || null, id)
// NOTE: We intentionally DO NOT call notifyDataChanged() here.
// Draft saving is a high-frequency background task. Triggering a
// full UI refresh on every keystroke debounce causes massive rendering lag.
return true
})
// Commit snippet draft
ipcMain.handle('db:commitSnippetDraft', (event, id) => {
const row = db.prepare('SELECT code_draft FROM snippets WHERE id = ?').get(id)
if (row && row.code_draft != null) {
const stmt = db.prepare(
'UPDATE snippets SET code = code_draft, code_draft = NULL, is_draft = 0, timestamp = ? WHERE id = ?'
)
stmt.run(Date.now(), id)
notifyDataChanged()
}
return true
})
// Get setting
ipcMain.handle('db:getSetting', (event, key) => {
const row = db.prepare('SELECT value FROM settings WHERE key = ?').get(key)
return row ? row.value : null
})
// Save setting
ipcMain.handle('db:saveSetting', (event, key, value) => {
db.prepare('INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)').run(key, value)
return true
})
// --- FOLDERS ---
ipcMain.handle('db:getFolders', () => {
return preparedStatements.getFolders.all()
})
ipcMain.handle('db:saveFolder', (event, folder) => {
try {
// Prevent duplicate folder names in the same parent (exclude soft deleted)
if (folder.name && folder.name.trim()) {
const parentId = folder.parent_id || null
const existing = db
.prepare(
'SELECT id FROM folders WHERE name = ? COLLATE NOCASE AND id != ? AND (parent_id IS ?) AND is_deleted = 0'
)
.get(folder.name.trim(), folder.id, parentId)
if (existing) {
throw new Error('DUPLICATE_FOLDER_NAME')
}
}
const dbPayload = {
id: folder.id,
name: folder.name,
parent_id: folder.parent_id || null,
collapsed: folder.collapsed ? 1 : 0,
sort_index: folder.sort_index || 0,
created_at: folder.created_at || Date.now(),
updated_at: Date.now()
}
preparedStatements.saveFolder.run(dbPayload)
notifyDataChanged()
return true
} catch (err) {
console.error('db:saveFolder failed:', err)
throw err
}
})
ipcMain.handle('db:deleteFolder', (event, id) => {
try {
const now = Date.now()
const recursiveDelete = (folderId) => {
// 1. Soft delete all snippets in this folder
db.prepare('UPDATE snippets SET is_deleted = 1, deleted_at = ? WHERE folder_id = ?').run(
now,
folderId
)
// 2. Find all child folders
const children = db
.prepare('SELECT id FROM folders WHERE parent_id = ? AND is_deleted = 0')
.all(folderId)
// 3. Recurse into children
for (const child of children) {
recursiveDelete(child.id)
}
// 4. Soft delete the folder itself
db.prepare('UPDATE folders SET is_deleted = 1, deleted_at = ? WHERE id = ?').run(
now,
folderId
)
}
db.transaction(() => {
recursiveDelete(id)
})()
notifyDataChanged()
return true
} catch (e) {
console.error('Recursive folder delete failed:', e)
throw e
}
})
ipcMain.handle('db:restoreFolder', (event, id) => {
try {
const recursiveRestore = (folderId) => {
// 1. Restore all snippets in this folder that were deleted at the same time or were simply in it
// To be safe, we restore all snippets that have this folder_id and are deleted
db.prepare('UPDATE snippets SET is_deleted = 0, deleted_at = NULL WHERE folder_id = ?').run(
folderId
)
// 2. Find all child folders (even deleted ones)
const children = db.prepare('SELECT id FROM folders WHERE parent_id = ?').all(folderId)
// 3. Recurse
for (const child of children) {
recursiveRestore(child.id)
}
// 4. Restore the folder itself
db.prepare('UPDATE folders SET is_deleted = 0, deleted_at = NULL WHERE id = ?').run(
folderId
)
}
db.transaction(() => {
recursiveRestore(id)
})()
notifyDataChanged()
return true
} catch (e) {
console.error('Recursive folder restore failed:', e)
throw e
}
})
ipcMain.handle('db:permanentDeleteFolder', (event, id) => {
try {
const recursivePermanentDelete = (folderId) => {
// 1. Delete all snippets in this folder
db.prepare('DELETE FROM snippets WHERE folder_id = ?').run(folderId)
// 2. Find all child folders
const children = db.prepare('SELECT id FROM folders WHERE parent_id = ?').all(folderId)
// 3. Recurse
for (const child of children) {
recursivePermanentDelete(child.id)
}
// 4. Delete the folder itself
db.prepare('DELETE FROM folders WHERE id = ?').run(folderId)
}
db.transaction(() => {
recursivePermanentDelete(id)
})()
notifyDataChanged()
return true
} catch (e) {
console.error('Recursive folder permanent delete failed:', e)
throw e
}
})
// Get Trash (unified)
ipcMain.handle('db:getTrash', () => {
const snippets = preparedStatements.getTrash.all().map(transformRow)
const folders = preparedStatements.getFolderTrash.all().map((f) => ({ ...f, type: 'folder' }))
return [...snippets, ...folders].sort((a, b) => (b.deleted_at || 0) - (a.deleted_at || 0))
})
ipcMain.handle('db:moveSnippet', (event, snippetId, folderId) => {
preparedStatements.updateSnippetFolder.run(folderId || null, Date.now(), snippetId)
notifyDataChanged()
return true
})
ipcMain.handle('db:moveFolder', (event, folderId, parentId) => {
preparedStatements.updateFolderParent.run(parentId || null, Date.now(), folderId)
notifyDataChanged()
return true
})
ipcMain.handle('db:toggleFolderCollapse', (event, folderId, collapsed) => {
preparedStatements.toggleFolderCollapse.run(collapsed ? 1 : 0, folderId)
return true
})
}