Sources/OrgApp/SQLiteBlocks.swift
547 lines · 27979 bytes
1#if canImport(SQLite3)
2import Foundation
3import OrgCore
4import SQLite3
5
6/// sqlite blocks with the SQLite library, as `sqlite3` (macOS's, 3.54.0) runs them for ob-sqlite,
7/// for builds that can't start it. The command-line options ob-sqlite writes and the dot-commands
8/// `.headers`, `.mode`, `.separator`, `.nullvalue` and `.import` into an existing table are
9/// emulated in the list, csv, column, html and line modes. Anything else, and values whose text
10/// `sqlite3` would escape or lay out by display width, is refused rather than shown differently.
11public enum SQLiteBlocks {
12 /// Runs `job` when it is an sqlite block, in `directory` or its `:dir`; nil for other jobs.
13 public static func run(_ job: BabelJob, directory: URL) throws -> BabelOutput? {
14 guard job.language == "sqlite", let command = job.sqlite else { return nil }
15 let folder = job.directory.map { URL(fileURLWithPath: $0, relativeTo: directory).standardizedFileURL } ?? directory
16 guard FileManager.default.fileExists(atPath: folder.path) else { throw Babel.Failure.message("No folder \(folder.path) for :dir.") }
17 do {
18 guard let arguments = command.arguments else { throw Refusal(.shell) }
19 var shell = try Shell(arguments: arguments)
20 // Echoed statements as a table make Emacs's table conversion fail.
21 if shell.echo, !Babel.resultCondScalar(job.finish.params) { throw Refusal(.echo) }
22 var input = job.input
23 var temporary: URL?
24 if !job.dataFiles.isEmpty {
25 let files = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-sqlite-\(UUID().uuidString)")
26 try FileManager.default.createDirectory(at: files, withIntermediateDirectories: true)
27 temporary = files
28 for (token, contents) in job.dataFiles {
29 let file = files.appendingPathComponent("sql-data-\(token.filter(\.isNumber))")
30 try contents.write(to: file, atomically: true, encoding: .utf8)
31 input = input.replacingOccurrences(of: token, with: file.path)
32 }
33 }
34 defer { if let temporary { try? FileManager.default.removeItem(at: temporary) } }
35 return try shell.run(input, folder: folder)
36 } catch let refusal as Refusal {
37 throw Babel.Failure.message(refusal.message)
38 }
39 }
40
41 /// Why a block can't run as `sqlite3` would run it.
42 struct Refusal: Error, Equatable {
43 enum Reason: Equatable {
44 case shell, dotCommand(String), blob, control, width, explain, newTable, importRows, encoding, echo
45 }
46 let reason: Reason
47 /// Statements before the refused one ran.
48 var partly = false
49 init(_ reason: Reason, partly: Bool = false) { (self.reason, self.partly) = (reason, partly) }
50
51 var message: String {
52 let what: String
53 switch reason {
54 case .shell: what = String(localized: "header arguments with shell syntax", comment: "Why an sqlite block can't run here")
55 case .dotCommand(let name): what = String(localized: "the dot-command \(name)", comment: "Why an sqlite block can't run here")
56 case .blob: what = String(localized: "BLOB values", comment: "Why an sqlite block can't run here")
57 case .control: what = String(localized: "control characters in values", comment: "Why an sqlite block can't run here")
58 case .width: what = String(localized: "text other than plain ASCII in column or line mode", comment: "Why an sqlite block can't run here")
59 case .explain: what = String(localized: "EXPLAIN statements", comment: "Why an sqlite block can't run here")
60 case .newTable: what = String(localized: ".import into a table that doesn't exist yet", comment: "Why an sqlite block can't run here")
61 case .importRows: what = String(localized: ".import of rows that don't fit the table", comment: "Why an sqlite block can't run here")
62 case .encoding: what = String(localized: "text that isn't UTF-8", comment: "Why an sqlite block can't run here")
63 case .echo: what = String(localized: ":echo with a result that isn't text", comment: "Why an sqlite block can't run here")
64 }
65 return partly
66 ? String(localized: "This sqlite block can't run here: \(what). The statements before it ran.", comment: "An sqlite block refused partway")
67 : String(localized: "This sqlite block can't run here: \(what).", comment: "An sqlite block refused before it ran")
68 }
69 }
70
71 /// `sqlite3` reading the input as a script.
72 struct Shell {
73 enum Mode: String { case list, csv, column, html, line }
74 var mode = Mode.list
75 var header = false
76 /// Set by `.headers`, which outlasts a change of mode; the command-line options don't.
77 var headerFlag: Bool?
78 var separator = "|"
79 var rowSeparator = "\n"
80 var nullValue = ""
81 var echo = false
82 var bail = false
83 var readonly = false
84 var database: String?
85
86 init(arguments: [String]) throws {
87 var i = 0
88 while i < arguments.count {
89 let argument = arguments[i]
90 switch argument {
91 case "-header": header = true
92 case "-noheader": header = false
93 case "-separator", "-nullvalue":
94 guard i + 1 < arguments.count else { throw Refusal(.shell) }
95 i += 1
96 if argument == "-separator" { separator = arguments[i] } else { nullValue = arguments[i] }
97 case "-echo": echo = true
98 case "-bail": bail = true
99 case "-readonly": readonly = true
100 case "-csv", "-list", "-column", "-html", "-line": change(to: Mode(rawValue: String(argument.dropFirst()))!)
101 default:
102 guard !argument.hasPrefix("-"), database == nil else { throw Refusal(.shell) }
103 database = argument
104 }
105 i += 1
106 }
107 }
108
109 mutating func change(to new: Mode) {
110 mode = new
111 separator = ["csv": ",", "list": "|", "line": ": "][new.rawValue] ?? ""
112 rowSeparator = new == .csv ? "\r\n" : "\n"
113 nullValue = ""
114 header = headerFlag ?? (new == .column || new == .html)
115 }
116
117 /// What `process_input` reads: dot-commands, lines it only echoes, and SQL.
118 enum Item {
119 case echo(String)
120 case dot(String, [String])
121 case sql(String, line: Int)
122 }
123
124 static func isSpace(_ c: UInt8) -> Bool { c == 32 || (9...13).contains(c) }
125
126 /// `line_is_all_whitespace`: spaces and SQL comments.
127 static func isAllWhitespace(_ line: String) -> Bool {
128 let z = Array(line.utf8)
129 var i = 0
130 while i < z.count {
131 if isSpace(z[i]) { i += 1; continue }
132 if z[i] == UInt8(ascii: "/"), i + 1 < z.count, z[i + 1] == UInt8(ascii: "*") {
133 i += 2
134 while i < z.count, !(z[i] == UInt8(ascii: "*") && i + 1 < z.count && z[i + 1] == UInt8(ascii: "/")) { i += 1 }
135 if i >= z.count { return false }
136 i += 2
137 continue
138 }
139 if z[i] == UInt8(ascii: "-"), i + 1 < z.count, z[i + 1] == UInt8(ascii: "-") {
140 while i < z.count, z[i] != UInt8(ascii: "\n") { i += 1 }
141 if i >= z.count { return true }
142 continue
143 }
144 return false
145 }
146 return true
147 }
148
149 static func items(_ input: String) throws -> [Item] {
150 var lines = input.components(separatedBy: "\n")
151 if lines.last == "" { lines.removeLast() }
152 var items: [Item] = []
153 var sql = ""
154 var start = 0
155 for (n, line) in lines.enumerated() {
156 if sql.isEmpty, isAllWhitespace(line) {
157 items.append(.echo(line))
158 continue
159 }
160 if sql.isEmpty, line.hasPrefix(".") || line.hasPrefix("#") {
161 items.append(line.hasPrefix(".") ? .dot(line, try dotArguments(line)) : .echo(line))
162 continue
163 }
164 if sql.isEmpty {
165 sql = String(decoding: line.utf8.drop(while: isSpace), as: UTF8.self)
166 start = n + 1
167 } else {
168 sql += "\n" + line
169 }
170 if line.contains(";"), sqlite3_complete(sql) != 0 {
171 items.append(.sql(sql, line: start))
172 sql = ""
173 } else if !sql.isEmpty, isAllWhitespace(sql) {
174 items.append(.echo(sql))
175 sql = ""
176 }
177 }
178 if !sql.isEmpty { items.append(.sql(sql, line: start)) }
179 return items
180 }
181
182 /// A dot-command's words, refused unless it is one of those emulated, written plainly.
183 static func dotArguments(_ line: String) throws -> [String] {
184 let words = line.dropFirst().split(whereSeparator: { $0 == " " || $0 == "\t" }).map(String.init)
185 let name = words.first ?? ""
186 let refusal = Refusal(.dotCommand("." + name))
187 guard !line.contains(where: { "\"'\\\r;".contains($0) }) else { throw refusal }
188 switch name {
189 case "header", "headers":
190 guard words.count == 2, ["on", "off", "yes", "no", "1", "0", "true", "false"].contains(words[1]) else { throw refusal }
191 case "mode":
192 guard words.count == 2, Mode(rawValue: words[1]) != nil else { throw refusal }
193 case "separator", "nullvalue":
194 guard words.count == 2 else { throw refusal }
195 case "import":
196 let rest = words.dropFirst().filter { $0 != "--csv" && $0 != "-csv" }
197 guard rest.count == 2, !rest[rest.startIndex].hasPrefix("-"), !rest[rest.startIndex].hasPrefix("|"),
198 !rest[rest.startIndex].hasPrefix("<<"), !rest.last!.hasPrefix("-"), !rest.last!.contains(".") else { throw refusal }
199 default:
200 throw refusal
201 }
202 return words
203 }
204
205 mutating func run(_ input: String, folder: URL) throws -> BabelOutput {
206 let items = try Self.items(input)
207 var out = Data()
208 var err = ""
209 func write(_ s: String) { out.append(contentsOf: Array(s.utf8)) }
210 var db: OpaquePointer?
211 let flags = readonly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
212 let path = database.map { URL(fileURLWithPath: $0, relativeTo: folder).standardizedFileURL.path } ?? ":memory:"
213 defer { sqlite3_close(db) }
214 if sqlite3_open_v2(path, &db, flags, nil) != SQLITE_OK {
215 let reason = db.map { String(cString: sqlite3_errmsg($0)) } ?? "out of memory"
216 if Sandbox.isActive || !Self.onMac {
217 throw Babel.Failure.message(String(localized: "Can't open the database \(database ?? ""): \(reason). orgstar can open files only in the folders it has access to.", comment: "An sqlite block's database that can't be opened"))
218 }
219 return BabelOutput(stdout: "", stderr: "Error: unable to open database \"\(database ?? "")\": \(reason)\n", status: 1)
220 }
221 var errors = 0
222 var ran = false
223 for item in items {
224 if errors > 0, bail { break }
225 switch item {
226 case .echo(let line):
227 if echo { write(line + "\n") }
228 case .dot(let line, let words):
229 if echo { write(line + "\n") }
230 do {
231 if try dot(words, db: db!, error: &err) { errors += 1 }
232 } catch var refusal as Refusal {
233 refusal.partly = ran
234 throw refusal
235 }
236 ran = true
237 case .sql(let sql, let line):
238 if echo { write(sql + "\n") }
239 do {
240 if try execute(sql, line: line, db: db!, write: write, error: &err) { errors += 1 }
241 } catch var refusal as Refusal {
242 refusal.partly = refusal.partly || ran
243 throw refusal
244 }
245 ran = true
246 }
247 }
248 return BabelOutput(stdout: String(decoding: out, as: UTF8.self), stderr: err, status: errors > 0 ? 1 : 0)
249 }
250
251 static var onMac: Bool {
252 #if os(macOS)
253 true
254 #else
255 false
256 #endif
257 }
258
259 /// A dot-command; true when it failed.
260 mutating func dot(_ words: [String], db: OpaquePointer, error: inout String) throws -> Bool {
261 switch words[0] {
262 case "header", "headers":
263 headerFlag = ["on", "yes", "1", "true"].contains(words[1])
264 header = headerFlag!
265 case "mode":
266 change(to: Mode(rawValue: words[1])!)
267 case "separator":
268 separator = words[1]
269 case "nullvalue":
270 nullValue = words[1]
271 default:
272 return try importFile(words, db: db, error: &error)
273 }
274 return false
275 }
276
277 /// `.import FILE TABLE` into a table that exists, as CSV.
278 func importFile(_ words: [String], db: OpaquePointer, error: inout String) throws -> Bool {
279 let rest = words.dropFirst().filter { $0 != "--csv" && $0 != "-csv" }
280 let csvOption = words.count != rest.count + 1
281 let (file, table) = (rest[rest.startIndex], rest[rest.startIndex + 1])
282 var columnSeparator = csvOption ? UInt8(ascii: ",") : (separator.utf8.first ?? UInt8(ascii: ","))
283 if columnSeparator >= 0x80 { columnSeparator = UInt8(ascii: ",") }
284 var statement: OpaquePointer?
285 let quoted = "\"" + table.replacingOccurrences(of: "\"", with: "\"\"") + "\""
286 guard sqlite3_prepare_v2(db, "SELECT count(*) FROM pragma_table_info('\(table.replacingOccurrences(of: "'", with: "''"))')", -1, &statement, nil) == SQLITE_OK else {
287 throw Refusal(.newTable)
288 }
289 let columns = sqlite3_step(statement) == SQLITE_ROW ? Int(sqlite3_column_int(statement, 0)) : 0
290 sqlite3_finalize(statement)
291 guard columns > 0 else { throw Refusal(.newTable) }
292 guard let data = FileManager.default.contents(atPath: file) else {
293 error += "Error: cannot open \"\(file)\"\n"
294 return true
295 }
296 let rows = try Self.csvRows(Array(data), separator: columnSeparator)
297 guard rows.allSatisfy({ $0.count == columns }) else { throw Refusal(.importRows) }
298 let insert = "INSERT INTO \(quoted) VALUES(" + Array(repeating: "?", count: columns).joined(separator: ",") + ")"
299 guard sqlite3_prepare_v2(db, insert, -1, &statement, nil) == SQLITE_OK else { throw Refusal(.newTable) }
300 defer { sqlite3_finalize(statement) }
301 let commit = sqlite3_get_autocommit(db) != 0
302 if commit { sqlite3_exec(db, "BEGIN", nil, nil, nil) }
303 var failed = false
304 let transient = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
305 for (n, row) in rows.enumerated() {
306 for (i, field) in row.enumerated() { sqlite3_bind_text(statement, Int32(i + 1), field, -1, transient) }
307 sqlite3_step(statement)
308 if sqlite3_reset(statement) != SQLITE_OK {
309 error += "\(file):\(n + 1): INSERT failed: \(String(cString: sqlite3_errmsg(db)))\n"
310 failed = true
311 if bail { break }
312 }
313 }
314 if commit { sqlite3_exec(db, "COMMIT", nil, nil, nil) }
315 return failed
316 }
317
318 /// `csv_read_one_field` over a file of well-formed CSV: rows of fields.
319 static func csvRows(_ bytes: [UInt8], separator: UInt8) throws -> [[String]] {
320 let quote = UInt8(ascii: "\""), newline = UInt8(ascii: "\n"), cr = UInt8(ascii: "\r")
321 var rows: [[String]] = []
322 var row: [String] = []
323 var i = 0
324 // Any quote must open a field and close it; else the reader's warnings and
325 // recovery would apply.
326 while i < bytes.count {
327 var field: [UInt8] = []
328 if bytes[i] == quote {
329 i += 1
330 while true {
331 guard i < bytes.count else { throw Refusal(.importRows) }
332 if bytes[i] == quote {
333 if i + 1 < bytes.count, bytes[i + 1] == quote {
334 field.append(quote)
335 i += 2
336 continue
337 }
338 i += 1
339 break
340 }
341 field.append(bytes[i])
342 i += 1
343 }
344 guard i == bytes.count || bytes[i] == separator || bytes[i] == newline else { throw Refusal(.importRows) }
345 } else {
346 while i < bytes.count, bytes[i] != separator, bytes[i] != newline {
347 guard bytes[i] != quote else { throw Refusal(.importRows) }
348 field.append(bytes[i])
349 i += 1
350 }
351 if i < bytes.count, bytes[i] == newline, field.last == cr { field.removeLast() }
352 }
353 guard let text = String(bytes: field, encoding: .utf8) else { throw Refusal(.encoding) }
354 row.append(text)
355 if i < bytes.count, bytes[i] == separator {
356 i += 1
357 if i == bytes.count { row.append("") }
358 } else {
359 rows.append(row)
360 row = []
361 if i < bytes.count { i += 1 }
362 }
363 }
364 if !row.isEmpty { rows.append(row) }
365 // The first-row byte-order mark the reader skips.
366 if let first = rows.first?.first, first.hasPrefix("\u{FEFF}") { throw Refusal(.encoding) }
367 return rows
368 }
369
370 /// `shell_exec` of one group of statements; true when one failed.
371 func execute(_ sql: String, line: Int, db: OpaquePointer, write: (String) -> Void, error: inout String) throws -> Bool {
372 var bytes = Array(sql.utf8CString)
373 return try bytes.withUnsafeMutableBufferPointer { buffer -> Bool in
374 var next: UnsafePointer<CChar>? = UnsafePointer(buffer.baseAddress!)
375 while let start = next, start.pointee != 0 {
376 var statement: OpaquePointer?
377 var tail: UnsafePointer<CChar>?
378 if sqlite3_prepare_v2(db, start, -1, &statement, &tail) != SQLITE_OK {
379 error += "Parse error near line \(line): \(String(cString: sqlite3_errmsg(db)))\n"
380 return true
381 }
382 next = tail
383 while let rest = next, rest.pointee != 0, Self.isSpace(UInt8(bitPattern: rest.pointee)) { next = rest + 1 }
384 guard let statement else { continue }
385 defer { sqlite3_finalize(statement) }
386 if sqlite3_stmt_isexplain(statement) != 0 { throw Refusal(.explain) }
387 let failed = try output(statement, db: db, write: write)
388 if failed {
389 error += "Error near line \(line): \(String(cString: sqlite3_errmsg(db)))\n"
390 return true
391 }
392 }
393 return false
394 }
395 }
396
397 /// A value as text, with its type; nil text for NULL.
398 struct Cell {
399 let text: String?
400 let numeric: Bool
401 }
402
403 func cell(_ statement: OpaquePointer, _ i: Int32) throws -> Cell {
404 switch sqlite3_column_type(statement, i) {
405 case SQLITE_NULL: return Cell(text: nil, numeric: false)
406 case SQLITE_BLOB: throw Refusal(.blob)
407 case let type:
408 guard let pointer = sqlite3_column_text(statement, i) else { return Cell(text: nil, numeric: false) }
409 let bytes = UnsafeBufferPointer(start: pointer, count: Int(sqlite3_column_bytes(statement, i)))
410 guard let text = String(bytes: bytes, encoding: .utf8) else { throw Refusal(.encoding) }
411 try Self.check(text)
412 return Cell(text: text, numeric: type == SQLITE_INTEGER || type == SQLITE_FLOAT)
413 }
414 }
415
416 /// Control characters other than tab and newline `sqlite3` escapes.
417 static func check(_ text: String) throws {
418 if text.unicodeScalars.contains(where: { ($0.value < 0x20 && $0 != "\t" && $0 != "\n") || $0.value == 0x7F }) {
419 throw Refusal(.control)
420 }
421 }
422
423 /// Writes the statement's rows in the mode; true when stepping failed.
424 func output(_ statement: OpaquePointer, db: OpaquePointer, write: (String) -> Void) throws -> Bool {
425 let count = sqlite3_column_count(statement)
426 let names = try (0..<count).map { i -> String in
427 let name = sqlite3_column_name(statement, i).map { String(cString: $0) } ?? ""
428 try Self.check(name)
429 return name
430 }
431 var rows: [[Cell]] = []
432 var failed = false
433 var buffered = ""
434 func emit(_ s: String) { if mode == .column { buffered += s } else { write(s) } }
435 while true {
436 let rc = sqlite3_step(statement)
437 if rc == SQLITE_DONE { break }
438 guard rc == SQLITE_ROW else {
439 failed = true
440 break
441 }
442 guard count > 0 else { continue }
443 let row = try (0..<count).map { try cell(statement, $0) }
444 switch mode {
445 case .column:
446 rows.append(row)
447 case .line:
448 let width = try names.map { name -> Int in
449 guard name.allSatisfy({ $0.isASCII }) else { throw Refusal(.width) }
450 return name.utf8.count
451 }.max() ?? 0
452 if !rows.isEmpty { emit("\n") }
453 rows.append([])
454 for (name, value) in zip(names, row) {
455 let pieces = (value.text ?? nullValue).components(separatedBy: "\n")
456 var lines = Array(pieces)
457 // A final newline ends the last line.
458 if lines.count > 1, lines.last == "" { lines.removeLast() }
459 emit(String(repeating: " ", count: width - name.utf8.count) + name + separator + lines[0] + "\n")
460 for more in lines.dropFirst() {
461 emit(String(repeating: " ", count: width + separator.utf8.count) + more + "\n")
462 }
463 }
464 case .html:
465 if rows.isEmpty, header {
466 emit("<TR>\n" + names.map { "<TH>" + Self.html($0) + "\n" }.joined() + "</TR>\n")
467 }
468 rows.append([])
469 emit("<TR>\n" + row.map { "<TD>" + ($0.text.map(Self.html) ?? "null") + "\n" }.joined() + "</TR>\n")
470 case .list, .csv:
471 if rows.isEmpty, header {
472 emit(names.map { mode == .csv ? csv($0) : $0 }.joined(separator: separator) + rowSeparator)
473 }
474 rows.append([])
475 emit(row.map { value in
476 guard let text = value.text else { return nullValue }
477 return mode == .csv && !value.numeric ? csv(text) : text
478 }.joined(separator: separator) + rowSeparator)
479 }
480 }
481 if mode == .column, !rows.isEmpty {
482 try column(names: names, rows: rows, emit: emit)
483 write(buffered)
484 }
485 return failed
486 }
487
488 /// CSV quoting: a field with a control character, space, quote, apostrophe, DEL or byte
489 /// above ASCII, or with the separator, is quoted.
490 func csv(_ text: String) -> String {
491 let special = text.isEmpty || text.utf8.contains { $0 < 0x20 || $0 == 0x20 || $0 == 0x22 || $0 == 0x27 || $0 >= 0x7F }
492 guard special || (!separator.isEmpty && text.contains(separator)) else { return text }
493 return "\"" + text.replacingOccurrences(of: "\"", with: "\"\"") + "\""
494 }
495
496 /// `sqlite3`'s HTML escaping, which writes `>` as `<`.
497 static func html(_ text: String) -> String {
498 var out = ""
499 for c in text.unicodeScalars {
500 switch c {
501 case "<", ">": out += "<"
502 case "&": out += "&"
503 case "\"": out += """
504 case "'": out += "'"
505 default: out.unicodeScalars.append(c)
506 }
507 }
508 return out
509 }
510
511 /// Column mode: each column as wide as its widest text, the titles centered over a rule,
512 /// numbers to the right, two spaces between columns, no spaces at the ends of lines.
513 func column(names: [String], rows: [[Cell]], emit: (String) -> Void) throws {
514 func plain(_ s: String) throws -> String {
515 guard s.allSatisfy({ $0.isASCII && $0 != "\t" && $0 != "\n" }) else { throw Refusal(.width) }
516 return s
517 }
518 let texts = try rows.map { try $0.map { try plain($0.text ?? nullValue) } }
519 let titles = try names.map(plain)
520 var widths = Array(repeating: 0, count: names.count)
521 for (i, title) in titles.enumerated() where header { widths[i] = max(widths[i], title.count) }
522 for row in texts { for (i, text) in row.enumerated() { widths[i] = max(widths[i], text.count) } }
523 func line(_ cells: [String], _ align: (Int) -> Character) -> String {
524 var s = ""
525 for (i, text) in cells.enumerated() {
526 let space = widths[i] - text.count
527 switch align(i) {
528 case "c": s += String(repeating: " ", count: space / 2) + text + String(repeating: " ", count: space - space / 2)
529 case "r": s += String(repeating: " ", count: space) + text
530 default: s += text + String(repeating: " ", count: space)
531 }
532 if i < cells.count - 1 { s += " " }
533 }
534 while s.last == " " { s.removeLast() }
535 return s + "\n"
536 }
537 if header {
538 emit(line(titles) { _ in "c" })
539 emit(line(widths.map { String(repeating: "-", count: $0) }) { _ in "l" })
540 }
541 for (row, cells) in zip(texts, rows) {
542 emit(line(row) { cells[$0].numeric ? "r" : "l" })
543 }
544 }
545 }
546}
547#endif