From: SVN by r. <sv...@ca...> - 2007-10-28 11:42:31
|
Author: roy Date: 2007-10-28 12:41:30 +0100 (Sun, 28 Oct 2007) New Revision: 188 Modified: src/main/java/nl/improved/sqlclient/SQLShell.java src/main/java/nl/improved/sqlclient/commands/Command.java src/main/java/nl/improved/sqlclient/commands/DescCommand.java src/main/java/nl/improved/sqlclient/commands/InfoCommand.java src/main/java/nl/improved/sqlclient/commands/ShowCommand.java Log: made desc command work somewhat again... TODO: make de<tab> include desc option as well.. instead of only 'delete from' Modified: src/main/java/nl/improved/sqlclient/SQLShell.java =================================================================== --- src/main/java/nl/improved/sqlclient/SQLShell.java 2007-10-28 11:12:50 UTC (rev 187) +++ src/main/java/nl/improved/sqlclient/SQLShell.java 2007-10-28 11:41:30 UTC (rev 188) @@ -553,7 +553,28 @@ * @return the tab completion value. */ protected CharSequence getTabCompletion(SQLCommand commandLines, Point cursorPosition) { - TabCompletionInfo info = SQLUtil.getTabCompletionInfo(commandLines, cursorPosition); + TabCompletionInfo info = null; + String cmd = commandLines.getCommandString(); + if (cmd.length() > 0) { + if (cmd.indexOf(' ') > 0) { + cmd = cmd.substring(0, cmd.indexOf(' ')).trim(); + } + Command tmpCommand = commands.findCommand(cmd); + if (tmpCommand == null) { + for (Command c : commands.getCommands()) { + if (cmd.equalsIgnoreCase(c.getCommandString().toString())) { + tmpCommand = c; + break; + } + } + } + if (tmpCommand != null) { + info = tmpCommand.getTabCompletionInfo(commandLines, cursorPosition); + } + } + if (info == null) { + info = SQLUtil.getTabCompletionInfo(commandLines, cursorPosition); + } if (info.getMatchType() == TabCompletionInfo.MatchType.SQL_KEYWORD) { return nullToEmpty(findMatch(info.getPossibleMatches(), info.getStart())); } @@ -795,7 +816,7 @@ * @param commandPoint the cursor position * @return some tab completion info for the specified command. */ - public TabCompletionInfo getTabCompletion(List<? extends CharSequence> commandInfo, Point commandPoint) { + public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { return null; } @@ -846,7 +867,7 @@ * @param commandPoint the cursor position * @return some tab completion info for the specified command. */ - public TabCompletionInfo getTabCompletion(List<? extends CharSequence> commandInfo, Point commandPoint) { + public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { return null; } public CharSequence getHelp() { @@ -878,7 +899,7 @@ * @param commandPoint the cursor position * @return some tab completion info for the specified command. */ - public TabCompletionInfo getTabCompletion(List<? extends CharSequence> commandInfo, Point commandPoint) { + public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { return null; } public CharSequence getHelp() { @@ -910,7 +931,7 @@ * @param commandPoint the cursor position * @return some tab completion info for the specified command. */ - public TabCompletionInfo getTabCompletion(List<? extends CharSequence> commandInfo, Point commandPoint) { + public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { return null; } public CharSequence getHelp() { @@ -939,7 +960,7 @@ * @param commandPoint the cursor position * @return some tab completion info for the specified command. */ - public TabCompletionInfo getTabCompletion(List<? extends CharSequence> commandInfo, Point commandPoint) { + public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { return null; } } @@ -1020,7 +1041,7 @@ * @param commandPoint the cursor position * @return some tab completion info for the specified command. */ - public TabCompletionInfo getTabCompletion(List<? extends CharSequence> commandInfo, Point commandPoint) { + public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { return null; } public CharSequence getHelp() { @@ -1079,7 +1100,7 @@ * @param commandPoint the cursor position * @return some tab completion info for the specified command. */ - public TabCompletionInfo getTabCompletion(List<? extends CharSequence> commandInfo, Point commandPoint) { + public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { return null; } public CharSequence getHelp() { @@ -1128,7 +1149,7 @@ * @param commandPoint the cursor position * @return some tab completion info for the specified command. */ - public TabCompletionInfo getTabCompletion(List<? extends CharSequence> commandInfo, Point commandPoint) { + public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { return null; } public CharSequence getHelp() { Modified: src/main/java/nl/improved/sqlclient/commands/Command.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/Command.java 2007-10-28 11:12:50 UTC (rev 187) +++ src/main/java/nl/improved/sqlclient/commands/Command.java 2007-10-28 11:41:30 UTC (rev 188) @@ -42,7 +42,7 @@ * @param commandPoint the cursor position * @return some tab completion info for the specified command. */ - TabCompletionInfo getTabCompletion(List<? extends CharSequence> commandInfo, Point commandPoint); + TabCompletionInfo getTabCompletionInfo(SQLCommand commandInfo, Point commandPoint); /** * Returns a explenation string of how to use this command. * @return a explenation string of how to use this command. Modified: src/main/java/nl/improved/sqlclient/commands/DescCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/DescCommand.java 2007-10-28 11:12:50 UTC (rev 187) +++ src/main/java/nl/improved/sqlclient/commands/DescCommand.java 2007-10-28 11:41:30 UTC (rev 188) @@ -106,7 +106,9 @@ } - public TabCompletionInfo getTabCompletion(List<? extends CharSequence> commandInfo, Point commandPoint) { + public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { + List commandInfo = command.getLines(); + String startOfCommand = SQLUtil.getStartOfCommand(commandInfo, commandPoint); String end = startOfCommand.substring(startOfCommand.lastIndexOf(' ')+1); return new TabCompletionInfo(TabCompletionInfo.MatchType.TABLE_NAMES, new ArrayList<String>(), end); Modified: src/main/java/nl/improved/sqlclient/commands/InfoCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/InfoCommand.java 2007-10-28 11:12:50 UTC (rev 187) +++ src/main/java/nl/improved/sqlclient/commands/InfoCommand.java 2007-10-28 11:41:30 UTC (rev 188) @@ -74,7 +74,7 @@ * @param commandPoint the cursor position * @return some tab completion info for the specified command. */ - public TabCompletionInfo getTabCompletion(List<? extends CharSequence> commandInfo, Point commandPoint) { + public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { return null; } Modified: src/main/java/nl/improved/sqlclient/commands/ShowCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/ShowCommand.java 2007-10-28 11:12:50 UTC (rev 187) +++ src/main/java/nl/improved/sqlclient/commands/ShowCommand.java 2007-10-28 11:41:30 UTC (rev 188) @@ -102,7 +102,7 @@ * @param commandPoint the cursor position * @return some tab completion info for the specified command. */ - public TabCompletionInfo getTabCompletion(List<? extends CharSequence> commandInfo, Point commandPoint) { + public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { return null; } |
From: SVN by r. <sv...@ca...> - 2008-01-27 10:53:02
|
Author: roy Date: 2008-01-27 11:41:23 +0100 (Sun, 27 Jan 2008) New Revision: 229 Modified: src/main/java/nl/improved/sqlclient/DBConnector.java src/main/java/nl/improved/sqlclient/commands/DescCommand.java src/main/java/nl/improved/sqlclient/commands/ShowCommand.java Log: fix case sensitivity that differs per databse (oracle wants uppercase, mysql wants lowercase.. sigh) Modified: src/main/java/nl/improved/sqlclient/DBConnector.java =================================================================== --- src/main/java/nl/improved/sqlclient/DBConnector.java 2008-01-24 21:02:26 UTC (rev 228) +++ src/main/java/nl/improved/sqlclient/DBConnector.java 2008-01-27 10:41:23 UTC (rev 229) @@ -17,6 +17,7 @@ import java.sql.Connection; import java.sql.DriverManager; +import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Hashtable; @@ -37,6 +38,7 @@ public final class DBConnector { private static DBConnector instance = null; + private boolean tableNamesUppercase = false; private Map<String, ConnectionSettings> predefinedConnections; private String defaultConnector; @@ -79,6 +81,16 @@ return connect(defaultConnector, null, null); } + public String translateDbVar(String name) { + if (name == null) { + return null; + } + if (tableNamesUppercase) { + return name.toUpperCase(); + } + return name.toLowerCase(); + } + /** * Return the used schema. * NOTE: hack because Oracle uses as a schema the current username @@ -244,6 +256,24 @@ activeConnection = DriverManager.getConnection(settings.getConnectionURL(), username, password); activeConnection.setAutoCommit(autoCommit); + // INITIALIZE to uppercase type + try { + ResultSet rs = activeConnection.getMetaData() + .getTables(activeConnection.getCatalog(), getSchema() + , null, new String[]{"TABLE"}); + while (rs.next()) { + String tableName = rs.getString("TABLE_NAME"); + for (int i = 0; i < tableName.length(); i++) { + if (Character.isLetter(tableName.charAt(i))) { + this.tableNamesUppercase = Character.isUpperCase(tableName.charAt(i)); + break; + } + } + } + } catch(Exception e) { + /* ignore */ + } + // END INITIALIZE return activeConnection; } Modified: src/main/java/nl/improved/sqlclient/commands/DescCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/DescCommand.java 2008-01-24 21:02:26 UTC (rev 228) +++ src/main/java/nl/improved/sqlclient/commands/DescCommand.java 2008-01-27 10:41:23 UTC (rev 229) @@ -40,7 +40,7 @@ if (cmd.endsWith(";")) { cmd = cmd.substring(0, cmd.length()-1); } - String tableName = cmd.substring(cmd.lastIndexOf(' ')).trim().toUpperCase(); + String tableName = DBConnector.getInstance().translateDbVar(cmd.substring(cmd.lastIndexOf(' ')).trim()); ResultBuilder result = new ResultBuilder(); result.setHorizontalSeparatorEnabled(false); result.setVerticalSeparator(' '); @@ -101,11 +101,13 @@ * Return the command string desc. * @return the command string desc. */ + @Override public CharSequence getCommandString() { return "desc"; } + @Override public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { List commandInfo = command.getLines(); Modified: src/main/java/nl/improved/sqlclient/commands/ShowCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/ShowCommand.java 2008-01-24 21:02:26 UTC (rev 228) +++ src/main/java/nl/improved/sqlclient/commands/ShowCommand.java 2008-01-27 10:41:23 UTC (rev 229) @@ -44,7 +44,7 @@ if (subCommand.startsWith("TABLES")) { if (subCommand.indexOf(' ') > 0) { String otherCommand = subCommand.substring(subCommand.indexOf(' ')).trim(); - String columnName = otherCommand.substring(otherCommand.indexOf(' ')).trim().toUpperCase(); + String columnName = DBConnector.getInstance().translateDbVar(otherCommand.substring(otherCommand.indexOf(' ')).trim()); if (otherCommand.toUpperCase().matches("HAVING[\\s]+[A-Z]+.*")) { try { ResultSet rs = conn.getMetaData().getColumns(conn.getCatalog() @@ -103,6 +103,7 @@ * @param commandPoint the cursor position * @return some tab completion info for the specified command. */ + @Override public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { String commandString = command.getUntrimmedCommandString(); String commandStringUpper = commandString.toUpperCase(); |
From: SVN by r. <sv...@ca...> - 2008-02-13 07:23:57
|
Author: roy Date: 2008-02-13 08:23:46 +0100 (Wed, 13 Feb 2008) New Revision: 234 Modified: src/main/java/nl/improved/sqlclient/QueryExecutor.java src/main/java/nl/improved/sqlclient/SQLShell.java src/main/java/nl/improved/sqlclient/commands/Command.java src/main/java/nl/improved/sqlclient/commands/DescCommand.java src/main/java/nl/improved/sqlclient/commands/InfoCommand.java src/main/java/nl/improved/sqlclient/commands/ShowCommand.java Log: added abort to command interface code cleanup some initial work started for running a commands in the background (so abort can actually be called :) ) Modified: src/main/java/nl/improved/sqlclient/QueryExecutor.java =================================================================== --- src/main/java/nl/improved/sqlclient/QueryExecutor.java 2008-02-10 15:17:36 UTC (rev 233) +++ src/main/java/nl/improved/sqlclient/QueryExecutor.java 2008-02-13 07:23:46 UTC (rev 234) @@ -26,6 +26,8 @@ import java.util.ArrayList; import java.text.DateFormat; import java.text.SimpleDateFormat; +import java.util.logging.Level; +import java.util.logging.Logger; import nl.improved.sqlclient.util.ResultBuilder; /** @@ -161,6 +163,15 @@ } } + public CharSequence cancel() { + try { + DBConnector.getInstance().getStatement().cancel(); + return "Cancel accepted"; + } catch (SQLException ex) { + return "Cancel Failed: "+ ex.toString(); + } + } + /** * Executes a SQL query. * @param command the SQL query to execute. @@ -189,6 +200,7 @@ while (results.next()) { for (int col = 1; col <= metadata.getColumnCount(); col++ ) { displayValue.set(col-1, rowCount, getDisplayValue(results, col), isNumeric(metadata, col) ? ResultBuilder.Alignment.RIGHT : ResultBuilder.Alignment.LEFT); + //try {Thread.sleep(10);} catch(Exception e2) {} } rowCount++; } Modified: src/main/java/nl/improved/sqlclient/SQLShell.java =================================================================== --- src/main/java/nl/improved/sqlclient/SQLShell.java 2008-02-10 15:17:36 UTC (rev 233) +++ src/main/java/nl/improved/sqlclient/SQLShell.java 2008-02-13 07:23:46 UTC (rev 234) @@ -38,6 +38,8 @@ */ public class SQLShell extends Window { + private CommandThread commandThread; + /** * The (default) maximum matches to show in a selection dialog. */ @@ -94,11 +96,6 @@ private CommandManager commands = new CommandManager(); /** - * Executor for SQL Statements - */ - private StatementExecutor queryExecutor; - - /** * Constructor. */ public SQLShell() { @@ -193,6 +190,7 @@ * @param inp the character that is being pressed by the user. */ protected void handleInput(InputChar inp) { + debug("Input: " + inp.getCode()); try { if (inp.getCode() != InputChar.KEY_PPAGE && inp.getCode() != InputChar.KEY_NPAGE) { pageUpCount = 0; // some character entered, so reset pageup count @@ -281,6 +279,11 @@ if (commandLines.getCommandString().length() == 0) { //Quit on empty commandline, ignore otherwise executeCommand(new InputCommand("quit")); } + } else if (inp.toString() != null && inp.toString().equals("")) { // ctrl+a + output("Abort requested"); + if (commandThread.isAlive() && commandThread.getCommand().abort()) { + output("Abort done.."); + } } else { if (inp.getCharacter() == '\n') { // execute the command @@ -604,26 +607,47 @@ * @return true if it succeeded. */ protected boolean executeCommand(SQLCommand sqlCommand) { - String command = sqlCommand.getCommandString(); - Command cCommand = commands.findCommand(command); + return executeCommand(sqlCommand, false); + } + + private boolean executeCommand(final SQLCommand sqlCommand, boolean direct) { + if (commandThread != null && commandThread.isAlive()) { + try { commandThread.join();}catch(Exception e) {} + } + final String command = sqlCommand.getCommandString(); + final Command cCommand = commands.findCommand(command); if (cCommand != null) { output(sqlCommand.getUntrimmedCommandString()); - try { - output(cCommand.execute(sqlCommand)); - } catch(Exception e) { - error(e); + commandThread = new CommandThread(cCommand) { + public void run() { + try { + output(cCommand.execute(sqlCommand)); + } catch(Exception e) { + error(e); + } + } + }; + if (direct || cCommand instanceof QuitCommand || cCommand instanceof ConnectCommand) { + commandThread.run(); + } else { + //commandThread.start(); // TODO + commandThread.run(); } return true; } if (sqlCommand.endsWith(";")) { // execute sql command output(sqlCommand.getUntrimmedCommandString()); - try { - output(getResult(command)); - } catch(SQLException e) { - error(e); - } catch(IllegalStateException e) { - error(e); + commandThread = new CommandThread(new QueryCommand()) { + public void run() { + output(getCommand().execute(sqlCommand)); + } + }; + if (direct) { + commandThread.run(); + } else { + //commandThread.start(); // TODO + commandThread.run(); } return true; } else if (command.equalsIgnoreCase("printStackTrace")) { @@ -637,20 +661,6 @@ return false; } - /** - * Execute a query and return its result. - * @param command the query to execute - * @return the result of the query - */ - protected CharSequence getResult(CharSequence command) throws SQLException { - if (command.length() > "select".length() && "select".equalsIgnoreCase(command.subSequence(0, "create".length()).toString())) { - return DBConnector.getInstance().getQueryExecutor().executeQuery(command); - } - if (queryExecutor == null) { - queryExecutor = new StatementExecutor(); - } - return queryExecutor.execute(command); - } /** * Paint the screen. @@ -799,6 +809,7 @@ * @param command the command string for setting up a connection * @return a readable result of the execution of this command. */ + @Override public CharSequence execute(SQLCommand cmd) { String command = cmd.getCommandString(); try { @@ -812,6 +823,7 @@ throw new IllegalStateException("Failed to connect: " + e.getMessage(), e); } } + @Override public CharSequence getCommandString() { return "connect"; } @@ -822,10 +834,12 @@ * @param commandPoint the cursor position * @return some tab completion info for the specified command. */ + @Override public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { return null; } + @Override public CharSequence getHelp() { StringBuffer buf = new StringBuffer(); Iterator<String> idents = DBConnector.getInstance().getPredefinedConnectionIdentifiers().iterator(); @@ -850,11 +864,17 @@ "Currently configured connection identifiers:\n"+ buf.toString(); } + + @Override + public boolean abort() { + return false;// not implemented + } } /** * Command that enables the user to close a connection. */ private static class DisConnectCommand implements Command { + @Override public CharSequence execute(SQLCommand cmd) { try { DBConnector.getInstance().disconnect(); @@ -863,6 +883,7 @@ throw new IllegalStateException("Failed to disconnect: " + e.getMessage(), e); } } + @Override public CharSequence getCommandString() { return "disconnect"; } @@ -873,18 +894,25 @@ * @param commandPoint the cursor position * @return some tab completion info for the specified command. */ + @Override public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { return null; } + @Override public CharSequence getHelp() { return "Close the current conection to the database"; } + @Override + public boolean abort() { + return false;// not implemented + } } /** * Some basic window settings like resize. */ private class WindowCommand implements Command { + @Override public CharSequence execute(SQLCommand cmd) { String command = cmd.getCommandString(); String argument = command.trim().substring("window".length()).trim(); @@ -895,6 +923,7 @@ return "Uknown command '"+ argument+"'"; } + @Override public CharSequence getCommandString() { return "window"; } @@ -905,18 +934,25 @@ * @param commandPoint the cursor position * @return some tab completion info for the specified command. */ + @Override public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { return null; } + @Override public CharSequence getHelp() { return "window resize: notify the sql client of a screen resize"; } + @Override + public boolean abort() { + return false;// not implemented + } } /** * Provide a list of commands executed. */ private class HistoryCommand implements Command { + @Override public CharSequence execute(SQLCommand command) { StringBuilder returnValue = new StringBuilder(); Iterator<SQLCommand> iCommands = commandHistory.iterator(); @@ -927,6 +963,7 @@ } return returnValue; } + @Override public CharSequence getCommandString() { return "history"; } @@ -937,13 +974,19 @@ * @param commandPoint the cursor position * @return some tab completion info for the specified command. */ + @Override public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { return null; } + @Override public CharSequence getHelp() { return "Show history of executed statements\n" + "By using '/<search>' you can search the command history" ; } + @Override + public boolean abort() { + return false;// not implemented + } } /** @@ -955,13 +998,16 @@ public QuitCommand(String cmd) { this.cmd = cmd; } + @Override public CharSequence execute(SQLCommand command) { hide(); // quit return "Application terminated."; } + @Override public CharSequence getHelp() { return "Quit(exit) the application."; } + @Override public CharSequence getCommandString() { return cmd; } @@ -971,14 +1017,20 @@ * @param commandPoint the cursor position * @return some tab completion info for the specified command. */ + @Override public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { return null; } + @Override + public boolean abort() { + return false;// not implemented + } } /** * Provide help to the user. */ private class HelpCommand implements Command { + @Override public CharSequence execute(SQLCommand sqlCommand) { // the execution of help consists of: // 1. is general help.. @@ -1042,6 +1094,7 @@ returnValue.insert(0, helpHeader); return returnValue; } + @Override public CharSequence getCommandString() { return "help"; } @@ -1052,14 +1105,25 @@ * @param commandPoint the cursor position * @return some tab completion info for the specified command. */ + @Override public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { return null; } + @Override public CharSequence getHelp() { return "this command. Please use 'help' to get a list of available commands you can use."; } + @Override + public boolean abort() { + return false;// not implemented + } } + /** + * Convert '~/' to the username dir. + * @param fileName the filename to convert + * @return the converted filename + */ private static String toFileName(String fileName) { if (fileName.startsWith("~/")) { return System.getProperty("user.home")+fileName.substring(1); @@ -1073,6 +1137,7 @@ private class SpoolCommand implements Command { private String fileName; + @Override public CharSequence execute(SQLCommand cmd) { String command = cmd.getCommandString(); String nextPart = command.substring("spool".length()).trim(); @@ -1101,6 +1166,7 @@ } } + @Override public CharSequence getCommandString() { return "spool"; } @@ -1111,14 +1177,20 @@ * @param commandPoint the cursor position * @return some tab completion info for the specified command. */ + @Override public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { return null; } + @Override public CharSequence getHelp() { return "filename: Spool all output and queries to the specified file\n"+ "off : Stop spooling data to the file.\n" + "Current status:"+(spoolWriter != null ? "on, writing to '"+fileName+"'" : "off"); } + @Override + public boolean abort() { + return false;// not implemented + } } private class ExecuteBatchCommand implements Command { @@ -1150,6 +1222,7 @@ } } + @Override public CharSequence getCommandString() { return "@"; } @@ -1160,6 +1233,7 @@ * @param commandPoint the cursor position * @return some tab completion info for the specified command. */ + @Override public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { String fileName = command.getCommandString().substring(1).trim(); // cutoff '@' String dirName; @@ -1184,11 +1258,16 @@ return new TabCompletionInfo(TabCompletionInfo.MatchType.UNKNOWN,Arrays.asList(new File(dirName).list()) , fileName); } + @Override public CharSequence getHelp() { return "Specify filename to execute a 'batch' command.\n"+ "For example '@mystatements.sql' executes all statements part of the mystatements.sql file in the current directory."+ "Note that all statements must be terminated with ';' (sql statements as well as connect statements or spool)"; } + @Override + public boolean abort() { + return false;// not implemented + } } /** @@ -1223,6 +1302,73 @@ } } + private static class CommandThread extends Thread { + private Command cmd; + public CommandThread(Command cmd) { + this.cmd = cmd; + } + + Command getCommand() { + return cmd; + } + } + + private class QueryCommand implements Command { + + /** + * Executor for SQL Statements + */ + private StatementExecutor statementExecutor; + + @Override + public CharSequence execute(SQLCommand cmd) { + try { + String command = cmd.getCommandString(); + if (command.length() > "select".length() && "select".equalsIgnoreCase(command.subSequence(0, "create".length()).toString())) { + return DBConnector.getInstance().getQueryExecutor().executeQuery(command); + } + if (statementExecutor == null) { + statementExecutor = new StatementExecutor(); + } + return statementExecutor.execute(command); + } catch(SQLException e) { + error(e); + return ""; + } catch(IllegalStateException e) { + error(e); + return ""; + } + } + + @Override + public CharSequence getCommandString() { + return ""; + } + + @Override + public TabCompletionInfo getTabCompletionInfo(SQLCommand commandInfo, Point commandPoint) { + // TODO call SQLUTil.. + return null; + } + + @Override + public CharSequence getHelp() { + return ""; + } + + @Override + public boolean abort() { + try { + DBConnector.getInstance().getStatement().cancel(); + return true; + } catch (SQLException ex) { + Logger.getLogger(SQLShell.class.getName()).log(Level.SEVERE, null, ex); + return false; + } + } + + } + public static void main(String[] args) { SQLShell shell = new SQLShell(); shell.show(); Modified: src/main/java/nl/improved/sqlclient/commands/Command.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/Command.java 2008-02-10 15:17:36 UTC (rev 233) +++ src/main/java/nl/improved/sqlclient/commands/Command.java 2008-02-13 07:23:46 UTC (rev 234) @@ -48,4 +48,10 @@ * @return a explenation string of how to use this command. */ CharSequence getHelp(); + + /** + * Attempt to abort the command and return true if succeeded. + * @return true if abort succeeded + */ + boolean abort(); } Modified: src/main/java/nl/improved/sqlclient/commands/DescCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/DescCommand.java 2008-02-10 15:17:36 UTC (rev 233) +++ src/main/java/nl/improved/sqlclient/commands/DescCommand.java 2008-02-13 07:23:46 UTC (rev 234) @@ -123,4 +123,9 @@ return "Describes the table structure.\n" + "For example 'desc mytable' shows the properties of the mytable table"; } + + @Override + public boolean abort() { + throw new UnsupportedOperationException("Not supported yet."); + } } Modified: src/main/java/nl/improved/sqlclient/commands/InfoCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/InfoCommand.java 2008-02-10 15:17:36 UTC (rev 233) +++ src/main/java/nl/improved/sqlclient/commands/InfoCommand.java 2008-02-13 07:23:46 UTC (rev 234) @@ -33,6 +33,7 @@ * @param command the command that is executed * @return the info of the connection */ + @Override public CharSequence execute(SQLCommand cmd) { java.sql.Connection conn = DBConnector.getInstance().getConnection(); StringBuilder returnValue = new StringBuilder(); @@ -64,6 +65,7 @@ * Return the command string. * @return the command string. */ + @Override public CharSequence getCommandString() { return "info"; } @@ -74,6 +76,7 @@ * @param commandPoint the cursor position * @return some tab completion info for the specified command. */ + @Override public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { return null; } @@ -82,7 +85,13 @@ * Return the command help. * @return the command help. */ + @Override public CharSequence getHelp() { return "Shows information about the current connection."; } + + @Override + public boolean abort() { + return false; + } } Modified: src/main/java/nl/improved/sqlclient/commands/ShowCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/ShowCommand.java 2008-02-10 15:17:36 UTC (rev 233) +++ src/main/java/nl/improved/sqlclient/commands/ShowCommand.java 2008-02-13 07:23:46 UTC (rev 234) @@ -33,6 +33,7 @@ /** * Execute the describe command. */ + @Override public CharSequence execute(SQLCommand command) { java.sql.Connection conn = DBConnector.getInstance().getConnection(); String cmd = command.getCommandString(); @@ -93,6 +94,7 @@ * Return the command string desc. * @return the command string desc. */ + @Override public CharSequence getCommandString() { return "show"; } @@ -129,8 +131,14 @@ * Return the command help. * @return the command help. */ + @Override public CharSequence getHelp() { return "tables: show all tables available in the currently selected schema\n"+ "tables having columnname: same as 'show tables' but limited to tables with that specific columnname"; } + + @Override + public boolean abort() { + return false; // not implemented + } } |
From: SVN by r. <sv...@ca...> - 2008-02-26 20:43:28
|
Author: roy Date: 2008-02-26 21:43:14 +0100 (Tue, 26 Feb 2008) New Revision: 239 Modified: src/main/java/nl/improved/sqlclient/SQLShell.java src/main/java/nl/improved/sqlclient/commands/Command.java src/main/java/nl/improved/sqlclient/commands/DescCommand.java src/main/java/nl/improved/sqlclient/commands/InfoCommand.java src/main/java/nl/improved/sqlclient/commands/ShowCommand.java Log: refactor step to configure background process support Modified: src/main/java/nl/improved/sqlclient/SQLShell.java =================================================================== --- src/main/java/nl/improved/sqlclient/SQLShell.java 2008-02-19 20:02:17 UTC (rev 238) +++ src/main/java/nl/improved/sqlclient/SQLShell.java 2008-02-26 20:43:14 UTC (rev 239) @@ -727,44 +727,8 @@ } private boolean executeCommand(final SQLCommand sqlCommand, boolean direct) { - if (commandThread != null && commandThread.isAlive()) { - try { commandThread.join();}catch(Exception e) {} - } - final String command = sqlCommand.getCommandString(); - final Command cCommand = commands.findCommand(command); - if (cCommand != null) { - output(sqlCommand.getUntrimmedCommandString()); - commandThread = new CommandThread(cCommand) { - public void execute() { - try { - output(cCommand.execute(sqlCommand)); - } catch(Exception e) { - error(e); - } - } - }; - if (direct || cCommand instanceof QuitCommand || cCommand instanceof ConnectCommand) { - commandThread.run(); - } else { - commandThread.start(); - } - return true; - } - if (sqlCommand.endsWith(";")) { - // execute sql command - output(sqlCommand.getUntrimmedCommandString()); - commandThread = new CommandThread(new QueryCommand()) { - public void execute() { - output(getCommand().execute(sqlCommand)); - } - }; - if (direct) { - commandThread.run(); - } else { - commandThread.start(); - } - return true; - } else if (command.equalsIgnoreCase("printStackTrace")) { + final String commandString = sqlCommand.getCommandString(); + if (commandString.equalsIgnoreCase("printStackTrace")) { if (lastExceptionDetails == null) { output("No known last exception to print"); } else { @@ -772,8 +736,41 @@ } return true; } - return false; + final Command command = createCommand(commandString); + if (command == null) { + return false; + } + // make sure only one command is run at once + if (commandThread != null && commandThread.isAlive()) { + try { + commandThread.join(); + } catch (InterruptedException ex) { + Logger.getLogger(SQLShell.class.getName()).log(Level.SEVERE, null, ex); + } + } + if (direct || !command.backgroundProcessSupported()) { + output(command.execute(sqlCommand)); + } else { + commandThread = new CommandThread(command) { + @Override + void execute() { + output(getCommand().execute(sqlCommand)); + } + }; + commandThread.start(); + } + return true; } + private Command createCommand(String commandString) { + Command command = commands.findCommand(commandString); + if (command != null) { + return command; + } + if (commandString.endsWith(";")) { + return new QueryCommand(); // TODO is this ever reached??? + } + return null; + } /** @@ -983,6 +980,10 @@ public boolean abort() { return false;// not implemented } + @Override + public boolean backgroundProcessSupported() { + return false; + } } /** * Command that enables the user to close a connection. @@ -1020,6 +1021,10 @@ public boolean abort() { return false;// not implemented } + @Override + public boolean backgroundProcessSupported() { + return false; + } } /** @@ -1060,6 +1065,10 @@ public boolean abort() { return false;// not implemented } + @Override + public boolean backgroundProcessSupported() { + return false; + } } /** @@ -1101,6 +1110,10 @@ public boolean abort() { return false;// not implemented } + @Override + public boolean backgroundProcessSupported() { + return false; + } } /** @@ -1139,6 +1152,10 @@ public boolean abort() { return false;// not implemented } + @Override + public boolean backgroundProcessSupported() { + return false; + } } /** * Provide help to the user. @@ -1252,6 +1269,10 @@ public boolean abort() { return false;// not implemented } + @Override + public boolean backgroundProcessSupported() { + return false; + } } /** @@ -1326,26 +1347,40 @@ public boolean abort() { return false;// not implemented } + @Override + public boolean backgroundProcessSupported() { + return false; + } } private class ExecuteBatchCommand implements Command { + private boolean cancelled = false; + @Override public CharSequence execute(SQLCommand sqlCommand) { + cancelled = false; String command = sqlCommand.getCommandString(); // read file from file system and execute FileInputStream fin = null; try { fin = new FileInputStream(toFileName(command.substring(1))); + output("Reading file: "+ toFileName(command.substring(1))+"\n"); BufferedReader reader = new BufferedReader(new InputStreamReader(fin)); StringBuilder cmd = new StringBuilder(); String line; - while ( (line = reader.readLine()) != null) { + while ( ((line = reader.readLine()) != null)) { + if (cancelled) { + return "Aborted"; + } if (line.startsWith("--")) { continue; } cmd.append(line); if (line.endsWith(";")) { // Exec cmd - executeCommand(new InputCommand(cmd)); + String commandString = cmd.toString(); + Command cCommand = createCommand(commandString); + output(commandString); + output(cCommand.execute(new InputCommand(commandString))); // TODO start in background... cmd=new StringBuilder(); } } @@ -1401,8 +1436,13 @@ } @Override public boolean abort() { - return false;// not implemented + cancelled = true; + return true; } + @Override + public boolean backgroundProcessSupported() { + return true; + } } /** @@ -1510,6 +1550,10 @@ output(DBConnector.getInstance().getQueryExecutor().cancel()); return true; } + @Override + public boolean backgroundProcessSupported() { + return true; + } } Modified: src/main/java/nl/improved/sqlclient/commands/Command.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/Command.java 2008-02-19 20:02:17 UTC (rev 238) +++ src/main/java/nl/improved/sqlclient/commands/Command.java 2008-02-26 20:43:14 UTC (rev 239) @@ -54,4 +54,10 @@ * @return true if abort succeeded */ boolean abort(); + + /** + * Return true if the command (instance) supports to be started in the background. + * @return true if the command (instance) supports to be started in the background. + */ + boolean backgroundProcessSupported(); } Modified: src/main/java/nl/improved/sqlclient/commands/DescCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/DescCommand.java 2008-02-19 20:02:17 UTC (rev 238) +++ src/main/java/nl/improved/sqlclient/commands/DescCommand.java 2008-02-26 20:43:14 UTC (rev 239) @@ -128,4 +128,8 @@ public boolean abort() { throw new UnsupportedOperationException("Not supported yet."); } + @Override + public boolean backgroundProcessSupported() { + return false; + } } Modified: src/main/java/nl/improved/sqlclient/commands/InfoCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/InfoCommand.java 2008-02-19 20:02:17 UTC (rev 238) +++ src/main/java/nl/improved/sqlclient/commands/InfoCommand.java 2008-02-26 20:43:14 UTC (rev 239) @@ -94,4 +94,8 @@ public boolean abort() { return false; } + @Override + public boolean backgroundProcessSupported() { + return false; + } } Modified: src/main/java/nl/improved/sqlclient/commands/ShowCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/ShowCommand.java 2008-02-19 20:02:17 UTC (rev 238) +++ src/main/java/nl/improved/sqlclient/commands/ShowCommand.java 2008-02-26 20:43:14 UTC (rev 239) @@ -141,4 +141,8 @@ public boolean abort() { return false; // not implemented } + @Override + public boolean backgroundProcessSupported() { + return false; + } } |
From: SVN by r. <sv...@ca...> - 2008-03-18 21:18:54
|
Author: roy Date: 2008-03-18 22:18:43 +0100 (Tue, 18 Mar 2008) New Revision: 255 Modified: src/main/java/nl/improved/sqlclient/SQLShell.java src/main/java/nl/improved/sqlclient/SQLUtil.java src/main/java/nl/improved/sqlclient/TabCompletionInfo.java src/main/java/nl/improved/sqlclient/commands/ShowCommand.java Log: small refector step to rename UNKNOWN to OTHER added tab completion for connect @.. Modified: src/main/java/nl/improved/sqlclient/SQLShell.java =================================================================== --- src/main/java/nl/improved/sqlclient/SQLShell.java 2008-03-18 20:56:18 UTC (rev 254) +++ src/main/java/nl/improved/sqlclient/SQLShell.java 2008-03-18 21:18:43 UTC (rev 255) @@ -22,6 +22,7 @@ import java.util.Arrays; import java.util.ArrayList; import java.util.Iterator; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.LinkedHashMap; @@ -720,7 +721,7 @@ if (info.getMatchType() == TabCompletionInfo.MatchType.COLUMN_NAMES) { return nullToEmpty(findMatch(getColumnNames(info.getPossibleMatches()), info.getStart())); } - if (info.getMatchType() == TabCompletionInfo.MatchType.UNKNOWN) { + if (info.getMatchType() == TabCompletionInfo.MatchType.OTHER) { return nullToEmpty(findMatch(info.getPossibleMatches(), info.getStart())); } Toolkit.beep(); @@ -964,6 +965,15 @@ */ @Override public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { + List commandInfo = command.getLines(); + + String startOfCommand = SQLUtil.getStartOfCommand(commandInfo, commandPoint); + if (startOfCommand.indexOf('@') >= 0) { + String end = startOfCommand.substring(startOfCommand.lastIndexOf('@')+1); + List<String> identifiers = new ArrayList<String>(DBConnector.getInstance().getPredefinedConnectionIdentifiers()); + Collections.sort(identifiers); + return new TabCompletionInfo(TabCompletionInfo.MatchType.OTHER, identifiers, end); + } return null; } @@ -1448,7 +1458,7 @@ dirName = "."; } } - return new TabCompletionInfo(TabCompletionInfo.MatchType.UNKNOWN,Arrays.asList(new File(dirName).list()) , fileName); + return new TabCompletionInfo(TabCompletionInfo.MatchType.OTHER,Arrays.asList(new File(dirName).list()) , fileName); } @Override Modified: src/main/java/nl/improved/sqlclient/SQLUtil.java =================================================================== --- src/main/java/nl/improved/sqlclient/SQLUtil.java 2008-03-18 20:56:18 UTC (rev 254) +++ src/main/java/nl/improved/sqlclient/SQLUtil.java 2008-03-18 21:18:43 UTC (rev 255) @@ -275,7 +275,7 @@ String columns = startOfCommand.substring(upperStart.indexOf("SELECT")+"SELECT".length(), upperStart.indexOf("FROM")).replaceAll(" ",""); return new TabCompletionInfo(TabCompletionInfo.MatchType.COLUMN_NAMES, Arrays.asList(columns.split(","))); } - return new TabCompletionInfo(TabCompletionInfo.MatchType.UNKNOWN, Arrays.asList(new String[0])); + return new TabCompletionInfo(TabCompletionInfo.MatchType.OTHER, Arrays.asList(new String[0])); } public static String getStartOfCommand(List<? extends CharSequence> commandInfo, Point commandPoint) { Modified: src/main/java/nl/improved/sqlclient/TabCompletionInfo.java =================================================================== --- src/main/java/nl/improved/sqlclient/TabCompletionInfo.java 2008-03-18 20:56:18 UTC (rev 254) +++ src/main/java/nl/improved/sqlclient/TabCompletionInfo.java 2008-03-18 21:18:43 UTC (rev 255) @@ -18,7 +18,7 @@ import java.util.List; public class TabCompletionInfo { - public enum MatchType {SQL_KEYWORD, TABLE_NAMES, COLUMN_NAMES, FILE_NAMES, UNKNOWN} + public enum MatchType {SQL_KEYWORD, TABLE_NAMES, COLUMN_NAMES, FILE_NAMES, OTHER} private MatchType type; private List<String> possibleMatches; Modified: src/main/java/nl/improved/sqlclient/commands/ShowCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/ShowCommand.java 2008-03-18 20:56:18 UTC (rev 254) +++ src/main/java/nl/improved/sqlclient/commands/ShowCommand.java 2008-03-18 21:18:43 UTC (rev 255) @@ -122,9 +122,9 @@ String startOfCommand = SQLUtil.getStartOfCommand(command.getLines(), commandPoint); String end = startOfCommand.substring(startOfCommand.lastIndexOf(' ')+1); if (commandStringUpper.matches("SHOW[\\s]+(|T|TA|TAB|TABL|TABLE)")) { - return new TabCompletionInfo(TabCompletionInfo.MatchType.UNKNOWN, Arrays.asList(new String[]{"TABLES"}), end); + return new TabCompletionInfo(TabCompletionInfo.MatchType.OTHER, Arrays.asList(new String[]{"TABLES"}), end); } - return new TabCompletionInfo(TabCompletionInfo.MatchType.UNKNOWN, Arrays.asList(new String[]{"HAVING"}), end); + return new TabCompletionInfo(TabCompletionInfo.MatchType.OTHER, Arrays.asList(new String[]{"HAVING"}), end); } /** |
From: SVN by r. <sv...@ca...> - 2008-04-04 18:33:16
|
Author: roy Date: 2008-04-04 20:33:05 +0200 (Fri, 04 Apr 2008) New Revision: 259 Modified: src/main/java/nl/improved/sqlclient/ src/main/java/nl/improved/sqlclient/commands/DescCommand.java Log: added @Override Property changes on: src/main/java/nl/improved/sqlclient ___________________________________________________________________ Name: svn:ignore - .SQLPlusPlus.java.swp .SQLPlus.java.swp .DBConnector.java.swp .SQLUtil.java.swp .Point.java.swp .SQLLineWrapper.java.swp .SQLOutput.java.swp .QueryExecutor.java.swp + .SQLPlusPlus.java.swp .SQLPlus.java.swp .DBConnector.java.swp .SQLUtil.java.swp .Point.java.swp .SQLLineWrapper.java.swp .SQLOutput.java.swp .QueryExecutor.java.swp .SQLShell.java.swp Modified: src/main/java/nl/improved/sqlclient/commands/DescCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/DescCommand.java 2008-04-04 11:07:07 UTC (rev 258) +++ src/main/java/nl/improved/sqlclient/commands/DescCommand.java 2008-04-04 18:33:05 UTC (rev 259) @@ -34,6 +34,7 @@ /** * Execute the describe command. */ + @Override public CharSequence execute(SQLCommand command) { java.sql.Connection conn = DBConnector.getInstance().getConnection(); String cmd = command.getCommandString(); |
From: SVN by r. <sv...@ca...> - 2009-01-16 19:46:53
|
Author: roy Date: 2009-01-16 20:46:42 +0100 (Fri, 16 Jan 2009) New Revision: 348 Added: src/main/java/nl/improved/sqlclient/commands/CommandResult.java src/main/java/nl/improved/sqlclient/commands/SimpleCommandResult.java Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java src/main/java/nl/improved/sqlclient/QueryExecutor.java src/main/java/nl/improved/sqlclient/SQLShell.java src/main/java/nl/improved/sqlclient/commands/Command.java src/main/java/nl/improved/sqlclient/commands/DescCommand.java src/main/java/nl/improved/sqlclient/commands/InfoCommand.java src/main/java/nl/improved/sqlclient/commands/ShowCommand.java Log: lot of refactoring in command classes results can now be paged (initial version) Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-01-15 20:09:47 UTC (rev 347) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-01-16 19:46:42 UTC (rev 348) @@ -438,7 +438,14 @@ repaint(); if (/*direct ||*/ !cmd.cmd.backgroundProcessSupported()) { try { - output(cmd.cmd.execute(cmd.sql)); + CommandResult result = cmd.cmd.execute(cmd.sql); + Iterator<CharSequence> iResult = result.getResult(); + while (iResult.hasNext()) { + output(iResult.next()); + } + if (!result.executedSuccessfully()) { + output("Execution Failed...\n"); + } } catch(Exception e) { error(e); } @@ -447,7 +454,14 @@ commandThread = new CommandThread(cmd.cmd) { @Override void execute() { - output(getCommand().execute(cmd.sql)); + CommandResult result = getCommand().execute(cmd.sql); + Iterator<CharSequence> iResult = result.getResult(); + while (iResult.hasNext()) { + output(iResult.next()); + } + if (!result.executedSuccessfully()) { + output("Execution Failed...\n"); + } repaint(); } }; @@ -1019,7 +1033,14 @@ } output(sqlCommand.getLines()); //repaint(); - output(command.execute(sqlCommand)); + CommandResult commandResult = command.execute(sqlCommand); + Iterator<CharSequence> result = commandResult.getResult(); + while (result.hasNext()) { + output(result.next()); + } + if (!commandResult.executedSuccessfully()) { + output("Execution Failed...\n"); + } repaint(); return true; } @@ -1100,7 +1121,7 @@ * @return a readable result of the execution of this command. */ @Override - public CharSequence execute(SQLCommand cmd) { + public CommandResult execute(SQLCommand cmd) { String command = cmd.getCommandString(); try { String cmdString = command.substring("connect".length()).trim(); @@ -1108,7 +1129,7 @@ cmdString = cmdString.substring(0, cmdString.length()-1); } if (connect(cmdString) == null) { - return "Connect failed. Unknown reason\n\n"; + return new SimpleCommandResult(false, "Connect failed. Unknown reason\n\n"); } } catch(SQLException e) { throw new IllegalStateException("Failed to connect: " + e.getMessage(), e); @@ -1116,12 +1137,11 @@ try { int tot = HistoryPersister.loadHistory(AbstractSQLShellWindow.this, ident, getScreen().MAX_LINE_LENGTH, getScreen().MAX_LINE_LENGTH); - return "Connected and history loaded (" + tot + " command(s)).\n\n"; + return new SimpleCommandResult(true, "Connected and history loaded (" + tot + " command(s)).\n\n"); } catch (CouldNotLoadHistoryException e) { // this.shell.setCommandIndex(0); - return "Connected (no history loaded).\n\n"; + return new SimpleCommandResult(true, "Connected (no history loaded).\n\n"); } - } @Override public CharSequence getCommandString() { @@ -1274,20 +1294,20 @@ private class DisConnectCommand implements Command { @Override - public CharSequence execute(SQLCommand cmd) { + public CommandResult execute(SQLCommand cmd) { try { DBConnector.getInstance().disconnect(); if (ident != null) { try { HistoryPersister.saveHistory(AbstractSQLShellWindow.this, ident, true); ident = null; - return "Disconnected (history saved).\n\n"; + return new SimpleCommandResult(true, "Disconnected (history saved).\n\n"); } catch (CouldNotSaveHistoryException e) { - return "Disconnected, could not save history: " + e.getMessage() - + "\n\n"; + return new SimpleCommandResult(false, "Disconnected, could not save history: " + e.getMessage() + + "\n\n"); } } - return "Disconnected"; + return new SimpleCommandResult(true, "Disconnected"); } catch(SQLException e) { throw new IllegalStateException("Failed to disconnect: " + e.getMessage(), e); } @@ -1326,7 +1346,7 @@ */ private class HistoryCommand implements Command { @Override - public CharSequence execute(SQLCommand command) { + public CommandResult execute(SQLCommand command) { StringBuffer returnValue = new StringBuffer(); Iterator<SQLCommand> iCommands = commandHistory.iterator(); returnValue.append("\n**** History Overview ****\n"); @@ -1342,8 +1362,9 @@ returnValue.append(cmdString); returnValue.append('\n'); } - return returnValue; + return new SimpleCommandResult(true, returnValue); } + @Override public CharSequence getCommandString() { return "history"; @@ -1384,11 +1405,11 @@ this.cmd = cmd; } @Override - public CharSequence execute(SQLCommand command) { + public CommandResult execute(SQLCommand command) { run = false; new DisConnectCommand().execute(null); close(); - return "Application terminated."; + return new SimpleCommandResult(true, "Application terminated."); } @Override public CharSequence getHelp() { @@ -1422,7 +1443,7 @@ */ private class HelpCommand implements Command { @Override - public CharSequence execute(SQLCommand sqlCommand) { + public CommandResult execute(SQLCommand sqlCommand) { // the execution of help consists of: // 1. is general help.. // 2. is detailed help about a specific command @@ -1451,21 +1472,21 @@ } } if (returnValue.length() == 0) { - return "Don't know what you mean by '"+ keyword+"'"; + return new SimpleCommandResult(false, "Don't know what you mean by '"+ keyword+"'"); } - return returnValue; + return new SimpleCommandResult(true, returnValue); } else { Iterator<Command> iCommands = commands.getCommands().iterator(); while (iCommands.hasNext()) { Command cmd= iCommands.next(); if (cmd.getCommandString().equals(cmdString)) { - return cmd.getCommandString()+": " + return new SimpleCommandResult(true, cmd.getCommandString()+": " + cmd.getHelp().toString().replaceAll("\n" - , "\n"+screen.getEmptyLine().substring(0, cmd.getCommandString().length()+3)); + , "\n"+screen.getEmptyLine().substring(0, cmd.getCommandString().length()+3))); } } } - return "Unkown command '"+ cmdString+"'"; + return new SimpleCommandResult(true, "Unkown command '"+ cmdString+"'"); } // default print all commands // TODO iterate @@ -1506,7 +1527,7 @@ " help -k searchstring (for example help -k column)\n"+ "This results in a list of commands matching the searchstring\n\n"; returnValue.insert(0, helpHeader); - return returnValue; + return new SimpleCommandResult(true, returnValue); } @Override public CharSequence getCommandString() { @@ -1639,7 +1660,7 @@ private String fileName; @Override - public CharSequence execute(SQLCommand cmd) { + public CommandResult execute(SQLCommand cmd) { String command = cmd.getCommandString(); String nextPart = command.substring("spool".length()).trim(); if (nextPart.equalsIgnoreCase("off")) { @@ -1648,9 +1669,9 @@ spoolWriter.close(); } catch(Exception e) {/*ignore*/} spoolWriter = null; - return "Spool closed."; + return new SimpleCommandResult(true, "Spool closed."); } else { - return "No spool to close."; + return new SimpleCommandResult(true, "No spool to close."); } } else { StringBuffer returnValue = new StringBuffer(100); @@ -1675,7 +1696,7 @@ throw new IllegalStateException("Failed to create spool ("+fileName+"): " + e.toString(), e); } returnValue.append("Spool to "+fileName+" created."); - return returnValue.toString(); + return new SimpleCommandResult(true, returnValue.toString()); } } @@ -1739,7 +1760,7 @@ private String fileName; @Override - public CharSequence execute(SQLCommand cmd) { + public CommandResult execute(SQLCommand cmd) { String command = cmd.getCommandString(); String nextPart = command.substring("dump".length()).trim(); String dumpFileName; @@ -1843,7 +1864,7 @@ out.close(); } } - return "Dump to "+fileName+" done. ("+ rowCount+" rows written)"; + return new SimpleCommandResult(true, "Dump to "+fileName+" done. ("+ rowCount+" rows written)"); } @Override @@ -1889,7 +1910,7 @@ private String fileName; @Override - public CharSequence execute(SQLCommand cmd) { + public CommandResult execute(SQLCommand cmd) { String command = cmd.getCommandString(); String nextPart = command.substring("read".length()).trim(); String dumpFileName; @@ -1993,7 +2014,7 @@ } catch (Exception e) { throw new IllegalStateException("Failed to read dump ("+fileName+"): " + e.toString(), e); } - return "Read from "+fileName+" done. (" + rowCount+" rows imported)"; + return new SimpleCommandResult(true, "Read from "+fileName+" done. (" + rowCount+" rows imported)"); } @Override @@ -2038,7 +2059,7 @@ } @Override - public CharSequence execute(SQLCommand sqlCommand) { + public CommandResult execute(SQLCommand sqlCommand) { cancelled = false; currentCommand = null; String command = sqlCommand.getCommandString(); @@ -2050,20 +2071,32 @@ BufferedReader reader = new BufferedReader(new InputStreamReader(fin)); StringBuffer cmd = new StringBuffer(); String line; + int errorCount = 0; while ( ((line = reader.readLine()) != null)) { if (cancelled) { - return "Aborted"; + return new SimpleCommandResult(true, "Aborted"); } if (line.startsWith("--")) { continue; } cmd.append(line); - if (line.endsWith(";")) { - // Exec cmd + //if (line.endsWith(";")) { String commandString = cmd.toString(); currentCommand = sqlShell.createCommand(commandString); + if (currentCommand == null) { + continue; + } + // Exec cmd sqlShell.output(commandString); - sqlShell.output(currentCommand.execute(new InputCommand(commandString))); + CommandResult result = currentCommand.execute(new InputCommand(commandString)); + Iterator<CharSequence> output = result.getResult(); + while (output.hasNext()) { + sqlShell.output(output.next()); + } + if (!result.executedSuccessfully()) { + errorCount++; + sqlShell.output("Execution Failed...\n"); + } cmd=new StringBuffer(); new Thread() { @Override @@ -2071,19 +2104,19 @@ sqlShell.repaint(); } }.start(); - } + //} } if (cancelled) { - return "Execution of file '" + toFileName(command.substring(1)) +"' aborted...."; + return new SimpleCommandResult(true, "Execution of file '" + toFileName(command.substring(1)) +"' aborted...."); } if (cmd.toString().trim().length() > 0) { - return "File '"+ toFileName(command.substring(1)) +"' missing a ';' at the end of the last command"; + return new SimpleCommandResult(false, "File '"+ toFileName(command.substring(1)) +"' missing a ';' at the end of the last command"); } else { - return "File '" + toFileName(command.substring(1)) +"' executed successfully."; + return new SimpleCommandResult(true, "File '" + toFileName(command.substring(1)) +"' executed " + (errorCount > 0 ? "with "+ errorCount+" errors." : "successfully.")); } } catch(IOException e) { sqlShell.error(e); - return "File '" + toFileName(command.substring(1)) +"' ended with errors."; + return new SimpleCommandResult(true, "File '" + toFileName(command.substring(1)) +"' ended with errors."); } finally { if (fin != null) try { fin.close();}catch(Exception e) {/*ignore*/} } @@ -2131,13 +2164,13 @@ * Simple command to save the current visible screen history (commands and it"s output). */ private class SaveCommand implements Command { - public CharSequence execute(SQLCommand cmd) { + public CommandResult execute(SQLCommand cmd) { String command = cmd.getCommandString().substring("save".length()).trim(); if (command.startsWith("history")) { String fileName = toFileName(command.substring("history".length()).trim()); File f = new File(fileName); if (f.exists() && !f.canWrite()) { - return "Unable to overwrite existing file : " + f.getAbsolutePath(); + return new SimpleCommandResult(false, "Unable to overwrite existing file : " + f.getAbsolutePath()); } FileWriter writer = null; try { @@ -2146,10 +2179,10 @@ writer.write(c.toString()); writer.write('\n'); } - return "History successfully written to : "+ f.getAbsolutePath(); + return new SimpleCommandResult(true, "History successfully written to : "+ f.getAbsolutePath()); } catch (IOException ex) { Logger.getLogger(AbstractSQLShellWindow.class.getName()).log(Level.SEVERE, null, ex); - return "Unable to write to file: "+ f.getAbsolutePath() +"("+ ex+")"; + return new SimpleCommandResult(false, "Unable to write to file: "+ f.getAbsolutePath() +"("+ ex+")"); } finally { if (writer != null) { try { @@ -2281,22 +2314,33 @@ * @return the result of the sql query. */ @Override - public CharSequence execute(SQLCommand cmd) { + public CommandResult execute(SQLCommand cmd) { try { - String command = cmd.getCommandString(); + final String command = cmd.getCommandString(); if (command.length() > "select".length() && "select".equalsIgnoreCase(command.subSequence(0, "create".length()).toString())) { - return DBConnector.getInstance().getQueryExecutor().executeQuery(command); + return new CommandResult() { + public boolean executedSuccessfully() { + return true; + } + public Iterator<CharSequence> getResult() { + try { + return DBConnector.getInstance().getQueryExecutor().executeQuery(command); + } catch (SQLException ex) { + return null; + } + } + }; } if (statementExecutor == null) { statementExecutor = new StatementExecutor(); } - return statementExecutor.execute(command); + return new SimpleCommandResult(true, statementExecutor.execute(command)); } catch(SQLException e) { error(e); - return ""; + return new SimpleCommandResult(false, ""); } catch(IllegalStateException e) { error(e); - return ""; + return new SimpleCommandResult(false, ""); } } Modified: src/main/java/nl/improved/sqlclient/QueryExecutor.java =================================================================== --- src/main/java/nl/improved/sqlclient/QueryExecutor.java 2009-01-15 20:09:47 UTC (rev 347) +++ src/main/java/nl/improved/sqlclient/QueryExecutor.java 2009-01-16 19:46:42 UTC (rev 348) @@ -26,6 +26,7 @@ import java.util.ArrayList; import java.text.DateFormat; import java.text.SimpleDateFormat; +import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; import nl.improved.sqlclient.util.ResultBuilder; @@ -90,28 +91,6 @@ } /** - * Returns the width at wich a column should be displayed. - * Usually the ResultSetMetaData will be responsible for this width, but a few exceptions - * are made (this would typicall be the case for dates). - * A minimum of 4 is used, so that NULL values won't break the layout. - * @param metadata the metadata describing the resultset - * @param column the column to check - * @return the width in characters that should be used to display the column. - */ - private int getColumnWidth(ResultSetMetaData metadata, int column) throws SQLException { - switch (metadata.getColumnType(column)) { - case Types.DATE: - return dateFormat.length(); - case Types.TIMESTAMP: - return timestampFormat.length(); - case Types.TIME: - return timeFormat.length(); - } - // Let's assume for now that most columns CAN actually contain NULL values, and therefore we want every column to have a minimum width of 4 - return Math.max(4, metadata.getColumnDisplaySize(column)); - } - - /** * Returns the value to display. * This deals with alignment for numeric columns, formatting for dates and special * treatment for NULL values. @@ -180,7 +159,7 @@ * @return the formatted result. * @throws SQLException if the database could not execute the SQL query for some reason. */ - protected CharSequence executeQuery(CharSequence command) throws SQLException { + protected Iterator<CharSequence> executeQuery(CharSequence command) throws SQLException { cancelled = false; ResultSet results = DBConnector.getInstance().getStatement().executeQuery(command.toString()); @@ -197,28 +176,74 @@ labels.add(metadata.getColumnLabel(col)); } - ResultBuilder displayValue = new ResultBuilder(); - displayValue.setHeader(labels); - int rowCount = 0; - while (results.next() && !cancelled) { - for (int col = 1; col <= metadata.getColumnCount(); col++ ) { - displayValue.set(col-1, rowCount, getDisplayValue(results, col), isNumeric(metadata, col) ? ResultBuilder.Alignment.RIGHT : ResultBuilder.Alignment.LEFT); - //try {Thread.sleep(10);} catch(Exception e2) {} + return new QueryExecutorIterator(results, labels, metadata); + } + + private class QueryExecutorIterator implements Iterator<CharSequence> { + + private ResultSet results; + private List<String> labels; + private int rowCount = 0; + private int columnCount; + private long start = System.currentTimeMillis(); + private ResultSetMetaData metadata; + private boolean next = true; + + public QueryExecutorIterator(ResultSet results, List<String> labels, ResultSetMetaData metadata) throws SQLException { + this.results = results; + this.labels = labels; + this.metadata = metadata; + columnCount = metadata.getColumnCount(); + } + + + + public boolean hasNext() { + return next; + } + + public CharSequence next() { + try { + next = false; + ResultBuilder displayValue = new ResultBuilder(); + displayValue.setHeader(labels); + int max = 1000; + while (results.next() && !cancelled) { + for (int col = 1; col <= columnCount; col++ ) { + displayValue.set(col-1, rowCount, getDisplayValue(results, col), isNumeric(metadata, col) ? ResultBuilder.Alignment.RIGHT : ResultBuilder.Alignment.LEFT); + //try {Thread.sleep(10);} catch(Exception e2) {} + } + rowCount++; + if (rowCount % max == 0) { + next = true; + break; + } + } + if (!next) { + StringBuilder footer = new StringBuilder(); + footer.append(rowCount); + footer.append(" row"); + if (rowCount != 1) { + footer.append("s"); + } + footer.append(" selected.\n"); + if (cancelled) { + footer.append("Aborted....\n"); + } + footer.append("Query took: "+ (System.currentTimeMillis() - start) +" millis\n\n"); + displayValue.setFooter(footer); + } else { + displayValue.setFooter("More...\n\n"); + } + return displayValue.toString(); + } catch(SQLException e) { + return null; } - rowCount++; } - StringBuilder footer = new StringBuilder(); - footer.append(rowCount); - footer.append(" row"); - if (rowCount != 1) { - footer.append("s"); + + public void remove() { + throw new UnsupportedOperationException("Not supported yet."); } - footer.append(" selected.\n"); - if (cancelled) { - footer.append("Aborted....\n"); - } - footer.append("Query took: "+ (System.currentTimeMillis() - start) +" millis\n\n"); - displayValue.setFooter(footer); - return displayValue.toString(); + } } Modified: src/main/java/nl/improved/sqlclient/SQLShell.java =================================================================== --- src/main/java/nl/improved/sqlclient/SQLShell.java 2009-01-15 20:09:47 UTC (rev 347) +++ src/main/java/nl/improved/sqlclient/SQLShell.java 2009-01-16 19:46:42 UTC (rev 348) @@ -90,12 +90,12 @@ } }; Command cmd = new nl.improved.sqlclient.AbstractSQLShellWindow.ExecuteBatchCommand(sqlshellWindow); - CharSequence output = cmd.execute(new SQLCommand("@"+ argsMap.get("-i"))); + cmd.execute(new SQLCommand("@"+ argsMap.get("-i"))); if (!argsMap.containsKey("-o")) { for (CharSequence s : sqlshellWindow.getScreen().getScreenBuffer()) { System.out.println(s); } - System.out.println(output); + //System.out.println(output); } else { File f = new File(argsMap.get("-o")); FileOutputStream fout = new FileOutputStream(f); @@ -103,8 +103,8 @@ fout.write(s.toString().getBytes()); fout.write('\n'); } - fout.write(output.toString().getBytes()); - fout.write('\n'); + //fout.write(output.toString().getBytes()); + //fout.write('\n'); } } else { //sqlshellWindow = new SQLShellWindow(); Modified: src/main/java/nl/improved/sqlclient/commands/Command.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/Command.java 2009-01-15 20:09:47 UTC (rev 347) +++ src/main/java/nl/improved/sqlclient/commands/Command.java 2009-01-16 19:46:42 UTC (rev 348) @@ -27,7 +27,7 @@ * @param command the command to execute * @return a readable result so the user knows what happened */ - CharSequence execute(SQLCommand cmd); + CommandResult execute(SQLCommand cmd); /** * Return the command key (like quit, help, connect) that should show up in the help list. * @return the command key that should show up in the help list. Added: src/main/java/nl/improved/sqlclient/commands/CommandResult.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/CommandResult.java 2009-01-15 20:09:47 UTC (rev 347) +++ src/main/java/nl/improved/sqlclient/commands/CommandResult.java 2009-01-16 19:46:42 UTC (rev 348) @@ -0,0 +1,18 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package nl.improved.sqlclient.commands; + +import java.util.Iterator; + +/** + * + * @author roy + */ +public interface CommandResult { + + boolean executedSuccessfully(); + Iterator<CharSequence> getResult(); +} Modified: src/main/java/nl/improved/sqlclient/commands/DescCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/DescCommand.java 2009-01-15 20:09:47 UTC (rev 347) +++ src/main/java/nl/improved/sqlclient/commands/DescCommand.java 2009-01-16 19:46:42 UTC (rev 348) @@ -35,7 +35,7 @@ * Execute the describe command. */ @Override - public CharSequence execute(SQLCommand command) { + public CommandResult execute(SQLCommand command) { java.sql.Connection conn = DBConnector.getInstance().getConnection(); String cmd = command.getCommandString(); if (cmd.endsWith(";")) { @@ -69,7 +69,7 @@ .getTables(conn.getCatalog(), DBConnector.getInstance().getSchema() , tableName, new String[]{"TABLE"}); if (!rs.next()) { - return "Failed to find table '"+tableName+"'"; + return new SimpleCommandResult(false, "Failed to find table '"+tableName+"'"); } } else { rs = conn.getMetaData().getPrimaryKeys(conn.getCatalog(), DBConnector.getInstance().getSchema(), tableName); @@ -95,7 +95,7 @@ } catch (SQLException ex) { throw new IllegalStateException("Failed to find columnnames for table: "+ tableName, ex); } - return result.toString(); + return new SimpleCommandResult(true, result.toString()); } /** Modified: src/main/java/nl/improved/sqlclient/commands/InfoCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/InfoCommand.java 2009-01-15 20:09:47 UTC (rev 347) +++ src/main/java/nl/improved/sqlclient/commands/InfoCommand.java 2009-01-16 19:46:42 UTC (rev 348) @@ -34,13 +34,13 @@ * @return the info of the connection */ @Override - public CharSequence execute(SQLCommand cmd) { + public CommandResult execute(SQLCommand cmd) { java.sql.Connection conn; try { conn = DBConnector.getInstance().getConnection(); } catch(IllegalStateException e) { - return "This command shows information about the current connection.\nCurrently SQLShell is not connected to a database server.\n"+ - "Please use the connect command to create a connection"; + return new SimpleCommandResult(false, "This command shows information about the current connection.\nCurrently SQLShell is not connected to a database server.\n"+ + "Please use the connect command to create a connection"); } StringBuffer returnValue = new StringBuffer(); try { @@ -64,7 +64,7 @@ throw new IllegalStateException("Failed to find table info: "+ ex, ex); } returnValue.append("\n"); - return returnValue; + return new SimpleCommandResult(true, returnValue); } /** Modified: src/main/java/nl/improved/sqlclient/commands/ShowCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/ShowCommand.java 2009-01-15 20:09:47 UTC (rev 347) +++ src/main/java/nl/improved/sqlclient/commands/ShowCommand.java 2009-01-16 19:46:42 UTC (rev 348) @@ -35,7 +35,7 @@ * Execute the describe command. */ @Override - public CharSequence execute(SQLCommand command) { + public CommandResult execute(SQLCommand command) { java.sql.Connection conn = DBConnector.getInstance().getConnection(); String cmd = command.getCommandString(); if (cmd.endsWith(";")) { @@ -82,7 +82,7 @@ returnValue.append('\n'); } returnValue.append("DONE\n"); - return returnValue.toString(); + return new SimpleCommandResult(true, returnValue.toString()); } catch(SQLException e) { throw new IllegalStateException("Failed to find tablenames" , e); } @@ -104,7 +104,7 @@ } else { returnValue.append("Don't know what to show for: '"+ cmd.substring(cmd.lastIndexOf(' ')).trim()+"'\n"); } - return returnValue; + return new SimpleCommandResult(true, returnValue); } /** Added: src/main/java/nl/improved/sqlclient/commands/SimpleCommandResult.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/SimpleCommandResult.java 2009-01-15 20:09:47 UTC (rev 347) +++ src/main/java/nl/improved/sqlclient/commands/SimpleCommandResult.java 2009-01-16 19:46:42 UTC (rev 348) @@ -0,0 +1,33 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package nl.improved.sqlclient.commands; + +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +/** + * + * @author roy + */ +public class SimpleCommandResult implements CommandResult { + private boolean success; + private CharSequence result; + + public SimpleCommandResult(boolean success, CharSequence result) { + this.success = success; + this.result = result; + } + + public boolean executedSuccessfully() { + return success; + } + + public Iterator<CharSequence> getResult() { + List<CharSequence> list = Arrays.asList(new CharSequence[]{result}); + return list.iterator(); + } +} |