forked from github/vscode-codeql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresults-view.ts
More file actions
1133 lines (1045 loc) · 34.9 KB
/
results-view.ts
File metadata and controls
1133 lines (1045 loc) · 34.9 KB
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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { Location, Result, Run } from "sarif";
import type {
WebviewPanel,
TextEditorSelectionChangeEvent,
Range,
} from "vscode";
import {
Diagnostic,
DiagnosticRelatedInformation,
DiagnosticSeverity,
languages,
Uri,
window,
env,
TextEditorSelectionChangeKind,
ViewColumn,
workspace,
} from "vscode";
import type { CodeQLCliServer, SourceInfo } from "../codeql-cli/cli";
import type {
DatabaseItem,
DatabaseManager,
} from "../databases/local-databases";
import { DatabaseEventKind } from "../databases/local-databases";
import {
decodeSourceArchiveUri,
zipArchiveScheme,
} from "../common/vscode/archive-filesystem-provider";
import {
asError,
assertNever,
getErrorMessage,
getErrorStack,
} from "../common/helpers-pure";
import type {
FromResultsViewMsg,
Interpretation,
IntoResultsViewMsg,
QueryMetadata,
ResultsPaths,
SortedResultSetInfo,
SortedResultsMap,
InterpretedResultsSortState,
RawResultsSortState,
ParsedResultSets,
EditorSelection,
} from "../common/interface-types";
import {
SortDirection,
ALERTS_TABLE_NAME,
GRAPH_TABLE_NAME,
NavigationDirection,
getDefaultResultSetName,
} from "../common/interface-types";
import { extLogger } from "../common/logging/vscode";
import type { Logger } from "../common/logging";
import { showAndLogExceptionWithTelemetry } from "../common/logging";
import type {
CompletedQueryInfo,
CompletedLocalQueryInfo,
} from "../query-results";
import { interpretResultsSarif, interpretGraphResults } from "../query-results";
import type { QueryEvaluationInfo } from "../run-queries-shared";
import {
parseSarifLocation,
parseSarifPlainTextMessage,
} from "../common/sarif-utils";
import { WebviewReveal, fileUriToWebviewUri } from "./webview";
import {
tryResolveLocation,
shownLocationDecoration,
shownLocationLineDecoration,
jumpToLocation,
} from "../databases/local-databases/locations";
import { bqrsToResultSet } from "../common/bqrs-raw-results-mapper";
import type { WebviewPanelConfig } from "../common/vscode/abstract-webview";
import { AbstractWebview } from "../common/vscode/abstract-webview";
import { isCanary, PAGE_SIZE } from "../config";
import type { HistoryItemLabelProvider } from "../query-history/history-item-label-provider";
import { telemetryListener } from "../common/vscode/telemetry";
import { redactableError } from "../common/errors";
import type { ResultsViewCommands } from "../common/commands";
import type { App } from "../common/app";
import type { Disposable } from "../common/disposable-object";
import type { RawResultSet } from "../common/raw-result-types";
import type { BqrsResultSetSchema } from "../common/bqrs-cli-types";
import { CachedOperation } from "../language-support/contextual/cached-operation";
/**
* results-view.ts
* ------------
*
* Displaying query results and linking back to source files when the
* webview asks us to.
*/
function sortMultiplier(sortDirection: SortDirection): number {
switch (sortDirection) {
case SortDirection.asc:
return 1;
case SortDirection.desc:
return -1;
}
}
function sortInterpretedResults(
results: Result[],
sortState: InterpretedResultsSortState | undefined,
): void {
if (sortState !== undefined) {
const multiplier = sortMultiplier(sortState.sortDirection);
switch (sortState.sortBy) {
case "alert-message":
results.sort((a, b) =>
a.message.text === undefined
? 0
: b.message.text === undefined
? 0
: multiplier *
a.message.text?.localeCompare(b.message.text, env.language),
);
break;
default:
assertNever(sortState.sortBy);
}
}
}
function interpretedPageSize(
interpretation: Interpretation | undefined,
): number {
if (interpretation?.data.t === "GraphInterpretationData") {
// Graph views always have one result per page.
return 1;
}
return PAGE_SIZE.getValue<number>();
}
function numPagesOfResultSet(
resultSet: RawResultSet,
interpretation?: Interpretation,
): number {
const pageSize = interpretedPageSize(interpretation);
const n =
interpretation?.data.t === "GraphInterpretationData"
? interpretation.data.dot.length
: resultSet.totalRowCount;
return Math.ceil(n / pageSize);
}
function numInterpretedPages(
interpretation: Interpretation | undefined,
): number {
if (!interpretation) {
return 0;
}
const pageSize = interpretedPageSize(interpretation);
const n =
interpretation.data.t === "GraphInterpretationData"
? interpretation.data.dot.length
: interpretation.data.runs[0].results?.length || 0;
return Math.ceil(n / pageSize);
}
/**
* The results view is used for displaying the results of a local query. It is a singleton; only 1 results view exists
* in the extension. It is created when the extension is activated and disposed of when the extension is deactivated.
* There can be multiple panels linked to this view over the lifetime of the extension, but there is only ever 1 panel
* active at a time.
*/
export class ResultsView extends AbstractWebview<
IntoResultsViewMsg,
FromResultsViewMsg
> {
private _displayedQuery?: CompletedLocalQueryInfo;
private _interpretation?: Interpretation;
private readonly _diagnosticCollection = languages.createDiagnosticCollection(
"codeql-query-results",
);
// Event listeners that should be disposed of when the view is disposed.
private disposableEventListeners: Disposable[] = [];
private schemaCache: CachedOperation<[], BqrsResultSetSchema[]>;
constructor(
app: App,
private databaseManager: DatabaseManager,
public cliServer: CodeQLCliServer,
public logger: Logger,
private labelProvider: HistoryItemLabelProvider,
) {
super(app);
// We can't use this.push for these two event listeners because they need to be disposed of when the view is
// disposed, not when the panel is disposed. The results view is a singleton, so we shouldn't be calling this.push.
this.disposableEventListeners.push(
window.onDidChangeTextEditorSelection(
this.handleSelectionChange.bind(this),
),
);
this.disposableEventListeners.push(
window.onDidChangeActiveTextEditor(() => {
this.sendEditorSelectionToWebview();
}),
);
this.disposableEventListeners.push(
this.databaseManager.onDidChangeDatabaseItem(({ kind }) => {
if (kind === DatabaseEventKind.Remove) {
this._diagnosticCollection.clear();
if (this.isShowingPanel) {
void this.postMessage({
t: "untoggleShowProblems",
});
}
}
}),
);
this.schemaCache = new CachedOperation(
this.getResultSetSchemasImpl.bind(this),
);
}
public getCommands(): ResultsViewCommands {
return {
"codeQLQueryResults.up": this.navigateResultView.bind(
this,
NavigationDirection.up,
),
"codeQLQueryResults.down": this.navigateResultView.bind(
this,
NavigationDirection.down,
),
"codeQLQueryResults.left": this.navigateResultView.bind(
this,
NavigationDirection.left,
),
"codeQLQueryResults.right": this.navigateResultView.bind(
this,
NavigationDirection.right,
),
// For backwards compatibility with keybindings set using an earlier version of the extension.
"codeQLQueryResults.nextPathStep": this.navigateResultView.bind(
this,
NavigationDirection.down,
),
"codeQLQueryResults.previousPathStep": this.navigateResultView.bind(
this,
NavigationDirection.up,
),
};
}
async navigateResultView(direction: NavigationDirection): Promise<void> {
if (!this.panel?.visible) {
return;
}
// Reveal the panel now as the subsequent call to 'window.showTextEditor' in 'showLocation' may destroy the webview otherwise.
this.panel.reveal();
await this.postMessage({ t: "navigate", direction });
}
protected getPanelConfig(): WebviewPanelConfig {
return {
viewId: "resultsView",
title: "CodeQL Query Results",
viewColumn: this.chooseColumnForWebview(),
preserveFocus: true,
view: "results",
// Required for the graph viewer which is using d3-graphviz WASM module. Only supported in canary mode.
allowWasmEval: isCanary(),
};
}
protected onPanelDispose(): void {
this._displayedQuery = undefined;
}
protected async onMessage(msg: FromResultsViewMsg): Promise<void> {
try {
switch (msg.t) {
case "viewLoaded":
this.onWebViewLoaded();
break;
case "viewSourceFile": {
await jumpToLocation(
msg.databaseUri,
msg.loc,
this.databaseManager,
this.logger,
);
break;
}
case "toggleDiagnostics": {
if (msg.visible) {
const databaseItem = this.databaseManager.findDatabaseItem(
Uri.parse(msg.databaseUri),
);
if (databaseItem !== undefined) {
await this.showResultsAsDiagnostics(
msg.origResultsPaths,
msg.metadata,
databaseItem,
);
}
} else {
// TODO: Only clear diagnostics on the same database.
this._diagnosticCollection.clear();
}
break;
}
case "changeSort":
await this.changeRawSortState(msg.resultSetName, msg.sortState);
telemetryListener?.sendUIInteraction("local-results-column-sorting");
break;
case "changeInterpretedSort":
await this.changeInterpretedSortState(msg.sortState);
break;
case "changePage":
if (
msg.selectedTable === ALERTS_TABLE_NAME ||
msg.selectedTable === GRAPH_TABLE_NAME
) {
await this.showPageOfInterpretedResults(msg.pageNumber);
} else {
await this.showPageOfRawResults(
msg.selectedTable,
msg.pageNumber,
// When we are in an unsorted state, we guarantee that
// sortedResultsInfo doesn't have an entry for the current
// result set. Use this to determine whether or not we use
// the sorted bqrs file.
!!this._displayedQuery?.completedQuery.sortedResultsInfo[
msg.selectedTable
],
);
}
break;
case "openFile":
await this.openFile(msg.filePath);
break;
case "telemetry":
telemetryListener?.sendUIInteraction(msg.action);
break;
case "unhandledError":
void showAndLogExceptionWithTelemetry(
extLogger,
telemetryListener,
redactableError(
msg.error,
)`Unhandled error in results view: ${msg.error.message}`,
);
break;
default:
assertNever(msg);
}
} catch (e) {
void showAndLogExceptionWithTelemetry(
extLogger,
telemetryListener,
redactableError(
asError(e),
)`Error handling message from results view: ${getErrorMessage(e)}`,
{
fullMessage: getErrorStack(e),
},
);
}
}
/**
* Choose where to open the webview.
*
* If there is a single view column, then open beside it.
* If there are multiple view columns, then open beside the active column,
* unless the active editor is the last column. In this case, open in the first column.
*
* The goal is to avoid opening new columns when there already are two columns open.
*/
private chooseColumnForWebview(): ViewColumn {
// This is not a great way to determine the number of view columns, but I
// can't find a vscode API that does it any better.
// Here, iterate through all the visible editors and determine the max view column.
// This won't work if the largest view column is empty.
const colCount = window.visibleTextEditors.reduce(
(maxVal, editor) =>
Math.max(
maxVal,
Number.parseInt(editor.viewColumn?.toFixed() || "0", 10),
),
0,
);
if (colCount <= 1) {
return ViewColumn.Beside;
}
const activeViewColumnNum = Number.parseInt(
window.activeTextEditor?.viewColumn?.toFixed() || "0",
10,
);
return activeViewColumnNum === colCount
? ViewColumn.One
: ViewColumn.Beside;
}
private async changeInterpretedSortState(
sortState: InterpretedResultsSortState | undefined,
): Promise<void> {
if (this._displayedQuery === undefined) {
void showAndLogExceptionWithTelemetry(
extLogger,
telemetryListener,
redactableError`Failed to sort results since evaluation info was unknown.`,
);
return;
}
// Notify the webview that it should expect new results.
await this.postMessage({ t: "resultsUpdating" });
await this._displayedQuery.completedQuery.updateInterpretedSortState(
sortState,
);
await this.showResults(this._displayedQuery, WebviewReveal.NotForced, true);
}
private async changeRawSortState(
resultSetName: string,
sortState: RawResultsSortState | undefined,
): Promise<void> {
if (this._displayedQuery === undefined) {
void showAndLogExceptionWithTelemetry(
extLogger,
telemetryListener,
redactableError`Failed to sort results since evaluation info was unknown.`,
);
return;
}
this.schemaCache.reset();
// Notify the webview that it should expect new results.
await this.postMessage({ t: "resultsUpdating" });
await this._displayedQuery.completedQuery.updateSortState(
this.cliServer,
resultSetName,
sortState,
);
// Sorting resets to first page, as there is arguably no particular
// correlation between the results on the nth page that the user
// was previously viewing and the contents of the nth page in a
// new sorted order.
await this.showPageOfRawResults(resultSetName, 0, true);
}
/**
* Show query results in webview panel.
* @param fullQuery Evaluation info for the executed query.
* @param shouldKeepOldResultsWhileRendering Should keep old results while rendering.
* @param forceReveal Force the webview panel to be visible and
* Appropriate when the user has just performed an explicit
* UI interaction requesting results, e.g. clicking on a query
* history entry.
*/
public async showResults(
fullQuery: CompletedLocalQueryInfo,
forceReveal: WebviewReveal,
shouldKeepOldResultsWhileRendering = false,
): Promise<void> {
if (!fullQuery.completedQuery?.successful) {
return;
}
const panel = await this.getPanel();
this._interpretation = undefined;
const interpretationPage = await this.interpretResultsInfo(
fullQuery.completedQuery.query,
fullQuery.completedQuery.interpretedResultsSortState,
);
const sortedResultsMap: SortedResultsMap = {};
Object.entries(fullQuery.completedQuery.sortedResultsInfo).forEach(
([k, v]) =>
(sortedResultsMap[k] = this.convertPathPropertiesToWebviewUris(
panel,
v,
)),
);
this._displayedQuery = fullQuery;
await this.waitForPanelLoaded();
if (!panel.visible) {
if (forceReveal === WebviewReveal.Forced) {
panel.reveal(undefined, true);
} else {
// The results panel exists, (`.getPanel()` guarantees it) but
// is not visible; it's in a not-currently-viewed tab. Show a
// more asynchronous message to not so abruptly interrupt
// user's workflow by immediately revealing the panel.
const showButton = "View Results";
const queryName = this.labelProvider.getShortLabel(fullQuery);
const resultPromise = window.showInformationMessage(
`Finished running query ${
queryName.length > 0 ? ` "${queryName}"` : ""
}.`,
showButton,
);
// Address this click asynchronously so we still update the
// query history immediately.
void resultPromise.then((result) => {
if (result === showButton) {
panel.reveal();
}
});
}
}
// Note that the resultSetSchemas will return offsets for the default (unsorted) page,
// which may not be correct. However, in this case, it doesn't matter since we only
// need the first offset, which will be the same no matter which sorting we use.
const resultSetSchemas = await this.getResultSetSchemas(
fullQuery.completedQuery,
);
const resultSetNames = resultSetSchemas.map((schema) => schema.name);
const selectedTable = getDefaultResultSetName(resultSetNames);
const schema = resultSetSchemas.find(
(resultSet) => resultSet.name === selectedTable,
)!;
// Use sorted results path if it exists. This may happen if we are
// reloading the results view after it has been sorted in the past.
const resultsPath = fullQuery.completedQuery.getResultsPath(selectedTable);
const pageSize = PAGE_SIZE.getValue<number>();
const chunk = await this.cliServer.bqrsDecode(resultsPath, schema.name, {
// Always send the first page.
// It may not wind up being the page we actually show,
// if there are interpreted results, but speculatively
// send anyway.
offset: schema.pagination?.offsets[0],
pageSize,
});
const resultSet = bqrsToResultSet(schema, chunk);
fullQuery.completedQuery.setResultCount(
interpretationPage?.numTotalResults || resultSet.totalRowCount,
);
const parsedResultSets: ParsedResultSets = {
pageNumber: 0,
pageSize,
numPages: numPagesOfResultSet(resultSet, this._interpretation),
numInterpretedPages: numInterpretedPages(this._interpretation),
resultSet: { t: "RawResultSet", resultSet },
selectedTable: undefined,
resultSetNames,
};
await this.postMessage({
t: "setUserSettings",
userSettings: {
// Only show provenance info in canary mode for now.
shouldShowProvenance: isCanary(),
},
});
await this.postMessage({
t: "setState",
interpretation: interpretationPage,
origResultsPaths: {
resultsPath: fullQuery.completedQuery.query.resultsPath,
interpretedResultsPath:
fullQuery.completedQuery.query.interpretedResultsPath,
},
resultsPath: this.convertPathToWebviewUri(
panel,
fullQuery.completedQuery.query.resultsPath,
),
parsedResultSets,
sortedResultsMap,
database: fullQuery.initialInfo.databaseInfo,
shouldKeepOldResultsWhileRendering,
metadata: fullQuery.completedQuery.query.metadata,
queryName: this.labelProvider.getLabel(fullQuery),
queryPath: fullQuery.initialInfo.queryPath,
});
// Send the current editor selection so the webview can apply filtering immediately
this.sendEditorSelectionToWebview();
}
/**
* Show a page of interpreted results
*/
public async showPageOfInterpretedResults(pageNumber: number): Promise<void> {
if (this._displayedQuery === undefined) {
throw new Error(
"Trying to show interpreted results but displayed query was undefined",
);
}
if (this._interpretation === undefined) {
throw new Error(
"Trying to show interpreted results but interpretation was undefined",
);
}
if (
this._interpretation.data.t === "SarifInterpretationData" &&
this._interpretation.data.runs[0].results === undefined
) {
throw new Error(
"Trying to show interpreted results but results were undefined",
);
}
const resultSetSchemas = await this.getResultSetSchemas(
this._displayedQuery.completedQuery,
);
const resultSetNames = resultSetSchemas.map((schema) => schema.name);
await this.postMessage({
t: "showInterpretedPage",
interpretation: this.getPageOfInterpretedResults(pageNumber),
database: this._displayedQuery.initialInfo.databaseInfo,
metadata: this._displayedQuery.completedQuery.query.metadata,
pageNumber,
resultSetNames,
pageSize: interpretedPageSize(this._interpretation),
numPages: numInterpretedPages(this._interpretation),
queryName: this.labelProvider.getLabel(this._displayedQuery),
queryPath: this._displayedQuery.initialInfo.queryPath,
});
}
private async getResultSetSchemas(
completedQuery: CompletedQueryInfo,
selectedTable = "",
): Promise<BqrsResultSetSchema[]> {
const resultsPath = completedQuery.getResultsPath(selectedTable);
return this.schemaCache.get(resultsPath);
}
private async getResultSetSchemasImpl(
resultsPath: string,
): Promise<BqrsResultSetSchema[]> {
const schemas = await this.cliServer.bqrsInfo(
resultsPath,
PAGE_SIZE.getValue(),
);
return schemas["result-sets"];
}
public async openFile(filePath: string) {
const textDocument = await workspace.openTextDocument(filePath);
await window.showTextDocument(textDocument, ViewColumn.One);
}
/**
* Show a page of raw results from the chosen table.
*/
public async showPageOfRawResults(
selectedTable: string,
pageNumber: number,
sorted = false,
): Promise<void> {
const results = this._displayedQuery;
if (results === undefined) {
throw new Error("trying to view a page of a query that is not loaded");
}
const panel = await this.getPanel();
const sortedResultsMap: SortedResultsMap = {};
Object.entries(results.completedQuery.sortedResultsInfo).forEach(
([k, v]) =>
(sortedResultsMap[k] = this.convertPathPropertiesToWebviewUris(
panel,
v,
)),
);
const resultSetSchemas = await this.getResultSetSchemas(
results.completedQuery,
sorted ? selectedTable : "",
);
// If there is a specific sorted table selected, a different bqrs file is loaded that doesn't have all the result set names.
// Make sure that we load all result set names here.
// See https://github.com/github/vscode-codeql/issues/1005
const allResultSetSchemas = sorted
? await this.getResultSetSchemas(results.completedQuery, "")
: resultSetSchemas;
const resultSetNames = allResultSetSchemas.map((schema) => schema.name);
const schema = resultSetSchemas.find(
(resultSet) => resultSet.name === selectedTable,
)!;
if (schema === undefined) {
throw new Error(`Query result set '${selectedTable}' not found.`);
}
const pageSize = PAGE_SIZE.getValue<number>();
const chunk = await this.cliServer.bqrsDecode(
results.completedQuery.getResultsPath(selectedTable, sorted),
schema.name,
{
offset: schema.pagination?.offsets[pageNumber],
pageSize,
},
);
const resultSet = bqrsToResultSet(schema, chunk);
const parsedResultSets: ParsedResultSets = {
pageNumber,
pageSize,
resultSet: { t: "RawResultSet", resultSet },
numPages: numPagesOfResultSet(resultSet),
numInterpretedPages: numInterpretedPages(this._interpretation),
selectedTable,
resultSetNames,
};
await this.postMessage({
t: "setState",
interpretation: this._interpretation,
origResultsPaths: {
resultsPath: results.completedQuery.query.resultsPath,
interpretedResultsPath:
results.completedQuery.query.interpretedResultsPath,
},
resultsPath: this.convertPathToWebviewUri(
panel,
results.completedQuery.query.resultsPath,
),
parsedResultSets,
sortedResultsMap,
database: results.initialInfo.databaseInfo,
shouldKeepOldResultsWhileRendering: false,
metadata: results.completedQuery.query.metadata,
queryName: this.labelProvider.getLabel(results),
queryPath: results.initialInfo.queryPath,
});
}
private async _getInterpretedResults(
metadata: QueryMetadata | undefined,
resultsPaths: ResultsPaths,
sourceInfo: SourceInfo | undefined,
sourceLocationPrefix: string,
sortState: InterpretedResultsSortState | undefined,
): Promise<Interpretation | undefined> {
if (!resultsPaths) {
void this.logger.log(
"No results path. Cannot display interpreted results.",
);
return undefined;
}
let data;
let numTotalResults;
// Graph results are only supported in canary mode because the graph viewer is not actively supported
if (metadata?.kind === GRAPH_TABLE_NAME && isCanary()) {
data = await interpretGraphResults(
this.cliServer,
metadata,
resultsPaths,
sourceInfo,
);
numTotalResults = data.dot.length;
} else {
const sarif = await interpretResultsSarif(
this.cliServer,
metadata,
resultsPaths,
sourceInfo,
);
sarif.runs.forEach((run) => {
if (run.results) {
sortInterpretedResults(run.results, sortState);
}
});
sarif.sortState = sortState;
data = sarif;
numTotalResults = (() => {
return sarif.runs?.[0]?.results ? sarif.runs[0].results.length : 0;
})();
}
const interpretation: Interpretation = {
data,
sourceLocationPrefix,
numTruncatedResults: 0,
numTotalResults,
};
this._interpretation = interpretation;
return interpretation;
}
private getPageOfInterpretedResults(pageNumber: number): Interpretation {
function getPageOfRun(run: Run): Run {
return {
...run,
results: run.results?.slice(
PAGE_SIZE.getValue<number>() * pageNumber,
PAGE_SIZE.getValue<number>() * (pageNumber + 1),
),
};
}
const interp = this._interpretation;
if (interp === undefined) {
throw new Error(
"Tried to get interpreted results before interpretation finished",
);
}
if (interp.data.t !== "SarifInterpretationData") {
return interp;
}
if (interp.data.runs.length !== 1) {
void this.logger.log(
`Warning: SARIF file had ${interp.data.runs.length} runs, expected 1`,
);
}
return {
...interp,
data: {
...interp.data,
runs: [getPageOfRun(interp.data.runs[0])],
},
};
}
private async interpretResultsInfo(
query: QueryEvaluationInfo,
sortState: InterpretedResultsSortState | undefined,
): Promise<Interpretation | undefined> {
if (
query.canHaveInterpretedResults() &&
query.quickEvalPosition === undefined // never do results interpretation if quickEval
) {
try {
const dbItem = this.databaseManager.findDatabaseItem(
Uri.file(query.dbItemPath),
);
if (!dbItem) {
throw new Error(
`Could not find database item for ${query.dbItemPath}`,
);
}
const sourceLocationPrefix = await dbItem.getSourceLocationPrefix(
this.cliServer,
);
const sourceArchiveUri = dbItem.sourceArchive;
const sourceInfo =
sourceArchiveUri === undefined
? undefined
: {
sourceArchive: sourceArchiveUri.fsPath,
sourceLocationPrefix,
};
await this._getInterpretedResults(
query.metadata,
{
resultsPath: query.resultsPath,
interpretedResultsPath: query.interpretedResultsPath,
},
sourceInfo,
sourceLocationPrefix,
sortState,
);
} catch (e) {
// If interpretation fails, accept the error and continue
// trying to render uninterpreted results anyway.
void showAndLogExceptionWithTelemetry(
extLogger,
telemetryListener,
redactableError(
asError(e),
)`Showing raw results instead of interpreted ones due to an error. ${getErrorMessage(
e,
)}`,
);
}
}
return this._interpretation && this.getPageOfInterpretedResults(0);
}
private async showResultsAsDiagnostics(
resultsInfo: ResultsPaths,
metadata: QueryMetadata | undefined,
database: DatabaseItem,
): Promise<void> {
const sourceLocationPrefix = await database.getSourceLocationPrefix(
this.cliServer,
);
const sourceArchiveUri = database.sourceArchive;
const sourceInfo =
sourceArchiveUri === undefined
? undefined
: {
sourceArchive: sourceArchiveUri.fsPath,
sourceLocationPrefix,
};
// TODO: Performance-testing to determine whether this truncation is necessary.
const interpretation = await this._getInterpretedResults(
metadata,
resultsInfo,
sourceInfo,
sourceLocationPrefix,
undefined,
);
if (!interpretation) {
return;
}
try {
await this.showProblemResultsAsDiagnostics(interpretation, database);
} catch (e) {
void this.logger.log(
`Exception while computing problem results as diagnostics: ${getErrorMessage(
e,
)}`,
);
this._diagnosticCollection.clear();
}
}
private async showProblemResultsAsDiagnostics(
interpretation: Interpretation,
databaseItem: DatabaseItem,
): Promise<void> {
const { data, sourceLocationPrefix } = interpretation;
if (data.t !== "SarifInterpretationData") {
return;
}
if (!data.runs || !data.runs[0].results) {
void this.logger.log(
"Didn't find a run in the sarif results. Error processing sarif?",
);
return;
}
const diagnostics: Array<[Uri, readonly Diagnostic[]]> = [];
for (const result of data.runs[0].results) {
const message = result.message.text;
if (message === undefined) {
void this.logger.log("Sarif had result without plaintext message");
continue;
}
if (!result.locations) {
void this.logger.log("Sarif had result without location");
continue;
}
const sarifLoc = parseSarifLocation(
result.locations[0],
sourceLocationPrefix,
);
if ("hint" in sarifLoc) {
continue;
}
const resultLocation = tryResolveLocation(sarifLoc, databaseItem);
if (!resultLocation) {
void this.logger.log(
`Sarif location was not resolvable: ${sarifLoc.uri.toString()}`,
);
continue;
}
const parsedMessage = parseSarifPlainTextMessage(message);
const relatedInformation: DiagnosticRelatedInformation[] = [];
const relatedLocationsById: { [k: number]: Location } = {};
for (const loc of result.relatedLocations || []) {
relatedLocationsById[loc.id!] = loc;
}
const resultMessageChunks: string[] = [];
for (const section of parsedMessage) {
if (typeof section === "string") {
resultMessageChunks.push(section);
} else {
resultMessageChunks.push(section.text);
const sarifChunkLoc = parseSarifLocation(
relatedLocationsById[section.dest],
sourceLocationPrefix,
);
if ("hint" in sarifChunkLoc) {
continue;
}