File size: 8,830 Bytes
5b7ed07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

from __future__ import annotations

import subprocess
from subprocess import CompletedProcess
from unittest.mock import MagicMock, patch

from superset.sql_validators.sqlite import SQLiteSQLValidator


def _mock_result(
    returncode: int,
    stderr: str = "",
    stdout: str = "",
) -> CompletedProcess[str]:
    return CompletedProcess(
        args=[],
        returncode=returncode,
        stdout=stdout,
        stderr=stderr,
    )


def test_valid_syntax() -> None:
    mock_database = MagicMock()
    sql = "SELECT 1, col FROM my_table"

    with (
        patch(
            "superset.sql_validators.sqlite.get_binary_path",
            return_value="syntaqlite",
        ),
        patch(
            "superset.sql_validators.sqlite.subprocess.run",
            return_value=_mock_result(returncode=0),
        ) as run,
    ):
        annotations = SQLiteSQLValidator.validate(
            sql=sql,
            catalog=None,
            schema="",
            database=mock_database,
        )

    assert annotations == []
    run.assert_called_once()
    command = run.call_args.args[0]
    assert "--input" not in command
    assert "-e" not in command
    assert run.call_args.kwargs["input"] == sql


def test_invalid_syntax_single_error() -> None:
    mock_database = MagicMock()
    stderr = (
        'error: near "SELEC": syntax error\n'
        " --> <input>:1:1\n"
        "  |\n"
        "1 | SELEC * FROM foo\n"
        "  | ^~~~~\n"
    )

    with (
        patch(
            "superset.sql_validators.sqlite.get_binary_path", return_value="syntaqlite"
        ),
        patch(
            "superset.sql_validators.sqlite.subprocess.run",
            return_value=_mock_result(returncode=1, stderr=stderr),
        ),
    ):
        annotations = SQLiteSQLValidator.validate(
            sql="SELEC * FROM foo",
            catalog=None,
            schema="",
            database=mock_database,
        )

    assert len(annotations) == 1
    annotation = annotations[0]
    assert annotation.line_number == 1
    assert annotation.start_column == 1
    # "SELEC" is 5 chars → caret + 4 tildes → end_column = 1 + 1 + 4 = 6
    assert annotation.end_column == 6
    assert "SELEC" in annotation.message


def test_invalid_syntax_multiple_errors() -> None:
    mock_database = MagicMock()
    stderr = (
        'error: near "SELEC": syntax error\n'
        " --> <input>:1:1\n"
        "  |\n"
        "1 | SELEC * FROM foo; SELEC * FROM bar\n"
        "  | ^~~~~\n\n"
        'error: near "SELEC": syntax error\n'
        " --> <input>:1:20\n"
        "  |\n"
        "1 | SELEC * FROM foo; SELEC * FROM bar\n"
        "  |                    ^~~~~\n"
    )

    with (
        patch(
            "superset.sql_validators.sqlite.get_binary_path", return_value="syntaqlite"
        ),
        patch(
            "superset.sql_validators.sqlite.subprocess.run",
            return_value=_mock_result(returncode=1, stderr=stderr),
        ),
    ):
        annotations = SQLiteSQLValidator.validate(
            sql="SELEC * FROM foo; SELEC * FROM bar",
            catalog=None,
            schema="",
            database=mock_database,
        )

    assert len(annotations) == 2
    assert "SELEC" in annotations[0].message
    # "SELEC" is 5 chars → caret + 4 tildes → end_column = start_column + 1 + 4
    assert isinstance(annotations[0].start_column, int)
    assert annotations[0].end_column == annotations[0].start_column + 5
    assert isinstance(annotations[1].start_column, int)
    assert annotations[1].end_column == annotations[1].start_column + 5


