@loaders.gl/core 5.0.0-rc.2 → 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 (229) hide show
  1. package/dist/arrow-geometry/geometry-codecs.cjs +51 -50
  2. package/dist/arrow-geometry/geometry-codecs.cjs.map +3 -3
  3. package/dist/arrow-geometry/geometry-codecs.d.ts +1 -1
  4. package/dist/arrow-geometry/geometry-codecs.d.ts.map +1 -1
  5. package/dist/arrow-geometry/geometry-codecs.js +27 -60
  6. package/dist/arrow-geometry/geometry-codecs.js.map +1 -1
  7. package/dist/arrow-geometry/triangulate-wkb.cjs +33 -118
  8. package/dist/arrow-geometry/triangulate-wkb.cjs.map +2 -2
  9. package/dist/arrow-geometry/triangulate-wkb.d.ts.map +1 -1
  10. package/dist/arrow-geometry/triangulate-wkb.js +39 -142
  11. package/dist/arrow-geometry/triangulate-wkb.js.map +1 -1
  12. package/dist/cluster-source.cjs +124 -370
  13. package/dist/cluster-source.cjs.map +3 -3
  14. package/dist/constants/index.cjs +2 -2
  15. package/dist/constants/index.d.ts +4 -4
  16. package/dist/constants/index.d.ts.map +1 -1
  17. package/dist/constants/index.js +2 -2
  18. package/dist/constants/index.js.map +1 -1
  19. package/dist/dist.dev.js +2 -2
  20. package/dist/dist.min.js +2 -2
  21. package/dist/federated-table-scan-source.cjs +166 -564
  22. package/dist/federated-table-scan-source.cjs.map +3 -3
  23. package/dist/geoarrow/geoarrow-converter/convert-geoarrow-geometry.cjs +15 -0
  24. package/dist/geoarrow/geoarrow-converter/convert-geoarrow-geometry.cjs.map +2 -2
  25. package/dist/geoarrow/geoarrow-converter/convert-geoarrow-geometry.js +19 -1
  26. package/dist/geoarrow/geoarrow-converter/convert-geoarrow-geometry.js.map +1 -1
  27. package/dist/geoarrow/get-geoarrow-vertex-count.cjs +6 -27
  28. package/dist/geoarrow/get-geoarrow-vertex-count.cjs.map +2 -2
  29. package/dist/geoarrow/get-geoarrow-vertex-count.d.ts.map +1 -1
  30. package/dist/geoarrow/get-geoarrow-vertex-count.js +9 -24
  31. package/dist/geoarrow/get-geoarrow-vertex-count.js.map +1 -1
  32. package/dist/geoarrow/lib/geometry-converters/wkb/helpers/parse-wkb-header.cjs +3 -5
  33. package/dist/geoarrow/lib/geometry-converters/wkb/helpers/parse-wkb-header.cjs.map +2 -2
  34. package/dist/geoarrow/lib/geometry-converters/wkb/helpers/parse-wkb-header.d.ts +2 -24
  35. package/dist/geoarrow/lib/geometry-converters/wkb/helpers/parse-wkb-header.d.ts.map +1 -1
  36. package/dist/geoarrow/lib/geometry-converters/wkb/helpers/parse-wkb-header.js +6 -28
  37. package/dist/geoarrow/lib/geometry-converters/wkb/helpers/parse-wkb-header.js.map +1 -1
  38. package/dist/geoarrow/lib/kernels/decode-wkt-native.cjs +20 -226
  39. package/dist/geoarrow/lib/kernels/decode-wkt-native.cjs.map +2 -2
  40. package/dist/geoarrow/lib/kernels/decode-wkt-native.d.ts +1 -2
  41. package/dist/geoarrow/lib/kernels/decode-wkt-native.d.ts.map +1 -1
  42. package/dist/geoarrow/lib/kernels/decode-wkt-native.js +23 -264
  43. package/dist/geoarrow/lib/kernels/decode-wkt-native.js.map +1 -1
  44. package/dist/index.cjs +4 -4
  45. package/dist/index.cjs.map +1 -1
  46. package/dist/lib/init.js +1 -1
  47. package/dist/lib/init.js.map +1 -1
  48. package/dist/loader-utils/index.cjs +31 -217
  49. package/dist/loader-utils/index.cjs.map +2 -2
  50. package/dist/loader-utils/json-loader.js +1 -1
  51. package/dist/loader-utils/json-loader.js.map +1 -1
  52. package/dist/loader-utils/lib/log-utils/log.js +1 -1
  53. package/dist/loader-utils/lib/log-utils/log.js.map +1 -1
  54. package/dist/loader-utils/lib/scan-utils/columnar-predicate.d.ts +4 -52
  55. package/dist/loader-utils/lib/scan-utils/columnar-predicate.d.ts.map +1 -1
  56. package/dist/loader-utils/lib/scan-utils/columnar-predicate.js +16 -236
  57. package/dist/loader-utils/lib/scan-utils/columnar-predicate.js.map +1 -1
  58. package/dist/loader-utils/lib/scan-utils/relational-query.d.ts +2 -0
  59. package/dist/loader-utils/lib/scan-utils/relational-query.d.ts.map +1 -1
  60. package/dist/loader-utils/lib/scan-utils/relational-query.js.map +1 -1
  61. package/dist/null-loader.js +1 -1
  62. package/dist/null-loader.js.map +1 -1
  63. package/dist/null-worker-node.js +1 -1
  64. package/dist/null-worker.js +1 -1
  65. package/dist/scan/arrow-execution/expressions.cjs +9 -78
  66. package/dist/scan/arrow-execution/expressions.cjs.map +3 -3
  67. package/dist/scan/arrow-execution/expressions.d.ts +2 -8
  68. package/dist/scan/arrow-execution/expressions.d.ts.map +1 -1
  69. package/dist/scan/arrow-execution/expressions.js +2 -55
  70. package/dist/scan/arrow-execution/expressions.js.map +1 -1
  71. package/dist/scan/arrow-execution/filter-arrow-table.cjs +41 -179
  72. package/dist/scan/arrow-execution/filter-arrow-table.cjs.map +3 -3
  73. package/dist/scan/arrow-execution/filter-arrow-table.d.ts +1 -5
  74. package/dist/scan/arrow-execution/filter-arrow-table.d.ts.map +1 -1
  75. package/dist/scan/arrow-execution/filter-arrow-table.js +44 -190
  76. package/dist/scan/arrow-execution/filter-arrow-table.js.map +1 -1
  77. package/dist/scan/arrow-execution.cjs +2 -2
  78. package/dist/scan/arrow-execution.cjs.map +2 -2
  79. package/dist/scan/arrow-execution.d.ts +1 -1
  80. package/dist/scan/arrow-execution.d.ts.map +1 -1
  81. package/dist/scan/arrow-execution.js +1 -1
  82. package/dist/scan/arrow-execution.js.map +1 -1
  83. package/dist/scan/arrow-query.cjs +3 -3
  84. package/dist/scan/arrow-query.cjs.map +2 -2
  85. package/dist/scan/arrow-query.d.ts +2 -2
  86. package/dist/scan/arrow-query.d.ts.map +1 -1
  87. package/dist/scan/arrow-query.js +2 -2
  88. package/dist/scan/arrow-query.js.map +1 -1
  89. package/dist/scan/federated-table-scan-source.cjs +3 -3
  90. package/dist/scan/federated-table-scan-source.cjs.map +2 -2
  91. package/dist/scan/federated-table-scan-source.js +1 -1
  92. package/dist/scan/federated-table-scan-source.js.map +1 -1
  93. package/dist/scan/index.cjs +9 -49
  94. package/dist/scan/index.cjs.map +3 -3
  95. package/dist/scan/index.d.ts +2 -2
  96. package/dist/scan/index.d.ts.map +1 -1
  97. package/dist/scan/index.js +2 -2
  98. package/dist/scan/index.js.map +1 -1
  99. package/dist/scan/plan-arrow-table-query.cjs +271 -0
  100. package/dist/scan/plan-arrow-table-query.cjs.map +7 -0
  101. package/dist/scan/plan-arrow-table-query.d.ts +50 -0
  102. package/dist/scan/plan-arrow-table-query.d.ts.map +1 -0
  103. package/dist/scan/plan-arrow-table-query.js +257 -0
  104. package/dist/scan/plan-arrow-table-query.js.map +1 -0
  105. package/dist/scan/query-arrow-table-in-batches.cjs +2 -39
  106. package/dist/scan/query-arrow-table-in-batches.cjs.map +2 -2
  107. package/dist/scan/query-arrow-table-in-batches.d.ts +1 -1
  108. package/dist/scan/query-arrow-table-in-batches.d.ts.map +1 -1
  109. package/dist/scan/query-arrow-table-in-batches.js +3 -26
  110. package/dist/scan/query-arrow-table-in-batches.js.map +1 -1
  111. package/dist/scan/query-arrow-table.cjs +7 -443
  112. package/dist/scan/query-arrow-table.cjs.map +3 -3
  113. package/dist/scan/query-arrow-table.d.ts +6 -54
  114. package/dist/scan/query-arrow-table.d.ts.map +1 -1
  115. package/dist/scan/query-arrow-table.js +6 -475
  116. package/dist/scan/query-arrow-table.js.map +1 -1
  117. package/dist/scan/query-pushdown.cjs +3 -4
  118. package/dist/scan/query-pushdown.cjs.map +2 -2
  119. package/dist/scan/query-pushdown.js +4 -5
  120. package/dist/scan/query-pushdown.js.map +1 -1
  121. package/dist/scan/query.cjs +10 -9
  122. package/dist/scan/query.cjs.map +2 -2
  123. package/dist/scan/query.d.ts.map +1 -1
  124. package/dist/scan/query.js +14 -5
  125. package/dist/scan/query.js.map +1 -1
  126. package/dist/scan/scan-engine.cjs +14 -7
  127. package/dist/scan/scan-engine.cjs.map +2 -2
  128. package/dist/scan/scan-engine.d.ts +1 -1
  129. package/dist/scan/scan-engine.d.ts.map +1 -1
  130. package/dist/scan/scan-engine.js +4 -9
  131. package/dist/scan/scan-engine.js.map +1 -1
  132. package/dist/scan/vector-table-scan-source.cjs +14 -3
  133. package/dist/scan/vector-table-scan-source.cjs.map +2 -2
  134. package/dist/scan/vector-table-scan-source.d.ts +1 -1
  135. package/dist/scan/vector-table-scan-source.d.ts.map +1 -1
  136. package/dist/scan/vector-table-scan-source.js +2 -1
  137. package/dist/scan/vector-table-scan-source.js.map +1 -1
  138. package/dist/schema-utils/index.cjs +11 -47
  139. package/dist/schema-utils/index.cjs.map +1 -1
  140. package/dist/schema-utils/lib/arrow/arrow-metadata.d.ts +2 -4
  141. package/dist/schema-utils/lib/arrow/arrow-metadata.d.ts.map +1 -1
  142. package/dist/schema-utils/lib/arrow/arrow-metadata.js +2 -43
  143. package/dist/schema-utils/lib/arrow/arrow-metadata.js.map +1 -1
  144. package/dist/vector-table-scan-source.cjs +854 -1314
  145. package/dist/vector-table-scan-source.cjs.map +3 -3
  146. package/dist/wkt/twkb/index.cjs +68 -5
  147. package/dist/wkt/twkb/index.cjs.map +3 -3
  148. package/dist/wkt/twkb/index.d.ts +10 -2
  149. package/dist/wkt/twkb/index.d.ts.map +1 -1
  150. package/dist/wkt/twkb/index.js +49 -2
  151. package/dist/wkt/twkb/index.js.map +1 -1
  152. package/dist/worker-utils/index.cjs +4 -4
  153. package/dist/worker-utils/index.cjs.map +1 -1
  154. package/dist/worker-utils/lib/env-utils/version.js +1 -1
  155. package/dist/worker-utils/lib/env-utils/version.js.map +1 -1
  156. package/package.json +7 -7
  157. package/src/arrow-geometry/geometry-codecs.ts +35 -78
  158. package/src/arrow-geometry/triangulate-wkb.ts +37 -169
  159. package/src/constants/index.ts +2 -2
  160. package/src/geoarrow/geoarrow-converter/convert-geoarrow-geometry.ts +22 -1
  161. package/src/geoarrow/get-geoarrow-vertex-count.ts +7 -32
  162. package/src/geoarrow/lib/geometry-converters/wkb/helpers/parse-wkb-header.ts +6 -30
  163. package/src/geoarrow/lib/kernels/decode-wkt-native.ts +23 -269
  164. package/src/loader-utils/lib/scan-utils/columnar-predicate.ts +46 -363
  165. package/src/loader-utils/lib/scan-utils/relational-query.ts +7 -1
  166. package/src/scan/arrow-execution/expressions.ts +2 -86
  167. package/src/scan/arrow-execution/filter-arrow-table.ts +54 -238
  168. package/src/scan/arrow-execution.ts +1 -1
  169. package/src/scan/arrow-query.ts +2 -2
  170. package/src/scan/federated-table-scan-source.ts +1 -1
  171. package/src/scan/index.ts +2 -2
  172. package/src/scan/plan-arrow-table-query.ts +367 -0
  173. package/src/scan/query-arrow-table-in-batches.ts +4 -33
  174. package/src/scan/query-arrow-table.ts +10 -626
  175. package/src/scan/query-pushdown.ts +3 -4
  176. package/src/scan/query.ts +16 -10
  177. package/src/scan/scan-engine.ts +4 -11
  178. package/src/scan/vector-table-scan-source.ts +2 -1
  179. package/src/schema-utils/lib/arrow/arrow-metadata.ts +2 -50
  180. package/src/wkt/twkb/index.ts +63 -2
  181. package/dist/scan/arrow-execution/portable-predicate-compatibility.cjs +0 -41
  182. package/dist/scan/arrow-execution/portable-predicate-compatibility.cjs.map +0 -7
  183. package/dist/scan/arrow-execution/portable-predicate-compatibility.d.ts +0 -5
  184. package/dist/scan/arrow-execution/portable-predicate-compatibility.d.ts.map +0 -1
  185. package/dist/scan/arrow-execution/portable-predicate-compatibility.js +0 -23
  186. package/dist/scan/arrow-execution/portable-predicate-compatibility.js.map +0 -1
  187. package/dist/scan/arrow-execution/project-arrow-table.cjs +0 -70
  188. package/dist/scan/arrow-execution/project-arrow-table.cjs.map +0 -7
  189. package/dist/scan/arrow-execution/project-arrow-table.d.ts +0 -8
  190. package/dist/scan/arrow-execution/project-arrow-table.d.ts.map +0 -1
  191. package/dist/scan/arrow-execution/project-arrow-table.js +0 -39
  192. package/dist/scan/arrow-execution/project-arrow-table.js.map +0 -1
  193. package/dist/scan/query-arrow-table-math.cjs +0 -41
  194. package/dist/scan/query-arrow-table-math.cjs.map +0 -7
  195. package/dist/scan/query-arrow-table-math.d.ts +0 -5
  196. package/dist/scan/query-arrow-table-math.d.ts.map +0 -1
  197. package/dist/scan/query-arrow-table-math.js +0 -14
  198. package/dist/scan/query-arrow-table-math.js.map +0 -1
  199. package/dist/wkt/twkb/convert-geometry-to-twkb.cjs +0 -211
  200. package/dist/wkt/twkb/convert-geometry-to-twkb.cjs.map +0 -7
  201. package/dist/wkt/twkb/convert-geometry-to-twkb.d.ts +0 -6
  202. package/dist/wkt/twkb/convert-geometry-to-twkb.d.ts.map +0 -1
  203. package/dist/wkt/twkb/convert-geometry-to-twkb.js +0 -204
  204. package/dist/wkt/twkb/convert-geometry-to-twkb.js.map +0 -1
  205. package/dist/wkt/twkb/convert-twkb-to-geometry.cjs +0 -251
  206. package/dist/wkt/twkb/convert-twkb-to-geometry.cjs.map +0 -7
  207. package/dist/wkt/twkb/convert-twkb-to-geometry.d.ts +0 -10
  208. package/dist/wkt/twkb/convert-twkb-to-geometry.d.ts.map +0 -1
  209. package/dist/wkt/twkb/convert-twkb-to-geometry.js +0 -261
  210. package/dist/wkt/twkb/convert-twkb-to-geometry.js.map +0 -1
  211. package/dist/wkt/twkb/twkb-io.cjs +0 -102
  212. package/dist/wkt/twkb/twkb-io.cjs.map +0 -7
  213. package/dist/wkt/twkb/twkb-io.d.ts +0 -33
  214. package/dist/wkt/twkb/twkb-io.d.ts.map +0 -1
  215. package/dist/wkt/twkb/twkb-io.js +0 -78
  216. package/dist/wkt/twkb/twkb-io.js.map +0 -1
  217. package/dist/wkt/twkb/twkb-types.cjs +0 -40
  218. package/dist/wkt/twkb/twkb-types.cjs.map +0 -7
  219. package/dist/wkt/twkb/twkb-types.d.ts +0 -11
  220. package/dist/wkt/twkb/twkb-types.d.ts.map +0 -1
  221. package/dist/wkt/twkb/twkb-types.js +0 -15
  222. package/dist/wkt/twkb/twkb-types.js.map +0 -1
  223. package/src/scan/arrow-execution/portable-predicate-compatibility.ts +0 -27
  224. package/src/scan/arrow-execution/project-arrow-table.ts +0 -53
  225. package/src/scan/query-arrow-table-math.ts +0 -23
  226. package/src/wkt/twkb/convert-geometry-to-twkb.ts +0 -317
  227. package/src/wkt/twkb/convert-twkb-to-geometry.ts +0 -373
  228. package/src/wkt/twkb/twkb-io.ts +0 -85
  229. 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,1230 +35,611 @@ 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));
