@query-farm/vgi 0.48.2 → 0.48.4

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 (54) hide show
  1. package/README.md +27 -0
  2. package/dist/arrow/impl-arrowjs/iterate.d.ts +7 -3
  3. package/dist/arrow/impl-flechette/iterate.d.ts +2 -1
  4. package/dist/catalog/descriptors.d.ts +30 -0
  5. package/dist/catalog/interface.d.ts +28 -0
  6. package/dist/catalog/read-only.d.ts +16 -2
  7. package/dist/client-entry.js +9 -25
  8. package/dist/client-entry.js.map +4 -4
  9. package/dist/functions/aggregate.d.ts +2 -1
  10. package/dist/functions/copy-from.d.ts +2 -1
  11. package/dist/functions/copy-to.d.ts +2 -1
  12. package/dist/functions/scalar.d.ts +2 -1
  13. package/dist/functions/table-buffering.d.ts +2 -1
  14. package/dist/functions/table-in-out.d.ts +3 -2
  15. package/dist/functions/table.d.ts +2 -1
  16. package/dist/functions/types.d.ts +2 -1
  17. package/dist/index.core.d.ts +4 -1
  18. package/dist/index.js +360 -72
  19. package/dist/index.js.map +25 -23
  20. package/dist/metadata/types.d.ts +3 -1
  21. package/dist/protocol/handlers/catalog/shared.d.ts +8 -0
  22. package/dist/secrets/helpers.d.ts +31 -3
  23. package/dist/secrets/requirements.d.ts +38 -0
  24. package/dist/serve-entry.js +51 -33
  25. package/dist/serve-entry.js.map +9 -9
  26. package/dist/worker-cf-entry.d.ts +2 -2
  27. package/dist/worker-cf-entry.js +296 -50
  28. package/dist/worker-cf-entry.js.map +21 -18
  29. package/dist/write-results.d.ts +57 -0
  30. package/package.json +1 -1
  31. package/src/arrow/impl-arrowjs/iterate.ts +17 -40
  32. package/src/arrow/impl-flechette/iterate.ts +5 -24
  33. package/src/catalog/descriptors.ts +30 -0
  34. package/src/catalog/interface.ts +51 -0
  35. package/src/catalog/read-only.ts +129 -21
  36. package/src/functions/aggregate.ts +3 -2
  37. package/src/functions/copy-from.ts +3 -2
  38. package/src/functions/copy-to.ts +2 -1
  39. package/src/functions/scalar.ts +3 -2
  40. package/src/functions/table-buffering.ts +3 -2
  41. package/src/functions/table-in-out.ts +5 -4
  42. package/src/functions/table.ts +3 -2
  43. package/src/functions/types.ts +2 -1
  44. package/src/index.core.ts +33 -0
  45. package/src/metadata/resolve.ts +2 -1
  46. package/src/metadata/serialize.ts +25 -5
  47. package/src/metadata/types.ts +3 -1
  48. package/src/protocol/handlers/catalog/shared.ts +17 -0
  49. package/src/protocol/handlers/catalog/table.ts +37 -0
  50. package/src/protocol/handlers/function.ts +42 -14
  51. package/src/secrets/helpers.ts +96 -9
  52. package/src/secrets/requirements.ts +121 -0
  53. package/src/worker-cf-entry.ts +14 -0
  54. package/src/write-results.ts +174 -0
@@ -3,9 +3,9 @@ export type { VgiFetchOptions } from "./http/fetch.js";
3
3
  export type { HostingOptions } from "./rpc-server.js";
4
4
  export { AuthUnavailableError, GrantKeys, GrantRefusedError, IdentityUnavailableError, StatusError, } from "@query-farm/vgi-rpc";
5
5
  export type { GrantMinter, IssuedGrant, TokenIdentity, TokenResolver } from "@query-farm/vgi-rpc";
6
- export { defineScalarFunction, defineTableFunction, defineAggregate, defineTableInOutFunction, defineRowTransformFunction, parentRowsMetadata, PARENT_ROW_METADATA_KEY, moreOutputMetadata, constraintSpecFields, cacheControlMetadata, FunctionRegistry, ReadOnlyCatalogInterface, CompositeCatalogInterface, CatalogInterface, Arguments, FunctionType, serializeAttachOptionSpec, serializeAttachOptionSpecs, serializeColumnStatistics, BindResultSchema, ScanFunctionResultSchema, } from "./index.core.js";
6
+ export { defineScalarFunction, defineTableFunction, defineAggregate, defineTableInOutFunction, defineRowTransformFunction, parentRowsMetadata, PARENT_ROW_METADATA_KEY, moreOutputMetadata, constraintSpecFields, cacheControlMetadata, FunctionRegistry, ReadOnlyCatalogInterface, CompositeCatalogInterface, CatalogInterface, Arguments, FunctionType, serializeAttachOptionSpec, serializeAttachOptionSpecs, serializeColumnStatistics, BindResultSchema, ScanFunctionResultSchema, secretType, secretsOfType, secretOfType, requireSecretOfType, secretByName, secretForScope, secretForScopeOfType, normalizeRequiredSecrets, } from "./index.core.js";
7
7
  export * from "./catalog/public-codecs.js";
