-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
cli_test.go
2124 lines (1942 loc) · 61.1 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.
//
// 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"
"io/ioutil"
"net"
"os"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"testing"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/build"
"github.com/cockroachdb/cockroach/pkg/cli/cliflags"
"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/testutils/skip"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
// register some workloads for TestWorkload
_ "github.com/cockroachdb/cockroach/pkg/workload/examples"
"github.com/cockroachdb/errors"
"github.com/stretchr/testify/assert"
)
type cliTest struct {
*server.TestServer
certsDir string
cleanupFunc func() error
prevStderr *os.File
// 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
noNodelocal bool
}
// testTempFilePrefix is a sentinel marker to be used as the prefix of a
// test file name. It is used to extract the file name from a uniquely
// generated (temp directory) file path.
const testTempFilePrefix = "test-temp-prefix-"
func (c *cliTest) fail(err interface{}) {
if c.t != nil {
defer c.logScope.Close(c.t)
c.t.Fatal(err)
} else {
panic(err)
}
}
func createTestCerts(certsDir string) (cleanup func() error) {
// 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),
filepath.Join(security.EmbeddedCertsDir, security.EmbeddedTenantClientCACert),
}
for _, a := range assets {
_, err := securitytest.RestrictedCopy(a, certsDir, filepath.Base(a))
if err != nil {
panic(err)
}
}
return func() error {
security.SetAssetLoader(securitytest.EmbeddedAssets)
return os.RemoveAll(certsDir)
}
}
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 {
c.cleanupFunc = createTestCerts(certsDir)
baseCfg.SSLCertsDir = certsDir
}
args := base.TestServerArgs{
Insecure: params.insecure,
SSLCertsDir: c.certsDir,
StoreSpecs: params.storeSpecs,
Locality: params.locality,
ExternalIODir: filepath.Join(certsDir, "extern"),
}
if params.noNodelocal {
args.ExternalIODir = ""
}
s, err := serverutils.StartServerRaw(args)
if err != nil {
c.fail(err)
}
c.TestServer = s.(*server.TestServer)
log.Infof(context.Background(), "server started at %s", c.ServingRPCAddr())
log.Infof(context.Background(), "SQL listener at %s", c.ServingSQLAddr())
}
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.
c.prevStderr = stderr
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
sqlCtx.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.Background(), "stopping server at %s / %s",
c.ServingRPCAddr(), c.ServingSQLAddr())
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.Background())
}
}
}
// restartServer stops and restarts the test server. The ServingRPCAddr() may
// have changed after this method returns.
func (c *cliTest) restartServer(params cliTestParams) {
c.stopServer()
log.Info(context.Background(), "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.Background(), "restarted server at %s / %s",
c.ServingRPCAddr(), c.ServingSQLAddr())
}
// 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() {
defer func() {
if c.t != nil {
c.logScope.Close(c.t)
}
}()
// Restore stderr.
stderr = c.prevStderr
log.Info(context.Background(), "stopping server and cleaning up CLI test")
c.stopServer()
if err := c.cleanupFunc(); err != nil {
panic(err)
}
}
func (c cliTest) Run(line string) {
a := strings.Fields(line)
c.RunWithArgs(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.Run(line)
})
}
func (c cliTest) RunWithCaptureArgs(args []string) (string, error) {
return captureOutput(func() {
c.RunWithArgs(args)
})
}
// 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()
outC <- captureResult{buf.String(), 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 isSQLCommand(args []string) (bool, error) {
cmd, _, err := cockroachCmd.Find(args)
if err != nil {
return false, err
}
// We use --echo-sql as a marker of SQL-only commands.
if f := flagSetForCmd(cmd).Lookup(cliflags.EchoSQL.Name); f != nil {
return true, nil
}
return false, nil
}
func (c cliTest) RunWithArgs(origArgs []string) {
TestingReset()
if err := func() error {
args := append([]string(nil), origArgs[:1]...)
if c.TestServer != nil {
addr := c.ServingRPCAddr()
if isSQL, err := isSQLCommand(origArgs); err != nil {
return err
} else if isSQL {
addr = c.ServingSQLAddr()
}
h, p, err := net.SplitHostPort(addr)
if err != nil {
return err
}
args = append(args, fmt.Sprintf("--host=%s", net.JoinHostPort(h, p)))
if c.Cfg.Insecure {
args = append(args, "--insecure=true")
} else {
args = append(args, "--insecure=false")
args = append(args, fmt.Sprintf("--certs-dir=%s", c.certsDir))
}
}
args = append(args, origArgs[1:]...)
// `nodelocal upload` CLI tests create test files in unique temp
// directories. Given that the expected output for such tests is defined as
// a static comment, it is not possible to match against the full file path.
// So, we trim the file path upto the sentinel prefix marker, and use only
// the file name for comparing against the expected output.
if len(origArgs) >= 3 && strings.Contains(origArgs[2], testTempFilePrefix) {
splitFilePath := strings.Split(origArgs[2], testTempFilePrefix)
origArgs[2] = splitFilePath[1]
}
if !c.omitArgs {
fmt.Fprintf(os.Stderr, "%s\n", args)
fmt.Println(strings.Join(origArgs, " "))
}
return Run(args)
}(); err != nil {
cliOutputError(os.Stdout, err, true /*showSeverity*/, false /*verbose*/)
}
}
func (c cliTest) RunWithCAArgs(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)()
skip.UnderShort(t)
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`, `--logtostderr=true`, `-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 --logtostderr=true -e select 1 as "1"
// 1
// 1
// sql --vmodule=foo=1 -e select 1 as "1"
// 1
// 1
}
func Example_demo() {
c := newCLITest(cliTestParams{noServer: true})
defer c.cleanup()
testData := [][]string{
{`demo`, `-e`, `show database`},
{`demo`, `-e`, `show database`, `--empty`},
{`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`},
// Test that if we start with --insecure we cannot perform
// commands that require a secure cluster.
{`demo`, `-e`, `CREATE USER test WITH PASSWORD 'testpass'`},
{`demo`, `--insecure`, `-e`, `CREATE USER test WITH PASSWORD 'testpass'`},
{`demo`, `--geo-partitioned-replicas`, `--disable-demo-license`},
}
setCLIDefaultsForTests()
// We must reset the security asset loader here, otherwise the dummy
// asset loader that is set by default in tests will not be able to
// find the certs that demo sets up.
security.ResetAssetLoader()
for _, cmd := range testData {
// `demo` sets up a server and log file redirection, which asserts
// that the logging subsystem has not been initialized yet. Fake
// this to be true.
log.TestingResetActive()
c.RunWithArgs(cmd)
}
// Output:
// demo -e show database
// database
// movr
// demo -e show database --empty
// database
// defaultdb
// demo -e show application_name
// application_name
// $ cockroach demo
// demo --format=table -e show database
// database
// ------------
// movr
// (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"
// ERROR: column "nonexistent" does not exist
// SQLSTATE: 42703
// 123
// 123
// demo startrek -e show databases
// database_name owner
// defaultdb root
// postgres root
// startrek demo
// system node
// demo startrek -e show databases --format=table
// database_name | owner
// ----------------+--------
// defaultdb | root
// postgres | root
// startrek | demo
// system | node
// (4 rows)
// demo -e CREATE USER test WITH PASSWORD 'testpass'
// CREATE ROLE
// demo --insecure -e CREATE USER test WITH PASSWORD 'testpass'
// ERROR: setting or updating a password is not supported in insecure mode
// SQLSTATE: 28P01
// demo --geo-partitioned-replicas --disable-demo-license
// ERROR: enterprise features are needed for this demo (--geo-partitioned-replicas)
}
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`})
// --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"`})
// Check that partial results + error get reported together.
c.RunWithArgs([]string{`sql`, `-e`, `select 1/(@1-2) from generate_series(1,3)`})
// 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 owner
// defaultdb root
// postgres root
// system node
// t root
// 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)
// CREATE TABLE AS
// 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
// ERROR: woops! COPY has confused this client! Suggestion: use 'psql' for COPY
// sql --set=errexit=0 -e select nonexistent -e select 123 as "123"
// ERROR: column "nonexistent" does not exist
// SQLSTATE: 42703
// 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.
// ERROR: invalid syntax
// sql -e select 1/(@1-2) from generate_series(1,3)
// ?column?
// -1
// (error encountered after some results were delivered)
// ERROR: division by zero
// SQLSTATE: 22012
}
func Example_sql_watch() {
c := newCLITest(cliTestParams{})
defer c.cleanup()
c.RunWithArgs([]string{`sql`, `-e`, `create table d(x int); insert into d values(3)`})
c.RunWithArgs([]string{`sql`, `--watch`, `.1s`, `-e`, `update d set x=x-1 returning 1/x as dec`})
// Output:
// sql -e create table d(x int); insert into d values(3)
// INSERT 1
// sql --watch .1s -e update d set x=x-1 returning 1/x as dec
// dec
// 0.5
// dec
// 1
// ERROR: division by zero
// SQLSTATE: 22012
}
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:00 2016-01-25 15:10:10+00: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
// thenshort" κόσμε a|b ܈85
// 0 0 0 0 0 0 0 0
// sql --format=table -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 | INT | true | NULL | | {}
// very very long | | | | |
// not much | | | | |
// very very long | INT | true | NULL | | {}
// thenshort | | | | |
// κόσμε | INT | true | NULL | | {}
// a|b | INT | true | NULL | | {}
// ܈85 | INT | true | NULL | | {}
// (8 rows)
// sql --format=tsv -e select * from t.u
// "f""oo" f'oo f\oo "short
// very very long
// not much" "very very long
// thenshort" κόσμε a|b ܈85
// 0 0 0 0 0 0 0 0
// sql --format=csv -e select * from t.u
// "f""oo",f'oo,f\oo,"short
// very very long
// not much","very very long
// thenshort",κόσμε,a|b,܈85
// 0,0,0,0,0,0,0,0
// sql --format=table -e select * from t.u
// f"oo | f'oo | f\oo | short | very very long | κόσμε | a|b | ܈85
// | | | very very long | thenshort | | |
// | | | not much | | | |
// +------+------+------+----------------+----------------+-------+-----+-----+
// 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0
// (1 row)
// sql --format=records -e select * from t.u
// -[ RECORD 1 ]
// f"oo | 0
// f'oo | 0
// f\oo | 0
// short +| 0
// very very long+|
// not much |
// very very long+| 0
// thenshort |
// κόσμε | 0
// a|b | 0
// ܈85 | 0
// sql --format=sql -e select * from t.u
// CREATE TABLE results (
// "f""oo" STRING,
// "f'oo" STRING,
// "f\oo" STRING,
// "short
// very very long
// not much" STRING,
// "very very long
// thenshort" STRING,
// "κόσμε" STRING,
// "a|b" STRING,
// ܈85 STRING
// );
//
// INSERT INTO results VALUES ('0', '0', '0', '0', '0', '0', '0', '0');
// -- 1 row
// sql --format=html -e select * from t.u
// <table>
// <thead><tr><th>row</th><th>f"oo</th><th>f'oo</th><th>f\oo</th><th>short<br/>very very long<br/>not much</th><th>very very long<br/>thenshort</th><th>κόσμε</th><th>a|b</th><th>܈85</th></tr></thead>
// <tbody>
// <tr><td>1</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td></tr>
// </tbody>
// <tfoot><tr><td colspan=9>1 row</td></tr></tfoot></table>
// sql --format=raw -e select * from t.u
// # 8 columns
// # row 1
// ## 1
// 0
// ## 1
// 0
// ## 1
// 0
// ## 1
// 0
// ## 1
// 0
// ## 1
// 0
// ## 1
// 0
// ## 1
// 0
// # 1 row
}
func Example_sql_empty_table() {
c := newCLITest(cliTestParams{})
defer c.cleanup()
c.RunWithArgs([]string{"sql", "-e", "create database t;" +
"create table t.norows(x int);" +
"create table t.nocolsnorows();" +
"create table t.nocols(); insert into t.nocols(rowid) values (1),(2),(3);"})
for _, table := range []string{"norows", "nocols", "nocolsnorows"} {
for format := tableDisplayFormat(0); format < tableDisplayLastFormat; format++ {
c.RunWithArgs([]string{"sql", "--format=" + format.String(), "-e", "select * from t." + table})
}
}
// Output:
// sql -e create database t;create table t.norows(x int);create table t.nocolsnorows();create table t.nocols(); insert into t.nocols(rowid) values (1),(2),(3);
// INSERT 3
// sql --format=tsv -e select * from t.norows
// x
// sql --format=csv -e select * from t.norows
// x
// sql --format=table -e select * from t.norows
// x
// -----
// (0 rows)
// sql --format=records -e select * from t.norows
// sql --format=sql -e select * from t.norows
// CREATE TABLE results (
// x STRING
// );
//
// -- 0 rows
// sql --format=html -e select * from t.norows
// <table>
// <thead><tr><th>row</th><th>x</th></tr></thead>
// </tbody>
// <tfoot><tr><td colspan=2>0 rows</td></tr></tfoot></table>
// sql --format=raw -e select * from t.norows
// # 1 column
// # 0 rows
// sql --format=tsv -e select * from t.nocols
// # no columns
// # empty
// # empty
// # empty
// sql --format=csv -e select * from t.nocols
// # no columns
// # empty
// # empty
// # empty
// sql --format=table -e select * from t.nocols
// --
// (3 rows)
// sql --format=records -e select * from t.nocols
// (3 rows)
// sql --format=sql -e select * from t.nocols
// CREATE TABLE results (
// );
//
// INSERT INTO results(rowid) VALUES (DEFAULT);
// INSERT INTO results(rowid) VALUES (DEFAULT);
// INSERT INTO results(rowid) VALUES (DEFAULT);
// -- 3 rows
// sql --format=html -e select * from t.nocols
// <table>
// <thead><tr><th>row</th></tr></thead>
// <tbody>
// <tr><td>1</td></tr>
// <tr><td>2</td></tr>
// <tr><td>3</td></tr>
// </tbody>
// <tfoot><tr><td colspan=1>3 rows</td></tr></tfoot></table>
// sql --format=raw -e select * from t.nocols
// # 0 columns
// # row 1
// # row 2
// # row 3
// # 3 rows
// sql --format=tsv -e select * from t.nocolsnorows
// # no columns
// sql --format=csv -e select * from t.nocolsnorows
// # no columns
// sql --format=table -e select * from t.nocolsnorows
// --
// (0 rows)
// sql --format=records -e select * from t.nocolsnorows
// (0 rows)
// sql --format=sql -e select * from t.nocolsnorows
// CREATE TABLE results (
// );
//
// -- 0 rows
// sql --format=html -e select * from t.nocolsnorows
// <table>
// <thead><tr><th>row</th></tr></thead>
// </tbody>
// <tfoot><tr><td colspan=1>0 rows</td></tr></tfoot></table>
// sql --format=raw -e select * from t.nocolsnorows
// # 0 columns
// # 0 rows
}
func Example_csv_tsv_quoting() {
c := newCLITest(cliTestParams{})
defer c.cleanup()
testData := []string{
`ab`,
`a b`,
`a
bc
def`,
`a, b`,
`"a", "b"`,
`'a', 'b'`,
`a\,b`,
`a b`,
}
for _, sqlStr := range testData {
escaped := lex.EscapeSQLString(sqlStr)
sql := "select " + escaped + " as s, " + escaped + " as t"
c.RunWithArgs([]string{"sql", "--format=csv", "-e", sql})
c.RunWithArgs([]string{"sql", "--format=tsv", "-e", sql})
}
for _, identStr := range testData {
escaped1 := tree.NameString(identStr + "1")
escaped2 := tree.NameString(identStr + "2")
sql := "select 1 as " + escaped1 + ", 2 as " + escaped2
c.RunWithArgs([]string{"sql", "--format=csv", "-e", sql})
c.RunWithArgs([]string{"sql", "--format=tsv", "-e", sql})
}
// Output:
// sql --format=csv -e select 'ab' as s, 'ab' as t
// s,t
// ab,ab
// sql --format=tsv -e select 'ab' as s, 'ab' as t
// s t
// ab ab
// sql --format=csv -e select 'a b' as s, 'a b' as t
// s,t
// a b,a b
// sql --format=tsv -e select 'a b' as s, 'a b' as t
// s t
// a b a b
// sql --format=csv -e select e'a\nbc\ndef' as s, e'a\nbc\ndef' as t
// s,t
// "a
// bc
// def","a
// bc
// def"
// sql --format=tsv -e select e'a\nbc\ndef' as s, e'a\nbc\ndef' as t
// s t
// "a
// bc
// def" "a
// bc
// def"
// sql --format=csv -e select 'a, b' as s, 'a, b' as t
// s,t
// "a, b","a, b"
// sql --format=tsv -e select 'a, b' as s, 'a, b' as t
// s t
// a, b a, b
// sql --format=csv -e select '"a", "b"' as s, '"a", "b"' as t
// s,t
// """a"", ""b""","""a"", ""b"""
// sql --format=tsv -e select '"a", "b"' as s, '"a", "b"' as t
// s t
// """a"", ""b""" """a"", ""b"""
// sql --format=csv -e select e'\'a\', \'b\'' as s, e'\'a\', \'b\'' as t
// s,t
// "'a', 'b'","'a', 'b'"
// sql --format=tsv -e select e'\'a\', \'b\'' as s, e'\'a\', \'b\'' as t
// s t
// 'a', 'b' 'a', 'b'
// sql --format=csv -e select e'a\\,b' as s, e'a\\,b' as t
// s,t
// "a\,b","a\,b"
// sql --format=tsv -e select e'a\\,b' as s, e'a\\,b' as t
// s t
// a\,b a\,b
// sql --format=csv -e select e'a\tb' as s, e'a\tb' as t
// s,t
// a b,a b
// sql --format=tsv -e select e'a\tb' as s, e'a\tb' as t
// s t
// "a b" "a b"
// sql --format=csv -e select 1 as ab1, 2 as ab2
// ab1,ab2
// 1,2
// sql --format=tsv -e select 1 as ab1, 2 as ab2
// ab1 ab2
// 1 2
// sql --format=csv -e select 1 as "a b1", 2 as "a b2"
// a b1,a b2
// 1,2
// sql --format=tsv -e select 1 as "a b1", 2 as "a b2"
// a b1 a b2
// 1 2
// sql --format=csv -e select 1 as "a
// bc
// def1", 2 as "a
// bc
// def2"
// "a
// bc
// def1","a