Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Query Plan to results pane #18124

Open
wants to merge 19 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions localization/l10n/bundle.l10n.json
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@
"Messages": "Messages",
"Timestamp": "Timestamp",
"Message": "Message",
"Query Plan": "Query Plan",
"Open snapshot in new tab": "Open snapshot in new tab",
"Showplan XML": "Showplan XML",
"Show Filter": "Show Filter",
Expand Down
6 changes: 6 additions & 0 deletions localization/xliff/vscode-mssql.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -895,6 +895,9 @@
<trans-unit id="++CODE++10209ed1750a4b5c09b80ea470ed45083d8d1ad3d1da877d160d9ab61a5031fc">
<source xml:lang="en">Publishing Changes</source>
</trans-unit>
<trans-unit id="++CODE++f44ad102b5dd5df1b5691408d19d39ee92cc1c9ad20f7125845df3d961a805d3">
<source xml:lang="en">Query Plan</source>
</trans-unit>
<trans-unit id="++CODE++9e83dc6d2db272ac27cc875b994f834b62b7202a49b69e885f8f4e8f9c29a452">
<source xml:lang="en">Query executed</source>
</trans-unit>
Expand Down Expand Up @@ -1516,6 +1519,9 @@
<trans-unit id="mssql.enableSqlAuthenticationProvider">
<source xml:lang="en">Enables use of the Sql Authentication Provider for &apos;Microsoft Entra Id Interactive&apos; authentication mode when user selects &apos;AzureMFA&apos; authentication. This enables Server-side resource endpoint integration when fetching access tokens. This option is only supported for &apos;MSAL&apos; Authentication Library. Please restart Visual Studio Code after changing this option.</source>
</trans-unit>
<trans-unit id="mssql.showExecutionPlanInResults">
<source xml:lang="en">Estimated Plan</source>
</trans-unit>
<trans-unit id="mssql.runCurrentStatement">
<source xml:lang="en">Execute Current Statement</source>
</trans-unit>
Expand Down
14 changes: 14 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,11 @@
"command": "mssql.changeDatabase",
"when": "editorLangId == sql",
"group": "navigation@4"
},
{
"command": "mssql.showExecutionPlanInResults",
"when": "editorLangId == sql",
"group": "navigation@4"
}
],
"editor/context": [
Expand Down Expand Up @@ -799,6 +804,15 @@
"command": "mssql.userFeedback",
"title": "%mssql.userFeedback%",
"category": "MS SQL"
},
{
"command": "mssql.showExecutionPlanInResults",
"title": "%mssql.showExecutionPlanInResults%",
"category": "MS SQL",
"icon": {
"dark": "media/executionPlan_dark.svg",
"light": "media/executionPlan_light.svg"
}
}
],
"keybindings": [
Expand Down
1 change: 1 addition & 0 deletions package.nls.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"mssql.addAadAccount":"Add Microsoft Entra Account",
"mssql.removeAadAccount":"Remove Microsoft Entra Account",
"mssql.clearAzureAccountTokenCache":"Clear Microsoft Entra account token cache",
"mssql.showExecutionPlanInResults":"Estimated Plan",
"mssql.rebuildIntelliSenseCache":"Refresh IntelliSense Cache",
"mssql.logDebugInfo":"[Optional] Log debug output to the VS Code console (Help -> Toggle Developer Tools)",
"mssql.maxRecentConnections":"The maximum number of recently used connections to store in the connection list.",
Expand Down
1 change: 1 addition & 0 deletions src/constants/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ export const cmdAzureSignInToCloud = "azure-account.loginToCloud";
export const cmdAadRemoveAccount = "mssql.removeAadAccount";
export const cmdAadAddAccount = "mssql.addAadAccount";
export const cmdClearAzureTokenCache = "mssql.clearAzureAccountTokenCache";
export const cmdShowExecutionPlanInResults = "mssql.showExecutionPlanInResults";
export const cmdNewTable = "mssql.newTable";
export const cmdEditTable = "mssql.editTable";
export const cmdEditConnection = "mssql.editConnection";
Expand Down
80 changes: 47 additions & 33 deletions src/controllers/executionPlanWebviewController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import * as ep from "../reactviews/pages/ExecutionPlan/executionPlanInterfaces";
import { homedir } from "os";
import { exists } from "../utils/utils";
import UntitledSqlDocumentService from "../controllers/untitledSqlDocumentService";
import * as path from "path";
import { ApiStatus } from "../sharedInterfaces/webview";

export class ExecutionPlanWebviewController extends ReactWebviewPanelController<
Expand All @@ -30,16 +29,18 @@ export class ExecutionPlanWebviewController extends ReactWebviewPanelController<
`${xmlPlanFileName}`, // Sets the webview title
"executionPlan",
{
sqlPlanContent: executionPlanContents,
theme:
vscode.window.activeColorTheme.kind ===
vscode.ColorThemeKind.Dark
? "dark"
: "light",
loadState: ApiStatus.Loading,
executionPlan: undefined,
executionPlanGraphs: [],
totalCost: 0,
executionPlanState: {
sqlPlanContent: executionPlanContents,
theme:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use the theme variable in vscodeWebviewContextProvider. This implementation already doesn't support high contrast theme.

vscode.window.activeColorTheme.kind ===
vscode.ColorThemeKind.Dark
? "dark"
: "light",
loadState: ApiStatus.Loading,
executionPlan: undefined,
executionPlanGraphs: [],
totalCost: 0,
},
},
vscode.ViewColumn.Active,
{
Expand All @@ -59,7 +60,7 @@ export class ExecutionPlanWebviewController extends ReactWebviewPanelController<
}

private async initialize() {
this.state.loadState = ApiStatus.Loading;
this.state.executionPlanState.loadState = ApiStatus.Loading;
this.updateState();
await this.createExecutionPlanGraphs();
this.registerRpcHandlers();
Expand All @@ -70,17 +71,21 @@ export class ExecutionPlanWebviewController extends ReactWebviewPanelController<
await this.createExecutionPlanGraphs();
return {
...state,
executionPlan: this.state.executionPlan,
executionPlanGraphs: this.state.executionPlanGraphs,
executionPlanState: {
...state.executionPlanState,
sqlPlanContent: payload.sqlPlanContent,
executionPlan: this.state.executionPlanState.executionPlan,
executionPlanGraphs:
this.state.executionPlanState.executionPlanGraphs,
},
};
});
this.registerReducer("saveExecutionPlan", async (state, payload) => {
let folder = vscode.Uri.file(homedir());
if (await exists("Documents", folder)) {
folder = vscode.Uri.file(path.join(folder.path, "Documents"));
}

let filename: vscode.Uri;

// make the default filename of the plan to be saved-
// start ad plan.sqlplan, then plan1.sqlplan, ...
let counter = 1;
if (await exists(`plan.sqlplan`, folder)) {
while (await exists(`plan${counter}.sqlplan`, folder)) {
Expand All @@ -104,7 +109,7 @@ export class ExecutionPlanWebviewController extends ReactWebviewPanelController<

if (saveUri) {
// Write the content to the new file
await vscode.workspace.fs.writeFile(
vscode.workspace.fs.writeFile(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if writeFile is async and we don't want to await it, then we should explicitly use the void keyword.

saveUri,
Buffer.from(payload.sqlPlanContent),
);
Expand All @@ -118,49 +123,58 @@ export class ExecutionPlanWebviewController extends ReactWebviewPanelController<
language: "xml",
});

await vscode.window.showTextDocument(planXmlDoc);
vscode.window.showTextDocument(planXmlDoc);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

void keyword


return state;
});
this.registerReducer("showQuery", async (state, payload) => {
await this.untitledSqlDocumentService.newQuery(payload.query);
this.untitledSqlDocumentService.newQuery(payload.query);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

void keyword


return state;
});
this.registerReducer("updateTotalCost", async (state, payload) => {
this.state.totalCost += payload.totalCost;
this.state.executionPlanState.totalCost += payload.addedCost;

return {
...state,
totalCost: this.state.totalCost,
executionPlanState: {
...state.executionPlanState,
totalCost: this.state.executionPlanState.totalCost,
},
};
});
}

private async createExecutionPlanGraphs() {
if (!this.state.executionPlan) {
if (!this.state.executionPlanState.executionPlan) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NIT: Why not make this function cleaner and just create a new variable and add all the properties and the end

var executionPlan = {
	//fill all the required stuff
}
this.state = {
	this.state,
	executionPlanState: executionPlan
}

This will prevent you from repeating this.state.executionPlanState... every time.

const planFile: ep.ExecutionPlanGraphInfo = {
graphFileContent: this.executionPlanContents,
graphFileType: ".sqlplan",
};
try {
this.state.executionPlan =
this.state.executionPlanState.executionPlan =
await this.executionPlanService.getExecutionPlan(planFile);
this.state.executionPlanGraphs =
this.state.executionPlan.graphs;
this.state.loadState = ApiStatus.Loaded;
this.state.totalCost = this.calculateTotalCost();
this.state.executionPlanState.executionPlanGraphs =
this.state.executionPlanState.executionPlan.graphs;
this.state.executionPlanState.loadState = ApiStatus.Loaded;
this.state.executionPlanState.totalCost =
this.calculateTotalCost();
} catch (e) {
this.state.loadState = ApiStatus.Error;
this.state.errorMessage = e.toString();
this.state.executionPlanState.loadState = ApiStatus.Error;
this.state.executionPlanState.errorMessage = e.toString();
}
this.updateState();
}
this.updateState();
}

private calculateTotalCost(): number {
if (!this.state.executionPlanState.executionPlanGraphs) {
this.state.executionPlanState.loadState = ApiStatus.Error;
return 0;
}

let sum = 0;
for (const graph of this.state.executionPlanGraphs!) {
for (const graph of this.state.executionPlanState.executionPlanGraphs) {
sum += graph.root.cost + graph.root.subTreeCost;
}
return sum;
Expand Down
28 changes: 28 additions & 0 deletions src/controllers/mainController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ import { QueryResultWebviewController } from "../queryResult/queryResultWebViewC
import { MssqlProtocolHandler } from "../mssqlProtocolHandler";
import { isIConnectionInfo } from "../utils/utils";
import { getStandardNPSQuestions, UserSurvey } from "../nps/userSurvey";
import { ExecutionPlanOptions } from "../models/contracts/queryExecute";

/**
* The main controller class that initializes the extension
Expand All @@ -81,6 +82,10 @@ export default class MainController implements vscode.Disposable {
private _queryHistoryProvider: QueryHistoryProvider;
private _scriptingService: ScriptingService;
private _queryHistoryRegistered: boolean = false;
private _executionPlanOptions: ExecutionPlanOptions = {
includeEstimatedExecutionPlanXml: false,
includeActualExecutionPlanXml: false,
};
public sqlTasksService: SqlTasksService;
public dacFxService: DacFxService;
public schemaCompareService: SchemaCompareService;
Expand Down Expand Up @@ -186,6 +191,8 @@ export default class MainController implements vscode.Disposable {
this.registerCommand(Constants.cmdRunQuery);
this._event.on(Constants.cmdRunQuery, () => {
UserSurvey.getInstance().promptUserForNPSFeedback();
this._executionPlanOptions.includeEstimatedExecutionPlanXml =
false;
this.onRunQuery();
});
this.registerCommand(Constants.cmdManageConnectionProfiles);
Expand Down Expand Up @@ -258,6 +265,15 @@ export default class MainController implements vscode.Disposable {
this._event.on(Constants.cmdClearAzureTokenCache, () =>
this.onClearAzureTokenCache(),
);
this.registerCommand(Constants.cmdShowExecutionPlanInResults);
this._event.on(
Constants.cmdShowExecutionPlanInResults,
async () => {
this._executionPlanOptions.includeEstimatedExecutionPlanXml =
true;
this.onRunQuery();
},
);
this.initializeObjectExplorer();

this.registerCommandWithArgs(
Expand Down Expand Up @@ -338,6 +354,13 @@ export default class MainController implements vscode.Disposable {
SqlToolsServerClient.instance,
);

this._queryResultWebviewController.setExecutionPlanService(
this.executionPlanService,
);
this._queryResultWebviewController.setUntitledDocumentService(
this._untitledSqlDocumentService,
);

const providerInstance = new this.ExecutionPlanCustomEditorProvider(
this._context,
this.executionPlanService,
Expand Down Expand Up @@ -441,6 +464,7 @@ export default class MainController implements vscode.Disposable {
uri,
undefined,
title,
{},
queryPromise,
);
await queryPromise;
Expand Down Expand Up @@ -512,6 +536,8 @@ export default class MainController implements vscode.Disposable {
// Init Query Results Webview Controller
this._queryResultWebviewController = new QueryResultWebviewController(
this._context,
this.executionPlanService,
this.untitledSqlDocumentService,
);

// Init content provider for results pane
Expand Down Expand Up @@ -1525,11 +1551,13 @@ export default class MainController implements vscode.Disposable {
if (editor.document.getText(selectionToTrim).trim().length === 0) {
return;
}

await self._outputContentProvider.runQuery(
self._statusview,
uri,
querySelection,
title,
self._executionPlanOptions,
);
} catch (err) {
console.warn(`Unexpected error running query : ${err}`);
Expand Down
3 changes: 3 additions & 0 deletions src/controllers/queryRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
QueryExecutionOptionsParams,
QueryExecutionOptions,
DbCellValue,
ExecutionPlanOptions,
} from "../models/contracts/queryExecute";
import {
QueryDisposeParams,
Expand Down Expand Up @@ -197,12 +198,14 @@ export default class QueryRunner {
// Pulls the query text from the current document/selection and initiates the query
public async runQuery(
selection: ISelectionData,
executionPlanOptions?: ExecutionPlanOptions,
promise?: Deferred<boolean>,
): Promise<void> {
await this.doRunQuery(selection, async (onSuccess, onError) => {
// Put together the request
let queryDetails: QueryExecuteParams = {
ownerUri: this._ownerUri,
executionPlanOptions: executionPlanOptions,
querySelection: selection,
};

Expand Down
6 changes: 6 additions & 0 deletions src/models/contracts/queryExecute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ export namespace QueryExecuteStatementRequest {

export class QueryExecuteParams {
ownerUri: string;
executionPlanOptions?: ExecutionPlanOptions;
querySelection: ISelectionData;
}

Expand All @@ -115,6 +116,11 @@ export class QueryExecuteStatementParams {

export class QueryExecuteResult {}

export class ExecutionPlanOptions {
includeActualExecutionPlanXml?: boolean;
includeEstimatedExecutionPlanXml?: boolean;
}

// ------------------------------- < Query Results Request > ------------------------------------
export namespace QueryExecuteSubsetRequest {
export const type = new RequestType<
Expand Down
Loading
Loading