forked from joe-re/sql-language-server
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcreateServer.ts
More file actions
395 lines (372 loc) · 12.2 KB
/
Copy pathcreateServer.ts
File metadata and controls
395 lines (372 loc) · 12.2 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
import * as fs from 'fs'
import path from 'path'
import process from 'process'
import {
Connection,
InitializeResult,
CompletionItem,
CompletionParams,
} from 'vscode-languageserver/node'
import { TextDocuments } from 'vscode-languageserver'
import { CompletionTriggerKind } from 'vscode-languageserver-protocol/lib/common/protocol'
import { TextDocument } from 'vscode-languageserver-textdocument'
import {
CodeAction,
TextDocumentEdit,
TextEdit,
Position,
CodeActionKind,
} from 'vscode-languageserver-types'
import { lint, LintResult, FixDescription } from '@deepnote/sqlint'
import { RawConfig } from '@deepnote/sqlint'
import cache from './cache'
import { complete } from './complete'
import createDiagnostics from './createDiagnostics'
import createConnection from './createConnection'
import SettingStore, { Connection as SettingConnection } from './SettingStore'
import { Schema } from './database_libs/AbstractClient'
import getDatabaseClient from './database_libs/getDatabaseClient'
import { RequireSqlite3Error } from './database_libs/Sqlite3Client'
import { stubLogger } from './logger'
export type ConnectionMethod = 'node-ipc' | 'stdio'
const TRIGGER_CHARATER = '.'
export function createServerWithConnection(connection: Connection) {
const logger = stubLogger()
const documents = new TextDocuments(TextDocument)
documents.listen(connection)
let schema: Schema = { tables: [], functions: [] }
let hasConfigurationCapability = false
let rootPath = ''
let lintConfig: RawConfig | null | undefined
// Read schema file
function readJsonSchemaFile(filePath: string) {
if (filePath[0] === '~') {
const home = process.env.HOME || ''
filePath = path.join(home, filePath.slice(1))
}
logger.info(`loading schema file: ${filePath}`)
const data = fs.readFileSync(filePath, 'utf8').replace(/^\ufeff/u, '')
try {
schema = JSON.parse(data)
} catch (e) {
const err = e as NodeJS.ErrnoException
logger.error('failed to read schema file ' + err.message)
connection.sendNotification('sqlLanguageServer.error', {
message:
'Failed to read schema file: ' + filePath + ' error: ' + err.message,
})
throw e
}
}
function readAndMonitorJsonSchemaFile(filePath: string) {
fs.watchFile(filePath, () => {
logger.info(`change detected, reloading schema file: ${filePath}`)
readJsonSchemaFile(filePath)
})
// The readJsonSchemaFile function can throw exceptions so
// read file only after setting up monitoring
readJsonSchemaFile(filePath)
}
async function makeDiagnostics(document: TextDocument) {
const hasRules =
!!lintConfig && Object.prototype.hasOwnProperty.call(lintConfig, 'rules')
const diagnostics = createDiagnostics(
document.uri,
document.getText(),
hasRules ? lintConfig : null
)
connection.sendDiagnostics(diagnostics)
}
documents.onDidChangeContent(async (params) => {
logger.debug(
`onDidChangeContent: ${params.document.uri}, ${params.document.version}`
)
makeDiagnostics(params.document)
})
connection.onInitialize((params): InitializeResult => {
const capabilities = params.capabilities
// JupyterLab sends didChangeConfiguration information
// using both the workspace.configuration and
// workspace.didChangeConfiguration
hasConfigurationCapability =
!!capabilities.workspace &&
(!!capabilities.workspace.configuration ||
!!capabilities.workspace.didChangeConfiguration)
logger.debug(`onInitialize: ${params.rootPath}`)
rootPath = params.rootPath || ''
return {
capabilities: {
textDocumentSync: 1,
completionProvider: {
resolveProvider: true,
triggerCharacters: [TRIGGER_CHARATER],
},
renameProvider: true,
codeActionProvider: true,
executeCommandProvider: {
commands: [
'sqlLanguageServer.switchDatabaseConnection',
'sqlLanguageServer.fixAllFixableProblems',
],
},
},
}
})
connection.onInitialized(async () => {
SettingStore.getInstance().on('change', async () => {
logger.debug('onInitialize: receive change event from SettingStore')
try {
try {
connection.sendNotification('sqlLanguageServer.finishSetup', {
personalConfig: SettingStore.getInstance().getPersonalConfig(),
config: SettingStore.getInstance().getSetting(),
})
} catch (e) {
logger.error(e)
}
const setting = SettingStore.getInstance().getSetting()
if (setting.adapter == 'json') {
// Loading schema from json file
const path = setting.filename || ''
if (path == '') {
logger.error('filename must be provided')
connection.sendNotification('sqlLanguageServer.error', {
message: 'filename must be provided',
})
throw 'filename must be provided'
}
readAndMonitorJsonSchemaFile(path)
} else {
// Else get schema form database client
try {
const client = getDatabaseClient(
SettingStore.getInstance().getSetting()
)
schema = await client.getSchema()
logger.debug('get schema', JSON.stringify(schema))
} catch (e) {
logger.error('failed to get schema info')
if (e instanceof RequireSqlite3Error) {
connection.sendNotification('sqlLanguageServer.error', {
message: 'Need to rebuild sqlite3 module.',
})
}
throw e
}
}
} catch (e) {
logger.error(e)
}
})
const connections =
(hasConfigurationCapability &&
(
await connection.workspace.getConfiguration({
section: 'sqlLanguageServer',
})
)?.connections) ||
[]
if (connections.length > 0) {
SettingStore.getInstance().setSettingFromWorkspaceConfig(connections)
} else if (rootPath) {
SettingStore.getInstance().setSettingFromFile(
`${process.env.HOME}/.config/sql-language-server/.sqllsrc.json`,
`.sqllsrc.json`,
rootPath || ''
)
}
})
connection.onDidChangeConfiguration((change) => {
logger.debug('onDidChangeConfiguration', JSON.stringify(change))
if (!hasConfigurationCapability) {
return
}
if (
!Object.prototype.hasOwnProperty.call(
change.settings,
'sqlLanguageServer'
)
) {
logger.debug(
'onDidChangeConfiguration',
"it doesn't have sqlLanguageServer property"
)
return
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const sqlLanguageServerSetting = (change.settings as { [key: string]: any })
.sqlLanguageServer
const connections = (sqlLanguageServerSetting.connections ??
[]) as SettingConnection[]
if (connections.length > 0) {
SettingStore.getInstance().setSettingFromWorkspaceConfig(connections)
}
// On configuration changes we retrieve the lint config
const lint = sqlLanguageServerSetting.lint as RawConfig
lintConfig = lint
if (lint?.rules) {
documents.all().forEach((v) => {
makeDiagnostics(v)
})
}
})
connection.onCompletion((docParams: CompletionParams): CompletionItem[] => {
// Make sure the client does not send use completion request for characters
// other than the dot which we asked for.
if (
docParams.context?.triggerKind == CompletionTriggerKind.TriggerCharacter
) {
if (docParams.context?.triggerCharacter != TRIGGER_CHARATER) {
return []
}
}
const text = documents.get(docParams.textDocument.uri)?.getText()
if (!text) {
return []
}
logger.debug(text || '')
const pos = {
line: docParams.position.line,
column: docParams.position.character,
}
const setting = SettingStore.getInstance().getSetting()
const candidates = complete(
text,
pos,
schema,
setting.jupyterLabMode
).candidates
if (logger.isDebugEnabled())
logger.debug('onCompletion returns: ' + JSON.stringify(candidates))
return candidates
})
connection.onCodeAction((params) => {
const lintResult = cache.findLintCacheByRange(
params.textDocument.uri,
params.range
)
if (!lintResult) {
return []
}
const document = documents.get(params.textDocument.uri)
if (!document) {
return []
}
const text = document.getText()
if (!text) {
return []
}
function toPosition(text: string, offset: number) {
const lines = text.slice(0, offset).split('\n')
return Position.create(lines.length - 1, lines[lines.length - 1].length)
}
const fixes = Array.isArray(lintResult.lint.fix)
? lintResult.lint.fix
: [lintResult.lint.fix]
if (fixes.length === 0) {
return []
}
const action = CodeAction.create(
`fix: ${lintResult.diagnostic.message}`,
{
documentChanges: [
TextDocumentEdit.create(
{ uri: params.textDocument.uri, version: document.version },
fixes.map((v: FixDescription) => {
const edit =
v.range.startOffset === v.range.endOffset
? TextEdit.insert(
toPosition(text, v.range.startOffset),
v.text
)
: TextEdit.replace(
{
start: toPosition(text, v.range.startOffset),
end: toPosition(text, v.range.endOffset),
},
v.text
)
return edit
})
),
],
},
CodeActionKind.QuickFix
)
action.diagnostics = params.context.diagnostics
return [action]
})
connection.onCompletionResolve((item: CompletionItem): CompletionItem => {
return item
})
connection.onExecuteCommand((request) => {
logger.debug(
`received executeCommand request: ${request.command}, ${request.arguments}`
)
if (
request.command === 'switchDatabaseConnection' ||
request.command === 'sqlLanguageServer.switchDatabaseConnection'
) {
try {
SettingStore.getInstance().changeConnection(
(request.arguments && request.arguments[0]?.toString()) || ''
)
} catch (e) {
const err = e as NodeJS.ErrnoException
connection.sendNotification('sqlLanguageServer.error', {
message: err.message,
})
}
} else if (
request.command === 'fixAllFixableProblems' ||
request.command === 'sqlLanguageServer.fixAllFixableProblems'
) {
const uri = request.arguments ? request.arguments[0] : null
if (!uri) {
connection.sendNotification('sqlLanguageServer.error', {
message: 'fixAllFixableProblems: Need to specify uri',
})
return
}
const document = documents.get(uri.toString())
const text = document?.getText()
if (!text) {
logger.debug('Failed to get text')
return
}
const result: LintResult[] = JSON.parse(
lint({ formatType: 'json', text, fix: true })
)
if (result.length === 0 && result[0].fixedText) {
logger.debug("There's no fixable problems")
return
}
logger.debug('Fix all fixable problems', text, result[0].fixedText)
connection.workspace.applyEdit({
documentChanges: [
TextDocumentEdit.create(
{ uri: uri.toString(), version: document!.version },
[
TextEdit.replace(
{
start: Position.create(0, 0),
end: Position.create(Number.MAX_VALUE, Number.MAX_VALUE),
},
result[0].fixedText!
),
]
),
],
})
}
})
connection.listen()
logger.info('start sql-languager-server')
return connection
}
export function createServer(
params: { method?: ConnectionMethod; debug?: boolean } = {}
) {
const connection: Connection = createConnection(params.method ?? 'node-ipc')
return createServerWithConnection(connection)
}