File: query_test.py

package info (click to toggle)
sqlfluff 3.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 33,984 kB
  • sloc: python: 106,138; sql: 34,188; makefile: 52; sh: 8
file content (311 lines) | stat: -rw-r--r-- 9,967 bytes parent folder | download | duplicates (2)
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
305
306
307
308
309
310
311
"""Test the select_crawler module."""

import pytest

from sqlfluff.core.linter.linter import Linter
from sqlfluff.utils.analysis.query import Query


def _parse_and_crawl_outer(sql):
    """Helper function for select crawlers.

    Given a SQL statement this crawls the SQL and instantiates
    a Query on the outer relevant segment.
    """
    linter = Linter(dialect="ansi")
    parsed = linter.parse_string(sql)
    # Make sure it's fully parsable.
    assert "unparsable" not in parsed.tree.descendant_type_set
    # Create a crawler from the root segment.
    query = Query.from_root(parsed.tree, linter.dialect)
    # Analyse the segment.
    return query, linter


@pytest.mark.parametrize(
    "sql, expected_json",
    [
        (
            # Test trivial query.
            "select 1",
            {"selectables": ["select 1"]},
        ),
        (
            # Test set expression.
            "select 1 union select 2",
            {"selectables": ["select 1", "select 2"]},
        ),
        (
            # Test multiple CTEs.
            "with cte1 as (select 1 as x), cte2 as (select 2 as y) "
            "select * from cte1 join cte2 using (x)",
            {
                "ctes": {
                    "CTE1": {"selectables": ["select 1 as x"]},
                    "CTE2": {"selectables": ["select 2 as y"]},
                },
                "query_type": "WithCompound",
                "selectables": ["select * from cte1 join cte2 using (x)"],
            },
        ),
        (
            # Nested CTEs (from AM04 test suite)
            """
        with a as (
            with b as (select 1 from c)
            select * from b
        )
        select * from a
        """,
            {
                "ctes": {
                    "A": {
                        "ctes": {"B": {"selectables": ["select 1 from c"]}},
                        "query_type": "WithCompound",
                        "selectables": ["select * from b"],
                    }
                },
                "query_type": "WithCompound",
                "selectables": ["select * from a"],
            },
        ),
        (
            # Nested CTEs (from AM04 test suite)
            """
        with b as (select 1 from c)
        select * from (
            with a as (select * from b)
            select * from a
        )
        """,
            {
                "ctes": {"B": {"selectables": ["select 1 from c"]}},
                "query_type": "WithCompound",
                "selectables": [
                    "select * from (\n"
                    "            with a as (select * from b)\n"
                    "            select * from a\n"
                    "        )"
                ],
                "subqueries": [
                    # NOTE: Subquery from the FROM clause.
                    {
                        "ctes": {"A": {"selectables": ["select * from b"]}},
                        "query_type": "WithCompound",
                        "selectables": ["select * from a"],
                    },
                ],
            },
        ),
        (
            # Test that subquery in "from" not included.
            "select a.x from (select z from b)",
            {
                "selectables": ["select a.x from (select z from b)"],
                "subqueries": [{"selectables": ["select z from b"]}],
            },
        ),
        (
            # Test that subquery in "from" / "join" not included.
            "select a.x from a join (select z from b) as b on (a.x = b.x)",
            {
                "selectables": [
                    "select a.x from a join (select z from b) as b on (a.x = b.x)"
                ],
                "subqueries": [{"selectables": ["select z from b"]}],
            },
        ),
        (
            # In CTE main query, test that subquery in "from" not included.
            "with prep as (select 1) select a.x from (select z from b)",
            {
                "ctes": {"PREP": {"selectables": ["select 1"]}},
                "query_type": "WithCompound",
                "selectables": ["select a.x from (select z from b)"],
                "subqueries": [{"selectables": ["select z from b"]}],
            },
        ),
        (
            # In CTE main query, test that subquery in "from" / "join" not included.
            "with prep as (select 1) "
            "select a.x from a join (select z from b) as b on (a.x = b.x)",
            {
                "ctes": {"PREP": {"selectables": ["select 1"]}},
                "query_type": "WithCompound",
                "selectables": [
                    "select a.x from a join (select z from b) as b on (a.x = " "b.x)"
                ],
                "subqueries": [{"selectables": ["select z from b"]}],
            },
        ),
        (
            """with prep_1 as (
    with d as (
        select x, z from b
    )
    select * from d
)
select
    a.x, a.y, b.z
from a
join prep_1 using (x)
""",
            {
                "ctes": {
                    "PREP_1": {
                        "ctes": {
                            "D": {"selectables": ["select x, z from b"]},
                        },
                        "query_type": "WithCompound",
                        "selectables": ["select * from d"],
                    }
                },
                "query_type": "WithCompound",
                "selectables": [
                    "select\n    a.x, a.y, b.z\nfrom a\njoin prep_1 using (x)"
                ],
            },
        ),
        # Test with a UNION as the main selectable of a WITH
        (
            "with a as (select 1), b as (select 2) "
            "select * from a union select * from b\n",
            {
                "ctes": {
                    "A": {"selectables": ["select 1"]},
                    "B": {"selectables": ["select 2"]},
                },
                "query_type": "WithCompound",
                "selectables": [
                    "select * from a",
                    "select * from b",
                ],
            },
        ),
        # Test with a VALUES clause in a WITH
        (
            "WITH txt AS ( VALUES (1, 'foo') ) SELECT * FROM txt\n",
            {
                "ctes": {
                    "TXT": {"selectables": ["VALUES (1, 'foo')"]},
                },
                "query_type": "WithCompound",
                "selectables": [
                    "SELECT * FROM txt",
                ],
            },
        ),
        # Test with Subqueries
        (
            "SELECT (\n"
            "    SELECT other_table.other_table_field_1 FROM other_table\n"
            "    WHERE other_table.id = field_2\n"
            ") FROM\n"
            "(SELECT * FROM some_table) AS my_alias\n",
            {
                "selectables": [
                    "SELECT (\n"
                    "    SELECT other_table.other_table_field_1 FROM other_table\n"
                    "    WHERE other_table.id = field_2\n"
                    ") FROM\n"
                    "(SELECT * FROM some_table) AS my_alias",
                ],
                "subqueries": [
                    {
                        "selectables": [
                            "SELECT other_table.other_table_field_1 FROM other_table\n"
                            "    WHERE other_table.id = field_2",
                        ]
                    },
                    {"selectables": ["SELECT * FROM some_table"]},
                ],
            },
        ),
        # Test a MERGE
        (
            """MERGE INTO t USING (SELECT * FROM u) AS u ON (a = b)
WHEN MATCHED THEN
UPDATE SET a = b
WHEN NOT MATCHED THEN
INSERT (b) VALUES (c);""",
            {
                "selectables": [
                    """MERGE INTO t USING (SELECT * FROM u) AS u ON (a = b)
WHEN MATCHED THEN
UPDATE SET a = b
WHEN NOT MATCHED THEN
INSERT (b) VALUES (c)"""  # NOTE: No trailing semicolon
                ],
                "subqueries": [{"selectables": ["SELECT * FROM u"]}],
            },
        ),
        # Test a DELETE
        (
            """DELETE FROM agent1
WHERE EXISTS(
    SELECT customer.cust_id FROM customer
    WHERE agent1.agent_code <> customer.agent_code);""",
            {
                "selectables": [
                    """SELECT customer.cust_id FROM customer
    WHERE agent1.agent_code <> customer.agent_code"""
                ]
            },
        ),
        # Test an UPDATE
        (
            """UPDATE my_table
SET row_sum = (
    SELECT COUNT(*) AS row_sum
    FROM
        another_table
    WHERE
        another_table.id = my_tableeee.id
)""",
            {
                "selectables": [
                    """SELECT COUNT(*) AS row_sum
    FROM
        another_table
    WHERE
        another_table.id = my_tableeee.id"""
                ]
            },
        ),
    ],
)
def test_select_crawler_constructor(sql, expected_json):
    """Test Query when created using constructor."""
    query, _ = _parse_and_crawl_outer(sql)
    assert all(cte.cte_definition_segment is not None for cte in query.ctes.values())
    query_dict = query.as_dict()
    assert expected_json == query_dict


def test_select_crawler_nested():
    """Test invoking with an outer from_expression_segment."""
    sql = """
select
    a.x, a.y, b.z
from a
join (
    with d as (
        select x, z from b
    )
    select * from d
) using (x)
    """
    query, linter = _parse_and_crawl_outer(sql)

    inner_from = (
        query.selectables[0].select_info.table_aliases[1].from_expression_element
    )
    inner_select = next(inner_from.recursive_crawl("with_compound_statement"))
    inner_query = Query.from_segment(inner_select, linter.dialect)
    assert inner_query.as_dict() == {
        "selectables": [
            "select * from d",
        ],
        "ctes": {"D": {"selectables": ["select x, z from b"]}},
        "query_type": "WithCompound",
    }