8
- export type { CacheControl, CacheScope, AttachOptionSpec, ColumnStatistics, CatalogAttachResult, CatalogDescriptor, CatalogInfo, TableInfo, AttachOpaqueData, TransactionOpaqueData, SchemaInfo, VgiFunction, TableProcessParams, ArgumentSpec, ArgumentConstraints, RowTransformConfig, RowTransformProcessParams, TableInOutBindParams, ConstraintRecordSpec, ConstraintRecordView, } from "./index.core.js";
8
+ export type { CacheControl, CacheScope, AttachOptionSpec, ColumnStatistics, CatalogAttachResult, CatalogDescriptor, CatalogInfo, TableInfo, AttachOpaqueData, TransactionOpaqueData, SchemaInfo, VgiFunction, TableProcessParams, ArgumentSpec, ArgumentConstraints, RowTransformConfig, RowTransformProcessParams, TableInOutBindParams, ConstraintRecordSpec, ConstraintRecordView, SecretFields, SecretsDict, RequiredSecret, SecretRequirement, SecretRequirementSpec, } from "./index.core.js";
9
9
  export type { ProtocolConfig } from "./protocol/dispatch.js";
10
10
  export type { LandingInfo } from "./http/landing.js";
11
11
  export { createLandingRoutes } from "./http/landing.js";
