@malloy-publisher/server 0.0.235 → 0.0.236

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 (301) hide show
  1. package/dist/app/api-doc.yaml +47 -17
  2. package/dist/package_load_worker.mjs +8 -1
  3. package/dist/server.mjs +471 -54
  4. package/package.json +5 -2
  5. package/.eslintrc.json +0 -44
  6. package/.prettierignore +0 -1
  7. package/.prettierrc +0 -4
  8. package/build.ts +0 -97
  9. package/eslint.config.mjs +0 -76
  10. package/k6-tests/README.md +0 -144
  11. package/k6-tests/bun.lock +0 -797
  12. package/k6-tests/load-test/load-test-crud-connections.ts +0 -263
  13. package/k6-tests/load-test/load-test-crud-packages.ts +0 -461
  14. package/k6-tests/load-test/load-test-crud-projects.ts +0 -160
  15. package/k6-tests/load-test/load-test-crud.ts +0 -142
  16. package/k6-tests/load-test/load-test.ts +0 -784
  17. package/k6-tests/package.json +0 -27
  18. package/k6-tests/scripts/run-with-otel.sh +0 -50
  19. package/k6-tests/smoke-test/smoke-test.ts +0 -158
  20. package/k6-tests/tsconfig.json +0 -29
  21. package/k6-tests/utils/client_factory.ts +0 -128
  22. package/k6-tests/utils/common.ts +0 -489
  23. package/k6-tests/utils/logger.ts +0 -62
  24. package/k6-tests/utils/types.d.ts +0 -35
  25. package/malloy_mcp.dxt +0 -0
  26. package/publisher.config.example.bigquery.json +0 -33
  27. package/publisher.config.example.duckdb.json +0 -23
  28. package/publisher.config.json +0 -23
  29. package/scripts/bake-duckdb-extensions.js +0 -110
  30. package/src/config.spec.ts +0 -1535
  31. package/src/config.theme.spec.ts +0 -178
  32. package/src/config.ts +0 -1142
  33. package/src/constants.ts +0 -105
  34. package/src/controller/compile.controller.ts +0 -40
  35. package/src/controller/connection.controller.spec.ts +0 -849
  36. package/src/controller/connection.controller.ts +0 -901
  37. package/src/controller/database.controller.ts +0 -24
  38. package/src/controller/materialization.controller.spec.ts +0 -293
  39. package/src/controller/materialization.controller.ts +0 -319
  40. package/src/controller/model.controller.ts +0 -164
  41. package/src/controller/package.controller.spec.ts +0 -273
  42. package/src/controller/package.controller.ts +0 -306
  43. package/src/controller/query.controller.ts +0 -152
  44. package/src/controller/theme.controller.ts +0 -83
  45. package/src/controller/watch-mode.controller.ts +0 -243
  46. package/src/data_styles.ts +0 -71
  47. package/src/default-publisher.config.json +0 -23
  48. package/src/ducklake_version.spec.ts +0 -163
  49. package/src/ducklake_version.ts +0 -153
  50. package/src/errors.spec.ts +0 -119
  51. package/src/errors.ts +0 -237
  52. package/src/filter_deprecation.spec.ts +0 -64
  53. package/src/filter_deprecation.ts +0 -42
  54. package/src/health.spec.ts +0 -123
  55. package/src/health.ts +0 -233
  56. package/src/heap_check.spec.ts +0 -144
  57. package/src/heap_check.ts +0 -144
  58. package/src/instrumentation.ts +0 -214
  59. package/src/json_utils.spec.ts +0 -51
  60. package/src/json_utils.ts +0 -33
  61. package/src/logger.spec.ts +0 -210
  62. package/src/logger.ts +0 -251
  63. package/src/malloy_pin_prereqs.spec.ts +0 -25
  64. package/src/materialization_metrics.spec.ts +0 -169
  65. package/src/materialization_metrics.ts +0 -346
  66. package/src/mcp/error_messages.spec.ts +0 -35
  67. package/src/mcp/error_messages.ts +0 -183
  68. package/src/mcp/handler_utils.spec.ts +0 -108
  69. package/src/mcp/handler_utils.ts +0 -251
  70. package/src/mcp/mcp_constants.ts +0 -6
  71. package/src/mcp/query_envelope.spec.ts +0 -229
  72. package/src/mcp/query_envelope.ts +0 -240
  73. package/src/mcp/server.protocol.spec.ts +0 -250
  74. package/src/mcp/server.ts +0 -87
  75. package/src/mcp/skills/build_skills_bundle.spec.ts +0 -51
  76. package/src/mcp/skills/build_skills_bundle.ts +0 -176
  77. package/src/mcp/skills/skills_bundle.json +0 -1
  78. package/src/mcp/skills/skills_bundle.spec.ts +0 -171
  79. package/src/mcp/tool_response.spec.ts +0 -108
  80. package/src/mcp/tool_response.ts +0 -138
  81. package/src/mcp/tools/compile_tool.spec.ts +0 -315
  82. package/src/mcp/tools/compile_tool.ts +0 -208
  83. package/src/mcp/tools/docs_search/build_docs_index.ts +0 -132
  84. package/src/mcp/tools/docs_search/malloy_docs_index.json +0 -1
  85. package/src/mcp/tools/docs_search_tool.spec.ts +0 -32
  86. package/src/mcp/tools/docs_search_tool.ts +0 -128
  87. package/src/mcp/tools/embedding_index.spec.ts +0 -1236
  88. package/src/mcp/tools/embedding_index.ts +0 -808
  89. package/src/mcp/tools/execute_query_tool.spec.ts +0 -294
  90. package/src/mcp/tools/execute_query_tool.ts +0 -316
  91. package/src/mcp/tools/get_context_eval.ts +0 -275
  92. package/src/mcp/tools/get_context_tool.spec.ts +0 -592
  93. package/src/mcp/tools/get_context_tool.ts +0 -585
  94. package/src/mcp/tools/reload_package_tool.spec.ts +0 -232
  95. package/src/mcp/tools/reload_package_tool.ts +0 -132
  96. package/src/mcp_config.spec.ts +0 -919
  97. package/src/mcp_config.ts +0 -425
  98. package/src/oom_guards.integration.spec.ts +0 -269
  99. package/src/package_load/package_load_pool.spec.ts +0 -252
  100. package/src/package_load/package_load_pool.ts +0 -931
  101. package/src/package_load/package_load_worker.ts +0 -1034
  102. package/src/package_load/protocol.ts +0 -364
  103. package/src/package_load/rpc_wait_accountant.spec.ts +0 -109
  104. package/src/package_load/rpc_wait_accountant.ts +0 -76
  105. package/src/package_load_metrics.spec.ts +0 -114
  106. package/src/package_load_metrics.ts +0 -127
  107. package/src/path_safety.spec.ts +0 -158
  108. package/src/path_safety.ts +0 -146
  109. package/src/pg_helpers.spec.ts +0 -223
  110. package/src/pg_helpers.ts +0 -52
  111. package/src/query_cap_metrics.spec.ts +0 -89
  112. package/src/query_cap_metrics.ts +0 -116
  113. package/src/query_concurrency.spec.ts +0 -247
  114. package/src/query_concurrency.ts +0 -237
  115. package/src/query_metadata_metrics.ts +0 -49
  116. package/src/query_param_utils.ts +0 -29
  117. package/src/query_timeout.spec.ts +0 -224
  118. package/src/query_timeout.ts +0 -179
  119. package/src/runtime/publisher.js +0 -328
  120. package/src/server-old.ts +0 -988
  121. package/src/server.ts +0 -2059
  122. package/src/service/annotations.spec.ts +0 -118
  123. package/src/service/annotations.ts +0 -91
  124. package/src/service/authorize.spec.ts +0 -154
  125. package/src/service/authorize.ts +0 -498
  126. package/src/service/authorize_integration.spec.ts +0 -2041
  127. package/src/service/build_plan.spec.ts +0 -685
  128. package/src/service/build_plan.ts +0 -797
  129. package/src/service/compile_authorize.spec.ts +0 -85
  130. package/src/service/compile_fragment_techniques.spec.ts +0 -156
  131. package/src/service/connection.spec.ts +0 -2360
  132. package/src/service/connection.ts +0 -2187
  133. package/src/service/connection_config.spec.ts +0 -734
  134. package/src/service/connection_config.ts +0 -899
  135. package/src/service/connection_federation.spec.ts +0 -184
  136. package/src/service/connection_fingerprint.spec.ts +0 -102
  137. package/src/service/connection_service.spec.ts +0 -711
  138. package/src/service/connection_service.ts +0 -291
  139. package/src/service/cron_evaluator.spec.ts +0 -79
  140. package/src/service/cron_evaluator.ts +0 -105
  141. package/src/service/db_utils.spec.ts +0 -1085
  142. package/src/service/db_utils.ts +0 -1502
  143. package/src/service/duckdb_instance_isolation.spec.ts +0 -137
  144. package/src/service/ducklake_lazy_attach.spec.ts +0 -110
  145. package/src/service/embedding_provider.spec.ts +0 -329
  146. package/src/service/embedding_provider.ts +0 -236
  147. package/src/service/environment.ts +0 -2191
  148. package/src/service/environment_admission.spec.ts +0 -344
  149. package/src/service/environment_compile.spec.ts +0 -197
  150. package/src/service/environment_store.spec.ts +0 -2274
  151. package/src/service/environment_store.ts +0 -2434
  152. package/src/service/environment_store_anchoring.spec.ts +0 -107
  153. package/src/service/environment_store_clone.spec.ts +0 -350
  154. package/src/service/explore_visibility.spec.ts +0 -434
  155. package/src/service/exports_probe.spec.ts +0 -107
  156. package/src/service/extension_fetch_policy.spec.ts +0 -256
  157. package/src/service/filter.spec.ts +0 -458
  158. package/src/service/filter.ts +0 -341
  159. package/src/service/filter_bypass.spec.ts +0 -418
  160. package/src/service/filter_integration.spec.ts +0 -1004
  161. package/src/service/freshness.spec.ts +0 -183
  162. package/src/service/freshness.ts +0 -112
  163. package/src/service/gcs_s3_utils.ts +0 -427
  164. package/src/service/given.ts +0 -105
  165. package/src/service/givens_integration.spec.ts +0 -219
  166. package/src/service/manifest_loader.spec.ts +0 -189
  167. package/src/service/manifest_loader.ts +0 -156
  168. package/src/service/materialization_build_session.spec.ts +0 -435
  169. package/src/service/materialization_build_session.ts +0 -681
  170. package/src/service/materialization_config_validation.spec.ts +0 -99
  171. package/src/service/materialization_config_validation.ts +0 -120
  172. package/src/service/materialization_eligibility.spec.ts +0 -158
  173. package/src/service/materialization_eligibility.ts +0 -305
  174. package/src/service/materialization_schedule_surface.spec.ts +0 -256
  175. package/src/service/materialization_scheduler.spec.ts +0 -289
  176. package/src/service/materialization_scheduler.ts +0 -304
  177. package/src/service/materialization_serve_transform.spec.ts +0 -1003
  178. package/src/service/materialization_serve_transform.ts +0 -779
  179. package/src/service/materialization_service.spec.ts +0 -2373
  180. package/src/service/materialization_service.ts +0 -2342
  181. package/src/service/materialization_test_fixtures.ts +0 -249
  182. package/src/service/model.spec.ts +0 -1157
  183. package/src/service/model.ts +0 -3370
  184. package/src/service/model_limits.spec.ts +0 -209
  185. package/src/service/model_limits.ts +0 -131
  186. package/src/service/model_storage_serve.spec.ts +0 -193
  187. package/src/service/model_storage_serve_joins.spec.ts +0 -193
  188. package/src/service/package.spec.ts +0 -612
  189. package/src/service/package.ts +0 -1799
  190. package/src/service/package_manifest.spec.ts +0 -230
  191. package/src/service/package_manifest.ts +0 -241
  192. package/src/service/package_memory_governor.spec.ts +0 -173
  193. package/src/service/package_memory_governor.ts +0 -233
  194. package/src/service/package_quote_bound_tables.spec.ts +0 -171
  195. package/src/service/package_race.spec.ts +0 -208
  196. package/src/service/package_reload_safety.spec.ts +0 -193
  197. package/src/service/package_rollback.spec.ts +0 -190
  198. package/src/service/package_worker_path.spec.ts +0 -645
  199. package/src/service/path_injection.spec.ts +0 -39
  200. package/src/service/persist_annotation_validation.spec.ts +0 -89
  201. package/src/service/persist_annotation_validation.ts +0 -59
  202. package/src/service/persistence_policy.spec.ts +0 -374
  203. package/src/service/proxy.spec.ts +0 -414
  204. package/src/service/proxy.ts +0 -248
  205. package/src/service/query_boundary.spec.ts +0 -470
  206. package/src/service/query_metadata.spec.ts +0 -408
  207. package/src/service/query_metadata.ts +0 -492
  208. package/src/service/query_metadata_identity.spec.ts +0 -149
  209. package/src/service/query_text.spec.ts +0 -79
  210. package/src/service/query_text.ts +0 -43
  211. package/src/service/quoting.spec.ts +0 -135
  212. package/src/service/quoting.ts +0 -78
  213. package/src/service/resolve_environment.ts +0 -15
  214. package/src/service/restricted_mode.spec.ts +0 -299
  215. package/src/service/source_extraction.ts +0 -225
  216. package/src/service/theme_store.ts +0 -199
  217. package/src/storage/DatabaseInterface.ts +0 -198
  218. package/src/storage/StorageManager.ts +0 -113
  219. package/src/storage/duckdb/ConnectionRepository.ts +0 -143
  220. package/src/storage/duckdb/DuckDBConnection.ts +0 -123
  221. package/src/storage/duckdb/DuckDBRepository.ts +0 -208
  222. package/src/storage/duckdb/EnvironmentRepository.ts +0 -148
  223. package/src/storage/duckdb/MaterializationRepository.spec.ts +0 -191
  224. package/src/storage/duckdb/MaterializationRepository.ts +0 -336
  225. package/src/storage/duckdb/PackageRepository.ts +0 -135
  226. package/src/storage/duckdb/schema.ts +0 -229
  227. package/src/stream_helpers.spec.ts +0 -280
  228. package/src/stream_helpers.ts +0 -162
  229. package/src/telemetry.ts +0 -20
  230. package/src/test_helpers/metrics_harness.ts +0 -166
  231. package/src/theme_key_parity.spec.ts +0 -57
  232. package/src/utils.ts +0 -29
  233. package/tests/fixtures/authorize-compile/model.malloy +0 -9
  234. package/tests/fixtures/authorize-compile/publisher.json +0 -4
  235. package/tests/fixtures/html-pages-nopublic/model.malloy +0 -1
  236. package/tests/fixtures/html-pages-nopublic/publisher.json +0 -5
  237. package/tests/fixtures/html-pages-test/data.csv +0 -3
  238. package/tests/fixtures/html-pages-test/public/assets/app.css +0 -3
  239. package/tests/fixtures/html-pages-test/public/barehtml.html +0 -4
  240. package/tests/fixtures/html-pages-test/public/bodymeta.html +0 -8
  241. package/tests/fixtures/html-pages-test/public/data.json +0 -1
  242. package/tests/fixtures/html-pages-test/public/fitcomment.html +0 -11
  243. package/tests/fixtures/html-pages-test/public/index.html +0 -9
  244. package/tests/fixtures/html-pages-test/public/nohead.html +0 -8
  245. package/tests/fixtures/html-pages-test/public/notfit.html +0 -13
  246. package/tests/fixtures/html-pages-test/public/slides.html +0 -12
  247. package/tests/fixtures/html-pages-test/public/sub/page2.html +0 -9
  248. package/tests/fixtures/html-pages-test/public/unterminated.html +0 -10
  249. package/tests/fixtures/html-pages-test/publisher.json +0 -5
  250. package/tests/fixtures/html-pages-test/report.malloy +0 -1
  251. package/tests/fixtures/persist-multi-level/data/orders.csv +0 -5
  252. package/tests/fixtures/persist-multi-level/multi_level.malloy +0 -18
  253. package/tests/fixtures/persist-multi-level/publisher.json +0 -5
  254. package/tests/fixtures/persist-schedule-test/data/orders.csv +0 -5
  255. package/tests/fixtures/persist-schedule-test/persist_schedule_test.malloy +0 -11
  256. package/tests/fixtures/persist-schedule-test/publisher.json +0 -7
  257. package/tests/fixtures/persist-schedule-warn-test/data/orders.csv +0 -5
  258. package/tests/fixtures/persist-schedule-warn-test/persist_warn_test.malloy +0 -11
  259. package/tests/fixtures/persist-schedule-warn-test/publisher.json +0 -6
  260. package/tests/fixtures/persist-test/data/orders.csv +0 -5
  261. package/tests/fixtures/persist-test/persist_test.malloy +0 -11
  262. package/tests/fixtures/persist-test/publisher.json +0 -5
  263. package/tests/fixtures/publisher.config.json +0 -15
  264. package/tests/fixtures/query-givens/data/orders.csv +0 -7
  265. package/tests/fixtures/query-givens/model.malloy +0 -34
  266. package/tests/fixtures/query-givens/publisher.json +0 -5
  267. package/tests/fixtures/xlsx/database.xlsx +0 -0
  268. package/tests/harness/mcp_test_setup.ts +0 -332
  269. package/tests/harness/rest_e2e.ts +0 -68
  270. package/tests/integration/authorize/compile_authorize_http.integration.spec.ts +0 -92
  271. package/tests/integration/concurrent_package/concurrent_package.integration.spec.ts +0 -280
  272. package/tests/integration/duckdb_storage/duckdb_storage.integration.spec.ts +0 -138
  273. package/tests/integration/first_boot/readiness_line.integration.spec.ts +0 -177
  274. package/tests/integration/html_pages/html_pages.integration.spec.ts +0 -440
  275. package/tests/integration/legacy_routes/legacy_routes.integration.spec.ts +0 -259
  276. package/tests/integration/materialization/environment_list.integration.spec.ts +0 -133
  277. package/tests/integration/materialization/freshness_gate.integration.spec.ts +0 -292
  278. package/tests/integration/materialization/manifest_binding.integration.spec.ts +0 -430
  279. package/tests/integration/materialization/materialization_lifecycle.integration.spec.ts +0 -441
  280. package/tests/integration/materialization/orchestrated_rebind.integration.spec.ts +0 -150
  281. package/tests/integration/materialization/reference_manifest.integration.spec.ts +0 -251
  282. package/tests/integration/materialization/schedule_edit.integration.spec.ts +0 -126
  283. package/tests/integration/materialization/scheduler.integration.spec.ts +0 -200
  284. package/tests/integration/materialization/scheduler_recovery.integration.spec.ts +0 -172
  285. package/tests/integration/materialization/scheduler_transitions.integration.spec.ts +0 -256
  286. package/tests/integration/materialization/scheduler_wiring.integration.spec.ts +0 -143
  287. package/tests/integration/mcp/mcp_execute_query_tool.integration.spec.ts +0 -438
  288. package/tests/integration/mcp/mcp_get_context_semantic.integration.spec.ts +0 -235
  289. package/tests/integration/mcp/mcp_transport.integration.spec.ts +0 -98
  290. package/tests/integration/query_givens/query_givens.integration.spec.ts +0 -146
  291. package/tests/integration/query_givens/query_givens_authorize.integration.spec.ts +0 -121
  292. package/tests/integration/sdk_givens/sdk_givens.integration.spec.ts +0 -110
  293. package/tests/integration/watch-mode/watch_mode.integration.spec.ts +0 -421
  294. package/tests/unit/controller/theme.controller.spec.ts +0 -141
  295. package/tests/unit/duckdb/attached_databases.test.ts +0 -1243
  296. package/tests/unit/duckdb/duckdb_connection.test.ts +0 -181
  297. package/tests/unit/duckdb/legacy_schema_migration.test.ts +0 -197
  298. package/tests/unit/duckdb/repositories.test.ts +0 -208
  299. package/tests/unit/ducklake/ducklake.test.ts +0 -952
  300. package/tests/unit/service/theme_store.spec.ts +0 -139
  301. package/tsconfig.json +0 -32
