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.
Files changed (50) hide show
  1. sqlassert/__init__.py +34 -9
  2. sqlassert/__main__.py +9 -0
  3. sqlassert/check.py +451 -0
  4. sqlassert/diagnostics.py +70 -0
  5. sqlassert/dialects.py +258 -0
  6. sqlassert/discovery/__init__.py +30 -0
  7. sqlassert/discovery/bigquery.py +71 -0
  8. sqlassert/discovery/databricks.py +18 -0
  9. sqlassert/discovery/duckdb.py +159 -0
  10. sqlassert/discovery/fetcher.py +418 -0
  11. sqlassert/discovery/information_schema.py +327 -0
  12. sqlassert/discovery/mysql.py +70 -0
  13. sqlassert/discovery/postgres.py +142 -0
  14. sqlassert/discovery/redshift.py +36 -0
  15. sqlassert/discovery/snowflake.py +63 -0
  16. sqlassert/discovery/trino.py +37 -0
  17. sqlassert/edits.py +240 -0
  18. sqlassert/hazards.py +574 -0
  19. sqlassert/ir/__init__.py +58 -0
  20. sqlassert/ir/convert.py +3509 -0
  21. sqlassert/ir/model.py +779 -0
  22. sqlassert/main.py +51 -0
  23. sqlassert/properties.py +121 -0
  24. sqlassert/provenance.py +73 -0
  25. sqlassert/python_engine.py +356 -0
  26. sqlassert/reporting.py +105 -0
  27. sqlassert/rewrites.py +1541 -0
  28. sqlassert/rules/STYLEGUIDE.md +19 -0
  29. sqlassert/rules/__init__.py +11 -0
  30. sqlassert/rules/column_set.py +34 -0
  31. sqlassert/rules/domain.py +472 -0
  32. sqlassert/rules/equality.py +442 -0
  33. sqlassert/rules/exactly_one.py +114 -0
  34. sqlassert/rules/foreign_key.py +319 -0
  35. sqlassert/rules/join_cardinality.py +116 -0
  36. sqlassert/rules/nullability.py +627 -0
  37. sqlassert/rules/uniqueness.py +904 -0
  38. sqlassert/sql_parse.py +1081 -0
  39. sqlassert/suggest.py +418 -0
  40. sqlassert-0.3.3.dist-info/METADATA +807 -0
  41. sqlassert-0.3.3.dist-info/RECORD +46 -0
  42. {sqlassert-0.1.2.dist-info → sqlassert-0.3.3.dist-info}/WHEEL +1 -1
  43. sqlassert-0.3.3.dist-info/entry_points.txt +2 -0
  44. sqlassert-0.3.3.dist-info/licenses/LICENSE +21 -0
  45. sqlassert-0.3.3.dist-info/top_level.txt +2 -0
  46. sqlassert_cli.py +130 -0
  47. sqlassert/unique.py +0 -605
  48. sqlassert-0.1.2.dist-info/METADATA +0 -173
  49. sqlassert-0.1.2.dist-info/RECORD +0 -6
  50. sqlassert-0.1.2.dist-info/top_level.txt +0 -1
