Sources/OrgCore/Compute/BabelSQLite.swift

259 lines · 13614 bytes

  1import Foundation
  2
  3// ob-sqlite (Org 9.8.7): the body goes to `sqlite3` on standard input, with the options the
  4// header arguments name, and the output becomes the result through `org-table-convert-region`.
  5
  6extension Babel {
  7    /// An sqlite block's `sqlite3` command line.
  8    public struct SQLiteCommand: Sendable, Equatable {
  9        /// The command for the shell, as ob-sqlite writes it.
 10        public let command: String
 11        /// The command's words after `sqlite3` when they hold nothing the shell would change;
 12        /// nil otherwise.
 13        public let arguments: [String]?
 14    }
 15
 16    /// Stands, in a job's input, for a data file the runner writes (`BabelJob.dataFiles`).
 17    public static func dataFileToken(_ n: Int) -> String { "__ORGSTAR_DATA_FILE_\(n)__" }
 18
 19    static func sqliteJob(body: String, vars: [(String, VarValue)], params: Params, finishBase: (BabelJob.Finish.Kind) -> BabelJob.Finish,
 20                          directory: String?, block: Range<Int>, blockText: String, alwaysAsk: Bool) throws -> BabelJob {
 21        let separator = params.single[":separator"], nullvalue = params.single[":nullvalue"], db = params.single[":db"]
 22        let headers = params.single[":colnames"] == "yes"
 23        let others = [":header", ":echo", ":bail", ":column", ":csv", ":html", ":line", ":list"].filter { params.single[$0] != nil }
 24        let formatted = others.contains { [":csv", ":column", ":line", ":list", ":html"].contains($0) } || separator != nil
 25        let fields: [(String, String)] = [
 26            ("cmd", "sqlite3"),
 27            ("header", headers ? "-header" : "-noheader"),
 28            ("separator", separator.map { "-separator \($0)" } ?? ""),
 29            ("nullvalue", nullvalue.map { "-nullvalue \($0)" } ?? ""),
 30            ("others", others.map { "-" + $0.dropFirst() }.joined(separator: " ")),
 31            ("csv", formatted ? "" : "-csv"),
 32            ("readonly", params.single[":readonly"] == "yes" ? "-readonly" : ""),
 33            ("db", db ?? ""),
 34        ]
 35        // `org-fill-template`.
 36        var command = "%cmd %header %separator %nullvalue %others %csv %readonly %db "
 37        for (key, value) in fields { command = command.replacingOccurrences(of: "%" + key, with: value) }
 38        let words = command.split(separator: " ").dropFirst().map(String.init)
 39        let plain = words.allSatisfy { $0.range(of: "^[A-Za-z0-9._/:@%+=,-]+$", options: .regularExpression) != nil }
 40            && !(db?.hasPrefix("-") ?? false) && words.count == command.split(separator: " ").count - 1
 41
 42        // `org-babel-sql-expand-vars`: `$name` replaced, a table by a CSV file of it.
 43        var expanded = body
 44        var files: [String: String] = [:]
 45        for (name, value) in vars {
 46            guard name.range(of: "^[A-Za-z0-9_-]+$", options: .regularExpression) != nil else {
 47                throw Failure.message(":var \(name) isn't supported for sqlite blocks; nothing was run.")
 48            }
 49            let replacement: String
 50            switch value {
 51            case .scalar(let s): replacement = s
 52            case .number(let n): replacement = n
 53            case .table(let rows):
 54                let token = dataFileToken(files.count)
 55                files[token] = try csvFile(rows, name: name)
 56                replacement = token
 57            case .list:
 58                throw Failure.message(":var \(name) is a list, which sqlite blocks can't take; nothing was run.")
 59            }
 60            expanded = replacingCaseInsensitively("$" + name, in: expanded, with: replacement)
 61        }
 62        let input = [params.single[":prologue"] ?? "", expanded, params.single[":epilogue"] ?? ""].joined(separator: "\n") + "\n"
 63        var finish = finishBase(.sqlite(csv: !formatted, headers: headers))
 64        // ob-sqlite doesn't put back the names `:var` tables gave up.
 65        (finish.colnames, finish.rownames) = (nil, nil)
 66        var job = BabelJob(language: "sqlite", runner: .process(executable: command, arguments: []), input: input, directory: directory,
 67                           block: block, blockText: blockText, alwaysAsk: alwaysAsk, finish: finish)
 68        job.sqlite = SQLiteCommand(command: command, arguments: plain ? words : nil)
 69        job.dataFiles = files
 70        return job
 71    }
 72
 73    /// `replace-regexp-in-string` of a literal with `case-fold-search`.
 74    static func replacingCaseInsensitively(_ target: String, in text: String, with replacement: String) -> String {
 75        let ns = text as NSString
 76        var result = ""
 77        var location = 0
 78        while location <= ns.length {
 79            let found = ns.range(of: target, options: [.caseInsensitive, .literal], range: NSRange(location: location, length: ns.length - location))
 80            guard found.location != NSNotFound else { break }
 81            result += ns.substring(with: NSRange(location: location, length: found.location - location)) + replacement
 82            location = NSMaxRange(found)
 83        }
 84        return result + ns.substring(from: min(location, ns.length))
 85    }
 86
 87    /// `orgtbl-to-csv` of a table: rules dropped, a field with `"` or `,` quoted, no final
 88    /// newline. Cells the Org exporter could change are refused.
 89    static func csvFile(_ rows: [[Cell]?], name: String) throws -> String {
 90        try rows.compactMap { $0 }.map { row in
 91            try row.map { cell in
 92                let text = cellText(cell)
 93                guard text.range(of: "[\\[\\]{}<>@\\\\\\n\\t]|src_|call_", options: .regularExpression) == nil,
 94                      text == text.trimmingCharacters(in: .whitespaces) else {
 95                    throw Failure.message(":var \(name) has a cell the Org exporter may change; nothing was run.")
 96                }
 97                return text.contains("\"") || text.contains(",") ? "\"" + text.replacingOccurrences(of: "\"", with: "\"\"") + "\"" : text
 98            }.joined(separator: ",")
 99        }.joined(separator: "\n")
100    }
101
102    // MARK: - Results
103
104    /// ob-sqlite's result from `sqlite3`'s output: the output
105    /// as a string or through `org-table-convert-region` as a table, a single cell alone.
106    static func sqliteValue(_ output: String, csv: Bool, headers: Bool, scalar: Bool) -> Value {
107        // csv mode ends lines with CRLF, and Emacs keeps the CR.
108        let text = output
109        if scalar { return .string(text) }
110        if text.isEmpty { return .string("") }
111        guard var rows: [[String]?] = convertRegion(text, csv: csv) else { return .none }
112        if headers, let first = rows.first {
113            rows = [first, nil] + rows.dropFirst()
114        }
115        // `org-babel-sqlite-table-or-scalar`.
116        if rows.count == 1, let only = rows[0], only.count == 1 { return .string(babelRead(only[0])) }
117        return .table(rows.map { $0?.map(babelRead) })
118    }
119
120    /// The error Emacs stops with while making a table of the output, if any.
121    static func sqliteFailure(_ finish: BabelJob.Finish, _ output: BabelOutput) -> String? {
122        guard case .sqlite(let csv, _) = finish.kind, !resultCondScalar(finish.params), !finish.params.contains("discard"),
123              !output.stdout.isEmpty, convertRegion(output.stdout, csv: csv) == nil else { return nil }
124        return "Invalid search bound (wrong side of point)"
125    }
126
127    /// `org-babel-read` with Lisp evaluation inhibited: a number as Emacs prints it, a single
128    /// quoted string read, else the cell.
129    static func babelRead(_ cell: String) -> String {
130        guard cell.contains(where: { !$0.isWhitespace }) else { return cell }
131        if !cell.contains("\r"), let n = number(cell), cell.range(of: "^[0-9e.+ -]+$", options: .regularExpression) != nil { return n }
132        let trimmed = cell.trimmingCharacters(in: .whitespacesAndNewlines)
133        if trimmed.hasPrefix("\""), trimmed.count >= 2, trimmed.hasSuffix("\""),
134           let (sexp, length) = try? LispReader.readFirst(trimmed), length == trimmed.count, let s = sexp.string {
135            return s
136        }
137        return cell
138    }
139
140    /// `org-table-convert-region` on the whole output, then `org-table-to-lisp` of the aligned
141    /// table: rows of cells, padded to the widest row. Nil where Emacs fails: a last empty line
142    /// in a region read without a comma separator puts point past the search bound.
143    static func convertRegion(_ text: String, csv: Bool) -> [[String]?]? {
144        var b = Array(text.unicodeScalars)
145        let nl: Unicode.Scalar = "\n", tab: Unicode.Scalar = "\t", space: Unicode.Scalar = " ", comma: Unicode.Scalar = ",", quote: Unicode.Scalar = "\""
146        var end = b.last == nl ? b.count - 1 : b.count
147        var point = 0
148        func bol(_ i: Int) -> Bool { i == 0 || b[i - 1] == nl }
149        func replace(_ range: Range<Int>, _ s: [Unicode.Scalar]) {
150            b.replaceSubrange(range, with: s)
151            if end >= range.upperBound { end += s.count - range.count } else if end > range.lowerBound { end = range.lowerBound }
152        }
153        enum Separator { case comma, tab, spaces }
154        var separator = Separator.comma
155        if !csv {
156            let lines = String(String.UnicodeScalarView(b[0..<end])).components(separatedBy: "\n").filter { !$0.isEmpty }
157            if !lines.contains(where: { !$0.contains("\t") }) {
158                separator = .tab
159            } else if !lines.contains(where: { !$0.contains(",") }) {
160                separator = .comma
161            } else {
162                separator = .spaces
163            }
164        }
165        if separator == .comma {
166            while point < end {
167                if bol(point) {
168                    replace(point..<point, ["|", " "])
169                    point += 2
170                    continue
171                }
172                var j = point
173                while j < b.count, b[j] == space || b[j] == tab { j += 1 }
174                if j == b.count || b[j] == nl {
175                    // `[ \t]*$`, then the next line.
176                    replace(point..<j, [" ", "|"])
177                    point += 2
178                    if let next = b[point...].firstIndex(of: nl) { point = next + 1 } else { point = b.count }
179                    continue
180                }
181                if b[j] == quote, let close = b[(j + 1)...].firstIndex(of: quote) {
182                    let content = b[(j + 1)..<close].map { $0 == nl ? space : $0 }
183                    replace(point..<(close + 1), Array(content))
184                    point += content.count
185                    if point < b.count, b[point] == quote {
186                        replace(point..<point, [quote])
187                        point += 1
188                    }
189                    continue
190                }
191                if point < b.count, b[point] != comma, b[point] != nl {
192                    while point < b.count, b[point] != comma, b[point] != nl { point += 1 }
193                    continue
194                }
195                if j < b.count, b[j] == comma {
196                    replace(point..<(j + 1), [" ", "|", " "])
197                    point += 3
198                    continue
199                }
200                if let next = b[point...].firstIndex(of: nl) { point = next + 1 } else { point = b.count }
201            }
202        } else {
203            // `re-search-forward` of "^\\|\t", or "^ *\\| *\t *\\| \\{1,\\}", each match
204            // replaced by "| ".
205            while point <= end {
206                var match: Range<Int>?
207                var i = point
208                while i <= end, match == nil {
209                    if bol(i) {
210                        var k = i
211                        if separator == .spaces { while k < end, b[k] == space { k += 1 } }
212                        match = i..<k
213                    } else if i < end {
214                        if separator == .tab {
215                            if b[i] == tab { match = i..<(i + 1) }
216                        } else {
217                            var k = i
218                            while k < end, b[k] == space { k += 1 }
219                            if k < end, b[k] == tab {
220                                var m = k + 1
221                                while m < end, b[m] == space { m += 1 }
222                                match = i..<m
223                            } else if k > i {
224                                match = i..<k
225                            }
226                        }
227                    }
228                    i += 1
229                }
230                guard let found = match else { break }
231                if found.lowerBound == end { return nil }
232                replace(found, ["|", " "])
233                point = found.lowerBound + 2
234            }
235        }
236        // The table: the lines from the start that begin with `|`.
237        var rows: [[String]] = []
238        for line in String(String.UnicodeScalarView(b)).components(separatedBy: "\n") {
239            var s = Substring(line)
240            s = s.drop { $0 == " " || $0 == "\t" }
241            guard s.first == "|" else { break }
242            s = s.dropFirst()
243            var cells: [String] = []
244            while true {
245                s = s.drop { $0 == " " || $0 == "\t" }
246                if s.isEmpty { break }
247                let field = s.prefix { $0 != "|" }
248                var cell = Substring(field)
249                while let last = cell.last, last == " " || last == "\t" { cell = cell.dropLast() }
250                cells.append(String(cell))
251                s = s.dropFirst(field.count)
252                if !s.isEmpty { s = s.dropFirst() }
253            }
254            rows.append(cells)
255        }
256        let width = rows.map(\.count).max() ?? 0
257        return rows.map { $0 + Array(repeating: "", count: width - $0.count) }
258    }
259}