All files / rdf dataset-view.ts

97.56% Statements 80/82
95.65% Branches 88/92
100% Functions 15/15
97.46% Lines 77/79

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282                                                                                                                                            30079x     30079x 1x     30078x 30078x 30079x 30079x 30079x 30079x       30078x   30078x 4855x     25223x 25223x   25223x 25228x   25228x 25227x 25227x       25223x 25223x   25223x 5x       25223x               54x 14x     40x   40x 16x   16x 6x     24x 26x       40x 40x   40x             6x   6x 12x 6x       6x               1x               1x                 6x       6x 1x     5x       5x 1x     4x 1x     3x                           16x 16x 16x   16x   16x 6x 1x 6x 3x   2x         16x 1x         16x                           48x 41x     7x 5x     2x       30051x       30051x 4845x 30213x 27912x       25206x 25207x          
import * as rdfjs from "@rdfjs/types";
import type { Store } from "./store";
 
/**
 * Options for creating a {@link DatasetView}.
 */
export interface DatasetViewOptions {
    /**
     * URIs of the named graphs to scope the view to. If undefined, the view spans all quads in the store.
     */
    graphUris?: readonly string[];
 
    /**
     * Graph terms to scope the view to. Takes precedence over `graphUris`. Use this to scope
     * the view to graphs that cannot be expressed as URIs, such as the default graph.
     */
    graphs?: readonly rdfjs.Quad_Graph[];
 
    /**
     * Restrict the view to quads with this subject.
     */
    subject?: rdfjs.Term | null;
 
    /**
     * Restrict the view to quads with this predicate.
     */
    predicate?: rdfjs.Term | null;
 
    /**
     * Restrict the view to quads with this object.
     */
    object?: rdfjs.Term | null;
 
    /**
     * Whether to include inferred triples. If undefined, inferred triples are included when a
     * reasoner is available. With graphs, `false` leaves their inference graphs out; without
     * graphs, the view spans every graph of the store and `false` leaves every inference graph
     * out. If `true` without a reasoner, an error is thrown.
     */
    includeInferred?: boolean;
}
 
/**
 * A lazy, read-only RDF/JS DatasetCore view over a {@link Store}, optionally scoped to a set
 * of graphs and a quad pattern. The view does not copy any quads: iteration, counting and
 * containment checks delegate to the store's indexes, so the view always reflects the current
 * contents of the store.
 */
export class DatasetView implements rdfjs.DatasetCore<rdfjs.Quad> {
    private readonly _store: Store;
 
    private readonly _s: rdfjs.Term | null;
 
    private readonly _p: rdfjs.Term | null;
 
    private readonly _o: rdfjs.Term | null;
 
    /**
     * The graph terms the view is scoped to, including inference graphs if enabled.
     * `undefined` means the view spans all graphs; an empty array means the view is provably empty.
     */
    private readonly _scope?: readonly rdfjs.Quad_Graph[];
 
    /**
     * Whether the quads of the inference graphs are left out of a view that spans all graphs.
     */
    private readonly _excludeInferred: boolean;
 
    private _cachedSize?: number;
 
    private _cachedSizeVersion = -1;
 
    constructor(store: Store, options: DatasetViewOptions = {}) {
        if (options.includeInferred === true && !store.reasoner) {
            throw new Error('Reasoner is not available to include inferred triples.');
        }
 
        this._store = store;
        this._s = options.subject ?? null;
        this._p = options.predicate ?? null;
        this._o = options.object ?? null;
        this._scope = DatasetView._resolveScope(store, options);
        this._excludeInferred = this._scope === undefined && options.includeInferred === false && store.reasoner !== undefined;
    }
 
    private static _resolveScope(store: Store, options: DatasetViewOptions): rdfjs.Quad_Graph[] | undefined {
        const graphs = options.graphs ?? options.graphUris?.map(uri => store.dataFactory.namedNode(uri));
 
        if (graphs === undefined) {
            return undefined;
        }
 
        const scope: rdfjs.Quad_Graph[] = [];
        const seen = new Set<string>();
 
        const push = (graph: rdfjs.Quad_Graph) => {
            const key = graph.termType + ':' + graph.value;
 
            if (!seen.has(key)) {
                seen.add(key);
                scope.push(graph);
            }
        };
 
        for (const graph of graphs) {
            push(graph);
 
            if (options.includeInferred !== false && store.reasoner && graph.termType === 'NamedNode') {
                push(store.dataFactory.namedNode(store.reasoner.targetUriGenerator.getGraphUri(graph.value)));
            }
        }
 
        return scope;
    }
 
