forked from sqls-server/sqls
/
handler.go
430 lines (378 loc) · 11.3 KB
/
handler.go
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
package handler
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"runtime"
"github.com/sourcegraph/jsonrpc2"
"github.com/mikeismert/sqls/internal/config"
"github.com/mikeismert/sqls/internal/database"
"github.com/mikeismert/sqls/internal/lsp"
)
var (
ErrNoConnection = errors.New("no database connection")
)
type Server struct {
SpecificFileCfg *config.Config
DefaultFileCfg *config.Config
WSCfg *config.Config
dbConn *database.DBConnection
curDBCfg *database.DBConfig
curDBName string
curConnectionIndex int
// The initOptionDBConfig is an optional param
// sent by the client as part of the LSP InitializationOptions
// payload. If non-nil, the server will ignore all
// other configuration sources (workspace and user).
initOptionDBConfig *database.DBConfig
worker *database.Worker
files map[string]*File
}
type File struct {
LanguageID string
Text string
}
func NewServer() *Server {
worker := database.NewWorker()
worker.Start()
return &Server{
files: make(map[string]*File),
worker: worker,
}
}
func panicf(r interface{}, format string, v ...interface{}) error {
if r != nil {
// Same as net/http
const size = 64 << 10
buf := make([]byte, size)
buf = buf[:runtime.Stack(buf, false)]
id := fmt.Sprintf(format, v...)
log.Printf("panic serving %s: %v\n%s", id, r, string(buf))
return fmt.Errorf("unexpected panic: %v", r)
}
return nil
}
func (s *Server) Stop() error {
if err := s.dbConn.Close(); err != nil {
return err
}
s.worker.Stop()
return nil
}
func (s *Server) Handle(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) (result interface{}, err error) {
// Prevent any uncaught panics from taking the entire server down.
defer func() {
if perr := panicf(recover(), "%v", req.Method); perr != nil {
err = perr
}
}()
res, err := s.handle(ctx, conn, req)
if err != nil {
log.Printf("error serving, %+v\n", err)
}
return res, err
}
func (s *Server) handle(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) (result interface{}, err error) {
switch req.Method {
case "initialize":
return s.handleInitialize(ctx, conn, req)
case "initialized":
return
case "shutdown":
return s.handleShutdown(ctx, conn, req)
case "exit":
return s.handleExit(ctx, conn, req)
case "textDocument/didOpen":
return s.handleTextDocumentDidOpen(ctx, conn, req)
case "textDocument/didChange":
return s.handleTextDocumentDidChange(ctx, conn, req)
case "textDocument/didSave":
return s.handleTextDocumentDidSave(ctx, conn, req)
case "textDocument/didClose":
return s.handleTextDocumentDidClose(ctx, conn, req)
case "textDocument/completion":
return s.handleTextDocumentCompletion(ctx, conn, req)
case "textDocument/hover":
return s.handleTextDocumentHover(ctx, conn, req)
case "textDocument/codeAction":
return s.handleTextDocumentCodeAction(ctx, conn, req)
case "workspace/executeCommand":
return s.handleWorkspaceExecuteCommand(ctx, conn, req)
case "workspace/didChangeConfiguration":
return s.handleWorkspaceDidChangeConfiguration(ctx, conn, req)
case "textDocument/formatting":
return s.handleTextDocumentFormatting(ctx, conn, req)
case "textDocument/rangeFormatting":
return s.handleTextDocumentRangeFormatting(ctx, conn, req)
case "textDocument/signatureHelp":
return s.handleTextDocumentSignatureHelp(ctx, conn, req)
case "textDocument/rename":
return s.handleTextDocumentRename(ctx, conn, req)
case "textDocument/definition":
return s.handleDefinition(ctx, conn, req)
case "textDocument/typeDefinition":
return s.handleDefinition(ctx, conn, req)
}
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeMethodNotFound, Message: fmt.Sprintf("method not supported: %s", req.Method)}
}
func (s *Server) handleInitialize(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) (result interface{}, err error) {
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.InitializeParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
result = lsp.InitializeResult{
Capabilities: lsp.ServerCapabilities{
TextDocumentSync: lsp.TDSKFull,
HoverProvider: true,
CodeActionProvider: true,
CompletionProvider: &lsp.CompletionOptions{
TriggerCharacters: []string{"(", "."},
},
SignatureHelpProvider: &lsp.SignatureHelpOptions{
TriggerCharacters: []string{"(", ","},
RetriggerCharacters: []string{"(", ","},
WorkDoneProgressOptions: lsp.WorkDoneProgressOptions{
WorkDoneProgress: false,
},
},
DefinitionProvider: true,
DocumentFormattingProvider: true,
DocumentRangeFormattingProvider: true,
RenameProvider: true,
},
}
s.initOptionDBConfig = params.InitializationOptions.ConnectionConfig
// Initialize database database connection
// NOTE: If no connection is found at this point, it is possible that the connection settings are sent to workspace config, so don't make an error
messenger := lsp.NewLspMessenger(conn)
if err := s.reconnectionDB(ctx); err != nil {
if !errors.Is(ErrNoConnection, err) {
if err := messenger.ShowInfo(ctx, err.Error()); err != nil {
log.Println("send info", err.Error())
return nil, err
}
} else {
log.Println("send err", err.Error())
if err := messenger.ShowError(ctx, err.Error()); err != nil {
return nil, err
}
}
}
return result, nil
}
func (s *Server) handleShutdown(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) (result interface{}, err error) {
if s.dbConn != nil {
s.dbConn.Close()
}
return nil, nil
}
func (s *Server) handleExit(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) (result interface{}, err error) {
if s.dbConn != nil {
s.dbConn.Close()
}
err = s.Stop()
return nil, err
}
func (s *Server) handleTextDocumentDidOpen(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) (result interface{}, err error) {
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.DidOpenTextDocumentParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
if err := s.openFile(params.TextDocument.URI, params.TextDocument.LanguageID); err != nil {
return nil, err
}
if err := s.updateFile(params.TextDocument.URI, params.TextDocument.Text); err != nil {
return nil, err
}
return nil, nil
}
func (s *Server) handleTextDocumentDidChange(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) (result interface{}, err error) {
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.DidChangeTextDocumentParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
if err := s.updateFile(params.TextDocument.URI, params.ContentChanges[0].Text); err != nil {
return nil, err
}
return nil, nil
}
func (s *Server) handleTextDocumentDidSave(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) (result interface{}, err error) {
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.DidSaveTextDocumentParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
if params.Text != "" {
err = s.updateFile(params.TextDocument.URI, params.Text)
} else {
err = s.saveFile(params.TextDocument.URI)
}
if err != nil {
return nil, err
}
return nil, nil
}
func (s *Server) handleTextDocumentDidClose(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) (result interface{}, err error) {
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.DidCloseTextDocumentParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
if err := s.closeFile(params.TextDocument.URI); err != nil {
return nil, err
}
return nil, nil
}
func (s *Server) openFile(uri string, languageID string) error {
f := &File{
Text: "",
LanguageID: languageID,
}
s.files[uri] = f
return nil
}
func (s *Server) closeFile(uri string) error {
delete(s.files, uri)
return nil
}
func (s *Server) updateFile(uri string, text string) error {
f, ok := s.files[uri]
if !ok {
return fmt.Errorf("document not found: %v", uri)
}
f.Text = text
return nil
}
func (s *Server) saveFile(uri string) error {
return nil
}
func (s *Server) handleWorkspaceDidChangeConfiguration(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) (result interface{}, err error) {
// Update changed configration
var params lsp.DidChangeConfigurationParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
s.WSCfg = params.Settings.SQLS
// Skip database connection
if s.dbConn != nil {
return nil, nil
}
// Initialize database database connection
messenger := lsp.NewLspMessenger(conn)
if err := s.reconnectionDB(ctx); err != nil {
if !errors.Is(ErrNoConnection, err) {
if err := messenger.ShowInfo(ctx, err.Error()); err != nil {
log.Println("send info", err.Error())
return nil, err
}
} else {
log.Println("send err", err.Error())
if err := messenger.ShowError(ctx, err.Error()); err != nil {
return nil, err
}
}
}
return nil, nil
}
func (s *Server) reconnectionDB(ctx context.Context) error {
if err := s.dbConn.Close(); err != nil {
return err
}
dbConn, err := s.newDBConnection(ctx)
if err != nil {
return err
}
s.dbConn = dbConn
dbRepo, err := s.newDBRepository(ctx)
if err != nil {
return err
}
if err := s.worker.ReCache(ctx, dbRepo); err != nil {
return err
}
return nil
}
func (s *Server) newDBConnection(ctx context.Context) (*database.DBConnection, error) {
// Get the most preferred DB connection settings
connCfg := s.topConnection()
if connCfg == nil {
return nil, ErrNoConnection
}
if s.curConnectionIndex != 0 {
connCfg = s.getConnection(s.curConnectionIndex)
}
if connCfg == nil {
return nil, fmt.Errorf("not found database connection config, index %d", s.curConnectionIndex+1)
}
if s.curDBName != "" {
connCfg.DBName = s.curDBName
}
s.curDBCfg = connCfg
// Connect database
conn, err := database.Open(connCfg)
if err != nil {
return nil, err
}
return conn, nil
}
func (s *Server) newDBRepository(ctx context.Context) (database.DBRepository, error) {
repo, err := database.CreateRepository(s.curDBCfg.Driver, s.dbConn.Conn)
if err != nil {
return nil, err
}
return repo, nil
}
func (s *Server) topConnection() *database.DBConfig {
// if the init config is set, ignore all other connection configs
if s.initOptionDBConfig != nil {
return s.initOptionDBConfig
}
cfg := s.getConfig()
if cfg == nil || len(cfg.Connections) == 0 {
return nil
}
return cfg.Connections[0]
}
func (s *Server) getConnection(index int) *database.DBConfig {
cfg := s.getConfig()
if cfg == nil || (index < 0 && len(cfg.Connections) <= index) {
return nil
}
return cfg.Connections[index]
}
func (s *Server) getConfig() *config.Config {
var cfg *config.Config
switch {
case validConfig(s.SpecificFileCfg):
cfg = s.SpecificFileCfg
case validConfig(s.WSCfg):
cfg = s.WSCfg
case validConfig(s.DefaultFileCfg):
cfg = s.DefaultFileCfg
default:
cfg = config.NewConfig()
}
return cfg
}
func validConfig(cfg *config.Config) bool {
// if cfg != nil && len(cfg.Connections) > 0 {
if cfg != nil {
return true
}
return false
}