datadouble 0.0.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.
datadouble/resolve.py ADDED
@@ -0,0 +1,201 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Resolving the names a spec uses against a catalog.
5
+
6
+ A spec names tables by their parts joined with dots, and may leave out
7
+ leading parts: ``users``, ``public.users`` and ``shop.public.users`` all name
8
+ PostgreSQL's ``shop.public.users``, matching from the right. A name that fits
9
+ more than one table fails, naming them. Columns are ``table.column`` and
10
+ references ``child.column -> parent``. A table's own name may hold dots (a
11
+ MongoDB collection such as ``fs.files``); a dot in a spec name separates parts
12
+ everywhere else. Names are matched case-insensitively unless the spec sets
13
+ ``case_sensitive: true``, because engines fold identifier case differently.
14
+
15
+ Objects (functions, views and the like) are named the same way, with their
16
+ kind given separately, and a routine may add its argument types as the
17
+ catalog spells them: ``public.total(integer)``.
18
+ """
19
+
20
+ import fnmatch
21
+ import re
22
+ from collections.abc import Callable, Sequence
23
+ from dataclasses import dataclass
24
+
25
+ from datadouble.catalog import Catalog, Column, ObjectKind, SourceObject, Table
26
+ from datadouble.names import ColumnName, ColumnRef, TableName
27
+
28
+
29
+ class ResolveError(Exception):
30
+ """A name in the spec that does not match the catalog."""
31
+
32
+
33
+ @dataclass(frozen=True, slots=True)
34
+ class Reference:
35
+ """A parsed ``child[.columns] -> parent[.columns]`` reference."""
36
+
37
+ child: Table
38
+ columns: tuple[ColumnName, ...] | None
39
+ parent: Table
40
+ parent_columns: tuple[ColumnName, ...] | None
41
+
42
+
43
+ _ARROW = re.compile(r"\s*->\s*")
44
+ _SPACE = re.compile(r"\s+")
45
+
46
+
47
+ def ends_with(
48
+ parts: Sequence[str], pieces: Sequence[str], same: Callable[[str, str], bool]
49
+ ) -> bool:
50
+ """Whether a name's last parts are the pieces of a dotted spec name.
51
+
52
+ ``pieces`` is the spec name split at its dots, and ``same(piece, part)``
53
+ compares one piece with one part. Matching runs from the right, and a part
54
+ may take several pieces joined with dots, for names that hold dots.
55
+ """
56
+ if not pieces:
57
+ return True
58
+ if not parts:
59
+ return False
60
+ return any(
61
+ same(".".join(pieces[-taken:]), parts[-1]) and ends_with(parts[:-1], pieces[:-taken], same)
62
+ for taken in range(1, len(pieces) + 1)
63
+ )
64
+
65
+
66
+ class Resolver:
67
+ """Looks up spec names in one catalog."""
68
+
69
+ def __init__(self, catalog: Catalog, *, case_sensitive: bool) -> None:
70
+ """Index ``catalog`` for lookups."""
71
+ self.catalog = catalog
72
+ self.case_sensitive = case_sensitive
73
+
74
+ def _fold(self, text: str) -> str:
75
+ return text if self.case_sensitive else text.casefold()
76
+
77
+ def _same(self, piece: str, part: str) -> bool:
78
+ return self._fold(piece) == self._fold(part)
79
+
80
+ def _glob_same(self, piece: str, part: str) -> bool:
81
+ return fnmatch.fnmatchcase(self._fold(part), self._fold(piece))
82
+
83
+ def matches(self, pattern: str, name: TableName) -> bool:
84
+ """Whether a shell-style glob matches a table, from the right.
85
+
86
+ ``*`` matches within one part: ``audit.*`` matches every table in
87
+ namespaces called ``audit``, and ``shop.*.*`` every table in
88
+ PostgreSQL's database ``shop``.
89
+ """
90
+ return self.matches_parts(pattern, name.parts)
91
+
92
+ def matches_parts(self, pattern: str, parts: Sequence[str]) -> bool:
93
+ """Whether a glob matches a name given as its parts: a table's, or an object's."""
94
+ return ends_with(parts, pattern.split("."), self._glob_same)
95
+
96
+ def glob(self, pattern: str) -> tuple[TableName, ...]:
97
+ """Every table a glob matches, in catalog order."""
98
+ return tuple(name for name in self.catalog.names() if self.matches(pattern, name))
99
+
100
+ def _find(self, text: str) -> Table | None:
101
+ pieces = text.split(".")
102
+ found = [
103
+ table
104
+ for table in self.catalog.tables
105
+ if ends_with(table.name.parts, pieces, self._same)
106
+ ]
107
+ if len(found) > 1:
108
+ names = ", ".join(str(table.name) for table in found)
109
+ message = f"table {text!r} is ambiguous: it matches {names}; qualify it"
110
+ raise ResolveError(message)
111
+ return found[0] if found else None
112
+
113
+ def table(self, text: str) -> Table:
114
+ """The table a spec name refers to."""
115
+ table = self._find(text.strip())
116
+ if table is None:
117
+ message = f"table {text!r} is not in the catalog"
118
+ raise ResolveError(message)
119
+ return table
120
+
121
+ def object(self, kind: ObjectKind, text: str) -> SourceObject:
122
+ """The object of ``kind`` a spec name refers to, with argument types if given."""
123
+ name, opened, rest = text.strip().partition("(")
124
+ signature = _SPACE.sub("", self._fold(opened + rest)) if opened else None
125
+ pieces = name.strip().split(".")
126
+ found = [
127
+ item
128
+ for item in self.catalog.objects
129
+ if item.ref.kind is kind
130
+ and ends_with((*item.ref.namespace, item.ref.name), pieces, self._same)
131
+ and (
132
+ signature is None
133
+ or _SPACE.sub("", self._fold(item.ref.signature or "")) == signature
134
+ )
135
+ ]
136
+ if not found:
137
+ message = f"{kind} {text.strip()!r} is not in the catalog"
138
+ raise ResolveError(message)
139
+ if len(found) > 1:
140
+ names = ", ".join(str(item.ref) for item in found)
141
+ message = f"{kind} {text.strip()!r} is ambiguous: it matches {names}; qualify it"
142
+ raise ResolveError(message)
143
+ return found[0]
144
+
145
+ def column_of(self, table: Table, text: str) -> Column:
146
+ """The column of ``table`` a spec name refers to."""
147
+ wanted = self._fold(text.strip())
148
+ for column in table.columns:
149
+ if self._fold(column.name) == wanted:
150
+ return column
151
+ message = f"column {text!r} is not in table {table.name}"
152
+ raise ResolveError(message)
153
+
154
+ def column(self, text: str) -> ColumnRef:
155
+ """The column a ``table.column`` name refers to."""
156
+ table_text, dot, column_text = text.strip().rpartition(".")
157
+ if not dot or not table_text:
158
+ message = f"{text!r} is not a column name; write table.column"
159
+ raise ResolveError(message)
160
+ table = self.table(table_text)
161
+ return ColumnRef(table=table.name, column=self.column_of(table, column_text).name)
162
+
163
+ def _side(self, text: str) -> tuple[Table, tuple[ColumnName, ...] | None]:
164
+ """A table, or a table with columns: ``t``, ``t.c`` or ``t.(c1, c2)``."""
165
+ text = text.strip()
166
+ table_text, opened, listed = text.rpartition(".(")
167
+ if opened and table_text and listed.endswith(")") and "(" not in listed[:-1]:
168
+ table = self.table(table_text)
169
+ names = tuple(self.column_of(table, part).name for part in listed[:-1].split(","))
170
+ return table, names
171
+ whole = self._find(text)
172
+ if whole is not None:
173
+ return whole, None
174
+ table_text, dot, column_text = text.rpartition(".")
175
+ if dot and table_text:
176
+ table = self.table(table_text)
177
+ return table, (self.column_of(table, column_text).name,)
178
+ message = f"{text!r} is not a table or column in the catalog"
179
+ raise ResolveError(message)
180
+
181
+ def reference(self, text: str) -> Reference:
182
+ """Parse ``child[.columns] -> parent[.columns]``."""
183
+ match _ARROW.split(text.strip()):
184
+ case [left, right] if left and right:
185
+ child, columns = self._side(left)
186
+ parent, parent_columns = self._side(right)
187
+ return Reference(child, columns, parent, parent_columns)
188
+ case _:
189
+ message = f"{text!r} is not a reference; write child.column -> parent"
190
+ raise ResolveError(message)
191
+
192
+ def downward(self, text: str) -> Reference:
193
+ """Parse a ``parent -> child[.columns]`` entry from ``follow.down``."""
194
+ match _ARROW.split(text.strip()):
195
+ case [left, right] if left and right:
196
+ parent, parent_columns = self._side(left)
197
+ child, columns = self._side(right)
198
+ return Reference(child, columns, parent, parent_columns)
199
+ case _:
200
+ message = f"{text!r} is not a downward edge; write parent -> child"
201
+ raise ResolveError(message)