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.
@@ -21,7 +21,7 @@ from __future__ import annotations
21
21
 
22
22
  from abc import ABC, abstractmethod
23
23
  from collections.abc import Mapping
24
- from dataclasses import dataclass, field
24
+ from dataclasses import dataclass, field, replace
25
25
  from enum import Enum
26
26
 
27
27
  from sqlglot import Expr, exp
@@ -30,7 +30,7 @@ from sqlglot.optimizer.scope import traverse_scope
30
30
 
31
31
  from sqlassert import diagnostics as diag
32
32
  from sqlassert import ir
33
- from sqlassert.diagnostics import Diagnostic
33
+ from sqlassert.diagnostics import Diagnostic, quoted_all
34
34
  from sqlassert.dialects import semantics
35
35
  from sqlassert.ir.convert import IrConversionResult, IrParser
36
36
  from sqlassert.properties import NonNullColumn, Property, ReferentialCoverage, UniqueSet
@@ -48,15 +48,14 @@ class DatabaseRelationKind(Enum):
48
48
  @dataclass(frozen=True)
49
49
  class DatabaseColumn:
50
50
  """One catalog column. `data_type` is its SQL type as the database writes
51
- it (in the fetcher's `type_dialect`), or None when unknown; `collation` is
52
- the collation its comparisons use, None for the database's binary default.
53
- A fetcher that cannot tell a column's collation leaves `data_type` None,
54
- so no comparison is assumed to be by identity."""
51
+ it (in the fetcher's `type_dialect`), or None when unknown. sqlassert
52
+ supports the dialect's default collation only: a fetcher reports a column
53
+ under any other collation that may not compare by identity with
54
+ `data_type` None, so no comparison of it is assumed to be by identity."""
55
55
 
56
56
  name: str
57
57
  nullable: bool
58
58
  data_type: str | None = None
59
- collation: str | None = None
60
59
 
61
60
 
62
61
  @dataclass(frozen=True)
@@ -133,6 +132,26 @@ class DatabaseKnowledgeFetcher(ABC):
133
132
  def hydrate(self, ast: ParsedProgram, *, dialect: str, trust_unenforced_keys: bool = True) -> DatabaseHydration:
134
133
  return _Hydration(self, ast, dialect, trust_unenforced_keys).run()
135
134
 
135
+ def convert(
136
+ self, ast: ParsedProgram, *, dialect: str, trust_unenforced_keys: bool = True,
137
+ ) -> tuple[IrConversionResult, DatabaseHydration]:
138
+ """`hydrate` and `bind` together: the conversion with the catalog's
139
+ declarations, Knowledge and diagnostics merged in, and the hydration.
140
+ Its warnings are the catalog facts' and the SQL's own
141
+ (`diagnostics.SQL_WARNINGS`): a connection warning asks for what the
142
+ catalog has just answered."""
143
+ hydration = self.hydrate(ast, dialect=dialect, trust_unenforced_keys=trust_unenforced_keys)
144
+ conversion = hydration.conversion
145
+ facts = self.bind(conversion.program, hydration)
146
+ merged = replace(
147
+ conversion,
148
+ program=replace(conversion.program, declarations=conversion.program.declarations + facts.declarations),
149
+ knowledge=conversion.knowledge + facts.knowledge,
150
+ diagnostics=hydration.diagnostics + conversion.diagnostics,
151
+ warnings=(*facts.warnings, *(warning for warning in conversion.warnings if warning.code in diag.SQL_WARNINGS)),
152
+ )
153
+ return merged, hydration
154
+
136
155
  def bind(self, program: ir.Program, hydration: DatabaseHydration) -> CatalogFacts:
137
156
  """Catalog facts as Properties over ``program``'s Output Columns.
138
157
 
@@ -155,18 +174,20 @@ class DatabaseKnowledgeFetcher(ABC):
155
174
  else:
156
175
  warnings.append(Diagnostic(
157
176
  diag.UNENFORCED_CONSTRAINT,
158
- f"the {kind} ({', '.join(columns)}) of {metadata.identity} is not Knowledge, since {hydration.dialect} "
177
+ f"the {kind} ({quoted_all(columns)}) of {metadata.identity} is not Knowledge, since {hydration.dialect} "
159
178
  "does not enforce it: if the data satisfies it, analyze with trust_unenforced_keys=True",
160
179
  _origin(metadata),
161
180
  ))
162
181
 
163
- tables = {
164
- metadata.identity.lower(): (relation, metadata)
165
- for relation in program.named_relations
182
+ tables = [
183
+ (relation, metadata) for relation in program.named_relations
166
184
  if relation.role is ir.RelationRole.TABLE and (metadata := hydration.tables.get(relation.name.lower())) is not None
167
- }
185
+ ]
186
+ by_identity: dict[str, list[tuple[ir.NamedRelation, DatabaseRelationMetadata]]] = {}
187
+ for relation, metadata in tables:
188
+ by_identity.setdefault(metadata.identity.lower(), []).append((relation, metadata))
168
189
  keys_enforced = meaning.unique_keys == "enforced"
169
- for relation, metadata in tables.values():
190
+ for relation, metadata in tables:
170
191
  columns = {column.name.lower(): column for column in relation.output_columns}
171
192
  non_null = sorted({column.name.lower() for column in metadata.columns if not column.nullable})
172
193
  knowledge.extend(NonNullColumn(column=columns[name]) for name in non_null if name in columns)
@@ -177,16 +198,14 @@ class DatabaseKnowledgeFetcher(ABC):
177
198
  facts.extend(NonNullColumn(column=columns[name.lower()]) for name in unique_set if name.lower() not in non_null)
178
199
  place(facts, keys_enforced, "primary key" if primary else "unique key", unique_set, metadata)
179
200
  for foreign_key in metadata.foreign_keys:
180
- if foreign_key.referenced.lower() not in tables:
181
- continue
182
- target, target_metadata = tables[foreign_key.referenced.lower()]
183
- if _incomplete_reference(foreign_key, target_metadata):
184
- continue # Never seen from a consistent catalog; no fact is safer than a wrong one.
185
- referenced = {column.name.lower(): column for column in target.output_columns}
186
- place([ReferentialCoverage(
187
- columns=tuple(columns[name.lower()] for name in foreign_key.columns),
188
- referenced_columns=tuple(referenced[name.lower()] for name in foreign_key.referenced_columns),
189
- )], meaning.foreign_keys == "enforced", "foreign key", foreign_key.columns, metadata)
201
+ for target, target_metadata in by_identity.get(foreign_key.referenced.lower(), ()):
202
+ if _incomplete_reference(foreign_key, target_metadata):
203
+ continue # Never seen from a consistent catalog; no fact is safer than a wrong one.
204
+ referenced = {column.name.lower(): column for column in target.output_columns}
205
+ place([ReferentialCoverage(
206
+ columns=tuple(columns[name.lower()] for name in foreign_key.columns),
207
+ referenced_columns=tuple(referenced[name.lower()] for name in foreign_key.referenced_columns),
208
+ )], meaning.foreign_keys == "enforced", "foreign key", foreign_key.columns, metadata)
190
209
  return CatalogFacts(tuple(knowledge), tuple(declarations), tuple(dict.fromkeys(warnings)))
191
210
 
192
211
  @abstractmethod
@@ -217,10 +236,10 @@ def _incompleteness(metadata: DatabaseRelationMetadata) -> str | None:
217
236
  names = {column.name.lower() for column in metadata.columns}
218
237
  for unique_set in _unique_sets(metadata):
219
238
  if not unique_set or not {name.lower() for name in unique_set} <= names:
220
- return f"has a key ({', '.join(unique_set)}) over columns it does not list"
239
+ return f"has a key ({quoted_all(unique_set)}) over columns it does not list"
221
240
  for foreign_key in metadata.foreign_keys:
222
241
  if not {name.lower() for name in foreign_key.columns} <= names or len(foreign_key.columns) != len(foreign_key.referenced_columns):
223
- return f"has a foreign key ({', '.join(foreign_key.columns)}) that does not pair columns it lists"
242
+ return f"has a foreign key ({quoted_all(foreign_key.columns)}) that does not pair columns it lists"
224
243
  return None
225
244
 
226
245
 
@@ -316,7 +335,7 @@ class _Hydration:
316
335
  return declaration
317
336
 
318
337
  def _column_definition(self, column: DatabaseColumn) -> exp.ColumnDef:
319
- """The column with its catalog type and collation, so the Program
338
+ """The column with its catalog type, so the Program
320
339
  compares and enumerates it as the database does; untyped if the type
321
340
  does not parse."""
322
341
  definition = exp.ColumnDef(this=exp.to_identifier(column.name))
@@ -327,9 +346,6 @@ class _Hydration:
327
346
  except SqlglotError:
328
347
  return definition
329
348
  definition.set("kind", kind)
330
- if column.collation is not None:
331
- collate = exp.CollateColumnConstraint(this=exp.to_identifier(column.collation))
332
- definition.append("constraints", exp.ColumnConstraint(kind=collate))
333
349
  return definition
334
350
 
335
351
  def _view(self, metadata: DatabaseRelationMetadata) -> exp.Create | None:
@@ -10,9 +10,10 @@ is missing or incomplete there, and the parameter style.
10
10
 
11
11
  What it reports, and what it leaves out:
12
12
 
13
- - Every column has the dialect's default collation: per-column and
14
- per-table collations are not read (Postgres reports a nondeterministic one,
15
- which would otherwise be taken as comparing by identity).
13
+ - Every column has the dialect's default collation, the only one sqlassert
14
+ supports: per-column and per-table collations are not read, except where
15
+ one would otherwise be taken as comparing by identity (DuckDB's COLLATE,
16
+ Postgres's nondeterministic collations): such a column is reported untyped.
16
17
  - Primary keys, unique constraints, unique indexes and foreign keys are
17
18
  reported as declared; the catalog carries no per-constraint trust. Whether
18
19
  they are Knowledge is the dialect's `DialectSemantics` decision, applied
@@ -13,9 +13,9 @@ columns (not INCLUDE ones), when valid, immediate, with no `WHERE` and no
13
13
  expression. A table other tables inherit from returns their rows too, which
14
14
  its own keys and NOT NULLs do not cover, so it is columns only, as are
15
15
  foreign tables, whose constraints are never checked. A NOT NULL added NOT
16
- VALID does not count. A column's collation is reported only when it is
17
- nondeterministic: the dialect's default compares by identity, and such a
18
- collation does not.
16
+ VALID does not count. A column under a nondeterministic collation is
17
+ reported untyped: sqlassert supports the default collation only, and such a
18
+ collation does not compare by identity (a deterministic one does).
19
19
  """
20
20
 
21
21
  from __future__ import annotations
@@ -48,8 +48,7 @@ SELECT c.relname, a.attname,
48
48
  SELECT 1 FROM pg_catalog.pg_constraint k
49
49
  WHERE k.conrelid = c.oid AND k.contype = 'n' AND NOT k.convalidated AND a.attnum = ANY(k.conkey)
50
50
  ),
