@coasys/ad4m 0.13.0-test-2 → 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 +1060 -147
- package/lib/index.js +1054 -147
- package/lib/src/index.d.ts +0 -1
- package/lib/src/index.js +0 -1
- package/lib/src/language/Language.d.ts +26 -214
- package/lib/src/language/Language.js +28 -2
- package/lib/src/model/Ad4mModel.d.ts +25 -1
- package/lib/src/model/Ad4mModel.js +139 -30
- package/lib/src/model/Ad4mModel.test.js +214 -32
- package/lib/src/model/ModelQueryBuilder.d.ts +19 -0
- package/lib/src/model/ModelQueryBuilder.js +62 -18
- 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 +1 -0
- package/lib/src/model/hydration.js +279 -70
- package/lib/src/model/query-sparql.d.ts +78 -1
- package/lib/src/model/query-sparql.js +447 -16
- 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/query-utils.js +4 -0
- 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.js +48 -2
- package/lib/src/model/types.d.ts +49 -1
- package/lib/src/perspectives/PerspectiveClient.d.ts +2 -0
- package/lib/src/perspectives/PerspectiveClient.js +37 -9
- 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 +3 -0
- package/lib/src/perspectives/PerspectiveProxy.js +15 -0
- package/package.json +1 -1
- package/src/Ad4mClient.test.ts +56 -1
- package/src/index.ts +0 -1
- package/src/language/Language.ts +54 -275
- package/src/model/Ad4mModel.test.ts +222 -35
- package/src/model/Ad4mModel.ts +144 -30
- package/src/model/ModelQueryBuilder.ts +66 -18
- package/src/model/hydration-batching.test.ts +563 -0
- package/src/model/hydration.ts +249 -47
- package/src/model/query-sparql.test.ts +568 -0
- package/src/model/query-sparql.ts +473 -16
- package/src/model/query-utils.ts +4 -0
- package/src/model/subscription-delta.test.ts +207 -0
- package/src/model/subscription-pool.ts +50 -2
- package/src/model/types.ts +50 -1
- package/src/perspectives/PerspectiveClient.test.ts +204 -0
- package/src/perspectives/PerspectiveClient.ts +36 -7
- package/src/perspectives/PerspectiveProxy.ts +18 -0
- package/lib/src/model/query-surreal.d.ts +0 -44
- package/lib/src/model/query-surreal.js +0 -249
- package/lib/src/model/surreal-utils.d.ts +0 -42
- package/lib/src/model/surreal-utils.js +0 -128
- package/src/language/LanguageContext.ts +0 -37
- package/tsconfig-browser.json +0 -82
|
@@ -11,6 +11,7 @@ import { LinkQuery } from "../perspectives/LinkQuery";
|
|
|
11
11
|
import { getPropertiesMetadata, getRelationsMetadata, buildConformanceFilter } from "./decorators";
|
|
12
12
|
import { compileWhereClause } from "./query-utils";
|
|
13
13
|
import { escapeQueryString } from "../utils";
|
|
14
|
+
import { buildSPARQLGroupedCountQuery, parseSparqlGroupedCount } from "./query-sparql";
|
|
14
15
|
// ──────────────────────────────────────────────────────────
|
|
15
16
|
// Pure helpers
|
|
16
17
|
// ──────────────────────────────────────────────────────────
|
|
@@ -394,41 +395,44 @@ export async function evaluateCustomGettersForInstance(instance, perspective, me
|
|
|
394
395
|
// evaluate getters for fields that are requested (or included).
|
|
395
396
|
const projectionActive = options?.requestedProperties && options.requestedProperties.length > 0;
|
|
396
397
|
const projectionSet = projectionActive ? new Set(options.requestedProperties) : null;
|
|
397
|
-
// Evaluate property getters
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
398
|
+
// Evaluate property getters (skip when caller only wants relation type-filtering)
|
|
399
|
+
if (!options?.skipPropertyGetters) {
|
|
400
|
+
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
401
|
+
if (projectionSet && !projectionSet.has(propName))
|
|
402
|
+
continue;
|
|
403
|
+
if (propMeta.getter) {
|
|
404
|
+
try {
|
|
405
|
+
const rawGetter = propMeta.getter;
|
|
406
|
+
const getterWithBase = rawGetter.replace(/\?source\b/g, `<${instance.id}>`).replace(/<Base>/g, `<${instance.id}>`).replace(/Base/g, `<${instance.id}>`);
|
|
407
|
+
// If the getter is already SPARQL (starts with SELECT/ASK/CONSTRUCT), execute directly
|
|
408
|
+
const trimmed = getterWithBase.trim().toUpperCase();
|
|
409
|
+
if (trimmed.startsWith('SELECT') || trimmed.startsWith('ASK') || trimmed.startsWith('CONSTRUCT')) {
|
|
410
|
+
const result = await perspective.querySparql(getterWithBase);
|
|
411
|
+
if (trimmed.startsWith('ASK')) {
|
|
412
|
+
instance[propName] = result === true || result === 'true';
|
|
413
|
+
}
|
|
414
|
+
else if (result && result.length > 0) {
|
|
415
|
+
// Get first binding's first value
|
|
416
|
+
const firstRow = result[0];
|
|
417
|
+
const firstKey = Object.keys(firstRow)[0];
|
|
418
|
+
const val = firstRow[firstKey]?.value ?? firstRow[firstKey];
|
|
419
|
+
if (val !== undefined && val !== null && val !== 'None' && val !== '') {
|
|
420
|
+
instance[propName] = val;
|
|
421
|
+
}
|
|
419
422
|
}
|
|
420
423
|
}
|
|
424
|
+
else {
|
|
425
|
+
// Legacy SurrealDB-style getter — safety guard for getters that don't match
|
|
426
|
+
// SPARQL patterns (SELECT/ASK). Logs a warning but does not crash.
|
|
427
|
+
console.warn(`Unsupported legacy getter syntax for property ${propName} — use native SPARQL (SELECT/ASK): ${rawGetter.slice(0, 100)}`);
|
|
428
|
+
}
|
|
421
429
|
}
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
console.warn(`Unsupported legacy getter syntax for property ${propName} — use native SPARQL (SELECT/ASK): ${rawGetter.slice(0, 100)}`);
|
|
430
|
+
catch (error) {
|
|
431
|
+
console.warn(`Failed to evaluate getter for ${propName}:`, error);
|
|
425
432
|
}
|
|
426
433
|
}
|
|
427
|
-
catch (error) {
|
|
428
|
-
console.warn(`Failed to evaluate getter for ${propName}:`, error);
|
|
429
|
-
}
|
|
430
434
|
}
|
|
431
|
-
}
|
|
435
|
+
} // end skipPropertyGetters guard
|
|
432
436
|
// Evaluate relation getters (explicit or auto-generated from target)
|
|
433
437
|
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
434
438
|
// Skip relations excluded by property projection (unless in include map)
|
|
@@ -508,7 +512,8 @@ export async function evaluateCustomGettersForInstance(instance, perspective, me
|
|
|
508
512
|
}
|
|
509
513
|
}
|
|
510
514
|
else {
|
|
511
|
-
// Legacy SurrealDB-style getter —
|
|
515
|
+
// Legacy SurrealDB-style getter — safety guard for relation getters that don't
|
|
516
|
+
// match SPARQL patterns (SELECT/ASK). Logs a warning but does not crash.
|
|
512
517
|
console.warn(`Unsupported legacy getter syntax for relation ${relName} — use native SPARQL (SELECT/ASK): ${getter.slice(0, 100)}`);
|
|
513
518
|
}
|
|
514
519
|
}
|
|
@@ -564,7 +569,166 @@ export async function hydrateRelations(modelClass, instances, perspective, inclu
|
|
|
564
569
|
if (!includeMap || Object.keys(includeMap).length === 0)
|
|
565
570
|
return;
|
|
566
571
|
const relMeta = getRelationsMetadata(modelClass);
|
|
572
|
+
// ── Projections ($-prefixed keys) ────────────────────────────────────────
|
|
573
|
+
// Collect all projection entries up-front so we can batch the count queries
|
|
574
|
+
// together per-projection before processing. Each projection key starts
|
|
575
|
+
// with '$' and has a descriptor with a `from` field.
|
|
576
|
+
const projectionEntries = [];
|
|
577
|
+
for (const [key, val] of Object.entries(includeMap)) {
|
|
578
|
+
if (key.startsWith('$') && val !== null && typeof val === 'object' && 'from' in val) {
|
|
579
|
+
projectionEntries.push([key, val]);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
for (const [projKey, proj] of projectionEntries) {
|
|
583
|
+
const sourceMeta = relMeta[proj.from];
|
|
584
|
+
if (!sourceMeta) {
|
|
585
|
+
console.warn(`include projection "${projKey}": relation "${proj.from}" not found in metadata, skipping`);
|
|
586
|
+
for (const inst of instances)
|
|
587
|
+
inst[projKey] = proj.count ? 0 : [];
|
|
588
|
+
continue;
|
|
589
|
+
}
|
|
590
|
+
const TargetClass = sourceMeta.target();
|
|
591
|
+
const allParentIds = instances.map(inst => inst.id).filter(Boolean);
|
|
592
|
+
if (proj.count) {
|
|
593
|
+
// ── Path A: grouped SPARQL COUNT ─────────────────────────────────────
|
|
594
|
+
// One round-trip, zero instance hydration. Returns one row per parent.
|
|
595
|
+
const targetMetadata = TargetClass.getModelMetadata?.() ?? null;
|
|
596
|
+
const targetRelMeta = TargetClass.getAllRelationsMetadata?.() ?? {};
|
|
597
|
+
let countMap = new Map();
|
|
598
|
+
if (targetMetadata && allParentIds.length > 0) {
|
|
599
|
+
try {
|
|
600
|
+
const sparql = buildSPARQLGroupedCountQuery(targetMetadata, targetRelMeta, sourceMeta.predicate, allParentIds, proj.where);
|
|
601
|
+
const raw = await perspective.querySparql(sparql);
|
|
602
|
+
const rows = Array.isArray(raw) ? raw
|
|
603
|
+
: raw?.results?.bindings ?? raw?.bindings ?? [];
|
|
604
|
+
countMap = parseSparqlGroupedCount(rows);
|
|
605
|
+
}
|
|
606
|
+
catch (e) {
|
|
607
|
+
console.warn(`include projection "${projKey}" count query failed, falling back to 0:`, e);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
for (const inst of instances) {
|
|
611
|
+
inst[projKey] = countMap.get(inst.id) ?? 0;
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
else {
|
|
615
|
+
// ── Path B: findAll + Map distribution ───────────────────────────────
|
|
616
|
+
// For reverse relations we don't have the child IDs on the instance,
|
|
617
|
+
// so fall back to a parent-scoped findAll per instance (uncommon path).
|
|
618
|
+
const isReverse = sourceMeta.kind === 'belongsToOne' || sourceMeta.kind === 'belongsToMany';
|
|
619
|
+
if (isReverse) {
|
|
620
|
+
// Reverse: the link goes child→parent, reuse the batched SPARQL pattern
|
|
621
|
+
// from the existing belongsTo path to collect source IDs per parent.
|
|
622
|
+
if (allParentIds.length > 0) {
|
|
623
|
+
const sparqlQuery = `SELECT ?source ?target WHERE {
|
|
624
|
+
GRAPH ?g { ?source <${sourceMeta.predicate}> ?target }
|
|
625
|
+
FILTER(?target IN (${allParentIds.map(id => `<${id}>`).join(', ')}))
|
|
626
|
+
}`;
|
|
627
|
+
const sourcesByTarget = new Map();
|
|
628
|
+
try {
|
|
629
|
+
const raw = await perspective.querySparql(sparqlQuery);
|
|
630
|
+
const bindings = Array.isArray(raw) ? raw : raw?.results?.bindings ?? raw?.bindings ?? [];
|
|
631
|
+
for (const row of bindings) {
|
|
632
|
+
const source = row.source?.value ?? row.source;
|
|
633
|
+
const target = row.target?.value ?? row.target;
|
|
634
|
+
if (!source || !target)
|
|
635
|
+
continue;
|
|
636
|
+
if (!sourcesByTarget.has(target))
|
|
637
|
+
sourcesByTarget.set(target, []);
|
|
638
|
+
sourcesByTarget.get(target).push(source);
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
catch (e) {
|
|
642
|
+
console.warn(`include projection "${projKey}" reverse SPARQL failed:`, e);
|
|
643
|
+
}
|
|
644
|
+
const allSourceIds = new Set();
|
|
645
|
+
for (const ids of sourcesByTarget.values())
|
|
646
|
+
for (const id of ids)
|
|
647
|
+
allSourceIds.add(id);
|
|
648
|
+
const hydratedMap = new Map();
|
|
649
|
+
if (allSourceIds.size > 0) {
|
|
650
|
+
const results = await TargetClass.findAll(perspective, {
|
|
651
|
+
where: { id: Array.from(allSourceIds), ...(proj.where ?? {}) },
|
|
652
|
+
});
|
|
653
|
+
for (const r of results)
|
|
654
|
+
hydratedMap.set(r.id, r);
|
|
655
|
+
}
|
|
656
|
+
for (const inst of instances) {
|
|
657
|
+
const sourceIds = sourcesByTarget.get(inst.id) ?? [];
|
|
658
|
+
let resolved = sourceIds.map(id => hydratedMap.get(id)).filter((v) => v != null);
|
|
659
|
+
if (proj.limit != null) {
|
|
660
|
+
if (proj.limit === 1) {
|
|
661
|
+
inst[projKey] = resolved[0] ?? null;
|
|
662
|
+
}
|
|
663
|
+
else {
|
|
664
|
+
inst[projKey] = resolved.slice(0, proj.limit);
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
else {
|
|
668
|
+
inst[projKey] = resolved;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
else {
|
|
673
|
+
for (const inst of instances)
|
|
674
|
+
inst[projKey] = proj.limit === 1 ? null : [];
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
else {
|
|
678
|
+
// Forward: instance[from] holds raw child URIs — collect across all parents
|
|
679
|
+
const uriSet = new Set();
|
|
680
|
+
const rawCache = new Map();
|
|
681
|
+
for (const inst of instances) {
|
|
682
|
+
const raw = inst[proj.from];
|
|
683
|
+
const uris = [];
|
|
684
|
+
if (Array.isArray(raw)) {
|
|
685
|
+
for (const v of raw) {
|
|
686
|
+
const id = typeof v === 'string' ? v : v?.id;
|
|
687
|
+
if (id) {
|
|
688
|
+
uriSet.add(id);
|
|
689
|
+
uris.push(id);
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
else if (typeof raw === 'string') {
|
|
694
|
+
uriSet.add(raw);
|
|
695
|
+
uris.push(raw);
|
|
696
|
+
}
|
|
697
|
+
else if (raw?.id) {
|
|
698
|
+
uriSet.add(raw.id);
|
|
699
|
+
uris.push(raw.id);
|
|
700
|
+
}
|
|
701
|
+
rawCache.set(inst, uris);
|
|
702
|
+
}
|
|
703
|
+
const hydratedMap = new Map();
|
|
704
|
+
if (uriSet.size > 0) {
|
|
705
|
+
const results = await TargetClass.findAll(perspective, {
|
|
706
|
+
where: { id: Array.from(uriSet), ...(proj.where ?? {}) },
|
|
707
|
+
});
|
|
708
|
+
for (const r of results)
|
|
709
|
+
hydratedMap.set(r.id, r);
|
|
710
|
+
}
|
|
711
|
+
for (const inst of instances) {
|
|
712
|
+
const uris = rawCache.get(inst) ?? [];
|
|
713
|
+
const resolved = uris.map(id => hydratedMap.get(id)).filter((v) => v != null);
|
|
714
|
+
if (proj.limit === 1) {
|
|
715
|
+
inst[projKey] = resolved[0] ?? null;
|
|
716
|
+
}
|
|
717
|
+
else if (proj.limit != null) {
|
|
718
|
+
inst[projKey] = resolved.slice(0, proj.limit);
|
|
719
|
+
}
|
|
720
|
+
else {
|
|
721
|
+
inst[projKey] = resolved;
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
// ── Standard relations (non-projected) ───────────────────────────────────
|
|
567
728
|
for (const [relName, includeValue] of Object.entries(includeMap)) {
|
|
729
|
+
// Skip projection keys — already handled above
|
|
730
|
+
if (relName.startsWith('$') && typeof includeValue === 'object' && includeValue !== null && 'from' in includeValue)
|
|
731
|
+
continue;
|
|
568
732
|
const meta = relMeta[relName];
|
|
569
733
|
if (!meta) {
|
|
570
734
|
console.warn(`include: relation "${relName}" not found in metadata, skipping`);
|
|
@@ -579,57 +743,102 @@ export async function hydrateRelations(modelClass, instances, perspective, inclu
|
|
|
579
743
|
// ── Reverse relations (belongsToOne / belongsToMany) ──────────────────
|
|
580
744
|
// The link goes target→instance, so we query backwards:
|
|
581
745
|
// predicate = meta.predicate, target = inst.id → source is the related id
|
|
746
|
+
//
|
|
747
|
+
// PERF: Batch all reverse lookups into a single SPARQL query instead of
|
|
748
|
+
// N sequential perspective.get() calls (N+1 → 1 optimisation).
|
|
582
749
|
if (meta.kind === 'belongsToOne' || meta.kind === 'belongsToMany') {
|
|
583
|
-
|
|
750
|
+
const allIds = instances.map(inst => inst.id).filter(Boolean);
|
|
751
|
+
// Batch query: find all (source, target) pairs for this predicate
|
|
752
|
+
// where target is one of our instance IDs
|
|
753
|
+
const sourcesByTarget = new Map();
|
|
754
|
+
if (allIds.length > 0) {
|
|
755
|
+
const sparqlQuery = `SELECT ?source ?target WHERE {
|
|
756
|
+
GRAPH ?g { ?source <${meta.predicate}> ?target }
|
|
757
|
+
FILTER(?target IN (${allIds.map(id => `<${id}>`).join(', ')}))
|
|
758
|
+
}`;
|
|
759
|
+
try {
|
|
760
|
+
const sparqlResult = await perspective.querySparql(sparqlQuery);
|
|
761
|
+
// Parse SPARQL results — querySparql returns a flat array of row objects
|
|
762
|
+
// e.g. [{ source: "uri1", target: "uri2" }, ...]
|
|
763
|
+
const bindings = Array.isArray(sparqlResult) ? sparqlResult
|
|
764
|
+
: sparqlResult?.results?.bindings ?? sparqlResult?.bindings ?? [];
|
|
765
|
+
for (const row of bindings) {
|
|
766
|
+
const source = row.source?.value ?? row.source;
|
|
767
|
+
const target = row.target?.value ?? row.target;
|
|
768
|
+
if (!source || !target)
|
|
769
|
+
continue;
|
|
770
|
+
if (!sourcesByTarget.has(target))
|
|
771
|
+
sourcesByTarget.set(target, []);
|
|
772
|
+
sourcesByTarget.get(target).push(source);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
catch (e) {
|
|
776
|
+
// Fallback: sequential queries if SPARQL fails
|
|
777
|
+
console.warn('Batched reverse relation SPARQL failed, falling back to sequential:', e);
|
|
778
|
+
for (const inst of instances) {
|
|
779
|
+
const reverseLinks = await perspective.get(new LinkQuery({ predicate: meta.predicate, target: inst.id }));
|
|
780
|
+
const sourceIds = reverseLinks
|
|
781
|
+
.filter(l => l.data.target === inst.id)
|
|
782
|
+
.map(l => l.data.source);
|
|
783
|
+
if (sourceIds.length > 0) {
|
|
784
|
+
sourcesByTarget.set(inst.id, sourceIds);
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
// Collect ALL source IDs across all instances for batch hydration
|
|
790
|
+
const allSourceIds = new Set();
|
|
791
|
+
for (const ids of sourcesByTarget.values()) {
|
|
792
|
+
for (const id of ids)
|
|
793
|
+
allSourceIds.add(id);
|
|
794
|
+
}
|
|
795
|
+
// Batch-hydrate all related instances at once (1 findAll instead of N)
|
|
796
|
+
const hydratedMap = new Map();
|
|
797
|
+
if (allSourceIds.size > 0) {
|
|
798
|
+
const fetchQuery = {
|
|
799
|
+
where: {
|
|
800
|
+
id: Array.from(allSourceIds),
|
|
801
|
+
...(subQuery?.where ?? {}),
|
|
802
|
+
},
|
|
803
|
+
...(subQuery?.order && { order: subQuery.order }),
|
|
804
|
+
...(subQuery?.properties && { properties: subQuery.properties }),
|
|
805
|
+
};
|
|
806
|
+
try {
|
|
807
|
+
const allResults = await TargetClass.findAll(perspective, fetchQuery);
|
|
808
|
+
for (const r of allResults)
|
|
809
|
+
hydratedMap.set(r.id, r);
|
|
810
|
+
}
|
|
811
|
+
catch {
|
|
812
|
+
// Fallback: hydrate individually
|
|
813
|
+
await Promise.all(Array.from(allSourceIds).map(async (sid) => {
|
|
814
|
+
try {
|
|
815
|
+
const related = new TargetClass(perspective, sid);
|
|
816
|
+
await related.get(subQuery?.properties ? { properties: subQuery.properties } : undefined);
|
|
817
|
+
hydratedMap.set(sid, related);
|
|
818
|
+
}
|
|
819
|
+
catch { /* skip */ }
|
|
820
|
+
}));
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
// Assign hydrated instances to each parent
|
|
584
824
|
for (const inst of instances) {
|
|
585
|
-
const
|
|
586
|
-
|
|
587
|
-
// we only use links that genuinely point to this instance.
|
|
588
|
-
const sourceIds = reverseLinks
|
|
589
|
-
.filter(l => l.data.target === inst.id)
|
|
590
|
-
.map(l => l.data.source);
|
|
825
|
+
const instId = inst.id;
|
|
826
|
+
const sourceIds = sourcesByTarget.get(instId) ?? [];
|
|
591
827
|
if (meta.kind === 'belongsToOne') {
|
|
592
828
|
if (sourceIds.length === 0) {
|
|
593
829
|
inst[relName] = null;
|
|
594
830
|
continue;
|
|
595
831
|
}
|
|
596
832
|
const sourceId = sourceIds[sourceIds.length - 1]; // latest-wins
|
|
597
|
-
|
|
598
|
-
const related = new TargetClass(perspective, sourceId);
|
|
599
|
-
await related.get();
|
|
600
|
-
inst[relName] = related;
|
|
601
|
-
}
|
|
602
|
-
catch {
|
|
603
|
-
inst[relName] = null;
|
|
604
|
-
}
|
|
833
|
+
inst[relName] = hydratedMap.get(sourceId) ?? null;
|
|
605
834
|
}
|
|
606
835
|
else {
|
|
607
836
|
// belongsToMany — return array of hydrated instances
|
|
608
|
-
let hydrated =
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
...(subQuery.where ?? {}),
|
|
614
|
-
};
|
|
615
|
-
hydrated = await TargetClass.findAll(perspective, {
|
|
616
|
-
where: whereWithIds,
|
|
617
|
-
...(subQuery.order && { order: subQuery.order }),
|
|
618
|
-
...(subQuery.properties && { properties: subQuery.properties }),
|
|
619
|
-
});
|
|
620
|
-
}
|
|
621
|
-
else {
|
|
622
|
-
await Promise.all(sourceIds.map(async (sid) => {
|
|
623
|
-
try {
|
|
624
|
-
const related = new TargetClass(perspective, sid);
|
|
625
|
-
await related.get(subQuery?.properties ? { properties: subQuery.properties } : undefined);
|
|
626
|
-
hydrated.push(related);
|
|
627
|
-
}
|
|
628
|
-
catch { /* skip */ }
|
|
629
|
-
}));
|
|
630
|
-
}
|
|
631
|
-
// Apply order (client-side, if not already handled by findAll above)
|
|
632
|
-
if (subQuery?.order && !(subQuery.where || subQuery.properties)) {
|
|
837
|
+
let hydrated = sourceIds
|
|
838
|
+
.map(sid => hydratedMap.get(sid))
|
|
839
|
+
.filter((v) => v != null);
|
|
840
|
+
// Apply order (client-side)
|
|
841
|
+
if (subQuery?.order) {
|
|
633
842
|
const orderEntries = Object.entries(subQuery.order);
|
|
634
843
|
hydrated = hydrated.sort((a, b) => {
|
|
635
844
|
for (const [field, dir] of orderEntries) {
|
|
@@ -9,7 +9,21 @@
|
|
|
9
9
|
* @module
|
|
10
10
|
*/
|
|
11
11
|
import type { RelationMetadataEntry } from "./decorators";
|
|
12
|
-
import type { Query, ModelMetadata } from "./types";
|
|
12
|
+
import type { Where, Query, ModelMetadata } from "./types";
|
|
13
|
+
/**
|
|
14
|
+
* Check whether a `where` clause contains filters that cannot be pushed down
|
|
15
|
+
* to SPARQL and must be evaluated in JS after hydration.
|
|
16
|
+
*
|
|
17
|
+
* JS-only filters include:
|
|
18
|
+
* - Literal-stored properties (equality, comparison, contains, etc.)
|
|
19
|
+
* - Reverse relations (belongsToOne / belongsToMany)
|
|
20
|
+
* - author / timestamp filters (skipped by buildSPARQLWhereFilters)
|
|
21
|
+
*
|
|
22
|
+
* When JS-only filters exist, SPARQL-level LIMIT/OFFSET must NOT be applied
|
|
23
|
+
* because the database would cap the candidate set before JS filters run,
|
|
24
|
+
* potentially discarding matches beyond the LIMIT.
|
|
25
|
+
*/
|
|
26
|
+
export declare function hasJsOnlyWhereFilters(metadata: ModelMetadata, allRelationsMetadata: Record<string, RelationMetadataEntry>, where?: Where): boolean;
|
|
13
27
|
/**
|
|
14
28
|
* Format a value as a SPARQL string literal (double-quoted).
|
|
15
29
|
*/
|
|
@@ -22,6 +36,36 @@ export declare function formatSPARQLValue(value: any): string;
|
|
|
22
36
|
* with named graph storage and metadata keyed by graph IRI.
|
|
23
37
|
*/
|
|
24
38
|
export declare function buildSPARQLQuery(metadata: ModelMetadata, allRelationsMetadata: Record<string, RelationMetadataEntry>, query: Query, modelClass: any): string;
|
|
39
|
+
/**
|
|
40
|
+
* Build ORDER BY / LIMIT / OFFSET clauses for the SPARQL query.
|
|
41
|
+
*
|
|
42
|
+
* NOTE: The outer SELECT returns multiple rows per instance (one per link),
|
|
43
|
+
* so LIMIT/OFFSET at the outer level would cut off links mid-instance.
|
|
44
|
+
* This function is kept for backward compatibility and always returns "".
|
|
45
|
+
* SPARQL-level pagination is handled via a subquery in buildSPARQLQuery
|
|
46
|
+
* using buildPaginationSubquery().
|
|
47
|
+
*/
|
|
48
|
+
export declare function buildSPARQLOrderLimitOffset(_metadata: ModelMetadata, query: Query): string;
|
|
49
|
+
/**
|
|
50
|
+
* Build an inner subquery that selects DISTINCT ?source URIs with
|
|
51
|
+
* ORDER BY, LIMIT, and OFFSET applied at the instance level.
|
|
52
|
+
*
|
|
53
|
+
* Because the outer SELECT returns multiple rows per instance (one per link),
|
|
54
|
+
* we cannot apply LIMIT/OFFSET there. Instead this subquery constrains
|
|
55
|
+
* ?source to only the instances on the requested page.
|
|
56
|
+
*
|
|
57
|
+
* @internal — used by buildSPARQLQuery when SPARQL-level pagination is safe.
|
|
58
|
+
*/
|
|
59
|
+
export declare function buildPaginationSubquery(joinPatterns: string[], filterExpressions: string[], metadata: ModelMetadata, query: Query): string;
|
|
60
|
+
/**
|
|
61
|
+
* Build a SPARQL COUNT query that returns the total number of matching
|
|
62
|
+
* instances WITHOUT hydrating them. Uses the same WHERE clause as
|
|
63
|
+
* buildSPARQLQuery but wraps it in SELECT (COUNT(DISTINCT ?source) AS ?count).
|
|
64
|
+
*
|
|
65
|
+
* LIMIT/OFFSET from the query are stripped internally — this always counts
|
|
66
|
+
* the full result set.
|
|
67
|
+
*/
|
|
68
|
+
export declare function buildSPARQLCountQuery(metadata: ModelMetadata, allRelationsMetadata: Record<string, RelationMetadataEntry>, query: Query, modelClass: any): string;
|
|
25
69
|
/**
|
|
26
70
|
* Build a SPARQL query to fetch all links for a single instance.
|
|
27
71
|
*/
|
|
@@ -45,3 +89,36 @@ export declare function groupSPARQLResults(rows: Array<{
|
|
|
45
89
|
timestamp: string;
|
|
46
90
|
}>;
|
|
47
91
|
}>;
|
|
92
|
+
/**
|
|
93
|
+
* Parse a SPARQL COUNT result row into a number.
|
|
94
|
+
* Handles `row.count?.value` (RDF binding), `row.count` (direct number/string),
|
|
95
|
+
* NaN results, and empty/malformed results.
|
|
96
|
+
*
|
|
97
|
+
* @returns The parsed count, or `null` if the result cannot be interpreted.
|
|
98
|
+
*/
|
|
99
|
+
export declare function parseSparqlCount(result: any[]): number | null;
|
|
100
|
+
/**
|
|
101
|
+
* Build a SPARQL query that counts child instances grouped by parent IRI.
|
|
102
|
+
*
|
|
103
|
+
* Used by the projection Path A (`count: true`) in `hydrateRelations` to get
|
|
104
|
+
* per-parent counts in a single round-trip with zero instance hydration.
|
|
105
|
+
*
|
|
106
|
+
* Includes the full named graph block so that `?author` and `?timestamp` are
|
|
107
|
+
* bound and available for SPARQL FILTER expressions (unlike the intentionally
|
|
108
|
+
* minimal `buildSPARQLCountQuery` which omits them for speed).
|
|
109
|
+
*
|
|
110
|
+
* @param metadata - Model metadata for the **child** (target) class
|
|
111
|
+
* @param allRelationsMetadata - Relations metadata for the child class
|
|
112
|
+
* @param relationPredicate - The predicate linking `?parent` → `?source` (child)
|
|
113
|
+
* @param parentIds - IRI strings of all parent instances to count for
|
|
114
|
+
* @param where - Optional filter applied to child instances
|
|
115
|
+
*/
|
|
116
|
+
export declare function buildSPARQLGroupedCountQuery(metadata: ModelMetadata, allRelationsMetadata: Record<string, RelationMetadataEntry>, relationPredicate: string, parentIds: string[], where?: import('./types').Where): string;
|
|
117
|
+
/**
|
|
118
|
+
* Parse the result of `buildSPARQLGroupedCountQuery` into a map from parent IRI
|
|
119
|
+
* to count. Missing parents (zero matches) are absent from the map — callers
|
|
120
|
+
* should use `map.get(id) ?? 0`.
|
|
121
|
+
*
|
|
122
|
+
* @returns Map from parentId string → count number
|
|
123
|
+
*/
|
|
124
|
+
export declare function parseSparqlGroupedCount(result: any[]): Map<string, number>;
|