Skip to content

Commit

Permalink
fixes query highlight issue. Fixes driver not loading correctly. Close
Browse files Browse the repository at this point in the history
…#592, closes #600
  • Loading branch information
mtxr committed Jun 2, 2020
1 parent 22beb03 commit 06ac10f
Show file tree
Hide file tree
Showing 23 changed files with 160 additions and 98 deletions.
4 changes: 3 additions & 1 deletion build-tools/.vscode/launch.json
Expand Up @@ -25,12 +25,14 @@
}
},
{
"type": "pwa-node",
"type": "node",
"request": "attach",
"name": "Attach SQLTools LS",
"port": 6010,
"restart": true,
"sourceMaps": true,
"protocol": "inspector",
"timeout": 100000,
"skipFiles": [
"<node_internals>/**/*.js"
],
Expand Down
10 changes: 5 additions & 5 deletions build-tools/common/base-plugins.js
Expand Up @@ -21,11 +21,11 @@ const basePlugins = (name) => [
'process.env.AUTHOR': JSON.stringify(author),
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'production'),
}),
new webpack.SourceMapDevToolPlugin({
moduleFilenameTemplate: (info) => path.relative(rootdir, info.absoluteResourcePath),
filename: IS_PRODUCTION ? '[file].map' : undefined,
sourceRoot: path.relative(outdir, rootdir)
}),
// new webpack.SourceMapDevToolPlugin({
// moduleFilenameTemplate: (info) => path.relative(rootdir, info.absoluteResourcePath),
// filename: IS_PRODUCTION ? '[file].map' : undefined,
// sourceRoot: path.relative(outdir, rootdir)
// }),
new WebpackNotifierPlugin({ excludeWarnings: true }),
];

Expand Down
2 changes: 1 addition & 1 deletion build-tools/common/set-defaults.js
Expand Up @@ -36,7 +36,7 @@ module.exports = function setDefaults(config, includeDefaultPlugins = true) {
config.optimization.minimize = false;
config.optimization.minimizer = undefined;
}
config.devtool = false;
config.devtool = !IS_PRODUCTION ? 'source-map' : false;
config.mode = IS_PRODUCTION ? 'production' : 'development';
config.output = config.output || {};
config.output.path = config.output.path || outdir;
Expand Down
1 change: 1 addition & 0 deletions docs/src/pages/changelog.mdx
Expand Up @@ -9,6 +9,7 @@ route: /changelog

### 0.22.4 - (Jun 2, 2020)

