-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
sql.go
2479 lines (2172 loc) · 73.2 KB
/
sql.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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package clisqlshell
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"net/url"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/cockroachdb/cockroach/pkg/cli/clicfg"
"github.com/cockroachdb/cockroach/pkg/cli/clierror"
"github.com/cockroachdb/cockroach/pkg/cli/clisqlclient"
"github.com/cockroachdb/cockroach/pkg/cli/clisqlexec"
"github.com/cockroachdb/cockroach/pkg/docs"
"github.com/cockroachdb/cockroach/pkg/security/password"
"github.com/cockroachdb/cockroach/pkg/security/pprompt"
"github.com/cockroachdb/cockroach/pkg/server/pgurl"
"github.com/cockroachdb/cockroach/pkg/sql/lexbase"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/scanner"
"github.com/cockroachdb/cockroach/pkg/sql/sqlfsm"
"github.com/cockroachdb/cockroach/pkg/util/envutil"
"github.com/cockroachdb/errors"
readline "github.com/knz/go-libedit"
)
const (
// Refer to README.md to understand the general design guidelines for
// help texts.
helpMessageFmt = `You are using 'cockroach sql', CockroachDB's lightweight SQL client.
General
\q, quit, exit exit the shell (Ctrl+C/Ctrl+D also supported).
Help
\? or "help" print this help.
\h [NAME] help on syntax of SQL commands.
\hf [NAME] help on SQL built-in functions.
Query Buffer
\p during a multi-line statement, show the SQL entered so far.
\r during a multi-line statement, erase all the SQL entered so far.
\| CMD run an external command and run its output as SQL statements.
Connection
\c, \connect {[DB] [USER] [HOST] [PORT] | [URL]}
connect to a server or print the current connection URL.
(Omitted values reuse previous parameters. Use '-' to skip a field.)
\password [USERNAME]
securely change the password for a user
Input/Output
\echo [STRING] write the provided string to standard output.
\i execute commands from the specified file.
\ir as \i, but relative to the location of the current script.
\o [FILE] send all query results to the specified file.
\qecho [STRING] write the provided string to the query output stream (see \o).
Informational
\l list all databases in the CockroachDB cluster.
\dt show the tables of the current schema in the current database.
\dT show the user defined types of the current database.
\du [USER] list the specified user, or list the users for all databases if no user is specified.
\d [TABLE] show details about columns in the specified table, or alias for '\dt' if no table is specified.
\dd TABLE show details about constraints on the specified table.
Formatting
\x [on|off] toggle records display format.
Operating System
\! CMD run an external command and print its results on standard output.
Configuration
\set [NAME] set a client-side flag or (without argument) print the current settings.
\unset NAME unset a flag.
Statement diagnostics
\statement-diag list list available bundles.
\statement-diag download <bundle-id> [<filename>] download bundle.
%s
More documentation about our SQL dialect and the CLI shell is available online:
%s
%s`
demoCommandsHelp = `
Commands specific to the demo shell (EXPERIMENTAL):
\demo ls list the demo nodes and their connection URLs.
\demo shutdown <nodeid> stop a demo node.
\demo restart <nodeid> restart a stopped demo node.
\demo decommission <nodeid> decommission a node.
\demo recommission <nodeid> recommission a node.
\demo add <locality> add a node (locality specified as "region=<region>,zone=<zone>").
`
defaultPromptPattern = "%n@%M/%/%x>"
// debugPromptPattern avoids substitution patterns that require a db roundtrip.
debugPromptPattern = "%n@%M>"
)
// cliState defines the current state of the CLI during
// command-line processing.
//
// Note: options customizable via \set and \unset should be defined in
// sqlConnCtx or sqlCtx instead, so that the configuration remains global
// across multiple instances of cliState (e.g. across file inclusion
// with \i).
type cliState struct {
cliCtx *clicfg.Context
sqlConnCtx *clisqlclient.Context
sqlExecCtx *clisqlexec.Context
sqlCtx *Context
iCtx *internalContext
conn clisqlclient.Conn
// ins is used to read lines if isInteractive is true.
ins readline.EditLine
// buf is used to read lines if isInteractive is false.
buf *bufio.Reader
// singleStatement is set to true when this state level
// is currently processing for runString(). In that mode:
// - a missing semicolon at the end of input is ignored:
// runString("select 1") is valid.
// - errors are not printed by runStatement, since the
// caller of runString() is responsible for processing/
// printing the exitErr.
singleStatement bool
// levels is the number of inclusion recursion levels.
levels int
// includeDir is the directory relative to which relative
// includes (\ir) resolve the file name.
includeDir string
// The prompt at the beginning of a multi-line entry.
fullPrompt string
// The prompt on a continuation line in a multi-line entry.
continuePrompt string
// Which prompt to use to populate currentPrompt.
useContinuePrompt bool
// The current prompt, either fullPrompt or continuePrompt.
currentPrompt string
// State of COPY FROM on the client.
copyFromState *clisqlclient.CopyFromState
// State
//
// lastInputLine is the last valid line obtained from readline.
lastInputLine string
// atEOF indicates whether the last call to readline signaled EOF on input.
atEOF bool
// lastKnownTxnStatus reports the last known transaction
// status. Erased after every statement executed, until the next
// query to the server updates it.
lastKnownTxnStatus string
// forwardLines is the array of lookahead lines. This gets
// populated when there is more than one line of input
// in the data read by ReadLine(), which can happen
// when copy-pasting.
forwardLines []string
// partialLines is the array of lines accumulated so far in a
// multi-line entry.
partialLines []string
// partialStmtsLen represents the number of entries in partialLines
// parsed successfully so far. It grows larger than zero whenever 1)
// syntax checking is enabled and 2) multi-statement (as opposed to
// multi-line) entry starts, i.e. when the shell decides to continue
// inputting statements even after a full statement followed by a
// semicolon was read successfully. This is currently used for
// multi-line transaction editing.
partialStmtsLen int
// concatLines is the concatenation of partialLines, computed during
// doPrepareStatementLine and then reused in doRunStatements() and
// doCheckStatement().
concatLines string
// exitErr defines the error to report to the user upon termination.
// This can carry over from one line of input to another. For
// example in the interactive shell, a statement causing a SQL
// error, followed by lines of whitespace or SQL comments, followed
// by Ctrl+D, causes the shell to terminate with an error --
// reporting the status of the last valid SQL statement executed.
exitErr error
}
// cliStateEnum drives the CLI state machine in runInteractive().
type cliStateEnum int
const (
cliStart cliStateEnum = iota
cliStop
// Querying the server for the current transaction status
// and setting the prompt accordingly.
cliRefreshPrompt
// Just before reading the first line of a potentially multi-line
// statement.
cliStartLine
// Just before reading the 2nd line or after in a multi-line
// statement.
cliContinueLine
// Actually reading the input and checking for input errors.
cliReadLine
// Determine to do with the newly input line.
cliDecidePath
// Process the first line of a (possibly multi-line) entry.
cliProcessFirstLine
// Check and handle for client-side commands.
cliHandleCliCmd
// Concatenate the inputs so far, discard entry made only of whitespace
// and/or comments, and check for semicolons.
cliPrepareStatementLine
// Perform syntax validation if enabled with check_syntax,
// and possibly trigger entry for multi-line transactions.
cliCheckStatement
// Actually run the SQL buffered so far.
cliRunStatement
)
// printCliHelp prints a short inline help about the CLI.
func (c *cliState) printCliHelp() {
demoHelpStr := ""
if c.sqlCtx.DemoCluster != nil {
demoHelpStr = demoCommandsHelp
}
fmt.Fprintf(c.iCtx.stdout, helpMessageFmt,
demoHelpStr,
docs.URL("sql-statements.html"),
docs.URL("use-the-built-in-sql-client.html"),
)
fmt.Fprintln(c.iCtx.stdout)
}
const noLineEditor readline.EditLine = -1
func (c *cliState) hasEditor() bool {
return c.ins != noLineEditor
}
// addHistory persists a line of input to the readline history file.
func (c *cliState) addHistory(line string) {
if !c.hasEditor() || len(line) == 0 {
return
}
// ins.AddHistory will push command into memory and try to
// persist to disk (if ins's history file is set). err can
// be not nil only if it got a IO error while trying to persist.
if err := c.ins.AddHistory(line); err != nil {
fmt.Fprintf(c.iCtx.stderr, "warning: cannot save command-line history: %v\n", err)
c.ins.SetAutoSaveHistory("", false)
}
}
func (c *cliState) invalidSyntax(nextState cliStateEnum) cliStateEnum {
return c.invalidSyntaxf(nextState, `%s. Try \? for help.`, c.lastInputLine)
}
func (c *cliState) inCopy() bool {
return c.copyFromState != nil
}
func (c *cliState) resetCopy() {
c.copyFromState = nil
}
func (c *cliState) invalidSyntaxf(
nextState cliStateEnum, format string, args ...interface{},
) cliStateEnum {
fmt.Fprint(c.iCtx.stderr, "invalid syntax: ")
fmt.Fprintf(c.iCtx.stderr, format, args...)
fmt.Fprintln(c.iCtx.stderr)
c.exitErr = errInvalidSyntax
return nextState
}
func (c *cliState) invalidOptionChange(nextState cliStateEnum, opt string) cliStateEnum {
c.exitErr = errors.Newf("cannot change option during multi-line editing: %s\n", opt)
fmt.Fprintln(c.iCtx.stderr, c.exitErr)
return nextState
}
func (c *cliState) internalServerError(nextState cliStateEnum, err error) cliStateEnum {
fmt.Fprintf(c.iCtx.stderr, "internal server error: %v\n", err)
c.exitErr = err
return nextState
}
var options = map[string]struct {
description string
isBoolean bool
validDuringMultilineEntry bool
set func(c *cliState, val string) error
reset func(c *cliState) error
// display is used to retrieve the current value.
display func(c *cliState) string
deprecated bool
}{
`auto_trace`: {
description: "automatically run statement tracing on each executed statement",
isBoolean: false,
validDuringMultilineEntry: false,
set: func(c *cliState, val string) error {
b, err := clisqlclient.ParseBool(val)
if err != nil {
c.iCtx.autoTrace = "on, " + val
} else if b {
c.iCtx.autoTrace = "on, on"
} else {
c.iCtx.autoTrace = ""
}
return nil
},
reset: func(c *cliState) error {
c.iCtx.autoTrace = ""
return nil
},
display: func(c *cliState) string {
if c.iCtx.autoTrace == "" {
return "off"
}
return c.iCtx.autoTrace
},
},
`border`: {
description: "the border style for the display format 'table'",
isBoolean: false,
validDuringMultilineEntry: true,
set: func(c *cliState, val string) error {
v, err := strconv.Atoi(val)
if err != nil {
return err
}
if v < 0 || v > 3 {
return errors.New("only values between 0 and 4 are supported")
}
c.sqlExecCtx.TableBorderMode = v
return nil
},
display: func(c *cliState) string { return strconv.Itoa(c.sqlExecCtx.TableBorderMode) },
},
`display_format`: {
description: "the output format for tabular data (table, csv, tsv, html, ndjson, sql, records, raw)",
isBoolean: false,
validDuringMultilineEntry: true,
set: func(c *cliState, val string) error {
return c.sqlExecCtx.TableDisplayFormat.Set(val)
},
reset: func(c *cliState) error {
displayFormat := clisqlexec.TableDisplayTSV
if c.sqlExecCtx.TerminalOutput {
displayFormat = clisqlexec.TableDisplayTable
}
c.sqlExecCtx.TableDisplayFormat = displayFormat
return nil
},
display: func(c *cliState) string { return c.sqlExecCtx.TableDisplayFormat.String() },
},
`echo`: {
description: "show SQL queries before they are sent to the server",
isBoolean: true,
validDuringMultilineEntry: false,
set: func(c *cliState, _ string) error { c.sqlConnCtx.Echo = true; return nil },
reset: func(c *cliState) error { c.sqlConnCtx.Echo = false; return nil },
display: func(c *cliState) string { return strconv.FormatBool(c.sqlConnCtx.Echo) },
},
`errexit`: {
description: "exit the shell upon a query error",
isBoolean: true,
validDuringMultilineEntry: true,
set: func(c *cliState, _ string) error { c.iCtx.errExit = true; return nil },
reset: func(c *cliState) error { c.iCtx.errExit = false; return nil },
display: func(c *cliState) string { return strconv.FormatBool(c.iCtx.errExit) },
},
`check_syntax`: {
description: "check the SQL syntax before running a query",
isBoolean: true,
validDuringMultilineEntry: false,
set: func(c *cliState, _ string) error { c.iCtx.checkSyntax = true; return nil },
reset: func(c *cliState) error { c.iCtx.checkSyntax = false; return nil },
display: func(c *cliState) string { return strconv.FormatBool(c.iCtx.checkSyntax) },
},
`show_times`: {
description: "display the execution time after each query",
isBoolean: true,
validDuringMultilineEntry: true,
set: func(c *cliState, _ string) error { c.sqlExecCtx.ShowTimes = true; return nil },
reset: func(c *cliState) error { c.sqlExecCtx.ShowTimes = false; return nil },
display: func(c *cliState) string { return strconv.FormatBool(c.sqlExecCtx.ShowTimes) },
},
`show_server_times`: {
description: "display the server execution times for queries (requires show_times to be set)",
isBoolean: true,
validDuringMultilineEntry: true,
set: func(c *cliState, _ string) error { c.sqlConnCtx.EnableServerExecutionTimings = true; return nil },
reset: func(c *cliState) error { c.sqlConnCtx.EnableServerExecutionTimings = false; return nil },
display: func(c *cliState) string { return strconv.FormatBool(c.sqlConnCtx.EnableServerExecutionTimings) },
},
`verbose_times`: {
description: "display execution times with more precision (requires show_times to be set)",
isBoolean: true,
validDuringMultilineEntry: true,
set: func(c *cliState, _ string) error { c.sqlExecCtx.VerboseTimings = true; return nil },
reset: func(c *cliState) error { c.sqlExecCtx.VerboseTimings = false; return nil },
display: func(c *cliState) string { return strconv.FormatBool(c.sqlExecCtx.VerboseTimings) },
},
`smart_prompt`: {
description: "deprecated",
isBoolean: true,
validDuringMultilineEntry: false,
set: func(c *cliState, _ string) error { return nil },
reset: func(c *cliState) error { return nil },
display: func(c *cliState) string { return "false" },
deprecated: true,
},
`prompt1`: {
description: "prompt string to use before each command (the following are expanded: %M full host, %m host, %> port number, %n user, %/ database, %x txn status)",
isBoolean: false,
validDuringMultilineEntry: true,
set: func(c *cliState, val string) error {
c.iCtx.customPromptPattern = val
return nil
},
reset: func(c *cliState) error {
c.iCtx.customPromptPattern = defaultPromptPattern
return nil
},
display: func(c *cliState) string { return c.iCtx.customPromptPattern },
},
}
// optionNames retains the names of every option in the map above in sorted
// order. We want them sorted to ensure the output of \? is deterministic.
var optionNames = func() []string {
names := make([]string, 0, len(options))
for k := range options {
names = append(names, k)
}
sort.Strings(names)
return names
}()
// handleSet supports the \set client-side command.
func (c *cliState) handleSet(args []string, nextState, errState cliStateEnum) cliStateEnum {
if len(args) == 0 {
optData := make([][]string, 0, len(options))
for _, n := range optionNames {
if options[n].deprecated {
continue
}
optData = append(optData, []string{n, options[n].display(c), options[n].description})
}
err := c.sqlExecCtx.PrintQueryOutput(c.iCtx.stdout, c.iCtx.stderr,
[]string{"Option", "Value", "Description"},
clisqlexec.NewRowSliceIter(optData, "lll" /*align*/))
if err != nil {
panic(err)
}
return nextState
}
if len(args) == 1 {
// Try harder to find a value.
args = strings.SplitN(args[0], "=", 2)
}
opt, ok := options[args[0]]
if !ok {
return c.invalidSyntax(errState)
}
if len(c.partialLines) > 0 && !opt.validDuringMultilineEntry {
return c.invalidOptionChange(errState, args[0])
}
// Determine which value to use.
var val string
switch len(args) {
case 1:
val = "true"
case 2:
val = args[1]
default:
return c.invalidSyntax(errState)
}
// Run the command.
var err error
if !opt.isBoolean {
err = opt.set(c, val)
} else if b, e := clisqlclient.ParseBool(val); e != nil {
return c.invalidSyntax(errState)
} else if b {
err = opt.set(c, "true")
} else {
err = opt.reset(c)
}
if err != nil {
fmt.Fprintf(c.iCtx.stderr, "\\set %s: %v\n", strings.Join(args, " "), err)
c.exitErr = err
return errState
}
return nextState
}
// handleUnset supports the \unset client-side command.
func (c *cliState) handleUnset(args []string, nextState, errState cliStateEnum) cliStateEnum {
if len(args) != 1 {
return c.invalidSyntax(errState)
}
opt, ok := options[args[0]]
if !ok {
return c.invalidSyntax(errState)
}
if len(c.partialLines) > 0 && !opt.validDuringMultilineEntry {
return c.invalidOptionChange(errState, args[0])
}
if err := opt.reset(c); err != nil {
fmt.Fprintf(c.iCtx.stderr, "\\unset %s: %v\n", args[0], err)
c.exitErr = err
return errState
}
return nextState
}
func isEndOfStatement(lastTok int) bool {
return lastTok == ';' || lastTok == lexbase.HELPTOKEN
}
// handleDemo handles operations on \demo.
// This can only be done from `cockroach demo`.
func (c *cliState) handleDemo(cmd []string, nextState, errState cliStateEnum) cliStateEnum {
// A demo cluster signifies the presence of `cockroach demo`.
if c.sqlCtx.DemoCluster == nil {
return c.invalidSyntaxf(errState, `\demo can only be run with cockroach demo`)
}
// The \demo command has one of three patterns:
//
// - A lone command (currently, only ls)
// - A command followed by a string (add followed by locality string)
// - A command followed by a node number (shutdown, restart, decommission, recommission)
//
// We parse these commands separately, in the following blocks.
if len(cmd) == 1 && cmd[0] == "ls" {
c.sqlCtx.DemoCluster.ListDemoNodes(c.iCtx.stdout, c.iCtx.stderr, false /* justOne */)
return nextState
}
if len(cmd) != 2 {
return c.invalidSyntax(errState)
}
// Special case the add command it takes a string instead of a node number.
if cmd[0] == "add" {
return c.handleDemoAddNode(cmd, nextState, errState)
}
// If we've made it down here, we're handling the remaining demo node commands.
return c.handleDemoNodeCommands(cmd, nextState, errState)
}
// handleDemoAddNode handles the `add` node command in demo.
func (c *cliState) handleDemoAddNode(cmd []string, nextState, errState cliStateEnum) cliStateEnum {
if cmd[0] != "add" {
return c.internalServerError(errState, fmt.Errorf("bad call to handleDemoAddNode"))
}
addedNodeID, err := c.sqlCtx.DemoCluster.AddNode(context.Background(), cmd[1])
if err != nil {
return c.internalServerError(errState, err)
}
fmt.Fprintf(c.iCtx.stdout, "node %v has been added with locality \"%s\"\n",
addedNodeID, c.sqlCtx.DemoCluster.GetLocality(addedNodeID))
return nextState
}
// handleDemoNodeCommands handles the node commands in demo (with the exception of `add` which is handled
// with handleDemoAddNode.
func (c *cliState) handleDemoNodeCommands(
cmd []string, nextState, errState cliStateEnum,
) cliStateEnum {
nodeID, err := strconv.ParseInt(cmd[1], 10, 32)
if err != nil {
return c.invalidSyntaxf(
errState,
"%s",
errors.Wrapf(err, "%q is not a valid node ID", cmd[1]),
)
}
ctx := context.Background()
switch cmd[0] {
case "shutdown":
if err := c.sqlCtx.DemoCluster.DrainAndShutdown(ctx, int32(nodeID)); err != nil {
return c.internalServerError(errState, err)
}
fmt.Fprintf(c.iCtx.stdout, "node %d has been shutdown\n", nodeID)
return nextState
case "restart":
if err := c.sqlCtx.DemoCluster.RestartNode(ctx, int32(nodeID)); err != nil {
return c.internalServerError(errState, err)
}
fmt.Fprintf(c.iCtx.stdout, "node %d has been restarted\n", nodeID)
return nextState
case "recommission":
if err := c.sqlCtx.DemoCluster.Recommission(ctx, int32(nodeID)); err != nil {
return c.internalServerError(errState, err)
}
fmt.Fprintf(c.iCtx.stdout, "node %d has been recommissioned\n", nodeID)
return nextState
case "decommission":
if err := c.sqlCtx.DemoCluster.Decommission(ctx, int32(nodeID)); err != nil {
return c.internalServerError(errState, err)
}
fmt.Fprintf(c.iCtx.stdout, "node %d has been decommissioned\n", nodeID)
return nextState
}
return c.invalidSyntax(errState)
}
// handleHelp prints SQL help.
func (c *cliState) handleHelp(cmd []string, nextState, errState cliStateEnum) cliStateEnum {
command := strings.TrimSpace(strings.Join(cmd, " "))
helpText, _ := c.serverSideParse(command + " ??")
if helpText != "" {
fmt.Fprintln(c.iCtx.stdout, helpText)
} else {
fmt.Fprintf(c.iCtx.stderr,
"no help available for %q.\nTry \\h with no argument to see available help.\n", command)
c.exitErr = errors.New("no help available")
return errState
}
return nextState
}
// handleFunctionHelp prints help about built-in functions.
func (c *cliState) handleFunctionHelp(cmd []string, nextState, errState cliStateEnum) cliStateEnum {
funcName := strings.TrimSpace(strings.Join(cmd, " "))
helpText, _ := c.serverSideParse(fmt.Sprintf("select %s(??", funcName))
if helpText != "" {
fmt.Fprintln(c.iCtx.stdout, helpText)
} else {
fmt.Fprintf(c.iCtx.stderr,
"no help available for %q.\nTry \\hf with no argument to see available help.\n", funcName)
c.exitErr = errors.New("no help available")
return errState
}
return nextState
}
// execSyscmd executes system commands.
func (c *cliState) execSyscmd(command string) (string, error) {
var cmd *exec.Cmd
shell := envutil.GetShellCommand(command)
cmd = exec.Command(shell[0], shell[1:]...)
var out bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = c.iCtx.stderr
if err := cmd.Run(); err != nil {
return "", errors.Wrap(err, "error in external command")
}
return out.String(), nil
}
var errInvalidSyntax = errors.New("invalid syntax")
// runSyscmd runs system commands on the interactive CLI.
func (c *cliState) runSyscmd(line string, nextState, errState cliStateEnum) cliStateEnum {
command := strings.Trim(line[2:], " \r\n\t\f")
if command == "" {
fmt.Fprintf(c.iCtx.stderr, "Usage:\n \\! [command]\n")
c.exitErr = errInvalidSyntax
return errState
}
cmdOut, err := c.execSyscmd(command)
if err != nil {
fmt.Fprintf(c.iCtx.stderr, "command failed: %s\n", err)
c.exitErr = err
return errState
}
fmt.Fprint(c.iCtx.stdout, cmdOut)
return nextState
}
// pipeSyscmd executes system commands and pipe the output into the current SQL.
func (c *cliState) pipeSyscmd(line string, nextState, errState cliStateEnum) cliStateEnum {
command := strings.Trim(line[2:], " \n\r\t\f")
if command == "" {
fmt.Fprintf(c.iCtx.stderr, "Usage:\n \\| [command]\n")
c.exitErr = errInvalidSyntax
return errState
}
cmdOut, err := c.execSyscmd(command)
if err != nil {
fmt.Fprintf(c.iCtx.stderr, "command failed: %s\n", err)
c.exitErr = err
return errState
}
c.lastInputLine = cmdOut
return nextState
}
// rePromptFmt recognizes every substitution pattern in the prompt format string.
var rePromptFmt = regexp.MustCompile("(%.)")
// rePromptDbState recognizes every substitution pattern that requires
// access to the current database state.
// Currently:
// %/ database name
// %x txn status
var rePromptDbState = regexp.MustCompile("(?:^|[^%])%[/x]")
// unknownDbName is the string to use in the prompt when
// the database cannot be determined.
const unknownDbName = "?"
// unknownTxnStatus is the string to use in the prompt when the txn status cannot be determined.
const unknownTxnStatus = " ?"
// doRefreshPrompts refreshes the prompts of the client depending on the
// status of the current transaction.
func (c *cliState) doRefreshPrompts(nextState cliStateEnum) cliStateEnum {
if !c.hasEditor() {
return nextState
}
if c.useContinuePrompt {
if c.inCopy() {
c.continuePrompt = ">> "
} else if len(c.fullPrompt) < 3 {
c.continuePrompt = "> "
} else {
// continued statement prompt is: " -> ".
c.continuePrompt = strings.Repeat(" ", len(c.fullPrompt)-3) + "-> "
}
c.ins.SetLeftPrompt(c.continuePrompt)
return nextState
}
if c.inCopy() {
c.fullPrompt = ">>"
} else {
// Configure the editor to use the new prompt.
parsedURL, err := url.Parse(c.conn.GetURL())
if err != nil {
// If parsing fails, we'll keep the entire URL. The Open call succeeded, and that
// is the important part.
c.fullPrompt = c.conn.GetURL() + "> "
c.continuePrompt = strings.Repeat(" ", len(c.fullPrompt)-3) + "-> "
return nextState
}
userName := ""
if parsedURL.User != nil {
userName = parsedURL.User.Username()
}
dbName := unknownDbName
c.lastKnownTxnStatus = unknownTxnStatus
wantDbStateInPrompt := rePromptDbState.MatchString(c.iCtx.customPromptPattern)
if wantDbStateInPrompt {
c.refreshTransactionStatus()
// refreshDatabaseName() must be called *after* refreshTransactionStatus(),
// even when %/ appears before %x in the prompt format.
// This is because the database name should not be queried during
// some transaction phases.
dbName = c.refreshDatabaseName()
}
c.fullPrompt = rePromptFmt.ReplaceAllStringFunc(c.iCtx.customPromptPattern, func(m string) string {
switch m {
case "%M":
return parsedURL.Host // full host name.
case "%m":
return parsedURL.Hostname() // host name.
case "%>":
return parsedURL.Port() // port.
case "%n": // user name.
return userName
case "%/": // database name.
return dbName
case "%x": // txn status.
return c.lastKnownTxnStatus
case "%%":
return "%"
default:
err = fmt.Errorf("unrecognized format code in prompt: %q", m)
return ""
}
})
if err != nil {
c.fullPrompt = err.Error()
}
}
c.fullPrompt += " "
c.currentPrompt = c.fullPrompt
// Configure the editor to use the new prompt.
c.ins.SetLeftPrompt(c.currentPrompt)
return nextState
}
// refreshTransactionStatus retrieves and sets the current transaction status.
func (c *cliState) refreshTransactionStatus() {
c.lastKnownTxnStatus = unknownTxnStatus
dbVal, hasVal := c.conn.GetServerValue(
context.Background(),
"transaction status", `SHOW TRANSACTION STATUS`)
if !hasVal {
return
}
txnString := clisqlexec.FormatVal(
dbVal, false /* showPrintableUnicode */, false, /* shownewLinesAndTabs */
)
// Change the prompt based on the response from the server.
switch txnString {
case sqlfsm.NoTxnStateStr:
c.lastKnownTxnStatus = ""
case sqlfsm.AbortedStateStr:
c.lastKnownTxnStatus = " ERROR"
case sqlfsm.CommitWaitStateStr:
c.lastKnownTxnStatus = " DONE"
case sqlfsm.OpenStateStr:
// The state AutoRetry is reported by the server as Open, so no need to
// handle it here.
c.lastKnownTxnStatus = " OPEN"
}
}
// refreshDatabaseName retrieves the current database name from the server.
// The database name is only queried if there is no transaction ongoing,
// or the transaction is fully open.
func (c *cliState) refreshDatabaseName() string {
if !(c.lastKnownTxnStatus == "" /*NoTxn*/ ||
c.lastKnownTxnStatus == " OPEN" ||
c.lastKnownTxnStatus == unknownTxnStatus) {
return unknownDbName
}
dbVal, hasVal := c.conn.GetServerValue(
context.Background(),
"database name", `SHOW DATABASE`)
if !hasVal {
return unknownDbName
}
if dbVal == "" {
// Attempt to be helpful to new users.
fmt.Fprintln(c.iCtx.stderr, "warning: no current database set."+
" Use SET database = <dbname> to change, CREATE DATABASE to make a new database.")
}
dbName := clisqlexec.FormatVal(
dbVal, false /* showPrintableUnicode */, false, /* shownewLinesAndTabs */
)
// Preserve the current database name in case of reconnects.
c.conn.SetCurrentDatabase(dbName)
c.iCtx.dbName = dbName
return dbName
}
var cmdHistFile = envutil.EnvOrDefaultString("COCKROACH_SQL_CLI_HISTORY", ".cockroachsql_history")
// GetCompletions implements the readline.CompletionGenerator interface.
func (c *cliState) GetCompletions(s string) []string {
sql, _ := c.ins.GetLineInfo()
// In COPY mode, just add a tab character.
if c.inCopy() {
return []string{s + "\t"}
}
if !strings.HasSuffix(sql, "??") {
query := fmt.Sprintf(`SHOW COMPLETIONS AT OFFSET %d FOR %s`, len(sql), lexbase.EscapeSQLString(sql))
var rows [][]string
var err error
err = c.runWithInterruptableCtx(func(ctx context.Context) error {
_, rows, err = c.sqlExecCtx.RunQuery(ctx, c.conn, clisqlclient.MakeQuery(query), true /* showMoreChars */)
return err
})
if err != nil {
clierror.OutputError(c.iCtx.stdout, err, true /*showSeverity*/, false /*verbose*/)
}
var completions []string
for _, row := range rows {
completions = append(completions, row[0])
}
return completions
}
helpText, err := c.serverSideParse(sql)
if helpText != "" {
// We have a completion suggestion. Use that.
fmt.Fprintf(c.iCtx.stdout, "\nSuggestion:\n%s\n", helpText)
} else if err != nil {
// Some other error. Display it.
fmt.Fprintln(c.iCtx.stdout)
clierror.OutputError(c.iCtx.stdout, err, true /*showSeverity*/, false /*verbose*/)
}
// After the suggestion or error, re-display the prompt and current entry.
fmt.Fprint(c.iCtx.stdout, c.currentPrompt, sql)
return nil
}
func (c *cliState) doStart(nextState cliStateEnum) cliStateEnum {
// Common initialization.
c.partialLines = []string{}
if c.cliCtx.IsInteractive {
fmt.Fprintln(c.iCtx.stdout, "#\n# Enter \\? for a brief introduction.\n#")
}
return nextState
}
func (c *cliState) doStartLine(nextState cliStateEnum) cliStateEnum {
// Clear the input buffer.
c.atEOF = false
c.partialLines = c.partialLines[:0]
c.partialStmtsLen = 0
c.useContinuePrompt = false
return nextState
}
func (c *cliState) doContinueLine(nextState cliStateEnum) cliStateEnum {
c.atEOF = false
c.useContinuePrompt = true
return nextState
}
// doReadline reads a line of input and check the input status. If
// input was successful it populates c.lastInputLine. Otherwise
// c.exitErr is set in some cases and an error/retry state is returned.
func (c *cliState) doReadLine(nextState cliStateEnum) cliStateEnum {