    /**
     * Get the number of quads in the view. Computed from the store's indexes and memoized
     * until the store is modified.
     */
    get size(): number {
        if (this._cachedSizeVersion === this._store.version && this._cachedSize !== undefined) {
            return this._cachedSize;
        }
 
        let n = 0;
 
        if (this._scope === undefined) {
            n = this._store.countQuads(this._s, this._p, this._o, null);
 
            if (this._excludeInferred) {
                n -= this._countInferred();
            }
        } else {
            for (const graph of this._scope) {
                n += this._store.countQuads(this._s, this._p, this._o, graph);
            }
        }
 
        this._cachedSize = n;
        this._cachedSizeVersion = this._store.version;
 
        return n;
    }
 
    /**
     * Count the quads of the view's pattern in the inference graphs of the store.
     */
    private _countInferred(): number {
        let n = 0;
 
        for (const graphUri of this._store.getGraphs()) {
            if (this._store.isInferenceGraph(graphUri)) {
                n += this._store.countQuads(this._s, this._p, this._o, this._store.dataFactory.namedNode(graphUri));
            }
        }
 
        return n;
    }
 
    /**
     * Not supported: the view is read-only.
     * @throws An error indicating that the view is read-only.
     */
    add(_quad: rdfjs.Quad): this {
        throw new Error('DatasetView is read-only. Mutate the underlying Store instead.');
    }
 
    /**
     * Not supported: the view is read-only.
     * @throws An error indicating that the view is read-only.
     */
    delete(_quad: rdfjs.Quad): this {
        throw new Error('DatasetView is read-only. Mutate the underlying Store instead.');
    }
 
    /**
     * Indicates if the view contains a specific quad.
     * @param quad The quad to be checked.
     * @returns `true` if the quad matches the view's pattern and scope and exists in the store.
     */
    has(quad: rdfjs.Quad): boolean {
        Iif (this._s && !this._s.equals(quad.subject)) {
            return false;
        }
 
        if (this._p && !this._p.equals(quad.predicate)) {
            return false;
        }
 
        Iif (this._o && !this._o.equals(quad.object)) {
            return false;
        }
 
        if (this._scope !== undefined && !this._scope.some(graph => graph.equals(quad.graph))) {
            return false;
        }
 
        if (this._excludeInferred && this._store.isInferenceGraph(quad.graph)) {
            return false;
        }
 
        return this._store.has(quad);
    }
 
    /**
     * Get a new view narrowed to the quads matching the given pattern. The constraints of this
     * view are intersected with the given pattern: a term that conflicts with an existing
     * constraint results in an empty view.
     * @param subject The optional subject.
     * @param predicate The optional predicate.
     * @param object The optional object.
     * @param graph The optional graph.
     * @returns A new read-only dataset view of the matching quads.
     */
    match(subject?: rdfjs.Term | null, predicate?: rdfjs.Term | null, object?: rdfjs.Term | null, graph?: rdfjs.Term | null): DatasetView {
        const s = DatasetView._intersectTerm(this._s, subject);
        const p = DatasetView._intersectTerm(this._p, predicate);
        const o = DatasetView._intersectTerm(this._o, object);
 
        let scope = this._scope;
 
        if (graph != null) {
            if (this._excludeInferred && this._store.isInferenceGraph(graph as rdfjs.Quad_Graph)) {
                scope = [];
            } else if (scope === undefined || scope.some(g => g.equals(graph))) {
                scope = [graph as rdfjs.Quad_Graph];
            } else {
                scope = [];
            }
        }
 
        // A conflicting term constraint makes the view provably empty.
        if (s === undefined || p === undefined || o === undefined) {
            scope = [];
        }
 
        // The scope of this view is already resolved: a scoped view is narrowed to its graphs as
        // they are, a view spanning all graphs keeps excluding the inference graphs if it does.
        return new DatasetView(this._store, {
            subject: s ?? this._s,
            predicate: p ?? this._p,
            object: o ?? this._o,
            graphs: scope,
            includeInferred: scope !== undefined || this._excludeInferred ? false : undefined
        });
    }
 
    /**
     * Intersect an existing term constraint with an incoming one.
     * @returns The effective term constraint, or `undefined` if the terms conflict.
     */
    private static _intersectTerm(current: rdfjs.Term | null, incoming?: rdfjs.Term | null): rdfjs.Term | null | undefined {
        if (incoming == null) {
            return current;
        }
 
        if (current == null) {
            return incoming;
        }
 
        return current.equals(incoming) ? current : undefined;
    }
 
    [Symbol.iterator](): Iterator<rdfjs.Quad> {
        return this._iterate();
    }
 
    private *_iterate(): Generator<rdfjs.Quad> {
        if (this._scope === undefined) {
            for (const quad of this._store.matchQuads(this._s, this._p, this._o, null)) {
                if (!this._excludeInferred || !this._store.isInferenceGraph(quad.graph)) {
                    yield quad;
                }
            }
        } else {
            for (const graph of this._scope) {
                yield* this._store.matchQuads(this._s, this._p, this._o, graph);
            }
        }
    }
}