Debian Codegraph @

src/main/org/h2/tools/Shell.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.tools;
7
8 import java.io.BufferedReader;
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.InputStreamReader;
12 import java.io.PrintStream;
13 import java.io.StringReader;
14 import java.sql.Connection;
15 import java.sql.ResultSet;
16 import java.sql.ResultSetMetaData;
17 import java.sql.SQLException;
18 import java.sql.Statement;
19 import java.util.ArrayList;
20 import java.util.Properties;
21 import java.util.concurrent.TimeUnit;
22
23 import org.h2.api.ErrorCode;
24 import org.h2.engine.Constants;
25 import org.h2.server.web.ConnectionInfo;
26 import org.h2.util.JdbcUtils;
27 import org.h2.util.ScriptReader;
28 import org.h2.util.SortedProperties;
29 import org.h2.util.StringUtils;
30 import org.h2.util.Tool;
31 import org.h2.util.Utils;
32
33 /**
34 * Interactive command line tool to access a database using JDBC.
35 */
36 public class Shell extends Tool implements Runnable {
37
38 private static final int MAX_ROW_BUFFER = 5000;
39 private static final int HISTORY_COUNT = 20;
40 // Windows: '\u00b3';
41 private static final char BOX_VERTICAL = '|';
42
43 private PrintStream err = System.err;
44 private InputStream in = System.in;
45 private BufferedReader reader;
46 private Connection conn;
47 private Statement stat;
48 private boolean listMode;
49 private int maxColumnSize = 100;
50 private final ArrayList<String> history = new ArrayList<>();
51 private boolean stopHide;
52 private String serverPropertiesDir = Constants.SERVER_PROPERTIES_DIR;
53
54 /**
55 * Options are case sensitive.
56 * <table>
57 * <caption>Supported options</caption>
58 * <tr><td>[-help] or [-?]</td>
59 * <td>Print the list of options</td></tr>
60 * <tr><td>[-url "&lt;url&gt;"]</td>
61 * <td>The database URL (jdbc:h2:...)</td></tr>
62 * <tr><td>[-user &lt;user&gt;]</td>
63 * <td>The user name</td></tr>
64 * <tr><td>[-password &lt;pwd&gt;]</td>
65 * <td>The password</td></tr>
66 * <tr><td>[-driver &lt;class&gt;]</td>
67 * <td>The JDBC driver class to use (not required in most cases)</td></tr>
68 * <tr><td>[-sql "&lt;statements&gt;"]</td>
69 * <td>Execute the SQL statements and exit</td></tr>
70 * <tr><td>[-properties "&lt;dir&gt;"]</td>
71 * <td>Load the server properties from this directory</td></tr>
72 * </table>
73 * If special characters don't work as expected, you may need to use
74 * -Dfile.encoding=UTF-8 (Mac OS X) or CP850 (Windows).
75 *
76 * @param args the command line arguments
77 * @throws SQLException on failure
78 */
79 public static void main(String... args) throws SQLException {
80 new Shell().runTool(args);
81 }
82
83 /**
84 * Sets the standard error stream.
85 *
86 * @param err the new standard error stream
87 */
88 public void setErr(PrintStream err) {
89 this.err = err;
90 }
91
92 /**
93 * Redirects the standard input. By default, System.in is used.
94 *
95 * @param in the input stream to use
96 */
97 public void setIn(InputStream in) {
98 this.in = in;
99 }
100
101 /**
102 * Redirects the standard input. By default, System.in is used.
103 *
104 * @param reader the input stream reader to use
105 */
106 public void setInReader(BufferedReader reader) {
107 this.reader = reader;
108 }
109
110 /**
111 * Run the shell tool with the given command line settings.
112 *
113 * @param args the command line settings
114 */
115 @Override
116 public void runTool(String... args) throws SQLException {
117 String driver = null;
118 String url = null;
119 String user = "";
120 String password = "";
121 String sql = null;
122 for (int i = 0; args != null && i < args.length; i++) {
123 String arg = args[i];
124 if (arg.equals("-url")) {
125 url = args[++i];
126 } else if (arg.equals("-user")) {
127 user = args[++i];
128 } else if (arg.equals("-password")) {
129 password = args[++i];
130 } else if (arg.equals("-driver")) {
131 driver = args[++i];
132 } else if (arg.equals("-sql")) {
133 sql = args[++i];
134 } else if (arg.equals("-properties")) {
135 serverPropertiesDir = args[++i];
136 } else if (arg.equals("-help") || arg.equals("-?")) {
137 showUsage();
138 return;
139 } else if (arg.equals("-list")) {
140 listMode = true;
141 } else {
142 showUsageAndThrowUnsupportedOption(arg);
143 }
144 }
145 if (url != null) {
146 conn = JdbcUtils.getConnection(driver, url, user, password);
147 stat = conn.createStatement();
148 }
149 if (sql == null) {
150 promptLoop();
151 } else {
152 ScriptReader r = new ScriptReader(new StringReader(sql));
153 while (true) {
154 String s = r.readStatement();
155 if (s == null) {
156 break;
157 }
158 execute(s);
159 }
160 if (conn != null) {
161 conn.close();
162 }
163 }
164 }
165
166 /**
167 * Run the shell tool with the given connection and command line settings.
168 * The connection will be closed when the shell exits.
169 * This is primary used to integrate the Shell into another application.
170 * <p>
171 * Note: using the "-url" option in {@code args} doesn't make much sense
172 * since it will override the {@code conn} parameter.
173 * </p>
174 *
175 * @param conn the connection
176 * @param args the command line settings
177 * @throws SQLException on failure
178 */
179 public void runTool(Connection conn, String... args) throws SQLException {
180 this.conn = conn;
181 this.stat = conn.createStatement();
182 runTool(args);
183 }
184
185 private void showHelp() {
186 println("Commands are case insensitive; SQL statements end with ';'");
187 println("help or ? Display this help");
188 println("list Toggle result list / stack trace mode");
189 println("maxwidth Set maximum column width (default is 100)");
190 println("autocommit Enable or disable autocommit");
191 println("history Show the last 20 statements");
192 println("quit or exit Close the connection and exit");
193 println("");
194 }
195
196 private void promptLoop() {
197 println("");
198 println("Welcome to H2 Shell " + Constants.FULL_VERSION);
199 println("Exit with Ctrl+C");
200 if (conn != null) {
201 showHelp();
202 }
203 String statement = null;
204 if (reader == null) {
205 reader = new BufferedReader(new InputStreamReader(in));
206 }
207 while (true) {
208 try {
209 if (conn == null) {
210 connect();
211 showHelp();
212 }
213 if (statement == null) {
214 print("sql> ");
215 } else {
216 print("...> ");
217 }
218 String line = readLine();
219 if (line == null) {
220 break;
221 }
222 String trimmed = line.trim();
223 if (trimmed.isEmpty()) {
224 continue;
225 }
226 boolean end = trimmed.endsWith(";");
227 if (end) {
228 line = line.substring(0, line.lastIndexOf(';'));
229 trimmed = trimmed.substring(0, trimmed.length() - 1);
230 }
231 String lower = StringUtils.toLowerEnglish(trimmed);
232 if ("exit".equals(lower) || "quit".equals(lower)) {
233 break;
234 } else if ("help".equals(lower) || "?".equals(lower)) {
235 showHelp();
236 } else if ("list".equals(lower)) {
237 listMode = !listMode;
238 println("Result list mode is now " + (listMode ? "on" : "off"));
239 } else if ("history".equals(lower)) {
240 for (int i = 0, size = history.size(); i < size; i++) {
241 String s = history.get(i);
242 s = s.replace('\n', ' ').replace('\r', ' ');
243 println("#" + (1 + i) + ": " + s);
244 }
245 if (!history.isEmpty()) {
246 println("To re-run a statement, type the number and press and enter");
247 } else {
248 println("No history");
249 }
250 } else if (lower.startsWith("autocommit")) {
251 lower = StringUtils.trimSubstring(lower, "autocommit".length());
252 if ("true".equals(lower)) {
253 conn.setAutoCommit(true);
254 } else if ("false".equals(lower)) {
255 conn.setAutoCommit(false);
256 } else {
257 println("Usage: autocommit [true|false]");
258 }
259 println("Autocommit is now " + conn.getAutoCommit());
260 } else if (lower.startsWith("maxwidth")) {
261 lower = StringUtils.trimSubstring(lower, "maxwidth".length());
262 try {
263 maxColumnSize = Integer.parseInt(lower);
264 } catch (NumberFormatException e) {
265 println("Usage: maxwidth <integer value>");
266 }
267 println("Maximum column width is now " + maxColumnSize);
268 } else {
269 boolean addToHistory = true;
270 if (statement == null) {
271 if (StringUtils.isNumber(line)) {
272 int pos = Integer.parseInt(line);
273 if (pos == 0 || pos > history.size()) {
274 println("Not found");
275 } else {
276 statement = history.get(pos - 1);
277 addToHistory = false;
278 println(statement);
279 end = true;
280 }
281 } else {
282 statement = line;
283 }
284 } else {
285 statement += "\n" + line;
286 }
287 if (end) {
288 if (addToHistory) {
289 history.add(0, statement);
290 if (history.size() > HISTORY_COUNT) {
291 history.remove(HISTORY_COUNT);
292 }
293 }
294 execute(statement);
295 statement = null;
296 }
297 }
298 } catch (SQLException e) {
299 println("SQL Exception: " + e.getMessage());
300 statement = null;
301 } catch (IOException e) {
302 println(e.getMessage());
303 break;
304 } catch (Exception e) {
305 println("Exception: " + e.toString());
306 e.printStackTrace(err);
307 break;
308 }
309 }
310 if (conn != null) {
311 try {
312 conn.close();
313 println("Connection closed");
314 } catch (SQLException e) {
315 println("SQL Exception: " + e.getMessage());
316 e.printStackTrace(err);
317 }
318 }
319 }
320
321 private void connect() throws IOException, SQLException {
322 String url = "jdbc:h2:~/test";
323 String user = "";
324 String driver = null;
325 try {
326 Properties prop;
327 if ("null".equals(serverPropertiesDir)) {
328 prop = new Properties();
329 } else {
330 prop = SortedProperties.loadProperties(
331 serverPropertiesDir + "/" + Constants.SERVER_PROPERTIES_NAME);
332 }
333 String data = null;
334 boolean found = false;
335 for (int i = 0;; i++) {
336 String d = prop.getProperty(Integer.toString(i));
337 if (d == null) {
338 break;
339 }
340 found = true;
341 data = d;
342 }
343 if (found) {
344 ConnectionInfo info = new ConnectionInfo(data);
345 url = info.url;
346 user = info.user;
347 driver = info.driver;
348 }
349 } catch (IOException e) {
350 // ignore
351 }
352 println("[Enter] " + url);
353 print("URL ");
354 url = readLine(url).trim();
355 if (driver == null) {
356 driver = JdbcUtils.getDriver(url);
357 }
358 if (driver != null) {
359 println("[Enter] " + driver);
360 }
361 print("Driver ");
362 driver = readLine(driver).trim();
363 println("[Enter] " + user);
364 print("User ");
365 user = readLine(user);
366 conn = url.startsWith(Constants.START_URL) ? connectH2(driver, url, user)
367 : JdbcUtils.getConnection(driver, url, user, readPassword());
368 stat = conn.createStatement();
369 println("Connected");
370 }
371
372 private Connection connectH2(String driver, String url, String user) throws IOException, SQLException {
373 for (;;) {
374 String password = readPassword();
375 try {
376 return JdbcUtils.getConnection(driver, url + ";IFEXISTS=TRUE", user, password);
377 } catch (SQLException ex) {
378 if (ex.getErrorCode() == ErrorCode.DATABASE_NOT_FOUND_WITH_IF_EXISTS_1) {
379 println("Type the same password again to confirm database creation.");
380 String password2 = readPassword();
381 if (password.equals(password2)) {
382 return JdbcUtils.getConnection(driver, url, user, password);
383 } else {
384 println("Passwords don't match. Try again.");
385 }
386 } else {
387 throw ex;
388 }
389 }
390 }
391 }
392
393 /**
394 * Print the string without newline, and flush.
395 *
396 * @param s the string to print
397 */
398 protected void print(String s) {
399 out.print(s);
400 out.flush();
401 }
402
403 private void println(String s) {
404 out.println(s);
405 out.flush();
406 }
407
408 private String readPassword() throws IOException {
409 try {
410 Object console = Utils.callStaticMethod("java.lang.System.console");
411 print("Password ");
412 char[] password = (char[]) Utils.callMethod(console, "readPassword");
413 return password == null ? null : new String(password);
414 } catch (Exception e) {
415 // ignore, use the default solution
416 }
417 Thread passwordHider = new Thread(this, "Password hider");
418 stopHide = false;
419 passwordHider.start();
420 print("Password > ");
421 String p = readLine();
422 stopHide = true;
423 try {
424 passwordHider.join();
425 } catch (InterruptedException e) {
426 // ignore
427 }
428 print("\b\b");
429 return p;
430 }
431
432 /**
433 * INTERNAL.
434 * Hides the password by repeatedly printing
435 * backspace, backspace, &gt;, &lt;.
436 */
437 @Override
438 public void run() {
439 while (!stopHide) {
440 print("\b\b><");
441 try {
442 Thread.sleep(10);
443 } catch (InterruptedException e) {
444 // ignore
445 }
446 }
447 }
448
449
450 private String readLine(String defaultValue) throws IOException {
451 String s = readLine();
452 return s.isEmpty() ? defaultValue : s;
453 }
454
455 private String readLine() throws IOException {
456 String line = reader.readLine();
457 if (line == null) {
458 throw new IOException("Aborted");
459 }
460 return line;
461 }
462
463 private void execute(String sql) {
464 if (StringUtils.isWhitespaceOrEmpty(sql)) {
465 return;
466 }
467 long time = System.nanoTime();
468 try {
469 ResultSet rs = null;
470 try {
471 if (sql.startsWith("@")) {
472 rs = JdbcUtils.getMetaResultSet(conn, sql);
473 printResult(rs, listMode);
474 } else if (stat.execute(sql)) {
475 rs = stat.getResultSet();
476 int rowCount = printResult(rs, listMode);
477 time = System.nanoTime() - time;
478 println("(" + rowCount + (rowCount == 1 ?
479 " row, " : " rows, ") + TimeUnit.NANOSECONDS.toMillis(time) + " ms)");
480 } else {
481 long updateCount;
482 try {
483 updateCount = stat.getLargeUpdateCount();
484 } catch (UnsupportedOperationException e) {
485 updateCount = stat.getUpdateCount();
486 }
487 time = System.nanoTime() - time;
488 println("(Update count: " + updateCount + ", " +
489 TimeUnit.NANOSECONDS.toMillis(time) + " ms)");
490 }
491 } finally {
492 JdbcUtils.closeSilently(rs);
493 }
494 } catch (SQLException e) {
495 println("Error: " + e.toString());
496 if (listMode) {
497 e.printStackTrace(err);
498 }
499 }
500 }
501
502 private int printResult(ResultSet rs, boolean asList) throws SQLException {
503 if (asList) {
504 return printResultAsList(rs);
505 }
506 return printResultAsTable(rs);
507 }
508
509 private int printResultAsTable(ResultSet rs) throws SQLException {
510 ResultSetMetaData meta = rs.getMetaData();
511 int len = meta.getColumnCount();
512 boolean truncated = false;
513 ArrayList<String[]> rows = new ArrayList<>();
514 // buffer the header
515 String[] columns = new String[len];
516 for (int i = 0; i < len; i++) {
517 String s = meta.getColumnLabel(i + 1);
518 columns[i] = s == null ? "" : s;
519 }
520 rows.add(columns);
521 int rowCount = 0;
522 while (rs.next()) {
523 rowCount++;
524 truncated |= loadRow(rs, len, rows);
525 if (rowCount > MAX_ROW_BUFFER) {
526 printRows(rows, len);
527 rows.clear();
528 }
529 }
530 printRows(rows, len);
531 rows.clear();
532 if (truncated) {
533 println("(data is partially truncated)");
534 }
535 return rowCount;
536 }
537
538 private boolean loadRow(ResultSet rs, int len, ArrayList<String[]> rows)
539 throws SQLException {
540 boolean truncated = false;
541 String[] row = new String[len];
542 for (int i = 0; i < len; i++) {
543 String s = rs.getString(i + 1);
544 if (s == null) {
545 s = "null";
546 }
547 // only truncate if more than one column
548 if (len > 1 && s.length() > maxColumnSize) {
549 s = s.substring(0, maxColumnSize);
550 truncated = true;
551 }
552 row[i] = s;
553 }
554 rows.add(row);
555 return truncated;
556 }
557
558 private int[] printRows(ArrayList<String[]> rows, int len) {
559 int[] columnSizes = new int[len];
560 for (int i = 0; i < len; i++) {
561 int max = 0;
562 for (String[] row : rows) {
563 max = Math.max(max, row[i].length());
564 }
565 if (len > 1) {
566 max = Math.min(maxColumnSize, max);
567 }
568 columnSizes[i] = max;
569 }
570 for (String[] row : rows) {
571 StringBuilder buff = new StringBuilder();
572 for (int i = 0; i < len; i++) {
573 if (i > 0) {
574 buff.append(' ').append(BOX_VERTICAL).append(' ');
575 }
576 String s = row[i];
577 buff.append(s);
578 if (i < len - 1) {
579 for (int j = s.length(); j < columnSizes[i]; j++) {
580 buff.append(' ');
581 }
582 }
583 }
584 println(buff.toString());
585 }
586 return columnSizes;
587 }
588
589 private int printResultAsList(ResultSet rs) throws SQLException {
590 ResultSetMetaData meta = rs.getMetaData();
591 int longestLabel = 0;
592 int len = meta.getColumnCount();
593 String[] columns = new String[len];
594 for (int i = 0; i < len; i++) {
595 String s = meta.getColumnLabel(i + 1);
596 columns[i] = s;
597 longestLabel = Math.max(longestLabel, s.length());
598 }
599 StringBuilder buff = new StringBuilder();
600 int rowCount = 0;
601 while (rs.next()) {
602 rowCount++;
603 buff.setLength(0);
604 if (rowCount > 1) {
605 println("");
606 }
607 for (int i = 0; i < len; i++) {
608 if (i > 0) {
609 buff.append('\n');
610 }
611 String label = columns[i];
612 buff.append(label);
613 for (int j = label.length(); j < longestLabel; j++) {
614 buff.append(' ');
615 }
616 buff.append(": ").append(rs.getString(i + 1));
617 }
618 println(buff.toString());
619 }
620 if (rowCount == 0) {
621 for (int i = 0; i < len; i++) {
622 if (i > 0) {
623 buff.append('\n');
624 }
625 String label = columns[i];
626 buff.append(label);
627 }
628 println(buff.toString());
629 }
630 return rowCount;
631 }
632
633 }