sqlassert 0.3.1__py3-none-any.whl → 0.4.1__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 (73) hide show
  1. sqlassert/__init__.py +1 -2
  2. sqlassert/__main__.py +2 -131
  3. sqlassert/check.py +98 -16
  4. sqlassert/diagnostics.py +31 -7
  5. sqlassert/dialects.py +504 -27
  6. sqlassert/discovery/bigquery.py +3 -1
  7. sqlassert/discovery/databricks.py +25 -2
  8. sqlassert/discovery/duckdb.py +61 -23
  9. sqlassert/discovery/fetcher.py +170 -45
  10. sqlassert/discovery/information_schema.py +34 -5
  11. sqlassert/discovery/mysql.py +22 -1
  12. sqlassert/discovery/postgres.py +28 -12
  13. sqlassert/discovery/redshift.py +3 -2
  14. sqlassert/discovery/snowflake.py +3 -0
  15. sqlassert/discovery/trino.py +2 -2
  16. sqlassert/edits.py +240 -0
  17. sqlassert/hazards.py +735 -0
  18. sqlassert/ir/__init__.py +6 -1
  19. sqlassert/ir/convert/__init__.py +13 -0
  20. sqlassert/ir/convert/aggregation.py +439 -0
  21. sqlassert/ir/convert/builtins.py +140 -0
  22. sqlassert/ir/convert/expressions.py +572 -0
  23. sqlassert/ir/convert/joins.py +264 -0
  24. sqlassert/ir/convert/markers.py +249 -0
  25. sqlassert/ir/convert/parser.py +253 -0
  26. sqlassert/ir/convert/queries.py +259 -0
  27. sqlassert/ir/convert/schema.py +606 -0
  28. sqlassert/ir/convert/scopes.py +205 -0
  29. sqlassert/ir/convert/selects.py +337 -0
  30. sqlassert/ir/convert/shared.py +429 -0
  31. sqlassert/ir/convert/sources.py +432 -0
  32. sqlassert/ir/convert/subqueries.py +364 -0
  33. sqlassert/ir/convert/value_types.py +223 -0
  34. sqlassert/ir/convert/windows.py +275 -0
  35. sqlassert/ir/model.py +247 -66
  36. sqlassert/ir/names.py +63 -0
  37. sqlassert/main.py +3 -9
  38. sqlassert/properties.py +12 -1
  39. sqlassert/provenance.py +5 -1
  40. sqlassert/python_engine.py +167 -50
  41. sqlassert/reporting.py +36 -32
  42. sqlassert/rewrites.py +1591 -0
  43. sqlassert/rules/STYLEGUIDE.md +3 -2
  44. sqlassert/rules/causes/__init__.py +41 -0
  45. sqlassert/rules/causes/coverage.py +113 -0
  46. sqlassert/rules/causes/domain.py +123 -0
  47. sqlassert/rules/causes/joins.py +73 -0
  48. sqlassert/rules/causes/nulls.py +154 -0
  49. sqlassert/rules/causes/unique.py +523 -0
  50. sqlassert/rules/domain.py +123 -26
  51. sqlassert/rules/equality.py +153 -85
  52. sqlassert/rules/exactly_one.py +42 -2
  53. sqlassert/rules/foreign_key.py +15 -13
  54. sqlassert/rules/join_cardinality.py +302 -39
  55. sqlassert/rules/nullability.py +244 -35
  56. sqlassert/rules/uniqueness.py +513 -86
  57. sqlassert/rules/value_typing.py +337 -0
  58. sqlassert/sql_parse.py +224 -90
  59. sqlassert/suggest.py +132 -57
  60. sqlassert-0.4.1.dist-info/METADATA +235 -0
  61. sqlassert-0.4.1.dist-info/RECORD +69 -0
  62. sqlassert-0.4.1.dist-info/entry_points.txt +2 -0
  63. sqlassert-0.4.1.dist-info/top_level.txt +2 -0
  64. sqlassert_cli.py +130 -0
  65. sqlassert/improvements.py +0 -528
  66. sqlassert/ir/convert.py +0 -2377
  67. sqlassert/smells.py +0 -306
  68. sqlassert-0.3.1.dist-info/METADATA +0 -725
  69. sqlassert-0.3.1.dist-info/RECORD +0 -44
  70. sqlassert-0.3.1.dist-info/entry_points.txt +0 -2
  71. sqlassert-0.3.1.dist-info/top_level.txt +0 -1
  72. {sqlassert-0.3.1.dist-info → sqlassert-0.4.1.dist-info}/WHEEL +0 -0
  73. {sqlassert-0.3.1.dist-info → sqlassert-0.4.1.dist-info}/licenses/LICENSE +0 -0