@@ -1554,30 +1554,14 @@ function batchToSecretDict(batch) {
1554
1554
  const result = {};
1555
1555
  for (const field of a.schema.fields) {
1556
1556
  const col = a.getChild(field.name);
1557
- if (col) {
1558
- const type = field.type;
1559
- const val = codecFor(type).canonicalToRich(readCanonicalValue(type, col, 0));
1560
- let key = field.name;
1561
- let scope;
1562
- if (field.name.startsWith("secret_")) {
1563
- const secretType = field.metadata?.get?.("secret_type");
1564
- if (secretType) {
1565
- key = secretType;
1566
- scope = field.metadata?.get?.("scope") ?? undefined;
1567
- }
1568
- }
1569
- if (val && typeof val === "object" && !ArrayBuffer.isView(val)) {
1570
- const dict = { ...val };
1571
- if (key in result) {
1572
- throw new Error(`batchToSecretDict: duplicate secret_type '${key}' (scope=${scope ?? "none"}). ` + `Use scoped secrets with distinct scopes to avoid collisions.`);
1573
- }
1574
- result[key] = dict;
1575
- if (scope) {
1576
- result[`${key}:${scope}`] = dict;
1577
- }
1578
- } else if (val === null || val === undefined) {} else {
1579
- result[key] = {};
1580
- }
1557
+ if (!col)
1558
+ continue;
1559
+ const type = field.type;
1560
+ const val = codecFor(type).canonicalToRich(readCanonicalValue(type, col, 0));
1561
+ if (val && typeof val === "object" && !ArrayBuffer.isView(val)) {
1562
+ result[field.name] = { ...val };
1563
+ } else if (val !== null && val !== undefined) {
1564
+ result[field.name] = {};
1581
1565
  }
1582
1566
  }
1583
1567
  return result;
@@ -10006,6 +9990,11 @@ async function sealTransaction(plaintext, attachEnvelope, auth, signingKey) {
10006
9990
  return plaintext;
10007
9991
  return sealBytes(plaintext, signingKey, transactionAad(auth, attachEnvelope), TRANSACTION_ENVELOPE_VERSION);
10008
9992
  }
9993
+ async function openTransaction(envelope, attachEnvelope, auth, signingKey) {
9994
+ if (!signingKey || envelope.length === 0)
9995
+ return envelope;
9996
+ return openBytes(envelope, signingKey, transactionAad(auth, attachEnvelope), TRANSACTION_ENVELOPE_VERSION, "transaction_opaque_data");
9997
+ }
10009
9998
  async function unwrapParamsOpaque(params, ctx, signingKey) {
10010
9999
  const auth = ctx?.auth;
10011
10000
  let sealedAttach = new Uint8Array(0);
@@ -10286,7 +10275,12 @@ async function liveSplitAnchor(catalogInterface, bindCall, auth, signingKey) {
10286
10275
  if (!catalogInterface?.version || bindCall.attach_opaque_data == null)
10287
10276
  return;
10288
10277
  const raw = toUint8Array(bindCall.attach_opaque_data);
10289
- const txn = bindCall.transaction_opaque_data ? toUint8Array(bindCall.transaction_opaque_data) : undefined;
10278
+ let txn = bindCall.transaction_opaque_data ? toUint8Array(bindCall.transaction_opaque_data) : undefined;
10279
+ if (txn && txn.length > 0 && signingKey) {
10280
+ try {
10281
+ txn = await openTransaction(txn, raw, auth, signingKey);
10282
+ } catch {}
10283
+ }
10290
10284
  const forms = [
10291
10285
  async () => raw,
10292
10286
  async () => openAttach(raw, auth, signingKey)
@@ -10324,14 +10318,22 @@ function functionHandlers(config) {
10324
10318
  return env;
10325
10319
  return openAttach(env, ctx?.auth ?? currentRequestAuth(), signingKey);
10326
10320
  }
10321
+ async function openOpaque(bindCall, ctx) {
10322
+ const sealedAttach = bindCall.attach_opaque_data != null ? toUint8Array(bindCall.attach_opaque_data) : new Uint8Array(0);
10323
+ if (bindCall.transaction_opaque_data != null) {
10324
+ bindCall.transaction_opaque_data = await openTransaction(toUint8Array(bindCall.transaction_opaque_data), sealedAttach, ctx?.auth ?? currentRequestAuth(), signingKey);
10325
+ }
10326
+ bindCall.attach_opaque_data = await stripAttach(bindCall.attach_opaque_data, ctx);
10327
+ }
10327
10328
  async function strippedContext(bindCall, ctx) {
10328
- let attach = null;
10329
+ const copy = { ...bindCall };
10329
10330
  try {
10330
- attach = await stripAttach(bindCall.attach_opaque_data, ctx);
10331
+ await openOpaque(copy, ctx);
10331
10332
  } catch {
10332
- attach = null;
10333
+ copy.attach_opaque_data = null;
10334
+ copy.transaction_opaque_data = null;
10333
10335
  }
10334
- return overloadContext({ ...bindCall, attach_opaque_data: attach }, catalogInterface);
10336
+ return overloadContext(copy, catalogInterface);
10335
10337
  }
10336
10338
  const emptySchema = schema2([]);
10337
10339
  const dummyInputSchema = schema2([
@@ -10340,7 +10342,7 @@ function functionHandlers(config) {
10340
10342
  const bind = async (params, ctx) => {
10341
10343
  const innerParams = unwrapRequest(params.request);
10342
10344
  const request = deserializeBindRequest(innerParams);
10343
- request.attach_opaque_data = await stripAttach(request.attach_opaque_data, ctx);
10345
+ await openOpaque(request, ctx);
10344
10346
  const func = registry.get(request.function_name, overloadContext(request, catalogInterface));
10345
10347
  const response = await func.bind(request);
10346
10348
  validateProjectionOffer(response);
@@ -10355,7 +10357,7 @@ function functionHandlers(config) {
10355
10357
  const innerParams = unwrapRequest(params.request);
10356
10358
  const request = deserializeInitRequest(innerParams);
10357
10359
  const auth = ctx?.auth ?? currentRequestAuth();
10358
- request.bind_call.attach_opaque_data = await stripAttach(request.bind_call.attach_opaque_data, ctx);
10360
+ await openOpaque(request.bind_call, ctx);
10359
10361
  await resolveSplitPayloads(request, innerParams, {
10360
10362
  auth,
10361
10363
  signingKey,
@@ -10400,7 +10402,7 @@ function functionHandlers(config) {
10400
10402
  } else {
10401
10403
  const carried = parseCarriedInitRequest(state.initRequestPacked);
10402
10404
  const request = carried.request;
10403
- request.bind_call.attach_opaque_data = await stripAttach(request.bind_call.attach_opaque_data, undefined);
10405
+ await openOpaque(request.bind_call, undefined);
10404
10406
  await resolveSplitPayloads(request, { bind_call: carried.bindCallIpc }, {
10405
10407
  auth: currentRequestAuth(),
10406
10408
  signingKey,
@@ -10558,6 +10560,65 @@ function functionHandlers(config) {
10558
10560
  // src/protocol/handlers/aggregate.ts
10559
10561
  init_arrow();
10560
10562
 
10563
+ // src/secrets/requirements.ts
10564
+ var KNOWN_KEYS = new Set(["secretType", "secret_type", "scope", "secretName", "secret_name"]);
10565
+ function optionalString(value, what, where) {
10566
+ if (value === undefined || value === null)
10567
+ return null;
10568
+ if (typeof value !== "string") {
10569
+ throw new TypeError(`${where}: ${what} must be a string, got ${typeof value}`);
10570
+ }
10571
+ return value === "" ? null : value;
10572
+ }
10573
+ function normalizeRequiredSecrets(value, functionName = "<function>") {
10574
+ if (value === undefined || value === null)
10575
+ return [];
10576
+ const where = `requiredSecrets of '${functionName}'`;
10577
+ if (!Array.isArray(value)) {
10578
+ throw new TypeError(`${where} must be an array of secret types or { secretType, scope?, secretName? } objects, got ${typeof value}`);
10579
+ }
10580
+ const out = [];
10581
+ const seen = new Set;
10582
+ value.forEach((entry, i) => {
10583
+ const at = `${where}[${i}]`;
10584
+ let req;
10585
+ if (typeof entry === "string") {
10586
+ if (entry === "")
10587
+ throw new TypeError(`${at}: secret type must not be empty`);
10588
+ req = { secretType: entry, scope: null, secretName: null };
10589
+ } else if (entry !== null && typeof entry === "object" && !Array.isArray(entry)) {
10590
+ const obj = entry;
10591
+ const unknown = Object.keys(obj).filter((k) => !KNOWN_KEYS.has(k));
10592
+ if (unknown.length > 0) {
10593
+ throw new TypeError(`${at}: unknown key(s) ${unknown.map((k) => `'${k}'`).join(", ")}; ` + `expected secretType, scope, secretName`);
10594
+ }
10595
+ if (obj.secretType !== undefined && obj.secret_type !== undefined && obj.secretType !== obj.secret_type) {
10596
+ throw new TypeError(`${at}: secretType and secret_type disagree`);
10597
+ }
10598
+ if (obj.secretName !== undefined && obj.secret_name !== undefined && obj.secretName !== obj.secret_name) {
10599
+ throw new TypeError(`${at}: secretName and secret_name disagree`);
10600
+ }
10601
+ const secretType = obj.secretType ?? obj.secret_type;
10602
+ if (typeof secretType !== "string" || secretType === "") {
10603
+ throw new TypeError(`${at}: secretType must be a non-empty string`);
10604
+ }
10605
+ req = {
10606
+ secretType,
10607
+ scope: optionalString(obj.scope, "scope", at),
10608
+ secretName: optionalString(obj.secretName ?? obj.secret_name, "secretName", at)
10609
+ };
10610
+ } else {
10611
+ throw new TypeError(`${at}: expected a secret type string or a { secretType, scope?, secretName? } object, got ` + (entry === null ? "null" : Array.isArray(entry) ? "array" : typeof entry));
10612
+ }
10613
+ const key = JSON.stringify([req.secretType, req.scope, req.secretName]);
10614
+ if (seen.has(key))
10615
+ return;
10616
+ seen.add(key);
10617
+ out.push(req);
10618
+ });
10619
+ return out;
10620
+ }
10621
+
10561
10622
  // src/functions/aggregate.ts
10562
10623
  init_arrow();
10563
10624
 
@@ -10886,7 +10947,7 @@ function defineAggregate(config) {
10886
10947
  tags: config.tags,
10887
10948
  parameterDefaultValues: config.parameterDefaultValues,
10888
10949
  nullHandling: config.nullHandling,
10889
- requiredSecrets: config.requiredSecrets
10950
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name)
10890
10951
  };
10891
10952
  const isAnyType = isNull(config.outputType);
10892
10953
  const defaultOutputSchema = isAnyType ? schema2([field2("result", nullType2(), true, new Map([["vgi:any", "true"]]))]) : schema2([field2("result", config.outputType, true)]);
@@ -12761,6 +12822,15 @@ class CatalogInterface {
12761
12822
  tableScanFunctionGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData) {
12762
12823
  throw new CatalogReadOnlyError("table_scan_function_get");
12763
12824
  }
12825
+ tableInsertFunctionGet(attachOpaqueData, schemaPath, name, transactionOpaqueData, writableBranchFunctionName) {
12826
+ throw new CatalogReadOnlyError("table_insert_function_get");
12827
+ }
12828
+ tableUpdateFunctionGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
12829
+ throw new CatalogReadOnlyError("table_update_function_get");
12830
+ }
12831
+ tableDeleteFunctionGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
12832
+ throw new CatalogReadOnlyError("table_delete_function_get");
12833
+ }
12764
12834
  tableScanBranchesGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData) {
12765
12835
  const legacy = this.tableScanFunctionGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData);
12766
12836
  return isPromise(legacy) ? legacy.then((r) => singleBranchResult(r)) : singleBranchResult(legacy);
@@ -13711,6 +13781,19 @@ function catalogTableHandlers(getCatalog, signingKey) {
13711
13781
  const scanResult = await cat.tableScanFunctionGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.at_unit, params.at_value, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
13712
13782
  return wrapResult(scanResult, ScanFunctionResultSchema);
13713
13783
  });
13784
+ const optionalTx = (params) => params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined;
13785
+ const catalogTableInsertFunctionGet = catalogHandler(signingKey, async (params) => {
13786
+ const result = await getCatalog().tableInsertFunctionGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, optionalTx(params), params.writable_branch_function_name ?? null);
13787
+ return wrapResult(result, ScanFunctionResultSchema);
13788
+ });
13789
+ const catalogTableUpdateFunctionGet = catalogHandler(signingKey, async (params) => {
13790
+ const result = await getCatalog().tableUpdateFunctionGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, optionalTx(params));
13791
+ return wrapResult(result, ScanFunctionResultSchema);
13792
+ });
13793
+ const catalogTableDeleteFunctionGet = catalogHandler(signingKey, async (params) => {
13794
+ const result = await getCatalog().tableDeleteFunctionGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, optionalTx(params));
13795
+ return wrapResult(result, ScanFunctionResultSchema);
13796
+ });
13714
13797
  const catalogTableScanBranchesGet = catalogHandler(signingKey, async (params) => {
13715
13798
  const cat = getCatalog();
13716
13799
  const branchesResult = await cat.tableScanBranchesGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.at_unit, params.at_value, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
@@ -13789,6 +13872,9 @@ function catalogTableHandlers(getCatalog, signingKey) {
13789
13872
  catalogTableDrop,
13790
13873
  catalogTableColumnStatisticsGet,
13791
13874
  catalogTableScanFunctionGet,
13875
+ catalogTableInsertFunctionGet,
13876
+ catalogTableUpdateFunctionGet,
13877
+ catalogTableDeleteFunctionGet,
13792
13878
  catalogTableScanBranchesGet,
13793
13879
  catalogTableCommentSet,
13794
13880
  catalogTableRename,
@@ -14283,6 +14369,24 @@ function cacheControlMetadata(cc, extra) {
14283
14369
  md.set(CACHE_PER_VALUE_KEY, "1");
14284
14370
  return md;
14285
14371
  }
14372
+ // src/write-results.ts
14373
+ var WRITE_OPERATIONS = ["insert", "update", "delete"];
14374
+ var MODE_RANK = { count: 0, rows: 1, changes: 2 };
14375
+ function validateWriteResultModes(modes) {
14376
+ const out = {};
14377
+ const unknown = Object.keys(modes).filter((op) => !WRITE_OPERATIONS.includes(op)).sort();
14378
+ if (unknown.length)
14379
+ throw new Error(`Unknown write operation(s): ${unknown.join(", ")}`);
14380
+ for (const [operation, mode] of Object.entries(modes)) {
14381
+ if (mode === undefined)
14382
+ continue;
14383
+ if (!(mode in MODE_RANK))
14384
+ throw new Error(`Unknown write result mode '${mode}' for '${operation}'`);
14385
+ out[operation] = mode;
14386
+ }
14387
+ return out;
14388
+ }
14389
+
14286
14390
  // src/functions/scalar.ts
14287
14391
  init_arrow();
14288
14392
  function defineScalarFunction(config) {
@@ -14367,7 +14471,7 @@ function defineScalarFunction(config) {
14367
14471
  parameterDefaultValues: config.parameterDefaultValues,
14368
14472
  maxWorkers: config.maxWorkers,
14369
14473
  requiredSettings: config.requiredSettings,
14370
- requiredSecrets: config.requiredSecrets
14474
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name)
14371
14475
  };
14372
14476
  const defaultOutputSchema = config.returns ? schema2([field2("result", config.returns, true)]) : schema2([field2("result", nullType2(), true, new Map([["vgi:any", "true"]]))]);
14373
14477
  return {
@@ -14555,7 +14659,7 @@ function defineTableFunction(config) {
14555
14659
  parameterDefaultValues: config.parameterDefaultValues,
14556
14660
  maxWorkers: config.maxWorkers,
14557
14661
  requiredSettings: config.requiredSettings,
14558
- requiredSecrets: config.requiredSecrets,
14662
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
14559
14663
  preservesOrder: config.preservesOrder,
14560
14664
  nullHandling: config.nullHandling,
14561
14665
  orderDependent: config.orderDependent,
@@ -14832,7 +14936,7 @@ function defineTableInOutFunction(config) {
14832
14936
  parameterDefaultValues: config.parameterDefaultValues,
14833
14937
  maxWorkers: config.maxWorkers,
14834
14938
  requiredSettings: config.requiredSettings,
14835
- requiredSecrets: config.requiredSecrets,
14939
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
14836
14940
  hasFinalize: !!config.finalize
14837
14941
  };
14838
14942
  function extractArgs(request) {
@@ -15142,7 +15246,7 @@ function defineRowTransformFunction(config) {
15142
15246
  parameterDefaultValues: config.parameterDefaultValues,
15143
15247
  maxWorkers: config.maxWorkers,
15144
15248
  requiredSettings: config.requiredSettings,
15145
- requiredSecrets: config.requiredSecrets,
15249
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
15146
15250
  hasFinalize: false,
15147
15251
  inputFromArgs: true,
15148
15252
  inputRowsPerCall
@@ -15379,7 +15483,7 @@ function resolveMetadata(func) {
15379
15483
  nullHandling: meta.nullHandling ?? "DEFAULT" /* DEFAULT */,
15380
15484
  argumentMonotonicity,
15381
15485
  requiredSettings: meta.requiredSettings ?? [],
15382
- requiredSecrets: meta.requiredSecrets ?? [],
15486
+ requiredSecrets: normalizeRequiredSecrets(meta.requiredSecrets, meta.name),
15383
15487
  projectionPushdown: meta.projectionPushdown ?? false,
15384
15488
  filterPushdown: meta.filterPushdown ?? false,
15385
15489
  samplingPushdown: meta.samplingPushdown ?? false,
@@ -15483,6 +15587,9 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
15483
15587
  this._registry = registry;
15484
15588
  if (options.perAttachItemIds)
15485
15589
  this.perAttachItemIds = true;
15590
+ for (const sch of descriptor.schemas ?? [])
15591
+ for (const tbl of sch.tables ?? [])
15592
+ validateWritableTable(tbl);
15486
15593
  for (const sch of descriptor.schemas ?? []) {
15487
15594
  for (const fn of sch.functions ?? [])
15488
15595
  registry.registerInSchema(fn, schemaDescriptorPath(sch), descriptor.name);
@@ -15531,8 +15638,9 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
15531
15638
  const settings = (this._descriptor.settings ?? []).map((s) => serializeSetting(s));
15532
15639
  const secretTypes = (this._descriptor.secretTypes ?? []).map((s) => serializeSecretType(s));
15533
15640
  const attachCatalogs = (this._descriptor.attachCatalogs ?? []).map((c) => encodeAttachCatalogInfo(c));
15534
- const available = this.catalogReadProfiles();
15535
- const read = selectReadProfiles(available, clientCapabilities);
15641
+ const available = catalogCapabilities({ read: this.catalogReadProfiles(), write: this.catalogWriteProfiles() });
15642
+ const advertised = available.read.length + available.write.length > 0;
15643
+ const selected = selectCatalogCapabilities(available, clientCapabilities);
15536
15644
  const hasTimeTravel = this._descriptor.schemas.some((s) => s.tables?.some((t) => t.supportsTimeTravel) ?? false);
15537
15645
  return buildCatalogAttachResult({
15538
15646
  attach_opaque_data: attachOpaqueData,
@@ -15553,17 +15661,21 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
15553
15661
  resolved_data_version: null,
15554
15662
  resolved_implementation_version: null,
15555
15663
  supports_catalog_contents: this.supportsCatalogContents,
15556
- catalog_capabilities: available.length ? encodeCatalogCapabilities({ read: [...available].sort(), ddl: [], write: [], transaction: [] }) : null,
15557
- selected_capabilities: available.length ? encodeCatalogCapabilities({ read, ddl: [], write: [], transaction: [] }) : null
15664
+ catalog_capabilities: advertised ? encodeCatalogCapabilities(available) : null,
15665
+ selected_capabilities: advertised ? encodeCatalogCapabilities(selected) : null
15558
15666
  });
15559
15667
  }
15560
15668
  catalogReadProfiles() {
15561
15669
  const hasConstraints = this._descriptor.schemas.some((s) => s.tables?.some((t) => (t.constraints?.length ?? 0) > 0) ?? false);
15562
15670
  return hasConstraints ? [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION] : [];
15563
15671
  }
15672
+ catalogWriteProfiles() {
15673
+ const writableConstrained = this._descriptor.schemas.some((s) => s.tables?.some((t) => (t.constraints?.length ?? 0) > 0 && (t.insertFunction || t.updateFunction || t.deleteFunction)) ?? false);
15674
+ return writableConstrained ? [CONSTRAINT_ENFORCE] : [];
15675
+ }
15564
15676
  catalogCapabilities(_attachOpaqueData) {
15565
- const read = this.catalogReadProfiles();
15566
- return read.length ? catalogCapabilities({ read }) : null;
15677
+ const caps = catalogCapabilities({ read: this.catalogReadProfiles(), write: this.catalogWriteProfiles() });
15678
+ return caps.read.length + caps.write.length ? caps : null;
15567
15679
  }
15568
15680
  detach(attachOpaqueData) {
15569
15681
  for (const [name, id] of this._attachments) {
@@ -15714,12 +15826,12 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
15714
15826
  columns,
15715
15827
  constraints: [...constraints],
15716
15828
  definition_revision: t.definitionRevision ?? null,
15717
- write_result_modes: {},
15829
+ write_result_modes: writeResultModesFor(t),
15718
15830
  supports_column_statistics: t.statistics != null && Object.keys(t.statistics).length > 0,
15719
15831
  scan_function: t.function && !t.columns ? inlineScanFunction(t.function, t.arguments, this._schemaForFunction(t.function)) : null,
15720
- insert_function: null,
15721
- update_function: null,
15722
- delete_function: null,
15832
+ insert_function: t.insertFunction ? inlineScanFunction(t.insertFunction, undefined, this._schemaForFunction(t.insertFunction)) : null,
15833
+ update_function: t.updateFunction ? inlineScanFunction(t.updateFunction, undefined, this._schemaForFunction(t.updateFunction)) : null,
15834
+ delete_function: t.deleteFunction ? inlineScanFunction(t.deleteFunction, undefined, this._schemaForFunction(t.deleteFunction)) : null,
15723
15835
  cardinality_estimate: t.inlinedCardinality ? Number(t.inlinedCardinality.estimate) : null,
15724
15836
  cardinality_max: t.inlinedCardinality ? Number(t.inlinedCardinality.max) : null,
15725
15837
  required_filters: requiredFilters
@@ -15817,7 +15929,11 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
15817
15929
  }
15818
15930
  }
15819
15931
  const outputSchemaBytes = serializeSchema(f.defaultOutputSchema ?? schema2([]));
15820
- const requiredSecrets = (meta.requiredSecrets ?? []).map((secretType) => ({ secret_type: secretType, scope: null, secret_name: null }));
15932
+ const requiredSecrets = meta.requiredSecrets.map((s) => ({
15933
+ secret_type: s.secretType,
15934
+ scope: s.scope,
15935
+ secret_name: s.secretName
15936
+ }));
15821
15937
  const derivedTags = {};
15822
15938
  const tags = { ...derivedTags, ...meta.tags ?? {} };
15823
15939
  return {
@@ -15977,6 +16093,32 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
15977
16093
  }
15978
16094
  throw new Error(`Table '${name}' is not function-backed`);
15979
16095
  }
16096
+ _writeFunctionGet(schemaPath, name, operation) {
16097
+ const schema = this._descriptor.schemas.find((sch) => schemaPathsEqual(schemaDescriptorPath(sch), schemaPath));
16098
+ const table = schema?.tables?.find((t) => t.name.toLowerCase() === name.toLowerCase());
16099
+ if (!table) {
16100
+ throw new VgiError(`Table '${name}' not found in schema ${schemaPathDisplay(schemaPath)}`, "NOT_FOUND");
16101
+ }
16102
+ const fn = writeFunctionOf(table, operation);
16103
+ if (!fn) {
16104
+ throw new CatalogReadOnlyError(`Table ${schemaPathDisplay(schemaPath)}.${table.name} does not support ${operation.toUpperCase()}`);
16105
+ }
16106
+ return {
16107
+ function_name: fn.meta.name,
16108
+ arguments: serializeArgsBatch(new Arguments, argumentSpecsToSchema(fn.argumentSpecs)),
16109
+ required_extensions: [],
16110
+ schema_path: this._schemaForFunction(fn)
16111
+ };
16112
+ }
16113
+ tableInsertFunctionGet(_attachOpaqueData, schemaPath, name, _transactionOpaqueData, _writableBranchFunctionName) {
16114
+ return this._writeFunctionGet(schemaPath, name, "insert");
16115
+ }
16116
+ tableUpdateFunctionGet(_attachOpaqueData, schemaPath, name, _transactionOpaqueData) {
16117
+ return this._writeFunctionGet(schemaPath, name, "update");
16118
+ }
16119
+ tableDeleteFunctionGet(_attachOpaqueData, schemaPath, name, _transactionOpaqueData) {
16120
+ return this._writeFunctionGet(schemaPath, name, "delete");
16121
+ }
15980
16122
  async tableGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData) {
15981
16123
  validateAtParams(atUnit, atValue);
15982
16124
  const schema = this._descriptor.schemas.find((s) => schemaPathsEqual(schemaDescriptorPath(s), schemaPath));
@@ -16222,6 +16364,28 @@ function sameSpelling(left, right) {
16222
16364
  const b = normalizeSchemaPath(right);
16223
16365
  return a.length === b.length && a.every((part, i) => part === b[i]);
16224
16366
  }
16367
+ function writeFunctionOf(table, operation) {
16368
+ return operation === "insert" ? table.insertFunction : operation === "update" ? table.updateFunction : table.deleteFunction;
16369
+ }
16370
+ function validateWritableTable(table) {
16371
+ const modes = validateWriteResultModes(table.writeResultModes ?? {});
16372
+ for (const operation of Object.keys(modes)) {
16373
+ if (!writeFunctionOf(table, operation)) {
16374
+ throw new Error(`Table '${table.name}': writeResultModes declares '${operation}' without a corresponding ${operation}Function`);
16375
+ }
16376
+ }
16377
+ if ((table.updateFunction || table.deleteFunction) && !table.function) {
16378
+ throw new Error(`Table '${table.name}': updateFunction and deleteFunction require a scan function (set 'function') to provide row ids`);
16379
+ }
16380
+ }
16381
+ function writeResultModesFor(table) {
16382
+ const out = {};
16383
+ for (const operation of WRITE_OPERATIONS) {
16384
+ if (writeFunctionOf(table, operation))
16385
+ out[operation] = table.writeResultModes?.[operation] ?? "count";
16386
+ }
16387
+ return out;
16388
+ }
16225
16389
  // src/catalog/indexes.ts
16226
16390
  var NO_OPTIONS_B64 = "/////zgAAAAQAAAAAAAKABAADgAHAAgACgAAAAAAAAEQAAAAAAAEAAgACAAAAAQACAAAAAQAAAAAAAAAAAAAAP////9QAAAAFAAAAAAAAAAAAAoADgAMAAcACAAKAAAAAAAAAxAAAAAEAAoAGAAMAAgABAAKAAAAFAAAABgAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////AAAAAA==";
16227
16391
  function emptyIndexOptions() {
@@ -16726,6 +16890,80 @@ class FunctionRegistry {
16726
16890
  return result;
16727
16891
  }
16728
16892
  }
16893
+ // src/secrets/helpers.ts
16894
+ function scalarStr(v) {
16895
+ if (v === null || v === undefined)
16896
+ return "";
16897
+ return typeof v === "string" ? v : String(v);
16898
+ }
16899
+ function secretType(secrets, name) {
16900
+ const f = secrets?.[name];
16901
+ return f && "type" in f ? scalarStr(f.type) : undefined;
16902
+ }
16903
+ function untyped(fields) {
16904
+ return !!fields && scalarStr(fields.type) === "";
16905
+ }
16906
+ function keyedByType(secrets, type) {
16907
+ const f = secrets?.[type];
16908
+ return untyped(f) ? f : undefined;
16909
+ }
16910
+ function secretsOfType(secrets, type) {
16911
+ const typed = Object.values(secrets ?? {}).filter((f) => scalarStr(f.type) === type);
16912
+ if (typed.length > 0)
16913
+ return typed;
16914
+ const legacy = keyedByType(secrets, type);
16915
+ return legacy ? [legacy] : [];
16916
+ }
16917
+ function secretOfType(secrets, type) {
16918
+ const all = secretsOfType(secrets, type);
16919
+ return all.find((f) => scalarStr(f.scope) === "") ?? all[0];
16920
+ }
16921
+ function requireSecretOfType(secrets, type) {
16922
+ const found = secretOfType(secrets, type);
16923
+ if (!found) {
16924
+ throw new Error(`required secret of type '${type}' was not found; create one with CREATE SECRET (TYPE ${type}, ...)`);
16925
+ }
16926
+ return found;
16927
+ }
16928
+ function secretByName(secrets, name, type) {
16929
+ if (!secrets || !Object.prototype.hasOwnProperty.call(secrets, name))
16930
+ return;
16931
+ const f = secrets[name];
16932
+ if (!f)
16933
+ return;
16934
+ if (type === undefined || untyped(f) || scalarStr(f.type) === type)
16935
+ return f;
16936
+ return;
16937
+ }
16938
+ function secretForScope(secrets, path) {
16939
+ return selectForScope(secrets, path, undefined);
16940
+ }
16941
+ function secretForScopeOfType(secrets, path, type) {
16942
+ return selectForScope(secrets, path, type) ?? keyedByType(secrets, type);
16943
+ }
16944
+ function selectForScope(secrets, path, type) {
16945
+ let best;
16946
+ let bestLen = -1;
16947
+ let fallback;
16948
+ for (const fields of Object.values(secrets ?? {})) {
16949
+ if (type !== undefined && scalarStr(fields.type) !== type)
16950
+ continue;
16951
+ const scope = scalarStr(fields.scope);
16952
+ if (!scope) {
16953
+ if (!fallback)
16954
+ fallback = fields;
16955
+ continue;
16956
+ }
16957
+ for (const prefix of scope.split(`
16958
+ `)) {
16959
+ if (prefix && path.startsWith(prefix) && prefix.length > bestLen) {
16960
+ bestLen = prefix.length;
16961
+ best = fields;
16962
+ }
16963
+ }
16964
+ }
16965
+ return best ?? fallback;
16966
+ }
16729
16967
  // src/index.core.ts
16730
16968
  import { str, bytes, int as int3, int32 as int323, float, float32 as float323, bool as bool3, toSchema, OutputCollector, AuthContext as AuthContext2 } from "@query-farm/vgi-rpc";
16731
16969
  import { subprocessConnect, httpConnect, tcpConnect } from "@query-farm/vgi-rpc";
@@ -16875,13 +17113,21 @@ export {
16875
17113
  list2 as list,
16876
17114
  map2 as map,
16877
17115
  moreOutputMetadata,
17116
+ normalizeRequiredSecrets,
16878
17117
  nullType2 as nullType,
16879
17118
  parentRowsMetadata,
16880
17119
  projectBatch,
16881
17120
  projectSchema,
16882
17121
  readConstraintRecord,
17122
+ requireSecretOfType,
16883
17123
  safeNumber,
16884
17124
  schema2 as schema,
17125
+ secretByName,
17126
+ secretForScope,
17127
+ secretForScopeOfType,
17128
+ secretOfType,
17129
+ secretType,
17130
+ secretsOfType,
16885
17131
  selectCatalogCapabilities,
16886
17132
  selectReadProfiles,
16887
17133
  serializeAttachOptionSpec,
@@ -16914,4 +17160,4 @@ export {
16914
17160
  validateTableConstraints
16915
17161
  };
16916
17162
 
16917
- //# debugId=F8503787BE8D309164756E2164756E21
17163
+ //# debugId=FAC9CCEE4111237264756E2164756E21