@loaders.gl/core 5.0.0-rc.1 → 5.0.0

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 (296) hide show
  1. package/SCAN-README.md +8 -8
  2. package/dist/arrow-geometry/binary-features.cjs +2 -2
  3. package/dist/arrow-geometry/binary-features.cjs.map +2 -2
  4. package/dist/arrow-geometry/binary-features.js +1 -1
  5. package/dist/arrow-geometry/binary-features.js.map +1 -1
  6. package/dist/arrow-geometry/geometry-codecs.cjs +51 -50
  7. package/dist/arrow-geometry/geometry-codecs.cjs.map +3 -3
  8. package/dist/arrow-geometry/geometry-codecs.d.ts +1 -1
  9. package/dist/arrow-geometry/geometry-codecs.d.ts.map +1 -1
  10. package/dist/arrow-geometry/geometry-codecs.js +27 -60
  11. package/dist/arrow-geometry/geometry-codecs.js.map +1 -1
  12. package/dist/arrow-geometry/legacy-binary/convert-flat-geojson-to-binary-features.cjs +2 -2
  13. package/dist/arrow-geometry/legacy-binary/convert-flat-geojson-to-binary-features.cjs.map +2 -2
  14. package/dist/arrow-geometry/legacy-binary/convert-flat-geojson-to-binary-features.js +1 -1
  15. package/dist/arrow-geometry/legacy-binary/convert-flat-geojson-to-binary-features.js.map +1 -1
  16. package/dist/arrow-geometry/legacy-binary/convert-geojson-to-flat-geojson.cjs +2 -2
  17. package/dist/arrow-geometry/legacy-binary/convert-geojson-to-flat-geojson.cjs.map +2 -2
  18. package/dist/arrow-geometry/legacy-binary/convert-geojson-to-flat-geojson.js +1 -1
  19. package/dist/arrow-geometry/legacy-binary/convert-geojson-to-flat-geojson.js.map +1 -1
  20. package/dist/arrow-geometry/triangulate-wkb.cjs +33 -118
  21. package/dist/arrow-geometry/triangulate-wkb.cjs.map +2 -2
  22. package/dist/arrow-geometry/triangulate-wkb.d.ts.map +1 -1
  23. package/dist/arrow-geometry/triangulate-wkb.js +39 -142
  24. package/dist/arrow-geometry/triangulate-wkb.js.map +1 -1
  25. package/dist/cluster-source.cjs +128 -374
  26. package/dist/cluster-source.cjs.map +3 -3
  27. package/dist/constants/index.cjs +2 -2
  28. package/dist/constants/index.d.ts +4 -4
  29. package/dist/constants/index.d.ts.map +1 -1
  30. package/dist/constants/index.js +2 -2
  31. package/dist/constants/index.js.map +1 -1
  32. package/dist/dist.dev.js +63 -15
  33. package/dist/dist.min.js +3 -3
  34. package/dist/federated-table-scan-source.cjs +174 -660
  35. package/dist/federated-table-scan-source.cjs.map +3 -3
  36. package/dist/geoarrow/geoarrow-converter/convert-geoarrow-geometry.cjs +15 -0
  37. package/dist/geoarrow/geoarrow-converter/convert-geoarrow-geometry.cjs.map +2 -2
  38. package/dist/geoarrow/geoarrow-converter/convert-geoarrow-geometry.js +19 -1
  39. package/dist/geoarrow/geoarrow-converter/convert-geoarrow-geometry.js.map +1 -1
  40. package/dist/geoarrow/get-geoarrow-vertex-count.cjs +6 -27
  41. package/dist/geoarrow/get-geoarrow-vertex-count.cjs.map +2 -2
  42. package/dist/geoarrow/get-geoarrow-vertex-count.d.ts.map +1 -1
  43. package/dist/geoarrow/get-geoarrow-vertex-count.js +9 -24
  44. package/dist/geoarrow/get-geoarrow-vertex-count.js.map +1 -1
  45. package/dist/geoarrow/lib/feature-collection-converters/convert-geometry-column-to-binary-feature-collection.cjs +2 -2
  46. package/dist/geoarrow/lib/feature-collection-converters/convert-geometry-column-to-binary-feature-collection.cjs.map +2 -2
  47. package/dist/geoarrow/lib/feature-collection-converters/convert-geometry-column-to-binary-feature-collection.js +1 -1
  48. package/dist/geoarrow/lib/feature-collection-converters/convert-geometry-column-to-binary-feature-collection.js.map +1 -1
  49. package/dist/geoarrow/lib/geometry-converters/wkb/helpers/parse-wkb-header.cjs +3 -5
  50. package/dist/geoarrow/lib/geometry-converters/wkb/helpers/parse-wkb-header.cjs.map +2 -2
  51. package/dist/geoarrow/lib/geometry-converters/wkb/helpers/parse-wkb-header.d.ts +2 -24
  52. package/dist/geoarrow/lib/geometry-converters/wkb/helpers/parse-wkb-header.d.ts.map +1 -1
  53. package/dist/geoarrow/lib/geometry-converters/wkb/helpers/parse-wkb-header.js +6 -28
  54. package/dist/geoarrow/lib/geometry-converters/wkb/helpers/parse-wkb-header.js.map +1 -1
  55. package/dist/geoarrow/lib/kernels/decode-wkt-native.cjs +20 -226
  56. package/dist/geoarrow/lib/kernels/decode-wkt-native.cjs.map +2 -2
  57. package/dist/geoarrow/lib/kernels/decode-wkt-native.d.ts +1 -2
  58. package/dist/geoarrow/lib/kernels/decode-wkt-native.d.ts.map +1 -1
  59. package/dist/geoarrow/lib/kernels/decode-wkt-native.js +23 -264
  60. package/dist/geoarrow/lib/kernels/decode-wkt-native.js.map +1 -1
  61. package/dist/index.cjs +67 -19
  62. package/dist/index.cjs.map +1 -1
  63. package/dist/lib/api/load.js +36 -7
  64. package/dist/lib/api/load.js.map +1 -1
  65. package/dist/lib/api/parse.js +5 -2
  66. package/dist/lib/api/parse.js.map +1 -1
  67. package/dist/lib/init.js +1 -1
  68. package/dist/lib/init.js.map +1 -1
  69. package/dist/loader-utils/index.cjs +67 -229
  70. package/dist/loader-utils/index.cjs.map +2 -2
  71. package/dist/loader-utils/json-loader.js +1 -1
  72. package/dist/loader-utils/json-loader.js.map +1 -1
  73. package/dist/loader-utils/lib/log-utils/log.js +1 -1
  74. package/dist/loader-utils/lib/log-utils/log.js.map +1 -1
  75. package/dist/loader-utils/lib/scan-utils/columnar-predicate.d.ts +4 -52
  76. package/dist/loader-utils/lib/scan-utils/columnar-predicate.d.ts.map +1 -1
  77. package/dist/loader-utils/lib/scan-utils/columnar-predicate.js +16 -236
  78. package/dist/loader-utils/lib/scan-utils/columnar-predicate.js.map +1 -1
  79. package/dist/loader-utils/lib/scan-utils/relational-query.d.ts +2 -0
  80. package/dist/loader-utils/lib/scan-utils/relational-query.d.ts.map +1 -1
  81. package/dist/loader-utils/lib/scan-utils/relational-query.js.map +1 -1
  82. package/dist/loader-utils/lib/sources/tile-grid.d.ts +1 -1
  83. package/dist/loader-utils/lib/sources/tile-grid.d.ts.map +1 -1
  84. package/dist/loader-utils/lib/sources/tile-grid.js +1 -1
  85. package/dist/loader-utils/lib/sources/tile-grid.js.map +1 -1
  86. package/dist/loader-utils/lib/sources/tile-source-adapter.js +1 -1
  87. package/dist/loader-utils/lib/sources/tile-source-adapter.js.map +1 -1
  88. package/dist/loader-utils/lib/sources/tile-source.d.ts +1 -1
  89. package/dist/loader-utils/lib/sources/tile-source.d.ts.map +1 -1
  90. package/dist/loader-utils/loader-types.d.ts +6 -0
  91. package/dist/loader-utils/loader-types.d.ts.map +1 -1
  92. package/dist/loader-utils/loader-types.js.map +1 -1
  93. package/dist/loader-utils/tile-grid.cjs +5 -5
  94. package/dist/loader-utils/tile-grid.cjs.map +1 -1
  95. package/dist/null-loader.js +1 -1
  96. package/dist/null-loader.js.map +1 -1
  97. package/dist/null-worker-node.js +1 -1
  98. package/dist/null-worker.js +1 -1
  99. package/dist/scan/arrow-execution/expressions.cjs +9 -78
  100. package/dist/scan/arrow-execution/expressions.cjs.map +3 -3
  101. package/dist/scan/arrow-execution/expressions.d.ts +2 -8
  102. package/dist/scan/arrow-execution/expressions.d.ts.map +1 -1
  103. package/dist/scan/arrow-execution/expressions.js +2 -55
  104. package/dist/scan/arrow-execution/expressions.js.map +1 -1
  105. package/dist/scan/arrow-execution/filter-arrow-table.cjs +41 -179
  106. package/dist/scan/arrow-execution/filter-arrow-table.cjs.map +3 -3
  107. package/dist/scan/arrow-execution/filter-arrow-table.d.ts +1 -5
  108. package/dist/scan/arrow-execution/filter-arrow-table.d.ts.map +1 -1
  109. package/dist/scan/arrow-execution/filter-arrow-table.js +44 -190
  110. package/dist/scan/arrow-execution/filter-arrow-table.js.map +1 -1
  111. package/dist/scan/arrow-execution.cjs +2 -2
  112. package/dist/scan/arrow-execution.cjs.map +2 -2
  113. package/dist/scan/arrow-execution.d.ts +1 -1
  114. package/dist/scan/arrow-execution.d.ts.map +1 -1
  115. package/dist/scan/arrow-execution.js +1 -1
  116. package/dist/scan/arrow-execution.js.map +1 -1
  117. package/dist/scan/arrow-query.cjs +3 -3
  118. package/dist/scan/arrow-query.cjs.map +2 -2
  119. package/dist/scan/arrow-query.d.ts +2 -2
  120. package/dist/scan/arrow-query.d.ts.map +1 -1
  121. package/dist/scan/arrow-query.js +2 -2
  122. package/dist/scan/arrow-query.js.map +1 -1
  123. package/dist/scan/federated-table-scan-source.cjs +3 -3
  124. package/dist/scan/federated-table-scan-source.cjs.map +2 -2
  125. package/dist/scan/federated-table-scan-source.js +1 -1
  126. package/dist/scan/federated-table-scan-source.js.map +1 -1
  127. package/dist/scan/index.cjs +9 -49
  128. package/dist/scan/index.cjs.map +3 -3
  129. package/dist/scan/index.d.ts +2 -2
  130. package/dist/scan/index.d.ts.map +1 -1
  131. package/dist/scan/index.js +2 -2
  132. package/dist/scan/index.js.map +1 -1
  133. package/dist/scan/plan-arrow-table-query.cjs +271 -0
  134. package/dist/scan/plan-arrow-table-query.cjs.map +7 -0
  135. package/dist/scan/plan-arrow-table-query.d.ts +50 -0
  136. package/dist/scan/plan-arrow-table-query.d.ts.map +1 -0
  137. package/dist/scan/plan-arrow-table-query.js +257 -0
  138. package/dist/scan/plan-arrow-table-query.js.map +1 -0
  139. package/dist/scan/query-arrow-table-in-batches.cjs +2 -39
  140. package/dist/scan/query-arrow-table-in-batches.cjs.map +2 -2
  141. package/dist/scan/query-arrow-table-in-batches.d.ts +1 -1
  142. package/dist/scan/query-arrow-table-in-batches.d.ts.map +1 -1
  143. package/dist/scan/query-arrow-table-in-batches.js +3 -26
  144. package/dist/scan/query-arrow-table-in-batches.js.map +1 -1
  145. package/dist/scan/query-arrow-table.cjs +7 -443
  146. package/dist/scan/query-arrow-table.cjs.map +3 -3
  147. package/dist/scan/query-arrow-table.d.ts +6 -54
  148. package/dist/scan/query-arrow-table.d.ts.map +1 -1
  149. package/dist/scan/query-arrow-table.js +6 -475
  150. package/dist/scan/query-arrow-table.js.map +1 -1
  151. package/dist/scan/query-pushdown.cjs +3 -4
  152. package/dist/scan/query-pushdown.cjs.map +2 -2
  153. package/dist/scan/query-pushdown.js +4 -5
  154. package/dist/scan/query-pushdown.js.map +1 -1
  155. package/dist/scan/query-scales.cjs +2 -1
  156. package/dist/scan/query-scales.cjs.map +2 -2
  157. package/dist/scan/query-scales.d.ts +2 -1
  158. package/dist/scan/query-scales.d.ts.map +1 -1
  159. package/dist/scan/query-scales.js +2 -1
  160. package/dist/scan/query-scales.js.map +1 -1
  161. package/dist/scan/query.cjs +10 -9
  162. package/dist/scan/query.cjs.map +2 -2
  163. package/dist/scan/query.d.ts.map +1 -1
  164. package/dist/scan/query.js +14 -5
  165. package/dist/scan/query.js.map +1 -1
  166. package/dist/scan/scan-engine.cjs +14 -7
  167. package/dist/scan/scan-engine.cjs.map +2 -2
  168. package/dist/scan/scan-engine.d.ts +2 -2
  169. package/dist/scan/scan-engine.d.ts.map +1 -1
  170. package/dist/scan/scan-engine.js +5 -10
  171. package/dist/scan/scan-engine.js.map +1 -1
  172. package/dist/scan/sql-predicate-schema.cjs +10 -94
  173. package/dist/scan/sql-predicate-schema.cjs.map +3 -3
  174. package/dist/scan/sql-predicate-schema.d.ts +1 -1
  175. package/dist/scan/sql-predicate-schema.d.ts.map +1 -1
  176. package/dist/scan/sql-predicate-schema.js +9 -103
  177. package/dist/scan/sql-predicate-schema.js.map +1 -1
  178. package/dist/scan/sql-predicate-zod.cjs.map +1 -1
  179. package/dist/scan/sql-predicate-zod.d.ts +1 -1
  180. package/dist/scan/sql-predicate-zod.js +1 -1
  181. package/dist/scan/vector-table-scan-source.cjs +14 -3
  182. package/dist/scan/vector-table-scan-source.cjs.map +2 -2
  183. package/dist/scan/vector-table-scan-source.d.ts +1 -1
  184. package/dist/scan/vector-table-scan-source.d.ts.map +1 -1
  185. package/dist/scan/vector-table-scan-source.js +2 -1
  186. package/dist/scan/vector-table-scan-source.js.map +1 -1
  187. package/dist/schema-utils/index.cjs +11 -47
  188. package/dist/schema-utils/index.cjs.map +1 -1
  189. package/dist/schema-utils/lib/arrow/arrow-metadata.d.ts +2 -4
  190. package/dist/schema-utils/lib/arrow/arrow-metadata.d.ts.map +1 -1
  191. package/dist/schema-utils/lib/arrow/arrow-metadata.js +2 -43
  192. package/dist/schema-utils/lib/arrow/arrow-metadata.js.map +1 -1
  193. package/dist/vector-table-scan-source.cjs +905 -1453
  194. package/dist/vector-table-scan-source.cjs.map +3 -3
  195. package/dist/wkt/twkb/index.cjs +68 -5
  196. package/dist/wkt/twkb/index.cjs.map +3 -3
  197. package/dist/wkt/twkb/index.d.ts +10 -2
  198. package/dist/wkt/twkb/index.d.ts.map +1 -1
  199. package/dist/wkt/twkb/index.js +49 -2
  200. package/dist/wkt/twkb/index.js.map +1 -1
  201. package/dist/worker-utils/index.cjs +33 -9
  202. package/dist/worker-utils/index.cjs.map +1 -1
  203. package/dist/worker-utils/lib/env-utils/version.js +1 -1
  204. package/dist/worker-utils/lib/env-utils/version.js.map +1 -1
  205. package/dist/worker-utils/lib/worker-api/process-on-worker.d.ts +4 -1
  206. package/dist/worker-utils/lib/worker-api/process-on-worker.d.ts.map +1 -1
  207. package/dist/worker-utils/lib/worker-api/process-on-worker.js +40 -6
  208. package/dist/worker-utils/lib/worker-api/process-on-worker.js.map +1 -1
  209. package/package.json +24 -104
  210. package/src/arrow-geometry/binary-features.ts +1 -1
  211. package/src/arrow-geometry/geometry-codecs.ts +35 -78
  212. package/src/arrow-geometry/legacy-binary/convert-flat-geojson-to-binary-features.ts +1 -1
  213. package/src/arrow-geometry/legacy-binary/convert-geojson-to-flat-geojson.ts +1 -1
  214. package/src/arrow-geometry/triangulate-wkb.ts +37 -169
  215. package/src/constants/index.ts +2 -2
  216. package/src/geoarrow/geoarrow-converter/convert-geoarrow-geometry.ts +22 -1
  217. package/src/geoarrow/get-geoarrow-vertex-count.ts +7 -32
  218. package/src/geoarrow/lib/feature-collection-converters/convert-geometry-column-to-binary-feature-collection.ts +1 -1
  219. package/src/geoarrow/lib/geometry-converters/wkb/helpers/parse-wkb-header.ts +6 -30
  220. package/src/geoarrow/lib/kernels/decode-wkt-native.ts +23 -269
  221. package/src/lib/api/load.ts +36 -7
  222. package/src/lib/api/parse.ts +6 -2
  223. package/src/loader-utils/lib/scan-utils/columnar-predicate.ts +46 -363
  224. package/src/loader-utils/lib/scan-utils/relational-query.ts +7 -1
  225. package/src/loader-utils/lib/sources/tile-grid.ts +6 -2
  226. package/src/loader-utils/lib/sources/tile-source-adapter.ts +1 -1
  227. package/src/loader-utils/lib/sources/tile-source.ts +1 -1
  228. package/src/loader-utils/loader-types.ts +6 -0
  229. package/src/scan/arrow-execution/expressions.ts +2 -86
  230. package/src/scan/arrow-execution/filter-arrow-table.ts +54 -238
  231. package/src/scan/arrow-execution.ts +1 -1
  232. package/src/scan/arrow-query.ts +2 -2
  233. package/src/scan/federated-table-scan-source.ts +1 -1
  234. package/src/scan/index.ts +2 -2
  235. package/src/scan/plan-arrow-table-query.ts +367 -0
  236. package/src/scan/query-arrow-table-in-batches.ts +4 -33
  237. package/src/scan/query-arrow-table.ts +10 -626
  238. package/src/scan/query-pushdown.ts +3 -4
  239. package/src/scan/query-scales.ts +3 -4
  240. package/src/scan/query.ts +16 -10
  241. package/src/scan/scan-engine.ts +5 -12
  242. package/src/scan/sql-predicate-schema.ts +14 -125
  243. package/src/scan/sql-predicate-zod.ts +1 -1
  244. package/src/scan/vector-table-scan-source.ts +2 -1
  245. package/src/schema-utils/lib/arrow/arrow-metadata.ts +2 -50
  246. package/src/wkt/twkb/index.ts +63 -2
  247. package/src/worker-utils/lib/worker-api/process-on-worker.ts +39 -6
  248. package/dist/scan/arrow-execution/portable-predicate-compatibility.cjs +0 -41
  249. package/dist/scan/arrow-execution/portable-predicate-compatibility.cjs.map +0 -7
  250. package/dist/scan/arrow-execution/portable-predicate-compatibility.d.ts +0 -5
  251. package/dist/scan/arrow-execution/portable-predicate-compatibility.d.ts.map +0 -1
  252. package/dist/scan/arrow-execution/portable-predicate-compatibility.js +0 -23
  253. package/dist/scan/arrow-execution/portable-predicate-compatibility.js.map +0 -1
  254. package/dist/scan/arrow-execution/project-arrow-table.cjs +0 -70
  255. package/dist/scan/arrow-execution/project-arrow-table.cjs.map +0 -7
  256. package/dist/scan/arrow-execution/project-arrow-table.d.ts +0 -8
  257. package/dist/scan/arrow-execution/project-arrow-table.d.ts.map +0 -1
  258. package/dist/scan/arrow-execution/project-arrow-table.js +0 -39
  259. package/dist/scan/arrow-execution/project-arrow-table.js.map +0 -1
  260. package/dist/scan/query-arrow-table-math.cjs +0 -41
  261. package/dist/scan/query-arrow-table-math.cjs.map +0 -7
  262. package/dist/scan/query-arrow-table-math.d.ts +0 -5
  263. package/dist/scan/query-arrow-table-math.d.ts.map +0 -1
  264. package/dist/scan/query-arrow-table-math.js +0 -14
  265. package/dist/scan/query-arrow-table-math.js.map +0 -1
  266. package/dist/wkt/twkb/convert-geometry-to-twkb.cjs +0 -211
  267. package/dist/wkt/twkb/convert-geometry-to-twkb.cjs.map +0 -7
  268. package/dist/wkt/twkb/convert-geometry-to-twkb.d.ts +0 -6
  269. package/dist/wkt/twkb/convert-geometry-to-twkb.d.ts.map +0 -1
  270. package/dist/wkt/twkb/convert-geometry-to-twkb.js +0 -204
  271. package/dist/wkt/twkb/convert-geometry-to-twkb.js.map +0 -1
  272. package/dist/wkt/twkb/convert-twkb-to-geometry.cjs +0 -251
  273. package/dist/wkt/twkb/convert-twkb-to-geometry.cjs.map +0 -7
  274. package/dist/wkt/twkb/convert-twkb-to-geometry.d.ts +0 -10
  275. package/dist/wkt/twkb/convert-twkb-to-geometry.d.ts.map +0 -1
  276. package/dist/wkt/twkb/convert-twkb-to-geometry.js +0 -261
  277. package/dist/wkt/twkb/convert-twkb-to-geometry.js.map +0 -1
  278. package/dist/wkt/twkb/twkb-io.cjs +0 -102
  279. package/dist/wkt/twkb/twkb-io.cjs.map +0 -7
  280. package/dist/wkt/twkb/twkb-io.d.ts +0 -33
  281. package/dist/wkt/twkb/twkb-io.d.ts.map +0 -1
  282. package/dist/wkt/twkb/twkb-io.js +0 -78
  283. package/dist/wkt/twkb/twkb-io.js.map +0 -1
  284. package/dist/wkt/twkb/twkb-types.cjs +0 -40
  285. package/dist/wkt/twkb/twkb-types.cjs.map +0 -7
  286. package/dist/wkt/twkb/twkb-types.d.ts +0 -11
  287. package/dist/wkt/twkb/twkb-types.d.ts.map +0 -1
  288. package/dist/wkt/twkb/twkb-types.js +0 -15
  289. package/dist/wkt/twkb/twkb-types.js.map +0 -1
  290. package/src/scan/arrow-execution/portable-predicate-compatibility.ts +0 -27
  291. package/src/scan/arrow-execution/project-arrow-table.ts +0 -53
  292. package/src/scan/query-arrow-table-math.ts +0 -23
  293. package/src/wkt/twkb/convert-geometry-to-twkb.ts +0 -317
  294. package/src/wkt/twkb/convert-twkb-to-geometry.ts +0 -373
  295. package/src/wkt/twkb/twkb-io.ts +0 -85
  296. package/src/wkt/twkb/twkb-types.ts +0 -14
