/
SqlLineArgsTest.java
2554 lines (2353 loc) · 87 KB
/
SqlLineArgsTest.java
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
/*
// Licensed to Julian Hyde under one or more contributor license
// agreements. See the NOTICE file distributed with this work for
// additional information regarding copyright ownership.
//
// Julian Hyde licenses this file to you under the Modified BSD License
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at:
//
// http://opensource.org/licenses/BSD-3-Clause
*/
package sqlline;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;
import org.h2.util.StringUtils;
import org.hamcrest.BaseMatcher;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hsqldb.jdbc.JDBCDatabaseMetaData;
import org.hsqldb.jdbc.JDBCResultSet;
import org.hsqldb.jdbc.JDBCResultSetMetaData;
import org.jline.builtins.Commands;
import org.jline.terminal.Terminal;
import org.junit.jupiter.api.Test;
import mockit.Expectations;
import mockit.Mock;
import mockit.MockUp;
import mockit.Mocked;
import mockit.internal.reflection.FieldReflection;
import net.hydromatic.scott.data.hsqldb.ScottHsqldb;
import sqlline.extensions.CustomApplication;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.*;
/**
* Executes tests of the command-line arguments to SqlLine.
*/
public class SqlLineArgsTest {
private static final ConnectionSpec CONNECTION_SPEC = ConnectionSpec.HSQLDB;
private ConnectionSpec connectionSpec;
public SqlLineArgsTest() {
connectionSpec = CONNECTION_SPEC;
}
static SqlLine.Status begin(SqlLine sqlLine, OutputStream os,
boolean saveHistory, String... args) {
try {
PrintStream beelineOutputStream = getPrintStream(os);
sqlLine.setOutputStream(beelineOutputStream);
sqlLine.setErrorStream(beelineOutputStream);
final InputStream is = new ByteArrayInputStream(new byte[0]);
return sqlLine.begin(args, is, saveHistory);
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
}
/**
* Execute a script with "beeline -f".
*
* @return The stderr and stdout from running the script
* @param args Script arguments
*/
private static Pair run(String... args) {
try {
SqlLine beeLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
SqlLine.Status status = begin(beeLine, os, false, args);
return new Pair(status, os.toString("UTF8"));
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
}
private Pair runScript(File scriptFile, boolean flag, String outputFileName) {
return runScript(connectionSpec, scriptFile, flag, outputFileName);
}
private static Pair runScript(ConnectionSpec connectionSpec, File scriptFile,
boolean flag, String outputFileName) {
List<String> args = new ArrayList<>();
Collections.addAll(args,
"-d", connectionSpec.driver,
"-u", connectionSpec.url,
"-n", connectionSpec.username,
"-p", connectionSpec.password);
if (flag) {
args.add("-f");
args.add(scriptFile.getAbsolutePath());
} else {
args.add("--run=" + scriptFile.getAbsolutePath());
}
if (outputFileName != null) {
args.add("-log");
args.add(outputFileName);
}
return run(args.toArray(new String[0]));
}
/**
* Attempts to execute a simple script file with the -f option to SqlLine.
* Tests for presence of an expected pattern in the output (stdout or stderr).
*
* @param scriptText Script text
* @param flag Command flag (--run or -f)
* @param statusMatcher Checks whether status is as expected
* @param outputMatcher Checks whether output is as expected
*/
private void checkScriptFile(String scriptText, boolean flag,
Matcher<SqlLine.Status> statusMatcher,
Matcher<String> outputMatcher) {
try {
// Put the script content in a temp file
File scriptFile = createTempFile("foo", "temp");
PrintStream os =
new PrintStream(
new FileOutputStream(scriptFile),
false,
StandardCharsets.UTF_8.name());
os.print(scriptText);
os.close();
Pair pair = runScript(scriptFile, flag, null);
// Check output before status. It gives a better clue what went wrong.
assertThat(toLinux(pair.output), outputMatcher);
assertThat(pair.status, statusMatcher);
final boolean delete = scriptFile.delete();
assertThat(delete, is(true));
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
}
/** Windows line separators in a string into Linux line separators;
* a Linux string is unchanged. */
private static String toLinux(String s) {
return s.replaceAll("\r\n", "\n");
}
private File createTempFile(String prefix, String suffix) {
return createTempFile(prefix, suffix, null);
}
private File createTempFile(String prefix, String suffix, Path directory) {
try {
final File file = directory == null
? Files.createTempFile(prefix, suffix).toFile()
: Files.createTempFile(directory, prefix, suffix).toFile();
file.deleteOnExit();
return file;
} catch (IOException e) {
// fail
throw new RuntimeException(e);
}
}
@Test
public void testMultilineScriptWithComments() {
final String script1Text =
"!set incremental true\n"
+ "-- a comment \n values\n--comment\n (\n1\n, ' ab'\n--comment\n)\n;\n";
checkScriptFile(script1Text, true,
equalTo(SqlLine.Status.OK),
containsString("+-------------+-----+\n"
+ "| C1 | C2 |\n"
+ "+-------------+-----+\n"
+ "| 1 | ab |\n"
+ "+-------------+-----+"));
final String script2Text =
"!set incremental true\n"
+ "--comment \n --comment2 \nvalues (';\n' /* comment */, '\"'"
+ "/*multiline;\n ;\n comment*/)\n -- ; \n; -- comment";
checkScriptFile(script2Text, true,
equalTo(SqlLine.Status.OK),
containsString("+-----+----+\n"
+ "| C1 | C2 |\n"
+ "+-----+----+\n"
+ "| ; \n"
+ " | \" |\n"
+ "+-----+----+"));
}
/**
* Attempt to execute a simple script file with the -f option to SqlLine.
* Test for presence of an expected pattern
* in the output (stdout or stderr), fail if not found.
*/
@Test
public void testPositiveScriptFile() {
checkScriptFile("call 100 + 23;\n",
true,
equalTo(SqlLine.Status.OK),
containsString(" 123 "));
}
/**
* As above, but using '-run' rather than '-f'.
*/
@Test
public void testPositiveScriptFileUsingRun() {
checkScriptFile("call 100 + 23;\n",
false,
equalTo(SqlLine.Status.OK),
containsString(" 123 "));
}
/**
* Test case for
* <a href="https://github.com/julianhyde/sqlline/issues/42">[SQLLINE-42],
* Script fails if first line is a comment</a>.
*/
@Test
public void testScriptFileStartsWithComment() {
final String scriptText = "-- a comment\n"
+ "call 100 + 23;\n";
checkScriptFile(scriptText, true,
equalTo(SqlLine.Status.OK),
containsString(" 123 "));
}
@Test
public void testScriptFileStartsWithEmptyLine() {
final String scriptText = "\n"
+ "call 100 + 23;\n";
checkScriptFile(scriptText, true,
equalTo(SqlLine.Status.OK),
containsString(" 123 "));
}
@Test
public void testScriptFileContainsComment() {
final String scriptText = "values 10 + 23;\n"
+ "-- a comment\n"
+ "values 100 + 23";
checkScriptFile(scriptText, true,
equalTo(SqlLine.Status.OK),
allOf(containsString(" 33 "), containsString(" 123 ")));
}
@Test
public void testMultilineScriptFileWithComments() {
final String scriptText = "--comment\n\n"
+ "values \n10 \n+ \n23;\n\n\n"
+ "-- a comment\n"
+ "\n\nvalues "
+ "--comment inside\n\n"
+ "100 --comment inside\n\n"
+ "+ \n\n23\n\n\n;\n\n\n\n";
checkScriptFile(scriptText, true,
equalTo(SqlLine.Status.OK),
allOf(containsString(" 33 "), containsString(" 123 ")));
}
@Test
public void testMultilineScriptFileWithMultilineQuotedStrings() {
final String scriptText = "--comment\n\n"
+ "values '\nmultiline;\n;\n; string\n'"
+ ";\n\n\n"
+ "values '\nmultiline2;\n;\n; string2\n'"
+ ";\n\n\n";
checkScriptFile(scriptText, true,
equalTo(SqlLine.Status.OK),
allOf(containsString("multiline2;"), containsString("; string2")));
}
@Test
public void testScriptWithMultilineStatementsInARow() {
final String scriptText = "!set incremental false\n"
+ "--comment\n\n"
+ "values 1;values 2;";
checkScriptFile(scriptText, true,
equalTo(SqlLine.Status.OK),
allOf(
containsString("+----+\n"
+ "| C1 |\n"
+ "+----+\n"
+ "| 1 |\n"
+ "+----+"),
containsString("+----+\n"
+ "| C1 |\n"
+ "+----+\n"
+ "| 2 |\n"
+ "+----+")));
}
@Test
public void testScriptWithMultilineStatementsAndCommentsInARow() {
final String scriptText = "!set incremental false\n"
+ "--comment;;\n\n"
+ "select * from (values ';') t (\";\");/*;select 1;*/values 2;";
checkScriptFile(scriptText, true,
equalTo(SqlLine.Status.OK),
allOf(
containsString("+---+\n"
+ "| ; |\n"
+ "+---+\n"
+ "| ; |\n"
+ "+---+"),
containsString("+----+\n"
+ "| C1 |\n"
+ "+----+\n"
+ "| 2 |\n"
+ "+----+")));
}
/**
* Tests sql with H2 specific one-line comment '//'
*/
@Test
public void testMultilineScriptWithH2Comments() {
final SqlLine sqlLine = new SqlLine();
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
final File tmpHistoryFile = createTempFile("queryToExecute", "temp");
try (BufferedWriter bw =
new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(tmpHistoryFile),
StandardCharsets.UTF_8))) {
final String script = "\n"
+ "\n"
+ "!set incremental true\n"
+ "\n"
+ "\n"
+ "select * from information_schema.tables// ';\n"
+ "// \";"
+ ";\n"
+ "\n"
+ "\n";
bw.write(script);
bw.flush();
}
SqlLine.Status status =
begin(sqlLine, os, false,
"-u", ConnectionSpec.H2.url,
"-n", ConnectionSpec.H2.username,
"--run=" + tmpHistoryFile.getAbsolutePath());
assertThat(status, equalTo(SqlLine.Status.OK));
String output = os.toString("UTF8");
final String expected = "| TABLE_CATALOG | TABLE_SCHEMA |"
+ " TABLE_NAME | TABLE_TYPE | STORAGE_TYPE | SQL |";
assertThat(output, containsString(expected));
sqlLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(sqlLine.isExit());
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
}
/** Test case for
* <a href="https://github.com/julianhyde/sqlline/issues/72">[SQLLINE-72]
* Allow quoted file names (including spaces) in <code>!record</code>,
* <code>!run</code> and <code>!script</code> commands</a>. */
@Test
public void testScriptFilenameWithSpace() {
final String scriptText = "values 10 + 23;\n"
+ "-- a comment\n"
+ "values 100 + 23;\n";
File scriptFile = createTempFile("Script with Spaces", ".sql");
try (PrintStream os = getPrintStream(new FileOutputStream(scriptFile))) {
os.print(scriptText);
Pair pair = runScript(scriptFile, true, null);
assertThat(pair.status, equalTo(SqlLine.Status.OK));
assertThat(pair.output,
allOf(containsString(" 33 "), containsString(" 123 ")));
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
}
@Test
public void testScriptWithOutput() {
final String scriptText = "!set maxcolumnwidth 20\n"
+ "!set incremental true\n"
+ "values 100 + 123;\n"
+ "-- a comment\n"
+ "values 100 + 253;\n";
File scriptFile = createTempFile("Script file name", ".sql");
try (PrintStream os = getPrintStream(new FileOutputStream(scriptFile))) {
os.print(scriptText);
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
File outputFile = createTempFile("testScriptWithOutput", ".out");
runScript(scriptFile, true, outputFile.getAbsolutePath());
assertFileContains(outputFile,
allOf(containsString("| 223 |"),
containsString("| 353 |")));
final boolean delete = outputFile.delete();
assertThat(delete, is(true));
}
/**
* Values that contain null.
*/
@Test
public void testNull() {
final String script = "!set incremental true\n"
+ "values (1, cast(null as integer), cast(null as varchar(3)));\n";
checkScriptFile(script, false,
equalTo(SqlLine.Status.OK),
containsString(
"+-------------+-------------+-----+\n"
+ "| C1 | C2 | C3 |\n"
+ "+-------------+-------------+-----+\n"
+ "| 1 | null | |\n"
+ "+-------------+-------------+-----+\n"));
}
@Test
public void testScan() {
final String expectedLine0 = "Compliant Version Driver Class";
final String expectedLine1 = "yes 2.4 org.hsqldb.jdbc.JDBCDriver";
checkScriptFile("!scan\n", false,
equalTo(SqlLine.Status.OK),
allOf(containsString(expectedLine0), containsString(expectedLine1)));
}
/**
* Table output without header.
*/
@Test
public void testTableOutputNullWithoutHeader() {
final String script = "!set showHeader false\n"
+ "!set incremental true\n"
+ "values (1, cast(null as integer), cast(null as varchar(3)));\n";
checkScriptFile(script, false,
equalTo(SqlLine.Status.OK),
containsString("| 1 | null | |\n"));
}
/**
* Csv output without header.
*/
@Test
public void testCsvNullWithoutHeader() {
final String script = "!set showHeader false\n"
+ "!set outputformat csv\n"
+ "values (1, cast(null as integer), cast(null as varchar(3)));\n";
checkScriptFile(script, false,
equalTo(SqlLine.Status.OK),
containsString("'1','null',''\n"));
}
/**
* Tests the "close" command,
* <a href="https://issues.apache.org/jira/browse/HIVE-5768">[HIVE-5768]
* Beeline connection cannot be closed with '!close' command</a> and
* <a href="https://github.com/julianhyde/sqlline/issues/139">[SQLLINE-139]
* Look for the exact match if there are multiple matches</a>.
*/
@Test
public void testClose() {
final String expected = "!close\n"
+ "Closing: org.hsqldb.jdbc.JDBCConnection";
checkScriptFile("!close\n", false, equalTo(SqlLine.Status.OK),
containsString(expected));
}
/**
* Test case for
* <a href="https://github.com/julianhyde/sqlline/issues/32">[SQLLINE-32]
* !help set' should print documentation for all variables</a>.
*/
@Test
public void testHelpSet() {
final String expected = "1/1 !help set\n"
+ "!set List / set a sqlline variable\n"
+ "\n"
+ "Variables:\n"
+ "\n"
+ "Variable Value Description\n"
+ "=============== ========== "
+ "==================================================\n"
+ "autoCommit true/false "
+ "Enable/disable automatic transaction commit\n"
+ "autoSave true/false Automatically save preferences\n";
checkScriptFile("!help set\n", false, equalTo(SqlLine.Status.OK),
containsString(expected));
// Make sure that each variable (autoCommit, autoSave, color, etc.) has a
// line in the output of '!help set'
final SqlLine sqlLine = new SqlLine();
String help = sqlLine.loc("help-set")
+ sqlLine.loc("variables");
final TreeSet<String> propertyNamesMixed =
Arrays.stream(BuiltInProperty.values())
.map(BuiltInProperty::propertyName)
.collect(Collectors.toCollection(TreeSet::new));
for (String p : propertyNamesMixed) {
assertThat(help, containsString("\n" + p + " "));
}
assertThat(propertyNamesMixed.contains("autoCommit"),
is(true));
assertThat(propertyNamesMixed.contains("autocommit"),
is(false));
assertThat(propertyNamesMixed.contains("trimScripts"),
is(true));
while (help.length() > 0) {
int i = help.indexOf("\n", 1);
if (i < 0) {
break;
}
if (i > 78) {
fail("line exceeds 78 chars: " + i + ": " + help.substring(0, i));
}
help = help.substring(i);
}
}
/**
* Test case for
* <a href="https://github.com/julianhyde/sqlline/issues/39">[SQLLINE-39]
* 'help set' should not break long lines</a>.
*
* <p>But it should break 'help all', which consists of a single long line.
*/
@Test
public void testHelpAll() {
// Note that "connections" has been broken onto a new line.
final String expected = "1/1 !help all\n"
+ "!all Execute the specified SQL against all the current\n"
+ " connections\n"
+ "Closing: org.hsqldb.jdbc.JDBCConnection\n"
+ "sqlline version ???\n";
checkScriptFile("!help all\n", false, equalTo(SqlLine.Status.OK),
is(expected));
}
/**
* Tests "!go <non-existent connection indexes>".
*/
@Test
public void testGoFailing() {
final String[] connectionIndexes = {"321", "invalid"};
for (String connectionIndex : connectionIndexes) {
final String script = "!go " + connectionIndex + "\n";
final String expected = "Invalid connection: " + connectionIndex;
checkScriptFile(script, false,
// Status.OTHER as checking of fail cases
equalTo(SqlLine.Status.OTHER), containsString(expected));
}
}
/**
* Tests "!help go". "go" and "#" are synonyms.
*/
@Test
public void testHelpGo() {
for (String c : new String[] {"go", "#"}) {
final String expected = "1/1 !help " + c + "\n"
+ "!go Select the current connection\n"
+ "Closing: org.hsqldb.jdbc.JDBCConnection\n"
+ "sqlline version ???\n";
checkScriptFile("!help " + c + "\n", false, equalTo(SqlLine.Status.OK),
is(expected));
}
}
/**
* Test case for
* <a href="https://github.com/julianhyde/sqlline/issues/121">!?, !#
* and other one-symbol length commands stopped working</a>
*
* <p>'!?' should work in the same way as '!help'.
*/
@Test
public void testHelpAsQuestionMark() {
final String script = "!?\n";
final String expected =
"!autocommit Set autocommit mode on or off";
checkScriptFile(script, false,
equalTo(SqlLine.Status.OK),
allOf(not(containsString("Unknown command: ?")),
containsString(expected)));
}
/**
* Test case for
* <a href="https://github.com/julianhyde/sqlline/issues/49">[SQLLINE-49]
* !manual command fails</a>.
*/
@Test
public void testManual() {
final String expectedLine = "sqlline version";
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
new MockUp<Commands>() {
@Mock
void less(Terminal terminal, InputStream in, PrintStream out,
PrintStream err, Path currentDir, String[] argv) {
}
};
SqlLine beeLine = new SqlLine();
SqlLine.Status status =
begin(beeLine, baos, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
beeLine.runCommands(new DispatchCallback(), "!manual");
String output = baos.toString("UTF8");
assertThat(output, containsString(expectedLine));
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
}
/** Test case for
* <a href="https://github.com/julianhyde/sqlline/issues/38">[SQLLINE-38]
* Expand ~ to user's home directory</a>. */
@Test
public void testRunFromHome() {
try {
Path tmpDir =
Files.createTempDirectory(
Paths.get(System.getProperty("user.home")),
"tmpdir" + System.nanoTime());
tmpDir.toFile().deleteOnExit();
File tmpFile = createTempFile("test", ".sql", tmpDir);
try (Writer fw = new OutputStreamWriter(
new FileOutputStream(tmpFile), StandardCharsets.UTF_8)) {
fw.write("!set outputformat csv\n");
fw.write("values (1, 2, 3, 4, 5);");
fw.flush();
checkScriptFile("!run ~" + File.separatorChar
+ tmpDir.getFileName()
+ File.separatorChar + tmpFile.getName().toString(),
false,
equalTo(SqlLine.Status.OK),
allOf(containsString("!set outputformat csv"),
containsString("values (1, 2, 3, 4, 5);")));
}
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
}
/**
* Test case for
* <a href="https://github.com/julianhyde/sqlline/issues/26">[SQLLINE-26]
* Flush output for each command when using !record command</a>.
*/
@Test
public void testRecord() {
File file = createTempFile("sqlline", ".log");
final String script = "!set incremental true\n"
+ "values 1;\n"
+ "!record " + file.getAbsolutePath() + "\n"
+ "!set outputformat csv\n"
+ "values 2;\n"
+ "!record\n"
+ "!set outputformat csv\n"
+ "values 3;\n";
checkScriptFile(script, false,
equalTo(SqlLine.Status.OK),
RegexMatcher.of("(?s)1/8 !set incremental true\n"
+ "2/8 values 1;\n"
+ "\\+-------------\\+\n"
+ "\\| C1 \\|\n"
+ "\\+-------------\\+\n"
+ "\\| 1 \\|\n"
+ "\\+-------------\\+\n"
+ "1 row selected \\([0-9.,]+ seconds\\)\n"
+ "3/8 !record .*.log\n"
+ "Saving all output to \".*.log\". Enter \"record\" with no arguments to stop it.\n"
+ "4/8 !set outputformat csv\n"
+ "5/8 values 2;\n"
+ "'C1'\n"
+ "'2'\n"
+ "1 row selected \\([0-9.,]+ seconds\\)\n"
+ "6/8 !record\n"
+ "Recording stopped.\n"
+ "7/8 !set outputformat csv\n"
+ "8/8 values 3;\n"
+ "'C1'\n"
+ "'3'\n"
+ "1 row selected \\([0-9.,]+ seconds\\)\n.*"));
// Now check that the right stuff got into the file.
assertFileContains(file,
RegexMatcher.of("Saving all output to \".*.log\". "
+ "Enter \"record\" with no arguments to stop it.\n"
+ "4/8 !set outputformat csv\n"
+ "5/8 values 2;\n"
+ "'C1'\n"
+ "'2'\n"
+ "1 row selected \\([0-9.,]+ seconds\\)\n"
+ "6/8 !record\n"));
}
/** Test case for
* <a href="https://github.com/julianhyde/sqlline/issues/62">[SQLLINE-62]
* Expand ~ to user's home directory</a>. */
@Test
public void testRecordHome() {
File home = new File(System.getProperty("user.home"));
File file;
for (int i = 0;; i++) {
file = new File(home, "sqlline" + i + ".log");
if (!file.exists()) {
break;
}
}
file.deleteOnExit();
final String s = "Saving all output to \".*.log\". "
+ "Enter \"record\" with no arguments to stop it.\n"
+ "2/4 !set outputformat csv\n"
+ "3/4 values 2;\n"
+ "'C1'\n"
+ "'2'\n"
+ "1 row selected \\([0-9.,]+ seconds\\)\n"
+ "4/4 !record\n";
checkScriptFile("!record " + file.getAbsolutePath() + "\n"
+ "!set outputformat csv\n"
+ "values 2;\n"
+ "!record\n",
false,
equalTo(SqlLine.Status.OK),
RegexMatcher.of("(?s)1/4 !record .*.log\n"
+ s
+ "Recording stopped.\n"
+ ".*"));
// Now check that the right stuff got into the file.
assertFileContains(file, RegexMatcher.of(s));
final boolean delete = file.delete();
assertThat(delete, is(true));
}
/**
* As {@link #testRecord()}, but file name is double-quoted and contains a
* space.
*/
@Test
public void testRecordFilenameWithSpace() {
File file = createTempFile("sqlline file with spaces", ".log");
final String script = "!set incremental true\n"
+ "values 1;\n"
+ "!record " + file.getAbsolutePath() + "\n"
+ "!set outputformat csv\n"
+ "values 2;\n"
+ "!record\n"
+ "!set outputformat csv\n"
+ "values 3;\n";
checkScriptFile(script, false,
equalTo(SqlLine.Status.OK),
RegexMatcher.of("(?s)1/8 !set incremental true\n"
+ "2/8 values 1;\n"
+ "\\+-------------\\+\n"
+ "\\| C1 \\|\n"
+ "\\+-------------\\+\n"
+ "\\| 1 \\|\n"
+ "\\+-------------\\+\n"
+ "1 row selected \\([0-9.,]+ seconds\\)\n"
+ "3/8 !record .*.log\n"
+ "Saving all output to \".*.log\". Enter \"record\" with no arguments to stop it.\n"
+ "4/8 !set outputformat csv\n"
+ "5/8 values 2;\n"
+ "'C1'\n"
+ "'2'\n"
+ "1 row selected \\([0-9.,]+ seconds\\)\n"
+ "6/8 !record\n"
+ "Recording stopped.\n"
+ "7/8 !set outputformat csv\n"
+ "8/8 values 3;\n"
+ "'C1'\n"
+ "'3'\n"
+ "1 row selected \\([0-9.,]+ seconds\\)\n.*"));
// Now check that the right stuff got into the file.
assertFileContains(file,
RegexMatcher.of("Saving all output to \".*.log\". "
+ "Enter \"record\" with no arguments to stop it.\n"
+ "4/8 !set outputformat csv\n"
+ "5/8 values 2;\n"
+ "'C1'\n"
+ "'2'\n"
+ "1 row selected \\([0-9.,]+ seconds\\)\n"
+ "6/8 !record\n"));
}
private static void assertFileContains(File file, Matcher<String> matcher) {
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(file),
StandardCharsets.UTF_8.name()))) {
final StringWriter stringWriter = new StringWriter();
for (;;) {
final String line = br.readLine();
if (line == null) {
break;
}
stringWriter.write(line);
stringWriter.write("\n");
}
assertThat(toLinux(stringWriter.toString()), matcher);
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
}
/**
* Test case for
* <a href="https://github.com/julianhyde/sqlline/issues/61">[SQLLINE-61]
* Add !nickname command</a>.
*/
@Test
public void testNickname() {
final String script = "!set outputformat csv\n"
+ "values 1;\n"
+ "!nickname foo\n"
+ "values 2;\n";
final String expected = "(?s)1/4 !set outputformat csv\n"
+ "2/4 values 1;\n"
+ "'C1'\n"
+ "'1'\n"
+ "1 row selected \\([0-9.,]+ seconds\\)\n"
+ "3/4 !nickname foo\n"
+ "4/4 values 2;\n"
+ "'C1'\n"
+ "'2'\n"
+ "1 row selected \\([0-9.,]+ seconds\\)\n.*";
checkScriptFile(script, false, equalTo(SqlLine.Status.OK),
RegexMatcher.of(expected));
}
/**
* Attempts to execute a simple script file with the -f option to SqlLine.
* The first command should fail and the second command should not execute.
*/
@Test
public void testBreakOnErrorScriptFile() {
checkScriptFile("select * from abcdefg01;\ncall 100 + 23;\n",
true,
equalTo(SqlLine.Status.OTHER),
not(containsString(" 123 ")));
}
/**
* Emulation of Apache Hive behavior with throwing exceptions
* while calling {@link DatabaseMetaData#storesUpperCaseIdentifiers()}
* and {@link DatabaseMetaData#supportsTransactionIsolationLevel(int)}.
*
* <p>Also please see
* <a href="https://github.com/julianhyde/sqlline/issues/183">[SQLLINE-183]</a>.
*
* @param meta Mocked JDBCDatabaseMetaData
*/
@Test
public void testExecutionWithNotSupportedMethods(
@Mocked final JDBCDatabaseMetaData meta) {
try {
new Expectations() {
{
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductName();
result = "hsqldb";
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductVersion();
result = "1.0";
// emulate apache hive behavior
meta.supportsTransactionIsolationLevel(4);
result = new SQLException("Method not supported");
}
};
SqlLine sqlLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-u",
"jdbc:hsqldb:res:scott",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback dc = new DispatchCallback();
sqlLine.initArgs(args, dc);
os.reset();
sqlLine.runCommands(dc,
"!set incremental true",
"values 1;");
final String output = os.toString("UTF8");
final String line0 = "+-------------+";
final String line1 = "| C1 |";
final String line2 = "+-------------+";
final String line3 = "| 1 |";
final String line4 = "+-------------+";
assertThat(output,
CoreMatchers.allOf(containsString(line0),
containsString(line1),
containsString(line2),
containsString(line3),
containsString(line4)));
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
}
@Test
public void testExecutionException(@Mocked final JDBCDatabaseMetaData meta,
@Mocked final JDBCResultSet resultSet) {
try {
new Expectations() {
{
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductName();
result = "hsqldb";
// prevent calls to functions that also call resultSet.next
meta.getSQLKeywords();
result = "";
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductVersion();
result = "1.0";
// Generate an exception on a call to resultSet.next
resultSet.next();
result = new SQLException("Generated Exception.");
}
};
SqlLine sqlLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-u",
"jdbc:hsqldb:res:scott",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback callback = new DispatchCallback();
sqlLine.initArgs(args, callback);
// If sqlline is not initialized, handleSQLException will print
// the entire stack trace.
// To prevent that, forcibly set init to true.
FieldReflection.setFieldValue(
sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true);
sqlLine.getConnection();
sqlLine.runCommands(callback,
"CREATE TABLE rsTest ( a int);",
"insert into rsTest values (1);",
"insert into rsTest values (2);",
"select a from rsTest; ");
String output = os.toString("UTF8");
assertThat(output, containsString("Generated Exception"));
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
}
/**
* Attempts to execute a missing script file with the -f option to SqlLine.
*/
@Test