Coverage for geoparser/gazetteer/build/stages/compile.py: 100%
133 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-20 18:08 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-20 18:08 +0000
1"""
2Projection compiler: turns feature blocks into DuckDB SQL.
4Each feature block compiles into:
6- one *feature query* producing ``(identifier, source, data, geometry)`` rows,
7 where rows sharing an identifier are merged (names collected, geometries
8 unioned, data values taken from the first row)
9- one or more *name queries* producing ``(identifier, text)`` rows from the
10 block's name specs (own columns or scalar expressions, including expressions
11 that expand into several names such as ``unnest(string_split(...))``)
13Both kinds of query select from the block's source (aliased ``src``) with the
14block's raw SQL joins appended. Column references resolve as follows: a bare
15identifier is a column of the block's source (qualified to ``src``); anything
16else is a scalar SQL expression or a qualified reference (``<source>.<column>``)
17passed through, with its bare identifiers qualified to ``src``. The same rule is
18applied inside each join's ``ON`` condition, so join clauses can reference the
19block's source columns bare (without a ``src.`` prefix) too.
21Geometry columns are staged in the gazetteer's coordinate system (see
22:mod:`stages.load`), so expressions and spatial joins can mix sources freely and
23never have to transform anything. The one geometry that is not yet in that
24system is one built from a tabular source's plain coordinate columns, which is
25transformed here from the CRS its source declares.
27Geometry of rows sharing an identifier must be unioned, but ``ST_Union_Agg``
28holds unmanaged (unspillable) memory proportional to the number of groups, which
29is prohibitive for large sources of mostly-unique identifiers. The feature query
30therefore keeps the *first* row's geometry (a bounded aggregate), and geometries
31are unioned only for the few genuinely duplicated identifiers in a separate,
32bounded pass (:meth:`ProjectionCompiler.duplicate_geometry_query`). That pass
33runs over the block's source without its joins, so a block's ``identifier`` and
34``geometry`` must read from that source alone; references to a joined source are
35rejected up front (:meth:`ProjectionCompiler._resolve_own`).
36"""
38import re
39import typing as t
41from geoparser.gazetteer.build.schema import (
42 GEOMETRY_ATTRIBUTE,
43 FeatureConfig,
44 GazetteerConfig,
45 split_data_value,
46)
47from geoparser.gazetteer.build.stages.load import (
48 quote_identifier,
49 quote_literal,
50)
52# Reference to the source row order, used for deterministic "first" merge
53# semantics when rows sharing an identifier are collapsed.
54ROW_ORDER_REFERENCE = "src.rowid"
56_BARE_IDENTIFIER = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")
58# Matches string literals, quoted identifiers and bare identifiers so
59# expressions can be scanned token by token.
60_EXPRESSION_TOKEN = re.compile(
61 r"'(?:[^']|'')*'|\"[^\"]*\"|[A-Za-z_][A-Za-z0-9_]*"
62)
64# Alias the block's own source is available under inside compiled queries.
65SOURCE_ALIAS = "src"
68def qualifiers(expression: str) -> t.Set[str]:
69 """
70 Collect the table qualifiers a scalar SQL expression reads columns from.
72 Only qualifiers of column references are reported: string literals are
73 skipped, and so are function calls, whose name is followed by an opening
74 parenthesis rather than a dot.
76 Args:
77 expression: Scalar SQL expression
79 Returns:
80 Set of qualifier names, unquoted
81 """
82 found = set()
83 for match in _EXPRESSION_TOKEN.finditer(expression):
84 token = match.group(0)
85 if token.startswith("'"):
86 continue
87 if not expression[match.end() :].lstrip().startswith("."):
88 continue
89 # Skip the qualified part of an already-qualified reference
90 if expression[: match.start()].rstrip().endswith("."):
91 continue
92 found.add(token[1:-1] if token.startswith('"') else token)
93 return found
96def bare_references(expression: str) -> t.Set[str]:
97 """
98 Collect the unqualified column references of a scalar SQL expression.
100 Mirrors what :func:`qualify_expression` treats as a bare column: string
101 literals, quoted identifiers, qualified references and function names are
102 not reported.
104 Args:
105 expression: Scalar SQL expression
107 Returns:
108 Set of bare column names
109 """
110 found = set()
111 for match in _EXPRESSION_TOKEN.finditer(expression):
112 token = match.group(0)
113 if token.startswith("'") or token.startswith('"'):
114 continue
115 if expression[: match.start()].rstrip().endswith("."):
116 continue
117 if expression[match.end() :].lstrip().startswith("("):
118 continue
119 found.add(token)
120 return found
123def qualify_expression(expression: str, replacements: t.Mapping[str, str]) -> str:
124 """
125 Replace bare column references in a scalar SQL expression.
127 Used for expressions evaluated over the joined relation, where an
128 unqualified column name could be ambiguous between the feature's source and
129 a joined source. String literals, quoted identifiers, already-qualified
130 references, and function names are left untouched.
132 Args:
133 expression: Scalar SQL expression
134 replacements: Mapping of bare column names to qualified references
136 Returns:
137 Expression with bare column references replaced
138 """
140 def replace(match: re.Match) -> str:
141 token = match.group(0)
142 if token.startswith("'") or token.startswith('"'):
143 return token
144 if token not in replacements:
145 return token
146 # Skip already-qualified references (preceded by a dot)
147 before = expression[: match.start()].rstrip()
148 if before.endswith("."):
149 return token
150 # Skip function calls (followed by an opening parenthesis)
151 after = expression[match.end() :].lstrip()
152 if after.startswith("("):
153 return token
154 return replacements[token]
156 return _EXPRESSION_TOKEN.sub(replace, expression)
159class CompileError(ValueError):
160 """Raised when a feature block cannot be compiled against the staged data."""
163class ProjectionCompiler:
164 """
165 Compiles feature blocks of a gazetteer config into DuckDB SQL.
167 The compiler knows the columns of the staged sources (the catalog) to
168 resolve and validate bare column references against the block's source.
169 """
171 def __init__(
172 self, config: GazetteerConfig, catalog: t.Dict[str, t.List[str]]
173 ):
174 """
175 Initialize the compiler.
177 Args:
178 config: Validated gazetteer configuration
179 catalog: Mapping of staged source names to their column names
180 """
181 self.config = config
182 self.catalog = catalog
183 self._sources = {source.name: source for source in config.sources}
185 def feature_query(self, feature: FeatureConfig) -> str:
186 """
187 Compile the feature query for a feature block.
189 The query yields one row per distinct identifier with columns
190 ``identifier`` (VARCHAR), ``source`` (VARCHAR), ``data`` (JSON text)
191 and ``geometry`` (WKB blob or NULL).
193 Args:
194 feature: Feature block to compile
196 Returns:
197 DuckDB SQL string
198 """
199 from_clause = self._from_clause(feature)
200 identifier = self._feature_identifier(feature)
202 data_parts = []
203 for item in feature.data:
204 expression, alias = split_data_value(item)
205 value = self._resolve(feature, expression, f"data value '{alias}'")
206 data_parts.append(f"{quote_literal(alias)}: {self._first(value)}")
207 if data_parts:
208 data_sql = f"CAST(to_json({{{', '.join(data_parts)}}}) AS VARCHAR)"
209 else:
210 data_sql = "'{}'"
212 geometry_sql = self._geometry_select(feature)
214 return (
215 f"SELECT\n"
216 f" CAST(({identifier}) AS VARCHAR) AS identifier,\n"
217 f" {quote_literal(feature.source)} AS source,\n"
218 f" {data_sql} AS data,\n"
219 f" {geometry_sql} AS geometry\n"
220 f"{from_clause}\n"
221 f"WHERE ({identifier}) IS NOT NULL\n"
222 f"GROUP BY 1"
223 )
225 def name_queries(self, feature: FeatureConfig) -> t.List[str]:
226 """
227 Compile the name queries for a feature block.
229 Each query yields ``(identifier, text)`` rows with trimmed, non-empty
230 name strings. A name is a column or scalar expression; an expression
231 that produces a list (e.g. ``unnest(string_split(alt, ','))``) expands
232 into one name row per element.
234 Args:
235 feature: Feature block to compile
237 Returns:
238 List of DuckDB SQL strings
239 """
240 from_clause = self._from_clause(feature)
241 identifier = self._feature_identifier(feature)
243 queries = []
244 for name in feature.names:
245 value = self._resolve(feature, name, "name")
246 part = f"CAST(({value}) AS VARCHAR)"
247 queries.append(
248 f"SELECT DISTINCT identifier, trim(part) AS text\n"
249 f"FROM (\n"
250 f" SELECT CAST(({identifier}) AS VARCHAR) AS identifier, "
251 f"{part} AS part\n"
252 f" {from_clause}\n"
253 f" WHERE ({identifier}) IS NOT NULL\n"
254 f")\n"
255 f"WHERE part IS NOT NULL AND trim(part) <> ''"
256 )
257 return queries
259 def duplicate_geometry_query(
260 self, feature: FeatureConfig
261 ) -> t.Optional[str]:
262 """
263 Compile the geometry-merge query for duplicated identifiers.
265 Returns SQL yielding ``(identifier, geometry)`` rows only for
266 identifiers that occur in more than one source row, with their
267 geometries unioned into a single WKB blob. Returns ``None`` when the
268 block has no geometry.
270 This runs over the block's source alone (no joins): a feature's
271 geometry depends only on its source, and the block's left joins never
272 change a row's geometry, so a joined fan-out cannot affect the union.
273 Restricting ``ST_Union_Agg`` to the few duplicated identifiers keeps its
274 (unmanaged) memory bounded.
276 Args:
277 feature: Feature block to compile
279 Returns:
280 DuckDB SQL string, or None if the block has no geometry
281 """
282 if feature.geometry is None:
283 return None
284 identifier = self._feature_identifier(feature)
285 geometry = self._feature_geometry(feature)
286 source = quote_identifier(feature.source)
287 return (
288 f"WITH src_rows AS (\n"
289 f" SELECT CAST(({identifier}) AS VARCHAR) AS identifier, "
290 f"{geometry} AS geom\n"
291 f" FROM {source} AS src\n"
292 f" WHERE ({identifier}) IS NOT NULL\n"
293 f"),\n"
294 f"dups AS (\n"
295 f" SELECT identifier FROM src_rows GROUP BY 1 HAVING count(*) > 1\n"
296 f")\n"
297 f"SELECT r.identifier,\n"
298 f" CASE WHEN count(r.geom) = 0 THEN NULL "
299 f"ELSE ST_AsWKB(ST_Union_Agg(r.geom)) END AS geometry\n"
300 f"FROM src_rows r SEMI JOIN dups USING (identifier)\n"
301 f"GROUP BY 1"
302 )
304 def _from_clause(self, feature: FeatureConfig) -> str:
305 """
306 Build the FROM clause for a feature block.
308 The block's source is aliased ``src`` and the block's raw SQL join
309 clauses are appended, with bare source columns in each join's ``ON``
310 condition qualified to ``src`` (so joins need no ``src.`` prefix).
311 """
312 lines = [f"FROM {quote_identifier(feature.source)} AS src"]
313 lines.extend(self._qualify_join(feature, join) for join in feature.joins)
314 return "\n".join(lines)
316 def _qualify_join(self, feature: FeatureConfig, clause: str) -> str:
317 """
318 Qualify bare source columns within a join clause's ``ON`` condition.
320 Only the condition after the first ``ON`` keyword is rewritten, so the
321 joined table and alias are left untouched. Clauses without an ``ON``
322 (e.g. ``USING``/``CROSS JOIN``) are returned unchanged.
323 """
324 match = re.search(r"\sON\s", clause, re.IGNORECASE)
325 if match is None:
326 return clause
327 replacements = {
328 column: f'src."{column}"' for column in self.catalog[feature.source]
329 }
330 cut = match.end()
331 return clause[:cut] + qualify_expression(clause[cut:], replacements)
333 def _geometry_select(self, feature: FeatureConfig) -> str:
334 """
335 Build the (bounded) geometry expression for the feature query.
337 Keeps the first row's geometry as WKB. Geometries of duplicated
338 identifiers are unioned separately (see ``duplicate_geometry_query``).
339 """
340 if feature.geometry is None:
341 return "NULL"
342 geometry = self._feature_geometry(feature)
343 # ``count`` keeps geometry-less features NULL (arg_min over an all-NULL
344 # group would otherwise still be NULL, but this is explicit and matches
345 # the union pass).
346 return (
347 f"CASE WHEN count({geometry}) = 0 THEN NULL "
348 f"ELSE arg_min(ST_AsWKB({geometry}), {ROW_ORDER_REFERENCE}) END"
349 )
351 def _feature_identifier(self, feature: FeatureConfig) -> str:
352 """Resolve the identifier expression over the block's own source."""
353 return self._resolve_own(feature, feature.identifier, "identifier")
355 def _feature_geometry(self, feature: FeatureConfig) -> str:
356 """
357 Resolve the feature geometry expression in the gazetteer CRS.
359 A staged geometry column is already in that CRS (see
360 :meth:`Loader._reprojection`), so only a geometry built from plain
361 coordinate columns still has to be transformed, from the CRS its
362 source declares.
363 """
364 geometry = self._resolve_own(feature, feature.geometry, "geometry")
365 if self._reads_geometry_column(feature):
366 return geometry
367 native_crs = self._source_crs(feature.source)
368 if native_crs != self.config.crs:
369 geometry = (
370 f"ST_Transform({geometry}, {quote_literal(native_crs)}, "
371 f"{quote_literal(self.config.crs)}, always_xy := true)"
372 )
373 return geometry
375 def _reads_geometry_column(self, feature: FeatureConfig) -> bool:
376 """Whether the block's geometry is read from its source's geometry."""
377 if self._sources[feature.source].is_tabular:
378 return False
379 return GEOMETRY_ATTRIBUTE in bare_references(feature.geometry)
381 def _source_crs(self, source_name: str) -> str:
382 """Return the CRS of a source, defaulting to the gazetteer CRS."""
383 source = self._sources[source_name]
384 return source.crs or self.config.crs
386 def _first(self, value: str) -> str:
387 """Wrap a data value in the first-row aggregate."""
388 return f"arg_min({value}, {ROW_ORDER_REFERENCE})"
390 def _resolve_own(self, feature: FeatureConfig, value: str, context: str) -> str:
391 """
392 Resolve a reference that must read only the block's own source.
394 A feature's identifier and geometry are also evaluated over the source
395 by itself (see :meth:`duplicate_geometry_query`), where no joined table
396 exists, so a qualified reference to one would fail with an opaque SQL
397 error further down. Rejecting it here says what is actually wrong.
398 """
399 joined = qualifiers(value) - {SOURCE_ALIAS}
400 if joined:
401 names = ", ".join("'" + name + "'" for name in sorted(joined))
402 raise CompileError(
403 f"Feature '{feature.source}': {context} reads from {names}, but "
404 f"it must be derived from the block's own source "
405 f"'{feature.source}' alone. Move the joined value to 'data', or "
406 f"build the feature from the other source instead."
407 )
408 return self._resolve(feature, value, context)
410 def _resolve(self, feature: FeatureConfig, value: str, context: str) -> str:
411 """
412 Resolve a column-or-expression reference over the joined relation.
414 A bare identifier must name a column of the block's source (otherwise it
415 is a typo and we fail with a helpful hint) and is qualified to ``src``.
416 Anything else is a scalar SQL expression or a qualified reference
417 (``<source>.<column>``); its bare identifiers are qualified to ``src``
418 and it is passed through, so references to joined sources are the
419 author's responsibility.
420 """
421 base_columns = set(self.catalog[feature.source])
422 if _BARE_IDENTIFIER.match(value):
423 if value not in base_columns:
424 raise CompileError(
425 f"Feature '{feature.source}': {context} references unknown "
426 f"column '{value}' of source '{feature.source}'. "
427 f"{self._available_hint(base_columns)}"
428 )
429 return f"src.{quote_identifier(value)}"
430 replacements = {column: f'src."{column}"' for column in base_columns}
431 return f"({qualify_expression(value, replacements)})"
433 def _available_hint(self, columns: t.Set[str]) -> str:
434 """Build an error message hint listing the available columns."""
435 return f"Available columns: {', '.join(sorted(columns))}"