hypercadaster-ES 1.3.2__tar.gz → 1.4.0__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.0}/PKG-INFO +6 -6
  2. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/README.md +4 -2
  3. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/hypercadaster_ES/__init__.py +1 -1
  4. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/hypercadaster_ES/_db.py +179 -83
  5. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/hypercadaster_ES/building_inference.py +6 -4
  6. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/hypercadaster_ES/downloaders.py +350 -44
  7. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/hypercadaster_ES/mergers.py +243 -160
  8. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/hypercadaster_ES/social.py +57 -3
  9. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/hypercadaster_ES/utils.py +2 -77
  10. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0/hypercadaster_es.egg-info}/PKG-INFO +6 -6
  11. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/hypercadaster_es.egg-info/SOURCES.txt +3 -0
  12. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/hypercadaster_es.egg-info/requires.txt +1 -3
  13. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/setup.py +2 -4
  14. hypercadaster_es-1.4.0/tests/test_cartociudad_api.py +47 -0
  15. hypercadaster_es-1.4.0/tests/test_cat_address.py +72 -0
  16. hypercadaster_es-1.4.0/tests/test_db_layer.py +356 -0
  17. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/tests/test_social.py +35 -0
  18. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/LICENSE +0 -0
  19. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/MANIFEST.in +0 -0
  20. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/hypercadaster_ES/_pretty.py +0 -0
  21. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/hypercadaster_ES/cached_files/ine_inspire_codes.xlsx +0 -0
  22. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/hypercadaster_ES/energy.py +0 -0
  23. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/hypercadaster_ES/energy_config.yaml +0 -0
  24. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/hypercadaster_ES/functions.py +0 -0
  25. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/hypercadaster_ES/interoperability.py +0 -0
  26. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/hypercadaster_ES/reporting.py +0 -0
  27. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/hypercadaster_ES/topology.py +0 -0
  28. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/hypercadaster_ES/weather.py +0 -0
  29. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/hypercadaster_es.egg-info/dependency_links.txt +0 -0
  30. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/hypercadaster_es.egg-info/top_level.txt +0 -0
  31. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/setup.cfg +0 -0
  32. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/tests/test_aggregation.py +0 -0
  33. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/tests/test_agricultural_archetype.py +0 -0
  34. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/tests/test_cat_cache.py +0 -0
  35. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/tests/test_cat_empty_schema.py +0 -0
  36. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/tests/test_census_tract_aggregations.py +0 -0
  37. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/tests/test_code_normalisation.py +0 -0
  38. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/tests/test_codes.py +0 -0
  39. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/tests/test_dem_tiles.py +0 -0
  40. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/tests/test_energy_config.py +0 -0
  41. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/tests/test_energy_scenarios.py +0 -0
  42. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/tests/test_floorplan_partition.py +0 -0
  43. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/tests/test_geometry.py +0 -0
  44. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/tests/test_import_surface.py +0 -0
  45. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/tests/test_live_smoke.py +0 -0
  46. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/tests/test_shadow_rules.py +0 -0
  47. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/tests/test_theoretical_cat_spaces.py +0 -0
  48. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/tests/test_topology.py +0 -0
  49. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/tests/test_weather.py +0 -0
  50. {hypercadaster_es-1.3.2 → hypercadaster_es-1.4.0}/tests/test_zero_floor_buildings.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: hypercadaster_es
3
- Version: 1.3.2
3
+ Version: 1.4.0
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
@@ -96,7 +94,7 @@ A comprehensive Python library for downloading, processing, and analyzing Spanis
96
94
 