def test_multiline_error_reports_correct_line() -> None:
    mock_database = MagicMock()
    stderr = (
        'error: near "SELEC": syntax error\n'
        " --> <input>:2:1\n"
        "  |\n"
        "2 | SELEC * FROM foo\n"
        "  | ^~~~~\n"
    )

    with (
        patch(
            "superset.sql_validators.sqlite.get_binary_path", return_value="syntaqlite"
        ),
        patch(
            "superset.sql_validators.sqlite.subprocess.run",
            return_value=_mock_result(returncode=1, stderr=stderr),
        ),
    ):
        annotations = SQLiteSQLValidator.validate(
            sql="SELECT 1;\nSELEC * FROM foo",
            catalog=None,
            schema="",
            database=mock_database,
        )

    assert len(annotations) == 1
    assert annotations[0].line_number == 2


def test_empty_sql() -> None:
    mock_database = MagicMock()

    with (
        patch(
            "superset.sql_validators.sqlite.get_binary_path", return_value="syntaqlite"
        ),
        patch(
            "superset.sql_validators.sqlite.subprocess.run",
            return_value=_mock_result(returncode=0),
        ),
    ):
        annotations = SQLiteSQLValidator.validate(
            sql="",
            catalog=None,
            schema="",
            database=mock_database,
        )

    assert annotations == []


def test_valid_complex_query() -> None:
    mock_database = MagicMock()

    with (
        patch(
            "superset.sql_validators.sqlite.get_binary_path", return_value="syntaqlite"
        ),
        patch(
            "superset.sql_validators.sqlite.subprocess.run",
            return_value=_mock_result(returncode=0),
        ),
    ):
        annotations = SQLiteSQLValidator.validate(
            sql=(
                "SELECT a, COUNT(*) AS cnt "
                "FROM my_table "
                "WHERE b > 10 "
                "GROUP BY a "
                "HAVING cnt > 1 "
                "ORDER BY cnt DESC "
                "LIMIT 100"
            ),
            catalog=None,
            schema="",
            database=mock_database,
        )

    assert annotations == []


def test_annotation_to_dict() -> None:
    mock_database = MagicMock()
    stderr = (
        'error: near "SELEC": syntax error\n'
        " --> <input>:1:1\n"
        "  |\n"
        "1 | SELEC * FROM foo\n"
        "  | ^~~~~\n"
    )

    with (
        patch(
            "superset.sql_validators.sqlite.get_binary_path", return_value="syntaqlite"
        ),
        patch(
            "superset.sql_validators.sqlite.subprocess.run",
            return_value=_mock_result(returncode=1, stderr=stderr),
        ),
    ):
        annotations = SQLiteSQLValidator.validate(
            sql="SELEC * FROM foo",
            catalog=None,
            schema="",
            database=mock_database,
        )

    assert len(annotations) == 1
    result = annotations[0].to_dict()
    assert "line_number" in result
    assert "start_column" in result
    assert "end_column" in result
    assert "message" in result


def test_missing_syntaqlite_returns_annotation() -> None:
    mock_database = MagicMock()
    with patch("superset.sql_validators.sqlite.get_binary_path", None):
        annotations = SQLiteSQLValidator.validate(
            sql="SELECT 1",
            catalog=None,
            schema="",
            database=mock_database,
        )

    assert len(annotations) == 1
    assert "syntaqlite is not installed" in annotations[0].message
    assert annotations[0].line_number is None


def test_timeout_returns_annotation() -> None:
    mock_database = MagicMock()

    with (
        patch(
            "superset.sql_validators.sqlite.get_binary_path", return_value="syntaqlite"
        ),
        patch(
            "superset.sql_validators.sqlite.subprocess.run",
            side_effect=subprocess.TimeoutExpired(cmd="syntaqlite", timeout=10),
        ),
    ):
        annotations = SQLiteSQLValidator.validate(
            sql="SELECT 1",
            catalog=None,
            schema="",
            database=mock_database,
        )

    assert len(annotations) == 1
    assert "timed out" in annotations[0].message
    assert annotations[0].line_number is None


def test_get_validator_by_name() -> None:
    from superset.sql_validators import get_validator_by_name

    validator = get_validator_by_name("SQLiteSQLValidator")
    assert validator is SQLiteSQLValidator