- Add boolean option `sqltools.highlightQuery` to extension configuration so query highlight can be disabled/enabled. [#592](https://github.com/mtxr/vscode-sqltools/issues/592)
- Fixes drivers not loading correctly. [#600](https://github.com/mtxr/vscode-sqltools/issues/600)

### 0.22.3 - (Jun 2, 2020)
Expand Down
2 changes: 2 additions & 0 deletions packages/extension/language-client/client.ts
Expand Up @@ -169,6 +169,8 @@ export class SQLToolsLanguageClient implements ILanguageClient {
extensionPath: Context.extensionPath,
userEnvVars: Config.languageServerEnv
},
progressOnInitialization: true,
outputChannel: logger.outputChannel,
synchronize: {
configurationSection: [EXT_CONFIG_NAMESPACE, 'telemetry'],
fileEvents: Wspc.createFileSystemWatcher(`**/.${EXT_NAMESPACE}rc`),
Expand Down
11 changes: 8 additions & 3 deletions packages/extension/package.json
Expand Up @@ -104,9 +104,9 @@
"id": "sqltools.currentQueryOutline",
"description": "Background decoration color for current query",
"defaults": {
"dark": "#00a2ff50",
"light": "#00a2ff50",
"highContrast": "#00a2ff50"
"dark": "#00a2ff20",
"light": "#00a2ff20",
"highContrast": "#00a2ff20"
}
}
],
Expand Down Expand Up @@ -461,6 +461,11 @@
},
"markdownDescription": "Languages with SQL codelens enabled.\n\nYou can use any language identifier defined on https://code.visualstudio.com/docs/languages/identifiers.\n\nMore info about codelens, see https://vscode-sqltools.mteixeira.dev/features/codelens"
},
"sqltools.highlightQuery": {
"type": "boolean",
"default": true,
"markdownDescription": "Enable or disable hightlight current query under cursor."
},
"sqltools.format": {
"type": "object",
"properties": {
Expand Down
1 change: 0 additions & 1 deletion packages/extension/tsconfig.json
Expand Up @@ -7,7 +7,6 @@
"experimentalDecorators": true,
"lib": ["es6"],
"module": "commonjs",
"noEmit": true,
"removeComments": true,
"resolveJsonModule": true,
"sourceMap": true,
Expand Down
8 changes: 6 additions & 2 deletions packages/language-server/server.ts
Expand Up @@ -10,6 +10,7 @@ import { RegisterPlugin } from './contracts';
import LSContext from './context';
import { ExitCalledNotification } from '../extension/api/contracts';
import { resolve as pathResolve } from 'path';
import logger from '@sqltools/util/log';

class SQLToolsLanguageServer implements ILanguageServer {
private _server: IConnection;
Expand Down Expand Up @@ -113,6 +114,9 @@ class SQLToolsLanguageServer implements ILanguageServer {
ConfigRO.replaceAll(changes.settings[EXT_CONFIG_NAMESPACE]);
if (changes.settings.telemetry && changes.settings.telemetry.enableTelemetry) telemetry.enable();
else telemetry.disable();
if (changes.settings['sqltools.debug'] && changes.settings['sqltools.debug'].namespaces) {
(<any>logger)._debug.enable(changes.settings['sqltools.debug'].namespaces || '*,-babel*');
}

this.onDidChangeConfigurationHooks.forEach(hook => hook());
};
Expand Down Expand Up @@ -141,8 +145,8 @@ ExecPath: ${process.execPath}
return this;
}

public registerPlugin(plugin: ILanguageServerPlugin | ILanguageServerPlugin[]) {
return Promise.all(
public async registerPlugin(plugin: ILanguageServerPlugin | ILanguageServerPlugin[]) {
await Promise.all(
(Array.isArray(plugin) ? plugin : [plugin].filter(Boolean))
.map(p => p.register(this))
);
Expand Down
1 change: 0 additions & 1 deletion packages/language-server/tsconfig.json
Expand Up @@ -7,7 +7,6 @@
"experimentalDecorators": true,
"lib": ["es6"],
"module": "commonjs",
"noEmit": true,
"removeComments": true,
"resolveJsonModule": true,
"sourceMap": true,
Expand Down
4 changes: 4 additions & 0 deletions packages/plugins/codelens/extension.ts
Expand Up @@ -75,13 +75,17 @@ export default class CodeLensPlugin implements IExtensionPlugin {
if (event.affectsConfig('codelensLanguages')) {
this.createCodelens();
}
if (event.affectsConfig('highlightQuery')) {
this.updateDecorations(window.activeTextEditor);
}
});
}

reset() {
return this.provider.reset();
}
updateDecorations = (editor: TextEditor) => {
if (!Config.highlightQuery) return;
if (!editor || !editor.document || editor.document.uri.scheme === 'output' || !this.registeredLanguages.includes(editor.document.languageId)) {
return;
}
Expand Down
9 changes: 8 additions & 1 deletion packages/plugins/connection-manager/contracts.ts
Expand Up @@ -8,6 +8,13 @@ export const GetConnectionsRequest = new RequestType<
Error,
void
>('connection/GetConnectionsRequest');

export const ForceListRefresh = new RequestType<
void,
void,
Error,
void
>('connection/ForceListRefresh');
export const GetConnectionPasswordRequest = new RequestType<
{ conn: IConnection },
string,
Expand All @@ -21,7 +28,7 @@ export const RunCommandRequest = new RequestType<
void
>('connection/RunCommandRequest');
export const ConnectRequest = new RequestType<
{ conn: IConnection; password?: string },
{ conn: IConnection; password?: string, [id: string]: any },
IConnection,
Error,
void
Expand Down
5 changes: 4 additions & 1 deletion packages/plugins/connection-manager/extension.ts
Expand Up @@ -10,7 +10,7 @@ import { SidebarConnection, SidebarItem, ConnectionExplorer } from '@sqltools/pl
import ResultsWebviewManager from '@sqltools/plugins/connection-manager/screens/results';
import SettingsWebview from '@sqltools/plugins/connection-manager/screens/settings';
import { commands, QuickPickItem, window, workspace, ConfigurationTarget, Uri, TextEditor, TextDocument, ProgressLocation, Progress, CancellationTokenSource } from 'vscode';
import { ConnectRequest, DisconnectRequest, GetConnectionPasswordRequest, GetConnectionsRequest, RunCommandRequest, ProgressNotificationStart, ProgressNotificationComplete, ProgressNotificationStartParams, ProgressNotificationCompleteParams, TestConnectionRequest, GetChildrenForTreeItemRequest, SearchConnectionItemsRequest, SaveResultsRequest } from './contracts';
import { ConnectRequest, DisconnectRequest, GetConnectionPasswordRequest, GetConnectionsRequest, RunCommandRequest, ProgressNotificationStart, ProgressNotificationComplete, ProgressNotificationStartParams, ProgressNotificationCompleteParams, TestConnectionRequest, GetChildrenForTreeItemRequest, SearchConnectionItemsRequest, SaveResultsRequest, ForceListRefresh } from './contracts';
import path from 'path';
import CodeLensPlugin from '../codelens/extension';
import { extractConnName, getQueryParameters } from '@sqltools/util/query';
Expand Down Expand Up @@ -701,6 +701,9 @@ export default class ConnectionManagerPlugin implements IExtensionPlugin {
});
this.client.onNotification(ProgressNotificationStart, this.handler_progressStart);
this.client.onNotification(ProgressNotificationComplete, this.handler_progressComplete);
this.client.onRequest(ForceListRefresh, () => {
this.explorer.refresh();
});

// extension stuff
Context.subscriptions.push(
Expand Down
71 changes: 46 additions & 25 deletions packages/plugins/connection-manager/language-server.ts
Expand Up @@ -5,7 +5,7 @@ import { getConnectionId, migrateConnectionSetting } from '@sqltools/util/connec
import csvStringify from 'csv-stringify/lib/sync';
import { writeFile as writeFileWithCb } from 'fs';
import { promisify } from 'util';
import { ConnectRequest, DisconnectRequest, SearchConnectionItemsRequest, GetConnectionPasswordRequest, GetConnectionsRequest, RunCommandRequest, SaveResultsRequest, ProgressNotificationStart, ProgressNotificationComplete, TestConnectionRequest, GetChildrenForTreeItemRequest } from './contracts';
import { ConnectRequest, DisconnectRequest, SearchConnectionItemsRequest, GetConnectionPasswordRequest, GetConnectionsRequest, RunCommandRequest, SaveResultsRequest, ProgressNotificationStart, ProgressNotificationComplete, TestConnectionRequest, GetChildrenForTreeItemRequest, ForceListRefresh } from './contracts';
import Handlers from './cache/handlers';
import DependencyManager from './dependency-manager/language-server';
import { DependeciesAreBeingInstalledNotification } from './dependency-manager/contracts';
Expand All @@ -17,7 +17,7 @@ import queryResultsCache from './cache/query-results.model';

const writeFile = promisify(writeFileWithCb);

const log = logger.extend('conn-mann');
const log = logger.extend('conn-manager');

export default class ConnectionManagerPlugin implements ILanguageServerPlugin {
private server: ILanguageServer;
Expand Down Expand Up @@ -120,18 +120,22 @@ export default class ConnectionManagerPlugin implements ILanguageServerPlugin {
private openConnectionHandler: RequestHandler<typeof ConnectRequest> = async (req: {
conn: IConnection;
password?: string;
internalRequest: boolean;
}): Promise<IConnection> => {
if (!req || !req.conn) {
return undefined;
}
let c = await this.getConnectionInstance(req.conn);
let progressBase;
let progressBase: any;
let c: Connection;
try {
let c = await this.getConnectionInstance(req.conn);
if (c) {
log.extend('debug')('Connection instance already exists for %s.', c.getName());
await Handlers.Connect(c);
return this.serializarConnectionState(req.conn);
}
c = new Connection(req.conn, () => this.server.server.workspace.getWorkspaceFolders());
log.extend('debug')('Connection instance created for %s.', c.getName());

// @OPTIMIZE
progressBase = {
Expand All @@ -141,13 +145,14 @@ export default class ConnectionManagerPlugin implements ILanguageServerPlugin {

if (req.password) c.setPassword(req.password);

this.server.sendNotification(ProgressNotificationStart, { ...progressBase, message: 'Connecting....' });
await Handlers.Connect(c);

this.server.sendNotification(ProgressNotificationStart, { ...progressBase, message: 'Connecting....' });
await c.connect();
this.server.sendNotification(ProgressNotificationComplete, { ...progressBase, message: 'Connected!' });
return this.serializarConnectionState(req.conn);
} catch (e) {
if (req.internalRequest) return Promise.reject(e);
log.extend('Connecting error: %O', e);
await Handlers.Disconnect(c);
progressBase && this.server.sendNotification(ProgressNotificationComplete, progressBase);
Expand All @@ -161,7 +166,7 @@ export default class ConnectionManagerPlugin implements ILanguageServerPlugin {

telemetry.registerException(e);

throw e;
throw Promise.resolve(e);
}
};

Expand Down Expand Up @@ -250,7 +255,8 @@ export default class ConnectionManagerPlugin implements ILanguageServerPlugin {
}

// internal utils
public _autoConnectIfActive = async () => {
public _autoConnectIfActive = async (retryCount = 0) => {
if (retryCount >= RETRY_LIMIT) return;
const defaultConnections: IConnection[] = [];
const [ activeConnections, lastUsedId ] = await Promise.all([
connectionStateCache.get(ACTIVE_CONNECTIONS_KEY, {}),
Expand All @@ -259,41 +265,56 @@ export default class ConnectionManagerPlugin implements ILanguageServerPlugin {
if (lastUsedId && activeConnections[lastUsedId]) {
defaultConnections.push(await this.serializarConnectionState(activeConnections[lastUsedId].serialize()));
}
if (defaultConnections.length === 0
&& (
typeof ConfigRO.autoConnectTo === 'string'
|| (
Array.isArray(ConfigRO.autoConnectTo) && ConfigRO.autoConnectTo.length > 0
)
)
if (
typeof ConfigRO.autoConnectTo === 'string'
|| (
Array.isArray(ConfigRO.autoConnectTo) && ConfigRO.autoConnectTo.length > 0
)
) {
const autoConnectTo = Array.isArray(ConfigRO.autoConnectTo)
? ConfigRO.autoConnectTo
: [ConfigRO.autoConnectTo];
log.extend('info')(`Configuration set to auto connect to: ${autoConnectTo}`);
log.extend('info')(`Configuration set to auto connect to: %s. retry count: %d`, autoConnectTo.join(', '), retryCount);

defaultConnections.push(...ConfigRO.connections
.filter((conn) => conn && autoConnectTo.indexOf(conn.name) >= 0)
.filter(Boolean));
const existingConnections = ConfigRO.connections;
autoConnectTo.forEach(connName => {
if (defaultConnections.find(c => c.name === connName)) return;
const foundConn = existingConnections.find(c => connName === c.name);
if (!foundConn) return;
defaultConnections.push(foundConn);
});
}
if (defaultConnections.length === 0) {
return;
}
log.extend('debug')(`Found connections: %s. retry count: %d`, defaultConnections.map(c => c.name).join(', '), retryCount);
try {
await Promise.all(defaultConnections.slice(1).map(conn =>
(<Promise<IConnection>>this.openConnectionHandler({ conn }))
await Promise.all(defaultConnections.slice(1).map(conn => {
log.extend('info')(`Auto connect to %s`, conn.name);
return Promise.resolve(this.openConnectionHandler({ conn, internalRequest: true }))
.catch(e => {
this.server.notifyError(`Failed to auto connect to ${conn.name}`, e);
if (retryCount < RETRY_LIMIT) return Promise.reject(e);
this.server.notifyError(`Failed to auto connect to ${conn.name}`, e);
return Promise.resolve();
}),
));

await this.openConnectionHandler({ conn: defaultConnections[0] });
});
}));
log.extend('debug')('Will mark %s as active', defaultConnections[0].name);
// leave the last one active
await this.openConnectionHandler({ conn: defaultConnections[0], internalRequest: true });
this.server.sendRequest(ForceListRefresh, undefined);
} catch (error) {
if (retryCount < RETRY_LIMIT) {
log.extend('info')('auto connect will retry: attempts %d', retryCount + 1);
return new Promise((res) => {
setTimeout(res, 1000);
}).then(() => this._autoConnectIfActive(retryCount++));
}
log.extend('error')('auto connect error >> %O', error);
if (error.data && error.data.notification) {
return void this.server.sendNotification(error.data.notification, error.data.args);
}
this.server.notifyError('Auto connect failed', error);
}
}
}
const RETRY_LIMIT = 15;
4 changes: 2 additions & 2 deletions packages/plugins/package.json
Expand Up @@ -12,10 +12,10 @@
"@material-ui/core": "^4.9.7",
"@material-ui/icons": "^4.9.1",
"@rjsf/core": "^2.0.1",
"@sqltools/base-driver": "latest",
"@sqltools/base-driver": "*",
"@sqltools/formatter": "*",
"@sqltools/language-server": "*",
"@sqltools/types": "latest",
"@sqltools/types": "*",
"@sqltools/util": "*",
"@sqltools/vscode": "*",
"command-exists": "1.2.9",
Expand Down
4 changes: 4 additions & 0 deletions packages/types/README.md
Expand Up @@ -12,6 +12,10 @@ This package is part of [vscode-sqltools](https://github.com/mtxr/vscode-sqltool

# Changelog

### v0.1.4

- Add boolean option `highlightQuery` to extension configuration so query highlight can be disabled/enabled.

### v0.1.3

- fixed `checkDependencies` being requred. It's optional
Expand Down
9 changes: 8 additions & 1 deletion packages/types/index.d.ts
Expand Up @@ -560,6 +560,13 @@ export interface ISettings {
* @see {@link https://code.visualstudio.com/docs/languages/identifiers} for more information.
*/
codelensLanguages?: CodelensLanguages;
/**
* Languages with SQL CodeLens enabled.
* @type {boolean}
* @default true
* @memberof ISettings
*/
highlightQuery?: boolean;
/**
* Format document/selection options
* @type {IFormatOptions}
Expand Down Expand Up @@ -784,7 +791,7 @@ export type LSContextMap = Omit<Map<string, any>, 'clear' | 'delete'> & { drive
export interface ILanguageServer {
listen(): void;
getContext(): LSContextMap;
registerPlugin(plugin: ILanguageServerPlugin): this;
registerPlugin(plugin: ILanguageServerPlugin | ILanguageServerPlugin[]): Promise<void>;
sendNotification: LSIConnection['sendNotification'];
onRequest: LSIConnection['onRequest'];
onNotification: LSIConnection['onNotification'];
Expand Down
2 changes: 1 addition & 1 deletion packages/types/package.json
@@ -1,6 +1,6 @@
{
"name": "@sqltools/types",
"version": "0.1.3",
"version": "0.1.4",
"description": "SQLTools interfaces and types",
"types": "index.d.ts",
"main": "index.js",
Expand Down

0 comments on commit 06ac10f

Please sign in to comment.