classifyre-cli 0.9.7__py3-none-any.whl → 0.9.9__py3-none-any.whl

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: classifyre-cli
3
- Version: 0.9.7
3
+ Version: 0.9.9
4
4
  Summary: Classifyre CLI — scan data sources for personal data and secrets
5
5
  License: MIT
6
6
  Keywords: data,governance,masking,pii,secrets
@@ -14,7 +14,7 @@ src/detectors/config.py,sha256=CCrzp8Js8tQ1E34_Pl9ChY8JFjvUalXbnJJ-QWk54d4,1683
14
14
  src/detectors/dependencies.py,sha256=C5FBnkBMWCnx34WkOrM7yTO8zcOV_zP0RbyvMtw8A20,3851
15
15
  src/detectors/engine_version.py,sha256=v5v80y1hV49RiFbc38xDfOYhOC4wxuUfI0gcJvf3GOk,4124
16
16
  src/detectors/errors.py,sha256=bpmaSD21kb48Sy4OoWmPuYR4Miq3PFKNvZ1_d5_ApVc,812
17
- src/detectors/tabular_lines.py,sha256=ahsPh2OL2uqB7FBHvPDv51Msci5x2pM-uH9rya8nFsM,2065
17
+ src/detectors/tabular_lines.py,sha256=2LjyMbFx8XOw0reHactOvjVT8KEU-fLImf27vP1NbY4,2186
18
18
  src/detectors/broken_links/__init__.py,sha256=maN50pAfC9IJGNUUIHGVM4YnjTAozRI43APLUCQrJcE,77
19
19
  src/detectors/broken_links/detector.py,sha256=k1ocQAI-cOuf6HSuipvKfdKyvpjOq5vAvIR1PmSjT3Y,9332
20
20
  src/detectors/content/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -84,23 +84,23 @@ src/pipeline/__init__.py,sha256=BCWl3hwwLkmZc2vQ2fEyUdhis4TPK930HEgXTog8NjA,742
84
84
  src/pipeline/asset_payload_server.py,sha256=6LPEcybDk6gKYw6cSVXRKAHmZhkczwkjt3YgE6kN644,9773
85
85
  src/pipeline/content_provider.py,sha256=XiSOED7Lw0S663ybZo4iveQRceg5f51tdU9tyv2erSg,1078
86
86
  src/pipeline/detector_breaker.py,sha256=-G8rN3RSTpm2gP6HYHORVpMh0D_36kNO9YiOsbUB3VU,8781
87
- src/pipeline/detector_pipeline.py,sha256=NbLKhVhj3MYX7TGnzE_2igjLHDFQGnaMHDUgA1NNGx4,69438
87
+ src/pipeline/detector_pipeline.py,sha256=q7DwM2JipJOWuSl2VuvjCjtKGxABrxkXleLTDjTXOm4,69740
88
88
  src/pipeline/finding_context.py,sha256=lK_my9WUZTiMF26HRMq69z74mz8im6VNYLJ_XWuLBuk,3878
89
89
  src/pipeline/media_artifact.py,sha256=f11MFz5fdJGMSm3cL71KikvQsjXoyse0PzzheCaWifg,10597
90
90
  src/pipeline/parsed_content_provider.py,sha256=rHTvvBvjTQtCJF3HT8GC1oSZV3eQ2PbgZ2tCtLIPVOE,4382
91
91
  src/pipeline/payload_window.py,sha256=YIXAfvjPAtr_lQBfy8ZXUe445miOU3Dbop0OmRzOjTQ,25515
92
- src/pipeline/scan_cache.py,sha256=cje5Fcbf2vJDOd3DOoTT__gn28fxQp_HojZESnhr2_s,30219
92
+ src/pipeline/scan_cache.py,sha256=px8JZTDcwPUP1Gn59YpWpApZDZkOxo7u-Ar_P_3yp6g,30665
93
93
  src/pipeline/text_artifact.py,sha256=7gpu1r6Ipc0nAt4S8bdzcy8KV9JKaTRgHPgrMw7J1I8,2433
94
94
  src/pipeline/worker_pool.py,sha256=Yjr_2LXxV2nYNcXNN4gFRPK9KN15GP_IkkAzaplKaTc,10543
95
95
  src/query/__init__.py,sha256=RhfyfKL7loabux082s5CMWFlBTq3rDl3q23LwpurAO0,989
96
- src/query/bindings.py,sha256=KMqATSAJHGD9y3HrWhbE1w8ixJgGV5dDsqHq2FgkL-A,6258
96
+ src/query/bindings.py,sha256=l5z-B5upWnuGrtR077lk_j6GcHHCk4UD3iZDV59P0A8,6287
97
97
  src/query/describe.py,sha256=oJBA2WruLYWXROHHlg2Y_P9T6KtWyATUiYbx2T8KoSw,3245
98
98
  src/query/gate.py,sha256=cNvdANq3cvcc9AGE-wk2Ad_1HpsZKphUNBscCTga-eM,13040
99
99
  src/query/masks.py,sha256=E-B1kt_99BIcaKpTEYGXYLGKnr3R5b-piLqaZci84Aw,10982
100
100
  src/query/predicate.py,sha256=VH4U3UyfAL5aWKdcrSSgADy5T3s7WVWJowmNywo6EaE,1644
101
101
  src/query/rows.py,sha256=JcUgThkVIKJsQIlhemT_xQ0aiQNItCQ-x8NsLx0KLhc,4588
102
102
  src/query/runner.py,sha256=EBwcaMHwSgBgdGNr9k_DMhEB2yc0qcDWGUm8C0AzPjw,7888
103
- src/query/session.py,sha256=Galv55hZwUrhJbIQe7WuyU5d2NoM5UYhip3HEdgYVsc,43432
103
+ src/query/session.py,sha256=7wQPHWfz9wxJ3HByrFxBIXHlolC2DxNTmgLbB6Xkipg,44540
104
104
  src/query/warm.py,sha256=E1QQKm2FqJ5M8hOPeLBYn24bjetFeE8GPYaf8PoR1T8,7719
105
105
  src/query/worker.py,sha256=nxW6sqkVFOiCtJh5Tbek8esoY07pxnWrhCwvC8D9e88,52962
106
106
  src/query/connectors/__init__.py,sha256=e8rZ-xjwo4qewUMzdwAl5yifTY0sPpUGFaWyYeB48R4,4669
