All files / languages/sparql/services sparql-result-serializer.ts

83.92% Statements 94/112
68.08% Branches 32/47
87.5% Functions 7/8
83.92% Lines 94/112

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 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302                                      25x             14x   14x 23x   23x 22x           14x                 14x                                           7x 7x   7x     1x 1x   1x 1x     1x   1x     7x 7x   7x 11x         11x 8x 3x 2x 2x 1x 1x 1x 1x     11x     7x 6x   6x 8x 6x     8x     6x     7x 7x   7x 5x   5x 1x       7x             7x                                                                                                                       4x 4x   3x 1x       2x 4x     4x   4x 2x 2x   2x 2x   2x 2x         2x 4x   4x 2x       2x 2x   2x   1x 1x                     14x 14x 1x     13x   13x 9x     4x   4x 5x 5x   5x 5x   5x 5x         4x 4x 4x   4x   3x 1x 1x 1x           12x   1x 1x      
import * as vscode from 'vscode';
import { AsyncIterator } from 'asynciterator';
import { Uri } from '@faubulous/mentor-rdf';
import { rdfDataFactory } from '@src/utilities/rdf';
import { RdfSyntax, SparqlVariableParser } from '@faubulous/mentor-rdf-parsers';
import { ParserFactory } from '@src/languages/parser-factory';
import { SerializationOptions, termToString, TurtleSerializer } from '@faubulous/mentor-rdf-serializers';
import { Bindings, Quad, Term } from "@rdfjs/types";
import { IPrefixLookupService } from '@src/services/document';
import { BindingsResult, SparqlQueryExecutionState } from "./sparql-query-state";
import { toArrayWithCancellation } from '@src/utilities/vscode/cancellation';
import { resolveFormattingConfig } from '@src/utilities/vscode/config';
import { NamespaceMap } from '@src/utilities';
import { getLog } from '@src/utilities/vscode/log';
 
/**
 * Handler for serializing SPARQL query results.
 */
export class SparqlResultSerializer {
	constructor(private readonly _prefixLookupService: IPrefixLookupService) { }
 
	/**
	 * Dedupes triples and drops named-graph terms: Turtle has no graphs, and
	 * the serializer would skip named-graph quads outright.
	 */
	private _prepareQuads(quads: Quad[]): Quad[] {
		const unique = new Map<string, Quad>();
 
		for (const q of quads) {
			const key = `${termToString(q.subject)} ${termToString(q.predicate)} ${termToString(q.object)}`;
 
			if (!unique.has(key)) {
				unique.set(key, q.graph.termType === 'DefaultGraph'
					? q
					: rdfDataFactory.quad(q.subject as any, q.predicate as any, q.object as any));
			}
		}
 
		return [...unique.values()];
	}
 
	/**
	 * Builds pretty-printing serializer options from the `mentor.formatting.*`
	 * settings, mirroring the Format Document defaults. Blank nodes are
	 * relabeled so store-internal ids do not leak into exports.
	 */
	private _buildTurtleOptions(prefixes: Record<string, string>): SerializationOptions {
		return {
			prefixes,
			directiveStyle: 'turtle',
			// prettyPrint gates blank-line and inline-blank-node formatting in the
			// serializer; set it explicitly so exports never depend on the library default.
			prettyPrint: true,
			maxLineWidth: resolveFormattingConfig('turtle', 'maxLineWidth', 120),
			spaceBeforePunctuation: resolveFormattingConfig('turtle', 'spaceBeforePunctuation', true),
			blankLinesBetweenSubjects: resolveFormattingConfig('turtle', 'blankLinesBetweenSubjects', true),
			relabelBlankNodes: true,
		};
	}
 
