You can subscribe to this list here.
2007 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
(8) |
Oct
(34) |
Nov
(7) |
Dec
(2) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2008 |
Jan
(29) |
Feb
(10) |
Mar
(14) |
Apr
(4) |
May
(2) |
Jun
|
Jul
(14) |
Aug
(25) |
Sep
(6) |
Oct
(18) |
Nov
(4) |
Dec
(14) |
2009 |
Jan
(28) |
Feb
(15) |
Mar
(15) |
Apr
(8) |
May
|
Jun
|
Jul
(1) |
Aug
(4) |
Sep
(12) |
Oct
(1) |
Nov
|
Dec
(22) |
2010 |
Jan
(14) |
Feb
|
Mar
(2) |
Apr
|
May
(7) |
Jun
|
Jul
(3) |
Aug
(1) |
Sep
|
Oct
|
Nov
|
Dec
|
From: SVN by r. <sv...@ca...> - 2009-09-30 18:15:03
|
Author: roy Date: 2009-09-30 20:14:51 +0200 (Wed, 30 Sep 2009) New Revision: 426 Added: src/test/java/nl/improved/sqlclient/util/ResultBuilderTest.java Modified: src/main/java/nl/improved/sqlclient/util/ResultBuilder.java Log: fix output when no rows returned added unit tests Modified: src/main/java/nl/improved/sqlclient/util/ResultBuilder.java =================================================================== --- src/main/java/nl/improved/sqlclient/util/ResultBuilder.java 2009-09-30 17:50:15 UTC (rev 425) +++ src/main/java/nl/improved/sqlclient/util/ResultBuilder.java 2009-09-30 18:14:51 UTC (rev 426) @@ -105,10 +105,13 @@ result.append(horizontalSeperator); } } - result.append('\n'); Iterator<Cell> cells = rows.iterator(); int prevRow = 0; - result.append(verticalSeparator); + boolean rowsAvailable = cells.hasNext(); + if (rowsAvailable) { + result.append('\n'); + result.append(verticalSeparator); + } while (cells.hasNext()) { Cell cell = cells.next(); if (cell != null && cell.row != prevRow) { @@ -137,12 +140,12 @@ } } result.append('\n'); - if (horizontalSeperatorEnabled) { + if (rowsAvailable && horizontalSeperatorEnabled) { for (int i = 0; i < rowLength-1; i++) { result.append(horizontalSeperator); } + result.append('\n'); } - result.append('\n'); if (footer != null) { result.append(footer); result.append('\n'); Added: src/test/java/nl/improved/sqlclient/util/ResultBuilderTest.java =================================================================== --- src/test/java/nl/improved/sqlclient/util/ResultBuilderTest.java 2009-09-30 17:50:15 UTC (rev 425) +++ src/test/java/nl/improved/sqlclient/util/ResultBuilderTest.java 2009-09-30 18:14:51 UTC (rev 426) @@ -0,0 +1,56 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package nl.improved.sqlclient.util; + +import java.util.Arrays; +import junit.framework.TestCase; +import nl.improved.sqlclient.util.ResultBuilder.Alignment; + +/** + * + * @author roy + */ +public class ResultBuilderTest extends TestCase { + + public ResultBuilderTest(String testName) { + super(testName); + } + + + /** + * Test of toString method, of class ResultBuilder. + */ + public void testToString() { + ResultBuilder instance = new ResultBuilder(); + instance.setHeader(Arrays.asList(new String[]{"ID"})); + String expected = + "----\n" + + "|ID|\n"+ + "----\n" ; + assertEquals(expected, instance.toString()); + expected = + "----\n" + + "|ID|\n"+ + "----\n" + + "| 1|\n"+ + "----\n" ; + instance.set(0, 0, "1", Alignment.RIGHT); + assertEquals(expected, instance.toString()); + expected = + "----\n" + + "|ID|\n"+ + "----\n" + + "| 1|\n"+ + "----\n"+ + "F\n"; + instance.setFooter("F"); + //System.out.println("---------"); + //System.out.println(instance.toString()); + //System.out.println("---------"); + assertEquals(expected, instance.toString()); + } + +} |
From: SVN by r. <sv...@ca...> - 2009-09-30 17:50:25
|
Author: roy Date: 2009-09-30 19:50:15 +0200 (Wed, 30 Sep 2009) New Revision: 425 Modified: src/main/java/nl/improved/sqlclient/commands/DescCommand.java Log: fixes in separators Modified: src/main/java/nl/improved/sqlclient/commands/DescCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/DescCommand.java 2009-09-26 13:39:06 UTC (rev 424) +++ src/main/java/nl/improved/sqlclient/commands/DescCommand.java 2009-09-30 17:50:15 UTC (rev 425) @@ -43,8 +43,10 @@ } String tableName = DBConnector.getInstance().translateDbVar(cmd.substring(cmd.lastIndexOf(' ')).trim()); ResultBuilder result = new ResultBuilder(); - result.setHorizontalSeparatorEnabled(false); - result.setVerticalSeparator(' '); + boolean oldEnabled = ResultBuilder.getHorizontalSeparatorEnabled(); + char oldChar = ResultBuilder.getVerticalSeparator(); + ResultBuilder.setHorizontalSeparatorEnabled(false); + ResultBuilder.setVerticalSeparator(' '); boolean foundMatch = false; try { ResultSet rs = conn.getMetaData().getColumns(conn.getCatalog(), DBConnector.getInstance().getSchema(), tableName, "%"); @@ -67,7 +69,7 @@ if (!foundMatch) { rs = conn.getMetaData() .getTables(conn.getCatalog(), DBConnector.getInstance().getSchema() - , tableName, new String[]{"TABLE"}); + , tableName, null); if (!rs.next()) { return new SimpleCommandResult(false, "Failed to find table '"+tableName+"'"); } @@ -92,10 +94,13 @@ } result.setFooter(footer); } + return new SimpleCommandResult(true, result.toString()); } catch (SQLException ex) { throw new IllegalStateException("Failed to find columnnames for table: "+ tableName, ex); + } finally { + ResultBuilder.setHorizontalSeparatorEnabled(oldEnabled); + ResultBuilder.setVerticalSeparator(oldChar); } - return new SimpleCommandResult(true, result.toString()); } /** |
From: SVN by r. <sv...@ca...> - 2009-09-26 14:06:08
|
Author: roy Date: 2009-09-26 15:39:06 +0200 (Sat, 26 Sep 2009) New Revision: 424 Modified: ChangeLog Log: mention changes Modified: ChangeLog =================================================================== --- ChangeLog 2009-09-26 13:29:39 UTC (rev 423) +++ ChangeLog 2009-09-26 13:39:06 UTC (rev 424) @@ -4,6 +4,8 @@ - added support for aliases in table names * Added initial settings command (to change for the current login session) the horizontal or vertical separator character * Added initial support for variables (in settings command.. see 'help set' for more information) + * History completion + * dump as <filename> support added 0.6.2 (2009-02-20) * Commandline input support |
From: SVN by r. <sv...@ca...> - 2009-09-26 13:29:54
|
Author: roy Date: 2009-09-26 15:29:39 +0200 (Sat, 26 Sep 2009) New Revision: 423 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java src/main/java/nl/improved/sqlclient/history/HistoryPersister.java Log: clean up code for history some more history fixes Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-09-26 12:51:06 UTC (rev 422) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-09-26 13:29:39 UTC (rev 423) @@ -69,10 +69,6 @@ */ private List<SQLCommand> commandHistory = new LimitedArrayList<SQLCommand>(50); /** - * Index for browsing commands. - */ - private int commandIndex = 0; - /** * Some debug info holding the last trace of an exception. */ private String lastExceptionDetails; @@ -192,8 +188,8 @@ specialActionKeys.put(InputKey.SpecialKey.UP, new KeyAction() { @Override public void execute() { - if (commandIndex > 0) { - commandLines = commandHistory.get(--commandIndex); + if (commandHistory.indexOf(commandLines) > 0) { + commandLines = commandHistory.get(commandHistory.indexOf(commandLines)-1); Point cursorPosition = screen.getCursorPosition(); cursorPosition.y = commandLines.getLines().size()-1; CharSequence lineBuffer = commandLines.getLines().get(cursorPosition.y); @@ -208,8 +204,8 @@ specialActionKeys.put(InputKey.SpecialKey.DOWN, new KeyAction() { @Override public void execute() { - if (commandIndex < commandHistory.size()-1) { - commandLines = commandHistory.get(++commandIndex); + if (commandHistory.indexOf(commandLines) < commandHistory.size()-1) { + commandLines = commandHistory.get(commandHistory.indexOf(commandLines)+1); Point cursorPosition = screen.getCursorPosition(); cursorPosition.y = commandLines.getLines().size()-1; CharSequence lineBuffer = commandLines.getLines().get(cursorPosition.y); @@ -480,18 +476,6 @@ return commandHistory; } - public int getCommandIndex() { - return commandIndex; - } - - /** - * Change the current command index. - * @param i - */ - public void setCommandIndex(int i) { - this.commandIndex = i; - } - public abstract void show(); /** @@ -662,14 +646,13 @@ if (command.length() > 0 && command.charAt(0) == '/') { // search in history String matchPattern=".*"+command.substring(1,command.length())+".*"; for (int cIndex = commandHistory.size()-1; cIndex >=0; cIndex--) { - if (cIndex == commandIndex) { + if (cIndex == commandHistory.indexOf(commandLines)) { continue; // skip current command } SQLCommand newSqlCommand = commandHistory.get(cIndex); String commandString = newSqlCommand.getCommandString(); if (commandString.matches(matchPattern)) { commandHistory.remove(commandLines); - commandIndex = commandHistory.indexOf(newSqlCommand); commandLines = newSqlCommand; Point cursorPosition = screen.getCursorPosition(); cursorPosition.y = 0; @@ -681,9 +664,12 @@ beep(); // TODO clear search?? return; } else if (executeCommand(sqlCommand)) { + if (commandHistory.indexOf(sqlCommand) < commandHistory.size()-1) { + commandHistory.remove(sqlCommand); + commandHistory.add(sqlCommand); + } commandLines = new SQLCommand(); commandHistory.add(commandLines); - commandIndex = commandHistory.size()-1; newLine(); Point cursorPosition = screen.getCursorPosition(); cursorPosition.y = commandLines.getLines().size()-1; @@ -721,6 +707,9 @@ } else { Point cursorPosition = screen.getCursorPosition(); List<StringBuffer> editableLines = getEditableCommand().getEditableLines(); + if (editableLines.size() < cursorPosition.y) { + editableLines.add(new StringBuffer()); + } StringBuffer currentLine = editableLines.get(cursorPosition.y); if (cursorPosition.x > currentLine.length()) { for (int i = currentLine.length(); i < cursorPosition.x; i++) { @@ -780,16 +769,19 @@ * @return the editable version of the commandlines. */ protected SQLCommand getEditableCommand() { - if (commandIndex != commandHistory.size() -1) { + if (commandHistory.indexOf(commandLines) != commandHistory.size() -1) { SQLCommand current = commandLines; commandLines = new SQLCommand(); commandLines.getEditableLines().clear(); for (StringBuffer buf : current.getEditableLines()) { commandLines.getEditableLines().add(new StringBuffer(buf)); } + SQLCommand last = commandHistory.get(commandHistory.size()-1); + // clean up empty last + if (last.getLines().size() == 1 && last.getLines().get(0).length() == 0) { + commandHistory.remove(last); + } commandHistory.add(commandLines); - commandIndex = commandHistory.size() -1; - } return commandLines; } Modified: src/main/java/nl/improved/sqlclient/history/HistoryPersister.java =================================================================== --- src/main/java/nl/improved/sqlclient/history/HistoryPersister.java 2009-09-26 12:51:06 UTC (rev 422) +++ src/main/java/nl/improved/sqlclient/history/HistoryPersister.java 2009-09-26 13:29:39 UTC (rev 423) @@ -27,7 +27,6 @@ import nl.improved.sqlclient.AbstractSQLShellWindow; import nl.improved.sqlclient.SQLCommand; -import nl.improved.sqlclient.SQLShell; import nl.improved.sqlclient.history.exception.CouldNotLoadHistoryException; import nl.improved.sqlclient.history.exception.CouldNotSaveHistoryException; @@ -84,7 +83,7 @@ } log("ok 2"); r.close(); - shell.setCommandIndex(history.size() - 1); + //shell.setCommandIndex(history.size() - 1); return tot; } catch (IOException e) { history.add(EMPTY_COMMAND); @@ -102,7 +101,6 @@ public static void saveHistory(final AbstractSQLShellWindow shell, final String key, final boolean excludeLastCommand) throws CouldNotSaveHistoryException { List<SQLCommand> history = shell.getCommandHistory(); - int commandIndex = shell.getCommandIndex(); log("saving history... (" + history.size() + " commands)"); |
From: SVN by r. <sv...@ca...> - 2009-09-26 12:51:30
|
Author: roy Date: 2009-09-26 14:51:06 +0200 (Sat, 26 Sep 2009) New Revision: 422 Added: src/main/java/nl/improved/sqlclient/commands/DumpCommand.java src/main/java/nl/improved/sqlclient/commands/ReadCommand.java src/main/java/nl/improved/sqlclient/commands/ReadDumpCommand.java src/test/java/nl/improved/sqlclient/commands/DumpCommandTest.java Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java Log: unit test for dump command added support for dump as <filename> fixed 'where clause' in dump Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-09-22 18:54:54 UTC (rev 421) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-09-26 12:51:06 UTC (rev 422) @@ -21,21 +21,14 @@ import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; -import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.sql.Connection; -import java.sql.Date; -import java.sql.PreparedStatement; import java.sql.ResultSet; -import java.sql.ResultSetMetaData; import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Types; -import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.ArrayList; import java.util.Iterator; @@ -47,14 +40,6 @@ import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.sax.SAXTransformerFactory; -import javax.xml.transform.sax.TransformerHandler; -import javax.xml.transform.stream.StreamResult; import nl.improved.sqlclient.DBConnector.ConnectionSettings; import nl.improved.sqlclient.commands.*; import nl.improved.sqlclient.history.HistoryPersister; @@ -63,14 +48,6 @@ //import nl.improved.sqlclient.util.Function; import nl.improved.sqlclient.util.LimitedArrayList; //import nl.improved.sqlclient.util.oracle.Functions; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.AttributesImpl; -import sun.misc.BASE64Decoder; -import sun.misc.BASE64Encoder; /** * The SQLShell abstract main class. @@ -1597,7 +1574,7 @@ * @param fileName the filename to convert * @return the converted filename */ - private static String toFileName(String fileName) { + public static String toFileName(String fileName) { if (fileName.startsWith("~/")) { return System.getProperty("user.home")+fileName.substring(1); } @@ -1610,7 +1587,7 @@ * @param otherMatches an optional list of other matches that are not filenames * @return the tabcompletion information found based on the filename prefix and other matches (optional) */ - private static TabCompletionInfo getFileNameTabCompletionInfo(String fileNamePrefix, String... otherMatches) { + public static TabCompletionInfo getFileNameTabCompletionInfo(String fileNamePrefix, String... otherMatches) { String dirName; if (fileNamePrefix.equals("")) { fileNamePrefix = "."; @@ -1768,330 +1745,10 @@ } @Override public boolean backgroundProcessSupported() { - return false; + return true; // must be placed at the end of the background command list } } - private abstract class ReadDumpCommand implements Command { - public static final String DATE_FORMAT = "yyyyMMddHHmmss"; - boolean isBinary(int columnType) { - if (columnType == Types.BINARY || - columnType == Types.BLOB || - columnType == Types.CLOB || - //columnType == Types.LONGNVARCHAR || // jdk 1.6 - columnType == Types.LONGVARBINARY || - columnType == Types.LONGVARCHAR || - //columnType == Types.NCLOB || // jdk 1.6 - columnType == Types.OTHER) { - return true; - } - return false; - - } - } - /** - * Writes the result of a query into a dump file so that it can be read back. - */ - private class DumpCommand extends ReadDumpCommand { - private String fileName; - - @Override - public CommandResult execute(SQLCommand cmd) { - String command = cmd.getCommandString(); - String nextPart = command.substring("dump".length()).trim(); - String dumpFileName; - if (nextPart.indexOf(' ') > 0) { - dumpFileName = nextPart.substring(0, nextPart.indexOf(' ')); - } else { - dumpFileName = nextPart; - } - int rowCount = 0; - PrintWriter out = null; - try { - File f; - if (dumpFileName.toLowerCase().endsWith(".dmp")) { - f = new File(toFileName(dumpFileName)); - } else { - f = new File(toFileName(dumpFileName +".dmp")); - } - fileName = f.getAbsolutePath(); - if ((f.exists() && !f.canWrite()) || (!f.exists() && !f.createNewFile())) { - throw new IllegalStateException("Failed to create spool to file: '"+fileName+"'"); - } - out = new PrintWriter(new FileWriter(fileName)); - StreamResult streamResult = new StreamResult(out); - SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); - // SAX2.0 ContentHandler. - TransformerHandler hd = tf.newTransformerHandler(); - Transformer serializer = hd.getTransformer(); - serializer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1"); - //serializer.setOutputProperty(OutputKeys.INDENT,"no"); - hd.setResult(streamResult); - hd.startDocument(); - AttributesImpl atts = new AttributesImpl(); - atts.addAttribute("", "", "tablename", "", dumpFileName); - // USERS tag. - hd.startElement("","","dump",atts); - - String query = "select * from " + nextPart; - Connection c = DBConnector.getInstance().getConnection(); - Statement stmt = c.createStatement(); - ResultSet rs = stmt.executeQuery(query); - SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT); - while (rs.next()) { - atts.clear(); - hd.startElement("","","row",atts); - ResultSetMetaData metaData = rs.getMetaData(); - for (int col = 1; col <= metaData.getColumnCount(); col++) { - atts.addAttribute("","","name","",metaData.getColumnName(col)); - if (metaData.getColumnType(col) == Types.DATE || metaData.getColumnType(col) == Types.TIMESTAMP) { - atts.addAttribute("","","type","","date"); - atts.addAttribute("","","type_name","",metaData.getColumnTypeName(col)); - hd.startElement("","","col",atts); - Date date = rs.getDate(col); - if (date != null) { - String dateString = formatter.format(date); - hd.characters(dateString.toCharArray(), 0, dateString.length()); - } - } else if (isBinary(metaData.getColumnType(col))) { - atts.addAttribute("","","type","","binary"); - atts.addAttribute("","","type_name","",metaData.getColumnTypeName(col)); - hd.startElement("","","col",atts); - - BASE64Encoder enc = new BASE64Encoder(); - int bytesSize = 128; - byte[] bytes = new byte[bytesSize]; - int read; - InputStream valueStream = rs.getBinaryStream(col); - if (valueStream != null) { - while ( (read = valueStream.read(bytes)) != -1) { - if (read == 0) { - continue; - } - if (read != bytes.length) { - bytes = Arrays.copyOf(bytes, read); - } - String stringValue = enc.encode(bytes) +"\n"; - hd.characters(stringValue.toCharArray(), 0, stringValue.length()); - if (bytes.length != bytesSize) { - bytes = new byte[bytesSize]; - } - } - } - } else { - atts.addAttribute("","","type","",Integer.toString(metaData.getColumnType(col))); - atts.addAttribute("","","type_name","",metaData.getColumnTypeName(col)); - hd.startElement("","","col",atts); - String value= rs.getString(col); - if (value != null) { - hd.characters(value.toCharArray(), 0, value.length()); - } - } - hd.endElement("","","col"); - } - hd.endElement("","","row"); - rowCount++; - } - hd.endElement("","","dump"); - hd.endDocument(); - } catch (SAXException ex) { - Logger.getLogger(AbstractSQLShellWindow.class.getName()).log(Level.SEVERE, null, ex); - } catch (TransformerConfigurationException e) { - throw new IllegalStateException("Failed to create xml handler: " + e.toString(), e); - } catch (SQLException e) { - throw new IllegalStateException("Failed to execute query for dump("+fileName+"): " + e.toString(), e); - } catch (IOException e) { - throw new IllegalStateException("Failed to create dump ("+fileName+"): " + e.toString(), e); - } finally { - if (out != null) { - out.close(); - } - } - return new SimpleCommandResult(true, "Dump to "+fileName+" done. ("+ rowCount+" rows written)"); - } - - @Override - public CharSequence getCommandString() { - return "dump"; - } - - /** - * Returns some tab completion info for the specified command. - * @param commandInfo the command lines - * @param commandPoint the cursor position - * @return some tab completion info for the specified command. - */ - @Override - public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { - List<String> commandInfo = new ArrayList<String>(2); - commandInfo.add("SELECT * FROM"); - commandInfo.add(command.getCommandString().substring("dump ".length())); - debug(commandInfo.toString()); - Point point = new Point(commandPoint.x - "dump ".length(), commandPoint.y+1); - return SQLUtil.getTabCompletionInfo(commandInfo, point); - } - - @Override - public CharSequence getHelp() { - return "tablename [where clause]\n" + - "For example: dump users where role='manager';\n\n" + - "See 'read' for options to read the dump file back into the table"; - } - @Override - public boolean abort() { - return false;// not implemented - } - @Override - public boolean backgroundProcessSupported() { - return false; - } - } - /** - * Read the result of a dump file. - */ - private class ReadCommand extends ReadDumpCommand { - private String fileName; - - @Override - public CommandResult execute(SQLCommand cmd) { - String command = cmd.getCommandString(); - String nextPart = command.substring("read".length()).trim(); - String dumpFileName; - if (nextPart.indexOf(' ') > 0) { - dumpFileName = nextPart.substring(0, nextPart.indexOf(' ')); - } else { - dumpFileName = nextPart; - } - int rowCount = 0; - try { - File f = new File(toFileName(dumpFileName +".dmp")); - fileName = f.getAbsolutePath(); - if (!f.exists() && !f.canRead()) { - throw new IllegalStateException("Failed to read dump file: '"+fileName+"'"); - } - // Step 1: create a DocumentBuilderFactory - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - - // Step 2: create a DocumentBuilder - DocumentBuilder db = dbf.newDocumentBuilder(); - - // Step 3: parse the input file to get a Document object - Document doc = db.parse(new File(fileName)); - - Element documentElement = doc.getDocumentElement(); - String tableName = documentElement.getAttribute("tablename"); - NodeList nodeList = documentElement.getElementsByTagName("row"); - - String query = "insert into " + tableName +" ("; - String values = ") values ("; - Element n = (Element) nodeList.item(0); // row - NodeList cols = n.getElementsByTagName("col"); - for (int colNr = 0; colNr < cols.getLength(); colNr++) { - query += cols.item(colNr).getAttributes().getNamedItem("name").getNodeValue(); - values += "?"; - if (colNr +1 < cols.getLength()) { - query +=", "; - values +=", "; - } - } - query = query + values +")"; - Connection c = DBConnector.getInstance().getConnection(); - PreparedStatement pstmt = c.prepareStatement(query); - SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT); - for (int nodeNr = 0; nodeNr < nodeList.getLength(); nodeNr++) { - Element row = (Element) nodeList.item(nodeNr); // row - NodeList columns = row.getElementsByTagName("col"); - for (int colNr = 0; colNr < columns.getLength(); colNr++) { - Element column = (Element) columns.item(colNr); - Node type = column.getAttributes().getNamedItem("type"); - if (type != null) { - String typeString = type.getNodeValue(); - if (typeString.equals("date")) { - String nodeValue = column.getTextContent(); - if (nodeValue == null || nodeValue.equals("")) { - pstmt.setDate(colNr+1, null); - } else { - pstmt.setDate(colNr+1, new Date(formatter.parse(nodeValue).getTime())); - } - } else if (typeString.equals("binary")) { // (isBinary(metaData.getColumnType(col))) - String nodeValue = column.getTextContent(); - BASE64Decoder decoder = new BASE64Decoder(); - byte[] value = decoder.decodeBuffer(nodeValue); - //pstmt.setBinaryStream(colNr+1, new ByteArrayInputStream(value)); - pstmt.setBytes(colNr+1, value); - } else { - String nodeValue = column.getTextContent(); - int iType = Integer.parseInt(typeString); - switch (iType) { - case Types.INTEGER : - case Types.SMALLINT : - case Types.BIGINT : - pstmt.setInt(colNr+1, Integer.parseInt(nodeValue)); - break; - case Types.DOUBLE : pstmt.setDouble(colNr+1, Double.parseDouble(nodeValue)); - break; - case Types.VARCHAR : - case Types.CHAR : - case Types.LONGNVARCHAR : - case Types.NCHAR : - case Types.NVARCHAR : - pstmt.setString(colNr+1, nodeValue); - break; - default: - debug("WARNING Unhandled type: "+ typeString +" trying to fallback to String"); - pstmt.setString(colNr+1, nodeValue); - } - } - } else { - //debug(nodeNr +" ? "+column.getTextContent()); - pstmt.setString(colNr+1, column.getTextContent()); - } - } - pstmt.executeUpdate(); - rowCount++; - } - } catch (SQLException e) { - throw new IllegalStateException("Failed to execute update query for dump("+fileName+"): " + e.toString(), e); - } catch (IOException e) { - throw new IllegalStateException("Failed to read dump ("+fileName+"): " + e.toString(), e); - } catch (Exception e) { - throw new IllegalStateException("Failed to read dump ("+fileName+"): " + e.toString(), e); - } - return new SimpleCommandResult(true, "Read from "+fileName+" done. (" + rowCount+" rows imported)"); - } - - @Override - public CharSequence getCommandString() { - return "read"; - } - - /** - * Returns some tab completion info for the specified command. - * @param commandInfo the command lines - * @param commandPoint the cursor position - * @return some tab completion info for the specified command. - */ - @Override - public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { - String fn = command.getCommandString().substring("read".length()).trim(); - return getFileNameTabCompletionInfo(fn); - } - - @Override - public CharSequence getHelp() { - return "filename: read dump file from filename\n"+ - "See 'dump' for options to create a dump file"; - } - @Override - public boolean abort() { - return false;// not implemented - } - @Override - public boolean backgroundProcessSupported() { - return false; - } - } - public static class ExecuteBatchCommand implements Command { private boolean cancelled; private Command currentCommand; Added: src/main/java/nl/improved/sqlclient/commands/DumpCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/DumpCommand.java 2009-09-22 18:54:54 UTC (rev 421) +++ src/main/java/nl/improved/sqlclient/commands/DumpCommand.java 2009-09-26 12:51:06 UTC (rev 422) @@ -0,0 +1,219 @@ +package nl.improved.sqlclient.commands; + +import nl.improved.sqlclient.*; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintWriter; +import java.sql.Connection; +import java.sql.Date; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Types; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TransformerHandler; +import javax.xml.transform.stream.StreamResult; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; +import sun.misc.BASE64Encoder; + +/** + * Writes the result of a query into a dump file so that it can be read back. + */ +public class DumpCommand extends ReadDumpCommand { + + private String fileName; + + // 0 filename + // 1 tablename + // 2 query + static String[] getParsedStrings(SQLCommand cmd) { + String[] result = new String[3]; + String command = cmd.getCommandString(); + String commandUpperCase = command.toUpperCase(); + if (!commandUpperCase.startsWith("DUMP")) { + return result; + } + String nextPart; + String tableName; + String dumpFileName; + if (commandUpperCase.matches("DUMP AS [A-Z]+.*\\s+[A-Z]*.*")) { + int start = commandUpperCase.indexOf(' ',"DUMP AS ".length() +1); + dumpFileName = command.substring("DUMP AS".length(), start).trim(); + nextPart = command.substring(start).trim(); + } else { + nextPart = command.substring("dump".length()).trim(); + dumpFileName = null; + } + if (nextPart.indexOf(' ') > 0) { + tableName = nextPart.substring(0, nextPart.indexOf(' ')).trim(); + } else { + tableName = nextPart; + } + if (dumpFileName == null) { + dumpFileName = tableName; + } + result[0] = dumpFileName; + result[1] = tableName; + result[2] = nextPart.substring(nextPart.indexOf(tableName)); + return result; + } + + @Override + public CommandResult execute(SQLCommand cmd) { + String[] result = getParsedStrings(cmd); + String dumpFileName = result[0]; + String tableName = result[1]; + String query = "select * from " + result[2]; + int rowCount = 0; + PrintWriter out = null; + try { + File f; + if (dumpFileName.toLowerCase().endsWith(".dmp")) { + f = new File(AbstractSQLShellWindow.toFileName(dumpFileName)); + } else { + f = new File(AbstractSQLShellWindow.toFileName(dumpFileName + ".dmp")); + } + fileName = f.getAbsolutePath(); + if ((f.exists() && !f.canWrite()) || (!f.exists() && !f.createNewFile())) { + throw new IllegalStateException("Failed to create spool to file: \'" + fileName + "\'"); + } + out = new PrintWriter(new FileWriter(fileName)); + StreamResult streamResult = new StreamResult(out); + SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); + // SAX2.0 ContentHandler. + TransformerHandler hd = tf.newTransformerHandler(); + Transformer serializer = hd.getTransformer(); + serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); + //serializer.setOutputProperty(OutputKeys.INDENT,"no"); + hd.setResult(streamResult); + hd.startDocument(); + AttributesImpl atts = new AttributesImpl(); + atts.addAttribute("", "", "tablename", "", tableName); + // USERS tag. + hd.startElement("", "", "dump", atts); + Connection c = DBConnector.getInstance().getConnection(); + Statement stmt = c.createStatement(); + ResultSet rs = stmt.executeQuery(query); + SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT); + while (rs.next()) { + atts.clear(); + hd.startElement("", "", "row", atts); + ResultSetMetaData metaData = rs.getMetaData(); + for (int col = 1; col <= metaData.getColumnCount(); col++) { + atts.addAttribute("", "", "name", "", metaData.getColumnName(col)); + if (metaData.getColumnType(col) == Types.DATE || metaData.getColumnType(col) == Types.TIMESTAMP) { + atts.addAttribute("", "", "type", "", "date"); + atts.addAttribute("", "", "type_name", "", metaData.getColumnTypeName(col)); + hd.startElement("", "", "col", atts); + Date date = rs.getDate(col); + if (date != null) { + String dateString = formatter.format(date); + hd.characters(dateString.toCharArray(), 0, dateString.length()); + } + } else if (isBinary(metaData.getColumnType(col))) { + atts.addAttribute("", "", "type", "", "binary"); + atts.addAttribute("", "", "type_name", "", metaData.getColumnTypeName(col)); + hd.startElement("", "", "col", atts); + BASE64Encoder enc = new BASE64Encoder(); + int bytesSize = 128; + byte[] bytes = new byte[bytesSize]; + int read; + InputStream valueStream = rs.getBinaryStream(col); + if (valueStream != null) { + while ((read = valueStream.read(bytes)) != -1) { + if (read == 0) { + continue; + } + if (read != bytes.length) { + bytes = Arrays.copyOf(bytes, read); + } + String stringValue = enc.encode(bytes) + "\n"; + hd.characters(stringValue.toCharArray(), 0, stringValue.length()); + if (bytes.length != bytesSize) { + bytes = new byte[bytesSize]; + } + } + } + } else { + atts.addAttribute("", "", "type", "", Integer.toString(metaData.getColumnType(col))); + atts.addAttribute("", "", "type_name", "", metaData.getColumnTypeName(col)); + hd.startElement("", "", "col", atts); + String value = rs.getString(col); + if (value != null) { + hd.characters(value.toCharArray(), 0, value.length()); + } + } + hd.endElement("", "", "col"); + } + hd.endElement("", "", "row"); + rowCount++; + } + hd.endElement("", "", "dump"); + hd.endDocument(); + } catch (SAXException ex) { + Logger.getLogger(AbstractSQLShellWindow.class.getName()).log(Level.SEVERE, null, ex); + } catch (TransformerConfigurationException e) { + throw new IllegalStateException("Failed to create xml handler: " + e.toString(), e); + } catch (SQLException e) { + throw new IllegalStateException("Failed to execute query for dump(" + fileName + "): " + e.toString(), e); + } catch (IOException e) { + throw new IllegalStateException("Failed to create dump (" + fileName + "): " + e.toString(), e); + } finally { + if (out != null) { + out.close(); + } + } + return new SimpleCommandResult(true, "Dump to " + fileName + " done. (" + rowCount + " rows written)"); + } + + @Override + public CharSequence getCommandString() { + return "dump"; + } + + /** + * Returns some tab completion info for the specified command. + * @param commandInfo the command lines + * @param commandPoint the cursor position + * @return some tab completion info for the specified command. + */ + @Override + public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { + String[] parsedStrings = getParsedStrings(command); + List<String> commandInfo = new ArrayList<String>(2); + commandInfo.add("SELECT * FROM "); + commandInfo.add(parsedStrings[2]); + //debug(commandInfo.toString()); + int correction = command.getCommandString().length() - parsedStrings[2].length(); + Point point = new Point(commandPoint.x - correction, 1); // TODO fix. + return SQLUtil.getTabCompletionInfo(commandInfo, point); + } + + @Override + public CharSequence getHelp() { + return "tablename [where clause]\n" + "For example: dump users where role=\'manager\';\n\n" + "See \'read\' for options to read the dump file back into the table"; + } + + @Override + public boolean abort() { + return false; + } + + @Override + public boolean backgroundProcessSupported() { + return false; + } +} Added: src/main/java/nl/improved/sqlclient/commands/ReadCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/ReadCommand.java 2009-09-22 18:54:54 UTC (rev 421) +++ src/main/java/nl/improved/sqlclient/commands/ReadCommand.java 2009-09-26 12:51:06 UTC (rev 422) @@ -0,0 +1,163 @@ +package nl.improved.sqlclient.commands; + +import nl.improved.sqlclient.*; +import java.io.File; +import java.io.IOException; +import java.sql.Connection; +import java.sql.Date; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Types; +import java.text.SimpleDateFormat; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import sun.misc.BASE64Decoder; + +/** + * Read the result of a dump file. + */ +public class ReadCommand extends ReadDumpCommand { + + private String fileName; + + @Override + public CommandResult execute(SQLCommand cmd) { + String command = cmd.getCommandString(); + String nextPart = command.substring("read".length()).trim(); + String dumpFileName; + if (nextPart.indexOf(' ') > 0) { + dumpFileName = nextPart.substring(0, nextPart.indexOf(' ')); + } else { + dumpFileName = nextPart; + } + int rowCount = 0; + try { + File f = new File(AbstractSQLShellWindow.toFileName(dumpFileName + ".dmp")); + fileName = f.getAbsolutePath(); + if (!f.exists() && !f.canRead()) { + throw new IllegalStateException("Failed to read dump file: \'" + fileName + "\'"); + } + // Step 1: create a DocumentBuilderFactory + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + // Step 2: create a DocumentBuilder + DocumentBuilder db = dbf.newDocumentBuilder(); + // Step 3: parse the input file to get a Document object + Document doc = db.parse(new File(fileName)); + Element documentElement = doc.getDocumentElement(); + String tableName = documentElement.getAttribute("tablename"); + NodeList nodeList = documentElement.getElementsByTagName("row"); + String query = "insert into " + tableName + " ("; + String values = ") values ("; + Element n = (Element) nodeList.item(0); + // row + NodeList cols = n.getElementsByTagName("col"); + for (int colNr = 0; colNr < cols.getLength(); colNr++) { + query += cols.item(colNr).getAttributes().getNamedItem("name").getNodeValue(); + values += "?"; + if (colNr + 1 < cols.getLength()) { + query += ", "; + values += ", "; + } + } + query = query + values + ")"; + Connection c = DBConnector.getInstance().getConnection(); + PreparedStatement pstmt = c.prepareStatement(query); + SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT); + for (int nodeNr = 0; nodeNr < nodeList.getLength(); nodeNr++) { + Element row = (Element) nodeList.item(nodeNr); + // row + NodeList columns = row.getElementsByTagName("col"); + for (int colNr = 0; colNr < columns.getLength(); colNr++) { + Element column = (Element) columns.item(colNr); + Node type = column.getAttributes().getNamedItem("type"); + if (type != null) { + String typeString = type.getNodeValue(); + if (typeString.equals("date")) { + String nodeValue = column.getTextContent(); + if (nodeValue == null || nodeValue.equals("")) { + pstmt.setDate(colNr + 1, null); + } else { + pstmt.setDate(colNr + 1, new Date(formatter.parse(nodeValue).getTime())); + } + } else if (typeString.equals("binary")) { + String nodeValue = column.getTextContent(); + BASE64Decoder decoder = new BASE64Decoder(); + byte[] value = decoder.decodeBuffer(nodeValue); + pstmt.setBytes(colNr + 1, value); + } else { + String nodeValue = column.getTextContent(); + int iType = Integer.parseInt(typeString); + switch (iType) { + case Types.INTEGER: + case Types.SMALLINT: + case Types.BIGINT: + pstmt.setInt(colNr + 1, Integer.parseInt(nodeValue)); + break; + case Types.DOUBLE: + pstmt.setDouble(colNr + 1, Double.parseDouble(nodeValue)); + break; + case Types.VARCHAR: + case Types.CHAR: + case Types.LONGNVARCHAR: + case Types.NCHAR: + case Types.NVARCHAR: + pstmt.setString(colNr + 1, nodeValue); + break; + default: + pstmt.setString(colNr + 1, nodeValue); + } + } + } else { + //debug(nodeNr +" ? "+column.getTextContent()); + pstmt.setString(colNr + 1, column.getTextContent()); + } + } + pstmt.executeUpdate(); + rowCount++; + } + } catch (SQLException e) { + throw new IllegalStateException("Failed to execute update query for dump(" + fileName + "): " + e.toString(), e); + } catch (IOException e) { + throw new IllegalStateException("Failed to read dump (" + fileName + "): " + e.toString(), e); + } catch (Exception e) { + throw new IllegalStateException("Failed to read dump (" + fileName + "): " + e.toString(), e); + } + return new SimpleCommandResult(true, "Read from " + fileName + " done. (" + rowCount + " rows imported)"); + } + + @Override + public CharSequence getCommandString() { + return "read"; + } + + /** + * Returns some tab completion info for the specified command. + * @param commandInfo the command lines + * @param commandPoint the cursor position + * @return some tab completion info for the specified command. + */ + @Override + public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { + String fn = command.getCommandString().substring("read".length()).trim(); + return AbstractSQLShellWindow.getFileNameTabCompletionInfo(fn); + } + + @Override + public CharSequence getHelp() { + return "filename: read dump file from filename\n" + "See \'dump\' for options to create a dump file"; + } + + @Override + public boolean abort() { + return false; + } + + @Override + public boolean backgroundProcessSupported() { + return false; + } +} Added: src/main/java/nl/improved/sqlclient/commands/ReadDumpCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/ReadDumpCommand.java 2009-09-22 18:54:54 UTC (rev 421) +++ src/main/java/nl/improved/sqlclient/commands/ReadDumpCommand.java 2009-09-26 12:51:06 UTC (rev 422) @@ -0,0 +1,16 @@ +package nl.improved.sqlclient.commands; + +import java.sql.Types; +import nl.improved.sqlclient.commands.Command; + +abstract class ReadDumpCommand implements Command { + + public static final String DATE_FORMAT = "yyyyMMddHHmmss"; + + boolean isBinary(int columnType) { + if (columnType == Types.BINARY || columnType == Types.BLOB || columnType == Types.CLOB || columnType == Types.LONGVARBINARY || columnType == Types.LONGVARCHAR || columnType == Types.OTHER) { + return true; + } + return false; + } +} Added: src/test/java/nl/improved/sqlclient/commands/DumpCommandTest.java =================================================================== --- src/test/java/nl/improved/sqlclient/commands/DumpCommandTest.java 2009-09-22 18:54:54 UTC (rev 421) +++ src/test/java/nl/improved/sqlclient/commands/DumpCommandTest.java 2009-09-26 12:51:06 UTC (rev 422) @@ -0,0 +1,97 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package nl.improved.sqlclient.commands; + +import junit.framework.TestCase; +import nl.improved.sqlclient.Point; +import nl.improved.sqlclient.SQLCommand; +import nl.improved.sqlclient.TabCompletionInfo; + +/** + * + * @author roy + */ +public class DumpCommandTest extends TestCase { + + public DumpCommandTest(String testName) { + super(testName); + } + + /** + * Test of getCommandString method, of class DumpCommand. + */ + public void testGetParsedStrings() { + // Simple dump entire table + SQLCommand cmd = new SQLCommand("dump mytable"); + String[] result = DumpCommand.getParsedStrings(cmd); + assertNotNull(result); + assertEquals(3, result.length); + assertEquals("mytable", result[0]); + assertEquals("mytable", result[1]); + assertEquals("mytable", result[2]); + + // Dump table with where clause + cmd = new SQLCommand("dump mytable where dumped=false"); + result = DumpCommand.getParsedStrings(cmd); + assertNotNull(result); + assertEquals(3, result.length); + assertEquals("mytable", result[0]); + assertEquals("mytable", result[1]); + assertEquals("mytable where dumped=false", result[2]); + + // Dump table with filename + cmd = new SQLCommand("dump as myfile mytable"); + result = DumpCommand.getParsedStrings(cmd); + assertNotNull(result); + assertEquals(3, result.length); + assertEquals("myfile", result[0]); + assertEquals("mytable", result[1]); + assertEquals("mytable", result[2]); + + // Dump table with filename with where clause + cmd = new SQLCommand("dump as myfile mytable where dumped=false"); + result = DumpCommand.getParsedStrings(cmd); + assertNotNull(result); + assertEquals(3, result.length); + assertEquals("myfile", result[0]); + assertEquals("mytable", result[1]); + assertEquals("mytable where dumped=false", result[2]); + + // Dump incomplete command + cmd = new SQLCommand("dump as myfile "); + result = DumpCommand.getParsedStrings(cmd); + assertNotNull(result); + assertEquals(3, result.length); + assertEquals("myfile", result[0]); + assertEquals("", result[1]); + assertEquals("", result[2]); + } + + /** + * Test of getTabCompletionInfo method, of class DumpCommand. + */ + public void testGetTabCompletionInfo() { + System.out.println("getTabCompletionInfo"); + SQLCommand cmd = new SQLCommand("dump t"); + DumpCommand dcmd = new DumpCommand(); + TabCompletionInfo completionInfo = dcmd.getTabCompletionInfo(cmd, new Point(cmd.getCommandString().length(), 0)); + assertNotNull(completionInfo); + assertEquals(TabCompletionInfo.MatchType.TABLE_NAMES, completionInfo.getMatchType()); + assertEquals("t", completionInfo.getStart()); + + cmd = new SQLCommand("dump as tmp "); + completionInfo = dcmd.getTabCompletionInfo(cmd, new Point(cmd.getCommandString().length(), 0)); + assertNotNull(completionInfo); + assertEquals(TabCompletionInfo.MatchType.TABLE_NAMES, completionInfo.getMatchType()); + assertEquals("", completionInfo.getStart()); + + cmd = new SQLCommand("dump as tmp f"); + completionInfo = dcmd.getTabCompletionInfo(cmd, new Point(cmd.getCommandString().length(), 0)); + assertNotNull(completionInfo); + assertEquals(TabCompletionInfo.MatchType.TABLE_NAMES, completionInfo.getMatchType()); + assertEquals("f", completionInfo.getStart()); + } +} |
From: SVN by r. <sv...@ca...> - 2009-09-22 18:55:09
|
Author: roy Date: 2009-09-22 20:54:54 +0200 (Tue, 22 Sep 2009) New Revision: 421 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java Log: fix 'force exit' when spool is used wrongly Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-09-21 18:55:07 UTC (rev 420) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-09-22 18:54:54 UTC (rev 421) @@ -1697,7 +1697,9 @@ public CommandResult execute(SQLCommand cmd) { String command = cmd.getCommandString(); String nextPart = command.substring("spool".length()).trim(); - if (nextPart.equalsIgnoreCase("off")) { + if (nextPart.equalsIgnoreCase("")) { + return new SimpleCommandResult(false, "Please provide a valid argument. See 'help spool' for more information"); + } else if (nextPart.equalsIgnoreCase("off")) { if (spoolWriter != null) { try { spoolWriter.close(); |
From: SVN by r. <sv...@ca...> - 2009-09-21 18:55:24
|
Author: roy Date: 2009-09-21 20:55:07 +0200 (Mon, 21 Sep 2009) New Revision: 420 Added: src/main/java/nl/improved/sqlclient/commands/QueryCommand.java src/test/java/nl/improved/sqlclient/commands/QueryCommandTest.java Removed: src/test/java/nl/improved/sqlclient/SQLCommandTest.java Modified: / db/testdb.properties src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java src/main/java/nl/improved/sqlclient/QueryExecutor.java src/main/java/nl/improved/sqlclient/SQLCommand.java src/main/java/nl/improved/sqlclient/StatementExecutor.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/SettingsCommand.java src/main/java/nl/improved/sqlclient/commands/ShowCommand.java src/main/java/nl/improved/sqlclient/commands/SimpleCommandResult.java Log: previous version of variables broke a lot of commands this version enables variables only for sql commands Property changes on: ___________________________________________________________________ Name: svn:ignore - target + target .BUGS.txt.swp Modified: db/testdb.properties =================================================================== --- db/testdb.properties 2009-09-19 13:15:22 UTC (rev 419) +++ db/testdb.properties 2009-09-21 18:55:07 UTC (rev 420) @@ -1,5 +1,5 @@ -#HSQL Database Engine 1.8.0.7 -#Mon Aug 13 23:55:03 GMT+01:00 2007 +#HSQL Database Engine 1.8.0.8 +#Sat Sep 19 14:54:00 CEST 2009 hsqldb.script_format=0 runtime.gc_interval=0 sql.enforce_strict_size=false Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-09-19 13:15:22 UTC (rev 419) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-09-21 18:55:07 UTC (rev 420) @@ -15,7 +15,6 @@ */ package nl.improved.sqlclient; -import nl.improved.sqlclient.commands.SettingsCommand; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; @@ -611,11 +610,11 @@ } System.setErr(errorStream); System.setOut(outStream); - File errFile = getErrFile(); - if (errFile != null && errFile.length() > 0L) { + File errorFile = getErrFile(); + if (errorFile != null && errorFile.length() > 0L) { try { System.out.println("There where errors during execution of sqlshell:"); - BufferedReader reader = new BufferedReader(new FileReader(errFile)); + BufferedReader reader = new BufferedReader(new FileReader(errorFile)); String line; while ( (line = reader.readLine()) != null) { System.out.println(line); @@ -2372,82 +2371,7 @@ } } - /** - * Query command responsible for executing a sql query. - */ - private class QueryCommand implements Command { - /** - * Executor for SQL Statements. - */ - private StatementExecutor statementExecutor; - - /** - * Execute the sql query. - * @param cmd the sqlcommand containing the sql query - * @return the result of the sql query. - */ - @Override - public CommandResult execute(SQLCommand cmd) { - try { - final String command = cmd.getCommandString(); - if (command.length() > "select".length() && "select".equalsIgnoreCase(command.subSequence(0, "create".length()).toString())) { - return new CommandResult() { - public boolean executedSuccessfully() { - return true; - } - public Iterator<CharSequence> getResult() { - try { - return DBConnector.getInstance().getQueryExecutor().executeQuery(command); - } catch (SQLException ex) { - throw new IllegalArgumentException(ex); - } - } - }; - } - if (statementExecutor == null) { - statementExecutor = new StatementExecutor(); - } - return new SimpleCommandResult(true, statementExecutor.execute(command)); - } catch(SQLException e) { - error(e); - return new SimpleCommandResult(false, ""); - } catch(IllegalStateException e) { - error(e); - return new SimpleCommandResult(false, ""); - } - } - - @Override - public CharSequence getCommandString() { - return ""; - } - - @Override - public TabCompletionInfo getTabCompletionInfo(SQLCommand commandInfo, Point commandPoint) { - // TODO call SQLUTil.. - debug("GET TAB COMPLETION OF QUERY COMMAND"); - return null; - } - - @Override - public CharSequence getHelp() { - return ""; - } - - @Override - public boolean abort() { - //DBConnector.getInstance().getStatement().cancel(); - output(DBConnector.getInstance().getQueryExecutor().cancel()); - return true; - } - @Override - public boolean backgroundProcessSupported() { - return true; - } - } - - /** * The key action interface. * Implement this interface for handling key actions. Modified: src/main/java/nl/improved/sqlclient/QueryExecutor.java =================================================================== --- src/main/java/nl/improved/sqlclient/QueryExecutor.java 2009-09-19 13:15:22 UTC (rev 419) +++ src/main/java/nl/improved/sqlclient/QueryExecutor.java 2009-09-21 18:55:07 UTC (rev 420) @@ -149,13 +149,13 @@ } } - public CharSequence cancel() { + public boolean cancel() { try { DBConnector.getInstance().getStatement().cancel(); cancelled = true; - return "Cancel accepted"; + return true; } catch (SQLException ex) { - return "Cancel Failed: "+ ex.toString(); + return false; } } @@ -165,7 +165,7 @@ * @return the formatted result. * @throws SQLException if the database could not execute the SQL query for some reason. */ - protected Iterator<CharSequence> executeQuery(CharSequence command) throws SQLException { + public Iterator<CharSequence> executeQuery(CharSequence command) throws SQLException { cancelled = false; long start = System.currentTimeMillis(); ResultSet results = DBConnector.getInstance().getStatement().executeQuery(command.toString()); Modified: src/main/java/nl/improved/sqlclient/SQLCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/SQLCommand.java 2009-09-19 13:15:22 UTC (rev 419) +++ src/main/java/nl/improved/sqlclient/SQLCommand.java 2009-09-21 18:55:07 UTC (rev 420) @@ -2,16 +2,12 @@ import java.util.List; import java.util.ArrayList; -import java.util.HashMap; import java.util.Iterator; -import java.util.Map; public class SQLCommand { private List<StringBuffer> commandLines; - private static Map<String, String> variables = new HashMap<String, String>(); - /** * Constructor. */ @@ -27,27 +23,10 @@ commandLines.add(new StringBuffer(cmd)); } - /** - * Register variables. - * @param var the variable name - * @param value the variable value - * @return the previous value, if any - */ - public static String registerVariable(String var, String value) { - return variables.put(var, value); - } - /** - * Unregister variables. - * @param var the variable name - * @return the value, if any - */ - public static String unregisterVariable(String var) { - return variables.remove(var); - } - public List<StringBuffer> getEditableLines() { return commandLines; } + public List<? extends CharSequence> getLines() { return commandLines; } @@ -97,44 +76,7 @@ if (returnString.endsWith(";")) { returnString = returnString.substring(0, returnString.length()-1).trim(); } - return replaceVariables(returnString); + return returnString; } - private String replaceVariables(String returnString) { - StringBuffer returnValue = new StringBuffer(); - int lastIndex = 0; - int previous = 0; - while ( (lastIndex = returnString.indexOf('@', lastIndex)) > 0) { - returnValue.append(returnString.substring(previous, lastIndex)); - if (getQuoteCount(returnValue) %2 == 1) { - returnValue.append(returnString.charAt(lastIndex)); - lastIndex++; - previous = lastIndex; - continue; - } - int end = returnString.indexOf(' ', lastIndex); - if (end < 0) { - end = returnString.indexOf(';', lastIndex); - if (end < 0) { - end = returnString.length(); - } - } - String varName = returnString.substring(lastIndex+1, end); - returnValue.append(variables.get(varName)); - previous = end; - lastIndex = end; - } - returnValue.append(returnString.substring(previous)); - return returnValue.toString(); - } - - static int getQuoteCount(StringBuffer returnValue) { - int amount = 0; - int lastIndex = 0; - while ( (lastIndex = returnValue.indexOf("\'", lastIndex) ) > 0) { - amount++; - lastIndex++; - } - return amount; - } } Modified: src/main/java/nl/improved/sqlclient/StatementExecutor.java =================================================================== --- src/main/java/nl/improved/sqlclient/StatementExecutor.java 2009-09-19 13:15:22 UTC (rev 419) +++ src/main/java/nl/improved/sqlclient/StatementExecutor.java 2009-09-21 18:55:07 UTC (rev 420) @@ -45,7 +45,7 @@ * @return info about the command execution. * @throws SQLException if the database could not execute the SQL statement for some reason. */ - protected CharSequence execute(CharSequence command) throws SQLException { + public CharSequence execute(CharSequence command) throws SQLException { Connection connection = DBConnector.getInstance().getConnection(); String commandString = command.toString(); //Special handling for commit Modified: src/main/java/nl/improved/sqlclient/commands/DescCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/DescCommand.java 2009-09-19 13:15:22 UTC (rev 419) +++ src/main/java/nl/improved/sqlclient/commands/DescCommand.java 2009-09-21 18:55:07 UTC (rev 420) @@ -15,12 +15,12 @@ */ package nl.improved.sqlclient.commands; +import nl.improved.sqlclient.SQLCommand; import java.util.List; import java.util.ArrayList; import nl.improved.sqlclient.Point; import nl.improved.sqlclient.SQLUtil; import nl.improved.sqlclient.TabCompletionInfo; -import nl.improved.sqlclient.SQLCommand; import nl.improved.sqlclient.DBConnector; import nl.improved.sqlclient.util.ResultBuilder; import java.sql.ResultSet; Modified: src/main/java/nl/improved/sqlclient/commands/InfoCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/InfoCommand.java 2009-09-19 13:15:22 UTC (rev 419) +++ src/main/java/nl/improved/sqlclient/commands/InfoCommand.java 2009-09-21 18:55:07 UTC (rev 420) @@ -15,9 +15,9 @@ */ package nl.improved.sqlclient.commands; +import nl.improved.sqlclient.SQLCommand; import nl.improved.sqlclient.Point; import nl.improved.sqlclient.TabCompletionInfo; -import nl.improved.sqlclient.SQLCommand; import nl.improved.sqlclient.DBConnector; import java.sql.SQLException; import java.sql.DatabaseMetaData; Added: src/main/java/nl/improved/sqlclient/commands/QueryCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/QueryCommand.java 2009-09-19 13:15:22 UTC (rev 419) +++ src/main/java/nl/improved/sqlclient/commands/QueryCommand.java 2009-09-21 18:55:07 UTC (rev 420) @@ -0,0 +1,140 @@ +package nl.improved.sqlclient.commands; + +import nl.improved.sqlclient.*; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +/** + * Query command responsible for executing a sql query. + */ +public class QueryCommand implements Command { + + + private static Map<String, String> variables = new HashMap<String, String>(); + /** + * Executor for SQL Statements. + */ + private StatementExecutor statementExecutor; + + /** + * Register variables. + * @param var the variable name + * @param value the variable value + * @return the previous value, if any + */ + public static String registerVariable(String var, String value) { + return variables.put(var, value); + } + /** + * Unregister variables. + * @param var the variable name + * @return the value, if any + */ + public static String unregisterVariable(String var) { + return variables.remove(var); + } + + /** + * Execute the sql query. + * @param cmd the sqlcommand containing the sql query + * @return the result of the sql query. + */ + @Override + public CommandResult execute(SQLCommand cmd) { + try { + final String command = replaceVariables(cmd.getCommandString()); + if (command.length() > "select".length() && "select".equalsIgnoreCase(command.subSequence(0, "create".length()).toString())) { + return new CommandResult() { + + public boolean executedSuccessfully() { + return true; + } + + public Iterator<CharSequence> getResult() { + try { + return DBConnector.getInstance().getQueryExecutor().executeQuery(command); + } catch (SQLException ex) { + throw new IllegalArgumentException(ex); + } + } + }; + } + if (statementExecutor == null) { + statementExecutor = new StatementExecutor(); + } + return new SimpleCommandResult(true, statementExecutor.execute(command)); + } catch (SQLException e) { + return new SimpleCommandResult(e); + } catch (IllegalStateException e) { + return new SimpleCommandResult(e); + } + } + + @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() { + DBConnector.getInstance().getQueryExecutor().cancel(); + //output(DBConnector.getInstance().getQueryExecutor().cancel()); + return true; + } + + @Override + public boolean backgroundProcessSupported() { + return true; + } + + static String replaceVariables(String returnString) { + StringBuffer returnValue = new StringBuffer(); + int lastIndex = 0; + int previous = 0; + while ( (lastIndex = returnString.indexOf('@', lastIndex)) > 0) { + returnValue.append(returnString.substring(previous, lastIndex)); + if (getQuoteCount(returnValue) %2 == 1) { + returnValue.append(returnString.charAt(lastIndex)); + lastIndex++; + previous = lastIndex; + continue; + } + int end = returnString.indexOf(' ', lastIndex); + if (end < 0) { + end = returnString.indexOf(';', lastIndex); + if (end < 0) { + end = returnString.length(); + } + } + String varName = returnString.substring(lastIndex+1, end); + returnValue.append(variables.get(varName)); + previous = end; + lastIndex = end; + } + returnValue.append(returnString.substring(previous)); + return returnValue.toString(); + } + + static int getQuoteCount(StringBuffer returnValue) { + int amount = 0; + int lastIndex = 0; + while ( (lastIndex = returnValue.indexOf("\'", lastIndex) ) > 0) { + amount++; + lastIndex++; + } + return amount; + } +} Modified: src/main/java/nl/improved/sqlclient/commands/SettingsCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/SettingsCommand.java 2009-09-19 13:15:22 UTC (rev 419) +++ src/main/java/nl/improved/sqlclient/commands/SettingsCommand.java 2009-09-21 18:55:07 UTC (rev 420) @@ -5,8 +5,8 @@ package nl.improved.sqlclient.commands; +import nl.improved.sqlclient.SQLCommand; import nl.improved.sqlclient.Point; -import nl.improved.sqlclient.SQLCommand; import nl.improved.sqlclient.TabCompletionInfo; import nl.improved.sqlclient.util.ResultBuilder; @@ -38,7 +38,7 @@ } String varName = cmdString.substring(1, cmdString.indexOf('=')).trim(); String varValue = cmdString.substring(cmdString.indexOf('=')+1).trim(); - SQLCommand.registerVariable(varName, varValue); + QueryCommand.registerVariable(varName, varValue); return new SimpleCommandResult(true, "Registred variable '"+varName+"' to value '"+varValue+"'"); } Modified: src/main/java/nl/improved/sqlclient/commands/ShowCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/ShowCommand.java 2009-09-19 13:15:22 UTC (rev 419) +++ src/main/java/nl/improved/sqlclient/commands/ShowCommand.java 2009-09-21 18:55:07 UTC (rev 420) @@ -15,8 +15,8 @@ */ package nl.improved.sqlclient.commands; +import nl.improved.sqlclient.SQLCommand; import java.sql.DatabaseMetaData; -import nl.improved.sqlclient.SQLCommand; import nl.improved.sqlclient.DBConnector; import nl.improved.sqlclient.Point; import nl.improved.sqlclient.SQLUtil; Modified: src/main/java/nl/improved/sqlclient/commands/SimpleCommandResult.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/SimpleCommandResult.java 2009-09-19 13:15:22 UTC (rev 419) +++ src/main/java/nl/improved/sqlclient/commands/SimpleCommandResult.java 2009-09-21 18:55:07 UTC (rev 420) @@ -16,12 +16,24 @@ public class SimpleCommandResult implements CommandResult { private boolean success; private CharSequence result; + private final Throwable throwable; public SimpleCommandResult(boolean success, CharSequence result) { this.success = success; this.result = result; + throwable = null; } + public SimpleCommandResult(Throwable t) { + this.success = false; + this.result = t.toString(); + this.throwable = t; + } + + public Throwable getThrowable() { + return throwable; + } + public boolean executedSuccessfully() { return success; } Deleted: src/test/java/nl/improved/sqlclient/SQLCommandTest.java =================================================================== --- src/test/java/nl/improved/sqlclient/SQLCommandTest.java 2009-09-19 13:15:22 UTC (rev 419) +++ src/test/java/nl/improved/sqlclient/SQLCommandTest.java 2009-09-21 18:55:07 UTC (rev 420) @@ -1,66 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ - -package nl.improved.sqlclient; - -import java.util.List; -import junit.framework.TestCase; - -/** - * - * @author roy - */ -public class SQLCommandTest extends TestCase { - - public SQLCommandTest(String testName) { - super(testName); - } - - /** - * Test of registerVariable method, of class SQLCommand. - */ - public void testRegisterVariable() { - String var = "test"; - String value = "value"; - String expResult = null; - String result = SQLCommand.registerVariable(var, value); - assertEquals(expResult, result); - value = "value2"; - expResult = "value"; - result = SQLCommand.registerVariable(var, value); - assertEquals(expResult, result); - } - - /** - * Test of getCommandString method, of class SQLCommand. - */ - public void testGetCommandString() { - SQLCommand cmd = new SQLCommand("select * from test"); - assertEquals("select * from test", cmd.getCommandString()); - cmd = new SQLCommand("select * from test;"); - assertEquals("select * from test", cmd.getCommandString()); - - cmd = new SQLCommand("select * from test where a='b';"); - assertEquals("select * from test where a='b'", cmd.getCommandString()); - - // with variables - cmd = new SQLCommand("select * from test where a=@b;"); - assertEquals("select * from test where a=null", cmd.getCommandString()); - SQLCommand.registerVariable("b", "'b'"); - assertEquals("select * from test where a='b'", cmd.getCommandString()); - cmd = new SQLCommand("select * from test where a='@b';"); - assertEquals("select * from test where a='@b'", cmd.getCommandString()); - } - - public void testQuoteCount() { - StringBuffer buf = new StringBuffer("select * from test"); - assertEquals(0, SQLCommand.getQuoteCount(buf)); - buf.append(" where a='b"); - assertEquals(1, SQLCommand.getQuoteCount(buf)); - buf.append(" '"); - assertEquals(2, SQLCommand.getQuoteCount(buf)); - - } -} Copied: src/test/java/nl/improved/sqlclient/commands/QueryCommandTest.java (from rev 418, src/test/java/nl/improved/sqlclient/SQLCommandTest.java) =================================================================== --- src/test/java/nl/improved/sqlclient/SQLCommandTest.java 2009-09-19 12:55:14 UTC (rev 418) +++ src/test/java/nl/improved/sqlclient/commands/QueryCommandTest.java 2009-09-21 18:55:07 UTC (rev 420) @@ -0,0 +1,68 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package nl.improved.sqlclient.commands; + +import java.util.List; +import junit.framework.TestCase; +import nl.improved.sqlclient.SQLCommand; + +/** + * + * @author roy + */ +public class QueryCommandTest extends TestCase { + + public QueryCommandTest(String testName) { + super(testName); + } + + /** + * Test of registerVariable method, of class QueryCommand. + */ + public void testRegisterVariable() { + String var = "test"; + String value = "value"; + String expResult = null; + String result = QueryCommand.registerVariable(var, value); + assertEquals(expResult, result); + value = "value2"; + expResult = "value"; + result = QueryCommand.registerVariable(var, value); + assertEquals(expResult, result); + } + + /** + * Test of getCommandString method, of class QueryCommand. + */ + public void testGetCommandString() { + SQLCommand cmd = new SQLCommand("select * from test"); + assertEquals("select * from test" + , QueryCommand.replaceVariables(cmd.getCommandString())); + cmd = new SQLCommand("select * from test;"); + assertEquals("select * from test" , QueryCommand.replaceVariables(cmd.getCommandString())); + + cmd = new SQLCommand("select * from test where a='b';"); + assertEquals("select * from test where a='b'", QueryCommand.replaceVariables(cmd.getCommandString())); + + // with variables + cmd = new SQLCommand("select * from test where a=@b;"); + assertEquals("select * from test where a=null", QueryCommand.replaceVariables(cmd.getCommandString())); + QueryCommand.registerVariable("b", "'b'"); + assertEquals("select * from test where a='b'", QueryCommand.replaceVariables(cmd.getCommandString())); + cmd = new SQLCommand("select * from test where a='@b';"); + assertEquals("select * from test where a='@b'", QueryCommand.replaceVariables(cmd.getCommandString())); + } + + public void testQuoteCount() { + StringBuffer buf = new StringBuffer("select * from test"); + assertEquals(0, QueryCommand.getQuoteCount(buf)); + buf.append(" where a='b"); + assertEquals(1, QueryCommand.getQuoteCount(buf)); + buf.append(" '"); + assertEquals(2, QueryCommand.getQuoteCount(buf)); + + } +} Property changes on: src/test/java/nl/improved/sqlclient/commands/QueryCommandTest.java ___________________________________________________________________ Name: svn:mergeinfo + |
From: SVN by r. <sv...@ca...> - 2009-09-19 13:15:41
|
Author: roy Date: 2009-09-19 15:15:22 +0200 (Sat, 19 Sep 2009) New Revision: 419 Modified: src/main/java/nl/improved/sqlclient/SQLCommand.java Log: fix escaping command Modified: src/main/java/nl/improved/sqlclient/SQLCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/SQLCommand.java 2009-09-19 12:55:14 UTC (rev 418) +++ src/main/java/nl/improved/sqlclient/SQLCommand.java 2009-09-19 13:15:22 UTC (rev 419) @@ -107,6 +107,8 @@ while ( (lastIndex = returnString.indexOf('@', lastIndex)) > 0) { returnValue.append(returnString.substring(previous, lastIndex)); if (getQuoteCount(returnValue) %2 == 1) { + returnValue.append(returnString.charAt(lastIndex)); + lastIndex++; previous = lastIndex; continue; } |
From: SVN by r. <sv...@ca...> - 2009-09-19 12:55:30
|
Author: roy Date: 2009-09-19 14:55:14 +0200 (Sat, 19 Sep 2009) New Revision: 418 Added: src/test/java/nl/improved/sqlclient/SQLCommandTest.java Modified: ChangeLog src/main/java/nl/improved/sqlclient/SQLCommand.java src/main/java/nl/improved/sqlclient/commands/SettingsCommand.java Log: added initial support for variables see 'help set' for more information Modified: ChangeLog =================================================================== --- ChangeLog 2009-09-18 11:55:18 UTC (rev 417) +++ ChangeLog 2009-09-19 12:55:14 UTC (rev 418) @@ -3,6 +3,7 @@ - improved group by and order by - added support for aliases in table names * Added initial settings command (to change for the current login session) the horizontal or vertical separator character + * Added initial support for variables (in settings command.. see 'help set' for more information) 0.6.2 (2009-02-20) * Commandline input support Modified: src/main/java/nl/improved/sqlclient/SQLCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/SQLCommand.java 2009-09-18 11:55:18 UTC (rev 417) +++ src/main/java/nl/improved/sqlclient/SQLCommand.java 2009-09-19 12:55:14 UTC (rev 418) @@ -2,12 +2,16 @@ import java.util.List; import java.util.ArrayList; +import java.util.HashMap; import java.util.Iterator; +import java.util.Map; public class SQLCommand { private List<StringBuffer> commandLines; + private static Map<String, String> variables = new HashMap<String, String>(); + /** * Constructor. */ @@ -23,6 +27,24 @@ commandLines.add(new StringBuffer(cmd)); } + /** + * Register variables. + * @param var the variable name + * @param value the variable value + * @return the previous value, if any + */ + public static String registerVariable(String var, String value) { + return variables.put(var, value); + } + /** + * Unregister variables. + * @param var the variable name + * @return the value, if any + */ + public static String unregisterVariable(String var) { + return variables.remove(var); + } + public List<StringBuffer> getEditableLines() { return commandLines; } @@ -65,11 +87,52 @@ } return returnValue.toString(); } + + /** + * Returns the command string with variables replaced. + * @return + */ public String getCommandString() { String returnString = getUntrimmedCommandString(); if (returnString.endsWith(";")) { returnString = returnString.substring(0, returnString.length()-1).trim(); } - return returnString; + return replaceVariables(returnString); } + + private String replaceVariables(String returnString) { + StringBuffer returnValue = new StringBuffer(); + int lastIndex = 0; + int previous = 0; + while ( (lastIndex = returnString.indexOf('@', lastIndex)) > 0) { + returnValue.append(returnString.substring(previous, lastIndex)); + if (getQuoteCount(returnValue) %2 == 1) { + previous = lastIndex; + continue; + } + int end = returnString.indexOf(' ', lastIndex); + if (end < 0) { + end = returnString.indexOf(';', lastIndex); + if (end < 0) { + end = returnString.length(); + } + } + String varName = returnString.substring(lastIndex+1, end); + returnValue.append(variables.get(varName)); + previous = end; + lastIndex = end; + } + returnValue.append(returnString.substring(previous)); + return returnValue.toString(); + } + + static int getQuoteCount(StringBuffer returnValue) { + int amount = 0; + int lastIndex = 0; + while ( (lastIndex = returnValue.indexOf("\'", lastIndex) ) > 0) { + amount++; + lastIndex++; + } + return amount; + } } Modified: src/main/java/nl/improved/sqlclient/commands/SettingsCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/SettingsCommand.java 2009-09-18 11:55:18 UTC (rev 417) +++ src/main/java/nl/improved/sqlclient/commands/SettingsCommand.java 2009-09-19 12:55:14 UTC (rev 418) @@ -21,18 +21,27 @@ public CommandResult execute(SQLCommand cmd) { String cmdString = cmd.getUntrimmedCommandString().substring("set ".length()).trim(); - if (cmdString.indexOf(' ') < 0) { - return new SimpleCommandResult(false, "Please provide an argument"); - } - String setter = cmdString.substring(0, cmdString.indexOf(' ')); + String setter = cmdString.substring(0, cmdString.indexOf('=')); if (setter.equals("hSeparatorChar")) { - ResultBuilder.setHorizontalSeparator(cmdString.charAt(cmdString.indexOf(' ')+1)); + ResultBuilder.setHorizontalSeparator(cmdString.charAt(cmdString.indexOf('=')+1)); return new SimpleCommandResult(true, "Horizontal separator updated to '"+ResultBuilder.getHorizontalSeparator()+"'."); } if (setter.equals("vSeparatorChar")) { - ResultBuilder.setVerticalSeparator(cmdString.charAt(cmdString.indexOf(' ')+1)); + ResultBuilder.setVerticalSeparator(cmdString.charAt(cmdString.indexOf('=')+1)); return new SimpleCommandResult(true, "Vertical separator updated to '"+ResultBuilder.getVerticalSeparator()+"'."); } + if (setter.startsWith("@")) { // variable + // see + // http://www.science.uva.nl/ict/ossdocs/mysql/manual_Reference.html + if (!cmdString.contains("=")) { + return new SimpleCommandResult(false, "Setter of variable '"+ setter+"' requires an assignment.."); + } + String varName = cmdString.substring(1, cmdString.indexOf('=')).trim(); + String varValue = cmdString.substring(cmdString.indexOf('=')+1).trim(); + SQLCommand.registerVariable(varName, varValue); + return new SimpleCommandResult(true, "Registred variable '"+varName+"' to value '"+varValue+"'"); + + } return new SimpleCommandResult(false, "Please provide a valid argument"); } @@ -49,7 +58,8 @@ return "Change settings of sqlshell properties" + "Settings are:\n"+ "hSeparatorChar\n"+ - "vSeparatorChar"; + "vSeparatorChar\n" + + "@variable=value"; } public boolean abort() { Added: src/test/java/nl/improved/sqlclient/SQLCommandTest.java =================================================================== --- src/test/java/nl/improved/sqlclient/SQLCommandTest.java 2009-09-18 11:55:18 UTC (rev 417) +++ src/test/java/nl/improved/sqlclient/SQLCommandTest.java 2009-09-19 12:55:14 UTC (rev 418) @@ -0,0 +1,66 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package nl.improved.sqlclient; + +import java.util.List; +import junit.framework.TestCase; + +/** + * + * @author roy + */ +public class SQLCommandTest extends TestCase { + + public SQLCommandTest(String testName) { + super(testName); + } + + /** + * Test of registerVariable method, of class SQLCommand. + */ + public void testRegisterVariable() { + String var = "test"; + String value = "value"; + String expResult = null; + String result = SQLCommand.registerVariable(var, value); + assertEquals(expResult, result); + value = "value2"; + expResult = "value"; + result = SQLCommand.registerVariable(var, value); + assertEquals(expResult, result); + } + + /** + * Test of getCommandString method, of class SQLCommand. + */ + public void testGetCommandString() { + SQLCommand cmd = new SQLCommand("select * from test"); + assertEquals("select * from test", cmd.getCommandString()); + cmd = new SQLCommand("select * from test;"); + assertEquals("select * from test", cmd.getCommandString()); + + cmd = new SQLCommand("select * from test where a='b';"); + assertEquals("select * from test where a='b'", cmd.getCommandString()); + + // with variables + cmd = new SQLCommand("select * from test where a=@b;"); + assertEquals("select * from test where a=null", cmd.getCommandString()); + SQLCommand.registerVariable("b", "'b'"); + assertEquals("select * from test where a='b'", cmd.getCommandString()); + cmd = new SQLCommand("select * from test where a='@b';"); + assertEquals("select * from test where a='@b'", cmd.getCommandString()); + } + + public void testQuoteCount() { + StringBuffer buf = new StringBuffer("select * from test"); + assertEquals(0, SQLCommand.getQuoteCount(buf)); + buf.append(" where a='b"); + assertEquals(1, SQLCommand.getQuoteCount(buf)); + buf.append(" '"); + assertEquals(2, SQLCommand.getQuoteCount(buf)); + + } +} |
From: SVN by r. <sv...@ca...> - 2009-09-18 11:55:31
|
Author: roy Date: 2009-09-18 13:55:18 +0200 (Fri, 18 Sep 2009) New Revision: 417 Modified: ChangeLog Log: mention changes Modified: ChangeLog =================================================================== --- ChangeLog 2009-09-18 11:44:47 UTC (rev 416) +++ ChangeLog 2009-09-18 11:55:18 UTC (rev 417) @@ -2,6 +2,7 @@ * Rewritten tab completion engine - improved group by and order by - added support for aliases in table names + * Added initial settings command (to change for the current login session) the horizontal or vertical separator character 0.6.2 (2009-02-20) * Commandline input support |
From: SVN by r. <sv...@ca...> - 2009-09-18 11:45:10
|
Author: roy Date: 2009-09-18 13:44:47 +0200 (Fri, 18 Sep 2009) New Revision: 416 Added: src/main/java/nl/improved/sqlclient/commands/SettingsCommand.java Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java src/main/java/nl/improved/sqlclient/util/ResultBuilder.java Log: added support for setting vertical and horizontal separators Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-09-15 12:39:51 UTC (rev 415) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-09-18 11:44:47 UTC (rev 416) @@ -15,6 +15,7 @@ */ package nl.improved.sqlclient; +import nl.improved.sqlclient.commands.SettingsCommand; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; @@ -173,6 +174,7 @@ commands.register("QUIT[\\s]*", new QuitCommand("quit")); commands.register("EXIT[\\s]*", new QuitCommand("exit")); commands.register("SAVE[\\s]*.*", new SaveCommand()); + commands.register("SET[\\s]*.*", new SettingsCommand()); //commands.register("\\\\Q[\\s]*", new QuitCommand("\\q")); commands.register("@.*", new ExecuteBatchCommand(this)); commands.register("(SELECT|UPDATE|ALTER|INSERT|DELETE).*;[\\s]*", new QueryCommand()); Added: src/main/java/nl/improved/sqlclient/commands/SettingsCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/SettingsCommand.java 2009-09-15 12:39:51 UTC (rev 415) +++ src/main/java/nl/improved/sqlclient/commands/SettingsCommand.java 2009-09-18 11:44:47 UTC (rev 416) @@ -0,0 +1,63 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package nl.improved.sqlclient.commands; + +import nl.improved.sqlclient.Point; +import nl.improved.sqlclient.SQLCommand; +import nl.improved.sqlclient.TabCompletionInfo; +import nl.improved.sqlclient.util.ResultBuilder; + +/** + * + * @author roy + */ +public class SettingsCommand implements Command { + + public SettingsCommand() { + } + + public CommandResult execute(SQLCommand cmd) { + String cmdString = cmd.getUntrimmedCommandString().substring("set ".length()).trim(); + if (cmdString.indexOf(' ') < 0) { + return new SimpleCommandResult(false, "Please provide an argument"); + } + String setter = cmdString.substring(0, cmdString.indexOf(' ')); + if (setter.equals("hSeparatorChar")) { + ResultBuilder.setHorizontalSeparator(cmdString.charAt(cmdString.indexOf(' ')+1)); + return new SimpleCommandResult(true, "Horizontal separator updated to '"+ResultBuilder.getHorizontalSeparator()+"'."); + } + if (setter.equals("vSeparatorChar")) { + ResultBuilder.setVerticalSeparator(cmdString.charAt(cmdString.indexOf(' ')+1)); + return new SimpleCommandResult(true, "Vertical separator updated to '"+ResultBuilder.getVerticalSeparator()+"'."); + } + return new SimpleCommandResult(false, "Please provide a valid argument"); + + } + + public CharSequence getCommandString() { + return "set"; + } + + public TabCompletionInfo getTabCompletionInfo(SQLCommand commandInfo, Point commandPoint) { + return null; + } + + public CharSequence getHelp() { + return "Change settings of sqlshell properties" + + "Settings are:\n"+ + "hSeparatorChar\n"+ + "vSeparatorChar"; + } + + public boolean abort() { + return false; + } + + public boolean backgroundProcessSupported() { + return false; + } + +} Modified: src/main/java/nl/improved/sqlclient/util/ResultBuilder.java =================================================================== --- src/main/java/nl/improved/sqlclient/util/ResultBuilder.java 2009-09-15 12:39:51 UTC (rev 415) +++ src/main/java/nl/improved/sqlclient/util/ResultBuilder.java 2009-09-18 11:44:47 UTC (rev 416) @@ -1,7 +1,15 @@ package nl.improved.sqlclient.util; -import java.awt.event.ActionEvent; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +/** + * Converts query results to a readable format. + * @author roy + */ public class ResultBuilder { public enum Alignment {LEFT, RIGHT}; @@ -10,31 +18,31 @@ private List<String> header; private CharSequence footer; - private boolean horizontalSeperatorEnabled = true; - private char horizontalSeperator = '-', verticalSeparator ='|'; + private static boolean horizontalSeperatorEnabled = true; + private static char horizontalSeperator = '-', verticalSeparator ='|'; private RowList rows = new RowList(); - public void setHorizontalSeparatorEnabled(boolean enabled) { - this.horizontalSeperatorEnabled = enabled; + public static void setHorizontalSeparatorEnabled(boolean enabled) { + horizontalSeperatorEnabled = enabled; } - public boolean getHorizontalSeparatorEnabled() { + public static boolean getHorizontalSeparatorEnabled() { return horizontalSeperatorEnabled; } - public void setHorizontalSeparator(char c) { - this.horizontalSeperator = c; + public static void setHorizontalSeparator(char c) { + horizontalSeperator = c; } - public char getHorizontalSeparator() { + public static char getHorizontalSeparator() { return horizontalSeperator; } - public void setVerticalSeparator(char c) { - this.verticalSeparator = c; + public static void setVerticalSeparator(char c) { + verticalSeparator = c; } - public char getVerticalSeparator() { + public static char getVerticalSeparator() { return verticalSeparator; } |
From: SVN by r. <sv...@ca...> - 2009-09-15 13:06:49
|
Author: roy Date: 2009-09-15 14:39:51 +0200 (Tue, 15 Sep 2009) New Revision: 415 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java Log: fix export for null values (byte arrays) Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-08-06 18:31:54 UTC (rev 414) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-09-15 12:39:51 UTC (rev 415) @@ -1860,18 +1860,20 @@ byte[] bytes = new byte[bytesSize]; int read; InputStream valueStream = rs.getBinaryStream(col); - while ( (read = valueStream.read(bytes)) != -1) { - if (read == 0) { - continue; + if (valueStream != null) { + while ( (read = valueStream.read(bytes)) != -1) { + if (read == 0) { + continue; + } + if (read != bytes.length) { + bytes = Arrays.copyOf(bytes, read); + } + String stringValue = enc.encode(bytes) +"\n"; + hd.characters(stringValue.toCharArray(), 0, stringValue.length()); + if (bytes.length != bytesSize) { + bytes = new byte[bytesSize]; + } } - if (read != bytes.length) { - bytes = Arrays.copyOf(bytes, read); - } - String stringValue = enc.encode(bytes) +"\n"; - hd.characters(stringValue.toCharArray(), 0, stringValue.length()); - if (bytes.length != bytesSize) { - bytes = new byte[bytesSize]; - } } } else { atts.addAttribute("","","type","",Integer.toString(metaData.getColumnType(col))); |
From: SVN by r. <sv...@ca...> - 2009-08-06 18:32:07
|
Author: roy Date: 2009-08-06 20:31:54 +0200 (Thu, 06 Aug 2009) New Revision: 414 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java Log: fix tab completion for tablenames Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-08-03 07:46:11 UTC (rev 413) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-08-06 18:31:54 UTC (rev 414) @@ -868,7 +868,7 @@ protected List<String> getTableNames() { List<String> returnValue = new ArrayList<String>(); try { - ResultSet rs = getConnection().getMetaData().getTables(getConnection().getCatalog(), DBConnector.getInstance().getSchema(), "%", new String[]{"%"}); + ResultSet rs = getConnection().getMetaData().getTables(getConnection().getCatalog(), DBConnector.getInstance().getSchema(), "%", new String[]{"TABLE"}); while (rs.next()) { if (!returnValue.contains(rs.getString("TABLE_NAME"))) { returnValue.add(rs.getString("TABLE_NAME")); |
From: SVN by r. <sv...@ca...> - 2009-08-03 07:46:28
|
Author: roy Date: 2009-08-03 09:46:11 +0200 (Mon, 03 Aug 2009) New Revision: 413 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java src/main/java/nl/improved/sqlclient/history/HistoryPersister.java Log: rewrote history Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-08-02 15:24:51 UTC (rev 412) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-08-03 07:46:11 UTC (rev 413) @@ -60,7 +60,7 @@ import nl.improved.sqlclient.history.HistoryPersister; import nl.improved.sqlclient.history.exception.CouldNotLoadHistoryException; import nl.improved.sqlclient.history.exception.CouldNotSaveHistoryException; -import nl.improved.sqlclient.util.Function; +//import nl.improved.sqlclient.util.Function; import nl.improved.sqlclient.util.LimitedArrayList; //import nl.improved.sqlclient.util.oracle.Functions; import org.w3c.dom.Document; @@ -659,7 +659,7 @@ * Handle key input. * @param inp the character that is being pressed by the user. */ - protected void handleInput(InputKey inp) { + protected synchronized void handleInput(InputKey inp) { try { if (!inp.isSpecialKey() || (inp.getSpecialKeyValue() != InputKey.SpecialKey.PAGE_UP && inp.getSpecialKeyValue() != InputKey.SpecialKey.PAGE_DOWN)) { screen.setPageUpCount(0); // some character entered, so reset pageup count @@ -690,7 +690,7 @@ SQLCommand newSqlCommand = commandHistory.get(cIndex); String commandString = newSqlCommand.getCommandString(); if (commandString.matches(matchPattern)) { - commandHistory.remove(commandIndex); + commandHistory.remove(commandLines); commandIndex = commandHistory.indexOf(newSqlCommand); commandLines = newSqlCommand; Point cursorPosition = screen.getCursorPosition(); @@ -703,24 +703,10 @@ beep(); // TODO clear search?? return; } else if (executeCommand(sqlCommand)) { - // clear command history - if (commandIndex != commandHistory.size()-1) { - SQLCommand tmpLines = commandLines; - commandLines = commandHistory.get(commandHistory.size()-1); - if (commandLines.getCommandString().equals("")) { - commandHistory.add(commandHistory.size()-1, tmpLines); - } else { - commandHistory.add(tmpLines); - commandLines = tmpLines; - } - commandHistory.remove(commandIndex); - } - if (!commandLines.getCommandString().equals("")) { - commandLines = new SQLCommand(); - commandHistory.add(commandLines); - newLine(); - } + commandLines = new SQLCommand(); + commandHistory.add(commandLines); commandIndex = commandHistory.size()-1; + newLine(); Point cursorPosition = screen.getCursorPosition(); cursorPosition.y = commandLines.getLines().size()-1; cursorPosition.x = commandLines.getLines().get(cursorPosition.y).length(); @@ -816,20 +802,16 @@ * @return the editable version of the commandlines. */ protected SQLCommand getEditableCommand() { - if (commandHistory.indexOf(commandLines) != commandHistory.size()-1) { - List<? extends CharSequence> tmp = commandLines.getLines(); - if (commandHistory.get(commandHistory.size()-1).getLines().size() == 1 - && commandHistory.get(commandHistory.size()-1).getLines().get(0).length() == 0) { - commandLines = commandHistory.get(commandHistory.size()-1); - commandLines.getEditableLines().remove(0); - } else { - commandLines = new SQLCommand(); - commandHistory.add(commandLines); + if (commandIndex != commandHistory.size() -1) { + SQLCommand current = commandLines; + commandLines = new SQLCommand(); + commandLines.getEditableLines().clear(); + for (StringBuffer buf : current.getEditableLines()) { + commandLines.getEditableLines().add(new StringBuffer(buf)); } - for (int i = 0; i < tmp.size(); i++) { - commandLines.getEditableLines().add(new StringBuffer(tmp.get(i))); - } - commandIndex = commandHistory.size()-1; + commandHistory.add(commandLines); + commandIndex = commandHistory.size() -1; + } return commandLines; } Modified: src/main/java/nl/improved/sqlclient/history/HistoryPersister.java =================================================================== --- src/main/java/nl/improved/sqlclient/history/HistoryPersister.java 2009-08-02 15:24:51 UTC (rev 412) +++ src/main/java/nl/improved/sqlclient/history/HistoryPersister.java 2009-08-03 07:46:11 UTC (rev 413) @@ -88,7 +88,7 @@ return tot; } catch (IOException e) { history.add(EMPTY_COMMAND); - shell.setCommandIndex(0); + //shell.setCommandIndex(0); throw new CouldNotLoadHistoryException(e); } } |
From: SVN by r. <sv...@ca...> - 2009-08-02 15:25:08
|
Author: roy Date: 2009-08-02 17:24:51 +0200 (Sun, 02 Aug 2009) New Revision: 412 Modified: src/main/java/nl/improved/sqlclient/commands/InfoCommand.java Log: added some system functions in desc Modified: src/main/java/nl/improved/sqlclient/commands/InfoCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/InfoCommand.java 2009-08-02 15:24:06 UTC (rev 411) +++ src/main/java/nl/improved/sqlclient/commands/InfoCommand.java 2009-08-02 15:24:51 UTC (rev 412) @@ -15,7 +15,6 @@ */ package nl.improved.sqlclient.commands; -import java.util.List; import nl.improved.sqlclient.Point; import nl.improved.sqlclient.TabCompletionInfo; import nl.improved.sqlclient.SQLCommand; @@ -60,6 +59,13 @@ while (rs.next()) { returnValue.append(" : "+ rs.getString("TABLE_SCHEM")+"\n"); } + returnValue.append("System: "); + returnValue.append(metaData.getSystemFunctions()); + returnValue.append("\nTimeDate"); + returnValue.append(metaData.getTimeDateFunctions()); + returnValue.append("\nNumeric"); + returnValue.append(metaData.getNumericFunctions()); + returnValue.append('\n'); } catch (SQLException ex) { throw new IllegalStateException("Failed to find table info: "+ ex, ex); } |
From: SVN by r. <sv...@ca...> - 2009-08-02 15:24:23
|
Author: roy Date: 2009-08-02 17:24:06 +0200 (Sun, 02 Aug 2009) New Revision: 411 Modified: src/main/java/nl/improved/sqlclient/charva/CharvaSQLShellWindow.java Log: added some debug info Modified: src/main/java/nl/improved/sqlclient/charva/CharvaSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/charva/CharvaSQLShellWindow.java 2009-07-30 07:33:38 UTC (rev 410) +++ src/main/java/nl/improved/sqlclient/charva/CharvaSQLShellWindow.java 2009-08-02 15:24:06 UTC (rev 411) @@ -149,6 +149,7 @@ try { int start = textComponent.getLineStartOffset(lineCount - (commandLines.size() - cursorPos.y)); textComponent.setCaretPosition(start + cursorPos.x + (Screen.PROMPT+" >").length()); + debug("Set caret position: "+ start+"+"+cursorPos.x+"+"+(Screen.PROMPT+" >").length()); } catch(Exception e) { debug("ERROR: failed to calculate line end: "+ lineCount +"-"+ cursorPos.y +"/"+ getScreenHeight()); } @@ -202,6 +203,7 @@ try { int start = textComponent.getLineStartOffset(lineCount - (commandLines.size() - cursorPos.y)); textComponent.setCaretPosition(start + cursorPos.x + (Screen.PROMPT+" >").length()); + debug("Set caret position: "+ start+"+"+cursorPos.x+"+"+(Screen.PROMPT+" >").length()); } catch(Exception e) { debug("ERROR: failed to calculate line end: "+ lineCount +"-"+ cursorPos.y +"/"+ getScreenHeight()); } |
From: SVN by r. <sv...@ca...> - 2009-07-30 08:00:37
|
Author: roy Date: 2009-07-30 09:33:38 +0200 (Thu, 30 Jul 2009) New Revision: 410 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java Log: read command fixes Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-04-26 14:07:47 UTC (rev 409) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-07-30 07:33:38 UTC (rev 410) @@ -1823,7 +1823,12 @@ int rowCount = 0; PrintWriter out = null; try { - File f = new File(toFileName(dumpFileName +".dmp")); + File f; + if (dumpFileName.toLowerCase().endsWith(".dmp")) { + f = new File(toFileName(dumpFileName)); + } else { + f = new File(toFileName(dumpFileName +".dmp")); + } fileName = f.getAbsolutePath(); if ((f.exists() && !f.canWrite()) || (!f.exists() && !f.createNewFile())) { throw new IllegalStateException("Failed to create spool to file: '"+fileName+"'"); @@ -1854,7 +1859,7 @@ ResultSetMetaData metaData = rs.getMetaData(); for (int col = 1; col <= metaData.getColumnCount(); col++) { atts.addAttribute("","","name","",metaData.getColumnName(col)); - if (metaData.getColumnType(col) == Types.DATE) { + if (metaData.getColumnType(col) == Types.DATE || metaData.getColumnType(col) == Types.TIMESTAMP) { atts.addAttribute("","","type","","date"); atts.addAttribute("","","type_name","",metaData.getColumnTypeName(col)); hd.startElement("","","col",atts); |
From: SVN by r. <sv...@ca...> - 2009-04-26 14:08:00
|
Author: roy Date: 2009-04-26 16:07:47 +0200 (Sun, 26 Apr 2009) New Revision: 409 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java src/main/java/nl/improved/sqlclient/DBConnector.java Log: show views as well (not working currently on oracle...) Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-04-26 13:20:44 UTC (rev 408) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-04-26 14:07:47 UTC (rev 409) @@ -886,7 +886,7 @@ protected List<String> getTableNames() { List<String> returnValue = new ArrayList<String>(); try { - ResultSet rs = getConnection().getMetaData().getTables(getConnection().getCatalog(), DBConnector.getInstance().getSchema(), null, new String[]{"TABLE"}); + ResultSet rs = getConnection().getMetaData().getTables(getConnection().getCatalog(), DBConnector.getInstance().getSchema(), "%", new String[]{"%"}); while (rs.next()) { if (!returnValue.contains(rs.getString("TABLE_NAME"))) { returnValue.add(rs.getString("TABLE_NAME")); Modified: src/main/java/nl/improved/sqlclient/DBConnector.java =================================================================== --- src/main/java/nl/improved/sqlclient/DBConnector.java 2009-04-26 13:20:44 UTC (rev 408) +++ src/main/java/nl/improved/sqlclient/DBConnector.java 2009-04-26 14:07:47 UTC (rev 409) @@ -197,7 +197,7 @@ try { DatabaseMetaData metaData = activeConnection.getMetaData(); ResultSet rs = metaData.getTables(activeConnection.getCatalog(), getSchema() - , null, new String[]{"TABLE"}); + , null, null); while (rs.next()) { String tableName = rs.getString("TABLE_NAME"); tableNames.put(tableName.toLowerCase(), tableName); |
From: SVN by r. <sv...@ca...> - 2009-04-26 13:21:04
|
Author: roy Date: 2009-04-26 15:20:44 +0200 (Sun, 26 Apr 2009) New Revision: 408 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java Log: fix insert from past causing an indexoutofbounds in some cases Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-04-26 12:33:02 UTC (rev 407) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-04-26 13:20:44 UTC (rev 408) @@ -769,11 +769,11 @@ // check if the new line is becoming too long if (currentLine.length() > screen.MAX_LINE_LENGTH) { // TODO search for lastspace that is not between '' ?? - int lastSpace = SQLUtil.getLastBreakIndex(currentLine.toString());//currentLine.lastIndexOf(" "); - int lastChar = currentLine.charAt(lastSpace); + int lastSpace = SQLUtil.getLastBreakIndex(currentLine.toString().substring(0, screen.MAX_LINE_LENGTH-2));//currentLine.lastIndexOf(" "); if (lastSpace == -1) { lastSpace = currentLine.length(); } + int lastChar = currentLine.charAt(lastSpace); // check if there are enough 'next' lines // if not.. add one if (editableLines.size()-1 == cursorPosition.y) { |
From: SVN by r. <sv...@ca...> - 2009-04-26 12:33:10
|
Author: roy Date: 2009-04-26 14:33:02 +0200 (Sun, 26 Apr 2009) New Revision: 407 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java Log: some command history fixes Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-04-26 12:02:00 UTC (rev 406) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-04-26 12:33:02 UTC (rev 407) @@ -348,7 +348,7 @@ } return; } - StringBuffer lineBuffer = commandLines.getEditableLines().get(cursorPosition.y); + StringBuffer lineBuffer = getEditableCommand().getEditableLines().get(cursorPosition.y); int previousBreak = SQLUtil.getLastBreakIndex(lineBuffer.substring(0, cursorPosition.x-1)); if (lineBuffer.charAt(previousBreak) == ' ' || lineBuffer.charAt(previousBreak) == '\t') { previousBreak++; @@ -366,10 +366,11 @@ public void execute() { Point cursorPosition = screen.getCursorPosition(); if (cursorPosition.x > 0) { - StringBuffer lineBuffer = commandLines.getEditableLines().get(cursorPosition.y); + StringBuffer lineBuffer = getEditableCommand().getEditableLines().get(cursorPosition.y); lineBuffer.delete(0, cursorPosition.x); cursorPosition.x = 0; } else if (cursorPosition.y > 0) { + SQLCommand commandLines = getEditableCommand(); StringBuffer lineBuffer = commandLines.getEditableLines().get(cursorPosition.y); if (lineBuffer.length() == 0) { commandLines.getEditableLines().remove(cursorPosition.y); |
From: SVN by r. <sv...@ca...> - 2009-04-26 12:02:14
|
Author: roy Date: 2009-04-26 14:02:00 +0200 (Sun, 26 Apr 2009) New Revision: 406 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java Log: don't return null when save has an invalid option Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-04-20 20:14:57 UTC (rev 405) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-04-26 12:02:00 UTC (rev 406) @@ -2276,7 +2276,7 @@ } } - return null; + return new SimpleCommandResult(false, "Uknown option for save. See 'help save' for options"); } public CharSequence getCommandString() { |
From: SVN by r. <sv...@ca...> - 2009-04-20 20:15:09
|
Author: roy Date: 2009-04-20 22:14:57 +0200 (Mon, 20 Apr 2009) New Revision: 405 Modified: src/main/java/nl/improved/sqlclient/charva/CharvaSQLShellWindow.java Log: remove debug statement Modified: src/main/java/nl/improved/sqlclient/charva/CharvaSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/charva/CharvaSQLShellWindow.java 2009-04-20 20:12:45 UTC (rev 404) +++ src/main/java/nl/improved/sqlclient/charva/CharvaSQLShellWindow.java 2009-04-20 20:14:57 UTC (rev 405) @@ -88,7 +88,7 @@ @Override public void paint(final Screen screen) { - debug("PageUpCount: "+ screen.getPageUpCount()); + //debug("PageUpCount: "+ screen.getPageUpCount()); if (screen.getPageUpCount() > 0) { paintSlow(screen); return; |
From: SVN by r. <sv...@ca...> - 2009-04-20 20:12:58
|
Author: roy Date: 2009-04-20 22:12:45 +0200 (Mon, 20 Apr 2009) New Revision: 404 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java Log: uncomment printstacktrace Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-04-20 19:27:31 UTC (rev 403) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2009-04-20 20:12:45 UTC (rev 404) @@ -729,7 +729,7 @@ } CharSequence newText; if (inp.getCharacter() == '\t') { - new Throwable().printStackTrace(); + //new Throwable().printStackTrace(); try { Point cursorPosition = screen.getCursorPosition(); newText = getTabCompletion(commandLines, cursorPosition); |
From: SVN by r. <sv...@ca...> - 2009-04-20 19:27:38
|
Author: roy Date: 2009-04-20 21:27:31 +0200 (Mon, 20 Apr 2009) New Revision: 403 Modified: src/main/java/nl/improved/sqlclient/QueryExecutor.java Log: fix start time Modified: src/main/java/nl/improved/sqlclient/QueryExecutor.java =================================================================== --- src/main/java/nl/improved/sqlclient/QueryExecutor.java 2009-04-16 09:06:27 UTC (rev 402) +++ src/main/java/nl/improved/sqlclient/QueryExecutor.java 2009-04-20 19:27:31 UTC (rev 403) @@ -167,6 +167,7 @@ */ protected Iterator<CharSequence> executeQuery(CharSequence command) throws SQLException { cancelled = false; + long start = System.currentTimeMillis(); ResultSet results = DBConnector.getInstance().getStatement().executeQuery(command.toString()); //StringBuffer separator = new StringBuffer(); @@ -180,7 +181,7 @@ labels.add(metadata.getColumnLabel(col)); } - return new QueryExecutorIterator(results, labels, metadata); + return new QueryExecutorIterator(start, results, labels, metadata); } private class QueryExecutorIterator implements Iterator<CharSequence> { @@ -189,11 +190,12 @@ private List<String> labels; private int rowCount = 0; private int columnCount; - private long start = System.currentTimeMillis(); + private long start; private ResultSetMetaData metadata; private boolean next = true; - public QueryExecutorIterator(ResultSet results, List<String> labels, ResultSetMetaData metadata) throws SQLException { + public QueryExecutorIterator(long start, ResultSet results, List<String> labels, ResultSetMetaData metadata) throws SQLException { + this.start = start; this.results = results; this.labels = labels; this.metadata = metadata; |
From: SVN by r. <sv...@ca...> - 2009-04-16 09:06:33
|
Author: roy Date: 2009-04-16 11:06:27 +0200 (Thu, 16 Apr 2009) New Revision: 402 Modified: src/main/java/nl/improved/sqlclient/QueryExecutor.java Log: added support for oracle rowid select Modified: src/main/java/nl/improved/sqlclient/QueryExecutor.java =================================================================== --- src/main/java/nl/improved/sqlclient/QueryExecutor.java 2009-03-31 19:41:04 UTC (rev 401) +++ src/main/java/nl/improved/sqlclient/QueryExecutor.java 2009-04-16 09:06:27 UTC (rev 402) @@ -139,6 +139,12 @@ if (colValue == null) { return "NULL"; } else { + if (colValue.getClass().getName().equals("oracle.sql.ROWID")) { + try { + java.lang.reflect.Method m = colValue.getClass().getMethod("stringValue"); + return m.invoke(colValue).toString(); + } catch (Throwable ex) {/* ignore .. probable no oracle jdbc in classpath*/ } + } return colValue.toString(); } } |