@@ -112,20 +112,20 @@ src/query/connectors/databricks.py,sha256=Cvlke_yM72iUO6RB8H-i6duRxiOiTpwbQJsFIJ
112
112
  src/query/connectors/meilisearch.py,sha256=_mpeFJ_Nn1eIaz6BHm6viOY1ioQahYNxNkV5eKIrPow,8909
113
113
  src/query/connectors/mysql.py,sha256=7QyYY35yt_-oRsaWrhLz-7O7zCiSrZqyw-EW2veu1cw,5598
114
114
  src/query/connectors/neo4j.py,sha256=leGRZ-uH4Ba2G3yp2mYx8Jouao7nmu5E3B9jUjO8MXk,8533
115
- src/query/connectors/object_storage.py,sha256=hN_-_q5XAQwnWgR2Ogdysj_PDghuqi1dcpTB1Wtf5kU,5354
115
+ src/query/connectors/object_storage.py,sha256=UsljQgZw1ddmO5tyYEWRB96S5ZXz4uvWESXhqjlxEj0,3587
116
116
  src/query/connectors/odbc.py,sha256=23URmiz3pDTDrGO08zC7BAQa6ugztAE_JM7dK8iPLnQ,2936
117
117
  src/query/connectors/postgres.py,sha256=pOvVxToZCTs2oE3KW1f0lvjo2Br0_NTl9Nj3VX7TYkQ,2916
118
118
  src/sources/__init__.py,sha256=wYksO_0IcvlGXLouWapKyqzL0jG0El4rDDGRfwa4Zqk,3350
119
119
  src/sources/asset_metadata.py,sha256=OnHwnUSlT1Ow_6Rz2SnJvZyJvaz00TsuQgAnXjTXsdA,6143
120
120
  src/sources/atlassian_common.py,sha256=oi8Eoq9pEaLBXXgnrSzohwXDxlWyZmMtMgNHfB3kMkA,11605
121
- src/sources/base.py,sha256=7atzku_IEqXhuDZS98cuqBQsOzb1B76ZwPPcIdFAPmM,42114
121
+ src/sources/base.py,sha256=57L_VU1L2AwXj1n5iNzsT2oGea0ANwRIFl1GgJMP2Lo,42418
122
122
  src/sources/dependencies.py,sha256=ei5P3S1CxnNN-zKlChKwzyWEeAApYggPM_YoqrSNWaU,2699
123
123
  src/sources/duckdb_attached_base.py,sha256=tNXDebuFWkdomsmx4LELV9FNqegyJrrSPyQUs87fiDc,9050
124
124
  src/sources/inline_paging.py,sha256=bv-SIDLrRFdROa6yEf6bq2545kopbsUXUFuhJGd_wJc,2942
125
125
  src/sources/recipe_normalizer.py,sha256=tgZj_jYnT-67rlDiEF9AsQUS7EcxCvDUUsk2LO8RrRE,6207
126
126
  src/sources/s3_client.py,sha256=_v-JlCihlltbbI6dA-OeW4rAvglCKVmj4r8Ib1ViU_A,2368
127
127
  src/sources/search_engine_base.py,sha256=meQbpV2Si2T8tBe2DS7VvvpZZ7KVCn6cNqCYCwdwLUE,18308
128
- src/sources/tabular_base.py,sha256=TlzQ-kXPg9aOqYEefgnREHkZ3pGaniu3Oz-yeFoZPE8,62238
128
+ src/sources/tabular_base.py,sha256=mO0HCWT6sKhRarqLklZpEJUNXrCulT-IixxbV7cc66A,62440
129
129
  src/sources/tabular_utils.py,sha256=zHgdQlw10CmIRAUc98VR3TahIf2N51XUWCf_uezRMeE,8539
130
130
  src/sources/athena/__init__.py,sha256=zOxrzPsc1cz7m2JZPh1kCpkipIFgSGSGrFbrtrADgdM,61
131
131
  src/sources/athena/source.py,sha256=f1BqZVxFvqXDZ_hBRfo9SAh7edjfvmg_C4IBBlT8_CI,10986
@@ -187,7 +187,7 @@ src/sources/neo4j/source.py,sha256=NcGbW_aj2A3rjAW_InOD6QwqFctP1StWYw9qKi7ChGA,2
187
187
  src/sources/notion/__init__.py,sha256=FIOPK4itaRGa449jBpvRQd_qlJPPRsjIhSoUBUnMem0,61
188
188
  src/sources/notion/client.py,sha256=Wu-JSXI9KnDgfRUzzP8Vm-_TbhY2FDHdEID_Z-EcMd8,8262
189
189
  src/sources/notion/source.py,sha256=vaqWGVDtdlBAbuhI2vBf3zRQIG56-9C7_yBuflM1DS8,38218
190
- src/sources/object_storage/base.py,sha256=Y_WA8ZsUqwXO7hhcF0Po2zsyWSuk0kJ5KC9w6LzqRH8,71612
190
+ src/sources/object_storage/base.py,sha256=LSdRcYne00FonoBnrXJtBWafnW_WudSSFU-pYoWl3g0,76219
191
191
  src/sources/odbc/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
192
192
  src/sources/odbc/source.py,sha256=7S1yADOS__u7JzinD78NurZH66UdMtdTkmApX7nutrk,30207
193
193
  src/sources/opensearch/__init__.py,sha256=Z6wjAWy_pQlCCkWzJyh3DdR091Evqkmks2wTqVo1eCc,69
@@ -195,7 +195,7 @@ src/sources/opensearch/source.py,sha256=i9NQE7XP5zYXeWdW6od3gKTQGD76H_z3VApN0qNj
195
195
  src/sources/oracle/__init__.py,sha256=saYMyNR-UGniyVgLYS8u1PwPO5WQ_mEuq8WqYrl30rU,61
196
196
  src/sources/oracle/source.py,sha256=-C_PteXxiq8CHuWcJua6zHDgiQUnoPoDcUUROm_JQD8,29126
197
197
  src/sources/postgresql/__init__.py,sha256=lHNYhsvG9fdnrr4b2Ya1mSdDdDRImmWOUEpQSXSu9dE,69
198
- src/sources/postgresql/source.py,sha256=ukti25TWXsPRxeIAZeDSjk4zyLxPtu62v7fWeU5rSwo,16278
198
+ src/sources/postgresql/source.py,sha256=Wg3ZaOwT1QT5XJV-uxdOwjjGXsiw4IjVF15obfEa94M,16865
199
199
  src/sources/powerbi/__init__.py,sha256=oDQQoV94r8xHqNjlCeFOULA-8Wyzr6tNCGznFEHEHF0,63
