Coverage for geoparser/gazetteer/build/schema.py: 100%

175 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-20 18:08 +0000

1""" 

2Declarative gazetteer configuration schema. 

3 

4A gazetteer config describes how source files are projected into the canonical 

5feature store. It has two top-level concepts: 

6 

7- ``sources``: files to acquire and stage (transient; discarded after the 

8 build). Every source declares its ``attributes`` (name and data type), so its 

9 schema is explicit regardless of file format. 

10- ``features``: one block per source, describing how that source's rows project 

11 into canonical features (identifier, names, geometry, data). A block may 

12 ``join`` other sources to enrich its rows. A feature's ``source`` in the 

13 artifact is the name of the source it is built from. 

14 

15Values (``identifier``, ``names``, ``geometry`` and each ``data`` entry) are 

16column references or scalar SQL expressions evaluated over the block's source, 

17aliased ``src``; a bare column name refers to that source, and columns of 

18joined sources are referenced by qualification (``<alias>.<column>``). A 

19``data`` entry names the key it is stored under with a trailing ``AS <alias>`` 

20(as in a SQL ``SELECT``); a bare or qualified column reference may omit it, in 

21which case the column's own name is the key. 

22 

23Joins are written as raw SQL join clauses (e.g. 

24``"LEFT JOIN countryInfo c ON src.country_code = c.ISO"``); the whole 

25joined table is available, and the values to keep are selected in ``data``. 

26""" 

27 

28from __future__ import annotations 

29 

30import re 

31import typing as t 

32from enum import Enum 

33from pathlib import Path 

34 

35import yaml 

36from pydantic import BaseModel, Field, field_validator, model_validator 

37 

38# Source names are used as identifiers (staging table names, join aliases), so 

39# they are restricted to a safe character set. 

40_NAME_PATTERN = re.compile(r"^[a-zA-Z0-9_-]+$") 

41_IDENTIFIER_PATTERN = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$") 

42 

43DEFAULT_CRS = "EPSG:4326" 

44 

45# Staged spatial sources always expose their geometry under this attribute name. 

46GEOMETRY_ATTRIBUTE = "geometry" 

47 

48 

49class DataType(str, Enum): 

50 """Data types a source attribute can declare.""" 

51 

52 TEXT = "text" 

53 INTEGER = "integer" 

54 REAL = "real" 

55 GEOMETRY = "geometry" 

56 

57 

58class AttributeDef(BaseModel): 

59 """ 

60 A declared attribute (column) of a source. 

61 

62 The data type is always required, so a source's schema reads the same 

63 whatever the file format. Spatial sources declare their geometry as an 

64 attribute of type ``geometry`` named ``geometry``. 

65 """ 

66 

67 name: str 

68 type: DataType 

69 

70 

71class SourceConfig(BaseModel): 

72 """ 

73 A source file to acquire and stage. 

74 

75 A source is tabular (delimited text) when ``delimiter`` is set, otherwise 

76 it is a spatial file readable by DuckDB's spatial extension (shapefile, 

77 GeoPackage, GeoJSON, ...). Every source declares its ``attributes``; a 

78 spatial source must declare exactly one geometry attribute (named 

79 ``geometry``), and a tabular source must declare none. 

80 """ 

81 

82 name: str 

83 url: t.Optional[str] = None 

84 path: t.Optional[str] = None 

85 file: str 

86 

87 # Tabular options 

88 delimiter: t.Optional[str] = None 

89 quote: t.Optional[str] = None 

90 skip_rows: int = 0 

91 

92 # Coordinate reference system of the source's geometry/coordinates. 

93 # Geometries are re-projected into the gazetteer's CRS during the build, 

94 # so configs never transform coordinates themselves. 

95 crs: t.Optional[str] = None 

96 

97 attributes: t.List[AttributeDef] 

98 

99 @property 

100 def is_tabular(self) -> bool: 

101 """Whether this source is a delimited text file.""" 

102 return self.delimiter is not None 

103 

104 @property 

105 def data_attributes(self) -> t.List[AttributeDef]: 

106 """The non-geometry attributes of this source.""" 

107 return [a for a in self.attributes if a.type != DataType.GEOMETRY] 

108 

109 @field_validator("name") 

110 @classmethod 

111 def validate_name(cls, value: str) -> str: 

112 if not _IDENTIFIER_PATTERN.match(value): 

113 raise ValueError( 

114 f"Source name '{value}' must start with a letter or underscore " 

115 "and contain only letters, digits and underscores" 

116 ) 

117 return value 

118 

119 @model_validator(mode="after") 

120 def validate_source(self) -> "SourceConfig": 

121 if bool(self.url) == bool(self.path): 

122 raise ValueError( 

123 f"Source '{self.name}' must define exactly one of 'url' or 'path'" 

124 ) 