	/**
	 * Serializes SPARQL query results into a format suitable for the webview.
	 * @param documentIri The IRI of the document where the query was run.
	 * @param bindingStream The SPARQL query results as a BindingsStream.
	 * @param limit The maximum number of results to serialize.
	 * @returns An object containing the serialized results.
	 */
	async serializeBindings(context: SparqlQueryExecutionState, bindingStream: AsyncIterator<Bindings>, token: vscode.CancellationToken): Promise<BindingsResult> {
		// Note: This evaluates the query results and collects the bindings.
		const bindings = await toArrayWithCancellation(bindingStream, token);
		const parsedColumns: string[] = [];
 
		if (context.query) {
			// Shared instances: lexer/parser construction is expensive, and the
			// shared lexer may carry another caller's blank node ID generator.
			const lexer = ParserFactory.getLexer(RdfSyntax.Sparql);
			lexer.blankNodeIdGenerator = undefined;
 
			const lexResult = lexer.tokenize(context.query);
			const cst = ParserFactory.getParser(RdfSyntax.Sparql).parse(lexResult.tokens);
 
			// Parse the variables from select queries in the order they were defined.
			const variables = new SparqlVariableParser().getSelectedVariables(cst);
 
			parsedColumns.push(...variables);
		}
 
		const namespaces = new Set<string>();
		const rows: Record<string, any>[] = [];
 
		const serializeTerm = (value: Term): Record<string, any> => {
			const term: Record<string, any> = {
				termType: value.termType,
				value: value.value,
			};
 
			if (value.termType === 'NamedNode') {
				namespaces.add(Uri.getNamespaceIri(value.value));
			} else if (value.termType === 'Literal') {
				term.datatype = { termType: 'NamedNode', value: value.datatype.value };
				term.language = value.language;
			} else Eif (value.termType === 'Quad') {
				term.subject = serializeTerm(value.subject);
				term.predicate = serializeTerm(value.predicate);
				term.object = serializeTerm(value.object);
			}
 
			return term;
		};
 
		for (const binding of bindings) {
			const row: Record<string, any> = {};
 
			for (const [key, value] of binding) {
				if (!parsedColumns.includes(key.value)) {
					parsedColumns.push(key.value);
				}
 
				row[key.value] = serializeTerm(value);
			}
 
			rows.push(row);
		}
 
		const documentIri = context.documentIri ?? '';
		const namespaceMap: NamespaceMap = {};
 
		for (const iri of namespaces) {
			const prefix = this._prefixLookupService.getPrefixForIri(documentIri, iri, '\0');
 
			if (prefix !== '\0') {
				namespaceMap[iri] = prefix;
			}
		}
 
		const result: BindingsResult = {
			type: 'bindings',
			columns: parsedColumns,
			rows,
			namespaceMap
		};
 
		return result;
	}
 
	/**
	 * Builds a bindings result from a list of IRIs for a single column, without
	 * executing a query. Used to render already-cached data (e.g. auto-loaded
	 * named graphs) in the standard results table.
	 * @param query The SPARQL query the IRIs correspond to; used to derive the column name.
	 * @param iris The IRIs to render, one per row.
	 * @param documentIri The IRI of the document used for prefix resolution.
	 * @returns A BindingsResult mirroring the shape produced by {@link serializeBindings}.
	 */
	serializeIriList(query: string, iris: string[], documentIri: string = ''): BindingsResult {
		let column = 'graph';
 
		try {
			const lexer = ParserFactory.getLexer(RdfSyntax.Sparql);
			lexer.blankNodeIdGenerator = undefined;
 
			const lexResult = lexer.tokenize(query);
			const cst = ParserFactory.getParser(RdfSyntax.Sparql).parse(lexResult.tokens);
			const variables = new SparqlVariableParser().getSelectedVariables(cst);
 
			if (variables.length > 0) {
				column = variables[0];
			}
		} catch {
			// Keep the default column name if the query cannot be parsed.
		}
 
		const namespaceMap: NamespaceMap = {};
		const rows: Record<string, any>[] = [];
 
		for (const iri of iris) {
			const namespace = Uri.getNamespaceIri(iri);
			const prefix = this._prefixLookupService.getPrefixForIri(documentIri, namespace, '\0');
 
			if (prefix !== '\0') {
				namespaceMap[namespace] = prefix;
			}
 
			rows.push({ [column]: { termType: 'NamedNode', value: iri } });
		}
 
		return {
			type: 'bindings',
			columns: [column],
			rows,
			namespaceMap
		};
	}
 