97
95
  [![Python Version](https://img.shields.io/badge/python-3.12+-blue.svg)](https://python.org)
98
96
  [![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)
97
+ [![Version](https://img.shields.io/badge/version-1.4.0-green.svg)](https://github.com/BeeGroup-cimne/hypercadaster_ES)
100
98
 
101
99
  ## 🎯 Overview
102
100
 
@@ -206,6 +204,8 @@ For detailed installation instructions and advanced examples, see [Installation
206
204
 
207
205
  **Co-authors:**
208
206
  - **David Blanco** - dblanco@cimne.upc.edu
207
+ - **Kerin Cardona** - kcardona@cimne.upc.edu
208
+ - **Jordi Cipriano** - cipriano@cimne.upc.edu
209
209
  - **Gerard Laguna** - glaguna@cimne.upc.edu
210
210
  - **Nadiya Mehraj** - nmehraj@cimne.upc.edu
211
211
 
@@ -221,4 +221,4 @@ This project is licensed under the **EUPL v1.2**. See the [license](https://join
221
221
 
222
222
  *hypercadaster_ES - Built with ❤️ for the Spanish urban analysis and building research community*
223
223
 
224
- *Last updated: November 2026 | Version 1.3.2*
224
+ *Last updated: November 2026 | Version 1.4.0*
@@ -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.0-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.0*
@@ -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.0"
30
30
  __author__ = "Jose Manuel Broto Vispe"
31
31
  __email__ = "jmbrotovispe@gmail.com"
32
32
 
@@ -106,11 +106,34 @@ 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
+
109
123
  def _table_exists(con: duckdb.DuckDBPyConnection, table: str) -> bool:
110
- return con.execute(
111
- "SELECT 1 FROM information_schema.tables WHERE table_name = ?",
124
+ """True when ``table`` exists in the connection's own ``main`` schema.
125
+
126
+ Catalog lookup, never a probing query that can fail: under duckdb 2.0 a
127
+ failed statement aborts an enclosing transaction even when caught. Scoped to
128
+ the current database so a same-named table in an ATTACHed shard is ignored.
129
+ """
130
+ return fetch_first(
131
+ con,
132
+ "SELECT 1 FROM information_schema.tables "
133
+ "WHERE table_catalog = current_database() AND table_schema = 'main' "
134
+ "AND table_name = ? LIMIT 1",
112
135
  [table],
113
- ).fetchone() is not None
136
+ ) is not None
114
137
 
115
138
 
116
139
  def cat_cache_read(results_dir: str, cadaster_code: str):
@@ -168,12 +191,12 @@ def cat_cache_clear(results_dir: str, cadaster_code: Optional[str] = None) -> in
168
191
  if not _table_exists(con, tbl):
169
192
  continue
170
193
  if cadaster_code is None:
171
- removed += con.execute(f'SELECT COUNT(*) FROM "{tbl}"').fetchone()[0]
194
+ removed += fetch_first(con, f'SELECT COUNT(*) FROM "{tbl}"')[0]
172
195
  con.execute(f'DROP TABLE "{tbl}"')
173
196
  else:
174
- removed += con.execute(
175
- f'SELECT COUNT(*) FROM "{tbl}" WHERE cadaster_code = ?',
176
- [str(cadaster_code)]).fetchone()[0]
197
+ removed += fetch_first(
198
+ con, f'SELECT COUNT(*) FROM "{tbl}" WHERE cadaster_code = ?',
199
+ [str(cadaster_code)])[0]
177
200
  con.execute(
178
201
  f'DELETE FROM "{tbl}" WHERE cadaster_code = ?',
179
202
  [str(cadaster_code)])
@@ -348,9 +371,8 @@ def set_table_crs(con: duckdb.DuckDBPyConnection, table: str, crs) -> None:
348
371
 
349
372
  def get_table_crs(con: duckdb.DuckDBPyConnection, table: str):
350
373
  """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()
374
+ row = fetch_first(
375
+ con, "SELECT value FROM _meta WHERE key = ?", [f"crs:{table}"])
354
376
  if row is None:
355
377
  return None
356
378
  from pyproj import CRS as _CRS
@@ -413,11 +435,13 @@ def _df_with_wkb(gdf: gpd.GeoDataFrame, geom_cols: Iterable[str]) -> pd.DataFram
413
435
  # object (dict, list, numpy scalar, etc.). Strings and bytes pass
414
436
  # through as-is; they're already DuckDB-compatible. This handles
415
437
  # round-trips through read_gdf which unpickles BLOB columns on read.
438
+ # The decision covers EVERY value, not a sample: a column that is str in
439
+ # some rows and float / dict in others (shard type drift) must be pickled
440
+ # whole, or DuckDB either rejects the frame or silently coerces it.
416
441
  for col in df.columns:
417
442
  if col in geom_set or df[col].dtype != object:
418
443
  continue
419
- sample = _first_non_null(df[col])
420
- if sample is None or isinstance(sample, (str, bytes, bytearray, memoryview)):
444
+ if _object_kind(df[col]) in ("null", "str", "bytes"):
421
445
  continue
422
446
  df[col] = [None if _is_null(v) else _to_pickle_bytes(v) for v in df[col]]
423
447
  return df
@@ -467,20 +491,15 @@ def write_gdf(con: duckdb.DuckDBPyConnection, table: str, gdf: gpd.GeoDataFrame,
467
491
  for col in gdf.columns:
468
492
  if col in geom_set:
469
493
  continue
470
- sample = _first_non_null(gdf[col])
471
- if isinstance(sample, _BaseGeometry):
494
+ if not isinstance(_first_non_null(gdf[col]), _BaseGeometry):
495
+ continue # cheap reject; a geometry column's first value is one
496
+ # Only when EVERY value is a geometry; a mixed column is pickled.
497
+ if _object_kind(gdf[col]) == "geometry":
472
498
  geom_set.add(col)
473
499
  geom_cols = tuple(geom_set)
474
500
  df = _df_with_wkb(gdf, geom_cols)
475
501
  con.register("_tmp_write_gdf", df)
476
502
 
477
- def _table_exists() -> bool:
478
- try:
479
- con.execute(f'DESCRIBE "{table}"')
480
- return True
481
- except Exception:
482
- return False
483
-
484
503
  def _reconcile_schema():
485
504
  """ADD COLUMN for every frame column the table doesn't have yet."""
486
505
  existing = {r[0] for r in con.execute(f'DESCRIBE "{table}"').fetchall()}
@@ -515,7 +534,7 @@ def write_gdf(con: duckdb.DuckDBPyConnection, table: str, gdf: gpd.GeoDataFrame,
515
534
  f"key_cols={key_cols!r}, frame columns missing "
516
535
  f"{[k for k in keys if k not in df.columns]}"
517
536
  )
518
- if not _table_exists():
537
+ if not _table_exists(con, table):
519
538
  con.execute(
520
539
  f'CREATE TABLE "{table}" AS SELECT {select_sql} FROM _tmp_write_gdf'
521
540
  )
@@ -643,11 +662,12 @@ def get_blob_for_building(results_dir: str, cadaster_code: str,
643
662
  select_sql = ", ".join(f'"{c}"' for c in cols)
644
663
  con = open_shard_read(db_path(results_dir))
645
664
  try:
646
- row = con.execute(
665
+ row = fetch_first(
666
+ con,
647
667
  f'SELECT {select_sql} FROM "main"."{table}" '
648
668
  f'WHERE cadaster_code = ? AND building_reference = ? LIMIT 1',
649
669
  [cadaster_code, building_reference],
650
- ).fetchone()
670
+ )
651
671
  finally:
652
672
  con.close()
653
673
  if row is None:
@@ -694,6 +714,29 @@ def read_df_safe_chunks(con: duckdb.DuckDBPyConnection, table: str, *,
694
714
  sql += f" WHERE {where}"
695
715
 
696
716
  result = con.execute(sql, params or [])
717
+ exhausted = False
718
+ try:
719
+ yield from _decoded_chunks(result, cols, types, geom_cols,
720
+ vectors_per_chunk)
721
+ exhausted = True
722
+ finally:
723
+ # Do NOT call result.close(): DuckDB's Python API returns the same
724
+ # connection object from con.execute(), so closing the "result"
725
+ # would close the connection itself. If the consumer stopped early
726
+ # the result is only partially read, which under duckdb 2.0 blocks
727
+ # register()/sql() on this connection — replacing it with a trivial
728
+ # execute() releases it (and is harmless on 1.x).
729
+ if not exhausted:
730
+ try:
731
+ con.execute("SELECT 1").fetchall()
732
+ except Exception:
733
+ pass
734
+ del result
735
+
736
+
737
+ def _decoded_chunks(result, cols, types, geom_cols, vectors_per_chunk):
738
+ """Yield decoded pandas chunks from an open ``execute()`` result until it
739
+ is exhausted (helper for :func:`read_df_safe_chunks`)."""
697
740
  while True:
698
741
  try:
699
742
  chunk = result.fetch_df_chunk(vectors_per_chunk)
@@ -709,20 +752,9 @@ def read_df_safe_chunks(con: duckdb.DuckDBPyConnection, table: str, *,
709
752
  for col in cols:
710
753
  if types[col] != "BLOB" or col in geom_cols:
711
754
  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]]
755
+ if _any_pickled(chunk[col]):
756
+ chunk[col] = [_maybe_unpickle(b) for b in chunk[col]]
719
757
  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
758
 
727
759
 
728
760
  def ingest_shard_table(central_con: duckdb.DuckDBPyConnection, *,
@@ -766,17 +798,18 @@ def ingest_shard_table(central_con: duckdb.DuckDBPyConnection, *,
766
798
 
767
799
  # Fully qualify with "main" so DESCRIBE / ALTER don't get confused by
768
800
  # an identically-named table in the ATTACH'd shard.
769
- try:
801
+ # Catalog lookup rather than a DESCRIBE probe: Phase A runs this inside
802
+ # BEGIN TRANSACTION, and under duckdb 2.0 a failed probe (table missing on
803
+ # the first shard) aborts the transaction even when caught.
804
+ central_exists = _table_exists(central_con, central_table)
805
+ if central_exists:
770
806
  existing_rows = central_con.execute(
771
807
  f'DESCRIBE "main"."{central_table}"'
772
808
  ).fetchall()
773
809
  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:
810
+ else:
777
811
  existing_types = {}
778
- existing = set()
779
- central_exists = False
812
+ existing = set(existing_types.keys())
780
813
 
781
814
  bookkeeping_cols = list(bookkeeping.keys())
782
815
  pickle_wrap_cols: set = set()
@@ -844,6 +877,7 @@ def ingest_shard_table(central_con: duckdb.DuckDBPyConnection, *,
844
877
  existing_types[n] = "BLOB"
845
878
  kept.append((n, "BLOB"))
846
879
  except Exception as _wide_err:
880
+ _raise_if_txn_aborted(central_con, _wide_err)
847
881
  sys.stderr.write(
848
882
  f"[ingest_shard_table] could not widen '{n}' "
849
883
  f"from {ct} to BLOB ({_wide_err}); dropping for "
@@ -863,6 +897,7 @@ def ingest_shard_table(central_con: duckdb.DuckDBPyConnection, *,
863
897
  existing_types[n] = "DOUBLE"
864
898
  kept.append((n, "DOUBLE"))
865
899
  except Exception as _ne:
900
+ _raise_if_txn_aborted(central_con, _ne)
866
901
  sys.stderr.write(
867
902
  f"[ingest_shard_table] type drift on '{n}' "
868
903
  f"(central={ct}, shard={st}); could not widen "
@@ -1015,6 +1050,22 @@ def ingest_shard_table(central_con: duckdb.DuckDBPyConnection, *,
1015
1050
  central_con.unregister("_tmp_ingest_wrap")
1016
1051
 
1017
1052
 
1053
+ def _raise_if_txn_aborted(con: duckdb.DuckDBPyConnection,
1054
+ err: Exception) -> None:
1055
+ """Re-raise ``err`` when it left ``con``'s transaction aborted.
1056
+
1057
+ duckdb 2.0 aborts an explicit transaction on any failed statement, so a
1058
+ caught error can't be recovered from inside it: every later statement
1059
+ fails and COMMIT rolls back. Probing with a no-op tells the two cases
1060
+ apart; under autocommit (and duckdb 1.x) the probe succeeds and the
1061
+ caller's fallback proceeds.
1062
+ """
1063
+ try:
1064
+ con.execute("SELECT 1").fetchall()
1065
+ except Exception:
1066
+ raise err
1067
+
1068
+
1018
1069
  def _is_null(v) -> bool:
1019
1070
  """True for None / pd.NA / NaN floats. Robust against scalars where
1020
1071
  pd.isna would broadcast (e.g. ndarrays in object columns)."""
@@ -1057,17 +1108,14 @@ def _classify_columns(df: pd.DataFrame) -> Tuple[List[str], List[str], List[str]
1057
1108
  if s.dtype != object and dtype_name != "geometry":
1058
1109
  primitive.append(col)
1059
1110
  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"):
1111
+ # Classified over every value, not a sample, so a column mixing str
1112
+ # with other types (shard type drift) is pickled rather than handed to
1113
+ # DuckDB as a column it can't type.
1114
+ kind = _object_kind(s)
1115
+ if kind == "geometry":
1066
1116
  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
1117
+ elif kind in ("null", "str", "bytes"):
1118
+ primitive.append(col) # bytes: already binary, stored as BLOB
1071
1119
  else:
1072
1120
  opaque.append(col)
1073
1121
  return primitive, geometry, opaque
@@ -1196,21 +1244,61 @@ def read_df_safe(con: duckdb.DuckDBPyConnection, table: str, *,
1196
1244
  # look like pickle (start with 0x80) and successfully unpickle, use
1197
1245
  # the rehydrated value; otherwise leave as raw bytes. Per-row
1198
1246
  # 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.
1247
+ # shards (text widened by type drift + pickles), and row order is
1248
+ # arbitrary (preserve_insertion_order=false) — so the decision must
1249
+ # not depend on whichever value happens to come first.
1201
1250
  for col in cols:
1202
1251
  if types[col] != "BLOB" or col in geom_cols:
1203
1252
  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]]
1253
+ if _any_pickled(df[col]):
1254
+ df[col] = [_maybe_unpickle(b) for b in df[col]]
1211
1255
  return df
1212
1256
 
1213
1257
 
1258
+ def _is_pickle_bytes(v) -> bool:
1259
+ """True for a bytes-like value carrying our pickle prefix (0x80)."""
1260
+ if not isinstance(v, (bytes, bytearray, memoryview)):
1261
+ return False
1262
+ return len(v) >= 2 and bytes(v[:1]) == b"\x80"
1263
+
1264
+
1265
+ def _any_pickled(series) -> bool:
1266
+ """True when any value of ``series`` looks like our pickled BLOB."""
1267
+ return any(_is_pickle_bytes(v) for v in series)
1268
+
1269
+
1270
+ def _object_kind(series: pd.Series) -> str:
1271
+ """Classify an object column over ALL its non-null values.
1272
+
1273
+ Returns ``'null'`` (no values), ``'str'`` / ``'bytes'`` (every value of
1274
+ that type), ``'geometry'`` (every value a shapely geometry) or ``'mixed'``
1275
+ (anything else, including a mix of the above). pandas' C-level
1276
+ ``infer_dtype`` short-circuits the common homogeneous cases.
1277
+ """
1278
+ inferred = pd.api.types.infer_dtype(series, skipna=True)
1279
+ if inferred == "empty":
1280
+ return "null"
1281
+ if inferred == "string":
1282
+ return "str"
1283
+ if inferred == "bytes":
1284
+ return "bytes"
1285
+ kinds = set()
1286
+ for v in series:
1287
+ if _is_null(v):
1288
+ continue
1289
+ if isinstance(v, str):
1290
+ kinds.add("str")
1291
+ elif isinstance(v, (bytes, bytearray, memoryview)):
1292
+ kinds.add("bytes")
1293
+ elif hasattr(v, "__geo_interface__") and hasattr(v, "wkb"):
1294
+ kinds.add("geometry")
1295
+ else:
1296
+ return "mixed"
1297
+ if len(kinds) > 1:
1298
+ return "mixed"
1299
+ return kinds.pop() if kinds else "null"
1300
+
1301
+
1214
1302
  def _maybe_unpickle(b):
1215
1303
  """Try to unpickle bytes; on any failure (or non-pickle), return raw."""
1216
1304
  if b is None or b is pd.NA:
@@ -1367,20 +1455,26 @@ def read_gdf(con: duckdb.DuckDBPyConnection, table: str, *,
1367
1455
  if col in geom_typed:
1368
1456
  df[col] = [_wkb_or_none(v) for v in df[col]]
1369
1457
  continue
1370
- sample = _first_non_null(df[col])
1371
- if sample is None or not isinstance(sample, (bytes, bytearray, memoryview)):
1458
+ blobs = [v for v in df[col] if isinstance(v, (bytes, bytearray, memoryview))]
1459
+ if not blobs:
1372
1460
  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]]
1461
+ # Decide per value, never from the first row (row order is arbitrary):
1462
+ # a column widened to BLOB by shard type drift holds text-encoded
1463
+ # values from early shards AND pickles from later ones. Pickles are
1464
+ # always rehydrated; the remaining bytes are decoded to str only when
1465
+ # all of them are valid UTF-8 text (e.g. a widened date string), else
1466
+ # they stay raw so genuinely binary data is never half-decoded.
1467
+ raw = [bytes(v) for v in blobs if not _is_pickle_bytes(v)]
1468
+ try:
1469
+ for b in raw:
1470
+ b.decode('utf-8')
1471
+ decode_text = bool(raw)
1472
+ except UnicodeDecodeError:
1473
+ decode_text = False
1474
+ df[col] = [_maybe_unpickle(v) if _is_pickle_bytes(v)
1475
+ else _text_or_bytes(v) if decode_text
1476
+ else v
1477
+ for v in df[col]]
1384
1478
  return gpd.GeoDataFrame(df, geometry=geom_col, crs=get_table_crs(con, table))
1385
1479
 
1386
1480
 
@@ -1422,17 +1516,17 @@ class ResultsHandle:
1422
1516
  def sbr_relation(self) -> duckdb.DuckDBPyRelation:
1423
1517
  """Return a lazy DuckDB relation for sbr_results filtered by code."""
1424
1518
  con = self._con()
1425
- return con.execute(
1519
+ return con.sql(
1426
1520
  'SELECT * FROM "main"."sbr_results" WHERE cadaster_code = ?',
1427
- [self.cadaster_code],
1521
+ params=[self.cadaster_code],
1428
1522
  )
1429
1523
 
1430
1524
  def br_relation(self) -> duckdb.DuckDBPyRelation:
1431
1525
  """Return a lazy DuckDB relation for br_results filtered by code."""
1432
1526
  con = self._con()
1433
- return con.execute(
1527
+ return con.sql(
1434
1528
  'SELECT * FROM "main"."br_results" WHERE cadaster_code = ?',
1435
- [self.cadaster_code],
1529
+ params=[self.cadaster_code],
1436
1530
  )
1437
1531
 
1438
1532
  # -- batched iteration --------------------------------------------------
@@ -1504,10 +1598,11 @@ class ResultsHandle:
1504
1598
  con = self._con()
1505
1599
  own_con = con is not self._parent_con
1506
1600
  try:
1507
- row = con.execute(
1601
+ row = fetch_first(
1602
+ con,
1508
1603
  'SELECT count(*) FROM "main"."sbr_results" WHERE cadaster_code = ?',
1509
1604
  [self.cadaster_code],
1510
- ).fetchone()
1605
+ )
1511
1606
  return row[0] if row else 0
1512
1607
  finally:
1513
1608
  if own_con:
@@ -1518,10 +1613,11 @@ class ResultsHandle:
1518
1613
  con = self._con()
1519
1614
  own_con = con is not self._parent_con
1520
1615
  try:
1521
- row = con.execute(
1616
+ row = fetch_first(
1617
+ con,
1522
1618
  'SELECT count(*) FROM "main"."br_results" WHERE cadaster_code = ?',
1523
1619
  [self.cadaster_code],
1524
- ).fetchone()
1620
+ )
1525
1621
  return row[0] if row else 0
1526
1622
  finally:
1527
1623
  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