@query-farm/vgi 0.47.1 → 0.48.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/catalog/column-expressions.d.ts +22 -1
- package/dist/catalog/column-metadata.d.ts +7 -0
- package/dist/catalog/column-types.d.ts +15 -0
- package/dist/catalog/composite.d.ts +2 -0
- package/dist/catalog/constraints.d.ts +110 -12
- package/dist/catalog/descriptors.d.ts +19 -1
- package/dist/catalog/indexes.d.ts +29 -0
- package/dist/catalog/interface.d.ts +41 -0
- package/dist/catalog/public-codecs.d.ts +6 -0
- package/dist/catalog/read-only.d.ts +3 -0
- package/dist/catalog/sql-grammar.d.ts +53 -0
- package/dist/catalog/unconstrained-columns.d.ts +8 -0
- package/dist/client/types.d.ts +5 -1
- package/dist/client-entry.d.ts +1 -0
- package/dist/client-entry.js +1435 -152
- package/dist/client-entry.js.map +15 -11
- package/dist/generated/vgi-client.d.ts +5 -0
- package/dist/generated/vgi-protocol-schemas.d.ts +5 -0
- package/dist/generated/vgi-protocol-types.d.ts +57 -0
- package/dist/generated/vgi-service.d.ts +1 -1
- package/dist/index.core.d.ts +3 -1
- package/dist/index.js +1940 -545
- package/dist/index.js.map +26 -22
- package/dist/protocol/dispatch.d.ts +1 -1
- package/dist/protocol/serializers/splits.d.ts +41 -1
- package/dist/serve-entry.js +1172 -58
- package/dist/serve-entry.js.map +20 -17
- package/dist/worker-cf-entry.d.ts +2 -1
- package/dist/worker-cf-entry.js +1538 -191
- package/dist/worker-cf-entry.js.map +26 -22
- package/package.json +1 -1
- package/src/catalog/column-expressions.ts +85 -7
- package/src/catalog/column-metadata.ts +20 -2
- package/src/catalog/column-types.ts +50 -0
- package/src/catalog/composite.ts +10 -0
- package/src/catalog/constraints.ts +496 -58
- package/src/catalog/contents-codec.ts +3 -3
- package/src/catalog/descriptors.ts +19 -1
- package/src/catalog/indexes.ts +59 -0
- package/src/catalog/interface.ts +103 -1
- package/src/catalog/public-codecs.ts +36 -0
- package/src/catalog/read-only.ts +92 -36
- package/src/catalog/sql-grammar.ts +476 -0
- package/src/catalog/unconstrained-columns.ts +34 -8
- package/src/client/client.ts +6 -3
- package/src/client/types.ts +5 -1
- package/src/client-entry.ts +4 -0
- package/src/generated/vgi-client.ts +6 -1
- package/src/generated/vgi-protocol-schemas.ts +36 -1
- package/src/generated/vgi-protocol-types.ts +130 -1
- package/src/generated/vgi-service.ts +2 -2
- package/src/index.core.ts +34 -1
- package/src/protocol/dispatch.ts +1 -1
- package/src/protocol/handlers/catalog/admin.ts +14 -13
- package/src/protocol/handlers/catalog/table.ts +58 -11
- package/src/protocol/serializers/splits.ts +82 -9
- package/src/worker-cf-entry.ts +2 -4
package/dist/serve-entry.js
CHANGED
|
@@ -2955,6 +2955,18 @@ function deserializeBindResponse(params) {
|
|
|
2955
2955
|
repeatability: parseBindRepeatability(params.repeatability)
|
|
2956
2956
|
};
|
|
2957
2957
|
}
|
|
2958
|
+
// src/protocol/types.ts
|
|
2959
|
+
var OrderByDirection;
|
|
2960
|
+
((OrderByDirection) => {
|
|
2961
|
+
OrderByDirection["ASC"] = "ASC";
|
|
2962
|
+
OrderByDirection["DESC"] = "DESC";
|
|
2963
|
+
})(OrderByDirection ||= {});
|
|
2964
|
+
var OrderByNullOrder;
|
|
2965
|
+
((OrderByNullOrder) => {
|
|
2966
|
+
OrderByNullOrder["NULLS_FIRST"] = "NULLS_FIRST";
|
|
2967
|
+
OrderByNullOrder["NULLS_LAST"] = "NULLS_LAST";
|
|
2968
|
+
})(OrderByNullOrder ||= {});
|
|
2969
|
+
|
|
2958
2970
|
// src/protocol/serializers/init.ts
|
|
2959
2971
|
var INIT_REQUEST_SCHEMA = schema2([
|
|
2960
2972
|
field2("bind_call", binary2(), false),
|
|
@@ -3396,7 +3408,7 @@ import {
|
|
|
3396
3408
|
Protocol
|
|
3397
3409
|
} from "@query-farm/vgi-rpc";
|
|
3398
3410
|
var VGI_PROTOCOL_NAME = "vgi.v3";
|
|
3399
|
-
var VGI_PROTOCOL_VERSION = "3.
|
|
3411
|
+
var VGI_PROTOCOL_VERSION = "3.1.0";
|
|
3400
3412
|
function exchangeStream(callbacks) {
|
|
3401
3413
|
return { kind: "exchange", ...callbacks };
|
|
3402
3414
|
}
|
|
@@ -4986,6 +4998,26 @@ var CopyFromFormatInfoSchema = schema2([
|
|
|
4986
4998
|
field2("description", utf82(), false),
|
|
4987
4999
|
field2("ordered", bool2(), false)
|
|
4988
5000
|
]);
|
|
5001
|
+
var FieldPathSchema = schema2([
|
|
5002
|
+
field2("components", list2(field2("item", utf82(), true)), false)
|
|
5003
|
+
]);
|
|
5004
|
+
var TransformSpecSchema = schema2([
|
|
5005
|
+
field2("id", utf82(), false),
|
|
5006
|
+
field2("inputs", list2(field2("item", binary2(), true)), false),
|
|
5007
|
+
field2("parameters", binary2(), true)
|
|
5008
|
+
]);
|
|
5009
|
+
var KeyGroupingSchema = schema2([
|
|
5010
|
+
field2("keys", list2(field2("item", binary2(), true)), false)
|
|
5011
|
+
]);
|
|
5012
|
+
var RangeKeySchema = schema2([
|
|
5013
|
+
field2("transform", binary2(), false),
|
|
5014
|
+
field2("direction", dictionary2(utf82(), int162()), false),
|
|
5015
|
+
field2("null_order", dictionary2(utf82(), int162()), false)
|
|
5016
|
+
]);
|
|
5017
|
+
var RangePartitioningSchema = schema2([
|
|
5018
|
+
field2("keys", list2(field2("item", binary2(), true)), false),
|
|
5019
|
+
field2("split_points", binary2(), false)
|
|
5020
|
+
]);
|
|
4989
5021
|
var MacroParameterSchema = schema2([
|
|
4990
5022
|
field2("name", utf82(), false),
|
|
4991
5023
|
field2("declared_type", binary2(), true),
|
|
@@ -5216,6 +5248,9 @@ var ScanSplitSchema = schema2([
|
|
|
5216
5248
|
field2("estimated_rows", int642(), true),
|
|
5217
5249
|
field2("rows_exact", bool2(), false),
|
|
5218
5250
|
field2("estimated_bytes", int642(), true),
|
|
5251
|
+
field2("key_value", binary2(), true),
|
|
5252
|
+
field2("range_index", int642(), true),
|
|
5253
|
+
field2("column_bounds", binary2(), true),
|
|
5219
5254
|
field2("partition_bounds", binary2(), true),
|
|
5220
5255
|
field2("column_statistics", binary2(), true),
|
|
5221
5256
|
field2("location_ids", list2(field2("item", int642(), true)), true),
|
|
@@ -5691,6 +5726,8 @@ var TableFunctionPlanResultSchema = schema2([
|
|
|
5691
5726
|
field2("catalog_version", int642(), true),
|
|
5692
5727
|
field2("scope", utf82(), false),
|
|
5693
5728
|
field2("locations", list2(field2("item", utf82(), true)), true),
|
|
5729
|
+
field2("key_grouping", binary2(), true),
|
|
5730
|
+
field2("range_partitioning", binary2(), true),
|
|
5694
5731
|
field2("partitioning", list2(field2("item", binary2(), true)), true),
|
|
5695
5732
|
field2("sort_order", list2(field2("item", binary2(), true)), true),
|
|
5696
5733
|
field2("cache_max_age_seconds", int642(), true),
|
|
@@ -6364,7 +6401,10 @@ function decodeASDCollection(schema, bytes) {
|
|
|
6364
6401
|
// src/generated/vgi-protocol-types.ts
|
|
6365
6402
|
var encodeCatalogCapabilities = (v) => encodeASD(CatalogCapabilitiesSchema, v);
|
|
6366
6403
|
var decodeCatalogCapabilities = (b) => decodeASD(CatalogCapabilitiesSchema, b);
|
|
6404
|
+
var decodeCatalogObjectRef = (b) => decodeASD(CatalogObjectRefSchema, b);
|
|
6405
|
+
var encodeSqlExpression = (v) => encodeASD(SqlExpressionSchema, v);
|
|
6367
6406
|
var decodeSqlExpression = (b) => decodeASD(SqlExpressionSchema, b);
|
|
6407
|
+
var decodeConstraintDefinition = (b) => decodeASD(ConstraintDefinitionSchema, b);
|
|
6368
6408
|
function buildCatalogAttachResult(init) {
|
|
6369
6409
|
return {
|
|
6370
6410
|
attach_opaque_data: init.attach_opaque_data,
|
|
@@ -6404,9 +6444,612 @@ function buildCatalogContentsResponse(init) {
|
|
|
6404
6444
|
};
|
|
6405
6445
|
}
|
|
6406
6446
|
|
|
6447
|
+
// src/catalog/sql-grammar.ts
|
|
6448
|
+
class GrammarError extends Error {
|
|
6449
|
+
}
|
|
6450
|
+
var fail = (message) => {
|
|
6451
|
+
throw new GrammarError(message);
|
|
6452
|
+
};
|
|
6453
|
+
var RESERVED = new Set([
|
|
6454
|
+
"all",
|
|
6455
|
+
"and",
|
|
6456
|
+
"any",
|
|
6457
|
+
"array",
|
|
6458
|
+
"as",
|
|
6459
|
+
"asc",
|
|
6460
|
+
"between",
|
|
6461
|
+
"both",
|
|
6462
|
+
"case",
|
|
6463
|
+
"cast",
|
|
6464
|
+
"check",
|
|
6465
|
+
"collate",
|
|
6466
|
+
"column",
|
|
6467
|
+
"constraint",
|
|
6468
|
+
"create",
|
|
6469
|
+
"default",
|
|
6470
|
+
"desc",
|
|
6471
|
+
"distinct",
|
|
6472
|
+
"do",
|
|
6473
|
+
"else",
|
|
6474
|
+
"end",
|
|
6475
|
+
"except",
|
|
6476
|
+
"false",
|
|
6477
|
+
"fetch",
|
|
6478
|
+
"for",
|
|
6479
|
+
"foreign",
|
|
6480
|
+
"from",
|
|
6481
|
+
"glob",
|
|
6482
|
+
"grant",
|
|
6483
|
+
"group",
|
|
6484
|
+
"having",
|
|
6485
|
+
"ilike",
|
|
6486
|
+
"in",
|
|
6487
|
+
"intersect",
|
|
6488
|
+
"interval",
|
|
6489
|
+
"into",
|
|
6490
|
+
"is",
|
|
6491
|
+
"isnull",
|
|
6492
|
+
"like",
|
|
6493
|
+
"limit",
|
|
6494
|
+
"not",
|
|
6495
|
+
"notnull",
|
|
6496
|
+
"null",
|
|
6497
|
+
"offset",
|
|
6498
|
+
"on",
|
|
6499
|
+
"or",
|
|
6500
|
+
"order",
|
|
6501
|
+
"primary",
|
|
6502
|
+
"references",
|
|
6503
|
+
"returning",
|
|
6504
|
+
"select",
|
|
6505
|
+
"similar",
|
|
6506
|
+
"some",
|
|
6507
|
+
"table",
|
|
6508
|
+
"then",
|
|
6509
|
+
"to",
|
|
6510
|
+
"true",
|
|
6511
|
+
"try_cast",
|
|
6512
|
+
"union",
|
|
6513
|
+
"unique",
|
|
6514
|
+
"using",
|
|
6515
|
+
"when",
|
|
6516
|
+
"where",
|
|
6517
|
+
"window",
|
|
6518
|
+
"with"
|
|
6519
|
+
]);
|
|
6520
|
+
var OPERATORS = ["::", "<=", ">=", "<>", "!=", "==", "||", "//", "**", "=", "<", ">", "+", "-", "*", "/", "%", "^", "(", ")", ",", "."];
|
|
6521
|
+
function tokenize(sql) {
|
|
6522
|
+
const out = [];
|
|
6523
|
+
let i = 0;
|
|
6524
|
+
while (i < sql.length) {
|
|
6525
|
+
const c = sql[i];
|
|
6526
|
+
if (/\s/.test(c)) {
|
|
6527
|
+
i++;
|
|
6528
|
+
continue;
|
|
6529
|
+
}
|
|
6530
|
+
if (sql.startsWith("--", i)) {
|
|
6531
|
+
while (i < sql.length && sql[i] !== `
|
|
6532
|
+
`)
|
|
6533
|
+
i++;
|
|
6534
|
+
continue;
|
|
6535
|
+
}
|
|
6536
|
+
if (sql.startsWith("/*", i)) {
|
|
6537
|
+
const close = sql.indexOf("*/", i + 2);
|
|
6538
|
+
if (close < 0)
|
|
6539
|
+
fail("unterminated comment");
|
|
6540
|
+
i = close + 2;
|
|
6541
|
+
continue;
|
|
6542
|
+
}
|
|
6543
|
+
if (/[0-9]/.test(c) || c === "." && /[0-9]/.test(sql[i + 1] ?? "")) {
|
|
6544
|
+
const m = /^(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?/.exec(sql.slice(i));
|
|
6545
|
+
if (/[A-Za-z_]/.test(sql[i + m[0].length] ?? ""))
|
|
6546
|
+
fail("unsupported numeric literal");
|
|
6547
|
+
out.push({ t: "num", v: m[0] });
|
|
6548
|
+
i += m[0].length;
|
|
6549
|
+
continue;
|
|
6550
|
+
}
|
|
6551
|
+
if (c === "'" || c === '"') {
|
|
6552
|
+
let j = i + 1, text = "";
|
|
6553
|
+
for (;; ) {
|
|
6554
|
+
if (j >= sql.length)
|
|
6555
|
+
fail("unterminated quoted text");
|
|
6556
|
+
if (sql[j] === c) {
|
|
6557
|
+
if (sql[j + 1] === c) {
|
|
6558
|
+
text += c;
|
|
6559
|
+
j += 2;
|
|
6560
|
+
continue;
|
|
6561
|
+
}
|
|
6562
|
+
break;
|
|
6563
|
+
}
|
|
6564
|
+
text += sql[j++];
|
|
6565
|
+
}
|
|
6566
|
+
out.push(c === "'" ? { t: "str", v: text } : { t: "ident", v: text, quoted: true });
|
|
6567
|
+
i = j + 1;
|
|
6568
|
+
continue;
|
|
6569
|
+
}
|
|
6570
|
+
if (/[A-Za-z_\u0080-\uFFFF]/.test(c)) {
|
|
6571
|
+
const m = /^[A-Za-z_\u0080-\uFFFF][A-Za-z0-9_$\u0080-\uFFFF]*/.exec(sql.slice(i));
|
|
6572
|
+
out.push({ t: "ident", v: m[0], quoted: false });
|
|
6573
|
+
i += m[0].length;
|
|
6574
|
+
continue;
|
|
6575
|
+
}
|
|
6576
|
+
const op = OPERATORS.find((o) => sql.startsWith(o, i));
|
|
6577
|
+
if (!op)
|
|
6578
|
+
fail(`unsupported character '${c}'`);
|
|
6579
|
+
out.push({ t: "op", v: op });
|
|
6580
|
+
i += op.length;
|
|
6581
|
+
}
|
|
6582
|
+
out.push({ t: "end" });
|
|
6583
|
+
return out;
|
|
6584
|
+
}
|
|
6585
|
+
var CAST_TYPES = {
|
|
6586
|
+
boolean: "BOOLEAN",
|
|
6587
|
+
bool: "BOOLEAN",
|
|
6588
|
+
logical: "BOOLEAN",
|
|
6589
|
+
tinyint: "TINYINT",
|
|
6590
|
+
int1: "TINYINT",
|
|
6591
|
+
smallint: "SMALLINT",
|
|
6592
|
+
int2: "SMALLINT",
|
|
6593
|
+
short: "SMALLINT",
|
|
6594
|
+
integer: "INTEGER",
|
|
6595
|
+
int: "INTEGER",
|
|
6596
|
+
int4: "INTEGER",
|
|
6597
|
+
signed: "INTEGER",
|
|
6598
|
+
bigint: "BIGINT",
|
|
6599
|
+
int8: "BIGINT",
|
|
6600
|
+
long: "BIGINT",
|
|
6601
|
+
float: "FLOAT",
|
|
6602
|
+
real: "FLOAT",
|
|
6603
|
+
float4: "FLOAT",
|
|
6604
|
+
double: "DOUBLE",
|
|
6605
|
+
float8: "DOUBLE",
|
|
6606
|
+
decimal: "DECIMAL",
|
|
6607
|
+
numeric: "DECIMAL",
|
|
6608
|
+
varchar: "VARCHAR",
|
|
6609
|
+
text: "VARCHAR",
|
|
6610
|
+
string: "VARCHAR",
|
|
6611
|
+
char: "VARCHAR",
|
|
6612
|
+
bpchar: "VARCHAR",
|
|
6613
|
+
nvarchar: "VARCHAR",
|
|
6614
|
+
character: "VARCHAR"
|
|
6615
|
+
};
|
|
6616
|
+
var INT64_MAX = (1n << 63n) - 1n;
|
|
6617
|
+
function literalNumber(text, negative) {
|
|
6618
|
+
if (/^[0-9]+$/.test(text)) {
|
|
6619
|
+
const value = BigInt(text) * (negative ? -1n : 1n);
|
|
6620
|
+
const type = value >= -(2n ** 31n) && value < 2n ** 31n ? "INTEGER" : value >= -INT64_MAX - 1n && value <= INT64_MAX ? "BIGINT" : "HUGEINT";
|
|
6621
|
+
return { kind: "constant", type };
|
|
6622
|
+
}
|
|
6623
|
+
if (!/[eE]/.test(text) && text.replace(".", "").replace(/^0+/, "").length <= 38)
|
|
6624
|
+
return { kind: "constant", type: "DECIMAL" };
|
|
6625
|
+
return { kind: "constant", type: "DOUBLE" };
|
|
6626
|
+
}
|
|
6627
|
+
|
|
6628
|
+
class Parser {
|
|
6629
|
+
tokens;
|
|
6630
|
+
pos = 0;
|
|
6631
|
+
constructor(tokens) {
|
|
6632
|
+
this.tokens = tokens;
|
|
6633
|
+
}
|
|
6634
|
+
peek(offset = 0) {
|
|
6635
|
+
return this.tokens[Math.min(this.pos + offset, this.tokens.length - 1)];
|
|
6636
|
+
}
|
|
6637
|
+
next() {
|
|
6638
|
+
return this.tokens[this.pos++];
|
|
6639
|
+
}
|
|
6640
|
+
isOp(v, offset = 0) {
|
|
6641
|
+
const t = this.peek(offset);
|
|
6642
|
+
return t.t === "op" && t.v === v;
|
|
6643
|
+
}
|
|
6644
|
+
isWord(word, offset = 0) {
|
|
6645
|
+
const t = this.peek(offset);
|
|
6646
|
+
return t.t === "ident" && !t.quoted && t.v.toLowerCase() === word;
|
|
6647
|
+
}
|
|
6648
|
+
expectOp(v) {
|
|
6649
|
+
if (!this.isOp(v))
|
|
6650
|
+
fail(`expected '${v}'`);
|
|
6651
|
+
this.pos++;
|
|
6652
|
+
}
|
|
6653
|
+
parseAll() {
|
|
6654
|
+
const node = this.expr();
|
|
6655
|
+
if (this.peek().t !== "end")
|
|
6656
|
+
fail("unexpected text after the expression");
|
|
6657
|
+
return node;
|
|
6658
|
+
}
|
|
6659
|
+
expr() {
|
|
6660
|
+
return this.or();
|
|
6661
|
+
}
|
|
6662
|
+
or() {
|
|
6663
|
+
let left = this.and();
|
|
6664
|
+
while (this.isWord("or")) {
|
|
6665
|
+
this.pos++;
|
|
6666
|
+
left = { kind: "conjunction", op: "OR", children: [left, this.and()] };
|
|
6667
|
+
}
|
|
6668
|
+
return left;
|
|
6669
|
+
}
|
|
6670
|
+
and() {
|
|
6671
|
+
let left = this.not();
|
|
6672
|
+
while (this.isWord("and")) {
|
|
6673
|
+
this.pos++;
|
|
6674
|
+
left = { kind: "conjunction", op: "AND", children: [left, this.not()] };
|
|
6675
|
+
}
|
|
6676
|
+
return left;
|
|
6677
|
+
}
|
|
6678
|
+
not() {
|
|
6679
|
+
if (this.isWord("not")) {
|
|
6680
|
+
this.pos++;
|
|
6681
|
+
return { kind: "operator", op: "NOT", children: [this.not()] };
|
|
6682
|
+
}
|
|
6683
|
+
return this.is();
|
|
6684
|
+
}
|
|
6685
|
+
is() {
|
|
6686
|
+
let left = this.comparison();
|
|
6687
|
+
for (;; ) {
|
|
6688
|
+
if (this.isWord("isnull")) {
|
|
6689
|
+
this.pos++;
|
|
6690
|
+
left = { kind: "operator", op: "IS_NULL", children: [left] };
|
|
6691
|
+
continue;
|
|
6692
|
+
}
|
|
6693
|
+
if (this.isWord("notnull")) {
|
|
6694
|
+
this.pos++;
|
|
6695
|
+
left = { kind: "operator", op: "IS_NOT_NULL", children: [left] };
|
|
6696
|
+
continue;
|
|
6697
|
+
}
|
|
6698
|
+
if (this.isWord("is")) {
|
|
6699
|
+
this.pos++;
|
|
6700
|
+
const negated = this.isWord("not");
|
|
6701
|
+
if (negated)
|
|
6702
|
+
this.pos++;
|
|
6703
|
+
if (!this.isWord("null"))
|
|
6704
|
+
fail("only IS [NOT] NULL is supported");
|
|
6705
|
+
this.pos++;
|
|
6706
|
+
left = { kind: "operator", op: negated ? "IS_NOT_NULL" : "IS_NULL", children: [left] };
|
|
6707
|
+
continue;
|
|
6708
|
+
}
|
|
6709
|
+
return left;
|
|
6710
|
+
}
|
|
6711
|
+
}
|
|
6712
|
+
comparison() {
|
|
6713
|
+
const left = this.otherOp();
|
|
6714
|
+
const t = this.peek();
|
|
6715
|
+
if (t.t === "op" && ["=", "==", "<>", "!=", "<", ">", "<=", ">="].includes(t.v)) {
|
|
6716
|
+
this.pos++;
|
|
6717
|
+
const right = this.otherOp();
|
|
6718
|
+
const next = this.peek();
|
|
6719
|
+
if (next.t === "op" && ["=", "==", "<>", "!=", "<", ">", "<=", ">="].includes(next.v))
|
|
6720
|
+
fail("chained comparisons are unsupported");
|
|
6721
|
+
return { kind: "comparison", op: t.v === "==" ? "=" : t.v === "!=" ? "<>" : t.v, left, right };
|
|
6722
|
+
}
|
|
6723
|
+
for (const word of ["between", "in", "like", "ilike", "glob", "similar", "not", "collate"]) {
|
|
6724
|
+
if (this.isWord(word))
|
|
6725
|
+
fail(`${word.toUpperCase()} is outside the supported scalar grammar`);
|
|
6726
|
+
}
|
|
6727
|
+
return left;
|
|
6728
|
+
}
|
|
6729
|
+
otherOp() {
|
|
6730
|
+
let left = this.additive();
|
|
6731
|
+
for (;; ) {
|
|
6732
|
+
const t = this.peek();
|
|
6733
|
+
if (t.t === "op" && ["||", "//", "**"].includes(t.v)) {
|
|
6734
|
+
this.pos++;
|
|
6735
|
+
left = { kind: "function", name: t.v, qualified: false, children: [left, this.additive()] };
|
|
6736
|
+
continue;
|
|
6737
|
+
}
|
|
6738
|
+
return left;
|
|
6739
|
+
}
|
|
6740
|
+
}
|
|
6741
|
+
additive() {
|
|
6742
|
+
let left = this.multiplicative();
|
|
6743
|
+
for (;; ) {
|
|
6744
|
+
const t = this.peek();
|
|
6745
|
+
if (t.t === "op" && (t.v === "+" || t.v === "-")) {
|
|
6746
|
+
this.pos++;
|
|
6747
|
+
left = { kind: "function", name: t.v, qualified: false, children: [left, this.multiplicative()] };
|
|
6748
|
+
continue;
|
|
6749
|
+
}
|
|
6750
|
+
return left;
|
|
6751
|
+
}
|
|
6752
|
+
}
|
|
6753
|
+
multiplicative() {
|
|
6754
|
+
let left = this.power();
|
|
6755
|
+
for (;; ) {
|
|
6756
|
+
const t = this.peek();
|
|
6757
|
+
if (t.t === "op" && (t.v === "*" || t.v === "/" || t.v === "%")) {
|
|
6758
|
+
this.pos++;
|
|
6759
|
+
left = { kind: "function", name: t.v, qualified: false, children: [left, this.power()] };
|
|
6760
|
+
continue;
|
|
6761
|
+
}
|
|
6762
|
+
return left;
|
|
6763
|
+
}
|
|
6764
|
+
}
|
|
6765
|
+
power() {
|
|
6766
|
+
let left = this.unary();
|
|
6767
|
+
while (this.isOp("^")) {
|
|
6768
|
+
this.pos++;
|
|
6769
|
+
left = { kind: "function", name: "^", qualified: false, children: [left, this.unary()] };
|
|
6770
|
+
}
|
|
6771
|
+
return left;
|
|
6772
|
+
}
|
|
6773
|
+
unary() {
|
|
6774
|
+
if (this.isOp("-") || this.isOp("+")) {
|
|
6775
|
+
const sign = this.next().v;
|
|
6776
|
+
const operand = this.unary();
|
|
6777
|
+
if (sign === "-" && operand.kind === "constant" && operand.fromNumber) {
|
|
6778
|
+
const folded = literalNumber(operand.text, !operand.negative);
|
|
6779
|
+
return Object.assign(folded, { fromNumber: true, text: operand.text, negative: !operand.negative });
|
|
6780
|
+
}
|
|
6781
|
+
return { kind: "function", name: sign, qualified: false, children: [operand] };
|
|
6782
|
+
}
|
|
6783
|
+
return this.postfix();
|
|
6784
|
+
}
|
|
6785
|
+
postfix() {
|
|
6786
|
+
let node = this.primary();
|
|
6787
|
+
for (;; ) {
|
|
6788
|
+
if (this.isOp("::")) {
|
|
6789
|
+
this.pos++;
|
|
6790
|
+
node = { kind: "cast", ...this.typeName(), child: node };
|
|
6791
|
+
continue;
|
|
6792
|
+
}
|
|
6793
|
+
if (this.isOp("["))
|
|
6794
|
+
fail("subscripts are unsupported");
|
|
6795
|
+
return node;
|
|
6796
|
+
}
|
|
6797
|
+
}
|
|
6798
|
+
typeName() {
|
|
6799
|
+
const t = this.next();
|
|
6800
|
+
if (t.t !== "ident")
|
|
6801
|
+
fail("expected a type name");
|
|
6802
|
+
const first = t.v.toLowerCase();
|
|
6803
|
+
let qualified = false;
|
|
6804
|
+
while (this.isOp(".")) {
|
|
6805
|
+
this.pos++;
|
|
6806
|
+
if (this.next().t !== "ident")
|
|
6807
|
+
fail("expected a type name");
|
|
6808
|
+
qualified = true;
|
|
6809
|
+
}
|
|
6810
|
+
let name = first;
|
|
6811
|
+
if (first === "double" && this.isWord("precision")) {
|
|
6812
|
+
this.pos++;
|
|
6813
|
+
name = "double";
|
|
6814
|
+
}
|
|
6815
|
+
if (first === "character" && this.isWord("varying")) {
|
|
6816
|
+
this.pos++;
|
|
6817
|
+
name = "varchar";
|
|
6818
|
+
}
|
|
6819
|
+
let params = [];
|
|
6820
|
+
if (this.isOp("(")) {
|
|
6821
|
+
this.pos++;
|
|
6822
|
+
for (;; ) {
|
|
6823
|
+
const p = this.next();
|
|
6824
|
+
if (p.t !== "num")
|
|
6825
|
+
fail("unsupported type parameter");
|
|
6826
|
+
params.push(p.v);
|
|
6827
|
+
if (this.isOp(",")) {
|
|
6828
|
+
this.pos++;
|
|
6829
|
+
continue;
|
|
6830
|
+
}
|
|
6831
|
+
break;
|
|
6832
|
+
}
|
|
6833
|
+
this.expectOp(")");
|
|
6834
|
+
}
|
|
6835
|
+
if (this.isOp("["))
|
|
6836
|
+
fail("array types are unsupported");
|
|
6837
|
+
let type = CAST_TYPES[name] ?? null;
|
|
6838
|
+
if (type === "FLOAT" && params.length === 1 && Number(params[0]) > 24)
|
|
6839
|
+
type = "DOUBLE";
|
|
6840
|
+
return { type, qualified };
|
|
6841
|
+
}
|
|
6842
|
+
primary() {
|
|
6843
|
+
const t = this.next();
|
|
6844
|
+
if (t.t === "num")
|
|
6845
|
+
return Object.assign(literalNumber(t.v, false), { fromNumber: true, text: t.v, negative: false });
|
|
6846
|
+
if (t.t === "str") {
|
|
6847
|
+
if (this.peek().t === "str")
|
|
6848
|
+
fail("adjacent string literals are unsupported");
|
|
6849
|
+
return { kind: "constant", type: "VARCHAR" };
|
|
6850
|
+
}
|
|
6851
|
+
if (t.t === "op") {
|
|
6852
|
+
if (t.v === "(") {
|
|
6853
|
+
const inner = this.expr();
|
|
6854
|
+
if (this.isOp(","))
|
|
6855
|
+
fail("row constructors are unsupported");
|
|
6856
|
+
this.expectOp(")");
|
|
6857
|
+
return inner;
|
|
6858
|
+
}
|
|
6859
|
+
return fail(`unexpected '${t.v}'`);
|
|
6860
|
+
}
|
|
6861
|
+
if (t.t === "end")
|
|
6862
|
+
return fail("expected an expression");
|
|
6863
|
+
const word = t.v.toLowerCase();
|
|
6864
|
+
if (!t.quoted) {
|
|
6865
|
+
if (word === "null")
|
|
6866
|
+
return { kind: "constant", type: "NULL" };
|
|
6867
|
+
if (word === "true" || word === "false")
|
|
6868
|
+
return { kind: "constant", type: "BOOLEAN" };
|
|
6869
|
+
if (word === "cast" && this.isOp("(")) {
|
|
6870
|
+
this.pos++;
|
|
6871
|
+
const child = this.expr();
|
|
6872
|
+
if (!this.isWord("as"))
|
|
6873
|
+
fail("expected AS in CAST");
|
|
6874
|
+
this.pos++;
|
|
6875
|
+
const target = this.typeName();
|
|
6876
|
+
this.expectOp(")");
|
|
6877
|
+
return { kind: "cast", ...target, child };
|
|
6878
|
+
}
|
|
6879
|
+
if (word === "case")
|
|
6880
|
+
fail("CASE is outside the supported scalar grammar");
|
|
6881
|
+
if (RESERVED.has(word))
|
|
6882
|
+
fail(`unexpected keyword ${t.v.toUpperCase()}`);
|
|
6883
|
+
}
|
|
6884
|
+
const names = [t.v];
|
|
6885
|
+
while (this.isOp(".")) {
|
|
6886
|
+
this.pos++;
|
|
6887
|
+
const part = this.next();
|
|
6888
|
+
if (part.t !== "ident")
|
|
6889
|
+
fail("unsupported qualified name");
|
|
6890
|
+
names.push(part.v);
|
|
6891
|
+
}
|
|
6892
|
+
if (this.isOp("(")) {
|
|
6893
|
+
this.pos++;
|
|
6894
|
+
const children = [];
|
|
6895
|
+
if (this.isWord("distinct"))
|
|
6896
|
+
fail("DISTINCT function arguments are unsupported");
|
|
6897
|
+
if (!this.isOp(")")) {
|
|
6898
|
+
for (;; ) {
|
|
6899
|
+
if (this.isOp("*"))
|
|
6900
|
+
fail("star arguments are unsupported");
|
|
6901
|
+
if (this.peek(1).t === "op" && (this.peek(1).v === ":" || this.peek(1).v === "=") && this.peek().t === "ident")
|
|
6902
|
+
fail("named scalar arguments are unsupported");
|
|
6903
|
+
children.push(this.expr());
|
|
6904
|
+
if (this.isOp(",")) {
|
|
6905
|
+
this.pos++;
|
|
6906
|
+
continue;
|
|
6907
|
+
}
|
|
6908
|
+
break;
|
|
6909
|
+
}
|
|
6910
|
+
}
|
|
6911
|
+
if (this.isWord("order"))
|
|
6912
|
+
fail("ordered function arguments are unsupported");
|
|
6913
|
+
this.expectOp(")");
|
|
6914
|
+
if (this.isWord("filter") || this.isWord("over"))
|
|
6915
|
+
fail("aggregate and window functions are unsupported");
|
|
6916
|
+
if (names.length === 1 && !t.quoted && word === "coalesce")
|
|
6917
|
+
return { kind: "operator", op: "COALESCE", children };
|
|
6918
|
+
return { kind: "function", name: names[names.length - 1], qualified: names.length > 1, children };
|
|
6919
|
+
}
|
|
6920
|
+
if (this.peek().t === "str")
|
|
6921
|
+
fail("typed literals are unsupported");
|
|
6922
|
+
return { kind: "column", names };
|
|
6923
|
+
}
|
|
6924
|
+
}
|
|
6925
|
+
function parseScalarSql(sql) {
|
|
6926
|
+
if (typeof sql !== "string" || !sql || sql.includes("\x00") || new TextEncoder().encode(sql).length > 1024 * 1024)
|
|
6927
|
+
fail("invalid SQL size or text");
|
|
6928
|
+
return new Parser(tokenize(sql)).parseAll();
|
|
6929
|
+
}
|
|
6930
|
+
var PRIMITIVE = new Set(["NULL", "BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE", "DECIMAL", "VARCHAR"]);
|
|
6931
|
+
var GENERATED_PRIMITIVE = new Set(["NULL", "BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "VARCHAR"]);
|
|
6932
|
+
var ALLOWED_FUNCTIONS = new Set(["+", "-", "*", "%", "abs", "lower", "upper"]);
|
|
6933
|
+
function validateColumnExpressionSql(sql, options) {
|
|
6934
|
+
const { usingColumns, generated } = options;
|
|
6935
|
+
const primitive = generated ? GENERATED_PRIMITIVE : PRIMITIVE;
|
|
6936
|
+
const columns = [];
|
|
6937
|
+
let nodes = 0;
|
|
6938
|
+
const visit = (node, depth) => {
|
|
6939
|
+
if (depth > 64 || ++nodes > 4096)
|
|
6940
|
+
fail("scalar expression is too complex");
|
|
6941
|
+
switch (node.kind) {
|
|
6942
|
+
case "constant":
|
|
6943
|
+
if (!primitive.has(node.type))
|
|
6944
|
+
fail(`unsupported scalar literal type ${node.type}`);
|
|
6945
|
+
return;
|
|
6946
|
+
case "column":
|
|
6947
|
+
if (!usingColumns || node.names.length !== 1)
|
|
6948
|
+
fail("column references are unsupported in this scope");
|
|
6949
|
+
columns.push(node.names[0]);
|
|
6950
|
+
return;
|
|
6951
|
+
case "cast":
|
|
6952
|
+
if (node.qualified)
|
|
6953
|
+
fail("qualified scalar cast types are unsupported");
|
|
6954
|
+
if (node.type === null || !primitive.has(node.type))
|
|
6955
|
+
fail("unsupported scalar cast");
|
|
6956
|
+
visit(node.child, depth + 1);
|
|
6957
|
+
return;
|
|
6958
|
+
case "comparison":
|
|
6959
|
+
visit(node.left, depth + 1);
|
|
6960
|
+
visit(node.right, depth + 1);
|
|
6961
|
+
return;
|
|
6962
|
+
case "conjunction":
|
|
6963
|
+
case "operator":
|
|
6964
|
+
node.children.forEach((c) => visit(c, depth + 1));
|
|
6965
|
+
return;
|
|
6966
|
+
case "function": {
|
|
6967
|
+
const lower = node.name.toLowerCase();
|
|
6968
|
+
const ok = !node.qualified && (ALLOWED_FUNCTIONS.has(lower) || usingColumns && !generated && node.name === "/" || generated && node.name === "||");
|
|
6969
|
+
if (!ok)
|
|
6970
|
+
fail(`unsupported scalar function '${node.name}'`);
|
|
6971
|
+
node.children.forEach((c) => visit(c, depth + 1));
|
|
6972
|
+
return;
|
|
6973
|
+
}
|
|
6974
|
+
}
|
|
6975
|
+
};
|
|
6976
|
+
try {
|
|
6977
|
+
visit(parseScalarSql(sql), 0);
|
|
6978
|
+
} catch (error) {
|
|
6979
|
+
if (error instanceof GrammarError)
|
|
6980
|
+
throw error;
|
|
6981
|
+
throw new GrammarError(String(error?.message ?? error));
|
|
6982
|
+
}
|
|
6983
|
+
return columns;
|
|
6984
|
+
}
|
|
6985
|
+
function validateNumericCheckSql(sql, resolveColumn) {
|
|
6986
|
+
const node = parseScalarSql(sql);
|
|
6987
|
+
if (node.kind !== "comparison")
|
|
6988
|
+
fail("native CHECK read supports only Boolean numeric comparisons");
|
|
6989
|
+
const comparison = node;
|
|
6990
|
+
for (const operand of [comparison.left, comparison.right]) {
|
|
6991
|
+
if (operand.kind === "constant") {
|
|
6992
|
+
if (operand.type === "NULL" || operand.type === "BOOLEAN" || operand.type === "VARCHAR")
|
|
6993
|
+
fail("CHECK requires numeric operands");
|
|
6994
|
+
continue;
|
|
6995
|
+
}
|
|
6996
|
+
if (operand.kind !== "column")
|
|
6997
|
+
fail("native CHECK read supports only numeric column/constant comparisons");
|
|
6998
|
+
const column = operand;
|
|
6999
|
+
if (column.names.length !== 1)
|
|
7000
|
+
fail("CHECK requires unqualified column references");
|
|
7001
|
+
resolveColumn(column.names[0]);
|
|
7002
|
+
}
|
|
7003
|
+
}
|
|
7004
|
+
|
|
7005
|
+
// src/catalog/column-types.ts
|
|
7006
|
+
function isRowIdField(field) {
|
|
7007
|
+
return field.metadata?.has("is_row_id") ?? false;
|
|
7008
|
+
}
|
|
7009
|
+
function hasLogicalType(field) {
|
|
7010
|
+
for (const key of field.metadata?.keys() ?? [])
|
|
7011
|
+
if (key === "ARROW:extension:name" || key.startsWith("vgi.logical_type."))
|
|
7012
|
+
return true;
|
|
7013
|
+
return false;
|
|
7014
|
+
}
|
|
7015
|
+
function ordinaryStructChildren(field) {
|
|
7016
|
+
if (!isStruct(field.type) || hasLogicalType(field))
|
|
7017
|
+
return null;
|
|
7018
|
+
return field.type.children;
|
|
7019
|
+
}
|
|
7020
|
+
function isGeneratedField(field) {
|
|
7021
|
+
const m = field.metadata;
|
|
7022
|
+
return m != null && (m.has("vgi.column.generated.v1") || m.has("vgi.column.generation.v1") || m.has("generated_expression"));
|
|
7023
|
+
}
|
|
7024
|
+
function duckdbPrimitive(field) {
|
|
7025
|
+
if (hasLogicalType(field))
|
|
7026
|
+
return null;
|
|
7027
|
+
const t = field.type;
|
|
7028
|
+
switch (t.typeId) {
|
|
7029
|
+
case TypeId.Bool:
|
|
7030
|
+
return "BOOLEAN";
|
|
7031
|
+
case TypeId.Utf8:
|
|
7032
|
+
return "VARCHAR";
|
|
7033
|
+
case TypeId.Int: {
|
|
7034
|
+
if (!(t.isSigned ?? t.signed ?? true))
|
|
7035
|
+
return null;
|
|
7036
|
+
return { 8: "TINYINT", 16: "SMALLINT", 32: "INTEGER", 64: "BIGINT" }[t.bitWidth] ?? null;
|
|
7037
|
+
}
|
|
7038
|
+
case TypeId.Float:
|
|
7039
|
+
return t.precision === 1 ? "FLOAT" : t.precision === 2 ? "DOUBLE" : null;
|
|
7040
|
+
case TypeId.Decimal:
|
|
7041
|
+
return (t.bitWidth ?? 128) === 128 ? "DECIMAL" : null;
|
|
7042
|
+
default:
|
|
7043
|
+
return null;
|
|
7044
|
+
}
|
|
7045
|
+
}
|
|
7046
|
+
|
|
6407
7047
|
// src/catalog/column-expressions.ts
|
|
6408
7048
|
var GENERATED_EXPRESSION_KEY = "vgi.column.generated.v1";
|
|
6409
7049
|
var GENERATION_KEY = "vgi.column.generation.v1";
|
|
7050
|
+
var DEFAULT_EXPRESSION_KEY = "vgi.column.default.v1";
|
|
7051
|
+
var GENERATED_TYPES = new Set(["BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "VARCHAR"]);
|
|
7052
|
+
var DEFAULT_TYPES = new Set(["BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE", "DECIMAL", "VARCHAR"]);
|
|
6410
7053
|
var PROFILE = "vgi.expression.duckdb.scalar.v1";
|
|
6411
7054
|
var MAX_BYTES = 8 * 1024 * 1024;
|
|
6412
7055
|
var base64 = (bytes) => btoa(Array.from(bytes, (value) => String.fromCharCode(value)).join(""));
|
|
@@ -6517,7 +7160,34 @@ function validateEncoded(encoded, owner) {
|
|
|
6517
7160
|
throw new Error("invalid SqlExpression record schema");
|
|
6518
7161
|
const utf8 = new TextDecoder("utf-8", { fatal: true });
|
|
6519
7162
|
textBuffers.forEach((buffer) => utf8.decode(buffer));
|
|
6520
|
-
|
|
7163
|
+
const value = decodeSqlExpression(bytes);
|
|
7164
|
+
expression(value, owner);
|
|
7165
|
+
return value.sql;
|
|
7166
|
+
}
|
|
7167
|
+
function generatedExpressionMetadata(sql, owner) {
|
|
7168
|
+
try {
|
|
7169
|
+
validateColumnExpressionSql(sql, { usingColumns: true, generated: true });
|
|
7170
|
+
} catch (error) {
|
|
7171
|
+
throw new Error(`generated expression ${JSON.stringify(sql)}: ${error.message}`);
|
|
7172
|
+
}
|
|
7173
|
+
return base64(encodeSqlExpression(sqlExpression(sql, owner)));
|
|
7174
|
+
}
|
|
7175
|
+
function sqlExpression(sql, schemaPath) {
|
|
7176
|
+
const owner = [...schemaPath];
|
|
7177
|
+
const value = {
|
|
7178
|
+
sql,
|
|
7179
|
+
profile: PROFILE,
|
|
7180
|
+
schema_path: [...owner],
|
|
7181
|
+
evaluation_context: {
|
|
7182
|
+
timezone: "UTC",
|
|
7183
|
+
collation: "binary",
|
|
7184
|
+
default_order: "asc",
|
|
7185
|
+
default_null_order: "nulls_last",
|
|
7186
|
+
preserve_insertion_order: true
|
|
7187
|
+
}
|
|
7188
|
+
};
|
|
7189
|
+
expression(value, owner);
|
|
7190
|
+
return value;
|
|
6521
7191
|
}
|
|
6522
7192
|
function validateColumnExpressions(schema, owner, allowGenerated = true) {
|
|
6523
7193
|
const type = (t) => {
|
|
@@ -6526,14 +7196,33 @@ function validateColumnExpressions(schema, owner, allowGenerated = true) {
|
|
|
6526
7196
|
if (t?.dictionary)
|
|
6527
7197
|
type(t.dictionary);
|
|
6528
7198
|
};
|
|
6529
|
-
const
|
|
7199
|
+
const topLevel = new Map;
|
|
7200
|
+
for (const f of schema.fields) {
|
|
7201
|
+
const key = String(f.name).toLowerCase();
|
|
7202
|
+
topLevel.set(key, [...topLevel.get(key) ?? [], f]);
|
|
7203
|
+
}
|
|
7204
|
+
const field = (f, top = false) => {
|
|
6530
7205
|
const metadata = f.metadata ?? new Map;
|
|
6531
7206
|
for (const key of metadata.keys()) {
|
|
6532
7207
|
if (key.startsWith("vgi.column.generated.") && key !== GENERATED_EXPRESSION_KEY || key.startsWith("vgi.column.generation.") && key !== GENERATION_KEY)
|
|
6533
7208
|
throw new Error("unknown generated metadata version");
|
|
6534
7209
|
}
|
|
7210
|
+
const where = `column ${f.name}`;
|
|
6535
7211
|
if (metadata.has("generated_expression"))
|
|
6536
|
-
throw new Error(
|
|
7212
|
+
throw new Error(`${where}: legacy generated_expression metadata is not read under vgi.v3; ` + "use generatedExpressionMetadata() (served tables are translated automatically)");
|
|
7213
|
+
if (metadata.has(DEFAULT_EXPRESSION_KEY)) {
|
|
7214
|
+
if (metadata.has("default") || metadata.has(GENERATED_EXPRESSION_KEY) || metadata.has(GENERATION_KEY))
|
|
7215
|
+
throw new Error(`${where}: canonical default conflicts with other column expression metadata`);
|
|
7216
|
+
const type = duckdbPrimitive(f);
|
|
7217
|
+
if (!type || !DEFAULT_TYPES.has(type))
|
|
7218
|
+
throw new Error(`${where}: DuckDB reads canonical defaults only for boolean, signed integer, float, decimal128 and utf8 columns`);
|
|
7219
|
+
const sql = validateEncoded(metadata.get(DEFAULT_EXPRESSION_KEY), owner);
|
|
7220
|
+
try {
|
|
7221
|
+
validateColumnExpressionSql(sql, { usingColumns: false, generated: false });
|
|
7222
|
+
} catch (error) {
|
|
7223
|
+
throw new Error(`${where}: default ${JSON.stringify(sql)}: ${error.message}`);
|
|
7224
|
+
}
|
|
7225
|
+
}
|
|
6537
7226
|
if (metadata.has(GENERATED_EXPRESSION_KEY) !== metadata.has(GENERATION_KEY))
|
|
6538
7227
|
throw new Error("generated expression and category must occur together");
|
|
6539
7228
|
if (metadata.has(GENERATED_EXPRESSION_KEY)) {
|
|
@@ -6541,13 +7230,34 @@ function validateColumnExpressions(schema, owner, allowGenerated = true) {
|
|
|
6541
7230
|
throw new Error("only VIRTUAL generated columns are supported");
|
|
6542
7231
|
if (metadata.has("default") || metadata.has("vgi.column.default.v1"))
|
|
6543
7232
|
throw new Error("generated column cannot have a default");
|
|
6544
|
-
validateEncoded(metadata.get(GENERATED_EXPRESSION_KEY), owner);
|
|
7233
|
+
const sql = validateEncoded(metadata.get(GENERATED_EXPRESSION_KEY), owner);
|
|
6545
7234
|
if (!allowGenerated)
|
|
6546
7235
|
throw new Error("generated columns unsupported by this catalog");
|
|
7236
|
+
if (!f.nullable)
|
|
7237
|
+
throw new Error(`${where}: DuckDB requires generated columns to be nullable`);
|
|
7238
|
+
const type = duckdbPrimitive(f);
|
|
7239
|
+
if (!type || !GENERATED_TYPES.has(type))
|
|
7240
|
+
throw new Error(`${where}: DuckDB generated columns must be boolean, signed integer or utf8`);
|
|
7241
|
+
let references;
|
|
7242
|
+
try {
|
|
7243
|
+
references = validateColumnExpressionSql(sql, { usingColumns: true, generated: true });
|
|
7244
|
+
} catch (error) {
|
|
7245
|
+
throw new Error(`${where}: generated expression ${JSON.stringify(sql)}: ${error.message}`);
|
|
7246
|
+
}
|
|
7247
|
+
if (top) {
|
|
7248
|
+
for (const name of references) {
|
|
7249
|
+
const matches = topLevel.get(name.toLowerCase()) ?? [];
|
|
7250
|
+
if (matches.length !== 1)
|
|
7251
|
+
throw new Error(`${where}: generated expression references a missing or ambiguous column ${name}`);
|
|
7252
|
+
const operand = duckdbPrimitive(matches[0]);
|
|
7253
|
+
if (!operand || !GENERATED_TYPES.has(operand))
|
|
7254
|
+
throw new Error(`${where}: generated expression operand ${name} must be boolean, signed integer or utf8`);
|
|
7255
|
+
}
|
|
7256
|
+
}
|
|
6547
7257
|
}
|
|
6548
7258
|
type(f.type);
|
|
6549
7259
|
};
|
|
6550
|
-
schema.fields.forEach(field);
|
|
7260
|
+
schema.fields.forEach((f) => field(f, true));
|
|
6551
7261
|
}
|
|
6552
7262
|
function validateColumnExpressionsIpc(bytes, owner, allowGenerated = true) {
|
|
6553
7263
|
validateColumnExpressions(deserializeSchema(bytes), owner, allowGenerated);
|
|
@@ -7655,14 +8365,40 @@ function deserializePlanRequest(params) {
|
|
|
7655
8365
|
projectionIds = [...raw].map(Number);
|
|
7656
8366
|
}
|
|
7657
8367
|
const asBigInt = (v) => v == null ? null : typeof v === "bigint" ? v : BigInt(Number(v));
|
|
8368
|
+
const asBytes = (v) => v == null ? null : toUint8Array2(v);
|
|
8369
|
+
const asBytesList = (v) => {
|
|
8370
|
+
if (v == null)
|
|
8371
|
+
return null;
|
|
8372
|
+
const values = Array.isArray(v) ? v : v && typeof v[Symbol.iterator] === "function" ? [...v] : [];
|
|
8373
|
+
return values.filter((entry) => entry != null).map(toUint8Array2);
|
|
8374
|
+
};
|
|
8375
|
+
const enumValue = (v, values) => {
|
|
8376
|
+
if (v == null)
|
|
8377
|
+
return null;
|
|
8378
|
+
const text = String(v);
|
|
8379
|
+
return values.includes(text) ? text : null;
|
|
8380
|
+
};
|
|
7658
8381
|
return {
|
|
7659
8382
|
bind_call: bindCall,
|
|
7660
|
-
bind_opaque_data:
|
|
8383
|
+
bind_opaque_data: asBytes(params.bind_opaque_data),
|
|
7661
8384
|
projection_ids: projectionIds,
|
|
7662
|
-
pushdown_filters:
|
|
8385
|
+
pushdown_filters: asBytes(params.pushdown_filters),
|
|
8386
|
+
join_keys: asBytesList(params.join_keys),
|
|
8387
|
+
row_limit: asBigInt(params.row_limit),
|
|
7663
8388
|
target_split_bytes: asBigInt(params.target_split_bytes),
|
|
7664
8389
|
min_splits: asBigInt(params.min_splits),
|
|
7665
|
-
|
|
8390
|
+
max_splits_per_response: asBigInt(params.max_splits_per_response),
|
|
8391
|
+
cursor: asBytes(params.cursor),
|
|
8392
|
+
refined_filters: asBytes(params.refined_filters),
|
|
8393
|
+
filters_complete: params.filters_complete == null ? true : Boolean(params.filters_complete),
|
|
8394
|
+
start_position: asBytes(params.start_position),
|
|
8395
|
+
end_position: asBytes(params.end_position),
|
|
8396
|
+
order_by_column_name: params.order_by_column_name == null ? null : String(params.order_by_column_name),
|
|
8397
|
+
order_by_direction: enumValue(params.order_by_direction, Object.values(OrderByDirection)),
|
|
8398
|
+
order_by_null_order: enumValue(params.order_by_null_order, Object.values(OrderByNullOrder)),
|
|
8399
|
+
order_by_limit: asBigInt(params.order_by_limit),
|
|
8400
|
+
tablesample_percentage: params.tablesample_percentage == null ? null : Number(params.tablesample_percentage),
|
|
8401
|
+
tablesample_seed: asBigInt(params.tablesample_seed)
|
|
7666
8402
|
};
|
|
7667
8403
|
}
|
|
7668
8404
|
function fingerprintInputs(bindCallBytes) {
|
|
@@ -7682,6 +8418,9 @@ function scanSplitRow(split, token) {
|
|
|
7682
8418
|
estimated_rows: asBigInt(split.estimatedRows),
|
|
7683
8419
|
rows_exact: split.rowsExact === true,
|
|
7684
8420
|
estimated_bytes: asBigInt(split.estimatedBytes),
|
|
8421
|
+
key_value: split.keyValue ?? null,
|
|
8422
|
+
range_index: asBigInt(split.rangeIndex),
|
|
8423
|
+
column_bounds: split.columnBounds ?? null,
|
|
7685
8424
|
partition_bounds: split.partitionBounds ?? null,
|
|
7686
8425
|
column_statistics: split.columnStatistics ?? null,
|
|
7687
8426
|
location_ids: split.locationIds ?? null,
|
|
@@ -7702,12 +8441,14 @@ function planResponseRow(result, splitBlobs) {
|
|
|
7702
8441
|
estimated_total_bytes: asBigInt(result.estimatedTotalBytes),
|
|
7703
8442
|
catalog_version: asBigInt(result.catalogVersion),
|
|
7704
8443
|
scope: result.scope ?? "catalog",
|
|
7705
|
-
locations: null,
|
|
7706
|
-
|
|
7707
|
-
|
|
8444
|
+
locations: result.locations ?? null,
|
|
8445
|
+
key_grouping: result.keyGrouping ?? null,
|
|
8446
|
+
range_partitioning: result.rangePartitioning ?? null,
|
|
8447
|
+
partitioning: result.partitioning ?? null,
|
|
8448
|
+
sort_order: result.sortOrder ?? null,
|
|
7708
8449
|
cache_max_age_seconds: asBigInt(result.cacheMaxAgeSeconds),
|
|
7709
|
-
start_position:
|
|
7710
|
-
end_position:
|
|
8450
|
+
start_position: result.startPosition ?? null,
|
|
8451
|
+
end_position: result.endPosition ?? null
|
|
7711
8452
|
};
|
|
7712
8453
|
}
|
|
7713
8454
|
|
|
@@ -8658,6 +9399,338 @@ var encodeSchemaInfo = (v) => encodeASD(SchemaInfoSchema, v);
|
|
|
8658
9399
|
var encodeTableInfo = (v) => encodeASD(TableInfoSchema, v);
|
|
8659
9400
|
var encodeViewInfo = (v) => encodeASD(ViewInfoSchema, v);
|
|
8660
9401
|
|
|
9402
|
+
// src/catalog/constraints.ts
|
|
9403
|
+
var CONSTRAINT_RECORDS_READ = "vgi.constraint.records.read.v1";
|
|
9404
|
+
var ROW_SCALAR_EXPRESSION = "vgi.expression.duckdb.scalar.v1";
|
|
9405
|
+
var CONSTRAINT_CREATE = "vgi.constraint.create.v1";
|
|
9406
|
+
var CONSTRAINT_MUTATE = "vgi.constraint.mutate.v1";
|
|
9407
|
+
var CONSTRAINT_ENFORCE = "vgi.constraint.enforce.v1";
|
|
9408
|
+
var TRANSACTION_DDL = "vgi.transaction.ddl.v1";
|
|
9409
|
+
var CHECK_CONTEXT = {
|
|
9410
|
+
timezone: "UTC",
|
|
9411
|
+
collation: "binary",
|
|
9412
|
+
default_order: "asc",
|
|
9413
|
+
default_null_order: "nulls_last",
|
|
9414
|
+
preserve_insertion_order: true
|
|
9415
|
+
};
|
|
9416
|
+
function identifier(value, what) {
|
|
9417
|
+
if (typeof value !== "string" || !value || value.includes("\x00") || new TextEncoder().encode(value).length > 4096)
|
|
9418
|
+
throw new Error(`${what} must be a nonempty identifier without NUL (at most 4096 bytes)`);
|
|
9419
|
+
}
|
|
9420
|
+
function checkPaths(paths, what, topLevelOnly) {
|
|
9421
|
+
if (paths.length > 1024)
|
|
9422
|
+
throw new Error(`${what}: too many column paths`);
|
|
9423
|
+
const seen = new Set;
|
|
9424
|
+
for (const path of paths) {
|
|
9425
|
+
if (path.length === 0 || path.length > 64)
|
|
9426
|
+
throw new Error(`${what}: column path must have 1..64 components`);
|
|
9427
|
+
if (topLevelOnly && path.length !== 1)
|
|
9428
|
+
throw new Error(`${what}: DuckDB reads nested column paths only for NOT_NULL; name a top-level column`);
|
|
9429
|
+
path.forEach((part) => identifier(part, `${what}: column path component`));
|
|
9430
|
+
const key = JSON.stringify(path);
|
|
9431
|
+
if (seen.has(key))
|
|
9432
|
+
throw new Error(`${what}: duplicate column path ${path.join(".")}`);
|
|
9433
|
+
seen.add(key);
|
|
9434
|
+
}
|
|
9435
|
+
}
|
|
9436
|
+
var KNOWN = {
|
|
9437
|
+
read: new Set([CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION, "vgi.index.definition.read.v1"]),
|
|
9438
|
+
ddl: new Set([CONSTRAINT_CREATE, CONSTRAINT_MUTATE, "vgi.index.definition.create.v1", "vgi.index.drop.v1"]),
|
|
9439
|
+
write: new Set([CONSTRAINT_ENFORCE]),
|
|
9440
|
+
transaction: new Set([TRANSACTION_DDL])
|
|
9441
|
+
};
|
|
9442
|
+
var REQUIRES = {
|
|
9443
|
+
[ROW_SCALAR_EXPRESSION]: [CONSTRAINT_RECORDS_READ],
|
|
9444
|
+
[CONSTRAINT_CREATE]: [CONSTRAINT_RECORDS_READ, CONSTRAINT_ENFORCE],
|
|
9445
|
+
[CONSTRAINT_MUTATE]: [CONSTRAINT_RECORDS_READ],
|
|
9446
|
+
[CONSTRAINT_ENFORCE]: [CONSTRAINT_RECORDS_READ],
|
|
9447
|
+
"vgi.index.definition.create.v1": ["vgi.index.definition.read.v1"],
|
|
9448
|
+
"vgi.index.drop.v1": ["vgi.index.definition.read.v1"]
|
|
9449
|
+
};
|
|
9450
|
+
var CATEGORIES = ["read", "ddl", "write", "transaction"];
|
|
9451
|
+
function catalogCapabilities(init = {}) {
|
|
9452
|
+
return {
|
|
9453
|
+
read: [...new Set(init.read ?? [])].sort(),
|
|
9454
|
+
ddl: [...new Set(init.ddl ?? [])].sort(),
|
|
9455
|
+
write: [...new Set(init.write ?? [])].sort(),
|
|
9456
|
+
transaction: [...new Set(init.transaction ?? [])].sort()
|
|
9457
|
+
};
|
|
9458
|
+
}
|
|
9459
|
+
function offeredCatalog(clientCapabilities) {
|
|
9460
|
+
if (clientCapabilities == null)
|
|
9461
|
+
return null;
|
|
9462
|
+
const client = clientCapabilities instanceof Uint8Array ? decodeASD(ClientCapabilitiesSchema, clientCapabilities) : clientCapabilities;
|
|
9463
|
+
return client.catalog == null ? null : decodeCatalogCapabilities(client.catalog);
|
|
9464
|
+
}
|
|
9465
|
+
function selectCatalogCapabilities(available, clientCapabilities, supportsTransactions = false) {
|
|
9466
|
+
const offered = offeredCatalog(clientCapabilities);
|
|
9467
|
+
if (offered == null)
|
|
9468
|
+
return catalogCapabilities();
|
|
9469
|
+
const chosen = new Set;
|
|
9470
|
+
for (const category of CATEGORIES)
|
|
9471
|
+
for (const p of available[category] ?? [])
|
|
9472
|
+
if (offered[category]?.includes(p))
|
|
9473
|
+
chosen.add(p);
|
|
9474
|
+
if (!supportsTransactions)
|
|
9475
|
+
chosen.delete(TRANSACTION_DDL);
|
|
9476
|
+
for (let changed = true;changed; ) {
|
|
9477
|
+
changed = false;
|
|
9478
|
+
for (const p of [...chosen])
|
|
9479
|
+
if ((REQUIRES[p] ?? []).some((r) => !chosen.has(r))) {
|
|
9480
|
+
chosen.delete(p);
|
|
9481
|
+
changed = true;
|
|
9482
|
+
}
|
|
9483
|
+
}
|
|
9484
|
+
const pick = (category) => (available[category] ?? []).filter((p) => chosen.has(p));
|
|
9485
|
+
return catalogCapabilities({ read: pick("read"), ddl: pick("ddl"), write: pick("write"), transaction: pick("transaction") });
|
|
9486
|
+
}
|
|
9487
|
+
function capabilitiesEmpty(caps) {
|
|
9488
|
+
return caps == null || CATEGORIES.every((c) => (caps[c] ?? []).length === 0);
|
|
9489
|
+
}
|
|
9490
|
+
function readConstraintRecord(bytes) {
|
|
9491
|
+
const info = decodeASD(ConstraintInfoSchema, bytes);
|
|
9492
|
+
const ref = decodeASD(CatalogObjectRefSchema, info.ref);
|
|
9493
|
+
const def = decodeASD(ConstraintDefinitionSchema, info.definition);
|
|
9494
|
+
const fk = def.foreign_key == null ? null : decodeASD(ForeignKeyDefinitionSchema, def.foreign_key);
|
|
9495
|
+
const target = fk == null ? null : decodeASD(CatalogObjectRefSchema, fk.referenced_table);
|
|
9496
|
+
const targetKey = info.referenced_constraint == null ? null : decodeASD(CatalogObjectRefSchema, info.referenced_constraint);
|
|
9497
|
+
return {
|
|
9498
|
+
schemaPath: [...ref.schema_path],
|
|
9499
|
+
table: ref.owner_table ?? "",
|
|
9500
|
+
id: ref.name,
|
|
9501
|
+
kind: def.kind,
|
|
9502
|
+
columns: [...def.column_paths].map((p) => [...p]),
|
|
9503
|
+
enforcement: info.enforcement,
|
|
9504
|
+
validation: info.validation,
|
|
9505
|
+
declaredName: def.declared_name ?? null,
|
|
9506
|
+
checkSql: def.check_expression == null ? null : decodeASD(SqlExpressionSchema, def.check_expression).sql,
|
|
9507
|
+
references: fk == null || target == null ? null : {
|
|
9508
|
+
schemaPath: [...target.schema_path],
|
|
9509
|
+
table: target.name,
|
|
9510
|
+
columns: [...fk.referenced_column_paths].map((p) => [...p]),
|
|
9511
|
+
constraintId: targetKey?.name ?? null,
|
|
9512
|
+
constraintTable: targetKey?.owner_table ?? null,
|
|
9513
|
+
constraintSchemaPath: targetKey == null ? null : [...targetKey.schema_path],
|
|
9514
|
+
match: fk.match,
|
|
9515
|
+
onUpdate: fk.on_update,
|
|
9516
|
+
onDelete: fk.on_delete
|
|
9517
|
+
}
|
|
9518
|
+
};
|
|
9519
|
+
}
|
|
9520
|
+
function fieldsByExactName(fields, name) {
|
|
9521
|
+
const out = [];
|
|
9522
|
+
fields.forEach((f, i) => {
|
|
9523
|
+
if (f.name === name)
|
|
9524
|
+
out.push(i);
|
|
9525
|
+
});
|
|
9526
|
+
return out;
|
|
9527
|
+
}
|
|
9528
|
+
function validateTableConstraints(table, schemaPath, fields, constraints) {
|
|
9529
|
+
if (constraints.length > 1024)
|
|
9530
|
+
throw new Error(`Table '${table}': too many constraints (at most 1024)`);
|
|
9531
|
+
const rowIds = fields.map((f, i) => isRowIdField(f) ? i : -1).filter((i) => i >= 0);
|
|
9532
|
+
if (rowIds.length > 1)
|
|
9533
|
+
throw new Error(`Table '${table}': at most one column may carry is_row_id`);
|
|
9534
|
+
const rowId = rowIds[0] ?? -1;
|
|
9535
|
+
const records = [];
|
|
9536
|
+
const required = new Set;
|
|
9537
|
+
const ids = new Set;
|
|
9538
|
+
const labels = new Set;
|
|
9539
|
+
let primaryKeys = 0;
|
|
9540
|
+
for (const bytes of constraints) {
|
|
9541
|
+
let record;
|
|
9542
|
+
try {
|
|
9543
|
+
record = readConstraintRecord(bytes);
|
|
9544
|
+
} catch (error) {
|
|
9545
|
+
throw new Error(`Table '${table}': undecodable constraint record: ${error.message}`);
|
|
9546
|
+
}
|
|
9547
|
+
const where = `Table '${table}': constraint '${record.id}'`;
|
|
9548
|
+
const fail = (message) => {
|
|
9549
|
+
throw new Error(`${where}: ${message}`);
|
|
9550
|
+
};
|
|
9551
|
+
if (schemaPath.length !== 1 || record.schemaPath.length !== 1 || record.schemaPath[0] !== schemaPath[0] || record.table !== table)
|
|
9552
|
+
fail(`belongs to ${JSON.stringify(record.schemaPath)}.${record.table || "?"}, not the serving table ` + `${JSON.stringify([...schemaPath])}.${table} (DuckDB reads only one-component schema paths)`);
|
|
9553
|
+
if (ids.has(record.id))
|
|
9554
|
+
fail("duplicate constraint id");
|
|
9555
|
+
ids.add(record.id);
|
|
9556
|
+
if (record.declaredName != null) {
|
|
9557
|
+
const label = record.declaredName.toLowerCase();
|
|
9558
|
+
if (labels.has(label))
|
|
9559
|
+
fail(`duplicate declared name '${record.declaredName}'`);
|
|
9560
|
+
labels.add(label);
|
|
9561
|
+
}
|
|
9562
|
+
if (record.enforcement !== "ENFORCED" || record.validation !== "ALL_ROWS")
|
|
9563
|
+
fail(`is ${record.enforcement}/${record.validation}; DuckDB accepts only ENFORCED + ALL_ROWS records`);
|
|
9564
|
+
try {
|
|
9565
|
+
checkPaths(record.columns, record.kind, record.kind !== "NOT_NULL");
|
|
9566
|
+
} catch (error) {
|
|
9567
|
+
fail(error.message);
|
|
9568
|
+
}
|
|
9569
|
+
const resolveTop = (path) => {
|
|
9570
|
+
const matches = fieldsByExactName(fields, path[0]);
|
|
9571
|
+
if (matches.length !== 1 || matches[0] === rowId)
|
|
9572
|
+
fail(`column path ${path.join(".")} names a missing, ambiguous or row-id column`);
|
|
9573
|
+
return matches[0];
|
|
9574
|
+
};
|
|
9575
|
+
switch (record.kind) {
|
|
9576
|
+
case "CHECK": {
|
|
9577
|
+
if (record.checkSql == null)
|
|
9578
|
+
fail("CHECK without an expression");
|
|
9579
|
+
validateCheckRecord(bytes, where, schemaPath, fields, rowId);
|
|
9580
|
+
break;
|
|
9581
|
+
}
|
|
9582
|
+
case "NOT_NULL": {
|
|
9583
|
+
if (record.columns.length !== 1)
|
|
9584
|
+
fail("NOT_NULL requires exactly one column path");
|
|
9585
|
+
const path = record.columns[0];
|
|
9586
|
+
let field = fields[resolveTop(path)];
|
|
9587
|
+
for (let depth = 1;depth < path.length; depth++) {
|
|
9588
|
+
const children = ordinaryStructChildren(field);
|
|
9589
|
+
if (!children)
|
|
9590
|
+
fail(`column path ${path.join(".")} must traverse ordinary STRUCT fields`);
|
|
9591
|
+
const matches = fieldsByExactName(children, path[depth]);
|
|
9592
|
+
if (matches.length !== 1)
|
|
9593
|
+
fail(`column path ${path.join(".")} names a missing or ambiguous nested field`);
|
|
9594
|
+
field = children[matches[0]];
|
|
9595
|
+
}
|
|
9596
|
+
if (path.length === 1 && isGeneratedField(field))
|
|
9597
|
+
fail(`column ${path[0]} is a generated column, which DuckDB requires to be nullable`);
|
|
9598
|
+
required.add(JSON.stringify(path));
|
|
9599
|
+
break;
|
|
9600
|
+
}
|
|
9601
|
+
case "PRIMARY_KEY":
|
|
9602
|
+
case "UNIQUE": {
|
|
9603
|
+
for (const path of record.columns) {
|
|
9604
|
+
const index = resolveTop(path);
|
|
9605
|
+
if (record.kind === "PRIMARY_KEY" && isGeneratedField(fields[index]))
|
|
9606
|
+
fail(`PRIMARY KEY column ${path[0]} is a generated column, which DuckDB requires to be nullable`);
|
|
9607
|
+
}
|
|
9608
|
+
if (record.kind === "PRIMARY_KEY") {
|
|
9609
|
+
if (++primaryKeys > 1)
|
|
9610
|
+
fail("a table may have only one PRIMARY KEY");
|
|
9611
|
+
for (const path of record.columns)
|
|
9612
|
+
required.add(JSON.stringify(path));
|
|
9613
|
+
}
|
|
9614
|
+
break;
|
|
9615
|
+
}
|
|
9616
|
+
case "FOREIGN_KEY": {
|
|
9617
|
+
record.columns.forEach(resolveTop);
|
|
9618
|
+
const ref = record.references;
|
|
9619
|
+
if (ref == null || ref.constraintId == null)
|
|
9620
|
+
fail("FOREIGN_KEY requires a referenced table and referenced constraint");
|
|
9621
|
+
if (ref.schemaPath.length !== 1 || ref.schemaPath[0] !== schemaPath[0] || JSON.stringify(ref.constraintSchemaPath) !== JSON.stringify(ref.schemaPath) || ref.constraintTable !== ref.table)
|
|
9622
|
+
fail("DuckDB reads only foreign keys to an identified key of a table in the same schema");
|
|
9623
|
+
if (ref.columns.length !== record.columns.length)
|
|
9624
|
+
fail("foreign key arity mismatch");
|
|
9625
|
+
try {
|
|
9626
|
+
checkPaths(ref.columns, "FOREIGN_KEY referenced", true);
|
|
9627
|
+
} catch (error) {
|
|
9628
|
+
fail(error.message);
|
|
9629
|
+
}
|
|
9630
|
+
if (ref.match !== undefined && ref.match !== "SIMPLE")
|
|
9631
|
+
fail(`MATCH ${ref.match} is unsupported; DuckDB reads only MATCH SIMPLE`);
|
|
9632
|
+
for (const action of [ref.onUpdate, ref.onDelete])
|
|
9633
|
+
if (action !== undefined && action !== "NO_ACTION" && action !== "RESTRICT")
|
|
9634
|
+
fail(`referential action ${action} is unsupported; DuckDB reads only NO_ACTION or RESTRICT`);
|
|
9635
|
+
break;
|
|
9636
|
+
}
|
|
9637
|
+
default:
|
|
9638
|
+
fail(`unknown constraint kind ${String(record.kind)}`);
|
|
9639
|
+
}
|
|
9640
|
+
records.push(record);
|
|
9641
|
+
}
|
|
9642
|
+
return { records, required };
|
|
9643
|
+
}
|
|
9644
|
+
function validateCheckRecord(bytes, where, schemaPath, fields, rowId) {
|
|
9645
|
+
const info = decodeASD(ConstraintInfoSchema, bytes);
|
|
9646
|
+
const def = decodeASD(ConstraintDefinitionSchema, info.definition);
|
|
9647
|
+
const expression = decodeASD(SqlExpressionSchema, def.check_expression);
|
|
9648
|
+
const fail = (message) => {
|
|
9649
|
+
throw new Error(`${where}: ${message}`);
|
|
9650
|
+
};
|
|
9651
|
+
if (expression.profile !== ROW_SCALAR_EXPRESSION)
|
|
9652
|
+
fail(`unsupported CHECK expression profile ${expression.profile}`);
|
|
9653
|
+
if (JSON.stringify([...expression.schema_path]) !== JSON.stringify([...schemaPath]))
|
|
9654
|
+
fail("CHECK expression belongs to another schema");
|
|
9655
|
+
const context = expression.evaluation_context ?? {};
|
|
9656
|
+
for (const [key, value] of Object.entries(CHECK_CONTEXT))
|
|
9657
|
+
if (context[key] !== value)
|
|
9658
|
+
fail(`unsupported CHECK evaluation context (${key} must be ${String(value)})`);
|
|
9659
|
+
try {
|
|
9660
|
+
validateNumericCheckSql(expression.sql, (name) => {
|
|
9661
|
+
const lower = name.toLowerCase();
|
|
9662
|
+
const matches = fields.map((f, i) => f.name.toLowerCase() === lower ? i : -1).filter((i) => i >= 0);
|
|
9663
|
+
if (matches.length > 1)
|
|
9664
|
+
throw new Error(`ambiguous CHECK column reference ${name}`);
|
|
9665
|
+
if (matches.length === 0 || matches[0] === rowId)
|
|
9666
|
+
throw new Error(`CHECK references a missing or row-id column ${name}`);
|
|
9667
|
+
const column = fields[matches[0]];
|
|
9668
|
+
if (column.metadata.has("ARROW:extension:name"))
|
|
9669
|
+
throw new Error(`CHECK operand ${name} has an extension type`);
|
|
9670
|
+
if (isGeneratedField(column))
|
|
9671
|
+
throw new Error(`CHECK operand ${name} is a generated column`);
|
|
9672
|
+
const type = duckdbPrimitive(column);
|
|
9673
|
+
if (!type || !["TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE"].includes(type))
|
|
9674
|
+
throw new Error(`CHECK requires primitive signed numeric columns; ${name} is not one`);
|
|
9675
|
+
});
|
|
9676
|
+
} catch (error) {
|
|
9677
|
+
fail(`${error.message} (CHECK SQL: ${expression.sql})`);
|
|
9678
|
+
}
|
|
9679
|
+
}
|
|
9680
|
+
function servedConstraintFields(fields, required) {
|
|
9681
|
+
const rewrite = (list, prefix) => {
|
|
9682
|
+
let changed = false;
|
|
9683
|
+
const out = list.map((f) => {
|
|
9684
|
+
if (prefix.length === 0 && isRowIdField(f))
|
|
9685
|
+
return f;
|
|
9686
|
+
const path = [...prefix, f.name];
|
|
9687
|
+
const nullable = !required.has(JSON.stringify(path));
|
|
9688
|
+
const children = ordinaryStructChildren(f);
|
|
9689
|
+
const newChildren = children ? rewrite(children, path) : null;
|
|
9690
|
+
if (nullable === f.nullable && (newChildren == null || newChildren === children))
|
|
9691
|
+
return f;
|
|
9692
|
+
changed = true;
|
|
9693
|
+
const type = newChildren && newChildren !== children ? struct2(newChildren) : f.type;
|
|
9694
|
+
return field2(f.name, type, nullable, new Map(f.metadata));
|
|
9695
|
+
});
|
|
9696
|
+
return changed ? out : list;
|
|
9697
|
+
};
|
|
9698
|
+
return rewrite(fields, []);
|
|
9699
|
+
}
|
|
9700
|
+
function translateLegacyGenerated(fields, owner, table) {
|
|
9701
|
+
let changed = false;
|
|
9702
|
+
const out = fields.map((f) => {
|
|
9703
|
+
const sql = f.metadata.get("generated_expression");
|
|
9704
|
+
if (sql === undefined)
|
|
9705
|
+
return f;
|
|
9706
|
+
if (f.metadata.has(GENERATED_EXPRESSION_KEY) || f.metadata.has(GENERATION_KEY))
|
|
9707
|
+
throw new Error(`Table '${table}': column ${f.name} carries both legacy generated_expression and canonical generated metadata`);
|
|
9708
|
+
const metadata = new Map(f.metadata);
|
|
9709
|
+
metadata.delete("generated_expression");
|
|
9710
|
+
metadata.set(GENERATED_EXPRESSION_KEY, generatedExpressionMetadata(sql, [...owner]));
|
|
9711
|
+
metadata.set(GENERATION_KEY, "virtual");
|
|
9712
|
+
changed = true;
|
|
9713
|
+
return field2(f.name, f.type, f.nullable, metadata);
|
|
9714
|
+
});
|
|
9715
|
+
return changed ? out : fields;
|
|
9716
|
+
}
|
|
9717
|
+
function servedTableSchema(table, schemaPath, schema, constraints) {
|
|
9718
|
+
let fields = translateLegacyGenerated(schema.fields, schemaPath, table);
|
|
9719
|
+
const { required } = validateTableConstraints(table, schemaPath, fields, constraints);
|
|
9720
|
+
fields = servedConstraintFields(fields, required);
|
|
9721
|
+
return fields === schema.fields ? schema : schema2(fields, schema.metadata);
|
|
9722
|
+
}
|
|
9723
|
+
function servedTableInfo(info) {
|
|
9724
|
+
if (!info.columns || info.columns.length === 0) {
|
|
9725
|
+
if ((info.constraints ?? []).length)
|
|
9726
|
+
throw new Error(`Table '${info.name}': constraints on a table without columns`);
|
|
9727
|
+
return info;
|
|
9728
|
+
}
|
|
9729
|
+
const schema = deserializeSchema(info.columns);
|
|
9730
|
+
const served = servedTableSchema(info.name, info.schema_path, schema, info.constraints ?? []);
|
|
9731
|
+
return served === schema ? info : { ...info, columns: serializeSchema(served) };
|
|
9732
|
+
}
|
|
9733
|
+
|
|
8661
9734
|
// src/catalog/column-metadata.ts
|
|
8662
9735
|
function scalarText(value) {
|
|
8663
9736
|
for (let i = 0;i < value.length; i++) {
|
|
@@ -8794,9 +9867,21 @@ function validateTableInfoColumns(info) {
|
|
|
8794
9867
|
validateColumnExpressionsIpc(info.columns, info.schema_path);
|
|
8795
9868
|
}
|
|
8796
9869
|
}
|
|
9870
|
+
function servedValidatedTableInfo(info) {
|
|
9871
|
+
if (info.columns.length)
|
|
9872
|
+
validateColumnMetadataIpc(info.columns);
|
|
9873
|
+
const served = servedTableInfo(info);
|
|
9874
|
+
if (served.columns.length) {
|
|
9875
|
+
try {
|
|
9876
|
+
validateColumnExpressionsIpc(served.columns, served.schema_path);
|
|
9877
|
+
} catch (error) {
|
|
9878
|
+
throw new Error(`Table '${served.name}': ${error.message}`);
|
|
9879
|
+
}
|
|
9880
|
+
}
|
|
9881
|
+
return served;
|
|
9882
|
+
}
|
|
8797
9883
|
function encodeValidatedTableInfo(info) {
|
|
8798
|
-
|
|
8799
|
-
return encodeTableInfo(info);
|
|
9884
|
+
return encodeTableInfo(servedValidatedTableInfo(info));
|
|
8800
9885
|
}
|
|
8801
9886
|
|
|
8802
9887
|
// src/protocol/handlers/catalog/admin.ts
|
|
@@ -8818,20 +9903,6 @@ function catalogStringMap(raw) {
|
|
|
8818
9903
|
return result;
|
|
8819
9904
|
}
|
|
8820
9905
|
|
|
8821
|
-
// src/catalog/constraints.ts
|
|
8822
|
-
var CONSTRAINT_RECORDS_READ = "vgi.constraint.records.read.v1";
|
|
8823
|
-
var ROW_SCALAR_EXPRESSION = "vgi.expression.duckdb.scalar.v1";
|
|
8824
|
-
function selectReadProfiles(available, clientCapabilities) {
|
|
8825
|
-
if (clientCapabilities == null || available.length === 0)
|
|
8826
|
-
return [];
|
|
8827
|
-
const client = decodeASD(ClientCapabilitiesSchema, clientCapabilities);
|
|
8828
|
-
const offered = client.catalog == null ? [] : decodeCatalogCapabilities(client.catalog).read;
|
|
8829
|
-
const selected = available.filter((p) => offered.includes(p));
|
|
8830
|
-
if (!selected.includes(CONSTRAINT_RECORDS_READ))
|
|
8831
|
-
return selected.filter((p) => p !== ROW_SCALAR_EXPRESSION).sort();
|
|
8832
|
-
return selected.sort();
|
|
8833
|
-
}
|
|
8834
|
-
|
|
8835
9906
|
// src/protocol/handlers/catalog/contents.ts
|
|
8836
9907
|
import { ExternalRef as ExternalRef2 } from "@query-farm/vgi-rpc";
|
|
8837
9908
|
|
|
@@ -8842,12 +9913,10 @@ import { ExternalRef, publishExternalResult, resolveExternalLocation } from "@qu
|
|
|
8842
9913
|
var schemaPathKey = (path) => JSON.stringify(path.map((part) => part.toLowerCase()));
|
|
8843
9914
|
var CATALOG_STREAM_KINDS = ["schemas", "tables", "views", "functions", "macros", "indexes"];
|
|
8844
9915
|
function encodeCatalogStreams(inventory) {
|
|
8845
|
-
|
|
8846
|
-
for (const table of schema.tables)
|
|
8847
|
-
validateTableInfoColumns(table);
|
|
9916
|
+
const tables = inventory.flatMap((s) => s.tables.map(servedValidatedTableInfo));
|
|
8848
9917
|
const streams = {
|
|
8849
9918
|
schemas: encodeASDCollection(SchemaInfoSchema, inventory.map((s) => s.schema)),
|
|
8850
|
-
tables: encodeASDCollection(TableInfoSchema,
|
|
9919
|
+
tables: encodeASDCollection(TableInfoSchema, tables),
|
|
8851
9920
|
views: encodeASDCollection(ViewInfoSchema, inventory.flatMap((s) => s.views)),
|
|
8852
9921
|
functions: encodeASDCollection(FunctionInfoSchema, inventory.flatMap((s) => [...s.scalar_functions, ...s.aggregate_functions, ...s.table_functions])),
|
|
8853
9922
|
macros: encodeASDCollection(MacroInfoSchema, inventory.flatMap((s) => [...s.scalar_macros, ...s.table_macros])),
|
|
@@ -9915,13 +10984,10 @@ function catalogAdminHandlers(getCatalog, signingKey) {
|
|
|
9915
10984
|
}
|
|
9916
10985
|
const clientCapabilities = innerParams.client_capabilities == null ? null : toUint8Array(innerParams.client_capabilities);
|
|
9917
10986
|
const result = await cat.attach(innerParams.name, optionsDict, innerParams.data_version_spec ?? null, innerParams.implementation_version ?? null, clientCapabilities);
|
|
9918
|
-
|
|
9919
|
-
|
|
9920
|
-
|
|
9921
|
-
result.selected_capabilities = encodeCatalogCapabilities(
|
|
9922
|
-
...chosen,
|
|
9923
|
-
read: selectReadProfiles(available.read, clientCapabilities)
|
|
9924
|
-
});
|
|
10987
|
+
const advertised = result.catalog_capabilities != null ? decodeCatalogCapabilities(toUint8Array(result.catalog_capabilities)) : await cat.catalogCapabilities(toUint8Array(result.attach_opaque_data));
|
|
10988
|
+
if (!capabilitiesEmpty(advertised)) {
|
|
10989
|
+
result.catalog_capabilities = encodeCatalogCapabilities(catalogCapabilities(advertised));
|
|
10990
|
+
result.selected_capabilities = encodeCatalogCapabilities(selectCatalogCapabilities(advertised, clientCapabilities, result.supports_transactions ?? false));
|
|
9925
10991
|
}
|
|
9926
10992
|
const sealedAttach = await sealAttach(toUint8Array(result.attach_opaque_data), ctx?.auth, signingKey);
|
|
9927
10993
|
return wrapResult(buildCatalogAttachResult({
|
|
@@ -10057,27 +11123,39 @@ import { MethodNotImplementedError as MethodNotImplementedError4 } from "@query-
|
|
|
10057
11123
|
|
|
10058
11124
|
// src/catalog/unconstrained-columns.ts
|
|
10059
11125
|
import { MethodNotImplementedError as MethodNotImplementedError3 } from "@query-farm/vgi-rpc";
|
|
10060
|
-
function
|
|
10061
|
-
const
|
|
11126
|
+
function requireCreateColumns(columns, constraintDefinitions = []) {
|
|
11127
|
+
const required = new Set;
|
|
11128
|
+
for (const bytes of constraintDefinitions) {
|
|
11129
|
+
let def;
|
|
11130
|
+
try {
|
|
11131
|
+
def = decodeConstraintDefinition(bytes);
|
|
11132
|
+
} catch (error) {
|
|
11133
|
+
throw new Error(`catalog_table_create: undecodable constraint definition: ${error.message}`);
|
|
11134
|
+
}
|
|
11135
|
+
if (def.kind === "NOT_NULL" || def.kind === "PRIMARY_KEY")
|
|
11136
|
+
for (const path of def.column_paths)
|
|
11137
|
+
required.add(JSON.stringify([...path]));
|
|
11138
|
+
}
|
|
11139
|
+
const visit = (field, path, depth) => {
|
|
10062
11140
|
if (depth > 64)
|
|
10063
11141
|
throw new MethodNotImplementedError3("catalog_table_create: column nesting exceeds supported depth");
|
|
10064
|
-
if (
|
|
11142
|
+
if (depth === 0 && field.metadata?.has("is_row_id"))
|
|
10065
11143
|
return;
|
|
10066
11144
|
for (const key of field.metadata?.keys() ?? []) {
|
|
10067
11145
|
if (key === "ARROW:extension:name" || key.startsWith("vgi.logical_type.")) {
|
|
10068
11146
|
throw new MethodNotImplementedError3("catalog_table_create: logical column types require negotiation");
|
|
10069
11147
|
}
|
|
10070
11148
|
}
|
|
10071
|
-
if (!field.nullable) {
|
|
10072
|
-
throw new MethodNotImplementedError3(
|
|
11149
|
+
if (!field.nullable && !required.has(JSON.stringify(path))) {
|
|
11150
|
+
throw new MethodNotImplementedError3(`catalog_table_create: column ${path.join(".")} is non-nullable but no NOT_NULL/PRIMARY_KEY definition names it`);
|
|
10073
11151
|
}
|
|
10074
11152
|
if (isStruct(field.type)) {
|
|
10075
11153
|
for (const child of field.type.children)
|
|
10076
|
-
visit(child,
|
|
11154
|
+
visit(child, [...path, child.name], depth + 1);
|
|
10077
11155
|
}
|
|
10078
11156
|
};
|
|
10079
11157
|
for (const field of deserializeSchema(columns).fields)
|
|
10080
|
-
visit(field,
|
|
11158
|
+
visit(field, [field.name], 0);
|
|
10081
11159
|
}
|
|
10082
11160
|
|
|
10083
11161
|
// src/protocol/handlers/catalog/table.ts
|
|
@@ -10099,19 +11177,57 @@ function catalogTableHandlers(getCatalog, signingKey) {
|
|
|
10099
11177
|
const catalogTableCreate = catalogHandler(signingKey, async (params) => {
|
|
10100
11178
|
if (params.constraint_definitions == null)
|
|
10101
11179
|
throw new Error("constraint_definitions is required");
|
|
10102
|
-
|
|
10103
|
-
throw new MethodNotImplementedError4("catalog_table_create: canonical constraint enforcement is not supported");
|
|
10104
|
-
}
|
|
11180
|
+
const definitions = Array.from(params.constraint_definitions, (d) => toUint8Array(d));
|
|
10105
11181
|
if (params.comment != null || params.tags != null || params.options != null || params.layout != null) {
|
|
10106
11182
|
throw new MethodNotImplementedError4("catalog_table_create: table metadata/options/layout profiles are not supported");
|
|
10107
11183
|
}
|
|
11184
|
+
const attach = toUint8Array(params.attach_opaque_data);
|
|
11185
|
+
const cat = getCatalog();
|
|
11186
|
+
if (definitions.length > 0) {
|
|
11187
|
+
const caps = await cat.catalogCapabilities(attach);
|
|
11188
|
+
if (caps != null && !(caps.ddl.includes(CONSTRAINT_CREATE) && caps.write.includes(CONSTRAINT_ENFORCE))) {
|
|
11189
|
+
throw new MethodNotImplementedError4("catalog_table_create: this catalog does not enforce constraints (NOT NULL, PRIMARY KEY, UNIQUE, CHECK, " + "FOREIGN KEY); it advertises neither vgi.constraint.create.v1 nor vgi.constraint.enforce.v1");
|
|
11190
|
+
}
|
|
11191
|
+
}
|
|
10108
11192
|
validateColumnMetadataIpc(toUint8Array(params.columns));
|
|
10109
11193
|
validateColumnExpressionsIpc(toUint8Array(params.columns), params.schema_path);
|
|
10110
|
-
|
|
10111
|
-
|
|
10112
|
-
await cat.tableCreate(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, toUint8Array(params.columns), params.on_conflict, [], params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
|
|
11194
|
+
requireCreateColumns(toUint8Array(params.columns), definitions);
|
|
11195
|
+
await cat.tableCreate(attach, params.schema_path, params.name, toUint8Array(params.columns), params.on_conflict, definitions, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
|
|
10113
11196
|
return {};
|
|
10114
11197
|
});
|
|
11198
|
+
const catalogTableConstraintsApply = catalogHandler(signingKey, async (params) => {
|
|
11199
|
+
const attach = toUint8Array(params.attach_opaque_data);
|
|
11200
|
+
const cat = getCatalog();
|
|
11201
|
+
const caps = await cat.catalogCapabilities(attach);
|
|
11202
|
+
if (caps != null && !caps.ddl.includes(CONSTRAINT_MUTATE)) {
|
|
11203
|
+
throw new MethodNotImplementedError4("catalog_table_constraints_apply: this catalog does not advertise vgi.constraint.mutate.v1");
|
|
11204
|
+
}
|
|
11205
|
+
const table = toUint8Array(params.table);
|
|
11206
|
+
const expected = toUint8Array(params.expected_revision);
|
|
11207
|
+
const changes = Array.from(params.changes, (c) => toUint8Array(c));
|
|
11208
|
+
if (expected.length === 0 || changes.length === 0)
|
|
11209
|
+
throw new Error("catalog_table_constraints_apply: empty revision or change list");
|
|
11210
|
+
const snapshot = await cat.tableConstraintsApply({
|
|
11211
|
+
attach_opaque_data: attach,
|
|
11212
|
+
table,
|
|
11213
|
+
expected_revision: expected,
|
|
11214
|
+
changes,
|
|
11215
|
+
transaction_opaque_data: params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : null
|
|
11216
|
+
});
|
|
11217
|
+
const want = decodeCatalogObjectRef(table);
|
|
11218
|
+
const got = decodeCatalogObjectRef(toUint8Array(snapshot.table));
|
|
11219
|
+
if (got.name !== want.name || JSON.stringify([...got.schema_path]) !== JSON.stringify([...want.schema_path]))
|
|
11220
|
+
throw new Error("catalog_table_constraints_apply: the catalog returned a snapshot of a different table");
|
|
11221
|
+
const revision = toUint8Array(snapshot.definition_revision);
|
|
11222
|
+
if (revision.length === 0 || revision.length === expected.length && revision.every((b, i) => b === expected[i]))
|
|
11223
|
+
throw new Error(`catalog_table_constraints_apply: table '${want.name}' must return a new, nonempty definition_revision`);
|
|
11224
|
+
for (const record of snapshot.constraints) {
|
|
11225
|
+
const view = readConstraintRecord(toUint8Array(record));
|
|
11226
|
+
if (view.table !== want.name || JSON.stringify(view.schemaPath) !== JSON.stringify([...want.schema_path]))
|
|
11227
|
+
throw new Error(`catalog_table_constraints_apply: constraint '${view.id}' belongs to another table`);
|
|
11228
|
+
}
|
|
11229
|
+
return wrapResult({ table, definition_revision: revision, constraints: snapshot.constraints.map((c) => toUint8Array(c)) }, CatalogTableConstraintsApplyResultSchema);
|
|
11230
|
+
});
|
|
10115
11231
|
const catalogTableDrop = catalogHandler(signingKey, async (params) => {
|
|
10116
11232
|
const cat = getCatalog();
|
|
10117
11233
|
await cat.tableDrop(toUint8Array(params.attach_opaque_data), params.schema_path, params.name, params.ignore_not_found, params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
|
|
@@ -10199,9 +11315,7 @@ function catalogTableHandlers(getCatalog, signingKey) {
|
|
|
10199
11315
|
return {};
|
|
10200
11316
|
});
|
|
10201
11317
|
return {
|
|
10202
|
-
catalogTableConstraintsApply
|
|
10203
|
-
throw new MethodNotImplementedError4("catalog_table_constraints_apply");
|
|
10204
|
-
},
|
|
11318
|
+
catalogTableConstraintsApply,
|
|
10205
11319
|
catalogTableGet,
|
|
10206
11320
|
catalogTableCreate,
|
|
10207
11321
|
catalogTableDrop,
|
|
@@ -10788,4 +11902,4 @@ export {
|
|
|
10788
11902
|
serveVgiWorker
|
|
10789
11903
|
};
|
|
10790
11904
|
|
|
10791
|
-
//# debugId=
|
|
11905
|
+
//# debugId=C9BDB2DE50B86FAE64756E2164756E21
|