	/**
	 * Serializes a stream of quads into Turtle format.
	 * @param context The query execution context.
	 * @param quadStream The SPARQL query results as a QuadStream.
	 * @param token The cancellation token.
	 * @returns A string containing the serialized Turtle document.
	 */
	async serializeQuads(context: SparqlQueryExecutionState, quadStream: AsyncIterator<Quad>, token: vscode.CancellationToken): Promise<string> {
		try {
			const inputQuads = await toArrayWithCancellation(quadStream, token);
 
			if (inputQuads.length === 0) {
				return '';
			}
 
			// Get namespace prefixes for better formatting
			const documentIri = context.documentIri ?? '';
			const prefixMap: Record<string, string> = {};
 
			// Collect unique namespace IRIs from the quads
			const namespaces = new Set<string>();
 
			for (const quad of inputQuads) {
				Eif (quad.subject.termType === 'NamedNode') {
					namespaces.add(Uri.getNamespaceIri(quad.subject.value));
				}
				Eif (quad.predicate.termType === 'NamedNode') {
					namespaces.add(Uri.getNamespaceIri(quad.predicate.value));
				}
				Eif (quad.object.termType === 'NamedNode') {
					namespaces.add(Uri.getNamespaceIri(quad.object.value));
				}
			}
 
			// Build prefix map
			for (const iri of namespaces) {
				const prefix = this._prefixLookupService.getPrefixForIri(documentIri, iri, '');
 
				if (prefix !== '') {
					prefixMap[prefix] = iri;
				}
			}
 
			const outputQuads = this._prepareQuads(inputQuads);
			const outputOptions = this._buildTurtleOptions(prefixMap);
 
			return new TurtleSerializer().serialize(outputQuads, outputOptions);
		} catch (error) {
			getLog().error('Error serializing quads to Turtle:', error);
			return '';
		}
	}
 
	/**
	 * Serializes an array of quads into Turtle format without requiring a context.
	 * @param quads The array of quads to serialize.
	 * @param namespaces Optional namespace map for prefix resolution.
	 * @returns A string containing the serialized Turtle document.
	 */
	async serializeQuadsToString(quads: Quad[], namespaces?: Record<string, string>): Promise<string> {
		try {
			if (quads.length === 0) {
				return '';
			}
 
			const prefixMap: Record<string, string> = {};
 
			if (namespaces) {
				Object.assign(prefixMap, namespaces);
			} else {
				// Collect unique namespace IRIs from the quads
				const namespaceIris = new Set<string>();
 
				for (const quad of quads) {
					Eif (quad.subject.termType === 'NamedNode') {
						namespaceIris.add(Uri.getNamespaceIri(quad.subject.value));
					}
					Eif (quad.predicate.termType === 'NamedNode') {
						namespaceIris.add(Uri.getNamespaceIri(quad.predicate.value));
					}
					Eif (quad.object.termType === 'NamedNode') {
						namespaceIris.add(Uri.getNamespaceIri(quad.object.value));
					}
				}
 
				// Build prefix map using inference prefixes and default prefixes
				const inferencePrefixes = this._prefixLookupService.getInferencePrefixes();
				const defaultPrefixes = this._prefixLookupService.getDefaultPrefixes();
				const allPrefixes = { ...inferencePrefixes, ...defaultPrefixes };
 
				for (const iri of namespaceIris) {
					// allPrefixes is { prefix: iri }, so we need to find the prefix for this iri
					for (const [prefix, prefixIri] of Object.entries(allPrefixes)) {
						Eif (prefixIri === iri) {
							prefixMap[prefix] = iri;
							break;
						}
					}
				}
			}
 
			return new TurtleSerializer().serialize(this._prepareQuads(quads), this._buildTurtleOptions(prefixMap));
		} catch (error) {
			getLog().error('Error serializing quads to Turtle:', error);
			return '';
		}
	}
}