Strict nulls for contrib/restore and contrib/views (#12044)

* strict nulls for contrib/restore and contrib/views

* remove unnecessary function

* compile error
This commit is contained in:
Anthony Dresser
2020-09-01 17:53:29 -07:00
committed by GitHub
parent 9dde80ce1c
commit d8dcc90857
13 changed files with 148 additions and 200 deletions

View File

@@ -45,13 +45,13 @@ export class ManageAction extends Action {
super(id, label);
}
run(actionContext: ManageActionContext): Promise<boolean> {
return this._connectionManagementService.connect(actionContext.profile, actionContext.uri, { showDashboard: true, saveTheConnection: false, params: undefined, showConnectionDialogOnError: false, showFirewallRuleOnError: true }).then(
() => {
this._angularEventingService.sendAngularEvent(actionContext.uri, AngularEventType.NAV_DATABASE);
return true;
}
);
async run(actionContext: ManageActionContext): Promise<boolean> {
if (actionContext.profile) {
await this._connectionManagementService.connect(actionContext.profile, actionContext.uri, { showDashboard: true, saveTheConnection: false, params: undefined, showConnectionDialogOnError: false, showFirewallRuleOnError: true });
this._angularEventingService.sendAngularEvent(actionContext.uri, AngularEventType.NAV_DATABASE);
return true;
}
return false;
}
}
@@ -67,7 +67,9 @@ export class InsightAction extends Action {
}
async run(actionContext: InsightActionContext): Promise<void> {
await this._insightsDialogService.show(actionContext.insight, actionContext.profile);
if (actionContext.profile) {
await this._insightsDialogService.show(actionContext.insight, actionContext.profile);
}
}
}

View File

