@coasys/ad4m 0.12.0-rc1-dev.1 → 0.12.0-rc1-dev.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/jest.config.js +4 -4
- package/lib/index.cjs +5999 -6046
- package/lib/index.js +5977 -6040
- package/lib/src/Ad4mClient.d.ts +16 -9
- package/lib/src/Ad4mClient.js +25 -46
- package/lib/src/Ad4mClient.test.d.ts +1 -0
- package/lib/src/Ad4mClient.test.js +1204 -0
- package/lib/src/Literal.d.ts +2 -1
- package/lib/src/Literal.js +35 -38
- package/lib/src/Literal.test.d.ts +1 -0
- package/lib/src/Literal.test.js +41 -0
- package/lib/src/SmartLiteral.d.ts +2 -1
- package/lib/src/SmartLiteral.js +15 -30
- package/lib/src/agent/AgentClient.d.ts +4 -1
- package/lib/src/agent/AgentClient.js +99 -79
- package/lib/src/ai/AIClient.d.ts +2 -1
- package/lib/src/ai/AIClient.js +220 -224
- package/lib/src/expression/ExpressionClient.d.ts +1 -1
- package/lib/src/expression/ExpressionClient.js +86 -73
- package/lib/src/index.d.ts +1 -1
- package/lib/src/index.js +1 -1
- package/lib/src/language/LanguageClient.d.ts +1 -1
- package/lib/src/language/LanguageClient.js +52 -52
- package/lib/src/model/Ad4mModel.d.ts +157 -937
- package/lib/src/model/Ad4mModel.js +212 -2799
- package/lib/src/model/Ad4mModel.test.js +1002 -561
- package/lib/src/model/decorators.d.ts +94 -426
- package/lib/src/model/decorators.js +333 -741
- package/lib/src/model/mutation.d.ts +81 -0
- package/lib/src/model/mutation.js +317 -0
- package/lib/src/model/parentUtils.d.ts +32 -0
- package/lib/src/model/parentUtils.js +64 -0
- package/lib/src/model/prolog/generatePrologFacts.d.ts +36 -0
- package/lib/src/model/prolog/generatePrologFacts.js +139 -0
- package/lib/src/model/prolog/index.d.ts +1 -0
- package/lib/src/model/prolog/index.js +1 -0
- package/lib/src/model/query/ModelQueryBuilder.d.ts +82 -0
- package/lib/src/model/query/ModelQueryBuilder.js +115 -0
- package/lib/src/model/query/QueryBuilder.d.ts +101 -0
- package/lib/src/model/query/QueryBuilder.js +193 -0
- package/lib/src/model/query/SurrealQueryBuilder.d.ts +48 -0
- package/lib/src/model/query/SurrealQueryBuilder.js +371 -0
- package/lib/src/model/query/fetchInstance.d.ts +24 -0
- package/lib/src/model/query/fetchInstance.js +144 -0
- package/lib/src/model/query/hydration.d.ts +54 -0
- package/lib/src/model/query/hydration.js +214 -0
- package/lib/src/model/query/operations.d.ts +59 -0
- package/lib/src/model/query/operations.js +384 -0
- package/lib/src/model/query/snapshot.d.ts +59 -0
- package/lib/src/model/query/snapshot.js +106 -0
- package/lib/src/model/query/surrealCompiler.d.ts +42 -0
- package/lib/src/model/query/surrealCompiler.js +304 -0
- package/lib/src/model/schema/fromJSONSchema.d.ts +67 -0
- package/lib/src/model/schema/fromJSONSchema.js +264 -0
- package/lib/src/model/schema/metadata.d.ts +15 -0
- package/lib/src/model/schema/metadata.js +112 -0
- package/lib/src/model/subscription.d.ts +47 -0
- package/lib/src/model/subscription.js +231 -0
- package/lib/src/model/transaction.d.ts +27 -0
- package/lib/src/model/transaction.js +32 -0
- package/lib/src/model/types.d.ts +195 -0
- package/lib/src/model/types.js +8 -0
- package/lib/src/model/util.js +7 -7
- package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +5 -1
- package/lib/src/neighbourhood/NeighbourhoodClient.js +263 -181
- package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +2 -1
- package/lib/src/neighbourhood/NeighbourhoodProxy.js +13 -28
- package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +1 -5
- package/lib/src/perspectives/PerspectiveClient.d.ts +9 -9
- package/lib/src/perspectives/PerspectiveClient.js +316 -240
- package/lib/src/perspectives/PerspectiveProxy.d.ts +54 -92
- package/lib/src/perspectives/PerspectiveProxy.js +803 -444
- package/lib/src/runtime/RuntimeClient.d.ts +5 -1
- package/lib/src/runtime/RuntimeClient.js +412 -238
- package/lib/src/shacl/SHACLFlow.test.js +164 -105
- package/lib/src/shacl/SHACLShape.d.ts +17 -3
- package/lib/src/shacl/SHACLShape.js +127 -90
- package/lib/src/shacl/SHACLShape.test.js +244 -176
- package/lib/src/utils.d.ts +8 -0
- package/lib/src/utils.js +21 -7
- package/package.json +8 -13
- package/src/Ad4mClient.test.ts +1564 -1315
- package/src/Ad4mClient.ts +55 -54
- package/src/Literal.test.ts +45 -26
- package/src/Literal.ts +82 -66
- package/src/SmartLiteral.ts +74 -58
- package/src/agent/AgentClient.ts +144 -99
- package/src/ai/AIClient.ts +409 -359
- package/src/expression/ExpressionClient.ts +142 -96
- package/src/index.ts +1 -1
- package/src/language/LanguageClient.ts +137 -113
- package/src/model/Ad4mModel.test.ts +1128 -647
- package/src/model/Ad4mModel.ts +485 -3249
- package/src/model/IMPROVEMENTS.md +482 -0
- package/src/model/PREDICATE_COLLISION_FIX.md +651 -0
- package/src/model/README.md +317 -0
- package/src/model/SHACL_MUTATION_DECOUPLING.md +356 -0
- package/src/model/SUBSCRIPTION_STRATEGY.md +317 -0
- package/src/model/TC39_STAGE_3_DECORATORS.md +609 -0
- package/src/model/decorators.ts +689 -1046
- package/src/model/mutation.ts +461 -0
- package/src/model/parentUtils.ts +91 -0
- package/src/model/prolog/generatePrologFacts.ts +176 -0
- package/src/model/prolog/index.ts +1 -0
- package/src/model/query/ModelQueryBuilder.ts +173 -0
- package/src/model/query/fetchInstance.ts +181 -0
- package/src/model/query/hydration.ts +273 -0
- package/src/model/query/operations.ts +510 -0
- package/src/model/query/snapshot.ts +126 -0
- package/src/model/query/surrealCompiler.ts +376 -0
- package/src/model/schema/fromJSONSchema.ts +411 -0
- package/src/model/schema/metadata.ts +148 -0
- package/src/model/subscription.ts +307 -0
- package/src/model/transaction.ts +60 -0
- package/src/model/types.ts +207 -0
- package/src/model/util.ts +47 -48
- package/src/neighbourhood/NeighbourhoodClient.ts +393 -251
- package/src/neighbourhood/NeighbourhoodProxy.test.ts +3 -7
- package/src/neighbourhood/NeighbourhoodProxy.ts +58 -40
- package/src/perspectives/PerspectiveClient.ts +779 -540
- package/src/perspectives/PerspectiveProxy.ts +2860 -2053
- package/src/runtime/RuntimeClient.ts +775 -476
- package/src/shacl/SHACLFlow.test.ts +196 -129
- package/src/shacl/SHACLShape.test.ts +284 -190
- package/src/shacl/SHACLShape.ts +225 -172
- package/src/utils.ts +31 -17
- package/tsconfig.json +9 -10
- package/src/model/Subject.ts +0 -159
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure SurrealQL query-building functions for the AD4M model layer.
|
|
3
|
+
*
|
|
4
|
+
* All functions are stateless — they take `ModelMetadata` (and optionally a
|
|
5
|
+
* `Query`) as plain data and return strings or booleans. No dependency on the
|
|
6
|
+
* `Ad4mModel` class, which means they can be imported by tests and other
|
|
7
|
+
* modules without pulling in the full class graph.
|
|
8
|
+
*
|
|
9
|
+
* `Ad4mModel` keeps thin static wrapper methods with the original signatures so
|
|
10
|
+
* the public API is unchanged.
|
|
11
|
+
*/
|
|
12
|
+
import { escapeSurrealString } from "../../utils";
|
|
13
|
+
// ── Value formatting ────────────────────────────────────────────────────────
|
|
14
|
+
/**
|
|
15
|
+
* Formats a value for use in SurrealQL queries.
|
|
16
|
+
*
|
|
17
|
+
* - Strings: wrapped in single quotes, special characters escaped
|
|
18
|
+
* - Numbers / booleans: converted to string
|
|
19
|
+
* - Arrays: recursively formatted, wrapped in `[...]`
|
|
20
|
+
*/
|
|
21
|
+
export function formatSurrealValue(value) {
|
|
22
|
+
if (typeof value === "string") {
|
|
23
|
+
const escaped = value
|
|
24
|
+
.replace(/\\/g, "\\\\")
|
|
25
|
+
.replace(/'/g, "\\'")
|
|
26
|
+
.replace(/"/g, '\\"')
|
|
27
|
+
.replace(/\n/g, "\\n")
|
|
28
|
+
.replace(/\r/g, "\\r")
|
|
29
|
+
.replace(/\t/g, "\\t");
|
|
30
|
+
return `'${escaped}'`;
|
|
31
|
+
}
|
|
32
|
+
else if (typeof value === "number" || typeof value === "boolean") {
|
|
33
|
+
return String(value);
|
|
34
|
+
}
|
|
35
|
+
else if (Array.isArray(value)) {
|
|
36
|
+
return `[${value.map(formatSurrealValue).join(", ")}]`;
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
return String(value);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
// ── WHERE clause builders ───────────────────────────────────────────────────
|
|
43
|
+
/**
|
|
44
|
+
* Builds graph-traversal WHERE clause filters (`->link[WHERE ...]`).
|
|
45
|
+
* Used by `buildSurrealQuery` — more efficient than subqueries because
|
|
46
|
+
* SurrealDB can use graph indexes.
|
|
47
|
+
*/
|
|
48
|
+
export function buildGraphTraversalWhereClause(metadata, where) {
|
|
49
|
+
if (!where)
|
|
50
|
+
return "";
|
|
51
|
+
const conditions = [];
|
|
52
|
+
for (const [propertyName, condition] of Object.entries(where)) {
|
|
53
|
+
const isSpecial = ["base", "id", "author", "timestamp"].includes(propertyName);
|
|
54
|
+
if (isSpecial) {
|
|
55
|
+
if (propertyName === "author" || propertyName === "timestamp") {
|
|
56
|
+
continue; // filtered post-query in JavaScript
|
|
57
|
+
}
|
|
58
|
+
const columnName = "uri"; // base/id → uri in node table
|
|
59
|
+
if (Array.isArray(condition)) {
|
|
60
|
+
const formattedValues = condition.map(formatSurrealValue).join(", ");
|
|
61
|
+
conditions.push(`${columnName} IN [${formattedValues}]`);
|
|
62
|
+
}
|
|
63
|
+
else if (typeof condition === "object" && condition !== null) {
|
|
64
|
+
const ops = condition;
|
|
65
|
+
if (ops.not !== undefined) {
|
|
66
|
+
if (Array.isArray(ops.not)) {
|
|
67
|
+
const formattedValues = ops.not.map(formatSurrealValue).join(", ");
|
|
68
|
+
conditions.push(`${columnName} NOT IN [${formattedValues}]`);
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
conditions.push(`${columnName} != ${formatSurrealValue(ops.not)}`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
if (ops.between !== undefined &&
|
|
75
|
+
Array.isArray(ops.between) &&
|
|
76
|
+
ops.between.length === 2) {
|
|
77
|
+
conditions.push(`${columnName} >= ${formatSurrealValue(ops.between[0])} AND ${columnName} <= ${formatSurrealValue(ops.between[1])}`);
|
|
78
|
+
}
|
|
79
|
+
if (ops.gt !== undefined)
|
|
80
|
+
conditions.push(`${columnName} > ${formatSurrealValue(ops.gt)}`);
|
|
81
|
+
if (ops.gte !== undefined)
|
|
82
|
+
conditions.push(`${columnName} >= ${formatSurrealValue(ops.gte)}`);
|
|
83
|
+
if (ops.lt !== undefined)
|
|
84
|
+
conditions.push(`${columnName} < ${formatSurrealValue(ops.lt)}`);
|
|
85
|
+
if (ops.lte !== undefined)
|
|
86
|
+
conditions.push(`${columnName} <= ${formatSurrealValue(ops.lte)}`);
|
|
87
|
+
if (ops.contains !== undefined)
|
|
88
|
+
conditions.push(`${columnName} CONTAINS ${formatSurrealValue(ops.contains)}`);
|
|
89
|
+
}
|
|
90
|
+
else {
|
|
91
|
+
conditions.push(`${columnName} = ${formatSurrealValue(condition)}`);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
else {
|
|
95
|
+
const propMeta = metadata.properties[propertyName];
|
|
96
|
+
if (!propMeta)
|
|
97
|
+
continue;
|
|
98
|
+
const predicate = escapeSurrealString(propMeta.predicate);
|
|
99
|
+
const targetField = propMeta.resolveLanguage === "literal"
|
|
100
|
+
? "fn::parse_literal(out.uri)"
|
|
101
|
+
: "out.uri";
|
|
102
|
+
if (Array.isArray(condition)) {
|
|
103
|
+
const formattedValues = condition.map(formatSurrealValue).join(", ");
|
|
104
|
+
conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`);
|
|
105
|
+
}
|
|
106
|
+
else if (typeof condition === "object" && condition !== null) {
|
|
107
|
+
const ops = condition;
|
|
108
|
+
if (ops.not !== undefined) {
|
|
109
|
+
if (Array.isArray(ops.not)) {
|
|
110
|
+
const formattedValues = ops.not.map(formatSurrealValue).join(", ");
|
|
111
|
+
conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(ops.not)}]) = 0`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
const hasComparisonOps = ops.gt !== undefined ||
|
|
118
|
+
ops.gte !== undefined ||
|
|
119
|
+
ops.lt !== undefined ||
|
|
120
|
+
ops.lte !== undefined ||
|
|
121
|
+
ops.between !== undefined ||
|
|
122
|
+
ops.contains !== undefined;
|
|
123
|
+
if (hasComparisonOps) {
|
|
124
|
+
conditions.push(`count(->link[WHERE predicate = '${predicate}']) > 0`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
else {
|
|
128
|
+
conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(condition)}]) > 0`);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return conditions.join(" AND ");
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Builds a legacy subquery-based WHERE clause.
|
|
136
|
+
* Kept for compatibility; prefer `buildGraphTraversalWhereClause`.
|
|
137
|
+
*/
|
|
138
|
+
export function buildSurrealWhereClause(metadata, where) {
|
|
139
|
+
if (!where)
|
|
140
|
+
return "";
|
|
141
|
+
const conditions = [];
|
|
142
|
+
for (const [propertyName, condition] of Object.entries(where)) {
|
|
143
|
+
const isSpecial = ["base", "id", "author", "timestamp"].includes(propertyName);
|
|
144
|
+
if (isSpecial) {
|
|
145
|
+
if (propertyName === "author" || propertyName === "timestamp") {
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
const columnName = "source";
|
|
149
|
+
if (Array.isArray(condition)) {
|
|
150
|
+
const formattedValues = condition.map(formatSurrealValue).join(", ");
|
|
151
|
+
conditions.push(`${columnName} IN [${formattedValues}]`);
|
|
152
|
+
}
|
|
153
|
+
else if (typeof condition === "object" && condition !== null) {
|
|
154
|
+
const ops = condition;
|
|
155
|
+
if (ops.not !== undefined) {
|
|
156
|
+
if (Array.isArray(ops.not)) {
|
|
157
|
+
const formattedValues = ops.not.map(formatSurrealValue).join(", ");
|
|
158
|
+
conditions.push(`${columnName} NOT IN [${formattedValues}]`);
|
|
159
|
+
}
|
|
160
|
+
else {
|
|
161
|
+
conditions.push(`${columnName} != ${formatSurrealValue(ops.not)}`);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
if (ops.between !== undefined &&
|
|
165
|
+
Array.isArray(ops.between) &&
|
|
166
|
+
ops.between.length === 2) {
|
|
167
|
+
conditions.push(`${columnName} >= ${formatSurrealValue(ops.between[0])} AND ${columnName} <= ${formatSurrealValue(ops.between[1])}`);
|
|
168
|
+
}
|
|
169
|
+
if (ops.gt !== undefined)
|
|
170
|
+
conditions.push(`${columnName} > ${formatSurrealValue(ops.gt)}`);
|
|
171
|
+
if (ops.gte !== undefined)
|
|
172
|
+
conditions.push(`${columnName} >= ${formatSurrealValue(ops.gte)}`);
|
|
173
|
+
if (ops.lt !== undefined)
|
|
174
|
+
conditions.push(`${columnName} < ${formatSurrealValue(ops.lt)}`);
|
|
175
|
+
if (ops.lte !== undefined)
|
|
176
|
+
conditions.push(`${columnName} <= ${formatSurrealValue(ops.lte)}`);
|
|
177
|
+
if (ops.contains !== undefined)
|
|
178
|
+
conditions.push(`${columnName} CONTAINS ${formatSurrealValue(ops.contains)}`);
|
|
179
|
+
}
|
|
180
|
+
else {
|
|
181
|
+
conditions.push(`${columnName} = ${formatSurrealValue(condition)}`);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
else {
|
|
185
|
+
const propMeta = metadata.properties[propertyName];
|
|
186
|
+
if (!propMeta)
|
|
187
|
+
continue;
|
|
188
|
+
const predicate = escapeSurrealString(propMeta.predicate);
|
|
189
|
+
const targetField = propMeta.resolveLanguage === "literal"
|
|
190
|
+
? "fn::parse_literal(target)"
|
|
191
|
+
: "target";
|
|
192
|
+
if (Array.isArray(condition)) {
|
|
193
|
+
const formattedValues = condition.map(formatSurrealValue).join(", ");
|
|
194
|
+
conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}])`);
|
|
195
|
+
}
|
|
196
|
+
else if (typeof condition === "object" && condition !== null) {
|
|
197
|
+
const ops = condition;
|
|
198
|
+
if (ops.not !== undefined) {
|
|
199
|
+
if (Array.isArray(ops.not)) {
|
|
200
|
+
const formattedValues = ops.not.map(formatSurrealValue).join(", ");
|
|
201
|
+
conditions.push(`source NOT IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}])`);
|
|
202
|
+
}
|
|
203
|
+
else {
|
|
204
|
+
conditions.push(`source NOT IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(ops.not)})`);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
const hasComparisonOps = ops.gt !== undefined ||
|
|
208
|
+
ops.gte !== undefined ||
|
|
209
|
+
ops.lt !== undefined ||
|
|
210
|
+
ops.lte !== undefined ||
|
|
211
|
+
ops.between !== undefined ||
|
|
212
|
+
ops.contains !== undefined;
|
|
213
|
+
if (hasComparisonOps) {
|
|
214
|
+
conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}')`);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
else {
|
|
218
|
+
conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(condition)})`);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return conditions.join(" AND ");
|
|
223
|
+
}
|
|
224
|
+
// ── SELECT field builders ───────────────────────────────────────────────────
|
|
225
|
+
export function buildSurrealSelectFields(metadata, properties, relations) {
|
|
226
|
+
const fields = [];
|
|
227
|
+
const propsToFetch = properties || Object.keys(metadata.properties);
|
|
228
|
+
for (const propName of propsToFetch) {
|
|
229
|
+
const propMeta = metadata.properties[propName];
|
|
230
|
+
if (!propMeta)
|
|
231
|
+
continue;
|
|
232
|
+
const escapedPredicate = escapeSurrealString(propMeta.predicate);
|
|
233
|
+
fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}' LIMIT 1) AS ${propName}`);
|
|
234
|
+
}
|
|
235
|
+
const relationsToFetch = relations || Object.keys(metadata.relations);
|
|
236
|
+
for (const relationName of relationsToFetch) {
|
|
237
|
+
const relationMeta = metadata.relations[relationName];
|
|
238
|
+
if (!relationMeta)
|
|
239
|
+
continue;
|
|
240
|
+
const escapedPredicate = escapeSurrealString(relationMeta.predicate);
|
|
241
|
+
fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}') AS ${relationName}`);
|
|
242
|
+
}
|
|
243
|
+
fields.push(`(SELECT VALUE author FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS author`);
|
|
244
|
+
fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS createdAt`);
|
|
245
|
+
fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source ORDER BY timestamp DESC LIMIT 1) AS updatedAt`);
|
|
246
|
+
return fields.join(",\n ");
|
|
247
|
+
}
|
|
248
|
+
export function buildSurrealSelectFieldsWithAggregation(metadata, properties, relations) {
|
|
249
|
+
const fields = [];
|
|
250
|
+
const propsToFetch = properties || Object.keys(metadata.properties);
|
|
251
|
+
for (const propName of propsToFetch) {
|
|
252
|
+
const propMeta = metadata.properties[propName];
|
|
253
|
+
if (!propMeta)
|
|
254
|
+
continue;
|
|
255
|
+
const escapedPredicate = escapeSurrealString(propMeta.predicate);
|
|
256
|
+
fields.push(`array::first(target[WHERE predicate = '${escapedPredicate}']) AS ${propName}`);
|
|
257
|
+
}
|
|
258
|
+
const relationsToFetch = relations || Object.keys(metadata.relations);
|
|
259
|
+
for (const relationName of relationsToFetch) {
|
|
260
|
+
const relationMeta = metadata.relations[relationName];
|
|
261
|
+
if (!relationMeta)
|
|
262
|
+
continue;
|
|
263
|
+
const escapedPredicate = escapeSurrealString(relationMeta.predicate);
|
|
264
|
+
fields.push(`target[WHERE predicate = '${escapedPredicate}'] AS ${relationName}`);
|
|
265
|
+
}
|
|
266
|
+
fields.push(`array::first(author) AS author`);
|
|
267
|
+
fields.push(`array::first(timestamp) AS createdAt`);
|
|
268
|
+
fields.push(`array::last(timestamp) AS updatedAt`);
|
|
269
|
+
return fields.join(",\n ");
|
|
270
|
+
}
|
|
271
|
+
// ── Main query builders ─────────────────────────────────────────────────────
|
|
272
|
+
/**
|
|
273
|
+
* Builds the SurrealQL SELECT query for a given model metadata + query params.
|
|
274
|
+
* This is the extracted, pure-function form of `Ad4mModel.queryToSurrealQL`.
|
|
275
|
+
*/
|
|
276
|
+
export function buildSurrealQuery(metadata, query) {
|
|
277
|
+
const { where } = query;
|
|
278
|
+
const graphTraversalFilters = [];
|
|
279
|
+
for (const [, propMeta] of Object.entries(metadata.properties)) {
|
|
280
|
+
if (propMeta.required) {
|
|
281
|
+
if (propMeta.flag && propMeta.initial) {
|
|
282
|
+
graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
|
|
283
|
+
}
|
|
284
|
+
else {
|
|
285
|
+
graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
if (graphTraversalFilters.length === 0) {
|
|
290
|
+
for (const [, propMeta] of Object.entries(metadata.properties)) {
|
|
291
|
+
if (propMeta.initial) {
|
|
292
|
+
if (propMeta.flag) {
|
|
293
|
+
graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
|
|
294
|
+
}
|
|
295
|
+
else {
|
|
296
|
+
graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
|
|
297
|
+
}
|
|
298
|
+
break;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
const userWhereClause = buildGraphTraversalWhereClause(metadata, where);
|
|
303
|
+
const whereConditions = [
|
|
304
|
+
...graphTraversalFilters,
|
|
305
|
+
...(userWhereClause ? [userWhereClause] : []),
|
|
306
|
+
`count(->link) > 0`,
|
|
307
|
+
];
|
|
308
|
+
return `
|
|
309
|
+
SELECT
|
|
310
|
+
id AS source,
|
|
311
|
+
uri AS source_uri,
|
|
312
|
+
(SELECT predicate, out.uri AS target, author, timestamp FROM link WHERE in = $parent.id ORDER BY timestamp ASC) AS links
|
|
313
|
+
FROM node
|
|
314
|
+
WHERE ${whereConditions.join(" AND ")}
|
|
315
|
+
`.trim();
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Builds a count query (same as `buildSurrealQuery` but without LIMIT/OFFSET).
|
|
319
|
+
*/
|
|
320
|
+
export function buildSurrealCountQuery(metadata, query) {
|
|
321
|
+
const countQuery = { ...query };
|
|
322
|
+
delete countQuery.limit;
|
|
323
|
+
delete countQuery.offset;
|
|
324
|
+
return buildSurrealQuery(metadata, countQuery);
|
|
325
|
+
}
|
|
326
|
+
// ── Post-query filtering ────────────────────────────────────────────────────
|
|
327
|
+
/**
|
|
328
|
+
* Checks whether a single value satisfies a WhereCondition.
|
|
329
|
+
* Used for post-query JavaScript filtering of operators that SurrealDB
|
|
330
|
+
* cannot evaluate reliably (gt/gte/lt/lte/between/contains on literals).
|
|
331
|
+
*/
|
|
332
|
+
export function matchesCondition(value, condition) {
|
|
333
|
+
if (Array.isArray(condition)) {
|
|
334
|
+
return condition.includes(value);
|
|
335
|
+
}
|
|
336
|
+
if (typeof condition === "object" && condition !== null) {
|
|
337
|
+
const ops = condition;
|
|
338
|
+
if (ops.not !== undefined) {
|
|
339
|
+
return Array.isArray(ops.not)
|
|
340
|
+
? !ops.not.includes(value)
|
|
341
|
+
: value !== ops.not;
|
|
342
|
+
}
|
|
343
|
+
if (ops.between !== undefined &&
|
|
344
|
+
Array.isArray(ops.between) &&
|
|
345
|
+
ops.between.length === 2) {
|
|
346
|
+
return value >= ops.between[0] && value <= ops.between[1];
|
|
347
|
+
}
|
|
348
|
+
let allMet = true;
|
|
349
|
+
if (ops.gt !== undefined)
|
|
350
|
+
allMet = allMet && value > ops.gt;
|
|
351
|
+
if (ops.gte !== undefined)
|
|
352
|
+
allMet = allMet && value >= ops.gte;
|
|
353
|
+
if (ops.lt !== undefined)
|
|
354
|
+
allMet = allMet && value < ops.lt;
|
|
355
|
+
if (ops.lte !== undefined)
|
|
356
|
+
allMet = allMet && value <= ops.lte;
|
|
357
|
+
if (ops.contains !== undefined) {
|
|
358
|
+
if (typeof value === "string") {
|
|
359
|
+
allMet = allMet && value.includes(String(ops.contains));
|
|
360
|
+
}
|
|
361
|
+
else if (Array.isArray(value)) {
|
|
362
|
+
allMet = allMet && value.includes(ops.contains);
|
|
363
|
+
}
|
|
364
|
+
else {
|
|
365
|
+
allMet = false;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
return allMet;
|
|
369
|
+
}
|
|
370
|
+
return value === condition;
|
|
371
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Single-instance hydration pipeline for Ad4mModel.
|
|
3
|
+
*
|
|
4
|
+
* Extracted from Ad4mModel.getData() (Phase 3a Part 5).
|
|
5
|
+
*
|
|
6
|
+
* `fetchInstanceData()` queries SurrealDB for all links belonging to one
|
|
7
|
+
* instance and populates the instance in-place:
|
|
8
|
+
* 1. Forward-link query → shared `hydrateInstanceFromLinks`
|
|
9
|
+
* 2. relatedModel eager hydration via `_findAllInternal`
|
|
10
|
+
* 3. Reverse-relation batch query
|
|
11
|
+
* 4. Custom SurrealQL getters (`evaluateCustomGetters`)
|
|
12
|
+
*/
|
|
13
|
+
import type { PerspectiveProxy } from "../../perspectives/PerspectiveProxy";
|
|
14
|
+
import type { ModelMetadata, IncludeMap } from "../types";
|
|
15
|
+
/**
|
|
16
|
+
* Hydrates `instance` in-place from SurrealDB and returns it.
|
|
17
|
+
*
|
|
18
|
+
* @param instance - The Ad4mModel instance to populate
|
|
19
|
+
* @param perspective - Perspective that owns the instance
|
|
20
|
+
* @param id - The instance's base expression URI
|
|
21
|
+
* @param metadata - Pre-resolved model metadata (from `getModelMetadata()`)
|
|
22
|
+
* @param include - Optional eager-load map
|
|
23
|
+
*/
|
|
24
|
+
export declare function fetchInstanceData(instance: any, perspective: PerspectiveProxy, id: string, metadata: ModelMetadata, include?: IncludeMap): Promise<any>;
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Single-instance hydration pipeline for Ad4mModel.
|
|
3
|
+
*
|
|
4
|
+
* Extracted from Ad4mModel.getData() (Phase 3a Part 5).
|
|
5
|
+
*
|
|
6
|
+
* `fetchInstanceData()` queries SurrealDB for all links belonging to one
|
|
7
|
+
* instance and populates the instance in-place:
|
|
8
|
+
* 1. Forward-link query → shared `hydrateInstanceFromLinks`
|
|
9
|
+
* 2. relatedModel eager hydration via `_findAllInternal`
|
|
10
|
+
* 3. Reverse-relation batch query
|
|
11
|
+
* 4. Custom SurrealQL getters (`evaluateCustomGetters`)
|
|
12
|
+
*/
|
|
13
|
+
import { formatSurrealValue } from "./surrealCompiler";
|
|
14
|
+
import { hydrateInstanceFromLinks, evaluateCustomGetters } from "./hydration";
|
|
15
|
+
import { captureSnapshot } from "./snapshot";
|
|
16
|
+
import { _findAllInternal } from "./operations";
|
|
17
|
+
/**
|
|
18
|
+
* Hydrates `instance` in-place from SurrealDB and returns it.
|
|
19
|
+
*
|
|
20
|
+
* @param instance - The Ad4mModel instance to populate
|
|
21
|
+
* @param perspective - Perspective that owns the instance
|
|
22
|
+
* @param id - The instance's base expression URI
|
|
23
|
+
* @param metadata - Pre-resolved model metadata (from `getModelMetadata()`)
|
|
24
|
+
* @param include - Optional eager-load map
|
|
25
|
+
*/
|
|
26
|
+
export async function fetchInstanceData(instance, perspective, id, metadata, include) {
|
|
27
|
+
try {
|
|
28
|
+
const safeBase = formatSurrealValue(id);
|
|
29
|
+
// ── 1. Forward links ────────────────────────────────────────────────────
|
|
30
|
+
const links = await perspective.querySurrealDB(`
|
|
31
|
+
SELECT id, predicate, out.uri AS target, author, timestamp
|
|
32
|
+
FROM link
|
|
33
|
+
WHERE in.uri = ${safeBase}
|
|
34
|
+
ORDER BY timestamp ASC
|
|
35
|
+
`);
|
|
36
|
+
if (links && links.length > 0) {
|
|
37
|
+
// ── 2. Shared hydration: properties + forward relations + timestamps ──
|
|
38
|
+
await hydrateInstanceFromLinks(instance, links, metadata, perspective);
|
|
39
|
+
// ── 2. relatedModel eager hydration ──────────────────────────────────
|
|
40
|
+
const forwardRelations = Object.entries(metadata.relations).filter(([, m]) => !m.getter && m.direction !== "reverse");
|
|
41
|
+
for (const [relationName, relationMeta] of forwardRelations) {
|
|
42
|
+
const current = instance[relationName];
|
|
43
|
+
let values = Array.isArray(current)
|
|
44
|
+
? [...current]
|
|
45
|
+
: current != null
|
|
46
|
+
? [current]
|
|
47
|
+
: [];
|
|
48
|
+
// relatedModel: eager hydration — only when caller asked for it via include
|
|
49
|
+
const includeEntry = include?.[relationName];
|
|
50
|
+
if (includeEntry !== undefined &&
|
|
51
|
+
relationMeta.relatedModel &&
|
|
52
|
+
values.length > 0) {
|
|
53
|
+
try {
|
|
54
|
+
const RelatedModel = relationMeta.relatedModel();
|
|
55
|
+
const subQuery = includeEntry === true
|
|
56
|
+
? { where: { id: values } }
|
|
57
|
+
: {
|
|
58
|
+
...includeEntry,
|
|
59
|
+
where: { id: values, ...includeEntry.where },
|
|
60
|
+
};
|
|
61
|
+
const hydrated = await _findAllInternal(RelatedModel, perspective, subQuery, false);
|
|
62
|
+
instance[relationName] =
|
|
63
|
+
relationMeta.maxCount === 1
|
|
64
|
+
? (hydrated[0] ?? null)
|
|
65
|
+
: hydrated;
|
|
66
|
+
}
|
|
67
|
+
catch (e) {
|
|
68
|
+
console.warn(`Failed to hydrate ${relationName}:`, e);
|
|
69
|
+
instance[relationName] =
|
|
70
|
+
relationMeta.maxCount === 1
|
|
71
|
+
? (values[0] ?? null)
|
|
72
|
+
: values;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
else {
|
|
76
|
+
instance[relationName] =
|
|
77
|
+
relationMeta.maxCount === 1 ? (values[0] ?? null) : values;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
// ── 3. Reverse relations ────────────────────────────────────────────────
|
|
82
|
+
const reverseRelations = Object.entries(metadata.relations).filter(([, m]) => !m.getter && m.direction === "reverse");
|
|
83
|
+
if (reverseRelations.length > 0) {
|
|
84
|
+
let reverseLinks = [];
|
|
85
|
+
try {
|
|
86
|
+
reverseLinks =
|
|
87
|
+
(await perspective.querySurrealDB(`
|
|
88
|
+
SELECT in.uri AS source, predicate, id, author, timestamp
|
|
89
|
+
FROM link
|
|
90
|
+
WHERE out.uri = ${safeBase}
|
|
91
|
+
ORDER BY timestamp ASC
|
|
92
|
+
`)) ?? [];
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
// leave empty — instance just won't have reverse relation data
|
|
96
|
+
}
|
|
97
|
+
for (const [relationName, relationMeta] of reverseRelations) {
|
|
98
|
+
const matching = reverseLinks.filter((l) => l.predicate === relationMeta.predicate);
|
|
99
|
+
const values = matching.map((l) => l.source);
|
|
100
|
+
const includeEntry = include?.[relationName];
|
|
101
|
+
if (includeEntry !== undefined &&
|
|
102
|
+
relationMeta.relatedModel &&
|
|
103
|
+
values.length > 0) {
|
|
104
|
+
try {
|
|
105
|
+
const RelatedModel = relationMeta.relatedModel();
|
|
106
|
+
const subQuery = includeEntry === true
|
|
107
|
+
? { where: { id: values } }
|
|
108
|
+
: {
|
|
109
|
+
...includeEntry,
|
|
110
|
+
where: { id: values, ...includeEntry.where },
|
|
111
|
+
};
|
|
112
|
+
const hydrated = await _findAllInternal(RelatedModel, perspective, subQuery, false);
|
|
113
|
+
instance[relationName] =
|
|
114
|
+
relationMeta.maxCount === 1
|
|
115
|
+
? (hydrated[0] ?? null)
|
|
116
|
+
: hydrated;
|
|
117
|
+
}
|
|
118
|
+
catch (e) {
|
|
119
|
+
instance[relationName] =
|
|
120
|
+
relationMeta.maxCount === 1
|
|
121
|
+
? (values[0] ?? null)
|
|
122
|
+
: values;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
else {
|
|
126
|
+
instance[relationName] =
|
|
127
|
+
relationMeta.maxCount === 1 ? (values[0] ?? null) : values;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
// ── 4. Custom SurrealQL getters ─────────────────────────────────────────
|
|
132
|
+
await evaluateCustomGetters(instance, perspective, metadata);
|
|
133
|
+
// ── 5. Snapshot capture — baseline for dirty tracking on next save() ────
|
|
134
|
+
const schemaKeys = [
|
|
135
|
+
...Object.keys(metadata.properties),
|
|
136
|
+
...Object.keys(metadata.relations),
|
|
137
|
+
];
|
|
138
|
+
captureSnapshot(instance, schemaKeys);
|
|
139
|
+
}
|
|
140
|
+
catch (e) {
|
|
141
|
+
console.error(`SurrealDB getData failed for ${id}:`, e);
|
|
142
|
+
}
|
|
143
|
+
return instance;
|
|
144
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared instance hydration utilities for Ad4mModel.
|
|
3
|
+
*
|
|
4
|
+
* Both `getData()` (single-instance path) and `instancesFromSurrealResult()`
|
|
5
|
+
* (bulk path) delegate to `hydrateInstanceFromLinks()` and
|
|
6
|
+
* `evaluateCustomGetters()` here, guaranteeing identical semantics.
|
|
7
|
+
*
|
|
8
|
+
* Previously the two implementations diverged — most notably, `getData()` used
|
|
9
|
+
* "latest-wins" for properties while `instancesFromSurrealResult()` used
|
|
10
|
+
* "first-wins". Both now use latest-wins (last ASC-ordered link per predicate).
|
|
11
|
+
*/
|
|
12
|
+
import { PerspectiveProxy } from "../../perspectives/PerspectiveProxy";
|
|
13
|
+
import type { ModelMetadata } from "../types";
|
|
14
|
+
/** Raw link row as returned by SurrealDB queries. */
|
|
15
|
+
export interface RawLink {
|
|
16
|
+
predicate: string;
|
|
17
|
+
target: string;
|
|
18
|
+
author?: string;
|
|
19
|
+
timestamp?: string | number;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Normalise a SurrealDB timestamp to epoch-milliseconds.
|
|
23
|
+
*
|
|
24
|
+
* - ISO strings (`"2024-01-01T00:00:00Z"`) → `Date.getTime()`
|
|
25
|
+
* - Numeric strings (`"1700000000000"`) → `parseInt`
|
|
26
|
+
* - Numbers → returned as-is
|
|
27
|
+
* - Anything else → returned as-is (no data loss)
|
|
28
|
+
*/
|
|
29
|
+
export declare function normalizeTimestamp(ts: any): number | string;
|
|
30
|
+
/**
|
|
31
|
+
* Hydrates a model instance from a flat array of raw SurrealDB link rows.
|
|
32
|
+
*
|
|
33
|
+
* **Guarantees:**
|
|
34
|
+
* - Properties use *"latest-wins"* semantics — links must be ordered
|
|
35
|
+
* `ASC` by `timestamp`; the last matching link per predicate wins.
|
|
36
|
+
* - Forward relations preserve insertion order (links already ASC).
|
|
37
|
+
* - `createdAt` / `updatedAt` / `author` are derived from the global
|
|
38
|
+
* min/max timestamps across **all** links (not just property links).
|
|
39
|
+
*
|
|
40
|
+
* **Does NOT handle** (left to the caller):
|
|
41
|
+
* - Reverse relations — require a separate `WHERE out.uri = $base` query.
|
|
42
|
+
* - Custom getter evaluation — call `evaluateCustomGetters()` afterwards.
|
|
43
|
+
* - `relatedModel` eager hydration — do that in a batch pass afterwards.
|
|
44
|
+
*/
|
|
45
|
+
export declare function hydrateInstanceFromLinks(instance: any, links: RawLink[], metadata: ModelMetadata, perspective: PerspectiveProxy): Promise<void>;
|
|
46
|
+
/**
|
|
47
|
+
* Evaluates custom SurrealQL getter expressions for all `getter`-decorated
|
|
48
|
+
* properties and relations on a single model instance.
|
|
49
|
+
*
|
|
50
|
+
* Called by both `getData()` (single-instance path) and
|
|
51
|
+
* `instancesFromSurrealResult()` (bulk path) — single implementation so
|
|
52
|
+
* neither path can diverge.
|
|
53
|
+
*/
|
|
54
|
+
export declare function evaluateCustomGetters(instance: any, perspective: PerspectiveProxy, metadata: ModelMetadata): Promise<void>;
|