@coasys/ad4m 0.11.2-dev.5 → 0.11.2-dev.6
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/lib/index.cjs +137 -61
- package/lib/index.js +137 -61
- package/lib/src/model/Ad4mModel.d.ts +6 -5
- package/lib/src/model/Ad4mModel.js +63 -33
- package/lib/src/model/Ad4mModel.test.js +10 -10
- package/lib/src/model/decorators.d.ts +26 -18
- package/lib/src/model/decorators.js +40 -25
- package/lib/src/perspectives/PerspectiveProxy.d.ts +3 -0
- package/lib/src/perspectives/PerspectiveProxy.js +34 -3
- package/package.json +1 -1
- package/src/model/Ad4mModel.test.ts +10 -10
- package/src/model/Ad4mModel.ts +69 -34
- package/src/model/decorators.ts +48 -34
- package/src/perspectives/PerspectiveProxy.ts +43 -7
|
@@ -1140,6 +1140,7 @@ export class PerspectiveProxy {
|
|
|
1140
1140
|
const collName = result.Coll;
|
|
1141
1141
|
let predicate = null;
|
|
1142
1142
|
let instanceFilter = undefined;
|
|
1143
|
+
let condition = undefined;
|
|
1143
1144
|
// Try to extract predicate from collection_adder first
|
|
1144
1145
|
const adderResults = await this.infer(`subject_class("${className}", C), collection_adder(C, "${collName}", Adder)`);
|
|
1145
1146
|
if (adderResults && adderResults.length > 0) {
|
|
@@ -1149,6 +1150,8 @@ export class PerspectiveProxy {
|
|
|
1149
1150
|
predicate = predicateMatch[1] || predicateMatch[2];
|
|
1150
1151
|
}
|
|
1151
1152
|
}
|
|
1153
|
+
// Note: condition is not stored in SDNA, it's read from class metadata
|
|
1154
|
+
// It will be populated by augmentMetadataWithCollectionOptions() when needed
|
|
1152
1155
|
// Parse collection_getter from SDNA to extract predicate and instanceFilter
|
|
1153
1156
|
// Format 1 (findall): collection_getter(c, Base, "comments", List) :- findall(C, triple(Base, "todo://comment", C), List).
|
|
1154
1157
|
// Format 2 (setof): collection_getter(c, Base, "messages", List) :- setof(Target, (triple(Base, "flux://entry_type", Target), ...), List).
|
|
@@ -1184,7 +1187,7 @@ export class PerspectiveProxy {
|
|
|
1184
1187
|
}
|
|
1185
1188
|
}
|
|
1186
1189
|
if (predicate) {
|
|
1187
|
-
collections.set(collName, { predicate, instanceFilter });
|
|
1190
|
+
collections.set(collName, { predicate, instanceFilter, condition });
|
|
1188
1191
|
}
|
|
1189
1192
|
}
|
|
1190
1193
|
}
|
|
@@ -1260,6 +1263,7 @@ export class PerspectiveProxy {
|
|
|
1260
1263
|
/**
|
|
1261
1264
|
* Gets collection values using SurrealDB when Prolog fails.
|
|
1262
1265
|
* This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
|
|
1266
|
+
* Note: This is used by Subject.ts (legacy pattern). Ad4mModel.ts uses getModelMetadata() instead.
|
|
1263
1267
|
*/
|
|
1264
1268
|
async getCollectionValuesViaSurreal(baseExpression, className, collectionName) {
|
|
1265
1269
|
const metadata = await this.getSubjectClassMetadataFromSDNA(className);
|
|
@@ -1278,6 +1282,31 @@ export class PerspectiveProxy {
|
|
|
1278
1282
|
return [];
|
|
1279
1283
|
}
|
|
1280
1284
|
let values = result.map(r => r.value).filter(v => v !== "" && v !== '');
|
|
1285
|
+
// Apply condition filtering if present
|
|
1286
|
+
if (collMeta.condition && values.length > 0) {
|
|
1287
|
+
try {
|
|
1288
|
+
const filteredValues = [];
|
|
1289
|
+
for (const value of values) {
|
|
1290
|
+
let condition = collMeta.condition
|
|
1291
|
+
.replace(/\$perspective/g, `'${this.uuid}'`)
|
|
1292
|
+
.replace(/\$base/g, `'${baseExpression}'`)
|
|
1293
|
+
.replace(/Target/g, `'${value.replace(/'/g, "\\'")}'`);
|
|
1294
|
+
// If condition starts with WHERE, wrap in array length check
|
|
1295
|
+
if (condition.trim().startsWith('WHERE')) {
|
|
1296
|
+
condition = `array::len(SELECT * FROM link ${condition}) > 0`;
|
|
1297
|
+
}
|
|
1298
|
+
const filterResult = await this.querySurrealDB(`RETURN ${condition}`);
|
|
1299
|
+
const isTrue = filterResult === true || (Array.isArray(filterResult) && filterResult.length > 0 && filterResult[0] === true);
|
|
1300
|
+
if (isTrue) {
|
|
1301
|
+
filteredValues.push(value);
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
values = filteredValues;
|
|
1305
|
+
}
|
|
1306
|
+
catch (error) {
|
|
1307
|
+
console.warn(`Failed to apply condition filter for ${collectionName}:`, error);
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1281
1310
|
// Apply instance filter if present - batch-check all values at once
|
|
1282
1311
|
if (collMeta.instanceFilter) {
|
|
1283
1312
|
try {
|
|
@@ -1319,11 +1348,13 @@ export class PerspectiveProxy {
|
|
|
1319
1348
|
if (triple.target) {
|
|
1320
1349
|
// Flag: must match both predicate AND exact target value
|
|
1321
1350
|
const escapedTarget = escapeSurrealString(triple.target);
|
|
1322
|
-
|
|
1351
|
+
// Note: Removed GROUP BY because it was causing SurrealDB to only return one result
|
|
1352
|
+
checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}'`;
|
|
1323
1353
|
}
|
|
1324
1354
|
else {
|
|
1325
1355
|
// Property: just check predicate exists
|
|
1326
|
-
|
|
1356
|
+
// Note: Removed GROUP BY because it was causing SurrealDB to only return one result
|
|
1357
|
+
checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}'`;
|
|
1327
1358
|
}
|
|
1328
1359
|
const result = await this.querySurrealDB(checkQuery);
|
|
1329
1360
|
validExpressionSets.push(new Set(result.map(r => r.uri)));
|
package/package.json
CHANGED
|
@@ -57,7 +57,7 @@
|
|
|
57
57
|
"react-dom": "*"
|
|
58
58
|
},
|
|
59
59
|
"patchedDependencies": {},
|
|
60
|
-
"version": "0.11.2-dev.
|
|
60
|
+
"version": "0.11.2-dev.6",
|
|
61
61
|
"scripts": {
|
|
62
62
|
"build": "patch-package && tsc && pnpm run buildSchema && pnpm run bundle",
|
|
63
63
|
"buildSchema": "node --es-module-specifier-resolution=node lib/src/buildSchema.js",
|
|
@@ -22,7 +22,7 @@ describe("Ad4mModel.getModelMetadata()", () => {
|
|
|
22
22
|
@Optional({ through: "test://optional", writable: true })
|
|
23
23
|
optional: string = "";
|
|
24
24
|
|
|
25
|
-
@ReadOnly({ through: "test://readonly",
|
|
25
|
+
@ReadOnly({ through: "test://readonly", prologGetter: "custom_getter" })
|
|
26
26
|
readonly: string = "";
|
|
27
27
|
|
|
28
28
|
@Flag({ through: "test://type", value: "test://flag" })
|
|
@@ -47,7 +47,7 @@ describe("Ad4mModel.getModelMetadata()", () => {
|
|
|
47
47
|
// Verify "readonly" property
|
|
48
48
|
expect(metadata.properties.readonly.predicate).toBe("test://readonly");
|
|
49
49
|
expect(metadata.properties.readonly.writable).toBe(false);
|
|
50
|
-
expect(metadata.properties.readonly.
|
|
50
|
+
expect(metadata.properties.readonly.prologGetter).toBe("custom_getter");
|
|
51
51
|
|
|
52
52
|
// Verify "type" property (flag)
|
|
53
53
|
expect(metadata.properties.type.predicate).toBe("test://type");
|
|
@@ -114,18 +114,18 @@ describe("Ad4mModel.getModelMetadata()", () => {
|
|
|
114
114
|
class CustomModel extends Ad4mModel {
|
|
115
115
|
@Optional({
|
|
116
116
|
through: "test://computed",
|
|
117
|
-
|
|
118
|
-
|
|
117
|
+
prologGetter: "triple(Base, 'test://value', V), Value is V * 2",
|
|
118
|
+
prologSetter: "Value is V / 2, Actions = [{action: 'setSingleTarget', source: 'this', predicate: 'test://value', target: Value}]"
|
|
119
119
|
})
|
|
120
120
|
computed: number = 0;
|
|
121
121
|
}
|
|
122
122
|
|
|
123
123
|
const metadata = CustomModel.getModelMetadata();
|
|
124
124
|
|
|
125
|
-
// Assert
|
|
126
|
-
expect(metadata.properties.computed.
|
|
127
|
-
expect(metadata.properties.computed.
|
|
128
|
-
expect(metadata.properties.computed.
|
|
125
|
+
// Assert prologGetter and prologSetter contain the custom code
|
|
126
|
+
expect(metadata.properties.computed.prologGetter).toContain("triple(Base, 'test://value', V), Value is V * 2");
|
|
127
|
+
expect(metadata.properties.computed.prologSetter).toContain("Value is V / 2");
|
|
128
|
+
expect(metadata.properties.computed.prologSetter).toContain("setSingleTarget");
|
|
129
129
|
});
|
|
130
130
|
|
|
131
131
|
it("should handle collection with isInstance where clause", () => {
|
|
@@ -163,7 +163,7 @@ describe("Ad4mModel.getModelMetadata()", () => {
|
|
|
163
163
|
@Optional({ through: "recipe://description" })
|
|
164
164
|
description: string = "";
|
|
165
165
|
|
|
166
|
-
@ReadOnly({ through: "recipe://rating",
|
|
166
|
+
@ReadOnly({ through: "recipe://rating", prologGetter: "avg_rating(Base, Value)" })
|
|
167
167
|
rating: number = 0;
|
|
168
168
|
|
|
169
169
|
@Collection({ through: "recipe://ingredient" })
|
|
@@ -194,7 +194,7 @@ describe("Ad4mModel.getModelMetadata()", () => {
|
|
|
194
194
|
expect(metadata.properties.name.resolveLanguage).toBe("literal");
|
|
195
195
|
expect(metadata.properties.description.predicate).toBe("recipe://description");
|
|
196
196
|
expect(metadata.properties.rating.predicate).toBe("recipe://rating");
|
|
197
|
-
expect(metadata.properties.rating.
|
|
197
|
+
expect(metadata.properties.rating.prologGetter).toBe("avg_rating(Base, Value)");
|
|
198
198
|
expect(metadata.collections.ingredients.predicate).toBe("recipe://ingredient");
|
|
199
199
|
expect(metadata.collections.steps.predicate).toBe("recipe://step");
|
|
200
200
|
expect(metadata.collections.steps.local).toBe(true);
|
package/src/model/Ad4mModel.ts
CHANGED
|
@@ -90,11 +90,11 @@ export interface PropertyMetadata {
|
|
|
90
90
|
/** Language for resolution (e.g., "literal") */
|
|
91
91
|
resolveLanguage?: string;
|
|
92
92
|
/** Custom Prolog getter code */
|
|
93
|
-
|
|
93
|
+
prologGetter?: string;
|
|
94
94
|
/** Custom Prolog setter code */
|
|
95
|
-
|
|
95
|
+
prologSetter?: string;
|
|
96
96
|
/** Custom SurrealQL getter code */
|
|
97
|
-
|
|
97
|
+
getter?: string;
|
|
98
98
|
/** Whether stored locally only */
|
|
99
99
|
local?: boolean;
|
|
100
100
|
/** Transform function */
|
|
@@ -112,9 +112,9 @@ export interface CollectionMetadata {
|
|
|
112
112
|
/** The predicate URI (through value) */
|
|
113
113
|
predicate: string;
|
|
114
114
|
/** Filter conditions */
|
|
115
|
-
where?: { isInstance?: any; condition?: string };
|
|
115
|
+
where?: { isInstance?: any; prologCondition?: string; condition?: string };
|
|
116
116
|
/** Custom SurrealQL getter code */
|
|
117
|
-
|
|
117
|
+
getter?: string;
|
|
118
118
|
/** Whether stored locally only */
|
|
119
119
|
local?: boolean;
|
|
120
120
|
}
|
|
@@ -515,9 +515,9 @@ export class Ad4mModel {
|
|
|
515
515
|
writable: options.writable || false,
|
|
516
516
|
...(options.initial !== undefined && { initial: options.initial }),
|
|
517
517
|
...(options.resolveLanguage !== undefined && { resolveLanguage: options.resolveLanguage }),
|
|
518
|
+
...(options.prologGetter !== undefined && { prologGetter: options.prologGetter }),
|
|
518
519
|
...(options.getter !== undefined && { getter: options.getter }),
|
|
519
|
-
...(options.
|
|
520
|
-
...(options.setter !== undefined && { setter: options.setter }),
|
|
520
|
+
...(options.prologSetter !== undefined && { prologSetter: options.prologSetter }),
|
|
521
521
|
...(options.local !== undefined && { local: options.local }),
|
|
522
522
|
...(options.transform !== undefined && { transform: options.transform }),
|
|
523
523
|
...(options.flag !== undefined && { flag: options.flag })
|
|
@@ -535,7 +535,7 @@ export class Ad4mModel {
|
|
|
535
535
|
predicate: options.through || "",
|
|
536
536
|
...(options.where !== undefined && { where: options.where }),
|
|
537
537
|
...(options.local !== undefined && { local: options.local }),
|
|
538
|
-
...(options.
|
|
538
|
+
...(options.getter !== undefined && { getter: options.getter })
|
|
539
539
|
};
|
|
540
540
|
}
|
|
541
541
|
|
|
@@ -659,10 +659,10 @@ export class Ad4mModel {
|
|
|
659
659
|
throw new Error(`Property "${key}" is read-only and cannot be written`);
|
|
660
660
|
}
|
|
661
661
|
|
|
662
|
-
if (metadata.
|
|
663
|
-
// Custom setter - throw error for now (Phase 2)
|
|
662
|
+
if (metadata.prologSetter) {
|
|
663
|
+
// Custom Prolog setter - throw error for now (Phase 2)
|
|
664
664
|
throw new Error(
|
|
665
|
-
`Custom setter for property "${key}" not yet supported without Prolog. ` +
|
|
665
|
+
`Custom Prolog setter for property "${key}" not yet supported without Prolog. ` +
|
|
666
666
|
`Use standard @Property decorator or enable Prolog for custom setters.`
|
|
667
667
|
);
|
|
668
668
|
}
|
|
@@ -808,9 +808,9 @@ export class Ad4mModel {
|
|
|
808
808
|
let latestAuthor = null;
|
|
809
809
|
let originalAuthor = null;
|
|
810
810
|
|
|
811
|
-
// Process properties (skip those with
|
|
811
|
+
// Process properties (skip those with custom getter)
|
|
812
812
|
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
813
|
-
if (propMeta.
|
|
813
|
+
if (propMeta.getter) continue; // Handle via custom getter evaluation
|
|
814
814
|
const matching = links.filter((l: any) => l.predicate === propMeta.predicate);
|
|
815
815
|
if (matching.length > 0) {
|
|
816
816
|
// "Latest wins" semantics: select the last element since links are ordered ASC.
|
|
@@ -863,14 +863,49 @@ export class Ad4mModel {
|
|
|
863
863
|
}
|
|
864
864
|
}
|
|
865
865
|
|
|
866
|
-
// Process collections (skip those with
|
|
866
|
+
// Process collections (skip those with custom getter)
|
|
867
867
|
for (const [collName, collMeta] of Object.entries(metadata.collections)) {
|
|
868
|
-
if (collMeta.
|
|
868
|
+
if (collMeta.getter) continue; // Handle via custom getter evaluation
|
|
869
869
|
const matching = links.filter((l: any) => l.predicate === collMeta.predicate);
|
|
870
870
|
// Collections preserve chronological order: links are sorted ASC by timestamp,
|
|
871
871
|
// so the collection reflects the order in which items were added (oldest to newest).
|
|
872
872
|
let values = matching.map((l: any) => l.target);
|
|
873
873
|
|
|
874
|
+
// Apply where.condition filtering if present
|
|
875
|
+
if (collMeta.where?.condition && values.length > 0) {
|
|
876
|
+
try {
|
|
877
|
+
// Filter values by evaluating condition for each value
|
|
878
|
+
const filteredValues: string[] = [];
|
|
879
|
+
|
|
880
|
+
for (const value of values) {
|
|
881
|
+
let condition = collMeta.where.condition
|
|
882
|
+
.replace(/\$perspective/g, `'${this.#perspective.uuid}'`)
|
|
883
|
+
.replace(/\$base/g, `'${this.#baseExpression}'`)
|
|
884
|
+
.replace(/Target/g, `'${value.replace(/'/g, "\\'")}'`);
|
|
885
|
+
|
|
886
|
+
// If condition starts with WHERE, wrap it in array length check pattern
|
|
887
|
+
// Using array::len() to properly count matching links
|
|
888
|
+
if (condition.trim().startsWith('WHERE')) {
|
|
889
|
+
condition = `array::len(SELECT * FROM link ${condition}) > 0`;
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
const filterQuery = `RETURN ${condition}`;
|
|
893
|
+
const result = await this.#perspective.querySurrealDB(filterQuery);
|
|
894
|
+
|
|
895
|
+
// RETURN can return the value directly or in an array
|
|
896
|
+
const isTrue = result === true || (Array.isArray(result) && result.length > 0 && result[0] === true);
|
|
897
|
+
if (isTrue) {
|
|
898
|
+
filteredValues.push(value);
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
values = filteredValues;
|
|
903
|
+
} catch (error) {
|
|
904
|
+
console.warn(`Failed to apply condition filter for ${collName}:`, error);
|
|
905
|
+
// Keep unfiltered values on error
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
|
|
874
909
|
// Apply where.isInstance filtering if present
|
|
875
910
|
if (collMeta.where?.isInstance && values.length > 0) {
|
|
876
911
|
try {
|
|
@@ -903,12 +938,12 @@ export class Ad4mModel {
|
|
|
903
938
|
}
|
|
904
939
|
|
|
905
940
|
// Evaluate SurrealQL getters
|
|
906
|
-
await ctor.
|
|
941
|
+
await ctor.evaluateCustomGettersForInstance(this, this.#perspective, metadata);
|
|
907
942
|
|
|
908
|
-
// Apply where.isInstance filtering to
|
|
909
|
-
// (non-
|
|
943
|
+
// Apply where.isInstance filtering to getter collections
|
|
944
|
+
// (non-getter collections were already filtered above)
|
|
910
945
|
for (const [collName, collMeta] of Object.entries(metadata.collections)) {
|
|
911
|
-
if (collMeta.
|
|
946
|
+
if (collMeta.getter && collMeta.where?.isInstance && (this as any)[collName]?.length > 0) {
|
|
912
947
|
try {
|
|
913
948
|
const className = typeof collMeta.where.isInstance === 'string'
|
|
914
949
|
? collMeta.where.isInstance
|
|
@@ -962,19 +997,19 @@ export class Ad4mModel {
|
|
|
962
997
|
* Evaluates custom SurrealQL getters for properties and collections on a specific instance.
|
|
963
998
|
* @private
|
|
964
999
|
*/
|
|
965
|
-
private static async
|
|
1000
|
+
private static async evaluateCustomGettersForInstance(
|
|
966
1001
|
instance: any,
|
|
967
1002
|
perspective: PerspectiveProxy,
|
|
968
1003
|
metadata: any
|
|
969
1004
|
) {
|
|
970
1005
|
const safeBaseExpression = this.formatSurrealValue(instance.baseExpression);
|
|
971
1006
|
|
|
972
|
-
// Evaluate property
|
|
1007
|
+
// Evaluate property getters
|
|
973
1008
|
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
974
|
-
if ((propMeta as any).
|
|
1009
|
+
if ((propMeta as any).getter) {
|
|
975
1010
|
try {
|
|
976
1011
|
// Replace 'Base' placeholder with actual base expression
|
|
977
|
-
const query = (propMeta as any).
|
|
1012
|
+
const query = (propMeta as any).getter.replace(/Base/g, safeBaseExpression);
|
|
978
1013
|
// Query from node table to have graph traversal context
|
|
979
1014
|
const result = await perspective.querySurrealDB(
|
|
980
1015
|
`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`
|
|
@@ -983,17 +1018,17 @@ export class Ad4mModel {
|
|
|
983
1018
|
instance[propName] = result[0].value;
|
|
984
1019
|
}
|
|
985
1020
|
} catch (error) {
|
|
986
|
-
console.warn(`Failed to evaluate
|
|
1021
|
+
console.warn(`Failed to evaluate getter for ${propName}:`, error);
|
|
987
1022
|
}
|
|
988
1023
|
}
|
|
989
1024
|
}
|
|
990
1025
|
|
|
991
|
-
// Evaluate collection
|
|
1026
|
+
// Evaluate collection getters
|
|
992
1027
|
for (const [collName, collMeta] of Object.entries(metadata.collections)) {
|
|
993
|
-
if ((collMeta as any).
|
|
1028
|
+
if ((collMeta as any).getter) {
|
|
994
1029
|
try {
|
|
995
1030
|
// Replace 'Base' placeholder with actual base expression
|
|
996
|
-
const query = (collMeta as any).
|
|
1031
|
+
const query = (collMeta as any).getter.replace(/Base/g, safeBaseExpression);
|
|
997
1032
|
// Query from node table to have graph traversal context
|
|
998
1033
|
const result = await perspective.querySurrealDB(
|
|
999
1034
|
`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`
|
|
@@ -1006,7 +1041,7 @@ export class Ad4mModel {
|
|
|
1006
1041
|
: value;
|
|
1007
1042
|
}
|
|
1008
1043
|
} catch (error) {
|
|
1009
|
-
console.warn(`Failed to evaluate
|
|
1044
|
+
console.warn(`Failed to evaluate getter for ${collName}:`, error);
|
|
1010
1045
|
}
|
|
1011
1046
|
}
|
|
1012
1047
|
}
|
|
@@ -1622,10 +1657,10 @@ WHERE ${whereConditions.join(' AND ')}
|
|
|
1622
1657
|
}
|
|
1623
1658
|
}
|
|
1624
1659
|
|
|
1625
|
-
// Find matching property (skip those with
|
|
1660
|
+
// Find matching property (skip those with getter)
|
|
1626
1661
|
let foundProperty = false;
|
|
1627
1662
|
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
1628
|
-
if (propMeta.
|
|
1663
|
+
if (propMeta.getter) continue; // Handle via getter evaluation
|
|
1629
1664
|
if (propMeta.predicate === predicate) {
|
|
1630
1665
|
// For properties, take the first value (or we could use timestamp to get latest)
|
|
1631
1666
|
// Note: Empty objects {} are truthy, so we need to check for them explicitly
|
|
@@ -1692,10 +1727,10 @@ WHERE ${whereConditions.join(' AND ')}
|
|
|
1692
1727
|
}
|
|
1693
1728
|
}
|
|
1694
1729
|
|
|
1695
|
-
// If not a property, check if it's a collection (skip those with
|
|
1730
|
+
// If not a property, check if it's a collection (skip those with getter)
|
|
1696
1731
|
if (!foundProperty) {
|
|
1697
1732
|
for (const [collName, collMeta] of Object.entries(metadata.collections)) {
|
|
1698
|
-
if (collMeta.
|
|
1733
|
+
if (collMeta.getter) continue; // Handle via getter evaluation
|
|
1699
1734
|
if (collMeta.predicate === predicate) {
|
|
1700
1735
|
// For collections, accumulate all values with their timestamps and indices for sorting
|
|
1701
1736
|
if (!instance[collName]) {
|
|
@@ -1799,10 +1834,10 @@ WHERE ${whereConditions.join(' AND ')}
|
|
|
1799
1834
|
}
|
|
1800
1835
|
}
|
|
1801
1836
|
|
|
1802
|
-
// Evaluate
|
|
1837
|
+
// Evaluate custom getters for all instances (single pass)
|
|
1803
1838
|
// This populates collection values needed for where.isInstance filtering
|
|
1804
1839
|
for (const instance of instances) {
|
|
1805
|
-
await this.
|
|
1840
|
+
await this.evaluateCustomGettersForInstance(instance, perspective, metadata);
|
|
1806
1841
|
}
|
|
1807
1842
|
|
|
1808
1843
|
// Filter collections by where.isInstance if specified
|
package/src/model/decorators.ts
CHANGED
|
@@ -29,9 +29,9 @@ export interface InstanceQueryParams {
|
|
|
29
29
|
where?: object;
|
|
30
30
|
|
|
31
31
|
/**
|
|
32
|
-
* A string representing the condition clause of the query.
|
|
32
|
+
* A string representing the Prolog condition clause of the query.
|
|
33
33
|
*/
|
|
34
|
-
|
|
34
|
+
prologCondition?: string;
|
|
35
35
|
}
|
|
36
36
|
|
|
37
37
|
/**
|
|
@@ -65,14 +65,14 @@ condition?: string;
|
|
|
65
65
|
* static async findByName(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
|
|
66
66
|
*
|
|
67
67
|
* // Get highly rated recipes using a custom condition
|
|
68
|
-
* @InstanceQuery({
|
|
68
|
+
* @InstanceQuery({ prologCondition: "triple(Instance, 'recipe://rating', Rating), Rating > 4" })
|
|
69
69
|
* static async topRated(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
|
|
70
70
|
* }
|
|
71
71
|
* ```
|
|
72
72
|
*
|
|
73
73
|
* @param {Object} [options] - Query options
|
|
74
74
|
* @param {object} [options.where] - Object with property-value pairs to match
|
|
75
|
-
* @param {string} [options.
|
|
75
|
+
* @param {string} [options.prologCondition] - Custom Prolog condition for more complex queries
|
|
76
76
|
*/
|
|
77
77
|
export function InstanceQuery(options?: InstanceQueryParams) {
|
|
78
78
|
return function <T>(target: T, key: keyof T, descriptor: PropertyDescriptor) {
|
|
@@ -93,8 +93,8 @@ export function InstanceQuery(options?: InstanceQueryParams) {
|
|
|
93
93
|
}
|
|
94
94
|
}
|
|
95
95
|
|
|
96
|
-
if(options && options.
|
|
97
|
-
query += ', ' + options.
|
|
96
|
+
if(options && options.prologCondition) {
|
|
97
|
+
query += ', ' + options.prologCondition
|
|
98
98
|
}
|
|
99
99
|
|
|
100
100
|
// Try Prolog first
|
|
@@ -171,21 +171,21 @@ export interface PropertyOptions {
|
|
|
171
171
|
resolveLanguage?: string;
|
|
172
172
|
|
|
173
173
|
/**
|
|
174
|
-
* Custom getter to get the value of the property
|
|
174
|
+
* Custom Prolog getter to get the value of the property. If not provided, the default getter will be used.
|
|
175
175
|
*/
|
|
176
|
-
|
|
176
|
+
prologGetter?: string;
|
|
177
177
|
|
|
178
178
|
/**
|
|
179
|
-
* Custom setter to set the value of the property
|
|
179
|
+
* Custom Prolog setter to set the value of the property. Only available if the property is writable.
|
|
180
180
|
*/
|
|
181
|
-
|
|
181
|
+
prologSetter?: string;
|
|
182
182
|
|
|
183
183
|
/**
|
|
184
184
|
* Custom SurrealQL getter to resolve the property value. Use this for custom graph traversals.
|
|
185
185
|
* The expression can reference 'Base' which will be replaced with the instance's base expression.
|
|
186
186
|
* Example: "(<-link[WHERE predicate = 'flux://has_reply'].in.uri)[0]"
|
|
187
187
|
*/
|
|
188
|
-
|
|
188
|
+
getter?: string;
|
|
189
189
|
|
|
190
190
|
/**
|
|
191
191
|
* Indicates whether the property is stored locally in the perspective and not in the network. Useful for properties that are not meant to be shared with the network.
|
|
@@ -276,8 +276,8 @@ export interface PropertyOptions {
|
|
|
276
276
|
* @param {boolean} [opts.required] - Whether the property must have a value
|
|
277
277
|
* @param {boolean} [opts.writable=true] - Whether the property can be modified
|
|
278
278
|
* @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
|
|
279
|
-
* @param {string} [opts.
|
|
280
|
-
* @param {string} [opts.
|
|
279
|
+
* @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
|
|
280
|
+
* @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
|
|
281
281
|
* @param {boolean} [opts.local] - Whether the property should only be stored locally
|
|
282
282
|
*/
|
|
283
283
|
export function Optional(opts: PropertyOptions) {
|
|
@@ -290,8 +290,8 @@ export function Optional(opts: PropertyOptions) {
|
|
|
290
290
|
throw new Error("SubjectProperty requires an 'initial' option if 'required' is true");
|
|
291
291
|
}
|
|
292
292
|
|
|
293
|
-
if (!opts.through && !opts.
|
|
294
|
-
throw new Error("SubjectProperty requires either 'through' or '
|
|
293
|
+
if (!opts.through && !opts.prologGetter) {
|
|
294
|
+
throw new Error("SubjectProperty requires either 'through' or 'prologGetter' option")
|
|
295
295
|
}
|
|
296
296
|
|
|
297
297
|
target["__properties"] = target["__properties"] || {};
|
|
@@ -405,6 +405,7 @@ export function Flag(opts: FlagOptions) {
|
|
|
405
405
|
|
|
406
406
|
interface WhereOptions {
|
|
407
407
|
isInstance?: any
|
|
408
|
+
prologCondition?: string
|
|
408
409
|
condition?: string
|
|
409
410
|
}
|
|
410
411
|
|
|
@@ -424,7 +425,7 @@ export interface CollectionOptions {
|
|
|
424
425
|
* The expression can reference 'Base' which will be replaced with the instance's base expression.
|
|
425
426
|
* Example: "(<-link[WHERE predicate = 'flux://has_reply'].in.uri)"
|
|
426
427
|
*/
|
|
427
|
-
|
|
428
|
+
getter?: string;
|
|
428
429
|
|
|
429
430
|
/**
|
|
430
431
|
* Indicates whether the property is stored locally in the perspective and not in the network. Useful for properties that are not meant to be shared with the network.
|
|
@@ -468,13 +469,20 @@ export interface CollectionOptions {
|
|
|
468
469
|
* })
|
|
469
470
|
* comments: string[] = [];
|
|
470
471
|
*
|
|
471
|
-
* // Collection with custom filter condition
|
|
472
|
+
* // Collection with custom Prolog filter condition
|
|
472
473
|
* @Collection({
|
|
473
474
|
* through: "recipe://step",
|
|
474
|
-
* where: {
|
|
475
|
+
* where: { prologCondition: `triple(Target, "step://order", Order), Order < 3` }
|
|
475
476
|
* })
|
|
476
477
|
* firstSteps: string[] = [];
|
|
477
478
|
*
|
|
479
|
+
* // Collection with custom SurrealDB filter condition
|
|
480
|
+
* @Collection({
|
|
481
|
+
* through: "recipe://entries",
|
|
482
|
+
* where: { condition: `WHERE in.uri = Target AND predicate = 'recipe://has_ingredient' AND out.uri = 'recipe://test')`
|
|
483
|
+
* })
|
|
484
|
+
* ingredients: string[] = [];
|
|
485
|
+
*
|
|
478
486
|
* // Local-only collection not shared with network
|
|
479
487
|
* @Collection({
|
|
480
488
|
* through: "recipe://note",
|
|
@@ -494,7 +502,7 @@ export interface CollectionOptions {
|
|
|
494
502
|
* @param {string} opts.through - The predicate URI for collection links
|
|
495
503
|
* @param {WhereOptions} [opts.where] - Filter conditions for collection values
|
|
496
504
|
* @param {any} [opts.where.isInstance] - Model class to filter instances by
|
|
497
|
-
* @param {string} [opts.where.
|
|
505
|
+
* @param {string} [opts.where.prologCondition] - Custom Prolog condition for filtering
|
|
498
506
|
* @param {boolean} [opts.local] - Whether collection links are stored locally only
|
|
499
507
|
*/
|
|
500
508
|
export function Collection(opts: CollectionOptions) {
|
|
@@ -614,15 +622,15 @@ export function ModelOptions(opts: ModelOptionsOptions) {
|
|
|
614
622
|
for(let property in properties) {
|
|
615
623
|
let propertyCode = `property(${uuid}, "${property}").\n`
|
|
616
624
|
|
|
617
|
-
let { through, initial, required, resolveLanguage, writable, flag,
|
|
625
|
+
let { through, initial, required, resolveLanguage, writable, flag, prologGetter, prologSetter, local } = properties[property]
|
|
618
626
|
|
|
619
627
|
if(resolveLanguage) {
|
|
620
628
|
propertyCode += `property_resolve(${uuid}, "${property}").\n`
|
|
621
629
|
propertyCode += `property_resolve_language(${uuid}, "${property}", "${resolveLanguage}").\n`
|
|
622
630
|
}
|
|
623
631
|
|
|
624
|
-
if(
|
|
625
|
-
propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- ${
|
|
632
|
+
if(prologGetter) {
|
|
633
|
+
propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- ${prologGetter}.\n`
|
|
626
634
|
} else if(through) {
|
|
627
635
|
propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- triple(Base, "${through}", Value).\n`
|
|
628
636
|
|
|
@@ -635,8 +643,8 @@ export function ModelOptions(opts: ModelOptionsOptions) {
|
|
|
635
643
|
}
|
|
636
644
|
}
|
|
637
645
|
|
|
638
|
-
if(
|
|
639
|
-
propertyCode += `property_setter(${uuid}, "${property}", Actions) :- ${
|
|
646
|
+
if(prologSetter) {
|
|
647
|
+
propertyCode += `property_setter(${uuid}, "${property}", Actions) :- ${prologSetter}.\n`
|
|
640
648
|
} else if (writable && through) {
|
|
641
649
|
let setter = obj[propertyNameToSetterName(property)]
|
|
642
650
|
if(typeof setter === "function") {
|
|
@@ -679,8 +687,8 @@ export function ModelOptions(opts: ModelOptionsOptions) {
|
|
|
679
687
|
|
|
680
688
|
if(through) {
|
|
681
689
|
if(where) {
|
|
682
|
-
if(!where.isInstance && !where.condition) {
|
|
683
|
-
throw "'where' needs one of 'isInstance' or 'condition'"
|
|
690
|
+
if(!where.isInstance && !where.prologCondition && !where.condition) {
|
|
691
|
+
throw "'where' needs one of 'isInstance', 'prologCondition', or 'condition'"
|
|
684
692
|
}
|
|
685
693
|
|
|
686
694
|
let conditions = []
|
|
@@ -695,13 +703,19 @@ export function ModelOptions(opts: ModelOptionsOptions) {
|
|
|
695
703
|
conditions.push(`instance(OtherClass, Target), subject_class("${otherClass}", OtherClass)`)
|
|
696
704
|
}
|
|
697
705
|
|
|
698
|
-
if(where.
|
|
699
|
-
conditions.push(where.
|
|
706
|
+
if(where.prologCondition) {
|
|
707
|
+
conditions.push(where.prologCondition)
|
|
700
708
|
}
|
|
701
709
|
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
710
|
+
// If there are Prolog conditions (isInstance or prologCondition), use setof with conditions
|
|
711
|
+
// If only condition is present, use simple findall (SurrealDB will filter later)
|
|
712
|
+
if(conditions.length > 0) {
|
|
713
|
+
const conditionString = conditions.join(", ")
|
|
714
|
+
collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- setof(Target, (triple(Base, "${through}", Target), ${conditionString}), List).\n`
|
|
715
|
+
} else {
|
|
716
|
+
// Only SurrealDB condition present (no Prolog filtering)
|
|
717
|
+
collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- findall(C, triple(Base, "${through}", C), List).\n`
|
|
718
|
+
}
|
|
705
719
|
} else {
|
|
706
720
|
collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- findall(C, triple(Base, "${through}", C), List).\n`
|
|
707
721
|
}
|
|
@@ -810,8 +824,8 @@ export function ModelOptions(opts: ModelOptionsOptions) {
|
|
|
810
824
|
* @param {string} opts.through - The predicate URI for the property
|
|
811
825
|
* @param {string} [opts.initial] - Initial value (defaults to "literal://string:uninitialized")
|
|
812
826
|
* @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
|
|
813
|
-
* @param {string} [opts.
|
|
814
|
-
* @param {string} [opts.
|
|
827
|
+
* @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
|
|
828
|
+
* @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
|
|
815
829
|
* @param {boolean} [opts.local] - Whether the property should only be stored locally
|
|
816
830
|
*/
|
|
817
831
|
export function Property(opts: PropertyOptions) {
|
|
@@ -875,7 +889,7 @@ export function Property(opts: PropertyOptions) {
|
|
|
875
889
|
* @param {string} opts.through - The predicate URI for the property
|
|
876
890
|
* @param {string} [opts.initial] - Initial value (if property should have one)
|
|
877
891
|
* @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
|
|
878
|
-
* @param {string} [opts.
|
|
892
|
+
* @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
|
|
879
893
|
* @param {boolean} [opts.local] - Whether the property should only be stored locally
|
|
880
894
|
*/
|
|
881
895
|
export function ReadOnly(opts: PropertyOptions) {
|