@query-farm/vgi 0.47.1 → 0.47.2
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/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 +1410 -152
- package/dist/client-entry.js.map +12 -8
- package/dist/index.core.d.ts +1 -1
- package/dist/index.js +1681 -411
- package/dist/index.js.map +19 -16
- package/dist/serve-entry.js +1095 -49
- package/dist/serve-entry.js.map +13 -11
- package/dist/worker-cf-entry.d.ts +2 -1
- package/dist/worker-cf-entry.js +1459 -182
- package/dist/worker-cf-entry.js.map +19 -16
- 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/index.core.ts +2 -1
- package/src/protocol/handlers/catalog/admin.ts +14 -13
- package/src/protocol/handlers/catalog/table.ts +58 -11
- package/src/worker-cf-entry.ts +2 -4
package/dist/index.js
CHANGED
|
@@ -8879,49 +8879,1383 @@ var TableFunctionStatisticsParamsSchema = schema2([
|
|
|
8879
8879
|
]);
|
|
8880
8880
|
|
|
8881
8881
|
// src/generated/vgi-protocol-types.ts
|
|
8882
|
+
function buildMacroOverload(init) {
|
|
8883
|
+
return {
|
|
8884
|
+
parameters: init.parameters,
|
|
8885
|
+
definition: init.definition,
|
|
8886
|
+
profile: init.profile,
|
|
8887
|
+
schema_path: init.schema_path,
|
|
8888
|
+
macro_type: init.macro_type,
|
|
8889
|
+
evaluation_context: init.evaluation_context
|
|
8890
|
+
};
|
|
8891
|
+
}
|
|
8892
|
+
var encodeMacroOverload = (v) => encodeASD(MacroOverloadSchema, v);
|
|
8893
|
+
var decodeMacroOverload = (b) => decodeASD(MacroOverloadSchema, b);
|
|
8894
|
+
function buildCatalogCapabilities(init) {
|
|
8895
|
+
return {
|
|
8896
|
+
read: init.read ?? [],
|
|
8897
|
+
ddl: init.ddl ?? [],
|
|
8898
|
+
write: init.write ?? [],
|
|
8899
|
+
transaction: init.transaction ?? []
|
|
8900
|
+
};
|
|
8901
|
+
}
|
|
8882
8902
|
var encodeCatalogCapabilities = (v) => encodeASD(CatalogCapabilitiesSchema, v);
|
|
8883
8903
|
var decodeCatalogCapabilities = (b) => decodeASD(CatalogCapabilitiesSchema, b);
|
|
8904
|
+
var encodeCatalogObjectRef = (v) => encodeASD(CatalogObjectRefSchema, v);
|
|
8905
|
+
var decodeCatalogObjectRef = (b) => decodeASD(CatalogObjectRefSchema, b);
|
|
8884
8906
|
var encodeSqlExpression = (v) => encodeASD(SqlExpressionSchema, v);
|
|
8885
8907
|
var decodeSqlExpression = (b) => decodeASD(SqlExpressionSchema, b);
|
|
8908
|
+
var encodeForeignKeyDefinition = (v) => encodeASD(ForeignKeyDefinitionSchema, v);
|
|
8909
|
+
var decodeForeignKeyDefinition = (b) => decodeASD(ForeignKeyDefinitionSchema, b);
|
|
8910
|
+
function buildConstraintDefinition(init) {
|
|
8911
|
+
return {
|
|
8912
|
+
kind: init.kind,
|
|
8913
|
+
column_paths: init.column_paths ?? [],
|
|
8914
|
+
declared_name: init.declared_name ?? null,
|
|
8915
|
+
check_expression: init.check_expression ?? null,
|
|
8916
|
+
foreign_key: init.foreign_key ?? null
|
|
8917
|
+
};
|
|
8918
|
+
}
|
|
8919
|
+
var encodeConstraintDefinition = (v) => encodeASD(ConstraintDefinitionSchema, v);
|
|
8920
|
+
var decodeConstraintDefinition = (b) => decodeASD(ConstraintDefinitionSchema, b);
|
|
8921
|
+
var encodeConstraintInfo = (v) => encodeASD(ConstraintInfoSchema, v);
|
|
8922
|
+
var decodeConstraintInfo = (b) => decodeASD(ConstraintInfoSchema, b);
|
|
8923
|
+
function buildConstraintChange(init) {
|
|
8924
|
+
return {
|
|
8925
|
+
operation: init.operation,
|
|
8926
|
+
ref: init.ref ?? null,
|
|
8927
|
+
definition: init.definition ?? null,
|
|
8928
|
+
enforcement: init.enforcement ?? null,
|
|
8929
|
+
validation: init.validation ?? null,
|
|
8930
|
+
cascade: init.cascade ?? null,
|
|
8931
|
+
declared_name: init.declared_name ?? null
|
|
8932
|
+
};
|
|
8933
|
+
}
|
|
8934
|
+
var encodeConstraintChange = (v) => encodeASD(ConstraintChangeSchema, v);
|
|
8935
|
+
var decodeConstraintChange = (b) => decodeASD(ConstraintChangeSchema, b);
|
|
8936
|
+
var encodeConstraintSnapshot = (v) => encodeASD(ConstraintSnapshotSchema, v);
|
|
8937
|
+
var decodeConstraintSnapshot = (b) => decodeASD(ConstraintSnapshotSchema, b);
|
|
8938
|
+
var encodeConstraintsApplyRequest = (v) => encodeASD(ConstraintsApplyRequestSchema, v);
|
|
8939
|
+
var decodeConstraintsApplyRequest = (b) => decodeASD(ConstraintsApplyRequestSchema, b);
|
|
8940
|
+
var encodeIndexDefinition = (v) => encodeASD(IndexDefinitionSchema, v);
|
|
8941
|
+
var decodeIndexDefinition = (b) => decodeASD(IndexDefinitionSchema, b);
|
|
8886
8942
|
function buildCatalogAttachResult(init) {
|
|
8887
8943
|
return {
|
|
8888
|
-
attach_opaque_data: init.attach_opaque_data,
|
|
8889
|
-
supports_transactions: init.supports_transactions,
|
|
8890
|
-
supports_time_travel: init.supports_time_travel,
|
|
8891
|
-
catalog_version_frozen: init.catalog_version_frozen,
|
|
8892
|
-
catalog_version: init.catalog_version,
|
|
8893
|
-
attach_opaque_data_required: init.attach_opaque_data_required ?? true,
|
|
8894
|
-
default_schema: init.default_schema === undefined ? "main" : init.default_schema,
|
|
8895
|
-
settings: init.settings ?? [],
|
|
8896
|
-
secret_types: init.secret_types ?? [],
|
|
8897
|
-
attach_catalogs: init.attach_catalogs ?? [],
|
|
8898
|
-
comment: init.comment ?? null,
|
|
8899
|
-
tags: init.tags ?? {},
|
|
8900
|
-
supports_column_statistics: init.supports_column_statistics ?? false,
|
|
8901
|
-
global_functions: init.global_functions ?? [],
|
|
8902
|
-
global_function_prefix: init.global_function_prefix ?? "",
|
|
8903
|
-
resolved_data_version: init.resolved_data_version ?? null,
|
|
8904
|
-
resolved_implementation_version: init.resolved_implementation_version ?? null,
|
|
8905
|
-
supports_catalog_contents: init.supports_catalog_contents ?? false,
|
|
8906
|
-
catalog_capabilities: init.catalog_capabilities ?? null,
|
|
8907
|
-
selected_capabilities: init.selected_capabilities ?? null,
|
|
8908
|
-
query_pushdown: init.query_pushdown ?? null
|
|
8944
|
+
attach_opaque_data: init.attach_opaque_data,
|
|
8945
|
+
supports_transactions: init.supports_transactions,
|
|
8946
|
+
supports_time_travel: init.supports_time_travel,
|
|
8947
|
+
catalog_version_frozen: init.catalog_version_frozen,
|
|
8948
|
+
catalog_version: init.catalog_version,
|
|
8949
|
+
attach_opaque_data_required: init.attach_opaque_data_required ?? true,
|
|
8950
|
+
default_schema: init.default_schema === undefined ? "main" : init.default_schema,
|
|
8951
|
+
settings: init.settings ?? [],
|
|
8952
|
+
secret_types: init.secret_types ?? [],
|
|
8953
|
+
attach_catalogs: init.attach_catalogs ?? [],
|
|
8954
|
+
comment: init.comment ?? null,
|
|
8955
|
+
tags: init.tags ?? {},
|
|
8956
|
+
supports_column_statistics: init.supports_column_statistics ?? false,
|
|
8957
|
+
global_functions: init.global_functions ?? [],
|
|
8958
|
+
global_function_prefix: init.global_function_prefix ?? "",
|
|
8959
|
+
resolved_data_version: init.resolved_data_version ?? null,
|
|
8960
|
+
resolved_implementation_version: init.resolved_implementation_version ?? null,
|
|
8961
|
+
supports_catalog_contents: init.supports_catalog_contents ?? false,
|
|
8962
|
+
catalog_capabilities: init.catalog_capabilities ?? null,
|
|
8963
|
+
selected_capabilities: init.selected_capabilities ?? null,
|
|
8964
|
+
query_pushdown: init.query_pushdown ?? null
|
|
8965
|
+
};
|
|
8966
|
+
}
|
|
8967
|
+
function buildCatalogContentsResponse(init) {
|
|
8968
|
+
return {
|
|
8969
|
+
catalog_version: init.catalog_version,
|
|
8970
|
+
etag: init.etag ?? null,
|
|
8971
|
+
not_modified: init.not_modified ?? false,
|
|
8972
|
+
schemas: init.schemas ?? null,
|
|
8973
|
+
tables: init.tables ?? null,
|
|
8974
|
+
views: init.views ?? null,
|
|
8975
|
+
functions: init.functions ?? null,
|
|
8976
|
+
macros: init.macros ?? null,
|
|
8977
|
+
indexes: init.indexes ?? null
|
|
8978
|
+
};
|
|
8979
|
+
}
|
|
8980
|
+
var decodeCatalogContentsResponse = (b) => decodeASD(CatalogContentsResultSchema, b);
|
|
8981
|
+
|
|
8982
|
+
// src/catalog/constraints.ts
|
|
8983
|
+
init_arrow();
|
|
8984
|
+
|
|
8985
|
+
// src/catalog/sql-grammar.ts
|
|
8986
|
+
class GrammarError extends Error {
|
|
8987
|
+
}
|
|
8988
|
+
var fail = (message) => {
|
|
8989
|
+
throw new GrammarError(message);
|
|
8990
|
+
};
|
|
8991
|
+
var RESERVED = new Set([
|
|
8992
|
+
"all",
|
|
8993
|
+
"and",
|
|
8994
|
+
"any",
|
|
8995
|
+
"array",
|
|
8996
|
+
"as",
|
|
8997
|
+
"asc",
|
|
8998
|
+
"between",
|
|
8999
|
+
"both",
|
|
9000
|
+
"case",
|
|
9001
|
+
"cast",
|
|
9002
|
+
"check",
|
|
9003
|
+
"collate",
|
|
9004
|
+
"column",
|
|
9005
|
+
"constraint",
|
|
9006
|
+
"create",
|
|
9007
|
+
"default",
|
|
9008
|
+
"desc",
|
|
9009
|
+
"distinct",
|
|
9010
|
+
"do",
|
|
9011
|
+
"else",
|
|
9012
|
+
"end",
|
|
9013
|
+
"except",
|
|
9014
|
+
"false",
|
|
9015
|
+
"fetch",
|
|
9016
|
+
"for",
|
|
9017
|
+
"foreign",
|
|
9018
|
+
"from",
|
|
9019
|
+
"glob",
|
|
9020
|
+
"grant",
|
|
9021
|
+
"group",
|
|
9022
|
+
"having",
|
|
9023
|
+
"ilike",
|
|
9024
|
+
"in",
|
|
9025
|
+
"intersect",
|
|
9026
|
+
"interval",
|
|
9027
|
+
"into",
|
|
9028
|
+
"is",
|
|
9029
|
+
"isnull",
|
|
9030
|
+
"like",
|
|
9031
|
+
"limit",
|
|
9032
|
+
"not",
|
|
9033
|
+
"notnull",
|
|
9034
|
+
"null",
|
|
9035
|
+
"offset",
|
|
9036
|
+
"on",
|
|
9037
|
+
"or",
|
|
9038
|
+
"order",
|
|
9039
|
+
"primary",
|
|
9040
|
+
"references",
|
|
9041
|
+
"returning",
|
|
9042
|
+
"select",
|
|
9043
|
+
"similar",
|
|
9044
|
+
"some",
|
|
9045
|
+
"table",
|
|
9046
|
+
"then",
|
|
9047
|
+
"to",
|
|
9048
|
+
"true",
|
|
9049
|
+
"try_cast",
|
|
9050
|
+
"union",
|
|
9051
|
+
"unique",
|
|
9052
|
+
"using",
|
|
9053
|
+
"when",
|
|
9054
|
+
"where",
|
|
9055
|
+
"window",
|
|
9056
|
+
"with"
|
|
9057
|
+
]);
|
|
9058
|
+
var OPERATORS = ["::", "<=", ">=", "<>", "!=", "==", "||", "//", "**", "=", "<", ">", "+", "-", "*", "/", "%", "^", "(", ")", ",", "."];
|
|
9059
|
+
function tokenize(sql) {
|
|
9060
|
+
const out = [];
|
|
9061
|
+
let i = 0;
|
|
9062
|
+
while (i < sql.length) {
|
|
9063
|
+
const c = sql[i];
|
|
9064
|
+
if (/\s/.test(c)) {
|
|
9065
|
+
i++;
|
|
9066
|
+
continue;
|
|
9067
|
+
}
|
|
9068
|
+
if (sql.startsWith("--", i)) {
|
|
9069
|
+
while (i < sql.length && sql[i] !== `
|
|
9070
|
+
`)
|
|
9071
|
+
i++;
|
|
9072
|
+
continue;
|
|
9073
|
+
}
|
|
9074
|
+
if (sql.startsWith("/*", i)) {
|
|
9075
|
+
const close = sql.indexOf("*/", i + 2);
|
|
9076
|
+
if (close < 0)
|
|
9077
|
+
fail("unterminated comment");
|
|
9078
|
+
i = close + 2;
|
|
9079
|
+
continue;
|
|
9080
|
+
}
|
|
9081
|
+
if (/[0-9]/.test(c) || c === "." && /[0-9]/.test(sql[i + 1] ?? "")) {
|
|
9082
|
+
const m = /^(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?/.exec(sql.slice(i));
|
|
9083
|
+
if (/[A-Za-z_]/.test(sql[i + m[0].length] ?? ""))
|
|
9084
|
+
fail("unsupported numeric literal");
|
|
9085
|
+
out.push({ t: "num", v: m[0] });
|
|
9086
|
+
i += m[0].length;
|
|
9087
|
+
continue;
|
|
9088
|
+
}
|
|
9089
|
+
if (c === "'" || c === '"') {
|
|
9090
|
+
let j = i + 1, text = "";
|
|
9091
|
+
for (;; ) {
|
|
9092
|
+
if (j >= sql.length)
|
|
9093
|
+
fail("unterminated quoted text");
|
|
9094
|
+
if (sql[j] === c) {
|
|
9095
|
+
if (sql[j + 1] === c) {
|
|
9096
|
+
text += c;
|
|
9097
|
+
j += 2;
|
|
9098
|
+
continue;
|
|
9099
|
+
}
|
|
9100
|
+
break;
|
|
9101
|
+
}
|
|
9102
|
+
text += sql[j++];
|
|
9103
|
+
}
|
|
9104
|
+
out.push(c === "'" ? { t: "str", v: text } : { t: "ident", v: text, quoted: true });
|
|
9105
|
+
i = j + 1;
|
|
9106
|
+
continue;
|
|
9107
|
+
}
|
|
9108
|
+
if (/[A-Za-z_\u0080-]/.test(c)) {
|
|
9109
|
+
const m = /^[A-Za-z_\u0080-][A-Za-z0-9_$\u0080-]*/.exec(sql.slice(i));
|
|
9110
|
+
out.push({ t: "ident", v: m[0], quoted: false });
|
|
9111
|
+
i += m[0].length;
|
|
9112
|
+
continue;
|
|
9113
|
+
}
|
|
9114
|
+
const op = OPERATORS.find((o) => sql.startsWith(o, i));
|
|
9115
|
+
if (!op)
|
|
9116
|
+
fail(`unsupported character '${c}'`);
|
|
9117
|
+
out.push({ t: "op", v: op });
|
|
9118
|
+
i += op.length;
|
|
9119
|
+
}
|
|
9120
|
+
out.push({ t: "end" });
|
|
9121
|
+
return out;
|
|
9122
|
+
}
|
|
9123
|
+
var CAST_TYPES = {
|
|
9124
|
+
boolean: "BOOLEAN",
|
|
9125
|
+
bool: "BOOLEAN",
|
|
9126
|
+
logical: "BOOLEAN",
|
|
9127
|
+
tinyint: "TINYINT",
|
|
9128
|
+
int1: "TINYINT",
|
|
9129
|
+
smallint: "SMALLINT",
|
|
9130
|
+
int2: "SMALLINT",
|
|
9131
|
+
short: "SMALLINT",
|
|
9132
|
+
integer: "INTEGER",
|
|
9133
|
+
int: "INTEGER",
|
|
9134
|
+
int4: "INTEGER",
|
|
9135
|
+
signed: "INTEGER",
|
|
9136
|
+
bigint: "BIGINT",
|
|
9137
|
+
int8: "BIGINT",
|
|
9138
|
+
long: "BIGINT",
|
|
9139
|
+
float: "FLOAT",
|
|
9140
|
+
real: "FLOAT",
|
|
9141
|
+
float4: "FLOAT",
|
|
9142
|
+
double: "DOUBLE",
|
|
9143
|
+
float8: "DOUBLE",
|
|
9144
|
+
decimal: "DECIMAL",
|
|
9145
|
+
numeric: "DECIMAL",
|
|
9146
|
+
varchar: "VARCHAR",
|
|
9147
|
+
text: "VARCHAR",
|
|
9148
|
+
string: "VARCHAR",
|
|
9149
|
+
char: "VARCHAR",
|
|
9150
|
+
bpchar: "VARCHAR",
|
|
9151
|
+
nvarchar: "VARCHAR",
|
|
9152
|
+
character: "VARCHAR"
|
|
9153
|
+
};
|
|
9154
|
+
var INT64_MAX = (1n << 63n) - 1n;
|
|
9155
|
+
function literalNumber(text, negative) {
|
|
9156
|
+
if (/^[0-9]+$/.test(text)) {
|
|
9157
|
+
const value = BigInt(text) * (negative ? -1n : 1n);
|
|
9158
|
+
const type = value >= -(2n ** 31n) && value < 2n ** 31n ? "INTEGER" : value >= -INT64_MAX - 1n && value <= INT64_MAX ? "BIGINT" : "HUGEINT";
|
|
9159
|
+
return { kind: "constant", type };
|
|
9160
|
+
}
|
|
9161
|
+
if (!/[eE]/.test(text) && text.replace(".", "").replace(/^0+/, "").length <= 38)
|
|
9162
|
+
return { kind: "constant", type: "DECIMAL" };
|
|
9163
|
+
return { kind: "constant", type: "DOUBLE" };
|
|
9164
|
+
}
|
|
9165
|
+
|
|
9166
|
+
class Parser {
|
|
9167
|
+
tokens;
|
|
9168
|
+
pos = 0;
|
|
9169
|
+
constructor(tokens) {
|
|
9170
|
+
this.tokens = tokens;
|
|
9171
|
+
}
|
|
9172
|
+
peek(offset = 0) {
|
|
9173
|
+
return this.tokens[Math.min(this.pos + offset, this.tokens.length - 1)];
|
|
9174
|
+
}
|
|
9175
|
+
next() {
|
|
9176
|
+
return this.tokens[this.pos++];
|
|
9177
|
+
}
|
|
9178
|
+
isOp(v, offset = 0) {
|
|
9179
|
+
const t = this.peek(offset);
|
|
9180
|
+
return t.t === "op" && t.v === v;
|
|
9181
|
+
}
|
|
9182
|
+
isWord(word, offset = 0) {
|
|
9183
|
+
const t = this.peek(offset);
|
|
9184
|
+
return t.t === "ident" && !t.quoted && t.v.toLowerCase() === word;
|
|
9185
|
+
}
|
|
9186
|
+
expectOp(v) {
|
|
9187
|
+
if (!this.isOp(v))
|
|
9188
|
+
fail(`expected '${v}'`);
|
|
9189
|
+
this.pos++;
|
|
9190
|
+
}
|
|
9191
|
+
parseAll() {
|
|
9192
|
+
const node = this.expr();
|
|
9193
|
+
if (this.peek().t !== "end")
|
|
9194
|
+
fail("unexpected text after the expression");
|
|
9195
|
+
return node;
|
|
9196
|
+
}
|
|
9197
|
+
expr() {
|
|
9198
|
+
return this.or();
|
|
9199
|
+
}
|
|
9200
|
+
or() {
|
|
9201
|
+
let left = this.and();
|
|
9202
|
+
while (this.isWord("or")) {
|
|
9203
|
+
this.pos++;
|
|
9204
|
+
left = { kind: "conjunction", op: "OR", children: [left, this.and()] };
|
|
9205
|
+
}
|
|
9206
|
+
return left;
|
|
9207
|
+
}
|
|
9208
|
+
and() {
|
|
9209
|
+
let left = this.not();
|
|
9210
|
+
while (this.isWord("and")) {
|
|
9211
|
+
this.pos++;
|
|
9212
|
+
left = { kind: "conjunction", op: "AND", children: [left, this.not()] };
|
|
9213
|
+
}
|
|
9214
|
+
return left;
|
|
9215
|
+
}
|
|
9216
|
+
not() {
|
|
9217
|
+
if (this.isWord("not")) {
|
|
9218
|
+
this.pos++;
|
|
9219
|
+
return { kind: "operator", op: "NOT", children: [this.not()] };
|
|
9220
|
+
}
|
|
9221
|
+
return this.is();
|
|
9222
|
+
}
|
|
9223
|
+
is() {
|
|
9224
|
+
let left = this.comparison();
|
|
9225
|
+
for (;; ) {
|
|
9226
|
+
if (this.isWord("isnull")) {
|
|
9227
|
+
this.pos++;
|
|
9228
|
+
left = { kind: "operator", op: "IS_NULL", children: [left] };
|
|
9229
|
+
continue;
|
|
9230
|
+
}
|
|
9231
|
+
if (this.isWord("notnull")) {
|
|
9232
|
+
this.pos++;
|
|
9233
|
+
left = { kind: "operator", op: "IS_NOT_NULL", children: [left] };
|
|
9234
|
+
continue;
|
|
9235
|
+
}
|
|
9236
|
+
if (this.isWord("is")) {
|
|
9237
|
+
this.pos++;
|
|
9238
|
+
const negated = this.isWord("not");
|
|
9239
|
+
if (negated)
|
|
9240
|
+
this.pos++;
|
|
9241
|
+
if (!this.isWord("null"))
|
|
9242
|
+
fail("only IS [NOT] NULL is supported");
|
|
9243
|
+
this.pos++;
|
|
9244
|
+
left = { kind: "operator", op: negated ? "IS_NOT_NULL" : "IS_NULL", children: [left] };
|
|
9245
|
+
continue;
|
|
9246
|
+
}
|
|
9247
|
+
return left;
|
|
9248
|
+
}
|
|
9249
|
+
}
|
|
9250
|
+
comparison() {
|
|
9251
|
+
const left = this.otherOp();
|
|
9252
|
+
const t = this.peek();
|
|
9253
|
+
if (t.t === "op" && ["=", "==", "<>", "!=", "<", ">", "<=", ">="].includes(t.v)) {
|
|
9254
|
+
this.pos++;
|
|
9255
|
+
const right = this.otherOp();
|
|
9256
|
+
const next = this.peek();
|
|
9257
|
+
if (next.t === "op" && ["=", "==", "<>", "!=", "<", ">", "<=", ">="].includes(next.v))
|
|
9258
|
+
fail("chained comparisons are unsupported");
|
|
9259
|
+
return { kind: "comparison", op: t.v === "==" ? "=" : t.v === "!=" ? "<>" : t.v, left, right };
|
|
9260
|
+
}
|
|
9261
|
+
for (const word of ["between", "in", "like", "ilike", "glob", "similar", "not", "collate"]) {
|
|
9262
|
+
if (this.isWord(word))
|
|
9263
|
+
fail(`${word.toUpperCase()} is outside the supported scalar grammar`);
|
|
9264
|
+
}
|
|
9265
|
+
return left;
|
|
9266
|
+
}
|
|
9267
|
+
otherOp() {
|
|
9268
|
+
let left = this.additive();
|
|
9269
|
+
for (;; ) {
|
|
9270
|
+
const t = this.peek();
|
|
9271
|
+
if (t.t === "op" && ["||", "//", "**"].includes(t.v)) {
|
|
9272
|
+
this.pos++;
|
|
9273
|
+
left = { kind: "function", name: t.v, qualified: false, children: [left, this.additive()] };
|
|
9274
|
+
continue;
|
|
9275
|
+
}
|
|
9276
|
+
return left;
|
|
9277
|
+
}
|
|
9278
|
+
}
|
|
9279
|
+
additive() {
|
|
9280
|
+
let left = this.multiplicative();
|
|
9281
|
+
for (;; ) {
|
|
9282
|
+
const t = this.peek();
|
|
9283
|
+
if (t.t === "op" && (t.v === "+" || t.v === "-")) {
|
|
9284
|
+
this.pos++;
|
|
9285
|
+
left = { kind: "function", name: t.v, qualified: false, children: [left, this.multiplicative()] };
|
|
9286
|
+
continue;
|
|
9287
|
+
}
|
|
9288
|
+
return left;
|
|
9289
|
+
}
|
|
9290
|
+
}
|
|
9291
|
+
multiplicative() {
|
|
9292
|
+
let left = this.power();
|
|
9293
|
+
for (;; ) {
|
|
9294
|
+
const t = this.peek();
|
|
9295
|
+
if (t.t === "op" && (t.v === "*" || t.v === "/" || t.v === "%")) {
|
|
9296
|
+
this.pos++;
|
|
9297
|
+
left = { kind: "function", name: t.v, qualified: false, children: [left, this.power()] };
|
|
9298
|
+
continue;
|
|
9299
|
+
}
|
|
9300
|
+
return left;
|
|
9301
|
+
}
|
|
9302
|
+
}
|
|
9303
|
+
power() {
|
|
9304
|
+
let left = this.unary();
|
|
9305
|
+
while (this.isOp("^")) {
|
|
9306
|
+
this.pos++;
|
|
9307
|
+
left = { kind: "function", name: "^", qualified: false, children: [left, this.unary()] };
|
|
9308
|
+
}
|
|
9309
|
+
return left;
|
|
9310
|
+
}
|
|
9311
|
+
unary() {
|
|
9312
|
+
if (this.isOp("-") || this.isOp("+")) {
|
|
9313
|
+
const sign = this.next().v;
|
|
9314
|
+
const operand = this.unary();
|
|
9315
|
+
if (sign === "-" && operand.kind === "constant" && operand.fromNumber) {
|
|
9316
|
+
const folded = literalNumber(operand.text, !operand.negative);
|
|
9317
|
+
return Object.assign(folded, { fromNumber: true, text: operand.text, negative: !operand.negative });
|
|
9318
|
+
}
|
|
9319
|
+
return { kind: "function", name: sign, qualified: false, children: [operand] };
|
|
9320
|
+
}
|
|
9321
|
+
return this.postfix();
|
|
9322
|
+
}
|
|
9323
|
+
postfix() {
|
|
9324
|
+
let node = this.primary();
|
|
9325
|
+
for (;; ) {
|
|
9326
|
+
if (this.isOp("::")) {
|
|
9327
|
+
this.pos++;
|
|
9328
|
+
node = { kind: "cast", ...this.typeName(), child: node };
|
|
9329
|
+
continue;
|
|
9330
|
+
}
|
|
9331
|
+
if (this.isOp("["))
|
|
9332
|
+
fail("subscripts are unsupported");
|
|
9333
|
+
return node;
|
|
9334
|
+
}
|
|
9335
|
+
}
|
|
9336
|
+
typeName() {
|
|
9337
|
+
const t = this.next();
|
|
9338
|
+
if (t.t !== "ident")
|
|
9339
|
+
fail("expected a type name");
|
|
9340
|
+
const first = t.v.toLowerCase();
|
|
9341
|
+
let qualified = false;
|
|
9342
|
+
while (this.isOp(".")) {
|
|
9343
|
+
this.pos++;
|
|
9344
|
+
if (this.next().t !== "ident")
|
|
9345
|
+
fail("expected a type name");
|
|
9346
|
+
qualified = true;
|
|
9347
|
+
}
|
|
9348
|
+
let name = first;
|
|
9349
|
+
if (first === "double" && this.isWord("precision")) {
|
|
9350
|
+
this.pos++;
|
|
9351
|
+
name = "double";
|
|
9352
|
+
}
|
|
9353
|
+
if (first === "character" && this.isWord("varying")) {
|
|
9354
|
+
this.pos++;
|
|
9355
|
+
name = "varchar";
|
|
9356
|
+
}
|
|
9357
|
+
let params = [];
|
|
9358
|
+
if (this.isOp("(")) {
|
|
9359
|
+
this.pos++;
|
|
9360
|
+
for (;; ) {
|
|
9361
|
+
const p = this.next();
|
|
9362
|
+
if (p.t !== "num")
|
|
9363
|
+
fail("unsupported type parameter");
|
|
9364
|
+
params.push(p.v);
|
|
9365
|
+
if (this.isOp(",")) {
|
|
9366
|
+
this.pos++;
|
|
9367
|
+
continue;
|
|
9368
|
+
}
|
|
9369
|
+
break;
|
|
9370
|
+
}
|
|
9371
|
+
this.expectOp(")");
|
|
9372
|
+
}
|
|
9373
|
+
if (this.isOp("["))
|
|
9374
|
+
fail("array types are unsupported");
|
|
9375
|
+
let type = CAST_TYPES[name] ?? null;
|
|
9376
|
+
if (type === "FLOAT" && params.length === 1 && Number(params[0]) > 24)
|
|
9377
|
+
type = "DOUBLE";
|
|
9378
|
+
return { type, qualified };
|
|
9379
|
+
}
|
|
9380
|
+
primary() {
|
|
9381
|
+
const t = this.next();
|
|
9382
|
+
if (t.t === "num")
|
|
9383
|
+
return Object.assign(literalNumber(t.v, false), { fromNumber: true, text: t.v, negative: false });
|
|
9384
|
+
if (t.t === "str") {
|
|
9385
|
+
if (this.peek().t === "str")
|
|
9386
|
+
fail("adjacent string literals are unsupported");
|
|
9387
|
+
return { kind: "constant", type: "VARCHAR" };
|
|
9388
|
+
}
|
|
9389
|
+
if (t.t === "op") {
|
|
9390
|
+
if (t.v === "(") {
|
|
9391
|
+
const inner = this.expr();
|
|
9392
|
+
if (this.isOp(","))
|
|
9393
|
+
fail("row constructors are unsupported");
|
|
9394
|
+
this.expectOp(")");
|
|
9395
|
+
return inner;
|
|
9396
|
+
}
|
|
9397
|
+
return fail(`unexpected '${t.v}'`);
|
|
9398
|
+
}
|
|
9399
|
+
if (t.t === "end")
|
|
9400
|
+
return fail("expected an expression");
|
|
9401
|
+
const word = t.v.toLowerCase();
|
|
9402
|
+
if (!t.quoted) {
|
|
9403
|
+
if (word === "null")
|
|
9404
|
+
return { kind: "constant", type: "NULL" };
|
|
9405
|
+
if (word === "true" || word === "false")
|
|
9406
|
+
return { kind: "constant", type: "BOOLEAN" };
|
|
9407
|
+
if (word === "cast" && this.isOp("(")) {
|
|
9408
|
+
this.pos++;
|
|
9409
|
+
const child = this.expr();
|
|
9410
|
+
if (!this.isWord("as"))
|
|
9411
|
+
fail("expected AS in CAST");
|
|
9412
|
+
this.pos++;
|
|
9413
|
+
const target = this.typeName();
|
|
9414
|
+
this.expectOp(")");
|
|
9415
|
+
return { kind: "cast", ...target, child };
|
|
9416
|
+
}
|
|
9417
|
+
if (word === "case")
|
|
9418
|
+
fail("CASE is outside the supported scalar grammar");
|
|
9419
|
+
if (RESERVED.has(word))
|
|
9420
|
+
fail(`unexpected keyword ${t.v.toUpperCase()}`);
|
|
9421
|
+
}
|
|
9422
|
+
const names = [t.v];
|
|
9423
|
+
while (this.isOp(".")) {
|
|
9424
|
+
this.pos++;
|
|
9425
|
+
const part = this.next();
|
|
9426
|
+
if (part.t !== "ident")
|
|
9427
|
+
fail("unsupported qualified name");
|
|
9428
|
+
names.push(part.v);
|
|
9429
|
+
}
|
|
9430
|
+
if (this.isOp("(")) {
|
|
9431
|
+
this.pos++;
|
|
9432
|
+
const children = [];
|
|
9433
|
+
if (this.isWord("distinct"))
|
|
9434
|
+
fail("DISTINCT function arguments are unsupported");
|
|
9435
|
+
if (!this.isOp(")")) {
|
|
9436
|
+
for (;; ) {
|
|
9437
|
+
if (this.isOp("*"))
|
|
9438
|
+
fail("star arguments are unsupported");
|
|
9439
|
+
if (this.peek(1).t === "op" && (this.peek(1).v === ":" || this.peek(1).v === "=") && this.peek().t === "ident")
|
|
9440
|
+
fail("named scalar arguments are unsupported");
|
|
9441
|
+
children.push(this.expr());
|
|
9442
|
+
if (this.isOp(",")) {
|
|
9443
|
+
this.pos++;
|
|
9444
|
+
continue;
|
|
9445
|
+
}
|
|
9446
|
+
break;
|
|
9447
|
+
}
|
|
9448
|
+
}
|
|
9449
|
+
if (this.isWord("order"))
|
|
9450
|
+
fail("ordered function arguments are unsupported");
|
|
9451
|
+
this.expectOp(")");
|
|
9452
|
+
if (this.isWord("filter") || this.isWord("over"))
|
|
9453
|
+
fail("aggregate and window functions are unsupported");
|
|
9454
|
+
if (names.length === 1 && !t.quoted && word === "coalesce")
|
|
9455
|
+
return { kind: "operator", op: "COALESCE", children };
|
|
9456
|
+
return { kind: "function", name: names[names.length - 1], qualified: names.length > 1, children };
|
|
9457
|
+
}
|
|
9458
|
+
if (this.peek().t === "str")
|
|
9459
|
+
fail("typed literals are unsupported");
|
|
9460
|
+
return { kind: "column", names };
|
|
9461
|
+
}
|
|
9462
|
+
}
|
|
9463
|
+
function parseScalarSql(sql) {
|
|
9464
|
+
if (typeof sql !== "string" || !sql || sql.includes("\x00") || new TextEncoder().encode(sql).length > 1024 * 1024)
|
|
9465
|
+
fail("invalid SQL size or text");
|
|
9466
|
+
return new Parser(tokenize(sql)).parseAll();
|
|
9467
|
+
}
|
|
9468
|
+
var PRIMITIVE = new Set(["NULL", "BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE", "DECIMAL", "VARCHAR"]);
|
|
9469
|
+
var GENERATED_PRIMITIVE = new Set(["NULL", "BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "VARCHAR"]);
|
|
9470
|
+
var ALLOWED_FUNCTIONS = new Set(["+", "-", "*", "%", "abs", "lower", "upper"]);
|
|
9471
|
+
function validateColumnExpressionSql(sql, options) {
|
|
9472
|
+
const { usingColumns, generated } = options;
|
|
9473
|
+
const primitive = generated ? GENERATED_PRIMITIVE : PRIMITIVE;
|
|
9474
|
+
const columns = [];
|
|
9475
|
+
let nodes = 0;
|
|
9476
|
+
const visit = (node, depth) => {
|
|
9477
|
+
if (depth > 64 || ++nodes > 4096)
|
|
9478
|
+
fail("scalar expression is too complex");
|
|
9479
|
+
switch (node.kind) {
|
|
9480
|
+
case "constant":
|
|
9481
|
+
if (!primitive.has(node.type))
|
|
9482
|
+
fail(`unsupported scalar literal type ${node.type}`);
|
|
9483
|
+
return;
|
|
9484
|
+
case "column":
|
|
9485
|
+
if (!usingColumns || node.names.length !== 1)
|
|
9486
|
+
fail("column references are unsupported in this scope");
|
|
9487
|
+
columns.push(node.names[0]);
|
|
9488
|
+
return;
|
|
9489
|
+
case "cast":
|
|
9490
|
+
if (node.qualified)
|
|
9491
|
+
fail("qualified scalar cast types are unsupported");
|
|
9492
|
+
if (node.type === null || !primitive.has(node.type))
|
|
9493
|
+
fail("unsupported scalar cast");
|
|
9494
|
+
visit(node.child, depth + 1);
|
|
9495
|
+
return;
|
|
9496
|
+
case "comparison":
|
|
9497
|
+
visit(node.left, depth + 1);
|
|
9498
|
+
visit(node.right, depth + 1);
|
|
9499
|
+
return;
|
|
9500
|
+
case "conjunction":
|
|
9501
|
+
case "operator":
|
|
9502
|
+
node.children.forEach((c) => visit(c, depth + 1));
|
|
9503
|
+
return;
|
|
9504
|
+
case "function": {
|
|
9505
|
+
const lower = node.name.toLowerCase();
|
|
9506
|
+
const ok = !node.qualified && (ALLOWED_FUNCTIONS.has(lower) || usingColumns && !generated && node.name === "/" || generated && node.name === "||");
|
|
9507
|
+
if (!ok)
|
|
9508
|
+
fail(`unsupported scalar function '${node.name}'`);
|
|
9509
|
+
node.children.forEach((c) => visit(c, depth + 1));
|
|
9510
|
+
return;
|
|
9511
|
+
}
|
|
9512
|
+
}
|
|
9513
|
+
};
|
|
9514
|
+
try {
|
|
9515
|
+
visit(parseScalarSql(sql), 0);
|
|
9516
|
+
} catch (error) {
|
|
9517
|
+
if (error instanceof GrammarError)
|
|
9518
|
+
throw error;
|
|
9519
|
+
throw new GrammarError(String(error?.message ?? error));
|
|
9520
|
+
}
|
|
9521
|
+
return columns;
|
|
9522
|
+
}
|
|
9523
|
+
function validateNumericCheckSql(sql, resolveColumn) {
|
|
9524
|
+
const node = parseScalarSql(sql);
|
|
9525
|
+
if (node.kind !== "comparison")
|
|
9526
|
+
fail("native CHECK read supports only Boolean numeric comparisons");
|
|
9527
|
+
const comparison = node;
|
|
9528
|
+
for (const operand of [comparison.left, comparison.right]) {
|
|
9529
|
+
if (operand.kind === "constant") {
|
|
9530
|
+
if (operand.type === "NULL" || operand.type === "BOOLEAN" || operand.type === "VARCHAR")
|
|
9531
|
+
fail("CHECK requires numeric operands");
|
|
9532
|
+
continue;
|
|
9533
|
+
}
|
|
9534
|
+
if (operand.kind !== "column")
|
|
9535
|
+
fail("native CHECK read supports only numeric column/constant comparisons");
|
|
9536
|
+
const column = operand;
|
|
9537
|
+
if (column.names.length !== 1)
|
|
9538
|
+
fail("CHECK requires unqualified column references");
|
|
9539
|
+
resolveColumn(column.names[0]);
|
|
9540
|
+
}
|
|
9541
|
+
}
|
|
9542
|
+
|
|
9543
|
+
// src/catalog/column-types.ts
|
|
9544
|
+
init_arrow();
|
|
9545
|
+
function isRowIdField(field) {
|
|
9546
|
+
return field.metadata?.has("is_row_id") ?? false;
|
|
9547
|
+
}
|
|
9548
|
+
function hasLogicalType(field) {
|
|
9549
|
+
for (const key of field.metadata?.keys() ?? [])
|
|
9550
|
+
if (key === "ARROW:extension:name" || key.startsWith("vgi.logical_type."))
|
|
9551
|
+
return true;
|
|
9552
|
+
return false;
|
|
9553
|
+
}
|
|
9554
|
+
function ordinaryStructChildren(field) {
|
|
9555
|
+
if (!isStruct(field.type) || hasLogicalType(field))
|
|
9556
|
+
return null;
|
|
9557
|
+
return field.type.children;
|
|
9558
|
+
}
|
|
9559
|
+
function isGeneratedField(field) {
|
|
9560
|
+
const m = field.metadata;
|
|
9561
|
+
return m != null && (m.has("vgi.column.generated.v1") || m.has("vgi.column.generation.v1") || m.has("generated_expression"));
|
|
9562
|
+
}
|
|
9563
|
+
function duckdbPrimitive(field) {
|
|
9564
|
+
if (hasLogicalType(field))
|
|
9565
|
+
return null;
|
|
9566
|
+
const t = field.type;
|
|
9567
|
+
switch (t.typeId) {
|
|
9568
|
+
case TypeId.Bool:
|
|
9569
|
+
return "BOOLEAN";
|
|
9570
|
+
case TypeId.Utf8:
|
|
9571
|
+
return "VARCHAR";
|
|
9572
|
+
case TypeId.Int: {
|
|
9573
|
+
if (!(t.isSigned ?? t.signed ?? true))
|
|
9574
|
+
return null;
|
|
9575
|
+
return { 8: "TINYINT", 16: "SMALLINT", 32: "INTEGER", 64: "BIGINT" }[t.bitWidth] ?? null;
|
|
9576
|
+
}
|
|
9577
|
+
case TypeId.Float:
|
|
9578
|
+
return t.precision === 1 ? "FLOAT" : t.precision === 2 ? "DOUBLE" : null;
|
|
9579
|
+
case TypeId.Decimal:
|
|
9580
|
+
return (t.bitWidth ?? 128) === 128 ? "DECIMAL" : null;
|
|
9581
|
+
default:
|
|
9582
|
+
return null;
|
|
9583
|
+
}
|
|
9584
|
+
}
|
|
9585
|
+
|
|
9586
|
+
// src/catalog/column-expressions.ts
|
|
9587
|
+
init_arrow();
|
|
9588
|
+
var GENERATED_EXPRESSION_KEY = "vgi.column.generated.v1";
|
|
9589
|
+
var GENERATION_KEY = "vgi.column.generation.v1";
|
|
9590
|
+
var DEFAULT_EXPRESSION_KEY = "vgi.column.default.v1";
|
|
9591
|
+
var GENERATED_TYPES = new Set(["BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "VARCHAR"]);
|
|
9592
|
+
var DEFAULT_TYPES = new Set(["BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE", "DECIMAL", "VARCHAR"]);
|
|
9593
|
+
var PROFILE = "vgi.expression.duckdb.scalar.v1";
|
|
9594
|
+
var MAX_BYTES = 8 * 1024 * 1024;
|
|
9595
|
+
var base64 = (bytes) => btoa(Array.from(bytes, (value) => String.fromCharCode(value)).join(""));
|
|
9596
|
+
function text(value, maximum) {
|
|
9597
|
+
if (typeof value !== "string" || !value || value.includes("\x00") || new TextEncoder().encode(value).length > maximum)
|
|
9598
|
+
throw new Error("invalid generated expression text");
|
|
9599
|
+
for (let i = 0;i < value.length; i++) {
|
|
9600
|
+
const c = value.charCodeAt(i);
|
|
9601
|
+
if (c >= 55296 && c <= 56319) {
|
|
9602
|
+
const d = value.charCodeAt(++i);
|
|
9603
|
+
if (!(d >= 56320 && d <= 57343))
|
|
9604
|
+
throw new Error("invalid generated expression Unicode");
|
|
9605
|
+
} else if (c >= 56320 && c <= 57343)
|
|
9606
|
+
throw new Error("invalid generated expression Unicode");
|
|
9607
|
+
}
|
|
9608
|
+
}
|
|
9609
|
+
function expression(value, owner) {
|
|
9610
|
+
text(value.sql, 1024 * 1024);
|
|
9611
|
+
if (!value.sql.trim() || value.profile !== PROFILE)
|
|
9612
|
+
throw new Error("unsupported generated expression profile or empty SQL");
|
|
9613
|
+
if (!Array.isArray(value.schema_path) || value.schema_path.length > 32)
|
|
9614
|
+
throw new Error("invalid generated expression owner");
|
|
9615
|
+
value.schema_path.forEach((part) => text(part, 4096));
|
|
9616
|
+
if (JSON.stringify(value.schema_path) !== JSON.stringify(owner))
|
|
9617
|
+
throw new Error("generated expression owner differs from table schema");
|
|
9618
|
+
const context = value.evaluation_context;
|
|
9619
|
+
if (!context)
|
|
9620
|
+
throw new Error("generated expression requires explicit evaluation context");
|
|
9621
|
+
text(context.timezone, 256);
|
|
9622
|
+
text(context.collation, 256);
|
|
9623
|
+
if (!["asc", "desc"].includes(context.default_order) || ![
|
|
9624
|
+
"nulls_first",
|
|
9625
|
+
"nulls_last",
|
|
9626
|
+
"nulls_first_on_asc_last_on_desc",
|
|
9627
|
+
"nulls_last_on_asc_first_on_desc"
|
|
9628
|
+
].includes(context.default_null_order) || typeof context.preserve_insertion_order !== "boolean")
|
|
9629
|
+
throw new Error("invalid generated expression evaluation context");
|
|
9630
|
+
}
|
|
9631
|
+
function envelope(bytes) {
|
|
9632
|
+
if (!bytes.length || bytes.length > MAX_BYTES)
|
|
9633
|
+
throw new Error("invalid generated expression size");
|
|
9634
|
+
const data = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
9635
|
+
const kinds = [];
|
|
9636
|
+
const textBuffers = [];
|
|
9637
|
+
let offset = 0;
|
|
9638
|
+
while (offset < bytes.length) {
|
|
9639
|
+
const prefix = data.getInt32(offset, true) === -1 ? 8 : 4;
|
|
9640
|
+
const length = data.getInt32(offset + prefix - 4, true);
|
|
9641
|
+
offset += prefix;
|
|
9642
|
+
if (!length) {
|
|
9643
|
+
if (offset !== bytes.length || kinds.join(",") !== "1,3")
|
|
9644
|
+
throw new Error("SqlExpression requires exactly one complete IPC batch");
|
|
9645
|
+
return textBuffers;
|
|
9646
|
+
}
|
|
9647
|
+
if (length < 0 || offset + length > bytes.length)
|
|
9648
|
+
throw new Error("invalid expression IPC length");
|
|
9649
|
+
const p = offset + data.getUint32(offset, true), v = p - data.getInt32(p, true);
|
|
9650
|
+
const slot = (id) => 4 + id * 2 < data.getUint16(v, true) ? data.getUint16(v + 4 + id * 2, true) : 0;
|
|
9651
|
+
const kind = slot(1), body = slot(3);
|
|
9652
|
+
if (!kind)
|
|
9653
|
+
throw new Error("invalid expression IPC message");
|
|
9654
|
+
kinds.push(data.getUint8(p + kind));
|
|
9655
|
+
const bodyLength = body ? Number(data.getBigInt64(p + body, true)) : 0;
|
|
9656
|
+
if (bodyLength < 0 || bodyLength > bytes.length - offset - length)
|
|
9657
|
+
throw new Error("invalid expression IPC body");
|
|
9658
|
+
if (data.getUint8(p + kind) === 3) {
|
|
9659
|
+
const headerSlot = slot(2);
|
|
9660
|
+
const record = p + headerSlot + data.getUint32(p + headerSlot, true);
|
|
9661
|
+
const table = record - data.getInt32(record, true);
|
|
9662
|
+
const recordSlot = (id) => 4 + id * 2 < data.getUint16(table, true) ? data.getUint16(table + 4 + id * 2, true) : 0;
|
|
9663
|
+
if (recordSlot(3))
|
|
9664
|
+
throw new Error("compressed expression IPC is unsupported");
|
|
9665
|
+
const bufferSlot = recordSlot(2);
|
|
9666
|
+
const buffers = record + bufferSlot + data.getUint32(record + bufferSlot, true);
|
|
9667
|
+
if (data.getUint32(buffers, true) !== 26)
|
|
9668
|
+
throw new Error("invalid SqlExpression buffer layout");
|
|
9669
|
+
for (const index of [2, 5, 10, 14, 17, 20, 23]) {
|
|
9670
|
+
const buffer = buffers + 4 + index * 16;
|
|
9671
|
+
const start = Number(data.getBigInt64(buffer, true));
|
|
9672
|
+
const size = Number(data.getBigInt64(buffer + 8, true));
|
|
9673
|
+
if (start < 0 || size < 0 || start + size > bodyLength)
|
|
9674
|
+
throw new Error("invalid expression string buffer");
|
|
9675
|
+
textBuffers.push(bytes.subarray(offset + length + start, offset + length + start + size));
|
|
9676
|
+
}
|
|
9677
|
+
}
|
|
9678
|
+
offset += length + bodyLength;
|
|
9679
|
+
}
|
|
9680
|
+
throw new Error("expression IPC lacks end marker");
|
|
9681
|
+
}
|
|
9682
|
+
function shape(schema) {
|
|
9683
|
+
const field = (f) => [
|
|
9684
|
+
f.name,
|
|
9685
|
+
f.nullable,
|
|
9686
|
+
String(f.type),
|
|
9687
|
+
(f.type.children ?? []).map(field)
|
|
9688
|
+
];
|
|
9689
|
+
return JSON.stringify(schema.fields.map(field));
|
|
9690
|
+
}
|
|
9691
|
+
function validateEncoded(encoded, owner) {
|
|
9692
|
+
if (!encoded.length || encoded.length > 4 * Math.ceil(MAX_BYTES / 3))
|
|
9693
|
+
throw new Error("invalid generated expression size");
|
|
9694
|
+
const bytes = Uint8Array.from(atob(encoded), (c) => c.charCodeAt(0));
|
|
9695
|
+
if (base64(bytes) !== encoded)
|
|
9696
|
+
throw new Error("generated expression requires canonical base64");
|
|
9697
|
+
const textBuffers = envelope(bytes);
|
|
9698
|
+
const batch = deserializeBatch(bytes);
|
|
9699
|
+
if (batch.numRows !== 1 || shape(batch.schema) !== shape(SqlExpressionSchema))
|
|
9700
|
+
throw new Error("invalid SqlExpression record schema");
|
|
9701
|
+
const utf8 = new TextDecoder("utf-8", { fatal: true });
|
|
9702
|
+
textBuffers.forEach((buffer) => utf8.decode(buffer));
|
|
9703
|
+
const value = decodeSqlExpression(bytes);
|
|
9704
|
+
expression(value, owner);
|
|
9705
|
+
return value.sql;
|
|
9706
|
+
}
|
|
9707
|
+
function generatedExpressionMetadata(sql, owner) {
|
|
9708
|
+
try {
|
|
9709
|
+
validateColumnExpressionSql(sql, { usingColumns: true, generated: true });
|
|
9710
|
+
} catch (error) {
|
|
9711
|
+
throw new Error(`generated expression ${JSON.stringify(sql)}: ${error.message}`);
|
|
9712
|
+
}
|
|
9713
|
+
return base64(encodeSqlExpression(sqlExpression(sql, owner)));
|
|
9714
|
+
}
|
|
9715
|
+
function defaultExpressionMetadata(sql, owner) {
|
|
9716
|
+
validateColumnExpressionSql(sql, { usingColumns: false, generated: false });
|
|
9717
|
+
return base64(encodeSqlExpression(sqlExpression(sql, owner)));
|
|
9718
|
+
}
|
|
9719
|
+
function sqlExpression(sql, schemaPath) {
|
|
9720
|
+
const owner = [...schemaPath];
|
|
9721
|
+
const value = {
|
|
9722
|
+
sql,
|
|
9723
|
+
profile: PROFILE,
|
|
9724
|
+
schema_path: [...owner],
|
|
9725
|
+
evaluation_context: {
|
|
9726
|
+
timezone: "UTC",
|
|
9727
|
+
collation: "binary",
|
|
9728
|
+
default_order: "asc",
|
|
9729
|
+
default_null_order: "nulls_last",
|
|
9730
|
+
preserve_insertion_order: true
|
|
9731
|
+
}
|
|
9732
|
+
};
|
|
9733
|
+
expression(value, owner);
|
|
9734
|
+
return value;
|
|
9735
|
+
}
|
|
9736
|
+
function validateColumnExpressions(schema, owner, allowGenerated = true) {
|
|
9737
|
+
const type = (t) => {
|
|
9738
|
+
for (const f of t?.children ?? t?.fields ?? [])
|
|
9739
|
+
field(f);
|
|
9740
|
+
if (t?.dictionary)
|
|
9741
|
+
type(t.dictionary);
|
|
9742
|
+
};
|
|
9743
|
+
const topLevel = new Map;
|
|
9744
|
+
for (const f of schema.fields) {
|
|
9745
|
+
const key = String(f.name).toLowerCase();
|
|
9746
|
+
topLevel.set(key, [...topLevel.get(key) ?? [], f]);
|
|
9747
|
+
}
|
|
9748
|
+
const field = (f, top = false) => {
|
|
9749
|
+
const metadata = f.metadata ?? new Map;
|
|
9750
|
+
for (const key of metadata.keys()) {
|
|
9751
|
+
if (key.startsWith("vgi.column.generated.") && key !== GENERATED_EXPRESSION_KEY || key.startsWith("vgi.column.generation.") && key !== GENERATION_KEY)
|
|
9752
|
+
throw new Error("unknown generated metadata version");
|
|
9753
|
+
}
|
|
9754
|
+
const where = `column ${f.name}`;
|
|
9755
|
+
if (metadata.has("generated_expression"))
|
|
9756
|
+
throw new Error(`${where}: legacy generated_expression metadata is not read under vgi.v3; ` + "use generatedExpressionMetadata() (served tables are translated automatically)");
|
|
9757
|
+
if (metadata.has(DEFAULT_EXPRESSION_KEY)) {
|
|
9758
|
+
if (metadata.has("default") || metadata.has(GENERATED_EXPRESSION_KEY) || metadata.has(GENERATION_KEY))
|
|
9759
|
+
throw new Error(`${where}: canonical default conflicts with other column expression metadata`);
|
|
9760
|
+
const type = duckdbPrimitive(f);
|
|
9761
|
+
if (!type || !DEFAULT_TYPES.has(type))
|
|
9762
|
+
throw new Error(`${where}: DuckDB reads canonical defaults only for boolean, signed integer, float, decimal128 and utf8 columns`);
|
|
9763
|
+
const sql = validateEncoded(metadata.get(DEFAULT_EXPRESSION_KEY), owner);
|
|
9764
|
+
try {
|
|
9765
|
+
validateColumnExpressionSql(sql, { usingColumns: false, generated: false });
|
|
9766
|
+
} catch (error) {
|
|
9767
|
+
throw new Error(`${where}: default ${JSON.stringify(sql)}: ${error.message}`);
|
|
9768
|
+
}
|
|
9769
|
+
}
|
|
9770
|
+
if (metadata.has(GENERATED_EXPRESSION_KEY) !== metadata.has(GENERATION_KEY))
|
|
9771
|
+
throw new Error("generated expression and category must occur together");
|
|
9772
|
+
if (metadata.has(GENERATED_EXPRESSION_KEY)) {
|
|
9773
|
+
if (metadata.get(GENERATION_KEY) !== "virtual")
|
|
9774
|
+
throw new Error("only VIRTUAL generated columns are supported");
|
|
9775
|
+
if (metadata.has("default") || metadata.has("vgi.column.default.v1"))
|
|
9776
|
+
throw new Error("generated column cannot have a default");
|
|
9777
|
+
const sql = validateEncoded(metadata.get(GENERATED_EXPRESSION_KEY), owner);
|
|
9778
|
+
if (!allowGenerated)
|
|
9779
|
+
throw new Error("generated columns unsupported by this catalog");
|
|
9780
|
+
if (!f.nullable)
|
|
9781
|
+
throw new Error(`${where}: DuckDB requires generated columns to be nullable`);
|
|
9782
|
+
const type = duckdbPrimitive(f);
|
|
9783
|
+
if (!type || !GENERATED_TYPES.has(type))
|
|
9784
|
+
throw new Error(`${where}: DuckDB generated columns must be boolean, signed integer or utf8`);
|
|
9785
|
+
let references;
|
|
9786
|
+
try {
|
|
9787
|
+
references = validateColumnExpressionSql(sql, { usingColumns: true, generated: true });
|
|
9788
|
+
} catch (error) {
|
|
9789
|
+
throw new Error(`${where}: generated expression ${JSON.stringify(sql)}: ${error.message}`);
|
|
9790
|
+
}
|
|
9791
|
+
if (top) {
|
|
9792
|
+
for (const name of references) {
|
|
9793
|
+
const matches = topLevel.get(name.toLowerCase()) ?? [];
|
|
9794
|
+
if (matches.length !== 1)
|
|
9795
|
+
throw new Error(`${where}: generated expression references a missing or ambiguous column ${name}`);
|
|
9796
|
+
const operand = duckdbPrimitive(matches[0]);
|
|
9797
|
+
if (!operand || !GENERATED_TYPES.has(operand))
|
|
9798
|
+
throw new Error(`${where}: generated expression operand ${name} must be boolean, signed integer or utf8`);
|
|
9799
|
+
}
|
|
9800
|
+
}
|
|
9801
|
+
}
|
|
9802
|
+
type(f.type);
|
|
9803
|
+
};
|
|
9804
|
+
schema.fields.forEach((f) => field(f, true));
|
|
9805
|
+
}
|
|
9806
|
+
function validateColumnExpressionsIpc(bytes, owner, allowGenerated = true) {
|
|
9807
|
+
validateColumnExpressions(deserializeSchema(bytes), owner, allowGenerated);
|
|
9808
|
+
}
|
|
9809
|
+
|
|
9810
|
+
// src/catalog/constraints.ts
|
|
9811
|
+
var CONSTRAINT_RECORDS_READ = "vgi.constraint.records.read.v1";
|
|
9812
|
+
var ROW_SCALAR_EXPRESSION = "vgi.expression.duckdb.scalar.v1";
|
|
9813
|
+
var CONSTRAINT_CREATE = "vgi.constraint.create.v1";
|
|
9814
|
+
var CONSTRAINT_MUTATE = "vgi.constraint.mutate.v1";
|
|
9815
|
+
var CONSTRAINT_ENFORCE = "vgi.constraint.enforce.v1";
|
|
9816
|
+
var TRANSACTION_DDL = "vgi.transaction.ddl.v1";
|
|
9817
|
+
var CHECK_CONTEXT = {
|
|
9818
|
+
timezone: "UTC",
|
|
9819
|
+
collation: "binary",
|
|
9820
|
+
default_order: "asc",
|
|
9821
|
+
default_null_order: "nulls_last",
|
|
9822
|
+
preserve_insertion_order: true
|
|
9823
|
+
};
|
|
9824
|
+
function identifier(value, what) {
|
|
9825
|
+
if (typeof value !== "string" || !value || value.includes("\x00") || new TextEncoder().encode(value).length > 4096)
|
|
9826
|
+
throw new Error(`${what} must be a nonempty identifier without NUL (at most 4096 bytes)`);
|
|
9827
|
+
}
|
|
9828
|
+
function objectRef(kind, schemaPath, name, ownerTable) {
|
|
9829
|
+
return encodeASD(CatalogObjectRefSchema, { kind, schema_path: schemaPath, name, owner_table: ownerTable });
|
|
9830
|
+
}
|
|
9831
|
+
function checkPaths(paths, what, topLevelOnly) {
|
|
9832
|
+
if (paths.length > 1024)
|
|
9833
|
+
throw new Error(`${what}: too many column paths`);
|
|
9834
|
+
const seen = new Set;
|
|
9835
|
+
for (const path of paths) {
|
|
9836
|
+
if (path.length === 0 || path.length > 64)
|
|
9837
|
+
throw new Error(`${what}: column path must have 1..64 components`);
|
|
9838
|
+
if (topLevelOnly && path.length !== 1)
|
|
9839
|
+
throw new Error(`${what}: DuckDB reads nested column paths only for NOT_NULL; name a top-level column`);
|
|
9840
|
+
path.forEach((part) => identifier(part, `${what}: column path component`));
|
|
9841
|
+
const key = JSON.stringify(path);
|
|
9842
|
+
if (seen.has(key))
|
|
9843
|
+
throw new Error(`${what}: duplicate column path ${path.join(".")}`);
|
|
9844
|
+
seen.add(key);
|
|
9845
|
+
}
|
|
9846
|
+
}
|
|
9847
|
+
function constraintRecord(spec) {
|
|
9848
|
+
const what = `constraint '${spec.id}' on '${spec.table}'`;
|
|
9849
|
+
if (!spec.id || spec.id.includes("\x00"))
|
|
9850
|
+
throw new Error("constraint id must be nonempty without NUL");
|
|
9851
|
+
identifier(spec.table, "table");
|
|
9852
|
+
if (spec.schemaPath.length !== 1)
|
|
9853
|
+
throw new Error(`${what}: DuckDB reads only one-component schema paths`);
|
|
9854
|
+
identifier(spec.schemaPath[0], "schema");
|
|
9855
|
+
if (spec.enforcement !== "ENFORCED" || spec.validation !== "ALL_ROWS")
|
|
9856
|
+
throw new Error(`${what} is ${spec.enforcement}/${spec.validation}; DuckDB accepts only ENFORCED + ALL_ROWS records`);
|
|
9857
|
+
if (spec.declaredName !== undefined)
|
|
9858
|
+
identifier(spec.declaredName, `${what}: declaredName`);
|
|
9859
|
+
if (spec.kind === "CHECK" !== (spec.checkSql !== undefined))
|
|
9860
|
+
throw new Error("checkSql is required for CHECK and only CHECK");
|
|
9861
|
+
if (spec.kind === "CHECK" ? spec.columns.length !== 0 : spec.columns.length === 0)
|
|
9862
|
+
throw new Error(spec.kind === "CHECK" ? "CHECK takes no column paths" : `${spec.kind} requires column paths`);
|
|
9863
|
+
if (spec.kind === "NOT_NULL" && spec.columns.length !== 1)
|
|
9864
|
+
throw new Error("NOT_NULL requires exactly one column path");
|
|
9865
|
+
if (spec.kind === "FOREIGN_KEY" !== (spec.references !== undefined))
|
|
9866
|
+
throw new Error("references is required for FOREIGN_KEY and only FOREIGN_KEY");
|
|
9867
|
+
checkPaths(spec.columns, what, spec.kind !== "NOT_NULL");
|
|
9868
|
+
if (spec.checkSql !== undefined) {
|
|
9869
|
+
try {
|
|
9870
|
+
validateNumericCheckSql(spec.checkSql, () => {});
|
|
9871
|
+
} catch (error) {
|
|
9872
|
+
throw new Error(`${what}: ${error.message} (CHECK SQL: ${spec.checkSql})`);
|
|
9873
|
+
}
|
|
9874
|
+
}
|
|
9875
|
+
const ref = spec.references;
|
|
9876
|
+
if (ref) {
|
|
9877
|
+
if (ref.columns.length !== spec.columns.length)
|
|
9878
|
+
throw new Error("foreign key local and referenced arity must match");
|
|
9879
|
+
if (JSON.stringify(ref.schemaPath) !== JSON.stringify(spec.schemaPath))
|
|
9880
|
+
throw new Error(`${what}: DuckDB reads only foreign keys to a table in the same schema`);
|
|
9881
|
+
identifier(ref.table, `${what}: referenced table`);
|
|
9882
|
+
identifier(ref.constraintId, `${what}: referenced constraintId`);
|
|
9883
|
+
checkPaths(ref.columns, `${what} (referenced)`, true);
|
|
9884
|
+
}
|
|
9885
|
+
const check = spec.checkSql === undefined ? null : encodeASD(SqlExpressionSchema, {
|
|
9886
|
+
sql: spec.checkSql,
|
|
9887
|
+
profile: ROW_SCALAR_EXPRESSION,
|
|
9888
|
+
schema_path: spec.schemaPath,
|
|
9889
|
+
evaluation_context: CHECK_CONTEXT
|
|
9890
|
+
});
|
|
9891
|
+
const foreign = ref === undefined ? null : encodeASD(ForeignKeyDefinitionSchema, {
|
|
9892
|
+
referenced_table: objectRef("table", ref.schemaPath, ref.table, null),
|
|
9893
|
+
referenced_column_paths: ref.columns,
|
|
9894
|
+
match: "SIMPLE",
|
|
9895
|
+
on_update: "NO_ACTION",
|
|
9896
|
+
on_delete: "NO_ACTION"
|
|
9897
|
+
});
|
|
9898
|
+
return encodeASD(ConstraintInfoSchema, {
|
|
9899
|
+
ref: objectRef("constraint", spec.schemaPath, spec.id, spec.table),
|
|
9900
|
+
definition: encodeASD(ConstraintDefinitionSchema, {
|
|
9901
|
+
kind: spec.kind,
|
|
9902
|
+
column_paths: spec.columns,
|
|
9903
|
+
declared_name: spec.declaredName ?? null,
|
|
9904
|
+
check_expression: check,
|
|
9905
|
+
foreign_key: foreign
|
|
9906
|
+
}),
|
|
9907
|
+
enforcement: spec.enforcement,
|
|
9908
|
+
validation: spec.validation,
|
|
9909
|
+
referenced_constraint: ref === undefined ? null : objectRef("constraint", ref.schemaPath, ref.constraintId, ref.table)
|
|
9910
|
+
});
|
|
9911
|
+
}
|
|
9912
|
+
var KNOWN = {
|
|
9913
|
+
read: new Set([CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION, "vgi.index.definition.read.v1"]),
|
|
9914
|
+
ddl: new Set([CONSTRAINT_CREATE, CONSTRAINT_MUTATE, "vgi.index.definition.create.v1", "vgi.index.drop.v1"]),
|
|
9915
|
+
write: new Set([CONSTRAINT_ENFORCE]),
|
|
9916
|
+
transaction: new Set([TRANSACTION_DDL])
|
|
9917
|
+
};
|
|
9918
|
+
var REQUIRES = {
|
|
9919
|
+
[ROW_SCALAR_EXPRESSION]: [CONSTRAINT_RECORDS_READ],
|
|
9920
|
+
[CONSTRAINT_CREATE]: [CONSTRAINT_RECORDS_READ, CONSTRAINT_ENFORCE],
|
|
9921
|
+
[CONSTRAINT_MUTATE]: [CONSTRAINT_RECORDS_READ],
|
|
9922
|
+
[CONSTRAINT_ENFORCE]: [CONSTRAINT_RECORDS_READ],
|
|
9923
|
+
"vgi.index.definition.create.v1": ["vgi.index.definition.read.v1"],
|
|
9924
|
+
"vgi.index.drop.v1": ["vgi.index.definition.read.v1"]
|
|
9925
|
+
};
|
|
9926
|
+
var CATEGORIES = ["read", "ddl", "write", "transaction"];
|
|
9927
|
+
function catalogCapabilities(init = {}) {
|
|
9928
|
+
return {
|
|
9929
|
+
read: [...new Set(init.read ?? [])].sort(),
|
|
9930
|
+
ddl: [...new Set(init.ddl ?? [])].sort(),
|
|
9931
|
+
write: [...new Set(init.write ?? [])].sort(),
|
|
9932
|
+
transaction: [...new Set(init.transaction ?? [])].sort()
|
|
9933
|
+
};
|
|
9934
|
+
}
|
|
9935
|
+
function constraintCapabilities(options = {}) {
|
|
9936
|
+
const enforce = options.enforce || options.create;
|
|
9937
|
+
return catalogCapabilities({
|
|
9938
|
+
read: [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION],
|
|
9939
|
+
ddl: [...options.create ? [CONSTRAINT_CREATE] : [], ...options.mutate ? [CONSTRAINT_MUTATE] : []],
|
|
9940
|
+
write: enforce ? [CONSTRAINT_ENFORCE] : [],
|
|
9941
|
+
transaction: options.transactionDdl ? [TRANSACTION_DDL] : []
|
|
9942
|
+
});
|
|
9943
|
+
}
|
|
9944
|
+
function offeredCatalog(clientCapabilities) {
|
|
9945
|
+
if (clientCapabilities == null)
|
|
9946
|
+
return null;
|
|
9947
|
+
const client = clientCapabilities instanceof Uint8Array ? decodeASD(ClientCapabilitiesSchema, clientCapabilities) : clientCapabilities;
|
|
9948
|
+
return client.catalog == null ? null : decodeCatalogCapabilities(client.catalog);
|
|
9949
|
+
}
|
|
9950
|
+
function selectCatalogCapabilities(available, clientCapabilities, supportsTransactions = false) {
|
|
9951
|
+
const offered = offeredCatalog(clientCapabilities);
|
|
9952
|
+
if (offered == null)
|
|
9953
|
+
return catalogCapabilities();
|
|
9954
|
+
const chosen = new Set;
|
|
9955
|
+
for (const category of CATEGORIES)
|
|
9956
|
+
for (const p of available[category] ?? [])
|
|
9957
|
+
if (offered[category]?.includes(p))
|
|
9958
|
+
chosen.add(p);
|
|
9959
|
+
if (!supportsTransactions)
|
|
9960
|
+
chosen.delete(TRANSACTION_DDL);
|
|
9961
|
+
for (let changed = true;changed; ) {
|
|
9962
|
+
changed = false;
|
|
9963
|
+
for (const p of [...chosen])
|
|
9964
|
+
if ((REQUIRES[p] ?? []).some((r) => !chosen.has(r))) {
|
|
9965
|
+
chosen.delete(p);
|
|
9966
|
+
changed = true;
|
|
9967
|
+
}
|
|
9968
|
+
}
|
|
9969
|
+
const pick = (category) => (available[category] ?? []).filter((p) => chosen.has(p));
|
|
9970
|
+
return catalogCapabilities({ read: pick("read"), ddl: pick("ddl"), write: pick("write"), transaction: pick("transaction") });
|
|
9971
|
+
}
|
|
9972
|
+
function selectReadProfiles(available, clientCapabilities) {
|
|
9973
|
+
return selectCatalogCapabilities(catalogCapabilities({ read: [...available] }), clientCapabilities).read;
|
|
9974
|
+
}
|
|
9975
|
+
function defaultClientCapabilities(engine = "vgi-typescript") {
|
|
9976
|
+
return {
|
|
9977
|
+
engine,
|
|
9978
|
+
native_formats: [],
|
|
9979
|
+
catalogs: [],
|
|
9980
|
+
can_stream: true,
|
|
9981
|
+
filter_encodings: [],
|
|
9982
|
+
catalog: encodeCatalogCapabilities(catalogCapabilities({ read: [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION] })),
|
|
9983
|
+
query_pushdown: null
|
|
8909
9984
|
};
|
|
8910
9985
|
}
|
|
8911
|
-
function
|
|
9986
|
+
function capabilitiesEmpty(caps) {
|
|
9987
|
+
return caps == null || CATEGORIES.every((c) => (caps[c] ?? []).length === 0);
|
|
9988
|
+
}
|
|
9989
|
+
function readConstraintRecord(bytes) {
|
|
9990
|
+
const info = decodeASD(ConstraintInfoSchema, bytes);
|
|
9991
|
+
const ref = decodeASD(CatalogObjectRefSchema, info.ref);
|
|
9992
|
+
const def = decodeASD(ConstraintDefinitionSchema, info.definition);
|
|
9993
|
+
const fk = def.foreign_key == null ? null : decodeASD(ForeignKeyDefinitionSchema, def.foreign_key);
|
|
9994
|
+
const target = fk == null ? null : decodeASD(CatalogObjectRefSchema, fk.referenced_table);
|
|
9995
|
+
const targetKey = info.referenced_constraint == null ? null : decodeASD(CatalogObjectRefSchema, info.referenced_constraint);
|
|
8912
9996
|
return {
|
|
8913
|
-
|
|
8914
|
-
|
|
8915
|
-
|
|
8916
|
-
|
|
8917
|
-
|
|
8918
|
-
|
|
8919
|
-
|
|
8920
|
-
|
|
8921
|
-
|
|
9997
|
+
schemaPath: [...ref.schema_path],
|
|
9998
|
+
table: ref.owner_table ?? "",
|
|
9999
|
+
id: ref.name,
|
|
10000
|
+
kind: def.kind,
|
|
10001
|
+
columns: [...def.column_paths].map((p) => [...p]),
|
|
10002
|
+
enforcement: info.enforcement,
|
|
10003
|
+
validation: info.validation,
|
|
10004
|
+
declaredName: def.declared_name ?? null,
|
|
10005
|
+
checkSql: def.check_expression == null ? null : decodeASD(SqlExpressionSchema, def.check_expression).sql,
|
|
10006
|
+
references: fk == null || target == null ? null : {
|
|
10007
|
+
schemaPath: [...target.schema_path],
|
|
10008
|
+
table: target.name,
|
|
10009
|
+
columns: [...fk.referenced_column_paths].map((p) => [...p]),
|
|
10010
|
+
constraintId: targetKey?.name ?? null,
|
|
10011
|
+
constraintTable: targetKey?.owner_table ?? null,
|
|
10012
|
+
constraintSchemaPath: targetKey == null ? null : [...targetKey.schema_path],
|
|
10013
|
+
match: fk.match,
|
|
10014
|
+
onUpdate: fk.on_update,
|
|
10015
|
+
onDelete: fk.on_delete
|
|
10016
|
+
}
|
|
8922
10017
|
};
|
|
8923
10018
|
}
|
|
8924
|
-
|
|
10019
|
+
function fieldsByExactName(fields, name) {
|
|
10020
|
+
const out = [];
|
|
10021
|
+
fields.forEach((f, i) => {
|
|
10022
|
+
if (f.name === name)
|
|
10023
|
+
out.push(i);
|
|
10024
|
+
});
|
|
10025
|
+
return out;
|
|
10026
|
+
}
|
|
10027
|
+
function validateTableConstraints(table, schemaPath, fields, constraints) {
|
|
10028
|
+
if (constraints.length > 1024)
|
|
10029
|
+
throw new Error(`Table '${table}': too many constraints (at most 1024)`);
|
|
10030
|
+
const rowIds = fields.map((f, i) => isRowIdField(f) ? i : -1).filter((i) => i >= 0);
|
|
10031
|
+
if (rowIds.length > 1)
|
|
10032
|
+
throw new Error(`Table '${table}': at most one column may carry is_row_id`);
|
|
10033
|
+
const rowId = rowIds[0] ?? -1;
|
|
10034
|
+
const records = [];
|
|
10035
|
+
const required = new Set;
|
|
10036
|
+
const ids = new Set;
|
|
10037
|
+
const labels = new Set;
|
|
10038
|
+
let primaryKeys = 0;
|
|
10039
|
+
for (const bytes of constraints) {
|
|
10040
|
+
let record;
|
|
10041
|
+
try {
|
|
10042
|
+
record = readConstraintRecord(bytes);
|
|
10043
|
+
} catch (error) {
|
|
10044
|
+
throw new Error(`Table '${table}': undecodable constraint record: ${error.message}`);
|
|
10045
|
+
}
|
|
10046
|
+
const where = `Table '${table}': constraint '${record.id}'`;
|
|
10047
|
+
const fail = (message) => {
|
|
10048
|
+
throw new Error(`${where}: ${message}`);
|
|
10049
|
+
};
|
|
10050
|
+
if (schemaPath.length !== 1 || record.schemaPath.length !== 1 || record.schemaPath[0] !== schemaPath[0] || record.table !== table)
|
|
10051
|
+
fail(`belongs to ${JSON.stringify(record.schemaPath)}.${record.table || "?"}, not the serving table ` + `${JSON.stringify([...schemaPath])}.${table} (DuckDB reads only one-component schema paths)`);
|
|
10052
|
+
if (ids.has(record.id))
|
|
10053
|
+
fail("duplicate constraint id");
|
|
10054
|
+
ids.add(record.id);
|
|
10055
|
+
if (record.declaredName != null) {
|
|
10056
|
+
const label = record.declaredName.toLowerCase();
|
|
10057
|
+
if (labels.has(label))
|
|
10058
|
+
fail(`duplicate declared name '${record.declaredName}'`);
|
|
10059
|
+
labels.add(label);
|
|
10060
|
+
}
|
|
10061
|
+
if (record.enforcement !== "ENFORCED" || record.validation !== "ALL_ROWS")
|
|
10062
|
+
fail(`is ${record.enforcement}/${record.validation}; DuckDB accepts only ENFORCED + ALL_ROWS records`);
|
|
10063
|
+
try {
|
|
10064
|
+
checkPaths(record.columns, record.kind, record.kind !== "NOT_NULL");
|
|
10065
|
+
} catch (error) {
|
|
10066
|
+
fail(error.message);
|
|
10067
|
+
}
|
|
10068
|
+
const resolveTop = (path) => {
|
|
10069
|
+
const matches = fieldsByExactName(fields, path[0]);
|
|
10070
|
+
if (matches.length !== 1 || matches[0] === rowId)
|
|
10071
|
+
fail(`column path ${path.join(".")} names a missing, ambiguous or row-id column`);
|
|
10072
|
+
return matches[0];
|
|
10073
|
+
};
|
|
10074
|
+
switch (record.kind) {
|
|
10075
|
+
case "CHECK": {
|
|
10076
|
+
if (record.checkSql == null)
|
|
10077
|
+
fail("CHECK without an expression");
|
|
10078
|
+
validateCheckRecord(bytes, where, schemaPath, fields, rowId);
|
|
10079
|
+
break;
|
|
10080
|
+
}
|
|
10081
|
+
case "NOT_NULL": {
|
|
10082
|
+
if (record.columns.length !== 1)
|
|
10083
|
+
fail("NOT_NULL requires exactly one column path");
|
|
10084
|
+
const path = record.columns[0];
|
|
10085
|
+
let field = fields[resolveTop(path)];
|
|
10086
|
+
for (let depth = 1;depth < path.length; depth++) {
|
|
10087
|
+
const children = ordinaryStructChildren(field);
|
|
10088
|
+
if (!children)
|
|
10089
|
+
fail(`column path ${path.join(".")} must traverse ordinary STRUCT fields`);
|
|
10090
|
+
const matches = fieldsByExactName(children, path[depth]);
|
|
10091
|
+
if (matches.length !== 1)
|
|
10092
|
+
fail(`column path ${path.join(".")} names a missing or ambiguous nested field`);
|
|
10093
|
+
field = children[matches[0]];
|
|
10094
|
+
}
|
|
10095
|
+
if (path.length === 1 && isGeneratedField(field))
|
|
10096
|
+
fail(`column ${path[0]} is a generated column, which DuckDB requires to be nullable`);
|
|
10097
|
+
required.add(JSON.stringify(path));
|
|
10098
|
+
break;
|
|
10099
|
+
}
|
|
10100
|
+
case "PRIMARY_KEY":
|
|
10101
|
+
case "UNIQUE": {
|
|
10102
|
+
for (const path of record.columns) {
|
|
10103
|
+
const index = resolveTop(path);
|
|
10104
|
+
if (record.kind === "PRIMARY_KEY" && isGeneratedField(fields[index]))
|
|
10105
|
+
fail(`PRIMARY KEY column ${path[0]} is a generated column, which DuckDB requires to be nullable`);
|
|
10106
|
+
}
|
|
10107
|
+
if (record.kind === "PRIMARY_KEY") {
|
|
10108
|
+
if (++primaryKeys > 1)
|
|
10109
|
+
fail("a table may have only one PRIMARY KEY");
|
|
10110
|
+
for (const path of record.columns)
|
|
10111
|
+
required.add(JSON.stringify(path));
|
|
10112
|
+
}
|
|
10113
|
+
break;
|
|
10114
|
+
}
|
|
10115
|
+
case "FOREIGN_KEY": {
|
|
10116
|
+
record.columns.forEach(resolveTop);
|
|
10117
|
+
const ref = record.references;
|
|
10118
|
+
if (ref == null || ref.constraintId == null)
|
|
10119
|
+
fail("FOREIGN_KEY requires a referenced table and referenced constraint");
|
|
10120
|
+
if (ref.schemaPath.length !== 1 || ref.schemaPath[0] !== schemaPath[0] || JSON.stringify(ref.constraintSchemaPath) !== JSON.stringify(ref.schemaPath) || ref.constraintTable !== ref.table)
|
|
10121
|
+
fail("DuckDB reads only foreign keys to an identified key of a table in the same schema");
|
|
10122
|
+
if (ref.columns.length !== record.columns.length)
|
|
10123
|
+
fail("foreign key arity mismatch");
|
|
10124
|
+
try {
|
|
10125
|
+
checkPaths(ref.columns, "FOREIGN_KEY referenced", true);
|
|
10126
|
+
} catch (error) {
|
|
10127
|
+
fail(error.message);
|
|
10128
|
+
}
|
|
10129
|
+
if (ref.match !== undefined && ref.match !== "SIMPLE")
|
|
10130
|
+
fail(`MATCH ${ref.match} is unsupported; DuckDB reads only MATCH SIMPLE`);
|
|
10131
|
+
for (const action of [ref.onUpdate, ref.onDelete])
|
|
10132
|
+
if (action !== undefined && action !== "NO_ACTION" && action !== "RESTRICT")
|
|
10133
|
+
fail(`referential action ${action} is unsupported; DuckDB reads only NO_ACTION or RESTRICT`);
|
|
10134
|
+
break;
|
|
10135
|
+
}
|
|
10136
|
+
default:
|
|
10137
|
+
fail(`unknown constraint kind ${String(record.kind)}`);
|
|
10138
|
+
}
|
|
10139
|
+
records.push(record);
|
|
10140
|
+
}
|
|
10141
|
+
return { records, required };
|
|
10142
|
+
}
|
|
10143
|
+
function validateCheckRecord(bytes, where, schemaPath, fields, rowId) {
|
|
10144
|
+
const info = decodeASD(ConstraintInfoSchema, bytes);
|
|
10145
|
+
const def = decodeASD(ConstraintDefinitionSchema, info.definition);
|
|
10146
|
+
const expression = decodeASD(SqlExpressionSchema, def.check_expression);
|
|
10147
|
+
const fail = (message) => {
|
|
10148
|
+
throw new Error(`${where}: ${message}`);
|
|
10149
|
+
};
|
|
10150
|
+
if (expression.profile !== ROW_SCALAR_EXPRESSION)
|
|
10151
|
+
fail(`unsupported CHECK expression profile ${expression.profile}`);
|
|
10152
|
+
if (JSON.stringify([...expression.schema_path]) !== JSON.stringify([...schemaPath]))
|
|
10153
|
+
fail("CHECK expression belongs to another schema");
|
|
10154
|
+
const context = expression.evaluation_context ?? {};
|
|
10155
|
+
for (const [key, value] of Object.entries(CHECK_CONTEXT))
|
|
10156
|
+
if (context[key] !== value)
|
|
10157
|
+
fail(`unsupported CHECK evaluation context (${key} must be ${String(value)})`);
|
|
10158
|
+
try {
|
|
10159
|
+
validateNumericCheckSql(expression.sql, (name) => {
|
|
10160
|
+
const lower = name.toLowerCase();
|
|
10161
|
+
const matches = fields.map((f, i) => f.name.toLowerCase() === lower ? i : -1).filter((i) => i >= 0);
|
|
10162
|
+
if (matches.length > 1)
|
|
10163
|
+
throw new Error(`ambiguous CHECK column reference ${name}`);
|
|
10164
|
+
if (matches.length === 0 || matches[0] === rowId)
|
|
10165
|
+
throw new Error(`CHECK references a missing or row-id column ${name}`);
|
|
10166
|
+
const column = fields[matches[0]];
|
|
10167
|
+
if (column.metadata.has("ARROW:extension:name"))
|
|
10168
|
+
throw new Error(`CHECK operand ${name} has an extension type`);
|
|
10169
|
+
if (isGeneratedField(column))
|
|
10170
|
+
throw new Error(`CHECK operand ${name} is a generated column`);
|
|
10171
|
+
const type = duckdbPrimitive(column);
|
|
10172
|
+
if (!type || !["TINYINT", "SMALLINT", "INTEGER", "BIGINT", "FLOAT", "DOUBLE"].includes(type))
|
|
10173
|
+
throw new Error(`CHECK requires primitive signed numeric columns; ${name} is not one`);
|
|
10174
|
+
});
|
|
10175
|
+
} catch (error) {
|
|
10176
|
+
fail(`${error.message} (CHECK SQL: ${expression.sql})`);
|
|
10177
|
+
}
|
|
10178
|
+
}
|
|
10179
|
+
function validateForeignKeyTargets(tables) {
|
|
10180
|
+
const key = (schemaPath, name) => JSON.stringify([...schemaPath, name]);
|
|
10181
|
+
const byTable = new Map;
|
|
10182
|
+
for (const t of tables)
|
|
10183
|
+
byTable.set(key(t.schemaPath, t.name), t.constraints.map(readConstraintRecord));
|
|
10184
|
+
for (const t of tables) {
|
|
10185
|
+
for (const record of byTable.get(key(t.schemaPath, t.name)) ?? []) {
|
|
10186
|
+
if (record.kind !== "FOREIGN_KEY" || record.references == null)
|
|
10187
|
+
continue;
|
|
10188
|
+
const ref = record.references;
|
|
10189
|
+
const where = `Table '${t.name}': constraint '${record.id}'`;
|
|
10190
|
+
const target = byTable.get(key(ref.schemaPath, ref.table));
|
|
10191
|
+
if (!target)
|
|
10192
|
+
throw new Error(`${where}: references table ${[...ref.schemaPath, ref.table].join(".")}, which this catalog does not serve`);
|
|
10193
|
+
const key_ = target.find((r) => r.id === ref.constraintId);
|
|
10194
|
+
if (!key_ || key_.kind !== "PRIMARY_KEY" && key_.kind !== "UNIQUE")
|
|
10195
|
+
throw new Error(`${where}: referenced constraint '${ref.constraintId}' is not a PRIMARY_KEY or UNIQUE record of '${ref.table}'`);
|
|
10196
|
+
const want = new Set(ref.columns.map((p) => JSON.stringify(p)));
|
|
10197
|
+
if (key_.columns.length !== want.size || !key_.columns.every((p) => want.has(JSON.stringify(p))))
|
|
10198
|
+
throw new Error(`${where}: referenced columns do not match constraint '${ref.constraintId}' of '${ref.table}'`);
|
|
10199
|
+
}
|
|
10200
|
+
}
|
|
10201
|
+
}
|
|
10202
|
+
function servedConstraintFields(fields, required) {
|
|
10203
|
+
const rewrite = (list, prefix) => {
|
|
10204
|
+
let changed = false;
|
|
10205
|
+
const out = list.map((f) => {
|
|
10206
|
+
if (prefix.length === 0 && isRowIdField(f))
|
|
10207
|
+
return f;
|
|
10208
|
+
const path = [...prefix, f.name];
|
|
10209
|
+
const nullable = !required.has(JSON.stringify(path));
|
|
10210
|
+
const children = ordinaryStructChildren(f);
|
|
10211
|
+
const newChildren = children ? rewrite(children, path) : null;
|
|
10212
|
+
if (nullable === f.nullable && (newChildren == null || newChildren === children))
|
|
10213
|
+
return f;
|
|
10214
|
+
changed = true;
|
|
10215
|
+
const type = newChildren && newChildren !== children ? struct2(newChildren) : f.type;
|
|
10216
|
+
return field2(f.name, type, nullable, new Map(f.metadata));
|
|
10217
|
+
});
|
|
10218
|
+
return changed ? out : list;
|
|
10219
|
+
};
|
|
10220
|
+
return rewrite(fields, []);
|
|
10221
|
+
}
|
|
10222
|
+
function validateConstraintNullability(table, fields, constraints) {
|
|
10223
|
+
const schemaPath = constraints.length ? readConstraintRecord(constraints[0]).schemaPath : ["main"];
|
|
10224
|
+
validateTableConstraints(table, schemaPath, fields, constraints);
|
|
10225
|
+
}
|
|
10226
|
+
function translateLegacyGenerated(fields, owner, table) {
|
|
10227
|
+
let changed = false;
|
|
10228
|
+
const out = fields.map((f) => {
|
|
10229
|
+
const sql = f.metadata.get("generated_expression");
|
|
10230
|
+
if (sql === undefined)
|
|
10231
|
+
return f;
|
|
10232
|
+
if (f.metadata.has(GENERATED_EXPRESSION_KEY) || f.metadata.has(GENERATION_KEY))
|
|
10233
|
+
throw new Error(`Table '${table}': column ${f.name} carries both legacy generated_expression and canonical generated metadata`);
|
|
10234
|
+
const metadata = new Map(f.metadata);
|
|
10235
|
+
metadata.delete("generated_expression");
|
|
10236
|
+
metadata.set(GENERATED_EXPRESSION_KEY, generatedExpressionMetadata(sql, [...owner]));
|
|
10237
|
+
metadata.set(GENERATION_KEY, "virtual");
|
|
10238
|
+
changed = true;
|
|
10239
|
+
return field2(f.name, f.type, f.nullable, metadata);
|
|
10240
|
+
});
|
|
10241
|
+
return changed ? out : fields;
|
|
10242
|
+
}
|
|
10243
|
+
function servedTableSchema(table, schemaPath, schema, constraints) {
|
|
10244
|
+
let fields = translateLegacyGenerated(schema.fields, schemaPath, table);
|
|
10245
|
+
const { required } = validateTableConstraints(table, schemaPath, fields, constraints);
|
|
10246
|
+
fields = servedConstraintFields(fields, required);
|
|
10247
|
+
return fields === schema.fields ? schema : schema2(fields, schema.metadata);
|
|
10248
|
+
}
|
|
10249
|
+
function servedTableInfo(info) {
|
|
10250
|
+
if (!info.columns || info.columns.length === 0) {
|
|
10251
|
+
if ((info.constraints ?? []).length)
|
|
10252
|
+
throw new Error(`Table '${info.name}': constraints on a table without columns`);
|
|
10253
|
+
return info;
|
|
10254
|
+
}
|
|
10255
|
+
const schema = deserializeSchema(info.columns);
|
|
10256
|
+
const served = servedTableSchema(info.name, info.schema_path, schema, info.constraints ?? []);
|
|
10257
|
+
return served === schema ? info : { ...info, columns: serializeSchema(served) };
|
|
10258
|
+
}
|
|
8925
10259
|
// src/generated/vgi-client.ts
|
|
8926
10260
|
var encodeCatalogInfo = (v) => encodeASD(CatalogInfoSchema, v);
|
|
8927
10261
|
var decodeCatalogInfo = (b) => decodeASD(CatalogInfoSchema, b);
|
|
@@ -9113,6 +10447,56 @@ class CatalogInterface {
|
|
|
9113
10447
|
tableCreate(attachOpaqueData, schemaPath, name, columns, onConflict, constraintDefinitions, transactionOpaqueData) {
|
|
9114
10448
|
throw new CatalogReadOnlyError("table_create");
|
|
9115
10449
|
}
|
|
10450
|
+
catalogCapabilities(_attachOpaqueData) {
|
|
10451
|
+
const proto = CatalogInterface.prototype;
|
|
10452
|
+
if (this.tableConstraintsApply !== proto.tableConstraintsApply || this._implementsLegacyNotNull())
|
|
10453
|
+
return constraintCapabilities({ mutate: true, enforce: true });
|
|
10454
|
+
return null;
|
|
10455
|
+
}
|
|
10456
|
+
_implementsLegacyNotNull() {
|
|
10457
|
+
const proto = CatalogInterface.prototype;
|
|
10458
|
+
return this.tableNotNullSet !== proto.tableNotNullSet || this.tableNotNullDrop !== proto.tableNotNullDrop;
|
|
10459
|
+
}
|
|
10460
|
+
async tableConstraintsApply(request) {
|
|
10461
|
+
if (!this._implementsLegacyNotNull())
|
|
10462
|
+
throw new VgiError("catalog_table_constraints_apply is not implemented by this catalog", "UNIMPLEMENTED");
|
|
10463
|
+
const target = decodeCatalogObjectRef(request.table);
|
|
10464
|
+
const attach = request.attach_opaque_data;
|
|
10465
|
+
const tx = request.transaction_opaque_data ?? undefined;
|
|
10466
|
+
const schemaPath = [...target.schema_path];
|
|
10467
|
+
const read = async () => {
|
|
10468
|
+
const info = await this.tableGet(attach, schemaPath, target.name, undefined, undefined, tx);
|
|
10469
|
+
if (!info)
|
|
10470
|
+
throw new CatalogNotFoundError("Table", target.name);
|
|
10471
|
+
return info;
|
|
10472
|
+
};
|
|
10473
|
+
const before = await read();
|
|
10474
|
+
if (!sameBytes2(before.definition_revision ?? null, request.expected_revision))
|
|
10475
|
+
throw new VgiError(`Table '${target.name}': definition_revision changed; retry the statement`, "FAILED_PRECONDITION");
|
|
10476
|
+
const records = (before.constraints ?? []).map(readConstraintRecord);
|
|
10477
|
+
for (const bytes of request.changes) {
|
|
10478
|
+
const change = decodeConstraintChange(bytes);
|
|
10479
|
+
if (change.operation === "ADD" && change.definition != null) {
|
|
10480
|
+
const def = decodeConstraintDefinition(change.definition);
|
|
10481
|
+
if (def.kind === "NOT_NULL" && def.column_paths.length === 1 && def.column_paths[0].length === 1) {
|
|
10482
|
+
await this.tableNotNullSet(attach, schemaPath, target.name, [...def.column_paths[0]], false, tx);
|
|
10483
|
+
continue;
|
|
10484
|
+
}
|
|
10485
|
+
} else if (change.operation === "DROP" && change.ref != null) {
|
|
10486
|
+
const id = decodeCatalogObjectRef(change.ref).name;
|
|
10487
|
+
const record = records.find((r) => r.id === id);
|
|
10488
|
+
if (record?.kind === "NOT_NULL" && record.columns[0]?.length === 1) {
|
|
10489
|
+
await this.tableNotNullDrop(attach, schemaPath, target.name, record.columns[0], false, tx);
|
|
10490
|
+
continue;
|
|
10491
|
+
}
|
|
10492
|
+
}
|
|
10493
|
+
throw new VgiError("catalog_table_constraints_apply: only ADD/DROP of a top-level NOT_NULL routes to tableNotNullSet/tableNotNullDrop; implement tableConstraintsApply", "UNIMPLEMENTED");
|
|
10494
|
+
}
|
|
10495
|
+
const after = await read();
|
|
10496
|
+
if (after.definition_revision == null || sameBytes2(after.definition_revision, before.definition_revision ?? null))
|
|
10497
|
+
throw new VgiError(`Table '${target.name}': the NOT NULL change was applied but tableGet still serves the old definition_revision; ` + "a catalog using tableNotNullSet/tableNotNullDrop must rotate it (or implement tableConstraintsApply)", "INTERNAL");
|
|
10498
|
+
return { table: request.table, definition_revision: after.definition_revision, constraints: after.constraints ?? [] };
|
|
10499
|
+
}
|
|
9116
10500
|
tableDrop(attachOpaqueData, schemaPath, name, ignoreNotFound, transactionOpaqueData) {
|
|
9117
10501
|
throw new CatalogReadOnlyError("table_drop");
|
|
9118
10502
|
}
|
|
@@ -9201,211 +10585,55 @@ class CatalogInterface {
|
|
|
9201
10585
|
async catalogContents(attachOpaqueData, _ifNoneMatch) {
|
|
9202
10586
|
const schemas = await this.schemas(attachOpaqueData, undefined);
|
|
9203
10587
|
const contents = await Promise.all(schemas.map(async (schema) => {
|
|
9204
|
-
const counts = schema.estimated_object_count ?? {};
|
|
9205
|
-
const path = schema.path;
|
|
9206
|
-
const kind = async (countKey, list) => (counts[countKey] ?? 1) === 0 ? [] : [...await list()];
|
|
9207
|
-
const [tables, views, scalarFunctions, aggregateFunctions, tableFunctions, scalarMacros, tableMacros, indexes] = await Promise.all([
|
|
9208
|
-
kind("table", () => this.schemaContentsTables(attachOpaqueData, path)),
|
|
9209
|
-
kind("view", () => this.schemaContentsViews(attachOpaqueData, path)),
|
|
9210
|
-
kind("scalar_function", () => this.schemaContentsFunctions(attachOpaqueData, path, "scalar_function")),
|
|
9211
|
-
kind("aggregate_function", () => this.schemaContentsFunctions(attachOpaqueData, path, "aggregate_function")),
|
|
9212
|
-
kind("table_function", () => this.schemaContentsFunctions(attachOpaqueData, path, "table_function")),
|
|
9213
|
-
kind("macro", () => this.schemaContentsMacros(attachOpaqueData, path, "scalar_macro")),
|
|
9214
|
-
kind("macro", () => this.schemaContentsMacros(attachOpaqueData, path, "table_macro")),
|
|
9215
|
-
kind("index", () => this.schemaContentsIndexes(attachOpaqueData, path))
|
|
9216
|
-
]);
|
|
9217
|
-
return {
|
|
9218
|
-
schema,
|
|
9219
|
-
tables,
|
|
9220
|
-
views,
|
|
9221
|
-
scalar_functions: scalarFunctions,
|
|
9222
|
-
aggregate_functions: aggregateFunctions,
|
|
9223
|
-
table_functions: tableFunctions,
|
|
9224
|
-
scalar_macros: scalarMacros,
|
|
9225
|
-
table_macros: tableMacros,
|
|
9226
|
-
indexes
|
|
9227
|
-
};
|
|
9228
|
-
}));
|
|
9229
|
-
return { schemas: contents };
|
|
9230
|
-
}
|
|
9231
|
-
catalogContentsCacheable() {
|
|
9232
|
-
return this.catalogContentsAttachIndependent && this.catalogVersionFrozen;
|
|
9233
|
-
}
|
|
9234
|
-
catalogContentsOwner(_attachOpaqueData) {
|
|
9235
|
-
return this;
|
|
9236
|
-
}
|
|
9237
|
-
transactionBegin(attachOpaqueData) {
|
|
9238
|
-
return null;
|
|
9239
|
-
}
|
|
9240
|
-
transactionCommit(attachOpaqueData, transactionOpaqueData) {}
|
|
9241
|
-
transactionRollback(attachOpaqueData, transactionOpaqueData) {}
|
|
9242
|
-
}
|
|
9243
|
-
// src/catalog/column-expressions.ts
|
|
9244
|
-
init_arrow();
|
|
9245
|
-
var GENERATED_EXPRESSION_KEY = "vgi.column.generated.v1";
|
|
9246
|
-
var GENERATION_KEY = "vgi.column.generation.v1";
|
|
9247
|
-
var PROFILE = "vgi.expression.duckdb.scalar.v1";
|
|
9248
|
-
var MAX_BYTES = 8 * 1024 * 1024;
|
|
9249
|
-
var base64 = (bytes) => btoa(Array.from(bytes, (value) => String.fromCharCode(value)).join(""));
|
|
9250
|
-
function text(value, maximum) {
|
|
9251
|
-
if (typeof value !== "string" || !value || value.includes("\x00") || new TextEncoder().encode(value).length > maximum)
|
|
9252
|
-
throw new Error("invalid generated expression text");
|
|
9253
|
-
for (let i = 0;i < value.length; i++) {
|
|
9254
|
-
const c = value.charCodeAt(i);
|
|
9255
|
-
if (c >= 55296 && c <= 56319) {
|
|
9256
|
-
const d = value.charCodeAt(++i);
|
|
9257
|
-
if (!(d >= 56320 && d <= 57343))
|
|
9258
|
-
throw new Error("invalid generated expression Unicode");
|
|
9259
|
-
} else if (c >= 56320 && c <= 57343)
|
|
9260
|
-
throw new Error("invalid generated expression Unicode");
|
|
9261
|
-
}
|
|
9262
|
-
}
|
|
9263
|
-
function expression(value, owner) {
|
|
9264
|
-
text(value.sql, 1024 * 1024);
|
|
9265
|
-
if (!value.sql.trim() || value.profile !== PROFILE)
|
|
9266
|
-
throw new Error("unsupported generated expression profile or empty SQL");
|
|
9267
|
-
if (!Array.isArray(value.schema_path) || value.schema_path.length > 32)
|
|
9268
|
-
throw new Error("invalid generated expression owner");
|
|
9269
|
-
value.schema_path.forEach((part) => text(part, 4096));
|
|
9270
|
-
if (JSON.stringify(value.schema_path) !== JSON.stringify(owner))
|
|
9271
|
-
throw new Error("generated expression owner differs from table schema");
|
|
9272
|
-
const context = value.evaluation_context;
|
|
9273
|
-
if (!context)
|
|
9274
|
-
throw new Error("generated expression requires explicit evaluation context");
|
|
9275
|
-
text(context.timezone, 256);
|
|
9276
|
-
text(context.collation, 256);
|
|
9277
|
-
if (!["asc", "desc"].includes(context.default_order) || ![
|
|
9278
|
-
"nulls_first",
|
|
9279
|
-
"nulls_last",
|
|
9280
|
-
"nulls_first_on_asc_last_on_desc",
|
|
9281
|
-
"nulls_last_on_asc_first_on_desc"
|
|
9282
|
-
].includes(context.default_null_order) || typeof context.preserve_insertion_order !== "boolean")
|
|
9283
|
-
throw new Error("invalid generated expression evaluation context");
|
|
9284
|
-
}
|
|
9285
|
-
function envelope(bytes) {
|
|
9286
|
-
if (!bytes.length || bytes.length > MAX_BYTES)
|
|
9287
|
-
throw new Error("invalid generated expression size");
|
|
9288
|
-
const data = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
9289
|
-
const kinds = [];
|
|
9290
|
-
const textBuffers = [];
|
|
9291
|
-
let offset = 0;
|
|
9292
|
-
while (offset < bytes.length) {
|
|
9293
|
-
const prefix = data.getInt32(offset, true) === -1 ? 8 : 4;
|
|
9294
|
-
const length = data.getInt32(offset + prefix - 4, true);
|
|
9295
|
-
offset += prefix;
|
|
9296
|
-
if (!length) {
|
|
9297
|
-
if (offset !== bytes.length || kinds.join(",") !== "1,3")
|
|
9298
|
-
throw new Error("SqlExpression requires exactly one complete IPC batch");
|
|
9299
|
-
return textBuffers;
|
|
9300
|
-
}
|
|
9301
|
-
if (length < 0 || offset + length > bytes.length)
|
|
9302
|
-
throw new Error("invalid expression IPC length");
|
|
9303
|
-
const p = offset + data.getUint32(offset, true), v = p - data.getInt32(p, true);
|
|
9304
|
-
const slot = (id) => 4 + id * 2 < data.getUint16(v, true) ? data.getUint16(v + 4 + id * 2, true) : 0;
|
|
9305
|
-
const kind = slot(1), body = slot(3);
|
|
9306
|
-
if (!kind)
|
|
9307
|
-
throw new Error("invalid expression IPC message");
|
|
9308
|
-
kinds.push(data.getUint8(p + kind));
|
|
9309
|
-
const bodyLength = body ? Number(data.getBigInt64(p + body, true)) : 0;
|
|
9310
|
-
if (bodyLength < 0 || bodyLength > bytes.length - offset - length)
|
|
9311
|
-
throw new Error("invalid expression IPC body");
|
|
9312
|
-
if (data.getUint8(p + kind) === 3) {
|
|
9313
|
-
const headerSlot = slot(2);
|
|
9314
|
-
const record = p + headerSlot + data.getUint32(p + headerSlot, true);
|
|
9315
|
-
const table = record - data.getInt32(record, true);
|
|
9316
|
-
const recordSlot = (id) => 4 + id * 2 < data.getUint16(table, true) ? data.getUint16(table + 4 + id * 2, true) : 0;
|
|
9317
|
-
if (recordSlot(3))
|
|
9318
|
-
throw new Error("compressed expression IPC is unsupported");
|
|
9319
|
-
const bufferSlot = recordSlot(2);
|
|
9320
|
-
const buffers = record + bufferSlot + data.getUint32(record + bufferSlot, true);
|
|
9321
|
-
if (data.getUint32(buffers, true) !== 26)
|
|
9322
|
-
throw new Error("invalid SqlExpression buffer layout");
|
|
9323
|
-
for (const index of [2, 5, 10, 14, 17, 20, 23]) {
|
|
9324
|
-
const buffer = buffers + 4 + index * 16;
|
|
9325
|
-
const start = Number(data.getBigInt64(buffer, true));
|
|
9326
|
-
const size = Number(data.getBigInt64(buffer + 8, true));
|
|
9327
|
-
if (start < 0 || size < 0 || start + size > bodyLength)
|
|
9328
|
-
throw new Error("invalid expression string buffer");
|
|
9329
|
-
textBuffers.push(bytes.subarray(offset + length + start, offset + length + start + size));
|
|
9330
|
-
}
|
|
9331
|
-
}
|
|
9332
|
-
offset += length + bodyLength;
|
|
10588
|
+
const counts = schema.estimated_object_count ?? {};
|
|
10589
|
+
const path = schema.path;
|
|
10590
|
+
const kind = async (countKey, list) => (counts[countKey] ?? 1) === 0 ? [] : [...await list()];
|
|
10591
|
+
const [tables, views, scalarFunctions, aggregateFunctions, tableFunctions, scalarMacros, tableMacros, indexes] = await Promise.all([
|
|
10592
|
+
kind("table", () => this.schemaContentsTables(attachOpaqueData, path)),
|
|
10593
|
+
kind("view", () => this.schemaContentsViews(attachOpaqueData, path)),
|
|
10594
|
+
kind("scalar_function", () => this.schemaContentsFunctions(attachOpaqueData, path, "scalar_function")),
|
|
10595
|
+
kind("aggregate_function", () => this.schemaContentsFunctions(attachOpaqueData, path, "aggregate_function")),
|
|
10596
|
+
kind("table_function", () => this.schemaContentsFunctions(attachOpaqueData, path, "table_function")),
|
|
10597
|
+
kind("macro", () => this.schemaContentsMacros(attachOpaqueData, path, "scalar_macro")),
|
|
10598
|
+
kind("macro", () => this.schemaContentsMacros(attachOpaqueData, path, "table_macro")),
|
|
10599
|
+
kind("index", () => this.schemaContentsIndexes(attachOpaqueData, path))
|
|
10600
|
+
]);
|
|
10601
|
+
return {
|
|
10602
|
+
schema,
|
|
10603
|
+
tables,
|
|
10604
|
+
views,
|
|
10605
|
+
scalar_functions: scalarFunctions,
|
|
10606
|
+
aggregate_functions: aggregateFunctions,
|
|
10607
|
+
table_functions: tableFunctions,
|
|
10608
|
+
scalar_macros: scalarMacros,
|
|
10609
|
+
table_macros: tableMacros,
|
|
10610
|
+
indexes
|
|
10611
|
+
};
|
|
10612
|
+
}));
|
|
10613
|
+
return { schemas: contents };
|
|
9333
10614
|
}
|
|
9334
|
-
|
|
9335
|
-
|
|
9336
|
-
|
|
9337
|
-
|
|
9338
|
-
|
|
9339
|
-
|
|
9340
|
-
|
|
9341
|
-
|
|
9342
|
-
|
|
9343
|
-
|
|
9344
|
-
}
|
|
9345
|
-
function validateEncoded(encoded, owner) {
|
|
9346
|
-
if (!encoded.length || encoded.length > 4 * Math.ceil(MAX_BYTES / 3))
|
|
9347
|
-
throw new Error("invalid generated expression size");
|
|
9348
|
-
const bytes = Uint8Array.from(atob(encoded), (c) => c.charCodeAt(0));
|
|
9349
|
-
if (base64(bytes) !== encoded)
|
|
9350
|
-
throw new Error("generated expression requires canonical base64");
|
|
9351
|
-
const textBuffers = envelope(bytes);
|
|
9352
|
-
const batch = deserializeBatch(bytes);
|
|
9353
|
-
if (batch.numRows !== 1 || shape(batch.schema) !== shape(SqlExpressionSchema))
|
|
9354
|
-
throw new Error("invalid SqlExpression record schema");
|
|
9355
|
-
const utf8 = new TextDecoder("utf-8", { fatal: true });
|
|
9356
|
-
textBuffers.forEach((buffer) => utf8.decode(buffer));
|
|
9357
|
-
expression(decodeSqlExpression(bytes), owner);
|
|
9358
|
-
}
|
|
9359
|
-
function generatedExpressionMetadata(sql, owner) {
|
|
9360
|
-
const value = {
|
|
9361
|
-
sql,
|
|
9362
|
-
profile: PROFILE,
|
|
9363
|
-
schema_path: [...owner],
|
|
9364
|
-
evaluation_context: {
|
|
9365
|
-
timezone: "UTC",
|
|
9366
|
-
collation: "binary",
|
|
9367
|
-
default_order: "asc",
|
|
9368
|
-
default_null_order: "nulls_last",
|
|
9369
|
-
preserve_insertion_order: true
|
|
9370
|
-
}
|
|
9371
|
-
};
|
|
9372
|
-
expression(value, owner);
|
|
9373
|
-
return base64(encodeSqlExpression(value));
|
|
9374
|
-
}
|
|
9375
|
-
function validateColumnExpressions(schema, owner, allowGenerated = true) {
|
|
9376
|
-
const type = (t) => {
|
|
9377
|
-
for (const f of t?.children ?? t?.fields ?? [])
|
|
9378
|
-
field(f);
|
|
9379
|
-
if (t?.dictionary)
|
|
9380
|
-
type(t.dictionary);
|
|
9381
|
-
};
|
|
9382
|
-
const field = (f) => {
|
|
9383
|
-
const metadata = f.metadata ?? new Map;
|
|
9384
|
-
for (const key of metadata.keys()) {
|
|
9385
|
-
if (key.startsWith("vgi.column.generated.") && key !== GENERATED_EXPRESSION_KEY || key.startsWith("vgi.column.generation.") && key !== GENERATION_KEY)
|
|
9386
|
-
throw new Error("unknown generated metadata version");
|
|
9387
|
-
}
|
|
9388
|
-
if (metadata.has("generated_expression"))
|
|
9389
|
-
throw new Error("legacy generated expression requires explicit canonical translation");
|
|
9390
|
-
if (metadata.has(GENERATED_EXPRESSION_KEY) !== metadata.has(GENERATION_KEY))
|
|
9391
|
-
throw new Error("generated expression and category must occur together");
|
|
9392
|
-
if (metadata.has(GENERATED_EXPRESSION_KEY)) {
|
|
9393
|
-
if (metadata.get(GENERATION_KEY) !== "virtual")
|
|
9394
|
-
throw new Error("only VIRTUAL generated columns are supported");
|
|
9395
|
-
if (metadata.has("default") || metadata.has("vgi.column.default.v1"))
|
|
9396
|
-
throw new Error("generated column cannot have a default");
|
|
9397
|
-
validateEncoded(metadata.get(GENERATED_EXPRESSION_KEY), owner);
|
|
9398
|
-
if (!allowGenerated)
|
|
9399
|
-
throw new Error("generated columns unsupported by this catalog");
|
|
9400
|
-
}
|
|
9401
|
-
type(f.type);
|
|
9402
|
-
};
|
|
9403
|
-
schema.fields.forEach(field);
|
|
10615
|
+
catalogContentsCacheable() {
|
|
10616
|
+
return this.catalogContentsAttachIndependent && this.catalogVersionFrozen;
|
|
10617
|
+
}
|
|
10618
|
+
catalogContentsOwner(_attachOpaqueData) {
|
|
10619
|
+
return this;
|
|
10620
|
+
}
|
|
10621
|
+
transactionBegin(attachOpaqueData) {
|
|
10622
|
+
return null;
|
|
10623
|
+
}
|
|
10624
|
+
transactionCommit(attachOpaqueData, transactionOpaqueData) {}
|
|
10625
|
+
transactionRollback(attachOpaqueData, transactionOpaqueData) {}
|
|
9404
10626
|
}
|
|
9405
|
-
function
|
|
9406
|
-
|
|
10627
|
+
function sameBytes2(a, b) {
|
|
10628
|
+
if (a == null || b == null)
|
|
10629
|
+
return a == b;
|
|
10630
|
+
if (a.length !== b.length)
|
|
10631
|
+
return false;
|
|
10632
|
+
for (let i = 0;i < a.length; i++)
|
|
10633
|
+
if (a[i] !== b[i])
|
|
10634
|
+
return false;
|
|
10635
|
+
return true;
|
|
9407
10636
|
}
|
|
9408
|
-
|
|
9409
10637
|
// src/catalog/column-metadata.ts
|
|
9410
10638
|
function scalarText(value) {
|
|
9411
10639
|
for (let i = 0;i < value.length; i++) {
|
|
@@ -9557,9 +10785,21 @@ function validateTableInfoColumns(info) {
|
|
|
9557
10785
|
validateColumnExpressionsIpc(info.columns, info.schema_path);
|
|
9558
10786
|
}
|
|
9559
10787
|
}
|
|
10788
|
+
function servedValidatedTableInfo(info) {
|
|
10789
|
+
if (info.columns.length)
|
|
10790
|
+
validateColumnMetadataIpc(info.columns);
|
|
10791
|
+
const served = servedTableInfo(info);
|
|
10792
|
+
if (served.columns.length) {
|
|
10793
|
+
try {
|
|
10794
|
+
validateColumnExpressionsIpc(served.columns, served.schema_path);
|
|
10795
|
+
} catch (error) {
|
|
10796
|
+
throw new Error(`Table '${served.name}': ${error.message}`);
|
|
10797
|
+
}
|
|
10798
|
+
}
|
|
10799
|
+
return served;
|
|
10800
|
+
}
|
|
9560
10801
|
function encodeValidatedTableInfo(info) {
|
|
9561
|
-
|
|
9562
|
-
return encodeTableInfo(info);
|
|
10802
|
+
return encodeTableInfo(servedValidatedTableInfo(info));
|
|
9563
10803
|
}
|
|
9564
10804
|
|
|
9565
10805
|
// src/catalog/read-only.ts
|
|
@@ -9926,128 +11166,6 @@ function macroOverloads(macro, owner) {
|
|
|
9926
11166
|
}];
|
|
9927
11167
|
}
|
|
9928
11168
|
|
|
9929
|
-
// src/catalog/constraints.ts
|
|
9930
|
-
init_arrow();
|
|
9931
|
-
var CONSTRAINT_RECORDS_READ = "vgi.constraint.records.read.v1";
|
|
9932
|
-
var ROW_SCALAR_EXPRESSION = "vgi.expression.duckdb.scalar.v1";
|
|
9933
|
-
function objectRef(kind, schemaPath, name, ownerTable) {
|
|
9934
|
-
return encodeASD(CatalogObjectRefSchema, { kind, schema_path: schemaPath, name, owner_table: ownerTable });
|
|
9935
|
-
}
|
|
9936
|
-
function constraintRecord(spec) {
|
|
9937
|
-
if (!spec.id || spec.id.includes("\x00"))
|
|
9938
|
-
throw new Error("constraint id must be nonempty without NUL");
|
|
9939
|
-
if (spec.kind === "CHECK" !== (spec.checkSql !== undefined))
|
|
9940
|
-
throw new Error("checkSql is required for CHECK and only CHECK");
|
|
9941
|
-
if (spec.kind === "CHECK" ? spec.columns.length !== 0 : spec.columns.length === 0)
|
|
9942
|
-
throw new Error(spec.kind === "CHECK" ? "CHECK takes no column paths" : `${spec.kind} requires column paths`);
|
|
9943
|
-
if (spec.kind === "NOT_NULL" && spec.columns.length !== 1)
|
|
9944
|
-
throw new Error("NOT_NULL requires exactly one column path");
|
|
9945
|
-
if (spec.kind === "FOREIGN_KEY" !== (spec.references !== undefined))
|
|
9946
|
-
throw new Error("references is required for FOREIGN_KEY and only FOREIGN_KEY");
|
|
9947
|
-
if (spec.references && spec.references.columns.length !== spec.columns.length)
|
|
9948
|
-
throw new Error("foreign key local and referenced arity must match");
|
|
9949
|
-
const check = spec.checkSql === undefined ? null : encodeASD(SqlExpressionSchema, {
|
|
9950
|
-
sql: spec.checkSql,
|
|
9951
|
-
profile: ROW_SCALAR_EXPRESSION,
|
|
9952
|
-
schema_path: spec.schemaPath,
|
|
9953
|
-
evaluation_context: {
|
|
9954
|
-
timezone: "UTC",
|
|
9955
|
-
collation: "binary",
|
|
9956
|
-
default_order: "asc",
|
|
9957
|
-
default_null_order: "nulls_last",
|
|
9958
|
-
preserve_insertion_order: true
|
|
9959
|
-
}
|
|
9960
|
-
});
|
|
9961
|
-
const ref = spec.references;
|
|
9962
|
-
const foreign = ref === undefined ? null : encodeASD(ForeignKeyDefinitionSchema, {
|
|
9963
|
-
referenced_table: objectRef("table", ref.schemaPath, ref.table, null),
|
|
9964
|
-
referenced_column_paths: ref.columns,
|
|
9965
|
-
match: "SIMPLE",
|
|
9966
|
-
on_update: "NO_ACTION",
|
|
9967
|
-
on_delete: "NO_ACTION"
|
|
9968
|
-
});
|
|
9969
|
-
return encodeASD(ConstraintInfoSchema, {
|
|
9970
|
-
ref: objectRef("constraint", spec.schemaPath, spec.id, spec.table),
|
|
9971
|
-
definition: encodeASD(ConstraintDefinitionSchema, {
|
|
9972
|
-
kind: spec.kind,
|
|
9973
|
-
column_paths: spec.columns,
|
|
9974
|
-
declared_name: spec.declaredName ?? null,
|
|
9975
|
-
check_expression: check,
|
|
9976
|
-
foreign_key: foreign
|
|
9977
|
-
}),
|
|
9978
|
-
enforcement: spec.enforcement,
|
|
9979
|
-
validation: spec.validation,
|
|
9980
|
-
referenced_constraint: ref === undefined ? null : objectRef("constraint", ref.schemaPath, ref.constraintId, ref.table)
|
|
9981
|
-
});
|
|
9982
|
-
}
|
|
9983
|
-
function selectReadProfiles(available, clientCapabilities) {
|
|
9984
|
-
if (clientCapabilities == null || available.length === 0)
|
|
9985
|
-
return [];
|
|
9986
|
-
const client = decodeASD(ClientCapabilitiesSchema, clientCapabilities);
|
|
9987
|
-
const offered = client.catalog == null ? [] : decodeCatalogCapabilities(client.catalog).read;
|
|
9988
|
-
const selected = available.filter((p) => offered.includes(p));
|
|
9989
|
-
if (!selected.includes(CONSTRAINT_RECORDS_READ))
|
|
9990
|
-
return selected.filter((p) => p !== ROW_SCALAR_EXPRESSION).sort();
|
|
9991
|
-
return selected.sort();
|
|
9992
|
-
}
|
|
9993
|
-
function readConstraintRecord(bytes) {
|
|
9994
|
-
const info = decodeASD(ConstraintInfoSchema, bytes);
|
|
9995
|
-
const ref = decodeASD(CatalogObjectRefSchema, info.ref);
|
|
9996
|
-
const def = decodeASD(ConstraintDefinitionSchema, info.definition);
|
|
9997
|
-
const fk = def.foreign_key == null ? null : decodeASD(ForeignKeyDefinitionSchema, def.foreign_key);
|
|
9998
|
-
const target = fk == null ? null : decodeASD(CatalogObjectRefSchema, fk.referenced_table);
|
|
9999
|
-
const targetKey = info.referenced_constraint == null ? null : decodeASD(CatalogObjectRefSchema, info.referenced_constraint);
|
|
10000
|
-
return {
|
|
10001
|
-
schemaPath: [...ref.schema_path],
|
|
10002
|
-
table: ref.owner_table ?? "",
|
|
10003
|
-
id: ref.name,
|
|
10004
|
-
kind: def.kind,
|
|
10005
|
-
columns: [...def.column_paths].map((p) => [...p]),
|
|
10006
|
-
enforcement: info.enforcement,
|
|
10007
|
-
validation: info.validation,
|
|
10008
|
-
declaredName: def.declared_name ?? null,
|
|
10009
|
-
checkSql: def.check_expression == null ? null : decodeASD(SqlExpressionSchema, def.check_expression).sql,
|
|
10010
|
-
references: fk == null || target == null ? null : {
|
|
10011
|
-
schemaPath: [...target.schema_path],
|
|
10012
|
-
table: target.name,
|
|
10013
|
-
columns: [...fk.referenced_column_paths].map((p) => [...p]),
|
|
10014
|
-
constraintId: targetKey?.name ?? null
|
|
10015
|
-
}
|
|
10016
|
-
};
|
|
10017
|
-
}
|
|
10018
|
-
function ordinaryStructChildren(field) {
|
|
10019
|
-
if (!isStruct(field.type))
|
|
10020
|
-
return null;
|
|
10021
|
-
for (const key of field.metadata.keys())
|
|
10022
|
-
if (key === "ARROW:extension:name" || key.startsWith("vgi.logical_type."))
|
|
10023
|
-
return null;
|
|
10024
|
-
return field.type.children;
|
|
10025
|
-
}
|
|
10026
|
-
function validateConstraintNullability(table, fields, constraints) {
|
|
10027
|
-
const required = new Set;
|
|
10028
|
-
for (const bytes of constraints) {
|
|
10029
|
-
const record = readConstraintRecord(bytes);
|
|
10030
|
-
if (record.enforcement !== "ENFORCED" || record.validation !== "ALL_ROWS")
|
|
10031
|
-
throw new Error(`Table '${table}': constraint '${record.id}' is ${record.enforcement}/${record.validation}; ` + "DuckDB accepts only ENFORCED + ALL_ROWS records");
|
|
10032
|
-
if (record.kind === "NOT_NULL" || record.kind === "PRIMARY_KEY")
|
|
10033
|
-
for (const path of record.columns)
|
|
10034
|
-
required.add(JSON.stringify(path));
|
|
10035
|
-
}
|
|
10036
|
-
const walk = (children, prefix) => {
|
|
10037
|
-
for (const field of children) {
|
|
10038
|
-
const path = [...prefix, field.name];
|
|
10039
|
-
const key = JSON.stringify(path);
|
|
10040
|
-
if (field.nullable === required.has(key)) {
|
|
10041
|
-
throw new Error(field.nullable ? `Table '${table}': column ${path.join(".")} is in a NOT_NULL/PRIMARY_KEY record but its Arrow field is nullable` : `Table '${table}': column ${path.join(".")} is non-nullable in Arrow but no NOT_NULL/PRIMARY_KEY record names it; ` + "declare one with constraintRecord() or make the field nullable");
|
|
10042
|
-
}
|
|
10043
|
-
const nested = ordinaryStructChildren(field);
|
|
10044
|
-
if (nested)
|
|
10045
|
-
walk(nested, path);
|
|
10046
|
-
}
|
|
10047
|
-
};
|
|
10048
|
-
walk(fields, []);
|
|
10049
|
-
}
|
|
10050
|
-
|
|
10051
11169
|
// src/catalog/read-only.ts
|
|
10052
11170
|
var READ_ONLY_ITEM_ATTACH_ID = new TextEncoder().encode("readonly-catalog-");
|
|
10053
11171
|
|
|
@@ -10147,6 +11265,10 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
|
|
|
10147
11265
|
const hasConstraints = this._descriptor.schemas.some((s) => s.tables?.some((t) => (t.constraints?.length ?? 0) > 0) ?? false);
|
|
10148
11266
|
return hasConstraints ? [CONSTRAINT_RECORDS_READ, ROW_SCALAR_EXPRESSION] : [];
|
|
10149
11267
|
}
|
|
11268
|
+
catalogCapabilities(_attachOpaqueData) {
|
|
11269
|
+
const read = this.catalogReadProfiles();
|
|
11270
|
+
return read.length ? catalogCapabilities({ read }) : null;
|
|
11271
|
+
}
|
|
10150
11272
|
detach(attachOpaqueData) {
|
|
10151
11273
|
for (const [name, id] of this._attachments) {
|
|
10152
11274
|
if (bufferEquals(id, attachOpaqueData)) {
|
|
@@ -10207,8 +11329,12 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
|
|
|
10207
11329
|
const schema = this._descriptor.schemas.find((s) => schemaPathsEqual(schemaDescriptorPath(s), path));
|
|
10208
11330
|
if (!schema || !schema.tables)
|
|
10209
11331
|
return [];
|
|
10210
|
-
|
|
11332
|
+
const infos = await Promise.all(schema.tables.map(async (t) => {
|
|
11333
|
+
if (t.notNull?.length || t.unique?.length || t.primaryKey?.length || t.check?.length || t.foreignKey?.length) {
|
|
11334
|
+
throw new Error(`Table '${t.name}': notNull/unique/primaryKey/check/foreignKey are not sent under vgi.v3; ` + "declare canonical records with constraintRecord() in `constraints` instead");
|
|
11335
|
+
}
|
|
10211
11336
|
let colSchema;
|
|
11337
|
+
let bindFailed = false;
|
|
10212
11338
|
if (t.columns) {
|
|
10213
11339
|
colSchema = t.columns;
|
|
10214
11340
|
} else if (t.function) {
|
|
@@ -10230,26 +11356,31 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
|
|
|
10230
11356
|
colSchema = response.output_schema;
|
|
10231
11357
|
} catch {
|
|
10232
11358
|
colSchema = schema2([]);
|
|
11359
|
+
bindFailed = true;
|
|
10233
11360
|
}
|
|
10234
11361
|
} else {
|
|
10235
11362
|
colSchema = schema2([]);
|
|
10236
11363
|
}
|
|
10237
|
-
if (
|
|
10238
|
-
|
|
10239
|
-
|
|
10240
|
-
|
|
10241
|
-
|
|
10242
|
-
|
|
10243
|
-
|
|
10244
|
-
|
|
11364
|
+
if (!bindFailed) {
|
|
11365
|
+
if (t.defaults) {
|
|
11366
|
+
colSchema = applyDefaults(colSchema, t.defaults, path);
|
|
11367
|
+
}
|
|
11368
|
+
if (t.generatedColumns) {
|
|
11369
|
+
colSchema = applyGeneratedColumns(colSchema, t.generatedColumns, path, t.name);
|
|
11370
|
+
}
|
|
11371
|
+
if (t.columnComments) {
|
|
11372
|
+
colSchema = applyColumnComments(colSchema, t.columnComments, t.name);
|
|
11373
|
+
}
|
|
10245
11374
|
}
|
|
10246
11375
|
validateColumnMetadata(colSchema);
|
|
10247
|
-
|
|
10248
|
-
|
|
10249
|
-
|
|
10250
|
-
|
|
10251
|
-
|
|
11376
|
+
const constraints = bindFailed ? [] : t.constraints ?? [];
|
|
11377
|
+
colSchema = servedTableSchema(t.name, path, colSchema, constraints);
|
|
11378
|
+
try {
|
|
11379
|
+
validateColumnExpressions(colSchema, path);
|
|
11380
|
+
} catch (error) {
|
|
11381
|
+
throw new Error(`Table '${t.name}': ${error.message}`);
|
|
10252
11382
|
}
|
|
11383
|
+
const columns = serializeSchema(colSchema);
|
|
10253
11384
|
const requiredFilters = t.requiredFilters ?? [];
|
|
10254
11385
|
for (const group of requiredFilters) {
|
|
10255
11386
|
if (!Array.isArray(group) || group.length === 0)
|
|
@@ -10284,7 +11415,7 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
|
|
|
10284
11415
|
name: t.name,
|
|
10285
11416
|
schema_path: normalizeSchemaPath(path),
|
|
10286
11417
|
columns,
|
|
10287
|
-
constraints:
|
|
11418
|
+
constraints: [...constraints],
|
|
10288
11419
|
definition_revision: t.definitionRevision ?? null,
|
|
10289
11420
|
write_result_modes: {},
|
|
10290
11421
|
supports_column_statistics: t.statistics != null && Object.keys(t.statistics).length > 0,
|
|
@@ -10297,6 +11428,8 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
|
|
|
10297
11428
|
required_filters: requiredFilters
|
|
10298
11429
|
};
|
|
10299
11430
|
}));
|
|
11431
|
+
validateForeignKeyTargets(infos.map((info) => ({ schemaPath: info.schema_path, name: info.name, constraints: info.constraints })));
|
|
11432
|
+
return infos;
|
|
10300
11433
|
}
|
|
10301
11434
|
tableColumnStatisticsGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
|
|
10302
11435
|
const schema = this._descriptor.schemas.find((s) => schemaPathsEqual(schemaDescriptorPath(s), schemaPath));
|
|
@@ -10606,7 +11739,14 @@ function defaultToSql(value) {
|
|
|
10606
11739
|
const escaped = value.replace(/'/g, "''");
|
|
10607
11740
|
return `'${escaped}'`;
|
|
10608
11741
|
}
|
|
10609
|
-
function
|
|
11742
|
+
function canonicalDefault(type, value) {
|
|
11743
|
+
if (type === "BOOLEAN")
|
|
11744
|
+
return typeof value === "boolean";
|
|
11745
|
+
if (type === "VARCHAR")
|
|
11746
|
+
return typeof value === "string";
|
|
11747
|
+
return false;
|
|
11748
|
+
}
|
|
11749
|
+
function applyDefaults(schema, defaults, owner) {
|
|
10610
11750
|
let result = schema;
|
|
10611
11751
|
for (const [colName, value] of Object.entries(defaults)) {
|
|
10612
11752
|
const idx = result.fields.findIndex((f) => f.name === colName);
|
|
@@ -10614,7 +11754,12 @@ function applyDefaults(schema, defaults) {
|
|
|
10614
11754
|
continue;
|
|
10615
11755
|
const f = result.fields[idx];
|
|
10616
11756
|
const existingMeta = f.metadata ? new Map(f.metadata) : new Map;
|
|
10617
|
-
|
|
11757
|
+
const sql = defaultToSql(value);
|
|
11758
|
+
if (canonicalDefault(duckdbPrimitive(f), value)) {
|
|
11759
|
+
existingMeta.set("vgi.column.default.v1", defaultExpressionMetadata(sql, owner));
|
|
11760
|
+
} else {
|
|
11761
|
+
existingMeta.set("default", sql);
|
|
11762
|
+
}
|
|
10618
11763
|
const newField = field2(f.name, f.type, f.nullable, existingMeta);
|
|
10619
11764
|
const fields = [...result.fields];
|
|
10620
11765
|
fields[idx] = newField;
|
|
@@ -10622,17 +11767,21 @@ function applyDefaults(schema, defaults) {
|
|
|
10622
11767
|
}
|
|
10623
11768
|
return result;
|
|
10624
11769
|
}
|
|
10625
|
-
function applyGeneratedColumns(schema, generated, owner) {
|
|
11770
|
+
function applyGeneratedColumns(schema, generated, owner, table) {
|
|
10626
11771
|
let result = schema;
|
|
10627
11772
|
for (const [colName, expression] of Object.entries(generated)) {
|
|
10628
11773
|
const idx = result.fields.findIndex((f) => f.name === colName);
|
|
10629
11774
|
if (idx < 0)
|
|
10630
|
-
throw new Error(`
|
|
11775
|
+
throw new Error(`Table '${table}': generatedColumns names unknown column ${colName}`);
|
|
10631
11776
|
const f = result.fields[idx];
|
|
10632
11777
|
const existingMeta = f.metadata ? new Map(f.metadata) : new Map;
|
|
10633
11778
|
if (existingMeta.has(GENERATED_EXPRESSION_KEY) || existingMeta.has("generated_expression"))
|
|
10634
|
-
throw new Error(
|
|
10635
|
-
|
|
11779
|
+
throw new Error(`Table '${table}': generatedColumns for ${colName} conflicts with existing expression metadata`);
|
|
11780
|
+
try {
|
|
11781
|
+
existingMeta.set(GENERATED_EXPRESSION_KEY, generatedExpressionMetadata(expression, owner));
|
|
11782
|
+
} catch (error) {
|
|
11783
|
+
throw new Error(`Table '${table}': column ${colName}: ${error.message}`);
|
|
11784
|
+
}
|
|
10636
11785
|
existingMeta.set(GENERATION_KEY, "virtual");
|
|
10637
11786
|
const newField = field2(f.name, f.type, f.nullable, existingMeta);
|
|
10638
11787
|
const fields = [...result.fields];
|
|
@@ -10641,12 +11790,12 @@ function applyGeneratedColumns(schema, generated, owner) {
|
|
|
10641
11790
|
}
|
|
10642
11791
|
return result;
|
|
10643
11792
|
}
|
|
10644
|
-
function applyColumnComments(schema, comments) {
|
|
11793
|
+
function applyColumnComments(schema, comments, table) {
|
|
10645
11794
|
let result = schema;
|
|
10646
11795
|
for (const [colName, comment] of Object.entries(comments)) {
|
|
10647
11796
|
const idx = result.fields.findIndex((f) => f.name === colName);
|
|
10648
11797
|
if (idx < 0)
|
|
10649
|
-
throw new Error(`
|
|
11798
|
+
throw new Error(`Table '${table}': columnComments names unknown column ${colName}`);
|
|
10650
11799
|
const f = result.fields[idx];
|
|
10651
11800
|
const existingMeta = f.metadata ? new Map(f.metadata) : new Map;
|
|
10652
11801
|
existingMeta.set("comment", comment);
|
|
@@ -10776,6 +11925,29 @@ function sameSpelling(left, right) {
|
|
|
10776
11925
|
const b = normalizeSchemaPath(right);
|
|
10777
11926
|
return a.length === b.length && a.every((part, i) => part === b[i]);
|
|
10778
11927
|
}
|
|
11928
|
+
// src/catalog/indexes.ts
|
|
11929
|
+
var NO_OPTIONS_B64 = "/////zgAAAAQAAAAAAAKABAADgAHAAgACgAAAAAAAAEQAAAAAAAEAAgACAAAAAQACAAAAAQAAAAAAAAAAAAAAP////9QAAAAFAAAAAAAAAAAAAoADgAMAAcACAAKAAAAAAAAAxAAAAAEAAoAGAAMAAgABAAKAAAAFAAAABgAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////AAAAAA==";
|
|
11930
|
+
function emptyIndexOptions() {
|
|
11931
|
+
return Uint8Array.from(atob(NO_OPTIONS_B64), (c) => c.charCodeAt(0));
|
|
11932
|
+
}
|
|
11933
|
+
function canonicalIndex(spec) {
|
|
11934
|
+
if (spec.columns.length === 0)
|
|
11935
|
+
throw new Error(`index on '${spec.table}' requires at least one key`);
|
|
11936
|
+
if (!spec.algorithm)
|
|
11937
|
+
throw new Error("index algorithm must be nonempty");
|
|
11938
|
+
const values = spec.options ?? emptyIndexOptions();
|
|
11939
|
+
return {
|
|
11940
|
+
definition: encodeASD(IndexDefinitionSchema, {
|
|
11941
|
+
table: encodeASD(CatalogObjectRefSchema, { kind: "table", schema_path: spec.schemaPath, name: spec.table, owner_table: null }),
|
|
11942
|
+
algorithm: spec.algorithm,
|
|
11943
|
+
keys: spec.columns.map((path) => encodeASD(IndexKeySchema, { column_path: path, expression: null })),
|
|
11944
|
+
options: values,
|
|
11945
|
+
constraint_type: spec.constraintType ?? "NONE",
|
|
11946
|
+
associated_constraint: spec.associatedConstraintId == null ? null : encodeASD(CatalogObjectRefSchema, { kind: "constraint", schema_path: spec.schemaPath, name: spec.associatedConstraintId, owner_table: spec.table })
|
|
11947
|
+
}),
|
|
11948
|
+
options: encodeASD(OptionStateSchema, { values, explicit_names: spec.explicitOptionNames ?? [] })
|
|
11949
|
+
};
|
|
11950
|
+
}
|
|
10779
11951
|
// node_modules/@noble/ciphers/utils.js
|
|
10780
11952
|
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
|
|
10781
11953
|
function isBytes(a) {
|
|
@@ -11712,6 +12884,12 @@ class CompositeCatalogInterface extends CatalogInterface {
|
|
|
11712
12884
|
async tableNotNullDrop(...args) {
|
|
11713
12885
|
await this._route(args[0]).tableNotNullDrop(...args);
|
|
11714
12886
|
}
|
|
12887
|
+
async tableConstraintsApply(request) {
|
|
12888
|
+
return await this._route(request.attach_opaque_data).tableConstraintsApply(request);
|
|
12889
|
+
}
|
|
12890
|
+
async catalogCapabilities(attachOpaqueData) {
|
|
12891
|
+
return await this._route(attachOpaqueData).catalogCapabilities(attachOpaqueData);
|
|
12892
|
+
}
|
|
11715
12893
|
async viewCreate(...args) {
|
|
11716
12894
|
await this._route(args[0]).viewCreate(...args);
|
|
11717
12895
|
}
|
|
@@ -14827,12 +16005,10 @@ import { ExternalRef, publishExternalResult, resolveExternalLocation } from "@qu
|
|
|
14827
16005
|
var schemaPathKey2 = (path) => JSON.stringify(path.map((part) => part.toLowerCase()));
|
|
14828
16006
|
var CATALOG_STREAM_KINDS = ["schemas", "tables", "views", "functions", "macros", "indexes"];
|
|
14829
16007
|
function encodeCatalogStreams(inventory) {
|
|
14830
|
-
|
|
14831
|
-
for (const table of schema.tables)
|
|
14832
|
-
validateTableInfoColumns(table);
|
|
16008
|
+
const tables = inventory.flatMap((s) => s.tables.map(servedValidatedTableInfo));
|
|
14833
16009
|
const streams = {
|
|
14834
16010
|
schemas: encodeASDCollection(SchemaInfoSchema, inventory.map((s) => s.schema)),
|
|
14835
|
-
tables: encodeASDCollection(TableInfoSchema,
|
|
16011
|
+
tables: encodeASDCollection(TableInfoSchema, tables),
|
|
14836
16012
|
views: encodeASDCollection(ViewInfoSchema, inventory.flatMap((s) => s.views)),
|
|
14837
16013
|
functions: encodeASDCollection(FunctionInfoSchema, inventory.flatMap((s) => [...s.scalar_functions, ...s.aggregate_functions, ...s.table_functions])),
|
|
14838
16014
|
macros: encodeASDCollection(MacroInfoSchema, inventory.flatMap((s) => [...s.scalar_macros, ...s.table_macros])),
|
|
@@ -15888,13 +17064,10 @@ function catalogAdminHandlers(getCatalog, signingKey) {
|
|
|
15888
17064
|
}
|
|
15889
17065
|
const clientCapabilities = innerParams.client_capabilities == null ? null : toUint8Array(innerParams.client_capabilities);
|
|
15890
17066
|
const result = await cat.attach(innerParams.name, optionsDict, innerParams.data_version_spec ?? null, innerParams.implementation_version ?? null, clientCapabilities);
|
|
15891
|
-
|
|
15892
|
-
|
|
15893
|
-
|
|
15894
|
-
result.selected_capabilities = encodeCatalogCapabilities(
|
|
15895
|
-
...chosen,
|
|
15896
|
-
read: selectReadProfiles(available.read, clientCapabilities)
|
|
15897
|
-
});
|
|
17067
|
+
const advertised = result.catalog_capabilities != null ? decodeCatalogCapabilities(toUint8Array(result.catalog_capabilities)) : await cat.catalogCapabilities(toUint8Array(result.attach_opaque_data));
|
|
17068
|
+
if (!capabilitiesEmpty(advertised)) {
|
|
17069
|
+
result.catalog_capabilities = encodeCatalogCapabilities(catalogCapabilities(advertised));
|
|
17070
|
+
result.selected_capabilities = encodeCatalogCapabilities(selectCatalogCapabilities(advertised, clientCapabilities, result.supports_transactions ?? false));
|
|
15898
17071
|
}
|
|
15899
17072
|
const sealedAttach = await sealAttach(toUint8Array(result.attach_opaque_data), ctx?.auth, signingKey);
|
|
15900
17073
|
return wrapResult(buildCatalogAttachResult({
|
|
@@ -16031,27 +17204,39 @@ import { MethodNotImplementedError as MethodNotImplementedError4 } from "@query-
|
|
|
16031
17204
|
// src/catalog/unconstrained-columns.ts
|
|
16032
17205
|
init_arrow();
|
|
16033
17206
|
import { MethodNotImplementedError as MethodNotImplementedError3 } from "@query-farm/vgi-rpc";
|
|
16034
|
-
function
|
|
16035
|
-
const
|
|
17207
|
+
function requireCreateColumns(columns, constraintDefinitions = []) {
|
|
17208
|
+
const required = new Set;
|
|
17209
|
+
for (const bytes of constraintDefinitions) {
|
|
17210
|
+
let def;
|
|
17211
|
+
try {
|
|
17212
|
+
def = decodeConstraintDefinition(bytes);
|
|
17213
|
+
} catch (error) {
|
|
17214
|
+
throw new Error(`catalog_table_create: undecodable constraint definition: ${error.message}`);
|
|
17215
|
+
}
|
|
17216
|
+
if (def.kind === "NOT_NULL" || def.kind === "PRIMARY_KEY")
|
|
17217
|
+
for (const path of def.column_paths)
|
|
17218
|
+
required.add(JSON.stringify([...path]));
|
|
17219
|
+
}
|
|
17220
|
+
const visit = (field, path, depth) => {
|
|
16036
17221
|
if (depth > 64)
|
|
16037
17222
|
throw new MethodNotImplementedError3("catalog_table_create: column nesting exceeds supported depth");
|
|
16038
|
-
if (
|
|
17223
|
+
if (depth === 0 && field.metadata?.has("is_row_id"))
|
|
16039
17224
|
return;
|
|
16040
17225
|
for (const key of field.metadata?.keys() ?? []) {
|
|
16041
17226
|
if (key === "ARROW:extension:name" || key.startsWith("vgi.logical_type.")) {
|
|
16042
17227
|
throw new MethodNotImplementedError3("catalog_table_create: logical column types require negotiation");
|
|
16043
17228
|
}
|
|
16044
17229
|
}
|
|
16045
|
-
if (!field.nullable) {
|
|
16046
|
-
throw new MethodNotImplementedError3(
|
|
17230
|
+
if (!field.nullable && !required.has(JSON.stringify(path))) {
|
|
17231
|
+
throw new MethodNotImplementedError3(`catalog_table_create: column ${path.join(".")} is non-nullable but no NOT_NULL/PRIMARY_KEY definition names it`);
|
|
16047
17232
|
}
|
|
16048
17233
|
if (isStruct(field.type)) {
|
|
16049
17234
|
for (const child of field.type.children)
|
|
16050
|
-
visit(child,
|
|
17235
|
+
visit(child, [...path, child.name], depth + 1);
|
|
16051
17236
|
}
|
|
16052
17237
|
};
|
|
16053
17238
|
for (const field of deserializeSchema(columns).fields)
|
|
16054
|
-
visit(field,
|
|
17239
|
+
visit(field, [field.name], 0);
|
|
16055
17240
|
}
|
|
16056
17241
|
|
|
16057
17242
|
// src/protocol/handlers/catalog/table.ts
|
|
@@ -16073,19 +17258,57 @@ function catalogTableHandlers(getCatalog, signingKey) {
|
|
|
16073
17258
|
const catalogTableCreate = catalogHandler(signingKey, async (params) => {
|
|
16074
17259
|
if (params.constraint_definitions == null)
|
|
16075
17260
|
throw new Error("constraint_definitions is required");
|
|
16076
|
-
|
|
16077
|
-
throw new MethodNotImplementedError4("catalog_table_create: canonical constraint enforcement is not supported");
|
|
16078
|
-
}
|
|
17261
|
+
const definitions = Array.from(params.constraint_definitions, (d) => toUint8Array(d));
|
|
16079
17262
|
if (params.comment != null || params.tags != null || params.options != null || params.layout != null) {
|
|
16080
17263
|
throw new MethodNotImplementedError4("catalog_table_create: table metadata/options/layout profiles are not supported");
|
|
16081
17264
|
}
|
|
17265
|
+
const attach = toUint8Array(params.attach_opaque_data);
|
|
17266
|
+
const cat = getCatalog();
|
|
17267
|
+
if (definitions.length > 0) {
|
|
17268
|
+
const caps = await cat.catalogCapabilities(attach);
|
|
17269
|
+
if (caps != null && !(caps.ddl.includes(CONSTRAINT_CREATE) && caps.write.includes(CONSTRAINT_ENFORCE))) {
|
|
17270
|
+
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");
|
|
17271
|
+
}
|
|
17272
|
+
}
|
|
16082
17273
|
validateColumnMetadataIpc(toUint8Array(params.columns));
|
|
16083
17274
|
validateColumnExpressionsIpc(toUint8Array(params.columns), params.schema_path);
|
|
16084
|
-
|
|
16085
|
-
|
|
16086
|
-
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);
|
|
17275
|
+
requireCreateColumns(toUint8Array(params.columns), definitions);
|
|
17276
|
+
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);
|
|
16087
17277
|
return {};
|
|
16088
17278
|
});
|
|
17279
|
+
const catalogTableConstraintsApply = catalogHandler(signingKey, async (params) => {
|
|
17280
|
+
const attach = toUint8Array(params.attach_opaque_data);
|
|
17281
|
+
const cat = getCatalog();
|
|
17282
|
+
const caps = await cat.catalogCapabilities(attach);
|
|
17283
|
+
if (caps != null && !caps.ddl.includes(CONSTRAINT_MUTATE)) {
|
|
17284
|
+
throw new MethodNotImplementedError4("catalog_table_constraints_apply: this catalog does not advertise vgi.constraint.mutate.v1");
|
|
17285
|
+
}
|
|
17286
|
+
const table = toUint8Array(params.table);
|
|
17287
|
+
const expected = toUint8Array(params.expected_revision);
|
|
17288
|
+
const changes = Array.from(params.changes, (c) => toUint8Array(c));
|
|
17289
|
+
if (expected.length === 0 || changes.length === 0)
|
|
17290
|
+
throw new Error("catalog_table_constraints_apply: empty revision or change list");
|
|
17291
|
+
const snapshot = await cat.tableConstraintsApply({
|
|
17292
|
+
attach_opaque_data: attach,
|
|
17293
|
+
table,
|
|
17294
|
+
expected_revision: expected,
|
|
17295
|
+
changes,
|
|
17296
|
+
transaction_opaque_data: params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : null
|
|
17297
|
+
});
|
|
17298
|
+
const want = decodeCatalogObjectRef(table);
|
|
17299
|
+
const got = decodeCatalogObjectRef(toUint8Array(snapshot.table));
|
|
17300
|
+
if (got.name !== want.name || JSON.stringify([...got.schema_path]) !== JSON.stringify([...want.schema_path]))
|
|
17301
|
+
throw new Error("catalog_table_constraints_apply: the catalog returned a snapshot of a different table");
|
|
17302
|
+
const revision = toUint8Array(snapshot.definition_revision);
|
|
17303
|
+
if (revision.length === 0 || revision.length === expected.length && revision.every((b, i) => b === expected[i]))
|
|
17304
|
+
throw new Error(`catalog_table_constraints_apply: table '${want.name}' must return a new, nonempty definition_revision`);
|
|
17305
|
+
for (const record of snapshot.constraints) {
|
|
17306
|
+
const view = readConstraintRecord(toUint8Array(record));
|
|
17307
|
+
if (view.table !== want.name || JSON.stringify(view.schemaPath) !== JSON.stringify([...want.schema_path]))
|
|
17308
|
+
throw new Error(`catalog_table_constraints_apply: constraint '${view.id}' belongs to another table`);
|
|
17309
|
+
}
|
|
17310
|
+
return wrapResult({ table, definition_revision: revision, constraints: snapshot.constraints.map((c) => toUint8Array(c)) }, CatalogTableConstraintsApplyResultSchema);
|
|
17311
|
+
});
|
|
16089
17312
|
const catalogTableDrop = catalogHandler(signingKey, async (params) => {
|
|
16090
17313
|
const cat = getCatalog();
|
|
16091
17314
|
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);
|
|
@@ -16173,9 +17396,7 @@ function catalogTableHandlers(getCatalog, signingKey) {
|
|
|
16173
17396
|
return {};
|
|
16174
17397
|
});
|
|
16175
17398
|
return {
|
|
16176
|
-
catalogTableConstraintsApply
|
|
16177
|
-
throw new MethodNotImplementedError4("catalog_table_constraints_apply");
|
|
16178
|
-
},
|
|
17399
|
+
catalogTableConstraintsApply,
|
|
16179
17400
|
catalogTableGet,
|
|
16180
17401
|
catalogTableCreate,
|
|
16181
17402
|
catalogTableDrop,
|
|
@@ -16963,7 +18184,7 @@ class VgiClient {
|
|
|
16963
18184
|
options: [wireOptions],
|
|
16964
18185
|
data_version_spec: [opts?.dataVersionSpec ?? null],
|
|
16965
18186
|
implementation_version: [opts?.implementationVersion ?? null],
|
|
16966
|
-
client_capabilities: [opts?.clientCapabilities ? encodeASD(ClientCapabilitiesSchema, opts
|
|
18187
|
+
client_capabilities: [opts?.clientCapabilities === null ? null : encodeASD(ClientCapabilitiesSchema, opts?.clientCapabilities ?? defaultClientCapabilities("vgi-typescript-client"))]
|
|
16967
18188
|
}, schema);
|
|
16968
18189
|
const result = await this.rpc.call("catalog_attach", wrapRequest(innerBatch));
|
|
16969
18190
|
if (!result)
|
|
@@ -17991,6 +19212,9 @@ export {
|
|
|
17991
19212
|
CACHE_STALE_IF_ERROR_KEY,
|
|
17992
19213
|
CACHE_STALE_WHILE_REVALIDATE_KEY,
|
|
17993
19214
|
CACHE_TTL_KEY,
|
|
19215
|
+
CONSTRAINT_CREATE,
|
|
19216
|
+
CONSTRAINT_ENFORCE,
|
|
19217
|
+
CONSTRAINT_MUTATE,
|
|
17994
19218
|
CONSTRAINT_RECORDS_READ,
|
|
17995
19219
|
CONTINUE,
|
|
17996
19220
|
CatalogAlreadyExistsError,
|
|
@@ -18001,6 +19225,7 @@ export {
|
|
|
18001
19225
|
CatalogSnapshotManager,
|
|
18002
19226
|
ComparisonOp,
|
|
18003
19227
|
CompositeCatalogInterface,
|
|
19228
|
+
DEFAULT_EXPRESSION_KEY,
|
|
18004
19229
|
DEFAULT_MAX_WORKERS,
|
|
18005
19230
|
DateUnit3 as DateUnit,
|
|
18006
19231
|
DistinctDependence,
|
|
@@ -18012,6 +19237,8 @@ export {
|
|
|
18012
19237
|
FunctionStorageCfDo,
|
|
18013
19238
|
FunctionStorageSqlite,
|
|
18014
19239
|
FunctionType,
|
|
19240
|
+
GENERATED_EXPRESSION_KEY,
|
|
19241
|
+
GENERATION_KEY,
|
|
18015
19242
|
GROUP_COLUMN_NAME,
|
|
18016
19243
|
GrantKeys2 as GrantKeys,
|
|
18017
19244
|
GrantRefusedError,
|
|
@@ -18041,6 +19268,7 @@ export {
|
|
|
18041
19268
|
ScanFunctionResultSchema,
|
|
18042
19269
|
SealAttachDeniedError,
|
|
18043
19270
|
StatusError,
|
|
19271
|
+
TRANSACTION_DDL,
|
|
18044
19272
|
TableInOutPhase,
|
|
18045
19273
|
TimeUnit2 as TimeUnit,
|
|
18046
19274
|
TypeId,
|
|
@@ -18080,14 +19308,21 @@ export {
|
|
|
18080
19308
|
binary2 as binary,
|
|
18081
19309
|
bool3 as bool,
|
|
18082
19310
|
buildCatalogAttachResult,
|
|
19311
|
+
buildCatalogCapabilities,
|
|
19312
|
+
buildConstraintChange,
|
|
19313
|
+
buildConstraintDefinition,
|
|
18083
19314
|
buildJoinKeysLookup,
|
|
19315
|
+
buildMacroOverload,
|
|
18084
19316
|
buildRpcServer,
|
|
18085
19317
|
buildScanBranchesResult,
|
|
18086
19318
|
buildVgiProtocol,
|
|
18087
19319
|
bytes,
|
|
18088
19320
|
cacheControlMetadata,
|
|
19321
|
+
canonicalIndex,
|
|
19322
|
+
catalogCapabilities,
|
|
18089
19323
|
codecFor,
|
|
18090
19324
|
columnFromArray,
|
|
19325
|
+
constraintCapabilities,
|
|
18091
19326
|
constraintRecord,
|
|
18092
19327
|
constraintSpecFields,
|
|
18093
19328
|
createLandingRoutes,
|
|
@@ -18097,13 +19332,26 @@ export {
|
|
|
18097
19332
|
decimal2 as decimal,
|
|
18098
19333
|
decimal1282 as decimal128,
|
|
18099
19334
|
decimal2562 as decimal256,
|
|
19335
|
+
decodeCatalogCapabilities,
|
|
18100
19336
|
decodeCatalogInfo,
|
|
19337
|
+
decodeCatalogObjectRef,
|
|
19338
|
+
decodeConstraintChange,
|
|
19339
|
+
decodeConstraintDefinition,
|
|
19340
|
+
decodeConstraintInfo,
|
|
19341
|
+
decodeConstraintSnapshot,
|
|
19342
|
+
decodeConstraintsApplyRequest,
|
|
18101
19343
|
decodeDictValue,
|
|
19344
|
+
decodeForeignKeyDefinition,
|
|
18102
19345
|
decodeFunctionInfo,
|
|
19346
|
+
decodeIndexDefinition,
|
|
18103
19347
|
decodeMacroInfo,
|
|
19348
|
+
decodeMacroOverload,
|
|
18104
19349
|
decodeSchemaInfo,
|
|
19350
|
+
decodeSqlExpression,
|
|
18105
19351
|
decodeTableInfo,
|
|
18106
19352
|
decodeViewInfo,
|
|
19353
|
+
defaultClientCapabilities,
|
|
19354
|
+
defaultExpressionMetadata,
|
|
18107
19355
|
defineAggregate,
|
|
18108
19356
|
defineCopyFromFunction,
|
|
18109
19357
|
defineCopyToFunction,
|
|
@@ -18126,13 +19374,25 @@ export {
|
|
|
18126
19374
|
durationNanos,
|
|
18127
19375
|
durationSeconds,
|
|
18128
19376
|
emptyBatch,
|
|
19377
|
+
emptyIndexOptions,
|
|
18129
19378
|
encodeAttachTicket,
|
|
19379
|
+
encodeCatalogCapabilities,
|
|
18130
19380
|
encodeCatalogInfo,
|
|
19381
|
+
encodeCatalogObjectRef,
|
|
19382
|
+
encodeConstraintChange,
|
|
19383
|
+
encodeConstraintDefinition,
|
|
19384
|
+
encodeConstraintInfo,
|
|
19385
|
+
encodeConstraintSnapshot,
|
|
19386
|
+
encodeConstraintsApplyRequest,
|
|
18131
19387
|
encodeCopyFromFormatInfo,
|
|
19388
|
+
encodeForeignKeyDefinition,
|
|
18132
19389
|
encodeFormatOptions,
|
|
18133
19390
|
encodeFunctionInfo,
|
|
19391
|
+
encodeIndexDefinition,
|
|
18134
19392
|
encodeMacroInfo,
|
|
19393
|
+
encodeMacroOverload,
|
|
18135
19394
|
encodeSchemaInfo,
|
|
19395
|
+
encodeSqlExpression,
|
|
18136
19396
|
encodeTableInfo,
|
|
18137
19397
|
encodeViewInfo,
|
|
18138
19398
|
field2 as field,
|
|
@@ -18149,6 +19409,7 @@ export {
|
|
|
18149
19409
|
fromBrandedBigInt,
|
|
18150
19410
|
fromBrandedNumber,
|
|
18151
19411
|
storage as functionStorage,
|
|
19412
|
+
generatedExpressionMetadata,
|
|
18152
19413
|
grantKeysFromArgv,
|
|
18153
19414
|
httpConnect,
|
|
18154
19415
|
int3 as int,
|
|
@@ -18209,6 +19470,7 @@ export {
|
|
|
18209
19470
|
secretForScopeOfType,
|
|
18210
19471
|
secretType,
|
|
18211
19472
|
secretsOfType,
|
|
19473
|
+
selectCatalogCapabilities,
|
|
18212
19474
|
selectReadProfiles,
|
|
18213
19475
|
serializeAttachOptionSpec,
|
|
18214
19476
|
serializeAttachOptionSpecs,
|
|
@@ -18216,8 +19478,12 @@ export {
|
|
|
18216
19478
|
serializeColumnStatistics,
|
|
18217
19479
|
serializeSchema,
|
|
18218
19480
|
serializeUserState,
|
|
19481
|
+
servedConstraintFields,
|
|
19482
|
+
servedTableInfo,
|
|
19483
|
+
servedTableSchema,
|
|
18219
19484
|
setStorage,
|
|
18220
19485
|
sparseUnion2 as sparseUnion,
|
|
19486
|
+
sqlExpression,
|
|
18221
19487
|
str,
|
|
18222
19488
|
struct2 as struct,
|
|
18223
19489
|
subprocessConnect,
|
|
@@ -18241,7 +19507,11 @@ export {
|
|
|
18241
19507
|
uint82 as uint8,
|
|
18242
19508
|
union2 as union,
|
|
18243
19509
|
utf82 as utf8,
|
|
18244
|
-
|
|
19510
|
+
validateColumnExpressionSql,
|
|
19511
|
+
validateConstraintNullability,
|
|
19512
|
+
validateForeignKeyTargets,
|
|
19513
|
+
validateNumericCheckSql,
|
|
19514
|
+
validateTableConstraints
|
|
18245
19515
|
};
|
|
18246
19516
|
|
|
18247
|
-
//# debugId=
|
|
19517
|
+
//# debugId=89F18E0425AB222A64756E2164756E21
|