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

100% Statements 101/101
78.94% Branches 30/38
100% Functions 9/9
100% Lines 101/101

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                                19x                               7x 7x   7x 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                             5x 5x   4x 1x       3x     3x 3x       3x 3x     3x   3x 3x 3x   3x 3x   3x 3x         3x 5x   5x 2x         3x         3x     3x 3x 3x 1x   2x         1x 1x                     7x 7x 1x     6x   6x 7x     6x   6x 1x     5x   5x 6x 6x   6x 6x   6x 6x         5x 5x 5x   5x   4x 1x 1x 1x           5x         5x   5x 5x 5x 1x   4x         1x 1x      
import * as vscode from 'vscode';
import { AsyncIterator } from 'asynciterator';
import { Store, Writer } from 'n3';
import { Uri } from '@faubulous/mentor-rdf';
import { SparqlLexer, SparqlParser, SparqlVariableParser } from '@faubulous/mentor-rdf-parsers';
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 { NamespaceMap } from '@src/utilities';
 
/**
 * Handler for serializing SPARQL query results.
 */
export class SparqlResultSerializer {
	constructor(
		private readonly prefixLookupService: IPrefixLookupService
	) {}
 
	/**
	 * 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) {
			const lexResult = new SparqlLexer().tokenize(context.query);
			const cst = new SparqlParser().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 if (Evalue.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;
	}
 
	/**
	 * 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 quads = await toArrayWithCancellation(quadStream, token);
 
			if (quads.length === 0) {
				return '';
			}
 
			// TODO: Request quads from communica instead of manually filtering the triples.
			const store = new Store();
 
			// Add all quads to the writer
			for (const q of quads) {
				store.addQuad(q.subject, q.predicate, q.object);
			}
 
			// 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 quads) {
				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;
				}
			}
 
			// Create N3 writer with prefixes
			const writer = new Writer({
				format: 'text/turtle',
				prefixes: prefixMap
			});
 
			writer.addQuads(store.toArray());
 
			// Return the serialized Turtle string
			return new Promise<string>((resolve, reject) => {
				writer.end((error, result) => {
					if (error) {
						reject(error);
					} else {
						resolve(result);
					}
				});
			});
		} catch (error) {
			console.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 store = new Store();
 
			for (const q of quads) {
				store.addQuad(q.subject, q.predicate, q.object);
			}
 
			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;
						}
					}
				}
			}
 
			const writer = new Writer({
				format: 'text/turtle',
				prefixes: prefixMap
			});
 
			writer.addQuads(store.toArray());
 
			return new Promise<string>((resolve, reject) => {
				writer.end((error, result) => {
					if (error) {
						reject(error);
					} else {
						resolve(result);
					}
				});
			});
		} catch (error) {
			console.error('Error serializing quads to Turtle:', error);
			return '';
		}
	}
}