@@ -0,0 +1,37 @@
1
+ """Trino: the standard discovery, each catalog's own `information_schema`, over the `trino` client.
2
+
3
+ Trino federates catalogs, each with its own `catalog.information_schema`;
4
+ a name may be qualified by any catalog. Its `information_schema` has
5
+ `TABLES`, `COLUMNS` and `VIEWS` but no constraint views: Trino has no key
6
+ constraints, and does not surface those a connector's source enforces, so a
7
+ Trino catalog reports NOT NULLs and no keys. That loses proofs, never
8
+ soundness. Parameters are `?` (the client's qmark style).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections.abc import Sequence
14
+
15
+ from sqlassert.discovery.fetcher import DatabaseForeignKey, DatabaseMetadataError, DatabaseRelationMetadata
16
+ from sqlassert.discovery.information_schema import InformationSchemaKnowledgeFetcher, Key, quoted
17
+
18
+
19
+ class TrinoKnowledgeFetcher(InformationSchemaKnowledgeFetcher):
20
+ type_dialect = "trino"
21
+ paramstyle = "qmark"
22
+ cross_catalog = True
23
+
24
+ def session(self, scope: DatabaseRelationMetadata | None) -> tuple[str, tuple[str, ...]]:
25
+ catalog, path = super().session(scope)
26
+ if catalog is None: # The client may connect without a catalog.
27
+ raise DatabaseMetadataError("the Trino session has no current catalog: connect with catalog=")
28
+ return catalog, path
29
+
30
+ def information_schema(self, catalog: str, schema: str) -> str:
31
+ return f"{quoted(catalog)}.information_schema"
32
+
33
+ def keys(self, catalog: str, schema: str, tables: Sequence[str]) -> list[Key]:
34
+ return []
35
+
36
+ def foreign_keys(self, catalog: str, schema: str, tables: Sequence[str]) -> list[tuple[str, DatabaseForeignKey]]:
37
+ return []
sqlassert/edits.py ADDED
@@ -0,0 +1,240 @@
1
+ """Rewrite Edits: exact text changes to a SQL Program, placed from its tokens.
2
+
3
+ A Rewrite carries the edits that make it (`Edit`: replace the text between two
4
+ offsets of the original SQL). Edits are placed from SQLGlot's token stream,
5
+ whose tokens keep their source offsets; the AST keeps them only on
6
+ identifiers, literals and function names. An edit never deletes a comment or
7
+ a Property Marker: whatever of either lies in a span it replaces is kept in
8
+ its replacement. Everything shown of a Rewrite -- the rewritten SQL, its
9
+ diff -- is derived from its edits.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import difflib
15
+ from collections.abc import Iterable, Sequence
16
+ from dataclasses import dataclass
17
+
18
+ from sqlglot.tokens import Token, TokenType
19
+
20
+ from sqlassert.sql_parse import SqlassertToken
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class Edit:
25
+ """Replace the original SQL's text from `start` to `end` (offsets, `end`
26
+ exclusive) with `replacement`; an insertion when they are equal."""
27
+
28
+ start: int
29
+ end: int
30
+ replacement: str
31
+
32
+
33
+ def apply_edits(sql: str, edits: Iterable[Edit]) -> str:
34
+ """`sql` with `edits` applied. They must not overlap."""
35
+ ordered = sorted(edits, key=lambda edit: (edit.start, edit.end))
36
+ for before, after in zip(ordered, ordered[1:]):
37
+ if after.start < before.end:
38
+ raise ValueError(f"overlapping edits: {before} and {after}")
39
+ for edit in reversed(ordered):
40
+ sql = sql[:edit.start] + edit.replacement + sql[edit.end:]
41
+ return sql
42
+
43
+
44
+ def unified_diff(sql: str, edits: Iterable[Edit], *, name: str = "original", context: int = 2) -> str:
45
+ """The unified diff from `sql` to `sql` with `edits` applied, with
46
+ `@@ -10,4 +10,5 @@` hunk headers and `context` lines around each change."""
47
+ lines = difflib.unified_diff(
48
+ sql.splitlines(), apply_edits(sql, edits).splitlines(), f"{name}", f"{name} (rewritten)", n=context, lineterm="",
49
+ )
50
+ return "\n".join(lines)
51
+
52
+
53
+ # Tokens that open and close a nesting level: no clause or list separator
54
+ # inside one belongs to the level outside it.
55
+ _OPENS = {TokenType.L_PAREN, TokenType.L_BRACKET, TokenType.L_BRACE, TokenType.CASE}
56
+ _CLOSES = {TokenType.R_PAREN, TokenType.R_BRACKET, TokenType.R_BRACE, TokenType.END}
57
+
58
+
59
+ class Source:
60
+ """The SQL text and its SQL tokens: Property Markers are left out, like
61
+ comments, so no edit's span starts or ends inside one and every edit
62
+ keeps them (`kept`). Token positions are indexes into `tokens`."""
63
+
64
+ def __init__(self, sql: str, tokens: Sequence[Token]) -> None:
65
+ self.sql = sql
66
+ self.tokens: list[Token] = []
67
+ marker = False
68
+ for token in tokens:
69
+ if isinstance(token.token_type, SqlassertToken):
70
+ # A column marker's open token is followed by plain tokens up to its close.
71
+ marker = token.token_type.name.endswith("_OPEN")
72
+ continue
73
+ if not marker:
74
+ self.tokens.append(token)
75
+ self._by_start = {token.start: index for index, token in enumerate(self.tokens)}
76
+
77
+ def at(self, offset: int) -> int | None:
78
+ """The token that starts at `offset`."""
79
+ return self._by_start.get(offset)
80
+
81
+ def after(self, offset: int) -> int | None:
82
+ """The first token that starts at or after `offset`."""
83
+ return next((index for index, token in enumerate(self.tokens) if token.start >= offset), None)
84
+
85
+ def before(self, offset: int) -> int | None:
86
+ """The last token that ends at or before `offset`."""
87
+ return next((index for index in range(len(self.tokens) - 1, -1, -1) if self.tokens[index].end < offset), None)
88
+
89
+ def is_(self, index: int | None, *types: TokenType) -> bool:
90
+ return index is not None and 0 <= index < len(self.tokens) and self.tokens[index].token_type in types
91
+
92
+ def start(self, index: int) -> int:
93
+ return self.tokens[index].start
94
+
95
+ def end(self, index: int) -> int:
96
+ """The offset just past token `index`."""
97
+ return self.tokens[index].end + 1
98
+
99
+ def text(self, first: int, last: int) -> str:
100
+ """The SQL from token `first` through token `last`, verbatim."""
101
+ return self.sql[self.start(first):self.end(last)]
102
+
103
+ def closing(self, index: int) -> int | None:
104
+ """The token that closes the nesting level token `index` opens."""
105
+ depth = 0
106
+ for current in range(index, len(self.tokens)):
107
+ kind = self.tokens[current].token_type
108
+ depth += kind in _OPENS
109
+ depth -= kind in _CLOSES
110
+ if depth == 0:
111
+ return current
112
+ return None
113
+
114
+ def opening(self, index: int) -> int | None:
115
+ """The token that opens the nesting level token `index` closes."""
116
+ depth = 0
117
+ for current in range(index, -1, -1):
118
+ kind = self.tokens[current].token_type
119
+ depth += kind in _CLOSES
120
+ depth -= kind in _OPENS
121
+ if depth == 0:
122
+ return current
123
+ return None
124
+
125
+ def top_level(self, first: int, last: int, *types: TokenType) -> list[int]:
126
+ """The tokens of `types` from `first` through `last` outside every
127
+ nesting level that opens there. An AND that closes a BETWEEN is not one."""
128
+ found = []
129
+ depth = 0
130
+ between = 0
131
+ for index in range(first, last + 1):
132
+ kind = self.tokens[index].token_type
133
+ if kind in _CLOSES:
134
+ depth -= 1
135
+ elif kind in _OPENS:
136
+ depth += 1
137
+ elif depth == 0 and kind is TokenType.BETWEEN:
138
+ between += 1
139
+ elif depth == 0 and kind is TokenType.AND and between:
140
+ between -= 1
141
+ elif depth == 0 and kind in types:
142
+ found.append(index)
143
+ return found
144
+
145
+ def split(self, first: int, last: int, separator: TokenType) -> list[tuple[int, int]]:
146
+ """The `(first, last)` tokens of each part of `first`..`last` between
147
+ top-level `separator` tokens."""
148
+ parts, start = [], first
149
+ for index in self.top_level(first, last, separator):
150
+ parts.append((start, index - 1))
151
+ start = index + 1
152
+ parts.append((start, last))
153
+ return parts
154
+
155
+ def kept(self, start: int, end: int, moved: Iterable[tuple[int, int]] = ()) -> list[str]:
156
+ """The comments and Property Markers between offsets `start` and `end`,
157
+ outside the SQL tokens: what an edit there must keep. One that ends a
158
+ line ends with its line break, so a `--` comment still ends there.
159
+ Those inside a `moved` token range are not: the edit writes that text
160
+ elsewhere, verbatim."""
161
+ spans = [(self.start(first), self.end(last)) for first, last in moved]
162
+ pieces = []
163
+ cursor = start
164
+ for token in self.tokens:
165
+ if token.end < start or token.start >= end:
166
+ continue
167
+ if not any(left <= cursor and token.start <= right for left, right in spans):
168
+ pieces.extend(self._kept_in(cursor, token.start))
169
+ cursor = token.end + 1
170
+ pieces.extend(self._kept_in(cursor, end))
171
+ return pieces
172
+
173
+ def _kept_in(self, start: int, end: int) -> list[str]:
174
+ gap = self.sql[start:end]
175
+ text = gap.strip()
176
+ if not text:
177
+ return []
178
+ trailing = gap[len(gap.rstrip()):]
179
+ return [text + ("\n" if "\n" in trailing else "")]
180
+
181
+ def replace(self, first: int, last: int, text: str, moved: Iterable[tuple[int, int]] = ()) -> Edit:
182
+ """Tokens `first` through `last` replaced by `text`, keeping the
183
+ comments and markers between them, but those `moved` (`kept`), after it."""
184
+ start, end = self.start(first), self.end(last)
185
+ kept = self.kept(start, end, moved)
186
+ return Edit(start, end, _joined([text, *kept]) if text else _joined(kept))
187
+
188
+ def delete(self, first: int, last: int, moved: Iterable[tuple[int, int]] = ()) -> Edit:
189
+ """Tokens `first` through `last` deleted, with the whitespace on one
190
+ side of them (the line's, when they start one), keeping any comment or
191
+ marker between them but those `moved` (`kept`)."""
192
+ start, end = self.start(first), self.end(last)
193
+ leading = len(self.sql[:start]) - len(self.sql[:start].rstrip())
194
+ trailing = len(self.sql[end:]) - len(self.sql[end:].lstrip())
195
+ kept = self.kept(start, end, moved)
196
+ # Whitespace on one side only goes when nothing then runs into the
197
+ # deleted text's neighbour: `(... ORDER BY a)`, not `(...), b AS`.
198
+ before = self.sql[start - leading - 1:start - leading]
199
+ after = self.sql[end + trailing:end + trailing + 1]
200
+ if leading and not trailing and after not in {"", ")", ",", ";"}:
201
+ leading = 0
202
+ if trailing and not leading and before not in {"", "("}:
203
+ trailing = 0
204
+ if trailing and after and (not leading or "\n" in self.sql[start - leading:start]):
205
+ return Edit(start, end + trailing, _joined(kept) + (" " if kept and not kept[-1].endswith("\n") else ""))
206
+ if leading:
207
+ return Edit(start - leading, end, (" " if kept else "") + _joined(kept))
208
+ return Edit(start, end, _joined(kept))
209
+
210
+ def tokens_of(self, span: tuple[int, int] | None) -> tuple[int, int] | None:
211
+ """The first and last tokens of a `(start, end)` source span."""
212
+ if span is None:
213
+ return None
214
+ first, last = self.at(span[0]), self.before(span[1])
215
+ return None if first is None or last is None or last < first else (first, last)
216
+
217
+ def deletions(self, ranges: Iterable[tuple[int, int]]) -> tuple[Edit, ...]:
218
+ """Each `(first, last)` token range deleted (`delete`), ranges with no
219
+ token between them as one."""
220
+ merged: list[tuple[int, int]] = []
221
+ for first, last in sorted(ranges):
222
+ if merged and first <= merged[-1][1] + 1:
223
+ merged[-1] = (merged[-1][0], max(last, merged[-1][1]))
224
+ else:
225
+ merged.append((first, last))
226
+ return tuple(self.delete(first, last) for first, last in merged)
227
+
228
+ def insert_before(self, index: int, text: str) -> Edit:
229
+ return Edit(self.start(index), self.start(index), text)
230
+
231
+ def insert_after(self, index: int, text: str) -> Edit:
232
+ return Edit(self.end(index), self.end(index), text)
233
+
234
+
235
+ def _joined(pieces: list[str]) -> str:
236
+ text = ""
237
+ for piece in pieces:
238
+ text += piece if not text or text.endswith("\n") else " " + piece
239
+ return text
240
+