Sources/OrgIndex/IndexStore.swift

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