sqlassert-dbt 0.3.3__tar.gz → 0.4.2__tar.gz

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 (44) hide show
  1. {sqlassert_dbt-0.3.3/sqlassert_dbt.egg-info → sqlassert_dbt-0.4.2}/PKG-INFO +7 -9
  2. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/README.md +5 -7
  3. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/pyproject.toml +3 -3
  4. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/sqlassert_dbt/__init__.py +1 -1
  5. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/sqlassert_dbt/__main__.py +1 -1
  6. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/sqlassert_dbt/connect.py +6 -8
  7. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/sqlassert_dbt/expectations.py +49 -17
  8. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/sqlassert_dbt/manifest.py +52 -2
  9. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/sqlassert_dbt/program.py +187 -125
  10. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/sqlassert_dbt/project.py +8 -2
  11. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2/sqlassert_dbt.egg-info}/PKG-INFO +7 -9
  12. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/sqlassert_dbt.egg-info/SOURCES.txt +1 -0
  13. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/sqlassert_dbt.egg-info/scm_file_list.json +1 -0
  14. sqlassert_dbt-0.4.2/sqlassert_dbt.egg-info/scm_version.json +8 -0
  15. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/tests/conftest.py +7 -0
  16. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/tests/test_contracts.py +2 -14
  17. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/tests/test_dbt.py +54 -20
  18. sqlassert_dbt-0.4.2/tests/test_file_sources.py +114 -0
  19. sqlassert_dbt-0.3.3/sqlassert_dbt.egg-info/scm_version.json +0 -8
  20. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/LICENSE +0 -0
  21. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/setup.cfg +0 -0
  22. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/sqlassert_dbt/jinja.py +0 -0
  23. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/sqlassert_dbt/report.py +0 -0
  24. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/sqlassert_dbt.egg-info/dependency_links.txt +0 -0
  25. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/sqlassert_dbt.egg-info/entry_points.txt +0 -0
  26. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/sqlassert_dbt.egg-info/requires.txt +1 -1
  27. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/sqlassert_dbt.egg-info/top_level.txt +0 -0
  28. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/tests/dbt_project/dbt_project.yml +0 -0
  29. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/tests/dbt_project/models/active_customers.sql +0 -0
  30. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/tests/dbt_project/models/customer_keys.sql +0 -0
  31. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/tests/dbt_project/models/customer_orders.sql +0 -0
  32. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/tests/dbt_project/models/customer_signups.sql +0 -0
  33. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/tests/dbt_project/models/customers.sql +0 -0
  34. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/tests/dbt_project/models/orders_appended.sql +0 -0
  35. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/tests/dbt_project/models/orders_incremental.sql +0 -0
  36. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/tests/dbt_project/models/schema.yml +0 -0
  37. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/tests/dbt_project/models/stg_customers.sql +0 -0
  38. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/tests/dbt_project/models/stg_orders.sql +0 -0
  39. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/tests/dbt_project/profiles.yml +0 -0
  40. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/tests/dbt_project/seeds/raw_payments.csv +0 -0
  41. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/tests/dbt_runs.py +0 -0
  42. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/tests/test_catalog.py +0 -0
  43. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/tests/test_connect.py +0 -0
  44. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.2}/tests/test_suggest.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sqlassert-dbt
3
- Version: 0.3.3
3
+ Version: 0.4.2
4
4
  Summary: Check a dbt project's tests and sqlassert markers from its compiled manifest.
5
5
  Author: Fred Israel
6
6
  License-Expression: MIT
@@ -14,10 +14,10 @@ Classifier: Topic :: Software Development :: Quality Assurance
14
14
  Requires-Python: >=3.13
15
15
  Description-Content-Type: text/markdown
16
16
  License-File: LICENSE
17
+ Requires-Dist: dbt-core>=1.12
17
18
  Requires-Dist: sqlassert>=0.3.1
18
19
  Requires-Dist: sqlglot<31,>=30.30
19
20
  Provides-Extra: test
