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