476
- }
477
- function makeArrowMetadataBatch(schema) {
478
- return new arrow2.RecordBatch(snapshotArrowSchema(schema), void 0);
391
+ function dateToMilliseconds(value) {
392
+ return value instanceof Date ? value.getTime() : value;
479
393
  }
480
-
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
- }
485
-
486
- // src/loader-utils/lib/scan-utils/columnar-predicate.ts
487
- function getColumnarPredicateColumns(predicate) {
488
- return [...new Set(getColumnarPredicatePaths(predicate).map((path) => path[0]))];
489
- }
490
- function getColumnarPredicatePath(property) {
491
- return typeof property.property === "string" ? [property.property] : [...property.property];
492
- }
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()];
502
- }
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;
509
- }
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");
515
- }
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");
520
- }
521
- });
522
- }
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;
526
- }
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);
532
- }
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 })
545
- });
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
- });
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);
558
412
  }
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
590
- });
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);
591
419
  }
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
- }
597
- return;
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();
598
428
  }
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
- );
429
+ });
430
+
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();
608
438
  }
439
+ });
440
+
441
+ // dist/scan/sql-predicate-schema.js
442
+ function validateSQLPredicate(value) {
443
+ (0, import_parser.validateSQLPredicate)(value);
444
+ rejectPredicateCasts(value, "$");
609
445
  }