200
200
  src/sources/powerbi/source.py,sha256=2KdGzOXe2Htatflza7wNoBYR0BucH0WB0J_uycgdMWY,35169
201
201
  src/sources/reddit/__init__.py,sha256=ilcyMJOgzMkX7GYWDioTyBqvPkMr5iBguYTb6bzUquY,61
@@ -230,7 +230,7 @@ src/utils/duckdb_engine.py,sha256=RunGvCvfiKJA45YP7aW9XRBvGCHuZxrTXh3U8a9e05Q,11
230
230
  src/utils/embedded_files.py,sha256=zXAJr_OAsZD4iI6MUuAuD1x7awvh7n91Ez4pUSmhxnY,25296
231
231
  src/utils/external_video.py,sha256=xnp071RpBFX0xhsnUXxRlY3IKg7DsE4sH0w6B4c_e_k,11695
232
232
  src/utils/file_metadata.py,sha256=hC4Xl_w__McWi2QKKWAcEEQcdWo1LLOHrgTUMp-fyOE,10533
233
- src/utils/file_parser.py,sha256=oiWZ8SEqz1HvnUl0qoQnfE8qW6CVIN9aSsftN2hErY8,102732
233
+ src/utils/file_parser.py,sha256=6SD8rwy8mFU4c6H_Tb0pbQpH41a2zgxIB_qkN0SdzuI,102792
234
234
  src/utils/file_to_images.py,sha256=rU9uATckg8JDxHZLobjOJdwkrC2CZxegMS4hv76txTI,4782
235
235
  src/utils/hashing.py,sha256=T0GL1FWtG32QJID5RN3X-TzHHkolnNK6EfADvX6sdlE,2490
236
236
  src/utils/lakehouse_layout.py,sha256=EilfOlOfrTAF2fn0S6v2_EM_eoYEtqt5Ja-1E7QSM24,4706
@@ -246,15 +246,16 @@ src/utils/resources.py,sha256=2ejFjz9r_Kv_d-sUGD0oj54U-ZIUSxDAu7aD4YEv4FQ,2630
246
246
  src/utils/sampling_cursor.py,sha256=J1k91Js9ks3mp3JMOb0Jcy5XOkWQlvLDBlxzCXzrNfg,1864
247
247
  src/utils/sampling_frontier.py,sha256=4e8Ugy5NiPaEr2YGpQ5-i_Dy3m8J_aOSl81HlFTX_PU,25232
248
248
  src/utils/source_files.py,sha256=OKZSW64cur0HTuWPRkV1sJg_Z2LFGWzUsC853gGlFBY,5033
249
+ src/utils/sql_files.py,sha256=Vd-77U6rpI80GJh9uPHyPsM9qTCGytpvv76VegKA39M,5501
249
250
  src/utils/sql_lineage.py,sha256=dMz8l32VyohIZuwMkMj2WEqYsEiFHCqQiOa2RFrIq6A,22082
250
- src/utils/table_files.py,sha256=NbjlLKJr-y_ANFeQbF0OfFgP1oTCdlu6tIp30gDzZJA,31907
251
+ src/utils/table_files.py,sha256=S9SX5Ig5PAh-PpNqbROTBeAEfTzc_2jgc4fy7j0zp88,32838
251
252
  src/utils/torch_runtime.py,sha256=79NYfvJ7fjHGgeLXX8rK63qJFuO2Gao1jjRAQ4nicrk,2527
252
253
  src/utils/transcription.py,sha256=WOitCBNTZ7rrGq41ZGH99XmAIyqxvqmnJHxbK3RP7Rs,16943
253
254
  src/utils/urn.py,sha256=gqSl0H0FBZZ3cJbpDWX1ewGcyZz2MrNVTIQdoFrQMM0,12622
254
255
  src/utils/uv_sync.py,sha256=L4ETHuidlgFLbz4e3Vv0Ornh7w8xrkYeFQQGw0hJe8E,10214
255
256
  src/utils/validation.py,sha256=5NHsgyZwyEONRu9_ADxUAQNPvbMnpMhKL-hpgFEVMm8,3837
256
257
  src/utils/video_processing.py,sha256=B6Br9ybFEa_ioglJGo0P9Fmp1e2B95C24joAktwrjww,11293
257
- classifyre_cli-0.9.7.dist-info/METADATA,sha256=LzjAnfU_ZQkFH2dXqaV25j_L1oxmNNIglfu20DJO17A,5841
258
- classifyre_cli-0.9.7.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
259
- classifyre_cli-0.9.7.dist-info/entry_points.txt,sha256=edxllyMiIFfajgCZ3dTRACXYGC34ZX1AYTezMSR5E_8,45
260
- classifyre_cli-0.9.7.dist-info/RECORD,,
258
+ classifyre_cli-0.9.9.dist-info/METADATA,sha256=pQR3ZP6IfMO27cywYN7fZM0jWkQPMV6lI3ur4QMWDPg,5841
259
+ classifyre_cli-0.9.9.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
260
+ classifyre_cli-0.9.9.dist-info/entry_points.txt,sha256=edxllyMiIFfajgCZ3dTRACXYGC34ZX1AYTezMSR5E_8,45
261
+ classifyre_cli-0.9.9.dist-info/RECORD,,
@@ -20,8 +20,10 @@ from dataclasses import dataclass
20
20
 
21
21
  _ROW_RE = re.compile(r"^row_(\d+):$")
22
22
  # Two spaces then a name that does not start with a space: a deeper line
23
- # (`` password: x``) is a continuation of the cell above, not a column.
24
- _CELL_RE = re.compile(r"^ ([^\s:][^:]*):(?: ?(.*))?$")
23
+ # (`` password: x``) is a continuation of the cell above, not a column. The
24
+ # name ends at the first colon followed by a space or nothing, so a column
25
+ # called ``aws:token`` keeps its whole name.
26
+ _CELL_RE = re.compile(r"^ ([^\s:].*?):(?: (.*))?$")
25
27
  _CONTINUATION_RE = re.compile(r"^ ")
26
28
 
27
29
 
@@ -301,6 +301,12 @@ class DetectorPipeline:
301
301
  text_content_type = None
302
302
  link_content = self._build_links_payload(asset.links)
303
303
 
304
+ # What only the content tells (a table file's columns) is added to the
305
+ # asset before it is read, whether or not any detector covers it.
306
+ prepare = getattr(self.source, "prepare_asset", None)
307
+ if prepare is not None and not records_only:
308
+ await prepare(asset)
309
+
304
310
  active_detectors = self.detectors
305
311
  if only is not None:
