forked from sqls-server/sqls
/
execute_command.go
458 lines (413 loc) · 10.8 KB
/
execute_command.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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
package handler
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"strconv"
"strings"
"github.com/mikeismert/sqls/ast"
"github.com/mikeismert/sqls/internal/database"
"github.com/mikeismert/sqls/internal/lsp"
"github.com/mikeismert/sqls/parser"
"github.com/olekukonko/tablewriter"
"github.com/sourcegraph/jsonrpc2"
)
const (
CommandExecuteQuery = "executeQuery"
CommandShowDatabases = "showDatabases"
CommandShowSchemas = "showSchemas"
CommandShowConnections = "showConnections"
CommandSwitchDatabase = "switchDatabase"
CommandSwitchConnection = "switchConnections"
CommandShowTables = "showTables"
)
func (h *Server) handleTextDocumentCodeAction(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.CodeActionParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
commands := []lsp.Command{
{
Title: "Execute Query",
Command: CommandExecuteQuery,
Arguments: []interface{}{params.TextDocument.URI},
},
{
Title: "Show Databases",
Command: CommandShowDatabases,
Arguments: []interface{}{},
},
{
Title: "Show Schemas",
Command: CommandShowSchemas,
Arguments: []interface{}{},
},
{
Title: "Show Connections",
Command: CommandShowConnections,
Arguments: []interface{}{},
},
{
Title: "Switch Database",
Command: CommandSwitchDatabase,
Arguments: []interface{}{},
},
{
Title: "Switch Connections",
Command: CommandSwitchConnection,
Arguments: []interface{}{},
},
{
Title: "Show Tables",
Command: CommandShowTables,
Arguments: []interface{}{},
},
}
return commands, nil
}
func (s *Server) handleWorkspaceExecuteCommand(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.ExecuteCommandParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
switch params.Command {
case CommandExecuteQuery:
return s.executeQuery(ctx, params)
case CommandShowDatabases:
return s.showDatabases(ctx, params)
case CommandShowSchemas:
return s.showSchemas(ctx, params)
case CommandShowConnections:
return s.showConnections(ctx, params)
case CommandSwitchDatabase:
return s.switchDatabase(ctx, params)
case CommandSwitchConnection:
return s.switchConnections(ctx, params)
case CommandShowTables:
return s.showTables(ctx, params)
}
return nil, fmt.Errorf("unsupported command: %v", params.Command)
}
func (s *Server) executeQuery(ctx context.Context, params lsp.ExecuteCommandParams) (result interface{}, err error) {
// parse execute command arguments
if s.dbConn == nil {
return nil, errors.New("database connection is not open")
}
if len(params.Arguments) == 0 {
return nil, fmt.Errorf("required arguments were not provided: <File URI>")
}
uri, ok := params.Arguments[0].(string)
if !ok {
return nil, fmt.Errorf("specify the file uri as a string")
}
f, ok := s.files[uri]
if !ok {
return nil, fmt.Errorf("document not found, %q", uri)
}
showVertical := false
if len(params.Arguments) > 1 {
showVerticalFlag, ok := params.Arguments[1].(string)
if ok {
if showVerticalFlag == "-show-vertical" {
showVertical = true
}
}
}
// extract target query
text := f.Text
if params.Range != nil {
text = extractRangeText(
text,
params.Range.Start.Line,
params.Range.Start.Character,
params.Range.End.Line,
params.Range.End.Character,
)
}
stmts, err := getStatements(text)
if err != nil {
return nil, err
}
// execute statements
buf := new(bytes.Buffer)
for _, stmt := range stmts {
query := strings.TrimSpace(stmt.String())
if query == "" {
continue
}
if _, isQuery := database.QueryExecType(query, ""); isQuery {
res, err := s.query(ctx, query, showVertical)
if err != nil {
return nil, err
}
fmt.Fprintln(buf, res)
} else {
res, err := s.exec(ctx, query, showVertical)
if err != nil {
return nil, err
}
fmt.Fprintln(buf, res)
}
}
return buf.String(), nil
}
func extractRangeText(text string, startLine, startChar, endLine, endChar int) string {
writer := bytes.NewBufferString("")
scanner := bufio.NewScanner(strings.NewReader(text))
i := 0
for scanner.Scan() {
t := scanner.Text()
if i >= startLine && i <= endLine {
st, en := 0, len(t)
if i == startLine {
st = startChar
}
if i == endLine {
en = endChar
}
writer.Write([]byte(t[st:en]))
if i != endLine {
writer.Write([]byte("\n"))
}
}
i++
}
return writer.String()
}
func (s *Server) query(ctx context.Context, query string, vertical bool) (string, error) {
repo, err := s.newDBRepository(ctx)
if err != nil {
return "", err
}
rows, err := repo.Query(ctx, query)
if err != nil {
return "", err
}
columns, err := database.Columns(rows)
if err != nil {
return "", err
}
stringRows, err := database.ScanRows(rows, len(columns))
if err != nil {
return "", err
}
buf := new(bytes.Buffer)
if vertical {
table := newVerticalTableWriter(buf)
table.setHeaders(columns)
for _, stringRow := range stringRows {
table.appendRow(stringRow)
}
table.render()
} else {
table := tablewriter.NewWriter(buf)
table.SetHeader(columns)
for _, stringRow := range stringRows {
table.Append(stringRow)
}
table.Render()
}
fmt.Fprintf(buf, "%d rows in set", len(stringRows))
fmt.Fprintln(buf, "")
fmt.Fprintln(buf, "")
return buf.String(), nil
}
func (s *Server) exec(ctx context.Context, query string, vertical bool) (string, error) {
repo, err := s.newDBRepository(ctx)
if err != nil {
return "", err
}
result, err := repo.Exec(ctx, query)
if err != nil {
return "", err
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return "", err
}
buf := new(bytes.Buffer)
fmt.Fprintf(buf, "Query OK, %d row affected", rowsAffected)
fmt.Fprintln(buf, "")
fmt.Fprintln(buf, "")
return buf.String(), nil
}
func (s *Server) showDatabases(ctx context.Context, params lsp.ExecuteCommandParams) (result interface{}, err error) {
repo, err := s.newDBRepository(ctx)
if err != nil {
return "", err
}
databases, err := repo.Databases(ctx)
if err != nil {
return nil, err
}
return strings.Join(databases, "\n"), nil
}
func (s *Server) showSchemas(ctx context.Context, params lsp.ExecuteCommandParams) (result interface{}, err error) {
repo, err := s.newDBRepository(ctx)
if err != nil {
return "", err
}
schemas, err := repo.Schemas(ctx)
if err != nil {
return nil, err
}
return strings.Join(schemas, "\n"), nil
}
func (s *Server) switchDatabase(ctx context.Context, params lsp.ExecuteCommandParams) (result interface{}, err error) {
if len(params.Arguments) != 1 {
return nil, fmt.Errorf("required arguments were not provided: <DB Name>")
}
dbName, ok := params.Arguments[0].(string)
if !ok {
return nil, fmt.Errorf("specify the db name as a string")
}
// Change current database
s.curDBName = dbName
// close and reconnection to database
if err := s.reconnectionDB(ctx); err != nil {
return nil, err
}
return nil, nil
}
func (s *Server) showConnections(ctx context.Context, params lsp.ExecuteCommandParams) (result interface{}, err error) {
results := []string{}
conns := s.getConfig().Connections
for i, conn := range conns {
var desc string
if conn.DataSourceName != "" {
desc = conn.DataSourceName
} else {
switch conn.Proto {
case database.ProtoTCP:
desc = fmt.Sprintf("tcp(%s:%d)/%s", conn.Host, conn.Port, conn.DBName)
case database.ProtoUDP:
desc = fmt.Sprintf("udp(%s:%d)/%s", conn.Host, conn.Port, conn.DBName)
case database.ProtoUnix:
desc = fmt.Sprintf("unix(%s)/%s", conn.Path, conn.DBName)
}
}
res := fmt.Sprintf("%d %s %s %s", i+1, conn.Driver, conn.Alias, desc)
results = append(results, res)
}
return strings.Join(results, "\n"), nil
}
func (s *Server) switchConnections(ctx context.Context, params lsp.ExecuteCommandParams) (result interface{}, err error) {
if len(params.Arguments) != 1 {
return nil, fmt.Errorf("required arguments were not provided: <Connection Index>")
}
indexStr, ok := params.Arguments[0].(string)
if !ok {
return nil, fmt.Errorf("specify the connection index as a number")
}
var index int
cfg := s.getConfig()
if cfg != nil {
for i, conn := range cfg.Connections {
if conn.Alias == indexStr {
index = i + 1
break
}
}
} else {
index, _ = strconv.Atoi(indexStr)
}
if index <= 0 {
return nil, fmt.Errorf("specify the connection index as a number, %w", err)
}
index = index - 1
// Reconnect database
s.curConnectionIndex = index
// close and reconnection to database
if err := s.reconnectionDB(ctx); err != nil {
return nil, err
}
return nil, nil
}
func (s *Server) showTables(ctx context.Context, params lsp.ExecuteCommandParams) (result interface{}, err error) {
repo, err := s.newDBRepository(ctx)
if err != nil {
return "", err
}
m, err := repo.SchemaTables(ctx)
if err != nil {
return nil, err
}
schema, err := repo.CurrentSchema(ctx)
if err != nil {
return nil, err
}
results := []string{}
for k, vv := range m {
for _, v := range vv {
if k != "" {
if schema != k {
continue
}
results = append(results, k+"."+v)
} else {
results = append(results, v)
}
}
}
return strings.Join(results, "\n"), nil
}
func getStatements(text string) ([]*ast.Statement, error) {
parsed, err := parser.Parse(text)
if err != nil {
return nil, err
}
var stmts []*ast.Statement
for _, node := range parsed.GetTokens() {
stmt, ok := node.(*ast.Statement)
if !ok {
return nil, fmt.Errorf("invalid type want Statement parsed %T", stmt)
}
stmts = append(stmts, stmt)
}
return stmts, nil
}
type verticalTableWriter struct {
writer io.Writer
headers []string
rows [][]string
headerMaxLen int
}
func newVerticalTableWriter(writer io.Writer) *verticalTableWriter {
return &verticalTableWriter{
writer: writer,
}
}
func (vtw *verticalTableWriter) setHeaders(headers []string) {
vtw.headers = headers
for _, h := range headers {
length := len(h)
if vtw.headerMaxLen < length {
vtw.headerMaxLen = length
}
}
}
func (vtw *verticalTableWriter) appendRow(row []string) {
vtw.rows = append(vtw.rows, row)
}
func (vtw *verticalTableWriter) render() {
for rowNum, row := range vtw.rows {
fmt.Fprintf(vtw.writer, "***************************[ %d. row ]***************************", rowNum+1)
fmt.Fprintln(vtw.writer, "")
for colNum, col := range row {
header := vtw.headers[colNum]
padHeader := fmt.Sprintf("%"+strconv.Itoa(vtw.headerMaxLen)+"s", header)
fmt.Fprintf(vtw.writer, "%s | %s", padHeader, col)
fmt.Fprintln(vtw.writer, "")
}
}
}