@coasys/ad4m 0.13.0-test-1 → 0.13.0-test-3
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 +2377 -849
- package/lib/index.js +2354 -846
- package/lib/src/Literal.js +6 -5
- package/lib/src/agent/AgentClient.d.ts +5 -1
- package/lib/src/agent/AgentClient.js +48 -2
- package/lib/src/expression/ExpressionRef.js +2 -2
- package/lib/src/index.d.ts +0 -1
- package/lib/src/index.js +0 -1
- package/lib/src/language/Language.d.ts +26 -176
- package/lib/src/language/Language.js +28 -2
- package/lib/src/model/Ad4mModel.d.ts +52 -28
- package/lib/src/model/Ad4mModel.js +255 -118
- package/lib/src/model/Ad4mModel.test.js +1727 -537
- package/lib/src/model/ModelQueryBuilder.d.ts +67 -34
- package/lib/src/model/ModelQueryBuilder.js +208 -79
- package/lib/src/model/Subject.js +6 -6
- package/lib/src/model/decorators.d.ts +14 -8
- package/lib/src/model/decorators.js +41 -14
- package/lib/src/model/hydration-batch.d.ts +34 -0
- package/lib/src/model/hydration-batch.js +147 -0
- package/lib/src/model/hydration-batching.test.d.ts +7 -0
- package/lib/src/model/hydration-batching.test.js +456 -0
- package/lib/src/model/hydration.d.ts +4 -3
- package/lib/src/model/hydration.js +365 -86
- package/lib/src/model/index.d.ts +4 -1
- package/lib/src/model/index.js +4 -1
- package/lib/src/model/json-schema.js +2 -2
- package/lib/src/model/query-cache.d.ts +30 -0
- package/lib/src/model/query-cache.js +66 -0
- package/lib/src/model/query-cache.test.d.ts +1 -0
- package/lib/src/model/query-cache.test.js +43 -0
- package/lib/src/model/query-common.d.ts +1 -1
- package/lib/src/model/query-common.js +1 -1
- package/lib/src/model/query-sparql-batch.d.ts +17 -0
- package/lib/src/model/query-sparql-batch.js +260 -0
- package/lib/src/model/query-sparql.d.ts +124 -0
- package/lib/src/model/query-sparql.js +767 -0
- package/lib/src/model/query-sparql.test.d.ts +1 -0
- package/lib/src/model/query-sparql.test.js +495 -0
- package/lib/src/model/{surreal-utils.d.ts → query-utils.d.ts} +12 -9
- package/lib/src/model/{surreal-utils.js → query-utils.js} +43 -27
- package/lib/src/model/relation-filtering.test.js +15 -15
- package/lib/src/model/sdna.js +1 -1
- package/lib/src/model/shacl-gen.js +42 -18
- package/lib/src/model/subscription-delta.test.d.ts +24 -0
- package/lib/src/model/subscription-delta.test.js +180 -0
- package/lib/src/model/subscription-pool.d.ts +39 -0
- package/lib/src/model/subscription-pool.js +165 -0
- package/lib/src/model/types.d.ts +52 -4
- package/lib/src/model/types.js +1 -1
- package/lib/src/perspectives/PerspectiveClient.d.ts +3 -17
- package/lib/src/perspectives/PerspectiveClient.js +42 -66
- package/lib/src/perspectives/PerspectiveClient.test.d.ts +1 -0
- package/lib/src/perspectives/PerspectiveClient.test.js +169 -0
- package/lib/src/perspectives/PerspectiveProxy.d.ts +54 -30
- package/lib/src/perspectives/PerspectiveProxy.js +239 -177
- package/lib/src/perspectives/PerspectiveResolver.d.ts +0 -1
- package/lib/src/perspectives/PerspectiveResolver.js +0 -11
- package/lib/src/perspectives/WakerSubscriptionManager.d.ts +3 -3
- package/lib/src/perspectives/WakerSubscriptionManager.js +7 -8
- package/lib/src/runtime/RuntimeResolver.d.ts +11 -0
- package/lib/src/runtime/RuntimeResolver.js +56 -0
- package/lib/src/schema.gql +11 -1
- package/lib/src/shacl/SHACLFlow.d.ts +1 -1
- package/lib/src/shacl/SHACLFlow.js +9 -9
- package/lib/src/shacl/SHACLShape.d.ts +1 -1
- package/lib/src/shacl/SHACLShape.js +38 -38
- package/lib/src/typeDefs.js +11 -1
- package/lib/src/utils.d.ts +6 -6
- package/lib/src/utils.js +6 -6
- package/package.json +1 -1
- package/src/Ad4mClient.test.ts +56 -1
- package/src/Literal.test.ts +10 -5
- package/src/Literal.ts +6 -5
- package/src/agent/AgentClient.ts +53 -1
- package/src/expression/ExpressionRef.ts +2 -2
- package/src/index.ts +0 -1
- package/src/language/Language.ts +55 -231
- package/src/model/Ad4mModel.test.ts +1709 -572
- package/src/model/Ad4mModel.ts +274 -120
- package/src/model/ModelQueryBuilder.ts +234 -87
- package/src/model/Subject.ts +6 -6
- package/src/model/decorators.ts +51 -22
- package/src/model/hydration-batch.ts +205 -0
- package/src/model/hydration-batching.test.ts +563 -0
- package/src/model/hydration.ts +349 -84
- package/src/model/index.ts +4 -1
- package/src/model/json-schema.ts +2 -2
- package/src/model/query-cache.test.ts +54 -0
- package/src/model/query-cache.ts +79 -0
- package/src/model/query-common.ts +1 -1
- package/src/model/query-sparql-batch.ts +301 -0
- package/src/model/query-sparql.test.ts +568 -0
- package/src/model/query-sparql.ts +820 -0
- package/src/model/{surreal-utils.ts → query-utils.ts} +44 -27
- package/src/model/relation-filtering.test.ts +15 -15
- package/src/model/sdna.ts +1 -1
- package/src/model/shacl-gen.ts +42 -17
- package/src/model/subscription-delta.test.ts +207 -0
- package/src/model/subscription-pool.ts +211 -0
- package/src/model/types.ts +53 -4
- package/src/perspectives/PerspectiveClient.test.ts +204 -0
- package/src/perspectives/PerspectiveClient.ts +41 -68
- package/src/perspectives/PerspectiveProxy.ts +244 -181
- package/src/perspectives/PerspectiveResolver.ts +0 -8
- package/src/perspectives/WakerSubscriptionManager.ts +8 -9
- package/src/runtime/RuntimeResolver.ts +43 -0
- package/src/shacl/SHACLFlow.ts +9 -9
- package/src/shacl/SHACLShape.ts +39 -39
- package/src/utils.ts +6 -6
- package/lib/src/model/query-surreal.d.ts +0 -44
- package/lib/src/model/query-surreal.js +0 -249
- package/src/language/LanguageContext.ts +0 -37
- package/src/model/query-surreal.ts +0 -280
- package/tsconfig-browser.json +0 -82
|
@@ -430,16 +430,16 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
|
|
|
430
430
|
});
|
|
431
431
|
});
|
|
432
432
|
|
|
433
|
-
|
|
434
|
-
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
describe("Ad4mModel.queryToSPARQL()", () => {
|
|
435
437
|
const mockPerspective = {} as any;
|
|
436
438
|
|
|
437
|
-
// Helper function to normalize whitespace in queries for easier comparison
|
|
438
439
|
function normalizeQuery(query: string): string {
|
|
439
440
|
return query.replace(/\s+/g, ' ').trim();
|
|
440
441
|
}
|
|
441
442
|
|
|
442
|
-
// Test Recipe model — explicit required: true to test required-property query filters
|
|
443
443
|
@Model({ name: "Recipe" })
|
|
444
444
|
class Recipe extends Ad4mModel {
|
|
445
445
|
@Property({ through: "recipe://name", required: true })
|
|
@@ -452,403 +452,172 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
|
|
|
452
452
|
ingredients: string[] = [];
|
|
453
453
|
}
|
|
454
454
|
|
|
455
|
-
it("should generate basic query with no filters", async () => {
|
|
456
|
-
const query = await Recipe.
|
|
455
|
+
it("should generate basic SPARQL query with no filters", async () => {
|
|
456
|
+
const query = await (Recipe as any).queryToSPARQL(mockPerspective, {});
|
|
457
|
+
const norm = normalizeQuery(query);
|
|
457
458
|
|
|
458
|
-
|
|
459
|
-
expect(
|
|
460
|
-
|
|
461
|
-
expect(
|
|
462
|
-
expect(
|
|
463
|
-
// Should have graph traversal filters for required properties
|
|
464
|
-
expect(query).toContain("count(->link[WHERE");
|
|
459
|
+
// Must be a SPARQL SELECT
|
|
460
|
+
expect(norm).toContain("SELECT ?source ?predicate ?target ?author ?timestamp");
|
|
461
|
+
// Must have conformance JOIN for required properties using direct triple patterns
|
|
462
|
+
expect(norm).toContain("cfTarget_name");
|
|
463
|
+
expect(norm).toContain("recipe://name");
|
|
465
464
|
});
|
|
466
465
|
|
|
467
466
|
it("should generate query with simple property filter", async () => {
|
|
468
|
-
const query = await Recipe.
|
|
469
|
-
|
|
470
|
-
// Should have graph traversal filters for required properties and user filter
|
|
471
|
-
expect(query).toContain("count(->link[WHERE predicate = 'recipe://name']) > 0");
|
|
472
|
-
expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating']) > 0");
|
|
473
|
-
expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
|
|
474
|
-
});
|
|
475
|
-
|
|
476
|
-
it("should generate query with multiple property filters", async () => {
|
|
477
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: "Pasta", rating: 5 } });
|
|
478
|
-
|
|
479
|
-
expect(query).toContain("WHERE");
|
|
480
|
-
expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
|
|
481
|
-
expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating' AND fn::parse_literal(out.uri) = 5]) > 0");
|
|
482
|
-
expect(query).toContain("AND");
|
|
483
|
-
});
|
|
484
|
-
|
|
485
|
-
it("should handle gt operator (filtered in JavaScript, not SQL)", async () => {
|
|
486
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { gt: 4 } } });
|
|
487
|
-
|
|
488
|
-
// Comparison operators for regular properties are now filtered in JavaScript post-query
|
|
489
|
-
// The SQL just filters on the predicate existing
|
|
490
|
-
expect(query).toContain("FROM node");
|
|
491
|
-
|
|
492
|
-
// Should NOT contain comparison operators in SQL for regular properties
|
|
493
|
-
expect(query).not.toContain("target > 4");
|
|
494
|
-
});
|
|
495
|
-
|
|
496
|
-
it("should handle lt operator (filtered in JavaScript, not SQL)", async () => {
|
|
497
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { lt: 3 } } });
|
|
498
|
-
|
|
499
|
-
// Comparison operators are filtered in JavaScript post-query
|
|
500
|
-
expect(query).toContain("FROM node");
|
|
501
|
-
expect(query).not.toContain("target < 3");
|
|
502
|
-
});
|
|
503
|
-
|
|
504
|
-
it("should handle gte and lte operators (filtered in JavaScript, not SQL)", async () => {
|
|
505
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { gte: 3, lte: 5 } } });
|
|
506
|
-
|
|
507
|
-
// Comparison operators are filtered in JavaScript post-query
|
|
508
|
-
expect(query).toContain("FROM node");
|
|
509
|
-
expect(query).not.toContain("target >= 3");
|
|
510
|
-
expect(query).not.toContain("target <= 5");
|
|
511
|
-
});
|
|
512
|
-
|
|
513
|
-
it("should handle not operator with single value", async () => {
|
|
514
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { not: "Salad" } } });
|
|
515
|
-
|
|
516
|
-
// Not operator uses graph traversal with count = 0
|
|
517
|
-
expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Salad']) = 0");
|
|
518
|
-
});
|
|
519
|
-
|
|
520
|
-
it("should handle not operator with array (NOT IN)", async () => {
|
|
521
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { not: ["Salad", "Soup"] } } });
|
|
522
|
-
|
|
523
|
-
// Not operator with array uses graph traversal with count = 0
|
|
524
|
-
expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) IN ['Salad', 'Soup']]) = 0");
|
|
525
|
-
});
|
|
526
|
-
|
|
527
|
-
it("should handle between operator (filtered in JavaScript, not SQL)", async () => {
|
|
528
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { between: [3, 5] } } });
|
|
529
|
-
|
|
530
|
-
// Between operator for regular properties is now filtered in JavaScript post-query
|
|
531
|
-
expect(query).toContain("FROM node");
|
|
532
|
-
expect(query).not.toContain("target >= 3");
|
|
533
|
-
expect(query).not.toContain("target <= 5");
|
|
534
|
-
});
|
|
535
|
-
|
|
536
|
-
it("should handle contains operator on string property (filtered in JavaScript, not SQL)", async () => {
|
|
537
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { contains: "Past" } } });
|
|
538
|
-
|
|
539
|
-
// Contains operator for regular properties is now filtered in JavaScript post-query
|
|
540
|
-
expect(query).toContain("FROM node");
|
|
541
|
-
expect(query).not.toContain("target CONTAINS 'Past'");
|
|
542
|
-
});
|
|
543
|
-
|
|
544
|
-
it("should handle contains operator on regular property with substring (filtered in JavaScript, not SQL)", async () => {
|
|
545
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { contains: "Salad" } } });
|
|
546
|
-
|
|
547
|
-
// Contains operator is filtered in JavaScript post-query
|
|
548
|
-
expect(query).toContain("FROM node");
|
|
549
|
-
expect(query).not.toContain("target CONTAINS 'Salad'");
|
|
550
|
-
});
|
|
551
|
-
|
|
552
|
-
it.skip("should handle contains operator on special field (author)", async () => {
|
|
553
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { author: { contains: "alice" } } });
|
|
554
|
-
|
|
555
|
-
expect(query).toContain("WHERE author CONTAINS 'alice'");
|
|
556
|
-
// Should not use a subquery pattern
|
|
557
|
-
expect(query).not.toContain("SELECT source FROM node");
|
|
558
|
-
});
|
|
559
|
-
|
|
560
|
-
it.skip("should handle contains operator on special field (id)", async () => {
|
|
561
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { contains: "test" } } });
|
|
562
|
-
|
|
563
|
-
expect(query).toContain("WHERE source CONTAINS 'test'");
|
|
564
|
-
});
|
|
565
|
-
|
|
566
|
-
it("should handle array values (IN clause)", async () => {
|
|
567
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: ["Pasta", "Pizza"] } });
|
|
568
|
-
|
|
569
|
-
expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) IN ['Pasta', 'Pizza']]) > 0");
|
|
570
|
-
});
|
|
571
|
-
|
|
572
|
-
it.skip("should handle special fields (author, timestamp) without subqueries", async () => {
|
|
573
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { author: "did:key:alice" } });
|
|
574
|
-
|
|
575
|
-
expect(query).toContain("WHERE author = 'did:key:alice'");
|
|
576
|
-
// Ensure it's NOT using a subquery pattern for author in WHERE clause
|
|
577
|
-
expect(normalizeQuery(query)).not.toMatch(/WHERE.*source IN.*SELECT source FROM node.*author/);
|
|
578
|
-
});
|
|
579
|
-
|
|
580
|
-
it("should not generate ORDER BY clause in SQL (handled in JavaScript)", async () => {
|
|
581
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { order: { timestamp: "DESC" } });
|
|
582
|
-
|
|
583
|
-
// ORDER BY is now handled in JavaScript post-query
|
|
584
|
-
expect(query).toContain("FROM node");
|
|
585
|
-
expect(query).not.toContain("ORDER BY");
|
|
586
|
-
});
|
|
467
|
+
const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { name: "Pasta" } });
|
|
468
|
+
const norm = normalizeQuery(query);
|
|
587
469
|
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
//
|
|
592
|
-
expect(
|
|
593
|
-
expect(query).not.toContain("LIMIT");
|
|
470
|
+
expect(norm).toContain("SELECT ?source ?predicate ?target ?author ?timestamp");
|
|
471
|
+
// For literal-stored properties, SPARQL only adds a JOIN (no FILTER value) — filtering is in JS
|
|
472
|
+
expect(norm).toContain("recipe://name");
|
|
473
|
+
// Value should NOT be in SPARQL — filtering happens in JS post-filter
|
|
474
|
+
expect(norm).toContain("?wTarget_name");
|
|
594
475
|
});
|
|
595
476
|
|
|
596
|
-
it("should
|
|
597
|
-
const query = await Recipe.
|
|
477
|
+
it("should generate query with NOT operator", async () => {
|
|
478
|
+
const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { name: { not: "Salad" } } });
|
|
479
|
+
const norm = normalizeQuery(query);
|
|
598
480
|
|
|
599
|
-
//
|
|
600
|
-
expect(
|
|
601
|
-
expect(query).not.toContain("START");
|
|
481
|
+
// For literal-stored properties, NOT filtering is done in JS — no NOT EXISTS in SPARQL
|
|
482
|
+
expect(norm).toContain("recipe://name");
|
|
602
483
|
});
|
|
603
484
|
|
|
604
|
-
it("should generate
|
|
605
|
-
const query = await Recipe.
|
|
606
|
-
|
|
607
|
-
order: { timestamp: "DESC" },
|
|
608
|
-
limit: 10,
|
|
609
|
-
offset: 20
|
|
610
|
-
});
|
|
485
|
+
it("should generate query with NOT IN operator (array)", async () => {
|
|
486
|
+
const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { name: { not: ["Salad", "Soup"] } } });
|
|
487
|
+
const norm = normalizeQuery(query);
|
|
611
488
|
|
|
612
|
-
//
|
|
613
|
-
expect(
|
|
614
|
-
expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
|
|
615
|
-
// Comparison operators (gt) are filtered in JavaScript, not SQL
|
|
616
|
-
expect(query).not.toContain("out.uri > 4");
|
|
617
|
-
expect(query).not.toContain("target > 4");
|
|
618
|
-
// ORDER BY, LIMIT, START are now handled in JavaScript post-query
|
|
619
|
-
expect(query).not.toContain("ORDER BY");
|
|
620
|
-
expect(query).not.toContain("LIMIT");
|
|
621
|
-
expect(query).not.toContain("START");
|
|
489
|
+
// For literal-stored properties, NOT IN filtering is done in JS — no filter values in SPARQL
|
|
490
|
+
expect(norm).toContain("recipe://name");
|
|
622
491
|
});
|
|
623
492
|
|
|
624
|
-
it("should
|
|
625
|
-
const query = await Recipe.
|
|
493
|
+
it("should generate query with IN clause (array values)", async () => {
|
|
494
|
+
const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { name: ["Pasta", "Pizza"] } });
|
|
495
|
+
const norm = normalizeQuery(query);
|
|
626
496
|
|
|
627
|
-
//
|
|
628
|
-
expect(
|
|
629
|
-
|
|
497
|
+
// For literal-stored properties, IN filtering is done in JS — only a JOIN exists
|
|
498
|
+
expect(norm).toContain("recipe://name");
|
|
499
|
+
expect(norm).toContain("?wTarget_name");
|
|
630
500
|
});
|
|
631
501
|
|
|
632
|
-
it("should
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
@HasMany({ through: "test://coll1" })
|
|
636
|
-
coll1: string[] = [];
|
|
637
|
-
|
|
638
|
-
@HasMany({ through: "test://coll2" })
|
|
639
|
-
coll2: string[] = [];
|
|
640
|
-
}
|
|
641
|
-
|
|
642
|
-
const query = await MultiRelationModel.queryToSurrealQL(mockPerspective, {});
|
|
502
|
+
it("should generate query with base filter", async () => {
|
|
503
|
+
const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { base: "ad4m://test123" } });
|
|
504
|
+
const norm = normalizeQuery(query);
|
|
643
505
|
|
|
644
|
-
|
|
645
|
-
expect(
|
|
646
|
-
|
|
506
|
+
expect(norm).toContain("?source =");
|
|
507
|
+
expect(norm).toContain("ad4m://test123");
|
|
647
508
|
});
|
|
648
509
|
|
|
649
|
-
it("should escape
|
|
650
|
-
const query = await Recipe.
|
|
651
|
-
|
|
652
|
-
// Single quotes are escaped with backslash in SurrealDB
|
|
653
|
-
expect(query).toContain("O\\'Brien\\'s Recipe");
|
|
654
|
-
});
|
|
510
|
+
it("should escape special characters in SPARQL strings", async () => {
|
|
511
|
+
const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { name: 'O\'Brien' } });
|
|
512
|
+
const norm = normalizeQuery(query);
|
|
655
513
|
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
// Numeric values should not have quotes around them
|
|
660
|
-
expect(query).toContain("fn::parse_literal(out.uri) = 5");
|
|
661
|
-
expect(query).not.toContain("fn::parse_literal(out.uri) = '5'");
|
|
514
|
+
// Should not break the query
|
|
515
|
+
expect(norm).toContain("SELECT ?source");
|
|
662
516
|
});
|
|
663
517
|
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
name: "Pasta",
|
|
668
|
-
rating: { gte: 4, lte: 5 },
|
|
669
|
-
author: "did:key:alice"
|
|
670
|
-
},
|
|
671
|
-
order: { rating: "DESC" },
|
|
672
|
-
limit: 5
|
|
673
|
-
});
|
|
518
|
+
// =========================================================================
|
|
519
|
+
// Additional models for thorough SPARQL structure tests
|
|
520
|
+
// =========================================================================
|
|
674
521
|
|
|
675
|
-
|
|
522
|
+
@Model({ name: "Task" })
|
|
523
|
+
class Task extends Ad4mModel {
|
|
524
|
+
@Property({ through: "task://title", resolveLanguage: "literal", required: true })
|
|
525
|
+
title: string = "";
|
|
676
526
|
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
// Comparison operators (gte, lte) are filtered in JavaScript, not SQL
|
|
680
|
-
expect(normalized).not.toContain("out.uri >= 4");
|
|
681
|
-
expect(normalized).not.toContain("target >= 4");
|
|
682
|
-
expect(normalized).not.toContain("out.uri <= 5");
|
|
683
|
-
expect(normalized).not.toContain("target <= 5");
|
|
684
|
-
// author and timestamp filtering is done in JavaScript post-query
|
|
685
|
-
expect(normalized).not.toContain("author = 'did:key:alice'");
|
|
527
|
+
@Property({ through: "task://priority", resolveLanguage: "literal" })
|
|
528
|
+
priority: number = 0;
|
|
686
529
|
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
expect(normalized).not.toContain("LIMIT");
|
|
530
|
+
@Property({ through: "task://done", resolveLanguage: "literal" })
|
|
531
|
+
done: boolean = false;
|
|
690
532
|
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
});
|
|
533
|
+
@Optional({ through: "task://description" })
|
|
534
|
+
description: string = "";
|
|
694
535
|
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
// Should generate valid query with WHERE clause for required properties (name and rating)
|
|
699
|
-
expect(query).toContain("id AS source");
|
|
700
|
-
expect(query).toContain("uri AS source_uri");
|
|
701
|
-
expect(query).toContain("FROM node");
|
|
702
|
-
|
|
703
|
-
// Should have WHERE clause filtering for required properties using graph traversal
|
|
704
|
-
expect(query).toContain("WHERE");
|
|
705
|
-
expect(query).toContain("count(->link[WHERE predicate = 'recipe://name']) > 0");
|
|
706
|
-
expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating']) > 0");
|
|
707
|
-
expect(query).not.toContain("ORDER BY");
|
|
708
|
-
expect(query).not.toContain("START");
|
|
709
|
-
});
|
|
536
|
+
@HasMany({ through: "task://tag" })
|
|
537
|
+
tags: string[] = [];
|
|
710
538
|
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
expect(query).toContain("uri = 'literal://test'");
|
|
715
|
-
});
|
|
539
|
+
@HasMany({ through: "task://assignee" })
|
|
540
|
+
assignees: string[] = [];
|
|
541
|
+
}
|
|
716
542
|
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
}
|
|
543
|
+
@Model({ name: "EmptyModel" })
|
|
544
|
+
class EmptyModel extends Ad4mModel {
|
|
545
|
+
@Optional({ through: "empty://optField" })
|
|
546
|
+
optField: string = "";
|
|
547
|
+
}
|
|
722
548
|
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
});
|
|
549
|
+
// ---- Comparison operators (gt, lt, gte, lte, between, contains) ----
|
|
550
|
+
// These are handled in JS post-processing, NOT in SPARQL.
|
|
551
|
+
// The tests verify that the SPARQL still generates valid output (conformance filters)
|
|
552
|
+
// but does NOT inject FILTER clauses for these operators.
|
|
728
553
|
|
|
729
|
-
it("should
|
|
730
|
-
const query = await Recipe.
|
|
731
|
-
|
|
732
|
-
expect(
|
|
554
|
+
it("should inject SPARQL FILTER for gt operator", async () => {
|
|
555
|
+
const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { rating: { gt: 3 } } });
|
|
556
|
+
const norm = normalizeQuery(query);
|
|
557
|
+
expect(norm).toContain("SELECT ?source");
|
|
558
|
+
// gt is now handled via JS post-filter — SPARQL just joins the property
|
|
559
|
+
expect(norm).toContain("wTarget_cmp_rating");
|
|
733
560
|
});
|
|
734
561
|
|
|
735
|
-
it("should
|
|
736
|
-
const query = await Recipe.
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
562
|
+
it("should inject SPARQL FILTER for lt operator", async () => {
|
|
563
|
+
const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { rating: { lt: 5 } } });
|
|
564
|
+
const norm = normalizeQuery(query);
|
|
565
|
+
expect(norm).toContain("SELECT ?source");
|
|
566
|
+
// lt is now handled via JS post-filter
|
|
567
|
+
expect(norm).toContain("wTarget_cmp_rating");
|
|
740
568
|
});
|
|
741
569
|
|
|
742
|
-
it("should
|
|
743
|
-
const query = await Recipe.
|
|
744
|
-
|
|
745
|
-
expect(
|
|
570
|
+
it("should inject SPARQL FILTER for gte/lte combined", async () => {
|
|
571
|
+
const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { rating: { gte: 2, lte: 8 } } });
|
|
572
|
+
const norm = normalizeQuery(query);
|
|
573
|
+
expect(norm).toContain("SELECT ?source");
|
|
574
|
+
// gte/lte are now handled via JS post-filter
|
|
575
|
+
expect(norm).toContain("wTarget_cmp_rating");
|
|
746
576
|
});
|
|
747
577
|
|
|
748
|
-
it("should
|
|
749
|
-
const query = await Recipe.
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
expect(
|
|
578
|
+
it("should inject SPARQL FILTER for between operator", async () => {
|
|
579
|
+
const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { rating: { between: [1, 10] } } });
|
|
580
|
+
const norm = normalizeQuery(query);
|
|
581
|
+
expect(norm).toContain("SELECT ?source");
|
|
582
|
+
// between is now handled via JS post-filter
|
|
583
|
+
expect(norm).toContain("wTarget_cmp_rating");
|
|
754
584
|
});
|
|
755
585
|
|
|
756
|
-
it("should
|
|
757
|
-
const query = await Recipe.
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
expect(
|
|
586
|
+
it("should inject SPARQL FILTER for contains operator", async () => {
|
|
587
|
+
const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { name: { contains: "pasta" } } });
|
|
588
|
+
const norm = normalizeQuery(query);
|
|
589
|
+
expect(norm).toContain("SELECT ?source");
|
|
590
|
+
// contains is now handled via JS post-filter
|
|
591
|
+
expect(norm).toContain("wTarget_cmp_name");
|
|
762
592
|
});
|
|
763
593
|
|
|
764
|
-
|
|
765
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, {
|
|
766
|
-
where: {
|
|
767
|
-
author: "did:key:alice",
|
|
768
|
-
timestamp: { gt: 1000 }
|
|
769
|
-
}
|
|
770
|
-
});
|
|
771
|
-
|
|
772
|
-
// author and timestamp filtering is done in JavaScript post-query
|
|
773
|
-
expect(query).toContain("FROM node");
|
|
774
|
-
expect(query).not.toContain("author = 'did:key:alice'");
|
|
775
|
-
expect(query).not.toContain("timestamp > 1000");
|
|
776
|
-
});
|
|
594
|
+
// ---- Multiple property filters combined ----
|
|
777
595
|
|
|
778
|
-
it("should
|
|
779
|
-
const query = await Recipe.
|
|
780
|
-
where: {
|
|
781
|
-
name: "Pasta",
|
|
782
|
-
author: "did:key:alice",
|
|
783
|
-
rating: { gt: 4 }
|
|
784
|
-
}
|
|
596
|
+
it("should combine multiple property equality filters with &&", async () => {
|
|
597
|
+
const query = await (Recipe as any).queryToSPARQL(mockPerspective, {
|
|
598
|
+
where: { name: "Pasta", rating: ["4", "5"] }
|
|
785
599
|
});
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
expect(
|
|
790
|
-
|
|
791
|
-
expect(normalized).not.toContain("out.uri > 4");
|
|
792
|
-
expect(normalized).not.toContain("target > 4");
|
|
793
|
-
// author filtering is done in JavaScript post-query
|
|
794
|
-
expect(normalized).not.toContain("author = 'did:key:alice'");
|
|
795
|
-
});
|
|
796
|
-
|
|
797
|
-
it("should handle boolean values", async () => {
|
|
798
|
-
@Model({ name: "Task" })
|
|
799
|
-
class Task extends Ad4mModel {
|
|
800
|
-
@Property({ through: "task://completed" })
|
|
801
|
-
completed: boolean = false;
|
|
802
|
-
}
|
|
803
|
-
|
|
804
|
-
const query = await Task.queryToSurrealQL(mockPerspective, { where: { completed: true } });
|
|
805
|
-
|
|
806
|
-
expect(query).toContain("fn::parse_literal(out.uri) = true");
|
|
807
|
-
});
|
|
808
|
-
|
|
809
|
-
it("should handle array of numbers", async () => {
|
|
810
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: [4, 5] } });
|
|
811
|
-
|
|
812
|
-
expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating' AND fn::parse_literal(out.uri) IN [4, 5]]) > 0");
|
|
813
|
-
});
|
|
814
|
-
|
|
815
|
-
it("should skip unknown properties in where clause", async () => {
|
|
816
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { unknownProp: "value" } as any });
|
|
817
|
-
|
|
818
|
-
// Should not throw error, just skip the unknown property
|
|
819
|
-
expect(query).toContain("source");
|
|
820
|
-
|
|
821
|
-
// Should not contain any condition for unknownProp
|
|
822
|
-
expect(query).not.toContain("unknownProp");
|
|
823
|
-
});
|
|
824
|
-
|
|
825
|
-
it.skip("should skip unknown properties in select clause", async () => {
|
|
826
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: ["name", "unknownProp"] as any });
|
|
827
|
-
|
|
828
|
-
// Should include name using aggregation
|
|
829
|
-
expect(query).toContain("array::first(target[WHERE predicate = 'recipe://name']) AS name");
|
|
830
|
-
// Should not error on unknownProp, just skip it
|
|
831
|
-
expect(query).not.toContain("unknownProp");
|
|
600
|
+
const norm = normalizeQuery(query);
|
|
601
|
+
// Should have EXISTS blocks for both name and rating
|
|
602
|
+
expect(norm).toContain("recipe://name");
|
|
603
|
+
expect(norm).toContain("recipe://rating");
|
|
604
|
+
expect(norm).toContain("&&");
|
|
832
605
|
});
|
|
833
606
|
|
|
834
|
-
|
|
835
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { order: { name: "ASC" } });
|
|
607
|
+
// ---- ORDER BY, LIMIT, OFFSET are JS post-processed ----
|
|
836
608
|
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
expect(query).toContain("->link AS links");
|
|
847
|
-
|
|
609
|
+
it("should include ORDER BY/LIMIT/OFFSET in SPARQL pagination subquery", async () => {
|
|
610
|
+
const query = await (Recipe as any).queryToSPARQL(mockPerspective, { order: { name: "ASC" }, limit: 10, offset: 5 });
|
|
611
|
+
const norm = normalizeQuery(query);
|
|
612
|
+
expect(norm).toContain("SELECT ?source");
|
|
613
|
+
// SPARQL-level pagination via subquery
|
|
614
|
+
expect(norm).toContain("ORDER BY");
|
|
615
|
+
expect(norm).toContain("LIMIT 10");
|
|
616
|
+
expect(norm).toContain("OFFSET 5");
|
|
617
|
+
expect(norm).toContain("SELECT DISTINCT ?source");
|
|
848
618
|
});
|
|
849
619
|
});
|
|
850
|
-
|
|
851
|
-
describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", () => {
|
|
620
|
+
describe("Ad4mModel.instancesFromQueryResult() and SPARQL integration", () => {
|
|
852
621
|
// Test Recipe model
|
|
853
622
|
@Model({ name: "Recipe" })
|
|
854
623
|
class Recipe extends Ad4mModel {
|
|
@@ -862,9 +631,9 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
|
|
|
862
631
|
ingredients: string[] = [];
|
|
863
632
|
}
|
|
864
633
|
|
|
865
|
-
// Mock perspective with both
|
|
634
|
+
// Mock perspective with both querySparql and infer methods
|
|
866
635
|
const mockPerspective = {
|
|
867
|
-
|
|
636
|
+
querySparql: jest.fn(),
|
|
868
637
|
infer: jest.fn(),
|
|
869
638
|
uuid: 'test-perspective-uuid',
|
|
870
639
|
stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue('Recipe')
|
|
@@ -874,18 +643,18 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
|
|
|
874
643
|
jest.clearAllMocks();
|
|
875
644
|
});
|
|
876
645
|
|
|
877
|
-
it("should convert empty
|
|
878
|
-
const result = await Recipe.
|
|
646
|
+
it("should convert empty query results correctly", async () => {
|
|
647
|
+
const result = await Recipe.instancesFromQueryResult(mockPerspective, {}, []);
|
|
879
648
|
|
|
880
649
|
expect(result.results).toEqual([]);
|
|
881
650
|
expect(result.totalCount).toBe(0);
|
|
882
651
|
});
|
|
883
652
|
|
|
884
|
-
it("should convert
|
|
885
|
-
const
|
|
653
|
+
it("should convert query results to model instances", async () => {
|
|
654
|
+
const queryResults = [
|
|
886
655
|
{
|
|
887
656
|
source: "node:abc123",
|
|
888
|
-
source_uri: "literal
|
|
657
|
+
source_uri: "literal:recipe1",
|
|
889
658
|
links: [
|
|
890
659
|
{ predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
891
660
|
{ predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
@@ -896,7 +665,7 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
|
|
|
896
665
|
},
|
|
897
666
|
{
|
|
898
667
|
source: "node:def456",
|
|
899
|
-
source_uri: "literal
|
|
668
|
+
source_uri: "literal:recipe2",
|
|
900
669
|
links: [
|
|
901
670
|
{ predicate: "recipe://name", target: "Pizza", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
|
|
902
671
|
{ predicate: "recipe://rating", target: "4", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
|
|
@@ -907,7 +676,7 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
|
|
|
907
676
|
}
|
|
908
677
|
];
|
|
909
678
|
|
|
910
|
-
const result = await Recipe.
|
|
679
|
+
const result = await Recipe.instancesFromQueryResult(mockPerspective, {}, queryResults);
|
|
911
680
|
|
|
912
681
|
expect(result.results).toHaveLength(2);
|
|
913
682
|
expect(result.totalCount).toBe(2);
|
|
@@ -925,10 +694,10 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
|
|
|
925
694
|
});
|
|
926
695
|
|
|
927
696
|
it("should filter properties when query specifies properties", async () => {
|
|
928
|
-
const
|
|
697
|
+
const queryResults = [
|
|
929
698
|
{
|
|
930
699
|
source: "node:abc123",
|
|
931
|
-
source_uri: "literal
|
|
700
|
+
source_uri: "literal:recipe1",
|
|
932
701
|
links: [
|
|
933
702
|
{ predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
934
703
|
{ predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
@@ -938,10 +707,10 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
|
|
|
938
707
|
}
|
|
939
708
|
];
|
|
940
709
|
|
|
941
|
-
const result = await Recipe.
|
|
710
|
+
const result = await Recipe.instancesFromQueryResult(
|
|
942
711
|
mockPerspective,
|
|
943
712
|
{ properties: ["name"] },
|
|
944
|
-
|
|
713
|
+
queryResults
|
|
945
714
|
);
|
|
946
715
|
|
|
947
716
|
expect(result.results).toHaveLength(1);
|
|
@@ -956,10 +725,10 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
|
|
|
956
725
|
});
|
|
957
726
|
|
|
958
727
|
it("should filter properties when query specifies properties", async () => {
|
|
959
|
-
const
|
|
728
|
+
const queryResults = [
|
|
960
729
|
{
|
|
961
730
|
source: "node:abc123",
|
|
962
|
-
source_uri: "literal
|
|
731
|
+
source_uri: "literal:recipe1",
|
|
963
732
|
links: [
|
|
964
733
|
{ predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
965
734
|
{ predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
@@ -969,10 +738,10 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
|
|
|
969
738
|
}
|
|
970
739
|
];
|
|
971
740
|
|
|
972
|
-
const result = await Recipe.
|
|
741
|
+
const result = await Recipe.instancesFromQueryResult(
|
|
973
742
|
mockPerspective,
|
|
974
743
|
{ properties: ["name"] },
|
|
975
|
-
|
|
744
|
+
queryResults
|
|
976
745
|
);
|
|
977
746
|
|
|
978
747
|
expect(result.results).toHaveLength(1);
|
|
@@ -983,7 +752,7 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
|
|
|
983
752
|
});
|
|
984
753
|
|
|
985
754
|
it("should handle results missing base field", async () => {
|
|
986
|
-
const
|
|
755
|
+
const queryResults = [
|
|
987
756
|
{
|
|
988
757
|
links: [
|
|
989
758
|
{ predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
@@ -993,40 +762,35 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
|
|
|
993
762
|
} as any
|
|
994
763
|
];
|
|
995
764
|
|
|
996
|
-
const result = await Recipe.
|
|
765
|
+
const result = await Recipe.instancesFromQueryResult(mockPerspective, {}, queryResults);
|
|
997
766
|
|
|
998
767
|
// Should filter out the invalid result (or handle gracefully)
|
|
999
768
|
expect(result.results).toHaveLength(0);
|
|
1000
769
|
expect(result.totalCount).toBe(0);
|
|
1001
770
|
});
|
|
1002
771
|
|
|
1003
|
-
it("should use
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
{ predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
1010
|
-
{ predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
1011
|
-
{ predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
1012
|
-
]
|
|
1013
|
-
}
|
|
772
|
+
it("should use SPARQL when engine is 'sparql' in findAll()", async () => {
|
|
773
|
+
// Raw SPARQL rows (flat) — groupSPARQLResults will group them
|
|
774
|
+
const queryResults = [
|
|
775
|
+
{ source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
776
|
+
{ source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
777
|
+
{ source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
1014
778
|
];
|
|
1015
779
|
|
|
1016
|
-
mockPerspective.
|
|
780
|
+
mockPerspective.querySparql.mockResolvedValue(queryResults);
|
|
1017
781
|
|
|
1018
|
-
const results = await Recipe.findAll(mockPerspective, {});
|
|
782
|
+
const results = await Recipe.findAll(mockPerspective, {}, 'sparql');
|
|
1019
783
|
|
|
1020
|
-
expect(mockPerspective.
|
|
784
|
+
expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
|
|
1021
785
|
expect(mockPerspective.infer).not.toHaveBeenCalled();
|
|
1022
786
|
expect(results).toHaveLength(1);
|
|
1023
787
|
expect(results[0].name).toBe("Pasta");
|
|
1024
788
|
});
|
|
1025
789
|
|
|
1026
|
-
it("should use Prolog when
|
|
790
|
+
it("should use Prolog when engine is prolog in findAll()", async () => {
|
|
1027
791
|
const prologResults = [{
|
|
1028
792
|
AllInstances: [
|
|
1029
|
-
["literal
|
|
793
|
+
["literal:recipe1", [["name", "Pasta"]], [["ingredients", ["pasta"]]], "2023-01-01T00:00:00Z", "did:key:alice"]
|
|
1030
794
|
],
|
|
1031
795
|
TotalCount: 1
|
|
1032
796
|
}];
|
|
@@ -1036,118 +800,97 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
|
|
|
1036
800
|
const results = await Recipe.findAll(mockPerspective, {}, false);
|
|
1037
801
|
|
|
1038
802
|
expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
|
|
1039
|
-
expect(mockPerspective.
|
|
803
|
+
expect(mockPerspective.querySparql).not.toHaveBeenCalled();
|
|
1040
804
|
expect(results).toHaveLength(1);
|
|
1041
805
|
});
|
|
1042
806
|
|
|
1043
|
-
it("should use
|
|
1044
|
-
const
|
|
1045
|
-
{
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
links: [
|
|
1049
|
-
{ predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
1050
|
-
{ predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
1051
|
-
{ predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
1052
|
-
]
|
|
1053
|
-
}
|
|
807
|
+
it("should use SPARQL when engine is 'sparql' in findAllAndCount()", async () => {
|
|
808
|
+
const queryResults = [
|
|
809
|
+
{ source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
810
|
+
{ source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
811
|
+
{ source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
1054
812
|
];
|
|
1055
813
|
|
|
1056
|
-
mockPerspective.
|
|
814
|
+
mockPerspective.querySparql.mockResolvedValue(queryResults);
|
|
1057
815
|
|
|
1058
|
-
const { results, totalCount } = await Recipe.findAllAndCount(mockPerspective, {});
|
|
816
|
+
const { results, totalCount } = await Recipe.findAllAndCount(mockPerspective, {}, 'sparql');
|
|
1059
817
|
|
|
1060
|
-
expect(mockPerspective.
|
|
818
|
+
expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
|
|
1061
819
|
expect(mockPerspective.infer).not.toHaveBeenCalled();
|
|
1062
820
|
expect(results).toHaveLength(1);
|
|
1063
821
|
expect(totalCount).toBe(1);
|
|
1064
822
|
});
|
|
1065
823
|
|
|
1066
|
-
it("should use
|
|
1067
|
-
const
|
|
1068
|
-
{
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
links: [
|
|
1072
|
-
{ predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
1073
|
-
{ predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
1074
|
-
{ predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
1075
|
-
]
|
|
1076
|
-
}
|
|
824
|
+
it("should use SPARQL when engine is 'sparql' in paginate()", async () => {
|
|
825
|
+
const queryResults = [
|
|
826
|
+
{ source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
827
|
+
{ source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
828
|
+
{ source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
1077
829
|
];
|
|
1078
830
|
|
|
1079
|
-
|
|
831
|
+
// First call returns data, second call returns count (for SPARQL-paginated totalCount)
|
|
832
|
+
mockPerspective.querySparql
|
|
833
|
+
.mockResolvedValueOnce(queryResults)
|
|
834
|
+
.mockResolvedValueOnce([{ count: 1 }]);
|
|
1080
835
|
|
|
1081
|
-
|
|
836
|
+
// Include order to trigger SPARQL-level pagination (data + count queries)
|
|
837
|
+
const page = await Recipe.paginate(mockPerspective, 10, 1, { order: { name: 'ASC' as const } }, 'sparql');
|
|
1082
838
|
|
|
1083
|
-
|
|
839
|
+
// paginate now issues 2 SPARQL queries: data + count
|
|
840
|
+
expect(mockPerspective.querySparql).toHaveBeenCalledTimes(2);
|
|
1084
841
|
expect(mockPerspective.infer).not.toHaveBeenCalled();
|
|
1085
842
|
expect(page.results).toHaveLength(1);
|
|
1086
843
|
expect(page.pageSize).toBe(10);
|
|
1087
844
|
expect(page.pageNumber).toBe(1);
|
|
845
|
+
expect(page.totalCount).toBe(1);
|
|
1088
846
|
});
|
|
1089
847
|
|
|
1090
|
-
it("should use
|
|
1091
|
-
//
|
|
1092
|
-
|
|
1093
|
-
const surrealResults = Array.from({ length: 5 }, (_, i) => ({
|
|
1094
|
-
source: `node:abc${i+1}`,
|
|
1095
|
-
source_uri: `literal://recipe${i+1}`,
|
|
1096
|
-
links: [
|
|
1097
|
-
{ predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
1098
|
-
{ predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
1099
|
-
]
|
|
1100
|
-
}));
|
|
1101
|
-
|
|
1102
|
-
mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
|
|
848
|
+
it("should use SPARQL when engine is 'sparql' in count()", async () => {
|
|
849
|
+
// count() now uses an efficient COUNT query that returns [{ count: N }]
|
|
850
|
+
mockPerspective.querySparql.mockResolvedValue([{ count: 5 }]);
|
|
1103
851
|
|
|
1104
|
-
const count = await Recipe.count(mockPerspective, {});
|
|
852
|
+
const count = await Recipe.count(mockPerspective, {}, 'sparql');
|
|
1105
853
|
|
|
1106
|
-
expect(mockPerspective.
|
|
854
|
+
expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
|
|
1107
855
|
expect(mockPerspective.infer).not.toHaveBeenCalled();
|
|
1108
856
|
expect(count).toBe(5);
|
|
1109
857
|
});
|
|
1110
858
|
|
|
1111
|
-
it("should use Prolog when
|
|
859
|
+
it("should use Prolog when engine is prolog in count()", async () => {
|
|
1112
860
|
const prologResults = [{ TotalCount: 10 }];
|
|
1113
861
|
mockPerspective.infer.mockResolvedValue(prologResults);
|
|
1114
862
|
|
|
1115
863
|
const count = await Recipe.count(mockPerspective, {}, false);
|
|
1116
864
|
|
|
1117
865
|
expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
|
|
1118
|
-
expect(mockPerspective.
|
|
866
|
+
expect(mockPerspective.querySparql).not.toHaveBeenCalled();
|
|
1119
867
|
expect(count).toBe(10);
|
|
1120
868
|
});
|
|
1121
869
|
|
|
1122
|
-
it("should use
|
|
1123
|
-
const
|
|
1124
|
-
{
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
links: [
|
|
1128
|
-
{ predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
1129
|
-
{ predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
1130
|
-
{ predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
1131
|
-
]
|
|
1132
|
-
}
|
|
870
|
+
it("should use SPARQL when engine is 'sparql' in ModelQueryBuilder.get()", async () => {
|
|
871
|
+
const queryResults = [
|
|
872
|
+
{ source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
873
|
+
{ source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
874
|
+
{ source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
1133
875
|
];
|
|
1134
876
|
|
|
1135
|
-
mockPerspective.
|
|
877
|
+
mockPerspective.querySparql.mockResolvedValue(queryResults);
|
|
1136
878
|
|
|
1137
879
|
const results = await Recipe.query(mockPerspective)
|
|
1138
880
|
.where({ name: "Pasta" })
|
|
881
|
+
.engine('sparql')
|
|
1139
882
|
.get();
|
|
1140
883
|
|
|
1141
|
-
expect(mockPerspective.
|
|
884
|
+
expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
|
|
1142
885
|
expect(mockPerspective.infer).not.toHaveBeenCalled();
|
|
1143
886
|
expect(results).toHaveLength(1);
|
|
1144
887
|
expect(results[0].name).toBe("Pasta");
|
|
1145
888
|
});
|
|
1146
889
|
|
|
1147
|
-
it("should use Prolog when
|
|
890
|
+
it("should use Prolog when.engine('prolog') in ModelQueryBuilder.get()", async () => {
|
|
1148
891
|
const prologResults = [{
|
|
1149
892
|
AllInstances: [
|
|
1150
|
-
["literal
|
|
893
|
+
["literal:recipe1", [["name", "Pasta"]], [["ingredients", ["pasta"]]], "2023-01-01T00:00:00Z", "did:key:alice"]
|
|
1151
894
|
],
|
|
1152
895
|
TotalCount: 1
|
|
1153
896
|
}];
|
|
@@ -1156,55 +899,49 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
|
|
|
1156
899
|
|
|
1157
900
|
const results = await Recipe.query(mockPerspective)
|
|
1158
901
|
.where({ name: "Pasta" })
|
|
1159
|
-
.
|
|
902
|
+
.engine('prolog')
|
|
1160
903
|
.get();
|
|
1161
904
|
|
|
1162
905
|
expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
|
|
1163
|
-
expect(mockPerspective.
|
|
906
|
+
expect(mockPerspective.querySparql).not.toHaveBeenCalled();
|
|
1164
907
|
expect(results).toHaveLength(1);
|
|
1165
908
|
});
|
|
1166
909
|
|
|
1167
|
-
it("should use
|
|
910
|
+
it("should use SPARQL when engine is 'sparql' in ModelQueryBuilder.count()", async () => {
|
|
1168
911
|
// count() counts the number of rows returned by the query (one row per source)
|
|
1169
|
-
const
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
}));
|
|
1177
|
-
mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
|
|
912
|
+
const queryResults = [
|
|
913
|
+
...Array.from({ length: 3 }, (_, i) => [
|
|
914
|
+
{ source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
915
|
+
{ source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
916
|
+
]).flat()
|
|
917
|
+
];
|
|
918
|
+
mockPerspective.querySparql.mockResolvedValue(queryResults);
|
|
1178
919
|
|
|
1179
920
|
const count = await Recipe.query(mockPerspective)
|
|
1180
921
|
.where({ rating: { gt: 4 } })
|
|
922
|
+
.engine('sparql')
|
|
1181
923
|
.count();
|
|
1182
924
|
|
|
1183
|
-
expect(mockPerspective.
|
|
925
|
+
expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
|
|
1184
926
|
expect(mockPerspective.infer).not.toHaveBeenCalled();
|
|
1185
927
|
expect(count).toBe(3);
|
|
1186
928
|
});
|
|
1187
929
|
|
|
1188
|
-
it("should use
|
|
1189
|
-
const
|
|
1190
|
-
{
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
links: [
|
|
1194
|
-
{ predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
1195
|
-
{ predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
1196
|
-
{ predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
1197
|
-
]
|
|
1198
|
-
}
|
|
930
|
+
it("should use SPARQL when engine is 'sparql' in ModelQueryBuilder.paginate()", async () => {
|
|
931
|
+
const queryResults = [
|
|
932
|
+
{ source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
933
|
+
{ source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
934
|
+
{ source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
1199
935
|
];
|
|
1200
936
|
|
|
1201
|
-
mockPerspective.
|
|
937
|
+
mockPerspective.querySparql.mockResolvedValue(queryResults);
|
|
1202
938
|
|
|
1203
939
|
const page = await Recipe.query(mockPerspective)
|
|
1204
940
|
.where({ rating: { gt: 3 } })
|
|
941
|
+
.engine('sparql')
|
|
1205
942
|
.paginate(10, 1);
|
|
1206
943
|
|
|
1207
|
-
expect(mockPerspective.
|
|
944
|
+
expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
|
|
1208
945
|
expect(mockPerspective.infer).not.toHaveBeenCalled();
|
|
1209
946
|
expect(page.results).toHaveLength(1);
|
|
1210
947
|
expect(page.pageSize).toBe(10);
|
|
@@ -1228,7 +965,7 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
|
|
|
1228
965
|
|
|
1229
966
|
// Mock perspective
|
|
1230
967
|
const mockPerspective = {
|
|
1231
|
-
|
|
968
|
+
querySparql: jest.fn(),
|
|
1232
969
|
infer: jest.fn(),
|
|
1233
970
|
uuid: 'test-perspective-uuid',
|
|
1234
971
|
stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue('Recipe')
|
|
@@ -1238,159 +975,143 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
|
|
|
1238
975
|
jest.clearAllMocks();
|
|
1239
976
|
});
|
|
1240
977
|
|
|
1241
|
-
it("should apply JS-level filtering for gt operator on properties in
|
|
1242
|
-
// Mock
|
|
1243
|
-
const
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
]
|
|
1250
|
-
}));
|
|
978
|
+
it("should apply JS-level filtering for gt operator on properties in SPARQL count()", async () => {
|
|
979
|
+
// Mock query results: 5 recipes with ratings 1, 2, 3, 4, 5
|
|
980
|
+
const queryResults = [
|
|
981
|
+
...Array.from({ length: 5 }, (_, i) => [
|
|
982
|
+
{ source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
983
|
+
{ source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
984
|
+
]).flat()
|
|
985
|
+
];
|
|
1251
986
|
|
|
1252
|
-
mockPerspective.
|
|
987
|
+
mockPerspective.querySparql.mockResolvedValue(queryResults);
|
|
1253
988
|
|
|
1254
989
|
// Count recipes with rating > 3 (should match 2 recipes: rating 4 and 5)
|
|
1255
|
-
const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } });
|
|
990
|
+
const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } }, 'sparql');
|
|
1256
991
|
|
|
1257
992
|
// Verify count matches the number of instances that would be returned by findAll
|
|
1258
|
-
const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { gt: 3 } } });
|
|
993
|
+
const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { gt: 3 } } }, 'sparql');
|
|
1259
994
|
|
|
1260
995
|
expect(count).toBe(2);
|
|
1261
996
|
expect(count).toBe(findAllResults.length);
|
|
1262
997
|
});
|
|
1263
998
|
|
|
1264
|
-
it("should apply JS-level filtering for between operator on properties in
|
|
1265
|
-
// Mock
|
|
1266
|
-
const
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
]
|
|
1273
|
-
}));
|
|
999
|
+
it("should apply JS-level filtering for between operator on properties in SPARQL count()", async () => {
|
|
1000
|
+
// Mock query results: 5 recipes with ratings 1, 2, 3, 4, 5
|
|
1001
|
+
const queryResults = [
|
|
1002
|
+
...Array.from({ length: 5 }, (_, i) => [
|
|
1003
|
+
{ source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
1004
|
+
{ source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
1005
|
+
]).flat()
|
|
1006
|
+
];
|
|
1274
1007
|
|
|
1275
|
-
mockPerspective.
|
|
1008
|
+
mockPerspective.querySparql.mockResolvedValue(queryResults);
|
|
1276
1009
|
|
|
1277
1010
|
// Count recipes with rating between 2 and 4 (should match 3 recipes: rating 2, 3, 4)
|
|
1278
|
-
const count = await Recipe.count(mockPerspective, { where: { rating: { between: [2, 4] } } });
|
|
1011
|
+
const count = await Recipe.count(mockPerspective, { where: { rating: { between: [2, 4] } } }, 'sparql');
|
|
1279
1012
|
|
|
1280
1013
|
// Verify count matches the number of instances that would be returned by findAll
|
|
1281
|
-
const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { between: [2, 4] } } });
|
|
1014
|
+
const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { between: [2, 4] } } }, 'sparql');
|
|
1282
1015
|
|
|
1283
1016
|
expect(count).toBe(3);
|
|
1284
1017
|
expect(count).toBe(findAllResults.length);
|
|
1285
1018
|
});
|
|
1286
1019
|
|
|
1287
|
-
it("should apply JS-level filtering for timestamp gt operator in
|
|
1288
|
-
// Mock
|
|
1289
|
-
const
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
]
|
|
1296
|
-
}));
|
|
1020
|
+
it("should apply JS-level filtering for timestamp gt operator in SPARQL count()", async () => {
|
|
1021
|
+
// Mock query results: 5 recipes with different timestamps
|
|
1022
|
+
const queryResults = [
|
|
1023
|
+
...Array.from({ length: 5 }, (_, i) => [
|
|
1024
|
+
{ source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
|
|
1025
|
+
{ source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
|
|
1026
|
+
]).flat()
|
|
1027
|
+
];
|
|
1297
1028
|
|
|
1298
|
-
mockPerspective.
|
|
1029
|
+
mockPerspective.querySparql.mockResolvedValue(queryResults);
|
|
1299
1030
|
|
|
1300
1031
|
// Count recipes with timestamp > 2023-01-03 (should match 2 recipes: 2023-01-04 and 2023-01-05)
|
|
1301
1032
|
const targetTimestamp = new Date("2023-01-03T00:00:00Z").getTime();
|
|
1302
|
-
const count = await Recipe.count(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } });
|
|
1033
|
+
const count = await Recipe.count(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } }, 'sparql');
|
|
1303
1034
|
|
|
1304
1035
|
// Verify count matches the number of instances that would be returned by findAll
|
|
1305
|
-
const findAllResults = await Recipe.findAll(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } });
|
|
1036
|
+
const findAllResults = await Recipe.findAll(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } }, 'sparql');
|
|
1306
1037
|
|
|
1307
1038
|
expect(count).toBe(2);
|
|
1308
1039
|
expect(count).toBe(findAllResults.length);
|
|
1309
1040
|
});
|
|
1310
1041
|
|
|
1311
|
-
it("should apply JS-level filtering for timestamp between operator in
|
|
1312
|
-
// Mock
|
|
1313
|
-
const
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
]
|
|
1320
|
-
}));
|
|
1042
|
+
it("should apply JS-level filtering for timestamp between operator in SPARQL count()", async () => {
|
|
1043
|
+
// Mock query results: 5 recipes with different timestamps
|
|
1044
|
+
const queryResults = [
|
|
1045
|
+
...Array.from({ length: 5 }, (_, i) => [
|
|
1046
|
+
{ source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
|
|
1047
|
+
{ source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
|
|
1048
|
+
]).flat()
|
|
1049
|
+
];
|
|
1321
1050
|
|
|
1322
|
-
mockPerspective.
|
|
1051
|
+
mockPerspective.querySparql.mockResolvedValue(queryResults);
|
|
1323
1052
|
|
|
1324
1053
|
// Count recipes with timestamp between 2023-01-02 and 2023-01-04
|
|
1325
1054
|
const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
|
|
1326
1055
|
const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
|
|
1327
1056
|
const count = await Recipe.count(mockPerspective, {
|
|
1328
1057
|
where: { timestamp: { between: [startTimestamp, endTimestamp] } }
|
|
1329
|
-
});
|
|
1058
|
+
}, 'sparql');
|
|
1330
1059
|
|
|
1331
1060
|
// Verify count matches the number of instances that would be returned by findAll
|
|
1332
1061
|
const findAllResults = await Recipe.findAll(mockPerspective, {
|
|
1333
1062
|
where: { timestamp: { between: [startTimestamp, endTimestamp] } }
|
|
1334
|
-
});
|
|
1063
|
+
}, 'sparql');
|
|
1335
1064
|
|
|
1336
1065
|
expect(count).toBe(3);
|
|
1337
1066
|
expect(count).toBe(findAllResults.length);
|
|
1338
1067
|
});
|
|
1339
1068
|
|
|
1340
|
-
it("should apply JS-level filtering for author filtering in
|
|
1341
|
-
// Mock
|
|
1342
|
-
const
|
|
1343
|
-
...Array.from({ length: 3 }, (_, i) =>
|
|
1344
|
-
source: `
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
...Array.from({ length: 2 }, (_, i) => ({
|
|
1352
|
-
source: `node:def${i+4}`,
|
|
1353
|
-
source_uri: `literal://recipe${i+4}`,
|
|
1354
|
-
links: [
|
|
1355
|
-
{ predicate: "recipe://name", target: `Recipe ${i+4}`, author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
|
|
1356
|
-
{ predicate: "recipe://rating", target: "5", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" }
|
|
1357
|
-
]
|
|
1358
|
-
}))
|
|
1069
|
+
it("should apply JS-level filtering for author filtering in SPARQL count()", async () => {
|
|
1070
|
+
// Mock query results: 3 recipes by Alice and 2 by Bob
|
|
1071
|
+
const queryResults = [
|
|
1072
|
+
...Array.from({ length: 3 }, (_, i) => [
|
|
1073
|
+
{ source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
1074
|
+
{ source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
1075
|
+
]).flat(),
|
|
1076
|
+
...Array.from({ length: 2 }, (_, i) => [
|
|
1077
|
+
{ source: `literal:recipe${i+4}`, predicate: "recipe://name", target: `Recipe ${i+4}`, author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
|
|
1078
|
+
{ source: `literal:recipe${i+4}`, predicate: "recipe://rating", target: "5", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" }
|
|
1079
|
+
]).flat()
|
|
1359
1080
|
];
|
|
1360
1081
|
|
|
1361
|
-
mockPerspective.
|
|
1082
|
+
mockPerspective.querySparql.mockResolvedValue(queryResults);
|
|
1362
1083
|
|
|
1363
1084
|
// Count recipes by Alice (should match 3 recipes)
|
|
1364
|
-
const count = await Recipe.count(mockPerspective, { where: { author: "did:key:alice" } });
|
|
1085
|
+
const count = await Recipe.count(mockPerspective, { where: { author: "did:key:alice" } }, 'sparql');
|
|
1365
1086
|
|
|
1366
1087
|
// Verify count matches the number of instances that would be returned by findAll
|
|
1367
|
-
const findAllResults = await Recipe.findAll(mockPerspective, { where: { author: "did:key:alice" } });
|
|
1088
|
+
const findAllResults = await Recipe.findAll(mockPerspective, { where: { author: "did:key:alice" } }, 'sparql');
|
|
1368
1089
|
|
|
1369
1090
|
expect(count).toBe(3);
|
|
1370
1091
|
expect(count).toBe(findAllResults.length);
|
|
1371
1092
|
});
|
|
1372
1093
|
|
|
1373
1094
|
it("should apply JS-level filtering in ModelQueryBuilder.count() with gt operator", async () => {
|
|
1374
|
-
// Mock
|
|
1375
|
-
const
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
]
|
|
1382
|
-
}));
|
|
1095
|
+
// Mock query results: 5 recipes with ratings 1, 2, 3, 4, 5
|
|
1096
|
+
const queryResults = [
|
|
1097
|
+
...Array.from({ length: 5 }, (_, i) => [
|
|
1098
|
+
{ source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
1099
|
+
{ source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
1100
|
+
]).flat()
|
|
1101
|
+
];
|
|
1383
1102
|
|
|
1384
|
-
mockPerspective.
|
|
1103
|
+
mockPerspective.querySparql.mockResolvedValue(queryResults);
|
|
1385
1104
|
|
|
1386
1105
|
// Count recipes with rating > 3 using ModelQueryBuilder
|
|
1387
1106
|
const count = await Recipe.query(mockPerspective)
|
|
1388
1107
|
.where({ rating: { gt: 3 } })
|
|
1108
|
+
.engine('sparql')
|
|
1389
1109
|
.count();
|
|
1390
1110
|
|
|
1391
1111
|
// Verify count matches the number of instances that would be returned by get()
|
|
1392
1112
|
const getResults = await Recipe.query(mockPerspective)
|
|
1393
1113
|
.where({ rating: { gt: 3 } })
|
|
1114
|
+
.engine('sparql')
|
|
1394
1115
|
.get();
|
|
1395
1116
|
|
|
1396
1117
|
expect(count).toBe(2);
|
|
@@ -1398,17 +1119,15 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
|
|
|
1398
1119
|
});
|
|
1399
1120
|
|
|
1400
1121
|
it("should apply JS-level filtering in ModelQueryBuilder.count() with timestamp between", async () => {
|
|
1401
|
-
// Mock
|
|
1402
|
-
const
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
]
|
|
1409
|
-
}));
|
|
1122
|
+
// Mock query results: 5 recipes with different timestamps
|
|
1123
|
+
const queryResults = [
|
|
1124
|
+
...Array.from({ length: 5 }, (_, i) => [
|
|
1125
|
+
{ source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
|
|
1126
|
+
{ source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
|
|
1127
|
+
]).flat()
|
|
1128
|
+
];
|
|
1410
1129
|
|
|
1411
|
-
mockPerspective.
|
|
1130
|
+
mockPerspective.querySparql.mockResolvedValue(queryResults);
|
|
1412
1131
|
|
|
1413
1132
|
const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
|
|
1414
1133
|
const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
|
|
@@ -1416,11 +1135,13 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
|
|
|
1416
1135
|
// Count using ModelQueryBuilder
|
|
1417
1136
|
const count = await Recipe.query(mockPerspective)
|
|
1418
1137
|
.where({ timestamp: { between: [startTimestamp, endTimestamp] } })
|
|
1138
|
+
.engine('sparql')
|
|
1419
1139
|
.count();
|
|
1420
1140
|
|
|
1421
1141
|
// Verify count matches the number of instances that would be returned by get()
|
|
1422
1142
|
const getResults = await Recipe.query(mockPerspective)
|
|
1423
1143
|
.where({ timestamp: { between: [startTimestamp, endTimestamp] } })
|
|
1144
|
+
.engine('sparql')
|
|
1424
1145
|
.get();
|
|
1425
1146
|
|
|
1426
1147
|
expect(count).toBe(3);
|
|
@@ -1434,7 +1155,7 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
|
|
|
1434
1155
|
const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } }, false);
|
|
1435
1156
|
|
|
1436
1157
|
expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
|
|
1437
|
-
expect(mockPerspective.
|
|
1158
|
+
expect(mockPerspective.querySparql).not.toHaveBeenCalled();
|
|
1438
1159
|
expect(count).toBe(2);
|
|
1439
1160
|
});
|
|
1440
1161
|
|
|
@@ -1452,8 +1173,1424 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
|
|
|
1452
1173
|
);
|
|
1453
1174
|
|
|
1454
1175
|
expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
|
|
1455
|
-
expect(mockPerspective.
|
|
1176
|
+
expect(mockPerspective.querySparql).not.toHaveBeenCalled();
|
|
1456
1177
|
expect(count).toBe(3);
|
|
1457
1178
|
});
|
|
1458
1179
|
});
|
|
1459
1180
|
|
|
1181
|
+
|
|
1182
|
+
// ──────────────────────────────────────────────────────────
|
|
1183
|
+
// Batch SPARQL query builder tests
|
|
1184
|
+
// ──────────────────────────────────────────────────────────
|
|
1185
|
+
|
|
1186
|
+
import { buildBatchSPARQLQuery } from "./query-sparql-batch";
|
|
1187
|
+
|
|
1188
|
+
describe("buildBatchSPARQLQuery", () => {
|
|
1189
|
+
@Model({ name: "Author" })
|
|
1190
|
+
class Author extends Ad4mModel {
|
|
1191
|
+
@Property({ through: "author://name", required: true })
|
|
1192
|
+
name!: string;
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
@Model({ name: "Book" })
|
|
1196
|
+
class Book extends Ad4mModel {
|
|
1197
|
+
@Property({ through: "book://title", required: true })
|
|
1198
|
+
title!: string;
|
|
1199
|
+
|
|
1200
|
+
@HasMany(() => Author, { through: "book://author" })
|
|
1201
|
+
authors!: Author[];
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
it("should generate UNION branches for depth 0 and depth 1 includes", () => {
|
|
1205
|
+
const metadata = Book.getModelMetadata();
|
|
1206
|
+
const query = { include: { authors: true } };
|
|
1207
|
+
const sparql = buildBatchSPARQLQuery(metadata, query, Book);
|
|
1208
|
+
|
|
1209
|
+
expect(sparql).toContain("?depth");
|
|
1210
|
+
expect(sparql).toContain("?parentBase");
|
|
1211
|
+
expect(sparql).toContain("?relationName");
|
|
1212
|
+
expect(sparql).toContain("UNION");
|
|
1213
|
+
expect(sparql).toContain("BIND(\"0\" AS ?depth)");
|
|
1214
|
+
expect(sparql).toContain("BIND(\"1\" AS ?depth)");
|
|
1215
|
+
expect(sparql).toContain("book://author");
|
|
1216
|
+
});
|
|
1217
|
+
|
|
1218
|
+
it("should include parent filter when query.parent is specified", () => {
|
|
1219
|
+
const metadata = Book.getModelMetadata();
|
|
1220
|
+
const query = {
|
|
1221
|
+
parent: { id: "flux://library1", predicate: "library://books" },
|
|
1222
|
+
include: { authors: true },
|
|
1223
|
+
};
|
|
1224
|
+
const sparql = buildBatchSPARQLQuery(metadata, query, Book);
|
|
1225
|
+
|
|
1226
|
+
expect(sparql).toContain("flux://library1");
|
|
1227
|
+
expect(sparql).toContain("library://books");
|
|
1228
|
+
});
|
|
1229
|
+
|
|
1230
|
+
it("should include where filter for simple equality", () => {
|
|
1231
|
+
const metadata = Book.getModelMetadata();
|
|
1232
|
+
const query = {
|
|
1233
|
+
where: { title: "My Book" },
|
|
1234
|
+
include: { authors: true },
|
|
1235
|
+
};
|
|
1236
|
+
const sparql = buildBatchSPARQLQuery(metadata, query, Book);
|
|
1237
|
+
|
|
1238
|
+
// For literal-stored properties, SPARQL only has a JOIN (no FILTER value) — filtering in JS
|
|
1239
|
+
expect(sparql).toContain("book://title");
|
|
1240
|
+
expect(sparql).toContain("root_wTarget_eq_title");
|
|
1241
|
+
});
|
|
1242
|
+
|
|
1243
|
+
it("should throw when include is empty", () => {
|
|
1244
|
+
const metadata = Book.getModelMetadata();
|
|
1245
|
+
expect(() => buildBatchSPARQLQuery(metadata, {}, Book)).toThrow("requires query.include");
|
|
1246
|
+
});
|
|
1247
|
+
});
|
|
1248
|
+
|
|
1249
|
+
describe("SPARQL comparison filters", () => {
|
|
1250
|
+
@Model({ name: "Item" })
|
|
1251
|
+
class Item extends Ad4mModel {
|
|
1252
|
+
@Property({ through: "item://price", required: true })
|
|
1253
|
+
price!: string;
|
|
1254
|
+
|
|
1255
|
+
@Property({ through: "item://name", required: true })
|
|
1256
|
+
name!: string;
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
it("should generate gt filter", async () => {
|
|
1260
|
+
const mockPersp = { getLinks: jest.fn().mockResolvedValue([]) } as any;
|
|
1261
|
+
const query = await (Item as any).queryToSPARQL(mockPersp, { where: { price: { gt: 10 } } });
|
|
1262
|
+
// gt is now JS post-filter — SPARQL just joins the property
|
|
1263
|
+
expect(query).toContain("item://price");
|
|
1264
|
+
});
|
|
1265
|
+
|
|
1266
|
+
it("should generate between filter", async () => {
|
|
1267
|
+
const mockPersp = { getLinks: jest.fn().mockResolvedValue([]) } as any;
|
|
1268
|
+
const query = await (Item as any).queryToSPARQL(mockPersp, { where: { price: { between: [5, 20] } } });
|
|
1269
|
+
// between is now JS post-filter
|
|
1270
|
+
expect(query).toContain("item://price");
|
|
1271
|
+
});
|
|
1272
|
+
|
|
1273
|
+
it("should generate contains filter", async () => {
|
|
1274
|
+
const mockPersp = { getLinks: jest.fn().mockResolvedValue([]) } as any;
|
|
1275
|
+
const query = await (Item as any).queryToSPARQL(mockPersp, { where: { name: { contains: "widget" } } });
|
|
1276
|
+
// contains is now JS post-filter
|
|
1277
|
+
expect(query).toContain("item://name");
|
|
1278
|
+
});
|
|
1279
|
+
});
|
|
1280
|
+
|
|
1281
|
+
// ──────────────────────────────────────────────────────────
|
|
1282
|
+
// SPARQL Direct Triple Pattern & IRI Tests
|
|
1283
|
+
// ──────────────────────────────────────────────────────────
|
|
1284
|
+
|
|
1285
|
+
import { buildSPARQLQuery, groupSPARQLResults, formatSPARQLValue, buildSPARQLGetDataQuery } from "./query-sparql";
|
|
1286
|
+
|
|
1287
|
+
describe("SPARQL direct triple pattern generation", () => {
|
|
1288
|
+
@Model({ name: "Channel" })
|
|
1289
|
+
class Channel extends Ad4mModel {
|
|
1290
|
+
@Flag({ through: "flux://entry_type", value: "flux://channel" })
|
|
1291
|
+
type: string = "";
|
|
1292
|
+
|
|
1293
|
+
@Property({ through: "flux://name", resolveLanguage: "literal", required: true })
|
|
1294
|
+
name: string = "";
|
|
1295
|
+
|
|
1296
|
+
@Optional({ through: "flux://description" })
|
|
1297
|
+
description: string = "";
|
|
1298
|
+
|
|
1299
|
+
@HasMany({ through: "flux://has_message" })
|
|
1300
|
+
messages: string[] = [];
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
const mockPersp = {} as any;
|
|
1304
|
+
|
|
1305
|
+
it("generates direct triple pattern with ?source ?predicate ?target", async () => {
|
|
1306
|
+
const query = await (Channel as any).queryToSPARQL(mockPersp, {});
|
|
1307
|
+
// Must use direct triple pattern, not link-node reification
|
|
1308
|
+
expect(query).toContain("?source ?predicate ?target");
|
|
1309
|
+
expect(query).not.toContain("rdf:type");
|
|
1310
|
+
expect(query).not.toContain("ad4m:Link");
|
|
1311
|
+
});
|
|
1312
|
+
|
|
1313
|
+
it("generates Flag filter as ?source <predicate> <value>", async () => {
|
|
1314
|
+
const query = await (Channel as any).queryToSPARQL(mockPersp, {});
|
|
1315
|
+
expect(query).toContain("<flux://entry_type>");
|
|
1316
|
+
expect(query).toContain("<flux://channel>");
|
|
1317
|
+
});
|
|
1318
|
+
|
|
1319
|
+
it("generates Property binding as ?source <predicate> ?varName", async () => {
|
|
1320
|
+
const query = await (Channel as any).queryToSPARQL(mockPersp, {});
|
|
1321
|
+
expect(query).toContain("<flux://name>");
|
|
1322
|
+
expect(query).toMatch(/\?source\s+<flux:\/\/name>\s+\?cfTarget_name/);
|
|
1323
|
+
});
|
|
1324
|
+
|
|
1325
|
+
it("uses GRAPH ?linkGraph pattern for author/timestamp", async () => {
|
|
1326
|
+
const query = await (Channel as any).queryToSPARQL(mockPersp, {});
|
|
1327
|
+
expect(query).toContain("GRAPH ?linkGraph { ?source ?predicate ?target . }");
|
|
1328
|
+
expect(query).toContain("?linkGraph <ad4m://ontology/author> ?author");
|
|
1329
|
+
expect(query).toContain("?linkGraph <ad4m://ontology/timestamp> ?timestamp");
|
|
1330
|
+
});
|
|
1331
|
+
|
|
1332
|
+
it("does NOT contain RDF-star BIND(<< >> AS ?ann) pattern", async () => {
|
|
1333
|
+
const query = await (Channel as any).queryToSPARQL(mockPersp, {});
|
|
1334
|
+
expect(query).not.toContain("BIND(<<");
|
|
1335
|
+
expect(query).not.toContain("?ann ");
|
|
1336
|
+
});
|
|
1337
|
+
|
|
1338
|
+
it("uses FILTER(isIRI(?source)) to exclude non-IRI subjects", async () => {
|
|
1339
|
+
const query = await (Channel as any).queryToSPARQL(mockPersp, {});
|
|
1340
|
+
expect(query).toContain("FILTER(isIRI(?source)");
|
|
1341
|
+
});
|
|
1342
|
+
});
|
|
1343
|
+
|
|
1344
|
+
describe("SPARQL IRI formatting", () => {
|
|
1345
|
+
it("wraps AD4M URIs in angle brackets", () => {
|
|
1346
|
+
const query = buildSPARQLGetDataQuery("ad4m://test123");
|
|
1347
|
+
expect(query).toContain("<ad4m://test123>");
|
|
1348
|
+
});
|
|
1349
|
+
|
|
1350
|
+
it("wraps literal: URIs in angle brackets", () => {
|
|
1351
|
+
const query = buildSPARQLGetDataQuery("literal:string:foo");
|
|
1352
|
+
expect(query).toContain("<literal:string:foo>");
|
|
1353
|
+
});
|
|
1354
|
+
|
|
1355
|
+
it("wraps flux:// URIs in angle brackets", () => {
|
|
1356
|
+
const query = buildSPARQLGetDataQuery("flux://has_channel");
|
|
1357
|
+
expect(query).toContain("<flux://has_channel>");
|
|
1358
|
+
});
|
|
1359
|
+
|
|
1360
|
+
it("wraps did:key URIs in angle brackets", () => {
|
|
1361
|
+
const query = buildSPARQLGetDataQuery("did:key:z6MkhaXg");
|
|
1362
|
+
expect(query).toContain("<did:key:z6MkhaXg>");
|
|
1363
|
+
});
|
|
1364
|
+
});
|
|
1365
|
+
|
|
1366
|
+
describe("groupSPARQLResults", () => {
|
|
1367
|
+
it("groups flat rows by source URI", () => {
|
|
1368
|
+
const rows = [
|
|
1369
|
+
{ source: "ad4m://a", predicate: "p1", target: "t1", author: "auth1", timestamp: "ts1" },
|
|
1370
|
+
{ source: "ad4m://a", predicate: "p2", target: "t2", author: "auth1", timestamp: "ts1" },
|
|
1371
|
+
{ source: "ad4m://b", predicate: "p1", target: "t3", author: "auth2", timestamp: "ts2" },
|
|
1372
|
+
];
|
|
1373
|
+
const grouped = groupSPARQLResults(rows);
|
|
1374
|
+
expect(grouped).toHaveLength(2);
|
|
1375
|
+
|
|
1376
|
+
const aGroup = grouped.find(g => g.source_uri === "ad4m://a");
|
|
1377
|
+
expect(aGroup).toBeDefined();
|
|
1378
|
+
expect(aGroup!.links).toHaveLength(2);
|
|
1379
|
+
|
|
1380
|
+
const bGroup = grouped.find(g => g.source_uri === "ad4m://b");
|
|
1381
|
+
expect(bGroup).toBeDefined();
|
|
1382
|
+
expect(bGroup!.links).toHaveLength(1);
|
|
1383
|
+
});
|
|
1384
|
+
|
|
1385
|
+
it("returns empty array for empty input", () => {
|
|
1386
|
+
expect(groupSPARQLResults([])).toEqual([]);
|
|
1387
|
+
});
|
|
1388
|
+
|
|
1389
|
+
it("preserves metadata in grouped links", () => {
|
|
1390
|
+
const rows = [
|
|
1391
|
+
{ source: "x", predicate: "p", target: "t", author: "did:key:z6Mk", timestamp: "2024-01-01T00:00:00Z" },
|
|
1392
|
+
];
|
|
1393
|
+
const grouped = groupSPARQLResults(rows);
|
|
1394
|
+
expect(grouped[0].links[0].author).toBe("did:key:z6Mk");
|
|
1395
|
+
expect(grouped[0].links[0].timestamp).toBe("2024-01-01T00:00:00Z");
|
|
1396
|
+
});
|
|
1397
|
+
});
|
|
1398
|
+
|
|
1399
|
+
describe("formatSPARQLValue", () => {
|
|
1400
|
+
it("wraps strings in double quotes", () => {
|
|
1401
|
+
expect(formatSPARQLValue("hello")).toBe('"hello"');
|
|
1402
|
+
});
|
|
1403
|
+
|
|
1404
|
+
it("escapes special characters", () => {
|
|
1405
|
+
expect(formatSPARQLValue('say "hi"')).toBe('"say \\"hi\\""');
|
|
1406
|
+
});
|
|
1407
|
+
|
|
1408
|
+
it("converts numbers to quoted strings", () => {
|
|
1409
|
+
expect(formatSPARQLValue(42)).toBe('"42"');
|
|
1410
|
+
});
|
|
1411
|
+
});
|
|
1412
|
+
|
|
1413
|
+
// ──────────────────────────────────────────────────────────
|
|
1414
|
+
// Comprehensive SPARQL migration unit tests
|
|
1415
|
+
// ──────────────────────────────────────────────────────────
|
|
1416
|
+
|
|
1417
|
+
import { matchesCondition, hydrateFromLinks } from "./hydration";
|
|
1418
|
+
import { Literal } from "../Literal";
|
|
1419
|
+
|
|
1420
|
+
// Helper: create literal URLs using JSON encoding (which handles all types including booleans)
|
|
1421
|
+
function literalUrl(value: any): string {
|
|
1422
|
+
if (typeof value === 'string') return Literal.from(value).toUrl();
|
|
1423
|
+
// Use JSON encoding for numbers and booleans since Literal.get() doesn't handle boolean: prefix
|
|
1424
|
+
return `literal:json:${encodeURIComponent(JSON.stringify(value))}`;
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
describe("matchesCondition()", () => {
|
|
1428
|
+
// Simple equality
|
|
1429
|
+
it("simple string equality — match", () => {
|
|
1430
|
+
expect(matchesCondition("hello", "hello")).toBe(true);
|
|
1431
|
+
});
|
|
1432
|
+
it("simple string equality — mismatch", () => {
|
|
1433
|
+
expect(matchesCondition("hello", "world")).toBe(false);
|
|
1434
|
+
});
|
|
1435
|
+
it("simple boolean equality — true", () => {
|
|
1436
|
+
expect(matchesCondition(true, true)).toBe(true);
|
|
1437
|
+
});
|
|
1438
|
+
it("simple boolean equality — false", () => {
|
|
1439
|
+
expect(matchesCondition(false, false)).toBe(true);
|
|
1440
|
+
});
|
|
1441
|
+
it("boolean mismatch", () => {
|
|
1442
|
+
expect(matchesCondition(true, false)).toBe(false);
|
|
1443
|
+
});
|
|
1444
|
+
it("simple number equality", () => {
|
|
1445
|
+
expect(matchesCondition(42, 42)).toBe(true);
|
|
1446
|
+
});
|
|
1447
|
+
it("number mismatch", () => {
|
|
1448
|
+
expect(matchesCondition(42, 99)).toBe(false);
|
|
1449
|
+
});
|
|
1450
|
+
|
|
1451
|
+
// Array IN clause
|
|
1452
|
+
it("array IN clause — value present", () => {
|
|
1453
|
+
expect(matchesCondition("a", ["a", "b", "c"])).toBe(true);
|
|
1454
|
+
});
|
|
1455
|
+
it("array IN clause — value absent", () => {
|
|
1456
|
+
expect(matchesCondition("d", ["a", "b", "c"])).toBe(false);
|
|
1457
|
+
});
|
|
1458
|
+
|
|
1459
|
+
// NOT operator
|
|
1460
|
+
it("not operator with string", () => {
|
|
1461
|
+
expect(matchesCondition("bob", { not: "alice" })).toBe(true);
|
|
1462
|
+
expect(matchesCondition("alice", { not: "alice" })).toBe(false);
|
|
1463
|
+
});
|
|
1464
|
+
it("not operator with array (NOT IN)", () => {
|
|
1465
|
+
expect(matchesCondition("a", { not: ["b", "c"] })).toBe(true);
|
|
1466
|
+
expect(matchesCondition("b", { not: ["b", "c"] })).toBe(false);
|
|
1467
|
+
});
|
|
1468
|
+
|
|
1469
|
+
// Comparison operators
|
|
1470
|
+
it("gt", () => {
|
|
1471
|
+
expect(matchesCondition(10, { gt: 5 })).toBe(true);
|
|
1472
|
+
expect(matchesCondition(5, { gt: 5 })).toBe(false);
|
|
1473
|
+
});
|
|
1474
|
+
it("gte", () => {
|
|
1475
|
+
expect(matchesCondition(5, { gte: 5 })).toBe(true);
|
|
1476
|
+
expect(matchesCondition(4, { gte: 5 })).toBe(false);
|
|
1477
|
+
});
|
|
1478
|
+
it("lt", () => {
|
|
1479
|
+
expect(matchesCondition(3, { lt: 5 })).toBe(true);
|
|
1480
|
+
expect(matchesCondition(5, { lt: 5 })).toBe(false);
|
|
1481
|
+
});
|
|
1482
|
+
it("lte", () => {
|
|
1483
|
+
expect(matchesCondition(5, { lte: 5 })).toBe(true);
|
|
1484
|
+
expect(matchesCondition(6, { lte: 5 })).toBe(false);
|
|
1485
|
+
});
|
|
1486
|
+
it("combined gt + lt (range)", () => {
|
|
1487
|
+
expect(matchesCondition(5, { gt: 3, lt: 7 })).toBe(true);
|
|
1488
|
+
expect(matchesCondition(3, { gt: 3, lt: 7 })).toBe(false);
|
|
1489
|
+
expect(matchesCondition(7, { gt: 3, lt: 7 })).toBe(false);
|
|
1490
|
+
});
|
|
1491
|
+
|
|
1492
|
+
// Between
|
|
1493
|
+
it("between — inclusive range", () => {
|
|
1494
|
+
expect(matchesCondition(5, { between: [3, 7] })).toBe(true);
|
|
1495
|
+
expect(matchesCondition(3, { between: [3, 7] })).toBe(true);
|
|
1496
|
+
expect(matchesCondition(7, { between: [3, 7] })).toBe(true);
|
|
1497
|
+
expect(matchesCondition(2, { between: [3, 7] })).toBe(false);
|
|
1498
|
+
expect(matchesCondition(8, { between: [3, 7] })).toBe(false);
|
|
1499
|
+
});
|
|
1500
|
+
|
|
1501
|
+
// Contains
|
|
1502
|
+
it("contains with string", () => {
|
|
1503
|
+
expect(matchesCondition("hello world", { contains: "world" })).toBe(true);
|
|
1504
|
+
expect(matchesCondition("hello world", { contains: "xyz" })).toBe(false);
|
|
1505
|
+
});
|
|
1506
|
+
it("contains with array", () => {
|
|
1507
|
+
expect(matchesCondition(["a", "b", "c"], { contains: "b" })).toBe(true);
|
|
1508
|
+
expect(matchesCondition(["a", "b", "c"], { contains: "d" })).toBe(false);
|
|
1509
|
+
});
|
|
1510
|
+
|
|
1511
|
+
// Edge cases
|
|
1512
|
+
it("returns false for undefined value with equality check", () => {
|
|
1513
|
+
expect(matchesCondition(undefined, "hello")).toBe(false);
|
|
1514
|
+
});
|
|
1515
|
+
it("returns false for empty string when condition is non-empty", () => {
|
|
1516
|
+
expect(matchesCondition("", "Recipe 2")).toBe(false);
|
|
1517
|
+
});
|
|
1518
|
+
it("returns true for undefined with not operator", () => {
|
|
1519
|
+
expect(matchesCondition(undefined, { not: "hello" })).toBe(true);
|
|
1520
|
+
});
|
|
1521
|
+
});
|
|
1522
|
+
|
|
1523
|
+
describe("hydrateFromLinks()", () => {
|
|
1524
|
+
// Create a mock perspective that won't be called for literal properties
|
|
1525
|
+
const mockPerspective = {} as any;
|
|
1526
|
+
|
|
1527
|
+
@Model({ name: "HydrationTest" })
|
|
1528
|
+
class HydrationTest extends Ad4mModel {
|
|
1529
|
+
@Property({ through: "test://name", resolveLanguage: "literal" })
|
|
1530
|
+
name: string = "";
|
|
1531
|
+
|
|
1532
|
+
@Property({ through: "test://score", resolveLanguage: "literal" })
|
|
1533
|
+
score: number = 0;
|
|
1534
|
+
|
|
1535
|
+
@Property({ through: "test://active", resolveLanguage: "literal" })
|
|
1536
|
+
active: boolean = false;
|
|
1537
|
+
}
|
|
1538
|
+
|
|
1539
|
+
const metadata = HydrationTest.getModelMetadata();
|
|
1540
|
+
|
|
1541
|
+
it("hydrates all properties when requestedProperties is undefined", async () => {
|
|
1542
|
+
const instance = new HydrationTest(mockPerspective) as any;
|
|
1543
|
+
const links = [
|
|
1544
|
+
{ predicate: "test://name", target: literalUrl("Alice"), author: "did:test", timestamp: "1000" },
|
|
1545
|
+
{ predicate: "test://score", target: literalUrl(42), author: "did:test", timestamp: "1000" },
|
|
1546
|
+
{ predicate: "test://active", target: literalUrl(true), author: "did:test", timestamp: "1000" },
|
|
1547
|
+
];
|
|
1548
|
+
await hydrateFromLinks(instance, links, metadata, mockPerspective, undefined);
|
|
1549
|
+
expect(instance.name).toBe("Alice");
|
|
1550
|
+
expect(instance.score).toBe(42);
|
|
1551
|
+
expect(instance.active).toBe(true);
|
|
1552
|
+
});
|
|
1553
|
+
|
|
1554
|
+
it("hydrates only requested properties when requestedProperties is provided", async () => {
|
|
1555
|
+
const instance = new HydrationTest(mockPerspective) as any;
|
|
1556
|
+
const links = [
|
|
1557
|
+
{ predicate: "test://name", target: literalUrl("Alice"), author: "did:test", timestamp: "1000" },
|
|
1558
|
+
{ predicate: "test://score", target: literalUrl(42), author: "did:test", timestamp: "1000" },
|
|
1559
|
+
{ predicate: "test://active", target: literalUrl(true), author: "did:test", timestamp: "1000" },
|
|
1560
|
+
];
|
|
1561
|
+
await hydrateFromLinks(instance, links, metadata, mockPerspective, ["name"]);
|
|
1562
|
+
expect(instance.name).toBe("Alice");
|
|
1563
|
+
// score and active should remain at defaults since not requested
|
|
1564
|
+
expect(instance.score).toBe(0);
|
|
1565
|
+
expect(instance.active).toBe(false);
|
|
1566
|
+
});
|
|
1567
|
+
|
|
1568
|
+
it("hydrates where-clause + projection properties when both are in requestedProperties", async () => {
|
|
1569
|
+
const instance = new HydrationTest(mockPerspective) as any;
|
|
1570
|
+
const links = [
|
|
1571
|
+
{ predicate: "test://name", target: literalUrl("Recipe 2"), author: "did:test", timestamp: "1000" },
|
|
1572
|
+
{ predicate: "test://active", target: literalUrl(true), author: "did:test", timestamp: "1000" },
|
|
1573
|
+
];
|
|
1574
|
+
// Simulate merged hydration props: projection ["active"] + where clause props ["name"]
|
|
1575
|
+
await hydrateFromLinks(instance, links, metadata, mockPerspective, ["active", "name"]);
|
|
1576
|
+
expect(instance.name).toBe("Recipe 2");
|
|
1577
|
+
expect(instance.active).toBe(true);
|
|
1578
|
+
});
|
|
1579
|
+
|
|
1580
|
+
it("sets author and timestamps from links", async () => {
|
|
1581
|
+
const instance = new HydrationTest(mockPerspective) as any;
|
|
1582
|
+
const links = [
|
|
1583
|
+
{ predicate: "test://name", target: literalUrl("Bob"), author: "did:author1", timestamp: "1000" },
|
|
1584
|
+
{ predicate: "test://score", target: literalUrl(10), author: "did:author2", timestamp: "2000" },
|
|
1585
|
+
];
|
|
1586
|
+
await hydrateFromLinks(instance, links, metadata, mockPerspective);
|
|
1587
|
+
expect(instance.author).toBe("did:author1");
|
|
1588
|
+
expect(instance.createdAt).toBe(1000);
|
|
1589
|
+
expect(instance.updatedAt).toBe(2000);
|
|
1590
|
+
});
|
|
1591
|
+
|
|
1592
|
+
it("handles empty links array", async () => {
|
|
1593
|
+
const instance = new HydrationTest(mockPerspective) as any;
|
|
1594
|
+
await hydrateFromLinks(instance, [], metadata, mockPerspective);
|
|
1595
|
+
expect(instance.name).toBe("");
|
|
1596
|
+
expect(instance.score).toBe(0);
|
|
1597
|
+
});
|
|
1598
|
+
});
|
|
1599
|
+
|
|
1600
|
+
describe("instancesFromQueryResult — where + properties interaction", () => {
|
|
1601
|
+
const mockPerspective = {
|
|
1602
|
+
get: jest.fn().mockResolvedValue([]),
|
|
1603
|
+
querySparql: jest.fn().mockResolvedValue([]),
|
|
1604
|
+
getExpression: jest.fn().mockResolvedValue(null),
|
|
1605
|
+
} as any;
|
|
1606
|
+
|
|
1607
|
+
@Model({ name: "Recipe" })
|
|
1608
|
+
class Recipe extends Ad4mModel {
|
|
1609
|
+
@Property({ through: "recipe://name", resolveLanguage: "literal", required: true })
|
|
1610
|
+
name: string = "";
|
|
1611
|
+
|
|
1612
|
+
@Property({ through: "recipe://booleanTest", resolveLanguage: "literal" })
|
|
1613
|
+
booleanTest: boolean = false;
|
|
1614
|
+
|
|
1615
|
+
@Property({ through: "recipe://score", resolveLanguage: "literal" })
|
|
1616
|
+
score: number = 0;
|
|
1617
|
+
}
|
|
1618
|
+
|
|
1619
|
+
it("should filter by where clause property even when not in properties projection", async () => {
|
|
1620
|
+
// Simulate SPARQL result with two recipes
|
|
1621
|
+
const grouped = [
|
|
1622
|
+
{
|
|
1623
|
+
source_uri: "expr:recipe1",
|
|
1624
|
+
links: [
|
|
1625
|
+
{ predicate: "recipe://name", target: literalUrl("Recipe 1"), author: "did:test", timestamp: "1000" },
|
|
1626
|
+
{ predicate: "recipe://booleanTest", target: literalUrl(true), author: "did:test", timestamp: "1000" },
|
|
1627
|
+
],
|
|
1628
|
+
},
|
|
1629
|
+
{
|
|
1630
|
+
source_uri: "expr:recipe2",
|
|
1631
|
+
links: [
|
|
1632
|
+
{ predicate: "recipe://name", target: literalUrl("Recipe 2"), author: "did:test", timestamp: "1000" },
|
|
1633
|
+
{ predicate: "recipe://booleanTest", target: literalUrl(false), author: "did:test", timestamp: "1000" },
|
|
1634
|
+
],
|
|
1635
|
+
},
|
|
1636
|
+
];
|
|
1637
|
+
|
|
1638
|
+
const query = { where: { name: "Recipe 2" }, properties: ["booleanTest"] };
|
|
1639
|
+
const { results } = await Recipe.instancesFromQueryResult(mockPerspective, query, grouped);
|
|
1640
|
+
|
|
1641
|
+
expect(results.length).toBe(1);
|
|
1642
|
+
expect((results[0] as any).booleanTest).toBe(false);
|
|
1643
|
+
// name should be deleted after filtering since it wasn't in properties projection
|
|
1644
|
+
expect((results[0] as any).name).toBeUndefined();
|
|
1645
|
+
});
|
|
1646
|
+
|
|
1647
|
+
it("should delete unrequested properties AFTER where-filtering", async () => {
|
|
1648
|
+
const grouped = [
|
|
1649
|
+
{
|
|
1650
|
+
source_uri: "expr:recipe1",
|
|
1651
|
+
links: [
|
|
1652
|
+
{ predicate: "recipe://name", target: literalUrl("Recipe 1"), author: "did:test", timestamp: "1000" },
|
|
1653
|
+
{ predicate: "recipe://score", target: literalUrl(99), author: "did:test", timestamp: "1000" },
|
|
1654
|
+
],
|
|
1655
|
+
},
|
|
1656
|
+
];
|
|
1657
|
+
|
|
1658
|
+
const query = { where: { name: "Recipe 1" }, properties: ["score"] };
|
|
1659
|
+
const { results } = await Recipe.instancesFromQueryResult(mockPerspective, query, grouped);
|
|
1660
|
+
|
|
1661
|
+
expect(results.length).toBe(1);
|
|
1662
|
+
expect((results[0] as any).score).toBe(99);
|
|
1663
|
+
// name was used for filtering but should be deleted from final result
|
|
1664
|
+
expect((results[0] as any).name).toBeUndefined();
|
|
1665
|
+
});
|
|
1666
|
+
|
|
1667
|
+
it("should return all properties when no projection is specified", async () => {
|
|
1668
|
+
const grouped = [
|
|
1669
|
+
{
|
|
1670
|
+
source_uri: "expr:recipe1",
|
|
1671
|
+
links: [
|
|
1672
|
+
{ predicate: "recipe://name", target: literalUrl("Test"), author: "did:test", timestamp: "1000" },
|
|
1673
|
+
{ predicate: "recipe://booleanTest", target: literalUrl(true), author: "did:test", timestamp: "1000" },
|
|
1674
|
+
{ predicate: "recipe://score", target: literalUrl(50), author: "did:test", timestamp: "1000" },
|
|
1675
|
+
],
|
|
1676
|
+
},
|
|
1677
|
+
];
|
|
1678
|
+
|
|
1679
|
+
const query = { where: { name: "Test" } };
|
|
1680
|
+
const { results } = await Recipe.instancesFromQueryResult(mockPerspective, query, grouped);
|
|
1681
|
+
|
|
1682
|
+
expect(results.length).toBe(1);
|
|
1683
|
+
expect((results[0] as any).name).toBe("Test");
|
|
1684
|
+
expect((results[0] as any).booleanTest).toBe(true);
|
|
1685
|
+
expect((results[0] as any).score).toBe(50);
|
|
1686
|
+
});
|
|
1687
|
+
});
|
|
1688
|
+
|
|
1689
|
+
describe("groupSPARQLResults()", () => {
|
|
1690
|
+
it("groups rows by source", () => {
|
|
1691
|
+
const rows = [
|
|
1692
|
+
{ source: "a", predicate: "p1", target: "t1", author: "auth", timestamp: "ts1" },
|
|
1693
|
+
{ source: "a", predicate: "p2", target: "t2", author: "auth", timestamp: "ts2" },
|
|
1694
|
+
{ source: "b", predicate: "p1", target: "t3", author: "auth", timestamp: "ts3" },
|
|
1695
|
+
];
|
|
1696
|
+
const grouped = groupSPARQLResults(rows);
|
|
1697
|
+
expect(grouped.length).toBe(2);
|
|
1698
|
+
const groupA = grouped.find(g => g.source_uri === "a")!;
|
|
1699
|
+
const groupB = grouped.find(g => g.source_uri === "b")!;
|
|
1700
|
+
expect(groupA.links.length).toBe(2);
|
|
1701
|
+
expect(groupB.links.length).toBe(1);
|
|
1702
|
+
});
|
|
1703
|
+
|
|
1704
|
+
it("handles empty input", () => {
|
|
1705
|
+
expect(groupSPARQLResults([])).toEqual([]);
|
|
1706
|
+
});
|
|
1707
|
+
|
|
1708
|
+
it("preserves link metadata", () => {
|
|
1709
|
+
const rows = [
|
|
1710
|
+
{ source: "x", predicate: "pred", target: "tgt", author: "did:auth", timestamp: "2024-01-01" },
|
|
1711
|
+
];
|
|
1712
|
+
const grouped = groupSPARQLResults(rows);
|
|
1713
|
+
expect(grouped[0].links[0]).toEqual({
|
|
1714
|
+
predicate: "pred",
|
|
1715
|
+
target: "tgt",
|
|
1716
|
+
author: "did:auth",
|
|
1717
|
+
timestamp: "2024-01-01",
|
|
1718
|
+
});
|
|
1719
|
+
});
|
|
1720
|
+
});
|
|
1721
|
+
|
|
1722
|
+
describe("buildSPARQLQuery edge cases", () => {
|
|
1723
|
+
@Model({ name: "FlagModel" })
|
|
1724
|
+
class FlagModel extends Ad4mModel {
|
|
1725
|
+
@Flag({ through: "flag://type", value: "flag://FlagModel" })
|
|
1726
|
+
type: string = "";
|
|
1727
|
+
|
|
1728
|
+
@Property({ through: "flag://name", resolveLanguage: "literal", required: true })
|
|
1729
|
+
name: string = "";
|
|
1730
|
+
}
|
|
1731
|
+
|
|
1732
|
+
@Model({ name: "NoFlagModel" })
|
|
1733
|
+
class NoFlagModel extends Ad4mModel {
|
|
1734
|
+
@Property({ through: "noflag://title", resolveLanguage: "literal" })
|
|
1735
|
+
title: string = "";
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
it("adds conformance JOIN for flag + required properties", () => {
|
|
1739
|
+
const metadata = FlagModel.getModelMetadata();
|
|
1740
|
+
const allRelsMeta = {} as any;
|
|
1741
|
+
const sparql = buildSPARQLQuery(metadata, allRelsMeta, {}, FlagModel);
|
|
1742
|
+
// Should contain flag triple pattern
|
|
1743
|
+
expect(sparql).toContain("<flag://type>");
|
|
1744
|
+
expect(sparql).toContain("<flag://FlagModel>");
|
|
1745
|
+
// Should contain required property pattern
|
|
1746
|
+
expect(sparql).toContain("<flag://name>");
|
|
1747
|
+
});
|
|
1748
|
+
|
|
1749
|
+
it("uses structural subquery when no conformance patterns exist", () => {
|
|
1750
|
+
const metadata = NoFlagModel.getModelMetadata();
|
|
1751
|
+
const allRelsMeta = {} as any;
|
|
1752
|
+
const sparql = buildSPARQLQuery(metadata, allRelsMeta, {}, NoFlagModel);
|
|
1753
|
+
// Should contain structural subquery with DISTINCT
|
|
1754
|
+
expect(sparql).toContain("SELECT DISTINCT ?source");
|
|
1755
|
+
expect(sparql).toContain("<noflag://title>");
|
|
1756
|
+
});
|
|
1757
|
+
|
|
1758
|
+
it("adds JOIN for where-clause on literal-stored fields", () => {
|
|
1759
|
+
const metadata = FlagModel.getModelMetadata();
|
|
1760
|
+
const allRelsMeta = {} as any;
|
|
1761
|
+
const sparql = buildSPARQLQuery(metadata, allRelsMeta, { where: { name: "test" } }, FlagModel);
|
|
1762
|
+
// Where clause should add a join pattern for name
|
|
1763
|
+
expect(sparql).toContain("flag://name");
|
|
1764
|
+
});
|
|
1765
|
+
|
|
1766
|
+
it("handles where: {id: 'specific-id'} with FILTER on ?source", () => {
|
|
1767
|
+
const metadata = FlagModel.getModelMetadata();
|
|
1768
|
+
const allRelsMeta = {} as any;
|
|
1769
|
+
const sparql = buildSPARQLQuery(metadata, allRelsMeta, { where: { id: "expr:123" } as any }, FlagModel);
|
|
1770
|
+
// Should filter by source
|
|
1771
|
+
expect(sparql).toContain("expr:123");
|
|
1772
|
+
});
|
|
1773
|
+
});
|
|
1774
|
+
|
|
1775
|
+
describe("sparse fieldset property deletion timing", () => {
|
|
1776
|
+
const mockPerspective = {
|
|
1777
|
+
get: jest.fn().mockResolvedValue([]),
|
|
1778
|
+
querySparql: jest.fn().mockResolvedValue([]),
|
|
1779
|
+
getExpression: jest.fn().mockResolvedValue(null),
|
|
1780
|
+
} as any;
|
|
1781
|
+
|
|
1782
|
+
@Model({ name: "TimingTest" })
|
|
1783
|
+
class TimingTest extends Ad4mModel {
|
|
1784
|
+
@Property({ through: "timing://a", resolveLanguage: "literal" })
|
|
1785
|
+
a: string = "";
|
|
1786
|
+
|
|
1787
|
+
@Property({ through: "timing://b", resolveLanguage: "literal" })
|
|
1788
|
+
b: string = "";
|
|
1789
|
+
|
|
1790
|
+
@Property({ through: "timing://c", resolveLanguage: "literal" })
|
|
1791
|
+
c: string = "";
|
|
1792
|
+
}
|
|
1793
|
+
|
|
1794
|
+
it("where-clause properties are available during filtering but deleted after", async () => {
|
|
1795
|
+
const grouped = [
|
|
1796
|
+
{
|
|
1797
|
+
source_uri: "expr:1",
|
|
1798
|
+
links: [
|
|
1799
|
+
{ predicate: "timing://a", target: literalUrl("match"), author: "did:test", timestamp: "1000" },
|
|
1800
|
+
{ predicate: "timing://b", target: literalUrl("keep"), author: "did:test", timestamp: "1000" },
|
|
1801
|
+
{ predicate: "timing://c", target: literalUrl("ignore"), author: "did:test", timestamp: "1000" },
|
|
1802
|
+
],
|
|
1803
|
+
},
|
|
1804
|
+
{
|
|
1805
|
+
source_uri: "expr:2",
|
|
1806
|
+
links: [
|
|
1807
|
+
{ predicate: "timing://a", target: literalUrl("no-match"), author: "did:test", timestamp: "1000" },
|
|
1808
|
+
{ predicate: "timing://b", target: literalUrl("skip"), author: "did:test", timestamp: "1000" },
|
|
1809
|
+
{ predicate: "timing://c", target: literalUrl("skip"), author: "did:test", timestamp: "1000" },
|
|
1810
|
+
],
|
|
1811
|
+
},
|
|
1812
|
+
];
|
|
1813
|
+
|
|
1814
|
+
// properties projection asks for "b" only, where clause filters on "a"
|
|
1815
|
+
const query = { where: { a: "match" }, properties: ["b"] };
|
|
1816
|
+
const { results } = await TimingTest.instancesFromQueryResult(mockPerspective, query, grouped);
|
|
1817
|
+
|
|
1818
|
+
// Only the matching instance should survive
|
|
1819
|
+
expect(results.length).toBe(1);
|
|
1820
|
+
// "b" was requested — should be present
|
|
1821
|
+
expect((results[0] as any).b).toBe("keep");
|
|
1822
|
+
// "a" was used for filtering but not in projection — should be deleted
|
|
1823
|
+
expect((results[0] as any).a).toBeUndefined();
|
|
1824
|
+
// "c" was not requested — should be deleted
|
|
1825
|
+
expect((results[0] as any).c).toBeUndefined();
|
|
1826
|
+
});
|
|
1827
|
+
|
|
1828
|
+
it("properties not in projection are undefined after instancesFromQueryResult", async () => {
|
|
1829
|
+
const grouped = [
|
|
1830
|
+
{
|
|
1831
|
+
source_uri: "expr:1",
|
|
1832
|
+
links: [
|
|
1833
|
+
{ predicate: "timing://a", target: literalUrl("val-a"), author: "did:test", timestamp: "1000" },
|
|
1834
|
+
{ predicate: "timing://b", target: literalUrl("val-b"), author: "did:test", timestamp: "1000" },
|
|
1835
|
+
{ predicate: "timing://c", target: literalUrl("val-c"), author: "did:test", timestamp: "1000" },
|
|
1836
|
+
],
|
|
1837
|
+
},
|
|
1838
|
+
];
|
|
1839
|
+
|
|
1840
|
+
const query = { properties: ["a"] };
|
|
1841
|
+
const { results } = await TimingTest.instancesFromQueryResult(mockPerspective, query, grouped);
|
|
1842
|
+
|
|
1843
|
+
expect(results.length).toBe(1);
|
|
1844
|
+
expect((results[0] as any).a).toBe("val-a");
|
|
1845
|
+
expect((results[0] as any).b).toBeUndefined();
|
|
1846
|
+
expect((results[0] as any).c).toBeUndefined();
|
|
1847
|
+
});
|
|
1848
|
+
});
|
|
1849
|
+
|
|
1850
|
+
// ── Batch hydration for reverse relations (3.4) ─────────────────────────────
|
|
1851
|
+
describe("Batch hydration for reverse relations", () => {
|
|
1852
|
+
it("batch hydration should correctly group targets by parent instance ID", () => {
|
|
1853
|
+
// Test the grouping logic used in batch SPARQL hydration
|
|
1854
|
+
const sparqlResults = [
|
|
1855
|
+
{ target: "inst:1", source: "child:a" },
|
|
1856
|
+
{ target: "inst:1", source: "child:b" },
|
|
1857
|
+
{ target: "inst:2", source: "child:c" },
|
|
1858
|
+
{ target: "inst:3", source: "child:d" },
|
|
1859
|
+
{ target: "inst:3", source: "child:e" },
|
|
1860
|
+
{ target: "inst:3", source: "child:f" },
|
|
1861
|
+
];
|
|
1862
|
+
|
|
1863
|
+
const reverseLinksMap = new Map<string, string[]>();
|
|
1864
|
+
for (const row of sparqlResults) {
|
|
1865
|
+
if (!reverseLinksMap.has(row.target)) reverseLinksMap.set(row.target, []);
|
|
1866
|
+
reverseLinksMap.get(row.target)!.push(row.source);
|
|
1867
|
+
}
|
|
1868
|
+
|
|
1869
|
+
expect(reverseLinksMap.get("inst:1")).toEqual(["child:a", "child:b"]);
|
|
1870
|
+
expect(reverseLinksMap.get("inst:2")).toEqual(["child:c"]);
|
|
1871
|
+
expect(reverseLinksMap.get("inst:3")).toEqual(["child:d", "child:e", "child:f"]);
|
|
1872
|
+
});
|
|
1873
|
+
|
|
1874
|
+
it("batch hydration should handle empty relation sets without error", () => {
|
|
1875
|
+
const sparqlResults: any[] = [];
|
|
1876
|
+
const reverseLinksMap = new Map<string, string[]>();
|
|
1877
|
+
for (const row of sparqlResults) {
|
|
1878
|
+
if (!reverseLinksMap.has(row.target)) reverseLinksMap.set(row.target, []);
|
|
1879
|
+
reverseLinksMap.get(row.target)!.push(row.source);
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1882
|
+
expect(reverseLinksMap.size).toBe(0);
|
|
1883
|
+
expect(reverseLinksMap.get("nonexistent") || []).toEqual([]);
|
|
1884
|
+
});
|
|
1885
|
+
|
|
1886
|
+
it("batch hydration should return identical results to N+1 hydration (grouping equivalence)", () => {
|
|
1887
|
+
// Simulate N+1: each instance queries separately
|
|
1888
|
+
const instances = [{ id: "inst:1" }, { id: "inst:2" }];
|
|
1889
|
+
const allLinks = [
|
|
1890
|
+
{ data: { source: "child:a", predicate: "rel://has", target: "inst:1" } },
|
|
1891
|
+
{ data: { source: "child:b", predicate: "rel://has", target: "inst:1" } },
|
|
1892
|
+
{ data: { source: "child:c", predicate: "rel://has", target: "inst:2" } },
|
|
1893
|
+
];
|
|
1894
|
+
|
|
1895
|
+
// N+1 approach
|
|
1896
|
+
const n1Results = new Map<string, string[]>();
|
|
1897
|
+
for (const inst of instances) {
|
|
1898
|
+
const links = allLinks.filter(l => l.data.target === inst.id);
|
|
1899
|
+
n1Results.set(inst.id, links.map(l => l.data.source));
|
|
1900
|
+
}
|
|
1901
|
+
|
|
1902
|
+
// Batch approach
|
|
1903
|
+
const batchResults = new Map<string, string[]>();
|
|
1904
|
+
const sparqlRows = allLinks.map(l => ({ target: l.data.target, source: l.data.source }));
|
|
1905
|
+
for (const row of sparqlRows) {
|
|
1906
|
+
if (!batchResults.has(row.target)) batchResults.set(row.target, []);
|
|
1907
|
+
batchResults.get(row.target)!.push(row.source);
|
|
1908
|
+
}
|
|
1909
|
+
|
|
1910
|
+
// Results should be identical
|
|
1911
|
+
for (const inst of instances) {
|
|
1912
|
+
expect(batchResults.get(inst.id)).toEqual(n1Results.get(inst.id));
|
|
1913
|
+
}
|
|
1914
|
+
});
|
|
1915
|
+
|
|
1916
|
+
it("batch hydration with nested includes should use batched queries at each level", () => {
|
|
1917
|
+
// This test verifies the structure: nested includes result in multiple
|
|
1918
|
+
// batch operations, one per relation depth level
|
|
1919
|
+
const depth0Rows = [
|
|
1920
|
+
{ target: "root:1", source: "mid:a" },
|
|
1921
|
+
{ target: "root:1", source: "mid:b" },
|
|
1922
|
+
];
|
|
1923
|
+
const depth1Rows = [
|
|
1924
|
+
{ target: "mid:a", source: "leaf:x" },
|
|
1925
|
+
{ target: "mid:b", source: "leaf:y" },
|
|
1926
|
+
];
|
|
1927
|
+
|
|
1928
|
+
// Group each level
|
|
1929
|
+
const level0Map = new Map<string, string[]>();
|
|
1930
|
+
for (const r of depth0Rows) {
|
|
1931
|
+
if (!level0Map.has(r.target)) level0Map.set(r.target, []);
|
|
1932
|
+
level0Map.get(r.target)!.push(r.source);
|
|
1933
|
+
}
|
|
1934
|
+
|
|
1935
|
+
const level1Map = new Map<string, string[]>();
|
|
1936
|
+
for (const r of depth1Rows) {
|
|
1937
|
+
if (!level1Map.has(r.target)) level1Map.set(r.target, []);
|
|
1938
|
+
level1Map.get(r.target)!.push(r.source);
|
|
1939
|
+
}
|
|
1940
|
+
|
|
1941
|
+
expect(level0Map.get("root:1")).toEqual(["mid:a", "mid:b"]);
|
|
1942
|
+
expect(level1Map.get("mid:a")).toEqual(["leaf:x"]);
|
|
1943
|
+
expect(level1Map.get("mid:b")).toEqual(["leaf:y"]);
|
|
1944
|
+
});
|
|
1945
|
+
});
|
|
1946
|
+
|
|
1947
|
+
// ── Push-down FILTER for literal equality (3.5) ──────────────────────────────
|
|
1948
|
+
describe("Push-down FILTER for literal equality", () => {
|
|
1949
|
+
const mockPerspective = {} as any;
|
|
1950
|
+
|
|
1951
|
+
@Model({ name: "FilterTest" })
|
|
1952
|
+
class FilterTest extends Ad4mModel {
|
|
1953
|
+
@Property({ through: "ft://name", required: true })
|
|
1954
|
+
name: string = "";
|
|
1955
|
+
@Property({ through: "ft://rating", required: true })
|
|
1956
|
+
rating: number = 0;
|
|
1957
|
+
}
|
|
1958
|
+
|
|
1959
|
+
const normalizeQuery = (q: string) => q.replace(/\s+/g, " ").trim();
|
|
1960
|
+
|
|
1961
|
+
it("SPARQL query for where: { name: 'Alice' } should use <ad4m://fn/parse_literal> FILTER", async () => {
|
|
1962
|
+
const query = await (FilterTest as any).queryToSPARQL(mockPerspective, { where: { name: "Alice" } });
|
|
1963
|
+
const norm = normalizeQuery(query);
|
|
1964
|
+
// JOIN pattern exists
|
|
1965
|
+
expect(norm).toContain("?wTarget_name");
|
|
1966
|
+
// parse_literal push-down FILTER is present (using correct SPARQL IRI syntax)
|
|
1967
|
+
expect(norm).toContain("ad4m://fn/parse_literal");
|
|
1968
|
+
expect(norm).not.toContain("fn::parse_literal");
|
|
1969
|
+
});
|
|
1970
|
+
|
|
1971
|
+
it("SPARQL query for where: { name: ['Alice', 'Bob'] } should use <ad4m://fn/parse_literal> IN FILTER", async () => {
|
|
1972
|
+
const query = await (FilterTest as any).queryToSPARQL(mockPerspective, { where: { name: ["Alice", "Bob"] } });
|
|
1973
|
+
const norm = normalizeQuery(query);
|
|
1974
|
+
expect(norm).toContain("?wTarget_name");
|
|
1975
|
+
expect(norm).toContain("ad4m://fn/parse_literal");
|
|
1976
|
+
expect(norm).not.toContain("fn::parse_literal");
|
|
1977
|
+
});
|
|
1978
|
+
|
|
1979
|
+
it("SPARQL query for where: { rating: { gt: 5 } } should NOT include parse_literal FILTER", async () => {
|
|
1980
|
+
const query = await (FilterTest as any).queryToSPARQL(mockPerspective, { where: { rating: { gt: 5 } } });
|
|
1981
|
+
const norm = normalizeQuery(query);
|
|
1982
|
+
expect(norm).not.toContain("parse_literal");
|
|
1983
|
+
});
|
|
1984
|
+
|
|
1985
|
+
it("literal property where clause adds JOIN for JS post-filter", async () => {
|
|
1986
|
+
const query = await (FilterTest as any).queryToSPARQL(mockPerspective, { where: { name: "Alice" } });
|
|
1987
|
+
const norm = normalizeQuery(query);
|
|
1988
|
+
expect(norm).toContain("?wTarget_name");
|
|
1989
|
+
});
|
|
1990
|
+
});
|
|
1991
|
+
|
|
1992
|
+
// ── Lightweight fingerprint (3.7) ────────────────────────────────────────────
|
|
1993
|
+
describe("Lightweight fingerprint optimization", () => {
|
|
1994
|
+
// Replicate the buildFingerprint logic for testing
|
|
1995
|
+
const buildFingerprint = (results: any[]) => {
|
|
1996
|
+
if (results.length === 0) return '0:';
|
|
1997
|
+
const ids = results.map((r: any) => r.id || '').sort().join(',');
|
|
1998
|
+
const ts = results.map((r: any) => r.updatedAt || r.timestamp || '').join(',');
|
|
1999
|
+
return `${results.length}:${ids}:${ts}`;
|
|
2000
|
+
};
|
|
2001
|
+
|
|
2002
|
+
const base = [
|
|
2003
|
+
{ id: "a", updatedAt: "100" },
|
|
2004
|
+
{ id: "b", updatedAt: "200" },
|
|
2005
|
+
];
|
|
2006
|
+
|
|
2007
|
+
it("lightweight fingerprint should detect instance addition", () => {
|
|
2008
|
+
const fp1 = buildFingerprint(base);
|
|
2009
|
+
const fp2 = buildFingerprint([...base, { id: "c", updatedAt: "300" }]);
|
|
2010
|
+
expect(fp1).not.toBe(fp2);
|
|
2011
|
+
});
|
|
2012
|
+
|
|
2013
|
+
it("lightweight fingerprint should detect instance removal", () => {
|
|
2014
|
+
const fp1 = buildFingerprint(base);
|
|
2015
|
+
const fp2 = buildFingerprint([base[0]]);
|
|
2016
|
+
expect(fp1).not.toBe(fp2);
|
|
2017
|
+
});
|
|
2018
|
+
|
|
2019
|
+
it("lightweight fingerprint should detect timestamp change", () => {
|
|
2020
|
+
const fp1 = buildFingerprint(base);
|
|
2021
|
+
const fp2 = buildFingerprint([{ id: "a", updatedAt: "999" }, base[1]]);
|
|
2022
|
+
expect(fp1).not.toBe(fp2);
|
|
2023
|
+
});
|
|
2024
|
+
|
|
2025
|
+
it("lightweight fingerprint should NOT false-positive for identical sets", () => {
|
|
2026
|
+
const fp1 = buildFingerprint(base);
|
|
2027
|
+
const fp2 = buildFingerprint([...base]); // same data, new array
|
|
2028
|
+
expect(fp1).toBe(fp2);
|
|
2029
|
+
});
|
|
2030
|
+
});
|
|
2031
|
+
|
|
2032
|
+
// ── Native SPARQL getter evaluation ──────────────────────────────────────────
|
|
2033
|
+
describe("Native SPARQL getter evaluation", () => {
|
|
2034
|
+
const { evaluateCustomGettersForInstance } = require("./hydration");
|
|
2035
|
+
|
|
2036
|
+
const mockPerspective = {
|
|
2037
|
+
getLinks: jest.fn().mockResolvedValue([]),
|
|
2038
|
+
querySparql: jest.fn(),
|
|
2039
|
+
get: jest.fn().mockResolvedValue([]),
|
|
2040
|
+
};
|
|
2041
|
+
|
|
2042
|
+
beforeEach(() => {
|
|
2043
|
+
jest.clearAllMocks();
|
|
2044
|
+
});
|
|
2045
|
+
|
|
2046
|
+
it("should execute SELECT getter directly via querySparql", async () => {
|
|
2047
|
+
const metadata = {
|
|
2048
|
+
properties: {
|
|
2049
|
+
replyingTo: {
|
|
2050
|
+
predicate: "flux://has_reply",
|
|
2051
|
+
getter: 'SELECT ?target WHERE { ?target <flux://has_reply> ?source . } LIMIT 1',
|
|
2052
|
+
type: "string",
|
|
2053
|
+
}
|
|
2054
|
+
},
|
|
2055
|
+
relations: {},
|
|
2056
|
+
};
|
|
2057
|
+
|
|
2058
|
+
mockPerspective.querySparql.mockResolvedValue([
|
|
2059
|
+
{ target: { value: "literal:string:msg123" } }
|
|
2060
|
+
]);
|
|
2061
|
+
|
|
2062
|
+
const instance = { id: "test://msg1", replyingTo: undefined };
|
|
2063
|
+
await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
|
|
2064
|
+
|
|
2065
|
+
expect(mockPerspective.querySparql).toHaveBeenCalledWith(
|
|
2066
|
+
expect.stringContaining("SELECT ?target WHERE")
|
|
2067
|
+
);
|
|
2068
|
+
expect(instance.replyingTo).toBe("literal:string:msg123");
|
|
2069
|
+
});
|
|
2070
|
+
|
|
2071
|
+
it("should execute ASK getter and return boolean", async () => {
|
|
2072
|
+
const metadata = {
|
|
2073
|
+
properties: {
|
|
2074
|
+
isPopular: {
|
|
2075
|
+
predicate: "flux://is_popular",
|
|
2076
|
+
getter: 'ASK WHERE { SELECT (COUNT(DISTINCT ?reactor) AS ?count) WHERE { ?reactor <flux://reaction> ?source . } HAVING(?count > 5) }',
|
|
2077
|
+
type: "boolean",
|
|
2078
|
+
readOnly: true,
|
|
2079
|
+
}
|
|
2080
|
+
},
|
|
2081
|
+
relations: {},
|
|
2082
|
+
};
|
|
2083
|
+
|
|
2084
|
+
mockPerspective.querySparql.mockResolvedValue(true);
|
|
2085
|
+
|
|
2086
|
+
const instance = { id: "test://msg1", isPopular: false };
|
|
2087
|
+
await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
|
|
2088
|
+
|
|
2089
|
+
expect(mockPerspective.querySparql).toHaveBeenCalledWith(
|
|
2090
|
+
expect.stringContaining("ASK WHERE")
|
|
2091
|
+
);
|
|
2092
|
+
expect(instance.isPopular).toBe(true);
|
|
2093
|
+
});
|
|
2094
|
+
|
|
2095
|
+
it("should replace ?source with instance ID in SPARQL getter", async () => {
|
|
2096
|
+
const metadata = {
|
|
2097
|
+
properties: {
|
|
2098
|
+
author: {
|
|
2099
|
+
predicate: "test://author",
|
|
2100
|
+
getter: 'SELECT ?target WHERE { ?source <test://author> ?target . }',
|
|
2101
|
+
type: "string",
|
|
2102
|
+
}
|
|
2103
|
+
},
|
|
2104
|
+
relations: {},
|
|
2105
|
+
};
|
|
2106
|
+
|
|
2107
|
+
mockPerspective.querySparql.mockResolvedValue([
|
|
2108
|
+
{ target: { value: "did:key:abc123" } }
|
|
2109
|
+
]);
|
|
2110
|
+
|
|
2111
|
+
const instance = { id: "test://post1", author: undefined };
|
|
2112
|
+
await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
|
|
2113
|
+
|
|
2114
|
+
expect(mockPerspective.querySparql).toHaveBeenCalledWith(
|
|
2115
|
+
expect.stringContaining("<test://post1>")
|
|
2116
|
+
);
|
|
2117
|
+
expect(mockPerspective.querySparql).not.toHaveBeenCalledWith(
|
|
2118
|
+
expect.stringContaining("?source")
|
|
2119
|
+
);
|
|
2120
|
+
});
|
|
2121
|
+
|
|
2122
|
+
it("should handle empty SPARQL results gracefully", async () => {
|
|
2123
|
+
const metadata = {
|
|
2124
|
+
properties: {
|
|
2125
|
+
replyingTo: {
|
|
2126
|
+
predicate: "flux://has_reply",
|
|
2127
|
+
getter: 'SELECT ?target WHERE { ?target <flux://has_reply> ?source . } LIMIT 1',
|
|
2128
|
+
type: "string",
|
|
2129
|
+
}
|
|
2130
|
+
},
|
|
2131
|
+
relations: {},
|
|
2132
|
+
};
|
|
2133
|
+
|
|
2134
|
+
mockPerspective.querySparql.mockResolvedValue([]);
|
|
2135
|
+
|
|
2136
|
+
const instance = { id: "test://msg1", replyingTo: "original" };
|
|
2137
|
+
await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
|
|
2138
|
+
|
|
2139
|
+
// Should not overwrite with undefined
|
|
2140
|
+
expect(instance.replyingTo).toBe("original");
|
|
2141
|
+
});
|
|
2142
|
+
|
|
2143
|
+
it("should handle SPARQL getter errors without crashing", async () => {
|
|
2144
|
+
const metadata = {
|
|
2145
|
+
properties: {
|
|
2146
|
+
broken: {
|
|
2147
|
+
predicate: "test://broken",
|
|
2148
|
+
getter: 'SELECT ?target WHERE { INVALID SPARQL }',
|
|
2149
|
+
type: "string",
|
|
2150
|
+
}
|
|
2151
|
+
},
|
|
2152
|
+
relations: {},
|
|
2153
|
+
};
|
|
2154
|
+
|
|
2155
|
+
mockPerspective.querySparql.mockRejectedValue(new Error("SPARQL parse error"));
|
|
2156
|
+
|
|
2157
|
+
const instance = { id: "test://msg1", broken: undefined };
|
|
2158
|
+
const consoleSpy = jest.spyOn(console, "warn").mockImplementation();
|
|
2159
|
+
await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
|
|
2160
|
+
consoleSpy.mockRestore();
|
|
2161
|
+
|
|
2162
|
+
// Should not throw, should warn
|
|
2163
|
+
expect(instance.broken).toBeUndefined();
|
|
2164
|
+
});
|
|
2165
|
+
|
|
2166
|
+
it("should execute SPARQL getter for relations", async () => {
|
|
2167
|
+
const metadata = {
|
|
2168
|
+
properties: {},
|
|
2169
|
+
relations: {
|
|
2170
|
+
tags: {
|
|
2171
|
+
predicate: "test://has_tag",
|
|
2172
|
+
getter: 'SELECT ?target WHERE { ?source <test://has_tag> ?target . }',
|
|
2173
|
+
direction: "forward",
|
|
2174
|
+
}
|
|
2175
|
+
},
|
|
2176
|
+
};
|
|
2177
|
+
|
|
2178
|
+
mockPerspective.querySparql.mockResolvedValue([
|
|
2179
|
+
{ target: { value: "tag:a" } },
|
|
2180
|
+
{ target: { value: "tag:b" } },
|
|
2181
|
+
]);
|
|
2182
|
+
|
|
2183
|
+
const instance = { id: "test://post1", tags: [] };
|
|
2184
|
+
await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
|
|
2185
|
+
|
|
2186
|
+
expect(instance.tags).toEqual(["tag:a", "tag:b"]);
|
|
2187
|
+
});
|
|
2188
|
+
|
|
2189
|
+
it("should warn for legacy SurrealDB-style getter syntax instead of converting", async () => {
|
|
2190
|
+
const metadata = {
|
|
2191
|
+
properties: {
|
|
2192
|
+
legacy: {
|
|
2193
|
+
predicate: "test://legacy",
|
|
2194
|
+
getter: "(<-link[WHERE predicate = 'test://legacy'].in.uri)[0]",
|
|
2195
|
+
type: "string",
|
|
2196
|
+
}
|
|
2197
|
+
},
|
|
2198
|
+
relations: {},
|
|
2199
|
+
};
|
|
2200
|
+
|
|
2201
|
+
const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
|
|
2202
|
+
|
|
2203
|
+
const instance = { id: "test://msg1", legacy: undefined };
|
|
2204
|
+
await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
|
|
2205
|
+
|
|
2206
|
+
// Should NOT call querySparql — legacy getters are no longer converted
|
|
2207
|
+
expect(mockPerspective.querySparql).not.toHaveBeenCalled();
|
|
2208
|
+
// Should warn about unsupported syntax
|
|
2209
|
+
expect(warnSpy).toHaveBeenCalledWith(
|
|
2210
|
+
expect.stringContaining("Unsupported legacy getter syntax")
|
|
2211
|
+
);
|
|
2212
|
+
// Value should remain undefined
|
|
2213
|
+
expect(instance.legacy).toBeUndefined();
|
|
2214
|
+
|
|
2215
|
+
warnSpy.mockRestore();
|
|
2216
|
+
});
|
|
2217
|
+
});
|
|
2218
|
+
|
|
2219
|
+
// ── Subscribe callback timing ──────────────────────────────────────────
|
|
2220
|
+
describe("ModelQueryBuilder subscribe callback timing", () => {
|
|
2221
|
+
it("subscribe should not invoke callback synchronously before Promise resolves", async () => {
|
|
2222
|
+
// This test verifies that the initial callback from subscribe() is deferred
|
|
2223
|
+
// via queueMicrotask, preventing Preact/React hook lifecycle violations
|
|
2224
|
+
// when subscribe() is called from useEffect.
|
|
2225
|
+
|
|
2226
|
+
const mockPerspective = {
|
|
2227
|
+
getLinks: jest.fn().mockResolvedValue([]),
|
|
2228
|
+
subscribeQuery: jest.fn().mockResolvedValue({
|
|
2229
|
+
result: '[]',
|
|
2230
|
+
onResult: jest.fn(),
|
|
2231
|
+
dispose: jest.fn(),
|
|
2232
|
+
}),
|
|
2233
|
+
querySparql: jest.fn().mockResolvedValue('[]'),
|
|
2234
|
+
} as any;
|
|
2235
|
+
|
|
2236
|
+
const { Ad4mModel, Model, Property, Flag } = require("./index");
|
|
2237
|
+
|
|
2238
|
+
@Model({ name: "TimingTest" })
|
|
2239
|
+
class TimingTest extends Ad4mModel {
|
|
2240
|
+
@Flag({ through: "test://type", value: "test://timing" })
|
|
2241
|
+
type: string = "test://timing";
|
|
2242
|
+
@Property({ through: "test://name" })
|
|
2243
|
+
name: string = "";
|
|
2244
|
+
}
|
|
2245
|
+
|
|
2246
|
+
let callbackInvokedBeforeResolve = false;
|
|
2247
|
+
let promiseResolved = false;
|
|
2248
|
+
|
|
2249
|
+
const query = TimingTest.query(mockPerspective);
|
|
2250
|
+
const promise = query.subscribe((results: any[]) => {
|
|
2251
|
+
if (!promiseResolved) {
|
|
2252
|
+
callbackInvokedBeforeResolve = true;
|
|
2253
|
+
}
|
|
2254
|
+
});
|
|
2255
|
+
|
|
2256
|
+
// At this point the Promise hasn't resolved yet
|
|
2257
|
+
// The callback should NOT have fired synchronously
|
|
2258
|
+
expect(callbackInvokedBeforeResolve).toBe(false);
|
|
2259
|
+
|
|
2260
|
+
await promise;
|
|
2261
|
+
promiseResolved = true;
|
|
2262
|
+
|
|
2263
|
+
// After the microtask queue drains, the callback should fire
|
|
2264
|
+
await new Promise(r => setTimeout(r, 10));
|
|
2265
|
+
// The callback was deferred — it fires after the Promise resolves
|
|
2266
|
+
});
|
|
2267
|
+
});
|
|
2268
|
+
|
|
2269
|
+
// ============================================================================
|
|
2270
|
+
// Performance Optimisation Tests
|
|
2271
|
+
// ============================================================================
|
|
2272
|
+
|
|
2273
|
+
import { getCachedResult, setCachedResult, clearQueryCache, queryCacheSize } from "./query-cache";
|
|
2274
|
+
import { clearSubscriptionPool, subscriptionPoolSize } from "./subscription-pool";
|
|
2275
|
+
import { getPropertiesMetadata, getRelationsMetadata, getMemoizedSHACL } from "./decorators";
|
|
2276
|
+
|
|
2277
|
+
describe("QueryCache", () => {
|
|
2278
|
+
beforeEach(() => clearQueryCache());
|
|
2279
|
+
|
|
2280
|
+
it("should return undefined for cache miss", () => {
|
|
2281
|
+
expect(getCachedResult("uuid1", "SELECT ?s WHERE {}")).toBeUndefined();
|
|
2282
|
+
});
|
|
2283
|
+
|
|
2284
|
+
it("should return cached result within TTL", () => {
|
|
2285
|
+
const result = [{ s: "test" }];
|
|
2286
|
+
setCachedResult("uuid1", "SELECT ?s WHERE {}", result);
|
|
2287
|
+
expect(getCachedResult("uuid1", "SELECT ?s WHERE {}")).toBe(result);
|
|
2288
|
+
});
|
|
2289
|
+
|
|
2290
|
+
it("should expire after TTL", async () => {
|
|
2291
|
+
setCachedResult("uuid1", "SELECT ?s WHERE {}", [{ s: "test" }], 50);
|
|
2292
|
+
await new Promise(r => setTimeout(r, 60));
|
|
2293
|
+
expect(getCachedResult("uuid1", "SELECT ?s WHERE {}")).toBeUndefined();
|
|
2294
|
+
});
|
|
2295
|
+
|
|
2296
|
+
it("should cache independently per perspective", () => {
|
|
2297
|
+
setCachedResult("uuid1", "SELECT ?s WHERE {}", "result1");
|
|
2298
|
+
setCachedResult("uuid2", "SELECT ?s WHERE {}", "result2");
|
|
2299
|
+
expect(getCachedResult("uuid1", "SELECT ?s WHERE {}")).toBe("result1");
|
|
2300
|
+
expect(getCachedResult("uuid2", "SELECT ?s WHERE {}")).toBe("result2");
|
|
2301
|
+
});
|
|
2302
|
+
|
|
2303
|
+
it("should cache independently per query", () => {
|
|
2304
|
+
setCachedResult("uuid1", "query1", "r1");
|
|
2305
|
+
setCachedResult("uuid1", "query2", "r2");
|
|
2306
|
+
expect(getCachedResult("uuid1", "query1")).toBe("r1");
|
|
2307
|
+
expect(getCachedResult("uuid1", "query2")).toBe("r2");
|
|
2308
|
+
});
|
|
2309
|
+
|
|
2310
|
+
it("should clear all entries", () => {
|
|
2311
|
+
setCachedResult("uuid1", "q1", "r1");
|
|
2312
|
+
setCachedResult("uuid2", "q2", "r2");
|
|
2313
|
+
expect(queryCacheSize()).toBe(2);
|
|
2314
|
+
clearQueryCache();
|
|
2315
|
+
expect(queryCacheSize()).toBe(0);
|
|
2316
|
+
});
|
|
2317
|
+
});
|
|
2318
|
+
|
|
2319
|
+
describe("SHACL Memoisation", () => {
|
|
2320
|
+
it("should memoise generateSHACL() per class", () => {
|
|
2321
|
+
@Model({ name: "MemoTest1" })
|
|
2322
|
+
class MemoTest1 extends Ad4mModel {
|
|
2323
|
+
@Property({ through: "test://name" })
|
|
2324
|
+
name: string = "";
|
|
2325
|
+
}
|
|
2326
|
+
|
|
2327
|
+
const result1 = (MemoTest1 as any).generateSHACL();
|
|
2328
|
+
const result2 = (MemoTest1 as any).generateSHACL();
|
|
2329
|
+
expect(result1).toBe(result2); // Same reference = memoised
|
|
2330
|
+
});
|
|
2331
|
+
|
|
2332
|
+
it("should memoise getPropertiesMetadata per class", () => {
|
|
2333
|
+
@Model({ name: "PropMemoTest" })
|
|
2334
|
+
class PropMemoTest extends Ad4mModel {
|
|
2335
|
+
@Property({ through: "test://x" })
|
|
2336
|
+
x: string = "";
|
|
2337
|
+
}
|
|
2338
|
+
|
|
2339
|
+
const r1 = getPropertiesMetadata(PropMemoTest);
|
|
2340
|
+
const r2 = getPropertiesMetadata(PropMemoTest);
|
|
2341
|
+
expect(r1).toBe(r2); // Same reference
|
|
2342
|
+
});
|
|
2343
|
+
|
|
2344
|
+
it("should memoise getRelationsMetadata per class", () => {
|
|
2345
|
+
@Model({ name: "RelMemoTest" })
|
|
2346
|
+
class RelMemoTest extends Ad4mModel {
|
|
2347
|
+
@HasMany({ through: "test://items" })
|
|
2348
|
+
items: string[] = [];
|
|
2349
|
+
}
|
|
2350
|
+
|
|
2351
|
+
const r1 = getRelationsMetadata(RelMemoTest);
|
|
2352
|
+
const r2 = getRelationsMetadata(RelMemoTest);
|
|
2353
|
+
expect(r1).toBe(r2); // Same reference
|
|
2354
|
+
});
|
|
2355
|
+
|
|
2356
|
+
it("should return different results for different classes", () => {
|
|
2357
|
+
@Model({ name: "ClassA" })
|
|
2358
|
+
class ClassA extends Ad4mModel {
|
|
2359
|
+
@Property({ through: "test://a" })
|
|
2360
|
+
a: string = "";
|
|
2361
|
+
}
|
|
2362
|
+
|
|
2363
|
+
@Model({ name: "ClassB" })
|
|
2364
|
+
class ClassB extends Ad4mModel {
|
|
2365
|
+
@Property({ through: "test://b" })
|
|
2366
|
+
b: string = "";
|
|
2367
|
+
}
|
|
2368
|
+
|
|
2369
|
+
const propsA = getPropertiesMetadata(ClassA);
|
|
2370
|
+
const propsB = getPropertiesMetadata(ClassB);
|
|
2371
|
+
expect(propsA).not.toBe(propsB);
|
|
2372
|
+
expect(propsA).toHaveProperty("a");
|
|
2373
|
+
expect(propsB).toHaveProperty("b");
|
|
2374
|
+
});
|
|
2375
|
+
});
|
|
2376
|
+
|
|
2377
|
+
describe("Lazy Conformance Filters", () => {
|
|
2378
|
+
it("should defer conformance filter resolution until property access", () => {
|
|
2379
|
+
@Model({ name: "LazyTarget2" })
|
|
2380
|
+
class LazyTarget2 extends Ad4mModel {
|
|
2381
|
+
@Flag({ through: "test://type", value: "test://lazy" })
|
|
2382
|
+
type: string = "test://lazy";
|
|
2383
|
+
@Property({ through: "test://name", required: true })
|
|
2384
|
+
name: string = "";
|
|
2385
|
+
}
|
|
2386
|
+
|
|
2387
|
+
@Model({ name: "LazyParent2" })
|
|
2388
|
+
class LazyParent2 extends Ad4mModel {
|
|
2389
|
+
@HasMany(() => LazyTarget2, { through: "test://children" })
|
|
2390
|
+
children: string[] = [];
|
|
2391
|
+
}
|
|
2392
|
+
|
|
2393
|
+
// generateSHACL was called during @Model — the shape exists
|
|
2394
|
+
const shacl = (LazyParent2 as any).generateSHACL();
|
|
2395
|
+
expect(shacl).toBeDefined();
|
|
2396
|
+
expect(shacl.shape).toBeDefined();
|
|
2397
|
+
expect(shacl.name).toBe("LazyParent2");
|
|
2398
|
+
});
|
|
2399
|
+
});
|
|
2400
|
+
|
|
2401
|
+
// ──────────────────────────────────────────────────────────
|
|
2402
|
+
// instancesFromQueryResult — SPARQL vs JS pagination behaviour
|
|
2403
|
+
// ──────────────────────────────────────────────────────────
|
|
2404
|
+
|
|
2405
|
+
describe("instancesFromQueryResult — SPARQL vs JS pagination", () => {
|
|
2406
|
+
@Model({ name: "PaginationTestChannel" })
|
|
2407
|
+
class PaginationTestChannel extends Ad4mModel {
|
|
2408
|
+
@Flag({ through: "flux://entry_type", value: "flux://channel" })
|
|
2409
|
+
type: string = "";
|
|
2410
|
+
|
|
2411
|
+
@Property({ through: "flux://name", resolveLanguage: "literal" })
|
|
2412
|
+
name: string = "";
|
|
2413
|
+
}
|
|
2414
|
+
|
|
2415
|
+
const mockPerspective: any = {
|
|
2416
|
+
uuid: "test-uuid",
|
|
2417
|
+
querySparql: jest.fn().mockResolvedValue([]),
|
|
2418
|
+
get: jest.fn().mockResolvedValue([]),
|
|
2419
|
+
getExpression: jest.fn().mockResolvedValue(null),
|
|
2420
|
+
};
|
|
2421
|
+
|
|
2422
|
+
it("does NOT slice results when SPARQL pagination was applied", async () => {
|
|
2423
|
+
const grouped = Array.from({ length: 5 }, (_, i) => ({
|
|
2424
|
+
source_uri: `flux://ch-${i}`,
|
|
2425
|
+
links: [
|
|
2426
|
+
{ predicate: "flux://entry_type", target: "flux://channel", author: "did:key:a", timestamp: String(1000 + i) },
|
|
2427
|
+
{ predicate: "flux://name", target: `literal:string:Channel${i}`, author: "did:key:a", timestamp: String(1000 + i) },
|
|
2428
|
+
],
|
|
2429
|
+
}));
|
|
2430
|
+
|
|
2431
|
+
// Include order to trigger SPARQL-level pagination (subquery with ORDER BY)
|
|
2432
|
+
const query = { limit: 5, offset: 10, order: { name: 'ASC' as const } };
|
|
2433
|
+
const result = await (PaginationTestChannel as any).instancesFromQueryResult(mockPerspective, query, grouped);
|
|
2434
|
+
|
|
2435
|
+
// sparqlPaginated = true (limit+offset+order present, no JS-only where filters),
|
|
2436
|
+
// so JS should NOT re-slice — all 5 items come through as-is.
|
|
2437
|
+
expect(result.results.length).toBe(5);
|
|
2438
|
+
expect(result.totalCount).toBe(5);
|
|
2439
|
+
});
|
|
2440
|
+
|
|
2441
|
+
it("applies JS-level slicing as fallback when JS-only filters exist", async () => {
|
|
2442
|
+
const grouped = Array.from({ length: 10 }, (_, i) => ({
|
|
2443
|
+
source_uri: `flux://ch-${i}`,
|
|
2444
|
+
links: [
|
|
2445
|
+
{ predicate: "flux://entry_type", target: "flux://channel", author: "did:key:a", timestamp: String(1000 + i) },
|
|
2446
|
+
{ predicate: "flux://name", target: `literal:string:Ch${i}`, author: "did:key:a", timestamp: String(1000 + i) },
|
|
2447
|
+
],
|
|
2448
|
+
}));
|
|
2449
|
+
|
|
2450
|
+
const query = { limit: 3, offset: 0, where: { author: "did:key:a" } };
|
|
2451
|
+
const result = await (PaginationTestChannel as any).instancesFromQueryResult(mockPerspective, query, grouped);
|
|
2452
|
+
expect(result.results.length).toBe(3);
|
|
2453
|
+
});
|
|
2454
|
+
});
|
|
2455
|
+
|
|
2456
|
+
// ──────────────────────────────────────────────────────────
|
|
2457
|
+
// deepQuery opt-in — getter evaluation on collection queries
|
|
2458
|
+
// ──────────────────────────────────────────────────────────
|
|
2459
|
+
|
|
2460
|
+
describe("deepQuery opt-in — getter evaluation", () => {
|
|
2461
|
+
@Model({ name: "DeepQueryTestMessage" })
|
|
2462
|
+
class DeepQueryTestMessage extends Ad4mModel {
|
|
2463
|
+
@Flag({ through: "flux://entry_type", value: "flux://message" })
|
|
2464
|
+
type: string = "";
|
|
2465
|
+
|
|
2466
|
+
@Property({ through: "flux://body", resolveLanguage: "literal" })
|
|
2467
|
+
body: string = "";
|
|
2468
|
+
|
|
2469
|
+
@Property({
|
|
2470
|
+
through: "flux://has_reply",
|
|
2471
|
+
getter: `SELECT ?target WHERE { ?source <flux://has_reply> ?target . } LIMIT 1`,
|
|
2472
|
+
})
|
|
2473
|
+
replyingTo?: string;
|
|
2474
|
+
|
|
2475
|
+
@ReadOnly({
|
|
2476
|
+
through: "flux://is_popular",
|
|
2477
|
+
getter: `ASK WHERE { ?source <flux://is_popular> "true" . }`,
|
|
2478
|
+
})
|
|
2479
|
+
isPopular: boolean = false;
|
|
2480
|
+
|
|
2481
|
+
@HasMany({ through: "flux://reaction" })
|
|
2482
|
+
reactions: string[] = [];
|
|
2483
|
+
}
|
|
2484
|
+
|
|
2485
|
+
let sparqlCalls: string[];
|
|
2486
|
+
const mockPerspective: any = {
|
|
2487
|
+
uuid: "test-uuid",
|
|
2488
|
+
querySparql: jest.fn(async (q: string) => {
|
|
2489
|
+
sparqlCalls.push(q);
|
|
2490
|
+
return [];
|
|
2491
|
+
}),
|
|
2492
|
+
get: jest.fn().mockResolvedValue([]),
|
|
2493
|
+
getExpression: jest.fn().mockResolvedValue(null),
|
|
2494
|
+
stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue("DeepQueryTestMessage"),
|
|
2495
|
+
};
|
|
2496
|
+
|
|
2497
|
+
beforeEach(() => {
|
|
2498
|
+
sparqlCalls = [];
|
|
2499
|
+
mockPerspective.querySparql.mockClear();
|
|
2500
|
+
mockPerspective.get.mockClear();
|
|
2501
|
+
});
|
|
2502
|
+
|
|
2503
|
+
function makeMessageRows(count: number) {
|
|
2504
|
+
return Array.from({ length: count }, (_, i) => ({
|
|
2505
|
+
source_uri: `flux://msg-${i}`,
|
|
2506
|
+
links: [
|
|
2507
|
+
{ predicate: "flux://entry_type", target: "flux://message", author: "did:key:a", timestamp: String(2000 + i) },
|
|
2508
|
+
{ predicate: "flux://body", target: `literal:string:Hello${i}`, author: "did:key:a", timestamp: String(2000 + i) },
|
|
2509
|
+
],
|
|
2510
|
+
}));
|
|
2511
|
+
}
|
|
2512
|
+
|
|
2513
|
+
it("skips getter evaluation on collection queries by default", async () => {
|
|
2514
|
+
const grouped = makeMessageRows(5);
|
|
2515
|
+
const result = await (DeepQueryTestMessage as any).instancesFromQueryResult(mockPerspective, {}, grouped);
|
|
2516
|
+
expect(result.results.length).toBe(5);
|
|
2517
|
+
|
|
2518
|
+
const getterCalls = sparqlCalls.filter(
|
|
2519
|
+
(q) => q.includes("flux://has_reply") || q.includes("flux://is_popular")
|
|
2520
|
+
);
|
|
2521
|
+
expect(getterCalls.length).toBe(0);
|
|
2522
|
+
});
|
|
2523
|
+
|
|
2524
|
+
it("evaluates getter properties when deepQuery is true", async () => {
|
|
2525
|
+
const grouped = makeMessageRows(3);
|
|
2526
|
+
const result = await (DeepQueryTestMessage as any).instancesFromQueryResult(mockPerspective, { deepQuery: true }, grouped);
|
|
2527
|
+
expect(result.results.length).toBe(3);
|
|
2528
|
+
|
|
2529
|
+
const getterCalls = sparqlCalls.filter(
|
|
2530
|
+
(q) => q.includes("flux://has_reply") || q.includes("flux://is_popular")
|
|
2531
|
+
);
|
|
2532
|
+
expect(getterCalls.length).toBe(6); // 3 instances × 2 getters
|
|
2533
|
+
});
|
|
2534
|
+
|
|
2535
|
+
it("single-instance get() still evaluates getters by default", async () => {
|
|
2536
|
+
const instance = new DeepQueryTestMessage(mockPerspective, "flux://msg-single");
|
|
2537
|
+
mockPerspective.querySparql.mockImplementation(async (q: string) => {
|
|
2538
|
+
sparqlCalls.push(q);
|
|
2539
|
+
if (q.includes("flux://msg-single") && !q.includes("flux://has_reply") && !q.includes("flux://is_popular")) {
|
|
2540
|
+
return [
|
|
2541
|
+
{ source: "flux://msg-single", predicate: "flux://entry_type", target: "flux://message", author: "did:key:a", timestamp: "3000" },
|
|
2542
|
+
{ source: "flux://msg-single", predicate: "flux://body", target: "literal:string:Hello", author: "did:key:a", timestamp: "3000" },
|
|
2543
|
+
];
|
|
2544
|
+
}
|
|
2545
|
+
return [];
|
|
2546
|
+
});
|
|
2547
|
+
|
|
2548
|
+
await instance.get();
|
|
2549
|
+
const getterCalls = sparqlCalls.filter(
|
|
2550
|
+
(q) => q.includes("flux://has_reply") || q.includes("flux://is_popular")
|
|
2551
|
+
);
|
|
2552
|
+
expect(getterCalls.length).toBe(2);
|
|
2553
|
+
});
|
|
2554
|
+
|
|
2555
|
+
describe("Ad4mModel.evaluateGetters()", () => {
|
|
2556
|
+
it("resolves getters for a batch of instances", async () => {
|
|
2557
|
+
const grouped = makeMessageRows(4);
|
|
2558
|
+
const result = await (DeepQueryTestMessage as any).instancesFromQueryResult(mockPerspective, {}, grouped);
|
|
2559
|
+
sparqlCalls = [];
|
|
2560
|
+
|
|
2561
|
+
await DeepQueryTestMessage.evaluateGetters(result.results.slice(0, 2), mockPerspective, ["replyingTo"]);
|
|
2562
|
+
|
|
2563
|
+
const replyCalls = sparqlCalls.filter((q) => q.includes("flux://has_reply"));
|
|
2564
|
+
expect(replyCalls.length).toBe(2);
|
|
2565
|
+
const popularCalls = sparqlCalls.filter((q) => q.includes("flux://is_popular"));
|
|
2566
|
+
expect(popularCalls.length).toBe(0);
|
|
2567
|
+
});
|
|
2568
|
+
|
|
2569
|
+
it("evaluates all getters when propertyNames is omitted", async () => {
|
|
2570
|
+
const grouped = makeMessageRows(2);
|
|
2571
|
+
const result = await (DeepQueryTestMessage as any).instancesFromQueryResult(mockPerspective, {}, grouped);
|
|
2572
|
+
sparqlCalls = [];
|
|
2573
|
+
|
|
2574
|
+
await DeepQueryTestMessage.evaluateGetters(result.results, mockPerspective);
|
|
2575
|
+
|
|
2576
|
+
const replyCalls = sparqlCalls.filter((q) => q.includes("flux://has_reply"));
|
|
2577
|
+
const popularCalls = sparqlCalls.filter((q) => q.includes("flux://is_popular"));
|
|
2578
|
+
expect(replyCalls.length).toBe(2);
|
|
2579
|
+
expect(popularCalls.length).toBe(2);
|
|
2580
|
+
});
|
|
2581
|
+
|
|
2582
|
+
it("handles empty array gracefully", async () => {
|
|
2583
|
+
sparqlCalls = [];
|
|
2584
|
+
await DeepQueryTestMessage.evaluateGetters([], mockPerspective);
|
|
2585
|
+
expect(sparqlCalls.length).toBe(0);
|
|
2586
|
+
});
|
|
2587
|
+
});
|
|
2588
|
+
|
|
2589
|
+
describe("deepQuery via ModelQueryBuilder", () => {
|
|
2590
|
+
it("deepQuery() method sets deepQuery flag on queryParams", () => {
|
|
2591
|
+
const builder = DeepQueryTestMessage.query(mockPerspective);
|
|
2592
|
+
(builder as any).deepQuery();
|
|
2593
|
+
expect((builder as any).queryParams.deepQuery).toBe(true);
|
|
2594
|
+
});
|
|
2595
|
+
});
|
|
2596
|
+
});
|