@@ -1,1502 +0,0 @@
1
- import { ClientSecretCredential } from "@azure/identity";
2
- import { ContainerClient } from "@azure/storage-blob";
3
- import { BigQuery } from "@google-cloud/bigquery";
4
- import { Connection, TableSourceDef } from "@malloydata/malloy";
5
- import { components } from "../api";
6
- import { logger } from "../logger";
7
- import {
8
- CloudStorageCredentials,
9
- gcsConnectionToCredentials,
10
- getCloudTablesWithColumns,
11
- listCloudDirectorySchemas,
12
- listDataFilesInDirectory,
13
- parseCloudUri,
14
- s3ConnectionToCredentials,
15
- } from "./gcs_s3_utils";
16
- import { ApiConnection } from "./model";
17
-
18
- type ApiSchema = components["schemas"]["Schema"];
19
- type ApiTable = components["schemas"]["Table"];
20
- type ApiAzureConnection = components["schemas"]["AzureConnection"];
21
-
22
- /**
23
- * Build a SQL `AND column IN (...)` fragment for optional table-name filtering.
24
- * Returns an empty string when `values` is undefined or empty.
25
- */
26
- export function sqlInFilter(columnName: string, values?: string[]): string {
27
- if (!values || values.length === 0) return "";
28
- const escaped = values.map((v) => `'${v.replace(/'/g, "''")}'`);
29
- return `AND ${columnName} IN (${escaped.join(", ")})`;
30
- }
31
-
32
- /**
33
- * Group INFORMATION_SCHEMA.COLUMNS rows into ApiTable objects.
34
- * Handles both upper-case (Snowflake) and lower-case (Postgres/DuckDB) column names.
35
- */
36
- function groupColumnRowsIntoTables(
37
- rows: unknown[],
38
- buildResource: (tableName: string) => string,
39
- ): ApiTable[] {
40
- const tableMap = new Map<string, { name: string; type: string }[]>();
41
- for (const row of rows) {
42
- const r = row as Record<string, unknown>;
43
- const tableName = String(r.TABLE_NAME ?? r.table_name ?? "");
44
- const columnName = String(r.COLUMN_NAME ?? r.column_name ?? "");
45
- const dataType = String(r.DATA_TYPE ?? r.data_type ?? "").toLowerCase();
46
- if (!tableName) continue;
47
- if (!tableMap.has(tableName)) tableMap.set(tableName, []);
48
- tableMap.get(tableName)!.push({ name: columnName, type: dataType });
49
- }
50
- const tables: ApiTable[] = [];
51
- for (const [tableName, columns] of tableMap) {
52
- tables.push({ resource: buildResource(tableName), columns });
53
- }
54
- return tables;
55
- }
56
-
57
- function createBigQueryClient(connection: ApiConnection): BigQuery {
58
- if (!connection.bigqueryConnection) {
59
- throw new Error("BigQuery connection is required");
60
- }
61
-
62
- const config: {
63
- projectId: string;
64
- credentials?: object;
65
- keyFilename?: string;
66
- } = {
67
- projectId: connection.bigqueryConnection.defaultProjectId || "",
68
- };
69
-
70
- // Add service account key if provided
71
- if (connection.bigqueryConnection.serviceAccountKeyJson) {
72
- let credentials: Record<string, unknown>;
73
- try {
74
- credentials = JSON.parse(
75
- connection.bigqueryConnection.serviceAccountKeyJson,
76
- );
77
- } catch (parseError) {
78
- throw new Error(
79
- `Failed to parse BigQuery service account key JSON: ${(parseError as Error).message}`,
80
- );
81
- }
82
- config.credentials = credentials;
83
-
84
- if (!config.projectId && credentials.project_id) {
85
- config.projectId = credentials.project_id as string;
86
- }
87
-
88
- if (!config.projectId) {
89
- throw new Error(
90
- "BigQuery project ID is required. Either set the defaultProjectId in the connection configuration or the project_id in the service account key JSON.",
91
- );
92
- }
93
- } else if (
94
- Object.keys(connection.bigqueryConnection).length === 0 &&
95
- process.env.GOOGLE_APPLICATION_CREDENTIALS
96
- ) {
97
- // Note: The BigQuery client will infer the project ID from the ADC file.
98
- config.keyFilename = process.env.GOOGLE_APPLICATION_CREDENTIALS || "";
99
- } else {
100
- throw new Error(
101
- "BigQuery connection is required, either set the bigqueryConnection in the connection configuration or set the GOOGLE_APPLICATION_CREDENTIALS environment variable.",
102
- );
103
- }
104
-
105
- return new BigQuery(config);
106
- }
107
-
108
- function standardizeRunSQLResult(result: unknown): unknown[] {
109
- // Handle different result formats from malloyConnection.runSQL
110
- return Array.isArray(result)
111
- ? result
112
- : (result as { rows?: unknown[] }).rows || [];
113
- }
114
-
115
- function getCloudCredentialsFromAttachedDatabases(
116
- attachedDatabases: components["schemas"]["AttachedDatabase"][],
117
- storageType: "gcs" | "s3",
118
- ): CloudStorageCredentials | null {
119
- for (const attachedDb of attachedDatabases) {
120
- if (
121
- attachedDb.type === "gcs" &&
122
- storageType === "gcs" &&
123
- attachedDb.gcsConnection
124
- ) {
125
- return gcsConnectionToCredentials(attachedDb.gcsConnection);
126
- }
127
- if (
128
- attachedDb.type === "s3" &&
129
- storageType === "s3" &&
130
- attachedDb.s3Connection
131
- ) {
132
- return s3ConnectionToCredentials(attachedDb.s3Connection);
133
- }
134
- }
135
- return null;
136
- }
137
-
138
- async function getSchemasForBigQuery(
139
- connection: ApiConnection,
140
- ): Promise<ApiSchema[]> {
141
- if (!connection.bigqueryConnection) {
142
- throw new Error("BigQuery connection is required");
143
- }
144
- try {
145
- const bigquery = createBigQueryClient(connection);
146
- const [datasets] = await bigquery.getDatasets();
147
-
148
- return await Promise.all(
149
- datasets.map(async (dataset) => {
150
- const [metadata] = await dataset.getMetadata();
151
- return {
152
- name: dataset.id,
153
- isHidden: false,
154
- isDefault: false,
155
- description: (metadata as { description?: string })?.description,
156
- };
157
- }),
158
- );
159
- } catch (error) {
160
- logger.error(
161
- `Error getting schemas for BigQuery connection ${connection.name}`,
162
- { error },
163
- );
164
- throw new Error(
165
- `Failed to get schemas for BigQuery connection ${connection.name}: ${(error as Error).message}`,
166
- );
167
- }
168
- }
169
-
170
- async function getSchemasForPostgres(
171
- connection: ApiConnection,
172
- malloyConnection: Connection,
173
- ): Promise<ApiSchema[]> {
174
- if (!connection.postgresConnection) {
175
- throw new Error("Postgres connection is required");
176
- }
177
- try {
178
- // Wrap in row_to_json because the Malloy Postgres driver's runSQL
179
- // de-JSONs each row via row.row (matching Malloy-generated queries).
180
- const result = await malloyConnection.runSQL(
181
- "SELECT row_to_json(t) as row FROM (SELECT schema_name FROM information_schema.schemata ORDER BY schema_name) t",
182
- );
183
- const rows = standardizeRunSQLResult(result);
184
- return rows.map((row: unknown) => {
185
- const typedRow = row as Record<string, unknown>;
186
- const schemaName = String(
187
- typedRow.schema_name ?? typedRow.SCHEMA_NAME ?? "",
188
- );
189
- return {
190
- name: schemaName,
191
- isHidden: ["information_schema", "pg_catalog", "pg_toast"].includes(
192
- schemaName,
193
- ),
194
- isDefault: schemaName === "public",
195
- };
196
- });
197
- } catch (error) {
198
- logger.error(
199
- `Error getting schemas for Postgres connection ${connection.name}`,
200
- { error },
201
- );
202
- throw new Error(
203
- `Failed to get schemas for Postgres connection ${connection.name}: ${(error as Error).message}`,
204
- );
205
- }
206
- }
207
-
208
- async function getSchemasForMySQL(
209
- connection: ApiConnection,
210
- ): Promise<ApiSchema[]> {
211
- if (!connection.mysqlConnection) {
212
- throw new Error("Mysql connection is required");
213
- }
214
- return [
215
- {
216
- name: connection.mysqlConnection.database || "mysql",
217
- isHidden: false,
218
- isDefault: true,
219
- },
220
- ];
221
- }
222
-
223
- async function getSchemasForSnowflake(
224
- connection: ApiConnection,
225
- malloyConnection: Connection,
226
- ): Promise<ApiSchema[]> {
227
- if (!connection.snowflakeConnection) {
228
- throw new Error("Snowflake connection is required");
229
- }
230
- try {
231
- const database = connection.snowflakeConnection.database;
232
- const schema = connection.snowflakeConnection.schema;
233
-
234
- const filters: string[] = [];
235
- if (database) {
236
- filters.push(`CATALOG_NAME = '${database}'`);
237
- }
238
- if (schema) {
239
- filters.push(`SCHEMA_NAME = '${schema}'`);
240
- }
241
- const whereClause =
242
- filters.length > 0 ? `WHERE ${filters.join(" AND ")}` : "";
243
-
244
- const result = await malloyConnection.runSQL(
245
- `SELECT CATALOG_NAME, SCHEMA_NAME, SCHEMA_OWNER FROM ${database ? `${database}.` : ""}INFORMATION_SCHEMA.SCHEMATA ${whereClause} ORDER BY SCHEMA_NAME`,
246
- );
247
- const rows = standardizeRunSQLResult(result);
248
- return rows.map((row: unknown) => {
249
- const typedRow = row as Record<string, unknown>;
250
- const catalogName = String(
251
- typedRow.CATALOG_NAME ?? typedRow.catalog_name ?? "",
252
- );
253
- const schemaName = String(
254
- typedRow.SCHEMA_NAME ?? typedRow.schema_name ?? "",
255
- );
256
- const owner = String(
257
- typedRow.SCHEMA_OWNER ?? typedRow.schema_owner ?? "",
258
- );
259
- return {
260
- name: `${catalogName}.${schemaName}`,
261
- isHidden:
262
- ["SNOWFLAKE", ""].includes(owner) ||
263
- schemaName === "INFORMATION_SCHEMA",
264
- isDefault: schema ? schemaName === schema : false,
265
- };
266
- });
267
- } catch (error) {
268
- logger.error(
269
- `Error getting schemas for Snowflake connection ${connection.name}`,
270
- { error },
271
- );
272
- throw new Error(
273
- `Failed to get schemas for Snowflake connection ${connection.name}: ${(error as Error).message}`,
274
- );
275
- }
276
- }
277
-
278
- async function getSchemasForTrino(
279
- connection: ApiConnection,
280
- malloyConnection: Connection,
281
- ): Promise<ApiSchema[]> {
282
- if (!connection.trinoConnection) {
283
- throw new Error("Trino connection is required");
284
- }
285
- try {
286
- const configuredSchema = connection.trinoConnection.schema;
287
- let allRows: { catalog: string; schema: string }[] = [];
288
-
289
- if (connection.trinoConnection.catalog) {
290
- const catalog = connection.trinoConnection.catalog;
291
- const result = await malloyConnection.runSQL(
292
- `SELECT schema_name FROM ${catalog}.information_schema.schemata ORDER BY schema_name`,
293
- );
294
- const rows = standardizeRunSQLResult(result);
295
- allRows = rows.map((row: unknown) => {
296
- const r = row as Record<string, unknown>;
297
- return {
298
- catalog,
299
- schema: String(r.schema_name ?? r.Schema ?? ""),
300
- };
301
- });
302
- } else {
303
- const catalogsResult = await malloyConnection.runSQL(`SHOW CATALOGS`);
304
- const catalogNames = standardizeRunSQLResult(catalogsResult).map(
305
- (row: unknown) => {
306
- const r = row as Record<string, unknown>;
307
- return String(r.Catalog ?? r.catalog ?? "");
308
- },
309
- );
310
-
311
- for (const catalog of catalogNames) {
312
- try {
313
- const result = await malloyConnection.runSQL(
314
- `SELECT schema_name FROM ${catalog}.information_schema.schemata ORDER BY schema_name`,
315
- );
316
- const rows = standardizeRunSQLResult(result);
317
- for (const row of rows) {
318
- const r = row as Record<string, unknown>;
319
- allRows.push({
320
- catalog,
321
- schema: String(r.schema_name ?? r.Schema ?? ""),
322
- });
323
- }
324
- } catch (catalogError) {
325
- logger.warn(
326
- `Failed to list schemas for Trino catalog ${catalog}`,
327
- { error: catalogError },
328
- );
329
- }
330
- }
331
- }
332
-
333
- return allRows.map(({ catalog, schema }) => {
334
- const name = connection.trinoConnection?.catalog
335
- ? schema
336
- : `${catalog}.${schema}`;
337
- return {
338
- name,
339
- isHidden: ["information_schema", "performance_schema"].includes(
340
- schema,
341
- ),
342
- isDefault: configuredSchema ? schema === configuredSchema : false,
343
- };
344
- });
345
- } catch (error) {
346
- logger.error(
347
- `Error getting schemas for Trino connection ${connection.name}`,
348
- { error },
349
- );
350
- throw new Error(
351
- `Failed to get schemas for Trino connection ${connection.name}: ${(error as Error).message}`,
352
- );
353
- }
354
- }
355
-
356
- async function getSchemasForDatabricks(
357
- connection: ApiConnection,
358
- malloyConnection: Connection,
359
- ): Promise<ApiSchema[]> {
360
- if (!connection.databricksConnection) {
361
- throw new Error("Databricks connection is required");
362
- }
363
- try {
364
- const configuredSchema = connection.databricksConnection.defaultSchema;
365
- let allRows: { catalog: string; schema: string }[] = [];
366
-
367
- if (connection.databricksConnection.defaultCatalog) {
368
- const catalog = connection.databricksConnection.defaultCatalog;
369
- const result = await malloyConnection.runSQL(
370
- `SELECT schema_name FROM ${catalog}.information_schema.schemata ORDER BY schema_name`,
371
- );
372
- const rows = standardizeRunSQLResult(result);
373
- allRows = rows.map((row: unknown) => {
374
- const r = row as Record<string, unknown>;
375
- return {
376
- catalog,
377
- schema: String(r.schema_name ?? r.Schema ?? ""),
378
- };
379
- });
380
- } else {
381
- const catalogsResult = await malloyConnection.runSQL(`SHOW CATALOGS`);
382
- const catalogNames = standardizeRunSQLResult(catalogsResult).map(
383
- (row: unknown) => {
384
- const r = row as Record<string, unknown>;
385
- return String(r.catalog ?? r.Catalog ?? r.catalog_name ?? "");
386
- },
387
- );
388
-
389
- for (const catalog of catalogNames) {
390
- try {
391
- const result = await malloyConnection.runSQL(
392
- `SELECT schema_name FROM ${catalog}.information_schema.schemata ORDER BY schema_name`,
393
- );
394
- const rows = standardizeRunSQLResult(result);
395
- for (const row of rows) {
396
- const r = row as Record<string, unknown>;
397
- allRows.push({
398
- catalog,
399
- schema: String(r.schema_name ?? r.Schema ?? ""),
400
- });
401
- }
402
- } catch (catalogError) {
403
- logger.warn(
404
- `Failed to list schemas for Databricks catalog ${catalog}`,
405
- { error: catalogError },
406
- );
407
- }
408
- }
409
- }
410
- logger.info("allRows for Schemas for Databricks", { allRows });
411
- return allRows.map(({ catalog, schema }) => {
412
- const name = connection.databricksConnection?.defaultCatalog
413
- ? schema
414
- : `${catalog}.${schema}`;
415
- return {
416
- name,
417
- isHidden: ["information_schema"].includes(schema),
418
- isDefault: configuredSchema ? schema === configuredSchema : false,
419
- };
420
- });
421
- } catch (error) {
422
- logger.error(
423
- `Error getting schemas for Databricks connection ${connection.name}`,
424
- { error },
425
- );
426
- throw new Error(
427
- `Failed to get schemas for Databricks connection ${connection.name}: ${(error as Error).message}`,
428
- );
429
- }
430
- }
431
-
432
- async function getSchemasForDuckDB(
433
- connection: ApiConnection,
434
- malloyConnection: Connection,
435
- ): Promise<ApiSchema[]> {
436
- if (!connection.duckdbConnection) {
437
- throw new Error("DuckDB connection is required");
438
- }
439
- try {
440
- const result = await malloyConnection.runSQL(
441
- "SELECT DISTINCT schema_name,catalog_name FROM information_schema.schemata ORDER BY catalog_name,schema_name",
442
- { rowLimit: 1000 },
443
- );
444
-
445
- const rows = standardizeRunSQLResult(result);
446
-
447
- const schemas: ApiSchema[] = rows.map((row: unknown) => {
448
- const typedRow = row as Record<string, unknown>;
449
- const schemaName = String(typedRow.schema_name ?? "");
450
- const catalogName = String(typedRow.catalog_name ?? "");
451
-
452
- return {
453
- name: `${catalogName}.${schemaName}`,
454
- isHidden:
455
- [
456
- "information_schema",
457
- "performance_schema",
458
- "pg_catalog",
459
- "pg_toast",
460
- "",
461
- ].includes(schemaName) ||
462
- ["md_information_schema", "system"].includes(catalogName),
463
- isDefault: catalogName === "main",
464
- };
465
- });
466
-
467
- const attachedDatabases =
468
- connection.duckdbConnection.attachedDatabases || [];
469
-
470
- const cloudDatabases = attachedDatabases.filter(
471
- (attachedDb) =>
472
- (attachedDb.type === "gcs" || attachedDb.type === "s3") &&
473
- (attachedDb.gcsConnection || attachedDb.s3Connection),
474
- );
475
-
476
- const cloudDbPromises = cloudDatabases.map(async (attachedDb) => {
477
- const dbType = attachedDb.type as "gcs" | "s3";
478
- const credentials =
479
- dbType === "gcs"
480
- ? gcsConnectionToCredentials(attachedDb.gcsConnection!)
481
- : s3ConnectionToCredentials(attachedDb.s3Connection!);
482
-
483
- try {
484
- return await listCloudDirectorySchemas(credentials);
485
- } catch (cloudError) {
486
- logger.warn(
487
- `Failed to list ${dbType.toUpperCase()} directory schemas for ${attachedDb.name}`,
488
- { error: cloudError },
489
- );
490
- return [];
491
- }
492
- });
493
-
494
- const cloudSchemaArrays = await Promise.all(cloudDbPromises);
495
- for (const cloudSchemas of cloudSchemaArrays) {
496
- schemas.push(...cloudSchemas);
497
- }
498
-
499
- const azureDatabases = attachedDatabases.filter(
500
- (attachedDb) =>
501
- attachedDb.type === "azure" && attachedDb.azureConnection,
502
- );
503
- for (const attachedDb of azureDatabases) {
504
- if (attachedDb.name) {
505
- schemas.push({
506
- name: attachedDb.name,
507
- isHidden: false,
508
- isDefault: false,
509
- });
510
- }
511
- }
512
-
513
- return schemas;
514
- } catch (error) {
515
- logger.error(
516
- `Error getting schemas for DuckDB connection ${connection.name}`,
517
- { error },
518
- );
519
- throw new Error(
520
- `Failed to get schemas for DuckDB connection ${connection.name}: ${(error as Error).message}`,
521
- );
522
- }
523
- }
524
-
525
- async function getSchemasForMotherDuck(
526
- connection: ApiConnection,
527
- malloyConnection: Connection,
528
- ): Promise<ApiSchema[]> {
529
- if (!connection.motherduckConnection) {
530
- throw new Error("MotherDuck connection is required");
531
- }
532
- try {
533
- const database = connection.motherduckConnection.database;
534
- const whereClause = database ? `WHERE catalog_name = '${database}'` : "";
535
- const result = await malloyConnection.runSQL(
536
- `SELECT DISTINCT schema_name FROM information_schema.schemata ${whereClause} ORDER BY schema_name`,
537
- );
538
- const rows = standardizeRunSQLResult(result);
539
- return rows.map((row: unknown) => {
540
- const typedRow = row as Record<string, unknown>;
541
- const schemaName = String(
542
- typedRow.schema_name ?? typedRow.SCHEMA_NAME ?? "",
543
- );
544
- return {
545
- name: schemaName,
546
- isHidden: ["information_schema", "performance_schema", ""].includes(
547
- schemaName,
548
- ),
549
- isDefault: schemaName === "main",
550
- };
551
- });
552
- } catch (error) {
553
- logger.error(
554
- `Error getting schemas for MotherDuck connection ${connection.name}`,
555
- { error },
556
- );
557
- throw new Error(
558
- `Failed to get schemas for MotherDuck connection ${connection.name}: ${(error as Error).message}`,
559
- );
560
- }
561
- }
562
-
563
- async function getSchemasForDuckLake(
564
- connection: ApiConnection,
565
- malloyConnection: Connection,
566
- ): Promise<ApiSchema[]> {
567
- try {
568
- // The catalog is attached with the connection name (see attachDuckLake in connection.ts)
569
- const catalogName = connection.name;
570
- const result = await malloyConnection.runSQL(
571
- `SELECT schema_name FROM information_schema.schemata WHERE catalog_name = '${catalogName}' ORDER BY schema_name`,
572
- { rowLimit: 1000 },
573
- );
574
- const rows = standardizeRunSQLResult(result);
575
-
576
- return rows.map((row: unknown) => {
577
- const typedRow = row as Record<string, unknown>;
578
- const schemaName = typedRow.schema_name as string;
579
- const shouldShow = schemaName === "main" || schemaName === "public";
580
- return {
581
- name: schemaName,
582
- isHidden: !shouldShow,
583
- isDefault: false,
584
- };
585
- });
586
- } catch (error) {
587
- logger.error(
588
- `Error getting schemas for DuckLake connection ${connection.name}`,
589
- { error },
590
- );
591
- throw new Error(
592
- `Failed to get schemas for DuckLake connection ${connection.name}: ${(error as Error).message}`,
593
- );
594
- }
595
- }
596
-
597
- /** Abort introspection requests that hang instead of holding the slot open. */
598
- const PUBLISHER_INTROSPECTION_TIMEOUT_MS = 60_000;
599
-
600
- /**
601
- * Strip any userinfo (`user:pass@`) from a URL before it reaches a log or error
602
- * message. `connectionUri` comes from a config file and may legitimately carry
603
- * embedded credentials; the bearer token always travels in the header, never
604
- * the URL, but this keeps any URL-embedded secret out of thrown messages too.
605
- */
606
- function redactUrlCredentials(url: string): string {
607
- try {
608
- const parsed = new URL(url);
609
- parsed.username = "";
610
- parsed.password = "";
611
- return parsed.toString();
612
- } catch {
613
- // Non-absolute / unparseable: nothing to redact, return as-is.
614
- return url;
615
- }
616
- }
617
-
618
- /**
619
- * Publisher proxy connections introspect against the remote dataplane, which
620
- * exposes the same connection API as this server. Schema/table discovery is a
621
- * GET passthrough — the remote owns the dialect-specific introspection and
622
- * returns the same Schema/Table shapes, so we forward the response verbatim
623
- * (no Malloy connection involved).
624
- *
625
- * URL contract: the request is the configured `connectionUri` with the
626
- * introspection `pathSuffix` appended verbatim. `connectionUri` must point at
627
- * the connection resource itself (`.../connections/<name>`), so this path and
628
- * the data path (db-publisher's `PublisherConnection`) resolve against the same
629
- * remote connection. Note the two halves derive their URL differently: the
630
- * db-publisher client re-parses `connectionUri` and rebuilds it through its
631
- * generated client, while this introspection path appends to it verbatim — the
632
- * remote must serve both forms for a given `connectionUri`. Keep them pointed at
633
- * the same connection resource so they stay in agreement.
634
- */
635
- async function fetchFromPublisherDataplane<T>(
636
- connection: ApiConnection,
637
- pathSuffix: string,
638
- ): Promise<T> {
639
- const publisher = connection.publisherConnection;
640
- // Type-narrowing guard only — the user-facing validation (with the
641
- // actionable `Fix:` message) lives in validateConnectionShape, which every
642
- // connection passes before it can be assembled and introspected here.
643
- if (!publisher?.connectionUri) {
644
- throw new Error(
645
- `Publisher connection "${connection.name}" is missing connectionUri`,
646
- );
647
- }
648
- const url = `${publisher.connectionUri.replace(/\/+$/, "")}${pathSuffix}`;
649
- const headers: Record<string, string> = {};
650
- if (publisher.accessToken) {
651
- headers["Authorization"] = `Bearer ${publisher.accessToken}`;
652
- }
653
-
654
- let response: Response;
655
- try {
656
- response = await fetch(url, {
657
- headers,
658
- signal: AbortSignal.timeout(PUBLISHER_INTROSPECTION_TIMEOUT_MS),
659
- });
660
- } catch (error) {
661
- // Network-level failure (DNS, connection refused, timeout) — no HTTP
662
- // status. Surface it with the connection name, like the other
663
- // introspectors, and never echo the token-bearing header.
664
- const reason =
665
- (error as Error)?.name === "TimeoutError"
666
- ? `timed out after ${PUBLISHER_INTROSPECTION_TIMEOUT_MS}ms`
667
- : (error as Error).message;
668
- throw new Error(
669
- `Publisher dataplane request to ${redactUrlCredentials(url)} failed ` +
670
- `for connection "${connection.name}": ${reason}`,
671
- );
672
- }
673
-
674
- if (!response.ok) {
675
- const body = await response.text().catch(() => "");
676
- throw new Error(
677
- `Publisher dataplane request to ${redactUrlCredentials(url)} failed ` +
678
- `(${response.status}): ${body.slice(0, 200)}`,
679
- );
680
- }
681
- return (await response.json()) as T;
682
- }
683
-
684
- async function getSchemasForPublisher(
685
- connection: ApiConnection,
686
- ): Promise<ApiSchema[]> {
687
- return fetchFromPublisherDataplane<ApiSchema[]>(connection, "/schemas");
688
- }
689
-
690
- async function listTablesForPublisher(
691
- connection: ApiConnection,
692
- schemaName: string,
693
- tableNames?: string[],
694
- ): Promise<ApiTable[]> {
695
- const tables = await fetchFromPublisherDataplane<ApiTable[]>(
696
- connection,
697
- `/schemas/${encodeURIComponent(schemaName)}/tables`,
698
- );
699
- if (!tableNames) {
700
- return tables;
701
- }
702
- // `tableNames` is a bare-table-name filter (see listTablesForBigQuery). The
703
- // remote's `resource` is dotted and its qualification depends on the remote
704
- // dialect ("<schema>.<table>" or "<catalog>.<schema>.<table>"), so match the
705
- // bare name (last segment) as well as the schema-stripped and full forms. An
706
- // unrecognized shape still matches on the full resource rather than being
707
- // silently dropped.
708
- const allowed = new Set(tableNames);
709
- const prefix = `${schemaName}.`;
710
- return tables.filter((table) => {
711
- const resource = table.resource ?? "";
712
- const schemaStripped = resource.startsWith(prefix)
713
- ? resource.slice(prefix.length)
714
- : resource;
715
- const bareName = resource.slice(resource.lastIndexOf(".") + 1);
716
- return (
717
- allowed.has(bareName) ||
718
- allowed.has(schemaStripped) ||
719
- allowed.has(resource)
720
- );
721
- });
722
- }
723
-
724
- export async function getSchemasForConnection(
725
- connection: ApiConnection,
726
- malloyConnection: Connection,
727
- ): Promise<ApiSchema[]> {
728
- switch (connection.type) {
729
- case "bigquery":
730
- return getSchemasForBigQuery(connection);
731
- case "postgres":
732
- return getSchemasForPostgres(connection, malloyConnection);
733
- case "mysql":
734
- return getSchemasForMySQL(connection);
735
- case "snowflake":
736
- return getSchemasForSnowflake(connection, malloyConnection);
737
- case "trino":
738
- return getSchemasForTrino(connection, malloyConnection);
739
- case "databricks":
740
- return getSchemasForDatabricks(connection, malloyConnection);
741
- case "duckdb":
742
- return getSchemasForDuckDB(connection, malloyConnection);
743
- case "motherduck":
744
- return getSchemasForMotherDuck(connection, malloyConnection);
745
- case "ducklake":
746
- return getSchemasForDuckLake(connection, malloyConnection);
747
- case "publisher":
748
- return getSchemasForPublisher(connection);
749
- default:
750
- throw new Error(`Unsupported connection type: ${connection.type}`);
751
- }
752
- }
753
-
754
- function getFileType(key: string): string {
755
- const lowerKey = key.toLowerCase();
756
- if (lowerKey.endsWith(".csv")) return "csv";
757
- if (lowerKey.endsWith(".parquet")) return "parquet";
758
- if (lowerKey.endsWith(".json")) return "json";
759
- if (lowerKey.endsWith(".jsonl") || lowerKey.endsWith(".ndjson"))
760
- return "jsonl";
761
- return "unknown";
762
- }
763
-
764
- /**
765
- * Lists blobs in an Azure container matching a glob-like prefix/extension filter.
766
- * Parses an HTTPS SAS URL like:
767
- * https://account.blob.core.windows.net/container/path/*.parquet?sasToken
768
- * Returns individual file URLs with the SAS token appended.
769
- */
770
- async function listAzureBlobs(
771
- fileUrl: string,
772
- azureConnection?: ApiAzureConnection,
773
- ): Promise<{ url: string; blobName: string }[]> {
774
- // Split URL and SAS token carefully to avoid encoding issues with signatures
775
- const queryStart = fileUrl.indexOf("?");
776
- const baseUrl = queryStart >= 0 ? fileUrl.substring(0, queryStart) : fileUrl;
777
- const sasToken = queryStart >= 0 ? fileUrl.substring(queryStart) : "";
778
-
779
- // Parse the URL to extract account, container, and blob path
780
- let accountUrl: string;
781
- let container: string;
782
- let blobPath: string;
783
-
784
- if (baseUrl.startsWith("abfss://")) {
785
- // abfss://container/path or abfss://account.dfs.core.windows.net/container/path
786
- const withoutScheme = baseUrl.substring("abfss://".length);
787
- const parts = withoutScheme.split("/").filter(Boolean);
788
- if (parts[0].includes(".")) {
789
- // Fully qualified: abfss://account.dfs.core.windows.net/container/path
790
- const accountName = parts[0].split(".")[0];
791
- accountUrl = `https://${accountName}.blob.core.windows.net`;
792
- container = parts[1];
793
- blobPath = parts.slice(2).join("/");
794
- } else {
795
- // Short form: abfss://container/path — need accountName from config
796
- if (!azureConnection?.accountName) {
797
- throw new Error(
798
- "accountName is required to list blobs with abfss:// URLs",
799
- );
800
- }
801
- accountUrl = `https://${azureConnection.accountName}.blob.core.windows.net`;
802
- container = parts[0];
803
- blobPath = parts.slice(1).join("/");
804
- }
805
- } else {
806
- // https://account.blob.core.windows.net/container/path
807
- const url = new URL(baseUrl);
808
- const pathParts = url.pathname.split("/").filter(Boolean);
809
- container = pathParts[0];
810
- blobPath = pathParts.slice(1).join("/");
811
- accountUrl = `${url.protocol}//${url.host}`;
812
- }
813
-
814
- // Three supported glob patterns:
815
- // path/file.ext → single file (handled upstream by isAzureSingleFileUrl)
816
- // path/*.ext → files directly in path/ with that extension (no subdirs)
817
- // path/** → all valid data files in path/ and nested dirs (recursive)
818
- let prefix: string;
819
- let extensionFilter = ""; // for *.ext pattern
820
- let recursive = true; // for ** pattern
821
-
822
- if (blobPath.endsWith("**")) {
823
- // Recursive listing: everything under this prefix
824
- prefix = blobPath.slice(0, -2);
825
- recursive = true;
826
- } else if (blobPath.includes("*")) {
827
- // Single-level glob: path/*.ext — files directly in that dir only
828
- const starIndex = blobPath.indexOf("*");
829
- prefix = blobPath.substring(0, starIndex);
830
- extensionFilter = blobPath.substring(starIndex + 1); // e.g. ".parquet"
831
- recursive = false;
832
- } else {
833
- // No glob — use blobPath as prefix (container-level listing)
834
- prefix = blobPath;
835
- recursive = true;
836
- }
837
-
838
- // Create ContainerClient with appropriate authentication
839
- let containerClient: ContainerClient;
840
- if (
841
- azureConnection?.authType === "service_principal" &&
842
- azureConnection.tenantId &&
843
- azureConnection.clientId &&
844
- azureConnection.clientSecret
845
- ) {
846
- const credential = new ClientSecretCredential(
847
- azureConnection.tenantId,
848
- azureConnection.clientId,
849
- azureConnection.clientSecret,
850
- );
851
- containerClient = new ContainerClient(
852
- `${accountUrl}/${container}`,
853
- credential,
854
- );
855
- } else {
856
- // SAS token auth — append token to container URL
857
- const containerUrl = `${accountUrl}/${container}${sasToken}`;
858
- containerClient = new ContainerClient(containerUrl);
859
- }
860
-
861
- const matchingFiles: { url: string; blobName: string }[] = [];
862
- for await (const blob of containerClient.listBlobsFlat({
863
- prefix: prefix || undefined,
864
- })) {
865
- if (extensionFilter && !blob.name.endsWith(extensionFilter)) continue;
866
- // For *.ext (non-recursive): only allow files directly in prefix dir
867
- if (!recursive) {
868
- const nameAfterPrefix = blob.name.substring(prefix.length);
869
- if (nameAfterPrefix.includes("/")) continue;
870
- }
871
- if (!isDataFile(blob.name)) continue;
872
- // For SPN: use abfss:// URLs that DuckDB's azure extension can read
873
- // For SAS: use https:// URLs with token appended
874
- let url: string;
875
- if (azureConnection?.authType === "service_principal") {
876
- const account =
877
- azureConnection.accountName ||
878
- accountUrl.split("//")[1]?.split(".")[0];
879
- url = `abfss://${account}.dfs.core.windows.net/${container}/${blob.name}`;
880
- } else {
881
- url = `${accountUrl}/${container}/${blob.name}${sasToken}`;
882
- }
883
- matchingFiles.push({ url, blobName: blob.name });
884
- }
885
-
886
- logger.info(
887
- `Listed ${matchingFiles.length} matching blobs in Azure container ${container} with prefix "${prefix}"`,
888
- );
889
- return matchingFiles;
890
- }
891
-
892
- function isDataFile(key: string): boolean {
893
- const lowerKey = key.toLowerCase();
894
- return (
895
- lowerKey.endsWith(".csv") ||
896
- lowerKey.endsWith(".parquet") ||
897
- lowerKey.endsWith(".json") ||
898
- lowerKey.endsWith(".jsonl") ||
899
- lowerKey.endsWith(".ndjson")
900
- );
901
- }
902
-
903
- async function describeRemoteFile(
904
- malloyConnection: Connection,
905
- fileUri: string,
906
- ): Promise<ApiTable> {
907
- const pathWithoutQuery = fileUri.split("?")[0];
908
- const fileType = getFileType(pathWithoutQuery);
909
-
910
- let describeQuery: string;
911
- switch (fileType) {
912
- case "csv":
913
- describeQuery = `DESCRIBE SELECT * FROM read_csv('${fileUri}', auto_detect=true) LIMIT 1`;
914
- break;
915
- case "parquet":
916
- describeQuery = `DESCRIBE SELECT * FROM read_parquet('${fileUri}') LIMIT 1`;
917
- break;
918
- case "json":
919
- describeQuery = `DESCRIBE SELECT * FROM read_json('${fileUri}', auto_detect=true) LIMIT 1`;
920
- break;
921
- case "jsonl":
922
- describeQuery = `DESCRIBE SELECT * FROM read_json('${fileUri}', format='newline_delimited', auto_detect=true) LIMIT 1`;
923
- break;
924
- default:
925
- logger.warn(`Unsupported file type for file: ${fileUri}`);
926
- return { resource: fileUri, columns: [] };
927
- }
928
-
929
- const result = await malloyConnection.runSQL(describeQuery);
930
- const rows = standardizeRunSQLResult(result);
931
- const columns = rows.map((row: unknown) => {
932
- const typedRow = row as Record<string, unknown>;
933
- return {
934
- name: (typedRow.column_name || typedRow.name) as string,
935
- type: (typedRow.column_type || typedRow.type) as string,
936
- };
937
- });
938
-
939
- const fileName = pathWithoutQuery.split("/").pop() || fileUri;
940
- return { resource: fileName, columns };
941
- }
942
-
943
- function isAzureSingleFileUrl(fileUri: string): boolean {
944
- const pathWithoutQuery = fileUri.split("?")[0];
945
- // Has a glob — not a single file
946
- if (pathWithoutQuery.includes("*")) return false;
947
- // Ends with / — directory listing
948
- if (pathWithoutQuery.endsWith("/")) return false;
949
- // Check if the last path segment has a data file extension
950
- const lastSegment = pathWithoutQuery.split("/").pop() || "";
951
- return isDataFile(lastSegment);
952
- }
953
-
954
- async function describeAzureFile(
955
- malloyConnection: Connection,
956
- fileUri: string,
957
- azureConnection?: ApiAzureConnection,
958
- ): Promise<ApiTable[]> {
959
- try {
960
- if (isAzureSingleFileUrl(fileUri)) {
961
- // Single file — describe directly via DuckDB
962
- return [await describeRemoteFile(malloyConnection, fileUri)];
963
- }
964
-
965
- // Glob pattern or container/directory URL — list blobs via Azure SDK
966
- const blobs = await listAzureBlobs(fileUri, azureConnection);
967
- if (blobs.length === 0) {
968
- return [{ resource: fileUri, columns: [] }];
969
- }
970
-
971
- const results = await Promise.all(
972
- blobs.map(async ({ url, blobName }) => {
973
- try {
974
- const table = await describeRemoteFile(malloyConnection, url);
975
- return { ...table, resource: blobName };
976
- } catch (error) {
977
- logger.warn(`Failed to describe Azure blob: ${url}`, { error });
978
- return { resource: blobName, columns: [] } as ApiTable;
979
- }
980
- }),
981
- );
982
- return results;
983
- } catch (error) {
984
- logger.error(`Failed to describe Azure file: ${fileUri}`, { error });
985
- throw new Error(
986
- `Failed to describe Azure file: ${error instanceof Error ? error.message : String(error)}`,
987
- );
988
- }
989
- }
990
-
991
- export async function listTablesForSchema(
992
- connection: ApiConnection,
993
- schemaName: string,
994
- malloyConnection: Connection,
995
- tableNames?: string[],
996
- ): Promise<ApiTable[]> {
997
- switch (connection.type) {
998
- case "bigquery":
999
- return listTablesForBigQuery(
1000
- connection,
1001
- schemaName,
1002
- malloyConnection,
1003
- tableNames,
1004
- );
1005
- case "mysql":
1006
- return listTablesForMySQL(
1007
- connection,
1008
- schemaName,
1009
- malloyConnection,
1010
- tableNames,
1011
- );
1012
- case "postgres":
1013
- return listTablesForPostgres(
1014
- connection,
1015
- schemaName,
1016
- malloyConnection,
1017
- tableNames,
1018
- );
1019
- case "snowflake":
1020
- return listTablesForSnowflake(
1021
- connection,
1022
- schemaName,
1023
- malloyConnection,
1024
- tableNames,
1025
- );
1026
- case "trino":
1027
- return listTablesForTrino(
1028
- connection,
1029
- schemaName,
1030
- malloyConnection,
1031
- tableNames,
1032
- );
1033
- case "databricks":
1034
- return listTablesForDatabricks(
1035
- connection,
1036
- schemaName,
1037
- malloyConnection,
1038
- tableNames,
1039
- );
1040
- case "duckdb":
1041
- return listTablesForDuckDB(
1042
- connection,
1043
- schemaName,
1044
- malloyConnection,
1045
- tableNames,
1046
- );
1047
- case "motherduck":
1048
- return listTablesForMotherDuck(
1049
- connection,
1050
- schemaName,
1051
- malloyConnection,
1052
- tableNames,
1053
- );
1054
- case "ducklake":
1055
- return listTablesForDuckLake(
1056
- connection,
1057
- schemaName,
1058
- malloyConnection,
1059
- tableNames,
1060
- );
1061
- case "publisher":
1062
- return listTablesForPublisher(connection, schemaName, tableNames);
1063
- default:
1064
- throw new Error(`Unsupported connection type: ${connection.type}`);
1065
- }
1066
- }
1067
-
1068
- /**
1069
- * BigQuery: list tables via API client, then fetch each table's schema
1070
- * individually since BigQuery's INFORMATION_SCHEMA is region-scoped.
1071
- */
1072
- async function listTablesForBigQuery(
1073
- connection: ApiConnection,
1074
- schemaName: string,
1075
- malloyConnection: Connection,
1076
- tableNames?: string[],
1077
- ): Promise<ApiTable[]> {
1078
- try {
1079
- const bigquery = createBigQueryClient(connection);
1080
- // A 3-segment table reference ("project.dataset.table") reaches here with a
1081
- // project-qualified schema ("project.dataset"). bigquery.dataset() takes a
1082
- // BARE dataset id plus an optional projectId, so passing "project.dataset" as
1083
- // the id resolves to a non-existent dataset in the client's default project —
1084
- // the dataset's tables never list, so the orphan sweep can't see (and reclaim)
1085
- // those tables. Split the project off the last dot. (Domain-scoped project ids
1086
- // like "domain.com:project" keep their dots/colon since we split on the last.)
1087
- const lastDot = schemaName.lastIndexOf(".");
1088
- const dataset =
1089
- lastDot === -1
1090
- ? bigquery.dataset(schemaName)
1091
- : bigquery.dataset(schemaName.slice(lastDot + 1), {
1092
- projectId: schemaName.slice(0, lastDot),
1093
- });
1094
- const [tables] = await dataset.getTables();
1095
-
1096
- let names = tables
1097
- .map((table) => table.id)
1098
- .filter((id): id is string => id !== undefined);
1099
- if (tableNames) {
1100
- const allowed = new Set(tableNames);
1101
- names = names.filter((id) => allowed.has(id));
1102
- }
1103
-
1104
- const results = await Promise.all(
1105
- names.map(async (tableName) => {
1106
- const tablePath = `${schemaName}.${tableName}`;
1107
- try {
1108
- const source = await (
1109
- malloyConnection as Connection & {
1110
- fetchTableSchema: (
1111
- tableKey: string,
1112
- tablePath: string,
1113
- ) => Promise<TableSourceDef | undefined>;
1114
- }
1115
- ).fetchTableSchema(tableName, tablePath);
1116
- const columns =
1117
- source?.fields?.map((field) => ({
1118
- name: field.name,
1119
- type: field.type,
1120
- })) || [];
1121
- return { resource: tablePath, columns };
1122
- } catch (error) {
1123
- logger.warn(`Failed to get schema for table ${tableName}`, {
1124
- error: extractErrorDataFromError(error),
1125
- schemaName,
1126
- tableName,
1127
- });
1128
- return { resource: tablePath, columns: [] };
1129
- }
1130
- }),
1131
- );
1132
- return results;
1133
- } catch (error) {
1134
- logger.error(
1135
- `Error getting tables for BigQuery schema ${schemaName} in connection ${connection.name}`,
1136
- { error },
1137
- );
1138
- throw new Error(
1139
- `Failed to get tables for BigQuery schema ${schemaName} in connection ${connection.name}: ${(error as Error).message}`,
1140
- );
1141
- }
1142
- }
1143
-
1144
- async function listTablesForMySQL(
1145
- connection: ApiConnection,
1146
- schemaName: string,
1147
- malloyConnection: Connection,
1148
- tableNames?: string[],
1149
- ): Promise<ApiTable[]> {
1150
- if (!connection.mysqlConnection) {
1151
- throw new Error("Mysql connection is required");
1152
- }
1153
- try {
1154
- const result = await malloyConnection.runSQL(
1155
- `SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE FROM information_schema.columns WHERE table_schema = '${schemaName}' ${sqlInFilter("TABLE_NAME", tableNames)} ORDER BY TABLE_NAME, ORDINAL_POSITION`,
1156
- );
1157
- const rows = standardizeRunSQLResult(result);
1158
- return groupColumnRowsIntoTables(rows, (t) => `${schemaName}.${t}`);
1159
- } catch (error) {
1160
- logger.error(
1161
- `Error getting tables for MySQL schema ${schemaName} in connection ${connection.name}`,
1162
- { error },
1163
- );
1164
- throw new Error(
1165
- `Failed to get tables for MySQL schema ${schemaName} in connection ${connection.name}: ${(error as Error).message}`,
1166
- );
1167
- }
1168
- }
1169
-
1170
- async function listTablesForPostgres(
1171
- connection: ApiConnection,
1172
- schemaName: string,
1173
- malloyConnection: Connection,
1174
- tableNames?: string[],
1175
- ): Promise<ApiTable[]> {
1176
- if (!connection.postgresConnection) {
1177
- throw new Error("Postgres connection is required");
1178
- }
1179
- try {
1180
- // Wrap in row_to_json because the Malloy Postgres driver's runSQL
1181
- // de-JSONs each row via row.row (matching Malloy-generated queries).
1182
- const result = await malloyConnection.runSQL(
1183
- `SELECT row_to_json(t) as row FROM (SELECT table_name, column_name, data_type FROM information_schema.columns WHERE table_schema = '${schemaName}' ${sqlInFilter("table_name", tableNames)} ORDER BY table_name, ordinal_position) t`,
1184
- );
1185
- const rows = standardizeRunSQLResult(result);
1186
- return groupColumnRowsIntoTables(rows, (t) => `${schemaName}.${t}`);
1187
- } catch (error) {
1188
- logger.error(
1189
- `Error getting tables for Postgres schema ${schemaName} in connection ${connection.name}`,
1190
- { error },
1191
- );
1192
- throw new Error(
1193
- `Failed to get tables for Postgres schema ${schemaName} in connection ${connection.name}: ${(error as Error).message}`,
1194
- );
1195
- }
1196
- }
1197
-
1198
- async function listTablesForSnowflake(
1199
- connection: ApiConnection,
1200
- schemaName: string,
1201
- malloyConnection: Connection,
1202
- tableNames?: string[],
1203
- ): Promise<ApiTable[]> {
1204
- if (!connection.snowflakeConnection) {
1205
- throw new Error("Snowflake connection is required");
1206
- }
1207
- try {
1208
- const parts = schemaName.split(".");
1209
- let databaseName: string;
1210
- let schemaOnly: string;
1211
-
1212
- if (parts.length >= 2) {
1213
- databaseName = parts[0];
1214
- schemaOnly = parts[1];
1215
- } else {
1216
- databaseName = connection.snowflakeConnection.database ?? "";
1217
- schemaOnly = parts[0];
1218
- }
1219
-
1220
- if (!databaseName) {
1221
- throw new Error(
1222
- `Cannot resolve database for schema "${schemaName}": provide DATABASE.SCHEMA or configure a database on the connection`,
1223
- );
1224
- }
1225
-
1226
- const qualifiedSchema = `${databaseName}.${schemaOnly}`;
1227
- const result = await malloyConnection.runSQL(
1228
- `SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE FROM ${databaseName}.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '${schemaOnly}' ${sqlInFilter("TABLE_NAME", tableNames)} ORDER BY TABLE_NAME, ORDINAL_POSITION`,
1229
- );
1230
- const rows = standardizeRunSQLResult(result);
1231
- return groupColumnRowsIntoTables(rows, (t) => `${qualifiedSchema}.${t}`);
1232
- } catch (error) {
1233
- logger.error(
1234
- `Error getting tables for Snowflake schema ${schemaName} in connection ${connection.name}`,
1235
- { error },
1236
- );
1237
- throw new Error(
1238
- `Failed to get tables for Snowflake schema ${schemaName} in connection ${connection.name}: ${(error as Error).message}`,
1239
- );
1240
- }
1241
- }
1242
-
1243
- async function listTablesForTrino(
1244
- connection: ApiConnection,
1245
- schemaName: string,
1246
- malloyConnection: Connection,
1247
- tableNames?: string[],
1248
- ): Promise<ApiTable[]> {
1249
- if (!connection.trinoConnection) {
1250
- throw new Error("Trino connection is required");
1251
- }
1252
- try {
1253
- let catalogPrefix: string;
1254
- let schemaOnly: string;
1255
- let resourcePrefix: string;
1256
-
1257
- if (connection.trinoConnection.catalog) {
1258
- catalogPrefix = `${connection.trinoConnection.catalog}.`;
1259
- schemaOnly = schemaName;
1260
- resourcePrefix = `${connection.trinoConnection.catalog}.${schemaName}`;
1261
- } else {
1262
- const dotIdx = schemaName.indexOf(".");
1263
- if (dotIdx > 0) {
1264
- catalogPrefix = `${schemaName.substring(0, dotIdx)}.`;
1265
- schemaOnly = schemaName.substring(dotIdx + 1);
1266
- } else {
1267
- catalogPrefix = "";
1268
- schemaOnly = schemaName;
1269
- }
1270
- resourcePrefix = schemaName;
1271
- }
1272
-
1273
- const result = await malloyConnection.runSQL(
1274
- `SELECT table_name, column_name, data_type FROM ${catalogPrefix}information_schema.columns WHERE table_schema = '${schemaOnly}' ${sqlInFilter("table_name", tableNames)} ORDER BY table_name, ordinal_position`,
1275
- );
1276
- const rows = standardizeRunSQLResult(result);
1277
- return groupColumnRowsIntoTables(rows, (t) => `${resourcePrefix}.${t}`);
1278
- } catch (error) {
1279
- logger.error(
1280
- `Error getting tables for Trino schema ${schemaName} in connection ${connection.name}`,
1281
- { error },
1282
- );
1283
- throw new Error(
1284
- `Failed to get tables for Trino schema ${schemaName} in connection ${connection.name}: ${(error as Error).message}`,
1285
- );
1286
- }
1287
- }
1288
-
1289
- async function listTablesForDatabricks(
1290
- connection: ApiConnection,
1291
- schemaName: string,
1292
- malloyConnection: Connection,
1293
- tableNames?: string[],
1294
- ): Promise<ApiTable[]> {
1295
- if (!connection.databricksConnection) {
1296
- throw new Error("Databricks connection is required");
1297
- }
1298
- try {
1299
- let catalogPrefix: string;
1300
- let schemaOnly: string;
1301
- let resourcePrefix: string;
1302
-
1303
- if (connection.databricksConnection.defaultCatalog) {
1304
- catalogPrefix = `${connection.databricksConnection.defaultCatalog}.`;
1305
- schemaOnly = schemaName;
1306
- resourcePrefix = `${connection.databricksConnection.defaultCatalog}.${schemaName}`;
1307
- } else {
1308
- const dotIdx = schemaName.indexOf(".");
1309
- if (dotIdx > 0) {
1310
- catalogPrefix = `${schemaName.substring(0, dotIdx)}.`;
1311
- schemaOnly = schemaName.substring(dotIdx + 1);
1312
- } else {
1313
- catalogPrefix = "";
1314
- schemaOnly = schemaName;
1315
- }
1316
- resourcePrefix = schemaName;
1317
- }
1318
-
1319
- const result = await malloyConnection.runSQL(
1320
- `SELECT table_name, column_name, data_type FROM ${catalogPrefix}information_schema.columns WHERE table_schema = '${schemaOnly}' ${sqlInFilter("table_name", tableNames)} ORDER BY table_name, ordinal_position`,
1321
- );
1322
- const rows = standardizeRunSQLResult(result);
1323
- return groupColumnRowsIntoTables(rows, (t) => `${resourcePrefix}.${t}`);
1324
- } catch (error) {
1325
- logger.error(
1326
- `Error getting tables for Databricks schema ${schemaName} in connection ${connection.name}`,
1327
- { error },
1328
- );
1329
- throw new Error(
1330
- `Failed to get tables for Databricks schema ${schemaName} in connection ${connection.name}: ${(error as Error).message}`,
1331
- );
1332
- }
1333
- }
1334
-
1335
- async function listTablesForDuckDB(
1336
- connection: ApiConnection,
1337
- schemaName: string,
1338
- malloyConnection: Connection,
1339
- tableNames?: string[],
1340
- ): Promise<ApiTable[]> {
1341
- if (!connection.duckdbConnection) {
1342
- throw new Error("DuckDB connection is required");
1343
- }
1344
-
1345
- const attachedDbs = connection.duckdbConnection.attachedDatabases || [];
1346
-
1347
- // Azure attached database matched by name
1348
- const azureDb = attachedDbs.find(
1349
- (db) =>
1350
- db.type === "azure" && db.name === schemaName && db.azureConnection,
1351
- );
1352
- if (azureDb) {
1353
- const azureConn = azureDb.azureConnection!;
1354
- const fileUrl =
1355
- azureConn.authType === "sas_token"
1356
- ? azureConn.sasUrl
1357
- : azureConn.fileUrl;
1358
- if (fileUrl) {
1359
- return describeAzureFile(malloyConnection, fileUrl, azureConn);
1360
- }
1361
- }
1362
-
1363
- // Azure ADLS file path (abfss://, https://, az://)
1364
- if (
1365
- schemaName.startsWith("abfss://") ||
1366
- schemaName.startsWith("https://") ||
1367
- schemaName.startsWith("az://")
1368
- ) {
1369
- return describeAzureFile(malloyConnection, schemaName);
1370
- }
1371
-
1372
- // Cloud storage (GCS/S3)
1373
- const parsedUri = parseCloudUri(schemaName);
1374
- if (parsedUri) {
1375
- const {
1376
- type: cloudType,
1377
- bucket: bucketName,
1378
- path: directoryPath,
1379
- } = parsedUri;
1380
- const credentials = getCloudCredentialsFromAttachedDatabases(
1381
- attachedDbs,
1382
- cloudType,
1383
- );
1384
- if (!credentials) {
1385
- throw new Error(
1386
- `${cloudType.toUpperCase()} credentials not found in attached databases`,
1387
- );
1388
- }
1389
- const fileKeys = await listDataFilesInDirectory(
1390
- credentials,
1391
- bucketName,
1392
- directoryPath,
1393
- );
1394
- return getCloudTablesWithColumns(
1395
- malloyConnection,
1396
- credentials,
1397
- bucketName,
1398
- fileKeys,
1399
- );
1400
- }
1401
-
1402
- // Regular DuckDB schema — query information_schema.columns
1403
- const dotIdx = schemaName.indexOf(".");
1404
- if (dotIdx < 0) {
1405
- throw new Error(
1406
- `DuckDB schema name must be qualified as "catalog.schema", got "${schemaName}"`,
1407
- );
1408
- }
1409
- const catalogName = schemaName.substring(0, dotIdx);
1410
- const actualSchemaName = schemaName.substring(dotIdx + 1);
1411
-
1412
- try {
1413
- const result = await malloyConnection.runSQL(
1414
- `SELECT table_name, column_name, data_type FROM information_schema.columns WHERE table_schema = '${actualSchemaName}' AND table_catalog = '${catalogName}' ${sqlInFilter("table_name", tableNames)} ORDER BY table_name, ordinal_position`,
1415
- );
1416
- const rows = standardizeRunSQLResult(result);
1417
- return groupColumnRowsIntoTables(rows, (t) => `${schemaName}.${t}`);
1418
- } catch (error) {
1419
- logger.error(
1420
- `Error getting tables for DuckDB schema ${schemaName} in connection ${connection.name}`,
1421
- { error },
1422
- );
1423
- throw new Error(
1424
- `Failed to get tables for DuckDB schema ${schemaName} in connection ${connection.name}: ${(error as Error).message}`,
1425
- );
1426
- }
1427
- }
1428
-
1429
- async function listTablesForMotherDuck(
1430
- connection: ApiConnection,
1431
- schemaName: string,
1432
- malloyConnection: Connection,
1433
- tableNames?: string[],
1434
- ): Promise<ApiTable[]> {
1435
- if (!connection.motherduckConnection) {
1436
- throw new Error("MotherDuck connection is required");
1437
- }
1438
- try {
1439
- const result = await malloyConnection.runSQL(
1440
- `SELECT table_name, column_name, data_type FROM information_schema.columns WHERE table_schema = '${schemaName}' ${sqlInFilter("table_name", tableNames)} ORDER BY table_name, ordinal_position`,
1441
- );
1442
- const rows = standardizeRunSQLResult(result);
1443
- return groupColumnRowsIntoTables(rows, (t) => `${schemaName}.${t}`);
1444
- } catch (error) {
1445
- logger.error(
1446
- `Error getting tables for MotherDuck schema ${schemaName} in connection ${connection.name}`,
1447
- { error },
1448
- );
1449
- throw new Error(
1450
- `Failed to get tables for MotherDuck schema ${schemaName} in connection ${connection.name}: ${(error as Error).message}`,
1451
- );
1452
- }
1453
- }
1454
-
1455
- async function listTablesForDuckLake(
1456
- connection: ApiConnection,
1457
- schemaName: string,
1458
- malloyConnection: Connection,
1459
- tableNames?: string[],
1460
- ): Promise<ApiTable[]> {
1461
- // Prefix bare schema names with the catalog (connection) name.
1462
- // Two-part names like "catalog.schema" are already qualified.
1463
- if (!schemaName.includes(".")) {
1464
- schemaName = `${connection.name}.${schemaName}`;
1465
- }
1466
-
1467
- const catalogName = schemaName.split(".")[0];
1468
- const actualSchemaName = schemaName.split(".")[1];
1469
- try {
1470
- const result = await malloyConnection.runSQL(
1471
- `SELECT table_name, column_name, data_type FROM information_schema.columns WHERE table_schema = '${actualSchemaName}' AND table_catalog = '${catalogName}' ${sqlInFilter("table_name", tableNames)} ORDER BY table_name, ordinal_position`,
1472
- );
1473
- const rows = standardizeRunSQLResult(result);
1474
- return groupColumnRowsIntoTables(rows, (t) => `${schemaName}.${t}`);
1475
- } catch (error) {
1476
- logger.error(
1477
- `Error getting tables for DuckLake schema ${schemaName} in connection ${connection.name}`,
1478
- { error },
1479
- );
1480
- throw new Error(
1481
- `Failed to get tables for DuckLake schema ${schemaName} in connection ${connection.name}: ${(error as Error).message}`,
1482
- );
1483
- }
1484
- }
1485
-
1486
- export function extractErrorDataFromError(error: unknown): {
1487
- error: string;
1488
- stack?: string;
1489
- task?: unknown;
1490
- } {
1491
- const errorMessage = error instanceof Error ? error.message : String(error);
1492
- const errorData: { error: string; stack?: string; task?: unknown } = {
1493
- error: errorMessage,
1494
- };
1495
- if (error instanceof Error && logger.level === "debug") {
1496
- errorData.stack = error.stack;
1497
- }
1498
- if (error && typeof error === "object" && "task" in error) {
1499
- errorData.task = (error as { task?: unknown }).task;
1500
- }
1501
- return errorData;
1502
- }