610
- function getNonEmptyMetadataValue(metadata, key) {
611
- const value = metadata == null ? void 0 : metadata[key];
612
- return value || void 0;
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
+ }
613
452
  }
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
+ });
614
460
 
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
- ];
461
+ // dist/scan/table-query.js
462
+ function planTableQuery2(sourceColumnNames, options = {}) {
627
463
  if (options.predicate) {
628
- steps.push(Object.freeze({ kind: "filter", predicate: options.predicate }));
629
- }
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 }));
464
+ validateSQLPredicate(options.predicate);
633
465
  }
634
- return Object.freeze(steps);
466
+ return planTableQuery(sourceColumnNames, options);
635
467
  }
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}`);
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.");
646
481
  }
647
- seenColumnNames.add(columnName);
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
+ });
648
494
  }
649
- validateTableQueryLimit(options.limit);
650
495
  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.");
496
+ validateSQLPredicate(options.predicate);
657
497
  }
498
+ return explainTableQuery(sourceTable.schema.fields.map((field) => field.name), options, ARROW_TABLE_QUERY_CAPABILITIES);
658
499
  }
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}`);
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.");
669
505
  }
670
- expressionNames.add(expression.name);
506
+ return (execute ?? executePortableArrowQuery)(sourceTable, {
507
+ where: options.predicate,
508
+ select: options.select,
509
+ limit: options.limit,
510
+ signal: options.signal
511
+ });
671
512
  }
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);
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
+ }
686
519
  }
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);
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);
693
523
  }
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, {
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, {
699
547
  ...options,
700
548
  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]) });
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 });
711
560
  }
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
- });
795
-
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
- }
825
-
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;
921
- }
922
- function evaluateOr(values) {
923
- if (values.includes(true)) {
924
- return true;
925
- }
926
- return values.includes(null) ? null : false;
927
- }
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;
938
- }
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
- }
958
- }
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);
983
- }
984
- if (typeof left === "string" && typeof right === "string") {
985
- return left === right ? 0 : left < right ? -1 : 1;
986
- }
987
- if (typeof left === "boolean" && typeof right === "boolean") {
988
- return Number(left) - Number(right);
989
- }
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.");
995
- }
996
- return left === right ? 0 : left < right ? -1 : 1;
997
- }
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;
1006
- }
1007
- function getArrowQueryValueType(value) {
1008
- if (value instanceof Date) {
1009
- return "Date";
1010
- }
1011
- if (value instanceof Uint8Array) {
1012
- return "Uint8Array";
1013
- }
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-schema.js
1036
- var import_parser = require("@math.gl/sql/parser");
1037
- function validateSQLPredicate(value) {
1038
- (0, import_parser.validateSQLPredicate)(value);
1039
- rejectPredicateCasts(value, "$");
1040
- }
1041
- function rejectPredicateCasts(predicate, path) {
1042
- if (predicate.op === "and" || predicate.op === "or" || predicate.op === "not") {
1043
- predicate.args.forEach((child, index) => rejectPredicateCasts(child, path + ".args[" + index + "]"));
1044
- } else if (Object.hasOwn(predicate.args[0], "casts")) {
1045
- throw new Error("SQL predicate " + path + ".args[0] requires a non-empty property reference");
1046
- }
1047
- }
1048
-
1049
- // dist/scan/table-query.js
1050
- function planTableQuery2(sourceColumnNames, options = {}) {
1051
- if (options.predicate) {
1052
- validateSQLPredicate(options.predicate);
1053
- }
1054
- return planTableQuery(sourceColumnNames, options);
1055
- }
1056
-
1057
- // dist/scan/query-arrow-table.js
1058
- function explainArrowTableQuery(sourceTable, options = {}) {
1059
- if (options.select !== void 0) {
1060
- if (options.columns !== void 0 || hasRelationalOperators(options) || options.join) {
1061
- throw new Error("Arrow select cannot be combined with columns or relational operators.");
1062
- }
1063
- const projected = projectArrowTable(sourceTable, options.select);
1064
- const columns = [
1065
- ...new Set(options.select.map((selection) => typeof selection === "string" ? selection : selection.column))
1066
- ];
1067
- const { select, ...remainingOptions } = options;
1068
- const explanation = explainArrowTableQuery(sourceTable, { ...remainingOptions, columns });
1069
- const outputColumns = Object.freeze(projected.schema.fields.map((field) => field.name));
1070
- return Object.freeze({
1071
- ...explanation,
1072
- outputColumns,
1073
- plan: Object.freeze(explanation.plan.map((step) => step.kind === "project" ? Object.freeze({ ...step, columns: outputColumns, select }) : step))
1074
- });
1075
- }
1076
- if (options.predicate) {
1077
- validateSQLPredicate(options.predicate);
1078
- }
1079
- return explainTableQuery(sourceTable.schema.fields.map((field) => field.name), options, ARROW_TABLE_QUERY_CAPABILITIES);
1080
- }
1081
- var executePortableArrowQuery = (table, { select, where, limit, signal }) => {
1082
- if (where)
1083
- table = filterArrowTable(table, where, { limit, signal });
1084
- const projected = select ? projectArrowTable(table, select) : table;
1085
- return projected.numRows === 0 || limit === void 0 ? projected : projected.slice(0, limit);
1086
- };
1087
- function queryArrowTable(sourceTable, options = {}, executeLinear = executePortableArrowQuery) {
1088
- throwIfAborted(options.signal);
1089
- if (options.select !== void 0) {
1090
- if (options.columns !== void 0 || hasRelationalOperators(options) || options.join) {
1091
- throw new Error("Arrow select cannot be combined with columns or relational operators.");
1092
- }
1093
- projectArrowTable(sourceTable, options.select);
1094
- const columns = [
1095
- ...new Set(options.select.map((selection) => typeof selection === "string" ? selection : selection.column))
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 }
1096
565
  ];
1097
- const { select, ...remainingOptions } = options;
1098
- const result = queryArrowTable(sourceTable, { ...remainingOptions, columns }, executeLinear);
1099
- return projectArrowTable(result, select);
1100
- }
1101
- if (options.join) {
1102
- validateArrowJoinQuery(sourceTable, options);
1103
- }
1104
- if (options.join && hasRelationalOperatorsExceptJoin(options)) {
1105
- throw new Error("Arrow joins cannot yet be combined with other relational operators.");
1106
- }
1107
- if (options.join && !hasRelationalOperatorsExceptJoin(options)) {
1108
- return queryArrowJoin(sourceTable, options);
1109
- }
1110
- if (hasRelationalOperators(options)) {
1111
- return queryArrowTableRelational(sourceTable, options);
1112
- }
1113
- const plan = planTableQuery2(sourceTable.schema.fields.map((field) => field.name), options);
1114
- const projection = plan.find((step) => step.kind === "project");
1115
- return executeLinear(sourceTable, {
1116
- where: options.predicate,
1117
- select: projection == null ? void 0 : projection.columns,
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,
1118
582
  limit: options.limit,
1119
583
  signal: options.signal
1120
584
  });
1121
585
  }