125 

126 if not self.attributes: 

127 raise ValueError( 

128 f"Source '{self.name}' must declare at least one attribute" 

129 ) 

130 names = [attribute.name for attribute in self.attributes] 

131 duplicates = {name for name in names if names.count(name) > 1} 

132 if duplicates: 

133 raise ValueError( 

134 f"Source '{self.name}' has duplicate attribute names: " 

135 f"{', '.join(sorted(duplicates))}" 

136 ) 

137 

138 geometry_attributes = [ 

139 a for a in self.attributes if a.type == DataType.GEOMETRY 

140 ] 

141 if self.is_tabular: 

142 if geometry_attributes: 

143 raise ValueError( 

144 f"Source '{self.name}': tabular sources cannot declare a " 

145 "geometry attribute" 

146 ) 

147 else: 

148 for field in ("quote",): 

149 if getattr(self, field) is not None: 

150 raise ValueError( 

151 f"Source '{self.name}': '{field}' is only valid for tabular " 

152 "sources (those with a 'delimiter')" 

153 ) 

154 if self.skip_rows: 

155 raise ValueError( 

156 f"Source '{self.name}': 'skip_rows' is only valid for tabular " 

157 "sources" 

158 ) 

159 if len(geometry_attributes) != 1: 

160 raise ValueError( 

161 f"Source '{self.name}': a spatial source must declare exactly " 

162 "one geometry attribute" 

163 ) 

164 if geometry_attributes[0].name != GEOMETRY_ATTRIBUTE: 

165 raise ValueError( 

166 f"Source '{self.name}': the geometry attribute must be named " 

167 f"'{GEOMETRY_ATTRIBUTE}'" 

168 ) 

169 return self 

170 

171 

172# Matches a bare or dot-qualified identifier (``NAME``, ``g.NAME``), each 

173# component optionally double-quoted (``"My Column".other``). 

174_QUALIFIED_IDENTIFIER = re.compile( 

175 r'^(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)' 

176 r'(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))*$' 

177) 

178 

179# Matches a trailing SQL alias, as in ``SELECT <expr> AS <alias>``. 

180_ALIAS_SUFFIX = re.compile( 

181 r'\s+AS\s+("[^"]+"|[A-Za-z_][A-Za-z0-9_]*)\s*$', re.IGNORECASE 

182) 

183 

184 

185def split_data_value(value: str) -> t.Tuple[str, t.Optional[str]]: 

186 """ 

187 Split a ``data`` entry into its SQL expression and output key. 

188 

189 A trailing ``AS <alias>`` (as in a SQL ``SELECT``) names the key 

190 explicitly. Otherwise the entry must be a bare or dot-qualified column 

191 reference (``NAME``, ``g.NAME``), whose last component names the key; a 

192 plain expression without ``AS`` has no derivable key, so its key is 

193 ``None``. 

194 

195 Args: 

196 value: Raw ``data`` entry, e.g. ``"NAME"`` or ``"g.NAME AS GEMEINDE_NAME"`` 

197 

198 Returns: 

199 Tuple of (SQL expression, output key or None) 

200 """ 

201 match = _ALIAS_SUFFIX.search(value) 

202 if match: 

203 alias = match.group(1) 

204 if alias.startswith('"'): 

205 alias = alias[1:-1] 

206 return value[: match.start()].strip(), alias 

207 

208 expression = value.strip() 

209 if _QUALIFIED_IDENTIFIER.match(expression): 

210 last = expression.rsplit(".", 1)[-1] 

211 if last.startswith('"'): 

212 last = last[1:-1] 

213 return expression, last 

214 return expression, None 

215 

216 

217class FeatureConfig(BaseModel): 

218 """ 

219 Projection of one source into canonical features. 

220 

221 Rows of ``source`` (enriched by ``joins``) are grouped by ``identifier``; 

222 each group becomes one feature with the listed names, geometry and data. 

223 Rows sharing an identifier are merged by collecting all names, unioning 

224 their geometries and keeping the first row's data values. The feature's 

225 ``source`` in the artifact is the name of ``source``. 

226 

227 ``joins`` are raw SQL join clauses appended to ``FROM <source> AS src``, so 

228 they may reference the block's source as ``src`` and any joined (or earlier 

229 joined) source by name; the whole joined table is available and the values 

230 to keep are selected in ``data``. 

231 """ 

232 

233 source: str 

234 joins: t.List[str] = Field(default_factory=list) 

235 identifier: str 

236 geometry: t.Optional[str] = None 

237 names: t.List[str] 

238 data: t.List[str] = Field(default_factory=list) 

239 

240 @field_validator("names") 

241 @classmethod 

242 def validate_names(cls, value: t.List[str]) -> t.List[str]: 

243 if not value: 

