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