1122
- function queryArrowTableRelational(sourceTable, options) {
1123
- var _a, _b, _c, _d, _e, _f;
1124
- const sourceData = sourceTable;
1125
- const sourceColumnNames = sourceData.schema.fields.map((field) => field.name);
1126
- const relationalPlan = planRelationalQuery(sourceColumnNames, options);
1127
- const scanStep = relationalPlan.tablePlan.find((step) => step.kind === "scan");
1128
- if (!scanStep || scanStep.kind !== "scan") {
1129
- throw new Error("Arrow relational query plan is missing a scan step.");
1130
- }
1131
- const scannedTable = sourceData.select([...scanStep.columns]);
1132
- const filteredTable = queryArrowTable(scannedTable, {
1133
- predicate: options.predicate,
1134
- columns: scanStep.columns,
1135
- signal: options.signal
1136
- });
1137
- let rows = arrowTableToRows(filteredTable);
1138
- for (const child of options.union || []) {
1139
- const childTable = (_a = options.tables) == null ? void 0 : _a[child.source];
1140
- if (!childTable)
1141
- throw new Error(`Arrow union source not found: ${child.source}`);
1142
- const childResult = queryArrowTable(childTable, {
1143
- ...child.query || {},
1144
- columns: getUnionChildColumns(sourceColumnNames, options),
1145
- signal: options.signal
1146
- });
1147
- rows = rows.concat(arrowTableToRows(childResult));
1148
- }
1149
- for (const expression of options.expressions || []) {
1150
- for (const row of rows) {
1151
- row[expression.name] = evaluateRelationalExpression(expression, row);
1152
- }
1153
- }
1154
- if (((_b = options.groupBy) == null ? void 0 : _b.length) || ((_c = options.aggregates) == null ? void 0 : _c.length)) {
1155
- rows = aggregateRows(rows, options.groupBy || [], options.aggregates || []);
1156
- }
1157
- if ((_d = options.orderBy) == null ? void 0 : _d.length) {
1158
- const orderBy = options.orderBy;
1159
- rows = rows.map((row, index) => ({ row, index })).sort((left, right) => compareRows(left.row, right.row, orderBy) || left.index - right.index).map((entry) => entry.row);
1160
- }
1161
- 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);
1162
- const outputRows = rows.map((row) => {
1163
- const output = {};
1164
- for (const columnName of outputColumns) {
1165
- if (!(columnName in row)) {
1166
- throw new Error(`Arrow relational query column not found: ${columnName}`);
1167
- }
1168
- output[columnName] = row[columnName];
1169
- }
1170
- return output;
1171
- });
1172
- const limit = options.limit === void 0 ? outputRows.length : options.limit;
1173
- const limitedRows = outputRows.slice(0, limit);
1174
- return limitedRows.length ? convertRowsToArrowTable(limitedRows) : createEmptyRelationalResult(sourceData, outputColumns, options);
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
+ };
1175
607
  }