51
- pg_catalog.format_type(a.atttypid, a.atttypmod),
52
- CASE WHEN a.attcollation = 0 OR co.collisdeterministic THEN NULL ELSE co.collname END
51
+ CASE WHEN a.attcollation = 0 OR co.collisdeterministic THEN pg_catalog.format_type(a.atttypid, a.atttypmod) END
53
52
  FROM pg_catalog.pg_attribute a
54
53
  JOIN {_RELATION} ON c.oid = a.attrelid
55
54
  LEFT JOIN pg_catalog.pg_collation co ON co.oid = a.attcollation
@@ -116,8 +115,8 @@ class PostgresKnowledgeFetcher(InformationSchemaKnowledgeFetcher):
116
115
 
117
116
  def columns(self, catalog: str, schema: str, tables: Sequence[str]) -> list[tuple[str, DatabaseColumn]]:
118
117
  return [
119
- (table, DatabaseColumn(column, nullable, data_type, collation))
120
- for table, column, nullable, data_type, collation in self._rows(_COLUMNS, (schema, list(tables)))
118
+ (table, DatabaseColumn(column, nullable, data_type))
119
+ for table, column, nullable, data_type in self._rows(_COLUMNS, (schema, list(tables)))
121
120
  ]
122
121
 
123
122
  def keys(self, catalog: str, schema: str, tables: Sequence[str]) -> list[Key]:
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
+