@@ -10,15 +10,20 @@ 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
19
20
  by `DatabaseKnowledgeFetcher.bind`: where the dialect does not enforce them
20
21
  they hold only under `trust_unenforced_keys`.
21
22
  - A unique index with a `WHERE` or an expression key part is never a key.
23
+ One over the same columns as another key is reported once.
24
+ - CHECK constraints are reported only where the database enforces them, as
25
+ the text of their condition; the hydration declares them with the table,
26
+ so they mean what the same CHECK written in SQL means.
22
27
  """
23
28
 
24
29
  from __future__ import annotations
@@ -161,6 +166,13 @@ ORDER BY k.TABLE_NAME, k.CONSTRAINT_NAME, k.ORDINAL_POSITION
161
166
  """
162
167
  return foreign_keys_from_pairs(self._rows(sql, (schema, *tables)))
163
168
 
169
+ def checks(self, catalog: str, schema: str, tables: Sequence[str]) -> list[tuple[str, str]]:
170
+ """Each enforced CHECK constraint's condition, as SQL text in the
171
+ dialect, by table. None here: of the dialects on the standard views
172
+ alone, Snowflake, BigQuery, Redshift and Trino have no CHECK
173
+ constraints; a dialect that enforces them overrides this."""
174
+ return []
175
+
164
176
  def view_definition(self, relation: DatabaseRelationMetadata) -> str | None:
165
177
  """The view's stored text: its body, or a whole `CREATE VIEW`."""
166
178
  sql = f"SELECT VIEW_DEFINITION FROM {self.information_schema(relation.catalog, relation.schema)}.VIEWS WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s"
@@ -197,6 +209,7 @@ ORDER BY k.TABLE_NAME, k.CONSTRAINT_NAME, k.ORDINAL_POSITION
197
209
  columns: dict[_Key, list[DatabaseColumn]] = {}
198
210
  keys: dict[_Key, list[Key]] = {}
199
211
  foreign_keys: dict[_Key, list[DatabaseForeignKey]] = {}
212
+ checks: dict[_Key, list[str]] = {}
200
213
  for (table_catalog, schema), group in tables.items():
201
214
  listed = sorted(group)
202
215
  for table, column in self.columns(table_catalog, schema, listed):
@@ -205,6 +218,8 @@ ORDER BY k.TABLE_NAME, k.CONSTRAINT_NAME, k.ORDINAL_POSITION
205
218
  keys.setdefault((table_catalog, schema, key.table), []).append(key)
206
219
  for table, foreign_key in self.foreign_keys(table_catalog, schema, listed):
207
220
  foreign_keys.setdefault((table_catalog, schema, table), []).append(foreign_key)
221
+ for table, condition in self.checks(table_catalog, schema, listed):
222
+ checks.setdefault((table_catalog, schema, table), []).append(condition)
208
223
 
209
224
  metadata: dict[str, DatabaseRelationMetadata] = {}
210
225
  for name, relation in resolved.items():
@@ -218,11 +233,13 @@ ORDER BY k.TABLE_NAME, k.CONSTRAINT_NAME, k.ORDINAL_POSITION
218
233
  metadata[name] = DatabaseRelationMetadata(*path_key, DatabaseRelationKind.TABLE, own)
219
234
  continue
220
235
  table_keys = keys.get(path_key, [])
236
+ primary_key = next((key.columns for key in table_keys if key.primary), ())
221
237
  metadata[name] = DatabaseRelationMetadata(
222
238
  *path_key, DatabaseRelationKind.TABLE, own,
223
- primary_key=next((key.columns for key in table_keys if key.primary), ()),
224
- unique_sets=tuple(key.columns for key in table_keys if not key.primary),
239
+ primary_key=primary_key,
240
+ unique_sets=_distinct_sets(primary_key, [key.columns for key in table_keys if not key.primary]),
225
241
  foreign_keys=tuple(foreign_keys.get(path_key, ())),
242
+ checks=tuple(checks.get(path_key, ())),
226
243
  )
227
244
  return metadata
228
245
 
@@ -322,5 +339,17 @@ def placeholders(values: Sequence[Any]) -> str:
322
339
  return ", ".join(["%s"] * len(values))
323
340
 
324
341
 
342
+ def _distinct_sets(primary_key: tuple[str, ...], unique_sets: Sequence[tuple[str, ...]]) -> tuple[tuple[str, ...], ...]:
343
+ """Each unique set once, and none that repeats the primary key: a unique
344
+ index may repeat a UNIQUE constraint over the same columns."""
345
+ seen = {frozenset(name.lower() for name in primary_key)} if primary_key else set()
346
+ distinct: list[tuple[str, ...]] = []
347
+ for columns in unique_sets:
348
+ if (lowered := frozenset(name.lower() for name in columns)) not in seen:
349
+ seen.add(lowered)
350
+ distinct.append(columns)
351
+ return tuple(distinct)
352
+
353
+
325
354
  def _lower(path: tuple[str, str, str]) -> _Key:
