@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
package/dist/index.js CHANGED
@@ -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;
@@ -2623,6 +2607,162 @@ function cacheControlMetadata(cc, extra) {
2623
2607
  md.set(CACHE_PER_VALUE_KEY, "1");
2624
2608
  return md;
2625
2609
  }
2610
+ // src/write-results.ts
2611
+ init_arrow();
2612
+
2613
+ // src/util/bytes.ts
2614
+ function toUint8Array(val) {
2615
+ if (val instanceof Uint8Array)
2616
+ return val;
2617
+ if (val instanceof ArrayBuffer)
2618
+ return new Uint8Array(val);
2619
+ if (typeof Buffer !== "undefined" && Buffer.isBuffer(val))
2620
+ return new Uint8Array(val);
2621
+ if (val && val.buffer instanceof ArrayBuffer) {
2622
+ return new Uint8Array(val.buffer, val.byteOffset, val.byteLength);
2623
+ }
2624
+ return new Uint8Array(0);
2625
+ }
2626
+
2627
+ // src/write-results.ts
2628
+ var WRITE_OPERATIONS = ["insert", "update", "delete"];
2629
+ var WRITE_RESULT_MODES = ["count", "rows", "changes"];
2630
+ var MODE_RANK = { count: 0, rows: 1, changes: 2 };
2631
+ var ROW_ID_METADATA_KEY = "is_row_id";
2632
+ function rowIdField(name = "rowid", type = int642()) {
2633
+ return field2(name, type, false, new Map([[ROW_ID_METADATA_KEY, ""]]));
2634
+ }
2635
+ function validateWriteResultModes(modes) {
2636
+ const out = {};
2637
+ const unknown = Object.keys(modes).filter((op) => !WRITE_OPERATIONS.includes(op)).sort();
2638
+ if (unknown.length)
2639
+ throw new Error(`Unknown write operation(s): ${unknown.join(", ")}`);
2640
+ for (const [operation, mode] of Object.entries(modes)) {
2641
+ if (mode === undefined)
2642
+ continue;
2643
+ if (!(mode in MODE_RANK))
2644
+ throw new Error(`Unknown write result mode '${mode}' for '${operation}'`);
2645
+ out[operation] = mode;
2646
+ }
2647
+ return out;
2648
+ }
2649
+ function supportsWriteResultMode(maximum, requested) {
2650
+ return maximum in MODE_RANK && requested in MODE_RANK && MODE_RANK[maximum] >= MODE_RANK[requested];
2651
+ }
2652
+ function coerceWriteResultMode(value) {
2653
+ if (typeof value !== "string" || !(value in MODE_RANK)) {
2654
+ throw new Error(`Unknown write result mode: ${JSON.stringify(value)}`);
2655
+ }
2656
+ return value;
2657
+ }
2658
+ function userColumns(columns) {
2659
+ return schema2(columns.fields.filter((f) => !f.metadata?.has(ROW_ID_METADATA_KEY)));
2660
+ }
2661
+ function writeResultSchema(mode, tableSchema) {
2662
+ if (mode === "count")
2663
+ return schema2([field2("count", int642(), false)]);
2664
+ if (mode === "rows")
2665
+ return tableSchema;
2666
+ const rowType = struct2(tableSchema.fields);
2667
+ return schema2([field2("old", rowType, true), field2("new", rowType, true)]);
2668
+ }
2669
+ function writeCountBatch(count) {
2670
+ return batchFromColumns({ count: [BigInt(count)] }, writeResultSchema("count", schema2([])));
2671
+ }
2672
+ function writeRowsBatch(tableSchema, rows) {
2673
+ const columns = {};
2674
+ for (const f of tableSchema.fields)
2675
+ columns[f.name] = rows.map((r) => r[f.name] ?? null);
2676
+ return batchFromColumns(columns, tableSchema);
2677
+ }
2678
+ function writeChangesBatch(tableSchema, oldRows, newRows) {
2679
+ if (oldRows.length !== newRows.length)
2680
+ throw new Error("oldRows and newRows must have equal length");
2681
+ const pick = (row) => row == null ? null : Object.fromEntries(tableSchema.fields.map((f) => [f.name, row[f.name] ?? null]));
2682
+ return batchFromColumns({ old: oldRows.map(pick), new: newRows.map(pick) }, writeResultSchema("changes", tableSchema));
2683
+ }
2684
+ function writeResultBatch(mode, tableSchema, oldRows, newRows) {
2685
+ if (mode === "count")
2686
+ return writeCountBatch(newRows.length);
2687
+ if (mode === "changes")
2688
+ return writeChangesBatch(tableSchema, oldRows, newRows);
2689
+ return writeRowsBatch(tableSchema, newRows.map((row, i) => row ?? oldRows[i]));
2690
+ }
2691
+ function writeOptions(bindCall) {
2692
+ const out = { resultMode: "count", onConflict: "throw", onConflictColumns: [] };
2693
+ const raw = bindCall.arguments?.get("write_options", null);
2694
+ if (raw == null)
2695
+ return out;
2696
+ const row = [...iterRows(deserializeBatch(toUint8Array(raw)))][0];
2697
+ if (!row)
2698
+ return out;
2699
+ if (row.result_mode != null)
2700
+ out.resultMode = coerceWriteResultMode(row.result_mode);
2701
+ if (row.on_conflict != null)
2702
+ out.onConflict = String(row.on_conflict);
2703
+ if (row.on_conflict_columns != null)
2704
+ out.onConflictColumns = Array.from(row.on_conflict_columns);
2705
+ return out;
2706
+ }
2707
+ // src/secrets/requirements.ts
2708
+ var KNOWN_KEYS = new Set(["secretType", "secret_type", "scope", "secretName", "secret_name"]);
2709
+ function optionalString(value, what, where) {
2710
+ if (value === undefined || value === null)
2711
+ return null;
2712
+ if (typeof value !== "string") {
2713
+ throw new TypeError(`${where}: ${what} must be a string, got ${typeof value}`);
2714
+ }
2715
+ return value === "" ? null : value;
2716
+ }
2717
+ function normalizeRequiredSecrets(value, functionName = "<function>") {
2718
+ if (value === undefined || value === null)
2719
+ return [];
2720
+ const where = `requiredSecrets of '${functionName}'`;
2721
+ if (!Array.isArray(value)) {
2722
+ throw new TypeError(`${where} must be an array of secret types or { secretType, scope?, secretName? } objects, got ${typeof value}`);
2723
+ }
2724
+ const out = [];
2725
+ const seen = new Set;
2726
+ value.forEach((entry, i) => {
2727
+ const at = `${where}[${i}]`;
2728
+ let req;
2729
+ if (typeof entry === "string") {
2730
+ if (entry === "")
2731
+ throw new TypeError(`${at}: secret type must not be empty`);
2732
+ req = { secretType: entry, scope: null, secretName: null };
2733
+ } else if (entry !== null && typeof entry === "object" && !Array.isArray(entry)) {
2734
+ const obj = entry;
2735
+ const unknown = Object.keys(obj).filter((k) => !KNOWN_KEYS.has(k));
2736
+ if (unknown.length > 0) {
2737
+ throw new TypeError(`${at}: unknown key(s) ${unknown.map((k) => `'${k}'`).join(", ")}; ` + `expected secretType, scope, secretName`);
2738
+ }
2739
+ if (obj.secretType !== undefined && obj.secret_type !== undefined && obj.secretType !== obj.secret_type) {
2740
+ throw new TypeError(`${at}: secretType and secret_type disagree`);
2741
+ }
2742
+ if (obj.secretName !== undefined && obj.secret_name !== undefined && obj.secretName !== obj.secret_name) {
2743
+ throw new TypeError(`${at}: secretName and secret_name disagree`);
2744
+ }
2745
+ const secretType = obj.secretType ?? obj.secret_type;
2746
+ if (typeof secretType !== "string" || secretType === "") {
2747
+ throw new TypeError(`${at}: secretType must be a non-empty string`);
2748
+ }
2749
+ req = {
2750
+ secretType,
2751
+ scope: optionalString(obj.scope, "scope", at),
2752
+ secretName: optionalString(obj.secretName ?? obj.secret_name, "secretName", at)
2753
+ };
2754
+ } else {
2755
+ 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));
2756
+ }
2757
+ const key = JSON.stringify([req.secretType, req.scope, req.secretName]);
2758
+ if (seen.has(key))
2759
+ return;
2760
+ seen.add(key);
2761
+ out.push(req);
2762
+ });
2763
+ return out;
2764
+ }
2765
+
2626
2766
  // src/functions/scalar.ts