306
312
  active_detectors = [
@@ -44,6 +44,7 @@ from ..detectors.engine_version import (
44
44
  pipeline_engine_version,
45
45
  )
46
46
  from ..utils.hashing import calculate_checksum
47
+ from ..utils.sql_files import scan_reader_state
47
48
 
48
49
  logger = logging.getLogger(__name__)
49
50
 
@@ -388,12 +389,16 @@ class ScanCache:
388
389
  self._embedding_plan = plan
389
390
 
390
391
  def media_state_for(self, asset: Any) -> dict[str, str]:
391
- """What to record once this asset's media has been sent, if it has any."""
392
+ """What to record beside the detectors once this asset has been read.
393
+
394
+ How its content was read, and its media once sent, if it has any.
395
+ """
392
396
  plan = self._embedding_plan
393
397
  entry = (
394
398
  plan.cache_entry_for(getattr(asset, "asset_type", None)) if plan is not None else None
395
399
  )
396
- return {entry[0]: entry[1]} if entry else {}
400
+ media = {entry[0]: entry[1]} if entry else {}
401
+ return {**scan_reader_state(getattr(asset, "metadata", None)), **media}
397
402
 
398
403
  @staticmethod
399
404
  def _force_full_rescan() -> bool:
@@ -524,6 +529,10 @@ class ScanCache:
524
529
  return ScanPlan.full("content hash changed")
525
530
  content_hash = digest
526
531
 
532
+ reader_state = scan_reader_state(getattr(asset, "metadata", None))
533
+ if any(prior.detectors.get(key) != value for key, value in reader_state.items()):
534
+ return ScanPlan.full("the file is now read differently")
535
+
527
536
  stale = {
528
537
  key
529
538
  for key, fingerprint in self._cacheable.items()
src/query/bindings.py CHANGED
@@ -23,9 +23,10 @@ from __future__ import annotations
23
23
  import math
24
24
  from typing import Any
25
25
 
26
+ from ..utils.sql_files import FILE_FORMATS, SPATIAL_FORMATS
26
27
  from .connectors import BindingError, QueryBinding, TableLocation, binding_class, declared_sources
27
28
  from .connectors.arrow import ConnectorError, ScanStats
28
- from .connectors.object_storage import FILE_FORMATS, LAKEHOUSE_FORMATS, SPATIAL_FORMATS
29
+ from .connectors.object_storage import LAKEHOUSE_FORMATS
29
30
 
30
31
  __all__ = [
31
32
  "ATTACHED_CATALOG_TYPES",
@@ -11,17 +11,12 @@ from __future__ import annotations
11
11
  from typing import Any
12
12
 
13
13
  from ...utils.duckdb_engine import quote_identifier, sql_literal
14
+ from ...utils.sql_files import FILE_FORMATS, file_relation
14
15
  from .base import BindingError, QueryBinding, SourceContext, TableLocation
15
16
 
16
17
  #: Formats DuckDB reads natively, by the ``format`` of a location.
17
18
  #: Keep in sync with ``LAKEHOUSE_FORMATS`` in apps/api/src/data-query/sql-names.ts.
18
19
  LAKEHOUSE_FORMATS = frozenset({"delta", "iceberg"})
19
- #: Geospatial files, read with the ``spatial`` extension (``ST_Read``); geometries
20
- #: come out as WKT text, so no spatial function has to be allowed in SQL.
21
- SPATIAL_FORMATS = frozenset({"geojson", "fgb", "dbf"})
22
- #: Keep in sync with ``FILE_FORMATS`` in apps/api/src/data-query/sql-names.ts
23
- #: (``json`` here is read via ``read_json_auto``).
24
- FILE_FORMATS = frozenset({"parquet", "csv", "tsv", "jsonl", "json", "avro", *SPATIAL_FORMATS})
25
20
 
26
21
 
27
22
  class ObjectStorageBinding(QueryBinding):
@@ -69,22 +64,9 @@ class ObjectStorageBinding(QueryBinding):
69
64
  self._iceberg_version_guessing = True
70
65
  return f"iceberg_scan({uri}, allow_moved_paths = true)"
71
66
  if location.kind == "file":
72
- if fmt == "parquet":
73
- return f"read_parquet({uri})"
74
- if fmt == "csv":
75
- return f"read_csv({uri}, auto_detect = true)"
76
- if fmt == "tsv":
77
- return f"read_csv({uri}, auto_detect = true, delim = '\\t')"
78
- if fmt == "jsonl":
79
- return f"read_json({uri}, format = 'newline_delimited')"
80
- if fmt == "json":
81
- return f"read_json_auto({uri})"
82
- if fmt == "avro":
83
- self.load(conn, "avro")
84
- return f"read_avro({uri})"
85
- if fmt in SPATIAL_FORMATS:
86
- return self._spatial(conn, uri)
87
- raise BindingError(f"{fmt or 'These'} files cannot be queried with SQL yet.")
67
+ if fmt not in FILE_FORMATS:
68
+ raise BindingError(f"{fmt or 'These'} files cannot be queried with SQL yet.")
69
+ return file_relation(conn, fmt, uri)
88
70
  raise BindingError(f"Unknown table location kind '{location.kind}'.")
89
71
 
90
72
  def local_paths(self) -> list[str]:
@@ -93,23 +75,3 @@ class ObjectStorageBinding(QueryBinding):
93
75
  return []
94
76
  root = str(self._storage.uri(""))
95
77
  return [] if "://" in root else [root]
96
-
97
- def _spatial(self, conn: Any, uri: str) -> str:
98
- """``ST_Read`` with every geometry column turned into WKT text.
99
-
100
- The raw column is a binary geometry only spatial functions can read;
101
- as text it shows in a result and compares like any string.
102
- """
103
- self.load(conn, "spatial")
104
- source = f"ST_Read({uri})"
105
- columns = conn.execute(f"DESCRIBE SELECT * FROM {source}").fetchall()
106
- geometries = [
107
- name for name, kind, *_ in columns if str(kind).upper().startswith("GEOMETRY")
108
- ]
109
- if not geometries:
110
- return source
111
- replaced = ", ".join(
112
- f"ST_AsText({quote_identifier(name)}) AS {quote_identifier(name)}"
113
- for name in geometries
114
- )
115
- return f"(SELECT * REPLACE ({replaced}) FROM {source})"
src/query/session.py CHANGED
@@ -995,9 +995,10 @@ def _js_safe(table: Any) -> Any:
995
995
  or pa.types.is_decimal256(kind)
996
996
  )
997
997
  if unsafe:
998
+ text = _interval_text if pa.types.is_interval(kind) else str
998
999
  columns.append(
999
1000
  pa.array(
1000
- [None if v is None else str(v) for v in column.to_pylist()],
1001
+ [None if v is None else text(v) for v in column.to_pylist()],
1001
1002
  type=pa.string(),
1002
1003
  )
1003
1004
  )
@@ -1007,6 +1008,29 @@ def _js_safe(table: Any) -> Any:
1007
1008
  return pa.table(columns, names=_unique(names))
1008
1009
 
1009
1010
 
1011
+ def _interval_text(value: Any) -> str:
1012
+ """An interval as PostgreSQL writes it: ``1 year 2 mons 3 days 04:05:06.5``.
1013
+
1014
+ Arrow's value is (months, days, nanoseconds), whose ``str`` is the name of a
1015
+ Python tuple. The SQL gateway reads this form back for the binary protocol.
1016
+ """
1017
+ months, days, nanoseconds = value
1018
+ parts = []
1019
+ sign = -1 if months < 0 else 1
1020
+ years, months = (sign * part for part in divmod(abs(months), 12))
1021
+ for amount, unit in ((years, "year"), (months, "mon"), (days, "day")):
1022
+ if amount:
1023
+ parts.append(f"{amount} {unit}{'' if amount == 1 else 's'}")
1024
+ if nanoseconds or not parts:
1025
+ minus = "-" if nanoseconds < 0 else ""
1026
+ seconds, micros = divmod(abs(nanoseconds) // 1000, 1_000_000)
1027
+ minutes, seconds = divmod(seconds, 60)
1028
+ hours, minutes = divmod(minutes, 60)
1029
+ fraction = f".{micros:06d}".rstrip("0") if micros else ""
1030
+ parts.append(f"{minus}{hours:02d}:{minutes:02d}:{seconds:02d}{fraction}")
1031
+ return " ".join(parts)
1032
+
1033
+
1010
1034
  def _unique(names: list[str]) -> list[str]:
1011
1035
  seen: dict[str, int] = {}
1012
1036
  out = []
src/sources/base.py CHANGED
@@ -528,6 +528,14 @@ class BaseSource(ABC):
528
528
  """Return the safe default verification mode for this source instance."""
529
529
  return self.SCAN_CACHE_VERIFY
530
530
 
531
+ async def prepare_asset(self, asset: Any) -> None:
532
+ """Called once per asset before its content is read for detection.
533
+
534
+ For what only the content tells and the asset's metadata should carry,
535
+ like a table file's columns. Override in subclasses.
536
+ """
537
+ return None
538
+
531
539
  def evict_asset_cache(self, asset_hash: str) -> None:
532
540
  """Free cached content for a processed asset. Override in subclasses."""
533
541
  pass
@@ -2,6 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  import asyncio
4
4
  import hashlib
5
+ import io
5
6
  import itertools
6
7
  import logging
7
8
  import random
@@ -36,7 +37,7 @@ from ...utils.embedded_files import (
36
37
  has_embedded_files,
37
38
  iter_embedded_files,
38
39
  )
39
- from ...utils.file_metadata import extract_file_metadata
40
+ from ...utils.file_metadata import build_columns, extract_file_metadata
40
41
  from ...utils.file_parser import (
41
42
  ARROW_FILE_MIME_TYPE,
42
43
  TABULAR_FILE_EXTENSIONS,
@@ -52,7 +53,8 @@ from ...utils.lakehouse_layout import table_root_of, table_roots
52
53
  from ...utils.lakehouse_tables import LakehouseTable, TableStorage, describe_table
53
54
  from ...utils.payload import spool
54
55
  from ...utils.sampling_frontier import time_rank
55
- from ...utils.table_files import LAKEHOUSE_TABLE_MIME_TYPE
56
+ from ...utils.sql_files import LINE_FORMATS, describe_file, sql_file_format, suffix_for
57
+ from ...utils.table_files import JSON_TABLE_MIME_TYPE, LAKEHOUSE_TABLE_MIME_TYPE
56
58
  from ...utils.urn import Urn, UrnError
57
59
  from ..base import BaseSource
58
60
  from ..dependencies import require_module
@@ -229,6 +231,8 @@ class ObjectStorageSourceBase(BaseSource, ABC):
229
231
  self._content_cache: dict[str, tuple[str, str]] = {}
230
232
  self._hash_to_uri: dict[str, str] = {}
231
233
  self._object_ref_by_hash: dict[str, ObjectRef] = {}
234
+ # Objects opened by prepare_asset, for the page reader to take over.
235
+ self._prepared: dict[str, tuple[Any, str]] = {}
232
236
  # Object key per asset hash for the whole run. Unlike the ref map it is
233
237
  # never evicted: the AUTOMATIC sweeping list is written at the end of
234
238
  # the run, after every asset's cache has been released.
@@ -831,6 +835,94 @@ class ObjectStorageSourceBase(BaseSource, ABC):
831
835
  raw_bytes=None if is_non_extractable else file_bytes,
832
836
  )
833
837
 
838
+ #: How much of a file is read to learn its columns: for a line-based file the
839
+ #: rows DuckDB samples to type them; others (a JSON array, a geo file) only
840
+ #: parse whole, up to the larger limit.
841
+ SCHEMA_HEAD_BYTES = 4 * 1024 * 1024
842
+ SCHEMA_MAX_FILE_BYTES = 64 * 1024 * 1024
843
+
844
+ async def prepare_asset(self, asset: SingleAssetScanResults) -> None:
845
+ """Record the columns a SQL query of this file returns, before it is read.
846
+
847
+ Without them the catalog, a SQL connection and column masks know the
848
+ file as a table with no columns. The object opened here is the one the
849
+ pages are then read from, so a scan still downloads it once.
850
+ """
851
+ asset_hash = str(asset.hash)
852
+ ref = self._object_ref_by_hash.get(asset_hash)
853
+ metadata = asset.metadata
854
+ if ref is None or ref.table is not None or not isinstance(metadata, dict):
855
+ return
856
+ mime = metadata.get("mime_type")
857
+ fmt = sql_file_format(mime if isinstance(mime, str) else None, ref.key)
858
+ if fmt is None or not self._include_content_preview():
859
+ return
860
+ # Parquet and Avro are read for their metadata during discovery.
861
+ if fmt in ("parquet", "avro") and metadata.get("columns"):
862
+ return
863
+ try:
864
+ held = self._bytes_cache.get(asset_hash)
865
+ if held is not None:
866
+ columns = self._columns_of(io.BytesIO(held), fmt)
867
+ else:
868
+ handle, stream_mime = self._open_object(ref)
869
+ self._prepared[asset_hash] = (handle, stream_mime)
870
+ columns = self._columns_of(handle, fmt)
871
+ handle.seek(0)
872
+ except Exception as exc:
873
+ logger.warning(
874
+ "No columns recorded for %s, so SQL connections cannot serve it: %s", ref.key, exc
875
+ )
876
+ return
877
+ if columns:
878
+ asset.metadata = {**metadata, "columns": columns}
879
+
880
+ def _columns_of(self, handle: Any, fmt: str) -> list[dict[str, Any]] | None:
881
+ """The columns of an open file; None when it is too large to describe."""
882
+ handle.seek(0)
883
+ if fmt == "parquet":
884
+ import pyarrow.parquet as pq # type: ignore[import-untyped]
885
+
886
+ schema = pq.ParquetFile(handle).schema_arrow
887
+ return build_columns(
888
+ list(schema.names), {field.name: str(field.type) for field in schema}
889
+ )
890
+ by_line = fmt in LINE_FORMATS
891
+ limit = self.SCHEMA_HEAD_BYTES if by_line else self.SCHEMA_MAX_FILE_BYTES
892
+ data = handle.read(limit + 1)
893
+ if len(data) > limit:
894
+ if not by_line:
895
+ return None
896
+ # Whole lines only: half a row would change what the columns look like.
897
+ data = data[: data.rfind(b"\n", 0, limit) + 1]
898
+ if not data:
899
+ return None
900
+ with tempfile.NamedTemporaryFile(suffix=suffix_for(fmt)) as copy:
901
+ copy.write(data)
902
+ copy.flush()
903
+ columns = describe_file(copy.name, fmt)
904
+ return build_columns([name for name, _ in columns], dict(columns))
905
+
906
+ def _drop_prepared(self, asset_hash: str) -> None:
907
+ prepared = self._prepared.pop(asset_hash, None)
908
+ if prepared is not None:
909
+ try:
910
+ prepared[0].close()
911
+ except Exception: # pragma: no cover - close is best effort
912
+ pass
913
+
914
+ def _content_mime(self, asset_id: str, mime: str) -> str:
915
+ """A ``.json`` file SQL reads as a table is scanned as one, row by row.
916
+
917
+ Its findings then name the column they are in, which is what column
918
+ masks go by; scanned as one text they would mask nothing.
919
+ """
920
+ asset_hash, _ = self._object_identity(asset_id)
921
+ ref = self._object_ref_by_hash.get(asset_hash)
922
+ if ref is None or ref.table is not None:
923
+ return mime
924
+ return JSON_TABLE_MIME_TYPE if sql_file_format(mime, ref.key) == "json" else mime
925
+
834
926
  def _to_asset(self, ref: ObjectRef) -> SingleAssetScanResults:
835
927
  if ref.table is not None:
836
928
  return self._table_to_asset(ref)
@@ -1484,14 +1576,17 @@ class ObjectStorageSourceBase(BaseSource, ABC):
1484
1576
  if ref is not None:
1485
1577
  handle: Any = None
1486
1578
  try:
1487
- handle, stream_mime = self._open_object(ref)
1579
+ prepared = self._prepared.pop(asset_hash, None)
1580
+ handle, stream_mime = prepared or self._open_object(ref)
1488
1581
  logger.info(
1489
1582
  "fetch_content_pages(%s): streaming %s as %s",
1490
1583
  asset_id,
1491
1584
  ref.key,
1492
1585
  stream_mime or "unknown",
1493
1586
  )
1494
- async for page in self._pump_pages(asset_id, handle, stream_mime):
1587
+ async for page in self._pump_pages(
1588
+ asset_id, handle, self._content_mime(asset_id, stream_mime)
1589
+ ):
1495
1590
  yield "", page
1496
1591
  finally:
1497
1592
  if handle is not None:
@@ -1511,7 +1606,9 @@ class ObjectStorageSourceBase(BaseSource, ABC):
1511
1606
  )
1512
1607
 
1513
1608
  if raw_bytes is not None:
1514
- async for page in self._pump_pages(asset_id, raw_bytes, mime):
1609
+ async for page in self._pump_pages(
1610
+ asset_id, raw_bytes, self._content_mime(asset_id, mime)
1611
+ ):
1515
1612
  yield "", page
1516
1613
  self._content_pages_processed.add(asset_id)
1517
1614
  return
@@ -1669,6 +1766,7 @@ class ObjectStorageSourceBase(BaseSource, ABC):
1669
1766
  self._bytes_cache.pop(asset_hash, None)
1670
1767
  self._mime_cache.pop(asset_hash, None)
1671
1768
  self._object_ref_by_hash.pop(asset_hash, None)
1769
+ self._drop_prepared(asset_hash)
1672
1770
  if external_url:
1673
1771
  archive_path = self._member_bytes_cache.pop(external_url, archive_path)
1674
1772
  self._content_cache.pop(external_url, None)
@@ -1688,6 +1786,8 @@ class ObjectStorageSourceBase(BaseSource, ABC):
1688
1786
  super().abort()
1689
1787
 
1690
1788
  def cleanup(self) -> None:
1789
+ for asset_hash in list(self._prepared):
1790
+ self._drop_prepared(asset_hash)
1691
1791
  self._reset_member_cache()
1692
1792
  client = self._cached_client
1693
1793
  if client is None:
@@ -25,6 +25,19 @@ def _quote_identifier(identifier: str) -> str:
25
25
  class PostgreSQLSource(BaseTabularSource):
26
26
  source_type = "postgresql"
27
27
 
28
+ # ``data_type`` calls every array "ARRAY" and a four-bit string "bit": a SQL
29
+ # connection would show the first as text and the second as a boolean. A
30
+ # query answers money as formatted text ("$12.34"), so it is recorded as such.
31
+ _COLUMN_TYPE_SQL = """
32
+ CASE
33
+ WHEN data_type = 'ARRAY' THEN substr(udt_name, 2) || '[]'
34
+ WHEN data_type = 'bit' AND character_maximum_length > 1
35
+ THEN 'bit(' || character_maximum_length || ')'
36
+ WHEN data_type = 'money' THEN 'text (money)'
37
+ ELSE data_type
38
+ END
39
+ """
40
+
28
41
  def __init__(
29
42
  self,
30
43
  recipe: dict[str, Any],
@@ -437,6 +437,10 @@ class BaseTabularSource(BaseSource):
437
437
  """Return cached ``{column_name: nullable}`` map when populated by metadata queries."""
438
438
  return self._column_nullability_cache.get(table_ref.table_key, {})
439
439
 
440
+ #: The expression of ``information_schema.columns`` recorded as a column's
441
+ #: type. A dialect overrides it where ``data_type`` says too little.
442
+ _COLUMN_TYPE_SQL = "data_type"
443
+
440
444
  def _available_column_types(self, table_ref: TableRef) -> dict[str, str]:
441
445
  """Return ordered ``{column_name: data_type}`` via ``information_schema``.
442
446
 
@@ -450,7 +454,7 @@ class BaseTabularSource(BaseSource):
450
454
  with conn.cursor() as cursor:
451
455
  cursor.execute(
452
456
  f"""
453
- SELECT column_name, data_type, is_nullable
457
+ SELECT column_name, {self._COLUMN_TYPE_SQL}, is_nullable
454
458
  FROM information_schema.columns
455
459
  WHERE table_schema = {ph} AND table_name = {ph}
456
460
  ORDER BY ordinal_position
src/utils/file_parser.py CHANGED
@@ -26,6 +26,7 @@ from .table_files import (
26
26
  FLATGEOBUF_MIME_TYPE,
27
27
  GEOJSON_MIME_TYPE,
28
28
  GEOPACKAGE_MIME_TYPE,
29
+ JSON_TABLE_MIME_TYPE,
29
30
  LAKEHOUSE_TABLE_MIME_TYPE,
30
31
  NDJSON_MIME_TYPE,
31
32
  ORC_MAGIC,
@@ -2193,6 +2194,7 @@ _TABLE_FORMAT_LABELS = {
2193
2194
  "text/tab-separated-values": "TSV",
2194
2195
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "XLSX",
2195
2196
  NDJSON_MIME_TYPE: "JSON lines",
2197
+ JSON_TABLE_MIME_TYPE: "JSON",
2196
2198
  AVRO_MIME_TYPE: "Avro",
2197
2199
  ORC_MIME_TYPE: "ORC",
2198
2200
  VORTEX_MIME_TYPE: "Vortex",
src/utils/sql_files.py ADDED
@@ -0,0 +1,148 @@
1
+ """The files SQL can read from a bucket or folder, and how it reads them.
2
+
3
+ One definition for the query engine and the scan (docs/prd/DQ-data-query.md).
4
+ The scan records the columns *this* relation returns, so what the catalog, a
5
+ SQL connection and column masks say a file has is what a query gets. A reader
6
+ added here is picked up by both; a format listed here without recorded columns
7
+ is a table a SQL connection cannot serve.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from pathlib import PurePosixPath
13
+ from typing import Any
14
+
15
+ from .duckdb_engine import connect, load_extension, quote_identifier, sql_literal
16
+
17
+ #: Geospatial files, read with the ``spatial`` extension (``ST_Read``); geometries
18
+ #: come out as WKT text, so no spatial function has to be allowed in SQL.
19
+ SPATIAL_FORMATS = frozenset({"geojson", "fgb", "dbf"})
20
+
21
+ #: Keep in sync with ``FILE_FORMATS`` in apps/api/src/data-query/sql-names.ts
22
+ #: (``json`` here is read via ``read_json_auto``).
23
+ FILE_FORMATS = frozenset({"parquet", "csv", "tsv", "jsonl", "json", "avro", *SPATIAL_FORMATS})
24
+
25
+ #: Mirrors ``FILE_FORMATS`` / ``FILE_FORMATS_BY_EXTENSION`` in sql-names.ts: the
26
+ #: MIME type decides, else the extension.
27
+ FORMATS_BY_MIME_TYPE = {
28
+ "application/parquet": "parquet",
29
+ "application/vnd.apache.parquet": "parquet",
30
+ "application/x-parquet": "parquet",
31
+ "text/csv": "csv",
32
+ "application/csv": "csv",
33
+ "text/tab-separated-values": "tsv",
34
+ "application/x-ndjson": "jsonl",
35
+ "application/jsonl": "jsonl",
36
+ "application/x-jsonlines": "jsonl",
37
+ "application/avro": "avro",
38
+ "application/vnd.apache.avro": "avro",
39
+ "application/json": "json",
40
+ "application/geo+json": "geojson",
41
+ "application/vnd.flatgeobuf": "fgb",
42
+ "application/vnd.dbf": "dbf",
43
+ }
44
+ FORMATS_BY_EXTENSION = {
45
+ "parquet": "parquet",
46
+ "csv": "csv",
47
+ "tsv": "tsv",
48
+ "jsonl": "jsonl",
49
+ "ndjson": "jsonl",
50
+ "avro": "avro",
51
+ "json": "json",
52
+ "geojson": "geojson",
53
+ "fgb": "fgb",
54
+ "dbf": "dbf",
55
+ }
56
+
57
+ #: Formats a prefix of the file is enough to describe: one record per line.
58
+ LINE_FORMATS = frozenset({"csv", "tsv", "jsonl"})
59
+
60
+ #: The extension a temporary copy needs: GDAL picks a driver by it.
61
+ _SUFFIXES = {name: f".{name}" for name in FILE_FORMATS}
62
+
63
+ _EXTENSIONS = {"avro": "avro", **dict.fromkeys(SPATIAL_FORMATS, "spatial")}
64
+
65
+
66
+ def sql_file_format(mime_type: str | None, object_key: str) -> str | None:
67
+ """The format SQL would read this file as; None when it cannot be queried."""
68
+ mime = (mime_type or "").split(";", 1)[0].strip().lower()
69
+ if mime in FORMATS_BY_MIME_TYPE:
70
+ return FORMATS_BY_MIME_TYPE[mime]
71
+ extension = PurePosixPath(object_key).suffix.lower().lstrip(".")
72
+ return FORMATS_BY_EXTENSION.get(extension)
73
+
74
+
75
+ def scan_reader_state(metadata: Any) -> dict[str, str]:
76
+ """Marks, per asset, a change in how its content is read, for the scan cache.
77
+
78
+ A table file's columns are recorded while it is processed (and a ``.json``
79
+ one is scanned row by row), so one scanned before that is read again though
80
+ neither it nor any detector changed.
81
+ """
82
+ if not isinstance(metadata, dict):
83
+ return {}
84
+ key = metadata.get("object_key")
85
+ if not isinstance(key, str) or "#" in key:
86
+ return {}
87
+ mime = metadata.get("mime_type")
88
+ fmt = sql_file_format(mime if isinstance(mime, str) else None, key)
89
+ if fmt is None or fmt in ("parquet", "avro"):
90
+ return {}
91
+ return {"reader::sql-table": "1"}
92
+
93
+
94
+ def suffix_for(fmt: str) -> str:
95
+ return _SUFFIXES.get(fmt, "")
96
+
97
+
98
+ def file_relation(conn: Any, fmt: str, uri: str) -> str:
99
+ """The SQL relation reading the file at ``uri`` (a quoted literal).
100
+
101
+ ``conn`` gets whatever extension the format needs.
102
+ """
103
+ extension = _EXTENSIONS.get(fmt)
104
+ if extension:
105
+ load_extension(conn, extension)
106
+ if fmt == "parquet":
107
+ return f"read_parquet({uri})"
108
+ if fmt == "csv":
109
+ return f"read_csv({uri}, auto_detect = true)"
110
+ if fmt == "tsv":
111
+ return f"read_csv({uri}, auto_detect = true, delim = '\\t')"
112
+ if fmt == "jsonl":
113
+ return f"read_json({uri}, format = 'newline_delimited')"
114
+ if fmt == "json":
115
+ return f"read_json_auto({uri})"
116
+ if fmt == "avro":
117
+ return f"read_avro({uri})"
118
+ if fmt in SPATIAL_FORMATS:
119
+ return _spatial(conn, uri)
120
+ raise ValueError(f"{fmt or 'These'} files cannot be queried with SQL yet.")
121
+
122
+
123
+ def _spatial(conn: Any, uri: str) -> str:
124
+ """``ST_Read`` with every geometry column turned into WKT text.
125
+
126
+ The raw column is a binary geometry only spatial functions can read;
127
+ as text it shows in a result and compares like any string.
128
+ """
129
+ source = f"ST_Read({uri})"
130
+ columns = conn.execute(f"DESCRIBE SELECT * FROM {source}").fetchall()
131
+ geometries = [name for name, kind, *_ in columns if str(kind).upper().startswith("GEOMETRY")]
132
+ if not geometries:
133
+ return source
134
+ replaced = ", ".join(
135
+ f"ST_AsText({quote_identifier(name)}) AS {quote_identifier(name)}" for name in geometries
136
+ )
137
+ return f"(SELECT * REPLACE ({replaced}) FROM {source})"
138
+
139
+
140
+ def describe_file(path: str, fmt: str) -> list[tuple[str, str]]:
141
+ """``[(column, SQL type), …]`` a query of the local file ``path`` returns."""
142
+ conn = connect()
143
+ try:
144
+ relation = file_relation(conn, fmt, sql_literal(path))
145
+ rows = conn.execute(f"DESCRIBE SELECT * FROM {relation}").fetchall()
146
+ finally:
147
+ conn.close()
148
+ return [(str(row[0]), str(row[1])) for row in rows]
src/utils/table_files.py CHANGED
@@ -87,6 +87,11 @@ SPATIAL_DRIVERS = {
87
87
  DELIMITED_MIME_TYPES = frozenset({CSV_MIME_TYPE, TSV_MIME_TYPE})
88
88
  DATABASE_MIME_TYPES = frozenset({SQLITE_MIME_TYPE, GEOPACKAGE_MIME_TYPE, DUCKDB_MIME_TYPE})
89
89
 
90
+ # A JSON file SQL reads as a table (``utils.sql_files``). Not a MIME type any
91
+ # file declares: a source passes it to have the file scanned row by row with the
92
+ # query's own columns, so a finding names the column it is in and can be masked.
93
+ JSON_TABLE_MIME_TYPE = "application/vnd.classifyre.json-table"
94
+
90
95
  # Formats read by this module (Parquet and Arrow IPC stay in file_parser, where
91
96
  # their range-reading paths live).
92
97
  TABLE_FILE_MIME_TYPES = frozenset(
@@ -100,12 +105,15 @@ TABLE_FILE_MIME_TYPES = frozenset(
100
105
  *DATABASE_MIME_TYPES,
101
106
  *SPATIAL_DRIVERS,
102
107
  LAKEHOUSE_TABLE_MIME_TYPE,
108
+ JSON_TABLE_MIME_TYPE,
103
109
  }
104
110
  )
105
111
 
106
112
  # Formats whose text a detector can still read when the table reader fails on
107
113
  # them — a malformed CSV is better scanned as text than not at all.
108
- TEXT_FALLBACK_MIME_TYPES = frozenset({*DELIMITED_MIME_TYPES, NDJSON_MIME_TYPE, GEOJSON_MIME_TYPE})
114
+ TEXT_FALLBACK_MIME_TYPES = frozenset(
115
+ {*DELIMITED_MIME_TYPES, NDJSON_MIME_TYPE, GEOJSON_MIME_TYPE, JSON_TABLE_MIME_TYPE}
116
+ )
109
117
 
110
118
  # The SQLite file header, and DuckDB's magic at byte 8 of its file header.
111
119
  SQLITE_MAGIC = b"SQLite format 3\x00"
@@ -175,6 +183,8 @@ def iter_table_batches(
175
183
  yield from _iter_database(source, mime_type, begin, max_rows, batch_rows)
176
184
  elif mime_type in SPATIAL_DRIVERS:
177
185
  yield from _iter_spatial(source, mime_type, begin, max_rows, batch_rows)
186
+ elif mime_type == JSON_TABLE_MIME_TYPE:
187
+ yield from _iter_json_table(source, begin, max_rows, batch_rows)
178
188
  elif mime_type == LAKEHOUSE_TABLE_MIME_TYPE:
179
189
  from .lakehouse_tables import iter_lakehouse_batches
180
190
 
@@ -335,6 +345,15 @@ def _iter_ndjson(
335
345
  yield from _duckdb_batches(query, begin, max_rows, batch_rows)
336
346
 
337
347
 
348
+ def _iter_json_table(
349
+ source: BinarySource, begin: int, max_rows: int | None, batch_rows: int
350
+ ) -> Iterator[TableBatch]:
351
+ """A ``.json`` file as the query engine reads it: same relation, same columns."""
352
+ with materialized_path(source, suffix=".json", transcode_from=_text_encoding(source)) as path:
353
+ query = f"SELECT * FROM read_json_auto({sql_literal(path)})"
354
+ yield from _duckdb_batches(query, begin, max_rows, batch_rows)
355
+
356
+
338
357
  # ── Avro ─────────────────────────────────────────────────────────────────
339
358
 
340
359