@coasys/ad4m 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1476 @@
1
+ import { Ad4mModel } from "./Ad4mModel";
2
+ import { ModelOptions, Property, Optional, ReadOnly, Collection, Flag } from "./decorators";
3
+
4
+ describe("Ad4mModel.getModelMetadata()", () => {
5
+ it("should extract basic model metadata with className", () => {
6
+ @ModelOptions({ name: "SimpleModel" })
7
+ class SimpleModel extends Ad4mModel {}
8
+
9
+ const metadata = SimpleModel.getModelMetadata();
10
+
11
+ expect(metadata.className).toBe("SimpleModel");
12
+ expect(metadata.properties).toEqual({});
13
+ expect(metadata.collections).toEqual({});
14
+ });
15
+
16
+ it("should extract property metadata with all fields", () => {
17
+ @ModelOptions({ name: "PropertyModel" })
18
+ class PropertyModel extends Ad4mModel {
19
+ @Property({ through: "test://name", resolveLanguage: "literal" })
20
+ name: string = "";
21
+
22
+ @Optional({ through: "test://optional", writable: true })
23
+ optional: string = "";
24
+
25
+ @ReadOnly({ through: "test://readonly", getter: "custom_getter" })
26
+ readonly: string = "";
27
+
28
+ @Flag({ through: "test://type", value: "test://flag" })
29
+ type: string = "";
30
+ }
31
+
32
+ const metadata = PropertyModel.getModelMetadata();
33
+
34
+ // Should have 4 properties
35
+ expect(Object.keys(metadata.properties)).toHaveLength(4);
36
+
37
+ // Verify "name" property
38
+ expect(metadata.properties.name.predicate).toBe("test://name");
39
+ expect(metadata.properties.name.required).toBe(true);
40
+ expect(metadata.properties.name.writable).toBe(true);
41
+ expect(metadata.properties.name.resolveLanguage).toBe("literal");
42
+
43
+ // Verify "optional" property
44
+ expect(metadata.properties.optional.predicate).toBe("test://optional");
45
+ expect(metadata.properties.optional.writable).toBe(true);
46
+
47
+ // Verify "readonly" property
48
+ expect(metadata.properties.readonly.predicate).toBe("test://readonly");
49
+ expect(metadata.properties.readonly.writable).toBe(false);
50
+ expect(metadata.properties.readonly.getter).toBe("custom_getter");
51
+
52
+ // Verify "type" property (flag)
53
+ expect(metadata.properties.type.predicate).toBe("test://type");
54
+ expect(metadata.properties.type.flag).toBe(true);
55
+ expect(metadata.properties.type.initial).toBe("test://flag");
56
+ });
57
+
58
+ it("should extract collection metadata with where clauses", () => {
59
+ @ModelOptions({ name: "CollectionModel" })
60
+ class CollectionModel extends Ad4mModel {
61
+ @Collection({ through: "test://items" })
62
+ items: string[] = [];
63
+
64
+ @Collection({
65
+ through: "test://filtered",
66
+ where: { condition: "triple(Target, 'test://active', 'true')" }
67
+ })
68
+ filtered: string[] = [];
69
+
70
+ @Collection({ through: "test://local", local: true })
71
+ local: string[] = [];
72
+ }
73
+
74
+ const metadata = CollectionModel.getModelMetadata();
75
+
76
+ // Should have 3 collections
77
+ expect(Object.keys(metadata.collections)).toHaveLength(3);
78
+
79
+ // Verify "items" collection
80
+ expect(metadata.collections.items.predicate).toBe("test://items");
81
+ expect(metadata.collections.items.where).toBeUndefined();
82
+
83
+ // Verify "filtered" collection
84
+ expect(metadata.collections.filtered.predicate).toBe("test://filtered");
85
+ expect(metadata.collections.filtered.where?.condition).toBe("triple(Target, 'test://active', 'true')");
86
+
87
+ // Verify "local" collection
88
+ expect(metadata.collections.local.predicate).toBe("test://local");
89
+ expect(metadata.collections.local.local).toBe(true);
90
+ });
91
+
92
+ it("should extract transform function from property metadata", () => {
93
+ @ModelOptions({ name: "TransformModel" })
94
+ class TransformModel extends Ad4mModel {
95
+ @Optional({
96
+ through: "test://data",
97
+ transform: (value: string) => value.toUpperCase()
98
+ })
99
+ data: string = "";
100
+ }
101
+
102
+ const metadata = TransformModel.getModelMetadata();
103
+
104
+ // Assert transform is a function
105
+ expect(typeof metadata.properties.data.transform).toBe("function");
106
+
107
+ // Test the transform function
108
+ const transformed = metadata.properties.data.transform!("test");
109
+ expect(transformed).toBe("TEST");
110
+ });
111
+
112
+ it("should extract custom getter and setter from property metadata", () => {
113
+ @ModelOptions({ name: "CustomModel" })
114
+ class CustomModel extends Ad4mModel {
115
+ @Optional({
116
+ through: "test://computed",
117
+ getter: "triple(Base, 'test://value', V), Value is V * 2",
118
+ setter: "Value is V / 2, Actions = [{action: 'setSingleTarget', source: 'this', predicate: 'test://value', target: Value}]"
119
+ })
120
+ computed: number = 0;
121
+ }
122
+
123
+ const metadata = CustomModel.getModelMetadata();
124
+
125
+ // Assert getter and setter contain the custom code
126
+ expect(metadata.properties.computed.getter).toContain("triple(Base, 'test://value', V), Value is V * 2");
127
+ expect(metadata.properties.computed.setter).toContain("Value is V / 2");
128
+ expect(metadata.properties.computed.setter).toContain("setSingleTarget");
129
+ });
130
+
131
+ it("should handle collection with isInstance where clause", () => {
132
+ @ModelOptions({ name: "Comment" })
133
+ class Comment extends Ad4mModel {}
134
+
135
+ @ModelOptions({ name: "Post" })
136
+ class Post extends Ad4mModel {
137
+ @Collection({
138
+ through: "post://comment",
139
+ where: { isInstance: Comment }
140
+ })
141
+ comments: string[] = [];
142
+ }
143
+
144
+ const metadata = Post.getModelMetadata();
145
+
146
+ // Assert isInstance is defined
147
+ expect(metadata.collections.comments.where?.isInstance).toBeDefined();
148
+ });
149
+
150
+ it("should throw error for class without @ModelOptions decorator", () => {
151
+ class NoDecoratorModel extends Ad4mModel {}
152
+
153
+ // Assert that calling getModelMetadata throws an error
154
+ expect(() => NoDecoratorModel.getModelMetadata()).toThrow("Model class must be decorated with @ModelOptions");
155
+ });
156
+
157
+ it("should handle complex model with mixed property and collection types", () => {
158
+ @ModelOptions({ name: "Recipe" })
159
+ class Recipe extends Ad4mModel {
160
+ @Property({ through: "recipe://name", resolveLanguage: "literal" })
161
+ name: string = "";
162
+
163
+ @Optional({ through: "recipe://description" })
164
+ description: string = "";
165
+
166
+ @ReadOnly({ through: "recipe://rating", getter: "avg_rating(Base, Value)" })
167
+ rating: number = 0;
168
+
169
+ @Collection({ through: "recipe://ingredient" })
170
+ ingredients: string[] = [];
171
+
172
+ @Collection({ through: "recipe://step", local: true })
173
+ steps: string[] = [];
174
+ }
175
+
176
+ const metadata = Recipe.getModelMetadata();
177
+
178
+ // Assert className
179
+ expect(metadata.className).toBe("Recipe");
180
+
181
+ // Assert properties has 3 entries
182
+ expect(Object.keys(metadata.properties)).toHaveLength(3);
183
+ expect(metadata.properties.name).toBeDefined();
184
+ expect(metadata.properties.description).toBeDefined();
185
+ expect(metadata.properties.rating).toBeDefined();
186
+
187
+ // Assert collections has 2 entries
188
+ expect(Object.keys(metadata.collections)).toHaveLength(2);
189
+ expect(metadata.collections.ingredients).toBeDefined();
190
+ expect(metadata.collections.steps).toBeDefined();
191
+
192
+ // Verify all metadata fields are correctly extracted
193
+ expect(metadata.properties.name.predicate).toBe("recipe://name");
194
+ expect(metadata.properties.name.resolveLanguage).toBe("literal");
195
+ expect(metadata.properties.description.predicate).toBe("recipe://description");
196
+ expect(metadata.properties.rating.predicate).toBe("recipe://rating");
197
+ expect(metadata.properties.rating.getter).toBe("avg_rating(Base, Value)");
198
+ expect(metadata.collections.ingredients.predicate).toBe("recipe://ingredient");
199
+ expect(metadata.collections.steps.predicate).toBe("recipe://step");
200
+ expect(metadata.collections.steps.local).toBe(true);
201
+ });
202
+ });
203
+
204
+ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
205
+ it("should extract metadata from a model created via fromJSONSchema with basic properties", () => {
206
+ const schema = {
207
+ title: "Product",
208
+ type: "object",
209
+ properties: {
210
+ name: { type: "string" },
211
+ price: { type: "number" },
212
+ description: { type: "string" }
213
+ },
214
+ required: ["name", "price"]
215
+ };
216
+
217
+ const ProductClass = Ad4mModel.fromJSONSchema(schema, {
218
+ name: "Product",
219
+ namespace: "product://",
220
+ resolveLanguage: "literal"
221
+ });
222
+
223
+ const metadata = ProductClass.getModelMetadata();
224
+
225
+ // Verify className
226
+ expect(metadata.className).toBe("Product");
227
+
228
+ // Verify properties are extracted
229
+ expect(Object.keys(metadata.properties).length).toBeGreaterThan(0);
230
+ expect(metadata.properties.name).toBeDefined();
231
+ expect(metadata.properties.name.predicate).toBe("product://name");
232
+ expect(metadata.properties.name.required).toBe(true);
233
+ expect(metadata.properties.name.writable).toBe(true);
234
+ expect(metadata.properties.name.resolveLanguage).toBe("literal");
235
+
236
+ expect(metadata.properties.price).toBeDefined();
237
+ expect(metadata.properties.price.predicate).toBe("product://price");
238
+ expect(metadata.properties.price.required).toBe(true);
239
+ expect(metadata.properties.price.resolveLanguage).toBe("literal");
240
+
241
+ expect(metadata.properties.description).toBeDefined();
242
+ expect(metadata.properties.description.predicate).toBe("product://description");
243
+ expect(metadata.properties.description.required).toBe(false);
244
+ });
245
+
246
+ it("should extract collections from a model created via fromJSONSchema with arrays", () => {
247
+ const schema = {
248
+ title: "Post",
249
+ type: "object",
250
+ properties: {
251
+ title: { type: "string" },
252
+ tags: {
253
+ type: "array",
254
+ items: { type: "string" }
255
+ },
256
+ comments: {
257
+ type: "array",
258
+ items: { type: "string" }
259
+ }
260
+ },
261
+ required: ["title"]
262
+ };
263
+
264
+ const PostClass = Ad4mModel.fromJSONSchema(schema, {
265
+ name: "Post",
266
+ namespace: "post://"
267
+ });
268
+
269
+ const metadata = PostClass.getModelMetadata();
270
+
271
+ // Verify className
272
+ expect(metadata.className).toBe("Post");
273
+
274
+ // Verify collections are extracted
275
+ expect(Object.keys(metadata.collections).length).toBeGreaterThan(0);
276
+ expect(metadata.collections.tags).toBeDefined();
277
+ expect(metadata.collections.tags.predicate).toBe("post://tags");
278
+
279
+ expect(metadata.collections.comments).toBeDefined();
280
+ expect(metadata.collections.comments.predicate).toBe("post://comments");
281
+
282
+ // Verify properties (should include at least title)
283
+ expect(metadata.properties.title).toBeDefined();
284
+ expect(metadata.properties.title.predicate).toBe("post://title");
285
+ expect(metadata.properties.title.required).toBe(true);
286
+ });
287
+
288
+ it("should handle x-ad4m metadata in JSON schema for property options", () => {
289
+ const schema = {
290
+ title: "Contact",
291
+ "x-ad4m": {
292
+ namespace: "contact://"
293
+ },
294
+ type: "object",
295
+ properties: {
296
+ name: {
297
+ type: "string",
298
+ "x-ad4m": {
299
+ through: "foaf://name",
300
+ resolveLanguage: "literal",
301
+ writable: true
302
+ }
303
+ },
304
+ email: {
305
+ type: "string",
306
+ "x-ad4m": {
307
+ through: "foaf://mbox",
308
+ local: true
309
+ }
310
+ }
311
+ },
312
+ required: ["name"]
313
+ };
314
+
315
+ const ContactClass = Ad4mModel.fromJSONSchema(schema, {
316
+ name: "Contact"
317
+ });
318
+
319
+ const metadata = ContactClass.getModelMetadata();
320
+
321
+ // Verify x-ad4m metadata is respected
322
+ expect(metadata.properties.name.predicate).toBe("foaf://name");
323
+ expect(metadata.properties.name.resolveLanguage).toBe("literal");
324
+ expect(metadata.properties.name.writable).toBe(true);
325
+ expect(metadata.properties.name.required).toBe(true);
326
+
327
+ expect(metadata.properties.email.predicate).toBe("foaf://mbox");
328
+ expect(metadata.properties.email.local).toBe(true);
329
+ });
330
+
331
+ it("should handle property mapping override in options", () => {
332
+ const schema = {
333
+ title: "User",
334
+ type: "object",
335
+ properties: {
336
+ username: { type: "string" },
337
+ fullName: { type: "string" }
338
+ },
339
+ required: ["username"]
340
+ };
341
+
342
+ const UserClass = Ad4mModel.fromJSONSchema(schema, {
343
+ name: "User",
344
+ namespace: "user://",
345
+ propertyMapping: {
346
+ username: "custom://identifier",
347
+ fullName: "custom://name"
348
+ }
349
+ });
350
+
351
+ const metadata = UserClass.getModelMetadata();
352
+
353
+ // Verify property mappings are applied
354
+ expect(metadata.properties.username.predicate).toBe("custom://identifier");
355
+ expect(metadata.properties.fullName.predicate).toBe("custom://name");
356
+ });
357
+
358
+ it("should extract metadata from dynamically generated models with mixed types", () => {
359
+ const schema = {
360
+ title: "Article",
361
+ type: "object",
362
+ properties: {
363
+ title: { type: "string" },
364
+ views: { type: "number" },
365
+ published: { type: "boolean" },
366
+ authors: {
367
+ type: "array",
368
+ items: { type: "string" }
369
+ },
370
+ tags: {
371
+ type: "array",
372
+ items: { type: "string" },
373
+ "x-ad4m": {
374
+ local: true
375
+ }
376
+ }
377
+ },
378
+ required: ["title", "published"]
379
+ };
380
+
381
+ const ArticleClass = Ad4mModel.fromJSONSchema(schema, {
382
+ name: "Article",
383
+ namespace: "article://",
384
+ resolveLanguage: "literal"
385
+ });
386
+
387
+ const metadata = ArticleClass.getModelMetadata();
388
+
389
+ // Verify className
390
+ expect(metadata.className).toBe("Article");
391
+
392
+ // Verify properties
393
+ expect(metadata.properties.title).toBeDefined();
394
+ expect(metadata.properties.title.predicate).toBe("article://title");
395
+ expect(metadata.properties.title.required).toBe(true);
396
+ expect(metadata.properties.title.resolveLanguage).toBe("literal");
397
+
398
+ expect(metadata.properties.views).toBeDefined();
399
+ expect(metadata.properties.views.predicate).toBe("article://views");
400
+ expect(metadata.properties.views.resolveLanguage).toBe("literal");
401
+
402
+ expect(metadata.properties.published).toBeDefined();
403
+ expect(metadata.properties.published.predicate).toBe("article://published");
404
+ expect(metadata.properties.published.required).toBe(true);
405
+
406
+ // Verify collections
407
+ expect(metadata.collections.authors).toBeDefined();
408
+ expect(metadata.collections.authors.predicate).toBe("article://authors");
409
+
410
+ expect(metadata.collections.tags).toBeDefined();
411
+ expect(metadata.collections.tags.predicate).toBe("article://tags");
412
+ expect(metadata.collections.tags.local).toBe(true);
413
+ });
414
+
415
+ it("should handle models with only an auto-generated type flag", () => {
416
+ const schema = {
417
+ title: "EmptyModel",
418
+ type: "object",
419
+ properties: {}
420
+ };
421
+
422
+ const EmptyModelClass = Ad4mModel.fromJSONSchema(schema, {
423
+ name: "EmptyModel",
424
+ namespace: "empty://"
425
+ });
426
+
427
+ const metadata = EmptyModelClass.getModelMetadata();
428
+
429
+ // Should have className
430
+ expect(metadata.className).toBe("EmptyModel");
431
+
432
+ // Should have the auto-generated __ad4m_type property
433
+ expect(metadata.properties.__ad4m_type).toBeDefined();
434
+ expect(metadata.properties.__ad4m_type.predicate).toBe("ad4m://type");
435
+ expect(metadata.properties.__ad4m_type.initial).toBe("empty://instance");
436
+ expect(metadata.properties.__ad4m_type.flag).toBe(true);
437
+ });
438
+ });
439
+
440
+ describe("Ad4mModel.queryToSurrealQL()", () => {
441
+ // Mock perspective proxy (minimal since queryToSurrealQL doesn't actually call it)
442
+ const mockPerspective = {} as any;
443
+
444
+ // Helper function to normalize whitespace in queries for easier comparison
445
+ function normalizeQuery(query: string): string {
446
+ return query.replace(/\s+/g, ' ').trim();
447
+ }
448
+
449
+ // Test Recipe model
450
+ @ModelOptions({ name: "Recipe" })
451
+ class Recipe extends Ad4mModel {
452
+ @Property({ through: "recipe://name" })
453
+ name: string = "";
454
+
455
+ @Property({ through: "recipe://rating" })
456
+ rating: number = 0;
457
+
458
+ @Collection({ through: "recipe://ingredient" })
459
+ ingredients: string[] = [];
460
+ }
461
+
462
+ it("should generate basic query with no filters", async () => {
463
+ const query = await Recipe.queryToSurrealQL(mockPerspective, {});
464
+
465
+ expect(query).toContain("id AS source");
466
+ expect(query).toContain("uri AS source_uri");
467
+ expect(query).toContain("FROM node");
468
+ expect(query).toContain("->link[WHERE perspective = $perspective] AS links");
469
+ expect(query).toContain("WHERE");
470
+ // Should have graph traversal filters for required properties
471
+ expect(query).toContain("count(->link[WHERE");
472
+ });
473
+
474
+ it("should generate query with simple property filter", async () => {
475
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: "Pasta" } });
476
+
477
+ // Should have graph traversal filters for required properties and user filter
478
+ expect(query).toContain("count(->link[WHERE perspective = $perspective AND predicate = 'recipe://name']) > 0");
479
+ expect(query).toContain("count(->link[WHERE perspective = $perspective AND predicate = 'recipe://rating']) > 0");
480
+ expect(query).toContain("count(->link[WHERE perspective = $perspective AND predicate = 'recipe://name' AND out.uri = 'Pasta']) > 0");
481
+ });
482
+
483
+ it("should generate query with multiple property filters", async () => {
484
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: "Pasta", rating: 5 } });
485
+
486
+ expect(query).toContain("WHERE");
487
+ expect(query).toContain("count(->link[WHERE perspective = $perspective AND predicate = 'recipe://name' AND out.uri = 'Pasta']) > 0");
488
+ expect(query).toContain("count(->link[WHERE perspective = $perspective AND predicate = 'recipe://rating' AND out.uri = 5]) > 0");
489
+ expect(query).toContain("AND");
490
+ });
491
+
492
+ it("should handle gt operator (filtered in JavaScript, not SQL)", async () => {
493
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { gt: 4 } } });
494
+
495
+ // Comparison operators for regular properties are now filtered in JavaScript post-query
496
+ // The SQL just filters on the predicate existing
497
+ expect(query).toContain("FROM node");
498
+
499
+ // Should NOT contain comparison operators in SQL for regular properties
500
+ expect(query).not.toContain("target > 4");
501
+ });
502
+
503
+ it("should handle lt operator (filtered in JavaScript, not SQL)", async () => {
504
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { lt: 3 } } });
505
+
506
+ // Comparison operators are filtered in JavaScript post-query
507
+ expect(query).toContain("FROM node");
508
+ expect(query).not.toContain("target < 3");
509
+ });
510
+
511
+ it("should handle gte and lte operators (filtered in JavaScript, not SQL)", async () => {
512
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { gte: 3, lte: 5 } } });
513
+
514
+ // Comparison operators are filtered in JavaScript post-query
515
+ expect(query).toContain("FROM node");
516
+ expect(query).not.toContain("target >= 3");
517
+ expect(query).not.toContain("target <= 5");
518
+ });
519
+
520
+ it("should handle not operator with single value", async () => {
521
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { not: "Salad" } } });
522
+
523
+ // Not operator uses graph traversal with count = 0
524
+ expect(query).toContain("count(->link[WHERE perspective = $perspective AND predicate = 'recipe://name' AND out.uri = 'Salad']) = 0");
525
+ });
526
+
527
+ it("should handle not operator with array (NOT IN)", async () => {
528
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { not: ["Salad", "Soup"] } } });
529
+
530
+ // Not operator with array uses graph traversal with count = 0
531
+ expect(query).toContain("count(->link[WHERE perspective = $perspective AND predicate = 'recipe://name' AND out.uri IN ['Salad', 'Soup']]) = 0");
532
+ });
533
+
534
+ it("should handle between operator (filtered in JavaScript, not SQL)", async () => {
535
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { between: [3, 5] } } });
536
+
537
+ // Between operator for regular properties is now filtered in JavaScript post-query
538
+ expect(query).toContain("FROM node");
539
+ expect(query).not.toContain("target >= 3");
540
+ expect(query).not.toContain("target <= 5");
541
+ });
542
+
543
+ it("should handle contains operator on string property (filtered in JavaScript, not SQL)", async () => {
544
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { contains: "Past" } } });
545
+
546
+ // Contains operator for regular properties is now filtered in JavaScript post-query
547
+ expect(query).toContain("FROM node");
548
+ expect(query).not.toContain("target CONTAINS 'Past'");
549
+ });
550
+
551
+ it("should handle contains operator on regular property with substring (filtered in JavaScript, not SQL)", async () => {
552
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { contains: "Salad" } } });
553
+
554
+ // Contains operator is filtered in JavaScript post-query
555
+ expect(query).toContain("FROM node");
556
+ expect(query).not.toContain("target CONTAINS 'Salad'");
557
+ });
558
+
559
+ it.skip("should handle contains operator on special field (author)", async () => {
560
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { author: { contains: "alice" } } });
561
+
562
+ expect(query).toContain("WHERE author CONTAINS 'alice'");
563
+ // Should not use a subquery pattern
564
+ expect(query).not.toContain("SELECT source FROM node");
565
+ });
566
+
567
+ it.skip("should handle contains operator on special field (base)", async () => {
568
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { base: { contains: "test" } } });
569
+
570
+ expect(query).toContain("WHERE source CONTAINS 'test'");
571
+ });
572
+
573
+ it("should handle array values (IN clause)", async () => {
574
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: ["Pasta", "Pizza"] } });
575
+
576
+ expect(query).toContain("count(->link[WHERE perspective = $perspective AND predicate = 'recipe://name' AND out.uri IN ['Pasta', 'Pizza']]) > 0");
577
+ });
578
+
579
+ it.skip("should handle special fields (author, timestamp) without subqueries", async () => {
580
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { author: "did:key:alice" } });
581
+
582
+ expect(query).toContain("WHERE author = 'did:key:alice'");
583
+ // Ensure it's NOT using a subquery pattern for author in WHERE clause
584
+ expect(normalizeQuery(query)).not.toMatch(/WHERE.*source IN.*SELECT source FROM node.*author/);
585
+ });
586
+
587
+ it("should not generate ORDER BY clause in SQL (handled in JavaScript)", async () => {
588
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { order: { timestamp: "DESC" } });
589
+
590
+ // ORDER BY is now handled in JavaScript post-query
591
+ expect(query).toContain("FROM node");
592
+ expect(query).not.toContain("ORDER BY");
593
+ });
594
+
595
+ it("should not generate LIMIT clause in SQL (handled in JavaScript)", async () => {
596
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { limit: 10 });
597
+
598
+ // LIMIT is now handled in JavaScript post-query
599
+ expect(query).toContain("FROM node");
600
+ expect(query).not.toContain("LIMIT");
601
+ });
602
+
603
+ it("should not generate START clause in SQL (handled in JavaScript)", async () => {
604
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { offset: 20 });
605
+
606
+ // START/offset is now handled in JavaScript post-query
607
+ expect(query).toContain("FROM node");
608
+ expect(query).not.toContain("START");
609
+ });
610
+
611
+ it("should generate complete query with all options (ORDER BY, LIMIT, START handled in JS)", async () => {
612
+ const query = await Recipe.queryToSurrealQL(mockPerspective, {
613
+ where: { name: "Pasta", rating: { gt: 4 } },
614
+ order: { timestamp: "DESC" },
615
+ limit: 10,
616
+ offset: 20
617
+ });
618
+
619
+ // WHERE clause uses graph traversal filters
620
+ expect(query).toContain("WHERE");
621
+ expect(query).toContain("count(->link[WHERE perspective = $perspective AND predicate = 'recipe://name' AND out.uri = 'Pasta']) > 0");
622
+ // Comparison operators (gt) are filtered in JavaScript, not SQL
623
+ expect(query).not.toContain("out.uri > 4");
624
+ expect(query).not.toContain("target > 4");
625
+ // ORDER BY, LIMIT, START are now handled in JavaScript post-query
626
+ expect(query).not.toContain("ORDER BY");
627
+ expect(query).not.toContain("LIMIT");
628
+ expect(query).not.toContain("START");
629
+ });
630
+
631
+ it("should only select requested properties", async () => {
632
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: ["name"] });
633
+
634
+ // With array::group(), all link data is selected, filtering happens in instancesFromSurrealResult
635
+ expect(query).toContain("->link[WHERE perspective = $perspective] AS links");
636
+
637
+ });
638
+
639
+ it("should only select requested collections", async () => {
640
+ @ModelOptions({ name: "MultiCollectionModel" })
641
+ class MultiCollectionModel extends Ad4mModel {
642
+ @Collection({ through: "test://coll1" })
643
+ coll1: string[] = [];
644
+
645
+ @Collection({ through: "test://coll2" })
646
+ coll2: string[] = [];
647
+ }
648
+
649
+ const query = await MultiCollectionModel.queryToSurrealQL(mockPerspective, { collections: ["coll1"] });
650
+
651
+ // With array::group(), all link data is selected, filtering happens in instancesFromSurrealResult
652
+ expect(query).toContain("->link[WHERE perspective = $perspective] AS links");
653
+
654
+ });
655
+
656
+ it("should escape single quotes in string values", async () => {
657
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: "O'Brien's Recipe" } });
658
+
659
+ // Single quotes are escaped with backslash in SurrealDB
660
+ expect(query).toContain("O\\'Brien\\'s Recipe");
661
+ });
662
+
663
+ it("should handle numeric values without quotes", async () => {
664
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: 5 } });
665
+
666
+ // Numeric values should not have quotes around them
667
+ expect(query).toContain("out.uri = 5");
668
+ expect(query).not.toContain("out.uri = '5'");
669
+ });
670
+
671
+ it("should handle complex nested query (comparisons, ORDER BY, LIMIT handled in JS)", async () => {
672
+ const query = await Recipe.queryToSurrealQL(mockPerspective, {
673
+ where: {
674
+ name: "Pasta",
675
+ rating: { gte: 4, lte: 5 },
676
+ author: "did:key:alice"
677
+ },
678
+ order: { rating: "DESC" },
679
+ limit: 5
680
+ });
681
+
682
+ const normalized = normalizeQuery(query);
683
+
684
+ // Verify graph traversal filters are present
685
+ expect(normalized).toContain("count(->link[WHERE perspective = $perspective AND predicate = 'recipe://name' AND out.uri = 'Pasta']) > 0");
686
+ // Comparison operators (gte, lte) are filtered in JavaScript, not SQL
687
+ expect(normalized).not.toContain("out.uri >= 4");
688
+ expect(normalized).not.toContain("target >= 4");
689
+ expect(normalized).not.toContain("out.uri <= 5");
690
+ expect(normalized).not.toContain("target <= 5");
691
+ // author and timestamp filtering is done in JavaScript post-query
692
+ expect(normalized).not.toContain("author = 'did:key:alice'");
693
+
694
+ // ORDER BY and LIMIT are handled in JavaScript post-query
695
+ expect(normalized).not.toContain("ORDER BY");
696
+ expect(normalized).not.toContain("LIMIT");
697
+
698
+ // Verify query structure (FROM node, no GROUP BY)
699
+ expect(normalized).toContain("FROM node");
700
+ });
701
+
702
+ it("should handle empty query object", async () => {
703
+ const query = await Recipe.queryToSurrealQL(mockPerspective, {});
704
+
705
+ // Should generate valid query with WHERE clause for required properties (name and rating)
706
+ expect(query).toContain("id AS source");
707
+ expect(query).toContain("uri AS source_uri");
708
+ expect(query).toContain("FROM node");
709
+
710
+ // Should have WHERE clause filtering for required properties using graph traversal
711
+ expect(query).toContain("WHERE");
712
+ expect(query).toContain("count(->link[WHERE perspective = $perspective AND predicate = 'recipe://name']) > 0");
713
+ expect(query).toContain("count(->link[WHERE perspective = $perspective AND predicate = 'recipe://rating']) > 0");
714
+ expect(query).not.toContain("ORDER BY");
715
+ expect(query).not.toContain("START");
716
+ });
717
+
718
+ it("should handle base special field", async () => {
719
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { base: "literal://test" } });
720
+
721
+ expect(query).toContain("uri = 'literal://test'");
722
+ });
723
+
724
+ it("should handle base special field with array (IN clause)", async () => {
725
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { base: ["literal://test1", "literal://test2"] } });
726
+
727
+ expect(query).toContain("uri IN ['literal://test1', 'literal://test2']");
728
+ });
729
+
730
+ it("should handle base special field with not operator", async () => {
731
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { base: { not: "literal://test" } } });
732
+
733
+ expect(query).toContain("uri != 'literal://test'");
734
+ });
735
+
736
+ it("should handle base special field with not operator and array (NOT IN)", async () => {
737
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { base: { not: ["literal://test1", "literal://test2"] } } });
738
+
739
+ expect(query).toContain("uri NOT IN ['literal://test1', 'literal://test2']");
740
+ });
741
+
742
+ it("should handle base special field with between operator", async () => {
743
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { base: { between: ["literal://a", "literal://z"] } } } as any);
744
+
745
+ const normalized = normalizeQuery(query);
746
+ expect(normalized).toContain("uri >= 'literal://a' AND uri <= 'literal://z'");
747
+ });
748
+
749
+ it("should handle base special field with gt operator", async () => {
750
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { base: { gt: "literal://m" } } } as any);
751
+
752
+ expect(query).toContain("uri > 'literal://m'");
753
+ });
754
+
755
+ it("should handle base special field with gte and lte operators", async () => {
756
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { base: { gte: "literal://a", lte: "literal://z" } } } as any);
757
+
758
+ const normalized = normalizeQuery(query);
759
+ expect(normalized).toContain("uri >= 'literal://a'");
760
+ expect(normalized).toContain("uri <= 'literal://z'");
761
+ });
762
+
763
+ it("should handle timestamp special field with gt operator (filtered in JavaScript)", async () => {
764
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { timestamp: { gt: 1234567890 } } });
765
+
766
+ // timestamp filtering is done in JavaScript post-query
767
+ expect(query).toContain("FROM node");
768
+ expect(query).not.toContain("timestamp > 1234567890");
769
+ });
770
+
771
+ it("should handle multiple special fields (filtered in JavaScript)", async () => {
772
+ const query = await Recipe.queryToSurrealQL(mockPerspective, {
773
+ where: {
774
+ author: "did:key:alice",
775
+ timestamp: { gt: 1000 }
776
+ }
777
+ });
778
+
779
+ // author and timestamp filtering is done in JavaScript post-query
780
+ expect(query).toContain("FROM node");
781
+ expect(query).not.toContain("author = 'did:key:alice'");
782
+ expect(query).not.toContain("timestamp > 1000");
783
+ });
784
+
785
+ it("should handle mixed special and regular properties", async () => {
786
+ const query = await Recipe.queryToSurrealQL(mockPerspective, {
787
+ where: {
788
+ name: "Pasta",
789
+ author: "did:key:alice",
790
+ rating: { gt: 4 }
791
+ }
792
+ });
793
+
794
+ const normalized = normalizeQuery(query);
795
+ // Regular properties use graph traversal filters
796
+ expect(normalized).toContain("count(->link[WHERE perspective = $perspective AND predicate = 'recipe://name' AND out.uri = 'Pasta']) > 0");
797
+ // Comparison operators (gt) are filtered in JavaScript, not SQL
798
+ expect(normalized).not.toContain("out.uri > 4");
799
+ expect(normalized).not.toContain("target > 4");
800
+ // author filtering is done in JavaScript post-query
801
+ expect(normalized).not.toContain("author = 'did:key:alice'");
802
+ });
803
+
804
+ it("should handle boolean values", async () => {
805
+ @ModelOptions({ name: "Task" })
806
+ class Task extends Ad4mModel {
807
+ @Property({ through: "task://completed" })
808
+ completed: boolean = false;
809
+ }
810
+
811
+ const query = await Task.queryToSurrealQL(mockPerspective, { where: { completed: true } });
812
+
813
+ expect(query).toContain("out.uri = true");
814
+ });
815
+
816
+ it("should handle array of numbers", async () => {
817
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: [4, 5] } });
818
+
819
+ expect(query).toContain("count(->link[WHERE perspective = $perspective AND predicate = 'recipe://rating' AND out.uri IN [4, 5]]) > 0");
820
+ });
821
+
822
+ it("should skip unknown properties in where clause", async () => {
823
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { unknownProp: "value" } as any });
824
+
825
+ // Should not throw error, just skip the unknown property
826
+ expect(query).toContain("source");
827
+
828
+ // Should not contain any condition for unknownProp
829
+ expect(query).not.toContain("unknownProp");
830
+ });
831
+
832
+ it.skip("should skip unknown properties in select clause", async () => {
833
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: ["name", "unknownProp"] as any });
834
+
835
+ // Should include name using aggregation
836
+ expect(query).toContain("array::first(target[WHERE predicate = 'recipe://name']) AS name");
837
+ // Should not error on unknownProp, just skip it
838
+ expect(query).not.toContain("unknownProp");
839
+ });
840
+
841
+ it("should handle order by regular property (handled in JavaScript)", async () => {
842
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { order: { name: "ASC" } });
843
+
844
+ // ORDER BY is now handled in JavaScript post-query
845
+ expect(query).toContain("FROM node");
846
+ expect(query).not.toContain("ORDER BY");
847
+ });
848
+
849
+ it("should generate query with only properties, no collections", async () => {
850
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: ["name", "rating"], collections: [] });
851
+
852
+ // With array::group(), all link data is selected, filtering happens in instancesFromSurrealResult
853
+ expect(query).toContain("->link[WHERE perspective = $perspective] AS links");
854
+
855
+ });
856
+
857
+ it("should generate query with only collections, no properties", async () => {
858
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: [], collections: ["ingredients"] });
859
+
860
+ // With array::group(), all link data is selected, filtering happens in instancesFromSurrealResult
861
+ expect(query).toContain("->link[WHERE perspective = $perspective] AS links");
862
+
863
+ });
864
+ });
865
+
866
+ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", () => {
867
+ // Test Recipe model
868
+ @ModelOptions({ name: "Recipe" })
869
+ class Recipe extends Ad4mModel {
870
+ @Property({ through: "recipe://name" })
871
+ name: string = "";
872
+
873
+ @Property({ through: "recipe://rating" })
874
+ rating: number = 0;
875
+
876
+ @Collection({ through: "recipe://ingredient" })
877
+ ingredients: string[] = [];
878
+ }
879
+
880
+ // Mock perspective with both querySurrealDB and infer methods
881
+ const mockPerspective = {
882
+ querySurrealDB: jest.fn(),
883
+ infer: jest.fn(),
884
+ uuid: 'test-perspective-uuid',
885
+ stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue('Recipe')
886
+ } as any;
887
+
888
+ beforeEach(() => {
889
+ jest.clearAllMocks();
890
+ });
891
+
892
+ it("should convert empty SurrealDB results correctly", async () => {
893
+ const result = await Recipe.instancesFromSurrealResult(mockPerspective, {}, []);
894
+
895
+ expect(result.results).toEqual([]);
896
+ expect(result.totalCount).toBe(0);
897
+ });
898
+
899
+ it("should convert SurrealDB results to model instances", async () => {
900
+ const surrealResults = [
901
+ {
902
+ source: "node:abc123",
903
+ source_uri: "literal://recipe1",
904
+ links: [
905
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
906
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
907
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
908
+ { predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
909
+ { predicate: "recipe://ingredient", target: "cheese", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
910
+ ]
911
+ },
912
+ {
913
+ source: "node:def456",
914
+ source_uri: "literal://recipe2",
915
+ links: [
916
+ { predicate: "recipe://name", target: "Pizza", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
917
+ { predicate: "recipe://rating", target: "4", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
918
+ { predicate: "recipe://ingredient", target: "dough", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
919
+ { predicate: "recipe://ingredient", target: "cheese", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
920
+ { predicate: "recipe://ingredient", target: "tomato", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" }
921
+ ]
922
+ }
923
+ ];
924
+
925
+ const result = await Recipe.instancesFromSurrealResult(mockPerspective, {}, surrealResults);
926
+
927
+ expect(result.results).toHaveLength(2);
928
+ expect(result.totalCount).toBe(2);
929
+
930
+ const recipe1 = result.results[0];
931
+ expect(recipe1).toBeInstanceOf(Recipe);
932
+ expect(recipe1.name).toBe("Pasta");
933
+ expect(recipe1.rating).toBe(5);
934
+ expect(recipe1.ingredients).toEqual(["pasta", "tomato", "cheese"]);
935
+
936
+ const recipe2 = result.results[1];
937
+ expect(recipe2).toBeInstanceOf(Recipe);
938
+ expect(recipe2.name).toBe("Pizza");
939
+ expect(recipe2.rating).toBe(4);
940
+ });
941
+
942
+ it("should filter properties when query specifies properties", async () => {
943
+ const surrealResults = [
944
+ {
945
+ source: "node:abc123",
946
+ source_uri: "literal://recipe1",
947
+ links: [
948
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
949
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
950
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
951
+ { predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
952
+ ]
953
+ }
954
+ ];
955
+
956
+ const result = await Recipe.instancesFromSurrealResult(
957
+ mockPerspective,
958
+ { properties: ["name"] },
959
+ surrealResults
960
+ );
961
+
962
+ expect(result.results).toHaveLength(1);
963
+ const recipe = result.results[0];
964
+ expect(recipe.name).toBe("Pasta");
965
+ // rating and ingredients should be removed since only "name" was requested
966
+ expect(recipe.rating).toBeUndefined();
967
+ expect(recipe.ingredients).toBeUndefined();
968
+ // author and timestamp should still be present
969
+ expect(recipe.author).toBe("did:key:alice");
970
+ // Timestamp is converted to Unix epoch (milliseconds)
971
+ expect(recipe.timestamp).toBe(new Date("2023-01-01T00:00:00Z").getTime());
972
+ });
973
+
974
+ it("should filter collections when query specifies collections", async () => {
975
+ const surrealResults = [
976
+ {
977
+ source: "node:abc123",
978
+ source_uri: "literal://recipe1",
979
+ links: [
980
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
981
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
982
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
983
+ { predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
984
+ ]
985
+ }
986
+ ];
987
+
988
+ const result = await Recipe.instancesFromSurrealResult(
989
+ mockPerspective,
990
+ { collections: ["ingredients"] },
991
+ surrealResults
992
+ );
993
+
994
+ expect(result.results).toHaveLength(1);
995
+ const recipe = result.results[0];
996
+ expect(recipe.ingredients).toEqual(["pasta", "tomato"]);
997
+ // name and rating should be removed since only "ingredients" was requested
998
+ expect(recipe.name).toBeUndefined();
999
+ expect(recipe.rating).toBeUndefined();
1000
+ });
1001
+
1002
+ it("should handle results missing base field", async () => {
1003
+ const surrealResults = [
1004
+ {
1005
+ links: [
1006
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1007
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1008
+ ]
1009
+ // Missing source field
1010
+ } as any
1011
+ ];
1012
+
1013
+ const result = await Recipe.instancesFromSurrealResult(mockPerspective, {}, surrealResults);
1014
+
1015
+ // Should filter out the invalid result (or handle gracefully)
1016
+ expect(result.results).toHaveLength(0);
1017
+ expect(result.totalCount).toBe(0);
1018
+ });
1019
+
1020
+ it("should use SurrealDB by default in findAll()", async () => {
1021
+ const surrealResults = [
1022
+ {
1023
+ source: "node:abc123",
1024
+ source_uri: "literal://recipe1",
1025
+ links: [
1026
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1027
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1028
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1029
+ ]
1030
+ }
1031
+ ];
1032
+
1033
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1034
+
1035
+ const results = await Recipe.findAll(mockPerspective, {});
1036
+
1037
+ expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
1038
+ expect(mockPerspective.infer).not.toHaveBeenCalled();
1039
+ expect(results).toHaveLength(1);
1040
+ expect(results[0].name).toBe("Pasta");
1041
+ });
1042
+
1043
+ it("should use Prolog when useSurrealDB is false in findAll()", async () => {
1044
+ const prologResults = [{
1045
+ AllInstances: [
1046
+ ["literal://recipe1", [["name", "Pasta"]], [["ingredients", ["pasta"]]], "2023-01-01T00:00:00Z", "did:key:alice"]
1047
+ ],
1048
+ TotalCount: 1
1049
+ }];
1050
+
1051
+ mockPerspective.infer.mockResolvedValue(prologResults);
1052
+
1053
+ const results = await Recipe.findAll(mockPerspective, {}, false);
1054
+
1055
+ expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1056
+ expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
1057
+ expect(results).toHaveLength(1);
1058
+ });
1059
+
1060
+ it("should use SurrealDB by default in findAllAndCount()", async () => {
1061
+ const surrealResults = [
1062
+ {
1063
+ source: "node:abc123",
1064
+ source_uri: "literal://recipe1",
1065
+ links: [
1066
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1067
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1068
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1069
+ ]
1070
+ }
1071
+ ];
1072
+
1073
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1074
+
1075
+ const { results, totalCount } = await Recipe.findAllAndCount(mockPerspective, {});
1076
+
1077
+ expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
1078
+ expect(mockPerspective.infer).not.toHaveBeenCalled();
1079
+ expect(results).toHaveLength(1);
1080
+ expect(totalCount).toBe(1);
1081
+ });
1082
+
1083
+ it("should use SurrealDB by default in paginate()", async () => {
1084
+ const surrealResults = [
1085
+ {
1086
+ source: "node:abc123",
1087
+ source_uri: "literal://recipe1",
1088
+ links: [
1089
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1090
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1091
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1092
+ ]
1093
+ }
1094
+ ];
1095
+
1096
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1097
+
1098
+ const page = await Recipe.paginate(mockPerspective, 10, 1, {});
1099
+
1100
+ expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
1101
+ expect(mockPerspective.infer).not.toHaveBeenCalled();
1102
+ expect(page.results).toHaveLength(1);
1103
+ expect(page.pageSize).toBe(10);
1104
+ expect(page.pageNumber).toBe(1);
1105
+ });
1106
+
1107
+ it("should use SurrealDB by default in count()", async () => {
1108
+ // Since count() uses result.length and GROUP BY returns one row per source,
1109
+ // mock 5 recipe sources
1110
+ const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1111
+ source: `node:abc${i+1}`,
1112
+ source_uri: `literal://recipe${i+1}`,
1113
+ links: [
1114
+ { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1115
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1116
+ ]
1117
+ }));
1118
+
1119
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1120
+
1121
+ const count = await Recipe.count(mockPerspective, {});
1122
+
1123
+ expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
1124
+ expect(mockPerspective.infer).not.toHaveBeenCalled();
1125
+ expect(count).toBe(5);
1126
+ });
1127
+
1128
+ it("should use Prolog when useSurrealDB is false in count()", async () => {
1129
+ const prologResults = [{ TotalCount: 10 }];
1130
+ mockPerspective.infer.mockResolvedValue(prologResults);
1131
+
1132
+ const count = await Recipe.count(mockPerspective, {}, false);
1133
+
1134
+ expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1135
+ expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
1136
+ expect(count).toBe(10);
1137
+ });
1138
+
1139
+ it("should use SurrealDB by default in ModelQueryBuilder.get()", async () => {
1140
+ const surrealResults = [
1141
+ {
1142
+ source: "node:abc123",
1143
+ source_uri: "literal://recipe1",
1144
+ links: [
1145
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1146
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1147
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1148
+ ]
1149
+ }
1150
+ ];
1151
+
1152
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1153
+
1154
+ const results = await Recipe.query(mockPerspective)
1155
+ .where({ name: "Pasta" })
1156
+ .get();
1157
+
1158
+ expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
1159
+ expect(mockPerspective.infer).not.toHaveBeenCalled();
1160
+ expect(results).toHaveLength(1);
1161
+ expect(results[0].name).toBe("Pasta");
1162
+ });
1163
+
1164
+ it("should use Prolog when useSurrealDB(false) in ModelQueryBuilder.get()", async () => {
1165
+ const prologResults = [{
1166
+ AllInstances: [
1167
+ ["literal://recipe1", [["name", "Pasta"]], [["ingredients", ["pasta"]]], "2023-01-01T00:00:00Z", "did:key:alice"]
1168
+ ],
1169
+ TotalCount: 1
1170
+ }];
1171
+
1172
+ mockPerspective.infer.mockResolvedValue(prologResults);
1173
+
1174
+ const results = await Recipe.query(mockPerspective)
1175
+ .where({ name: "Pasta" })
1176
+ .useSurrealDB(false)
1177
+ .get();
1178
+
1179
+ expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1180
+ expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
1181
+ expect(results).toHaveLength(1);
1182
+ });
1183
+
1184
+ it("should use SurrealDB by default in ModelQueryBuilder.count()", async () => {
1185
+ // count() counts the number of rows returned by the query (one row per source)
1186
+ const surrealResults = Array.from({ length: 3 }, (_, i) => ({
1187
+ source: `node:abc${i+1}`,
1188
+ source_uri: `literal://recipe${i+1}`,
1189
+ links: [
1190
+ { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1191
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1192
+ ]
1193
+ }));
1194
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1195
+
1196
+ const count = await Recipe.query(mockPerspective)
1197
+ .where({ rating: { gt: 4 } })
1198
+ .count();
1199
+
1200
+ expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
1201
+ expect(mockPerspective.infer).not.toHaveBeenCalled();
1202
+ expect(count).toBe(3);
1203
+ });
1204
+
1205
+ it("should use SurrealDB by default in ModelQueryBuilder.paginate()", async () => {
1206
+ const surrealResults = [
1207
+ {
1208
+ source: "node:abc123",
1209
+ source_uri: "literal://recipe1",
1210
+ links: [
1211
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1212
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1213
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1214
+ ]
1215
+ }
1216
+ ];
1217
+
1218
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1219
+
1220
+ const page = await Recipe.query(mockPerspective)
1221
+ .where({ rating: { gt: 3 } })
1222
+ .paginate(10, 1);
1223
+
1224
+ expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
1225
+ expect(mockPerspective.infer).not.toHaveBeenCalled();
1226
+ expect(page.results).toHaveLength(1);
1227
+ expect(page.pageSize).toBe(10);
1228
+ expect(page.pageNumber).toBe(1);
1229
+ });
1230
+ });
1231
+
1232
+ describe("Ad4mModel.count() with advanced where conditions", () => {
1233
+ // Test Recipe model
1234
+ @ModelOptions({ name: "Recipe" })
1235
+ class Recipe extends Ad4mModel {
1236
+ @Property({ through: "recipe://name" })
1237
+ name: string = "";
1238
+
1239
+ @Property({ through: "recipe://rating" })
1240
+ rating: number = 0;
1241
+
1242
+ @Collection({ through: "recipe://ingredient" })
1243
+ ingredients: string[] = [];
1244
+ }
1245
+
1246
+ // Mock perspective
1247
+ const mockPerspective = {
1248
+ querySurrealDB: jest.fn(),
1249
+ infer: jest.fn(),
1250
+ uuid: 'test-perspective-uuid',
1251
+ stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue('Recipe')
1252
+ } as any;
1253
+
1254
+ beforeEach(() => {
1255
+ jest.clearAllMocks();
1256
+ });
1257
+
1258
+ it("should apply JS-level filtering for gt operator on properties in SurrealDB count()", async () => {
1259
+ // Mock SurrealDB results: 5 recipes with ratings 1, 2, 3, 4, 5
1260
+ const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1261
+ source: `node:abc${i+1}`,
1262
+ source_uri: `literal://recipe${i+1}`,
1263
+ links: [
1264
+ { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1265
+ { predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1266
+ ]
1267
+ }));
1268
+
1269
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1270
+
1271
+ // Count recipes with rating > 3 (should match 2 recipes: rating 4 and 5)
1272
+ const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } });
1273
+
1274
+ // Verify count matches the number of instances that would be returned by findAll
1275
+ const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { gt: 3 } } });
1276
+
1277
+ expect(count).toBe(2);
1278
+ expect(count).toBe(findAllResults.length);
1279
+ });
1280
+
1281
+ it("should apply JS-level filtering for between operator on properties in SurrealDB count()", async () => {
1282
+ // Mock SurrealDB results: 5 recipes with ratings 1, 2, 3, 4, 5
1283
+ const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1284
+ source: `node:abc${i+1}`,
1285
+ source_uri: `literal://recipe${i+1}`,
1286
+ links: [
1287
+ { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1288
+ { predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1289
+ ]
1290
+ }));
1291
+
1292
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1293
+
1294
+ // Count recipes with rating between 2 and 4 (should match 3 recipes: rating 2, 3, 4)
1295
+ const count = await Recipe.count(mockPerspective, { where: { rating: { between: [2, 4] } } });
1296
+
1297
+ // Verify count matches the number of instances that would be returned by findAll
1298
+ const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { between: [2, 4] } } });
1299
+
1300
+ expect(count).toBe(3);
1301
+ expect(count).toBe(findAllResults.length);
1302
+ });
1303
+
1304
+ it("should apply JS-level filtering for timestamp gt operator in SurrealDB count()", async () => {
1305
+ // Mock SurrealDB results: 5 recipes with different timestamps
1306
+ const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1307
+ source: `node:abc${i+1}`,
1308
+ source_uri: `literal://recipe${i+1}`,
1309
+ links: [
1310
+ { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
1311
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
1312
+ ]
1313
+ }));
1314
+
1315
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1316
+
1317
+ // Count recipes with timestamp > 2023-01-03 (should match 2 recipes: 2023-01-04 and 2023-01-05)
1318
+ const targetTimestamp = new Date("2023-01-03T00:00:00Z").getTime();
1319
+ const count = await Recipe.count(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } });
1320
+
1321
+ // Verify count matches the number of instances that would be returned by findAll
1322
+ const findAllResults = await Recipe.findAll(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } });
1323
+
1324
+ expect(count).toBe(2);
1325
+ expect(count).toBe(findAllResults.length);
1326
+ });
1327
+
1328
+ it("should apply JS-level filtering for timestamp between operator in SurrealDB count()", async () => {
1329
+ // Mock SurrealDB results: 5 recipes with different timestamps
1330
+ const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1331
+ source: `node:abc${i+1}`,
1332
+ source_uri: `literal://recipe${i+1}`,
1333
+ links: [
1334
+ { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
1335
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
1336
+ ]
1337
+ }));
1338
+
1339
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1340
+
1341
+ // Count recipes with timestamp between 2023-01-02 and 2023-01-04
1342
+ const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1343
+ const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
1344
+ const count = await Recipe.count(mockPerspective, {
1345
+ where: { timestamp: { between: [startTimestamp, endTimestamp] } }
1346
+ });
1347
+
1348
+ // Verify count matches the number of instances that would be returned by findAll
1349
+ const findAllResults = await Recipe.findAll(mockPerspective, {
1350
+ where: { timestamp: { between: [startTimestamp, endTimestamp] } }
1351
+ });
1352
+
1353
+ expect(count).toBe(3);
1354
+ expect(count).toBe(findAllResults.length);
1355
+ });
1356
+
1357
+ it("should apply JS-level filtering for author filtering in SurrealDB count()", async () => {
1358
+ // Mock SurrealDB results: 3 recipes by Alice and 2 by Bob
1359
+ const surrealResults = [
1360
+ ...Array.from({ length: 3 }, (_, i) => ({
1361
+ source: `node:abc${i+1}`,
1362
+ source_uri: `literal://recipe${i+1}`,
1363
+ links: [
1364
+ { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1365
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1366
+ ]
1367
+ })),
1368
+ ...Array.from({ length: 2 }, (_, i) => ({
1369
+ source: `node:def${i+4}`,
1370
+ source_uri: `literal://recipe${i+4}`,
1371
+ links: [
1372
+ { predicate: "recipe://name", target: `Recipe ${i+4}`, author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
1373
+ { predicate: "recipe://rating", target: "5", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" }
1374
+ ]
1375
+ }))
1376
+ ];
1377
+
1378
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1379
+
1380
+ // Count recipes by Alice (should match 3 recipes)
1381
+ const count = await Recipe.count(mockPerspective, { where: { author: "did:key:alice" } });
1382
+
1383
+ // Verify count matches the number of instances that would be returned by findAll
1384
+ const findAllResults = await Recipe.findAll(mockPerspective, { where: { author: "did:key:alice" } });
1385
+
1386
+ expect(count).toBe(3);
1387
+ expect(count).toBe(findAllResults.length);
1388
+ });
1389
+
1390
+ it("should apply JS-level filtering in ModelQueryBuilder.count() with gt operator", async () => {
1391
+ // Mock SurrealDB results: 5 recipes with ratings 1, 2, 3, 4, 5
1392
+ const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1393
+ source: `node:abc${i+1}`,
1394
+ source_uri: `literal://recipe${i+1}`,
1395
+ links: [
1396
+ { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1397
+ { predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1398
+ ]
1399
+ }));
1400
+
1401
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1402
+
1403
+ // Count recipes with rating > 3 using ModelQueryBuilder
1404
+ const count = await Recipe.query(mockPerspective)
1405
+ .where({ rating: { gt: 3 } })
1406
+ .count();
1407
+
1408
+ // Verify count matches the number of instances that would be returned by get()
1409
+ const getResults = await Recipe.query(mockPerspective)
1410
+ .where({ rating: { gt: 3 } })
1411
+ .get();
1412
+
1413
+ expect(count).toBe(2);
1414
+ expect(count).toBe(getResults.length);
1415
+ });
1416
+
1417
+ it("should apply JS-level filtering in ModelQueryBuilder.count() with timestamp between", async () => {
1418
+ // Mock SurrealDB results: 5 recipes with different timestamps
1419
+ const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1420
+ source: `node:abc${i+1}`,
1421
+ source_uri: `literal://recipe${i+1}`,
1422
+ links: [
1423
+ { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
1424
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
1425
+ ]
1426
+ }));
1427
+
1428
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1429
+
1430
+ const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1431
+ const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
1432
+
1433
+ // Count using ModelQueryBuilder
1434
+ const count = await Recipe.query(mockPerspective)
1435
+ .where({ timestamp: { between: [startTimestamp, endTimestamp] } })
1436
+ .count();
1437
+
1438
+ // Verify count matches the number of instances that would be returned by get()
1439
+ const getResults = await Recipe.query(mockPerspective)
1440
+ .where({ timestamp: { between: [startTimestamp, endTimestamp] } })
1441
+ .get();
1442
+
1443
+ expect(count).toBe(3);
1444
+ expect(count).toBe(getResults.length);
1445
+ });
1446
+
1447
+ it("should handle count() with Prolog for gt operator (legacy)", async () => {
1448
+ const prologResults = [{ TotalCount: 2 }];
1449
+ mockPerspective.infer.mockResolvedValue(prologResults);
1450
+
1451
+ const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } }, false);
1452
+
1453
+ expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1454
+ expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
1455
+ expect(count).toBe(2);
1456
+ });
1457
+
1458
+ it("should handle count() with Prolog for timestamp between (legacy)", async () => {
1459
+ const prologResults = [{ TotalCount: 3 }];
1460
+ mockPerspective.infer.mockResolvedValue(prologResults);
1461
+
1462
+ const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1463
+ const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
1464
+
1465
+ const count = await Recipe.count(
1466
+ mockPerspective,
1467
+ { where: { timestamp: { between: [startTimestamp, endTimestamp] } } },
1468
+ false
1469
+ );
1470
+
1471
+ expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1472
+ expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
1473
+ expect(count).toBe(3);
1474
+ });
1475
+ });
1476
+