1176
- function getUnionChildColumns(sourceColumnNames, options) {
1177
- var _a, _b;
1178
- const expressionNames = new Set((options.expressions || []).map((expression) => expression.name));
1179
- const aggregateNames = new Set((options.aggregates || []).map((aggregate) => aggregate.name));
1180
- 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);
1181
- const requiredColumns = new Set(outputColumns.filter((column) => !expressionNames.has(column) && !aggregateNames.has(column)));
1182
- for (const expression of options.expressions || []) {
1183
- const definition = expression.expression;
1184
- if (definition.op === "column")
1185
- requiredColumns.add(definition.column);
1186
- if ("left" in definition) {
1187
- requiredColumns.add(definition.left);
1188
- requiredColumns.add(definition.right);
1189
- }
1190
- }
1191
- for (const key of options.orderBy || []) {
1192
- if (!expressionNames.has(key.column) && !aggregateNames.has(key.column)) {
1193
- requiredColumns.add(key.column);
1194
- }
1195
- }
1196
- for (const column of options.groupBy || [])
1197
- requiredColumns.add(column);
1198
- for (const aggregate of options.aggregates || []) {
1199
- if (aggregate.column)
1200
- requiredColumns.add(aggregate.column);
1201
- }
1202
- return sourceColumnNames.filter((column) => requiredColumns.has(column));
608
+ function literal(value) {
609
+ return { type: "Literal", value };
1203
610
  }
