Sources/OrgIndex/IndexStore.swift

9f4554a96f2c77e714e6b67f2669774ffc3c57df
orgstar/Sources/OrgIndex/IndexStore.swift

609 lines · 31428 bytes

33 symbols in this file
  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    public func headings(withID id: String, overlay: [String: FileRecord] = [:]) throws -> [HeadingLocation] {
407        let indexed = try database.read { db in
408            try Row.fetchAll(
409                db,
410                sql: """
411                    SELECT f.path, f.hash, h.ordinal, h.title, h.start_offset
412                    FROM headings h JOIN files f ON f.id = h.file_id
413                    WHERE h.org_id = ? ORDER BY f.path, h.ordinal
414                    """,
415                arguments: [id]
416            ).map(location)
417        }
418        let files = try database.read { db in
419            try Row.fetchAll(db, sql: "SELECT path, hash FROM files WHERE org_id = ? ORDER BY path", arguments: [id])
420                .map { HeadingLocation.file($0["path"], contentHash: $0["hash"]) }
421        }
422        let live = overlay.values.sorted { $0.path < $1.path }.flatMap { record in
423            (record.fileID == id ? [HeadingLocation.file(record.path, contentHash: record.hash)] : [])
424                + record.headings.filter { $0.orgID == id }.map { location(record, $0) }
425        }
426        return (files + indexed).filter { overlay[$0.path] == nil } + live
427    }
428
429    /// A heading or file with an ID: an org-roam node.
430    public struct Node: Sendable, Hashable {
431        public let id: String
432        public let title: String
433        public let location: HeadingLocation
434        /// `ROAM_ALIASES`: other titles the node is found by.
435        public var aliases: [String] = []
436        /// `ROAM_REFS`: links and `cite:` keys the node stands for.
437        public var refs: [String] = []
438        /// A file's `#+FILETAGS`; a heading's tags, inherited ones first.
439        public var tags: [String] = []
440    }
441
442    /// Every heading and file with an ID and without `ROAM_EXCLUDE`, files first, unsaved
443    /// buffers' in place of their files'. A file's title is its `#+TITLE`, else its name
444    /// without `.org`.
445    public func nodes(overlay: [String: FileRecord] = [:]) throws -> [Node] {
446        func fileTitle(_ path: String, _ title: String?) -> String { title ?? ((path as NSString).lastPathComponent as NSString).deletingPathExtension }
447        func node(_ id: String, _ title: String, _ location: HeadingLocation, _ roam: RoamProperties, _ tags: [String]) -> Node? {
448            roam.excluded ? nil : Node(id: id, title: title, location: location, aliases: roam.aliasList, refs: roam.refList, tags: tags)
449        }
450        func tags(_ joined: String?) -> [String] { joined?.split(separator: ":").map(String.init) ?? [] }
451        let indexed = try database.read { db in
452            let files = try Row.fetchAll(
453                db,
454                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"
455            ).compactMap { row in
456                node(row["org_id"], fileTitle(row["path"], row["title"]), .file(row["path"], contentHash: row["hash"]),
457                     RoamProperties(aliases: row["roam_aliases"], refs: row["roam_refs"], exclude: row["roam_exclude"]), tags(row["tags"]))
458            }
459            let headings = try Row.fetchAll(
460                db,
461                sql: """
462                    SELECT f.path, f.hash, h.ordinal, h.title, h.start_offset, h.org_id,
463                        (SELECT value FROM properties WHERE heading_id = h.id AND key = 'ROAM_ALIASES' AND inherited = 0) AS aliases,
464                        (SELECT value FROM properties WHERE heading_id = h.id AND key = 'ROAM_REFS' AND inherited = 0) AS refs,
465                        (SELECT value FROM properties WHERE heading_id = h.id AND key = 'ROAM_EXCLUDE' AND inherited = 0) AS exclude,
466                        (SELECT group_concat(tag, ':') FROM (SELECT tag FROM tags WHERE heading_id = h.id ORDER BY rowid)) AS tags
467                    FROM headings h JOIN files f ON f.id = h.file_id
468                    WHERE h.org_id IS NOT NULL AND f.kind = 'org' ORDER BY f.path, h.ordinal
469                    """
470            ).compactMap { row in
471                node(row["org_id"], row["title"], location(row), RoamProperties(aliases: row["aliases"], refs: row["refs"], exclude: row["exclude"]), tags(row["tags"]))
472            }
473            return files + headings
474        }
475        let live = overlay.values.sorted { $0.path < $1.path }.flatMap { record in
476            (record.fileID.flatMap { node($0, fileTitle(record.path, record.title), .file(record.path, contentHash: record.hash), record.fileRoam, record.fileTags) }.map { [$0] } ?? [])
477                + record.headings.compactMap { heading in
478                    heading.orgID.flatMap { node($0, heading.title, location(record, heading), RoamProperties(heading.properties), heading.tags.map(\.name)) }
479                }
480        }
481        return indexed.filter { overlay[$0.location.path] == nil } + live
482    }
483
484    /// Every Org, Markdown (`.md`) and text file with a Denote identifier in its name, as a
485    /// node with that identifier, titled by its front matter (an Org file's `#+TITLE`, a
486    /// Markdown file's first heading without one), else its name; unsaved buffers' titles in
487    /// place of their files'.
488    public func denoteNodes(overlay: [String: FileRecord] = [:]) throws -> [Node] {
489        func node(_ path: String, _ title: String?, _ hash: String) -> Node? {
490            guard Denote.FileType(path: path) != nil, let id = Denote.identifier(ofFile: path) else { return nil }
491            return Node(id: id, title: title ?? ((path as NSString).lastPathComponent as NSString).deletingPathExtension, location: .file(path, contentHash: hash))
492        }
493        let indexed = try database.read { db in
494            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"]) }
495        }
496        let live = overlay.values.sorted { $0.path < $1.path }.compactMap { node($0.path, $0.title, $0.hash) }
497        return indexed.filter { overlay[$0.location.path] == nil } + live
498    }
499
500    /// Where every heading with an ID and without `ROAM_EXCLUDE` starts and ends, subtree
501    /// included, by file: the text each of org-roam's heading nodes covers. Unsaved buffers' in place of their files'.
502    public func nodeSections(overlay: [String: FileRecord] = [:]) throws -> [String: [(id: String, range: Range<Int>)]] {
503        var sections: [String: [(id: String, range: Range<Int>)]] = [:]
504        try database.read { db in
505            let rows = try Row.fetchAll(db, sql: """
506                SELECT f.path, h.org_id, h.start_offset, h.end_offset,
507                    (SELECT value FROM properties WHERE heading_id = h.id AND key = 'ROAM_EXCLUDE' AND inherited = 0) AS exclude
508                FROM headings h JOIN files f ON f.id = h.file_id
509                WHERE h.org_id IS NOT NULL AND f.kind = 'org' ORDER BY f.path, h.ordinal
510                """)
511            for row in rows where overlay[row["path"]] == nil && !RoamProperties(exclude: row["exclude"]).excluded {
512                sections[row["path"], default: []].append((row["org_id"], (row["start_offset"] as Int)..<(row["end_offset"] as Int)))
513            }
514        }
515        for record in overlay.values {
516            sections[record.path] = record.headings.compactMap { heading in
517                RoamProperties(heading.properties).excluded ? nil : heading.orgID.map { ($0, heading.start..<heading.end) }
518            }
519        }
520        return sections
521    }
522
523    /// Every link and the heading it's in, or the file for links before its first heading,
524    /// unsaved buffers' in place of their files'. Of Markdown and text files, Denote's links.
525    public func links(overlay: [String: FileRecord] = [:]) throws -> [(source: HeadingLocation, target: String)] {
526        let indexed = try database.read { db in
527            try Row.fetchAll(
528                db,
529                sql: """
530                    SELECT f.path, f.hash, -1 AS ordinal, '' AS title, 0 AS start_offset, l.target
531                    FROM file_links l JOIN files f ON f.id = l.file_id WHERE f.kind IN ('org', 'text')
532                    UNION ALL
533                    SELECT f.path, f.hash, h.ordinal, h.title, h.start_offset, l.target
534                    FROM links l JOIN headings h ON h.id = l.heading_id JOIN files f ON f.id = h.file_id
535                    WHERE f.kind IN ('org', 'text') ORDER BY 1, 3
536                    """
537            ).map { row in
538                let location = location(row)
539                return (source: location.ordinal == HeadingLocation.fileOrdinal ? .file(location.path, contentHash: location.contentHash) : location,
540                        target: row["target"] as String)
541            }
542        }
543        let live = overlay.values.sorted { $0.path < $1.path }.flatMap { record in
544            record.links.map { (source: HeadingLocation.file(record.path, contentHash: record.hash), target: $0.target) }
545                + record.headings.flatMap { heading in heading.links.map { (source: location(record, heading), target: $0.target) } }
546        }
547        return indexed.filter { overlay[$0.source.path] == nil } + live
548    }
549
550    /// The text under a heading, or before a file's first heading, that a location from
551    /// `links` or `search` stands for.
552    public func text(of location: HeadingLocation, overlay: [String: FileRecord] = [:]) throws -> String? {
553        if let record = overlay[location.path] {
554            if location.ordinal == HeadingLocation.fileOrdinal { return record.preamble }
555            return record.headings.first { $0.ordinal == location.ordinal }?.body
556        }
557        return try database.read { db in
558            if location.ordinal == HeadingLocation.fileOrdinal {
559                return try String.fetchOne(db, sql: """
560                    SELECT files_fts.body FROM files_fts JOIN files f ON f.id = files_fts.rowid WHERE f.path = ?
561                    """, arguments: [location.path])
562            }
563            return try String.fetchOne(db, sql: """
564                SELECT headings_fts.body FROM headings_fts JOIN headings h ON h.id = headings_fts.rowid
565                JOIN files f ON f.id = h.file_id WHERE f.path = ? AND h.ordinal = ?
566                """, arguments: [location.path, location.ordinal])
567        }
568    }
569
570    /// IDs used by more than one heading.
571    public func duplicateIDs(overlay: [String: FileRecord] = [:]) throws -> [String: [HeadingLocation]] {
572        let indexed = try database.read { db in
573            try Row.fetchAll(
574                db,
575                sql: """
576                    SELECT h.org_id, f.path, f.hash, h.ordinal, h.title, h.start_offset
577                    FROM headings h JOIN files f ON f.id = h.file_id
578                    WHERE h.org_id IN (SELECT org_id FROM headings WHERE org_id IS NOT NULL GROUP BY org_id HAVING count(*) > 1)
579                       OR (h.org_id IS NOT NULL AND ? > 0)
580                    ORDER BY f.path, h.ordinal
581                    """,
582                arguments: [overlay.count]
583            ).map { (id: $0["org_id"] as String, location: location($0)) }
584        }
585        var byID: [String: [HeadingLocation]] = [:]
586        for row in indexed where overlay[row.location.path] == nil {
587            byID[row.id, default: []].append(row.location)
588        }
589        for record in overlay.values.sorted(by: { $0.path < $1.path }) {
590            for heading in record.headings {
591                if let id = heading.orgID { byID[id, default: []].append(location(record, heading)) }
592            }
593        }
594        return byID.filter { $0.value.count > 1 }
595    }
596
597    /// Lower-cased runs of letters and digits, as the unicode61 tokenizer splits them.
598    static func words(_ text: String) -> [String] {
599        text.lowercased().split { !$0.isLetter && !$0.isNumber }.map(String.init)
600    }
601
602    private func location(_ row: Row) -> HeadingLocation {
603        HeadingLocation(path: row["path"], ordinal: row["ordinal"], title: row["title"], start: row["start_offset"], contentHash: row["hash"])
604    }
605
606    private func location(_ record: FileRecord, _ heading: HeadingRecord) -> HeadingLocation {
607        HeadingLocation(path: record.path, ordinal: heading.ordinal, title: heading.title, start: heading.start, contentHash: record.hash)
608    }
609}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form