-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
cli_test.go
2488 lines (2310 loc) · 69.4 KB
/
cli_test.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.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
package cli
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"testing"
"time"
"github.com/pkg/errors"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/build"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/security/securitytest"
"github.com/cockroachdb/cockroach/pkg/server"
"github.com/cockroachdb/cockroach/pkg/sql/lex"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
)
type cliTest struct {
*server.TestServer
certsDir string
cleanupFunc func() error
// t is the testing.T instance used for this test.
// Example_xxx tests may have this set to nil.
t *testing.T
// logScope binds the lifetime of the log files to this test, when t
// is not nil
logScope *log.TestLogScope
// if true, doesn't print args during RunWithArgs
omitArgs bool
}
type cliTestParams struct {
t *testing.T
insecure bool
noServer bool
storeSpecs []base.StoreSpec
locality roachpb.Locality
}
func (c *cliTest) fail(err interface{}) {
if c.t != nil {
defer c.logScope.Close(c.t)
c.t.Fatal(err)
} else {
panic(err)
}
}
func newCLITest(params cliTestParams) cliTest {
c := cliTest{t: params.t}
certsDir, err := ioutil.TempDir("", "cli-test")
if err != nil {
c.fail(err)
}
c.certsDir = certsDir
if c.t != nil {
c.logScope = log.Scope(c.t)
}
c.cleanupFunc = func() error { return nil }
if !params.noServer {
if !params.insecure {
// Copy these assets to disk from embedded strings, so this test can
// run from a standalone binary.
// Disable embedded certs, or the security library will try to load
// our real files as embedded assets.
security.ResetAssetLoader()
assets := []string{
filepath.Join(security.EmbeddedCertsDir, security.EmbeddedCACert),
filepath.Join(security.EmbeddedCertsDir, security.EmbeddedCAKey),
filepath.Join(security.EmbeddedCertsDir, security.EmbeddedNodeCert),
filepath.Join(security.EmbeddedCertsDir, security.EmbeddedNodeKey),
filepath.Join(security.EmbeddedCertsDir, security.EmbeddedRootCert),
filepath.Join(security.EmbeddedCertsDir, security.EmbeddedRootKey),
}
for _, a := range assets {
securitytest.RestrictedCopy(nil, a, certsDir, filepath.Base(a))
}
baseCfg.SSLCertsDir = certsDir
c.cleanupFunc = func() error {
security.SetAssetLoader(securitytest.EmbeddedAssets)
return os.RemoveAll(c.certsDir)
}
}
s, err := serverutils.StartServerRaw(base.TestServerArgs{
Insecure: params.insecure,
SSLCertsDir: c.certsDir,
StoreSpecs: params.storeSpecs,
Locality: params.locality,
})
if err != nil {
c.fail(err)
}
c.TestServer = s.(*server.TestServer)
log.Infof(context.TODO(), "server started at %s", c.ServingAddr())
}
baseCfg.User = security.NodeUser
// Ensure that CLI error messages and anything meant for the
// original stderr is redirected to stdout, where it can be
// captured.
stderr = os.Stdout
return c
}
// setCLIDefaultsForTests invokes initCLIDefaults but pretends the
// output is not a terminal, even if it happens to be. This ensures
// e.g. that tests ran with -v have the same output as those without.
func setCLIDefaultsForTests() {
initCLIDefaults()
cliCtx.terminalOutput = false
cliCtx.showTimes = false
// Even though we pretend there is no terminal, most tests want
// pretty tables.
cliCtx.tableDisplayFormat = tableDisplayTable
}
// stopServer stops the test server.
func (c *cliTest) stopServer() {
if c.TestServer != nil {
log.Infof(context.TODO(), "stopping server at %s", c.ServingAddr())
select {
case <-c.Stopper().ShouldStop():
// If ShouldStop() doesn't block, that means someone has already
// called Stop(). We just need to wait.
<-c.Stopper().IsStopped()
default:
c.Stopper().Stop(context.TODO())
}
}
}
// restartServer stops and restarts the test server. The ServingAddr() may
// have changed after this method returns.
func (c *cliTest) restartServer(params cliTestParams) {
c.stopServer()
log.Info(context.TODO(), "restarting server")
s, err := serverutils.StartServerRaw(base.TestServerArgs{
Insecure: params.insecure,
SSLCertsDir: c.certsDir,
StoreSpecs: params.storeSpecs,
})
if err != nil {
c.fail(err)
}
c.TestServer = s.(*server.TestServer)
log.Infof(context.TODO(), "restarted server at %s", c.ServingAddr())
}
// cleanup cleans up after the test, stopping the server if necessary.
// The log files are removed if the test has succeeded.
func (c *cliTest) cleanup() {
if c.t != nil {
defer c.logScope.Close(c.t)
}
// Restore stderr.
stderr = log.OrigStderr
log.Info(context.TODO(), "stopping server and cleaning up CLI test")
c.stopServer()
if err := c.cleanupFunc(); err != nil {
panic(err)
}
}
func (c cliTest) Run(line string) {
redirectOutput(func() { c.runUnredirected(line) })
}
func (c cliTest) runUnredirected(line string) {
a := strings.Fields(line)
c.runWithArgsUnredirected(a)
}
// RunWithCapture runs c and returns a string containing the output of c
// and any error that may have occurred capturing the output. We do not propagate
// errors in executing c, because those will be caught when the test verifies
// the output of c.
func (c cliTest) RunWithCapture(line string) (out string, err error) {
return captureOutput(func() {
c.runUnredirected(line)
})
}
func (c cliTest) RunWithCaptureArgs(args []string) (string, error) {
return captureOutput(func() {
c.runWithArgsUnredirected(args)
})
}
// stripWhitespaces removes whitespaces before each newline character.
// We need to strip whitespace because otherwise we get test failures
// in Example_tests: some tests produce whitespace at the end of each
// line, the reference output is in Go comments here, and most text
// editor remove trailing whitespaces in source files.
func stripWhitespaces(s string) string {
start := 0
var res strings.Builder
for i := 0; i < len(s); i++ {
if s[i] != '\n' {
continue
}
end := i
for ; end > start && s[end-1] == ' '; end-- {
}
res.WriteString(s[start:end])
res.WriteByte('\n')
start = i + 1
}
end := len(s)
for ; end > start && s[end-1] == ' '; end-- {
}
res.WriteString(s[start:end])
return res.String()
}
func TestStripWhitespaces(t *testing.T) {
defer leaktest.AfterTest(t)()
testData := []struct {
in, out string
}{
{" ", ""},
{" \n", "\n"},
{"abc", "abc"},
{"abc ", "abc"},
{"abc \n", "abc\n"},
{"abc \nxyz", "abc\nxyz"},
}
for _, test := range testData {
t.Run(test.in, func(t *testing.T) {
res := stripWhitespaces(test.in)
if res != test.out {
t.Errorf("%q: got %q, expected %q", test.in, res, test.out)
}
})
}
}
// redirectOutput runs f and prints out either its output, or the
// error if one was produed. We use redirectOutput for the various
// Run functions because this ensures that trailing whitespace
// on each line is properly stripped out; otherwise Example_ tests
// don't work properly.
func redirectOutput(f func()) {
out, err := captureOutput(f)
if err != nil {
fmt.Fprintln(stderr, err)
} else {
fmt.Print(out)
}
}
// captureOutput runs f and returns a string containing the output and any
// error that may have occurred capturing the output.
func captureOutput(f func()) (out string, err error) {
// Heavily inspired by Go's testing/example.go:runExample().
// Funnel stdout into a pipe.
stdoutSave, stderrRedirSave := os.Stdout, stderr
r, w, err := os.Pipe()
if err != nil {
return "", err
}
os.Stdout = w
stderr = w
// Send all bytes from piped stdout through the output channel.
type captureResult struct {
out string
err error
}
outC := make(chan captureResult)
go func() {
var buf bytes.Buffer
_, err := io.Copy(&buf, r)
r.Close()
s := stripWhitespaces(buf.String())
outC <- captureResult{s, err}
}()
// Clean up and record output in separate function to handle panics.
defer func() {
// Close pipe and restore normal stdout.
w.Close()
os.Stdout = stdoutSave
stderr = stderrRedirSave
outResult := <-outC
out, err = outResult.out, outResult.err
if x := recover(); x != nil {
err = errors.Errorf("panic: %v", x)
}
}()
// Run the command. The output will be returned in the defer block.
f()
return
}
func (c cliTest) RunWithArgs(origArgs []string) {
redirectOutput(func() { c.runWithArgsUnredirected(origArgs) })
}
func (c cliTest) runWithArgsUnredirected(origArgs []string) {
TestingReset()
if err := func() error {
args := append([]string(nil), origArgs[:1]...)
if c.TestServer != nil {
h, p, err := net.SplitHostPort(c.ServingAddr())
if err != nil {
return err
}
if c.Cfg.Insecure {
args = append(args, "--insecure")
} else {
args = append(args, "--insecure=false")
args = append(args, fmt.Sprintf("--certs-dir=%s", c.certsDir))
}
args = append(args, fmt.Sprintf("--host=%s:%s", h, p))
}
args = append(args, origArgs[1:]...)
if !c.omitArgs {
fmt.Fprintf(os.Stderr, "%s\n", args)
fmt.Println(strings.Join(origArgs, " "))
}
return Run(args)
}(); err != nil {
fmt.Println(err)
}
}
func (c cliTest) RunWithCAArgs(origArgs []string) {
redirectOutput(func() { c.runWithCAArgsUnredirected(origArgs) })
}
func (c cliTest) runWithCAArgsUnredirected(origArgs []string) {
TestingReset()
if err := func() error {
args := append([]string(nil), origArgs[:1]...)
if c.TestServer != nil {
args = append(args, fmt.Sprintf("--ca-key=%s", filepath.Join(c.certsDir, security.EmbeddedCAKey)))
args = append(args, fmt.Sprintf("--certs-dir=%s", c.certsDir))
}
args = append(args, origArgs[1:]...)
fmt.Fprintf(os.Stderr, "%s\n", args)
fmt.Println(strings.Join(origArgs, " "))
return Run(args)
}(); err != nil {
fmt.Println(err)
}
}
func TestQuit(t *testing.T) {
defer leaktest.AfterTest(t)()
if testing.Short() {
t.Skip("short flag")
}
c := newCLITest(cliTestParams{t: t})
defer c.cleanup()
c.Run("quit")
// Wait until this async command cleanups the server.
<-c.Stopper().IsStopped()
}
func Example_logging() {
c := newCLITest(cliTestParams{})
defer c.cleanup()
c.RunWithArgs([]string{`sql`, `--logtostderr=false`, `-e`, `select 1 as "1"`})
c.RunWithArgs([]string{`sql`, `--log-backtrace-at=foo.go:1`, `-e`, `select 1 as "1"`})
c.RunWithArgs([]string{`sql`, `--log-dir=`, `-e`, `select 1 as "1"`})
c.RunWithArgs([]string{`sql`, `--logtostderr=true`, `-e`, `select 1 as "1"`})
c.RunWithArgs([]string{`sql`, `--verbosity=0`, `-e`, `select 1 as "1"`})
c.RunWithArgs([]string{`sql`, `--vmodule=foo=1`, `-e`, `select 1 as "1"`})
// Output:
// sql --logtostderr=false -e select 1 as "1"
// 1
// 1
// sql --log-backtrace-at=foo.go:1 -e select 1 as "1"
// 1
// 1
// sql --log-dir= -e select 1 as "1"
// 1
// 1
// sql --logtostderr=true -e select 1 as "1"
// 1
// 1
// sql --verbosity=0 -e select 1 as "1"
// 1
// 1
// sql --vmodule=foo=1 -e select 1 as "1"
// 1
// 1
}
func Example_zone() {
storeSpec := base.DefaultTestStoreSpec
storeSpec.Attributes = roachpb.Attributes{Attrs: []string{"ssd"}}
c := newCLITest(cliTestParams{
storeSpecs: []base.StoreSpec{storeSpec},
locality: roachpb.Locality{
Tiers: []roachpb.Tier{
{Key: "region", Value: "us-east-1"},
{Key: "zone", Value: "us-east-1a"},
},
},
})
defer c.cleanup()
c.Run("zone ls")
c.Run("zone set system --file=./testdata/zone_attrs.yaml")
c.Run("zone ls")
c.Run("zone get .liveness")
c.Run("zone get .meta")
c.Run("zone get system.nonexistent")
c.Run("zone get system.descriptor")
c.Run("zone set system.descriptor --file=./testdata/zone_attrs.yaml")
c.Run("zone set system.namespace --file=./testdata/zone_attrs.yaml")
c.Run("zone set system.nonexistent --file=./testdata/zone_attrs.yaml")
c.Run("zone set system --file=./testdata/zone_range_max_bytes.yaml")
c.Run("zone get system")
c.Run("zone rm system")
c.Run("zone ls")
c.Run("zone rm .default")
c.Run("zone set .liveness --file=./testdata/zone_range_max_bytes.yaml")
c.Run("zone set .meta --file=./testdata/zone_range_max_bytes.yaml")
c.Run("zone set .system --file=./testdata/zone_range_max_bytes.yaml")
c.Run("zone set .timeseries --file=./testdata/zone_range_max_bytes.yaml")
c.Run("zone get .system")
c.Run("zone ls")
c.Run("zone set .default --file=./testdata/zone_range_max_bytes.yaml")
c.Run("zone get system")
c.Run("zone set .default --disable-replication")
c.Run("zone get system")
c.Run("zone rm .liveness")
c.Run("zone rm .meta")
c.Run("zone rm .system")
c.Run("zone ls")
c.Run("zone rm .timeseries")
c.Run("zone ls")
c.Run("zone rm .liveness")
c.Run("zone rm .meta")
c.Run("zone rm .system")
c.Run("zone rm .timeseries")
c.Run("zone set system.jobs@primary --file=./testdata/zone_attrs.yaml")
c.Run("zone set system --file=./testdata/zone_attrs_advanced.yaml")
c.Run("zone set system --file=./testdata/zone_attrs_experimental.yaml")
c.RunWithArgs([]string{"sql", "-e", "create database t; create table t.f (x int, y int)"})
c.Run("zone set t --file=./testdata/zone_range_max_bytes.yaml")
c.Run("zone ls")
c.Run("zone set t.f --file=./testdata/zone_range_max_bytes.yaml")
c.Run("zone ls")
c.RunWithArgs([]string{"sql", "-e", "drop database t cascade"})
// List the remaining zones, but also test that --format is recognized.
c.Run("zone ls --format=html")
// Output:
// zone ls
// zone
// .default
// .liveness
// .meta
// system.jobs
// zone set system --file=./testdata/zone_attrs.yaml
// system
// "range_min_bytes: 1048576
// range_max_bytes: 67108864
// gc:
// ttlseconds: 90000
// num_replicas: 1
// constraints: [+zone=us-east-1a, +ssd]
// "
// zone ls
// zone
// .default
// .liveness
// .meta
// system
// system.jobs
// zone get .liveness
// .liveness
// "range_min_bytes: 1048576
// range_max_bytes: 67108864
// gc:
// ttlseconds: 600
// num_replicas: 1
// constraints: []
// "
// zone get .meta
// .meta
// "range_min_bytes: 1048576
// range_max_bytes: 67108864
// gc:
// ttlseconds: 3600
// num_replicas: 1
// constraints: []
// "
// zone get system.nonexistent
// pq: relation "system.public.nonexistent" does not exist
// zone get system.descriptor
// system
// "range_min_bytes: 1048576
// range_max_bytes: 67108864
// gc:
// ttlseconds: 90000
// num_replicas: 1
// constraints: [+zone=us-east-1a, +ssd]
// "
// zone set system.descriptor --file=./testdata/zone_attrs.yaml
// pq: cannot set zone configs for system config tables; try setting your config on the entire "system" database instead
// zone set system.namespace --file=./testdata/zone_attrs.yaml
// pq: cannot set zone configs for system config tables; try setting your config on the entire "system" database instead
// zone set system.nonexistent --file=./testdata/zone_attrs.yaml
// pq: relation "system.public.nonexistent" does not exist
// zone set system --file=./testdata/zone_range_max_bytes.yaml
// system
// "range_min_bytes: 1048576
// range_max_bytes: 134217728
// gc:
// ttlseconds: 90000
// num_replicas: 3
// constraints: [+zone=us-east-1a, +ssd]
// "
// zone get system
// system
// "range_min_bytes: 1048576
// range_max_bytes: 134217728
// gc:
// ttlseconds: 90000
// num_replicas: 3
// constraints: [+zone=us-east-1a, +ssd]
// "
// zone rm system
// zone ls
// zone
// .default
// .liveness
// .meta
// system.jobs
// zone rm .default
// pq: cannot remove default zone
// zone set .liveness --file=./testdata/zone_range_max_bytes.yaml
// .liveness
// "range_min_bytes: 1048576
// range_max_bytes: 134217728
// gc:
// ttlseconds: 600
// num_replicas: 3
// constraints: []
// "
// zone set .meta --file=./testdata/zone_range_max_bytes.yaml
// .meta
// "range_min_bytes: 1048576
// range_max_bytes: 134217728
// gc:
// ttlseconds: 3600
// num_replicas: 3
// constraints: []
// "
// zone set .system --file=./testdata/zone_range_max_bytes.yaml
// .system
// "range_min_bytes: 1048576
// range_max_bytes: 134217728
// gc:
// ttlseconds: 90000
// num_replicas: 3
// constraints: []
// "
// zone set .timeseries --file=./testdata/zone_range_max_bytes.yaml
// .timeseries
// "range_min_bytes: 1048576
// range_max_bytes: 134217728
// gc:
// ttlseconds: 90000
// num_replicas: 3
// constraints: []
// "
// zone get .system
// .system
// "range_min_bytes: 1048576
// range_max_bytes: 134217728
// gc:
// ttlseconds: 90000
// num_replicas: 3
// constraints: []
// "
// zone ls
// zone
// .default
// .liveness
// .meta
// .system
// .timeseries
// system.jobs
// zone set .default --file=./testdata/zone_range_max_bytes.yaml
// .default
// "range_min_bytes: 1048576
// range_max_bytes: 134217728
// gc:
// ttlseconds: 90000
// num_replicas: 3
// constraints: []
// "
// zone get system
// .default
// "range_min_bytes: 1048576
// range_max_bytes: 134217728
// gc:
// ttlseconds: 90000
// num_replicas: 3
// constraints: []
// "
// zone set .default --disable-replication
// .default
// "range_min_bytes: 1048576
// range_max_bytes: 134217728
// gc:
// ttlseconds: 90000
// num_replicas: 1
// constraints: []
// "
// zone get system
// .default
// "range_min_bytes: 1048576
// range_max_bytes: 134217728
// gc:
// ttlseconds: 90000
// num_replicas: 1
// constraints: []
// "
// zone rm .liveness
// zone rm .meta
// zone rm .system
// zone ls
// zone
// .default
// .timeseries
// system.jobs
// zone rm .timeseries
// zone ls
// zone
// .default
// system.jobs
// zone rm .liveness
// zone rm .meta
// zone rm .system
// zone rm .timeseries
// zone set system.jobs@primary --file=./testdata/zone_attrs.yaml
// pq: setting zone configs on indexes or partitions requires a CCL binary
// zone set system --file=./testdata/zone_attrs_advanced.yaml
// system
// "range_min_bytes: 1048576
// range_max_bytes: 134217728
// gc:
// ttlseconds: 90000
// num_replicas: 3
// constraints: {+region=us-east-1: 1, '+zone=us-east-1a,+ssd': 1}
// lease_preferences: [[+region=us-east-1], [+zone=us-east-1a]]
// "
// zone set system --file=./testdata/zone_attrs_experimental.yaml
// system
// "range_min_bytes: 1048576
// range_max_bytes: 134217728
// gc:
// ttlseconds: 90000
// num_replicas: 3
// constraints: {+region=us-east-1: 1, '+zone=us-east-1a,+ssd': 1}
// lease_preferences: [[+zone=us-east-1a]]
// "
// sql -e create database t; create table t.f (x int, y int)
// CREATE TABLE
// zone set t --file=./testdata/zone_range_max_bytes.yaml
// t
// "range_min_bytes: 1048576
// range_max_bytes: 134217728
// gc:
// ttlseconds: 90000
// num_replicas: 3
// constraints: []
// "
// zone ls
// zone
// .default
// system
// system.jobs
// t
// zone set t.f --file=./testdata/zone_range_max_bytes.yaml
// t.f
// "range_min_bytes: 1048576
// range_max_bytes: 134217728
// gc:
// ttlseconds: 90000
// num_replicas: 3
// constraints: []
// "
// zone ls
// zone
// .default
// system
// system.jobs
// t
// t.f
// sql -e drop database t cascade
// DROP DATABASE
// zone ls
// <table>
// <thead><tr><th>row</th><th>zone</th></tr></thead>
// <tbody>
// <tr><td>1</td><td>.default</td></tr>
// <tr><td>2</td><td>system</td></tr>
// <tr><td>3</td><td>system.jobs</td></tr>
// </tbody>
// <tfoot><tr><td colspan=2>3 rows</td></tr></tfoot></table>
}
func Example_demo() {
c := newCLITest(cliTestParams{noServer: true})
defer c.cleanup()
testData := [][]string{
{`demo`, `-e`, `show database`},
{`demo`, `-e`, `show application_name`},
{`demo`, `--format=table`, `-e`, `show database`},
{`demo`, `-e`, `select 1 as "1"`, `-e`, `select 3 as "3"`},
{`demo`, `--echo-sql`, `-e`, `select 1 as "1"`},
{`demo`, `--set=errexit=0`, `-e`, `select nonexistent`, `-e`, `select 123 as "123"`},
{`demo`, `startrek`, `-e`, `show databases`},
{`demo`, `startrek`, `-e`, `show databases`, `--format=table`},
}
for _, cmd := range testData {
c.RunWithArgs(cmd)
}
// Output:
// demo -e show database
// database
// defaultdb
// demo -e show application_name
// application_name
// $ cockroach demo
// demo --format=table -e show database
// database
// +-----------+
// defaultdb
// (1 row)
// demo -e select 1 as "1" -e select 3 as "3"
// 1
// 1
// 3
// 3
// demo --echo-sql -e select 1 as "1"
// > select 1 as "1"
// 1
// 1
// demo --set=errexit=0 -e select nonexistent -e select 123 as "123"
// pq: column "nonexistent" does not exist
// 123
// 123
// demo startrek -e show databases
// database_name
// defaultdb
// postgres
// startrek
// system
// demo startrek -e show databases --format=table
// database_name
// +---------------+
// defaultdb
// postgres
// startrek
// system
// (4 rows)
}
func Example_sql() {
c := newCLITest(cliTestParams{})
defer c.cleanup()
c.RunWithArgs([]string{`sql`, `-e`, `show application_name`})
c.RunWithArgs([]string{`sql`, `-e`, `create database t; create table t.f (x int, y int); insert into t.f values (42, 69)`})
c.RunWithArgs([]string{`sql`, `-e`, `select 3 as "3"`, `-e`, `select * from t.f`})
c.RunWithArgs([]string{`sql`, `-e`, `begin`, `-e`, `select 3 as "3"`, `-e`, `commit`})
c.RunWithArgs([]string{`sql`, `-e`, `select * from t.f`})
c.RunWithArgs([]string{`sql`, `--execute=show databases`})
c.RunWithArgs([]string{`sql`, `-e`, `select 1 as "1"; select 2 as "2"`})
c.RunWithArgs([]string{`sql`, `-e`, `select 1 as "1"; select 2 as "@" where false`})
// CREATE TABLE AS returns a SELECT tag with a row count, check this.
c.RunWithArgs([]string{`sql`, `-e`, `create table t.g1 (x int)`})
c.RunWithArgs([]string{`sql`, `-e`, `create table t.g2 as select * from generate_series(1,10)`})
// It must be possible to access pre-defined/virtual tables even if the current database
// does not exist yet.
c.RunWithArgs([]string{`sql`, `-d`, `nonexistent`, `-e`, `select count(*) from "".information_schema.tables limit 0`})
// It must be possible to create the current database after the
// connection was established.
c.RunWithArgs([]string{`sql`, `-d`, `nonexistent`, `-e`, `create database nonexistent; create table foo(x int); select * from foo`})
// COPY should return an intelligible error message.
c.RunWithArgs([]string{`sql`, `-e`, `copy t.f from stdin`})
// --echo-sql should print out the SQL statements.
c.RunWithArgs([]string{`user`, `ls`, `--echo-sql`})
// --set changes client-side variables before executing commands.
c.RunWithArgs([]string{`sql`, `--set=errexit=0`, `-e`, `select nonexistent`, `-e`, `select 123 as "123"`})
c.RunWithArgs([]string{`sql`, `--set`, `echo=true`, `-e`, `select 123 as "123"`})
c.RunWithArgs([]string{`sql`, `--set`, `unknownoption`, `-e`, `select 123 as "123"`})
// Output:
// sql -e show application_name
// application_name
// $ cockroach sql
// sql -e create database t; create table t.f (x int, y int); insert into t.f values (42, 69)
// INSERT 1
// sql -e select 3 as "3" -e select * from t.f
// 3
// 3
// x y
// 42 69
// sql -e begin -e select 3 as "3" -e commit
// BEGIN
// 3
// 3
// COMMIT
// sql -e select * from t.f
// x y
// 42 69
// sql --execute=show databases
// database_name
// defaultdb
// postgres
// system
// t
// sql -e select 1 as "1"; select 2 as "2"
// 1
// 1
// 2
// 2
// sql -e select 1 as "1"; select 2 as "@" where false
// 1
// 1
// @
// sql -e create table t.g1 (x int)
// CREATE TABLE
// sql -e create table t.g2 as select * from generate_series(1,10)
// SELECT 10
// sql -d nonexistent -e select count(*) from "".information_schema.tables limit 0
// count
// sql -d nonexistent -e create database nonexistent; create table foo(x int); select * from foo
// x
// sql -e copy t.f from stdin
// woops! COPY has confused this client! Suggestion: use 'psql' for COPY
// user ls --echo-sql
// > SHOW USERS
// user_name
// root
// sql --set=errexit=0 -e select nonexistent -e select 123 as "123"
// pq: column "nonexistent" does not exist
// 123
// 123
// sql --set echo=true -e select 123 as "123"
// > select 123 as "123"
// 123
// 123
// sql --set unknownoption -e select 123 as "123"
// invalid syntax: \set unknownoption. Try \? for help.
// invalid syntax
}
func Example_sql_format() {
c := newCLITest(cliTestParams{})
defer c.cleanup()
c.RunWithArgs([]string{"sql", "-e", "create database t; create table t.times (bare timestamp, withtz timestamptz)"})
c.RunWithArgs([]string{"sql", "-e", "insert into t.times values ('2016-01-25 10:10:10', '2016-01-25 10:10:10-05:00')"})
c.RunWithArgs([]string{"sql", "-e", "select * from t.times"})
// Output:
// sql -e create database t; create table t.times (bare timestamp, withtz timestamptz)
// CREATE TABLE
// sql -e insert into t.times values ('2016-01-25 10:10:10', '2016-01-25 10:10:10-05:00')
// INSERT 1
// sql -e select * from t.times
// bare withtz
// 2016-01-25 10:10:10+00:00 2016-01-25 15:10:10+00:00
}
func Example_sql_column_labels() {
c := newCLITest(cliTestParams{})
defer c.cleanup()
testData := []string{
`f"oo`,
`f'oo`,
`f\oo`,
`short
very very long
not much`,
`very very long
thenshort`,
`κόσμε`,
`a|b`,
`܈85`,
}
tdef := make([]string, len(testData))
var vals bytes.Buffer
for i, col := range testData {
tdef[i] = tree.NameString(col) + " int"
if i > 0 {
vals.WriteString(", ")
}
vals.WriteByte('0')
}
c.RunWithArgs([]string{"sql", "-e", "create database t; create table t.u (" + strings.Join(tdef, ", ") + ")"})
c.RunWithArgs([]string{"sql", "-e", "insert into t.u values (" + vals.String() + ")"})
c.RunWithArgs([]string{"sql", "-e", "show columns from t.u"})
c.RunWithArgs([]string{"sql", "-e", "select * from t.u"})
c.RunWithArgs([]string{"sql", "--format=table", "-e", "show columns from t.u"})
for i := tableDisplayFormat(0); i < tableDisplayLastFormat; i++ {
c.RunWithArgs([]string{"sql", "--format=" + i.String(), "-e", "select * from t.u"})
}
// Output
// sql -e create database t; create table t.u ("f""oo" int, "f'oo" int, "f\oo" int, "short
// very very long
// not much" int, "very very long
// thenshort" int, "κόσμε" int, "a|b" int, ܈85 int)
// CREATE TABLE
// sql -e insert into t.u values (0, 0, 0, 0, 0, 0, 0, 0)
// INSERT 1
// sql -e show columns from t.u
// column_name data_type is_nullable column_default generation_expression indices
// "f""oo" INT true NULL {}
// f'oo INT true NULL {}
// f\oo INT true NULL {}
// "short
// very very long
// not much" INT true NULL {}
// "very very long
// thenshort" INT true NULL {}
// κόσμε INT true NULL {}
// a|b INT true NULL {}
// ܈85 INT true NULL {}
// sql -e select * from t.u
// "f""oo" f'oo f\oo "short
// very very long
// not much" "very very long