@niscorp/vex 0.4.3 → 0.4.5
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/CHANGELOG.md +20 -0
- package/DESIGN.md +22 -14
- package/DOCS.md +97 -6
- package/README.md +4 -0
- package/dist/adapters/express/index.d.cts +2 -2
- package/dist/adapters/express/index.d.ts +2 -2
- package/dist/adapters/hono/index.d.cts +2 -2
- package/dist/adapters/hono/index.d.ts +2 -2
- package/dist/agent/index.d.cts +1 -1
- package/dist/agent/index.d.ts +1 -1
- package/dist/{handler-CsFbanZA.d.cts → handler-CB0BqKsY.d.cts} +1 -1
- package/dist/{handler-CoJxInw-.d.ts → handler-O6XslV-S.d.ts} +1 -1
- package/dist/index.cjs +174 -27
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +173 -28
- package/dist/index.js.map +1 -1
- package/dist/{types-B2HEmyNq.d.cts → types-BmHuPfPS.d.cts} +33 -2
- package/dist/{types-DC68ZUuq.d.ts → types-D5CCaqcd.d.ts} +33 -2
- package/package.json +8 -8
package/dist/index.d.cts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { Q as QueryEngineConfig, a as QueryEngine, D as DatabaseSchema, R as ResolvedQuery, A as AnalysisConfig, b as AnalysisResult, C as CompiledQuery, c as ContextMeta, d as DatabaseAdapter, e as Row, F as FieldSchema, P as ParamSlot, f as ResolvedExists, g as QueryErrorCode, S as ScopePolicy, h as CacheBackend, i as CacheEntry, j as Refresh, M as MutationDefinition, k as ContextContract } from './types-
|
|
2
|
-
export { l as AdapterCapabilities, B as BoundParams, m as CoreMutation, E as EntitySchema,
|
|
1
|
+
import { Q as QueryEngineConfig, a as QueryEngine, D as DatabaseSchema, R as ResolvedQuery, A as AnalysisConfig, b as AnalysisResult, C as CompiledQuery, c as ContextMeta, d as DatabaseAdapter, e as Row, F as FieldSchema, P as ParamSlot, f as ResolvedExists, g as QueryErrorCode, S as ScopePolicy, h as CacheBackend, i as CacheEntry, j as Refresh, M as MutationDefinition, k as ContextContract } from './types-BmHuPfPS.cjs';
|
|
2
|
+
export { l as AdapterCapabilities, B as BoundParams, m as ColumnUpgrader, n as CoreMutation, E as EntitySchema, o as ExecuteOptions, G as GenerateDsl, p as GenerationCaller, I as IndexSchema, q as IntrospectOptions, r as ItemRef, L as LiveRowsConfig, s as LiveRowsStats, t as LookupValue, u as MapToShape, v as Mutation, w as MutationCacheEntry, x as MutationDefinitionSchema, y as MutationSchema, z as MutationValue, N as NamedScopeBehaviors, H as NormalizedType, O as OkCacheEntry, J as QueryErrorResponse, K as QueryRequest, T as QueryRequestSchema, U as QueryResponse, V as REFRESH_MODES, W as RelationSchema, X as ResolvedField, Y as ResolvedFilter, Z as ResolvedJoin, _ as ResolvedMutation, $ as ResolvedOnConflict, a0 as ResolvedSemantic, a1 as ResolvedSource, a2 as ReturnedRef, a3 as SCOPE_VERBS, a4 as ScopeBehaviors, a5 as ScopeBinding, a6 as ScopeEntityRule, a7 as ScopeMatch, a8 as ScopeRule, a9 as ScopeRules, aa as ScopeSet, ab as ScopeValues, ac as TestResult, ad as UNREADABLE_MODES, ae as UnsatisfiableCacheEntry, af as UpgradedColumn, ag as UpgradedColumns, ah as UpgradedColumnsSchema, ai as VexEvent, aj as VexEventHandler, ak as createScopePolicy, al as isRefresh, am as mergeScopePolicies, an as scopeBindings, ao as scopeGrants, ap as scopeProfiles } from './types-BmHuPfPS.cjs';
|
|
3
3
|
import { Q as Query, F as FieldOrValue, a as Filter } from './query.schema-B-LVNfyX.cjs';
|
|
4
4
|
export { A as AggregateExpression, b as AggregateExpressionSchema, C as ComputeExpression, c as ComputeExpressionSchema, d as ContextRef, e as FilterSchema, f as QuerySchema, S as ScopeRef, g as SortEntry, h as Source } from './query.schema-B-LVNfyX.cjs';
|
|
5
5
|
import { P as PgPool } from './introspect-D3OaXHBc.cjs';
|
|
6
6
|
import { Sequence } from '@niscorp/strata';
|
|
7
|
-
export { C as ContextField, a as ContextSignature, D as DiscoveryFingerprint, b as DiscoveryResponse, E as ExecuteRecord, M as MutationClient, c as MutationContext, d as MutationEffect, e as MutationTx, Q as QueryResult, V as VexHandlerConfig, f as VexLive, W as WriteEvent, g as WriteResult, h as collectMutationContext, i as collectQueryContext, j as executeMutation, k as executeWrites, l as handleDiscovery, m as handleFingerprintDelete, n as handleFingerprintPatch, o as handleQuery, p as lintMutation, q as mutationEffect, r as mutationMisfits, s as requiredContextKeys, t as tablesChangedBy } from './handler-
|
|
7
|
+
export { C as ContextField, a as ContextSignature, D as DiscoveryFingerprint, b as DiscoveryResponse, E as ExecuteRecord, M as MutationClient, c as MutationContext, d as MutationEffect, e as MutationTx, Q as QueryResult, V as VexHandlerConfig, f as VexLive, W as WriteEvent, g as WriteResult, h as collectMutationContext, i as collectQueryContext, j as executeMutation, k as executeWrites, l as handleDiscovery, m as handleFingerprintDelete, n as handleFingerprintPatch, o as handleQuery, p as lintMutation, q as mutationEffect, r as mutationMisfits, s as requiredContextKeys, t as tablesChangedBy } from './handler-CB0BqKsY.cjs';
|
|
8
8
|
import '@niscorp/prism';
|
|
9
9
|
import 'zod';
|
|
10
10
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { Q as QueryEngineConfig, a as QueryEngine, D as DatabaseSchema, R as ResolvedQuery, A as AnalysisConfig, b as AnalysisResult, C as CompiledQuery, c as ContextMeta, d as DatabaseAdapter, e as Row, F as FieldSchema, P as ParamSlot, f as ResolvedExists, g as QueryErrorCode, S as ScopePolicy, h as CacheBackend, i as CacheEntry, j as Refresh, M as MutationDefinition, k as ContextContract } from './types-
|
|
2
|
-
export { l as AdapterCapabilities, B as BoundParams, m as CoreMutation, E as EntitySchema,
|
|
1
|
+
import { Q as QueryEngineConfig, a as QueryEngine, D as DatabaseSchema, R as ResolvedQuery, A as AnalysisConfig, b as AnalysisResult, C as CompiledQuery, c as ContextMeta, d as DatabaseAdapter, e as Row, F as FieldSchema, P as ParamSlot, f as ResolvedExists, g as QueryErrorCode, S as ScopePolicy, h as CacheBackend, i as CacheEntry, j as Refresh, M as MutationDefinition, k as ContextContract } from './types-D5CCaqcd.js';
|
|
2
|
+
export { l as AdapterCapabilities, B as BoundParams, m as ColumnUpgrader, n as CoreMutation, E as EntitySchema, o as ExecuteOptions, G as GenerateDsl, p as GenerationCaller, I as IndexSchema, q as IntrospectOptions, r as ItemRef, L as LiveRowsConfig, s as LiveRowsStats, t as LookupValue, u as MapToShape, v as Mutation, w as MutationCacheEntry, x as MutationDefinitionSchema, y as MutationSchema, z as MutationValue, N as NamedScopeBehaviors, H as NormalizedType, O as OkCacheEntry, J as QueryErrorResponse, K as QueryRequest, T as QueryRequestSchema, U as QueryResponse, V as REFRESH_MODES, W as RelationSchema, X as ResolvedField, Y as ResolvedFilter, Z as ResolvedJoin, _ as ResolvedMutation, $ as ResolvedOnConflict, a0 as ResolvedSemantic, a1 as ResolvedSource, a2 as ReturnedRef, a3 as SCOPE_VERBS, a4 as ScopeBehaviors, a5 as ScopeBinding, a6 as ScopeEntityRule, a7 as ScopeMatch, a8 as ScopeRule, a9 as ScopeRules, aa as ScopeSet, ab as ScopeValues, ac as TestResult, ad as UNREADABLE_MODES, ae as UnsatisfiableCacheEntry, af as UpgradedColumn, ag as UpgradedColumns, ah as UpgradedColumnsSchema, ai as VexEvent, aj as VexEventHandler, ak as createScopePolicy, al as isRefresh, am as mergeScopePolicies, an as scopeBindings, ao as scopeGrants, ap as scopeProfiles } from './types-D5CCaqcd.js';
|
|
3
3
|
import { Q as Query, F as FieldOrValue, a as Filter } from './query.schema-B-LVNfyX.js';
|
|
4
4
|
export { A as AggregateExpression, b as AggregateExpressionSchema, C as ComputeExpression, c as ComputeExpressionSchema, d as ContextRef, e as FilterSchema, f as QuerySchema, S as ScopeRef, g as SortEntry, h as Source } from './query.schema-B-LVNfyX.js';
|
|
5
5
|
import { P as PgPool } from './introspect-D3OaXHBc.js';
|
|
6
6
|
import { Sequence } from '@niscorp/strata';
|
|
7
|
-
export { C as ContextField, a as ContextSignature, D as DiscoveryFingerprint, b as DiscoveryResponse, E as ExecuteRecord, M as MutationClient, c as MutationContext, d as MutationEffect, e as MutationTx, Q as QueryResult, V as VexHandlerConfig, f as VexLive, W as WriteEvent, g as WriteResult, h as collectMutationContext, i as collectQueryContext, j as executeMutation, k as executeWrites, l as handleDiscovery, m as handleFingerprintDelete, n as handleFingerprintPatch, o as handleQuery, p as lintMutation, q as mutationEffect, r as mutationMisfits, s as requiredContextKeys, t as tablesChangedBy } from './handler-
|
|
7
|
+
export { C as ContextField, a as ContextSignature, D as DiscoveryFingerprint, b as DiscoveryResponse, E as ExecuteRecord, M as MutationClient, c as MutationContext, d as MutationEffect, e as MutationTx, Q as QueryResult, V as VexHandlerConfig, f as VexLive, W as WriteEvent, g as WriteResult, h as collectMutationContext, i as collectQueryContext, j as executeMutation, k as executeWrites, l as handleDiscovery, m as handleFingerprintDelete, n as handleFingerprintPatch, o as handleQuery, p as lintMutation, q as mutationEffect, r as mutationMisfits, s as requiredContextKeys, t as tablesChangedBy } from './handler-O6XslV-S.js';
|
|
8
8
|
import '@niscorp/prism';
|
|
9
9
|
import 'zod';
|
|
10
10
|
|
package/dist/index.js
CHANGED
|
@@ -1065,6 +1065,128 @@ var createLiveRows = (config = {}, emit = () => {
|
|
|
1065
1065
|
};
|
|
1066
1066
|
return { read, follow, invalidate, stats, stop };
|
|
1067
1067
|
};
|
|
1068
|
+
var UNREADABLE_MODES = ["refuse", "omit", "null"];
|
|
1069
|
+
var UpgradedColumnSchema = z.object({
|
|
1070
|
+
stamp: z.string(),
|
|
1071
|
+
kind: z.union([z.string(), z.object({ grammar: z.string(), column: z.string() }).strict()]),
|
|
1072
|
+
unreadable: z.enum(UNREADABLE_MODES).optional()
|
|
1073
|
+
}).strict();
|
|
1074
|
+
var UpgradedColumnsSchema = z.record(z.string(), z.record(z.string(), UpgradedColumnSchema));
|
|
1075
|
+
var outputOf = (ref) => typeof ref === "string" ? { path: ref, key: ref.slice(ref.indexOf(".") + 1) } : { path: ref.field, key: ref.as };
|
|
1076
|
+
var outputsOf = (dsl, path) => (dsl.fields ?? []).map(outputOf).flatMap((out) => out.path === path ? [out.key] : []);
|
|
1077
|
+
var count = (value, path) => {
|
|
1078
|
+
if (value === path) return 1;
|
|
1079
|
+
if (Array.isArray(value)) return value.reduce((sum, item) => sum + count(item, path), 0);
|
|
1080
|
+
if (typeof value === "object" && value !== null) return Object.values(value).reduce((sum, item) => sum + count(item, path), 0);
|
|
1081
|
+
return 0;
|
|
1082
|
+
};
|
|
1083
|
+
var usesOutsideFields = (dsl, path, outer) => Object.entries(dsl).reduce((sum, [part, value]) => {
|
|
1084
|
+
if (part === "filter" || part === "sort" || outer && part === "fields") return sum;
|
|
1085
|
+
if (part !== "from") return sum + count(value, path);
|
|
1086
|
+
return sum + dsl.from.reduce((inner, source) => inner + (typeof source === "string" ? 0 : usesOutsideFields(source.query, path, false)), 0);
|
|
1087
|
+
}, 0);
|
|
1088
|
+
var selected = (dsl, path, upgraded) => {
|
|
1089
|
+
const [first, ...rest] = outputsOf(dsl, path);
|
|
1090
|
+
if (first === void 0) throw new VexError("invalid_dsl", `This read returns ${upgraded}, which is upgraded where it is read, without ${path}: add ${path} to its fields.`);
|
|
1091
|
+
return [first, ...rest];
|
|
1092
|
+
};
|
|
1093
|
+
var refuseSharedKeys = (dsl, upgrades) => {
|
|
1094
|
+
const sourcesByKey = /* @__PURE__ */ new Map();
|
|
1095
|
+
const note = (key, source) => {
|
|
1096
|
+
sourcesByKey.set(key, (sourcesByKey.get(key) ?? /* @__PURE__ */ new Set()).add(source));
|
|
1097
|
+
};
|
|
1098
|
+
for (const { path, key } of (dsl.fields ?? []).map(outputOf)) note(key, path);
|
|
1099
|
+
for (const key of [...Object.keys(dsl.compute ?? {}), ...Object.keys(dsl.aggregate ?? {})]) note(key, `the computed ${key}`);
|
|
1100
|
+
const used = upgrades.flatMap((upgrade) => [upgrade.key, ...upgrade.stampKeys, ...typeof upgrade.kind === "string" ? [] : [upgrade.kind.key]]);
|
|
1101
|
+
const shared = [...new Set(used)].filter((key) => (sourcesByKey.get(key)?.size ?? 0) > 1);
|
|
1102
|
+
if (shared.length > 0) {
|
|
1103
|
+
throw new VexError("invalid_dsl", `This read returns two values under one key (${shared.join(", ")}), and one is an upgraded column, its stamp or its kind: give each its own key with \`as\`.`);
|
|
1104
|
+
}
|
|
1105
|
+
};
|
|
1106
|
+
var declared = (columns) => Object.entries(columns).flatMap(([table, byColumn]) => Object.entries(byColumn).map(([column, upgraded]) => ({ table, column, upgraded })));
|
|
1107
|
+
var columnUpgrades = (dsl, columns) => {
|
|
1108
|
+
const upgrades = declared(columns).flatMap(({ table, column, upgraded }) => {
|
|
1109
|
+
const path = `${table}.${column}`;
|
|
1110
|
+
if (usesOutsideFields(dsl, path, true) > 0) {
|
|
1111
|
+
throw new VexError(
|
|
1112
|
+
"invalid_dsl",
|
|
1113
|
+
`${path} is upgraded where it is read, so a read returns it only as one of its own fields, never through a subquery, a compute, an aggregate or a groupBy. A filter or a sort on it compares the stored value.`
|
|
1114
|
+
);
|
|
1115
|
+
}
|
|
1116
|
+
const keys = outputsOf(dsl, path);
|
|
1117
|
+
if (keys.length === 0) return [];
|
|
1118
|
+
const stampKeys = selected(dsl, `${table}.${upgraded.stamp}`, path);
|
|
1119
|
+
const kind = typeof upgraded.kind === "string" ? upgraded.kind : { grammar: upgraded.kind.grammar, key: selected(dsl, `${table}.${upgraded.kind.column}`, path)[0] };
|
|
1120
|
+
return keys.map((key) => ({ path, key, stampKeys, kind, unreadable: upgraded.unreadable ?? "refuse" }));
|
|
1121
|
+
});
|
|
1122
|
+
refuseSharedKeys(dsl, upgrades);
|
|
1123
|
+
return upgrades;
|
|
1124
|
+
};
|
|
1125
|
+
var unknownKinds = (columns, upgrader) => declared(columns).flatMap(({ table, column, upgraded: { kind } }) => {
|
|
1126
|
+
if (typeof kind !== "string") return kind.grammar in upgrader.stamp ? [] : [`${table}.${column} names the grammar "${kind.grammar}"`];
|
|
1127
|
+
try {
|
|
1128
|
+
upgrader.locate({}, kind);
|
|
1129
|
+
return [];
|
|
1130
|
+
} catch {
|
|
1131
|
+
return [`${table}.${column} names the kind "${kind}"`];
|
|
1132
|
+
}
|
|
1133
|
+
});
|
|
1134
|
+
var mistypedColumns = (columns, schema) => declared(columns).flatMap(({ table, column, upgraded }) => {
|
|
1135
|
+
const fields = schema.entities.find((e) => e.name === table)?.fields ?? [];
|
|
1136
|
+
const json = (name) => {
|
|
1137
|
+
const field = fields.find((f) => f.name === name);
|
|
1138
|
+
if (field === void 0) return [`${table}.${name} is not in the database`];
|
|
1139
|
+
return ["json", "jsonb"].includes(field.type.toLowerCase()) ? [] : [`${table}.${name} is ${field.type}, not json`];
|
|
1140
|
+
};
|
|
1141
|
+
const { kind } = upgraded;
|
|
1142
|
+
const kindColumn = typeof kind === "string" || fields.some((f) => f.name === kind.column) ? [] : [`${table}.${kind.column} is not in the database`];
|
|
1143
|
+
return [...json(column), ...json(upgraded.stamp), ...kindColumn];
|
|
1144
|
+
});
|
|
1145
|
+
var StampSchema = z.union([z.null(), z.undefined(), z.record(z.string(), z.number().int().nonnegative())]);
|
|
1146
|
+
var stampOf = (value, path) => {
|
|
1147
|
+
const parsed = StampSchema.safeParse(value);
|
|
1148
|
+
if (!parsed.success) throw new VexError("execution_error", `The stamp beside ${path} is not a stamp: it must be null or an object of grammar names to whole numbers.`);
|
|
1149
|
+
return parsed.data ?? {};
|
|
1150
|
+
};
|
|
1151
|
+
var kindOf = (upgrade, row) => {
|
|
1152
|
+
if (typeof upgrade.kind === "string") return upgrade.kind;
|
|
1153
|
+
const name = row[upgrade.kind.key];
|
|
1154
|
+
if (typeof name !== "string") throw new VexError("execution_error", `The row's ${upgrade.kind.key} is not text, so it names no kind in ${upgrade.kind.grammar}.`);
|
|
1155
|
+
return `${upgrade.kind.grammar}/${name}`;
|
|
1156
|
+
};
|
|
1157
|
+
var reasonOf = (error) => {
|
|
1158
|
+
const message = error instanceof Error ? error.message.split("\n")[0] ?? "" : String(error);
|
|
1159
|
+
const code = error instanceof Error && "code" in error && typeof error.code === "string" ? `${error.code}: ` : "";
|
|
1160
|
+
return `${code}${message}`;
|
|
1161
|
+
};
|
|
1162
|
+
var upgradeRows = (rows, upgrades, upgrade) => {
|
|
1163
|
+
if (upgrades.length === 0) return { rows, warnings: [] };
|
|
1164
|
+
const warnings = [];
|
|
1165
|
+
const upgraded = rows.flatMap((row, index) => {
|
|
1166
|
+
const next = { ...row };
|
|
1167
|
+
const said = [];
|
|
1168
|
+
for (const column of upgrades) {
|
|
1169
|
+
const value = row[column.key];
|
|
1170
|
+
if (value === null || value === void 0) continue;
|
|
1171
|
+
try {
|
|
1172
|
+
const result = upgrade(value, { kind: kindOf(column, row), stamp: stampOf(row[column.stampKeys[0]], column.path) });
|
|
1173
|
+
next[column.key] = result.document;
|
|
1174
|
+
for (const stampKey of column.stampKeys) next[stampKey] = result.stamp;
|
|
1175
|
+
} catch (error) {
|
|
1176
|
+
if (column.unreadable === "refuse") throw error;
|
|
1177
|
+
if (column.unreadable === "omit") {
|
|
1178
|
+
warnings.push(`The database's row ${index} (counting from 0) was left out: its ${column.path} does not upgrade (${reasonOf(error)}).`);
|
|
1179
|
+
return [];
|
|
1180
|
+
}
|
|
1181
|
+
next[column.key] = null;
|
|
1182
|
+
said.push(`The database's row ${index} (counting from 0) has ${column.path} set to null: it does not upgrade (${reasonOf(error)}).`);
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
warnings.push(...said);
|
|
1186
|
+
return [next];
|
|
1187
|
+
});
|
|
1188
|
+
return { rows: upgraded, warnings };
|
|
1189
|
+
};
|
|
1068
1190
|
var applySortContext = (dsl, context) => {
|
|
1069
1191
|
const sortBy = context["sortBy"];
|
|
1070
1192
|
if (typeof sortBy !== "string" || sortBy === "") return dsl;
|
|
@@ -1079,7 +1201,18 @@ var DEFAULT_STATEMENT_TIMEOUT_MS = 1e4;
|
|
|
1079
1201
|
var DEFAULT_UNSATISFIABLE_TTL_MS = 3e5;
|
|
1080
1202
|
var DEFAULT_MAX_PRESENCE_VARIANTS = 32;
|
|
1081
1203
|
var createQueryEngine = (engineConfig) => {
|
|
1082
|
-
const { adapter, scope: scopePolicy, generateDsl, mapToShape, embed, behaviors } = engineConfig;
|
|
1204
|
+
const { adapter, scope: scopePolicy, generateDsl, mapToShape, embed, behaviors, upgrader } = engineConfig;
|
|
1205
|
+
const parsedColumns = UpgradedColumnsSchema.safeParse(engineConfig.upgradedColumns ?? {});
|
|
1206
|
+
if (!parsedColumns.success) throw new VexError("invalid_request", `The engine's upgradedColumns do not parse: ${parsedColumns.error.message}`);
|
|
1207
|
+
const upgradedColumns = parsedColumns.data;
|
|
1208
|
+
if (engineConfig.upgradedColumns !== void 0 && upgrader === void 0) {
|
|
1209
|
+
throw new VexError("invalid_request", "The engine was given `upgradedColumns` and no `upgrader`: hand it strata's `createUpgrader(grammars, { transform: evaluate })`.");
|
|
1210
|
+
}
|
|
1211
|
+
const unknown = upgrader === void 0 ? [] : unknownKinds(upgradedColumns, upgrader);
|
|
1212
|
+
if (unknown.length > 0) {
|
|
1213
|
+
throw new VexError("invalid_request", `The upgradedColumns name what the upgrader's grammars do not declare: ${unknown.join("; ")}. Fix the name, or give the upgrader that grammar.`);
|
|
1214
|
+
}
|
|
1215
|
+
const upgradeOf = (stored, upgrades) => upgrader === void 0 ? { rows: stored, warnings: [] } : upgradeRows(stored, upgrades, upgrader.upgrade);
|
|
1083
1216
|
const emit = engineConfig.onEvent ?? (() => {
|
|
1084
1217
|
});
|
|
1085
1218
|
const maxNestingDepth = engineConfig.config?.maxNestingDepth ?? DEFAULT_MAX_NESTING_DEPTH;
|
|
@@ -1131,6 +1264,10 @@ var createQueryEngine = (engineConfig) => {
|
|
|
1131
1264
|
throw new VexError("execution_error", `The behaviors name columns the database does not have: ${missing.map((m) => `${m.entity}.${m.field}`).join(", ")}.`);
|
|
1132
1265
|
}
|
|
1133
1266
|
}
|
|
1267
|
+
const mistyped = mistypedColumns(upgradedColumns, schema);
|
|
1268
|
+
if (mistyped.length > 0) {
|
|
1269
|
+
throw new VexError("execution_error", `The upgradedColumns do not fit the database: ${mistyped.join("; ")}. Fix the name, or add the column in a migration.`);
|
|
1270
|
+
}
|
|
1134
1271
|
cachedSchema = schema;
|
|
1135
1272
|
cachedFingerprint = computeSchemaFingerprint(schema);
|
|
1136
1273
|
return schema;
|
|
@@ -1169,7 +1306,7 @@ var createQueryEngine = (engineConfig) => {
|
|
|
1169
1306
|
);
|
|
1170
1307
|
}
|
|
1171
1308
|
const compiled = adapter.compile(resolved);
|
|
1172
|
-
return { compiled, warnings: analysis.warnings, ...engineLimit !== void 0 ? { engineLimit } : {} };
|
|
1309
|
+
return { compiled, warnings: analysis.warnings, upgrades: columnUpgrades(processedDsl, upgradedColumns), ...engineLimit !== void 0 ? { engineLimit } : {} };
|
|
1173
1310
|
};
|
|
1174
1311
|
const cutSaid = /* @__PURE__ */ new Set();
|
|
1175
1312
|
const cutNote = (engineLimit, stated, rowCount, shape, fingerprint) => {
|
|
@@ -1186,12 +1323,12 @@ var createQueryEngine = (engineConfig) => {
|
|
|
1186
1323
|
const test = async (dsl, scopeValues) => {
|
|
1187
1324
|
try {
|
|
1188
1325
|
const testDsl = { ...pruneOptional(dsl, "all"), limit: 5 };
|
|
1189
|
-
const { compiled, warnings } = runPipeline(testDsl);
|
|
1326
|
+
const { compiled, warnings, upgrades } = runPipeline(testDsl);
|
|
1190
1327
|
const syntheticContext = buildValidationContext(compiled.contextContract);
|
|
1191
1328
|
const scope = scopeValues ?? {};
|
|
1192
1329
|
requireScope(compiled, scope);
|
|
1193
|
-
const rows = await executeQuery(compiled, syntheticContext, scope, adapter, embed);
|
|
1194
|
-
return { rows, warnings, errors: [] };
|
|
1330
|
+
const { rows, warnings: upgradeWarnings } = upgradeOf(await executeQuery(compiled, syntheticContext, scope, adapter, embed), upgrades);
|
|
1331
|
+
return { rows, warnings: [...warnings, ...upgradeWarnings], errors: [] };
|
|
1195
1332
|
} catch (err) {
|
|
1196
1333
|
const message = err instanceof Error ? err.message : String(err);
|
|
1197
1334
|
return { rows: [], warnings: [], errors: [message] };
|
|
@@ -1249,13 +1386,15 @@ var createQueryEngine = (engineConfig) => {
|
|
|
1249
1386
|
const callerOf = (policy, scope, tables) => ({
|
|
1250
1387
|
bindings: scopeBindings(behaviors ?? {}, tables, scope),
|
|
1251
1388
|
read: async (dsl) => {
|
|
1252
|
-
const
|
|
1389
|
+
const pruned = pruneOptional(dsl, "all");
|
|
1390
|
+
const { compiled, warnings, upgrades } = runPipeline(pruned, policy);
|
|
1253
1391
|
requireScope(compiled, scope);
|
|
1254
1392
|
if (compiled.paramSlots.some((slot) => slot.kind === "semantic")) {
|
|
1255
1393
|
return { rows: [], sql: compiled.sql, warnings: [...warnings, "Semantic params present \u2014 execution skipped, SQL structure validated only"] };
|
|
1256
1394
|
}
|
|
1257
1395
|
const params = compiled.paramSlots.map((slot) => slot.kind === "scope" ? scope[slot.key] : null);
|
|
1258
|
-
|
|
1396
|
+
const { rows, warnings: upgradeWarnings } = upgradeOf(await adapter.execute(compiled, params), upgrades);
|
|
1397
|
+
return { rows, sql: compiled.sql, warnings: [...warnings, ...upgradeWarnings] };
|
|
1259
1398
|
}
|
|
1260
1399
|
});
|
|
1261
1400
|
const generateMissingDsl = async (validRequest, flightKey, negKey, entities, policy, scope) => {
|
|
@@ -1307,9 +1446,10 @@ var createQueryEngine = (engineConfig) => {
|
|
|
1307
1446
|
};
|
|
1308
1447
|
return execute(ir, source);
|
|
1309
1448
|
};
|
|
1310
|
-
const executeAndMap = async (compiled, validRequest, cachedIr, context, scope) => {
|
|
1449
|
+
const executeAndMap = async (compiled, validRequest, cachedIr, context, scope, upgrades) => {
|
|
1311
1450
|
const execStart = Date.now();
|
|
1312
|
-
const
|
|
1451
|
+
const stored = await executeQuery(compiled, context, scope, adapter, embed);
|
|
1452
|
+
const { rows, warnings: upgradeWarnings } = upgradeOf(stored, upgrades);
|
|
1313
1453
|
const executionMs = Date.now() - execStart;
|
|
1314
1454
|
emit({ type: "query.rows", count: rows.length, executionMs });
|
|
1315
1455
|
let result = rows;
|
|
@@ -1331,7 +1471,7 @@ var createQueryEngine = (engineConfig) => {
|
|
|
1331
1471
|
}
|
|
1332
1472
|
if (mappingMs !== void 0) emit({ type: "query.mapped", mappingMs });
|
|
1333
1473
|
}
|
|
1334
|
-
return { result,
|
|
1474
|
+
return { result, storedRowCount: stored.length, upgradeWarnings, executionMs, mappingMs, mappedIr, ...mappedConfig !== void 0 ? { mappedConfig } : {} };
|
|
1335
1475
|
};
|
|
1336
1476
|
const execute$1 = async (request, options) => {
|
|
1337
1477
|
if (exceedsDepth(request)) throw new VexError("invalid_request", `Invalid request: ${depthRefusal()}`);
|
|
@@ -1380,7 +1520,7 @@ var createQueryEngine = (engineConfig) => {
|
|
|
1380
1520
|
}
|
|
1381
1521
|
const presence = presenceOf(validRequest.context);
|
|
1382
1522
|
const shaped = pruneOptional(applySortContext(dsl, validRequest.context), presence);
|
|
1383
|
-
const { compiled, warnings, engineLimit } = runPipeline(shaped, activePolicy, cached.seeded === true);
|
|
1523
|
+
const { compiled, warnings, upgrades, engineLimit } = runPipeline(shaped, activePolicy, cached.seeded === true);
|
|
1384
1524
|
noteVariant(cached.fingerprint, presenceSignature(dsl, presence), warnings);
|
|
1385
1525
|
emit({ type: "query.sql", sql: compiled.sql, warnings });
|
|
1386
1526
|
requireScope(compiled, scope);
|
|
@@ -1406,7 +1546,11 @@ var createQueryEngine = (engineConfig) => {
|
|
|
1406
1546
|
const reactiveIr = cached.cachedIr;
|
|
1407
1547
|
if (cached.hit && cached.refresh === "reactive" && (effectiveRequest.shape === void 0 || reactiveIr !== void 0)) {
|
|
1408
1548
|
const shape = effectiveRequest.shape;
|
|
1409
|
-
const shapeRows = (
|
|
1549
|
+
const shapeRows = (stored) => {
|
|
1550
|
+
const { rows: rows2, warnings: upgradeWarnings3 } = upgradeOf(stored, upgrades);
|
|
1551
|
+
const result3 = shape === void 0 || reactiveIr === void 0 ? rows2 : mapRows(rows2, shape, reactiveIr, context, scope);
|
|
1552
|
+
return { result: result3, upgradeWarnings: upgradeWarnings3 };
|
|
1553
|
+
};
|
|
1410
1554
|
const params = await resolveParams(compiled.paramSlots, context, scope, embed);
|
|
1411
1555
|
const key = canonicalHash([compiled.sql, params]);
|
|
1412
1556
|
const source = { tables: [...discoverEntities(shaped)], fetch: () => adapter.execute(compiled, params) };
|
|
@@ -1414,10 +1558,10 @@ var createQueryEngine = (engineConfig) => {
|
|
|
1414
1558
|
const rows = await live.read(key, source);
|
|
1415
1559
|
const executionMs2 = Date.now() - execStart;
|
|
1416
1560
|
emit({ type: "query.rows", count: rows.length, executionMs: executionMs2 });
|
|
1417
|
-
const result2 = shapeRows(rows);
|
|
1418
|
-
const metaOf = (
|
|
1419
|
-
const cut2 = cutNote(engineLimit, shaped.limit,
|
|
1420
|
-
const said2 = cut2 === void 0 ?
|
|
1561
|
+
const { result: result2, upgradeWarnings: upgradeWarnings2 } = shapeRows(rows);
|
|
1562
|
+
const metaOf = (rowCount, upgraded) => {
|
|
1563
|
+
const cut2 = cutNote(engineLimit, shaped.limit, rowCount, shape, validRequest.fingerprint);
|
|
1564
|
+
const said2 = [...warnings, ...upgraded, ...cut2 === void 0 ? [] : [cut2]];
|
|
1421
1565
|
return {
|
|
1422
1566
|
cache: {
|
|
1423
1567
|
hit: cached.hit,
|
|
@@ -1430,29 +1574,30 @@ var createQueryEngine = (engineConfig) => {
|
|
|
1430
1574
|
};
|
|
1431
1575
|
const { signal, onChange } = options ?? {};
|
|
1432
1576
|
if (signal !== void 0 && onChange !== void 0) {
|
|
1433
|
-
let lastHash = canonicalHash(result2);
|
|
1577
|
+
let lastHash = canonicalHash([result2, upgradeWarnings2]);
|
|
1434
1578
|
live.follow(key, source, rows, {
|
|
1435
1579
|
deliver: (next) => {
|
|
1436
|
-
const nextResult = shapeRows(next);
|
|
1437
|
-
const nextHash = canonicalHash(nextResult);
|
|
1580
|
+
const { result: nextResult, upgradeWarnings: nextUpgradeWarnings } = shapeRows(next);
|
|
1581
|
+
const nextHash = canonicalHash([nextResult, nextUpgradeWarnings]);
|
|
1438
1582
|
if (nextHash === lastHash) return;
|
|
1439
1583
|
lastHash = nextHash;
|
|
1440
|
-
onChange({ result: nextResult, meta: metaOf(next.length) });
|
|
1584
|
+
onChange({ result: nextResult, meta: metaOf(next.length, nextUpgradeWarnings) });
|
|
1441
1585
|
}
|
|
1442
1586
|
}, signal);
|
|
1443
1587
|
}
|
|
1444
1588
|
emit({ type: "query.done", totalMs: Date.now() - t0 });
|
|
1445
|
-
return { result: result2, meta: { ...metaOf(rows.length), timing: { executionMs: executionMs2 } } };
|
|
1589
|
+
return { result: result2, meta: { ...metaOf(rows.length, upgradeWarnings2), timing: { executionMs: executionMs2 } } };
|
|
1446
1590
|
}
|
|
1447
|
-
const { result,
|
|
1591
|
+
const { result, storedRowCount, upgradeWarnings, executionMs, mappingMs, mappedIr, mappedConfig } = await executeAndMap(
|
|
1448
1592
|
compiled,
|
|
1449
1593
|
effectiveRequest,
|
|
1450
1594
|
cached.cachedIr,
|
|
1451
1595
|
context,
|
|
1452
|
-
scope
|
|
1596
|
+
scope,
|
|
1597
|
+
upgrades
|
|
1453
1598
|
);
|
|
1454
|
-
const cut = cutNote(engineLimit, shaped.limit,
|
|
1455
|
-
const said = cut === void 0 ?
|
|
1599
|
+
const cut = cutNote(engineLimit, shaped.limit, storedRowCount, effectiveRequest.shape, validRequest.fingerprint);
|
|
1600
|
+
const said = [...warnings, ...upgradeWarnings, ...cut === void 0 ? [] : [cut]];
|
|
1456
1601
|
if (!cached.hit) {
|
|
1457
1602
|
const now = Date.now();
|
|
1458
1603
|
const entry = {
|
|
@@ -1655,8 +1800,8 @@ var introspectPostgres = async (pool, options) => {
|
|
|
1655
1800
|
const rowCountMap = /* @__PURE__ */ new Map();
|
|
1656
1801
|
for (const row of rowCountsResult.rows) {
|
|
1657
1802
|
const table = row["table_name"];
|
|
1658
|
-
const
|
|
1659
|
-
rowCountMap.set(table,
|
|
1803
|
+
const count2 = Number(row["row_count"] ?? 0);
|
|
1804
|
+
rowCountMap.set(table, count2);
|
|
1660
1805
|
}
|
|
1661
1806
|
const columnsByTable = /* @__PURE__ */ new Map();
|
|
1662
1807
|
for (const row of columnsResult.rows) {
|
|
@@ -2315,6 +2460,6 @@ var seedCache = async (cache, entries) => {
|
|
|
2315
2460
|
}
|
|
2316
2461
|
};
|
|
2317
2462
|
|
|
2318
|
-
export { SCOPE_VERBS, analyze, createMemoryCache, createPostgresAdapter, createPostgresCache, createQueryEngine, createScopePolicy, createTieredCache, discoverEntities, mergeScopePolicies, resolve, scopeBindings, scopeGrants, scopeProfiles, seedCache, validateEntry, vexGuide };
|
|
2463
|
+
export { SCOPE_VERBS, UNREADABLE_MODES, UpgradedColumnsSchema, analyze, createMemoryCache, createPostgresAdapter, createPostgresCache, createQueryEngine, createScopePolicy, createTieredCache, discoverEntities, mergeScopePolicies, resolve, scopeBindings, scopeGrants, scopeProfiles, seedCache, validateEntry, vexGuide };
|
|
2319
2464
|
//# sourceMappingURL=index.js.map
|
|
2320
2465
|
//# sourceMappingURL=index.js.map
|