326
355
  return (path[0].lower(), path[1].lower(), path[2].lower())
@@ -11,7 +11,10 @@ Over any DB-API connection (PyMySQL, mysqlclient, mysql-connector). Overrides:
11
11
  primary key is named `PRIMARY`, which the standard join cannot tell apart.
12
12
  Only engines that enforce foreign keys (InnoDB, NDB) keep them in the
13
13
  catalog. `foreign_key_checks = 0` lets a session load rows that violate
14
- one, which no catalog records.
14
+ one, which no catalog records;
15
+ - checks: `CHECK_CONSTRAINTS`, joined to `TABLE_CONSTRAINTS` for the table
16
+ and `ENFORCED = 'YES'` (a NOT ENFORCED CHECK is never checked; an enforced
17
+ one added by ALTER TABLE checks the rows already there).
15
18
 
16
19
  MySQL has one catalog, which `information_schema` names `def`. A stored view
17
20
  definition qualifies every table it reads; an unqualified name in the Program
@@ -20,6 +23,7 @@ is in the current database.
20
23
 
21
24
  from __future__ import annotations
22
25
 
26
+ import re
23
27
  from collections.abc import Sequence
24
28
 
25
29
  from sqlassert.discovery.fetcher import DatabaseColumn, DatabaseForeignKey
@@ -68,3 +72,20 @@ class MySQLKnowledgeFetcher(InformationSchemaKnowledgeFetcher):
68
72
  "ORDER BY TABLE_NAME, CONSTRAINT_NAME, ORDINAL_POSITION"
69
73
  )
70
74
  return foreign_keys_from_pairs(self._rows(sql, (schema, *tables)))
75
+
76
+ def checks(self, catalog: str, schema: str, tables: Sequence[str]) -> list[tuple[str, str]]:
77
+ # CHECK constraint names are unique within a schema.
78
+ sql = (
79
+ "SELECT t.TABLE_NAME, c.CHECK_CLAUSE FROM information_schema.TABLE_CONSTRAINTS t "
80
+ "JOIN information_schema.CHECK_CONSTRAINTS c "
81
+ "ON c.CONSTRAINT_SCHEMA = t.CONSTRAINT_SCHEMA AND c.CONSTRAINT_NAME = t.CONSTRAINT_NAME "
82
+ f"WHERE t.CONSTRAINT_TYPE = 'CHECK' AND t.ENFORCED = 'YES' AND t.TABLE_SCHEMA = %s AND t.TABLE_NAME IN ({placeholders(tables)}) "
83
+ "ORDER BY t.TABLE_NAME, t.CONSTRAINT_NAME"
84
+ )
85
+ return [(table, _unescaped(clause)) for table, clause in self._rows(sql, (schema, *tables))]
86
+
87
+
88
+ def _unescaped(clause: str) -> str:
89
+ """`CHECK_CLAUSE` is the condition with each backslash and quote escaped
90
+ once more (`_utf8mb4\\'x\\'` for `_utf8mb4'x'`; probed, MySQL 8.4.13)."""
91
+ return re.sub(r"\\(.)", r"\1", clause, flags=re.DOTALL)
@@ -5,17 +5,17 @@ its table or holds a privilege on it other than SELECT, and a view's text only
5
5
  to its owner, so a read-only role would see no keys. Every hook here reads
6
6
  `pg_catalog` instead, over any DB-API connection (psycopg, psycopg2).
7
7
 
8
- Only constraints that hold on every row are reported: validated, enforced
9
- (PostgreSQL 18 has NOT ENFORCED), not DEFERRABLE, and, for a foreign key,
10
- onto a table without row-level security, which may hide a referenced row
11
- from the reader. Unique indexes no constraint owns count, over their key
8
+ Only constraints (keys, foreign keys, CHECKs) that hold on every row are
9
+ reported: validated, enforced (PostgreSQL 18 has NOT ENFORCED), not
10
+ DEFERRABLE, and, for a foreign key, onto a table without row-level
11
+ security, which may hide a referenced row from the reader. Unique indexes no constraint owns count, over their key
12
12
  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
- its own keys and NOT NULLs do not cover, so it is columns only, as are
14
+ its own keys, NOT NULLs and CHECKs need 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
@@ -86,6 +85,19 @@ WHERE i.indisunique AND i.indisvalid AND i.indimmediate AND i.indpred IS NULL AN
86
85
  ORDER BY c.relname, i.indexrelid
