hypercadaster-ES 1.3.2__tar.gz → 1.4.1__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 (50) hide show
  1. {hypercadaster_es-1.3.2/hypercadaster_es.egg-info → hypercadaster_es-1.4.1}/PKG-INFO +20 -7
  2. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/README.md +4 -2
  3. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/hypercadaster_ES/__init__.py +1 -1
  4. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/hypercadaster_ES/_db.py +195 -86
  5. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/hypercadaster_ES/building_inference.py +18 -11
  6. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/hypercadaster_ES/downloaders.py +350 -44
  7. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/hypercadaster_ES/mergers.py +243 -160
  8. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/hypercadaster_ES/social.py +57 -3
  9. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/hypercadaster_ES/utils.py +13 -88
  10. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1/hypercadaster_es.egg-info}/PKG-INFO +20 -7
  11. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/hypercadaster_es.egg-info/SOURCES.txt +3 -0
  12. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/hypercadaster_es.egg-info/requires.txt +1 -3
  13. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/setup.py +2 -4
  14. hypercadaster_es-1.4.1/tests/test_cartociudad_api.py +47 -0
  15. hypercadaster_es-1.4.1/tests/test_cat_address.py +72 -0
  16. hypercadaster_es-1.4.1/tests/test_db_layer.py +356 -0
  17. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/tests/test_social.py +35 -0
  18. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/LICENSE +0 -0
  19. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/MANIFEST.in +0 -0
  20. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/hypercadaster_ES/_pretty.py +0 -0
  21. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/hypercadaster_ES/cached_files/ine_inspire_codes.xlsx +0 -0
  22. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/hypercadaster_ES/energy.py +0 -0
  23. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/hypercadaster_ES/energy_config.yaml +0 -0
  24. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/hypercadaster_ES/functions.py +0 -0
  25. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/hypercadaster_ES/interoperability.py +0 -0
  26. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/hypercadaster_ES/reporting.py +0 -0
  27. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/hypercadaster_ES/topology.py +0 -0
  28. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/hypercadaster_ES/weather.py +0 -0
  29. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/hypercadaster_es.egg-info/dependency_links.txt +0 -0
  30. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/hypercadaster_es.egg-info/top_level.txt +0 -0
  31. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/setup.cfg +0 -0
  32. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/tests/test_aggregation.py +0 -0
  33. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/tests/test_agricultural_archetype.py +0 -0
  34. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/tests/test_cat_cache.py +0 -0
  35. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/tests/test_cat_empty_schema.py +0 -0
  36. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/tests/test_census_tract_aggregations.py +0 -0
  37. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/tests/test_code_normalisation.py +0 -0
  38. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/tests/test_codes.py +0 -0
  39. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/tests/test_dem_tiles.py +0 -0
  40. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/tests/test_energy_config.py +0 -0
  41. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/tests/test_energy_scenarios.py +0 -0
  42. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/tests/test_floorplan_partition.py +0 -0
  43. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/tests/test_geometry.py +0 -0
  44. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/tests/test_import_surface.py +0 -0
  45. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/tests/test_live_smoke.py +0 -0
  46. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/tests/test_shadow_rules.py +0 -0
  47. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/tests/test_theoretical_cat_spaces.py +0 -0
  48. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/tests/test_topology.py +0 -0
  49. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/tests/test_weather.py +0 -0
  50. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.1}/tests/test_zero_floor_buildings.py +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: hypercadaster_es
3
- Version: 1.3.2
3
+ Version: 1.4.1
4
4
  Summary: Python library to obtain the Spanish cadaster data joined with external attributes.
5
5
  Home-page: https://github.com/BeeGroup-cimne
6
6
  Author: Jose Manuel Broto Vispe
@@ -32,7 +32,6 @@ Requires-Dist: partd>=1.4
32
32
  Requires-Dist: shapely<3.0,>=2.0
33
33
  Requires-Dist: pyproj<4.0,>=3.5
34
34
  Requires-Dist: rasterio<2.0,>=1.3
35
- Requires-Dist: fiona<2.0,>=1.9
36
35
  Requires-Dist: geopandas<1.2,>=1.1.2
37
36
  Requires-Dist: pyogrio<1.0,>=0.8
38
37
  Requires-Dist: affine>=2.4
@@ -47,9 +46,8 @@ Requires-Dist: pyarrow>=23.0.1
47
46
  Requires-Dist: openpyxl>=3.1
48
47
  Requires-Dist: et-xmlfile>=1.1
49
48
  Requires-Dist: arrow>=1.4.0
50
- Requires-Dist: fastkml>=1.4.0
51
49
  Requires-Dist: lxml>=6.1.0
52
- Requires-Dist: duckdb<2,>=1.5.3
50
+ Requires-Dist: duckdb<3,>=1.5.3
53
51
  Requires-Dist: cdsapi>=0.7