1204
611
  function hasRelationalOperators(options) {
1205
- var _a, _b, _c, _d, _e;
1206
- 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);
1207
- }
1208
- function hasRelationalOperatorsExceptJoin(options) {
1209
612
  var _a, _b, _c, _d, _e;
1210
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));
1211
614
  }
1212
- function queryArrowJoin(sourceTable, options) {
1213
- var _a;
615
+ function queryArrowJoin(sourceTable, options, executeRelational) {
616
+ var _a, _b, _c, _d;
1214
617
  const join = options.join;
1215
- if (!join)
1216
- throw new Error("Arrow join query is missing a join definition.");
1217
618
  const childTable = (_a = options.tables) == null ? void 0 : _a[join.child.source];
1218
619
  if (!childTable)
1219
620
  throw new Error(`Arrow join source not found: ${join.child.source}`);
1220
- const leftResult = queryArrowTable(sourceTable, {
1221
- predicate: options.predicate,
1222
- columns: void 0,
621
+ const left = executeRelational(sourceTable, {
622
+ where: options.predicate,
1223
623
  signal: options.signal
1224
624
  });
1225
- const rightResult = queryArrowTable(childTable, {
1226
- ...join.child.query || {},
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,
1227
641
  signal: options.signal
1228
642
  });
1229
- const leftRows = arrowTableToRows(leftResult);
1230
- const rightRows = arrowTableToRows(rightResult);
1231
- const rightPrefix = `${join.child.source}.`;
1232
- const defaultOutputColumns = [
1233
- ...sourceTable.schema.fields.map((field) => field.name),
1234
- ...rightResult.schema.fields.map((field) => `${rightPrefix}${field.name}`)
1235
- ];
1236
- const rows = [];
1237
- for (const leftRow of leftRows) {
1238
- for (const rightRow of rightRows) {
1239
- 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) {
1240
- rows.push({
1241
- ...leftRow,
1242
- ...Object.fromEntries(Object.entries(rightRow).map(([key, value]) => [`${rightPrefix}${key}`, value]))
1243
- });
1244
- }
1245
- }
1246
- }
1247
- const outputColumns = options.columns || defaultOutputColumns;
1248
- const outputRows = rows.map((row) => Object.fromEntries(outputColumns.map((column) => [column, row[column]])));
1249
- const limitedRows = outputRows.slice(0, options.limit);
1250
- return limitedRows.length ? convertRowsToArrowTable(limitedRows) : createEmptyRelationalResult(sourceTable, outputColumns, options, new Map(rightResult.schema.fields.map((field) => [
1251
- `${rightPrefix}${field.name}`,
1252
- new arrow6.Field(`${rightPrefix}${field.name}`, field.type, field.nullable, field.metadata)
1253
- ])));
1254
643
  }
1255
644
  function validateArrowJoinQuery(sourceTable, options) {
1256
645
  var _a, _b, _c;
@@ -1298,180 +687,330 @@ function validateArrowJoinQuery(sourceTable, options) {
1298
687
  }
1299
688
  }
1300
689
  }
1301
- function arrowTableToRows(data) {
1302
- const columns = data.schema.fields.map((field) => ({
1303
- name: field.name,
1304
- vector: data.getChild(field.name)
1305
- }));
1306
- return Array.from({ length: data.numRows }, (_, rowIndex) => {
1307
- const row = {};
1308
- for (const column of columns) {
1309
- if (!column.vector)
1310
- throw new Error(`Arrow relational query could not read ${column.name}`);
1311
- row[column.name] = column.vector.get(rowIndex);
1312
- }
1313
- return row;
1314
- });
1315
- }
1316
- function evaluateRelationalExpression(expression, row) {
1317
- const definition = expression.expression;
1318
- if (definition.op === "literal")
1319
- return definition.value;
1320
- if (definition.op === "column")
1321
- return row[definition.column];
1322
- const left = row[definition.left];
1323
- const right = row[definition.right];
1324
- if (left === null || left === void 0 || right === null || right === void 0)
1325
- return null;
1326
- if (typeof left !== "number" || typeof right !== "number") {
1327
- throw new Error(`Arrow relational expression ${expression.name} requires numeric operands.`);
1328
- }
1329
- switch (definition.op) {
1330
- case "add":
1331
- return left + right;
1332
- case "subtract":
1333
- return left - right;
1334
- case "multiply":
1335
- return left * right;
1336
- case "divide":
1337
- return right === 0 ? null : left / right;
1338
- }
1339
- }
1340
- function compareRows(left, right, orderBy) {
1341
- for (const key of orderBy) {
1342
- const leftValue = left[key.column];
1343
- const rightValue = right[key.column];
1344
- const nulls = key.nulls || "last";
1345
- if (leftValue === null || leftValue === void 0 || rightValue === null || rightValue === void 0) {
1346
- if (leftValue === rightValue)
1347
- continue;
1348
- const nullResult = leftValue === null || leftValue === void 0 ? -1 : 1;
1349
- return nulls === "first" ? nullResult : -nullResult;
1350
- }
1351
- const result = compareSortValues(leftValue, rightValue);
1352
- if (result)
1353
- return (key.direction === "desc" ? -1 : 1) * result;
1354
- }
1355
- return 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
+ }
1356
696
  }
