Tests/OrgAppTests/SQLiteBlocksTests.swift

0dbf01d3bc8b68b775dfc3a8385b84bd682b85dd
orgstar/Tests/OrgAppTests/SQLiteBlocksTests.swift

221 lines · 14908 bytes

  1import Foundation
  2import OrgCore
  3import OrgDocument
  4import Testing
  5@testable import OrgApp
  6
  7/// sqlite blocks with the SQLite library, compared with macOS's `sqlite3` and with Emacs
  8/// running it.
  9struct SQLiteBlocksTests {
 10    static let sqlite3 = "/usr/bin/sqlite3"
 11    static let oracle = ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil && FileManager.default.isExecutableFile(atPath: sqlite3)
 12
 13    static let values = """
 14        select 1 as a, 'x y' as b, null as c, 2.50 as d, 'it''s' as e, '' as f, -7 as g, 0.1 + 0.2 as h
 15        union all select 22, 'é,ü', 'q"t', 1e20, '<&>', ' lead', 3.0, 'tab\tin';
 16        """
 17
 18    /// Options as ob-sqlite writes them, and scripts.
 19    static let cli: [([String], String)] = [
 20        (["-noheader", "-csv"], values),
 21        (["-header", "-csv"], values),
 22        (["-noheader", "-list"], values),
 23        (["-noheader", "-header", "-list"], values),
 24        (["-noheader", "-column"], "select 1 as a, 'xx' as long_name, 2.5 as mid union all select -10, null, 'text';\nselect 'second' as s;"),
 25        (["-noheader", "-html"], values),
 26        (["-noheader", "-line"], values + "\nselect 'a\nb\n' as multi, 'c' as longer_name;"),
 27        (["-noheader", "-separator", "X"], values),
 28        (["-header", "-separator", ";"], values),
 29        (["-noheader", "-separator", "X", "-nullvalue", "N"], values),
 30        (["-noheader", "-nullvalue", "N", "-csv"], values),
 31        (["-noheader", "-csv"], "\nselect 1;\n\n  select 2; select 3;\n# comment\nselect 4\n;\nselect 5"),
 32        (["-noheader", "-echo", "-csv"], "\nselect 1;\n   select 2;   select 3;\n# c\n.mode list\n\nselect 4\n;\n"),
 33        (["-noheader", "-csv"], ".headers on\nselect 1 as a;\n.mode column\nselect 2 as b;\n.mode list\nselect 3 as c;\n.mode csv\nselect 4 as d;\n"),
 34        (["-noheader", "-csv"], ".mode column\n.headers off\nselect 1 as a, null as n;\n.headers on\n.mode html\n.nullvalue N\nselect 1 as a, null as n;"),
 35        (["-noheader", "-csv"], ".mode line\n.separator X\nselect 1 as a, null as n;\n.mode csv\n.separator :\nselect 'a:b' as a, 'c,d';"),
 36        (["-noheader", "-csv"], ".nullvalue N\nselect null;\n.mode list\nselect null;\n.nullvalue M\nselect null, 1;"),
 37        (["-noheader", "-csv"], "create table t(a integer, b text, c real);\ninsert into t values (1, 'one', 1.5), (2, null, -0.25), (30, 'thirty', 1e100);\nselect * from t order by a;\nselect count(*) as n from t;\nselect a from t where 0;"),
 38        (["-noheader", "-column"], "create table t(a, b);\ninsert into t values (1, 'xx'), (22, null), (3.5, 'y');\nselect * from t;\nselect a from t where 0;\n"),
 39        (["-noheader", "-csv"], "select 1;\nselect * from nope;\nselect 2;\nselect 3; select * from nope; select 4;\nselect 5;"),
 40        (["-noheader", "-bail", "-csv"], "select 1;\nselect * from nope;\nselect 2;"),
 41        (["-noheader", "-csv"], "select 1 union all select abs(-9223372036854775808);\nselect 2;"),
 42        (["-noheader", "-csv"], "create table t(a unique);\ninsert into t values (1);\ninsert into t values (1);\nselect count(*) from t;"),
 43        (["-noheader", "-csv"], "select 1 -- a comment\n;\n/* c */ select 2;\n-- only a comment\nselect 3 /* trailing"),
 44        (["-noheader", "-csv"], "select $x, ?, :y;"),
 45        (["-noheader", "-html"], "select 'a''b\"c<d>e&f' as \"<h>\";"),
 46        (["-noheader", "-csv"], "select 'line\ntwo', 'a,b', '\"', 'plain' as \"col name\", 'x' as \"q\"\"n\";"),
 47        (["-noheader", "-csv"], ".mode list\n.separator ,\nselect 'a,b', 'c';\n.mode list\nselect 'a,b';"),
 48        (["-noheader", "-header", "-csv"], "create table t(a, b);\n.headers on\nselect * from t;\ninsert into t values (1, 2);\nselect * from t;"),
 49    ]
 50
 51    static func cliOutput(_ arguments: [String], _ input: String, folder: URL) throws -> (stdout: String, status: Int32) {
 52        let process = Process()
 53        process.executableURL = URL(fileURLWithPath: sqlite3)
 54        process.arguments = arguments
 55        process.currentDirectoryURL = folder
 56        let stdin = Pipe(), stdout = Pipe()
 57        process.standardInput = stdin
 58        process.standardOutput = stdout
 59        process.standardError = FileHandle.nullDevice
 60        try process.run()
 61        stdin.fileHandleForWriting.write(Data(input.utf8))
 62        try stdin.fileHandleForWriting.close()
 63        let data = stdout.fileHandleForReading.readDataToEndOfFile()
 64        process.waitUntilExit()
 65        return (String(decoding: data, as: UTF8.self), process.terminationStatus)
 66    }
 67
 68    @Test(.enabled(if: oracle))
 69    func shellMatchesSqlite3() throws {
 70        for (arguments, script) in Self.cli {
 71            let input = script + "\n"
 72            let theirFolder = try Folder(), ourFolder = try Folder()
 73            let theirs = try Self.cliOutput(arguments, input, folder: theirFolder.url)
 74            var shell = try SQLiteBlocks.Shell(arguments: arguments)
 75            let ours = try shell.run(input, folder: ourFolder.url)
 76            #expect(ours.stdout == theirs.stdout, "\(arguments) \(script.debugDescription)\nours:\n\(ours.stdout.debugDescription)\nsqlite3:\n\(theirs.stdout.debugDescription)")
 77            #expect(ours.status == theirs.status, "\(arguments) \(script.debugDescription)")
 78        }
 79    }
 80
 81    static let table = "#+NAME: tbl\n| id | name  |\n|----+-------|\n|  1 | one   |\n|  2 | two   |\n|  3 | x, \"y\" |\n\n"
 82
 83    static let blocks: [String] = [
 84        "#+begin_src sqlite\nselect 1 as a, 'x y' as b, null as c, 2.50 as d;\nselect 'q\"t', 'é', '007', '\"quoted\"';\n#+end_src\n",
 85        "#+begin_src sqlite :colnames yes\nselect 1 as a, 2 as b;\nselect 3, 4;\n#+end_src\n",
 86        "#+begin_src sqlite\nselect 42;\n#+end_src\n",
 87        "#+begin_src sqlite\nselect 'line\ntwo', 'a,b';\n#+end_src\n",
 88        "#+begin_src sqlite :list\nselect 1, 'x y';\n#+end_src\n",
 89        "#+begin_src sqlite :column\nselect 1 as a, 'x y' as b;\n#+end_src\n",
 90        "#+begin_src sqlite :html\nselect 1 as a, 'x' as b;\n#+end_src\n",
 91        "#+begin_src sqlite :line\nselect 1 as a, 'x' as b;\n#+end_src\n",
 92        "#+begin_src sqlite :separator X\nselect 1 as a, 'x y' as b;\n#+end_src\n",
 93        "#+begin_src sqlite :separator , :nullvalue N\nselect 1, null, 'a b';\n#+end_src\n",
 94        "#+begin_src sqlite :header\nselect 1 as a, 2 as b;\n#+end_src\n",
 95        "#+begin_src sqlite :csv\nselect 1 as a, 'b c' as b;\n#+end_src\n",
 96        "#+begin_src sqlite :results output\nselect 1, 2;\n#+end_src\n",
 97        "#+begin_src sqlite :results output\nselect 'line\ntwo', 'a,b';\n#+end_src\n",
 98        "#+begin_src sqlite :results verbatim\nselect 1, 2;\nselect 3, 4;\n#+end_src\n",
 99        "#+begin_src sqlite :results raw\nselect '*bold*';\n#+end_src\n",
100        "#+begin_src sqlite :results table\nselect 7;\n#+end_src\n",
101        "#+begin_src sqlite :results list\nselect 1, 2;\nselect 3, 4;\n#+end_src\n",
102        "#+begin_src sqlite\ncreate table t(a);\n#+end_src\n",
103        "#+begin_src sqlite\nselect 1 where 0;\n#+end_src\n",
104        "#+begin_src sqlite :db test.db\ncreate table if not exists t(a, b);\ninsert into t values (1, 'one'), (2, 'two');\nselect * from t order by a;\n#+end_src\n",
105        "#+begin_src sqlite :db test2.db :readonly yes\nselect 1;\n#+end_src\n",
106        "#+begin_src sqlite :var x=3 name=\"two\"\nselect $x * 2, '$name', $X;\n#+end_src\n",
107        "#+begin_src sqlite :var x=2.50\nselect $x;\n#+end_src\n",
108        table + "#+begin_src sqlite :var t=tbl\ncreate table v(id integer, name text);\n.mode csv\n.import $t v\nselect name, id * 10 from v order by id;\n#+end_src\n",
109        table + "#+begin_src sqlite :var t=tbl :colnames yes\ncreate table v(id integer, name text);\n.import --csv $t v\n.headers on\nselect * from v;\n#+end_src\n",
110        "#+begin_src sqlite :prologue \"create table p(a);\" :epilogue \"select count(*) from p;\"\ninsert into p values (1), (2);\n#+end_src\n",
111        "#+begin_src sqlite\nselect 1;\nselect * from nope;\nselect 2;\n#+end_src\n",
112        "#+begin_src sqlite :bail\nselect 1;\nselect * from nope;\nselect 2;\n#+end_src\n",
113        "#+begin_src sqlite :echo\nselect 1;\nselect 2;\n#+end_src\n",
114        "#+begin_src sqlite\nselect ' a ', '\"b\"', 'c\"d', '-', '1e3', '+5', '.5', '1.';\n#+end_src\n",
115        "#+begin_src sqlite :list\nselect 'a b', 'c';\nselect 'single';\n#+end_src\n",
116        "#+begin_src sqlite :list\nselect 'a' || char(9) || 'b', 'c';\nselect 'd' || char(9) || 'e';\n#+end_src\n",
117        "#+begin_src sqlite :separator ,\nselect 1, 2;\nselect 3;\n#+end_src\n",
118        "#+begin_src sqlite\nselect '';\n#+end_src\n",
119        "#+begin_src sqlite\nselect 1, '';\nselect '', '';\n#+end_src\n",
120    ]
121
122    /// The results the app inserts, as Emacs inserts them running `sqlite3`.
123    @MainActor
124    @Test(.enabled(if: oracle))
125    func resultsMatchEmacs() async throws {
126        let ourFolder = try Folder(), theirFolder = try Folder()
127        var forms: [String] = []
128        var ours: [String] = []
129        for text in Self.blocks {
130            let caret = (text as NSString).range(of: "#+begin_src").location + 2
131            let file = try ourFolder.write("b.org", text)
132            let session = DocumentSession(recovery: FileRecoveryStore(directory: ourFolder.url.appendingPathComponent(".r")))
133            session.open(file.path)
134            guard case .external(.babel(let job)) = session.perform(ExecuteSrcBlock(), path: file.path, at: caret, expect: nil) else {
135                Issue.record("not planned: \(text)")
136                return
137            }
138            _ = await session.runBabel(job)
139            ours.append(session.document?.text ?? "")
140            let quoted = "\"" + text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
141            forms.append("(with-temp-buffer (insert \(quoted)) (org-mode) (goto-char \(caret + 1)) (condition-case e (org-babel-execute-src-block) (error (insert (format \"ERROR: %S\" e)))) (princ (concat (buffer-string) \"\\f\")))")
142        }
143        let emacs = try Self.emacs("""
144            (progn (require 'org) (require 'ob-sqlite)
145              (setq org-confirm-babel-evaluate nil org-babel-sqlite3-command "\(Self.sqlite3)" default-directory "\(theirFolder.url.path)/")
146              \(forms.joined(separator: "\n")))
147            """).split(separator: "\u{0C}", omittingEmptySubsequences: false).map(String.init)
148        for (i, text) in Self.blocks.enumerated() {
149            #expect(ours[i] == emacs[i], "\(text)\nours:\n\(ours[i])\nemacs:\n\(emacs[i])")
150        }
151    }
152
153    /// Emacs in a UTF-8 locale, as it runs on the Mac.
154    static func emacs(_ form: String) throws -> String {
155        let process = Process()
156        process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
157        process.arguments = [ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs", "-Q", "--batch", "--eval", form]
158        process.environment = ProcessInfo.processInfo.environment.merging(["LANG": "en_US.UTF-8", "LC_ALL": "en_US.UTF-8"]) { $1 }
159        let pipe = Pipe()
160        process.standardOutput = pipe
161        process.standardError = FileHandle.nullDevice
162        try process.run()
163        let data = pipe.fileHandleForReading.readDataToEndOfFile()
164        process.waitUntilExit()
165        return String(decoding: data, as: UTF8.self)
166    }
167
168    static func plan(_ text: String) throws -> BabelJob {
169        let caret = (text as NSString).range(of: "#+begin_src").location + 2
170        let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret])
171        guard case .success(let job) = Babel.plan(context) else { throw Babel.Failure.message("not planned: \(text)") }
172        return job
173    }
174
175    /// What can't be shown as `sqlite3` shows it is refused, with nothing written.
176    @Test func refusals() throws {
177        let refused: [(String, SQLiteBlocks.Refusal)] = [
178            ("#+begin_src sqlite :db \"my file.db\"\nselect 1;\n#+end_src\n", .init(.shell)),
179            ("#+begin_src sqlite :separator |\nselect 1;\n#+end_src\n", .init(.shell)),
180            ("#+begin_src sqlite :header :separator ;\nselect 1;\n#+end_src\n", .init(.shell)),
181            ("#+begin_src sqlite\n.separator ;\nselect 1;\n#+end_src\n", .init(.dotCommand(".separator"))),
182            ("#+begin_src sqlite :db ~/x.db\nselect 1;\n#+end_src\n", .init(.shell)),
183            ("#+begin_src sqlite\n.tables\n#+end_src\n", .init(.dotCommand(".tables"))),
184            ("#+begin_src sqlite\n.mode box\nselect 1;\n#+end_src\n", .init(.dotCommand(".mode"))),
185            ("#+begin_src sqlite\n.separator \"\\t\"\nselect 1;\n#+end_src\n", .init(.dotCommand(".separator"))),
186            ("#+begin_src sqlite\nselect x'00';\n#+end_src\n", .init(.blob)),
187            ("#+begin_src sqlite\nselect 'a' || char(13) || 'b';\n#+end_src\n", .init(.control)),
188            ("#+begin_src sqlite :column\nselect 'é';\n#+end_src\n", .init(.width)),
189            ("#+begin_src sqlite :column\nselect 'a\nb';\n#+end_src\n", .init(.width)),
190            ("#+begin_src sqlite\nexplain select 1;\n#+end_src\n", .init(.explain)),
191            ("#+begin_src sqlite\ncreate table t(a);\nselect x'01';\n#+end_src\n", .init(.blob, partly: true)),
192            (Self.table + "#+begin_src sqlite :var t=tbl\n.import --csv $t v\n#+end_src\n", .init(.newTable)),
193            (Self.table + "#+begin_src sqlite :var t=tbl\ncreate table v(a);\n.import --csv $t v\n#+end_src\n", .init(.importRows, partly: true)),
194        ]
195        let folder = try Folder()
196        for (text, refusal) in refused {
197            #expect(throws: Babel.Failure.message(refusal.message), "\(text)") { try SQLiteBlocks.run(Self.plan(text), directory: folder.url) }
198        }
199        #expect(try SQLiteBlocks.run(Self.plan("#+begin_src js\n1\n#+end_src\n"), directory: folder.url) == nil)
200    }
201
202    /// The sandboxed builds run calc blocks natively, and say why they refuse one.
203    @MainActor
204    @Test func calcBlocksRunInTheSession() async throws {
205        let folder = try Folder()
206        for (text, message, result) in [
207            ("#+begin_src calc\n1/3\n#+end_src\n", "Code block evaluation complete.", "#+RESULTS:\n: 0.333333333333\n"),
208            ("#+begin_src calc\n1\n'x\n#+end_src\n", "This calc block can't be calculated here: stack command 'x.", ""),
209        ] {
210            let file = try folder.write("c.org", text)
211            let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.url.appendingPathComponent(".r")))
212            session.open(file.path)
213            guard case .external(.babel(let job)) = session.perform(ExecuteSrcBlock(), path: file.path, at: 2, expect: nil) else {
214                Issue.record("not planned: \(text)")
215                return
216            }
217            #expect(await session.runBabel(job) == message)
218            #expect(session.document?.text == text + (result.isEmpty ? "" : "\n" + result))
219        }
220    }
221}
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