54
52
  Requires-Dist: xarray>=2024.1
55
53
  Requires-Dist: cfgrib>=0.9.10
@@ -89,6 +87,19 @@ Requires-Dist: ruff>=0.4; extra == "dev"
89
87
  Requires-Dist: pytest>=7.0; extra == "dev"
90
88
  Requires-Dist: pytest-cov>=4.0; extra == "dev"
91
89
  Requires-Dist: pdoc>=14.0; extra == "dev"
90
+ Dynamic: author
91
+ Dynamic: author-email
92
+ Dynamic: classifier
93
+ Dynamic: description
94
+ Dynamic: description-content-type
95
+ Dynamic: home-page
96
+ Dynamic: keywords
97
+ Dynamic: license
98
+ Dynamic: license-file
99
+ Dynamic: provides-extra
100
+ Dynamic: requires-dist
101
+ Dynamic: requires-python
102
+ Dynamic: summary
92
103
 
93
104
  # hypercadaster_ES
94
105
 
@@ -96,7 +107,7 @@ A comprehensive Python library for downloading, processing, and analyzing Spanis
96
107
 
97
108
  [![Python Version](https://img.shields.io/badge/python-3.12+-blue.svg)](https://python.org)
98
109
  [![License](https://img.shields.io/badge/license-EUPL%20v1.2-blue.svg)](https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12)
99
- [![Version](https://img.shields.io/badge/version-1.3.2-green.svg)](https://github.com/BeeGroup-cimne/hypercadaster_ES)
110
+ [![Version](https://img.shields.io/badge/version-1.4.1-green.svg)](https://github.com/BeeGroup-cimne/hypercadaster_ES)
100
111
 
101
112
  ## 🎯 Overview
102
113
 
@@ -206,6 +217,8 @@ For detailed installation instructions and advanced examples, see [Installation
206
217
 
207
218
  **Co-authors:**
208
219
  - **David Blanco** - dblanco@cimne.upc.edu
220
+ - **Kerin Cardona** - kcardona@cimne.upc.edu
221
+ - **Jordi Cipriano** - cipriano@cimne.upc.edu
209
222
  - **Gerard Laguna** - glaguna@cimne.upc.edu
210
223
  - **Nadiya Mehraj** - nmehraj@cimne.upc.edu
211
224
 
@@ -221,4 +234,4 @@ This project is licensed under the **EUPL v1.2**. See the [license](https://join
221
234
 
222
235
  *hypercadaster_ES - Built with ❤️ for the Spanish urban analysis and building research community*
223
236
 
224
- *Last updated: November 2026 | Version 1.3.2*
237
+ *Last updated: November 2026 | Version 1.4.1*
@@ -4,7 +4,7 @@ A comprehensive Python library for downloading, processing, and analyzing Spanis
4
4
 
5
5
  [![Python Version](https://img.shields.io/badge/python-3.12+-blue.svg)](https://python.org)
6
6
  [![License](https://img.shields.io/badge/license-EUPL%20v1.2-blue.svg)](https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12)
7
- [![Version](https://img.shields.io/badge/version-1.3.2-green.svg)](https://github.com/BeeGroup-cimne/hypercadaster_ES)
7
+ [![Version](https://img.shields.io/badge/version-1.4.1-green.svg)](https://github.com/BeeGroup-cimne/hypercadaster_ES)
8
8
 
9
9
  ## 🎯 Overview
10
10
 
@@ -114,6 +114,8 @@ For detailed installation instructions and advanced examples, see [Installation
114
114
 
115
115
  **Co-authors:**
116
116
  - **David Blanco** - dblanco@cimne.upc.edu
117
+ - **Kerin Cardona** - kcardona@cimne.upc.edu
118
+ - **Jordi Cipriano** - cipriano@cimne.upc.edu
117
119
  - **Gerard Laguna** - glaguna@cimne.upc.edu
118
120
  - **Nadiya Mehraj** - nmehraj@cimne.upc.edu
119
121
 
@@ -129,4 +131,4 @@ This project is licensed under the **EUPL v1.2**. See the [license](https://join
129
131
 
130
132
  *hypercadaster_ES - Built with ❤️ for the Spanish urban analysis and building research community*
131
133
 
132
- *Last updated: November 2026 | Version 1.3.2*
134
+ *Last updated: November 2026 | Version 1.4.1*
@@ -26,7 +26,7 @@ from ._db import ResultsHandle
26
26
  from . import (mergers, utils, building_inference, downloaders, interoperability,
27
27
  energy, weather, social, topology, reporting)
28
28
 
29
- __version__ = "1.3.2"
29
+ __version__ = "1.4.1"
30
30
  __author__ = "Jose Manuel Broto Vispe"
31
31
  __email__ = "jmbrotovispe@gmail.com"
32
32
 
@@ -106,11 +106,39 @@ def ensure_schema(con: duckdb.DuckDBPyConnection) -> None:
106
106
  CAT_SPACES_TABLE = "cat_building_spaces"
107
107
 
108
108
 
109
+ def fetch_first(con: duckdb.DuckDBPyConnection, sql: str,
110
+ params: Optional[list] = None):
111
+ """Run ``sql`` and return its first row (or None), fully consuming the result.
112
+
113
+ Use instead of ``con.execute(...).fetchone()``: duckdb 2.0 treats a result
114
+ read with ``fetchone()`` as unfinished, and a later ``register()`` /
115
+ ``sql()`` on the same connection then raises ResourceInUseException. Only
116
+ for queries that return at most a handful of rows (COUNT, key lookups,
117
+ ``LIMIT 1``).
118
+ """
119
+ rows = con.execute(sql, params or []).fetchall()
120
+ return rows[0] if rows else None
121
+
122
+
123
+ def _is_null_type(type_name: str) -> bool:
124
+ """True for DuckDB's untyped "NULL" column type (DESCRIBE shows it quoted)."""
125
+ return type_name.strip('"').upper() == "NULL"
126
+
127
+
109
128
  def _table_exists(con: duckdb.DuckDBPyConnection, table: str) -> bool:
110
- return con.execute(
111
- "SELECT 1 FROM information_schema.tables WHERE table_name = ?",
129
+ """True when ``table`` exists in the connection's own ``main`` schema.
130
+
131
+ Catalog lookup, never a probing query that can fail: under duckdb 2.0 a
132
+ failed statement aborts an enclosing transaction even when caught. Scoped to
133
+ the current database so a same-named table in an ATTACHed shard is ignored.
134
+ """
135
+ return fetch_first(
136
+ con,
137
+ "SELECT 1 FROM information_schema.tables "
138
+ "WHERE table_catalog = current_database() AND table_schema = 'main' "
139
+ "AND table_name = ? LIMIT 1",
112
140
  [table],
113
- ).fetchone() is not None
141
+ ) is not None
114
142
 
115
143
 
116
144
  def cat_cache_read(results_dir: str, cadaster_code: str):
@@ -168,12 +196,12 @@ def cat_cache_clear(results_dir: str, cadaster_code: Optional[str] = None) -> in
168
196
  if not _table_exists(con, tbl):
169
197
  continue
170
198
  if cadaster_code is None:
171
- removed += con.execute(f'SELECT COUNT(*) FROM "{tbl}"').fetchone()[0]
199
+ removed += fetch_first(con, f'SELECT COUNT(*) FROM "{tbl}"')[0]
172
200
  con.execute(f'DROP TABLE "{tbl}"')
173
201
  else:
174
- removed += con.execute(
175
- f'SELECT COUNT(*) FROM "{tbl}" WHERE cadaster_code = ?',
176
- [str(cadaster_code)]).fetchone()[0]
202
+ removed += fetch_first(
203
+ con, f'SELECT COUNT(*) FROM "{tbl}" WHERE cadaster_code = ?',
204
+ [str(cadaster_code)])[0]
177
205
  con.execute(
178
206
  f'DELETE FROM "{tbl}" WHERE cadaster_code = ?',
179
207
  [str(cadaster_code)])
@@ -348,9 +376,8 @@ def set_table_crs(con: duckdb.DuckDBPyConnection, table: str, crs) -> None:
348
376
 
349
377
  def get_table_crs(con: duckdb.DuckDBPyConnection, table: str):
350
378
  """Return the stored ``pyproj.CRS`` for a table, or None if unset."""
351
- row = con.execute(
352
- "SELECT value FROM _meta WHERE key = ?", [f"crs:{table}"]
353
- ).fetchone()
379
+ row = fetch_first(
380
+ con, "SELECT value FROM _meta WHERE key = ?", [f"crs:{table}"])
354
381
  if row is None:
355
382
  return None
356
383
  from pyproj import CRS as _CRS
@@ -413,11 +440,13 @@ def _df_with_wkb(gdf: gpd.GeoDataFrame, geom_cols: Iterable[str]) -> pd.DataFram
413
440
  # object (dict, list, numpy scalar, etc.). Strings and bytes pass
414
441
  # through as-is; they're already DuckDB-compatible. This handles
415
442
  # round-trips through read_gdf which unpickles BLOB columns on read.
443
+ # The decision covers EVERY value, not a sample: a column that is str in
444
+ # some rows and float / dict in others (shard type drift) must be pickled
445
+ # whole, or DuckDB either rejects the frame or silently coerces it.
416
446
  for col in df.columns:
417
447
  if col in geom_set or df[col].dtype != object:
418
448
  continue
419
- sample = _first_non_null(df[col])
420
- if sample is None or isinstance(sample, (str, bytes, bytearray, memoryview)):
449
+ if _object_kind(df[col]) in ("null", "str", "bytes"):
421
450
  continue
422
451
  df[col] = [None if _is_null(v) else _to_pickle_bytes(v) for v in df[col]]
423
452
  return df
@@ -467,29 +496,32 @@ def write_gdf(con: duckdb.DuckDBPyConnection, table: str, gdf: gpd.GeoDataFrame,
467
496
  for col in gdf.columns:
468
497
  if col in geom_set:
469
498
  continue
470
- sample = _first_non_null(gdf[col])
471
- if isinstance(sample, _BaseGeometry):
499
+ if not isinstance(_first_non_null(gdf[col]), _BaseGeometry):
500
+ continue # cheap reject; a geometry column's first value is one
501
+ # Only when EVERY value is a geometry; a mixed column is pickled.
502
+ if _object_kind(gdf[col]) == "geometry":
472
503
  geom_set.add(col)
473
504
  geom_cols = tuple(geom_set)
474
505
  df = _df_with_wkb(gdf, geom_cols)
475
506
  con.register("_tmp_write_gdf", df)
476
507
 
477
- def _table_exists() -> bool:
478
- try:
479
- con.execute(f'DESCRIBE "{table}"')
480
- return True
481
- except Exception:
482
- return False
483
-
484
508
  def _reconcile_schema():
485
- """ADD COLUMN for every frame column the table doesn't have yet."""
486
- existing = {r[0] for r in con.execute(f'DESCRIBE "{table}"').fetchall()}
509
+ """ADD COLUMN for every frame column the table doesn't have yet.
510
+
511
+ A column created from an all-None frame column gets DuckDB's "NULL"
512
+ type, which nothing can be cast into; once a frame carries a real type
513
+ for it, the table column is retyped to that type.
514
+ """
515
+ existing = {r[0]: str(r[1])
516
+ for r in con.execute(f'DESCRIBE "{table}"').fetchall()}
487
517
  tmp_types = {r[0]: str(r[1])
488
518
  for r in con.execute('DESCRIBE _tmp_write_gdf').fetchall()}
489
519
  for c in df.columns:
520
+ _ty = 'GEOMETRY' if c in geom_set else tmp_types.get(c, 'VARCHAR')
490
521
  if c not in existing:
491
- _ty = 'GEOMETRY' if c in geom_set else tmp_types.get(c, 'VARCHAR')
492
522
  con.execute(f'ALTER TABLE "{table}" ADD COLUMN "{c}" {_ty}')
523
+ elif (_is_null_type(existing[c]) and not _is_null_type(_ty)):
524
+ con.execute(f'ALTER TABLE "{table}" ALTER COLUMN "{c}" TYPE {_ty}')
493
525
 
494
526
  try:
495
527
  select_sql = _geom_select_sql(df.columns, geom_cols)
@@ -515,7 +547,7 @@ def write_gdf(con: duckdb.DuckDBPyConnection, table: str, gdf: gpd.GeoDataFrame,
515
547
  f"key_cols={key_cols!r}, frame columns missing "
516
548
  f"{[k for k in keys if k not in df.columns]}"
517
549
  )
518
- if not _table_exists():
550
+ if not _table_exists(con, table):
519
551
  con.execute(
520
552
  f'CREATE TABLE "{table}" AS SELECT {select_sql} FROM _tmp_write_gdf'
521
553
  )
@@ -643,11 +675,12 @@ def get_blob_for_building(results_dir: str, cadaster_code: str,
643
675
  select_sql = ", ".join(f'"{c}"' for c in cols)
644
676
  con = open_shard_read(db_path(results_dir))
645
677
  try:
646
- row = con.execute(
678
+ row = fetch_first(
679
+ con,
647
680
  f'SELECT {select_sql} FROM "main"."{table}" '
648
681
  f'WHERE cadaster_code = ? AND building_reference = ? LIMIT 1',
649
682
  [cadaster_code, building_reference],
650
- ).fetchone()
683
+ )
651
684
  finally:
652
685
  con.close()
653
686
  if row is None:
@@ -694,6 +727,29 @@ def read_df_safe_chunks(con: duckdb.DuckDBPyConnection, table: str, *,
694
727
  sql += f" WHERE {where}"
695
728
 
696
729
  result = con.execute(sql, params or [])
730
+ exhausted = False
731
+ try:
732
+ yield from _decoded_chunks(result, cols, types, geom_cols,
733
+ vectors_per_chunk)
734
+ exhausted = True
735
+ finally:
736
+ # Do NOT call result.close(): DuckDB's Python API returns the same
737
+ # connection object from con.execute(), so closing the "result"
738
+ # would close the connection itself. If the consumer stopped early
739
+ # the result is only partially read, which under duckdb 2.0 blocks
740
+ # register()/sql() on this connection — replacing it with a trivial
741
+ # execute() releases it (and is harmless on 1.x).
742
+ if not exhausted:
743
+ try:
744
+ con.execute("SELECT 1").fetchall()
745
+ except Exception:
746
+ pass
747
+ del result
748
+
749
+
750
+ def _decoded_chunks(result, cols, types, geom_cols, vectors_per_chunk):
751
+ """Yield decoded pandas chunks from an open ``execute()`` result until it
752
+ is exhausted (helper for :func:`read_df_safe_chunks`)."""
697
753
  while True:
698
754
  try:
699
755
  chunk = result.fetch_df_chunk(vectors_per_chunk)
@@ -709,20 +765,9 @@ def read_df_safe_chunks(con: duckdb.DuckDBPyConnection, table: str, *,
709
765
  for col in cols:
710
766
  if types[col] != "BLOB" or col in geom_cols:
711
767
  continue
712
- sample = _first_non_null(chunk[col])
713
- if sample is None:
714
- continue
715
- sb = bytes(sample) if not isinstance(sample, bytes) else sample
716
- if not (len(sb) >= 2 and sb[0] == 0x80):
717
- continue
718
- chunk[col] = [_maybe_unpickle(b) for b in chunk[col]]
768
+ if _any_pickled(chunk[col]):
769
+ chunk[col] = [_maybe_unpickle(b) for b in chunk[col]]
719
770
  yield chunk
720
- # Do NOT call result.close(): DuckDB's Python API returns the same
721
- # connection object from con.execute(), so closing the "result"
722
- # would close the connection itself. Dropping the local reference
723
- # and letting the next con.execute() displace the cursor state is
724
- # the correct cleanup.
725
- del result
726
771
 
727
772
 
728
773
  def ingest_shard_table(central_con: duckdb.DuckDBPyConnection, *,
@@ -766,17 +811,18 @@ def ingest_shard_table(central_con: duckdb.DuckDBPyConnection, *,
766
811
 
767
812
  # Fully qualify with "main" so DESCRIBE / ALTER don't get confused by
768
813
  # an identically-named table in the ATTACH'd shard.
769
- try:
814
+ # Catalog lookup rather than a DESCRIBE probe: Phase A runs this inside
815
+ # BEGIN TRANSACTION, and under duckdb 2.0 a failed probe (table missing on
816
+ # the first shard) aborts the transaction even when caught.
817
+ central_exists = _table_exists(central_con, central_table)
818
+ if central_exists:
770
819
  existing_rows = central_con.execute(
771
820
  f'DESCRIBE "main"."{central_table}"'
772
821
  ).fetchall()
773
822
  existing_types = {r[0]: str(r[1]).upper() for r in existing_rows}
774
- existing = set(existing_types.keys())
775
- central_exists = True
776
- except Exception:
823
+ else:
777
824
  existing_types = {}
778
- existing = set()
779
- central_exists = False
825
+ existing = set(existing_types.keys())
780
826
 
781
827
  bookkeeping_cols = list(bookkeeping.keys())
782
828
  pickle_wrap_cols: set = set()
@@ -844,6 +890,7 @@ def ingest_shard_table(central_con: duckdb.DuckDBPyConnection, *,
844
890
  existing_types[n] = "BLOB"
845
891
  kept.append((n, "BLOB"))
846
892
  except Exception as _wide_err:
893
+ _raise_if_txn_aborted(central_con, _wide_err)
847
894
  sys.stderr.write(
848
895
  f"[ingest_shard_table] could not widen '{n}' "
849
896
  f"from {ct} to BLOB ({_wide_err}); dropping for "
@@ -863,6 +910,7 @@ def ingest_shard_table(central_con: duckdb.DuckDBPyConnection, *,
863
910
  existing_types[n] = "DOUBLE"
864
911
  kept.append((n, "DOUBLE"))
865
912
  except Exception as _ne:
913
+ _raise_if_txn_aborted(central_con, _ne)
866
914
  sys.stderr.write(
867
915
  f"[ingest_shard_table] type drift on '{n}' "
868
916
  f"(central={ct}, shard={st}); could not widen "
@@ -1015,6 +1063,22 @@ def ingest_shard_table(central_con: duckdb.DuckDBPyConnection, *,
1015
1063
  central_con.unregister("_tmp_ingest_wrap")
1016
1064
 
1017
1065
 
1066
+ def _raise_if_txn_aborted(con: duckdb.DuckDBPyConnection,
1067
+ err: Exception) -> None:
1068
+ """Re-raise ``err`` when it left ``con``'s transaction aborted.
1069
+
1070
+ duckdb 2.0 aborts an explicit transaction on any failed statement, so a
1071
+ caught error can't be recovered from inside it: every later statement
1072
+ fails and COMMIT rolls back. Probing with a no-op tells the two cases
1073
+ apart; under autocommit (and duckdb 1.x) the probe succeeds and the
1074
+ caller's fallback proceeds.
1075
+ """
1076
+ try:
1077
+ con.execute("SELECT 1").fetchall()
1078
+ except Exception:
1079
+ raise err
1080
+
1081
+
1018
1082
  def _is_null(v) -> bool:
1019
1083
  """True for None / pd.NA / NaN floats. Robust against scalars where
1020
1084
  pd.isna would broadcast (e.g. ndarrays in object columns)."""
@@ -1057,17 +1121,14 @@ def _classify_columns(df: pd.DataFrame) -> Tuple[List[str], List[str], List[str]
1057
1121
  if s.dtype != object and dtype_name != "geometry":
1058
1122
  primitive.append(col)
1059
1123
  continue
1060
- sample = _first_non_null(s)
1061
- if sample is None:
1062
- primitive.append(col)
1063
- continue
1064
- # Shapely objects all expose __geo_interface__ and wkb_hex / wkb attrs.
1065
- if hasattr(sample, "__geo_interface__") and hasattr(sample, "wkb"):
1124
+ # Classified over every value, not a sample, so a column mixing str
1125
+ # with other types (shard type drift) is pickled rather than handed to
1126
+ # DuckDB as a column it can't type.
1127
+ kind = _object_kind(s)
1128
+ if kind == "geometry":
1066
1129
  geometry.append(col)
1067
- elif isinstance(sample, str):
1068
- primitive.append(col)
1069
- elif isinstance(sample, (bytes, bytearray, memoryview)):
1070
- primitive.append(col) # already binary; let DuckDB store as BLOB
1130
+ elif kind in ("null", "str", "bytes"):
1131
+ primitive.append(col) # bytes: already binary, stored as BLOB
1071
1132
  else:
1072
1133
  opaque.append(col)
1073
1134
  return primitive, geometry, opaque
@@ -1196,21 +1257,61 @@ def read_df_safe(con: duckdb.DuckDBPyConnection, table: str, *,
1196
1257
  # look like pickle (start with 0x80) and successfully unpickle, use
1197
1258
  # the rehydrated value; otherwise leave as raw bytes. Per-row
1198
1259
  # robustness matters because a column may end up mixed across
1199
- # shards, and a single coincidentally-0x80 raw value used to crash
1200
- # the whole read.
1260
+ # shards (text widened by type drift + pickles), and row order is
1261
+ # arbitrary (preserve_insertion_order=false) — so the decision must
1262
+ # not depend on whichever value happens to come first.
1201
1263
  for col in cols:
1202
1264
  if types[col] != "BLOB" or col in geom_cols:
1203
1265
  continue
1204
- sample = _first_non_null(df[col])
1205
- if sample is None:
1206
- continue
1207
- sb = bytes(sample) if not isinstance(sample, bytes) else sample
1208
- if not (len(sb) >= 2 and sb[0] == 0x80):
1209
- continue # no row in the probe likely pickled; cheap-out
1210
- df[col] = [_maybe_unpickle(b) for b in df[col]]
1266
+ if _any_pickled(df[col]):
1267
+ df[col] = [_maybe_unpickle(b) for b in df[col]]
1211
1268
  return df
1212
1269
 
1213
1270
 
1271
+ def _is_pickle_bytes(v) -> bool:
1272
+ """True for a bytes-like value carrying our pickle prefix (0x80)."""
1273
+ if not isinstance(v, (bytes, bytearray, memoryview)):
1274
+ return False
1275
+ return len(v) >= 2 and bytes(v[:1]) == b"\x80"
1276
+
1277
+
1278
+ def _any_pickled(series) -> bool:
1279
+ """True when any value of ``series`` looks like our pickled BLOB."""
1280
+ return any(_is_pickle_bytes(v) for v in series)
1281
+
1282
+
1283
+ def _object_kind(series: pd.Series) -> str:
1284
+ """Classify an object column over ALL its non-null values.
1285
+
1286
+ Returns ``'null'`` (no values), ``'str'`` / ``'bytes'`` (every value of
1287
+ that type), ``'geometry'`` (every value a shapely geometry) or ``'mixed'``
1288
+ (anything else, including a mix of the above). pandas' C-level
1289
+ ``infer_dtype`` short-circuits the common homogeneous cases.
1290
+ """
1291
+ inferred = pd.api.types.infer_dtype(series, skipna=True)
1292
+ if inferred == "empty":
1293
+ return "null"
1294
+ if inferred == "string":
1295
+ return "str"
1296
+ if inferred == "bytes":
1297
+ return "bytes"
1298
+ kinds = set()
1299
+ for v in series:
1300
+ if _is_null(v):
1301
+ continue
1302
+ if isinstance(v, str):
1303
+ kinds.add("str")
1304
+ elif isinstance(v, (bytes, bytearray, memoryview)):
1305
+ kinds.add("bytes")
1306
+ elif hasattr(v, "__geo_interface__") and hasattr(v, "wkb"):
1307
+ kinds.add("geometry")
1308
+ else:
1309
+ return "mixed"
1310
+ if len(kinds) > 1:
1311
+ return "mixed"
1312
+ return kinds.pop() if kinds else "null"
1313
+
1314
+
1214
1315
  def _maybe_unpickle(b):
1215
1316
  """Try to unpickle bytes; on any failure (or non-pickle), return raw."""
1216
1317
  if b is None or b is pd.NA:
@@ -1367,20 +1468,26 @@ def read_gdf(con: duckdb.DuckDBPyConnection, table: str, *,
1367
1468
  if col in geom_typed:
1368
1469
  df[col] = [_wkb_or_none(v) for v in df[col]]
1369
1470
  continue
1370
- sample = _first_non_null(df[col])
1371
- if sample is None or not isinstance(sample, (bytes, bytearray, memoryview)):
1471
+ blobs = [v for v in df[col] if isinstance(v, (bytes, bytearray, memoryview))]
1472
+ if not blobs:
1372
1473
  continue
1373
- sb = bytes(sample) if not isinstance(sample, bytes) else sample
1374
- if len(sb) >= 2 and sb[0] == 0x80:
1375
- df[col] = [_maybe_unpickle(v) for v in df[col]] # pickled object
1376
- else:
1377
- # Non-pickle BLOB: decode to str if it is valid UTF-8 text (e.g. a
1378
- # date string that shard type-drift widened to BLOB), else keep raw.
1379
- try:
1380
- sb.decode('utf-8')
1381
- except Exception:
1382
- continue
1383
- df[col] = [_text_or_bytes(v) for v in df[col]]
1474
+ # Decide per value, never from the first row (row order is arbitrary):
1475
+ # a column widened to BLOB by shard type drift holds text-encoded
1476
+ # values from early shards AND pickles from later ones. Pickles are
1477
+ # always rehydrated; the remaining bytes are decoded to str only when
1478
+ # all of them are valid UTF-8 text (e.g. a widened date string), else
1479
+ # they stay raw so genuinely binary data is never half-decoded.
1480
+ raw = [bytes(v) for v in blobs if not _is_pickle_bytes(v)]
1481
+ try:
1482
+ for b in raw:
1483
+ b.decode('utf-8')
1484
+ decode_text = bool(raw)
1485
+ except UnicodeDecodeError:
1486
+ decode_text = False
1487
+ df[col] = [_maybe_unpickle(v) if _is_pickle_bytes(v)
1488
+ else _text_or_bytes(v) if decode_text
1489
+ else v
1490
+ for v in df[col]]
1384
1491
  return gpd.GeoDataFrame(df, geometry=geom_col, crs=get_table_crs(con, table))
1385
1492
 
1386
1493
 
@@ -1422,17 +1529,17 @@ class ResultsHandle:
1422
1529
  def sbr_relation(self) -> duckdb.DuckDBPyRelation:
1423
1530
  """Return a lazy DuckDB relation for sbr_results filtered by code."""
1424
1531
  con = self._con()
1425
- return con.execute(
1532
+ return con.sql(
1426
1533
  'SELECT * FROM "main"."sbr_results" WHERE cadaster_code = ?',
1427
- [self.cadaster_code],
1534
+ params=[self.cadaster_code],
1428
1535
  )
1429
1536
 
1430
1537
  def br_relation(self) -> duckdb.DuckDBPyRelation:
1431
1538
  """Return a lazy DuckDB relation for br_results filtered by code."""
1432
1539
  con = self._con()
1433
- return con.execute(
1540
+ return con.sql(
1434
1541
  'SELECT * FROM "main"."br_results" WHERE cadaster_code = ?',
1435
- [self.cadaster_code],
1542
+ params=[self.cadaster_code],
1436
1543
  )
1437
1544
 
1438
1545
  # -- batched iteration --------------------------------------------------
@@ -1504,10 +1611,11 @@ class ResultsHandle:
1504
1611
  con = self._con()
1505
1612
  own_con = con is not self._parent_con
1506
1613
  try:
1507
- row = con.execute(
1614
+ row = fetch_first(
1615
+ con,
1508
1616
  'SELECT count(*) FROM "main"."sbr_results" WHERE cadaster_code = ?',
1509
1617
  [self.cadaster_code],
1510
- ).fetchone()
1618
+ )
1511
1619
  return row[0] if row else 0
1512
1620
  finally:
1513
1621
  if own_con:
@@ -1518,10 +1626,11 @@ class ResultsHandle:
1518
1626
  con = self._con()
1519
1627
  own_con = con is not self._parent_con
1520
1628
  try:
1521
- row = con.execute(
1629
+ row = fetch_first(
1630
+ con,
1522
1631
  'SELECT count(*) FROM "main"."br_results" WHERE cadaster_code = ?',
1523
1632
  [self.cadaster_code],
1524
- ).fetchone()
1633
+ )
1525
1634
  return row[0] if row else 0
1526
1635
  finally:
1527
1636
  if own_con:
@@ -752,10 +752,11 @@ def process_building_parts(code, building_part_gdf_, buildings_CAT, parcels_gdf,
752
752
  try:
753
753
  def _aux_present(tbl):
754
754
  try:
755
- return _aux_con.execute(
755
+ return _db_mod_aux.fetch_first(
756
+ _aux_con,
756
757
  f'SELECT 1 FROM "main"."{tbl}" '
757
758
  f'WHERE cadaster_code = ? LIMIT 1', [code],
758
- ).fetchone() is not None
759
+ ) is not None
759
760
  except Exception:
760
761
  return False
761
762
 
@@ -1204,10 +1205,11 @@ def process_building_parts(code, building_part_gdf_, buildings_CAT, parcels_gdf,
1204
1205
  if cleanup_shards:
1205
1206
  with utils.stage_timer("post-KPI: cleanup aggregated shards"):
1206
1207
  try:
1207
- has_central_data = central_con.execute(
1208
+ has_central_data = _db_mod.fetch_first(
1209
+ central_con,
1208
1210
  'SELECT 1 FROM "main"."sbr_results" '
1209
1211
  'WHERE cadaster_code = ? LIMIT 1', [code],
1210
- ).fetchone() is not None
1212
+ ) is not None
1211
1213
  except Exception:
1212
1214
  has_central_data = False
1213
1215
 
@@ -3127,8 +3129,10 @@ def parse_horizontal_division_buildings_CAT_files(cadaster_code, CAT_files_dir):
3127
3129
  return None
3128
3130
 
3129
3131
  # Join the building space and building spaces detailed datasets. Order the items by floor.
3130
- building_spaces_detailed = combined_dfs[14]
3131
- building_spaces = combined_dfs[15]
3132
+ # parse_CAT_file stores blank fields as null; this function relies on blank
3133
+ # text fields being "" (filters, concat_str of references, floor sorting).
3134
+ building_spaces_detailed = combined_dfs[14].with_columns(pl.col(pl.Utf8).fill_null(""))
3135
+ building_spaces = combined_dfs[15].with_columns(pl.col(pl.Utf8).fill_null(""))
3132
3136
  building_spaces = building_spaces.with_columns(
3133
3137
  pl.concat_str(['building_reference', 'space1_reference'], separator=""
3134
3138
  ).alias("building_space_reference"),
@@ -3288,12 +3292,15 @@ def parse_horizontal_division_buildings_CAT_files(cadaster_code, CAT_files_dir):
3288
3292
  )
3289
3293
 
3290
3294
  # Calculate the complete address
3295
+ # Blank numbers ("" once nulls are filled, e.g. a space with no address)
3296
+ # are left empty like the all-zero ones. The cast runs on every row before
3297
+ # pl.when masks it, so "" is nulled first rather than cast.
3291
3298
  building_spaces_detailed = building_spaces_detailed.with_columns(
3292
- (pl.when(pl.col("street_number1") == "0000").then(pl.lit("")).otherwise(
3293
- pl.col("street_number1").cast(pl.Int16))).alias("street_number1"),
3294
- (pl.when(pl.col("street_number2") == "0000").then(pl.lit("")).otherwise(
3295
- pl.col("street_number2").cast(pl.Int16))).alias("street_number2"),
3296
- (pl.when(pl.col("km") == "00000").then(pl.lit("")).otherwise(pl.col("km").cast(pl.Int16))).alias("km")
3299
+ (pl.when(pl.col("street_number1").is_in(["0000", ""])).then(pl.lit("")).otherwise(
3300
+ pl.col("street_number1").replace("", None).cast(pl.Int16))).alias("street_number1"),
3301
+ (pl.when(pl.col("street_number2").is_in(["0000", ""])).then(pl.lit("")).otherwise(
3302
+ pl.col("street_number2").replace("", None).cast(pl.Int16))).alias("street_number2"),
3303
+ (pl.when(pl.col("km").is_in(["00000", ""])).then(pl.lit("")).otherwise(pl.col("km").replace("", None).cast(pl.Int16))).alias("km")
3297
3304
  )
3298
3305
  # Human-readable street components for the postal address: expand the
3299
3306
  # two-letter cadastral street-type acronym to its literal ("CR" ->