1357
- function compareSortValues(left, right) {
1358
- if (left instanceof Date && right instanceof Date)
1359
- return compareArrowQueryNumbers(left.getTime(), right.getTime());
1360
- if (typeof left === "bigint" && typeof right === "bigint")
1361
- return left === right ? 0 : left < right ? -1 : 1;
1362
- if (typeof left === "number" && typeof right === "number")
1363
- return compareArrowQueryNumbers(left, right);
1364
- if (typeof left === "string" && typeof right === "string")
1365
- return left === right ? 0 : left < right ? -1 : 1;
1366
- if (typeof left === "boolean" && typeof right === "boolean")
1367
- return Number(left) - Number(right);
1368
- throw new Error(`Arrow relational order cannot compare ${getArrowQueryValueType(left)} with ${getArrowQueryValueType(right)}.`);
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
+ });
714
+
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);
1369
724
  }
1370
- function aggregateRows(rows, groupBy, aggregates) {
1371
- const groups = /* @__PURE__ */ new Map();
1372
- for (const row of rows) {
1373
- const key = serializeGroupKey(groupBy.map((column) => row[column]));
1374
- const group = groups.get(key) || [];
1375
- group.push(row);
1376
- groups.set(key, group);
1377
- }
1378
- if (!groupBy.length && !rows.length)
1379
- groups.set("[]", []);
1380
- return [...groups.values()].map((group) => {
1381
- var _a;
1382
- const output = {};
1383
- for (const column of groupBy)
1384
- output[column] = ((_a = group[0]) == null ? void 0 : _a[column]) ?? null;
1385
- for (const aggregate of aggregates)
1386
- output[aggregate.name] = evaluateAggregate(aggregate, group);
1387
- return output;
1388
- });
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();
732
+ }
733
+ });
734
+
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);
743
+
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);
1389
748
  }
1390
- function serializeGroupKey(values) {
1391
- return values.map((value) => {
1392
- if (value === null || value === void 0)
1393
- return "null:";
1394
- if (value instanceof Date)
1395
- return `date:${value.getTime()}`;
1396
- if (value instanceof Uint8Array)
1397
- return `bytes:${Array.from(value).join(".")}`;
1398
- return `${typeof value}:${String(value)}`;
1399
- }).join("");
749
+ function serializeArrowSchema(arrowSchema) {
750
+ return {
751
+ fields: arrowSchema.fields.map((arrowField) => serializeArrowField(arrowField)),
752
+ metadata: serializeArrowMetadata(arrowSchema.metadata)
753
+ };
1400
754
  }
1401
- function createEmptyRelationalResult(sourceData, outputColumns, options, additionalFields) {
1402
- const sourceFields = new Map(sourceData.schema.fields.map((field) => [field.name, field]));
1403
- const expressions = new Map((options.expressions || []).map((expression) => [expression.name, expression]));
1404
- const aggregates = new Map((options.aggregates || []).map((aggregate) => [aggregate.name, aggregate]));
1405
- const fields = outputColumns.map((columnName) => {
1406
- const sourceField = sourceFields.get(columnName);
1407
- if (sourceField)
1408
- return sourceField;
1409
- const additionalField = additionalFields == null ? void 0 : additionalFields.get(columnName);
1410
- if (additionalField)
1411
- return additionalField;
1412
- const expression = expressions.get(columnName);
1413
- if (expression)
1414
- return new arrow6.Field(columnName, getExpressionType(expression, sourceFields), true);
1415
- const aggregate = aggregates.get(columnName);
1416
- if (aggregate)
1417
- return new arrow6.Field(columnName, getAggregateType(aggregate, sourceFields), true);
1418
- return new arrow6.Field(columnName, new arrow6.Utf8(), true);
1419
- });
1420
- const columns = {};
1421
- for (const field of fields)
1422
- columns[field.name] = arrow6.vectorFromArray([], field.type);
1423
- return new arrow6.Table(new arrow6.Schema(fields), columns);
755
+ function serializeArrowMetadata(arrowMetadata) {
756
+ return Object.fromEntries(arrowMetadata);
757
+ }
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
+ };
1424
765
  }
