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