20
- Requires-Dist: dbt-core>=1.12; extra == "test"
21
21
  Requires-Dist: dbt-duckdb>=1.11; extra == "test"
22
22
  Requires-Dist: duckdb; extra == "test"
23
23
  Requires-Dist: pytest; extra == "test"
@@ -64,10 +64,9 @@ A `profiles.yml` kept in the project directory is found without
64
64
  `--profiles-dir` (by `build`, `test` and `suggest`), unless the working
65
65
  directory has one or `DBT_PROFILES_DIR` is set.
66
66
 
67
- ## Check without dbt
67
+ ## Check
68
68
 
69
- `check` reads only `target/manifest.json`, so dbt does not need to be installed
70
- where it runs (a CI step after `dbt compile`, say):
69
+ `check` reads `target/manifest.json`, so run it after `dbt compile`:
71
70
 
72
71
  ```bash
73
72
  $ dbt compile
@@ -122,7 +121,7 @@ manifest cannot be read.
122
121
  A model's own tests are what gets proved. Upstream tests are evidence, used
123
122
  only when they fail on any failing row: not a test with `severity: warn`, a
124
123
  `where:` config, or `error_if`/`fail_calc` thresholds. A constraint counts only
125
- on a contracted table whose adapter enforces it.
124
+ on a table with an enforced contract, whether or not the adapter checks it.
126
125
 
127
126
  ## Suggest from the models you're editing
128
127
 
@@ -217,8 +216,7 @@ read then. An enforced contract's table is still declared from the contract,
217
216
  since the build may not have made it yet; every other table comes from the
218
217
  warehouse.
219
218
  As with `analyze_database`, a connection only adds proofs. A key the
220
- warehouse does not enforce is trusted as a Property Declaration, as the SQL's
221
- own are.
219
+ warehouse does not enforce is trusted, as the SQL's own are.
222
220
 
223
221
  ```bash
224
222
  $ sqlassert-dbt build --connect .
