sqlassert 0.1.2__py3-none-any.whl → 0.3.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sqlassert/__init__.py +34 -9
- sqlassert/__main__.py +9 -0
- sqlassert/check.py +451 -0
- sqlassert/diagnostics.py +70 -0
- sqlassert/dialects.py +258 -0
- sqlassert/discovery/__init__.py +30 -0
- sqlassert/discovery/bigquery.py +71 -0
- sqlassert/discovery/databricks.py +18 -0
- sqlassert/discovery/duckdb.py +159 -0
- sqlassert/discovery/fetcher.py +418 -0
- sqlassert/discovery/information_schema.py +327 -0
- sqlassert/discovery/mysql.py +70 -0
- sqlassert/discovery/postgres.py +142 -0
- sqlassert/discovery/redshift.py +36 -0
- sqlassert/discovery/snowflake.py +63 -0
- sqlassert/discovery/trino.py +37 -0
- sqlassert/edits.py +240 -0
- sqlassert/hazards.py +574 -0
- sqlassert/ir/__init__.py +58 -0
- sqlassert/ir/convert.py +3509 -0
- sqlassert/ir/model.py +779 -0
- sqlassert/main.py +51 -0
- sqlassert/properties.py +121 -0
- sqlassert/provenance.py +73 -0
- sqlassert/python_engine.py +356 -0
- sqlassert/reporting.py +105 -0
- sqlassert/rewrites.py +1541 -0
- sqlassert/rules/STYLEGUIDE.md +19 -0
- sqlassert/rules/__init__.py +11 -0
- sqlassert/rules/column_set.py +34 -0
- sqlassert/rules/domain.py +472 -0
- sqlassert/rules/equality.py +442 -0
- sqlassert/rules/exactly_one.py +114 -0
- sqlassert/rules/foreign_key.py +319 -0
- sqlassert/rules/join_cardinality.py +116 -0
- sqlassert/rules/nullability.py +627 -0
- sqlassert/rules/uniqueness.py +904 -0
- sqlassert/sql_parse.py +1081 -0
- sqlassert/suggest.py +418 -0
- sqlassert-0.3.3.dist-info/METADATA +807 -0
- sqlassert-0.3.3.dist-info/RECORD +46 -0
- {sqlassert-0.1.2.dist-info → sqlassert-0.3.3.dist-info}/WHEEL +1 -1
- sqlassert-0.3.3.dist-info/entry_points.txt +2 -0
- sqlassert-0.3.3.dist-info/licenses/LICENSE +21 -0
- sqlassert-0.3.3.dist-info/top_level.txt +2 -0
- sqlassert_cli.py +130 -0
- sqlassert/unique.py +0 -605
- sqlassert-0.1.2.dist-info/METADATA +0 -173
- sqlassert-0.1.2.dist-info/RECORD +0 -6
- sqlassert-0.1.2.dist-info/top_level.txt +0 -1
sqlassert/sql_parse.py
ADDED
|
@@ -0,0 +1,1081 @@
|
|
|
1
|
+
"""Parse SQL text into a SQL Program: Create Statements plus at most one Root
|
|
2
|
+
Select, with join markers resolved onto the joins they mark, column markers
|
|
3
|
+
resolved onto the Select Expressions they follow, and case markers resolved
|
|
4
|
+
onto the simple `CASE` expressions they precede.
|
|
5
|
+
|
|
6
|
+
The marker is real syntax, not a comment we go looking for: a custom dialect
|
|
7
|
+
tokenizes `/**ASSERT UNIQUE**/` as a token of its own and the join rule consumes it, so
|
|
8
|
+
the grammar is what requires a marker to sit immediately before its join. The
|
|
9
|
+
span is then recorded on the `Join` node, and nothing downstream re-reads SQL
|
|
10
|
+
text. `/**ASSERT EXHAUSTIVE**/` is likewise a primary expression of its own
|
|
11
|
+
that must continue with `CASE`. SQLGlot objects stop at this boundary; only the IR parser reads them.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from functools import lru_cache
|
|
17
|
+
from typing import Literal, NamedTuple
|
|
18
|
+
import enum
|
|
19
|
+
import re
|
|
20
|
+
|
|
21
|
+
from sqlglot import Expr, exp
|
|
22
|
+
from sqlglot.dialects.dialect import Dialect
|
|
23
|
+
from sqlglot.errors import ParseError, SqlglotError
|
|
24
|
+
from sqlglot.tokens import Token, TokenType
|
|
25
|
+
|
|
26
|
+
from sqlassert import diagnostics as diag
|
|
27
|
+
from sqlassert.diagnostics import Diagnostic
|
|
28
|
+
from sqlassert.ir.model import LiteralValue
|
|
29
|
+
from sqlassert.provenance import SQL, Origin, Span
|
|
30
|
+
|
|
31
|
+
# Where a resolved assertion is recorded on its Join node, and which join marker it was.
|
|
32
|
+
_ASSERTED_AT = "sqlassert.asserted_at"
|
|
33
|
+
_JOIN_MARKER_KIND = "sqlassert.join_marker_kind"
|
|
34
|
+
|
|
35
|
+
# A comment opening with `/**` is how an author writes an assertion or a
|
|
36
|
+
# Property Declaration.
|
|
37
|
+
# `/**/` is an empty comment, not the start of a marker.
|
|
38
|
+
_MARKER_SHAPED = re.compile(r"/\*\*(?!/).*?\*/", re.DOTALL)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _marker_shapes(sql: str, tokens: list[Token] | None = None) -> list[re.Match[str]]:
|
|
42
|
+
"""Every `/**...*/` span written as SQL: not inside a `--` comment or a
|
|
43
|
+
quoted string or identifier. A `--` comment is how an author switches a
|
|
44
|
+
marker off; text in quotes is data. Offsets are those of `sql`."""
|
|
45
|
+
masked = list(sql)
|
|
46
|
+
for token in tokens or ():
|
|
47
|
+
if token.token_type in (TokenType.HEREDOC_STRING, TokenType.RAW_STRING):
|
|
48
|
+
masked[token.start:token.end + 1] = (" " if char != "\n" else char for char in sql[token.start:token.end + 1])
|
|
49
|
+
sql = "".join(masked)
|
|
50
|
+
index, quote = 0, None
|
|
51
|
+
while index < len(sql):
|
|
52
|
+
char = sql[index]
|
|
53
|
+
if quote:
|
|
54
|
+
if char == quote:
|
|
55
|
+
if sql.startswith(quote * 2, index): # an escaped quote
|
|
56
|
+
masked[index] = masked[index + 1] = " "
|
|
57
|
+
index += 2
|
|
58
|
+
continue
|
|
59
|
+
quote = None
|
|
60
|
+
elif char != "\n":
|
|
61
|
+
masked[index] = " "
|
|
62
|
+
elif char in "'\"":
|
|
63
|
+
quote = char
|
|
64
|
+
elif sql.startswith("/*", index):
|
|
65
|
+
end = sql.find("*/", index + 2)
|
|
66
|
+
index = len(sql) if end < 0 else end + 2
|
|
67
|
+
continue
|
|
68
|
+
elif sql.startswith("--", index):
|
|
69
|
+
end = sql.find("\n", index)
|
|
70
|
+
end = len(sql) if end < 0 else end
|
|
71
|
+
masked[index:end] = " " * (end - index)
|
|
72
|
+
index = end
|
|
73
|
+
continue
|
|
74
|
+
index += 1
|
|
75
|
+
text = "".join(masked)
|
|
76
|
+
return [match for match in _MARKER_SHAPED.finditer(text)]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class SqlassertToken(enum.Enum):
|
|
80
|
+
"""Token types sqlassert adds to a dialect.
|
|
81
|
+
|
|
82
|
+
Deliberately a plain Enum: SQLGlot's own `TokenType` is an `IntEnum`, so a
|
|
83
|
+
member of ours sharing its integer value would compare equal to a real token
|
|
84
|
+
type and be swallowed by SQLGlot's keyword sets. A plain member can equal
|
|
85
|
+
nothing but itself, which also means no rule but ours can consume it.
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
SQLASSERT_UNIQUE = enum.auto()
|
|
89
|
+
SQLASSERT_MANY_TO_ONE = enum.auto()
|
|
90
|
+
SQLASSERT_ONE_TO_MANY = enum.auto()
|
|
91
|
+
SQLASSERT_ONE_TO_ONE = enum.auto()
|
|
92
|
+
SQLASSERT_EXACTLY_ONE = enum.auto()
|
|
93
|
+
SQLASSERT_EXHAUSTIVE = enum.auto()
|
|
94
|
+
SQLASSERT_UNIQUE_SET_OPEN = enum.auto()
|
|
95
|
+
SQLASSERT_NON_NULL_UNIQUE_SET_OPEN = enum.auto()
|
|
96
|
+
SQLASSERT_DECLARED_UNIQUE_SET_OPEN = enum.auto()
|
|
97
|
+
SQLASSERT_DECLARED_NON_NULL_UNIQUE_SET_OPEN = enum.auto()
|
|
98
|
+
SQLASSERT_NOT_NULL_OPEN = enum.auto()
|
|
99
|
+
SQLASSERT_DECLARED_NOT_NULL_OPEN = enum.auto()
|
|
100
|
+
SQLASSERT_NOT_NULL_ELEMENTS_OPEN = enum.auto()
|
|
101
|
+
SQLASSERT_DECLARED_NOT_NULL_ELEMENTS_OPEN = enum.auto()
|
|
102
|
+
SQLASSERT_FOREIGN_KEY_OPEN = enum.auto()
|
|
103
|
+
SQLASSERT_DECLARED_FOREIGN_KEY_OPEN = enum.auto()
|
|
104
|
+
SQLASSERT_DETERMINES_OPEN = enum.auto()
|
|
105
|
+
SQLASSERT_DECLARED_DETERMINES_OPEN = enum.auto()
|
|
106
|
+
SQLASSERT_ENUM_OPEN = enum.auto()
|
|
107
|
+
SQLASSERT_DECLARED_ENUM_OPEN = enum.auto()
|
|
108
|
+
SQLASSERT_MARKER_CLOSE = enum.auto()
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
# Every marker sqlassert understands, and the token each becomes. The single
|
|
112
|
+
# source of truth for the join markers and the fixed opening/closing
|
|
113
|
+
# literals of a column marker: the dialect tokenizes exactly these, and
|
|
114
|
+
# `_unrecognized_markers` reports anything else shaped like one.
|
|
115
|
+
#
|
|
116
|
+
# `ASSERT` asks for a proof; `DECLARE` states a trusted Property Declaration.
|
|
117
|
+
# A column marker -- `/**ASSERT UNIQUE(col, ...)**/`, `/**ASSERT NOT NULL(...)**/`,
|
|
118
|
+
# `/**DECLARE NOT NULL UNIQUE(...)**/`, and the rest of `_COLUMN_MARKER_OPENS` --
|
|
119
|
+
# carries a variable column list, so unlike the join marker it cannot be one
|
|
120
|
+
# fixed `KEYWORDS` literal: only its open and close are fixed text; the column
|
|
121
|
+
# list between them is ordinary SQL, parsed with the parser's own
|
|
122
|
+
# identifier-list machinery once the open token is matched
|
|
123
|
+
# (`_Parser._parse_select_query` below). A Foreign Key marker continues its
|
|
124
|
+
# column list with `REFERENCES relation(col, ...)`, pairing columns by position:
|
|
125
|
+
# `/**ASSERT FOREIGN KEY(a, b) REFERENCES t(x, y)**/`. A Functional Dependency
|
|
126
|
+
# marker splits its list with `->`: `/**ASSERT DETERMINES(a, b -> c)**/`. An
|
|
127
|
+
# Enumerated Domain marker names one column and the literals its non-null
|
|
128
|
+
# values are drawn from: `/**ASSERT ENUM(status IN ('new', 'paid'))**/`.
|
|
129
|
+
# `/**ASSERT EXHAUSTIVE**/` is written inside an expression, immediately
|
|
130
|
+
# before the simple `CASE` it marks.
|
|
131
|
+
MARKERS = {
|
|
132
|
+
"/**ASSERT UNIQUE**/": SqlassertToken.SQLASSERT_UNIQUE,
|
|
133
|
+
"/**ASSERT NOT MANY TO MANY**/": SqlassertToken.SQLASSERT_UNIQUE,
|
|
134
|
+
"/**ASSERT MANY TO ONE**/": SqlassertToken.SQLASSERT_MANY_TO_ONE,
|
|
135
|
+
"/**ASSERT ONE TO MANY**/": SqlassertToken.SQLASSERT_ONE_TO_MANY,
|
|
136
|
+
"/**ASSERT ONE TO ONE**/": SqlassertToken.SQLASSERT_ONE_TO_ONE,
|
|
137
|
+
"/**ASSERT EXACTLY ONE**/": SqlassertToken.SQLASSERT_EXACTLY_ONE,
|
|
138
|
+
"/**ASSERT EXHAUSTIVE**/": SqlassertToken.SQLASSERT_EXHAUSTIVE,
|
|
139
|
+
"/**ASSERT UNIQUE(": SqlassertToken.SQLASSERT_UNIQUE_SET_OPEN,
|
|
140
|
+
"/**ASSERT NOT NULL UNIQUE(": SqlassertToken.SQLASSERT_NON_NULL_UNIQUE_SET_OPEN,
|
|
141
|
+
# `PRIMARY KEY` is a convenience alias for `NOT NULL UNIQUE`: it does not
|
|
142
|
+
# mean one key per relation, and a relation may carry several.
|
|
143
|
+
"/**ASSERT PRIMARY KEY(": SqlassertToken.SQLASSERT_NON_NULL_UNIQUE_SET_OPEN,
|
|
144
|
+
"/**ASSERT NOT NULL(": SqlassertToken.SQLASSERT_NOT_NULL_OPEN,
|
|
145
|
+
"/**DECLARE UNIQUE(": SqlassertToken.SQLASSERT_DECLARED_UNIQUE_SET_OPEN,
|
|
146
|
+
"/**DECLARE NOT NULL UNIQUE(": SqlassertToken.SQLASSERT_DECLARED_NON_NULL_UNIQUE_SET_OPEN,
|
|
147
|
+
"/**DECLARE PRIMARY KEY(": SqlassertToken.SQLASSERT_DECLARED_NON_NULL_UNIQUE_SET_OPEN,
|
|
148
|
+
"/**DECLARE NOT NULL(": SqlassertToken.SQLASSERT_DECLARED_NOT_NULL_OPEN,
|
|
149
|
+
"/**ASSERT NOT NULL ELEMENTS(": SqlassertToken.SQLASSERT_NOT_NULL_ELEMENTS_OPEN,
|
|
150
|
+
"/**DECLARE NOT NULL ELEMENTS(": SqlassertToken.SQLASSERT_DECLARED_NOT_NULL_ELEMENTS_OPEN,
|
|
151
|
+
"/**ASSERT FOREIGN KEY(": SqlassertToken.SQLASSERT_FOREIGN_KEY_OPEN,
|
|
152
|
+
"/**DECLARE FOREIGN KEY(": SqlassertToken.SQLASSERT_DECLARED_FOREIGN_KEY_OPEN,
|
|
153
|
+
"/**ASSERT DETERMINES(": SqlassertToken.SQLASSERT_DETERMINES_OPEN,
|
|
154
|
+
"/**DECLARE DETERMINES(": SqlassertToken.SQLASSERT_DECLARED_DETERMINES_OPEN,
|
|
155
|
+
"/**ASSERT ENUM(": SqlassertToken.SQLASSERT_ENUM_OPEN,
|
|
156
|
+
"/**DECLARE ENUM(": SqlassertToken.SQLASSERT_DECLARED_ENUM_OPEN,
|
|
157
|
+
"**/": SqlassertToken.SQLASSERT_MARKER_CLOSE,
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
type JoinMarkerKind = Literal["unique-join", "many-to-one-join", "one-to-many-join", "one-to-one-join", "exactly-one-join"]
|
|
161
|
+
type ColumnMarkerKind = Literal[
|
|
162
|
+
"unique", "key", "not-null", "not-null-elements", "foreign-key", "determines", "enum",
|
|
163
|
+
"declared-unique", "declared-key", "declared-not-null", "declared-not-null-elements", "declared-foreign-key",
|
|
164
|
+
"declared-determines", "declared-enum",
|
|
165
|
+
]
|
|
166
|
+
|
|
167
|
+
# The join markers, written immediately before a JOIN, and the kind each states.
|
|
168
|
+
# The cardinality words read in FROM order: the left input is everything
|
|
169
|
+
# before the join, the right its joined source. "unique-join" (`UNIQUE`, or
|
|
170
|
+
# `NOT MANY TO MANY`) repeats rows of at most one input; "many-to-one-join"
|
|
171
|
+
# none of the left's, "one-to-many-join" none of the right's, "one-to-one-join"
|
|
172
|
+
# neither's; "exactly-one-join" matches every left row exactly once.
|
|
173
|
+
JOIN_MARKER_KINDS: dict[SqlassertToken, JoinMarkerKind] = {
|
|
174
|
+
SqlassertToken.SQLASSERT_UNIQUE: "unique-join",
|
|
175
|
+
SqlassertToken.SQLASSERT_MANY_TO_ONE: "many-to-one-join",
|
|
176
|
+
SqlassertToken.SQLASSERT_ONE_TO_MANY: "one-to-many-join",
|
|
177
|
+
SqlassertToken.SQLASSERT_ONE_TO_ONE: "one-to-one-join",
|
|
178
|
+
SqlassertToken.SQLASSERT_EXACTLY_ONE: "exactly-one-join",
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
# How diagnostics name each join marker kind.
|
|
182
|
+
JOIN_MARKER_NOUNS: dict[JoinMarkerKind, str] = {
|
|
183
|
+
"unique-join": "unique join", "many-to-one-join": "many to one join", "one-to-many-join": "one to many join",
|
|
184
|
+
"one-to-one-join": "one to one join", "exactly-one-join": "exactly one join",
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
# The markers written as one fixed literal: the join markers and the case marker.
|
|
188
|
+
_FIXED_MARKER_TOKENS = frozenset({*JOIN_MARKER_KINDS, SqlassertToken.SQLASSERT_EXHAUSTIVE})
|
|
189
|
+
|
|
190
|
+
# Where a resolved case marker's span is recorded on its `Case` node.
|
|
191
|
+
_EXHAUSTIVE_AT = "sqlassert.exhaustive_at"
|
|
192
|
+
|
|
193
|
+
# The open literals of a column marker, and the kind each one states --
|
|
194
|
+
# "unique" is a nullable-tolerant Unique Set, "key" the stricter
|
|
195
|
+
# Non-Null Unique Set, "not-null" non-nullness of every listed column,
|
|
196
|
+
# "not-null-elements" that no listed column's value has a NULL element, and
|
|
197
|
+
# "foreign-key" a Foreign Key from the listed columns, "determines" a Functional
|
|
198
|
+
# Dependency from the columns before `->` to those after, "enum" an Enumerated
|
|
199
|
+
# Domain of the one column before `IN`. A "declared-" kind states
|
|
200
|
+
# the same Property as a trusted declaration.
|
|
201
|
+
_COLUMN_MARKER_OPENS: dict[str, ColumnMarkerKind] = {
|
|
202
|
+
"/**ASSERT UNIQUE(": "unique",
|
|
203
|
+
"/**ASSERT NOT NULL UNIQUE(": "key",
|
|
204
|
+
"/**ASSERT PRIMARY KEY(": "key",
|
|
205
|
+
"/**ASSERT NOT NULL(": "not-null",
|
|
206
|
+
"/**DECLARE UNIQUE(": "declared-unique",
|
|
207
|
+
"/**DECLARE NOT NULL UNIQUE(": "declared-key",
|
|
208
|
+
"/**DECLARE PRIMARY KEY(": "declared-key",
|
|
209
|
+
"/**DECLARE NOT NULL(": "declared-not-null",
|
|
210
|
+
"/**ASSERT NOT NULL ELEMENTS(": "not-null-elements",
|
|
211
|
+
"/**DECLARE NOT NULL ELEMENTS(": "declared-not-null-elements",
|
|
212
|
+
"/**ASSERT FOREIGN KEY(": "foreign-key",
|
|
213
|
+
"/**DECLARE FOREIGN KEY(": "declared-foreign-key",
|
|
214
|
+
"/**ASSERT DETERMINES(": "determines",
|
|
215
|
+
"/**DECLARE DETERMINES(": "declared-determines",
|
|
216
|
+
"/**ASSERT ENUM(": "enum",
|
|
217
|
+
"/**DECLARE ENUM(": "declared-enum",
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
# Column marker kinds that are Property Declarations rather than Assertions.
|
|
221
|
+
DECLARED_KINDS: frozenset[ColumnMarkerKind] = frozenset({
|
|
222
|
+
"declared-unique", "declared-key", "declared-not-null", "declared-not-null-elements", "declared-foreign-key",
|
|
223
|
+
"declared-determines", "declared-enum",
|
|
224
|
+
})
|
|
225
|
+
|
|
226
|
+
# Column marker kinds followed by `REFERENCES relation(col, ...)`.
|
|
227
|
+
FOREIGN_KEY_KINDS: frozenset[ColumnMarkerKind] = frozenset({"foreign-key", "declared-foreign-key"})
|
|
228
|
+
|
|
229
|
+
# Column marker kinds whose list is `determinant -> dependent`.
|
|
230
|
+
DETERMINES_KINDS: frozenset[ColumnMarkerKind] = frozenset({"determines", "declared-determines"})
|
|
231
|
+
|
|
232
|
+
# Column marker kinds whose list is `column IN (literal, ...)`.
|
|
233
|
+
ENUM_KINDS: frozenset[ColumnMarkerKind] = frozenset({"enum", "declared-enum"})
|
|
234
|
+
|
|
235
|
+
# How diagnostics name each column marker kind.
|
|
236
|
+
MARKER_NOUNS: dict[ColumnMarkerKind, str] = {
|
|
237
|
+
"unique": "unique set assertion",
|
|
238
|
+
"key": "not null unique assertion",
|
|
239
|
+
"not-null": "not null assertion",
|
|
240
|
+
"declared-unique": "unique set declaration",
|
|
241
|
+
"declared-key": "not null unique declaration",
|
|
242
|
+
"declared-not-null": "not null declaration",
|
|
243
|
+
"not-null-elements": "not null elements assertion",
|
|
244
|
+
"declared-not-null-elements": "not null elements declaration",
|
|
245
|
+
"foreign-key": "foreign key assertion",
|
|
246
|
+
"declared-foreign-key": "foreign key declaration",
|
|
247
|
+
"determines": "functional dependency assertion",
|
|
248
|
+
"declared-determines": "functional dependency declaration",
|
|
249
|
+
"enum": "enum assertion",
|
|
250
|
+
"declared-enum": "enum declaration",
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
# Where resolved column markers are recorded on its Select node.
|
|
254
|
+
_COLUMN_MARKERS_AT = "sqlassert.unique_set_asserted_at"
|
|
255
|
+
|
|
256
|
+
# The source offset and line at which a marker for this Join, Select, or simple
|
|
257
|
+
# CASE would be written: a join marker right before the join's first keyword, a
|
|
258
|
+
# column marker right after the Select's last token, a case marker right before
|
|
259
|
+
# CASE. `suggest` pastes markers there.
|
|
260
|
+
_MARKER_POSITION = "sqlassert.marker_position"
|
|
261
|
+
|
|
262
|
+
# Where a Join, Select, query clause (WHERE, GROUP BY, HAVING, ORDER BY,
|
|
263
|
+
# LIMIT, ...), function call or plain DISTINCT is written: its `(start, end)` source offsets,
|
|
264
|
+
# from its first token to its last (a Select's start only, recorded as
|
|
265
|
+
# `(start, start)`: its end is its marker position). Rewrites place their
|
|
266
|
+
# edits from these and the token stream (`edits.py`).
|
|
267
|
+
_SPAN = "sqlassert.span"
|
|
268
|
+
|
|
269
|
+
# Tokens that end a set operation's operand but not the query: another
|
|
270
|
+
# operator, or the parenthesis around the operand.
|
|
271
|
+
_OPERAND_END_TOKENS = {TokenType.UNION, TokenType.INTERSECT, TokenType.EXCEPT, TokenType.R_PAREN}
|
|
272
|
+
|
|
273
|
+
_COLUMN_MARKER_OPEN_TOKENS = {
|
|
274
|
+
MARKERS[open_]: kind for open_, kind in _COLUMN_MARKER_OPENS.items()
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
_INTEGER = re.compile(r"\d+")
|
|
279
|
+
_DECIMAL = re.compile(r"\d+\.\d*|\.\d+")
|
|
280
|
+
_EXPONENT = re.compile(r"(\d+\.?\d*|\.\d+)[eE][+-]?\d+")
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def written_sql(node: Expr, dialect: str) -> str:
|
|
284
|
+
"""`node` as SQL, `x IS NOT NULL` spelled so: SQLGlot parses it as
|
|
285
|
+
`NOT x IS NULL` and most dialects write it back that way."""
|
|
286
|
+
if node.find(exp.Not) is None:
|
|
287
|
+
return node.sql(dialect=dialect)
|
|
288
|
+
return node.transform(_is_not_null).sql(dialect=dialect)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _is_not_null(node: Expr) -> Expr:
|
|
292
|
+
if isinstance(node, exp.Not) and isinstance(node.this, exp.Is) and not node.this.args.get("negate"):
|
|
293
|
+
return exp.Is(this=node.this.this.copy(), expression=node.this.expression.copy(), negate=True)
|
|
294
|
+
return node
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def literal_value(expression: Expr) -> LiteralValue | None:
|
|
298
|
+
"""The typed value of a string, numeric, or boolean literal, or None for
|
|
299
|
+
any other expression. A numeric literal may be negated."""
|
|
300
|
+
if isinstance(expression, exp.Boolean):
|
|
301
|
+
return LiteralValue(type="boolean", text="TRUE" if expression.this else "FALSE")
|
|
302
|
+
if isinstance(expression, exp.Literal) and expression.is_string:
|
|
303
|
+
return LiteralValue(type="string", text=expression.this)
|
|
304
|
+
negative = isinstance(expression, exp.Neg)
|
|
305
|
+
number = expression.this if negative else expression
|
|
306
|
+
if not isinstance(number, exp.Literal) or number.is_string:
|
|
307
|
+
return None
|
|
308
|
+
text: str = number.this
|
|
309
|
+
if _INTEGER.fullmatch(text):
|
|
310
|
+
# Leading zeros change neither the value nor the SQL type.
|
|
311
|
+
text = str(int(text))
|
|
312
|
+
negative = negative and text != "0"
|
|
313
|
+
elif _EXPONENT.fullmatch(text):
|
|
314
|
+
text = text.lower()
|
|
315
|
+
elif not _DECIMAL.fullmatch(text):
|
|
316
|
+
return None
|
|
317
|
+
return LiteralValue(type="numeric", text="-" + text if negative else text)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
class ColumnMarker(NamedTuple):
|
|
321
|
+
"""One column marker as written: `kind` is a value of `_COLUMN_MARKER_OPENS`.
|
|
322
|
+
|
|
323
|
+
A Foreign Key marker also names the referenced relation, as written, and
|
|
324
|
+
its referenced columns, paired with `columns` by position. A Functional
|
|
325
|
+
Dependency marker's `columns` are its determinant and `dependent` the
|
|
326
|
+
columns after `->`. An Enumerated Domain marker's one column is `columns`
|
|
327
|
+
and its distinct typed literals, in the order written, are `values`.
|
|
328
|
+
"""
|
|
329
|
+
|
|
330
|
+
kind: ColumnMarkerKind
|
|
331
|
+
columns: tuple[str, ...]
|
|
332
|
+
span: Span
|
|
333
|
+
referenced_relation: str | None = None
|
|
334
|
+
referenced_columns: tuple[str, ...] = ()
|
|
335
|
+
dependent: tuple[str, ...] = ()
|
|
336
|
+
values: tuple[LiteralValue, ...] = ()
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
class UnattachedMarker(ParseError):
|
|
340
|
+
"""A marker that does not mark a join."""
|
|
341
|
+
|
|
342
|
+
def __init__(self, message: str, span: Span, text: str) -> None:
|
|
343
|
+
super().__init__(message)
|
|
344
|
+
self.span = span
|
|
345
|
+
self.text = text
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
# Dialects whose set operators share one precedence, read left to right. The
|
|
349
|
+
# others follow the standard: INTERSECT binds tighter than UNION and EXCEPT.
|
|
350
|
+
_FLAT_SET_OPERATION_DIALECTS = frozenset({"oracle"})
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _intersect_first(chain: Expr | None) -> Expr | None:
|
|
354
|
+
"""A left-to-right chain of set operations, with INTERSECT bound first.
|
|
355
|
+
|
|
356
|
+
SQLGlot reads `a UNION ALL b INTERSECT c` as `(a UNION ALL b) INTERSECT c`;
|
|
357
|
+
standard SQL (and DuckDB, Postgres) means `a UNION ALL (b INTERSECT c)`.
|
|
358
|
+
Only the chain's left spine is flattened: a parenthesized operand is a
|
|
359
|
+
Subquery and keeps its own grouping. ORDER BY and LIMIT stay on the top.
|
|
360
|
+
"""
|
|
361
|
+
if not isinstance(chain, exp.SetOperation):
|
|
362
|
+
return chain
|
|
363
|
+
operations: list[exp.SetOperation] = []
|
|
364
|
+
node: Expr = chain
|
|
365
|
+
while isinstance(node, exp.SetOperation):
|
|
366
|
+
operations.append(node)
|
|
367
|
+
node = node.this
|
|
368
|
+
operations.reverse()
|
|
369
|
+
if not any(isinstance(operation, exp.Intersect) for operation in operations[1:]) or all(
|
|
370
|
+
isinstance(operation, exp.Intersect) for operation in operations
|
|
371
|
+
):
|
|
372
|
+
return chain
|
|
373
|
+
modifiers = {key: chain.args[key] for key in chain.args if key not in {"this", "expression", "distinct", "by_name", "side", "kind", "on"} and chain.args[key] is not None}
|
|
374
|
+
for key in modifiers:
|
|
375
|
+
chain.set(key, None)
|
|
376
|
+
# Fold each INTERSECT into its left neighbour's right operand, then chain the rest left to right.
|
|
377
|
+
terms: list[Expr] = [node]
|
|
378
|
+
joiners: list[exp.SetOperation] = []
|
|
379
|
+
for operation in operations:
|
|
380
|
+
right = operation.expression
|
|
381
|
+
if isinstance(operation, exp.Intersect):
|
|
382
|
+
operation.set("this", terms[-1])
|
|
383
|
+
operation.set("expression", right)
|
|
384
|
+
terms[-1] = operation
|
|
385
|
+
else:
|
|
386
|
+
terms.append(right)
|
|
387
|
+
joiners.append(operation)
|
|
388
|
+
result = terms[0]
|
|
389
|
+
for operation, right in zip(joiners, terms[1:]):
|
|
390
|
+
operation.set("this", result)
|
|
391
|
+
operation.set("expression", right)
|
|
392
|
+
result = operation
|
|
393
|
+
for key, value in modifiers.items():
|
|
394
|
+
result.set(key, value)
|
|
395
|
+
return result
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
@lru_cache(maxsize=None)
|
|
399
|
+
def sqlassert_dialect(base: str) -> type[Dialect]:
|
|
400
|
+
"""The named dialect, plus Property Markers as real syntax.
|
|
401
|
+
|
|
402
|
+
Cached because SQLGlot registers every dialect class by name, so one class
|
|
403
|
+
per base dialect must be built once rather than per analysis.
|
|
404
|
+
"""
|
|
405
|
+
parent = type(Dialect.get_or_raise(base))
|
|
406
|
+
|
|
407
|
+
# `Dialect` does not declare `Tokenizer`/`Parser` as class attributes --
|
|
408
|
+
# every concrete dialect sets its own, so the base class's static type
|
|
409
|
+
# cannot know they exist. This is exactly the private-API coupling
|
|
410
|
+
# documented below, not a type worth narrowing further.
|
|
411
|
+
class _Tokenizer(parent.Tokenizer): # ty: ignore[missing-attribute]
|
|
412
|
+
KEYWORDS = {**parent.Tokenizer.KEYWORDS, **MARKERS} # ty: ignore[missing-attribute]
|
|
413
|
+
|
|
414
|
+
# This hooks SQLGlot's private API: `Tokenizer.KEYWORDS`, `_parse_join`,
|
|
415
|
+
# `_match`, `_prev`, `_curr`. It is the best seam available — SQLGlot exposes
|
|
416
|
+
# no public way to extend a grammar — and it is deliberately preferred to the
|
|
417
|
+
# alternatives we tried: rewriting the SQL before parsing, and matching
|
|
418
|
+
# markers to joins ourselves by source offset. Both of those put the
|
|
419
|
+
# correctness of the marker-to-join mapping in our own code, where SQLGlot's
|
|
420
|
+
# comment placement varies with aliasing, whitespace, and the preceding
|
|
421
|
+
# predicate. Here the grammar decides, so it cannot drift out of step.
|
|
422
|
+
#
|
|
423
|
+
# The coupling breaks in two ways, and only one of them is safe by itself.
|
|
424
|
+
# If `_parse_join` is renamed or changes arity, this override stops running,
|
|
425
|
+
# the marker token is left with no rule to consume it, and parsing fails —
|
|
426
|
+
# loudly, and with nothing proved. But if `KEYWORDS` stops applying, the
|
|
427
|
+
# marker stays an ordinary comment and simply vanishes, which would leave a
|
|
428
|
+
# program reporting as proved. `_unresolved_markers` exists for that case;
|
|
429
|
+
# do not remove it, and do not add a fallback that carries on without the
|
|
430
|
+
# hook.
|
|
431
|
+
class _Parser(parent.Parser): # ty: ignore[missing-attribute]
|
|
432
|
+
# The case marker is a primary expression of its own, so it attaches
|
|
433
|
+
# to whatever expression follows it, which must be a simple CASE.
|
|
434
|
+
PRIMARY_PARSERS = {
|
|
435
|
+
**parent.Parser.PRIMARY_PARSERS, # ty: ignore[missing-attribute]
|
|
436
|
+
SqlassertToken.SQLASSERT_EXHAUSTIVE: lambda self, token: self._parse_exhaustive_case(token),
|
|
437
|
+
}
|
|
438
|
+
# Each query clause records where it is written (`_SPAN`).
|
|
439
|
+
QUERY_MODIFIER_PARSERS = {
|
|
440
|
+
token_type: _spanned_modifier(parse)
|
|
441
|
+
for token_type, parse in parent.Parser.QUERY_MODIFIER_PARSERS.items() # ty: ignore[missing-attribute]
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
def reset(self) -> None:
|
|
445
|
+
super().reset()
|
|
446
|
+
# The first token of each Select being parsed, innermost last.
|
|
447
|
+
self._query_starts: list[Token | None] = []
|
|
448
|
+
|
|
449
|
+
def expression(self, instance, token=None, comments=None):
|
|
450
|
+
# A plain DISTINCT is built right after its keyword is consumed.
|
|
451
|
+
if (
|
|
452
|
+
isinstance(instance, exp.Distinct) and instance.args.get("on") is None and self._prev is not None
|
|
453
|
+
and self._prev.token_type in self.DISTINCT_TOKENS
|
|
454
|
+
):
|
|
455
|
+
instance.meta[_SPAN] = (self._prev.start, self._prev.end + 1)
|
|
456
|
+
return super().expression(instance, token, comments)
|
|
457
|
+
def _span(self, token: Token) -> Span:
|
|
458
|
+
"""Where `token` is written in the SQL being parsed."""
|
|
459
|
+
return Span.of(self.sql, token.start, token.end + 1)
|
|
460
|
+
|
|
461
|
+
def _misplaced_case_marker(self, marker: Token) -> UnattachedMarker:
|
|
462
|
+
span = self._span(marker)
|
|
463
|
+
return UnattachedMarker(
|
|
464
|
+
f"the exhaustive assertion on line {span.line} is not followed by CASE; "
|
|
465
|
+
"it must sit immediately before a simple CASE expression",
|
|
466
|
+
span,
|
|
467
|
+
marker.text,
|
|
468
|
+
)
|
|
469
|
+
|
|
470
|
+
def _parse_exhaustive_case(self, marker: Token) -> exp.Case:
|
|
471
|
+
"""The simple CASE a case marker precedes.
|
|
472
|
+
|
|
473
|
+
Its WHEN values are distinct, non-null string, numeric, and boolean
|
|
474
|
+
literals: each is compared with the operand, so an arm matches a
|
|
475
|
+
domain member exactly when it is that literal.
|
|
476
|
+
"""
|
|
477
|
+
span = self._span(marker)
|
|
478
|
+
|
|
479
|
+
def malformed(problem: str) -> UnattachedMarker:
|
|
480
|
+
return UnattachedMarker(f"the exhaustive assertion on line {span.line} {problem}", span, marker.text)
|
|
481
|
+
|
|
482
|
+
if not self._match(TokenType.CASE):
|
|
483
|
+
raise self._misplaced_case_marker(marker)
|
|
484
|
+
case = self._parse_case()
|
|
485
|
+
if not isinstance(case, exp.Case):
|
|
486
|
+
raise self._misplaced_case_marker(marker)
|
|
487
|
+
if case.this is None:
|
|
488
|
+
raise malformed("marks a searched CASE; only a simple CASE operand WHEN value ... can be exhaustive")
|
|
489
|
+
values: list[LiteralValue] = []
|
|
490
|
+
for arm in case.args.get("ifs") or ():
|
|
491
|
+
when = arm.this
|
|
492
|
+
if isinstance(when, exp.Null):
|
|
493
|
+
raise malformed("has a WHEN NULL arm, which matches nothing; NOT NULL governs NULL")
|
|
494
|
+
value = literal_value(when)
|
|
495
|
+
if value is None:
|
|
496
|
+
raise malformed(f"has WHEN {when.sql(dialect=self.dialect)}, which is not a string, numeric, or boolean literal")
|
|
497
|
+
if value in values:
|
|
498
|
+
raise malformed(f"lists WHEN {value.sql()} more than once")
|
|
499
|
+
values.append(value)
|
|
500
|
+
case.meta[_EXHAUSTIVE_AT] = span
|
|
501
|
+
return case
|
|
502
|
+
|
|
503
|
+
def _parse_case(self, *args, **kwargs):
|
|
504
|
+
"""Record where a simple CASE's marker would be written: right
|
|
505
|
+
before its CASE keyword, already consumed here."""
|
|
506
|
+
start = self._prev
|
|
507
|
+
case = super()._parse_case(*args, **kwargs)
|
|
508
|
+
if isinstance(case, exp.Case) and case.this is not None and start is not None:
|
|
509
|
+
case.meta[_MARKER_POSITION] = (start.start, start.line)
|
|
510
|
+
return case
|
|
511
|
+
|
|
512
|
+
def _parse_join(self, *args, **kwargs):
|
|
513
|
+
if self._curr is not None and self._curr.token_type is SqlassertToken.SQLASSERT_EXHAUSTIVE:
|
|
514
|
+
raise self._misplaced_case_marker(self._curr)
|
|
515
|
+
if self._curr is None or self._curr.token_type not in JOIN_MARKER_KINDS:
|
|
516
|
+
start = self._curr
|
|
517
|
+
join = super()._parse_join(*args, **kwargs)
|
|
518
|
+
# A comma join has no JOIN keyword a marker could precede.
|
|
519
|
+
if join is not None and start is not None and start.token_type is not TokenType.COMMA:
|
|
520
|
+
join.meta[_MARKER_POSITION] = (start.start, start.line)
|
|
521
|
+
if self._prev is not None:
|
|
522
|
+
join.meta[_SPAN] = (start.start, self._prev.end + 1)
|
|
523
|
+
return join
|
|
524
|
+
|
|
525
|
+
kind = JOIN_MARKER_KINDS[self._curr.token_type]
|
|
526
|
+
self._advance()
|
|
527
|
+
span = self._span(self._prev)
|
|
528
|
+
unattached = UnattachedMarker(
|
|
529
|
+
f"the {JOIN_MARKER_NOUNS[kind]} marker on line {span.line} is not followed by the JOIN keyword",
|
|
530
|
+
span,
|
|
531
|
+
self._prev.text,
|
|
532
|
+
)
|
|
533
|
+
|
|
534
|
+
# A comma join carries no JOIN keyword to mark, and multiplies rows
|
|
535
|
+
# by definition. Marking one is a mistake, not an assertion.
|
|
536
|
+
if self._curr is not None and self._curr.token_type is TokenType.COMMA:
|
|
537
|
+
raise unattached
|
|
538
|
+
|
|
539
|
+
join = super()._parse_join(*args, **kwargs)
|
|
540
|
+
if join is None:
|
|
541
|
+
raise unattached
|
|
542
|
+
|
|
543
|
+
join.meta[_ASSERTED_AT] = span
|
|
544
|
+
join.meta[_JOIN_MARKER_KIND] = kind
|
|
545
|
+
return join
|
|
546
|
+
|
|
547
|
+
def _parse_select_query(self, *args, **kwargs):
|
|
548
|
+
"""Consume every trailing column marker immediately
|
|
549
|
+
after building a Select node -- the one production common to a
|
|
550
|
+
Root Select, a CTE definition, a view body, and a subquery, so a
|
|
551
|
+
marker means the same thing regardless of which of these it sits
|
|
552
|
+
on. Only fires on an actual `exp.Select`: this method is also
|
|
553
|
+
reached, recursively, while wrapping a parenthesized derived table
|
|
554
|
+
into an `exp.Subquery`, which has no trailing marker of its own to
|
|
555
|
+
consume.
|
|
556
|
+
"""
|
|
557
|
+
self._query_starts.append(self._curr)
|
|
558
|
+
from_first = self._curr is not None and self._curr.token_type is TokenType.FROM
|
|
559
|
+
try:
|
|
560
|
+
result = self._parse_select_query_markers(*args, **kwargs)
|
|
561
|
+
finally:
|
|
562
|
+
self._query_starts.pop()
|
|
563
|
+
if from_first:
|
|
564
|
+
_hoist_from_first_joins(result)
|
|
565
|
+
return result
|
|
566
|
+
|
|
567
|
+
def _parse_select_query_markers(self, *args, **kwargs):
|
|
568
|
+
result = super()._parse_select_query(*args, **kwargs)
|
|
569
|
+
if not isinstance(result, exp.Select):
|
|
570
|
+
return result
|
|
571
|
+
right_operand = not kwargs.get("parse_set_operation", True)
|
|
572
|
+
if right_operand:
|
|
573
|
+
# A set operation's right operand: no set operation is tried after it.
|
|
574
|
+
self._record_marker_position(result)
|
|
575
|
+
# A marker after it marks it when another operator, or the
|
|
576
|
+
# parenthesis closing it, follows; after the last token of the
|
|
577
|
+
# query, it marks the whole query.
|
|
578
|
+
index = self._index
|
|
579
|
+
found = self._parse_column_markers()
|
|
580
|
+
if found and not (self._curr is not None and self._curr.token_type in _OPERAND_END_TOKENS):
|
|
581
|
+
self._retreat(index)
|
|
582
|
+
found = []
|
|
583
|
+
if found:
|
|
584
|
+
result.meta[_COLUMN_MARKERS_AT] = found
|
|
585
|
+
return result
|
|
586
|
+
|
|
587
|
+
found = self._parse_column_markers()
|
|
588
|
+
if found:
|
|
589
|
+
result.meta[_COLUMN_MARKERS_AT] = found
|
|
590
|
+
|
|
591
|
+
# `super()._parse_select_query` already tried, and gave up, on
|
|
592
|
+
# attaching a following UNION/INTERSECT/EXCEPT to this same
|
|
593
|
+
# Select before returning -- its own last step runs before a
|
|
594
|
+
# trailing marker exists to get in the way, so the marker token
|
|
595
|
+
# sitting where it looked for a set-operation keyword reads as
|
|
596
|
+
# "no set operation here". Now that the marker is consumed, retry:
|
|
597
|
+
# a no-op if nothing follows, since `_parse_set_operations` only
|
|
598
|
+
# advances the cursor on an actual match.
|
|
599
|
+
return self._parse_set_operations(result) or result
|
|
600
|
+
|
|
601
|
+
def _parse_column_markers(self) -> list[ColumnMarker]:
|
|
602
|
+
"""Every column marker at the cursor, consumed."""
|
|
603
|
+
found: list[ColumnMarker] = []
|
|
604
|
+
while self._curr is not None and self._curr.token_type in _COLUMN_MARKER_OPEN_TOKENS:
|
|
605
|
+
kind = _COLUMN_MARKER_OPEN_TOKENS[self._curr.token_type]
|
|
606
|
+
open_ = self._curr
|
|
607
|
+
span = self._span(open_)
|
|
608
|
+
self._advance()
|
|
609
|
+
|
|
610
|
+
dependent: tuple[str, ...] = ()
|
|
611
|
+
values: tuple[LiteralValue, ...] = ()
|
|
612
|
+
if kind in DETERMINES_KINDS:
|
|
613
|
+
names, dependent = self._parse_marker_dependency(kind, span)
|
|
614
|
+
elif kind in ENUM_KINDS:
|
|
615
|
+
names, values = self._parse_marker_domain(kind, span)
|
|
616
|
+
else:
|
|
617
|
+
names = self._parse_marker_columns(kind, span)
|
|
618
|
+
referenced_relation, referenced_columns = None, ()
|
|
619
|
+
if kind in FOREIGN_KEY_KINDS:
|
|
620
|
+
referenced_relation, referenced_columns = self._parse_marker_reference(kind, span, len(names))
|
|
621
|
+
if not self._match(SqlassertToken.SQLASSERT_MARKER_CLOSE):
|
|
622
|
+
raise UnattachedMarker(
|
|
623
|
+
f"the {MARKER_NOUNS[kind]} on line {span.line} is not closed with **/", span, self._prev.text
|
|
624
|
+
)
|
|
625
|
+
|
|
626
|
+
whole = Span.of(self.sql, open_.start, self._prev.end + 1)
|
|
627
|
+
found.append(ColumnMarker(kind, names, whole, referenced_relation, referenced_columns, dependent, values))
|
|
628
|
+
if self._curr is not None and self._curr.token_type is SqlassertToken.SQLASSERT_EXHAUSTIVE:
|
|
629
|
+
raise self._misplaced_case_marker(self._curr)
|
|
630
|
+
return found
|
|
631
|
+
|
|
632
|
+
def _parse_set_operations(self, this, *args, **kwargs):
|
|
633
|
+
"""Record where a Select ends: the first time set operations are
|
|
634
|
+
tried after it, before any trailing marker is consumed. This is
|
|
635
|
+
also the only point that sees the left member of a set operation
|
|
636
|
+
as a Select of its own. The chain comes back with INTERSECT bound
|
|
637
|
+
first, as the dialect reads it.
|
|
638
|
+
"""
|
|
639
|
+
self._record_marker_position(this)
|
|
640
|
+
result = super()._parse_set_operations(this, *args, **kwargs)
|
|
641
|
+
result = result if base in _FLAT_SET_OPERATION_DIALECTS else _intersect_first(result)
|
|
642
|
+
if isinstance(result, exp.SetOperation) and result is not this:
|
|
643
|
+
# After the last token of the query: the whole query's markers.
|
|
644
|
+
if self._prev is not None:
|
|
645
|
+
result.meta[_MARKER_POSITION] = (self._prev.end + 1, self._prev.line)
|
|
646
|
+
found = self._parse_column_markers()
|
|
647
|
+
if found:
|
|
648
|
+
result.meta[_COLUMN_MARKERS_AT] = found
|
|
649
|
+
return result
|
|
650
|
+
|
|
651
|
+
def _record_marker_position(self, this) -> None:
|
|
652
|
+
if isinstance(this, exp.Select) and _MARKER_POSITION not in this.meta and self._prev is not None:
|
|
653
|
+
this.meta[_MARKER_POSITION] = (self._prev.end + 1, self._prev.line)
|
|
654
|
+
# Still inside the call that parsed it: its first token is on top.
|
|
655
|
+
start = self._query_starts[-1] if self._query_starts else None
|
|
656
|
+
if start is not None:
|
|
657
|
+
this.meta[_SPAN] = (start.start, start.start)
|
|
658
|
+
|
|
659
|
+
def _parse_function(self, *args, **kwargs):
|
|
660
|
+
start = self._curr
|
|
661
|
+
function = super()._parse_function(*args, **kwargs)
|
|
662
|
+
# A call written with parentheses: from its name to its `)`, or
|
|
663
|
+
# to the IGNORE or RESPECT NULLS after it.
|
|
664
|
+
if isinstance(function, Expr) and start is not None and self._prev is not None and self._prev is not start:
|
|
665
|
+
function.meta[_SPAN] = (start.start, self._prev.end + 1)
|
|
666
|
+
return function
|
|
667
|
+
|
|
668
|
+
def _spanned(self, parse):
|
|
669
|
+
"""`parse(self)`'s `(key, clause)`, the clause's `_SPAN` recorded."""
|
|
670
|
+
start = self._curr
|
|
671
|
+
key, clause = parse(self)
|
|
672
|
+
if isinstance(clause, Expr) and start is not None and self._prev is not None:
|
|
673
|
+
clause.meta[_SPAN] = (start.start, self._prev.end + 1)
|
|
674
|
+
return key, clause
|
|
675
|
+
|
|
676
|
+
def _marker_identifier(self, identifier: exp.Identifier, span: Span) -> str:
|
|
677
|
+
if base == "postgres" and identifier.quoted and identifier.name != identifier.name.lower():
|
|
678
|
+
raise UnattachedMarker("case-sensitive quoted PostgreSQL identifiers are not supported", span, self._prev.text)
|
|
679
|
+
return identifier.name
|
|
680
|
+
|
|
681
|
+
def _parse_marker_columns(self, kind: ColumnMarkerKind, span: Span) -> tuple[str, ...]:
|
|
682
|
+
"""A marker's column list after its opening parenthesis, through the closing one."""
|
|
683
|
+
columns = self._parse_csv(self._parse_id_var)
|
|
684
|
+
if not columns:
|
|
685
|
+
raise UnattachedMarker(f"the {MARKER_NOUNS[kind]} on line {span.line} names no columns", span, self._prev.text)
|
|
686
|
+
names = tuple(self._marker_identifier(column, span) for column in columns)
|
|
687
|
+
if len({name.lower() for name in names}) != len(names):
|
|
688
|
+
raise UnattachedMarker(
|
|
689
|
+
f"the {MARKER_NOUNS[kind]} on line {span.line} names the same column more than once",
|
|
690
|
+
span,
|
|
691
|
+
self._prev.text,
|
|
692
|
+
)
|
|
693
|
+
if not self._match(TokenType.R_PAREN):
|
|
694
|
+
raise UnattachedMarker(
|
|
695
|
+
f"the {MARKER_NOUNS[kind]} on line {span.line} is missing its closing parenthesis",
|
|
696
|
+
span,
|
|
697
|
+
self._prev.text,
|
|
698
|
+
)
|
|
699
|
+
return names
|
|
700
|
+
|
|
701
|
+
def _parse_marker_dependency(self, kind: ColumnMarkerKind, span: Span) -> tuple[tuple[str, ...], tuple[str, ...]]:
|
|
702
|
+
"""`determinant -> dependent`, each a column list, through the closing parenthesis."""
|
|
703
|
+
determinant = tuple(self._marker_identifier(column, span) for column in self._parse_csv(self._parse_id_var))
|
|
704
|
+
if not determinant or not self._match(TokenType.ARROW):
|
|
705
|
+
raise UnattachedMarker(
|
|
706
|
+
f"the {MARKER_NOUNS[kind]} on line {span.line} must list columns, then ->, then the columns they determine",
|
|
707
|
+
span,
|
|
708
|
+
self._prev.text,
|
|
709
|
+
)
|
|
710
|
+
dependent = self._parse_marker_columns(kind, span)
|
|
711
|
+
if len({name.lower() for name in determinant}) != len(determinant):
|
|
712
|
+
raise UnattachedMarker(
|
|
713
|
+
f"the {MARKER_NOUNS[kind]} on line {span.line} names the same column more than once",
|
|
714
|
+
span,
|
|
715
|
+
self._prev.text,
|
|
716
|
+
)
|
|
717
|
+
return determinant, dependent
|
|
718
|
+
|
|
719
|
+
def _parse_marker_domain(self, kind: ColumnMarkerKind, span: Span) -> tuple[tuple[str, ...], tuple[LiteralValue, ...]]:
|
|
720
|
+
"""`column IN (literal, ...)`, through the marker's closing parenthesis.
|
|
721
|
+
|
|
722
|
+
Members are distinct, non-null string, numeric, and boolean literals.
|
|
723
|
+
"""
|
|
724
|
+
|
|
725
|
+
def malformed(problem: str) -> UnattachedMarker:
|
|
726
|
+
return UnattachedMarker(f"the {MARKER_NOUNS[kind]} on line {span.line} {problem}", span, self._prev.text)
|
|
727
|
+
|
|
728
|
+
column = self._parse_id_var(any_token=False)
|
|
729
|
+
if column is None or not self._match(TokenType.IN) or not self._match(TokenType.L_PAREN):
|
|
730
|
+
raise malformed("must be written as ENUM(column IN ('value', ...))")
|
|
731
|
+
expressions = tuple(self._parse_csv(self._parse_bitwise))
|
|
732
|
+
if not self._match(TokenType.R_PAREN) or not self._match(TokenType.R_PAREN):
|
|
733
|
+
raise malformed("must be written as ENUM(column IN ('value', ...))")
|
|
734
|
+
if not expressions:
|
|
735
|
+
raise malformed("lists no values")
|
|
736
|
+
values: list[LiteralValue] = []
|
|
737
|
+
for expression in expressions:
|
|
738
|
+
if isinstance(expression, exp.Null):
|
|
739
|
+
raise malformed("lists NULL; NULL is never in an Enumerated Domain, and NOT NULL governs it")
|
|
740
|
+
value = literal_value(expression)
|
|
741
|
+
if value is None:
|
|
742
|
+
raise malformed(f"lists {expression.sql(dialect=self.dialect)}, which is not a string, numeric, or boolean literal")
|
|
743
|
+
if value in values:
|
|
744
|
+
raise malformed(f"lists {value.sql()} more than once")
|
|
745
|
+
values.append(value)
|
|
746
|
+
return (self._marker_identifier(column, span),), tuple(values)
|
|
747
|
+
|
|
748
|
+
def _parse_marker_reference(self, kind: ColumnMarkerKind, span: Span, count: int) -> tuple[str, tuple[str, ...]]:
|
|
749
|
+
"""`REFERENCES relation(col, ...)`, pairing `count` columns by position."""
|
|
750
|
+
missing = UnattachedMarker(
|
|
751
|
+
f"the {MARKER_NOUNS[kind]} on line {span.line} must continue with REFERENCES relation(column, ...)",
|
|
752
|
+
span,
|
|
753
|
+
self._prev.text,
|
|
754
|
+
)
|
|
755
|
+
if not self._match(TokenType.REFERENCES):
|
|
756
|
+
raise missing
|
|
757
|
+
parts = [self._parse_id_var(any_token=False)]
|
|
758
|
+
while parts[-1] is not None and self._match(TokenType.DOT):
|
|
759
|
+
parts.append(self._parse_id_var(any_token=False))
|
|
760
|
+
if None in parts or not self._match(TokenType.L_PAREN):
|
|
761
|
+
raise missing
|
|
762
|
+
names = [self._marker_identifier(part, span) for part in parts if part is not None]
|
|
763
|
+
if any("." in name for name in names):
|
|
764
|
+
raise UnattachedMarker("dots inside quoted relation identifiers are not supported", span, self._prev.text)
|
|
765
|
+
relation = ".".join(names)
|
|
766
|
+
columns = self._parse_marker_columns(kind, span)
|
|
767
|
+
if len(columns) != count:
|
|
768
|
+
raise UnattachedMarker(
|
|
769
|
+
f"the {MARKER_NOUNS[kind]} on line {span.line} pairs {count} column(s) with {len(columns)} "
|
|
770
|
+
f"referenced column(s) of {relation}",
|
|
771
|
+
span,
|
|
772
|
+
self._prev.text,
|
|
773
|
+
)
|
|
774
|
+
return relation, columns
|
|
775
|
+
|
|
776
|
+
return type(
|
|
777
|
+
f"SqlAssert{parent.__name__}",
|
|
778
|
+
(parent,),
|
|
779
|
+
{"Tokenizer": _Tokenizer, "Parser": _Parser},
|
|
780
|
+
)
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
@dataclass(frozen=True)
|
|
784
|
+
class ParsedProgram:
|
|
785
|
+
"""One SQL Program. Sequence arguments may be any iterable; what is stored
|
|
786
|
+
is always an immutable tuple."""
|
|
787
|
+
|
|
788
|
+
# CREATE and ALTER TABLE statements, in program order.
|
|
789
|
+
create_statements: tuple[Expr, ...] = ()
|
|
790
|
+
root_select: exp.Query | None = None
|
|
791
|
+
diagnostics: tuple[Diagnostic, ...] = ()
|
|
792
|
+
# The SQL text and its tokens, from which Rewrites place their edits.
|
|
793
|
+
sql: str = ""
|
|
794
|
+
tokens: tuple[Token, ...] = ()
|
|
795
|
+
|
|
796
|
+
def __post_init__(self) -> None:
|
|
797
|
+
object.__setattr__(self, "create_statements", tuple(self.create_statements))
|
|
798
|
+
object.__setattr__(self, "diagnostics", tuple(self.diagnostics))
|
|
799
|
+
object.__setattr__(self, "tokens", tuple(self.tokens))
|
|
800
|
+
|
|
801
|
+
|
|
802
|
+
class SqlParser:
|
|
803
|
+
"""Parses SQL text of one dialect into a SQL Program."""
|
|
804
|
+
|
|
805
|
+
def __init__(self, dialect: str) -> None:
|
|
806
|
+
self.dialect = dialect
|
|
807
|
+
self.dialect_class = sqlassert_dialect(dialect)
|
|
808
|
+
|
|
809
|
+
def parse(self, sql: str) -> ParsedProgram:
|
|
810
|
+
# Reported first, and on every path: a mistyped marker is invisible to
|
|
811
|
+
# the grammar, so nothing later in parsing can notice it.
|
|
812
|
+
dialect = self.dialect_class()
|
|
813
|
+
try:
|
|
814
|
+
tokens = dialect.tokenize(sql)
|
|
815
|
+
except SqlglotError as error:
|
|
816
|
+
return ParsedProgram(diagnostics=(*_unrecognized_markers(sql, _marker_shapes(sql)), self._unparseable(sql, error)))
|
|
817
|
+
shapes = _marker_shapes(sql, tokens)
|
|
818
|
+
diagnostics = _unrecognized_markers(sql, shapes)
|
|
819
|
+
try:
|
|
820
|
+
statements = [statement for statement in dialect.parser().parse(tokens, sql) if statement]
|
|
821
|
+
except UnattachedMarker as error:
|
|
822
|
+
return ParsedProgram(diagnostics=(*diagnostics, self._unattached(error)))
|
|
823
|
+
except SqlglotError as error:
|
|
824
|
+
return ParsedProgram(diagnostics=(*diagnostics, self._unparseable(sql, error)))
|
|
825
|
+
|
|
826
|
+
creates: list[Expr] = []
|
|
827
|
+
selects: list[exp.Query] = []
|
|
828
|
+
|
|
829
|
+
for statement in statements:
|
|
830
|
+
if isinstance(statement, exp.Create) or _is_alter_table(statement):
|
|
831
|
+
creates.append(statement)
|
|
832
|
+
elif isinstance(statement, exp.Query):
|
|
833
|
+
selects.append(statement)
|
|
834
|
+
else:
|
|
835
|
+
diagnostics.append(
|
|
836
|
+
Diagnostic(
|
|
837
|
+
diag.UNSUPPORTED_STATEMENT,
|
|
838
|
+
f"statement is not a create statement or a root select: {statement.sql(dialect=self.dialect)}",
|
|
839
|
+
)
|
|
840
|
+
)
|
|
841
|
+
|
|
842
|
+
# A marker only becomes an assertion if the dialect recognised it, so
|
|
843
|
+
# reconcile what the source contains against what parsing produced.
|
|
844
|
+
diagnostics.extend(_unresolved_markers(sql, statements, shapes))
|
|
845
|
+
diagnostics.extend(
|
|
846
|
+
Diagnostic(
|
|
847
|
+
diag.UNSUPPORTED_NATURAL_JOIN, "NATURAL JOIN is unsupported and an anti-pattern; write an explicit JOIN with ON or USING",
|
|
848
|
+
Origin(SQL, join.sql(dialect=self.dialect), min((node.meta["line"] for node in join.walk() if "line" in node.meta), default=None)),
|
|
849
|
+
)
|
|
850
|
+
for statement in statements for join in statement.find_all(exp.Join) if join.args.get("method") == "NATURAL"
|
|
851
|
+
)
|
|
852
|
+
|
|
853
|
+
if len(selects) > 1:
|
|
854
|
+
diagnostics.append(
|
|
855
|
+
Diagnostic(
|
|
856
|
+
diag.MULTIPLE_ROOT_SELECTS,
|
|
857
|
+
f"a SQL program allows at most one root select, found {len(selects)}",
|
|
858
|
+
)
|
|
859
|
+
)
|
|
860
|
+
return ParsedProgram(tuple(creates), None, tuple(diagnostics), sql, tuple(tokens))
|
|
861
|
+
|
|
862
|
+
return ParsedProgram(tuple(creates), selects[0] if selects else None, tuple(diagnostics), sql, tuple(tokens))
|
|
863
|
+
|
|
864
|
+
def _unattached(self, error: UnattachedMarker) -> Diagnostic:
|
|
865
|
+
return Diagnostic(diag.UNATTACHED_MARKER, str(error), Origin.marked(error.text, error.span))
|
|
866
|
+
|
|
867
|
+
def _unparseable(self, sql: str, error: SqlglotError) -> Diagnostic:
|
|
868
|
+
"""A parse failure, naming a marker when the program contains one.
|
|
869
|
+
|
|
870
|
+
A marker somewhere its rule never runs breaks the grammar outright,
|
|
871
|
+
and the reader should not have to hunt for SQL that is not broken.
|
|
872
|
+
"""
|
|
873
|
+
marker = self._marker_token(sql)
|
|
874
|
+
if marker is None:
|
|
875
|
+
return Diagnostic(diag.SQL_PARSE_FAILED, f"SQL could not be parsed: {error}")
|
|
876
|
+
span = Span.of(sql, marker.start, marker.end + 1)
|
|
877
|
+
return Diagnostic(
|
|
878
|
+
diag.SQL_PARSE_FAILED,
|
|
879
|
+
f"SQL could not be parsed, and a marker is on line {span.line}: {error}",
|
|
880
|
+
Origin.marked(marker.text, span),
|
|
881
|
+
)
|
|
882
|
+
|
|
883
|
+
def _marker_token(self, sql: str) -> Token | None:
|
|
884
|
+
try:
|
|
885
|
+
tokens = self.dialect_class.Tokenizer().tokenize(sql) # ty: ignore[missing-attribute]
|
|
886
|
+
except SqlglotError:
|
|
887
|
+
return None
|
|
888
|
+
return next(
|
|
889
|
+
(token for token in tokens if token.token_type in _FIXED_MARKER_TOKENS),
|
|
890
|
+
None,
|
|
891
|
+
)
|
|
892
|
+
|
|
893
|
+
|
|
894
|
+
def _is_recognized_marker(text: str) -> bool:
|
|
895
|
+
"""Whether `text` (a whole `/**...*/`-shaped span) is a marker this
|
|
896
|
+
dialect's grammar actually tokenizes -- a join marker exactly,
|
|
897
|
+
or a column marker's fixed open literal followed by
|
|
898
|
+
its close, with a variable column list in between that this text-level
|
|
899
|
+
check does not itself validate; the grammar does that once it parses.
|
|
900
|
+
|
|
901
|
+
Whitespace runs collapse to one space because the tokenizer matches a
|
|
902
|
+
multi-word literal such as `ASSERT UNIQUE` across any whitespace run.
|
|
903
|
+
"""
|
|
904
|
+
upper = re.sub(r"\s+", " ", text.upper())
|
|
905
|
+
if upper in MARKERS:
|
|
906
|
+
return True
|
|
907
|
+
return upper.endswith("**/") and any(upper.startswith(open_) for open_ in _COLUMN_MARKER_OPENS)
|
|
908
|
+
|
|
909
|
+
|
|
910
|
+
def _unrecognized_markers(sql: str, shapes: list[re.Match[str]]) -> list[Diagnostic]:
|
|
911
|
+
"""Comments shaped like a marker that are not one.
|
|
912
|
+
|
|
913
|
+
`/**…*/` is assertion syntax, so a comment written that way and left
|
|
914
|
+
unrecognized is far likelier a mistyped marker than a note — and a mistyped
|
|
915
|
+
marker that was silently ignored would read to its author as a proof.
|
|
916
|
+
"""
|
|
917
|
+
# `MARKERS` also holds the fragment literals a parameterized marker
|
|
918
|
+
# tokenizes as (`"/**ASSERT UNIQUE("`, `"**/"`) -- real grammar, but not
|
|
919
|
+
# themselves complete, user-facing marker shapes, so this list shows only
|
|
920
|
+
# whole shapes: the bare join markers, and each parameterized marker's
|
|
921
|
+
# full open-to-close form.
|
|
922
|
+
recognized = ", ".join(
|
|
923
|
+
sorted(literal for literal, token in MARKERS.items() if token in _FIXED_MARKER_TOKENS)
|
|
924
|
+
+ sorted(_marker_shape(open_, kind) for open_, kind in _COLUMN_MARKER_OPENS.items())
|
|
925
|
+
)
|
|
926
|
+
return [
|
|
927
|
+
Diagnostic(
|
|
928
|
+
diag.UNRECOGNIZED_MARKER,
|
|
929
|
+
f"{match.group(0)!r} on line {span.line} is not a sqlassert marker; "
|
|
930
|
+
f"{_marker_hint(match.group(0))}the markers are {recognized}",
|
|
931
|
+
Origin.marked(match.group(0), span),
|
|
932
|
+
)
|
|
933
|
+
for match in shapes
|
|
934
|
+
if not _is_recognized_marker(match.group(0))
|
|
935
|
+
for span in (Span.of(sql, match.start(), match.end()),)
|
|
936
|
+
]
|
|
937
|
+
|
|
938
|
+
|
|
939
|
+
def _marker_shape(open_: str, kind: ColumnMarkerKind) -> str:
|
|
940
|
+
"""The whole user-facing shape of a column marker opening with `open_`."""
|
|
941
|
+
reference = " REFERENCES relation(...)" if kind in FOREIGN_KEY_KINDS else ""
|
|
942
|
+
columns = "... -> ..." if kind in DETERMINES_KINDS else "column IN ('value', ...)" if kind in ENUM_KINDS else "..."
|
|
943
|
+
return f"{open_}{columns}){reference}**/"
|
|
944
|
+
|
|
945
|
+
|
|
946
|
+
def _marker_hint(text: str) -> str:
|
|
947
|
+
"""Point a marker written without `ASSERT`, or a `DECLARE` that only an
|
|
948
|
+
Assertion can be, at its explicit spelling."""
|
|
949
|
+
if re.sub(r"\s+", " ", text.upper()) == "/**DECLARE EXHAUSTIVE**/":
|
|
950
|
+
return "exhaustiveness can only be asserted, as in '/**ASSERT EXHAUSTIVE**/', never declared; "
|
|
951
|
+
explicit = "/**ASSERT " + text[3:]
|
|
952
|
+
if _is_recognized_marker(explicit):
|
|
953
|
+
return f"assertions need an explicit ASSERT, as in {explicit!r}; "
|
|
954
|
+
return ""
|
|
955
|
+
|
|
956
|
+
|
|
957
|
+
def _unresolved_markers(sql: str, statements: list[Expr], shapes: list[re.Match[str]]) -> list[Diagnostic]:
|
|
958
|
+
"""Recognized markers that did not become assertions.
|
|
959
|
+
|
|
960
|
+
Every marker in the source should have reached a join, a Select, or a CASE, or
|
|
961
|
+
raised `UnattachedMarker`. If one merely disappeared, the dialect stopped
|
|
962
|
+
recognising it — and the alternative to reporting that is a program whose
|
|
963
|
+
assertions were never checked reporting as proved.
|
|
964
|
+
"""
|
|
965
|
+
written = [match for match in shapes if _is_recognized_marker(match.group(0))]
|
|
966
|
+
resolved = sum(
|
|
967
|
+
1
|
|
968
|
+
for statement in statements
|
|
969
|
+
for join in statement.find_all(exp.Join)
|
|
970
|
+
if assertion_span(join) is not None
|
|
971
|
+
) + sum(
|
|
972
|
+
len(select.meta.get(_COLUMN_MARKERS_AT, ()))
|
|
973
|
+
for statement in statements
|
|
974
|
+
for select in statement.find_all(exp.Select, exp.SetOperation)
|
|
975
|
+
) + sum(
|
|
976
|
+
1
|
|
977
|
+
for statement in statements
|
|
978
|
+
for case in statement.find_all(exp.Case)
|
|
979
|
+
if exhaustive_span(case) is not None
|
|
980
|
+
)
|
|
981
|
+
if len(written) <= resolved:
|
|
982
|
+
return []
|
|
983
|
+
|
|
984
|
+
first = written[resolved]
|
|
985
|
+
span = Span.of(sql, first.start(), first.end())
|
|
986
|
+
return [
|
|
987
|
+
Diagnostic(
|
|
988
|
+
diag.UNRECOGNIZED_MARKER,
|
|
989
|
+
f"the marker on line {span.line} was not recognized: "
|
|
990
|
+
f"{resolved} of {len(written)} markers became assertions",
|
|
991
|
+
Origin.marked(first.group(0), span),
|
|
992
|
+
)
|
|
993
|
+
]
|
|
994
|
+
|
|
995
|
+
|
|
996
|
+
def assertion_span(join: exp.Join) -> Span | None:
|
|
997
|
+
"""Where the marker asserting a Property of this join is written, if any."""
|
|
998
|
+
return join.meta.get(_ASSERTED_AT)
|
|
999
|
+
|
|
1000
|
+
|
|
1001
|
+
def join_marker_kind(join: exp.Join) -> JoinMarkerKind | None:
|
|
1002
|
+
"""The kind (a value of `JOIN_MARKER_KINDS`) of the marker on this join, if any."""
|
|
1003
|
+
return join.meta.get(_JOIN_MARKER_KIND)
|
|
1004
|
+
|
|
1005
|
+
|
|
1006
|
+
def join_origin(join: exp.Join, dialect: str) -> Origin:
|
|
1007
|
+
"""A readable origin for an asserted join: its marker's span."""
|
|
1008
|
+
span = assertion_span(join)
|
|
1009
|
+
assert span is not None, "only an asserted join has a join origin"
|
|
1010
|
+
return Origin.marked(join.sql(dialect=dialect), span)
|
|
1011
|
+
|
|
1012
|
+
|
|
1013
|
+
def exhaustive_span(case: exp.Case) -> Span | None:
|
|
1014
|
+
"""Where the marker asserting this CASE exhaustive is written, if any."""
|
|
1015
|
+
return case.meta.get(_EXHAUSTIVE_AT)
|
|
1016
|
+
|
|
1017
|
+
|
|
1018
|
+
def _is_alter_table(statement: Expr) -> bool:
|
|
1019
|
+
return isinstance(statement, exp.Alter) and (statement.args.get("kind") or "").upper() == "TABLE"
|
|
1020
|
+
|
|
1021
|
+
|
|
1022
|
+
def _spanned_modifier(parse):
|
|
1023
|
+
return lambda self: self._spanned(parse)
|
|
1024
|
+
|
|
1025
|
+
|
|
1026
|
+
def _hoist_from_first_joins(query: Expr | None) -> None:
|
|
1027
|
+
"""A DuckDB FROM-first Select (`FROM a JOIN b ... SELECT ...`, or a bare
|
|
1028
|
+
`FROM a JOIN b`): SQLGlot hangs its joins on its first source, a table
|
|
1029
|
+
or derived table, where a Select written SELECT-first holds them itself
|
|
1030
|
+
(a parenthesized join's own stay inside it, on its first source). They
|
|
1031
|
+
move to the Select, so both read alike. It is the leftmost operand of a
|
|
1032
|
+
set operation."""
|
|
1033
|
+
while isinstance(query, exp.SetOperation):
|
|
1034
|
+
query = query.this
|
|
1035
|
+
from_ = query.args.get("from_") if isinstance(query, exp.Select) else None
|
|
1036
|
+
source = from_.this if isinstance(from_, exp.From) else None
|
|
1037
|
+
if isinstance(source, Expr) and source.args.get("joins") and isinstance(query, exp.Select):
|
|
1038
|
+
joins = source.args["joins"]
|
|
1039
|
+
source.set("joins", None)
|
|
1040
|
+
query.set("joins", [*joins, *(query.args.get("joins") or ())])
|
|
1041
|
+
|
|
1042
|
+
|
|
1043
|
+
def span(node: Expr) -> tuple[int, int] | None:
|
|
1044
|
+
"""The `(start, end)` source offsets where a Join, query clause, function
|
|
1045
|
+
call or plain DISTINCT is written; for a Select, `(start, start)`: where
|
|
1046
|
+
it starts."""
|
|
1047
|
+
return node.meta.get(_SPAN)
|
|
1048
|
+
|
|
1049
|
+
|
|
1050
|
+
def column_markers(query: exp.Query) -> tuple[ColumnMarker, ...]:
|
|
1051
|
+
"""Every column marker written on `query` -- a Select, or a set operation
|
|
1052
|
+
when written after its last token. Those whose kind is in
|
|
1053
|
+
`DECLARED_KINDS` are Property Declarations, the rest Assertions."""
|
|
1054
|
+
return tuple(query.meta.get(_COLUMN_MARKERS_AT, ()))
|
|
1055
|
+
|
|
1056
|
+
|
|
1057
|
+
def grouping(select: exp.Select) -> list[Expr] | None:
|
|
1058
|
+
"""What `select` groups by, or None when it does not aggregate.
|
|
1059
|
+
|
|
1060
|
+
[] is one group: a scalar aggregate (an aggregate function outside any
|
|
1061
|
+
window, with no GROUP BY) or `GROUP BY ()`. The empty grouping set groups
|
|
1062
|
+
by nothing, so `GROUP BY (), a` is `GROUP BY a`. GROUPING SETS, ROLLUP and
|
|
1063
|
+
CUBE are not in the list: the caller checks the Group for them. An
|
|
1064
|
+
aggregate under QUALIFY is None: QUALIFY lowers it.
|
|
1065
|
+
"""
|
|
1066
|
+
group = select.args.get("group")
|
|
1067
|
+
if isinstance(group, exp.Group):
|
|
1068
|
+
return [expression for expression in group.expressions if not (isinstance(expression, exp.Tuple) and not expression.expressions)]
|
|
1069
|
+
if select.args.get("qualify") is None and any(
|
|
1070
|
+
isinstance(node, exp.AggFunc) and node.find_ancestor(exp.Window, exp.Select) is select
|
|
1071
|
+
for item in select.expressions for node in item.find_all(exp.AggFunc)
|
|
1072
|
+
):
|
|
1073
|
+
return []
|
|
1074
|
+
return None
|
|
1075
|
+
|
|
1076
|
+
|
|
1077
|
+
def marker_position(node: exp.Join | exp.Query | exp.Case) -> tuple[int, int] | None:
|
|
1078
|
+
"""The source `(offset, line)` where a marker for this Join, Select, or
|
|
1079
|
+
simple CASE would be written, or None for a join no marker can precede,
|
|
1080
|
+
such as a comma join, and for a searched CASE."""
|
|
1081
|
+
return node.meta.get(_MARKER_POSITION)
|