Debian Codegraph @

tests/unit_tests/test_statements.py

raw
1 """The tricky-SQL corpus.
2
3 `tests/functional_tests/test_query_editor.py` exercises the same splitter
4 through the Query Editor, so a divergence between the two front ends fails
5 here or there rather than in a user's buffer.
6 """
7
8 from __future__ import annotations
9
10 import pytest
11
12 from harlequin.statements import Statement, find_separators, split
13
14 # (name, script, expected statements). The name is the pytest id.
15 CORPUS: list[tuple[str, str, list[str]]] = [
16 ("empty", "", []),
17 ("whitespace only", " \n\t\n ", []),
18 ("no separator", "select 1", ["select 1"]),
19 ("trailing separator", "select 1;", ["select 1;"]),
20 ("two statements", "select 1; select 2", ["select 1;", "select 2"]),
21 (
22 "two statements, both terminated",
23 "select 1;\nselect 2;\n",
24 ["select 1;", "select 2;"],
25 ),
26 ("bare separator", ";", [";"]),
27 (
28 "consecutive separators",
29 "select 1;;select 2",
30 ["select 1;", ";", "select 2"],
31 ),
32 (
33 "blank lines between statements",
34 "select 1;\n\n\n \n\nselect 2;",
35 ["select 1;", "select 2;"],
36 ),
37 # a semicolon inside any of these is part of a single node, so the grammar
38 # never offers it as a separator.
39 ("single-quoted literal", "select 'a;b'", ["select 'a;b'"]),
40 (
41 "single-quoted literal, then a real separator",
42 "select 'a;b'; select 2",
43 ["select 'a;b';", "select 2"],
44 ),
45 ("double-quoted identifier", 'select "a;b" from t', ['select "a;b" from t']),
46 ("line comment", "select 1 -- a; comment\n", ["select 1 -- a; comment"]),
47 (
48 "line comment after a separator",
49 "select 1; -- a; comment\nselect 2",
50 ["select 1;", "-- a; comment\nselect 2"],
51 ),
52 (
53 "block comment",
54 "select 1 /* a; comment */ from t",
55 ["select 1 /* a; comment */ from t"],
56 ),
57 (
58 "escaped quote inside a literal",
59 "select 'it''s; fine'; select 2",
60 ["select 'it''s; fine';", "select 2"],
61 ),
62 # the reason find_separators() returns character columns. A byte offset
63 # lands one position late per byte of overhead: one for é, six for 日本語.
64 # The first is the reproduction from #1015.
65 (
66 "non-ascii before a separator",
67 "select 'café';select 2",
68 ["select 'café';", "select 2"],
69 ),
70 (
71 "multibyte before a separator",
72 "select '日本語';select 2",
73 ["select '日本語';", "select 2"],
74 ),
75 (
76 "non-ascii on an earlier line",
77 "select 'né';\nselect 2;",
78 ["select 'né';", "select 2;"],
79 ),
80 (
81 "astral plane before a separator",
82 "select '🦜';select 2",
83 ["select '🦜';", "select 2"],
84 ),
85 (
86 "non-ascii identifier",
87 'select "日本" from t; select 2',
88 ['select "日本" from t;', "select 2"],
89 ),
90 (
91 "windows line endings",
92 "select 1;\r\nselect 2;\r\n",
93 ["select 1;", "select 2;"],
94 ),
95 (
96 "many statements on one line",
97 "select 1;select 2;select 3",
98 ["select 1;", "select 2;", "select 3"],
99 ),
100 # a semicolon inside a dollar-quoted body is body content, not a
101 # separator. The grammar exposes the body's `$tag$` delimiters either way:
102 # as function_body tags when it parses, and as bare tokens during error
103 # recovery when it cannot (a missing `returns` clause). See #1019.
104 (
105 "dollar-quoted body with returns",
106 "create function f() returns int as $$ select 1; $$; select 2",
107 ["create function f() returns int as $$ select 1; $$;", "select 2"],
108 ),
109 (
110 "dollar-quoted body, semicolon flush with delimiters",
111 "create function f() as $$;$$; select 2",
112 ["create function f() as $$;$$;", "select 2"],
113 ),
114 (
115 "labeled dollar-quoted body",
116 "create function f() returns int as $body$ select 1; $body$; select 2",
117 ["create function f() returns int as $body$ select 1; $body$;", "select 2"],
118 ),
119 (
120 "differently labeled delimiter inside a body",
121 "create function f() as $a$ select 1; $b$ 2; $a$; select 3",
122 ["create function f() as $a$ select 1; $b$ 2; $a$;", "select 3"],
123 ),
124 (
125 "two dollar-quoted bodies",
126 "create function f() as $$ a; $$; create function g() as $$ b; $$;",
127 ["create function f() as $$ a; $$;", "create function g() as $$ b; $$;"],
128 ),
129 (
130 "unmatched dollar-quote delimiter",
131 "select $tag$; select 2",
132 ["select $tag$;", "select 2"],
133 ),
134 (
135 "dollar-quote tag in a string literal",
136 "select '$$'; select 2",
137 ["select '$$';", "select 2"],
138 ),
139 (
140 "dollar-quote tag in a comment",
141 "select 1 -- $$ ; select 2",
142 ["select 1 -- $$ ; select 2"],
143 ),
144 (
145 "dollar-quoted literal in an expression",
146 "select $$a;b$$; select 2",
147 ["select $$a;b$$;", "select 2"],
148 ),
149 (
150 "transaction",
151 "begin; select 1; commit;",
152 ["begin;", "select 1;", "commit;"],
153 ),
154 (
155 "multiline dollar-quoted body",
156 "create function f() as $$\n select 1;\n$$;\nselect 2",
157 ["create function f() as $$\n select 1;\n$$;", "select 2"],
158 ),
159 (
160 "non-ascii inside a dollar-quoted body",
161 "create function f() as $$ select 'café'; $$; select 2",
162 ["create function f() as $$ select 'café'; $$;", "select 2"],
163 ),
164 (
165 "multiline dollar-quoted body with non-ascii",
166 "create function f() as $$\n select 'café';\n$$;\nselect 2",
167 ["create function f() as $$\n select 'café';\n$$;", "select 2"],
168 ),
169 ]
170
171
172 @pytest.mark.parametrize(
173 ("script", "expected"),
174 [(script, expected) for _, script, expected in CORPUS],
175 ids=[name for name, _, _ in CORPUS],
176 )
177 def test_split(script: str, expected: list[str]) -> None:
178 assert split(script) == [
179 Statement(sql=sql, index=i) for i, sql in enumerate(expected)
180 ]
181
182
183 @pytest.mark.parametrize(
184 ("script", "expected"),
185 [(script, expected) for _, script, expected in CORPUS],
186 ids=[name for name, _, _ in CORPUS],
187 )
188 def test_find_separators_agrees_with_split(script: str, expected: list[str]) -> None:
189 """Slicing a buffer at the separators must reproduce split()'s statements.
190
191 This is the property the Query Editor relies on: it slices with the points,
192 while `-f` slices with the offsets, and the two must not disagree.
193 """
194 lines = script.splitlines(keepends=True)
195 line_starts = [0]
196 for line in lines:
197 line_starts.append(line_starts[-1] + len(line))
198
199 offsets = [line_starts[row] + col for row, col in find_separators(script)]
200 sliced = []
201 start = 0
202 for end in [*offsets, len(script)]:
203 if sql := script[start:end].strip():
204 sliced.append(sql)
205 start = end
206
207 assert sliced == expected
208
209
210 def test_find_separators_returns_character_columns() -> None:
211 """Regression test for #1015, the byte-vs-character bug this module fixes.
212
213 tree-sitter reports `Point.column` in bytes; `café` is 5 bytes and 4
214 characters, so the raw node put the separator at column 15 instead of 14,
215 and `日本語` (9 bytes, 3 characters) at 19 instead of 13.
216 """
217 assert find_separators("select 'café';select 2") == [(0, 14)]
218 assert find_separators("select '日本語';select 2") == [(0, 13)]
219
220
221 def test_find_separators_on_multiple_lines() -> None:
222 script = "select 1;\nselect 'né';\nselect 3;"
223 assert find_separators(script) == [(0, 9), (1, 12), (2, 9)]
224
225
226 def test_find_separators_are_sorted() -> None:
227 """tree-sitter captures nodes in pattern-match order, not buffer order."""
228 script = "".join(f"select {i};\n" for i in range(50))
229 points = find_separators(script)
230 assert points == sorted(points)
231 assert len(points) == 50
232
233
234 def test_statements_are_indexed_in_order() -> None:
235 statements = split("select 1; select 2; select 3")
236 assert [s.index for s in statements] == [0, 1, 2]
237
238
239 def test_dollar_quoted_body_is_not_split() -> None:
240 """Regression test for #1019: a semicolon inside `$$ ... $$` is body content."""
241 script = "create function f() as $$ select 1; $$; select 2"
242 assert split(script) == [
243 Statement(sql="create function f() as $$ select 1; $$;", index=0),
244 Statement(sql="select 2", index=1),
245 ]
246
247
248 def test_find_separators_after_dollar_quoted_body() -> None:
249 """The separator after a dollar-quoted body is still a character column.
250
251 The fix pairs the body's delimiters on byte offsets, and a multiline body
252 puts non-ASCII before the separator that ends the statement -- so the
253 (row, col) point must come out of the same character conversion as any
254 other separator, not off by one per extra byte.
255 """
256 script = "create function f() as $$\n select 'café';\n$$;\nselect 2"
257 assert find_separators(script) == [(2, 3)]