@@ -238,7 +236,7 @@ report = analyze_project(project, fetcher=DuckDBKnowledgeFetcher(duckdb.connect(
238
236
  ```
239
237
 
240
238
  `suggest_models(..., fetcher=...)` takes one too. `check` stays
241
- connectionless: it runs where dbt is not installed.
239
+ connectionless.
242
240
 
243
241
  ## Details
244
242
 
@@ -39,10 +39,9 @@ A `profiles.yml` kept in the project directory is found without
39
39
  `--profiles-dir` (by `build`, `test` and `suggest`), unless the working
40
40
  directory has one or `DBT_PROFILES_DIR` is set.
41
41
 
42
- ## Check without dbt
42
+ ## Check
43
43
 
44
- `check` reads only `target/manifest.json`, so dbt does not need to be installed
45
- where it runs (a CI step after `dbt compile`, say):
44
+ `check` reads `target/manifest.json`, so run it after `dbt compile`:
46
45
 
47
46
  ```bash
48
47
  $ dbt compile
@@ -97,7 +96,7 @@ manifest cannot be read.
97
96
  A model's own tests are what gets proved. Upstream tests are evidence, used
98
97
  only when they fail on any failing row: not a test with `severity: warn`, a
99
98
  `where:` config, or `error_if`/`fail_calc` thresholds. A constraint counts only
100
- on a contracted table whose adapter enforces it.
99
+ on a table with an enforced contract, whether or not the adapter checks it.
101
100
 
102
101
  ## Suggest from the models you're editing
103
102
 
@@ -192,8 +191,7 @@ read then. An enforced contract's table is still declared from the contract,
192
191
  since the build may not have made it yet; every other table comes from the
193
192
  warehouse.
194
193
  As with `analyze_database`, a connection only adds proofs. A key the
195
- warehouse does not enforce is trusted as a Property Declaration, as the SQL's
196
- own are.
194
+ warehouse does not enforce is trusted, as the SQL's own are.
197
195
 
198
196
  ```bash
199
197
  $ sqlassert-dbt build --connect .
@@ -213,7 +211,7 @@ report = analyze_project(project, fetcher=DuckDBKnowledgeFetcher(duckdb.connect(
213
211
  ```
214
212
 
215
213
  `suggest_models(..., fetcher=...)` takes one too. `check` stays
216
- connectionless: it runs where dbt is not installed.
214
+ connectionless.
217
215
 
218
216
  ## Details
219
217
 
@@ -18,9 +18,10 @@ classifiers = [
18
18
  "Topic :: Database",
19
19
  "Topic :: Software Development :: Quality Assurance",
20
20
  ]
21
- # Reads target/manifest.json only: dbt itself is needed to compile the
22
- # project, not to check it, so it is a test dependency here.
21
+ # The plugin may use dbt itself (compiling, connecting); the sqlassert
22
+ # package never does.
23
23
  dependencies = [
24
+ "dbt-core>=1.12",
24
25
  "sqlassert>=0.3.1",
25
26
  "sqlglot>=30.30,<31",
26
27
  ]
@@ -34,7 +35,6 @@ sqlassert-dbt = "sqlassert_dbt.__main__:main"
34
35
 
35
36
  [project.optional-dependencies]
36
37
  test = [
37
- "dbt-core>=1.12",
38
38
  "dbt-duckdb>=1.11",
39
39
  "duckdb",
40
40
  "pytest",
@@ -1,4 +1,4 @@
1
- """dbt integration: check a dbt project's tests and Property Markers from its manifest, without dbt.
1
+ """dbt integration: check a dbt project's tests and Property Markers from its manifest.
2
2
 
3
3
  `analyze_project(project_dir)` reads `target/manifest.json` and returns a
4
4
  `DbtReport`: which tests the SQL proves (skippable), which it does not, which
@@ -59,7 +59,7 @@ def main(argv: list[str] | None = None) -> int:
59
59
  commands = parser.add_subparsers(dest="command", required=True)
60
60
  check = commands.add_parser(
61
61
  "check",
62
- help="check the tests and markers of a compiled project, without dbt",
62
+ help="check the tests and markers of a compiled project",
63
63
  description="Check a dbt project's tests and markers from its target/manifest.json (run `dbt compile` first). "
64
64
  f"Exit status: {EXIT_OK} every marker PROVED, {EXIT_FINDINGS} a marker UNKNOWN or a diagnostic reported, "
65
65
  f"{EXIT_USAGE} the manifest cannot be read.",
@@ -61,14 +61,12 @@ def dbt_fetcher(project: Path, dbt_arguments: list[str]) -> Generator[DatabaseKn
61
61
  """A fetcher over the connection dbt opens for `project` with the
62
62
  profile, target, profiles directory and vars in `dbt_arguments`, closed
63
63
  on exit: a DuckDB file takes one writer, so close it before dbt runs again."""
64
- try:
65
- import yaml
66
- from dbt.adapters.factory import cleanup_connections, get_adapter, register_adapter, reset_adapters
67
- from dbt.config.runtime import RuntimeConfig
68
- from dbt.flags import set_from_args
69
- from dbt.mp_context import get_mp_context
70
- except ImportError as error:
71
- raise ConnectError(f"--connect needs dbt installed in sqlassert-dbt's Python ({error})") from error
64
+ import yaml
65
+ from dbt.adapters.factory import cleanup_connections, get_adapter, register_adapter, reset_adapters
66
+ from dbt.config.runtime import RuntimeConfig
67
+ from dbt.flags import set_from_args
68
+ from dbt.mp_context import get_mp_context
69
+
72
70
  try:
73
71
  args = Namespace(
74
72
  project_dir=str(project), profiles_dir=str(_profiles_dir(project, dbt_arguments)),
@@ -30,14 +30,8 @@ from sqlassert.sql_parse import literal_value
30
30
  # Referential Coverage (a dbt relationships test checks no Unique Set on its target).
31
31
  type PropertyKind = Literal["unique", "key", "not_null", "enum", "coverage"]
32
32
 
33
- # Constraint types each adapter enforces when a contracted table is built
34
- # (dbt's per-adapter `CONSTRAINT_SUPPORT`). Every other adapter enforces
35
- # NOT NULL only; their keys are informational. Constraints never apply to views.
36
- _ENFORCED_CONSTRAINTS = {
37
- "postgres": frozenset({"not_null", "unique", "primary_key", "foreign_key"}),
38
- "duckdb": frozenset({"not_null", "unique", "primary_key", "foreign_key"}),
39
- }
40
- _NOT_NULL_ONLY = frozenset({"not_null"})
33
+ # Constraints a contracted table declares, whether or not the adapter enforces
34
+ # them (ADR 0012); they never apply to views.
41
35
  _CONSTRAINED_MATERIALIZATIONS = {"table", "incremental"}
42
36
 
43
37
  _IDENTIFIER = re.compile(r"[A-Za-z_][A-Za-z0-9_$]*")
@@ -91,18 +85,28 @@ def _test(test: Test, relations: Mapping[str, Relation]) -> Expectation | None:
91
85
  weakness = _weakness(test)
92
86
  unprovable = _threshold_unprovable(test)
93
87
  name = test.test_name if test.namespace is None else f"{test.namespace}.{test.test_name}"
88
+ kwargs = test.kwargs
89
+ # Written with or without its package's name, and whether the project
90
+ # overrides it or not: an override that keeps the name and signature is
91
+ # taken to keep the meaning.
92
+ expectation = f"dbt_expectations.{test.test_name}" if test.namespace in (None, "dbt_expectations") else None
93
+ if expectation in _DBT_EXPECTATIONS:
94
+ # The same checks as the core tests, unless a filter or ignored rows narrow them.
95
+ if kwargs.get("row_condition") or kwargs.get("ignore_row_if", "all_values_are_missing") not in _CHECKED_ROWS[expectation]:
96
+ return replace(base, asserted=None, declared=None, unprovable="it checks only the rows its row_condition or ignore_row_if keeps")
97
+ name, kwargs = _DBT_EXPECTATIONS[expectation], {**kwargs, **_expectation_kwargs(kwargs)}
94
98
  match name:
95
99
  case None:
96
100
  return replace(base, asserted=None, declared=None, unprovable="a singular test states no Property")
97
101
  case "unique" | "not_null" | "accepted_values" | "relationships":
98
- column = _column(test.kwargs.get("column_name") or test.column_name)
102
+ column = _column(kwargs.get("column_name") or test.column_name)
99
103
  if column is None:
100
104
  return replace(
101
105
  base,
102
- unprovable=f"it tests the expression {test.kwargs.get('column_name') or test.column_name!r}, not a column",
106
+ unprovable=f"it tests the expression {kwargs.get('column_name') or test.column_name!r}, not a column",
103
107
  )
104
108
  case "dbt_utils.unique_combination_of_columns":
105
- names = test.kwargs.get("combination_of_columns")
109
+ names = kwargs.get("combination_of_columns")
106
110
  columns = tuple(_column(name) for name in names) if isinstance(names, list) and names else (None,)
107
111
  if None in columns:
108
112
  return replace(base, asserted=None, declared=None, unprovable="its columns are not all plain columns")
@@ -118,15 +122,15 @@ def _test(test: Test, relations: Mapping[str, Relation]) -> Expectation | None:
118
122
  case "not_null":
119
123
  return replace(base, asserted="not_null", declared="not_null", columns=(column,), unprovable=unprovable, not_a_fact=weakness)
120
124
  case "accepted_values":
121
- values = _accepted_values(test.kwargs.get("values"), test.kwargs.get("quote", True))
125
+ values = _accepted_values(kwargs.get("values"), kwargs.get("quote", True))
122
126
  if values is None:
123
127
  return replace(base, asserted=None, declared=None, unprovable="its values are not all string, numeric or boolean literals")
124
128
  return replace(
125
129
  base, asserted="enum", declared="enum", columns=(column,), values=values, unprovable=unprovable, not_a_fact=weakness,
126
130
  )
127
131
  case _:
128
- target = _resolve_call(test.kwargs.get("to"), test.depends_on, relations)
129
- field = _column(test.kwargs.get("field"))
132
+ target = _resolve_call(kwargs.get("to"), test.depends_on, relations)
133
+ field = _column(kwargs.get("field"))
130
134
  if target is None or field is None:
131
135
  return replace(base, asserted=None, declared=None, unprovable="its `to` or `field` cannot be resolved")
132
136
  return replace(
@@ -135,6 +139,37 @@ def _test(test: Test, relations: Mapping[str, Relation]) -> Expectation | None:
135
139
  )
136
140
 
137
141
 
142
+ # dbt_expectations tests that check at least what a core or dbt_utils test
143
+ # checks: compound uniqueness over the rows not all NULL (rows with some NULL
144
+ # are checked too, which only adds rows to compare) or over the rows with no
145
+ # NULL (a Unique Set exempts the others too), uniqueness, non-null, and a
146
+ # value set (which also rejects NULL, more than accepted_values asks).
147
+ _DBT_EXPECTATIONS = {
148
+ "dbt_expectations.expect_compound_columns_to_be_unique": "dbt_utils.unique_combination_of_columns",
149
+ "dbt_expectations.expect_column_values_to_be_unique": "unique",
150
+ "dbt_expectations.expect_column_values_to_not_be_null": "not_null",
151
+ "dbt_expectations.expect_column_values_to_be_in_set": "accepted_values",
152
+ }
153
+ # The `ignore_row_if` each leaves checking enough rows for its Property.
154
+ _CHECKED_ROWS = {
155
+ name: ("all_values_are_missing", "any_value_is_missing") if name.endswith("compound_columns_to_be_unique")
156
+ else ("all_values_are_missing",)
157
+ for name in _DBT_EXPECTATIONS
158
+ }
159
+
160
+
161
+ def _expectation_kwargs(kwargs: Mapping[str, object]) -> dict[str, object]:
162
+ """A dbt_expectations test's arguments under the names its core twin reads."""
163
+ renamed: dict[str, object] = {}
164
+ if "column_list" in kwargs:
165
+ renamed["combination_of_columns"] = kwargs["column_list"]
166
+ if "value_set" in kwargs:
167
+ renamed["values"] = kwargs["value_set"]
168
+ if "quote_values" in kwargs:
169
+ renamed["quote"] = kwargs["quote_values"]
170
+ return renamed
171
+
172
+
138
173
  def _attached(test: Test, relations: Mapping[str, Relation]) -> str | None:
139
174
  if test.attached_node in relations:
140
175
  return test.attached_node
@@ -274,7 +309,6 @@ def resolve(
274
309
 
275
310
 
276
311
  def _constraints(relation: Relation, manifest: Manifest) -> Iterator[Expectation]:
277
- enforced = _ENFORCED_CONSTRAINTS.get(manifest.adapter_type or "", _NOT_NULL_ONLY)
278
312
  for index, constraint in enumerate(relation.constraints):
279
313
  kind: PropertyKind
280
314
  match constraint.type:
@@ -292,8 +326,6 @@ def _constraints(relation: Relation, manifest: Manifest) -> Iterator[Expectation
292
326
  not_a_fact = "the model's contract is not enforced"
293
327
  elif relation.materialized not in _CONSTRAINED_MATERIALIZATIONS:
294
328
  not_a_fact = f"constraints are not applied to a {relation.materialized} materialization"
295
- elif constraint.type not in enforced:
296
- not_a_fact = f"{manifest.adapter_type} does not enforce {constraint.type} constraints"
297
329
  else:
298
330
  not_a_fact = None
299
331
  base = Expectation(
@@ -10,9 +10,10 @@ manifest that is not a JSON object of nodes is a `ManifestError`.
10
10
  from __future__ import annotations
11
11
 
12
12
  import json
13
+ import re
13
14
  from collections.abc import Mapping
14
- from dataclasses import dataclass, field
15
- from pathlib import Path
15
+ from dataclasses import dataclass, field, replace
16
+ from pathlib import Path, PurePosixPath
16
17
  from typing import Any
17
18
 
18
19
 
@@ -82,6 +83,9 @@ class Relation:
82
83
  extra_ctes: tuple[InjectedCte, ...] = ()
83
84
  source_name: str | None = None
84
85
  version: str | None = None
86
+ # A source that reads files (dbt-duckdb `external_location`): the read dbt
87
+ # pasted where a table name goes; `relation_name` is then its stand-in.
88
+ file_read: str | None = None
85
89
 
86
90
  @property
87
91
  def label(self) -> str:
@@ -149,6 +153,7 @@ def load_manifest(path: Path) -> Manifest:
149
153
  for unique_id, node in _mapping(document.get("sources")).items():
150
154
  if isinstance(node, dict):
151
155
  relations[unique_id] = _relation(unique_id, node)
156
+ relations = _name_file_reads(relations)
152
157
  return Manifest(
153
158
  adapter_type=_text(metadata.get("adapter_type")),
154
159
  project_name=_text(metadata.get("project_name")),
@@ -158,6 +163,51 @@ def load_manifest(path: Path) -> Manifest:
158
163
  )
159
164
 
160
165
 
166
+ # What dbt-duckdb pastes for a source with `external_location`: a DuckDB
167
+ # `read_*` table function, or a quoted path DuckDB reads by its extension.
168
+ _FILE_READ = re.compile(r"read_[a-z0-9_]+\s*\(.*\)|'(?:[^']|'')*'", re.IGNORECASE | re.DOTALL)
169
+ _QUOTED = re.compile(r"'((?:[^']|'')*)'")
170
+
171
+
172
+ def _name_file_reads(relations: dict[str, Relation]) -> dict[str, Relation]:
173
+ """Give each source that reads files a table name, `__file_<file stem>`,
174
+ and write it where dbt pasted the read, so analysis declares and reads it
175
+ like any table. The read is one line, so no line moves."""
176
+ names: dict[str, str] = {} # read -> stand-in
177
+ for unique_id, relation in sorted(relations.items()):
178
+ read = relation.relation_name
179
+ if relation.resource_type != "source" or read is None or not _FILE_READ.fullmatch(read.strip()):
180
+ continue
181
+ if read in names:
182
+ relations[unique_id] = replace(relation, relation_name=names[read], file_read=read)
183
+ continue
184
+ path = _QUOTED.search(read)
185
+ stem = PurePosixPath(path.group(1).replace("''", "'")).name.split(".")[0] if path else ""
186
+ stem = re.sub(r"[^a-z0-9_]+", "_", stem.lower()).strip("_") or re.sub(r"[^a-z0-9_]+", "_", relation.name.lower())
187
+ name, count = f"__file_{stem}", 2
188
+ while name in names.values():
189
+ name, count = f"__file_{stem}_{count}", count + 1
190
+ names[read] = name
191
+ relations[unique_id] = replace(relation, relation_name=name, file_read=read)
192
+ if not names:
193
+ return relations
194
+ ordered = sorted(names, key=len, reverse=True) # A longer read first, should one contain another.
195
+
196
+ def rewrite(sql: str) -> str:
197
+ for read in ordered:
198
+ sql = sql.replace(read, names[read])
199
+ return sql
200
+
201
+ return {
202
+ unique_id: replace(
203
+ relation,
204
+ compiled_code=rewrite(relation.compiled_code) if relation.compiled_code else relation.compiled_code,
205
+ extra_ctes=tuple(replace(cte, sql=rewrite(cte.sql)) for cte in relation.extra_ctes),
206
+ ) if relation.compiled_code or relation.extra_ctes else relation
207
+ for unique_id, relation in relations.items()
208
+ }
209
+
210
+
161
211
  def _relation(unique_id: str, node: dict) -> Relation:
162
212
  config = _mapping(node.get("config"))
163
213
  columns = tuple(