Sources/OrgIndex/IndexStore.swift
cmc Search Notes: text before the first heading; snippets with highlighted matches
0c3d86f109 1 month ago498 lines · 24373 bytes
1import Foundation
2import GRDB
3
4/// What the index knows about a file without reading it.
5public struct FileState: Sendable, Equatable {
6 public let kind: FileKind
7 public let size: Int
8 public let mtime: Double
9 public let hash: String
10 public let settingsVersion: Int
11}
12
13/// A heading as found by a query. `contentHash` is the hash of the text the offsets refer to,
14/// so a caller can tell whether they still apply to an open buffer.
15public struct IndexedHeading: Sendable, Hashable {
16 public let location: HeadingLocation
17 public let level: Int
18 /// Titles from the top-level ancestor down to the heading itself.
19 public let outlinePath: [String]
20}
21
22public struct HeadingLocation: Sendable, Hashable {
23 public let path: String
24 /// `fileOrdinal` for the file itself, before its first heading.
25 public let ordinal: Int
26 public let title: String
27 public let start: Int
28 public let contentHash: String
29 /// The text around the match, for search results whose match is in the text.
30 public internal(set) var snippet: Snippet?
31
32 public init(path: String, ordinal: Int, title: String, start: Int, contentHash: String) {
33 self.path = path
34 self.ordinal = ordinal
35 self.title = title
36 self.start = start
37 self.contentHash = contentHash
38 }
39
40 public static let fileOrdinal = -1
41
42 /// The file before its first heading, titled by its name.
43 public static func file(_ path: String, contentHash: String) -> HeadingLocation {
44 HeadingLocation(path: path, ordinal: fileOrdinal, title: (path as NSString).lastPathComponent, start: 0, contentHash: contentHash)
45 }
46}
47
48/// One reconciliation's worth of changes, applied in a single transaction.
49public struct IndexChange: Sendable {
50 public var records: [FileRecord] = []
51 /// Unchanged content with a new modification time.
52 public var touches: [(path: String, mtime: Double)] = []
53 /// Renamed files whose content didn't change.
54 public var moves: [(from: String, to: String, mtime: Double)] = []
55 public var removals: [String] = []
56
57 public init() {}
58
59 public var isEmpty: Bool { records.isEmpty && touches.isEmpty && moves.isEmpty && removals.isEmpty }
60}
61
62/// The SQLite index. A cache: deleting it loses nothing that the files don't hold.
63public final class IndexStore: Sendable {
64 let database: DatabaseQueue
65
66 /// `path` nil opens an in-memory index.
67 public init(path: String? = nil) throws {
68 database = try path.map { try DatabaseQueue(path: $0) } ?? DatabaseQueue()
69 try Self.migrator.migrate(database)
70 }
71
72 static var migrator: DatabaseMigrator {
73 var migrator = DatabaseMigrator()
74 migrator.registerMigration("v1") { db in
75 try db.execute(sql: """
76 CREATE TABLE files (
77 id INTEGER PRIMARY KEY,
78 path TEXT NOT NULL UNIQUE,
79 root TEXT NOT NULL,
80 kind TEXT NOT NULL,
81 size INTEGER NOT NULL,
82 mtime REAL NOT NULL,
83 hash TEXT NOT NULL,
84 settings_version INTEGER NOT NULL,
85 parsed_at REAL NOT NULL
86 );
87 CREATE INDEX files_root ON files(root);
88 CREATE TABLE headings (
89 id INTEGER PRIMARY KEY,
90 file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE,
91 ordinal INTEGER NOT NULL,
92 parent_ordinal INTEGER,
93 start_offset INTEGER NOT NULL,
94 end_offset INTEGER NOT NULL,
95 level INTEGER NOT NULL,
96 todo TEXT,
97 is_done INTEGER NOT NULL,
98 priority TEXT,
99 title TEXT NOT NULL,
100 outline_path TEXT NOT NULL,
101 org_id TEXT,
102 archived INTEGER NOT NULL
103 );
104 CREATE INDEX headings_file ON headings(file_id);
105 CREATE INDEX headings_org_id ON headings(org_id);
106 CREATE TABLE tags (
107 heading_id INTEGER NOT NULL REFERENCES headings(id) ON DELETE CASCADE,
108 tag TEXT NOT NULL,
109 inherited INTEGER NOT NULL
110 );
111 CREATE INDEX tags_heading ON tags(heading_id);
112 CREATE TABLE properties (
113 heading_id INTEGER NOT NULL REFERENCES headings(id) ON DELETE CASCADE,
114 key TEXT NOT NULL,
115 value TEXT NOT NULL,
116 inherited INTEGER NOT NULL
117 );
118 CREATE INDEX properties_heading ON properties(heading_id);
119 CREATE TABLE timestamps (
120 heading_id INTEGER NOT NULL REFERENCES headings(id) ON DELETE CASCADE,
121 kind TEXT NOT NULL,
122 start_at TEXT NOT NULL,
123 end_at TEXT,
124 repeater TEXT,
125 warning TEXT
126 );
127 CREATE INDEX timestamps_heading ON timestamps(heading_id);
128 CREATE TABLE clocks (
129 heading_id INTEGER NOT NULL REFERENCES headings(id) ON DELETE CASCADE,
130 start_at TEXT NOT NULL,
131 end_at TEXT,
132 minutes INTEGER
133 );
134 CREATE INDEX clocks_heading ON clocks(heading_id);
135 CREATE TABLE links (
136 heading_id INTEGER NOT NULL REFERENCES headings(id) ON DELETE CASCADE,
137 type TEXT NOT NULL,
138 target TEXT NOT NULL
139 );
140 CREATE INDEX links_heading ON links(heading_id);
141 CREATE VIRTUAL TABLE headings_fts USING fts5(title, body, tokenize = 'unicode61 remove_diacritics 2');
142 CREATE TRIGGER headings_fts_delete AFTER DELETE ON headings BEGIN
143 DELETE FROM headings_fts WHERE rowid = old.id;
144 END;
145 """)
146 }
147 migrator.registerMigration("v2") { db in
148 // Links before a file's first heading; files are read again to fill it.
149 try db.execute(sql: """
150 CREATE TABLE file_links (
151 file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE,
152 type TEXT NOT NULL,
153 target TEXT NOT NULL
154 );
155 CREATE INDEX file_links_file ON file_links(file_id);
156 UPDATE files SET settings_version = -1;
157 """)
158 }
159 migrator.registerMigration("v3") { db in
160 // File-level IDs and titles, for org-roam file nodes; files are read again to fill them.
161 try db.execute(sql: """
162 ALTER TABLE files ADD COLUMN org_id TEXT;
163 ALTER TABLE files ADD COLUMN title TEXT;
164 CREATE INDEX files_org_id ON files(org_id);
165 UPDATE files SET settings_version = -1;
166 """)
167 }
168 migrator.registerMigration("v4") { db in
169 // Text before a file's first heading, searched as the file; files are read again to fill it.
170 try db.execute(sql: """
171 CREATE VIRTUAL TABLE files_fts USING fts5(body, tokenize = 'unicode61 remove_diacritics 2');
172 CREATE TRIGGER files_fts_delete AFTER DELETE ON files BEGIN
173 DELETE FROM files_fts WHERE rowid = old.id;
174 END;
175 UPDATE files SET settings_version = -1;
176 """)
177 }
178 return migrator
179 }
180
181 // MARK: - Writing
182
183 public func write(_ record: FileRecord) throws {
184 var change = IndexChange()
185 change.records = [record]
186 try apply(change)
187 }
188
189 public func apply(_ change: IndexChange) throws {
190 guard !change.isEmpty else { return }
191 try database.write { db in
192 for path in change.removals {
193 try db.execute(sql: "DELETE FROM files WHERE path = ?", arguments: [path])
194 }
195 for move in change.moves {
196 try db.execute(sql: "UPDATE files SET path = ?, mtime = ? WHERE path = ?", arguments: [move.to, move.mtime, move.from])
197 }
198 for touch in change.touches {
199 try db.execute(sql: "UPDATE files SET mtime = ? WHERE path = ?", arguments: [touch.mtime, touch.path])
200 }
201 for record in change.records {
202 try insert(record, db)
203 }
204 }
205 }
206
207 private func insert(_ record: FileRecord, _ db: Database) throws {
208 try db.execute(sql: "DELETE FROM files WHERE path = ?", arguments: [record.path])
209 try db.execute(
210 sql: """
211 INSERT INTO files (path, root, kind, size, mtime, hash, settings_version, parsed_at, org_id, title)
212 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
213 """,
214 arguments: [record.path, record.root, record.kind.rawValue, record.size, record.mtime, record.hash,
215 record.settingsVersion, Date().timeIntervalSince1970, record.fileID, record.title]
216 )
217 let fileID = db.lastInsertedRowID
218 if !record.preamble.allSatisfy(\.isWhitespace) {
219 try db.execute(sql: "INSERT INTO files_fts (rowid, body) VALUES (?, ?)", arguments: [fileID, record.preamble])
220 }
221 for link in record.links {
222 try db.execute(sql: "INSERT INTO file_links VALUES (?, ?, ?)", arguments: [fileID, link.type, link.target])
223 }
224 for heading in record.headings {
225 try db.execute(
226 sql: """
227 INSERT INTO headings (file_id, ordinal, parent_ordinal, start_offset, end_offset, level, todo,
228 is_done, priority, title, outline_path, org_id, archived)
229 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
230 """,
231 arguments: [fileID, heading.ordinal, heading.parent, heading.start, heading.end, heading.level, heading.todo,
232 heading.isDone, heading.priority, heading.title, heading.outlinePath.joined(separator: "\u{1F}"),
233 heading.orgID, heading.archived]
234 )
235 let id = db.lastInsertedRowID
236 try db.execute(sql: "INSERT INTO headings_fts (rowid, title, body) VALUES (?, ?, ?)", arguments: [id, heading.title, heading.body])
237 for tag in heading.tags {
238 try db.execute(sql: "INSERT INTO tags VALUES (?, ?, ?)", arguments: [id, tag.name, tag.inherited])
239 }
240 for property in heading.properties {
241 try db.execute(sql: "INSERT INTO properties VALUES (?, ?, ?, ?)", arguments: [id, property.key, property.value, property.inherited])
242 }
243 for stamp in heading.timestamps {
244 try db.execute(
245 sql: "INSERT INTO timestamps VALUES (?, ?, ?, ?, ?, ?)",
246 arguments: [id, stamp.kind.rawValue, stamp.start, stamp.end, stamp.repeater, stamp.warning]
247 )
248 }
249 for clock in heading.clocks {
250 try db.execute(sql: "INSERT INTO clocks VALUES (?, ?, ?, ?)", arguments: [id, clock.start, clock.end, clock.minutes])
251 }
252 for link in heading.links {
253 try db.execute(sql: "INSERT INTO links VALUES (?, ?, ?)", arguments: [id, link.type, link.target])
254 }
255 }
256 }
257
258 // MARK: - Reading
259
260 /// Indexed files under `root`, by path.
261 public func fileStates(root: String) throws -> [String: FileState] {
262 try database.read { db in
263 let rows = try Row.fetchAll(db, sql: "SELECT path, kind, size, mtime, hash, settings_version FROM files WHERE root = ?", arguments: [root])
264 var states: [String: FileState] = [:]
265 for row in rows {
266 states[row["path"]] = FileState(
267 kind: FileKind(rawValue: row["kind"]) ?? .org,
268 size: row["size"], mtime: row["mtime"], hash: row["hash"], settingsVersion: row["settings_version"]
269 )
270 }
271 return states
272 }
273 }
274
275 public func files() throws -> [(path: String, kind: FileKind)] {
276 try database.read { db in
277 try Row.fetchAll(db, sql: "SELECT path, kind FROM files ORDER BY path").map {
278 (path: $0["path"], kind: FileKind(rawValue: $0["kind"]) ?? .org)
279 }
280 }
281 }
282
283 // MARK: - Queries
284 //
285 // `overlay` holds records for open documents with unsaved edits, keyed by path. Their rows
286 // replace that file's indexed rows in every query.
287
288 /// Headings whose title or body contain every word of `query` as a word prefix, and files
289 /// whose text before the first heading does, best first, each with a snippet of the text
290 /// when the match is there.
291 public func search(_ query: String, overlay: [String: FileRecord] = [:], limit: Int = 50) throws -> [HeadingLocation] {
292 let terms = query.split(whereSeparator: \.isWhitespace).map(String.init)
293 guard !terms.isEmpty else { return [] }
294 let match = terms.map { "\"" + $0.replacingOccurrences(of: "\"", with: "\"\"") + "\"*" }.joined(separator: " ")
295 let prefixes = terms.flatMap(Self.words)
296 func withSnippet(_ location: HeadingLocation, _ body: String) -> HeadingLocation {
297 var location = location
298 location.snippet = Snippet(text: body, prefixes: prefixes)
299 return location
300 }
301 let indexed = try database.read { db in
302 let headings = try Row.fetchAll(
303 db,
304 sql: """
305 SELECT f.path, f.hash, h.ordinal, h.title, h.start_offset, headings_fts.body, bm25(headings_fts) AS rank
306 FROM headings_fts
307 JOIN headings h ON h.id = headings_fts.rowid
308 JOIN files f ON f.id = h.file_id
309 WHERE headings_fts MATCH ?
310 ORDER BY rank
311 LIMIT ?
312 """,
313 arguments: [match, limit + overlay.count * 10]
314 ).map { (location: withSnippet(location($0), $0["body"]), rank: $0["rank"] as Double) }
315 let files = try Row.fetchAll(
316 db,
317 sql: """
318 SELECT f.path, f.hash, f.title, files_fts.body, bm25(files_fts) AS rank
319 FROM files_fts
320 JOIN files f ON f.id = files_fts.rowid
321 WHERE files_fts MATCH ?
322 ORDER BY rank
323 LIMIT ?
324 """,
325 arguments: [match, limit + overlay.count]
326 ).map { (location: withSnippet(fileLocation($0["path"], title: $0["title"], hash: $0["hash"]), $0["body"]), rank: $0["rank"] as Double) }
327 return (headings + files).sorted { $0.rank < $1.rank }.map(\.location)
328 }
329 // Unsaved buffers get the same word-prefix matching as the full-text index.
330 func matches(_ text: String) -> Bool {
331 let words = Self.words(text)
332 return prefixes.allSatisfy { prefix in words.contains { $0.hasPrefix(prefix) } }
333 }
334 let live = overlay.values.sorted { $0.path < $1.path }.flatMap { record in
335 let file = matches(record.preamble) ? [withSnippet(fileLocation(record.path, title: record.title, hash: record.hash), record.preamble)] : []
336 return file + record.headings.filter { matches($0.title + "\n" + $0.body) }.map { withSnippet(location(record, $0), $0.body) }
337 }
338 return Array((live + indexed.filter { overlay[$0.path] == nil }).prefix(limit))
339 }
340
341 /// The file before its first heading, titled by its `#+TITLE` or else its name.
342 private func fileLocation(_ path: String, title: String?, hash: String) -> HeadingLocation {
343 let file = HeadingLocation.file(path, contentHash: hash)
344 guard let title, !title.isEmpty else { return file }
345 return HeadingLocation(path: path, ordinal: file.ordinal, title: title, start: 0, contentHash: hash)
346 }
347
348 /// Headings down to `maxLevel` in org files (not archives or conflict copies), with their
349 /// levels and outline paths, in file order: refile targets.
350 public func outline(maxLevel: Int) throws -> [IndexedHeading] {
351 try database.read { db in
352 try Row.fetchAll(
353 db,
354 sql: """
355 SELECT f.path, f.hash, h.ordinal, h.title, h.start_offset, h.level, h.outline_path
356 FROM headings h JOIN files f ON f.id = h.file_id
357 WHERE h.level <= ? AND f.kind = 'org' ORDER BY f.path, h.ordinal
358 """,
359 arguments: [maxLevel]
360 ).map { row in
361 IndexedHeading(
362 location: location(row), level: row["level"],
363 outlinePath: (row["outline_path"] as String).split(separator: "\u{1F}", omittingEmptySubsequences: false).map(String.init)
364 )
365 }
366 }
367 }
368
369 /// Headings with `:ID: id`. More than one means the ID is duplicated.
370 /// Every tag a heading has, most used first.
371 public func tags() throws -> [String] {
372 try database.read { db in
373 try String.fetchAll(db, sql: "SELECT tag FROM tags WHERE inherited = 0 GROUP BY tag ORDER BY count(*) DESC, tag")
374 }
375 }
376
377 public func headings(withID id: String, overlay: [String: FileRecord] = [:]) throws -> [HeadingLocation] {
378 let indexed = try database.read { db in
379 try Row.fetchAll(
380 db,
381 sql: """
382 SELECT f.path, f.hash, h.ordinal, h.title, h.start_offset
383 FROM headings h JOIN files f ON f.id = h.file_id
384 WHERE h.org_id = ? ORDER BY f.path, h.ordinal
385 """,
386 arguments: [id]
387 ).map(location)
388 }
389 let files = try database.read { db in
390 try Row.fetchAll(db, sql: "SELECT path, hash FROM files WHERE org_id = ? ORDER BY path", arguments: [id])
391 .map { HeadingLocation.file($0["path"], contentHash: $0["hash"]) }
392 }
393 let live = overlay.values.sorted { $0.path < $1.path }.flatMap { record in
394 (record.fileID == id ? [HeadingLocation.file(record.path, contentHash: record.hash)] : [])
395 + record.headings.filter { $0.orgID == id }.map { location(record, $0) }
396 }
397 return (files + indexed).filter { overlay[$0.path] == nil } + live
398 }
399
400 /// A heading or file with an ID: an org-roam node.
401 public struct Node: Sendable, Hashable {
402 public let id: String
403 public let title: String
404 public let location: HeadingLocation
405 }
406
407 /// Every heading and file with an ID, files first, unsaved buffers' in place of their
408 /// files'. A file's title is its `#+TITLE`, else its name without `.org`.
409 public func nodes(overlay: [String: FileRecord] = [:]) throws -> [Node] {
410 func fileTitle(_ path: String, _ title: String?) -> String { title ?? ((path as NSString).lastPathComponent as NSString).deletingPathExtension }
411 let indexed = try database.read { db in
412 let files = try Row.fetchAll(db, sql: "SELECT path, hash, org_id, title FROM files WHERE org_id IS NOT NULL AND kind = 'org' ORDER BY path").map { row in
413 Node(id: row["org_id"], title: fileTitle(row["path"], row["title"]), location: .file(row["path"], contentHash: row["hash"]))
414 }
415 let headings = try Row.fetchAll(
416 db,
417 sql: """
418 SELECT f.path, f.hash, h.ordinal, h.title, h.start_offset, h.org_id
419 FROM headings h JOIN files f ON f.id = h.file_id
420 WHERE h.org_id IS NOT NULL AND f.kind = 'org' ORDER BY f.path, h.ordinal
421 """
422 ).map { Node(id: $0["org_id"], title: $0["title"], location: location($0)) }
423 return files + headings
424 }
425 let live = overlay.values.sorted { $0.path < $1.path }.flatMap { record in
426 (record.fileID.map { [Node(id: $0, title: fileTitle(record.path, record.title), location: .file(record.path, contentHash: record.hash))] } ?? [])
427 + record.headings.compactMap { heading in heading.orgID.map { Node(id: $0, title: heading.title, location: location(record, heading)) } }
428 }
429 return indexed.filter { overlay[$0.location.path] == nil } + live
430 }
431
432 /// Every link and the heading it's in, or the file for links before its first heading,
433 /// unsaved buffers' in place of their files'.
434 public func links(overlay: [String: FileRecord] = [:]) throws -> [(source: HeadingLocation, target: String)] {
435 let indexed = try database.read { db in
436 try Row.fetchAll(
437 db,
438 sql: """
439 SELECT f.path, f.hash, -1 AS ordinal, '' AS title, 0 AS start_offset, l.target
440 FROM file_links l JOIN files f ON f.id = l.file_id WHERE f.kind = 'org'
441 UNION ALL
442 SELECT f.path, f.hash, h.ordinal, h.title, h.start_offset, l.target
443 FROM links l JOIN headings h ON h.id = l.heading_id JOIN files f ON f.id = h.file_id
444 WHERE f.kind = 'org' ORDER BY 1, 3
445 """
446 ).map { row in
447 let location = location(row)
448 return (source: location.ordinal == HeadingLocation.fileOrdinal ? .file(location.path, contentHash: location.contentHash) : location,
449 target: row["target"] as String)
450 }
451 }
452 let live = overlay.values.sorted { $0.path < $1.path }.flatMap { record in
453 record.links.map { (source: HeadingLocation.file(record.path, contentHash: record.hash), target: $0.target) }
454 + record.headings.flatMap { heading in heading.links.map { (source: location(record, heading), target: $0.target) } }
455 }
456 return indexed.filter { overlay[$0.source.path] == nil } + live
457 }
458
459 /// IDs used by more than one heading.
460 public func duplicateIDs(overlay: [String: FileRecord] = [:]) throws -> [String: [HeadingLocation]] {
461 let indexed = try database.read { db in
462 try Row.fetchAll(
463 db,
464 sql: """
465 SELECT h.org_id, f.path, f.hash, h.ordinal, h.title, h.start_offset
466 FROM headings h JOIN files f ON f.id = h.file_id
467 WHERE h.org_id IN (SELECT org_id FROM headings WHERE org_id IS NOT NULL GROUP BY org_id HAVING count(*) > 1)
468 OR (h.org_id IS NOT NULL AND ? > 0)
469 ORDER BY f.path, h.ordinal
470 """,
471 arguments: [overlay.count]
472 ).map { (id: $0["org_id"] as String, location: location($0)) }
473 }
474 var byID: [String: [HeadingLocation]] = [:]
475 for row in indexed where overlay[row.location.path] == nil {
476 byID[row.id, default: []].append(row.location)
477 }
478 for record in overlay.values.sorted(by: { $0.path < $1.path }) {
479 for heading in record.headings {
480 if let id = heading.orgID { byID[id, default: []].append(location(record, heading)) }
481 }
482 }
483 return byID.filter { $0.value.count > 1 }
484 }
485
486 /// Lower-cased runs of letters and digits, as the unicode61 tokenizer splits them.
487 static func words(_ text: String) -> [String] {
488 text.lowercased().split { !$0.isLetter && !$0.isNumber }.map(String.init)
489 }
490
491 private func location(_ row: Row) -> HeadingLocation {
492 HeadingLocation(path: row["path"], ordinal: row["ordinal"], title: row["title"], start: row["start_offset"], contentHash: row["hash"])
493 }
494
495 private func location(_ record: FileRecord, _ heading: HeadingRecord) -> HeadingLocation {
496 HeadingLocation(path: record.path, ordinal: heading.ordinal, title: heading.title, start: heading.start, contentHash: record.hash)
497 }
498}