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