-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
sql.go
1702 lines (1471 loc) · 50.3 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 cli
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/cli/cliflags"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/lex"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/sem/builtins"
"github.com/cockroachdb/cockroach/pkg/util/envutil"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/errors"
readline "github.com/knz/go-libedit"
isatty "github.com/mattn/go-isatty"
"github.com/spf13/cobra"
)
const (
welcomeMessage = `#
# Welcome to the CockroachDB SQL shell.
# All statements must be terminated by a semicolon.
# To exit, type: \q.
#
`
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.
Input/Output
\echo [STRING] write the provided string to standard output.
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 list the users for all databases.
\d [TABLE] show details about columns in the specified table, or alias for '\dt' if no table is specified.
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.
%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.
`
defaultPromptPattern = "%n@%M/%/%x>"
// debugPromptPattern avoids substitution patterns that require a db roundtrip.
debugPromptPattern = "%n@%M>"
)
// sqlShellCmd opens a sql shell.
var sqlShellCmd = &cobra.Command{
Use: "sql [options]",
Short: "open a sql shell",
Long: `
Open a sql shell running against a cockroach database.
`,
Args: cobra.NoArgs,
RunE: MaybeDecorateGRPCError(runTerm),
}
// cliState defines the current state of the CLI during
// command-line processing.
//
// Note: options customizable via \set and \unset should be defined in
// sqlCtx or cliCtx instead, so that the configuration remains globals
// across multiple instances of cliState (e.g. across file inclusion
// with \i).
type cliState struct {
conn *sqlConn
// 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
// levels is the number of inclusion recursion levels.
levels int
// 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
//
// 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 demoCtx.transientCluster != nil {
demoHelpStr = demoCommandsHelp
}
fmt.Printf(helpMessageFmt,
demoHelpStr,
base.DocsURL("sql-statements.html"),
base.DocsURL("use-the-built-in-sql-client.html"),
)
fmt.Println()
}
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 {
log.Warningf(context.TODO(), "cannot save command-line history: %s", err)
log.Info(context.TODO(), "command-line history will not be saved in this session")
c.ins.SetAutoSaveHistory("", false)
}
}
func (c *cliState) invalidSyntax(
nextState cliStateEnum, format string, args ...interface{},
) cliStateEnum {
fmt.Fprint(stderr, "invalid syntax: ")
fmt.Fprintf(stderr, format, args...)
fmt.Fprintln(stderr)
c.exitErr = errInvalidSyntax
return nextState
}
func (c *cliState) invalidOptSet(nextState cliStateEnum, args []string) cliStateEnum {
return c.invalidSyntax(nextState, `\set %s. Try \? for help.`, strings.Join(args, " "))
}
func (c *cliState) invalidOptionChange(nextState cliStateEnum, opt string) cliStateEnum {
fmt.Fprintf(stderr, "cannot change option during multi-line editing: %s\n", opt)
return nextState
}
func (c *cliState) internalServerError(nextState cliStateEnum, err error) cliStateEnum {
fmt.Fprintf(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(val string) error
reset func() error
// display is used to retrieve the current value.
display func() string
deprecated bool
}{
`auto_trace`: {
description: "automatically run statement tracing on each executed statement",
isBoolean: false,
validDuringMultilineEntry: false,
set: func(val string) error {
val = strings.ToLower(strings.TrimSpace(val))
switch val {
case "false", "0", "off":
sqlCtx.autoTrace = ""
case "true", "1":
val = "on"
fallthrough
default:
sqlCtx.autoTrace = "on, " + val
}
return nil
},
reset: func() error {
sqlCtx.autoTrace = ""
return nil
},
display: func() string {
if sqlCtx.autoTrace == "" {
return "off"
}
return sqlCtx.autoTrace
},
},
`display_format`: {
description: "the output format for tabular data (table, csv, tsv, html, sql, records, raw)",
isBoolean: false,
validDuringMultilineEntry: true,
set: func(val string) error {
return cliCtx.tableDisplayFormat.Set(val)
},
reset: func() error {
displayFormat := tableDisplayTSV
if cliCtx.terminalOutput {
displayFormat = tableDisplayTable
}
cliCtx.tableDisplayFormat = displayFormat
return nil
},
display: func() string { return cliCtx.tableDisplayFormat.String() },
},
`echo`: {
description: "show SQL queries before they are sent to the server",
isBoolean: true,
validDuringMultilineEntry: false,
set: func(_ string) error { sqlCtx.echo = true; return nil },
reset: func() error { sqlCtx.echo = false; return nil },
display: func() string { return strconv.FormatBool(sqlCtx.echo) },
},
`errexit`: {
description: "exit the shell upon a query error",
isBoolean: true,
validDuringMultilineEntry: true,
set: func(_ string) error { sqlCtx.errExit = true; return nil },
reset: func() error { sqlCtx.errExit = false; return nil },
display: func() string { return strconv.FormatBool(sqlCtx.errExit) },
},
`check_syntax`: {
description: "check the SQL syntax before running a query",
isBoolean: true,
validDuringMultilineEntry: false,
set: func(_ string) error { sqlCtx.checkSyntax = true; return nil },
reset: func() error { sqlCtx.checkSyntax = false; return nil },
display: func() string { return strconv.FormatBool(sqlCtx.checkSyntax) },
},
`show_times`: {
description: "display the execution time after each query",
isBoolean: true,
validDuringMultilineEntry: true,
set: func(_ string) error { sqlCtx.showTimes = true; return nil },
reset: func() error { sqlCtx.showTimes = false; return nil },
display: func() string { return strconv.FormatBool(sqlCtx.showTimes) },
},
`show_server_times`: {
description: "display the server execution times for queries (requires show_times to be set)",
isBoolean: true,
validDuringMultilineEntry: true,
set: func(_ string) error { sqlCtx.enableServerExecutionTimings = true; return nil },
reset: func() error { sqlCtx.enableServerExecutionTimings = false; return nil },
display: func() string { return strconv.FormatBool(sqlCtx.enableServerExecutionTimings) },
},
`verbose_times`: {
description: "display execution times with more precision (requires show_times to be set)",
isBoolean: true,
validDuringMultilineEntry: true,
set: func(_ string) error { sqlCtx.verboseTimings = true; return nil },
reset: func() error { sqlCtx.verboseTimings = false; return nil },
display: func() string { return strconv.FormatBool(sqlCtx.verboseTimings) },
},
`smart_prompt`: {
description: "deprecated",
isBoolean: true,
validDuringMultilineEntry: false,
set: func(_ string) error { return nil },
reset: func() error { return nil },
display: func() 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(val string) error {
sqlCtx.customPromptPattern = val
return nil
},
reset: func() error {
sqlCtx.customPromptPattern = defaultPromptPattern
return nil
},
display: func() string { return sqlCtx.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(), options[n].description})
}
err := printQueryOutput(os.Stdout,
[]string{"Option", "Value", "Description"},
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.invalidOptSet(errState, args)
}
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.invalidOptSet(errState, args)
}
// Run the command.
var err error
if !opt.isBoolean {
err = opt.set(val)
} else {
switch val {
case "true", "1", "on":
err = opt.set("true")
case "false", "0", "off":
err = opt.reset()
default:
return c.invalidOptSet(errState, args)
}
}
if err != nil {
fmt.Fprintf(stderr, "\\set %s: %v\n", strings.Join(args, " "), 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, `\unset %s. Try \? for help.`, strings.Join(args, " "))
}
opt, ok := options[args[0]]
if !ok {
return c.invalidSyntax(errState, `\unset %s. Try \? for help.`, strings.Join(args, " "))
}
if len(c.partialLines) > 0 && !opt.validDuringMultilineEntry {
return c.invalidOptionChange(errState, args[0])
}
if err := opt.reset(); err != nil {
fmt.Fprintf(stderr, "\\unset %s: %v\n", args[0], err)
return errState
}
return nextState
}
func isEndOfStatement(lastTok int) bool {
return lastTok == ';' || lastTok == parser.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 transient cluster signifies the presence of `cockroach demo`.
if demoCtx.transientCluster == nil {
return c.invalidSyntax(errState, `\demo can only be run with cockroach demo`)
}
if len(cmd) == 1 && cmd[0] == "ls" {
demoCtx.transientCluster.listDemoNodes(os.Stdout, false /* justOne */)
return nextState
}
if len(cmd) != 2 {
return c.invalidSyntax(errState, `\demo expects 2 parameters`)
}
nodeID, err := strconv.ParseInt(cmd[1], 10, 32)
if err != nil {
return c.invalidSyntax(
errState,
"%s",
errors.Wrapf(err, "cannot convert %s to string", cmd[2]).Error(),
)
}
switch cmd[0] {
case "shutdown":
if err := demoCtx.transientCluster.DrainAndShutdown(roachpb.NodeID(nodeID)); err != nil {
return c.internalServerError(errState, err)
}
fmt.Printf("node %d has been shutdown\n", nodeID)
return nextState
case "restart":
if err := demoCtx.transientCluster.RestartNode(roachpb.NodeID(nodeID)); err != nil {
return c.internalServerError(errState, err)
}
fmt.Printf("node %d has been restarted\n", nodeID)
return nextState
case "recommission":
if err := demoCtx.transientCluster.Recommission(roachpb.NodeID(nodeID)); err != nil {
return c.internalServerError(errState, err)
}
fmt.Printf("node %d has been recommissioned\n", nodeID)
return nextState
case "decommission":
if err := demoCtx.transientCluster.Decommission(roachpb.NodeID(nodeID)); err != nil {
return c.internalServerError(errState, err)
}
fmt.Printf("node %d has been decommissioned\n", nodeID)
return nextState
}
return c.invalidSyntax(errState, `command not recognized: %s`, cmd[0])
}
// handleHelp prints SQL help.
func (c *cliState) handleHelp(cmd []string, nextState, errState cliStateEnum) cliStateEnum {
cmdrest := strings.TrimSpace(strings.Join(cmd, " "))
command := strings.ToUpper(cmdrest)
if command == "" {
fmt.Print(parser.AllHelp)
} else {
if h, ok := parser.HelpMessages[command]; ok {
msg := parser.HelpMessage{Command: command, HelpMessageBody: h}
msg.Format(os.Stdout)
fmt.Println()
} else {
fmt.Fprintf(stderr,
"no help available for %q.\nTry \\h with no argument to see available help.\n", cmdrest)
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, " "))
if funcName == "" {
for _, f := range builtins.AllBuiltinNames {
fmt.Println(f)
}
fmt.Println()
} else {
helpText, _ := c.serverSideParse(fmt.Sprintf("select %s(??", funcName))
if helpText != "" {
fmt.Println(helpText)
} else {
fmt.Fprintf(stderr,
"no help available for %q.\nTry \\hf with no argument to see available help.\n", funcName)
return errState
}
}
return nextState
}
// execSyscmd executes system commands.
func 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 = stderr
if err := cmd.Run(); err != nil {
return "", fmt.Errorf("error in external command: %s", err)
}
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(stderr, "Usage:\n \\! [command]\n")
c.exitErr = errInvalidSyntax
return errState
}
cmdOut, err := execSyscmd(command)
if err != nil {
fmt.Fprintf(stderr, "command failed: %s\n", err)
c.exitErr = err
return errState
}
fmt.Print(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(stderr, "Usage:\n \\| [command]\n")
c.exitErr = errInvalidSyntax
return errState
}
cmdOut, err := execSyscmd(command)
if err != nil {
fmt.Fprintf(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
}
parsedURL, err := url.Parse(c.conn.url)
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.url + "> "
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(sqlCtx.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(sqlCtx.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 += " "
if len(c.fullPrompt) < 3 {
c.continuePrompt = "> "
} else {
// continued statement prompt is: " -> ".
c.continuePrompt = strings.Repeat(" ", len(c.fullPrompt)-3) + "-> "
}
switch c.useContinuePrompt {
case true:
c.currentPrompt = c.continuePrompt
case false:
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("transaction status", `SHOW TRANSACTION STATUS`)
if !hasVal {
return
}
txnString := formatVal(dbVal,
false /* showPrintableUnicode */, false /* shownewLinesAndTabs */)
// Change the prompt based on the response from the server.
switch txnString {
case sql.NoTxnStateStr:
c.lastKnownTxnStatus = ""
case sql.AbortedStateStr:
c.lastKnownTxnStatus = " ERROR"
case sql.CommitWaitStateStr:
c.lastKnownTxnStatus = " DONE"
case sql.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("database name", `SHOW DATABASE`)
if !hasVal {
return unknownDbName
}
if dbVal == "" {
// Attempt to be helpful to new users.
fmt.Fprintln(stderr, "warning: no current database set."+
" Use SET database = <dbname> to change, CREATE DATABASE to make a new database.")
}
dbName := formatVal(dbVal.(string),
false /* showPrintableUnicode */, false /* shownewLinesAndTabs */)
// Preserve the current database name in case of reconnects.
c.conn.dbName = dbName
return dbName
}
var cmdHistFile = envutil.EnvOrDefaultString("COCKROACH_SQL_CLI_HISTORY", ".cockroachsql_history")
// GetCompletions implements the readline.CompletionGenerator interface.
func (c *cliState) GetCompletions(_ string) []string {
sql, _ := c.ins.GetLineInfo()
if !strings.HasSuffix(sql, "??") {
fmt.Fprintf(c.ins.Stdout(),
"\ntab completion not supported; append '??' and press tab for contextual help\n\n")
} else {
helpText, err := c.serverSideParse(sql)
if helpText != "" {
// We have a completion suggestion. Use that.
fmt.Fprintf(c.ins.Stdout(), "\nSuggestion:\n%s\n", helpText)
} else if err != nil {
// Some other error. Display it.
fmt.Fprintln(c.ins.Stdout())
cliOutputError(c.ins.Stdout(), err, true /*showSeverity*/, false /*verbose*/)
}
}
// After the suggestion or error, re-display the prompt and current entry.
fmt.Fprint(c.ins.Stdout(), c.currentPrompt, sql)
return nil
}
func (c *cliState) doStart(nextState cliStateEnum) cliStateEnum {
// Common initialization.
c.partialLines = []string{}
if cliCtx.isInteractive {
fmt.Println("#\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 {
if len(c.forwardLines) > 0 {
// Are there some lines accumulated from a previous multi-line
// readline input? If so, consume one.
c.lastInputLine = c.forwardLines[0]
c.forwardLines = c.forwardLines[1:]
return nextState
}
var l string
var err error
if c.buf == nil {
l, err = c.ins.GetLine()
if len(l) > 0 && l[len(l)-1] == '\n' {
// Strip the final newline.
l = l[:len(l)-1]
} else {
// There was no newline at the end of the input
// (e.g. Ctrl+C was entered). Force one.
fmt.Fprintln(c.ins.Stdout())
}
} else {
l, err = c.buf.ReadString('\n')
// bufio.ReadString() differs from readline.Readline in the handling of
// EOF. Readline only returns EOF when there is nothing left to read and
// there is no partial line while bufio.ReadString() returns EOF when the
// end of input has been reached but will return the non-empty partial line
// as well. We workaround this by converting the bufio behavior to match
// the Readline behavior.
if err == io.EOF && len(l) != 0 {
err = nil
} else if err == nil {
// From the bufio.ReadString docs: ReadString returns err != nil if and
// only if the returned data does not end in delim. To match the behavior
// of readline.Readline, we strip off the trailing delimiter.
l = l[:len(l)-1]
}
}
switch {
case err == nil:
// Do we have multiple lines of input?
lines := strings.Split(l, "\n")
if len(lines) > 1 {
// Yes: only keep the first one for now, queue the remainder for
// next time the shell needs a line.
l = lines[0]
c.forwardLines = lines[1:]
}
// In any case, process one line.
case errors.Is(err, readline.ErrInterrupted):
if !cliCtx.isInteractive {
// Ctrl+C terminates non-interactive shells in all cases.
c.exitErr = err
return cliStop
}
if l != "" {
// Ctrl+C after the beginning of a line cancels the current
// line.
return cliReadLine
}
if len(c.partialLines) > 0 {
// Ctrl+C at the beginning of a line in a multi-line statement
// cancels the multi-line statement.
return cliStartLine
}
// Otherwise, also terminate with an interrupt error.
c.exitErr = err
return cliStop
case errors.Is(err, io.EOF):
c.atEOF = true
if cliCtx.isInteractive {
// In interactive mode, EOF terminates.
// exitErr is left to be whatever has set it previously.
return cliStop
}
// Non-interactive: if no partial statement, EOF terminates.
// exitErr is left to be whatever has set it previously.
if len(c.partialLines) == 0 {
return cliStop
}
// Otherwise, give the shell a chance to process the last input line.
default:
// Other errors terminate the shell.
fmt.Fprintf(stderr, "input error: %s\n", err)
c.exitErr = err
return cliStop
}
c.lastInputLine = l
return nextState
}
func (c *cliState) doProcessFirstLine(startState, nextState cliStateEnum) cliStateEnum {
// Special case: first line of multi-line statement.
// In this case ignore empty lines, and recognize "help" specially.
switch c.lastInputLine {
case "":
// Ignore empty lines, just continue reading if it isn't interactive mode.
return startState
case "help":
c.printCliHelp()