Sources/OrgCore/Compute/BabelSQLite.swift

0dbf01d3bc8b68b775dfc3a8385b84bd682b85dd
orgstar/Sources/OrgCore/Compute/BabelSQLite.swift

250 lines · 12934 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        var rows: [[String]?] = convertRegion(text, csv: csv)
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    /// `org-babel-read` with Lisp evaluation inhibited: a number as Emacs prints it, a single
121    /// quoted string read, else the cell.
122    static func babelRead(_ cell: String) -> String {
123        guard cell.contains(where: { !$0.isWhitespace }) else { return cell }
124        if !cell.contains("\r"), let n = number(cell), cell.range(of: "^[0-9e.+ -]+$", options: .regularExpression) != nil { return n }
125        let trimmed = cell.trimmingCharacters(in: .whitespacesAndNewlines)
126        if trimmed.hasPrefix("\""), trimmed.count >= 2, trimmed.hasSuffix("\""),
127           let (sexp, length) = try? LispReader.readFirst(trimmed), length == trimmed.count, let s = sexp.string {
128            return s
129        }
130        return cell
131    }
132
133    /// `org-table-convert-region` on the whole output, then `org-table-to-lisp` of the aligned
134    /// table: rows of cells, padded to the widest row.
135    static func convertRegion(_ text: String, csv: Bool) -> [[String]?] {
136        var b = Array(text.unicodeScalars)
137        let nl: Unicode.Scalar = "\n", tab: Unicode.Scalar = "\t", space: Unicode.Scalar = " ", comma: Unicode.Scalar = ",", quote: Unicode.Scalar = "\""
138        var end = b.last == nl ? b.count - 1 : b.count
139        var point = 0
140        func bol(_ i: Int) -> Bool { i == 0 || b[i - 1] == nl }
141        func replace(_ range: Range<Int>, _ s: [Unicode.Scalar]) {
142            b.replaceSubrange(range, with: s)
143            if end >= range.upperBound { end += s.count - range.count } else if end > range.lowerBound { end = range.lowerBound }
144        }
145        enum Separator { case comma, tab, spaces }
146        var separator = Separator.comma
147        if !csv {
148            let lines = String(String.UnicodeScalarView(b[0..<end])).components(separatedBy: "\n").filter { !$0.isEmpty }
149            if !lines.contains(where: { !$0.contains("\t") }) {
150                separator = .tab
151            } else if !lines.contains(where: { !$0.contains(",") }) {
152                separator = .comma
153            } else {
154                separator = .spaces
155            }
156        }
157        if separator == .comma {
158            while point < end {
159                if bol(point) {
160                    replace(point..<point, ["|", " "])
161                    point += 2
162                    continue
163                }
164                var j = point
165                while j < b.count, b[j] == space || b[j] == tab { j += 1 }
166                if j == b.count || b[j] == nl {
167                    // `[ \t]*$`, then the next line.
168                    replace(point..<j, [" ", "|"])
169                    point += 2
170                    if let next = b[point...].firstIndex(of: nl) { point = next + 1 } else { point = b.count }
171                    continue
172                }
173                if b[j] == quote, let close = b[(j + 1)...].firstIndex(of: quote) {
174                    let content = b[(j + 1)..<close].map { $0 == nl ? space : $0 }
175                    replace(point..<(close + 1), Array(content))
176                    point += content.count
177                    if point < b.count, b[point] == quote {
178                        replace(point..<point, [quote])
179                        point += 1
180                    }
181                    continue
182                }
183                if point < b.count, b[point] != comma, b[point] != nl {
184                    while point < b.count, b[point] != comma, b[point] != nl { point += 1 }
185                    continue
186                }
187                if j < b.count, b[j] == comma {
188                    replace(point..<(j + 1), [" ", "|", " "])
189                    point += 3
190                    continue
191                }
192                if let next = b[point...].firstIndex(of: nl) { point = next + 1 } else { point = b.count }
193            }
194        } else {
195            // `re-search-forward` of "^\\|\t", or "^ *\\| *\t *\\| \\{1,\\}", each match
196            // replaced by "| ".
197            while point <= end {
198                var match: Range<Int>?
199                var i = point
200                while i <= end, match == nil {
201                    if bol(i) {
202                        var k = i
203                        if separator == .spaces { while k < end, b[k] == space { k += 1 } }
204                        match = i..<k
205                    } else if i < end {
206                        if separator == .tab {
207                            if b[i] == tab { match = i..<(i + 1) }
208                        } else {
209                            var k = i
210                            while k < end, b[k] == space { k += 1 }
211                            if k < end, b[k] == tab {
212                                var m = k + 1
213                                while m < end, b[m] == space { m += 1 }
214                                match = i..<m
215                            } else if k > i {
216                                match = i..<k
217                            }
218                        }
219                    }
220                    i += 1
221                }
222                guard let found = match else { break }
223                replace(found, ["|", " "])
224                point = found.lowerBound + 2
225            }
226        }
227        // The table: the lines from the start that begin with `|`.
228        var rows: [[String]] = []
229        for line in String(String.UnicodeScalarView(b)).components(separatedBy: "\n") {
230            var s = Substring(line)
231            s = s.drop { $0 == " " || $0 == "\t" }
232            guard s.first == "|" else { break }
233            s = s.dropFirst()
234            var cells: [String] = []
235            while true {
236                s = s.drop { $0 == " " || $0 == "\t" }
237                if s.isEmpty { break }
238                let field = s.prefix { $0 != "|" }
239                var cell = Substring(field)
240                while let last = cell.last, last == " " || last == "\t" { cell = cell.dropLast() }
241                cells.append(String(cell))
242                s = s.dropFirst(field.count)
243                if !s.isEmpty { s = s.dropFirst() }
244            }
245            rows.append(cells)
246        }
247        let width = rows.map(\.count).max() ?? 0
248        return rows.map { $0 + Array(repeating: "", count: width - $0.count) }
249    }
250}
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