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 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 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 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 | 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 27x 76x 1x 76x 3x 2x 2x 2x 2x 2x 2x 3x 3x 1x 1x 1x 1x 1x 3x 1x 1x 2x 76x 76x 32x 12x 18x 12x 18x 10x 2x 2x 2x 7x 1x 1x 1x 6x 8x 5x 5x 5x 5x 5x 5x 3x 9x 9x 9x 9x 1x 8x 8x 8x 2x 2x 1x 1x 6x 6x 6x 7x 5x 2x 3x 1x 2x 1x 1x 4x 4x 9x 9x 9x 9x 9x 5x 5x 5x 4x 1x 3x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 15x 15x 7x 7x 7x 7x 7x 7x 15x 15x 14x 15x 15x 12x 5x 4x 7x 2x 2x 5x 3x 3x 2x 19x 18x 1x 1x 19x 21x 21x 3x 18x 5x 5x 4x 4x 4x 5x 5x 1x 5x 1x 1x 1x 1x 1x 13x 13x 13x 13x 12x 2x 5x 2x 1x 1x 1x 14x 9x 5x 2x 1x 2x 1x 1x 3x 1x 3x 1x 8x 8x 9x 9x 5579x 145x 8x 145x 145x 145x 145x 4554x 4552x 4552x 145x 5x 21x 2x 2x | import * as vscode from 'vscode';
import { RdfSyntax, RdfToken } from '@faubulous/mentor-rdf-parsers';
import { ParserFactory } from '@src/languages/parser-factory';
import type { QueryEngine } from "@comunica/query-sparql";
import { AsyncIterator } from 'asynciterator';
import { Bindings, Quad } from "@rdfjs/types";
import { AuthCredential } from '@src/services/core/credential';
import { ICredentialStorageService } from '@src/services/core';
import { getAuthorizationHeaderProvider } from './sparql-auth';
import { IDocumentConnectionService, ISparqlConnectionRegistry, ISparqlQuerySourceFactory } from '@src/languages/sparql/services';
import { ISparqlResultSerializer } from '@src/languages/sparql/services';
import { ITripleStoreConfigService } from './triple-store-config-service.interface';
import { WorkspaceUri } from "@src/providers/workspace-uri";
import { CancellationError, withCancellation } from '@src/utilities/vscode/cancellation';
import { getConfig } from '@src/utilities/vscode/config';
import { SparqlQueryExecutionState, SparqlQueryType, SparqlRawResponse, getQueryStateWithoutResult } from "./sparql-query-state";
import { SparqlConnection } from './sparql-connection';
/**
* A service for executing SPARQL queries against an RDF endpoint. The service
* keeps a log of the executed queries in temporal order in memory, and upon
* disposal, it saves the query history to a workspace-scoped local storage,
* excluding unsaved documents. This query history is then restored when the
* service is instantiated.
*/
export class SparqlQueryService {
/**
* The in-memory history of executed SPARQL queries, ordered from most recent to least recent.
*/
private readonly _history: SparqlQueryExecutionState[] = [];
/**
* The key for storing query history in local storage.
*/
private readonly _historyStorageKey = 'mentor.sparql.queryHistory';
/**
* The maximum number of entries to persist, and the number of most recent entries that
* keep their result and raw response in memory (see {@link _trimHistory}).
*/
private readonly _historyMaxEntries = 10;
/**
* The maximum number of entries to keep in memory at all; older ones are dropped.
*/
private readonly _historyMaxTotalEntries = 100;
/**
* The maximum number of characters of a raw response body to retain. Larger bodies are
* truncated to keep them out of memory and the webview message channel.
*/
private readonly _maxRawResponseLength = 5_000_000;
/**
* A map of cancellation tokens for currently running queries, keyed by query state ID.
*/
private readonly _cancellationTokens = new Map<string, vscode.CancellationTokenSource>();
/**
* The shared Comunica query engine, created lazily on the first query (see
* {@link _getQueryEngine}). Constructing an engine builds its entire
* actor/mediator pipeline — expensive, synchronous CPU on the shared extension
* host — while the engine itself holds no per-query state (sources and options
* are passed per call), so a single instance serves all queries. The promise is
* cached so concurrent first queries share one module load and one engine.
*/
private _queryEngine: Promise<QueryEngine> | undefined;
private readonly _onDidHistoryChange = new vscode.EventEmitter<void>();
/**
* Event that is triggered when the query history changes.
*/
onDidHistoryChange: vscode.Event<void> = this._onDidHistoryChange.event;
private readonly _onDidQueryExecutionStart = new vscode.EventEmitter<SparqlQueryExecutionState>();
/**
* Event that is triggered before a SPARQL query is about to be executed.
*/
onDidQueryExecutionStart: vscode.Event<SparqlQueryExecutionState> = this._onDidQueryExecutionStart.event;
private readonly _onDidQueryExecutionEnd = new vscode.EventEmitter<SparqlQueryExecutionState>();
/**
* Event that is triggered when a SPARQL query execution has ended with any result.
*/
onDidQueryExecutionEnd: vscode.Event<SparqlQueryExecutionState> = this._onDidQueryExecutionEnd.event;
constructor(
private readonly _extensionContext: vscode.ExtensionContext,
private readonly _credentialStorage: ICredentialStorageService,
private readonly _connectionRegistry: ISparqlConnectionRegistry,
private readonly _resultSerializer: ISparqlResultSerializer,
private readonly _storeConfigService: ITripleStoreConfigService,
private readonly _querySourceFactory: ISparqlQuerySourceFactory,
private readonly _documentConnectionService: IDocumentConnectionService
) {
for (const entry of this._loadQueryHistory()) {
this._history.push(entry);
}
const disposables = [
vscode.workspace.onDidCloseTextDocument((e) => this._onTextDocumentClosed(e))
];
this._extensionContext.subscriptions.push(...disposables);
}
/**
* Handles the closing of a text document and removes unsaved queries from the history.
* @param document A text document.
*/
private _onTextDocumentClosed(document: vscode.TextDocument) {
if (document.uri.scheme === 'untitled') {
const i = this._history.findIndex(q => q.documentIri && q.documentIri === document.uri.toString());
this.removeQueryStateAt(i);
}
}
/**
* Creates a new SPARQL query state from a query string.
* @param querySource The source document or notebook cell where the query is stored.
* @param query The SPARQL query string.
* @returns A new SparqlQueryExecutionState instance.
*/
createQuery(querySource: vscode.TextDocument | vscode.NotebookCell, query: string): SparqlQueryExecutionState {
const source = this._getDocumentFromQuerySource(querySource);
const workspaceIri = WorkspaceUri.toWorkspaceUri(source.document.uri);
const queryType = this._getQueryType(query);
return {
id: crypto.randomUUID(),
documentIri: source.document.uri.toString(),
workspaceIri: workspaceIri?.toString(),
notebookIri: source.notebookIri?.toString(),
cellIndex: source.cellIndex,
query,
queryType,
startTime: Date.now()
};
}
/**
* Creates a new SPARQL query state for a background query with no associated document.
* @param connection The SPARQL connection to execute the query against.
* @param query The SPARQL query string.
* @param label A human-readable label shown as the tab title (e.g. 'List Graphs').
* @returns A new SparqlQueryExecutionState instance marked as a background query.
*/
createBackgroundQuery(connection: SparqlConnection, query: string, label: string): SparqlQueryExecutionState {
const queryType = this._getQueryType(query);
return {
id: crypto.randomUUID(),
label,
connectionId: connection.id,
connectionName: connection.endpointUrl,
isBackground: true,
query,
queryType,
startTime: Date.now()
};
}
/**
* Creates a new SPARQL query state from a document or notebook cell.
* @param querySource The source document or notebook cell where the query is stored.
* @returns A new SparqlQueryContext instance.
*/
createQueryFromDocument(querySource: vscode.TextDocument | vscode.NotebookCell): SparqlQueryExecutionState {
const source = this._getDocumentFromQuerySource(querySource);
const workspaceIri = WorkspaceUri.toWorkspaceUri(source.document.uri);
const query = source.document.getText();
const queryType = this._getQueryType(query);
return {
id: crypto.randomUUID(),
documentIri: source.document.uri.toString(),
workspaceIri: workspaceIri?.toString(),
notebookIri: source.notebookIri?.toString(),
cellIndex: source.cellIndex,
query,
queryType,
startTime: Date.now()
};
}
private _getDocumentFromQuerySource(querySource: vscode.TextDocument | vscode.NotebookCell) {
if ('notebook' in querySource && querySource.notebook) {
const cell = querySource as vscode.NotebookCell;
return {
document: cell.document,
notebookIri: cell.notebook.uri,
cellIndex: cell.index
};
} else {
return {
document: querySource as vscode.TextDocument
};
}
}
private _loadQueryHistory(limit: number = 10): SparqlQueryExecutionState[] {
const history = this._extensionContext.workspaceState.get<SparqlQueryExecutionState[]>(this._historyStorageKey, []);
return history
.filter(q => q)
.slice(0, limit)
.sort((a, b) => b.startTime - a.startTime);
}
private async _persistQueryHistory(): Promise<void> {
// Exclude execution states that would not be valid after a restart. Only the
// metadata is persisted: writing results and raw responses to the workspace
// state after every execution cost megabytes per query, and a restored
// query re-runs when its tab is shown, as it does after a webview reload.
const filteredHistory = this._history
.filter(q => q && !q.isBackground && this._isPersistentDocumentIri(q.documentIri))
.slice(0, this._historyMaxEntries)
.map(getQueryStateWithoutResult);
await this._extensionContext.workspaceState.update(this._historyStorageKey, filteredHistory);
}
/**
* Indicates whether a document IRI still identifies the same document after a
* restart. Untitled documents are gone by then and notebook cell URIs change
* with every session.
* @param documentIri The document IRI of a history entry.
*/
private _isPersistentDocumentIri(documentIri: string | undefined): boolean {
return !!documentIri && !documentIri.startsWith('untitled') && !documentIri.startsWith('vscode-notebook-cell');
}
/**
* Get the SPARQL query state for a specific document IRI.
* @param documentIri The IRI of the document to retrieve the query state for.
* @returns The SparqlQueryState for the specified document, or `undefined` if not found.
*/
getQueryStateForDocument(documentIri: string): SparqlQueryExecutionState | undefined {
return this._history.find(q => q.documentIri === documentIri);
}
/**
* Removes a SPARQL query state from the history and triggers the history change event.
* @param state The SparqlQueryState to remove.
*/
removeQueryState(state: SparqlQueryExecutionState) {
const n = this._history.findIndex(q => q === state);
this.removeQueryStateAt(n);
}
/**
* Cancels a running SPARQL query execution.
* @param queryStateID Id of the query execution state.
* @returns `true` if the query was successfully cancelled, `false` otherwise.
*/
cancelQuery(queryStateID: string): boolean {
if (this._cancellationTokens.has(queryStateID)) {
this._cancellationTokens.get(queryStateID)?.cancel();
this._cancellationTokens.delete(queryStateID);
return true;
} else {
return false;
}
}
/**
* Removes the n-th item from the query history and triggers the history change event.
* @param index The index of the item to remove from the query history.
*/
removeQueryStateAt(index: number): boolean {
if (index >= 0 && index < this._history.length) {
const queryState = this._history[index];
this.cancelQuery(queryState.id);
this._history.splice(index, 1);
this._onDidHistoryChange.fire();
this._persistQueryHistory();
return true;
} else {
return false;
}
}
/**
* Executes a SPARQL query against the RDF store and returns the results.
* @param query The SPARQL query to execute.
* @param documentIri The IRI of the document where the query is run.
* @param tokenSource A cancellation token source to cancel the query execution.
* @returns A promise that resolves to the results of the query.
*/
async executeQuery(context: SparqlQueryExecutionState, tokenSource: vscode.CancellationTokenSource = new vscode.CancellationTokenSource()): Promise<SparqlQueryExecutionState> {
// Resolves to the last raw HTTP response received from the endpoint (if any), so it
// can be inspected via the results panel regardless of whether the query succeeded.
let rawResponsePromise: Promise<SparqlRawResponse | undefined> = Promise.resolve(undefined);
try {
const query = this._getQueryText(context);
if (!query) {
throw new Error('Unable to retrieve query from the document: ' + context.documentIri);
}
this._cancellationTokens.set(context.id, tokenSource);
this._logQueryExecutionStart(context);
let source: any;
if (context.connectionId && !context.documentIri) {
const connection = this._connectionRegistry.getConnection(context.connectionId);
if (!connection) {
throw new Error('Could not find connection with ID: ' + context.connectionId);
}
source = await this._querySourceFactory.getQuerySourceForConnection(connection);
} else {
const documentIri = vscode.Uri.parse(context.documentIri!);
source = await this._querySourceFactory.getQuerySourceForDocument(documentIri);
// Record the exact connection this query ran against so downstream actions
// triggered from the results view (e.g. Describe Resource on a binding) reuse
// it, rather than re-resolving from the source document — which may have since
// changed or fall back to the workspace store.
context.connectionId = this._documentConnectionService.getConnectionForDocument(documentIri).id;
}
const result = await this._executeQueryOnSource(query, source, tokenSource.token, (raw) => {
rawResponsePromise = raw;
});
if (result.type === 'bindings') {
context.result = await this._resultSerializer.serializeBindings(context, result.bindings, tokenSource.token);
} else if (result.type === 'boolean') {
context.result = {
type: 'boolean',
value: result.value
};
} else if (result.type === 'quads') {
context.result = {
type: 'quads',
mimeType: 'text/turtle',
document: await this._resultSerializer.serializeQuads(context, result.quads, tokenSource.token)
};
} else {
context.result = undefined;
}
} catch (error: any) {
// `fetch` (undici) reports low-level network failures as the opaque message
// 'fetch failed' and nests the real reason (ECONNREFUSED, ENOTFOUND, TLS errors,
// CORS, …) in `error.cause`. Surface it so the panel can show why it failed.
const cause = error?.cause;
context.error = {
type: error.name || 'QueryError',
message: error.message || 'Unknown error occurred while executing the query.',
cause: cause ? { code: cause.code, message: cause.message ?? String(cause) } : undefined,
stack: error.stack || '',
statusCode: error.statusCode || 500,
cancelled: error instanceof CancellationError
}
}
context.rawResponse = await rawResponsePromise;
context.endTime = Date.now();
this._logQueryExecutionEnd(context);
this._persistQueryHistory();
return context;
}
/**
* Registers an already-completed query state in the history and notifies listeners,
* without executing anything. Used to surface pre-computed results (e.g. named graphs
* already cached by the graph service) in the results panel.
* @param state The completed query execution state, including its `result`.
*/
registerCompletedQuery(state: SparqlQueryExecutionState): void {
state.endTime = state.endTime ?? Date.now();
this._logQueryExecution(state);
this._onDidQueryExecutionEnd.fire(state);
}
/**
* Executes a SPARQL query directly against a connection without requiring a document.
* This method does not log the query in history and is intended for internal/programmatic use.
* @param query The SPARQL query string to execute.
* @param connection The SPARQL connection to execute against.
* @returns The query result based on the query type.
*/
async executeQueryOnConnection(query: string, connection: SparqlConnection, inferenceEnabled?: boolean): Promise<{ type: 'boolean'; value: boolean } | { type: 'quads'; data: string } | { type: 'bindings'; bindings: any[] } | null> {
try {
const source = await this._querySourceFactory.getQuerySourceForConnection(connection, inferenceEnabled);
const result = await this._executeQueryOnSource(query, source);
if (result.type === 'boolean') {
return { type: 'boolean', value: result.value };
} else if (result.type === 'quads') {
const quads: Quad[] = [];
for await (const quad of result.quads) {
quads.push(quad);
}
const data = await this._resultSerializer.serializeQuadsToString(quads);
return { type: 'quads', data };
} else if (result.type === 'bindings') {
const bindings: Bindings[] = [];
for await (const binding of result.bindings) {
bindings.push(binding);
}
return { type: 'bindings', bindings: bindings };
}
return null;
} catch (error: any) {
throw new Error(`Query execution failed: ${error.message}`);
}
}
/**
* Executes a SPARQL query against a Comunica source and returns the raw result.
* @param query The SPARQL query string to execute.
* @param source The Comunica source to execute against.
* @param token Optional cancellation token.
* @returns The raw query result with type information.
*/
private async _executeQueryOnSource(
query: string,
source: any,
token?: vscode.CancellationToken,
onRawResponse?: (raw: Promise<SparqlRawResponse | undefined>) => void
): Promise<
| { type: 'boolean'; value: boolean }
| { type: 'quads'; quads: AsyncIterator<Quad> }
| { type: 'bindings'; bindings: AsyncIterator<Bindings> }
| { type: 'none' }
> {
const options: any = {
sources: [source],
unionDefaultGraph: true
};
if (source.type === 'sparql') {
const connection = source.connection;
const credential = await this._credentialStorage.getCredential(connection.id);
options.fetch = this._getFetchHandler(credential, onRawResponse);
// Apply store-specific query-text rewriting for inference (e.g. reasoning pragmas).
const inferenceEnabled = source.inferenceEnabled
?? this._connectionRegistry.getInferenceEnabled(connection.id);
const queryPragma = this._storeConfigService.getStoreConfig(connection.storeType)?.inference?.queryPragma;
Iif (queryPragma) {
const pragma = (inferenceEnabled ? queryPragma.enabled : queryPragma.disabled)?.trim();
if (pragma) {
query = `${pragma}\n${query}`;
}
}
}
// Apply query timeout from configuration (0 means no timeout)
const timeout = getConfig('sparql').get<number>('queryTimeout', 30000);
if (timeout > 0) {
options.timeout = timeout;
}
const queryEngine = await this._getQueryEngine();
const preparedQuery = await queryEngine.query(query, options);
if (preparedQuery.resultType === 'boolean') {
const value = token
? await withCancellation(preparedQuery.execute(), token)
: await preparedQuery.execute();
return { type: 'boolean', value };
} else if (preparedQuery.resultType === 'quads') {
const quads = await preparedQuery.execute();
return { type: 'quads', quads };
} else if (preparedQuery.resultType === 'bindings') {
const bindings = await preparedQuery.execute();
return { type: 'bindings', bindings };
}
return { type: 'none' };
}
/**
* Returns the shared Comunica query engine, loading the Comunica module on first
* use. The module is imported dynamically so that it is not evaluated when the
* extension activates: it makes up about half of the extension bundle, and
* evaluating it costs noticeable time and heap even in sessions that never run a
* query. The bundler inlines the module but defers its initialization until this
* import runs. A failed load is not cached, so the next query retries.
* @returns A promise that resolves to the shared query engine.
*/
private _getQueryEngine(): Promise<QueryEngine> {
this._queryEngine ??= import('@comunica/query-sparql')
.then(({ QueryEngine }) => new QueryEngine())
.catch(error => {
this._queryEngine = undefined;
throw error;
});
return this._queryEngine;
}
_getFetchHandler(
credential?: AuthCredential,
onRawResponse?: (raw: Promise<SparqlRawResponse | undefined>) => void
) {
const getAuthHeader = getAuthorizationHeaderProvider(credential);
// Without an authorization header to inject and without a need to capture the raw
// response, there is nothing to add over Comunica's default fetch.
if (!getAuthHeader && !onRawResponse) {
return undefined;
}
return async (input: RequestInfo | URL, init?: RequestInit) => {
const headers = new Headers(init?.headers || {});
if (getAuthHeader) {
const authHeader = await getAuthHeader();
Eif (authHeader) {
headers.set("Authorization", authHeader);
}
}
const response = await fetch(input, { ...init, headers });
if (onRawResponse) {
// Tee the body via `clone()` so the raw, unparsed response can be inspected
// without disturbing the stream Comunica consumes. Best-effort capture.
onRawResponse(this._readRawResponse(response.clone()));
}
return response;
};
}
/**
* Reads a (cloned) HTTP response into a serializable raw-response record, truncating the
* body to {@link MAX_RAW_RESPONSE_LENGTH}. Best-effort: resolves to `undefined` on failure.
* @param response A cloned response whose body has not yet been consumed.
* @returns The captured raw response, or `undefined` if it could not be read.
*/
private async _readRawResponse(response: Response): Promise<SparqlRawResponse | undefined> {
try {
const text = await response.text();
const truncated = text.length > this._maxRawResponseLength;
const body = truncated
? text.slice(0, this._maxRawResponseLength) + '\n\n… response truncated …'
: text;
return {
url: response.url,
status: response.status,
statusText: response.statusText,
contentType: response.headers.get('content-type') ?? undefined,
body
};
} catch {
return undefined;
}
}
_getQueryType(query: string): SparqlQueryType | undefined {
// Lexer construction is expensive (~3-7 ms) and this runs per code-lens
// refresh; use the shared instance. It may carry another caller's blank
// node ID generator — restore the default before tokenizing.
const lexer = ParserFactory.getLexer(RdfSyntax.Sparql);
lexer.blankNodeIdGenerator = undefined;
const lexingResult = lexer.tokenize(query);
for (const token of lexingResult.tokens) {
switch (token.tokenType.name) {
case RdfToken.ASK.name:
return 'boolean';
case RdfToken.SELECT.name:
return 'bindings';
case RdfToken.CONSTRUCT.name:
return 'quads';
case RdfToken.DESCRIBE.name:
return 'quads';
case RdfToken.FROM.name:
return undefined;
case RdfToken.WHERE.name:
return undefined;
}
}
}
private _getQueryText(context: SparqlQueryExecutionState): string | undefined {
if (context.query) {
return context.query;
} else if (context.notebookIri) {
const notebook = vscode.workspace.notebookDocuments.find(
n => n.uri.toString() === context.notebookIri
);
if (notebook) {
const cell = notebook.cellAt(context.cellIndex || 0);
return cell.document.getText();
}
} else {
const document = vscode.workspace.textDocuments.find(
d => d.uri.toString() === context.documentIri
);
if (document) {
return document.getText();
}
}
}
/**
* Update the SPARQL history and fire the appropriate events when a query is executed.
* @param context The context of the SPARQL query execution.
*/
private async _logQueryExecutionStart(context: SparqlQueryExecutionState) {
await this._logQueryExecution(context);
this._onDidQueryExecutionStart.fire(context);
}
/**
* Update the SPARQL history and fire the appropriate events when a query finished executing.
* @param context The context of the SPARQL query execution.
*/
private async _logQueryExecutionEnd(context: SparqlQueryExecutionState) {
await this._logQueryExecution(context);
this._onDidQueryExecutionEnd.fire(context);
}
/**
* Tracks query execution in history and persists to storage.
*/
private async _logQueryExecution(context: SparqlQueryExecutionState) {
const n = this._history.findIndex(q => q.documentIri === context.documentIri);
if (n >= 0) {
this._history.splice(n, 1);
}
this._history.unshift(context);
this._trimHistory();
this._onDidHistoryChange.fire();
}
/**
* Bounds the memory the history holds. Entries beyond the most recent
* {@link _historyMaxEntries} drop their result and raw response — the results
* webview keeps its own copy of what it displays — and the list itself is capped
* at {@link _historyMaxTotalEntries} entries. A query that is still running keeps
* its fields: its result is assigned before it is moved to the front on completion.
*/
private _trimHistory(): void {
for (const entry of this._history.slice(this._historyMaxEntries)) {
if (entry.endTime !== undefined) {
entry.result = undefined;
entry.rawResponse = undefined;
}
}
if (this._history.length > this._historyMaxTotalEntries) {
this._history.length = this._historyMaxTotalEntries;
}
}
/**
* Gets recent queries across all documents, ordered by execution time in descending order.
* @param limit The maximum number of recent queries to return.
* @returns A promise that resolves to an array of recent query entries.
*/
getQueryHistory(): SparqlQueryExecutionState[] {
return this._history;
}
/**
* Clears the persisted query history.
*/
clearQueryHistory(): void {
this._history.length = 0;
this._persistQueryHistory();
}
} |