87
86
  """
88
87
 
88
+ # A CHECK holds on every row once validated (one added NOT VALID has not
89
+ # checked the rows already there) and, in PostgreSQL 18, enforced; it is
90
+ # never deferrable. Column-level and table-level ones are alike here.
91
+ # `pg_get_expr` deparses the stored condition: `col IN (...)` comes back as
92
+ # `col = ANY (ARRAY[...])`, literals cast, which the CHECK reading accepts.
93
+ _CHECKS = f"""
94
+ SELECT c.relname, pg_catalog.pg_get_expr(k.conbin, k.conrelid)
95
+ FROM pg_catalog.pg_constraint k
96
+ JOIN {_RELATION} ON c.oid = k.conrelid
97
+ WHERE k.contype = 'c' AND k.convalidated {{enforced}} AND {_TABLES}
98
+ ORDER BY c.relname, k.conname
99
+ """
100
+
89
101
  VIEW = f"""
90
102
  SELECT pg_catalog.pg_get_viewdef(c.oid, true)
91
103
  FROM {_RELATION}
@@ -116,8 +128,8 @@ class PostgresKnowledgeFetcher(InformationSchemaKnowledgeFetcher):
116
128
 
117
129
  def columns(self, catalog: str, schema: str, tables: Sequence[str]) -> list[tuple[str, DatabaseColumn]]:
118
130
  return [
119
- (table, DatabaseColumn(column, nullable, data_type, collation))
120
- for table, column, nullable, data_type, collation in self._rows(_COLUMNS, (schema, list(tables)))
131
+ (table, DatabaseColumn(column, nullable, data_type))
132
+ for table, column, nullable, data_type in self._rows(_COLUMNS, (schema, list(tables)))
121
133
  ]
122
134
 
123
135
  def keys(self, catalog: str, schema: str, tables: Sequence[str]) -> list[Key]:
@@ -135,6 +147,10 @@ class PostgresKnowledgeFetcher(InformationSchemaKnowledgeFetcher):
135
147
  in self._rows(self._constraints("'f'"), (schema, list(tables)))
136
148
  ]
137
149
 
150
+ def checks(self, catalog: str, schema: str, tables: Sequence[str]) -> list[tuple[str, str]]:
151
+ sql = _CHECKS.format(enforced="AND k.conenforced" if self._enforced else "")
152
+ return [(table, condition) for table, condition in self._rows(sql, (schema, list(tables)))]
153
+
138
154
  def view_definition(self, relation: DatabaseRelationMetadata) -> str | None:
139
155
  rows = self._rows(VIEW, (relation.schema, relation.name))
140
156
  return rows[0][0] if rows else None
@@ -1,8 +1,9 @@
1
1
  """Amazon Redshift: the standard discovery, over any DB-API connection (redshift_connector, psycopg2).
2
2
 
3
3
  Redshift keeps PostgreSQL 8's `information_schema` and has no indexes, so
4
- there are no unique indexes to read. Its keys are not enforced: they hold
5
- only under `trust_unenforced_keys` (`dialects.py`). Overrides:
4
+ there are no unique indexes to read, nor CHECK constraints, which it does
5
+ not support. Its keys are not enforced: they hold only under
6
+ `trust_unenforced_keys` (`dialects.py`). Overrides:
6
7
 
7
8
  - session: `current_database()` and `current_schema()`. An unqualified name
8
9
  is looked up in the current schema only, so a table found later on the
@@ -8,6 +8,9 @@ enforced: they hold only under `trust_unenforced_keys` (`dialects.py`); the
8
8
  `rely` column those commands return is not read. `VIEWS.VIEW_DEFINITION` is
9
9
  the whole `CREATE VIEW`, and names inside it resolve in the view's own
10
10
  database and schema. Names qualified by another database are not looked up.
11
+ Snowflake has no unique indexes: a hybrid table's indexes are not unique, and
12
+ its UNIQUE constraints are read with the other keys. Snowflake has no CHECK
13
+ constraints, so none are read.
11
14
  """
12
15
 
13
16
  from __future__ import annotations
@@ -3,8 +3,8 @@
3
3
  Trino federates catalogs, each with its own `catalog.information_schema`;
4
4
  a name may be qualified by any catalog. Its `information_schema` has
5
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
6
+ or CHECK constraints or indexes, and does not surface those a connector's source
7
+ enforces, so a Trino catalog reports NOT NULLs and no keys. That loses proofs, never
8
8
  soundness. Parameters are `?` (the client's qmark style).
9
9
  """
10
10
 
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
+