sqlassert 0.3.1__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/__main__.py +2 -131
- sqlassert/check.py +10 -3
- sqlassert/diagnostics.py +19 -6
- sqlassert/dialects.py +69 -22
- sqlassert/discovery/duckdb.py +12 -16
- sqlassert/discovery/fetcher.py +45 -29
- sqlassert/discovery/information_schema.py +4 -3
- sqlassert/discovery/postgres.py +6 -7
- sqlassert/edits.py +240 -0
- sqlassert/hazards.py +574 -0
- sqlassert/ir/__init__.py +3 -1
- sqlassert/ir/convert.py +1315 -183
- sqlassert/ir/model.py +128 -25
- sqlassert/main.py +3 -9
- sqlassert/python_engine.py +63 -6
- sqlassert/reporting.py +3 -0
- sqlassert/rewrites.py +1541 -0
- sqlassert/rules/domain.py +117 -21
- sqlassert/rules/equality.py +238 -29
- sqlassert/rules/exactly_one.py +40 -1
- sqlassert/rules/foreign_key.py +7 -4
- sqlassert/rules/join_cardinality.py +33 -11
- sqlassert/rules/nullability.py +239 -30
- sqlassert/rules/uniqueness.py +355 -52
- sqlassert/sql_parse.py +196 -89
- sqlassert/suggest.py +127 -48
- {sqlassert-0.3.1.dist-info → sqlassert-0.3.3.dist-info}/METADATA +121 -39
- sqlassert-0.3.3.dist-info/RECORD +46 -0
- sqlassert-0.3.3.dist-info/entry_points.txt +2 -0
- sqlassert-0.3.3.dist-info/top_level.txt +2 -0
- sqlassert_cli.py +130 -0
- sqlassert/improvements.py +0 -528
- sqlassert/smells.py +0 -306
- sqlassert-0.3.1.dist-info/RECORD +0 -44
- sqlassert-0.3.1.dist-info/entry_points.txt +0 -2
- sqlassert-0.3.1.dist-info/top_level.txt +0 -1
- {sqlassert-0.3.1.dist-info → sqlassert-0.3.3.dist-info}/WHEEL +0 -0
- {sqlassert-0.3.1.dist-info → sqlassert-0.3.3.dist-info}/licenses/LICENSE +0 -0
sqlassert/sql_parse.py
CHANGED
|
@@ -18,9 +18,7 @@ from typing import Literal, NamedTuple
|
|
|
18
18
|
import enum
|
|
19
19
|
import re
|
|
20
20
|
|
|
21
|
-
import sqlglot
|
|
22
21
|
from sqlglot import Expr, exp
|
|
23
|
-
from sqlglot import tokens as sqlglot_tokens
|
|
24
22
|
from sqlglot.dialects.dialect import Dialect
|
|
25
23
|
from sqlglot.errors import ParseError, SqlglotError
|
|
26
24
|
from sqlglot.tokens import Token, TokenType
|
|
@@ -36,14 +34,19 @@ _JOIN_MARKER_KIND = "sqlassert.join_marker_kind"
|
|
|
36
34
|
|
|
37
35
|
# A comment opening with `/**` is how an author writes an assertion or a
|
|
38
36
|
# Property Declaration.
|
|
39
|
-
|
|
37
|
+
# `/**/` is an empty comment, not the start of a marker.
|
|
38
|
+
_MARKER_SHAPED = re.compile(r"/\*\*(?!/).*?\*/", re.DOTALL)
|
|
40
39
|
|
|
41
40
|
|
|
42
|
-
def _marker_shapes(sql: str) -> list[re.Match[str]]:
|
|
41
|
+
def _marker_shapes(sql: str, tokens: list[Token] | None = None) -> list[re.Match[str]]:
|
|
43
42
|
"""Every `/**...*/` span written as SQL: not inside a `--` comment or a
|
|
44
43
|
quoted string or identifier. A `--` comment is how an author switches a
|
|
45
44
|
marker off; text in quotes is data. Offsets are those of `sql`."""
|
|
46
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)
|
|
47
50
|
index, quote = 0, None
|
|
48
51
|
while index < len(sql):
|
|
49
52
|
char = sql[index]
|
|
@@ -256,6 +259,17 @@ _COLUMN_MARKERS_AT = "sqlassert.unique_set_asserted_at"
|
|
|
256
259
|
# CASE. `suggest` pastes markers there.
|
|
257
260
|
_MARKER_POSITION = "sqlassert.marker_position"
|
|
258
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
|
+
|
|
259
273
|
_COLUMN_MARKER_OPEN_TOKENS = {
|
|
260
274
|
MARKERS[open_]: kind for open_, kind in _COLUMN_MARKER_OPENS.items()
|
|
261
275
|
}
|
|
@@ -266,6 +280,20 @@ _DECIMAL = re.compile(r"\d+\.\d*|\.\d+")
|
|
|
266
280
|
_EXPONENT = re.compile(r"(\d+\.?\d*|\.\d+)[eE][+-]?\d+")
|
|
267
281
|
|
|
268
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
|
+
|
|
269
297
|
def literal_value(expression: Expr) -> LiteralValue | None:
|
|
270
298
|
"""The typed value of a string, numeric, or boolean literal, or None for
|
|
271
299
|
any other expression. A numeric literal may be negated."""
|
|
@@ -367,21 +395,6 @@ def _intersect_first(chain: Expr | None) -> Expr | None:
|
|
|
367
395
|
return result
|
|
368
396
|
|
|
369
397
|
|
|
370
|
-
_AMBIGUOUS_PIPES = "sqlassert_ambiguous_pipes"
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
def _ambiguous_pipes(**kwargs: Expr) -> exp.Or:
|
|
374
|
-
node = exp.Or(**kwargs)
|
|
375
|
-
node.meta[_AMBIGUOUS_PIPES] = True
|
|
376
|
-
return node
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
def is_ambiguous_pipes(node: Expr) -> bool:
|
|
380
|
-
"""Whether `node` is a `||` that a setting may make OR or concatenation
|
|
381
|
-
(MySQL's `PIPES_AS_CONCAT`): written as an OR, which its operands bound."""
|
|
382
|
-
return isinstance(node, exp.Or) and bool(node.meta.get(_AMBIGUOUS_PIPES))
|
|
383
|
-
|
|
384
|
-
|
|
385
398
|
@lru_cache(maxsize=None)
|
|
386
399
|
def sqlassert_dialect(base: str) -> type[Dialect]:
|
|
387
400
|
"""The named dialect, plus Property Markers as real syntax.
|
|
@@ -395,28 +408,8 @@ def sqlassert_dialect(base: str) -> type[Dialect]:
|
|
|
395
408
|
# every concrete dialect sets its own, so the base class's static type
|
|
396
409
|
# cannot know they exist. This is exactly the private-API coupling
|
|
397
410
|
# documented below, not a type worth narrowing further.
|
|
398
|
-
#
|
|
399
|
-
|
|
400
|
-
# SQLGlot 30, the optional Rust tokenizer indexed every `KEYWORDS` value
|
|
401
|
-
# against `TokenType` while building the class and KeyErrored on ours. Those
|
|
402
|
-
# versions expose a private switch which lets this dialect consistently use
|
|
403
|
-
# the Python tokenizer. SQLGlot 30 removed both that switch and the matching
|
|
404
|
-
# constructor argument; its tokenizer core accepts our Enum directly.
|
|
405
|
-
if hasattr(sqlglot_tokens, "USE_RS_TOKENIZER"):
|
|
406
|
-
previous_use_rs_tokenizer = getattr(sqlglot_tokens, "USE_RS_TOKENIZER")
|
|
407
|
-
setattr(sqlglot_tokens, "USE_RS_TOKENIZER", False)
|
|
408
|
-
try:
|
|
409
|
-
class _Tokenizer(parent.Tokenizer): # ty: ignore[unresolved-attribute]
|
|
410
|
-
KEYWORDS = {**parent.Tokenizer.KEYWORDS, **MARKERS} # ty: ignore[unresolved-attribute]
|
|
411
|
-
|
|
412
|
-
def __init__(self, *args, **kwargs) -> None:
|
|
413
|
-
kwargs.setdefault("use_rs_tokenizer", False)
|
|
414
|
-
super().__init__(*args, **kwargs)
|
|
415
|
-
finally:
|
|
416
|
-
setattr(sqlglot_tokens, "USE_RS_TOKENIZER", previous_use_rs_tokenizer)
|
|
417
|
-
else:
|
|
418
|
-
class _Tokenizer(parent.Tokenizer): # ty: ignore[unresolved-attribute]
|
|
419
|
-
KEYWORDS = {**parent.Tokenizer.KEYWORDS, **MARKERS} # ty: ignore[unresolved-attribute]
|
|
411
|
+
class _Tokenizer(parent.Tokenizer): # ty: ignore[missing-attribute]
|
|
412
|
+
KEYWORDS = {**parent.Tokenizer.KEYWORDS, **MARKERS} # ty: ignore[missing-attribute]
|
|
420
413
|
|
|
421
414
|
# This hooks SQLGlot's private API: `Tokenizer.KEYWORDS`, `_parse_join`,
|
|
422
415
|
# `_match`, `_prev`, `_curr`. It is the best seam available — SQLGlot exposes
|
|
@@ -435,21 +428,32 @@ def sqlassert_dialect(base: str) -> type[Dialect]:
|
|
|
435
428
|
# program reporting as proved. `_unresolved_markers` exists for that case;
|
|
436
429
|
# do not remove it, and do not add a fallback that carries on without the
|
|
437
430
|
# hook.
|
|
438
|
-
class _Parser(parent.Parser): # ty: ignore[
|
|
431
|
+
class _Parser(parent.Parser): # ty: ignore[missing-attribute]
|
|
439
432
|
# The case marker is a primary expression of its own, so it attaches
|
|
440
433
|
# to whatever expression follows it, which must be a simple CASE.
|
|
441
434
|
PRIMARY_PARSERS = {
|
|
442
|
-
**parent.Parser.PRIMARY_PARSERS, # ty: ignore[
|
|
435
|
+
**parent.Parser.PRIMARY_PARSERS, # ty: ignore[missing-attribute]
|
|
443
436
|
SqlassertToken.SQLASSERT_EXHAUSTIVE: lambda self, token: self._parse_exhaustive_case(token),
|
|
444
437
|
}
|
|
445
|
-
#
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
**parent.Parser.DISJUNCTION, # ty: ignore[unresolved-attribute]
|
|
450
|
-
**({TokenType.DPIPE: _ambiguous_pipes} if TokenType.DPIPE in parent.Parser.DISJUNCTION else {}), # ty: ignore[unresolved-attribute]
|
|
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]
|
|
451
442
|
}
|
|
452
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)
|
|
453
457
|
def _span(self, token: Token) -> Span:
|
|
454
458
|
"""Where `token` is written in the SQL being parsed."""
|
|
455
459
|
return Span.of(self.sql, token.start, token.end + 1)
|
|
@@ -514,6 +518,8 @@ def sqlassert_dialect(base: str) -> type[Dialect]:
|
|
|
514
518
|
# A comma join has no JOIN keyword a marker could precede.
|
|
515
519
|
if join is not None and start is not None and start.token_type is not TokenType.COMMA:
|
|
516
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)
|
|
517
523
|
return join
|
|
518
524
|
|
|
519
525
|
kind = JOIN_MARKER_KINDS[self._curr.token_type]
|
|
@@ -548,13 +554,52 @@ def sqlassert_dialect(base: str) -> type[Dialect]:
|
|
|
548
554
|
into an `exp.Subquery`, which has no trailing marker of its own to
|
|
549
555
|
consume.
|
|
550
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):
|
|
551
568
|
result = super()._parse_select_query(*args, **kwargs)
|
|
552
569
|
if not isinstance(result, exp.Select):
|
|
553
570
|
return result
|
|
554
|
-
|
|
571
|
+
right_operand = not kwargs.get("parse_set_operation", True)
|
|
572
|
+
if right_operand:
|
|
555
573
|
# A set operation's right operand: no set operation is tried after it.
|
|
556
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
|
|
557
600
|
|
|
601
|
+
def _parse_column_markers(self) -> list[ColumnMarker]:
|
|
602
|
+
"""Every column marker at the cursor, consumed."""
|
|
558
603
|
found: list[ColumnMarker] = []
|
|
559
604
|
while self._curr is not None and self._curr.token_type in _COLUMN_MARKER_OPEN_TOKENS:
|
|
560
605
|
kind = _COLUMN_MARKER_OPEN_TOKENS[self._curr.token_type]
|
|
@@ -580,25 +625,9 @@ def sqlassert_dialect(base: str) -> type[Dialect]:
|
|
|
580
625
|
|
|
581
626
|
whole = Span.of(self.sql, open_.start, self._prev.end + 1)
|
|
582
627
|
found.append(ColumnMarker(kind, names, whole, referenced_relation, referenced_columns, dependent, values))
|
|
583
|
-
|
|
584
|
-
if found:
|
|
585
|
-
result.meta[_COLUMN_MARKERS_AT] = found
|
|
586
628
|
if self._curr is not None and self._curr.token_type is SqlassertToken.SQLASSERT_EXHAUSTIVE:
|
|
587
629
|
raise self._misplaced_case_marker(self._curr)
|
|
588
|
-
|
|
589
|
-
# `super()._parse_select_query` already tried, and gave up, on
|
|
590
|
-
# attaching a following UNION/INTERSECT/EXCEPT to this same
|
|
591
|
-
# Select before returning -- its own last step runs before a
|
|
592
|
-
# trailing marker exists to get in the way, so the marker token
|
|
593
|
-
# sitting where it looked for a set-operation keyword reads as
|
|
594
|
-
# "no set operation here". Now that the marker is consumed, retry:
|
|
595
|
-
# a no-op if nothing follows, since `_parse_set_operations` only
|
|
596
|
-
# advances the cursor on an actual match. Not for the right operand
|
|
597
|
-
# of a set operation, which the left-associative loop that parses
|
|
598
|
-
# it attaches the next operator to instead.
|
|
599
|
-
if not kwargs.get("parse_set_operation", True):
|
|
600
|
-
return result
|
|
601
|
-
return self._parse_set_operations(result) or result
|
|
630
|
+
return found
|
|
602
631
|
|
|
603
632
|
def _parse_set_operations(self, this, *args, **kwargs):
|
|
604
633
|
"""Record where a Select ends: the first time set operations are
|
|
@@ -609,18 +638,52 @@ def sqlassert_dialect(base: str) -> type[Dialect]:
|
|
|
609
638
|
"""
|
|
610
639
|
self._record_marker_position(this)
|
|
611
640
|
result = super()._parse_set_operations(this, *args, **kwargs)
|
|
612
|
-
|
|
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
|
|
613
650
|
|
|
614
651
|
def _record_marker_position(self, this) -> None:
|
|
615
652
|
if isinstance(this, exp.Select) and _MARKER_POSITION not in this.meta and self._prev is not None:
|
|
616
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
|
|
617
680
|
|
|
618
681
|
def _parse_marker_columns(self, kind: ColumnMarkerKind, span: Span) -> tuple[str, ...]:
|
|
619
682
|
"""A marker's column list after its opening parenthesis, through the closing one."""
|
|
620
683
|
columns = self._parse_csv(self._parse_id_var)
|
|
621
684
|
if not columns:
|
|
622
685
|
raise UnattachedMarker(f"the {MARKER_NOUNS[kind]} on line {span.line} names no columns", span, self._prev.text)
|
|
623
|
-
names = tuple(column
|
|
686
|
+
names = tuple(self._marker_identifier(column, span) for column in columns)
|
|
624
687
|
if len({name.lower() for name in names}) != len(names):
|
|
625
688
|
raise UnattachedMarker(
|
|
626
689
|
f"the {MARKER_NOUNS[kind]} on line {span.line} names the same column more than once",
|
|
@@ -637,7 +700,7 @@ def sqlassert_dialect(base: str) -> type[Dialect]:
|
|
|
637
700
|
|
|
638
701
|
def _parse_marker_dependency(self, kind: ColumnMarkerKind, span: Span) -> tuple[tuple[str, ...], tuple[str, ...]]:
|
|
639
702
|
"""`determinant -> dependent`, each a column list, through the closing parenthesis."""
|
|
640
|
-
determinant = tuple(column
|
|
703
|
+
determinant = tuple(self._marker_identifier(column, span) for column in self._parse_csv(self._parse_id_var))
|
|
641
704
|
if not determinant or not self._match(TokenType.ARROW):
|
|
642
705
|
raise UnattachedMarker(
|
|
643
706
|
f"the {MARKER_NOUNS[kind]} on line {span.line} must list columns, then ->, then the columns they determine",
|
|
@@ -680,7 +743,7 @@ def sqlassert_dialect(base: str) -> type[Dialect]:
|
|
|
680
743
|
if value in values:
|
|
681
744
|
raise malformed(f"lists {value.sql()} more than once")
|
|
682
745
|
values.append(value)
|
|
683
|
-
return (column
|
|
746
|
+
return (self._marker_identifier(column, span),), tuple(values)
|
|
684
747
|
|
|
685
748
|
def _parse_marker_reference(self, kind: ColumnMarkerKind, span: Span, count: int) -> tuple[str, tuple[str, ...]]:
|
|
686
749
|
"""`REFERENCES relation(col, ...)`, pairing `count` columns by position."""
|
|
@@ -696,7 +759,10 @@ def sqlassert_dialect(base: str) -> type[Dialect]:
|
|
|
696
759
|
parts.append(self._parse_id_var(any_token=False))
|
|
697
760
|
if None in parts or not self._match(TokenType.L_PAREN):
|
|
698
761
|
raise missing
|
|
699
|
-
|
|
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)
|
|
700
766
|
columns = self._parse_marker_columns(kind, span)
|
|
701
767
|
if len(columns) != count:
|
|
702
768
|
raise UnattachedMarker(
|
|
@@ -723,10 +789,14 @@ class ParsedProgram:
|
|
|
723
789
|
create_statements: tuple[Expr, ...] = ()
|
|
724
790
|
root_select: exp.Query | None = None
|
|
725
791
|
diagnostics: tuple[Diagnostic, ...] = ()
|
|
792
|
+
# The SQL text and its tokens, from which Rewrites place their edits.
|
|
793
|
+
sql: str = ""
|
|
794
|
+
tokens: tuple[Token, ...] = ()
|
|
726
795
|
|
|
727
796
|
def __post_init__(self) -> None:
|
|
728
797
|
object.__setattr__(self, "create_statements", tuple(self.create_statements))
|
|
729
798
|
object.__setattr__(self, "diagnostics", tuple(self.diagnostics))
|
|
799
|
+
object.__setattr__(self, "tokens", tuple(self.tokens))
|
|
730
800
|
|
|
731
801
|
|
|
732
802
|
class SqlParser:
|
|
@@ -739,10 +809,15 @@ class SqlParser:
|
|
|
739
809
|
def parse(self, sql: str) -> ParsedProgram:
|
|
740
810
|
# Reported first, and on every path: a mistyped marker is invisible to
|
|
741
811
|
# the grammar, so nothing later in parsing can notice it.
|
|
742
|
-
|
|
743
|
-
|
|
812
|
+
dialect = self.dialect_class()
|
|
744
813
|
try:
|
|
745
|
-
|
|
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]
|
|
746
821
|
except UnattachedMarker as error:
|
|
747
822
|
return ParsedProgram(diagnostics=(*diagnostics, self._unattached(error)))
|
|
748
823
|
except SqlglotError as error:
|
|
@@ -766,9 +841,12 @@ class SqlParser:
|
|
|
766
841
|
|
|
767
842
|
# A marker only becomes an assertion if the dialect recognised it, so
|
|
768
843
|
# reconcile what the source contains against what parsing produced.
|
|
769
|
-
diagnostics.extend(_unresolved_markers(sql, statements))
|
|
844
|
+
diagnostics.extend(_unresolved_markers(sql, statements, shapes))
|
|
770
845
|
diagnostics.extend(
|
|
771
|
-
Diagnostic(
|
|
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
|
+
)
|
|
772
850
|
for statement in statements for join in statement.find_all(exp.Join) if join.args.get("method") == "NATURAL"
|
|
773
851
|
)
|
|
774
852
|
|
|
@@ -779,9 +857,9 @@ class SqlParser:
|
|
|
779
857
|
f"a SQL program allows at most one root select, found {len(selects)}",
|
|
780
858
|
)
|
|
781
859
|
)
|
|
782
|
-
return ParsedProgram(tuple(creates), None, tuple(diagnostics))
|
|
860
|
+
return ParsedProgram(tuple(creates), None, tuple(diagnostics), sql, tuple(tokens))
|
|
783
861
|
|
|
784
|
-
return ParsedProgram(tuple(creates), selects[0] if selects else None, tuple(diagnostics))
|
|
862
|
+
return ParsedProgram(tuple(creates), selects[0] if selects else None, tuple(diagnostics), sql, tuple(tokens))
|
|
785
863
|
|
|
786
864
|
def _unattached(self, error: UnattachedMarker) -> Diagnostic:
|
|
787
865
|
return Diagnostic(diag.UNATTACHED_MARKER, str(error), Origin.marked(error.text, error.span))
|
|
@@ -804,7 +882,7 @@ class SqlParser:
|
|
|
804
882
|
|
|
805
883
|
def _marker_token(self, sql: str) -> Token | None:
|
|
806
884
|
try:
|
|
807
|
-
tokens = self.dialect_class.Tokenizer().tokenize(sql) # ty: ignore[
|
|
885
|
+
tokens = self.dialect_class.Tokenizer().tokenize(sql) # ty: ignore[missing-attribute]
|
|
808
886
|
except SqlglotError:
|
|
809
887
|
return None
|
|
810
888
|
return next(
|
|
@@ -829,7 +907,7 @@ def _is_recognized_marker(text: str) -> bool:
|
|
|
829
907
|
return upper.endswith("**/") and any(upper.startswith(open_) for open_ in _COLUMN_MARKER_OPENS)
|
|
830
908
|
|
|
831
909
|
|
|
832
|
-
def _unrecognized_markers(sql: str) -> list[Diagnostic]:
|
|
910
|
+
def _unrecognized_markers(sql: str, shapes: list[re.Match[str]]) -> list[Diagnostic]:
|
|
833
911
|
"""Comments shaped like a marker that are not one.
|
|
834
912
|
|
|
835
913
|
`/**…*/` is assertion syntax, so a comment written that way and left
|
|
@@ -852,7 +930,7 @@ def _unrecognized_markers(sql: str) -> list[Diagnostic]:
|
|
|
852
930
|
f"{_marker_hint(match.group(0))}the markers are {recognized}",
|
|
853
931
|
Origin.marked(match.group(0), span),
|
|
854
932
|
)
|
|
855
|
-
for match in
|
|
933
|
+
for match in shapes
|
|
856
934
|
if not _is_recognized_marker(match.group(0))
|
|
857
935
|
for span in (Span.of(sql, match.start(), match.end()),)
|
|
858
936
|
]
|
|
@@ -876,7 +954,7 @@ def _marker_hint(text: str) -> str:
|
|
|
876
954
|
return ""
|
|
877
955
|
|
|
878
956
|
|
|
879
|
-
def _unresolved_markers(sql: str, statements: list[Expr]) -> list[Diagnostic]:
|
|
957
|
+
def _unresolved_markers(sql: str, statements: list[Expr], shapes: list[re.Match[str]]) -> list[Diagnostic]:
|
|
880
958
|
"""Recognized markers that did not become assertions.
|
|
881
959
|
|
|
882
960
|
Every marker in the source should have reached a join, a Select, or a CASE, or
|
|
@@ -884,7 +962,7 @@ def _unresolved_markers(sql: str, statements: list[Expr]) -> list[Diagnostic]:
|
|
|
884
962
|
recognising it — and the alternative to reporting that is a program whose
|
|
885
963
|
assertions were never checked reporting as proved.
|
|
886
964
|
"""
|
|
887
|
-
written = [match for match in
|
|
965
|
+
written = [match for match in shapes if _is_recognized_marker(match.group(0))]
|
|
888
966
|
resolved = sum(
|
|
889
967
|
1
|
|
890
968
|
for statement in statements
|
|
@@ -893,7 +971,7 @@ def _unresolved_markers(sql: str, statements: list[Expr]) -> list[Diagnostic]:
|
|
|
893
971
|
) + sum(
|
|
894
972
|
len(select.meta.get(_COLUMN_MARKERS_AT, ()))
|
|
895
973
|
for statement in statements
|
|
896
|
-
for select in statement.find_all(exp.Select)
|
|
974
|
+
for select in statement.find_all(exp.Select, exp.SetOperation)
|
|
897
975
|
) + sum(
|
|
898
976
|
1
|
|
899
977
|
for statement in statements
|
|
@@ -941,10 +1019,39 @@ def _is_alter_table(statement: Expr) -> bool:
|
|
|
941
1019
|
return isinstance(statement, exp.Alter) and (statement.args.get("kind") or "").upper() == "TABLE"
|
|
942
1020
|
|
|
943
1021
|
|
|
944
|
-
def
|
|
945
|
-
|
|
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
|
|
946
1053
|
`DECLARED_KINDS` are Property Declarations, the rest Assertions."""
|
|
947
|
-
return tuple(
|
|
1054
|
+
return tuple(query.meta.get(_COLUMN_MARKERS_AT, ()))
|
|
948
1055
|
|
|
949
1056
|
|
|
950
1057
|
def grouping(select: exp.Select) -> list[Expr] | None:
|
|
@@ -967,7 +1074,7 @@ def grouping(select: exp.Select) -> list[Expr] | None:
|
|
|
967
1074
|
return None
|
|
968
1075
|
|
|
969
1076
|
|
|
970
|
-
def marker_position(node: exp.Join | exp.
|
|
1077
|
+
def marker_position(node: exp.Join | exp.Query | exp.Case) -> tuple[int, int] | None:
|
|
971
1078
|
"""The source `(offset, line)` where a marker for this Join, Select, or
|
|
972
1079
|
simple CASE would be written, or None for a join no marker can precede,
|
|
973
1080
|
such as a comma join, and for a searched CASE."""
|