@@ -3,7 +3,7 @@
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { EditorInput, EditorModel } from 'vs/workbench/common/editor';
import { EditorInput } from 'vs/workbench/common/editor';
import { IDisposable } from 'vs/base/common/lifecycle';
import { URI } from 'vs/base/common/uri';
import { IModelService } from 'vs/editor/common/services/modelService';
@@ -15,22 +15,22 @@ import { mssqlProviderName } from 'sql/platform/connection/common/constants';
export class DashboardInput extends EditorInput {
private _uri: string;
private _uri?: string;
public static ID: string = 'workbench.editorinputs.connectiondashboardinputs';
public static SCHEMA: string = 'sqldashboard';
private _initializedPromise: Thenable<void>;
private _onConnectionChanged: IDisposable;
private _onConnectionChanged?: IDisposable;
public get initializedPromise(): Thenable<void> {
return this._initializedPromise;
}
private _uniqueSelector: string;
private _uniqueSelector?: string;
public hasBootstrapped = false;
// Holds the HTML content for the editor when the editor discards this input and loads another
private _parentContainer: HTMLElement;
private _parentContainer?: HTMLElement;
constructor(
_connectionProfile: IConnectionProfile,
@@ -98,7 +98,7 @@ export class DashboardInput extends EditorInput {
&& this.connectionProfile.databaseName.toLowerCase() === 'master';
}
public get uri(): string {
public get uri(): string | undefined {
return this._uri;
}
@@ -107,7 +107,7 @@ export class DashboardInput extends EditorInput {
if (this._onConnectionChanged) {
this._onConnectionChanged.dispose();
}
this._connectionService.disconnect(this._uri);
this._connectionService.disconnect(this._uri!);
super.dispose();
}
@@ -119,7 +119,6 @@ export class DashboardInput extends EditorInput {
const parentNode = this._parentContainer.parentNode;
if (parentNode) {
parentNode.removeChild(this._parentContainer);
this._parentContainer = null;
}
}
@@ -128,7 +127,7 @@ export class DashboardInput extends EditorInput {
this._parentContainer = container;
}
get container(): HTMLElement {
getContainer(): HTMLElement | undefined {
return this._parentContainer;
}
@@ -137,18 +136,14 @@ export class DashboardInput extends EditorInput {
}
public get connectionProfile(): IConnectionProfile {
return this._connectionService.getConnectionProfile(this._uri);
}
public resolve(refresh?: boolean): Promise<EditorModel> {
return undefined;
return this._connectionService.getConnectionProfile(this._uri!);
}
public get hasInitialized(): boolean {
return !!this._uniqueSelector;
}
public get uniqueSelector(): string {
public get uniqueSelector(): string | undefined {
return this._uniqueSelector;
}
@@ -168,6 +163,6 @@ export class DashboardInput extends EditorInput {
}
public get tabColor(): string {
return this._connectionService.getTabColorForUri(this.uri);
return this._connectionService.getTabColorForUri(this.uri!);
}
}

View File

@@ -4,52 +4,11 @@
*--------------------------------------------------------------------------------------------*/
import { IConnectionProfile } from 'sql/platform/connection/common/interfaces';
import {
IConnectionManagementService,
IConnectionCompletionOptions, ConnectionType,
RunQueryOnConnectionMode, IConnectionResult
} from 'sql/platform/connection/common/connectionManagement';
import { IConnectionManagementService } from 'sql/platform/connection/common/connectionManagement';
import { IObjectExplorerService } from 'sql/workbench/services/objectExplorer/browser/objectExplorerService';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { DashboardInput } from 'sql/workbench/browser/editor/profiler/dashboardInput';
export function replaceConnection(oldUri: string, newUri: string, connectionService: IConnectionManagementService): Promise<IConnectionResult> {
return new Promise<IConnectionResult>((resolve, reject) => {
let defaultResult: IConnectionResult = {
connected: false,
errorMessage: undefined,
errorCode: undefined,
callStack: undefined
};
if (connectionService) {
let connectionProfile = connectionService.getConnectionProfile(oldUri);
if (connectionProfile) {
let options: IConnectionCompletionOptions = {
params: { connectionType: ConnectionType.editor, runQueryOnCompletion: RunQueryOnConnectionMode.none },
saveTheConnection: false,
showDashboard: false,
showConnectionDialogOnError: true,
showFirewallRuleOnError: true
};
connectionService.disconnect(oldUri).then(() => {
connectionService.connect(connectionProfile, newUri, options).then(result => {
resolve(result);
}, connectError => {
reject(connectError);
});
}, disconnectError => {
reject(disconnectError);
});
} else {
resolve(defaultResult);
}
} else {
resolve(defaultResult);
}
});
}
/**
* Get the current global connection, which is the connection from the active editor, unless OE
* is focused or there is no such editor, in which case it comes from the OE selection. Returns
@@ -58,16 +17,17 @@ export function replaceConnection(oldUri: string, newUri: string, connectionServ
* @param topLevelOnly If true, only return top-level (i.e. connected) Object Explorer connections instead of database connections when appropriate
*/
export function getCurrentGlobalConnection(objectExplorerService: IObjectExplorerService, connectionManagementService: IConnectionManagementService, workbenchEditorService: IEditorService, topLevelOnly: boolean = false): IConnectionProfile | undefined {
let connection: IConnectionProfile;
let connection: IConnectionProfile | undefined;
// object Explorer Connection
let objectExplorerSelection = objectExplorerService.getSelectedProfileAndDatabase();
if (objectExplorerSelection) {
let objectExplorerProfile = objectExplorerSelection.profile;
if (connectionManagementService.isProfileConnected(objectExplorerProfile)) {
if (objectExplorerSelection.databaseName && !topLevelOnly) {
connection = objectExplorerProfile.cloneWithDatabase(objectExplorerSelection.databaseName);
} else {
connection = objectExplorerProfile;
if (objectExplorerSelection.profile) {
if (connectionManagementService.isProfileConnected(objectExplorerSelection.profile)) {
if (objectExplorerSelection.databaseName && !topLevelOnly) {
connection = objectExplorerSelection.profile.cloneWithDatabase(objectExplorerSelection.databaseName);
} else {
connection = objectExplorerSelection.profile;
}
}
}
if (objectExplorerService.isFocused()) {

View File

@@ -19,7 +19,6 @@ import { CommonServiceInterface } from 'sql/workbench/services/bootstrap/browser
import { alert } from 'vs/base/browser/ui/aria/aria';
import { IInputOptions, InputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { Delayer } from 'vs/base/common/async';
import { assign } from 'vs/base/common/objects';
import { isStringArray } from 'vs/base/common/types';
import 'vs/css!./media/explorerWidget';
import * as nls from 'vs/nls';
@@ -104,7 +103,7 @@ export class ExplorerWidget extends DashboardWidget implements IDashboardWidget,
this._register(subscriptionToDisposable(this._bootstrap.metadataService.metadata.subscribe(
data => {
if (data) {
const objectData = ObjectMetadataWrapper.createFromObjectMetadata(data.objectMetadata);
const objectData = data.objectMetadata.map(o => new ObjectMetadataWrapper(o));
objectData.sort(ObjectMetadataWrapper.sort);
this.updateTable(objectData);
}
@@ -155,7 +154,7 @@ export class ExplorerWidget extends DashboardWidget implements IDashboardWidget,
const currentProfile = this._bootstrap.connectionManagementService.connectionInfo.connectionProfile;
this.updateTable(data.map(d => {
const item = assign({}, d.options);
const item = Object.assign({}, d.options);
const profile = new ConnectionProfile(this.capabilitiesService, currentProfile);
profile.databaseName = d.options[NameProperty];
item[ConnectionProfilePropertyName] = profile;

View File

@@ -17,14 +17,12 @@ export class ObjectMetadataWrapper implements ObjectMetadata {
return `${this.schema}.${this.name}`;
}
constructor(from?: ObjectMetadata) {
if (from) {
this.metadataType = from.metadataType;
this.metadataTypeName = from.metadataTypeName;
this.urn = from.urn;
this.name = from.name;
this.schema = from.schema;
}
constructor(from: ObjectMetadata) {
this.metadataType = from.metadataType;
this.metadataTypeName = from.metadataTypeName;
this.urn = from.urn;
this.name = from.name;
this.schema = from.schema;
}
public matches(other: ObjectMetadataWrapper): boolean {
@@ -37,14 +35,6 @@ export class ObjectMetadataWrapper implements ObjectMetadata {
&& this.name === other.name;
}
public static createFromObjectMetadata(objectMetadata: ObjectMetadata[]): ObjectMetadataWrapper[] {
if (!objectMetadata) {
return undefined;
}
return objectMetadata.map(m => new ObjectMetadataWrapper(m));
}
// custom sort : Table > View > Stored Procedures > Function
public static sort(metadata1: ObjectMetadataWrapper, metadata2: ObjectMetadataWrapper): number {
// compare the object type

View File

@@ -13,44 +13,43 @@ import { FlavorProperties } from 'sql/workbench/contrib/dashboard/browser/dashbo
suite('Explorer Widget Tests', () => {
test('Sorting dashboard search objects works correctly', () => {
let testMetadata = ObjectMetadataWrapper.createFromObjectMetadata(
[
{
metadataType: MetadataType.View,
metadataTypeName: undefined,
urn: undefined,
name: 'testView',
schema: undefined
},
{
metadataType: MetadataType.Table,
metadataTypeName: undefined,
urn: undefined,
name: 'testTable',
schema: undefined
},
{
metadataType: MetadataType.SProc,
metadataTypeName: undefined,
urn: undefined,
name: 'testSProc',
schema: undefined
},
{
metadataType: MetadataType.Function,
metadataTypeName: undefined,
urn: undefined,
name: 'testFunction',
schema: undefined
},
{
metadataType: MetadataType.View,
metadataTypeName: undefined,
urn: undefined,
name: 'firstView',
schema: undefined
}
]);
let testMetadata = [
{
metadataType: MetadataType.View,
metadataTypeName: undefined,
urn: undefined,
name: 'testView',
schema: undefined
},
{
metadataType: MetadataType.Table,
metadataTypeName: undefined,
urn: undefined,
name: 'testTable',
schema: undefined
},
{
metadataType: MetadataType.SProc,
metadataTypeName: undefined,
urn: undefined,
name: 'testSProc',
schema: undefined
},
{
metadataType: MetadataType.Function,
metadataTypeName: undefined,
urn: undefined,
name: 'testFunction',
schema: undefined
},
{
metadataType: MetadataType.View,
metadataTypeName: undefined,
urn: undefined,
name: 'firstView',
schema: undefined
}
].map(m => new ObjectMetadataWrapper(m));
// If I sort the object metadata wrapper list using ExplorerWidget's sort function
let sortedMetadata = testMetadata.slice().sort(ObjectMetadataWrapper.sort);
@@ -79,44 +78,43 @@ suite('Explorer Widget Tests', () => {
});
test('object type filter', () => {
const testMetadata = ObjectMetadataWrapper.createFromObjectMetadata(
[
{
metadataType: MetadataType.View,
metadataTypeName: undefined,
urn: undefined,
name: 'testView',
schema: undefined
},
{
metadataType: MetadataType.Table,
metadataTypeName: undefined,
urn: undefined,
name: 'testTable',
schema: undefined
},
{
metadataType: MetadataType.SProc,
metadataTypeName: undefined,
urn: undefined,
name: 'testSProc',
schema: undefined
},
{
metadataType: MetadataType.Function,
metadataTypeName: undefined,
urn: undefined,
name: 'testFunction',
schema: undefined
},
{
metadataType: MetadataType.View,
metadataTypeName: undefined,
urn: undefined,
name: 'firstView',
schema: undefined
}
]);
const testMetadata = [
{
metadataType: MetadataType.View,
metadataTypeName: undefined,
urn: undefined,
name: 'testView',
schema: undefined
},
{
metadataType: MetadataType.Table,
metadataTypeName: undefined,
urn: undefined,
name: 'testTable',
schema: undefined
},
{
metadataType: MetadataType.SProc,
metadataTypeName: undefined,
urn: undefined,
name: 'testSProc',
schema: undefined
},
{
metadataType: MetadataType.Function,
metadataTypeName: undefined,
urn: undefined,
name: 'testFunction',
schema: undefined
},
{
metadataType: MetadataType.View,
metadataTypeName: undefined,
urn: undefined,
name: 'firstView',
schema: undefined
}
].map(o => new ObjectMetadataWrapper(o));
const filter = new ExplorerFilter('database', ['name']);
let result = filter.filter('t:', testMetadata);
assert.equal(result.length, 1, 'table type filter should return only 1 item');

View File

@@ -26,9 +26,11 @@ const DE_RESTORE_COMMAND_ID = 'dataExplorer.restore';
// Restore
CommandsRegistry.registerCommand({
id: DE_RESTORE_COMMAND_ID,
handler: (accessor, args: TreeViewItemHandleArg) => {
const commandService = accessor.get(ICommandService);
return commandService.executeCommand(RestoreAction.ID, args.$treeItem.payload);
handler: async (accessor, args: TreeViewItemHandleArg) => {
if (args.$treeItem?.payload) {
const commandService = accessor.get(ICommandService);
return commandService.executeCommand(RestoreAction.ID, args.$treeItem.payload);
}
}
});

View File

@@ -39,9 +39,10 @@ export class RestoreAction extends Task {
});
}
runTask(accessor: ServicesAccessor, profile: IConnectionProfile): void | Promise<void> {
runTask(accessor: ServicesAccessor, withProfile?: IConnectionProfile): void | Promise<void> {
let profile = withProfile;
const configurationService = accessor.get<IConfigurationService>(IConfigurationService);
const previewFeaturesEnabled: boolean = configurationService.getValue('workbench')['enablePreviewFeatures'];
const previewFeaturesEnabled: boolean = configurationService.getValue<{ enablePreviewFeatures: boolean }>('workbench').enablePreviewFeatures;
if (!previewFeaturesEnabled) {
return accessor.get<INotificationService>(INotificationService).info(localize('restore.isPreviewFeature', "You must enable preview features in order to use restore"));
}

View File

@@ -27,7 +27,7 @@ export class NodeContextKey extends Disposable implements IContextKey<INodeConte
private readonly _viewItemKey: IContextKey<string>;
private readonly _nodeContextKey: IContextKey<INodeContextValue>;
private _nodeContextUtils: MssqlNodeContext;
private _nodeContextUtils?: MssqlNodeContext;
constructor(
@IContextKeyService private contextKeyService: IContextKeyService,
@@ -47,7 +47,7 @@ export class NodeContextKey extends Disposable implements IContextKey<INodeConte
}
set(value: INodeContextValue) {
if (value.node && value.node.payload) {
if (value.node?.payload) {
this._connectableKey.set(true);
this._connectedKey.set(this.oeService.isNodeConnected(value.viewId, value.node));
this._connectionContextKey.set(value.node.payload);
@@ -56,14 +56,14 @@ export class NodeContextKey extends Disposable implements IContextKey<INodeConte
this._connectedKey.set(false);
this._connectionContextKey.reset();
}
if (value.node) {
if (value.node?.contextValue) {
this._viewItemKey.set(value.node.contextValue);
} else {
this._viewItemKey.reset();
}
this._nodeContextKey.set(value);
this._viewIdKey.set(value.viewId);
this._nodeContextUtils = new MssqlNodeContext(this._nodeContextKey.get(), this.contextKeyService,
this._nodeContextUtils = new MssqlNodeContext(this._nodeContextKey.get()!, this.contextKeyService,
this.connectionManagementService, this.capabilitiesService);
}
@@ -74,7 +74,7 @@ export class NodeContextKey extends Disposable implements IContextKey<INodeConte
this._connectedKey.reset();
this._connectionContextKey.reset();
this._nodeContextKey.reset();
this._nodeContextUtils.dispose();
this._nodeContextUtils?.dispose();
}
get(): INodeContextValue | undefined {

View File

@@ -665,7 +665,7 @@ class TreeDataSource implements IAsyncDataSource<ITreeItem, ITreeItem> {
if (node.childProvider) {
return this.objectExplorerService.providerExists(node.childProvider) && node.collapsibleState !== TreeItemCollapsibleState.None;
}
return this.treeView.dataProvider && node.collapsibleState !== TreeItemCollapsibleState.None;
return !!this.treeView.dataProvider && node.collapsibleState !== TreeItemCollapsibleState.None;
}
async getChildren(node: ITreeItem): Promise<any[]> {
@@ -812,7 +812,7 @@ class TreeRenderer extends Disposable implements ITreeRenderer<ITreeItem, FuzzyS
if (iconUrl || sqlIcon) {
templateData.icon.className = 'custom-view-tree-node-item-icon';
DOM.toggleClass(templateData.icon, sqlIcon, !!sqlIcon); // tracked change
DOM.toggleClass(templateData.icon, sqlIcon ?? '', !!sqlIcon); // tracked change
DOM.toggleClass(templateData.icon, 'icon', !!sqlIcon);
templateData.icon.style.backgroundImage = iconUrl ? DOM.asCSSUrl(iconUrl) : '';
} else {

View File

@@ -18,7 +18,6 @@ import { TreeItemCollapsibleState } from 'vs/workbench/common/views';
import { localize } from 'vs/nls';
import { NodeType } from 'sql/workbench/services/objectExplorer/common/nodeType';
import { UserCancelledConnectionError } from 'sql/base/common/errors';
import { assign } from 'vs/base/common/objects';
export const SERVICE_ID = 'oeShimService';
export const IOEShimService = createDecorator<IOEShimService>(SERVICE_ID);
@@ -29,7 +28,7 @@ export interface IOEShimService {
disconnectNode(viewId: string, node: ITreeItem): Promise<boolean>;
providerExists(providerId: string): boolean;
isNodeConnected(viewId: string, node: ITreeItem): boolean;
getNodeInfoForTreeItem(treeItem: ITreeItem): azdata.NodeInfo;
getNodeInfoForTreeItem(treeItem: ITreeItem): azdata.NodeInfo | undefined;
}
export class OEShimService extends Disposable implements IOEShimService {
@@ -67,10 +66,14 @@ export class OEShimService extends Disposable implements IOEShimService {
reject(new Error(e.errorMessage));
return;
}
let rootNode = this.oe.getSession(sessionResp.sessionId).rootNode;
let session = this.oe.getSession(sessionResp.sessionId);
if (!session) {
reject(new Error(`Could not have session for ${sessionResp.sessionId}`));
return;
}
// this is how we know it was shimmed
if (rootNode.nodePath) {
this.nodeHandleMap.set(generateNodeMapKey(viewId, node), rootNode.nodePath);
if (session.rootNode.nodePath) {
this.nodeHandleMap.set(generateNodeMapKey(viewId, node), session.rootNode.nodePath);
}
}
listener.dispose();
@@ -92,9 +95,9 @@ export class OEShimService extends Disposable implements IOEShimService {
onConnectCanceled: () => {
reject(new UserCancelledConnectionError(localize('loginCanceled', "User canceled")));
},
onConnectReject: undefined,
onConnectStart: undefined,
onDisconnect: undefined
onConnectReject: () => { },
onConnectStart: () => { },
onDisconnect: () => { }
});
// connection cancelled from firewall dialog
if (!result) {
@@ -110,7 +113,7 @@ export class OEShimService extends Disposable implements IOEShimService {
let key = generateSessionMapKey(viewId, node);
let session = this.sessionMap.get(key);
if (session) {
let closed = (await this.oe.closeSession(node.childProvider, this.oe.getSession(session))).success;
let closed = (await this.oe.closeSession(node.childProvider!, this.oe.getSession(session)!))!.success;
if (closed) {
this.sessionMap.delete(key);
}
@@ -123,21 +126,21 @@ export class OEShimService extends Disposable implements IOEShimService {
// verify the map is correct
let key = generateSessionMapKey(viewId, node);
if (!this.sessionMap.has(key)) {
this.sessionMap.set(key, await this.createSession(viewId, node.childProvider, node));
this.sessionMap.set(key, await this.createSession(viewId, node.childProvider!, node));
}
return this.sessionMap.get(key);
return this.sessionMap.get(key)!;
}
public async getChildren(node: ITreeItem, viewId: string): Promise<ITreeItem[]> {
if (node.payload) {
const sessionId = await this.getOrCreateSession(viewId, node);
const requestHandle = this.nodeHandleMap.get(generateNodeMapKey(viewId, node)) || node.handle;
const treeNode = new TreeNode(undefined, undefined, undefined, requestHandle, undefined, undefined, undefined, undefined, undefined, undefined);
const treeNode = new TreeNode(undefined!, undefined!, undefined!, requestHandle, undefined!); // hack since this entire system is a hack anyways
treeNode.connection = new ConnectionProfile(this.capabilities, node.payload);
const childrenNodes = await this.oe.refreshTreeNode({
success: undefined,
success: true,
sessionId,
rootNode: undefined,
rootNode: undefined!, // hack since this entire system is a hack anyways
errorMessage: undefined
}, treeNode);
return childrenNodes.map(n => this.treeNodeToITreeItem(viewId, n, node));
@@ -169,7 +172,7 @@ export class OEShimService extends Disposable implements IOEShimService {
const database = node.getDatabaseName();
if (database) {
databaseChanged = true;
updatedPayload = assign(updatedPayload, parentNode.payload);
updatedPayload = Object.assign(updatedPayload, parentNode.payload);
updatedPayload.databaseName = node.getDatabaseName();
}
}
@@ -187,7 +190,7 @@ export class OEShimService extends Disposable implements IOEShimService {
payload: node.payload || (databaseChanged ? updatedPayload : parentNode.payload)
};
let newTreeItem: ITreeItem = {
parentHandle: node.parent.id,
parentHandle: node.parent!.id,
handle,
collapsibleState: node.isAlwaysLeaf ? TreeItemCollapsibleState.None : TreeItemCollapsibleState.Collapsed,
label: {
@@ -213,7 +216,7 @@ export class OEShimService extends Disposable implements IOEShimService {
return this.sessionMap.has(generateSessionMapKey(viewId, node));
}
public getNodeInfoForTreeItem(treeItem: ITreeItem): azdata.NodeInfo {
public getNodeInfoForTreeItem(treeItem: ITreeItem): azdata.NodeInfo | undefined {
if (this.nodeInfoMap.has(treeItem)) {
return this.nodeInfoMap.get(treeItem);
}

View File

@@ -15,7 +15,7 @@ import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation
export interface ITaskOptions {
id: string;
title: string;
iconPath: { dark: string; light?: string; };
iconPath?: { dark: string; light?: string; };
description?: ITaskHandlerDescription;
iconClass?: string;
}