Coverage for geoparser/gazetteer/build/stages/load.py: 100%
81 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"""
2Loading of gazetteer source files into transient DuckDB tables.
4Tabular sources (those with a ``delimiter``) are loaded with DuckDB's CSV
5reader; everything else is loaded with the spatial extension's ``ST_Read``
6(shapefiles, GeoPackage, GeoJSON, ...). Loaded spatial tables always expose
7their geometry column under the name ``geometry``, re-projected from the
8source's declared ``crs`` into the gazetteer's. Every staged geometry column
9is therefore in one coordinate system, which is what lets expressions and
10spatial joins mix sources without transforming anything by hand.
11"""
13import typing as t
14from pathlib import Path
16import duckdb
18from geoparser.gazetteer.build.progress import advance, item, track
19from geoparser.gazetteer.build.schema import (
20 DEFAULT_CRS,
21 GEOMETRY_ATTRIBUTE,
22 DataType,
23 SourceConfig,
24)
26GEOMETRY_COLUMN = GEOMETRY_ATTRIBUTE
28# Mapping from config attribute types to DuckDB types
29_DUCKDB_TYPES = {
30 DataType.TEXT: "VARCHAR",
31 DataType.INTEGER: "BIGINT",
32 DataType.REAL: "DOUBLE",
33}
35# Substrings identifying the DuckDB error raised when its parallel CSV scanner
36# is asked to combine null padding with quoted newlines (see ``_load_tabular``).
37_PARALLEL_NULL_PADDING_HINTS = ("parallel", "null_padding")
40def quote_identifier(name: str) -> str:
41 """
42 Quote an SQL identifier for DuckDB.
44 Args:
45 name: Identifier to quote
47 Returns:
48 Double-quoted identifier with embedded quotes escaped
49 """
50 escaped = name.replace('"', '""')
51 return f'"{escaped}"'
54def quote_literal(value: str) -> str:
55 """
56 Quote a string literal for SQL.
58 Args:
59 value: String value to quote
61 Returns:
62 Single-quoted string literal with embedded quotes escaped
63 """
64 escaped = value.replace("'", "''")
65 return f"'{escaped}'"
68class Loader:
69 """Loads source files into tables of a DuckDB connection."""
71 def __init__(
72 self, connection: duckdb.DuckDBPyConnection, crs: str = DEFAULT_CRS
73 ):
74 """
75 Initialize the loader.
77 Args:
78 connection: DuckDB connection holding the loaded tables
79 crs: Coordinate reference system to stage geometries in
80 """
81 self.connection = connection
82 self.crs = crs
84 def load(self, source_config: SourceConfig, file_path: Path) -> int:
85 """
86 Load a source file into a table named after the source.
88 Reports its own progress (see :mod:`progress`): one item per query it
89 actually runs, rather than one bar guessing how to split its time
90 between them. Each item advances the active stage once it finishes.
92 Args:
93 source_config: Source configuration
94 file_path: Path to the resolved source file
96 Returns:
97 Number of loaded rows
98 """
99 if source_config.is_tabular:
100 self._load_tabular(source_config, file_path)
101 else:
102 self._load_spatial(source_config, file_path)
103 table = quote_identifier(source_config.name)
104 return self.connection.execute(f"SELECT count(*) FROM {table}").fetchone()[0]
106 def columns(self, table_name: str) -> t.List[str]:
107 """
108 Return the column names of a loaded table.
110 Args:
111 table_name: Name of the loaded table
113 Returns:
114 List of column names
115 """
116 rows = self.connection.execute(
117 "SELECT column_name FROM information_schema.columns "
118 "WHERE table_name = ? ORDER BY ordinal_position",
119 [table_name],
120 ).fetchall()
121 return [row[0] for row in rows]
123 def _load_tabular(self, source_config: SourceConfig, file_path: Path) -> None:
124 """
125 Load a delimited text file via DuckDB's CSV reader.
127 Rows shorter than the declared schema are padded with NULLs, which
128 tolerates the ragged exports many gazetteers ship. DuckDB's parallel
129 scanner refuses that padding for files whose quoted fields wrap across
130 lines (common in CSVs with prose columns), so such files are re-read
131 with the single-threaded scanner rather than rejected.
132 """
133 options = [
134 f"delim={quote_literal(source_config.delimiter)}",
135 f"skip={source_config.skip_rows}",
136 "header=false",
137 "null_padding=true",
138 ]
139 quote = source_config.quote if source_config.quote is not None else '"'
140 options.append(f"quote={quote_literal(quote)}")
141 if not quote:
142 options.append("escape=''")
144 column_spec = ", ".join(
145 f"{quote_literal(attribute.name)}: "
146 f"{quote_literal(_DUCKDB_TYPES[attribute.type])}"
147 for attribute in source_config.data_attributes
148 )
149 options.append(f"columns={{{column_spec}}}")
151 def load() -> None:
152 try:
153 self.connection.execute(
154 self._read_csv_sql(source_config, file_path, options)
155 )
156 except duckdb.Error as error:
157 message = str(error).lower()
158 if not all(hint in message for hint in _PARALLEL_NULL_PADDING_HINTS):
159 raise
160 self.connection.execute(
161 self._read_csv_sql(
162 source_config, file_path, options + ["parallel=false"]
163 )
164 )
166 with item(f"Loading {source_config.name}", total=100) as bar:
167 track(bar, self.connection.query_progress, load)
168 advance()
170 @staticmethod
171 def _read_csv_sql(
172 source_config: SourceConfig, file_path: Path, options: t.List[str]
173 ) -> str:
174 """Build the statement staging a delimited file into its table."""
175 table = quote_identifier(source_config.name)
176 return (
177 f"CREATE OR REPLACE TABLE {table} AS "
178 f"SELECT * FROM read_csv({quote_literal(str(file_path))}, "
179 f"{', '.join(options)})"
180 )
182 def _load_spatial(self, source_config: SourceConfig, file_path: Path) -> None:
183 """
184 Load a spatial file via ST_Read, projected onto its declared attributes.
186 The geometry column is normalized to ``geometry``, re-projected into
187 the gazetteer's coordinate system, and the non-geometry attributes are
188 cast to their declared types, so the loaded table has exactly the
189 schema the config declares (mirroring tabular sources). Loading the
190 file and normalizing its columns are each their own query, so they're
191 reported as two separate items in turn.
192 """
193 raw = quote_identifier(f"__raw_{source_config.name}")
194 read_sql = (
195 f"CREATE OR REPLACE TABLE {raw} AS "
196 f"SELECT * FROM ST_Read({quote_literal(str(file_path))})"
197 )
198 with item(f"Loading {source_config.name}", total=100) as bar:
199 track(bar, self.connection.query_progress, lambda: self.connection.execute(read_sql))
200 advance()
201 # Geometry types may carry a CRS parameter, e.g. GEOMETRY('EPSG:4326')
202 geometry_columns = [
203 row[0]
204 for row in self.connection.execute(
205 "SELECT column_name FROM information_schema.columns "
206 "WHERE table_name = ? AND data_type LIKE 'GEOMETRY%'",
207 [f"__raw_{source_config.name}"],
208 ).fetchall()
209 ]
210 if not geometry_columns:
211 raise ValueError(
212 f"Source '{source_config.name}': no geometry column found in "
213 f"{file_path}"
214 )
215 if len(geometry_columns) > 1:
216 raise ValueError(
217 f"Source '{source_config.name}': multiple geometry columns found "
218 f"in {file_path}: {', '.join(geometry_columns)}"
219 )
220 if geometry_columns[0] != GEOMETRY_COLUMN:
221 self.connection.execute(
222 f"ALTER TABLE {raw} RENAME COLUMN "
223 f"{quote_identifier(geometry_columns[0])} TO "
224 f"{quote_identifier(GEOMETRY_COLUMN)}"
225 )
227 select_parts = []
228 for attribute in source_config.attributes:
229 column = quote_identifier(attribute.name)
230 if attribute.type == DataType.GEOMETRY:
231 select_parts.append(f"{self._reprojection(source_config)} AS {column}")
232 else:
233 select_parts.append(
234 f"CAST({column} AS {_DUCKDB_TYPES[attribute.type]}) AS {column}"
235 )
236 table = quote_identifier(source_config.name)
237 cast_sql = (
238 f"CREATE OR REPLACE TABLE {table} AS "
239 f"SELECT {', '.join(select_parts)} FROM {raw}"
240 )
241 with item(f"Normalizing {source_config.name}", total=100) as bar:
242 track(bar, self.connection.query_progress, lambda: self.connection.execute(cast_sql))
243 advance()
244 self.connection.execute(f"DROP TABLE {raw}")
246 def _reprojection(self, source_config: SourceConfig) -> str:
247 """
248 Build the expression staging a source's geometry in the gazetteer CRS.
250 Doing this once per row, at load time, is both cheaper and less
251 error-prone than transforming at every place the column is read: from
252 here on, every staged geometry shares one coordinate system.
253 """
254 column = quote_identifier(GEOMETRY_COLUMN)
255 native_crs = source_config.crs or self.crs
256 if native_crs == self.crs:
257 return column
258 return (
259 f"ST_Transform({column}, {quote_literal(native_crs)}, "
260 f"{quote_literal(self.crs)}, always_xy := true)"
261 )