1425
- function getExpressionType(expression, sourceFields) {
1426
- var _a;
1427
- if (expression.expression.op === "literal") {
1428
- const value = expression.expression.value;
1429
- if (typeof value === "boolean")
1430
- return new arrow6.Bool();
1431
- if (typeof value === "number")
1432
- return new arrow6.Float64();
1433
- return new arrow6.Utf8();
1434
- }
1435
- if (expression.expression.op === "column") {
1436
- return ((_a = sourceFields.get(expression.expression.column)) == null ? void 0 : _a.type) || new arrow6.Utf8();
1437
- }
1438
- return new arrow6.Float64();
766
+ function serializeArrowType(arrowType) {
767
+ if (isArrowViewType(arrowType, "BinaryView")) {
768
+ return "binary-view";
769
+ }
770
+ if (isArrowViewType(arrowType, "Utf8View")) {
771
+ return "utf8-view";
772
+ }
773
+ if (isOptionalArrowType(arrowType, "LargeList")) {
774
+ const largeListType = arrowType;
775
+ return {
776
+ type: "large-list",
777
+ children: [serializeArrowField(largeListType.valueField)]
778
+ };
779
+ }
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}`);
951
+ }
1439
952
  }
1440
- function getAggregateType(aggregate, sourceFields) {
1441
- var _a;
1442
- if (aggregate.function === "count")
1443
- return new arrow6.Int32();
1444
- return aggregate.column ? ((_a = sourceFields.get(aggregate.column)) == null ? void 0 : _a.type) || new arrow6.Float64() : new arrow6.Float64();
953
+ function getOptionalArrowConstructor(typeName) {
954
+ return arrow[typeName];
1445
955
  }
1446
- function evaluateAggregate(aggregate, rows) {
1447
- if (aggregate.function === "count")
1448
- return aggregate.column ? rows.filter((row) => row[aggregate.column] != null).length : rows.length;
1449
- const values = rows.map((row) => row[aggregate.column]).filter((value) => value != null);
1450
- if (!values.length)
1451
- return null;
1452
- if (!values.every((value) => typeof value === "number"))
1453
- throw new Error(`Arrow aggregate ${aggregate.function} requires numeric values.`);
1454
- const numericValues = values;
1455
- switch (aggregate.function) {
1456
- case "sum":
1457
- return numericValues.reduce((sum, value) => sum + value, 0);
1458
- case "avg":
1459
- return numericValues.reduce((sum, value) => sum + value, 0) / numericValues.length;
1460
- case "min":
1461
- return Math.min(...numericValues);
1462
- case "max":
1463
- return Math.max(...numericValues);
956
+ function isArrowViewType(arrowType, viewTypeName) {
957
+ const constructor = getOptionalArrowConstructor(viewTypeName);
958
+ if (constructor && arrowType instanceof constructor) {
959
+ return true;
1464
960
  }
961
+ const guards = arrow.DataType;
962
+ const guard = viewTypeName === "BinaryView" ? guards.isBinaryView : guards.isUtf8View;
963
+ return Boolean(guard == null ? void 0 : guard(arrowType));
1465
964
  }
1466
- function throwIfAborted(signal) {
1467
- if (signal == null ? void 0 : signal.aborted) {
1468
- const error = new Error("Arrow query was aborted.");
1469
- error.name = "AbortError";
1470
- throw error;
965
+ function isOptionalArrowType(arrowType, typeName) {
966
+ const constructor = getOptionalArrowConstructor(typeName);
967
+ return Boolean(constructor && arrowType instanceof constructor);
968
+ }
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
+ }
1471
976
  }
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";
990
+ default:
991
+ throw new Error(`arrow dictionary index type not supported: ${arrowType.constructor.name}`);
992
+ }
993
+ }
994
+ function isSchemaDictionaryKeyType(keyType) {
995
+ return ["int8", "int16", "int32", "uint8", "uint16", "uint32"].includes(keyType);
996
+ }
997
+
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);
1003
+ }
1004
+
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");
1472
1008
  }
1473
1009
 
1474
1010
  // dist/scan/vector-table-scan-source.js
1011
+ init_loader_utils();
1012
+ init_table_query_capabilities();
1013
+ init_plan_arrow_table_query();
1475
1014
  var AddressedVectorTableScanSource = class {
1476
1015
  /** Stable adapter type reported by `getQueryMetadata()`. */
1477
1016
  sourceType;
@@ -1513,7 +1052,8 @@ var AddressedVectorTableScanSource = class {
1513
1052
  /** Applies the portable Arrow query to the addressed feature table. */
1514
1053
  async query(options = {}) {
1515
1054
  const table = await this.getTable(options.signal);
1516
- 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);
1517
1057
  }
1518
1058
  /** Explains the residual Arrow plan after resolving the addressed feature table. */
1519
1059
  async explain(options = {}) {