244 raise ValueError("A feature must define at least one name") 

245 for name in value: 

246 if not isinstance(name, str) or not name.strip(): 

247 raise ValueError("A feature name must be a non-empty string") 

248 return value 

249 

250 @field_validator("joins") 

251 @classmethod 

252 def validate_joins(cls, value: t.List[str]) -> t.List[str]: 

253 for join in value: 

254 if not isinstance(join, str) or not join.strip(): 

255 raise ValueError("A join must be a non-empty SQL join clause") 

256 return value 

257 

258 @field_validator("data") 

259 @classmethod 

260 def validate_data(cls, value: t.List[str]) -> t.List[str]: 

261 for item in value: 

262 if not isinstance(item, str) or not item.strip(): 

263 raise ValueError("A data value must be a non-empty string") 

264 if split_data_value(item)[1] is None: 

265 raise ValueError( 

266 f"Data value '{item}' is a scalar expression, so it needs " 

267 "an alias to name the stored key: '<expression> AS <alias>'" 

268 ) 

269 return value 

270 

271 @model_validator(mode="after") 

272 def validate_feature(self) -> "FeatureConfig": 

273 data_names = [split_data_value(item)[1] for item in self.data] 

274 duplicates = {name for name in data_names if data_names.count(name) > 1} 

275 if duplicates: 

276 raise ValueError( 

277 f"Feature '{self.source}' has duplicate data keys: " 

278 f"{', '.join(sorted(duplicates))}" 

279 ) 

280 return self 

281 

282 

283class GazetteerConfig(BaseModel): 

284 """Top-level gazetteer configuration.""" 

285 

286 name: str 

287 crs: str = DEFAULT_CRS 

288 # Minimum free bytes needed on the gazetteers volume during install 

289 # (peak working set). Measured from a real install and rounded up by 

290 # authors; omitted for custom configs that have not been measured. 

291 disk: t.Optional[int] = None 

292 sources: t.List[SourceConfig] 

293 features: t.List[FeatureConfig] 

294 

295 @field_validator("name") 

296 @classmethod 

297 def validate_name(cls, value: str) -> str: 

298 if not _NAME_PATTERN.match(value): 

299 raise ValueError( 

300 f"Gazetteer name '{value}' must contain only letters, digits, " 

301 "underscores and hyphens" 

302 ) 

303 return value 

304 

305 @field_validator("disk") 

306 @classmethod 

307 def validate_disk(cls, value: t.Optional[int]) -> t.Optional[int]: 

308 if value is not None and value <= 0: 

309 raise ValueError("disk must be a positive number of bytes") 

310 return value 

311 

312 @field_validator("sources") 

313 @classmethod 

314 def validate_sources(cls, value: t.List[SourceConfig]) -> t.List[SourceConfig]: 

315 if not value: 

316 raise ValueError("A gazetteer must define at least one source") 

317 names = [source.name for source in value] 

318 duplicates = {name for name in names if names.count(name) > 1} 

319 if duplicates: 

320 raise ValueError(f"Duplicate source names: {', '.join(sorted(duplicates))}") 

321 return value 

322 

323 @field_validator("features") 

324 @classmethod 

325 def validate_features(cls, value: t.List[FeatureConfig]) -> t.List[FeatureConfig]: 

326 if not value: 

327 raise ValueError("A gazetteer must define at least one feature block") 

328 sources = [feature.source for feature in value] 

329 duplicates = {name for name in sources if sources.count(name) > 1} 

330 if duplicates: 

331 raise ValueError( 

332 "Each source can back at most one feature block, but these back " 

333 f"several: {', '.join(sorted(duplicates))}" 

334 ) 

335 return value 

336 

337 @model_validator(mode="after") 

338 def validate_references(self) -> "GazetteerConfig": 

339 source_names = {source.name for source in self.sources} 

340 

341 for feature in self.features: 

342 if feature.source not in source_names: 

343 raise ValueError( 

344 f"Feature references unknown source '{feature.source}'" 

345 ) 

346 return self 

347 

348 @classmethod 

349 def from_yaml(cls, path: t.Union[str, Path]) -> "GazetteerConfig": 

350 """ 

351 Load and validate a gazetteer configuration from a YAML file. 

352 

353 Relative source paths are resolved against the config file's directory. 

354 

355 Args: 

356 path: Path to the YAML configuration file 

357 

358 Returns: 

359 Validated GazetteerConfig instance 

360 """ 

361 with open(path, "r", encoding="utf-8") as config_file: 

362 data = yaml.safe_load(config_file) 

363 config = cls.model_validate(data) 

364 base_dir = Path(path).resolve().parent 

365 for source in config.sources: 

366 if source.path and not Path(source.path).is_absolute(): 

367 source.path = str(base_dir / source.path) 

368 return config