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