1 package net.jaekl.squelch;
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import java.sql.Connection;
6 import java.sql.SQLException;
7 import java.util.Locale;
9 import net.jaekl.squelch.db.DbDriver;
10 import net.jaekl.squelch.db.MsSqlDriver;
11 import net.jaekl.squelch.db.MySqlDriver;
12 import net.jaekl.squelch.db.OracleDriver;
13 import net.jaekl.squelch.db.PostgresqlDriver;
14 import net.jaekl.squelch.stmt.Describe;
15 import net.jaekl.squelch.stmt.Select;
16 import net.jaekl.squelch.stmt.Stmt;
17 import net.jaekl.squelch.util.ConsoleInput;
18 import net.jaekl.squelch.util.ConsoleInputImpl;
19 import net.jaekl.squelch.util.ConsoleUtil;
21 public class Squelch {
22 static final String PROMPT = "> ";
23 private static final DbDriver[] DB_DRIVERS = {
27 new PostgresqlDriver()
29 private static final Stmt[] READ_ONLY_STATEMENTS = {
35 private Stmt[] m_statements;
38 m_args = new Args(this.getClass().getName());
39 m_statements = READ_ONLY_STATEMENTS;
42 public void doMain(String[] params)
44 try (PrintWriter pw = new PrintWriter(System.out))
46 if (!m_args.parseArgs(pw, params)) {
50 ConsoleInputImpl ci = ConsoleUtil.getInst().getInput();
52 } catch (IOException | ClassNotFoundException | SQLException | SquelchException e) {
57 public static void main(String[] args) {
58 new Squelch().doMain(args);
61 boolean isQuit(String line)
66 String trimmed = line.trim();
67 if (trimmed.endsWith(";")) {
68 trimmed = trimmed.substring(0, trimmed.length() - 1).trim();
70 String upperCased = trimmed.toUpperCase(Locale.CANADA);
72 if ( "EXIT".equals(upperCased)
73 || "QUIT".equals(upperCased)
74 || "\\q".equals(trimmed) )
81 Connection getConnection(DbDriver driver, String jdbcUrl)
82 throws ClassNotFoundException, SQLException, SquelchException
84 return driver.connect(jdbcUrl, m_args.getUser(), m_args.getPass());
87 DbDriver getDriverFor(String jdbcUrl) throws SquelchException
89 for (DbDriver driver : DB_DRIVERS) {
90 if (driver.handles(jdbcUrl)) {
94 throw new SquelchException("Cannot determine DB Driver for JDBC URL: \"" + jdbcUrl + "\".");
97 void pumpLines(PrintWriter pw, ConsoleInput ci) throws IOException, ClassNotFoundException, SQLException, SquelchException
100 String jdbcUrl = m_args.getUrl();
101 DbDriver driver = getDriverFor(jdbcUrl);
103 try (Connection conn = getConnection(driver, jdbcUrl))
106 boolean processed = false;
107 line = ci.readLine(PROMPT);
109 for (Stmt statement : m_statements) {
110 if (statement.handles(line)) {
112 statement.exec(driver, conn, pw, line);
114 catch (SQLException exc) {
115 exc.printStackTrace(pw);
126 // Unrecognized command
127 // TODO: add a string table, and a natural-language error message.
128 pw.println("??? \"" + line + "\"");