2627
2767
  init_arrow();
2628
2768
 
@@ -3084,7 +3224,7 @@ function defineScalarFunction(config) {
3084
3224
  parameterDefaultValues: config.parameterDefaultValues,
3085
3225
  maxWorkers: config.maxWorkers,
3086
3226
  requiredSettings: config.requiredSettings,
3087
- requiredSecrets: config.requiredSecrets
3227
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name)
3088
3228
  };
3089
3229
  const defaultOutputSchema = config.returns ? schema2([field2("result", config.returns, true)]) : schema2([field2("result", nullType2(), true, new Map([["vgi:any", "true"]]))]);
3090
3230
  return {
@@ -4886,7 +5026,7 @@ function defineTableFunction(config) {
4886
5026
  parameterDefaultValues: config.parameterDefaultValues,
4887
5027
  maxWorkers: config.maxWorkers,
4888
5028
  requiredSettings: config.requiredSettings,
4889
- requiredSecrets: config.requiredSecrets,
5029
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
4890
5030
  preservesOrder: config.preservesOrder,
4891
5031
  nullHandling: config.nullHandling,
4892
5032
  orderDependent: config.orderDependent,
@@ -5257,7 +5397,7 @@ function defineAggregate(config) {
5257
5397
  tags: config.tags,
5258
5398
  parameterDefaultValues: config.parameterDefaultValues,
5259
5399
  nullHandling: config.nullHandling,
5260
- requiredSecrets: config.requiredSecrets
5400
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name)
5261
5401
  };
5262
5402
  const isAnyType = isNull(config.outputType);
5263
5403
  const defaultOutputSchema = isAnyType ? schema2([field2("result", nullType2(), true, new Map([["vgi:any", "true"]]))]) : schema2([field2("result", config.outputType, true)]);
@@ -5286,20 +5426,6 @@ init_storage();
5286
5426
  init_arrow();
5287
5427
  init_registry();
5288
5428
 
5289
- // src/util/bytes.ts
5290
- function toUint8Array(val) {
5291
- if (val instanceof Uint8Array)
5292
- return val;
5293
- if (val instanceof ArrayBuffer)
5294
- return new Uint8Array(val);
5295
- if (typeof Buffer !== "undefined" && Buffer.isBuffer(val))
5296
- return new Uint8Array(val);
5297
- if (val && val.buffer instanceof ArrayBuffer) {
5298
- return new Uint8Array(val.buffer, val.byteOffset, val.byteLength);
5299
- }
5300
- return new Uint8Array(0);
5301
- }
5302
-
5303
5429
  // src/protocol/carried-init-request.ts
5304
5430
  init_arrow();
5305
5431
 
@@ -6436,7 +6562,7 @@ function defineTableInOutFunction(config) {
6436
6562
  parameterDefaultValues: config.parameterDefaultValues,
6437
6563
  maxWorkers: config.maxWorkers,
6438
6564
  requiredSettings: config.requiredSettings,
6439
- requiredSecrets: config.requiredSecrets,
6565
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
6440
6566
  hasFinalize: !!config.finalize
6441
6567
  };
6442
6568
  function extractArgs(request) {
@@ -6746,7 +6872,7 @@ function defineRowTransformFunction(config) {
6746
6872
  parameterDefaultValues: config.parameterDefaultValues,
6747
6873
  maxWorkers: config.maxWorkers,
6748
6874
  requiredSettings: config.requiredSettings,
6749
- requiredSecrets: config.requiredSecrets,
6875
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
6750
6876
  hasFinalize: false,
6751
6877
  inputFromArgs: true,
6752
6878
  inputRowsPerCall
@@ -6922,7 +7048,7 @@ function defineTableBufferingFunction(config) {
6922
7048
  parameterDefaultValues: config.parameterDefaultValues,
6923
7049
  maxWorkers: config.maxWorkers,
6924
7050
  requiredSettings: config.requiredSettings,
6925
- requiredSecrets: config.requiredSecrets,
7051
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
6926
7052
  hasFinalize: true,
6927
7053
  sinkOrderDependent: config.sinkOrderDependent,
6928
7054
  sourceOrderDependent: config.sourceOrderDependent,
@@ -7194,7 +7320,7 @@ function defineCopyFromFunction(config) {
7194
7320
  tags: config.tags,
7195
7321
  examples: config.examples,
7196
7322
  requiredSettings: config.requiredSettings,
7197
- requiredSecrets: config.requiredSecrets,
7323
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
7198
7324
  copyFromFormat: config.format,
7199
7325
  copyFromDirection: config.direction ?? "from",
7200
7326
  copyFromComment: config.comment ?? null
@@ -10622,6 +10748,15 @@ class CatalogInterface {
10622
10748
  tableScanFunctionGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData) {
10623
10749
  throw new CatalogReadOnlyError("table_scan_function_get");
10624
10750
  }
10751
+ tableInsertFunctionGet(attachOpaqueData, schemaPath, name, transactionOpaqueData, writableBranchFunctionName) {
10752
+ throw new CatalogReadOnlyError("table_insert_function_get");
10753
+ }
10754
+ tableUpdateFunctionGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
10755
+ throw new CatalogReadOnlyError("table_update_function_get");
10756
+ }
10757
+ tableDeleteFunctionGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
10758
+ throw new CatalogReadOnlyError("table_delete_function_get");
10759
+ }
10625
10760
  tableScanBranchesGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData) {
10626
10761
  const legacy = this.tableScanFunctionGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData);
10627
10762
  return isPromise(legacy) ? legacy.then((r) => singleBranchResult(r)) : singleBranchResult(legacy);
@@ -11051,7 +11186,7 @@ function resolveMetadata(func) {
11051
11186
  nullHandling: meta.nullHandling ?? "DEFAULT" /* DEFAULT */,
11052
11187
  argumentMonotonicity,
11053
11188
  requiredSettings: meta.requiredSettings ?? [],
11054
- requiredSecrets: meta.requiredSecrets ?? [],
11189
+ requiredSecrets: normalizeRequiredSecrets(meta.requiredSecrets, meta.name),
11055
11190
  projectionPushdown: meta.projectionPushdown ?? false,
11056
11191
  filterPushdown: meta.filterPushdown ?? false,
11057
11192
  samplingPushdown: meta.samplingPushdown ?? false,
@@ -11308,6 +11443,9 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
11308
11443
  this._registry = registry;
11309
11444
  if (options.perAttachItemIds)
11310
11445
  this.perAttachItemIds = true;
11446
+ for (const sch of descriptor.schemas ?? [])
11447
+ for (const tbl of sch.tables ?? [])
11448
+ validateWritableTable(tbl);
11311
11449
  for (const sch of descriptor.schemas ?? []) {
11312
11450
  for (const fn of sch.functions ?? [])
11313
11451
  registry.registerInSchema(fn, schemaDescriptorPath(sch), descriptor.name);
@@ -11356,8 +11494,9 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
11356
11494
  const settings = (this._descriptor.settings ?? []).map((s) => serializeSetting(s));
11357
11495
  const secretTypes = (this._descriptor.secretTypes ?? []).map((s) => serializeSecretType(s));
11358
11496
  const attachCatalogs = (this._descriptor.attachCatalogs ?? []).map((c) => encodeAttachCatalogInfo(c));
11359
- const available = this.catalogReadProfiles();
11360
- const read = selectReadProfiles(available, clientCapabilities);
11497
+ const available = catalogCapabilities({ read: this.catalogReadProfiles(), write: this.catalogWriteProfiles() });
11498
+ const advertised = available.read.length + available.write.length > 0;
11499
+ const selected = selectCatalogCapabilities(available, clientCapabilities);
11361
11500
  const hasTimeTravel = this._descriptor.schemas.some((s) => s.tables?.some((t) => t.supportsTimeTravel) ?? false);
11362
11501
  return buildCatalogAttachResult({
11363
11502
  attach_opaque_data: attachOpaqueData,
@@ -11378,17 +11517,21 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
11378
11517
  resolved_data_version: null,
11379
11518
  resolved_implementation_version: null,
11380
11519
  supports_catalog_contents: this.supportsCatalogContents,
11381
- catalog_capabilities: available.length ? encodeCatalogCapabilities({ read: [...available].sort(), ddl: [], write: [], transaction: [] }) : null,
11382
- selected_capabilities: available.length ? encodeCatalogCapabilities({ read, ddl: [], write: [], transaction: [] }) : null
11520
+ catalog_capabilities: advertised ? encodeCatalogCapabilities(available) : null,
11521
+ selected_capabilities: advertised ? encodeCatalogCapabilities(selected) : null
11383
11522
  });
11384
11523
  }
11385
11524
  catalogReadProfiles() {
11386
11525
  const hasConstraints = this._descriptor.schemas.some((s) => s.tables?.some((t) => (t.constraints?.length ?? 0) > 0) ?? false);
11387
11526
  return hasConstraints ? [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION] : [];
11388
11527
  }
11528
+ catalogWriteProfiles() {
11529
+ const writableConstrained = this._descriptor.schemas.some((s) => s.tables?.some((t) => (t.constraints?.length ?? 0) > 0 && (t.insertFunction || t.updateFunction || t.deleteFunction)) ?? false);
11530
+ return writableConstrained ? [CONSTRAINT_ENFORCE] : [];
11531
+ }
11389
11532
  catalogCapabilities(_attachOpaqueData) {
11390
- const read = this.catalogReadProfiles();
11391
- return read.length ? catalogCapabilities({ read }) : null;
11533
+ const caps = catalogCapabilities({ read: this.catalogReadProfiles(), write: this.catalogWriteProfiles() });
11534
+ return caps.read.length + caps.write.length ? caps : null;
11392
11535
  }
11393
11536
  detach(attachOpaqueData) {
11394
11537
  for (const [name, id] of this._attachments) {
@@ -11539,12 +11682,12 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
11539
11682
  columns,
11540
11683
  constraints: [...constraints],
11541
11684
  definition_revision: t.definitionRevision ?? null,
11542
- write_result_modes: {},
11685
+ write_result_modes: writeResultModesFor(t),
11543
11686
  supports_column_statistics: t.statistics != null && Object.keys(t.statistics).length > 0,
11544
11687
  scan_function: t.function && !t.columns ? inlineScanFunction(t.function, t.arguments, this._schemaForFunction(t.function)) : null,
11545
- insert_function: null,
11546
- update_function: null,
11547
- delete_function: null,
11688
+ insert_function: t.insertFunction ? inlineScanFunction(t.insertFunction, undefined, this._schemaForFunction(t.insertFunction)) : null,
11689
+ update_function: t.updateFunction ? inlineScanFunction(t.updateFunction, undefined, this._schemaForFunction(t.updateFunction)) : null,
11690
+ delete_function: t.deleteFunction ? inlineScanFunction(t.deleteFunction, undefined, this._schemaForFunction(t.deleteFunction)) : null,
11548
11691
  cardinality_estimate: t.inlinedCardinality ? Number(t.inlinedCardinality.estimate) : null,
11549
11692
  cardinality_max: t.inlinedCardinality ? Number(t.inlinedCardinality.max) : null,
11550
11693
  required_filters: requiredFilters
@@ -11642,7 +11785,11 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
11642
11785
  }
11643
11786
  }
11644
11787
  const outputSchemaBytes = serializeSchema(f.defaultOutputSchema ?? schema2([]));
11645
- const requiredSecrets = (meta.requiredSecrets ?? []).map((secretType) => ({ secret_type: secretType, scope: null, secret_name: null }));
11788
+ const requiredSecrets = meta.requiredSecrets.map((s) => ({
11789
+ secret_type: s.secretType,
11790
+ scope: s.scope,
11791
+ secret_name: s.secretName
11792
+ }));
11646
11793
  const derivedTags = {};
11647
11794
  const tags = { ...derivedTags, ...meta.tags ?? {} };
11648
11795
  return {
@@ -11802,6 +11949,32 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
11802
11949
  }
11803
11950
  throw new Error(`Table '${name}' is not function-backed`);
11804
11951
  }
11952
+ _writeFunctionGet(schemaPath, name, operation) {
11953
+ const schema = this._descriptor.schemas.find((sch) => schemaPathsEqual(schemaDescriptorPath(sch), schemaPath));
11954
+ const table = schema?.tables?.find((t) => t.name.toLowerCase() === name.toLowerCase());
11955
+ if (!table) {
11956
+ throw new VgiError(`Table '${name}' not found in schema ${schemaPathDisplay(schemaPath)}`, "NOT_FOUND");
11957
+ }
11958
+ const fn = writeFunctionOf(table, operation);
11959
+ if (!fn) {
11960
+ throw new CatalogReadOnlyError(`Table ${schemaPathDisplay(schemaPath)}.${table.name} does not support ${operation.toUpperCase()}`);
11961
+ }
11962
+ return {
11963
+ function_name: fn.meta.name,
11964
+ arguments: serializeArgsBatch(new Arguments, argumentSpecsToSchema(fn.argumentSpecs)),
11965
+ required_extensions: [],
11966
+ schema_path: this._schemaForFunction(fn)
11967
+ };
11968
+ }
11969
+ tableInsertFunctionGet(_attachOpaqueData, schemaPath, name, _transactionOpaqueData, _writableBranchFunctionName) {
11970
+ return this._writeFunctionGet(schemaPath, name, "insert");
11971
+ }
11972
+ tableUpdateFunctionGet(_attachOpaqueData, schemaPath, name, _transactionOpaqueData) {
11973
+ return this._writeFunctionGet(schemaPath, name, "update");
11974
+ }
11975
+ tableDeleteFunctionGet(_attachOpaqueData, schemaPath, name, _transactionOpaqueData) {
11976
+ return this._writeFunctionGet(schemaPath, name, "delete");
11977
+ }
11805
11978
  async tableGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData) {
11806
11979
  validateAtParams(atUnit, atValue);
11807
11980
  const schema = this._descriptor.schemas.find((s) => schemaPathsEqual(schemaDescriptorPath(s), schemaPath));
@@ -12047,6 +12220,28 @@ function sameSpelling(left, right) {
12047
12220
  const b = normalizeSchemaPath(right);
12048
12221
  return a.length === b.length && a.every((part, i) => part === b[i]);
12049
12222
  }
12223
+ function writeFunctionOf(table, operation) {
12224
+ return operation === "insert" ? table.insertFunction : operation === "update" ? table.updateFunction : table.deleteFunction;
12225
+ }
12226
+ function validateWritableTable(table) {
12227
+ const modes = validateWriteResultModes(table.writeResultModes ?? {});
12228
+ for (const operation of Object.keys(modes)) {
12229
+ if (!writeFunctionOf(table, operation)) {
12230
+ throw new Error(`Table '${table.name}': writeResultModes declares '${operation}' without a corresponding ${operation}Function`);
12231
+ }
12232
+ }
12233
+ if ((table.updateFunction || table.deleteFunction) && !table.function) {
12234
+ throw new Error(`Table '${table.name}': updateFunction and deleteFunction require a scan function (set 'function') to provide row ids`);
12235
+ }
12236
+ }
12237
+ function writeResultModesFor(table) {
12238
+ const out = {};
12239
+ for (const operation of WRITE_OPERATIONS) {
12240
+ if (writeFunctionOf(table, operation))
12241
+ out[operation] = table.writeResultModes?.[operation] ?? "count";
12242
+ }
12243
+ return out;
12244
+ }
12050
12245
  // src/catalog/indexes.ts
12051
12246
  var NO_OPTIONS_B64 = "/////zgAAAAQAAAAAAAKABAADgAHAAgACgAAAAAAAAEQAAAAAAAEAAgACAAAAAQACAAAAAQAAAAAAAAAAAAAAP////9QAAAAFAAAAAAAAAAAAAoADgAMAAcACAAKAAAAAAAAAxAAAAAEAAoAGAAMAAgABAAKAAAAFAAAABgAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////AAAAAA==";
12052
12247
  function emptyIndexOptions() {
@@ -13367,6 +13562,11 @@ var FILTER_CONTEXT_STRUCT = struct2([
13367
13562
  field2("profile", utf82(), false),
13368
13563
  field2("provider_fingerprint", utf82(), true)
13369
13564
  ]);
13565
+ var SECRET_REQUIREMENT_STRUCT = struct2([
13566
+ field2("secret_type", utf82(), false),
13567
+ field2("secret_name", utf82(), true),
13568
+ field2("scope", utf82(), true)
13569
+ ]);
13370
13570
  var METADATA_SCHEMA = schema2([
13371
13571
  field2("name", utf82(), false),
13372
13572
  field2("class_name", utf82(), false),
@@ -13380,7 +13580,7 @@ var METADATA_SCHEMA = schema2([
13380
13580
  field2("null_handling", utf82(), false),
13381
13581
  field2("argument_monotonicity", list2(field2("item", utf82(), true)), true),
13382
13582
  field2("required_settings", list2(field2("item", utf82(), true)), false),
13383
- field2("required_secrets", list2(field2("item", utf82(), true)), false),
13583
+ field2("required_secrets", list2(field2("item", SECRET_REQUIREMENT_STRUCT, true)), false),
13384
13584
  field2("projection_pushdown", bool2(), false),
13385
13585
  field2("filter_pushdown", bool2(), false),
13386
13586
  field2("filter_semantic_profiles", list2(field2("item", utf82(), true)), false),
@@ -13422,7 +13622,11 @@ function metadataToRow(m) {
13422
13622
  null_handling: m.nullHandling,
13423
13623
  argument_monotonicity: m.argumentMonotonicity,
13424
13624
  required_settings: m.requiredSettings,
13425
- required_secrets: m.requiredSecrets,
13625
+ required_secrets: m.requiredSecrets.map((s) => ({
13626
+ secret_type: s.secretType,
13627
+ secret_name: s.secretName,
13628
+ scope: s.scope
13629
+ })),
13426
13630
  projection_pushdown: m.projectionPushdown,
13427
13631
  filter_pushdown: m.filterPushdown,
13428
13632
  sampling_pushdown: m.samplingPushdown,
@@ -13515,7 +13719,7 @@ function arrowToMetadatas(batch) {
13515
13719
  const rawRequiredSettings = get("required_settings") ?? [];
13516
13720
  const requiredSettings = rawRequiredSettings ? [...rawRequiredSettings].filter((s) => s != null) : [];
13517
13721
  const rawRequiredSecrets = get("required_secrets") ?? [];
13518
- const requiredSecrets = rawRequiredSecrets ? [...rawRequiredSecrets].filter((s) => s != null) : [];
13722
+ const requiredSecrets = normalizeRequiredSecrets(rawRequiredSecrets ? [...rawRequiredSecrets].filter((s) => s != null).map((s) => typeof s === "string" ? s : { secretType: s.secret_type, secretName: s.secret_name ?? null, scope: s.scope ?? null }) : [], get("name") ?? "<function>");
13519
13723
  results.push({
13520
13724
  name: get("name") ?? "",
13521
13725
  className: get("class_name") ?? "",
@@ -15233,6 +15437,11 @@ async function sealTransaction(plaintext, attachEnvelope, auth, signingKey) {
15233
15437
  return plaintext;
15234
15438
  return sealBytes(plaintext, signingKey, transactionAad(auth, attachEnvelope), TRANSACTION_ENVELOPE_VERSION);
15235
15439
  }
15440
+ async function openTransaction(envelope, attachEnvelope, auth, signingKey) {
15441
+ if (!signingKey || envelope.length === 0)
15442
+ return envelope;
15443
+ return openBytes(envelope, signingKey, transactionAad(auth, attachEnvelope), TRANSACTION_ENVELOPE_VERSION, "transaction_opaque_data");
15444
+ }
15236
15445
  async function unwrapParamsOpaque(params, ctx, signingKey) {
15237
15446
  const auth = ctx?.auth;
15238
15447
  let sealedAttach = new Uint8Array(0);
@@ -15510,7 +15719,12 @@ async function liveSplitAnchor(catalogInterface, bindCall, auth, signingKey) {
15510
15719
  if (!catalogInterface?.version || bindCall.attach_opaque_data == null)
15511
15720
  return;
15512
15721
  const raw = toUint8Array(bindCall.attach_opaque_data);
15513
- const txn = bindCall.transaction_opaque_data ? toUint8Array(bindCall.transaction_opaque_data) : undefined;
15722
+ let txn = bindCall.transaction_opaque_data ? toUint8Array(bindCall.transaction_opaque_data) : undefined;
15723
+ if (txn && txn.length > 0 && signingKey) {
15724
+ try {
15725
+ txn = await openTransaction(txn, raw, auth, signingKey);
15726
+ } catch {}
15727
+ }
15514
15728
  const forms = [
15515
15729
  async () => raw,
15516
15730
  async () => openAttach(raw, auth, signingKey)
@@ -15548,14 +15762,22 @@ function functionHandlers(config) {
15548
15762
  return env;
15549
15763
  return openAttach(env, ctx?.auth ?? currentRequestAuth(), signingKey);
15550
15764
  }
15765
+ async function openOpaque(bindCall, ctx) {
15766
+ const sealedAttach = bindCall.attach_opaque_data != null ? toUint8Array(bindCall.attach_opaque_data) : new Uint8Array(0);
15767
+ if (bindCall.transaction_opaque_data != null) {
15768
+ bindCall.transaction_opaque_data = await openTransaction(toUint8Array(bindCall.transaction_opaque_data), sealedAttach, ctx?.auth ?? currentRequestAuth(), signingKey);
15769
+ }
15770
+ bindCall.attach_opaque_data = await stripAttach(bindCall.attach_opaque_data, ctx);
15771
+ }
15551
15772
  async function strippedContext(bindCall, ctx) {
15552
- let attach = null;
15773
+ const copy = { ...bindCall };
15553
15774
  try {
15554
- attach = await stripAttach(bindCall.attach_opaque_data, ctx);
15775
+ await openOpaque(copy, ctx);
15555
15776
  } catch {
15556
- attach = null;
15777
+ copy.attach_opaque_data = null;
15778
+ copy.transaction_opaque_data = null;
15557
15779
  }
15558
- return overloadContext({ ...bindCall, attach_opaque_data: attach }, catalogInterface);
15780
+ return overloadContext(copy, catalogInterface);
15559
15781
  }
15560
15782
  const emptySchema = schema2([]);
15561
15783
  const dummyInputSchema = schema2([
@@ -15564,7 +15786,7 @@ function functionHandlers(config) {
15564
15786
  const bind = async (params, ctx) => {
15565
15787
  const innerParams = unwrapRequest(params.request);
15566
15788
  const request = deserializeBindRequest(innerParams);
15567
- request.attach_opaque_data = await stripAttach(request.attach_opaque_data, ctx);
15789
+ await openOpaque(request, ctx);
15568
15790
  const func = registry.get(request.function_name, overloadContext(request, catalogInterface));
15569
15791
  const response = await func.bind(request);
15570
15792
  validateProjectionOffer(response);
@@ -15579,7 +15801,7 @@ function functionHandlers(config) {
15579
15801
  const innerParams = unwrapRequest(params.request);
15580
15802
  const request = deserializeInitRequest(innerParams);
15581
15803
  const auth = ctx?.auth ?? currentRequestAuth();
15582
- request.bind_call.attach_opaque_data = await stripAttach(request.bind_call.attach_opaque_data, ctx);
15804
+ await openOpaque(request.bind_call, ctx);
15583
15805
  await resolveSplitPayloads(request, innerParams, {
15584
15806
  auth,
15585
15807
  signingKey,
@@ -15624,7 +15846,7 @@ function functionHandlers(config) {
15624
15846
  } else {
15625
15847
  const carried = parseCarriedInitRequest(state.initRequestPacked);
15626
15848
  const request = carried.request;
15627
- request.bind_call.attach_opaque_data = await stripAttach(request.bind_call.attach_opaque_data, undefined);
15849
+ await openOpaque(request.bind_call, undefined);
15628
15850
  await resolveSplitPayloads(request, { bind_call: carried.bindCallIpc }, {
15629
15851
  auth: currentRequestAuth(),
15630
15852
  signingKey,
@@ -17483,6 +17705,19 @@ function catalogTableHandlers(getCatalog, signingKey) {
17483
17705
  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);
17484
17706
  return wrapResult(scanResult, ScanFunctionResultSchema);
17485
17707
  });
17708
+ const optionalTx = (params) => params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined;
17709
+ const catalogTableInsertFunctionGet = catalogHandler(signingKey, async (params) => {
17710
+ const result = await getCatalog().tableInsertFunctionGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, optionalTx(params), params.writable_branch_function_name ?? null);
17711
+ return wrapResult(result, ScanFunctionResultSchema);
17712
+ });
17713
+ const catalogTableUpdateFunctionGet = catalogHandler(signingKey, async (params) => {
17714
+ const result = await getCatalog().tableUpdateFunctionGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, optionalTx(params));
17715
+ return wrapResult(result, ScanFunctionResultSchema);
17716
+ });
17717
+ const catalogTableDeleteFunctionGet = catalogHandler(signingKey, async (params) => {
17718
+ const result = await getCatalog().tableDeleteFunctionGet(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, optionalTx(params));
17719
+ return wrapResult(result, ScanFunctionResultSchema);
17720
+ });
17486
17721
  const catalogTableScanBranchesGet = catalogHandler(signingKey, async (params) => {
17487
17722
  const cat = getCatalog();
17488
17723
  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);
@@ -17561,6 +17796,9 @@ function catalogTableHandlers(getCatalog, signingKey) {
17561
17796
  catalogTableDrop,
17562
17797
  catalogTableColumnStatisticsGet,
17563
17798
  catalogTableScanFunctionGet,
17799
+ catalogTableInsertFunctionGet,
17800
+ catalogTableUpdateFunctionGet,
17801
+ catalogTableDeleteFunctionGet,
17564
17802
  catalogTableScanBranchesGet,
17565
17803
  catalogTableCommentSet,
17566
17804
  catalogTableRename,
@@ -17813,14 +18051,46 @@ function secretType(secrets, name) {
17813
18051
  const f = secrets?.[name];
17814
18052
  return f && "type" in f ? scalarStr(f.type) : undefined;
17815
18053
  }
18054
+ function untyped(fields) {
18055
+ return !!fields && scalarStr(fields.type) === "";
18056
+ }
18057
+ function keyedByType(secrets, type) {
18058
+ const f = secrets?.[type];
18059
+ return untyped(f) ? f : undefined;
18060
+ }
17816
18061
  function secretsOfType(secrets, type) {
17817
- return Object.values(secrets ?? {}).filter((f) => scalarStr(f.type) === type);
18062
+ const typed = Object.values(secrets ?? {}).filter((f) => scalarStr(f.type) === type);
18063
+ if (typed.length > 0)
18064
+ return typed;
18065
+ const legacy = keyedByType(secrets, type);
18066
+ return legacy ? [legacy] : [];
18067
+ }
18068
+ function secretOfType(secrets, type) {
18069
+ const all = secretsOfType(secrets, type);
18070
+ return all.find((f) => scalarStr(f.scope) === "") ?? all[0];
18071
+ }
18072
+ function requireSecretOfType(secrets, type) {
18073
+ const found = secretOfType(secrets, type);
18074
+ if (!found) {
18075
+ throw new Error(`required secret of type '${type}' was not found; create one with CREATE SECRET (TYPE ${type}, ...)`);
18076
+ }
18077
+ return found;
18078
+ }
18079
+ function secretByName(secrets, name, type) {
18080
+ if (!secrets || !Object.prototype.hasOwnProperty.call(secrets, name))
18081
+ return;
18082
+ const f = secrets[name];
18083
+ if (!f)
18084
+ return;
18085
+ if (type === undefined || untyped(f) || scalarStr(f.type) === type)
18086
+ return f;
18087
+ return;
17818
18088
  }
17819
18089
  function secretForScope(secrets, path) {
17820
18090
  return selectForScope(secrets, path, undefined);
17821
18091
  }
17822
18092
  function secretForScopeOfType(secrets, path, type) {
17823
- return selectForScope(secrets, path, type);
18093
+ return selectForScope(secrets, path, type) ?? keyedByType(secrets, type);
17824
18094
  }
17825
18095
  function selectForScope(secrets, path, type) {
17826
18096
  let best;
@@ -19451,6 +19721,7 @@ export {
19451
19721
  PushdownFilters,
19452
19722
  READ_ONLY_ITEM_ATTACH_ID,
19453
19723
  RESERVED_ATTACH_OPTION,
19724
+ ROW_ID_METADATA_KEY,
19454
19725
  ROW_SCALAR_EXPRESSION,
19455
19726
  ReadOnlyCatalogInterface,
19456
19727
  ReservedAttachOptionError,
@@ -19472,6 +19743,8 @@ export {
19472
19743
  VgiClient,
19473
19744
  VgiClientError,
19474
19745
  VgiError,
19746
+ WRITE_OPERATIONS,
19747
+ WRITE_RESULT_MODES,
19475
19748
  Worker,
19476
19749
  adoptArrowJsShape,
19477
19750
  argumentSpecsToSchema,
@@ -19521,6 +19794,7 @@ export {
19521
19794
  canonicalIndex,
19522
19795
  catalogCapabilities,
19523
19796
  codecFor,
19797
+ coerceWriteResultMode,
19524
19798
  columnFromArray,
19525
19799
  constraintCapabilities,
19526
19800
  constraintRecord,
@@ -19658,6 +19932,7 @@ export {
19658
19932
  metadatasToArrow,
19659
19933
  mintAttachTicket,
19660
19934
  moreOutputMetadata,
19935
+ normalizeRequiredSecrets,
19661
19936
  normalizeSchemaPath,
19662
19937
  nullType2 as nullType,
19663
19938
  openAttachTicket,
@@ -19668,16 +19943,20 @@ export {
19668
19943
  readConstraintRecord,
19669
19944
  redeemAttachTicket,
19670
19945
  reprPushedFilters,
19946
+ requireSecretOfType,
19671
19947
  resolveMetadata,
19672
19948
  resolveStorageFromEnv,
19949
+ rowIdField,
19673
19950
  safeNumber,
19674
19951
  schema2 as schema,
19675
19952
  schemaPathDisplay,
19676
19953
  schemaPathKey,
19677
19954
  schemaPathsEqual,
19678
19955
  schemaToArgumentSpecs,
19956
+ secretByName,
19679
19957
  secretForScope,
19680
19958
  secretForScopeOfType,
19959
+ secretOfType,
19681
19960
  secretType,
19682
19961
  secretsOfType,
19683
19962
  selectCatalogCapabilities,
@@ -19697,6 +19976,7 @@ export {
19697
19976
  str,
19698
19977
  struct2 as struct,
19699
19978
  subprocessConnect,
19979
+ supportsWriteResultMode,
19700
19980
  tcpConnect,
19701
19981
  time2 as time,
19702
19982
  timeMicrosecond2 as timeMicrosecond,
@@ -19716,12 +19996,20 @@ export {
19716
19996
  uint642 as uint64,
19717
19997
  uint82 as uint8,
19718
19998
  union2 as union,
19999
+ userColumns,
19719
20000
  utf82 as utf8,
19720
20001
  validateColumnExpressionSql,
19721
20002
  validateConstraintNullability,
19722
20003
  validateForeignKeyTargets,
19723
20004
  validateNumericCheckSql,
19724
- validateTableConstraints
20005
+ validateTableConstraints,
20006
+ validateWriteResultModes,
20007
+ writeChangesBatch,
20008
+ writeCountBatch,
20009
+ writeOptions,
20010
+ writeResultBatch,
20011
+ writeResultSchema,
20012
+ writeRowsBatch
19725
20013
  };
19726
20014
 
19727
- //# debugId=0D39EB7B8CA153F964756E2164756E21
20015
+ //# debugId=403561B04FC0112564756E2164756E21