@@ -5,6 +5,14 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res, err) => function __init() {
9
+ if (err) throw err[0];
10
+ try {
11
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
12
+ } catch (e) {
13
+ throw err = [e], e;
14
+ }
15
+ };
8
16
  var __export = (target, all) => {
9
17
  for (var name in all)
10
18
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -27,1539 +35,982 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
27
35
  ));
28
36
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
37
 
30
- // dist/vector-table-scan-source.js
31
- var vector_table_scan_source_exports = {};
32
- __export(vector_table_scan_source_exports, {
33
- AddressedVectorTableScanSource: () => AddressedVectorTableScanSource,
34
- VectorFeatureTableScanSource: () => VectorFeatureTableScanSource,
35
- VectorTileTableScanSource: () => VectorTileTableScanSource
38
+ // src/loader-utils/lib/scan-utils/columnar-predicate.ts
39
+ var import_columnar_predicate, import_columnar_predicate2;
40
+ var init_columnar_predicate = __esm({
41
+ "src/loader-utils/lib/scan-utils/columnar-predicate.ts"() {
42
+ "use strict";
43
+ import_columnar_predicate = require("@math.gl/sql/columnar-predicate");
44
+ import_columnar_predicate2 = require("@math.gl/sql/columnar-predicate");
45
+ }
36
46
  });
37
- module.exports = __toCommonJS(vector_table_scan_source_exports);
38
47
 
39
- // src/schema-utils/lib/schema/convert-arrow-schema.ts
40
- var arrow = __toESM(require("apache-arrow"), 1);
41
- function convertArrowToSchema(arrowSchema) {
42
- return serializeArrowSchema(arrowSchema);
48
+ // src/loader-utils/lib/scan-utils/scan-query-metadata.ts
49
+ function createScanQueryMetadata(options) {
50
+ validateScanExecutionSupport(options.queryType, options.execution);
51
+ const schema = Object.freeze({
52
+ fields: Object.freeze(
53
+ options.schema.fields.map(
54
+ (field) => Object.freeze({ ...field, metadata: Object.freeze({ ...field.metadata }) })
55
+ )
56
+ ),
57
+ metadata: Object.freeze({ ...options.schema.metadata })
58
+ });
59
+ const columns = schema.fields.map(
60
+ (field) => {
61
+ var _a;
62
+ return Object.freeze({
63
+ name: field.name,
64
+ type: field.type,
65
+ nullable: field.nullable !== false,
66
+ role: ((_a = options.columnRoles) == null ? void 0 : _a[field.name]) || "attribute",
67
+ title: getNonEmptyMetadataValue(field.metadata, "title"),
68
+ description: getNonEmptyMetadataValue(field.metadata, "description"),
69
+ metadata: field.metadata || Object.freeze({})
70
+ });
71
+ }
72
+ );
73
+ const queryCapabilities = Object.freeze({ ...options.capabilities });
74
+ return Object.freeze({
75
+ sourceType: options.sourceType,
76
+ queryType: options.queryType,
77
+ execution: Object.freeze({ ...options.execution }),
78
+ name: options.name,
79
+ description: options.description,
80
+ schema,
81
+ columns: Object.freeze(columns),
82
+ capabilities: queryCapabilities,
83
+ queryCapabilities,
84
+ ...options.hasDefaultRowWindow ? { hasDefaultRowWindow: true } : {},
85
+ spatial: options.spatial ? Object.freeze({
86
+ ...options.spatial,
87
+ bounds: options.spatial.bounds ? Object.freeze({
88
+ minimum: Object.freeze([...options.spatial.bounds.minimum]),
89
+ maximum: Object.freeze([...options.spatial.bounds.maximum])
90
+ }) : void 0,
91
+ coordinateReferenceSystems: options.spatial.coordinateReferenceSystems ? Object.freeze([...options.spatial.coordinateReferenceSystems]) : void 0,
92
+ spatialReference: options.spatial.spatialReference ? (0, import_crs.createSpatialReference)(options.spatial.spatialReference) : void 0
93
+ }) : void 0,
94
+ statistics: options.statistics ? Object.freeze({ ...options.statistics }) : void 0,
95
+ levels: options.levels ? Object.freeze(
96
+ options.levels.map(
97
+ (level) => Object.freeze({
98
+ ...level,
99
+ scale: level.scale ? Object.freeze([...level.scale]) : void 0
100
+ })
101
+ )
102
+ ) : void 0
103
+ });
43
104
  }
44
- function serializeArrowSchema(arrowSchema) {
45
- return {
46
- fields: arrowSchema.fields.map((arrowField) => serializeArrowField(arrowField)),
47
- metadata: serializeArrowMetadata(arrowSchema.metadata)
105
+ function validateScanExecutionSupport(queryType, execution) {
106
+ if (execution.status === "metadata-only") {
107
+ if (!execution.reason.trim()) {
108
+ throw new Error("Metadata-only scan support requires a concrete reason");
109
+ }
110
+ return;
111
+ }
112
+ const validMethods = {
113
+ table: ["read", "query"],
114
+ raster: ["getRaster"],
115
+ "point-cloud": ["scan"]
48
116
  };
117
+ if (!validMethods[queryType].includes(execution.method)) {
118
+ throw new Error(
119
+ `Scan execution method "${execution.method}" is not valid for ${queryType} queries`
120
+ );
121
+ }
49
122
  }
50
- function deserializeArrowSchema(schema, options) {
51
- return new arrow.Schema(
52
- schema.fields.map((field) => deserializeArrowField(field, options)),
53
- deserializeArrowMetadata(schema.metadata)
54
- );
123
+ function getNonEmptyMetadataValue(metadata, key) {
124
+ const value = metadata == null ? void 0 : metadata[key];
125
+ return value || void 0;
55
126
  }
56
- function serializeArrowMetadata(arrowMetadata) {
57
- return Object.fromEntries(arrowMetadata);
127
+ var import_crs;
128
+ var init_scan_query_metadata = __esm({
129
+ "src/loader-utils/lib/scan-utils/scan-query-metadata.ts"() {
130
+ "use strict";
131
+ import_crs = require("@math.gl/geospatial/crs");
132
+ }
133
+ });
134
+
135
+ // src/loader-utils/lib/scan-utils/table-query.ts
136
+ function planTableQuery(sourceColumnNames, options = {}) {
137
+ validateTableQueryOptions(sourceColumnNames, options);
138
+ const outputColumnNames = options.columns ? [...options.columns] : [...sourceColumnNames];
139
+ const predicateColumnNames = options.predicate ? (0, import_columnar_predicate2.getColumnarPredicateColumns)(options.predicate) : [];
140
+ const requiredColumnNames = /* @__PURE__ */ new Set([...outputColumnNames, ...predicateColumnNames]);
141
+ const scanColumnNames = sourceColumnNames.filter(
142
+ (columnName) => requiredColumnNames.has(columnName)
143
+ );
144
+ const steps = [
145
+ Object.freeze({ kind: "scan", columns: Object.freeze(scanColumnNames) })
146
+ ];
147
+ if (options.predicate) {
148
+ steps.push(Object.freeze({ kind: "filter", predicate: options.predicate }));
149
+ }
150
+ steps.push(Object.freeze({ kind: "project", columns: Object.freeze(outputColumnNames) }));
151
+ if (options.limit !== void 0) {
152
+ steps.push(Object.freeze({ kind: "limit", limit: options.limit }));
153
+ }
154
+ return Object.freeze(steps);
58
155
  }
59
- function deserializeArrowMetadata(metadata) {
60
- return metadata ? new Map(Object.entries(metadata)) : /* @__PURE__ */ new Map();
156
+ function validateTableQueryOptions(sourceColumnNames, options) {
157
+ const availableColumnNames = new Set(sourceColumnNames);
158
+ const outputColumnNames = options.columns ?? sourceColumnNames;
159
+ const seenColumnNames = /* @__PURE__ */ new Set();
160
+ for (const columnName of outputColumnNames) {
161
+ if (!availableColumnNames.has(columnName)) {
162
+ throw new Error(`Table query column not found: ${columnName}`);
163
+ }
164
+ if (seenColumnNames.has(columnName)) {
165
+ throw new Error(`Table query column was selected more than once: ${columnName}`);
166
+ }
167
+ seenColumnNames.add(columnName);
168
+ }
169
+ validateTableQueryLimit(options.limit);
170
+ if (options.predicate) {
171
+ (0, import_columnar_predicate2.validateColumnarPredicate)(options.predicate, availableColumnNames);
172
+ }
61
173
  }
62
- function serializeArrowField(field) {
63
- return {
64
- name: field.name,
65
- type: serializeArrowType(field.type),
66
- nullable: field.nullable,
67
- metadata: serializeArrowMetadata(field.metadata)
68
- };
174
+ function validateTableQueryLimit(limit) {
175
+ if (limit !== void 0 && (!Number.isSafeInteger(limit) || limit < 0)) {
176
+ throw new Error("Table query limit must be a non-negative safe integer.");
177
+ }
69
178
  }
70
- function deserializeArrowField(field, options) {
71
- return new arrow.Field(
72
- field.name,
73
- deserializeArrowType(field.type, options),
74
- field.nullable,
75
- deserializeArrowMetadata(field.metadata)
179
+ var init_table_query = __esm({
180
+ "src/loader-utils/lib/scan-utils/table-query.ts"() {
181
+ "use strict";
182
+ init_columnar_predicate();
183
+ }
184
+ });
185
+
186
+ // src/loader-utils/lib/scan-utils/relational-query.ts
187
+ function planRelationalQuery(sourceColumnNames, options = {}) {
188
+ var _a, _b, _c, _d, _e, _f;
189
+ const available = new Set(sourceColumnNames);
190
+ const expressionNames = /* @__PURE__ */ new Set();
191
+ for (const expression of options.expressions || []) {
192
+ if (!expression.name) throw new Error("Relational expression names must be non-empty.");
193
+ if (available.has(expression.name) || expressionNames.has(expression.name)) {
194
+ throw new Error(`Relational expression duplicates column: ${expression.name}`);
195
+ }
196
+ expressionNames.add(expression.name);
197
+ }
198
+ const aggregateNames = new Set((options.aggregates || []).map((aggregate) => aggregate.name));
199
+ const requiredColumns = /* @__PURE__ */ new Set();
200
+ const availableColumns = new Set(sourceColumnNames);
201
+ for (const expression of options.expressions || []) {
202
+ const definition = expression.expression;
203
+ if (definition.op === "column") {
204
+ validateRelationalColumnReference(definition.column, availableColumns);
205
+ if (available.has(definition.column)) requiredColumns.add(definition.column);
206
+ }
207
+ if ("left" in definition) {
208
+ validateRelationalColumnReference(definition.left, availableColumns);
209
+ validateRelationalColumnReference(definition.right, availableColumns);
210
+ if (available.has(definition.left)) requiredColumns.add(definition.left);
211
+ if (available.has(definition.right)) requiredColumns.add(definition.right);
212
+ }
213
+ availableColumns.add(expression.name);
214
+ }
215
+ for (const key of options.orderBy || []) requiredColumns.add(key.column);
216
+ for (const key of options.groupBy || []) requiredColumns.add(key);
217
+ for (const aggregate of options.aggregates || []) {
218
+ if (aggregate.column) requiredColumns.add(aggregate.column);
219
+ }
220
+ const outputColumns = (_a = options.columns) == null ? void 0 : _a.filter(
221
+ (column) => !expressionNames.has(column) && !aggregateNames.has(column)
76
222
  );
77
- }
78
- function serializeArrowType(arrowType) {
79
- if (isArrowViewType(arrowType, "BinaryView")) {
80
- return "binary-view";
223
+ const tablePlan = [
224
+ ...planTableQuery(sourceColumnNames, {
225
+ ...options,
226
+ columns: outputColumns,
227
+ predicate: options.predicate
228
+ })
229
+ ];
230
+ const scanStep = tablePlan[0];
231
+ if ((scanStep == null ? void 0 : scanStep.kind) === "scan") {
232
+ const scanColumns = new Set(scanStep.columns);
233
+ for (const column of requiredColumns) {
234
+ if (available.has(column)) scanColumns.add(column);
235
+ }
236
+ tablePlan[0] = Object.freeze({ kind: "scan", columns: Object.freeze([...scanColumns]) });
81
237
  }
82
- if (isArrowViewType(arrowType, "Utf8View")) {
83
- return "utf8-view";
238
+ for (const expression of expressionNames) available.add(expression);
239
+ for (const aggregate of aggregateNames) available.add(aggregate);
240
+ for (const key of options.orderBy || []) {
241
+ if (!available.has(key.column))
242
+ throw new Error(`Relational order column not found: ${key.column}`);
84
243
  }
85
- if (isOptionalArrowType(arrowType, "LargeList")) {
86
- const largeListType = arrowType;
87
- return {
88
- type: "large-list",
89
- children: [serializeArrowField(largeListType.valueField)]
90
- };
244
+ for (const key of options.groupBy || []) {
245
+ if (!available.has(key)) throw new Error(`Relational group column not found: ${key}`);
91
246
  }
92
- switch (arrowType.constructor) {
93
- case arrow.Null:
94
- return "null";
95
- case arrow.Binary:
96
- return "binary";
97
- case arrow.FixedSizeBinary:
98
- return {
99
- type: "fixed-size-binary",
100
- byteWidth: arrowType.byteWidth
101
- };
102
- case arrow.Bool:
103
- return "bool";
104
- case arrow.Int:
105
- const intType = arrowType;
106
- return `${intType.isSigned ? "" : "u"}int${intType.bitWidth}`;
107
- case arrow.Int8:
108
- return "int8";
109
- case arrow.Int16:
110
- return "int16";
111
- case arrow.Int32:
112
- return "int32";
113
- case arrow.Int64:
114
- return "int64";
115
- case arrow.Uint8:
116
- return "uint8";
117
- case arrow.Uint16:
118
- return "uint16";
119
- case arrow.Uint32:
120
- return "uint32";
121
- case arrow.Uint64:
122
- return "uint64";
123
- case arrow.Float:
124
- const precision = arrowType.precision;
125
- switch (precision) {
126
- case arrow.Precision.HALF:
127
- return "float16";
128
- case arrow.Precision.SINGLE:
129
- return "float32";
130
- case arrow.Precision.DOUBLE:
131
- return "float64";
132
- default:
133
- return "float16";
134
- }
135
- case arrow.Float16:
136
- return "float16";
137
- case arrow.Float32:
138
- return "float32";
139
- case arrow.Float64:
140
- return "float64";
141
- case arrow.Utf8:
142
- return "utf8";
143
- case arrow.Decimal:
144
- const decimal = arrowType;
145
- return {
146
- type: "decimal",
147
- bitWidth: decimal.bitWidth,
148
- precision: decimal.precision,
149
- scale: decimal.scale
150
- };
151
- case arrow.Date_:
152
- const dateUnit = arrowType.unit;
153
- return dateUnit === arrow.DateUnit.DAY ? "date-day" : "date-millisecond";
154
- case arrow.DateDay:
155
- return "date-day";
156
- case arrow.DateMillisecond:
157
- return "date-millisecond";
158
- case arrow.Time:
159
- const timeUnit = arrowType.unit;
160
- switch (timeUnit) {
161
- case arrow.TimeUnit.SECOND:
162
- return "time-second";
163
- case arrow.TimeUnit.MILLISECOND:
164
- return "time-millisecond";
165
- case arrow.TimeUnit.MICROSECOND:
166
- return "time-microsecond";
167
- case arrow.TimeUnit.NANOSECOND:
168
- return "time-nanosecond";
169
- default:
170
- return "time-second";
171
- }
172
- case arrow.TimeMillisecond:
173
- return "time-millisecond";
174
- case arrow.TimeSecond:
175
- return "time-second";
176
- case arrow.TimeMicrosecond:
177
- return "time-microsecond";
178
- case arrow.TimeNanosecond:
179
- return "time-nanosecond";
180
- case arrow.Timestamp:
181
- const timeStampUnit = arrowType.unit;
182
- switch (timeStampUnit) {
183
- case arrow.TimeUnit.SECOND:
184
- return "timestamp-second";
185
- case arrow.TimeUnit.MILLISECOND:
186
- return "timestamp-millisecond";
187
- case arrow.TimeUnit.MICROSECOND:
188
- return "timestamp-microsecond";
189
- case arrow.TimeUnit.NANOSECOND:
190
- return "timestamp-nanosecond";
191
- default:
192
- return "timestamp-second";
193
- }
194
- case arrow.TimestampSecond:
195
- return "timestamp-second";
196
- case arrow.TimestampMillisecond:
197
- return "timestamp-millisecond";
198
- case arrow.TimestampMicrosecond:
199
- return "timestamp-microsecond";
200
- case arrow.TimestampNanosecond:
201
- return "timestamp-nanosecond";
202
- case arrow.Interval:
203
- const intervalUnit = arrowType.unit;
204
- switch (intervalUnit) {
205
- case arrow.IntervalUnit.DAY_TIME:
206
- return "interval-daytime";
207
- case arrow.IntervalUnit.YEAR_MONTH:
208
- return "interval-yearmonth";
209
- default:
210
- return "interval-daytime";
211
- }
212
- case arrow.IntervalDayTime:
213
- return "interval-daytime";
214
- case arrow.IntervalYearMonth:
215
- return "interval-yearmonth";
216
- case arrow.Map_:
217
- const mapType = arrowType;
218
- return {
219
- type: "map",
220
- keysSorted: mapType.keysSorted,
221
- children: mapType.children.map((arrowField) => serializeArrowField(arrowField))
222
- };
223
- case arrow.List:
224
- const listType = arrowType;
225
- const listField = listType.valueField;
226
- return {
227
- type: "list",
228
- children: [serializeArrowField(listField)]
229
- };
230
- case arrow.FixedSizeList:
231
- const fixedSizeList = arrowType;
232
- return {
233
- type: "fixed-size-list",
234
- listSize: fixedSizeList.listSize,
235
- children: [serializeArrowField(fixedSizeList.children[0])]
236
- };
237
- case arrow.Struct:
238
- const structType = arrowType;
239
- return {
240
- type: "struct",
241
- children: structType.children.map((arrowField) => serializeArrowField(arrowField))
242
- };
243
- case arrow.SparseUnion:
244
- case arrow.DenseUnion:
245
- const unionType = arrowType;
246
- return {
247
- type: unionType instanceof arrow.DenseUnion ? "dense-union" : "sparse-union",
248
- typeIds: unionType.typeIds,
249
- children: unionType.children.map((arrowField) => serializeArrowField(arrowField)),
250
- typeIdToChildIndex: { ...unionType.typeIdToChildIndex }
251
- };
252
- case arrow.Dictionary:
253
- const dictionaryType = arrowType;
254
- return {
255
- type: "dictionary",
256
- id: dictionaryType.id,
257
- indices: serializeArrowDictionaryKeyType(dictionaryType.indices),
258
- dictionary: serializeArrowType(dictionaryType.dictionary),
259
- isOrdered: dictionaryType.isOrdered
260
- };
261
- default:
262
- throw new Error(`arrow type not supported: ${arrowType.constructor.name}`);
263
- }
264
- }
265
- function deserializeArrowType(dataType, options) {
266
- if (typeof dataType === "object") {
267
- switch (dataType.type) {
268
- case "decimal":
269
- return new arrow.Decimal(dataType.scale, dataType.precision, dataType.bitWidth);
270
- case "map": {
271
- const children = dataType.children.map(
272
- (arrowField) => deserializeArrowField(arrowField, options)
273
- );
274
- return new arrow.Map_(children[0], dataType.keysSorted);
275
- }
276
- case "list": {
277
- const field = deserializeArrowField(dataType.children[0], options);
278
- return new arrow.List(field);
279
- }
280
- case "large-list": {
281
- const field = deserializeArrowField(dataType.children[0], options);
282
- const LargeList = getOptionalArrowConstructor("LargeList");
283
- if (!LargeList) {
284
- throw new Error(
285
- "LargeList requires an Apache Arrow runtime that exports the LargeList constructor"
286
- );
287
- }
288
- return new LargeList(field);
289
- }
290
- case "fixed-size-list": {
291
- const child = deserializeArrowField(dataType.children[0], options);
292
- return new arrow.FixedSizeList(dataType.listSize, child);
293
- }
294
- case "fixed-size-binary":
295
- return new arrow.FixedSizeBinary(dataType.byteWidth);
296
- case "struct": {
297
- const children = dataType.children.map(
298
- (arrowField) => deserializeArrowField(arrowField, options)
299
- );
300
- return new arrow.Struct(children);
301
- }
302
- case "sparse-union":
303
- case "dense-union": {
304
- const children = dataType.children.map(
305
- (arrowField) => deserializeArrowField(arrowField, options)
306
- );
307
- return dataType.type === "dense-union" ? new arrow.DenseUnion(dataType.typeIds, children) : new arrow.SparseUnion(dataType.typeIds, children);
308
- }
309
- case "dictionary": {
310
- return new arrow.Dictionary(
311
- deserializeArrowType(dataType.dictionary, options),
312
- deserializeArrowDictionaryKeyType(dataType.indices),
313
- dataType.id,
314
- dataType.isOrdered
315
- );
316
- }
317
- default:
318
- throw new Error("array type not supported");
247
+ for (const aggregate of options.aggregates || []) {
248
+ if (!aggregate.name) throw new Error("Relational aggregate names must be non-empty.");
249
+ if (aggregate.function !== "count" && !aggregate.column) {
250
+ throw new Error(`Relational aggregate ${aggregate.function} requires a column.`);
251
+ }
252
+ if (aggregate.column && !available.has(aggregate.column)) {
253
+ throw new Error(`Relational aggregate column not found: ${aggregate.column}`);
319
254
  }
320
255
  }
321
- switch (dataType) {
322
- case "null":
323
- return new arrow.Null();
324
- case "binary":
325
- return makeVariableWidthArrowType("BinaryView", new arrow.Binary(), options);
326
- case "binary-view":
327
- return makeRequiredArrowViewType("BinaryView");
328
- case "bool":
329
- return new arrow.Bool();
330
- case "int8":
331
- return new arrow.Int8();
332
- case "int16":
333
- return new arrow.Int16();
334
- case "int32":
335
- return new arrow.Int32();
336
- case "int64":
337
- return new arrow.Int64();
338
- case "uint8":
339
- return new arrow.Uint8();
340
- case "uint16":
341
- return new arrow.Uint16();
342
- case "uint32":
343
- return new arrow.Uint32();
344
- case "uint64":
345
- return new arrow.Uint64();
346
- case "float16":
347
- return new arrow.Float16();
348
- case "float32":
349
- return new arrow.Float32();
350
- case "float64":
351
- return new arrow.Float64();
352
- case "utf8":
353
- return makeVariableWidthArrowType("Utf8View", new arrow.Utf8(), options);
354
- case "utf8-view":
355
- return makeRequiredArrowViewType("Utf8View");
356
- case "date-day":
357
- return new arrow.DateDay();
358
- case "date-millisecond":
359
- return new arrow.DateMillisecond();
360
- case "time-second":
361
- return new arrow.TimeSecond();
362
- case "time-millisecond":
363
- return new arrow.TimeMillisecond();
364
- case "time-microsecond":
365
- return new arrow.TimeMicrosecond();
366
- case "time-nanosecond":
367
- return new arrow.TimeNanosecond();
368
- case "timestamp-second":
369
- return new arrow.TimestampSecond();
370
- case "timestamp-millisecond":
371
- return new arrow.TimestampMillisecond();
372
- case "timestamp-microsecond":
373
- return new arrow.TimestampMicrosecond();
374
- case "timestamp-nanosecond":
375
- return new arrow.TimestampNanosecond();
376
- case "interval-daytime":
377
- return new arrow.IntervalDayTime();
378
- case "interval-yearmonth":
379
- return new arrow.IntervalYearMonth();
380
- default:
381
- throw new Error("array type not supported");
256
+ const relationalSteps = [];
257
+ if ((_b = options.expressions) == null ? void 0 : _b.length)
258
+ relationalSteps.push({ kind: "expression", detail: options.expressions });
259
+ if ((_c = options.orderBy) == null ? void 0 : _c.length) relationalSteps.push({ kind: "order", detail: options.orderBy });
260
+ if (((_d = options.aggregates) == null ? void 0 : _d.length) || ((_e = options.groupBy) == null ? void 0 : _e.length)) {
261
+ relationalSteps.push({
262
+ kind: "aggregate",
263
+ detail: { groupBy: options.groupBy, aggregates: options.aggregates }
264
+ });
382
265
  }
266
+ if ((_f = options.union) == null ? void 0 : _f.length) relationalSteps.push({ kind: "union", detail: options.union });
267
+ if (options.join) relationalSteps.push({ kind: "join", detail: options.join });
268
+ return { tablePlan, relationalSteps: Object.freeze(relationalSteps) };
383
269
  }
384
- function getOptionalArrowConstructor(typeName) {
385
- return arrow[typeName];
270
+ function validateRelationalColumnReference(columnName, availableColumns) {
271
+ if (!availableColumns.has(columnName)) {
272
+ throw new Error(`Relational expression column not found: ${columnName}`);
273
+ }
386
274
  }
387
- function isArrowViewType(arrowType, viewTypeName) {
388
- const constructor = getOptionalArrowConstructor(viewTypeName);
389
- if (constructor && arrowType instanceof constructor) {
390
- return true;
275
+ var init_relational_query = __esm({
276
+ "src/loader-utils/lib/scan-utils/relational-query.ts"() {
277
+ "use strict";
278
+ init_table_query();
391
279
  }
392
- const guards = arrow.DataType;
393
- const guard = viewTypeName === "BinaryView" ? guards.isBinaryView : guards.isUtf8View;
394
- return Boolean(guard == null ? void 0 : guard(arrowType));
280
+ });
281
+
282
+ // src/loader-utils/lib/scan-utils/table-query-explain.ts
283
+ function explainTableQuery(sourceColumnNames, options, capabilities) {
284
+ const plan = planTableQuery(sourceColumnNames, options);
285
+ const outputColumns = options.columns ? [...options.columns] : [...sourceColumnNames];
286
+ const predicateColumns = options.predicate ? (0, import_columnar_predicate2.getColumnarPredicateColumns)(options.predicate) : [];
287
+ const requiredColumns = [...plan[0].kind === "scan" ? plan[0].columns : []];
288
+ return Object.freeze({
289
+ sourceColumns: Object.freeze([...sourceColumnNames]),
290
+ outputColumns: Object.freeze(outputColumns),
291
+ requiredColumns: Object.freeze(requiredColumns),
292
+ predicateColumns: Object.freeze(predicateColumns),
293
+ plan,
294
+ capabilities: Object.freeze({ ...capabilities }),
295
+ operators: Object.freeze({
296
+ projection: createOperatorExplanation(options.columns !== void 0, capabilities.projection),
297
+ predicate: createOperatorExplanation(options.predicate !== void 0, capabilities.predicate),
298
+ limit: createOperatorExplanation(options.limit !== void 0, capabilities.limit)
299
+ })
300
+ });
395
301
  }
396
- function isOptionalArrowType(arrowType, typeName) {
397
- const constructor = getOptionalArrowConstructor(typeName);
398
- return Boolean(constructor && arrowType instanceof constructor);
302
+ function createOperatorExplanation(enabled, support) {
303
+ return Object.freeze({ enabled, support });
399
304
  }
400
- function makeVariableWidthArrowType(viewTypeName, fallbackType, options) {
401
- const viewTypeMode = (options == null ? void 0 : options.viewTypes) || "never";
402
- if (viewTypeMode === "never") {
403
- return fallbackType;
404
- }
405
- const constructor = getOptionalArrowConstructor(viewTypeName);
406
- if (constructor) {
407
- return new constructor();
305
+ var init_table_query_explain = __esm({
306
+ "src/loader-utils/lib/scan-utils/table-query-explain.ts"() {
307
+ "use strict";
308
+ init_columnar_predicate();
309
+ init_table_query();
408
310
  }
409
- if (viewTypeMode === "require") {
410
- throw new Error(
411
- `${viewTypeName} requires apache-arrow 21.2.0 or later; the installed runtime does not support it`
412
- );
311
+ });
312
+
313
+ // src/loader-utils/index.ts
314
+ var init_loader_utils = __esm({
315
+ "src/loader-utils/index.ts"() {
316
+ "use strict";
317
+ init_columnar_predicate();
318
+ init_relational_query();
319
+ init_scan_query_metadata();
320
+ init_table_query();
321
+ init_table_query_explain();
413
322
  }
414
- return fallbackType;
415
- }
416
- function makeRequiredArrowViewType(viewTypeName) {
417
- const constructor = getOptionalArrowConstructor(viewTypeName);
418
- if (!constructor) {
419
- throw new Error(
420
- `${viewTypeName} requires apache-arrow 21.2.0 or later; the installed runtime does not support it`
421
- );
323
+ });
324
+
325
+ // dist/scan/table-query-capabilities.js
326
+ var ARROW_TABLE_QUERY_CAPABILITIES, SQL_DATA_SOURCE_TABLE_QUERY_CAPABILITIES;
327
+ var init_table_query_capabilities = __esm({
328
+ "dist/scan/table-query-capabilities.js"() {
329
+ "use strict";
330
+ ARROW_TABLE_QUERY_CAPABILITIES = Object.freeze({
331
+ projection: "residual",
332
+ predicate: "residual",
333
+ limit: "residual",
334
+ streaming: false,
335
+ cancellation: true,
336
+ expressions: "residual",
337
+ orderBy: "residual",
338
+ aggregates: "residual"
339
+ });
340
+ SQL_DATA_SOURCE_TABLE_QUERY_CAPABILITIES = Object.freeze({
341
+ projection: "pushdown",
342
+ predicate: "pushdown",
343
+ limit: "pushdown",
344
+ streaming: false,
345
+ cancellation: false,
346
+ expressions: "pushdown",
347
+ orderBy: "pushdown",
348
+ aggregates: "pushdown"
349
+ });
422
350
  }
423
- return new constructor();
351
+ });
352
+
353
+ // dist/scan/arrow-execution/filter-arrow-table.js
354
+ function filterArrowTable(source, predicate, options = {}) {
355
+ (0, import_columnar_predicate2.validateColumnarPredicate)(predicate, new Set(source.schema.fields.map((field) => field.name)));
356
+ const boundPredicate = normalizeArrowDatePredicate(predicate);
357
+ return filterArrowRows(source, (batch) => {
358
+ const evaluate = (0, import_columnar_predicate6.compileColumnarPredicate)(boundPredicate, (path) => bindPredicateColumn(batch, path));
359
+ return (rowIndex) => evaluate(rowIndex) === true;
360
+ }, options);
424
361
  }
425
- function serializeArrowDictionaryKeyType(arrowType) {
426
- if (arrowType instanceof arrow.Int) {
427
- const prefix = arrowType.isSigned ? "int" : "uint";
428
- const keyType = `${prefix}${arrowType.bitWidth}`;
429
- if (isSchemaDictionaryKeyType(keyType)) {
430
- return keyType;
362
+ function bindPredicateColumn(batch, [name, ...properties]) {
363
+ const column = batch.getChild(name);
364
+ if (!column)
365
+ throw new Error(`Arrow query column not found: ${name}`);
366
+ return (rowIndex) => {
367
+ let value = column.get(rowIndex);
368
+ for (const property of properties) {
369
+ if (value == null)
370
+ return null;
371
+ value = value[property];
431
372
  }
432
- }
433
- switch (arrowType.constructor) {
434
- case arrow.Int8:
435
- return "int8";
436
- case arrow.Int16:
437
- return "int16";
438
- case arrow.Int32:
439
- return "int32";
440
- case arrow.Uint8:
441
- return "uint8";
442
- case arrow.Uint16:
443
- return "uint16";
444
- case arrow.Uint32:
445
- return "uint32";
446
- default:
447
- throw new Error(`arrow dictionary index type not supported: ${arrowType.constructor.name}`);
448
- }
449
- }
450
- function isSchemaDictionaryKeyType(keyType) {
451
- return ["int8", "int16", "int32", "uint8", "uint16", "uint32"].includes(keyType);
373
+ return dateToMilliseconds(value);
374
+ };
452
375
  }
453
- function deserializeArrowDictionaryKeyType(keyType) {
454
- switch (keyType) {
455
- case "int8":
456
- return new arrow.Int8();
457
- case "int16":
458
- return new arrow.Int16();
459
- case "int32":
460
- return new arrow.Int32();
461
- case "uint8":
462
- return new arrow.Uint8();
463
- case "uint16":
464
- return new arrow.Uint16();
465
- case "uint32":
466
- return new arrow.Uint32();
376
+ function normalizeArrowDatePredicate(predicate) {
377
+ switch (predicate.op) {
378
+ case "and":
379
+ case "or":
380
+ return { ...predicate, args: predicate.args.map(normalizeArrowDatePredicate) };
381
+ case "not":
382
+ return { ...predicate, args: [normalizeArrowDatePredicate(predicate.args[0])] };
383
+ case "isNull":
384
+ return predicate;
385
+ case "in":
386
+ return { ...predicate, args: [predicate.args[0], predicate.args[1].map(dateToMilliseconds)] };
467
387
  default:
468
- throw new Error(`schema dictionary index type not supported: ${keyType}`);
388
+ return { ...predicate, args: [predicate.args[0], dateToMilliseconds(predicate.args[1])] };
469
389
  }
470
390
  }
471
-
472
- // src/schema-utils/lib/arrow/arrow-metadata.ts
473
- var arrow2 = __toESM(require("apache-arrow"), 1);
474
- function snapshotArrowSchema(schema) {
475
- return deserializeArrowSchema(serializeArrowSchema(schema));
391
+ function dateToMilliseconds(value) {
392
+ return value instanceof Date ? value.getTime() : value;
476
393
  }
477
- function makeArrowMetadataBatch(schema) {
478
- return new arrow2.RecordBatch(snapshotArrowSchema(schema), void 0);
394
+ function filterArrowRows(source, selectBatch, options = {}) {
395
+ var _a, _b, _c;
396
+ let remaining = options.limit ?? Infinity;
397
+ if (remaining !== Infinity && (!Number.isSafeInteger(remaining) || remaining < 0)) {
398
+ throw new Error("Arrow filter limit must be a non-negative safe integer.");
399
+ }
400
+ (_a = options.signal) == null ? void 0 : _a.throwIfAborted();
401
+ const batches = [];
402
+ for (const batch of source.batches) {
403
+ if (remaining === 0)
404
+ break;
405
+ (_b = options.signal) == null ? void 0 : _b.throwIfAborted();
406
+ const selectRow = selectBatch(batch);
407
+ const indices = [];
408
+ for (let rowIndex = 0; rowIndex < batch.numRows && indices.length < remaining; rowIndex++) {
409
+ (_c = options.signal) == null ? void 0 : _c.throwIfAborted();
410
+ if (selectRow(rowIndex))
411
+ indices.push(rowIndex);
412
+ }
413
+ remaining -= indices.length;
414
+ const selected = (0, import_arrow2.selectArrowBatchRows)(batch, indices);
415
+ if (selected)
416
+ batches.push(selected);
417
+ }
418
+ return new arrow3.Table(source.schema, batches);
479
419
  }
420
+ var arrow3, import_arrow2, import_columnar_predicate6;
421
+ var init_filter_arrow_table = __esm({
422
+ "dist/scan/arrow-execution/filter-arrow-table.js"() {
423
+ "use strict";
424
+ arrow3 = __toESM(require("apache-arrow"), 1);
425
+ import_arrow2 = require("@math.gl/core/arrow");
426
+ import_columnar_predicate6 = require("@math.gl/sql/columnar-predicate");
427
+ init_loader_utils();
428
+ }
429
+ });
480
430
 
481
- // dist/lib/loader-utils/native-arrow.js
482
- function isArrowTable(value) {
483
- return Boolean(value && typeof value === "object" && "schema" in value && "batches" in value && Array.isArray(value.batches) && "numRows" in value && typeof value.numRows === "number" && "getChildAt" in value && typeof value.getChildAt === "function");
484
- }
431
+ // dist/scan/arrow-execution.js
432
+ var import_arrow3;
433
+ var init_arrow_execution = __esm({
434
+ "dist/scan/arrow-execution.js"() {
435
+ "use strict";
436
+ import_arrow3 = require("@math.gl/core/arrow");
437
+ init_filter_arrow_table();
438
+ }
439
+ });
485
440
 
486
- // src/loader-utils/lib/scan-utils/columnar-predicate.ts
487
- function getColumnarPredicateColumns(predicate) {
488
- return [...new Set(getColumnarPredicatePaths(predicate).map((path) => path[0]))];
441
+ // dist/scan/sql-predicate-schema.js
442
+ function validateSQLPredicate(value) {
443
+ (0, import_parser.validateSQLPredicate)(value);
444
+ rejectPredicateCasts(value, "$");
489
445
  }
490
- function getColumnarPredicatePath(property) {
491
- return typeof property.property === "string" ? [property.property] : [...property.property];
446
+ function rejectPredicateCasts(predicate, path) {
447
+ if (predicate.op === "and" || predicate.op === "or" || predicate.op === "not") {
448
+ predicate.args.forEach((child, index) => rejectPredicateCasts(child, path + ".args[" + index + "]"));
449
+ } else if (Object.hasOwn(predicate.args[0], "casts")) {
450
+ throw new Error("SQL predicate " + path + ".args[0] requires a non-empty property reference");
451
+ }
492
452
  }
493
- function getColumnarPredicatePaths(predicate) {
494
- const paths = /* @__PURE__ */ new Map();
495
- visitColumnarPredicate(predicate, (child) => {
496
- if ("property" in child.args[0]) {
497
- const path = getColumnarPredicatePath(child.args[0]);
498
- paths.set(path.join("\0"), path);
499
- }
500
- });
501
- return [...paths.values()];
453
+ var import_parser;
454
+ var init_sql_predicate_schema = __esm({
455
+ "dist/scan/sql-predicate-schema.js"() {
456
+ "use strict";
457
+ import_parser = require("@math.gl/sql/parser");
458
+ }
459
+ });
460
+
461
+ // dist/scan/table-query.js
462
+ function planTableQuery2(sourceColumnNames, options = {}) {
463
+ if (options.predicate) {
464
+ validateSQLPredicate(options.predicate);
465
+ }
466
+ return planTableQuery(sourceColumnNames, options);
502
467
  }
503
- function validateColumnarPredicate(predicate, availableColumns) {
504
- visitColumnarPredicate(predicate, (child) => {
505
- if (child.op === "and" || child.op === "or") {
506
- if (child.args.length < 2)
507
- throw new Error(`Columnar predicate ${child.op} requires at least two child predicates`);
508
- return;
468
+ var init_table_query2 = __esm({
469
+ "dist/scan/table-query.js"() {
470
+ "use strict";
471
+ init_loader_utils();
472
+ init_sql_predicate_schema();
473
+ }
474
+ });
475
+
476
+ // dist/scan/plan-arrow-table-query.js
477
+ function explainArrowTableQuery(sourceTable, options = {}) {
478
+ if (options.select !== void 0) {
479
+ if (options.columns !== void 0 || hasRelationalOperators(options) || options.join) {
480
+ throw new Error("Arrow select cannot be combined with columns or relational operators.");
509
481
  }
510
- if (child.op === "not") return;
511
- const leaf = child;
512
- const path = getColumnarPredicatePath(leaf.args[0]);
513
- if (!path.length || path.some((component) => !component)) {
514
- throw new Error("Columnar predicate property path must contain non-empty strings");
482
+ const projected = (0, import_arrow3.projectArrowTable)(sourceTable, options.select);
483
+ const columns = [
484
+ ...new Set(options.select.map((selection) => typeof selection === "string" ? selection : selection.column))
485
+ ];
486
+ const { select, ...remainingOptions } = options;
487
+ const explanation = explainArrowTableQuery(sourceTable, { ...remainingOptions, columns });
488
+ const outputColumns = Object.freeze(projected.schema.fields.map((field) => field.name));
489
+ return Object.freeze({
490
+ ...explanation,
491
+ outputColumns,
492
+ plan: Object.freeze(explanation.plan.map((step) => step.kind === "project" ? Object.freeze({ ...step, columns: outputColumns, select }) : step))
493
+ });
494
+ }
495
+ if (options.predicate) {
496
+ validateSQLPredicate(options.predicate);
497
+ }
498
+ return explainTableQuery(sourceTable.schema.fields.map((field) => field.name), options, ARROW_TABLE_QUERY_CAPABILITIES);
499
+ }
500
+ function queryArrowTable(sourceTable, options = {}, execute) {
501
+ throwIfAborted(options.signal);
502
+ if (options.select !== void 0) {
503
+ if (options.columns !== void 0 || hasRelationalOperators(options) || options.join) {
504
+ throw new Error("Arrow select cannot be combined with columns or relational operators.");
515
505
  }
516
- if (!availableColumns.has(path[0]))
517
- throw new Error(`Columnar predicate column not found: ${path.join(".")}`);
518
- if (leaf.op === "in" && leaf.args[1].length === 0) {
519
- throw new Error("Columnar predicate in requires at least one value");
506
+ return (execute ?? executePortableArrowQuery)(sourceTable, {
507
+ where: options.predicate,
508
+ select: options.select,
509
+ limit: options.limit,
510
+ signal: options.signal
511
+ });
512
+ }
513
+ if (options.join || hasRelationalOperators(options)) {
514
+ if (options.join) {
515
+ validateArrowJoinQuery(sourceTable, options);
516
+ if (hasRelationalOperators(options)) {
517
+ throw new Error("Arrow joins cannot yet be combined with other relational operators.");
518
+ }
520
519
  }
520
+ if (!execute)
521
+ throw new Error("Relational queries require the SQL executor.");
522
+ return options.join ? queryArrowJoin(sourceTable, options, execute) : queryArrowTableRelational(sourceTable, options, execute);
523
+ }
524
+ const plan = planTableQuery2(sourceTable.schema.fields.map((field) => field.name), options);
525
+ const projection = plan.find((step) => step.kind === "project");
526
+ return (execute ?? executePortableArrowQuery)(sourceTable, {
527
+ where: options.predicate,
528
+ select: projection == null ? void 0 : projection.columns,
529
+ limit: options.limit,
530
+ signal: options.signal
531
+ });
532
+ }
533
+ function queryArrowTableRelational(sourceTable, options, execute) {
534
+ var _a, _b, _c;
535
+ const sourceColumns = sourceTable.schema.fields.map((field) => field.name);
536
+ const grouped = ((_a = options.groupBy) == null ? void 0 : _a.length) || ((_b = options.aggregates) == null ? void 0 : _b.length);
537
+ const outputColumns = options.columns ?? (grouped ? [...options.groupBy ?? [], ...(options.aggregates ?? []).map((aggregate) => aggregate.name)] : sourceColumns);
538
+ const plan = planRelationalQuery(sourceColumns, { ...options, columns: outputColumns });
539
+ const scan = plan.tablePlan.find((step) => step.kind === "scan");
540
+ let table = execute(sourceTable, {
541
+ where: options.predicate,
542
+ select: scan.columns,
543
+ signal: options.signal
544
+ });
545
+ if ((_c = options.union) == null ? void 0 : _c.length) {
546
+ const childPlan = planRelationalQuery(sourceColumns, {
547
+ ...options,
548
+ columns: outputColumns,
549
+ predicate: void 0
550
+ });
551
+ const columns = childPlan.tablePlan.find((step) => step.kind === "scan").columns;
552
+ const union = options.union.map((child) => {
553
+ var _a2;
554
+ const input = (_a2 = options.tables) == null ? void 0 : _a2[child.source];
555
+ if (!input)
556
+ throw new Error("Arrow union source not found: " + child.source);
557
+ return queryArrowTable(input, { ...child.query, columns, signal: options.signal }, execute);
558
+ });
559
+ table = execute((0, import_arrow3.projectArrowTable)(table, columns), { union, signal: options.signal });
560
+ }
561
+ for (const { name, expression } of options.expressions ?? []) {
562
+ const select = [
563
+ ...table.schema.fields.map((field) => field.name),
564
+ expression.op === "column" ? { column: expression.column, as: name } : { expression: toArrowExpression(expression), as: name }
565
+ ];
566
+ table = execute(table, { select, signal: options.signal });
567
+ }
568
+ return execute(table, {
569
+ select: outputColumns,
570
+ groupBy: options.groupBy,
571
+ aggregates: Object.fromEntries((options.aggregates ?? []).map((aggregate) => {
572
+ const expression = aggregate.column === void 0 ? void 0 : identifier(aggregate.column);
573
+ if (aggregate.function === "count")
574
+ return [aggregate.name, { operation: "COUNT", expression }];
575
+ const operations = { sum: "SUM", min: "MIN", max: "MAX", avg: "AVG" };
576
+ return [
577
+ aggregate.name,
578
+ { operation: operations[aggregate.function], expression }
579
+ ];
580
+ })),
581
+ orderBy: options.orderBy,
582
+ limit: options.limit,
583
+ signal: options.signal
521
584
  });
522
585
  }
523
- function isColumnarPredicateParameter(value) {
524
- const parameterValue = value;
525
- return typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length === 1 && Object.hasOwn(value, "parameter") && typeof parameterValue.parameter === "string" && parameterValue.parameter.length > 0;
586
+ function identifier(name) {
587
+ return { type: "Identifier", name };
588
+ }
589
+ function toArrowExpression(expression) {
590
+ if (expression.op === "literal")
591
+ return literal(expression.value);
592
+ const operators = { add: "+", subtract: "-", multiply: "*", divide: "/" };
593
+ const binary = {
594
+ type: "BinaryExpression",
595
+ operator: operators[expression.op],
596
+ left: identifier(expression.left),
597
+ right: identifier(expression.right)
598
+ };
599
+ if (expression.op !== "divide")
600
+ return binary;
601
+ return {
602
+ type: "ConditionalExpression",
603
+ test: { ...binary, operator: "===", left: binary.right, right: literal(0) },
604
+ consequent: literal(null),
605
+ alternate: binary
606
+ };
526
607
  }
527
- function visitColumnarPredicate(predicate, visitor) {
528
- visitor(predicate);
529
- if (predicate.op === "and" || predicate.op === "or")
530
- predicate.args.forEach((child) => visitColumnarPredicate(child, visitor));
531
- else if (predicate.op === "not") visitColumnarPredicate(predicate.args[0], visitor);
608
+ function literal(value) {
609
+ return { type: "Literal", value };
532
610
  }
533
-
534
- // src/loader-utils/lib/scan-utils/scan-query-metadata.ts
535
- var import_crs = require("@math.gl/geospatial/crs");
536
- function createScanQueryMetadata(options) {
537
- validateScanExecutionSupport(options.queryType, options.execution);
538
- const schema = Object.freeze({
539
- fields: Object.freeze(
540
- options.schema.fields.map(
541
- (field) => Object.freeze({ ...field, metadata: Object.freeze({ ...field.metadata }) })
542
- )
543
- ),
544
- metadata: Object.freeze({ ...options.schema.metadata })
611
+ function hasRelationalOperators(options) {
612
+ var _a, _b, _c, _d, _e;
613
+ return Boolean(((_a = options.expressions) == null ? void 0 : _a.length) || ((_b = options.orderBy) == null ? void 0 : _b.length) || ((_c = options.groupBy) == null ? void 0 : _c.length) || ((_d = options.aggregates) == null ? void 0 : _d.length) || ((_e = options.union) == null ? void 0 : _e.length));
614
+ }
615
+ function queryArrowJoin(sourceTable, options, executeRelational) {
616
+ var _a, _b, _c, _d;
617
+ const join = options.join;
618
+ const childTable = (_a = options.tables) == null ? void 0 : _a[join.child.source];
619
+ if (!childTable)
620
+ throw new Error(`Arrow join source not found: ${join.child.source}`);
621
+ const left = executeRelational(sourceTable, {
622
+ where: options.predicate,
623
+ signal: options.signal
545
624
  });
546
- const columns = schema.fields.map(
547
- (field) => {
548
- var _a;
549
- return Object.freeze({
550
- name: field.name,
551
- type: field.type,
552
- nullable: field.nullable !== false,
553
- role: ((_a = options.columnRoles) == null ? void 0 : _a[field.name]) || "attribute",
554
- title: getNonEmptyMetadataValue(field.metadata, "title"),
555
- description: getNonEmptyMetadataValue(field.metadata, "description"),
556
- metadata: field.metadata || Object.freeze({})
557
- });
558
- }
559
- );
560
- const queryCapabilities = Object.freeze({ ...options.capabilities });
561
- return Object.freeze({
562
- sourceType: options.sourceType,
563
- queryType: options.queryType,
564
- execution: Object.freeze({ ...options.execution }),
565
- name: options.name,
566
- description: options.description,
567
- schema,
568
- columns: Object.freeze(columns),
569
- capabilities: queryCapabilities,
570
- queryCapabilities,
571
- ...options.hasDefaultRowWindow ? { hasDefaultRowWindow: true } : {},
572
- spatial: options.spatial ? Object.freeze({
573
- ...options.spatial,
574
- bounds: options.spatial.bounds ? Object.freeze({
575
- minimum: Object.freeze([...options.spatial.bounds.minimum]),
576
- maximum: Object.freeze([...options.spatial.bounds.maximum])
577
- }) : void 0,
578
- coordinateReferenceSystems: options.spatial.coordinateReferenceSystems ? Object.freeze([...options.spatial.coordinateReferenceSystems]) : void 0,
579
- spatialReference: options.spatial.spatialReference ? (0, import_crs.createSpatialReference)(options.spatial.spatialReference) : void 0
580
- }) : void 0,
581
- statistics: options.statistics ? Object.freeze({ ...options.statistics }) : void 0,
582
- levels: options.levels ? Object.freeze(
583
- options.levels.map(
584
- (level) => Object.freeze({
585
- ...level,
586
- scale: level.scale ? Object.freeze([...level.scale]) : void 0
587
- })
588
- )
589
- ) : void 0
625
+ const right = executeRelational(childTable, {
626
+ where: (_b = join.child.query) == null ? void 0 : _b.predicate,
627
+ select: (_c = join.child.query) == null ? void 0 : _c.columns,
628
+ limit: (_d = join.child.query) == null ? void 0 : _d.limit,
629
+ signal: options.signal
630
+ });
631
+ return executeRelational(left, {
632
+ join: {
633
+ table: right,
634
+ type: join.type,
635
+ left: join.left,
636
+ right: join.right,
637
+ rightPrefix: `${join.child.source}.`
638
+ },
639
+ select: options.columns,
640
+ limit: options.limit,
641
+ signal: options.signal
590
642
  });
591
643
  }
592
- function validateScanExecutionSupport(queryType, execution) {
593
- if (execution.status === "metadata-only") {
594
- if (!execution.reason.trim()) {
595
- throw new Error("Metadata-only scan support requires a concrete reason");
596
- }
644
+ function validateArrowJoinQuery(sourceTable, options) {
645
+ var _a, _b, _c;
646
+ const join = options.join;
647
+ if (!join)
597
648
  return;
649
+ const sourceColumnNames = sourceTable.schema.fields.map((field) => field.name);
650
+ const childTable = (_a = options.tables) == null ? void 0 : _a[join.child.source];
651
+ if (!childTable)
652
+ throw new Error(`Arrow join source not found: ${join.child.source}`);
653
+ const childColumnNames = childTable.schema.fields.map((field) => field.name);
654
+ if (!sourceColumnNames.includes(join.left)) {
655
+ throw new Error(`Arrow join column not found: ${join.left}`);
598
656
  }
599
- const validMethods = {
600
- table: ["read", "query"],
601
- raster: ["getRaster"],
602
- "point-cloud": ["scan"]
603
- };
604
- if (!validMethods[queryType].includes(execution.method)) {
605
- throw new Error(
606
- `Scan execution method "${execution.method}" is not valid for ${queryType} queries`
607
- );
657
+ if (!childColumnNames.includes(join.right)) {
658
+ throw new Error(`Arrow join column not found: ${join.right}`);
659
+ }
660
+ const childPrefix = `${join.child.source}.`;
661
+ const rootColumns = (_b = options.columns) == null ? void 0 : _b.filter((column) => !column.startsWith(childPrefix));
662
+ planTableQuery2(sourceColumnNames, {
663
+ predicate: options.predicate,
664
+ columns: (rootColumns == null ? void 0 : rootColumns.length) ? rootColumns : void 0,
665
+ limit: options.limit,
666
+ signal: options.signal
667
+ });
668
+ const childQuery = join.child.query || {};
669
+ planTableQuery2(childColumnNames, childQuery);
670
+ const childOutputColumns = childQuery.columns || childColumnNames;
671
+ if (!childOutputColumns.includes(join.right)) {
672
+ throw new Error(`Arrow join child projection must include: ${join.right}`);
673
+ }
674
+ const projectedChildColumns = ((_c = options.columns) == null ? void 0 : _c.filter((column) => column.startsWith(childPrefix))) || [];
675
+ const seenChildColumns = /* @__PURE__ */ new Set();
676
+ for (const projectedColumn of projectedChildColumns) {
677
+ const childColumn = projectedColumn.slice(childPrefix.length);
678
+ if (!childColumnNames.includes(childColumn)) {
679
+ throw new Error(`Arrow join column not found: ${projectedColumn}`);
680
+ }
681
+ if (seenChildColumns.has(childColumn)) {
682
+ throw new Error(`Arrow query column was selected more than once: ${projectedColumn}`);
683
+ }
684
+ seenChildColumns.add(childColumn);
685
+ if (!childOutputColumns.includes(childColumn)) {
686
+ throw new Error(`Arrow join child projection does not include: ${childColumn}`);
687
+ }
608
688
  }
609
689
  }
610
- function getNonEmptyMetadataValue(metadata, key) {
611
- const value = metadata == null ? void 0 : metadata[key];
612
- return value || void 0;
690
+ function throwIfAborted(signal) {
691
+ if (signal == null ? void 0 : signal.aborted) {
692
+ const error = new Error("Arrow query was aborted.");
693
+ error.name = "AbortError";
694
+ throw error;
695
+ }
613
696
  }
697
+ var executePortableArrowQuery;
698
+ var init_plan_arrow_table_query = __esm({
699
+ "dist/scan/plan-arrow-table-query.js"() {
700
+ "use strict";
701
+ init_arrow_execution();
702
+ init_table_query2();
703
+ init_loader_utils();
704
+ init_table_query_capabilities();
705
+ init_sql_predicate_schema();
706
+ executePortableArrowQuery = (table, { select, where, limit, signal }) => {
707
+ if (where)
708
+ table = filterArrowTable(table, where, { limit, signal });
709
+ const projected = select ? (0, import_arrow3.projectArrowTable)(table, select) : table;
710
+ return projected.numRows === 0 || limit === void 0 ? projected : projected.slice(0, limit);
711
+ };
712
+ }
713
+ });
614
714
 
615
- // src/loader-utils/lib/scan-utils/table-query.ts
616
- function planTableQuery(sourceColumnNames, options = {}) {
617
- validateTableQueryOptions(sourceColumnNames, options);
618
- const outputColumnNames = options.columns ? [...options.columns] : [...sourceColumnNames];
619
- const predicateColumnNames = options.predicate ? getColumnarPredicateColumns(options.predicate) : [];
620
- const requiredColumnNames = /* @__PURE__ */ new Set([...outputColumnNames, ...predicateColumnNames]);
621
- const scanColumnNames = sourceColumnNames.filter(
622
- (columnName) => requiredColumnNames.has(columnName)
623
- );
624
- const steps = [
625
- Object.freeze({ kind: "scan", columns: Object.freeze(scanColumnNames) })
626
- ];
627
- if (options.predicate) {
628
- steps.push(Object.freeze({ kind: "filter", predicate: options.predicate }));
715
+ // dist/scan/query-arrow-table.js
716
+ var query_arrow_table_exports = {};
717
+ __export(query_arrow_table_exports, {
718
+ ARROW_TABLE_QUERY_CAPABILITIES: () => ARROW_TABLE_QUERY_CAPABILITIES,
719
+ explainArrowTableQuery: () => explainArrowTableQuery,
720
+ queryArrowTable: () => queryArrowTable2
721
+ });
722
+ function queryArrowTable2(source, options) {
723
+ return queryArrowTable(source, options, import_query.queryArrowTable);
724
+ }
725
+ var import_query;
726
+ var init_query_arrow_table = __esm({
727
+ "dist/scan/query-arrow-table.js"() {
728
+ "use strict";
729
+ import_query = require("@math.gl/sql/query");
730
+ init_plan_arrow_table_query();
731
+ init_plan_arrow_table_query();
629
732
  }
630
- steps.push(Object.freeze({ kind: "project", columns: Object.freeze(outputColumnNames) }));
631
- if (options.limit !== void 0) {
632
- steps.push(Object.freeze({ kind: "limit", limit: options.limit }));
633
- }
634
- return Object.freeze(steps);
635
- }
636
- function validateTableQueryOptions(sourceColumnNames, options) {
637
- const availableColumnNames = new Set(sourceColumnNames);
638
- const outputColumnNames = options.columns ?? sourceColumnNames;
639
- const seenColumnNames = /* @__PURE__ */ new Set();
640
- for (const columnName of outputColumnNames) {
641
- if (!availableColumnNames.has(columnName)) {
642
- throw new Error(`Table query column not found: ${columnName}`);
643
- }
644
- if (seenColumnNames.has(columnName)) {
645
- throw new Error(`Table query column was selected more than once: ${columnName}`);
646
- }
647
- seenColumnNames.add(columnName);
648
- }
649
- validateTableQueryLimit(options.limit);
650
- if (options.predicate) {
651
- validateColumnarPredicate(options.predicate, availableColumnNames);
652
- }
653
- }
654
- function validateTableQueryLimit(limit) {
655
- if (limit !== void 0 && (!Number.isSafeInteger(limit) || limit < 0)) {
656
- throw new Error("Table query limit must be a non-negative safe integer.");
657
- }
658
- }
659
-
660
- // src/loader-utils/lib/scan-utils/relational-query.ts
661
- function planRelationalQuery(sourceColumnNames, options = {}) {
662
- var _a, _b, _c, _d, _e, _f;
663
- const available = new Set(sourceColumnNames);
664
- const expressionNames = /* @__PURE__ */ new Set();
665
- for (const expression of options.expressions || []) {
666
- if (!expression.name) throw new Error("Relational expression names must be non-empty.");
667
- if (available.has(expression.name) || expressionNames.has(expression.name)) {
668
- throw new Error(`Relational expression duplicates column: ${expression.name}`);
669
- }
670
- expressionNames.add(expression.name);
671
- }
672
- const aggregateNames = new Set((options.aggregates || []).map((aggregate) => aggregate.name));
673
- const requiredColumns = /* @__PURE__ */ new Set();
674
- const availableColumns = new Set(sourceColumnNames);
675
- for (const expression of options.expressions || []) {
676
- const definition = expression.expression;
677
- if (definition.op === "column") {
678
- validateRelationalColumnReference(definition.column, availableColumns);
679
- if (available.has(definition.column)) requiredColumns.add(definition.column);
680
- }
681
- if ("left" in definition) {
682
- validateRelationalColumnReference(definition.left, availableColumns);
683
- validateRelationalColumnReference(definition.right, availableColumns);
684
- if (available.has(definition.left)) requiredColumns.add(definition.left);
685
- if (available.has(definition.right)) requiredColumns.add(definition.right);
686
- }
687
- availableColumns.add(expression.name);
688
- }
689
- for (const key of options.orderBy || []) requiredColumns.add(key.column);
690
- for (const key of options.groupBy || []) requiredColumns.add(key);
691
- for (const aggregate of options.aggregates || []) {
692
- if (aggregate.column) requiredColumns.add(aggregate.column);
693
- }
694
- const outputColumns = (_a = options.columns) == null ? void 0 : _a.filter(
695
- (column) => !expressionNames.has(column) && !aggregateNames.has(column)
696
- );
697
- const tablePlan = [
698
- ...planTableQuery(sourceColumnNames, {
699
- ...options,
700
- columns: outputColumns,
701
- predicate: options.predicate
702
- })
703
- ];
704
- const scanStep = tablePlan[0];
705
- if ((scanStep == null ? void 0 : scanStep.kind) === "scan") {
706
- const scanColumns = new Set(scanStep.columns);
707
- for (const column of requiredColumns) {
708
- if (available.has(column)) scanColumns.add(column);
709
- }
710
- tablePlan[0] = Object.freeze({ kind: "scan", columns: Object.freeze([...scanColumns]) });
711
- }
712
- for (const expression of expressionNames) available.add(expression);
713
- for (const aggregate of aggregateNames) available.add(aggregate);
714
- for (const key of options.orderBy || []) {
715
- if (!available.has(key.column))
716
- throw new Error(`Relational order column not found: ${key.column}`);
717
- }
718
- for (const key of options.groupBy || []) {
719
- if (!available.has(key)) throw new Error(`Relational group column not found: ${key}`);
720
- }
721
- for (const aggregate of options.aggregates || []) {
722
- if (!aggregate.name) throw new Error("Relational aggregate names must be non-empty.");
723
- if (aggregate.function !== "count" && !aggregate.column) {
724
- throw new Error(`Relational aggregate ${aggregate.function} requires a column.`);
725
- }
726
- if (aggregate.column && !available.has(aggregate.column)) {
727
- throw new Error(`Relational aggregate column not found: ${aggregate.column}`);
728
- }
729
- }
730
- const relationalSteps = [];
731
- if ((_b = options.expressions) == null ? void 0 : _b.length)
732
- relationalSteps.push({ kind: "expression", detail: options.expressions });
733
- if ((_c = options.orderBy) == null ? void 0 : _c.length) relationalSteps.push({ kind: "order", detail: options.orderBy });
734
- if (((_d = options.aggregates) == null ? void 0 : _d.length) || ((_e = options.groupBy) == null ? void 0 : _e.length)) {
735
- relationalSteps.push({
736
- kind: "aggregate",
737
- detail: { groupBy: options.groupBy, aggregates: options.aggregates }
738
- });
739
- }
740
- if ((_f = options.union) == null ? void 0 : _f.length) relationalSteps.push({ kind: "union", detail: options.union });
741
- if (options.join) relationalSteps.push({ kind: "join", detail: options.join });
742
- return { tablePlan, relationalSteps: Object.freeze(relationalSteps) };
743
- }
744
- function validateRelationalColumnReference(columnName, availableColumns) {
745
- if (!availableColumns.has(columnName)) {
746
- throw new Error(`Relational expression column not found: ${columnName}`);
747
- }
748
- }
749
-
750
- // src/loader-utils/lib/scan-utils/table-query-explain.ts
751
- function explainTableQuery(sourceColumnNames, options, capabilities) {
752
- const plan = planTableQuery(sourceColumnNames, options);
753
- const outputColumns = options.columns ? [...options.columns] : [...sourceColumnNames];
754
- const predicateColumns = options.predicate ? getColumnarPredicateColumns(options.predicate) : [];
755
- const requiredColumns = [...plan[0].kind === "scan" ? plan[0].columns : []];
756
- return Object.freeze({
757
- sourceColumns: Object.freeze([...sourceColumnNames]),
758
- outputColumns: Object.freeze(outputColumns),
759
- requiredColumns: Object.freeze(requiredColumns),
760
- predicateColumns: Object.freeze(predicateColumns),
761
- plan,
762
- capabilities: Object.freeze({ ...capabilities }),
763
- operators: Object.freeze({
764
- projection: createOperatorExplanation(options.columns !== void 0, capabilities.projection),
765
- predicate: createOperatorExplanation(options.predicate !== void 0, capabilities.predicate),
766
- limit: createOperatorExplanation(options.limit !== void 0, capabilities.limit)
767
- })
768
- });
769
- }
770
- function createOperatorExplanation(enabled, support) {
771
- return Object.freeze({ enabled, support });
772
- }
773
-
774
- // dist/scan/table-query-capabilities.js
775
- var ARROW_TABLE_QUERY_CAPABILITIES = Object.freeze({
776
- projection: "residual",
777
- predicate: "residual",
778
- limit: "residual",
779
- streaming: false,
780
- cancellation: true,
781
- expressions: "residual",
782
- orderBy: "residual",
783
- aggregates: "residual"
784
- });
785
- var SQL_DATA_SOURCE_TABLE_QUERY_CAPABILITIES = Object.freeze({
786
- projection: "pushdown",
787
- predicate: "pushdown",
788
- limit: "pushdown",
789
- streaming: false,
790
- cancellation: false,
791
- expressions: "pushdown",
792
- orderBy: "pushdown",
793
- aggregates: "pushdown"
794
733
  });
795
734
 
796
- // dist/scan/query-arrow-table.js
797
- var arrow6 = __toESM(require("apache-arrow"), 1);
798
-
799
- // dist/scan/arrow-execution/project-arrow-table.js
800
- var arrow3 = __toESM(require("apache-arrow"), 1);
801
- function projectArrowTable(source, selections) {
802
- const outputNames = /* @__PURE__ */ new Set();
803
- const indices = [];
804
- const fields = selections.map((selection) => {
805
- const column = typeof selection === "string" ? selection : selection.column;
806
- const name = typeof selection === "string" ? selection : selection.as === void 0 ? column : selection.as;
807
- const index = source.schema.fields.findIndex((field) => field.name === column);
808
- if (index < 0)
809
- throw new Error(`Arrow projection column not found: ${column}`);
810
- if (typeof name !== "string" || typeof selection !== "string" && selection.as !== void 0 && !name.length || outputNames.has(name)) {
811
- throw new Error(`Invalid or duplicate Arrow projection output name: ${name}`);
812
- }
813
- outputNames.add(name);
814
- indices.push(index);
815
- return source.schema.fields[index].clone({ name });
816
- });
817
- const schema = new arrow3.Schema(fields, source.schema.metadata);
818
- const batches = source.batches.map((batch) => new arrow3.RecordBatch(schema, arrow3.makeData({
819
- type: new arrow3.Struct(fields),
820
- length: batch.numRows,
821
- children: indices.map((index) => batch.data.children[index])
822
- }), batch.metadata));
823
- return new arrow3.Table(schema, batches);
824
- }
735
+ // dist/vector-table-scan-source.js
736
+ var vector_table_scan_source_exports = {};
737
+ __export(vector_table_scan_source_exports, {
738
+ AddressedVectorTableScanSource: () => AddressedVectorTableScanSource,
739
+ VectorFeatureTableScanSource: () => VectorFeatureTableScanSource,
740
+ VectorTileTableScanSource: () => VectorTileTableScanSource
741
+ });
742
+ module.exports = __toCommonJS(vector_table_scan_source_exports);
825
743
 
826
- // dist/scan/arrow-execution/filter-arrow-table.js
827
- var arrow4 = __toESM(require("apache-arrow"), 1);
828
- var import_arrow = require("@math.gl/core/arrow");
829
- function filterArrowTable(source, predicate, options = {}) {
830
- validateColumnarPredicate(predicate, new Set(source.schema.fields.map((field) => field.name)));
831
- const columnNames = getColumnarPredicateColumns(predicate);
832
- return filterArrowRows(source, (batch) => {
833
- const columns = getPredicateColumns(new arrow4.Table(source.schema, [batch]), columnNames);
834
- return (rowIndex) => evaluatePredicate(predicate, columns, rowIndex) === true;
835
- }, options);
836
- }
837
- function filterArrowRows(source, selectBatch, options = {}) {
838
- var _a, _b, _c;
839
- let remaining = options.limit ?? Infinity;
840
- if (remaining !== Infinity && (!Number.isSafeInteger(remaining) || remaining < 0)) {
841
- throw new Error("Arrow filter limit must be a non-negative safe integer.");
842
- }
843
- (_a = options.signal) == null ? void 0 : _a.throwIfAborted();
844
- const batches = [];
845
- for (const batch of source.batches) {
846
- if (remaining === 0)
847
- break;
848
- (_b = options.signal) == null ? void 0 : _b.throwIfAborted();
849
- const data = new arrow4.Table(source.schema, [batch]);
850
- const selectRow = selectBatch(batch);
851
- const indices = [];
852
- for (let rowIndex = 0; rowIndex < batch.numRows && indices.length < remaining; rowIndex++) {
853
- (_c = options.signal) == null ? void 0 : _c.throwIfAborted();
854
- if (selectRow(rowIndex))
855
- indices.push(rowIndex);
856
- }
857
- remaining -= indices.length;
858
- if (indices.length === 0)
859
- continue;
860
- if (indices.length === batch.numRows) {
861
- batches.push(batch);
862
- continue;
863
- }
864
- if (indices[indices.length - 1] - indices[0] + 1 === indices.length) {
865
- batches.push(batch.slice(indices[0], indices[indices.length - 1] + 1));
866
- continue;
867
- }
868
- const gathered = (0, import_arrow.takeArrowTableRows)(data, Int32Array.from(indices));
869
- batches.push(...gathered.batches);
870
- }
871
- return new arrow4.Table(source.schema, batches);
872
- }
873
- function getPredicateColumns(sourceTable, columnNames) {
874
- const columns = {};
875
- for (const columnName of columnNames) {
876
- const column = sourceTable.getChild(columnName);
877
- if (!column) {
878
- throw new Error(`Arrow query column not found: ${columnName}`);
879
- }
880
- columns[columnName] = column;
881
- }
882
- return columns;
883
- }
884
- function evaluatePredicate(predicate, columns, rowIndex) {
885
- if (isLogicalPredicate(predicate)) {
886
- const values = predicate.args.map((child) => evaluatePredicate(child, columns, rowIndex));
887
- return predicate.op === "and" ? evaluateAnd(values) : evaluateOr(values);
888
- }
889
- if (isNotPredicate(predicate)) {
890
- const value2 = evaluatePredicate(predicate.args[0], columns, rowIndex);
891
- return value2 === null ? null : !value2;
892
- }
893
- const value = getColumnValue(columns, predicate.args[0].property, rowIndex);
894
- if (isNullPredicate(predicate)) {
895
- return value === null || value === void 0;
896
- }
897
- if (isInPredicate(predicate)) {
898
- return evaluateIn(value, predicate.args[1]);
899
- }
900
- return evaluateComparison(value, predicate);
901
- }
902
- function getColumnValue(columns, columnName, rowIndex) {
903
- const path = typeof columnName === "string" ? [columnName] : columnName;
904
- const column = columns[path[0]];
905
- if (!column) {
906
- throw new Error(`Arrow query could not read predicate column "${columnName}".`);
907
- }
908
- let value = column.get(rowIndex);
909
- for (const property of path.slice(1)) {
910
- if (value === null || value === void 0)
911
- return null;
912
- value = value[property];
913
- }
914
- return value;
915
- }
916
- function evaluateAnd(values) {
917
- if (values.includes(false)) {
918
- return false;
919
- }
920
- return values.includes(null) ? null : true;
744
+ // src/schema-utils/lib/schema/convert-arrow-schema.ts
745
+ var arrow = __toESM(require("apache-arrow"), 1);
746
+ function convertArrowToSchema(arrowSchema) {
747
+ return serializeArrowSchema(arrowSchema);
921
748
  }
922
- function evaluateOr(values) {
923
- if (values.includes(true)) {
924
- return true;
925
- }
926
- return values.includes(null) ? null : false;
749
+ function serializeArrowSchema(arrowSchema) {
750
+ return {
751
+ fields: arrowSchema.fields.map((arrowField) => serializeArrowField(arrowField)),
752
+ metadata: serializeArrowMetadata(arrowSchema.metadata)
753
+ };
927
754
  }
928
- function evaluateIn(value, candidates) {
929
- if (value === null || value === void 0) {
930
- return null;
931
- }
932
- for (const candidate of candidates) {
933
- if (compareValues(value, candidate) === 0) {
934
- return true;
935
- }
936
- }
937
- return false;
755
+ function serializeArrowMetadata(arrowMetadata) {
756
+ return Object.fromEntries(arrowMetadata);
938
757
  }
939
- function evaluateComparison(value, predicate) {
940
- if (value === null || value === void 0) {
941
- return null;
942
- }
943
- const comparison = compareValues(value, predicate.args[1]);
944
- switch (predicate.op) {
945
- case "=":
946
- return comparison === 0;
947
- case "<>":
948
- return comparison !== 0;
949
- case "<":
950
- return comparison < 0;
951
- case "<=":
952
- return comparison <= 0;
953
- case ">":
954
- return comparison > 0;
955
- case ">=":
956
- return comparison >= 0;
957
- }
758
+ function serializeArrowField(field) {
759
+ return {
760
+ name: field.name,
761
+ type: serializeArrowType(field.type),
762
+ nullable: field.nullable,
763
+ metadata: serializeArrowMetadata(field.metadata)
764
+ };
958
765
  }
959
- function compareValues(left, right) {
960
- if (isColumnarPredicateParameter(right)) {
961
- throw new Error(`Arrow query parameter ":${right.parameter}" must be bound before query execution.`);
962
- }
963
- if (left instanceof Date && right instanceof Date) {
964
- return compareArrowQueryNumbers(left.getTime(), right.getTime());
965
- }
966
- if (typeof left === "number" && right instanceof Date) {
967
- return compareArrowQueryNumbers(left, right.getTime());
968
- }
969
- if (left instanceof Uint8Array && right instanceof Uint8Array) {
970
- return compareBinary(left, right);
971
- }
972
- if (typeof left === "bigint" && typeof right === "bigint") {
973
- return left === right ? 0 : left < right ? -1 : 1;
974
- }
975
- if (typeof left === "bigint" && typeof right === "number" || typeof left === "number" && typeof right === "bigint") {
976
- const numericValue = typeof left === "number" ? left : right;
977
- if (!Number.isFinite(numericValue))
978
- throw new Error("Arrow query cannot compare non-finite numbers.");
979
- return left < right ? -1 : left > right ? 1 : 0;
980
- }
981
- if (typeof left === "number" && typeof right === "number") {
982
- return compareArrowQueryNumbers(left, right);
766
+ function serializeArrowType(arrowType) {
767
+ if (isArrowViewType(arrowType, "BinaryView")) {
768
+ return "binary-view";
983
769
  }
984
- if (typeof left === "string" && typeof right === "string") {
985
- return left === right ? 0 : left < right ? -1 : 1;
770
+ if (isArrowViewType(arrowType, "Utf8View")) {
771
+ return "utf8-view";
986
772
  }
987
- if (typeof left === "boolean" && typeof right === "boolean") {
988
- return Number(left) - Number(right);
773
+ if (isOptionalArrowType(arrowType, "LargeList")) {
774
+ const largeListType = arrowType;
775
+ return {
776
+ type: "large-list",
777
+ children: [serializeArrowField(largeListType.valueField)]
778
+ };
989
779
  }
990
- throw new Error(`Arrow query cannot compare ${getArrowQueryValueType(left)} with ${getArrowQueryValueType(right)} values.`);
991
- }
992
- function compareArrowQueryNumbers(left, right) {
993
- if (!Number.isFinite(left) || !Number.isFinite(right)) {
994
- throw new Error("Arrow query cannot compare non-finite numbers.");
780
+ switch (arrowType.constructor) {
781
+ case arrow.Null:
782
+ return "null";
783
+ case arrow.Binary:
784
+ return "binary";
785
+ case arrow.FixedSizeBinary:
786
+ return {
787
+ type: "fixed-size-binary",
788
+ byteWidth: arrowType.byteWidth
789
+ };
790
+ case arrow.Bool:
791
+ return "bool";
792
+ case arrow.Int:
793
+ const intType = arrowType;
794
+ return `${intType.isSigned ? "" : "u"}int${intType.bitWidth}`;
795
+ case arrow.Int8:
796
+ return "int8";
797
+ case arrow.Int16:
798
+ return "int16";
799
+ case arrow.Int32:
800
+ return "int32";
801
+ case arrow.Int64:
802
+ return "int64";
803
+ case arrow.Uint8:
804
+ return "uint8";
805
+ case arrow.Uint16:
806
+ return "uint16";
807
+ case arrow.Uint32:
808
+ return "uint32";
809
+ case arrow.Uint64:
810
+ return "uint64";
811
+ case arrow.Float:
812
+ const precision = arrowType.precision;
813
+ switch (precision) {
814
+ case arrow.Precision.HALF:
815
+ return "float16";
816
+ case arrow.Precision.SINGLE:
817
+ return "float32";
818
+ case arrow.Precision.DOUBLE:
819
+ return "float64";
820
+ default:
821
+ return "float16";
822
+ }
823
+ case arrow.Float16:
824
+ return "float16";
825
+ case arrow.Float32:
826
+ return "float32";
827
+ case arrow.Float64:
828
+ return "float64";
829
+ case arrow.Utf8:
830
+ return "utf8";
831
+ case arrow.Decimal:
832
+ const decimal = arrowType;
833
+ return {
834
+ type: "decimal",
835
+ bitWidth: decimal.bitWidth,
836
+ precision: decimal.precision,
837
+ scale: decimal.scale
838
+ };
839
+ case arrow.Date_:
840
+ const dateUnit = arrowType.unit;
841
+ return dateUnit === arrow.DateUnit.DAY ? "date-day" : "date-millisecond";
842
+ case arrow.DateDay:
843
+ return "date-day";
844
+ case arrow.DateMillisecond:
845
+ return "date-millisecond";
846
+ case arrow.Time:
847
+ const timeUnit = arrowType.unit;
848
+ switch (timeUnit) {
849
+ case arrow.TimeUnit.SECOND:
850
+ return "time-second";
851
+ case arrow.TimeUnit.MILLISECOND:
852
+ return "time-millisecond";
853
+ case arrow.TimeUnit.MICROSECOND:
854
+ return "time-microsecond";
855
+ case arrow.TimeUnit.NANOSECOND:
856
+ return "time-nanosecond";
857
+ default:
858
+ return "time-second";
859
+ }
860
+ case arrow.TimeMillisecond:
861
+ return "time-millisecond";
862
+ case arrow.TimeSecond:
863
+ return "time-second";
864
+ case arrow.TimeMicrosecond:
865
+ return "time-microsecond";
866
+ case arrow.TimeNanosecond:
867
+ return "time-nanosecond";
868
+ case arrow.Timestamp:
869
+ const timeStampUnit = arrowType.unit;
870
+ switch (timeStampUnit) {
871
+ case arrow.TimeUnit.SECOND:
872
+ return "timestamp-second";
873
+ case arrow.TimeUnit.MILLISECOND:
874
+ return "timestamp-millisecond";
875
+ case arrow.TimeUnit.MICROSECOND:
876
+ return "timestamp-microsecond";
877
+ case arrow.TimeUnit.NANOSECOND:
878
+ return "timestamp-nanosecond";
879
+ default:
880
+ return "timestamp-second";
881
+ }
882
+ case arrow.TimestampSecond:
883
+ return "timestamp-second";
884
+ case arrow.TimestampMillisecond:
885
+ return "timestamp-millisecond";
886
+ case arrow.TimestampMicrosecond:
887
+ return "timestamp-microsecond";
888
+ case arrow.TimestampNanosecond:
889
+ return "timestamp-nanosecond";
890
+ case arrow.Interval:
891
+ const intervalUnit = arrowType.unit;
892
+ switch (intervalUnit) {
893
+ case arrow.IntervalUnit.DAY_TIME:
894
+ return "interval-daytime";
895
+ case arrow.IntervalUnit.YEAR_MONTH:
896
+ return "interval-yearmonth";
897
+ default:
898
+ return "interval-daytime";
899
+ }
900
+ case arrow.IntervalDayTime:
901
+ return "interval-daytime";
902
+ case arrow.IntervalYearMonth:
903
+ return "interval-yearmonth";
904
+ case arrow.Map_:
905
+ const mapType = arrowType;
906
+ return {
907
+ type: "map",
908
+ keysSorted: mapType.keysSorted,
909
+ children: mapType.children.map((arrowField) => serializeArrowField(arrowField))
910
+ };
911
+ case arrow.List:
912
+ const listType = arrowType;
913
+ const listField = listType.valueField;
914
+ return {
915
+ type: "list",
916
+ children: [serializeArrowField(listField)]
917
+ };
918
+ case arrow.FixedSizeList:
919
+ const fixedSizeList = arrowType;
920
+ return {
921
+ type: "fixed-size-list",
922
+ listSize: fixedSizeList.listSize,
923
+ children: [serializeArrowField(fixedSizeList.children[0])]
924
+ };
925
+ case arrow.Struct:
926
+ const structType = arrowType;
927
+ return {
928
+ type: "struct",
929
+ children: structType.children.map((arrowField) => serializeArrowField(arrowField))
930
+ };
931
+ case arrow.SparseUnion:
932
+ case arrow.DenseUnion:
933
+ const unionType = arrowType;
934
+ return {
935
+ type: unionType instanceof arrow.DenseUnion ? "dense-union" : "sparse-union",
936
+ typeIds: unionType.typeIds,
937
+ children: unionType.children.map((arrowField) => serializeArrowField(arrowField)),
938
+ typeIdToChildIndex: { ...unionType.typeIdToChildIndex }
939
+ };
940
+ case arrow.Dictionary:
941
+ const dictionaryType = arrowType;
942
+ return {
943
+ type: "dictionary",
944
+ id: dictionaryType.id,
945
+ indices: serializeArrowDictionaryKeyType(dictionaryType.indices),
946
+ dictionary: serializeArrowType(dictionaryType.dictionary),
947
+ isOrdered: dictionaryType.isOrdered
948
+ };
949
+ default:
950
+ throw new Error(`arrow type not supported: ${arrowType.constructor.name}`);
995
951
  }
996
- return left === right ? 0 : left < right ? -1 : 1;
997
952
  }
998
- function compareBinary(left, right) {
999
- const commonLength = Math.min(left.length, right.length);
1000
- for (let index = 0; index < commonLength; index++) {
1001
- if (left[index] !== right[index]) {
1002
- return left[index] < right[index] ? -1 : 1;
1003
- }
1004
- }
1005
- return left.length === right.length ? 0 : left.length < right.length ? -1 : 1;
953
+ function getOptionalArrowConstructor(typeName) {
954
+ return arrow[typeName];
1006
955
  }
1007
- function getArrowQueryValueType(value) {
1008
- if (value instanceof Date) {
1009
- return "Date";
1010
- }
1011
- if (value instanceof Uint8Array) {
1012
- return "Uint8Array";
956
+ function isArrowViewType(arrowType, viewTypeName) {
957
+ const constructor = getOptionalArrowConstructor(viewTypeName);
958
+ if (constructor && arrowType instanceof constructor) {
959
+ return true;
1013
960
  }
1014
- return typeof value;
1015
- }
1016
- function isLogicalPredicate(predicate) {
1017
- return predicate.op === "and" || predicate.op === "or";
1018
- }
1019
- function isNotPredicate(predicate) {
1020
- return predicate.op === "not";
1021
- }
1022
- function isNullPredicate(predicate) {
1023
- return predicate.op === "isNull";
1024
- }
1025
- function isInPredicate(predicate) {
1026
- return predicate.op === "in";
1027
- }
1028
-
1029
- // dist/scan/rows-to-arrow.js
1030
- var arrow5 = __toESM(require("apache-arrow"), 1);
1031
- function convertRowsToArrowTable(rows) {
1032
- return arrow5.tableFromJSON(rows);
1033
- }
1034
-
1035
- // dist/scan/sql-predicate-types.js
1036
- function isSQLPredicateParameter(value) {
1037
- return isColumnarPredicateParameter(value);
961
+ const guards = arrow.DataType;
962
+ const guard = viewTypeName === "BinaryView" ? guards.isBinaryView : guards.isUtf8View;
963
+ return Boolean(guard == null ? void 0 : guard(arrowType));
1038
964
  }
1039
-
1040
- // dist/scan/sql-predicate-schema.js
1041
- var MAXIMUM_PREDICATE_DEPTH = 64;
1042
- var MAXIMUM_PREDICATE_NODES = 4096;
1043
- function validateSQLPredicate(value) {
1044
- const state = { nodes: 0 };
1045
- validatePredicateNode(value, "$", 0, state);
965
+ function isOptionalArrowType(arrowType, typeName) {
966
+ const constructor = getOptionalArrowConstructor(typeName);
967
+ return Boolean(constructor && arrowType instanceof constructor);
1046
968
  }
1047
- function validatePredicateNode(value, path, depth, state) {
1048
- if (depth > MAXIMUM_PREDICATE_DEPTH) {
1049
- throw new Error(`SQL predicate ${path} exceeds the maximum nesting depth`);
1050
- }
1051
- state.nodes++;
1052
- if (state.nodes > MAXIMUM_PREDICATE_NODES) {
1053
- throw new Error("SQL predicate exceeds the maximum node count");
1054
- }
1055
- if (!isRecord(value) || !hasExactKeys(value, ["op", "args"])) {
1056
- throw new Error(`SQL predicate ${path} must contain only op and args`);
1057
- }
1058
- if (typeof value.op !== "string" || !Array.isArray(value.args)) {
1059
- throw new Error(`SQL predicate ${path} requires string op and array args`);
969
+ function serializeArrowDictionaryKeyType(arrowType) {
970
+ if (arrowType instanceof arrow.Int) {
971
+ const prefix = arrowType.isSigned ? "int" : "uint";
972
+ const keyType = `${prefix}${arrowType.bitWidth}`;
973
+ if (isSchemaDictionaryKeyType(keyType)) {
974
+ return keyType;
975
+ }
1060
976
  }
1061
- switch (value.op) {
1062
- case "and":
1063
- case "or":
1064
- if (value.args.length < 2) {
1065
- throw new Error(`SQL predicate ${path}.${value.op} requires at least two arguments`);
1066
- }
1067
- for (let index = 0; index < value.args.length; index++) {
1068
- validatePredicateNode(value.args[index], `${path}.args[${index}]`, depth + 1, state);
1069
- }
1070
- return;
1071
- case "not":
1072
- if (value.args.length !== 1) {
1073
- throw new Error(`SQL predicate ${path}.not requires exactly one argument`);
1074
- }
1075
- validatePredicateNode(value.args[0], `${path}.args[0]`, depth + 1, state);
1076
- return;
1077
- case "isNull":
1078
- if (value.args.length !== 1) {
1079
- throw new Error(`SQL predicate ${path}.isNull requires exactly one argument`);
1080
- }
1081
- validatePredicateProperty(value.args[0], `${path}.args[0]`);
1082
- return;
1083
- case "in":
1084
- if (value.args.length !== 2 || !Array.isArray(value.args[1]) || value.args[1].length === 0) {
1085
- throw new Error(`SQL predicate ${path}.in requires a property and non-empty value list`);
1086
- }
1087
- validatePredicateProperty(value.args[0], `${path}.args[0]`);
1088
- value.args[1].forEach((item, index) => validatePredicateValue(item, `${path}.args[1][${index}]`));
1089
- return;
1090
- case "=":
1091
- case "<>":
1092
- case "<":
1093
- case "<=":
1094
- case ">":
1095
- case ">=":
1096
- if (value.args.length !== 2) {
1097
- throw new Error(`SQL predicate ${path}.${value.op} requires exactly two arguments`);
1098
- }
1099
- validatePredicateProperty(value.args[0], `${path}.args[0]`);
1100
- validatePredicateValue(value.args[1], `${path}.args[1]`);
1101
- return;
977
+ switch (arrowType.constructor) {
978
+ case arrow.Int8:
979
+ return "int8";
980
+ case arrow.Int16:
981
+ return "int16";
982
+ case arrow.Int32:
983
+ return "int32";
984
+ case arrow.Uint8:
985
+ return "uint8";
986
+ case arrow.Uint16:
987
+ return "uint16";
988
+ case arrow.Uint32:
989
+ return "uint32";
1102
990
  default:
1103
- throw new Error(`SQL predicate ${path} has unsupported operator ${JSON.stringify(value.op)}`);
1104
- }
1105
- }
1106
- function validatePredicateProperty(value, path) {
1107
- if (!isRecord(value) || !hasAllowedKeys(value, ["property", "quoted"]) || typeof value.property !== "string" || value.property.length === 0 || value.quoted !== void 0 && typeof value.quoted !== "boolean") {
1108
- throw new Error(`SQL predicate ${path} requires a non-empty property reference`);
1109
- }
1110
- }
1111
- function validatePredicateValue(value, path) {
1112
- if (isSQLPredicateParameter(value)) {
1113
- return;
1114
- }
1115
- if (typeof value === "boolean" || typeof value === "bigint" || typeof value === "string" || value instanceof Uint8Array) {
1116
- return;
1117
- }
1118
- if (typeof value === "number" && Number.isFinite(value)) {
1119
- return;
1120
- }
1121
- if (value instanceof Date && Number.isFinite(value.getTime())) {
1122
- return;
991
+ throw new Error(`arrow dictionary index type not supported: ${arrowType.constructor.name}`);
1123
992
  }
1124
- throw new Error(`SQL predicate ${path} contains an unsupported scalar value`);
1125
- }
1126
- function isRecord(value) {
1127
- return typeof value === "object" && value !== null && !Array.isArray(value);
1128
993
  }
1129
- function hasExactKeys(value, expectedKeys) {
1130
- const keys = Object.keys(value);
1131
- return keys.length === expectedKeys.length && expectedKeys.every((key) => keys.includes(key));
1132
- }
1133
- function hasAllowedKeys(value, allowedKeys) {
1134
- return Object.keys(value).every((key) => allowedKeys.includes(key));
994
+ function isSchemaDictionaryKeyType(keyType) {
995
+ return ["int8", "int16", "int32", "uint8", "uint16", "uint32"].includes(keyType);
1135
996
  }
1136
997
 
1137
- // dist/scan/table-query.js
1138
- function planTableQuery2(sourceColumnNames, options = {}) {
1139
- if (options.predicate) {
1140
- validateSQLPredicate(options.predicate);
1141
- }
1142
- return planTableQuery(sourceColumnNames, options);
998
+ // src/schema-utils/lib/arrow/arrow-metadata.ts
999
+ var arrow2 = __toESM(require("apache-arrow"), 1);
1000
+ var import_arrow = require("@math.gl/core/arrow");
1001
+ function makeArrowMetadataBatch(schema) {
1002
+ return new arrow2.RecordBatch((0, import_arrow.snapshotArrowSchema)(schema), void 0);
1143
1003
  }
1144
1004
 
1145
- // dist/scan/query-arrow-table.js
1146
- function explainArrowTableQuery(sourceTable, options = {}) {
1147
- if (options.select !== void 0) {
1148
- if (options.columns !== void 0 || hasRelationalOperators(options) || options.join) {
1149
- throw new Error("Arrow select cannot be combined with columns or relational operators.");
1150
- }
1151
- const projected = projectArrowTable(sourceTable, options.select);
1152
- const columns = [
1153
- ...new Set(options.select.map((selection) => typeof selection === "string" ? selection : selection.column))
1154
- ];
1155
- const { select, ...remainingOptions } = options;
1156
- const explanation = explainArrowTableQuery(sourceTable, { ...remainingOptions, columns });
1157
- const outputColumns = Object.freeze(projected.schema.fields.map((field) => field.name));
1158
- return Object.freeze({
1159
- ...explanation,
1160
- outputColumns,
1161
- plan: Object.freeze(explanation.plan.map((step) => step.kind === "project" ? Object.freeze({ ...step, columns: outputColumns, select }) : step))
1162
- });
1163
- }
1164
- if (options.predicate) {
1165
- validateSQLPredicate(options.predicate);
1166
- }
1167
- return explainTableQuery(sourceTable.schema.fields.map((field) => field.name), options, ARROW_TABLE_QUERY_CAPABILITIES);
1168
- }
1169
- var executePortableArrowQuery = (table, { select, where, limit, signal }) => {
1170
- if (where)
1171
- table = filterArrowTable(table, where, { limit, signal });
1172
- const projected = select ? projectArrowTable(table, select) : table;
1173
- return projected.numRows === 0 || limit === void 0 ? projected : projected.slice(0, limit);
1174
- };
1175
- function queryArrowTable(sourceTable, options = {}, executeLinear = executePortableArrowQuery) {
1176
- throwIfAborted(options.signal);
1177
- if (options.select !== void 0) {
1178
- if (options.columns !== void 0 || hasRelationalOperators(options) || options.join) {
1179
- throw new Error("Arrow select cannot be combined with columns or relational operators.");
1180
- }
1181
- projectArrowTable(sourceTable, options.select);
1182
- const columns = [
1183
- ...new Set(options.select.map((selection) => typeof selection === "string" ? selection : selection.column))
1184
- ];
1185
- const { select, ...remainingOptions } = options;
1186
- const result = queryArrowTable(sourceTable, { ...remainingOptions, columns }, executeLinear);
1187
- return projectArrowTable(result, select);
1188
- }
1189
- if (options.join) {
1190
- validateArrowJoinQuery(sourceTable, options);
1191
- }
1192
- if (options.join && hasRelationalOperatorsExceptJoin(options)) {
1193
- throw new Error("Arrow joins cannot yet be combined with other relational operators.");
1194
- }
1195
- if (options.join && !hasRelationalOperatorsExceptJoin(options)) {
1196
- return queryArrowJoin(sourceTable, options);
1197
- }
1198
- if (hasRelationalOperators(options)) {
1199
- return queryArrowTableRelational(sourceTable, options);
1200
- }
1201
- const plan = planTableQuery2(sourceTable.schema.fields.map((field) => field.name), options);
1202
- const projection = plan.find((step) => step.kind === "project");
1203
- return executeLinear(sourceTable, {
1204
- where: options.predicate,
1205
- select: projection == null ? void 0 : projection.columns,
1206
- limit: options.limit,
1207
- signal: options.signal
1208
- });
1209
- }
1210
- function queryArrowTableRelational(sourceTable, options) {
1211
- var _a, _b, _c, _d, _e, _f;
1212
- const sourceData = sourceTable;
1213
- const sourceColumnNames = sourceData.schema.fields.map((field) => field.name);
1214
- const relationalPlan = planRelationalQuery(sourceColumnNames, options);
1215
- const scanStep = relationalPlan.tablePlan.find((step) => step.kind === "scan");
1216
- if (!scanStep || scanStep.kind !== "scan") {
1217
- throw new Error("Arrow relational query plan is missing a scan step.");
1218
- }
1219
- const scannedTable = sourceData.select([...scanStep.columns]);
1220
- const filteredTable = queryArrowTable(scannedTable, {
1221
- predicate: options.predicate,
1222
- columns: scanStep.columns,
1223
- signal: options.signal
1224
- });
1225
- let rows = arrowTableToRows(filteredTable);
1226
- for (const child of options.union || []) {
1227
- const childTable = (_a = options.tables) == null ? void 0 : _a[child.source];
1228
- if (!childTable)
1229
- throw new Error(`Arrow union source not found: ${child.source}`);
1230
- const childResult = queryArrowTable(childTable, {
1231
- ...child.query || {},
1232
- columns: getUnionChildColumns(sourceColumnNames, options),
1233
- signal: options.signal
1234
- });
1235
- rows = rows.concat(arrowTableToRows(childResult));
1236
- }
1237
- for (const expression of options.expressions || []) {
1238
- for (const row of rows) {
1239
- row[expression.name] = evaluateRelationalExpression(expression, row);
1240
- }
1241
- }
1242
- if (((_b = options.groupBy) == null ? void 0 : _b.length) || ((_c = options.aggregates) == null ? void 0 : _c.length)) {
1243
- rows = aggregateRows(rows, options.groupBy || [], options.aggregates || []);
1244
- }
1245
- if ((_d = options.orderBy) == null ? void 0 : _d.length) {
1246
- const orderBy = options.orderBy;
1247
- rows = rows.map((row, index) => ({ row, index })).sort((left, right) => compareRows(left.row, right.row, orderBy) || left.index - right.index).map((entry) => entry.row);
1248
- }
1249
- const outputColumns = options.columns || (((_e = options.groupBy) == null ? void 0 : _e.length) || ((_f = options.aggregates) == null ? void 0 : _f.length) ? [...options.groupBy || [], ...(options.aggregates || []).map((aggregate) => aggregate.name)] : sourceColumnNames);
1250
- const outputRows = rows.map((row) => {
1251
- const output = {};
1252
- for (const columnName of outputColumns) {
1253
- if (!(columnName in row)) {
1254
- throw new Error(`Arrow relational query column not found: ${columnName}`);
1255
- }
1256
- output[columnName] = row[columnName];
1257
- }
1258
- return output;
1259
- });
1260
- const limit = options.limit === void 0 ? outputRows.length : options.limit;
1261
- const limitedRows = outputRows.slice(0, limit);
1262
- return limitedRows.length ? convertRowsToArrowTable(limitedRows) : createEmptyRelationalResult(sourceData, outputColumns, options);
1263
- }
1264
- function getUnionChildColumns(sourceColumnNames, options) {
1265
- var _a, _b;
1266
- const expressionNames = new Set((options.expressions || []).map((expression) => expression.name));
1267
- const aggregateNames = new Set((options.aggregates || []).map((aggregate) => aggregate.name));
1268
- const outputColumns = options.columns || (((_a = options.groupBy) == null ? void 0 : _a.length) || ((_b = options.aggregates) == null ? void 0 : _b.length) ? [...options.groupBy || [], ...(options.aggregates || []).map((aggregate) => aggregate.name)] : sourceColumnNames);
1269
- const requiredColumns = new Set(outputColumns.filter((column) => !expressionNames.has(column) && !aggregateNames.has(column)));
1270
- for (const expression of options.expressions || []) {
1271
- const definition = expression.expression;
1272
- if (definition.op === "column")
1273
- requiredColumns.add(definition.column);
1274
- if ("left" in definition) {
1275
- requiredColumns.add(definition.left);
1276
- requiredColumns.add(definition.right);
1277
- }
1278
- }
1279
- for (const key of options.orderBy || []) {
1280
- if (!expressionNames.has(key.column) && !aggregateNames.has(key.column)) {
1281
- requiredColumns.add(key.column);
1282
- }
1283
- }
1284
- for (const column of options.groupBy || [])
1285
- requiredColumns.add(column);
1286
- for (const aggregate of options.aggregates || []) {
1287
- if (aggregate.column)
1288
- requiredColumns.add(aggregate.column);
1289
- }
1290
- return sourceColumnNames.filter((column) => requiredColumns.has(column));
1291
- }
1292
- function hasRelationalOperators(options) {
1293
- var _a, _b, _c, _d, _e;
1294
- return Boolean(((_a = options.expressions) == null ? void 0 : _a.length) || ((_b = options.orderBy) == null ? void 0 : _b.length) || ((_c = options.groupBy) == null ? void 0 : _c.length) || ((_d = options.aggregates) == null ? void 0 : _d.length) || ((_e = options.union) == null ? void 0 : _e.length) || options.join);
1295
- }
1296
- function hasRelationalOperatorsExceptJoin(options) {
1297
- var _a, _b, _c, _d, _e;
1298
- return Boolean(((_a = options.expressions) == null ? void 0 : _a.length) || ((_b = options.orderBy) == null ? void 0 : _b.length) || ((_c = options.groupBy) == null ? void 0 : _c.length) || ((_d = options.aggregates) == null ? void 0 : _d.length) || ((_e = options.union) == null ? void 0 : _e.length));
1299
- }
1300
- function queryArrowJoin(sourceTable, options) {
1301
- var _a;
1302
- const join = options.join;
1303
- if (!join)
1304
- throw new Error("Arrow join query is missing a join definition.");
1305
- const childTable = (_a = options.tables) == null ? void 0 : _a[join.child.source];
1306
- if (!childTable)
1307
- throw new Error(`Arrow join source not found: ${join.child.source}`);
1308
- const leftResult = queryArrowTable(sourceTable, {
1309
- predicate: options.predicate,
1310
- columns: void 0,
1311
- signal: options.signal
1312
- });
1313
- const rightResult = queryArrowTable(childTable, {
1314
- ...join.child.query || {},
1315
- signal: options.signal
1316
- });
1317
- const leftRows = arrowTableToRows(leftResult);
1318
- const rightRows = arrowTableToRows(rightResult);
1319
- const rightPrefix = `${join.child.source}.`;
1320
- const defaultOutputColumns = [
1321
- ...sourceTable.schema.fields.map((field) => field.name),
1322
- ...rightResult.schema.fields.map((field) => `${rightPrefix}${field.name}`)
1323
- ];
1324
- const rows = [];
1325
- for (const leftRow of leftRows) {
1326
- for (const rightRow of rightRows) {
1327
- if (leftRow[join.left] !== null && leftRow[join.left] !== void 0 && rightRow[join.right] !== null && rightRow[join.right] !== void 0 && compareSortValues(leftRow[join.left], rightRow[join.right]) === 0) {
1328
- rows.push({
1329
- ...leftRow,
1330
- ...Object.fromEntries(Object.entries(rightRow).map(([key, value]) => [`${rightPrefix}${key}`, value]))
1331
- });
1332
- }
1333
- }
1334
- }
1335
- const outputColumns = options.columns || defaultOutputColumns;
1336
- const outputRows = rows.map((row) => Object.fromEntries(outputColumns.map((column) => [column, row[column]])));
1337
- const limitedRows = outputRows.slice(0, options.limit);
1338
- return limitedRows.length ? convertRowsToArrowTable(limitedRows) : createEmptyRelationalResult(sourceTable, outputColumns, options, new Map(rightResult.schema.fields.map((field) => [
1339
- `${rightPrefix}${field.name}`,
1340
- new arrow6.Field(`${rightPrefix}${field.name}`, field.type, field.nullable, field.metadata)
1341
- ])));
1342
- }
1343
- function validateArrowJoinQuery(sourceTable, options) {
1344
- var _a, _b, _c;
1345
- const join = options.join;
1346
- if (!join)
1347
- return;
1348
- const sourceColumnNames = sourceTable.schema.fields.map((field) => field.name);
1349
- const childTable = (_a = options.tables) == null ? void 0 : _a[join.child.source];
1350
- if (!childTable)
1351
- throw new Error(`Arrow join source not found: ${join.child.source}`);
1352
- const childColumnNames = childTable.schema.fields.map((field) => field.name);
1353
- if (!sourceColumnNames.includes(join.left)) {
1354
- throw new Error(`Arrow join column not found: ${join.left}`);
1355
- }
1356
- if (!childColumnNames.includes(join.right)) {
1357
- throw new Error(`Arrow join column not found: ${join.right}`);
1358
- }
1359
- const childPrefix = `${join.child.source}.`;
1360
- const rootColumns = (_b = options.columns) == null ? void 0 : _b.filter((column) => !column.startsWith(childPrefix));
1361
- planTableQuery2(sourceColumnNames, {
1362
- predicate: options.predicate,
1363
- columns: (rootColumns == null ? void 0 : rootColumns.length) ? rootColumns : void 0,
1364
- limit: options.limit,
1365
- signal: options.signal
1366
- });
1367
- const childQuery = join.child.query || {};
1368
- planTableQuery2(childColumnNames, childQuery);
1369
- const childOutputColumns = childQuery.columns || childColumnNames;
1370
- if (!childOutputColumns.includes(join.right)) {
1371
- throw new Error(`Arrow join child projection must include: ${join.right}`);
1372
- }
1373
- const projectedChildColumns = ((_c = options.columns) == null ? void 0 : _c.filter((column) => column.startsWith(childPrefix))) || [];
1374
- const seenChildColumns = /* @__PURE__ */ new Set();
1375
- for (const projectedColumn of projectedChildColumns) {
1376
- const childColumn = projectedColumn.slice(childPrefix.length);
1377
- if (!childColumnNames.includes(childColumn)) {
1378
- throw new Error(`Arrow join column not found: ${projectedColumn}`);
1379
- }
1380
- if (seenChildColumns.has(childColumn)) {
1381
- throw new Error(`Arrow query column was selected more than once: ${projectedColumn}`);
1382
- }
1383
- seenChildColumns.add(childColumn);
1384
- if (!childOutputColumns.includes(childColumn)) {
1385
- throw new Error(`Arrow join child projection does not include: ${childColumn}`);
1386
- }
1387
- }
1388
- }
1389
- function arrowTableToRows(data) {
1390
- const columns = data.schema.fields.map((field) => ({
1391
- name: field.name,
1392
- vector: data.getChild(field.name)
1393
- }));
1394
- return Array.from({ length: data.numRows }, (_, rowIndex) => {
1395
- const row = {};
1396
- for (const column of columns) {
1397
- if (!column.vector)
1398
- throw new Error(`Arrow relational query could not read ${column.name}`);
1399
- row[column.name] = column.vector.get(rowIndex);
1400
- }
1401
- return row;
1402
- });
1403
- }
1404
- function evaluateRelationalExpression(expression, row) {
1405
- const definition = expression.expression;
1406
- if (definition.op === "literal")
1407
- return definition.value;
1408
- if (definition.op === "column")
1409
- return row[definition.column];
1410
- const left = row[definition.left];
1411
- const right = row[definition.right];
1412
- if (left === null || left === void 0 || right === null || right === void 0)
1413
- return null;
1414
- if (typeof left !== "number" || typeof right !== "number") {
1415
- throw new Error(`Arrow relational expression ${expression.name} requires numeric operands.`);
1416
- }
1417
- switch (definition.op) {
1418
- case "add":
1419
- return left + right;
1420
- case "subtract":
1421
- return left - right;
1422
- case "multiply":
1423
- return left * right;
1424
- case "divide":
1425
- return right === 0 ? null : left / right;
1426
- }
1427
- }
1428
- function compareRows(left, right, orderBy) {
1429
- for (const key of orderBy) {
1430
- const leftValue = left[key.column];
1431
- const rightValue = right[key.column];
1432
- const nulls = key.nulls || "last";
1433
- if (leftValue === null || leftValue === void 0 || rightValue === null || rightValue === void 0) {
1434
- if (leftValue === rightValue)
1435
- continue;
1436
- const nullResult = leftValue === null || leftValue === void 0 ? -1 : 1;
1437
- return nulls === "first" ? nullResult : -nullResult;
1438
- }
1439
- const result = compareSortValues(leftValue, rightValue);
1440
- if (result)
1441
- return (key.direction === "desc" ? -1 : 1) * result;
1442
- }
1443
- return 0;
1444
- }
1445
- function compareSortValues(left, right) {
1446
- if (left instanceof Date && right instanceof Date)
1447
- return compareArrowQueryNumbers(left.getTime(), right.getTime());
1448
- if (typeof left === "bigint" && typeof right === "bigint")
1449
- return left === right ? 0 : left < right ? -1 : 1;
1450
- if (typeof left === "number" && typeof right === "number")
1451
- return compareArrowQueryNumbers(left, right);
1452
- if (typeof left === "string" && typeof right === "string")
1453
- return left === right ? 0 : left < right ? -1 : 1;
1454
- if (typeof left === "boolean" && typeof right === "boolean")
1455
- return Number(left) - Number(right);
1456
- throw new Error(`Arrow relational order cannot compare ${getArrowQueryValueType(left)} with ${getArrowQueryValueType(right)}.`);
1457
- }
1458
- function aggregateRows(rows, groupBy, aggregates) {
1459
- const groups = /* @__PURE__ */ new Map();
1460
- for (const row of rows) {
1461
- const key = serializeGroupKey(groupBy.map((column) => row[column]));
1462
- const group = groups.get(key) || [];
1463
- group.push(row);
1464
- groups.set(key, group);
1465
- }
1466
- if (!groupBy.length && !rows.length)
1467
- groups.set("[]", []);
1468
- return [...groups.values()].map((group) => {
1469
- var _a;
1470
- const output = {};
1471
- for (const column of groupBy)
1472
- output[column] = ((_a = group[0]) == null ? void 0 : _a[column]) ?? null;
1473
- for (const aggregate of aggregates)
1474
- output[aggregate.name] = evaluateAggregate(aggregate, group);
1475
- return output;
1476
- });
1477
- }
1478
- function serializeGroupKey(values) {
1479
- return values.map((value) => {
1480
- if (value === null || value === void 0)
1481
- return "null:";
1482
- if (value instanceof Date)
1483
- return `date:${value.getTime()}`;
1484
- if (value instanceof Uint8Array)
1485
- return `bytes:${Array.from(value).join(".")}`;
1486
- return `${typeof value}:${String(value)}`;
1487
- }).join("");
1488
- }
1489
- function createEmptyRelationalResult(sourceData, outputColumns, options, additionalFields) {
1490
- const sourceFields = new Map(sourceData.schema.fields.map((field) => [field.name, field]));
1491
- const expressions = new Map((options.expressions || []).map((expression) => [expression.name, expression]));
1492
- const aggregates = new Map((options.aggregates || []).map((aggregate) => [aggregate.name, aggregate]));
1493
- const fields = outputColumns.map((columnName) => {
1494
- const sourceField = sourceFields.get(columnName);
1495
- if (sourceField)
1496
- return sourceField;
1497
- const additionalField = additionalFields == null ? void 0 : additionalFields.get(columnName);
1498
- if (additionalField)
1499
- return additionalField;
1500
- const expression = expressions.get(columnName);
1501
- if (expression)
1502
- return new arrow6.Field(columnName, getExpressionType(expression, sourceFields), true);
1503
- const aggregate = aggregates.get(columnName);
1504
- if (aggregate)
1505
- return new arrow6.Field(columnName, getAggregateType(aggregate, sourceFields), true);
1506
- return new arrow6.Field(columnName, new arrow6.Utf8(), true);
1507
- });
1508
- const columns = {};
1509
- for (const field of fields)
1510
- columns[field.name] = arrow6.vectorFromArray([], field.type);
1511
- return new arrow6.Table(new arrow6.Schema(fields), columns);
1512
- }
1513
- function getExpressionType(expression, sourceFields) {
1514
- var _a;
1515
- if (expression.expression.op === "literal") {
1516
- const value = expression.expression.value;
1517
- if (typeof value === "boolean")
1518
- return new arrow6.Bool();
1519
- if (typeof value === "number")
1520
- return new arrow6.Float64();
1521
- return new arrow6.Utf8();
1522
- }
1523
- if (expression.expression.op === "column") {
1524
- return ((_a = sourceFields.get(expression.expression.column)) == null ? void 0 : _a.type) || new arrow6.Utf8();
1525
- }
1526
- return new arrow6.Float64();
1527
- }
1528
- function getAggregateType(aggregate, sourceFields) {
1529
- var _a;
1530
- if (aggregate.function === "count")
1531
- return new arrow6.Int32();
1532
- return aggregate.column ? ((_a = sourceFields.get(aggregate.column)) == null ? void 0 : _a.type) || new arrow6.Float64() : new arrow6.Float64();
1533
- }
1534
- function evaluateAggregate(aggregate, rows) {
1535
- if (aggregate.function === "count")
1536
- return aggregate.column ? rows.filter((row) => row[aggregate.column] != null).length : rows.length;
1537
- const values = rows.map((row) => row[aggregate.column]).filter((value) => value != null);
1538
- if (!values.length)
1539
- return null;
1540
- if (!values.every((value) => typeof value === "number"))
1541
- throw new Error(`Arrow aggregate ${aggregate.function} requires numeric values.`);
1542
- const numericValues = values;
1543
- switch (aggregate.function) {
1544
- case "sum":
1545
- return numericValues.reduce((sum, value) => sum + value, 0);
1546
- case "avg":
1547
- return numericValues.reduce((sum, value) => sum + value, 0) / numericValues.length;
1548
- case "min":
1549
- return Math.min(...numericValues);
1550
- case "max":
1551
- return Math.max(...numericValues);
1552
- }
1553
- }
1554
- function throwIfAborted(signal) {
1555
- if (signal == null ? void 0 : signal.aborted) {
1556
- const error = new Error("Arrow query was aborted.");
1557
- error.name = "AbortError";
1558
- throw error;
1559
- }
1005
+ // dist/lib/loader-utils/native-arrow.js
1006
+ function isArrowTable(value) {
1007
+ return Boolean(value && typeof value === "object" && "schema" in value && "batches" in value && Array.isArray(value.batches) && "numRows" in value && typeof value.numRows === "number" && "getChildAt" in value && typeof value.getChildAt === "function");
1560
1008
  }
1561
1009
 
1562
1010
  // dist/scan/vector-table-scan-source.js
1011
+ init_loader_utils();
1012
+ init_table_query_capabilities();
1013
+ init_plan_arrow_table_query();
1563
1014
  var AddressedVectorTableScanSource = class {
1564
1015
  /** Stable adapter type reported by `getQueryMetadata()`. */
1565
1016
  sourceType;
@@ -1601,7 +1052,8 @@ var AddressedVectorTableScanSource = class {
1601
1052
  /** Applies the portable Arrow query to the addressed feature table. */
1602
1053
  async query(options = {}) {
1603
1054
  const table = await this.getTable(options.signal);
1604
- return queryArrowTable(table, options);
1055
+ const { queryArrowTable: queryArrowTable3 } = await Promise.resolve().then(() => (init_query_arrow_table(), query_arrow_table_exports));
1056
+ return queryArrowTable3(table, options);
1605
1057
  }
1606
1058
  /** Explains the residual Arrow plan after resolving the addressed feature table. */
1607
1059
  async explain(options = {}) {