├── .gitignore ├── .settings └── org.eclipse.jdt.core.prefs ├── LICENSE ├── README.md ├── pom.xml └── src └── main ├── java └── com │ └── xigole │ └── util │ └── sql │ ├── Jisql.java │ ├── MaskingThread.java │ └── outputformatter │ ├── CSVFormatter.java │ ├── DefaultFormatter.java │ ├── JisqlFormatter.java │ ├── NullFormatter.java │ └── XMLFormatter.java └── scripts ├── runit ├── runit.bat └── runit_query /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | -------------------------------------------------------------------------------- /.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 3 | org.eclipse.jdt.core.compiler.compliance=1.7 4 | org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled 5 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 6 | org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore 7 | org.eclipse.jdt.core.compiler.processAnnotations=disabled 8 | org.eclipse.jdt.core.compiler.release=disabled 9 | org.eclipse.jdt.core.compiler.source=1.7 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # jisql 2 | A simple utility to provide a command line interactive session with any SQL server with a JDBC driver 3 | 4 | Jisql is a Java based utility to provide a command line interactive session 5 | with a SQL server. This application is conceptually modeled on the Sybase 6 | 'isql' program with, obviously, strong similarities to Microsoft SQL/Server 7 | isql and osql (as Microsoft got SQL Server from Sybase). 8 | 9 | The program can act in a similar way to Oracle's sqlplus and PostgreSQL's psql. 10 | 11 | The complete Jisql package can be downloaded from: 12 | 13 | https://github.com/stdunbar/jisql 14 | 15 | A simple command line might look like (this should be all on one line) is: 16 | 17 | `java -cp lib/jisql-2.0.11.jar:lib/jopt-simple-3.2.jar: 18 | com.xigole.util.sql.Jisql -user scott -password blah -driver postgresql 19 | -cstring jdbc:postgresql://localhost:5432/scott -c \;` 20 | 21 | This logs into a PostgreSQL database as the user "scott", password "blah". It 22 | connects to the database named "scott". It uses the command terminator of ";", 23 | just like psql or sqlplus (which is escaped in the example so that it will not 24 | be interpreted by the Unix shell). If you do not use this the default is the 25 | term "go" on a single line like Sybase's isql or MS/SQL's isql/osql. Note that 26 | this command line sample does not use the included javacsv.jar so you could 27 | only use the XML or default output formatter (see below for more information). 28 | 29 | New in version 2.0.x 30 | The biggest change in version 2 is the addition of separate output 31 | formatters. Basically this allows you to more easily customize the output 32 | for your application. There are three formatters that are included with 33 | the distribution: 34 | 35 | * Default (does not have to be specified on the command line). This is 36 | the default formatter and it behaves like a "normal" format command line 37 | interface. Output is wrapped in "pretty" formatters (a highly subjective 38 | term). If you've used a database command line tool then this format will 39 | very likely feel familar. 40 | 41 | * CSV The output follows a Comma Separated Values format. The default 42 | separator is a comma but any other character can be used. I like using the 43 | pipe character as it makes parsing the output very easy. 44 | 45 | * XML The output is a very simple XML tree. Basically there is the normal 46 | XML processing instruction at the top and then every row is output with 47 | the column names. 48 | 49 | There is now a dependency on JOpt Simple in for the base 50 | configuration. Additionally, if you are using the CSVFormatter then it is 51 | dependent on Java CSV. 52 | 53 | ## New in version 2.0.5 54 | There is a bit better versioning information available. The jar has been 55 | renamed to include the version so that you can quickly see what you're 56 | running. This same version information is included in the code (run with 57 | -help or with no arguments to see the version) and in the jar manifest. 58 | 59 | ## New in version 2.0.12 60 | Moved to Maven for builds to help with dependencies. 61 | 62 | ## New in version 2.1 63 | Added -fetchsize option. 64 | Added the Null formatter - useful when benchmarking how quickly we can 65 | retrieve data from a server since no time is spent actually processing 66 | the data. 67 | 68 | ## Command line options 69 | 70 | * -driver This option allows you to specify the JDBC driver class name of the driver. There are several shortcuts that can be used: 71 | * jconnect4 - short for com.sybase.jdbc.SybDriver 72 | * jconnect5 - short for com.sybase.jdbc2.jdbc.SybDriver 73 | * jconnect6 - short for com.sybase.jdbc3.jdbc.SybDriver 74 | * oraclethin - short for oracle.jdbc.driver.OracleDriver 75 | * db2app - the DB2 "App" driver - COM.ibm.db2.jdbc.app.DB2Driver 76 | * db2net - the DB2 "Net" driver - COM.ibm.db2.jdbc.net.DB2Driver 77 | * mssql - short for com.microsoft.jdbc.sqlserver.SQLServerDriver 78 | * cloudscape - short for COM.cloudscape.core.JDBCDriver 79 | * pointbase - short for com.pointbase.jdbc.jdbcUniversalDriver 80 | * postgresql - short for org.postgresql.Driver 81 | * mysqlconj - short for com.mysql.jdbc.Driver - the Connector/J driver for MySQL 82 | * mysqlcaucho - short for com.caucho.jdbc.mysql.Driver - the Caucho driver for MySQL 83 | * Alternatively, any class name can be specified here. The shortcuts only 84 | exist for those of us who generate more typos than real text :) 85 | 86 | * -cstring This option allows you to specify the connection string to the 87 | database. This string is driver specific but almost always starts with 88 | "jdbc:". Connection strings for the drivers I have tested look like: 89 | 90 | * jconnect4, jconnect5, jconnect6 - Sybase connection strings take the form "jdbc:sybase:Tds:[hostname]:[port]/[dbName]" 91 | * oraclethin - The Oracle "thin" driver connection string looks like "jdbc:oracle:thin:@[hostname]:[port]:[oracle sid]" 92 | * db2app - The DB2 "App" driver connection string looks like "jdbc:db2:[dbName]" 93 | * db2net - The DB2 "Net" driver connection string looks like "jdbc:db2://[hostname]:[port]/[dbName]" 94 | * mssql - The MS/SQL driver connection string looks like "jdbc:microsoft:sqlserver://[hostname]:[port]/[dbName]" 95 | * cloudscape - The Cloudscape driver connection string looks like "jdbc:cloudscape:[dbName];create=true;autocommit=false" 96 | * pointbase - The Pointbase driver connection string looks like "jdbc:pointbase:server://[hostname]:[port]/[dbName]" 97 | * postgresql - The PostgreSQL driver connection string looks like "jdbc:postgresql://[hostname]:[port]/[dbName]" 98 | * mysqlconj - The MySQL Connector/J driver connection string looks like "jdbc:mysql://[hostname]:[port]/[dbName]" 99 | * mysqlcaucho - The MySQL Cahcho driver connection string looks like "jdbc:mysql-caucho://[hostname]:[port]/[dbName]" 100 | 101 | **Important** - each JDBC vendor has other flags and parameters that can be 102 | passed on the connection string. You should look at the documentation for 103 | your JDBC driver for more information. The strings listed are just a sample 104 | and may change with a new release of the driver. None of these strings are 105 | coded within the application - the list is provided for reference only. 106 | 107 | * -user or -u The user name to use to log into the database with. 108 | * -password or -p The password to use to log into the database with. If this 109 | option is missing then the program asks for the password. 110 | * -pf Optional file to specify the password. This prevents having to have it 111 | visible when looking at a process status. The first line of the file is read 112 | and used as the password. If both the command line password and this option 113 | are specified the command line password is used. 114 | * -c The "command terminator" to use. By default this application uses the 115 | string "go" (case insensitive) on a line by itself to determine when to 116 | send the string buffer to the database. You may specify something else 117 | with the -c option. For example, users of Oracle may prefer either the ";" 118 | (semi-colon) character or the "/" (forwardslash) character as that is what 119 | sqlplus uses. This string may occur as a standalone line or at the end of 120 | a particular line. 121 | * -input The name of a file to read commands from instead of System.in. 122 | * -query An optional single query to run instead of interacting with the 123 | command line or a file. Note - the command must have a command terminator. So, 124 | for example, your command line may be something like "-c \; -query "select * 125 | from blah;". If you do not include the command terminator then the command 126 | will hang, waiting for you to enter the default "go". 127 | * -fetchsize An optional value to set the "fetch size" on the connection. 128 | Fetch size controls how much data is returned from the database per request to the 129 | server and can have a significant impact on performance when fetching large numbers 130 | of rows. 131 | * -debug This turns on some internal debugging code. Not generally useful. 132 | * -driverinfo Allows you to print some information that the driver 133 | returns. Generally not very useful in all but a few cases. 134 | * -formatter Optionally specify a class name or short cut to format the 135 | output. There are three built in short cuts: 136 | * *csv* output the data in CSV format. 137 | * *xml* output the data in XML format. 138 | * *null* ignore all output. 139 | * *default* (does not have to be specified) - output the format in the "normal" format. 140 | * Otherwise, this is a class name that implements 141 | com.xigole.util.sql.outputformatter.JisqlFormatter. See the code for more 142 | information on implementing your own output formatter. 143 | 144 | 145 | The included default formatter supports the following command line options: 146 | * -noheader do not print the header column info. 147 | * -spacer The character to use for "empty" space. This defaults to the space 148 | character. From mrider - "I added the ability to specify the spacer for columns 149 | which used to be the single char ' '. I did this because of brain-dead 150 | Windows' command line copy/paste. It seems that when a line of text ends in 151 | space, copy does not copy that space. Which makes it difficult to copy/paste 152 | into another program. This can probably be ignored most of the time." 153 | * -w Specifies the maximum field width for a column. By default jisql defaults 154 | columns to a maximum width of 2048. By specifying a value for this jisql 155 | with truncate the output of columns that are wider than this parameter. 156 | * -delimiter Specify a single character delimiter for columns. 157 | * -trim trim the spaces from columns. 158 | * -nonull print an empty string instead of the word "NULL" when there is a null value. 159 | * -left left justify the output 160 | * -debug print debugging information about the result set. 161 | 162 | 163 | The include CSV formatter supports the following command line options: 164 | 165 | * -delimiter specifies the delimiter to use. By default a comma is used 166 | * -colnames if included then column names are printed as the first line of 167 | output. By default they are not included 168 | 169 | 170 | The included XML formatter does not have any additional output options. 171 | 172 | ## Building 173 | Jisql now uses a standard source code tree format along with a Maven pom.xml 174 | file. To build you would run: 175 | 176 | `mvn package` 177 | 178 | This will create a jisql.jar in the directory "target" along with a 179 | jisql-jar-with-dependencies.jar. Either of these can be used as you 180 | need. Please understand though that the dependencies jar will not 181 | contain your JDBC driver. 182 | 183 | 184 | ## Copyright 185 | Copyright (C) 2004-2015 Scott Dunbar (scott@xigole.com) 186 | 187 | Licensed under the Apache License, Version 2.0 (the "License"); you may not 188 | use this file except in compliance with the License. You may obtain a copy 189 | of the License at 190 | 191 | http://www.apache.org/licenses/LICENSE-2.0 192 | 193 | Unless required by applicable law or agreed to in writing, software distributed 194 | under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 195 | CONDITIONS OF ANY KIND, either express or implied. See the License for the 196 | specific language governing permissions and limitations under the License. 197 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | com.xigole 7 | 4.0.0 8 | jisql 9 | 2.1.0 10 | Xigole Jisql 11 | jar 12 | 13 | 14 | 1.7 15 | 3.0.0 16 | UTF-8 17 | 18 | 19 | 20 | ${maven.min.version} 21 | 22 | 23 | 24 | 25 | net.sourceforge.javacsv 26 | javacsv 27 | 2.0 28 | 29 | 30 | 31 | net.sf.jopt-simple 32 | jopt-simple 33 | 3.2 34 | 35 | 36 | 37 | 38 | jisql 39 | 40 | 41 | 42 | org.apache.maven.plugins 43 | maven-compiler-plugin 44 | 2.3.2 45 | 46 | ${java.min.version} 47 | ${java.min.version} 48 | 49 | 50 | 51 | 52 | org.apache.maven.plugins 53 | maven-assembly-plugin 54 | 2.4.1 55 | 56 | 57 | jar-with-dependencies 58 | 59 | 60 | 61 | com.xigole.util.sql.Jisql 62 | true 63 | 64 | 65 | 66 | 67 | 68 | make-assembly 69 | package 70 | 71 | single 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /src/main/java/com/xigole/util/sql/Jisql.java: -------------------------------------------------------------------------------- 1 | package com.xigole.util.sql; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.Console; 5 | import java.io.File; 6 | import java.io.FileNotFoundException; 7 | import java.io.FileReader; 8 | import java.io.InputStreamReader; 9 | import java.sql.Connection; 10 | import java.sql.DatabaseMetaData; 11 | import java.sql.Driver; 12 | import java.sql.DriverManager; 13 | import java.sql.DriverPropertyInfo; 14 | import java.sql.ResultSet; 15 | import java.sql.ResultSetMetaData; 16 | import java.sql.SQLException; 17 | import java.sql.Statement; 18 | import java.util.Properties; 19 | 20 | import joptsimple.OptionParser; 21 | import joptsimple.OptionSet; 22 | 23 | import com.xigole.util.sql.outputformatter.JisqlFormatter; 24 | 25 | /** 26 | * A simple utility to provide an interactive session with a SQL server. This 27 | * application is conceptually modeled on the Sybase 'isql' program with, 28 | * obviously, strong similarities to Microsoft SQL/Server isql and osql (as 29 | * Microsoft got SQL Server from Sybase). 30 | *

31 | * 32 | * The program can act in a similar way to Oracle's sqlplus and PostgreSQL's 33 | * psql. 34 | *

35 | * 36 | * A simple command line might look like (this should be all on one line) is:
37 | * 38 | * java -classpath lib/jisql.jar:<file containing native driver> 39 | * com.xigole.util.sql.Jisql -user scott -password blah -driver postgresql 40 | * -cstring jdbc:postgresql://localhost:5432/scott -c \; 41 | * 42 | *

43 | * 44 | * This logs into a PostgreSQL database as the user "scott", password "blah". It 45 | * connects to the database named "scott". It uses the command terminator of 46 | * ";", just like psql or sqlplus (which is escaped in the example so that it 47 | * will not be interpreted by the Unix shell). If you do not use this the 48 | * default is the term "go" on a single line like Sybase's isql or MS/SQL's 49 | * isql/osql. Note that there is a dependency on JOpt Simple in for the base 51 | * configuration. Additionally, if you are using the CSVFormatter then it is 52 | * dependent on Java CSV. 53 | *

54 | * 55 | * 56 | * Options: 57 | *

162 | *

163 | *   164 | *

165 | * The included default formatter supports the following command line options: 166 | * 187 | *

188 | *   189 | *

190 | * The include CSV formatter supports the following command line options: 191 | * 197 | *

198 | *   199 | *

200 | * The included XML formatter does not have any additional output options. 201 | *

202 | *   203 | *

204 | * 205 | * Copyright (C) 2004-2011 Scott Dunbar (scott@xigole.com) 206 | *

207 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not 208 | * use this file except in compliance with the License. You may obtain a copy of 209 | * the License at 210 | *

211 | * http://www.apache.org/licenses/LICENSE-2.0 212 | *

213 | * Unless required by applicable law or agreed to in writing, software 214 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 215 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 216 | * License for the specific language governing permissions and limitations under 217 | * the License. 218 | * 219 | */ 220 | 221 | public class Jisql { 222 | private static final String sybaseJConnect6DriverName = "com.sybase.jdbc3.jdbc.SybDriver"; 223 | private static final String sybaseJConnect5DriverName = "com.sybase.jdbc2.jdbc.SybDriver"; 224 | private static final String sybaseJConnect4DriverName = "com.sybase.jdbc.SybDriver"; 225 | private static final String oracleThinDriverName = "oracle.jdbc.driver.OracleDriver"; 226 | private static final String db2AppDriverName = "COM.ibm.db2.jdbc.app.DB2Driver"; 227 | private static final String db2NetDriverName = "COM.ibm.db2.jdbc.net.DB2Driver"; 228 | private static final String cloudscapeDriverName = "COM.cloudscape.core.JDBCDriver"; 229 | private static final String msqlDriverName = "com.microsoft.jdbc.sqlserver.SQLServerDriver"; 230 | private static final String pointbaseDriverName = "com.pointbase.jdbc.jdbcUniversalDriver"; 231 | private static final String postgresqlDriverName = "org.postgresql.Driver"; 232 | private static final String mySQLConnectJDriverName = "com.mysql.jdbc.Driver"; 233 | private static final String mySQLCauchoDriverName = "com.caucho.jdbc.mysql.Driver"; 234 | 235 | private static final String defaultFormatterClassName = "com.xigole.util.sql.outputformatter.DefaultFormatter"; 236 | private static final String csvFormatterClassName = "com.xigole.util.sql.outputformatter.CSVFormatter"; 237 | private static final String xmlFormatterClassName = "com.xigole.util.sql.outputformatter.XMLFormatter"; 238 | 239 | private String driverName = null; 240 | private String connectString = null; 241 | private String userName = null; 242 | private String password = null; 243 | private String passwordFileName = null; 244 | private String formatterClassName = defaultFormatterClassName; 245 | private int fetchSize = 0; 246 | 247 | private JisqlFormatter formatter = null; 248 | 249 | private Connection connection = null; 250 | private boolean printDebug = false; 251 | private boolean printDriverDetails = false; 252 | private Driver driver = null; 253 | private Properties props = null; 254 | private String inputFileName = null; 255 | private String commandTerminator = "go"; 256 | private String inputQuery = null; 257 | 258 | /** 259 | * Runs Jisql with the command line arguments provided. 260 | * 261 | */ 262 | public static void main(String argv[]) { 263 | Jisql jisql = new Jisql(); 264 | 265 | try { 266 | jisql.parseArgs(argv); 267 | } 268 | catch (Throwable t) { 269 | t.printStackTrace(); 270 | jisql.usage(); 271 | System.exit(1); 272 | } 273 | 274 | try { 275 | jisql.run(); 276 | } 277 | catch (Exception e) { 278 | e.printStackTrace(); 279 | System.exit(1); 280 | } 281 | 282 | System.exit(0); 283 | } 284 | 285 | public void run() throws Exception { 286 | 287 | try { 288 | driver = (Driver) Class.forName(driverName).newInstance(); 289 | props = new Properties(); 290 | 291 | props.put("user", userName); 292 | if (password != null) 293 | props.put("password", password); 294 | 295 | connection = DriverManager.getConnection(connectString, props); 296 | if (printDriverDetails) { 297 | printDriverInfo(); 298 | } 299 | else { 300 | doIsql(); 301 | } 302 | } 303 | catch (SQLException sqle) { 304 | printAllExceptions(sqle); 305 | } 306 | catch (ClassNotFoundException cnfe) { 307 | System.err.println("Cannot find the driver class \"" + driverName + "\" in the current classpath."); 308 | } 309 | catch (InstantiationException ie) { 310 | System.err.println("Cannot instantiate the driver class \"" + driverName + "\""); 311 | ie.printStackTrace(System.err); 312 | } 313 | catch (IllegalAccessException iae) { 314 | System.err.println("Cannot instantiate the driver class \"" + driverName + "\" because of an IllegalAccessException"); 315 | iae.printStackTrace(System.err); 316 | } 317 | finally { 318 | if (connection != null) { 319 | try { 320 | connection.close(); 321 | } 322 | catch (SQLException ignore) { 323 | /* ignored */ 324 | } 325 | } 326 | } 327 | } 328 | 329 | /** 330 | * The main loop for the Jisql program. This method handles the input from 331 | * either a command line or from a file. Output is handled through the 332 | * Formatter. 333 | * 334 | * @throws SQLException 335 | * if an exception occurs. 336 | * 337 | */ 338 | public void doIsql() throws SQLException { 339 | BufferedReader reader = null; 340 | Statement statement = null; 341 | ResultSet resultSet = null; 342 | ResultSetMetaData resultSetMetaData = null; 343 | StringBuffer query = null; 344 | 345 | if (inputFileName != null) { 346 | try { 347 | reader = new BufferedReader(new FileReader(inputFileName)); 348 | } 349 | catch (FileNotFoundException fnfe) { 350 | System.err.println("Unable to open \"" + inputFileName + "\""); 351 | fnfe.printStackTrace(System.err); 352 | return; 353 | } 354 | } 355 | else { 356 | reader = new BufferedReader(new InputStreamReader(System.in)); 357 | } 358 | 359 | printAllExceptions(connection.getWarnings()); 360 | statement = connection.createStatement(); 361 | if (fetchSize > 0) { 362 | statement.setFetchSize(fetchSize); 363 | } 364 | 365 | connection.clearWarnings(); 366 | 367 | while (true) { 368 | int linecount = 1; 369 | query = new StringBuffer(); 370 | 371 | try { 372 | if ((inputFileName == null) && (inputQuery == null)) 373 | System.out.print("\nEnter a query:\n"); 374 | 375 | while (true) { 376 | if ((inputFileName == null) && (inputQuery == null)) { 377 | System.out.print(linecount++ + " > "); 378 | System.out.flush(); 379 | } 380 | 381 | String line = null; 382 | if (inputQuery == null) 383 | line = reader.readLine(); 384 | else 385 | line = inputQuery.toString(); 386 | 387 | if (line == null || line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("exit")) 388 | return; 389 | 390 | if (line.equals("reset")) { 391 | query = new StringBuffer(); 392 | break; 393 | } 394 | 395 | if (line.trim().equalsIgnoreCase(commandTerminator) || line.trim().endsWith(commandTerminator)) { 396 | if (line.trim().endsWith(commandTerminator)) { 397 | line = line.substring(0, line.length() - commandTerminator.length()); 398 | query.append("\n"); 399 | query.append(line); 400 | } 401 | break; 402 | } 403 | 404 | query.append("\n"); 405 | query.append(line); 406 | } 407 | 408 | if (query.toString().length() == 0) 409 | continue; 410 | 411 | if (printDebug) 412 | System.out.println("executing: " + query.toString()); 413 | 414 | boolean moreResults = statement.execute(query.toString()); 415 | int rowsAffected = 0; 416 | do { 417 | printAllExceptions(statement.getWarnings()); 418 | statement.clearWarnings(); 419 | if (moreResults) { 420 | resultSet = statement.getResultSet(); 421 | 422 | printAllExceptions(resultSet.getWarnings()); 423 | resultSet.clearWarnings(); 424 | resultSetMetaData = resultSet.getMetaData(); 425 | 426 | formatter.formatHeader(System.out, resultSetMetaData); 427 | formatter.formatData(System.out, resultSet, resultSetMetaData); 428 | formatter.formatFooter(System.out, resultSetMetaData); 429 | 430 | int rowsSelected = statement.getUpdateCount(); 431 | 432 | if (rowsSelected >= 0) { 433 | System.out.println(rowsSelected + " rows affected."); 434 | } 435 | } 436 | else { 437 | rowsAffected = statement.getUpdateCount(); 438 | printAllExceptions(statement.getWarnings()); 439 | statement.clearWarnings(); 440 | if (rowsAffected >= 0) { 441 | System.out.println(rowsAffected + " rows affected."); 442 | } 443 | } 444 | 445 | // 446 | // I was having problems with the PostgreSQL driver throwing 447 | // a NullPointerException here so I just catch it and tell 448 | // the loop that it is done if it happens. 449 | // 450 | try { 451 | moreResults = statement.getMoreResults(); 452 | } 453 | catch (NullPointerException npe) { 454 | moreResults = false; 455 | } 456 | } 457 | 458 | while (moreResults || rowsAffected != -1); 459 | } 460 | catch (SQLException sqle) { 461 | printAllExceptions(sqle); 462 | statement.cancel(); 463 | statement.clearWarnings(); 464 | } 465 | catch (Exception e) { 466 | e.printStackTrace(System.err); 467 | } 468 | 469 | if (inputQuery != null) 470 | return; 471 | } 472 | } 473 | 474 | /** 475 | * Prints some information about the JDBC driver in use. 476 | * 477 | * @throws SQLException 478 | * if one of the methods called does. 479 | * 480 | */ 481 | private void printDriverInfo() throws SQLException { 482 | System.out.println("driver.getMajorVersion() is " + driver.getMajorVersion()); 483 | System.out.println("driver.getMinorVersion() is " + driver.getMinorVersion()); 484 | System.out.println("driver is " + (driver.jdbcCompliant() ? "" : "not ") + "JDBC compliant"); 485 | 486 | DriverPropertyInfo info[] = driver.getPropertyInfo(connectString, props); 487 | 488 | for (int i = 0; i < info.length; i++) { 489 | System.out.println("driver property named \"" + info[i].name + "\""); 490 | if (info[i].choices != null) { 491 | System.out.println("choices:"); 492 | for (int j = 0; j < info[i].choices.length; j++) 493 | System.out.println("\tchoice " + j + ": \"" + info[i].choices[j] + "\""); 494 | } 495 | System.out.println("description: \"" + info[i].description + "\""); 496 | System.out.println("required parameter?: \"" + info[i].required + "\""); 497 | System.out.println("current value: \"" + info[i].value + "\"\n"); 498 | } 499 | 500 | DatabaseMetaData metaData = connection.getMetaData(); 501 | 502 | System.out.println("metaData.getDatabaseProductName(): \"" + metaData.getDatabaseProductName() + "\""); 503 | System.out.println("metaData.getDatabaseProductVersion(): \"" + metaData.getDatabaseProductVersion() + "\""); 504 | 505 | System.out.println("metaData.getDriverName(): \"" + metaData.getDriverName() + "\""); 506 | System.out.println("metaData.getDriverVersion(): \"" + metaData.getDriverVersion() + "\""); 507 | } 508 | 509 | /** 510 | * Parse the command line arguments. This method parses what is needed for 511 | * the Jisql driver program and lets the configured formatter do the same. 512 | * 513 | * @param argv the command line arguments. 514 | * 515 | * @throws Exception if there are any errors parsing the command line arguments. 516 | * 517 | */ 518 | public void parseArgs(String argv[]) throws Throwable { 519 | // 520 | // I'm sure that there has to be a better way but I couldn't find a 521 | // command lineparser that would let me ignore unknown arguments. so 522 | // walk through the list once to find the formatter. then, use the 523 | // command line parser to do it "for real" 524 | // 525 | for (int argumentIndex = 0; argumentIndex < argv.length; argumentIndex++) { 526 | if (argv[argumentIndex].equals("-formatter")) { 527 | formatterClassName = argv[argumentIndex + 1]; 528 | break; 529 | } 530 | } 531 | 532 | if (formatterClassName.compareToIgnoreCase("csv") == 0) 533 | formatterClassName = csvFormatterClassName; 534 | else if (formatterClassName.compareToIgnoreCase("xml") == 0) 535 | formatterClassName = xmlFormatterClassName; 536 | else if (formatterClassName.compareToIgnoreCase("default") == 0) 537 | formatterClassName = defaultFormatterClassName; 538 | 539 | formatter = (JisqlFormatter) Class.forName(formatterClassName).newInstance(); 540 | 541 | OptionParser parser = new OptionParser(); 542 | parser.posixlyCorrect(false); 543 | 544 | parser.accepts("c").withRequiredArg().ofType(String.class); 545 | parser.accepts("cstring").withRequiredArg().ofType(String.class); 546 | parser.accepts("debug"); 547 | parser.accepts("driver").withRequiredArg().ofType(String.class); 548 | parser.accepts("driverinfo"); 549 | parser.accepts("fetchsize").withRequiredArg().ofType(Integer.class); 550 | parser.accepts("formatter").withRequiredArg().ofType(String.class); 551 | parser.accepts("help"); 552 | parser.accepts("input").withRequiredArg().ofType(String.class); 553 | parser.accepts("password").withOptionalArg().ofType(String.class); 554 | parser.accepts("p").withOptionalArg().ofType(String.class); 555 | parser.accepts("pf").withRequiredArg().ofType(String.class); 556 | parser.accepts("query").withRequiredArg().ofType(String.class); 557 | parser.accepts("user").withRequiredArg().ofType(String.class); 558 | parser.accepts("u").withRequiredArg().ofType(String.class); 559 | 560 | formatter.setSupportedOptions(parser); 561 | 562 | OptionSet options = parser.parse(argv); 563 | 564 | if (options.has("help")) { 565 | usage(); 566 | System.exit(1); 567 | } 568 | 569 | if (options.has("driver")) { 570 | driverName = (String) options.valueOf("driver"); 571 | 572 | if (driverName.compareToIgnoreCase("jconnect4") == 0) 573 | driverName = sybaseJConnect4DriverName; 574 | else if (driverName.compareToIgnoreCase("jconnect5") == 0) 575 | driverName = sybaseJConnect5DriverName; 576 | else if (driverName.compareToIgnoreCase("jconnect6") == 0) 577 | driverName = sybaseJConnect6DriverName; 578 | else if (driverName.compareToIgnoreCase("oraclethin") == 0) 579 | driverName = oracleThinDriverName; 580 | else if (driverName.compareToIgnoreCase("db2app") == 0) 581 | driverName = db2AppDriverName; 582 | else if (driverName.compareToIgnoreCase("db2net") == 0) 583 | driverName = db2NetDriverName; 584 | else if (driverName.compareToIgnoreCase("cloudscape") == 0) 585 | driverName = cloudscapeDriverName; 586 | else if (driverName.compareToIgnoreCase("mssql") == 0) 587 | driverName = msqlDriverName; 588 | else if (driverName.compareToIgnoreCase("pointbase") == 0) 589 | driverName = pointbaseDriverName; 590 | else if (driverName.compareToIgnoreCase("postgresql") == 0) 591 | driverName = postgresqlDriverName; 592 | else if (driverName.compareToIgnoreCase("mysqlconj") == 0) 593 | driverName = mySQLConnectJDriverName; 594 | else if (driverName.compareToIgnoreCase("mysqlcaucho") == 0) 595 | driverName = mySQLCauchoDriverName; 596 | } 597 | 598 | connectString = (String) options.valueOf("cstring"); 599 | 600 | if (options.has("c")) 601 | commandTerminator = (String) options.valueOf("c"); 602 | 603 | if (options.has("debug")) 604 | printDebug = true; 605 | 606 | if (options.has("user")) 607 | userName = (String) options.valueOf("user"); 608 | else if (options.has("u")) 609 | userName = (String) options.valueOf("u"); 610 | 611 | if (options.has("password")) 612 | password = (String) options.valueOf("password"); 613 | else if (options.has("p")) 614 | password = (String) options.valueOf("p"); 615 | 616 | if (options.has("fetchsize")) 617 | fetchSize = (int) options.valueOf("fetchsize"); 618 | 619 | if (options.has("driverinfo")) 620 | printDriverDetails = true; 621 | 622 | if (options.has("input")) 623 | inputFileName = (String) options.valueOf("input"); 624 | 625 | if (options.has("pf")) 626 | passwordFileName = (String) options.valueOf("pf"); 627 | 628 | if (options.has("query")) 629 | inputQuery = (String) options.valueOf("query"); 630 | 631 | if (driverName == null) 632 | throw new Exception("driver name must exist"); 633 | 634 | if (connectString == null) 635 | throw new Exception("connect string must exist"); 636 | 637 | if (userName == null) 638 | throw new Exception("user name must exist"); 639 | 640 | if ((password == null) && (passwordFileName == null)) { 641 | Console console = System.console(); 642 | password = new String( console.readPassword("Password (hit enter for no password): ") ); 643 | } 644 | else if (password == null) { 645 | File passwordFile = null; 646 | BufferedReader reader = null; 647 | 648 | passwordFile = new File(passwordFileName); 649 | if (!passwordFile.exists()) 650 | throw new Exception("the password file \"" + passwordFileName + "\" does not exist"); 651 | 652 | if (!passwordFile.isFile()) 653 | throw new Exception("the password file \"" + passwordFileName + "\" is not a normal file"); 654 | 655 | if (!passwordFile.canRead()) 656 | throw new Exception("the password file \"" + passwordFileName + "\" is not readable"); 657 | 658 | try { 659 | reader = new BufferedReader(new FileReader(passwordFile)); 660 | password = reader.readLine().trim(); 661 | } 662 | catch (Exception e) { 663 | throw new Exception("An error occured reading the password file", e); 664 | } 665 | finally { 666 | if (reader != null) { 667 | try { 668 | reader.close(); 669 | } 670 | catch (Exception ignore) { /* ignored */ 671 | } 672 | } 673 | } 674 | } 675 | 676 | formatter.consumeOptions(options); 677 | } 678 | 679 | /** 680 | * Walks through a SQLException and prints out every exception. 681 | * 682 | * @param sqle the Exception to print 683 | * 684 | */ 685 | private void printAllExceptions(SQLException sqle) { 686 | while (sqle != null) { 687 | System.err.println("SQLException : " + "SQL state: " + sqle.getSQLState() + " " + sqle.toString() + " ErrorCode: " 688 | + sqle.getErrorCode()); 689 | sqle = sqle.getNextException(); 690 | } 691 | } 692 | 693 | /** 694 | * Prints out the usage message for the Jisql driver and the configured 695 | * formatter. 696 | * 697 | */ 698 | private void usage() { 699 | System.err.println(); 700 | System.err.println( "Jisql v" + Jisql.class.getPackage().getImplementationVersion() + " copyright (c) 2015 Scott Dunbar (scott@xigole.com)" ); 701 | System.err.println("usage: java " + getClass().getName() + 702 | " -driver driver -cstring connect_string -user|-u username -password|-p password [-pf password_file] " + 703 | "[-c command_term] [-input file_name] [-fetchsize value] [-debug] [-driverinfo] [-formatter formatter]"); 704 | System.err.println("where:"); 705 | System.err 706 | .println("\t-driver specifies the JDBC driver to use. There are several builtin shortcuts - see the docs for details."); 707 | System.err.println("\t-cstring specifies the connection string to use. These are driver specific."); 708 | System.err.println("\t-user specifies a user name to log into a database server with."); 709 | System.err.println("\t-password specifies the user name to log into a database server with."); 710 | System.err.println("\t-pf specifies the name of a file that contains the password to log into a database server with."); 711 | System.err.println("\t The first line of file should contain the password and nothing else."); 712 | System.err.println("\t-c specifies the command terminator. The default is \"" + commandTerminator + "\""); 713 | System.err.println("\t-input specifies a file name to read commands from."); 714 | System.err 715 | .println("\t-query specifies an optional single query to run instead of interacting with the command line or a file."); 716 | System.err.println("\t Note that the command must include a command terminator or the command will hang"); 717 | System.err.println("\t-fetchsize specifies an optional value to set the 'fetch size' on the connection."); 718 | System.err.println("\t Fetch size controls how much data is returned from the database per request to the"); 719 | System.err.println("\t server and can have a significant impact on performance when fetching large numbers"); 720 | System.err.println("\t of rows."); 721 | System.err.println("\t-debug prints to stdout (System.out) debugging information"); 722 | System.err.println("\t-driverinfo prints to stdout (System.out) detailed driver information and then exits"); 723 | System.err 724 | .println("\t-formatter specifies either a class name or a pre-configured output formatter. See the docs for details."); 725 | 726 | if (formatter != null) { 727 | System.err.println("Additional command line arguments of the " + formatter.getClass().getName() + " class are"); 728 | formatter.usage(System.err); 729 | } 730 | 731 | System.err.println(); 732 | } 733 | } 734 | -------------------------------------------------------------------------------- /src/main/java/com/xigole/util/sql/MaskingThread.java: -------------------------------------------------------------------------------- 1 | package com.xigole.util.sql; 2 | 3 | /** 4 | * This class attempts to erase characters echoed to the console. 5 | *

6 | * This code is derived from 7 | * http://java.sun.com/features/2002/09/pword_mask.html, The article states 8 | *

9 | * 10 | * Feel free to reuse and improve the code in this article for your applications. 11 | * 12 | *

13 | * So I think that it should be ok to include it here. I have only removed 14 | * unneeded variables and changed to my coding style. No "real" changes 15 | * have been made. 16 | * 17 | */ 18 | public class MaskingThread extends Thread 19 | { 20 | private boolean stop = false; 21 | private String prompt = null; 22 | 23 | /** 24 | * @param thePrompt The prompt displayed to the user 25 | */ 26 | public MaskingThread(String thePrompt) 27 | { 28 | prompt = thePrompt; 29 | } 30 | 31 | /** 32 | * Begin masking until asked to stop. 33 | */ 34 | public void run() 35 | { 36 | while (!stop) 37 | { 38 | try 39 | { 40 | // attempt masking at this rate (refresh every 1 ms.) 41 | sleep(1); 42 | } 43 | catch (InterruptedException iex) 44 | { 45 | iex.printStackTrace(); 46 | } 47 | if (!stop) 48 | { 49 | // 50 | // sd - note what this does. If your prompt is really short 51 | // and your password is really long this won't work - some 52 | // characters will become visible 53 | // 54 | System.out.print( "\r" + prompt + " \r" + prompt ); 55 | } 56 | System.out.flush(); 57 | } 58 | } 59 | 60 | /** 61 | * Instruct the thread to stop masking. 62 | */ 63 | public void stopMasking() 64 | { 65 | stop = true; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/xigole/util/sql/outputformatter/CSVFormatter.java: -------------------------------------------------------------------------------- 1 | package com.xigole.util.sql.outputformatter; 2 | 3 | import java.io.PrintStream; 4 | import java.sql.ResultSet; 5 | import java.sql.ResultSetMetaData; 6 | 7 | import java.nio.charset.Charset; 8 | 9 | import joptsimple.OptionParser; 10 | import joptsimple.OptionSet; 11 | 12 | import com.csvreader.CsvWriter; 13 | 14 | 15 | /** 16 | * This is the default formatter for Jisql. It outputs data in a "normal" 17 | * format that is similar to most other database command line formatters. 18 | * 19 | */ 20 | public class CSVFormatter implements JisqlFormatter { 21 | private char delimiter = ','; 22 | private boolean includeColumnNames = false; 23 | 24 | 25 | /** 26 | * Sets a the supported option list for this formatter. This formatter accepts 27 | * the following options: 28 | * 29 | *

 

30 | * 31 | * 37 | * 38 | * @param parser the OptionParser to use. 39 | * 40 | */ 41 | public void setSupportedOptions( OptionParser parser ) { 42 | parser.accepts( "delimiter" ).withRequiredArg().ofType( String.class ); 43 | parser.accepts( "colnames" ); 44 | } 45 | 46 | /** 47 | * Consumes any options that were specified on the command line. 48 | * 49 | * @param options the OptionSet that the main driver is using. 50 | * 51 | * @throws Exception if there is a problem parsing the command line arguments. 52 | * 53 | */ 54 | public void consumeOptions( OptionSet options ) throws Exception { 55 | if( options.has( "delimiter" ) ) 56 | delimiter = ((String)(options.valueOf( "delimiter" ))).charAt( 0 ); 57 | 58 | if( options.has( "colnames" ) ) 59 | includeColumnNames = true; 60 | } 61 | 62 | /** 63 | * Called to output a usage message to the command line window. This 64 | * message should contain information on how to call the formatter. 65 | * 66 | * @param out the PrintStream to display the usage message on. 67 | * 68 | */ 69 | public void usage( PrintStream out ) { 70 | out.println("\t-delimiter specifies the character to use as the delimiter. This defaults to \"" + delimiter + "\"" ); 71 | out.println("\t-colnames outputs column names. By default there are no column names." ); 72 | } 73 | 74 | /** 75 | * Outputs an optional header for the CSV data. This header is only enabled 76 | * if the "colnames" parameter is included. 77 | * 78 | * @param out a PrintStream to send any output to. 79 | * @param metaData the ResultSetMetaData for the output. 80 | * 81 | */ 82 | public void formatHeader( PrintStream out, ResultSetMetaData metaData ) throws Exception { 83 | if( includeColumnNames ) { 84 | int numColumns = metaData.getColumnCount(); 85 | 86 | // 87 | // output the column names 88 | // 89 | for (int i = 1; i <= numColumns; i++) { 90 | out.print( metaData.getColumnName(i).trim() ); 91 | if( (i + 1) <= numColumns ) 92 | out.print( delimiter ); 93 | } 94 | 95 | out.println(); 96 | } 97 | } 98 | 99 | 100 | /** 101 | * Called to output the data. This class uses a third party library to output 102 | * the CSV data. The library escapes the data as needed. 103 | * 104 | * @param out the PrintStream to output data to. 105 | * @param resultSet the ResultSet for the row. 106 | * @param metaData the ResultSetMetaData for the row. 107 | * 108 | * 109 | */ 110 | public void formatData( PrintStream out, ResultSet resultSet, ResultSetMetaData metaData ) throws Exception { 111 | 112 | CsvWriter csvWriter = new CsvWriter( out, delimiter, Charset.defaultCharset() ); 113 | 114 | while( resultSet.next() ) { 115 | int numColumns = metaData.getColumnCount(); 116 | 117 | for (int i = 1; i <= numColumns; i++) { 118 | String result = resultSet.getString(i); 119 | if( !resultSet.wasNull() ) 120 | csvWriter.write( result ); 121 | else 122 | csvWriter.write( "" ); 123 | } 124 | 125 | csvWriter.endRecord(); 126 | } 127 | 128 | csvWriter.flush(); 129 | } 130 | 131 | 132 | /** 133 | * Outputs a footer for a query. For the CSVFormatter this method does nothing. 134 | * 135 | * @param out the PrintStream to output data to. 136 | * @param metaData the ResultSetMetaData for the output. 137 | * 138 | */ 139 | public void formatFooter( PrintStream out, ResultSetMetaData metaData ) throws Exception { 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /src/main/java/com/xigole/util/sql/outputformatter/DefaultFormatter.java: -------------------------------------------------------------------------------- 1 | package com.xigole.util.sql.outputformatter; 2 | 3 | import java.io.PrintStream; 4 | import java.sql.ResultSet; 5 | import java.sql.ResultSetMetaData; 6 | 7 | import joptsimple.OptionParser; 8 | import joptsimple.OptionSet; 9 | 10 | 11 | /** 12 | * This is the default formatter for Jisql. It outputs data in a "normal" 13 | * format that is similar to most other database command line formatters. 14 | * 15 | */ 16 | public class DefaultFormatter implements JisqlFormatter { 17 | private boolean trimColumns = false; 18 | private int columnWidth = 2048; // can be overridden with the -w switch 19 | private char spacer = ' '; 20 | private boolean printNull = true; 21 | private boolean leftJustify = false; 22 | private boolean printHeader = true; 23 | private boolean debug = false; 24 | private String delimiter = " | "; 25 | 26 | 27 | /** 28 | * Sets a the option list for this formatter. This formatter accepts the 29 | * following options: 30 | * 31 | *
  • -noheader do not print the header column info.
  • 32 | *
  • -spacer The character to use for "empty" space. This 33 | * defaults to the space character. From mrider - "I added the ability to 34 | * specify the spacer for columns - which used to be the single char ' '. I did 35 | * this because of brain-dead Windows' command line copy/paste. It seems that when 36 | * a line of text ends in space, copy does not copy that space. Which makes it 37 | * difficult to copy/paste into another program. This can probably be ignored 38 | * most of the time."
  • 39 | *
  • -delimiter Specify a single character delimiter for columns.
  • 40 | *
  • -trim trim the spaces from columns.
  • 41 | *
  • -nonull print an empty string instead of the word "NULL" 42 | * when there is a null value.
  • 43 | *
  • -left left justify the output
  • 44 | *
  • -w specify the max width of a column. The default is 2048
  • 45 | *
  • -debug add debug headers to the output
  • 46 | * 47 | * 48 | * @param parser the OptionParser to use. 49 | * 50 | */ 51 | public void setSupportedOptions( OptionParser parser ) { 52 | parser.accepts( "trim" ); 53 | parser.accepts( "w" ).withRequiredArg().ofType( Integer.class ); 54 | parser.accepts( "spacer" ).withRequiredArg().ofType( String.class ); 55 | parser.accepts( "left" ); 56 | parser.accepts( "nonull" ); 57 | parser.accepts( "noheader" ); 58 | parser.accepts( "debug" ); 59 | parser.accepts( "delimiter" ).withRequiredArg().ofType( String.class ); 60 | } 61 | 62 | /** 63 | * Consumes any options that were specified on the command line. 64 | * 65 | * @param options the OptionSet that the main driver is using. 66 | * 67 | * @throws Exception if there is a problem parsing the command line arguments. 68 | * 69 | */ 70 | public void consumeOptions( OptionSet options ) throws Exception { 71 | 72 | if( options.has( "trim" ) ) 73 | trimColumns = true; 74 | 75 | if( options.has( "w" ) ) 76 | columnWidth = (Integer)options.valueOf( "w" ); 77 | 78 | if( options.has( "spacer" ) ) 79 | spacer = ((String)(options.valueOf( "spacer" ))).charAt( 0 ); 80 | 81 | if( options.has( "left" ) ) 82 | leftJustify = true; 83 | 84 | if( options.has( "nonull" ) ) 85 | printNull = false; 86 | 87 | if( options.has( "noheader" ) ) 88 | printHeader = false; 89 | 90 | if( options.has( "debug" ) ) 91 | debug = true; 92 | 93 | if( options.hasArgument( "delimiter" ) ) 94 | delimiter = (String)options.valueOf( "delimiter" ); 95 | } 96 | 97 | 98 | 99 | /** 100 | * Called to output a usage message to the command line window. This 101 | * message should contain information on how to call the formatter. 102 | * 103 | * @param out the stream to print the output on 104 | * 105 | */ 106 | public void usage( PrintStream out ) { 107 | out.println("\t-w specifies the maximum field width for a column. The default is to output the full width of the column"); 108 | out.println("\t-spacer changes the spacer between columns from a single space to the first character of the argument"); 109 | out.println("\t-noheader do not print any header columns"); 110 | out.println("\t-left left justify the output"); 111 | out.println("\t-trim trim the data output. This is useful when specifying a delimiter."); 112 | out.println("\t-nonull print the empty string instead of the word \"NULL\" for null values."); 113 | out.println("\t-debug shows extra information about the output." ); 114 | out.println("\t-delimiter specifies the delimiter. The default is \"" + delimiter + "\"." ); 115 | 116 | } 117 | 118 | /** 119 | * Outputs a header for a query. For the DefaultFormatter the data is output 120 | * by default unless the "noheader" option is specified. 121 | * 122 | * @param out - a PrintStream to send any output to. 123 | * @param metaData - the ResultSetMetaData for the output. 124 | * 125 | */ 126 | public void formatHeader( PrintStream out, ResultSetMetaData metaData ) throws Exception { 127 | if( printHeader ) { 128 | int numColumns = metaData.getColumnCount(); 129 | 130 | if( debug ) { 131 | for (int i = 1; i <= numColumns; i++) { 132 | out.print( formatLabel( metaData.getColumnTypeName(i), 133 | metaData.getColumnDisplaySize(i))); 134 | out.print(delimiter); 135 | } 136 | } 137 | // 138 | // output the column names 139 | // 140 | for (int i = 1; i <= numColumns; i++) { 141 | out.print( formatLabel( metaData.getColumnName(i), 142 | metaData.getColumnDisplaySize(i))); 143 | out.print(delimiter); 144 | } 145 | 146 | out.println(); 147 | 148 | // 149 | // output pretty dividers 150 | // 151 | for (int i = 1; i <= numColumns; i++) { 152 | out.print( formatSeparator( metaData.getColumnName(i), 153 | metaData.getColumnDisplaySize(i))); 154 | 155 | if (i == numColumns) 156 | out.print("-|"); 157 | else 158 | out.print("-+-"); 159 | } 160 | 161 | out.println(); 162 | } 163 | } 164 | 165 | 166 | /** 167 | * Called to output the data. 168 | * 169 | * @param out the PrintStream to output data to. 170 | * @param resultSet the ResultSet for the row. 171 | * @param metaData the ResultSetMetaData for the row. 172 | * 173 | * 174 | */ 175 | public void formatData( PrintStream out, ResultSet resultSet, ResultSetMetaData metaData ) throws Exception { 176 | 177 | while( resultSet.next() ) { 178 | int numColumns = metaData.getColumnCount(); 179 | 180 | for (int i = 1; i <= numColumns; i++) { 181 | out.print( formatValue( metaData.getColumnName(i), 182 | resultSet.getString(i), 183 | metaData.getColumnDisplaySize(i))); 184 | out.print( delimiter ); 185 | } 186 | 187 | out.println(); 188 | } 189 | } 190 | 191 | 192 | /** 193 | * Outputs a footer for a query. This is called after all data has been 194 | * exhausted. This method isn't used in the DefaultFormatter. 195 | * 196 | * @param out the PrintStream to output data to. 197 | * @param metaData the ResultSetMetaData for the output. 198 | * 199 | */ 200 | public void formatFooter( PrintStream out, ResultSetMetaData metaData ) throws Exception { 201 | } 202 | 203 | 204 | 205 | /** 206 | * Formats a label for output. 207 | * 208 | * @param s - the label to format 209 | * @param width - the width of the field 210 | * 211 | * @return the formated label 212 | * 213 | */ 214 | private String formatLabel(String s, int width) { 215 | if (s == null) 216 | s = "NULL"; 217 | 218 | if (columnWidth != 0) { 219 | if (width > columnWidth) 220 | width = columnWidth; 221 | } 222 | 223 | if (width < s.length()) 224 | width = s.length(); 225 | 226 | int len = s.length(); 227 | 228 | if (len >= width) 229 | return s.substring(0, width); 230 | 231 | int fillWidth = width - len; 232 | StringBuffer fill = new StringBuffer(fillWidth); 233 | for (int i = 0; i < fillWidth; ++i) 234 | fill.append(spacer); 235 | if (leftJustify) 236 | return s + fill; 237 | else if (s.startsWith("-")) 238 | return "-" + fill + s.substring(1); 239 | else 240 | return fill + s; 241 | } 242 | 243 | /** 244 | * Formats a separator for display. 245 | * 246 | * @param s - the field for which the separator is being generated 247 | * @param width - the width of the field 248 | * 249 | * @return the formated separator 250 | * 251 | */ 252 | private String formatSeparator(String s, int width) { 253 | s = "NULL"; 254 | 255 | if (columnWidth != 0) { 256 | if (width > columnWidth) 257 | width = columnWidth; 258 | } 259 | 260 | if (width < s.length()) 261 | width = s.length(); 262 | 263 | int len = s.length(); 264 | 265 | if (len >= width) 266 | width = len; 267 | 268 | StringBuffer fill = new StringBuffer(width); 269 | for (int i = 0; i < width; ++i) 270 | fill.append('-'); 271 | 272 | if( trimColumns ) 273 | return fill.toString().trim(); 274 | else 275 | return fill.toString(); 276 | } 277 | 278 | /** 279 | * Formats a value for display. 280 | * 281 | * @param label the label associated with the value (for width purposes) 282 | * @param s - the value to format 283 | * @param width - the width of the field from the db. 284 | * 285 | * @return the formatted field. 286 | * 287 | */ 288 | private String formatValue(String label, String s, int width) { 289 | if (s == null) { 290 | if( printNull ) 291 | s = "NULL"; 292 | else 293 | s = ""; 294 | } 295 | 296 | if (columnWidth != 0) { 297 | if (width > columnWidth) 298 | width = columnWidth; 299 | } 300 | 301 | if (width < label.length()) 302 | width = label.length(); 303 | 304 | int len = s.length(); 305 | 306 | if (len >= width) { 307 | if( trimColumns ) 308 | return s.substring(0, width).trim(); 309 | else 310 | return s.substring(0, width); 311 | } 312 | 313 | int fillWidth = width - len; 314 | StringBuffer fill = new StringBuffer(fillWidth); 315 | for (int i = 0; i < fillWidth; ++i) 316 | fill.append(spacer); 317 | 318 | StringBuilder returnValue = new StringBuilder(); 319 | 320 | if (leftJustify) 321 | returnValue.append( s + fill ); 322 | else if (s.startsWith("-")) 323 | returnValue.append( "-" + fill + s.substring(1) ); 324 | else { 325 | returnValue.append( fill + s ); 326 | } 327 | 328 | if( trimColumns ) { 329 | return returnValue.toString().trim(); 330 | } 331 | else { 332 | return returnValue.toString(); 333 | } 334 | } 335 | } 336 | -------------------------------------------------------------------------------- /src/main/java/com/xigole/util/sql/outputformatter/JisqlFormatter.java: -------------------------------------------------------------------------------- 1 | package com.xigole.util.sql.outputformatter; 2 | 3 | import java.io.PrintStream; 4 | import java.sql.ResultSet; 5 | import java.sql.ResultSetMetaData; 6 | 7 | import joptsimple.OptionParser; 8 | import joptsimple.OptionSet; 9 | 10 | 11 | /** 12 | * This is the definition of what a JisqlFormatter does. 13 | * 14 | */ 15 | public interface JisqlFormatter { 16 | 17 | /** 18 | * Sets a the option list for this formatter. 19 | * 20 | * @param parser - the OptionParser to use. 21 | */ 22 | public void setSupportedOptions( OptionParser parser ); 23 | 24 | /** 25 | * Consumes any options that were specified on the command line. 26 | * 27 | * @param options the OptionSet that the main driver is using. Implementing 28 | * classes should add their supported parameters to the list. 29 | * 30 | * @throws Exception if there is a problem parsing the command line arguments. 31 | * Note that Jisql includes jopt-simple so you can use that 32 | * to parse your command line. See 33 | * http://jopt-simple.sourceforge.net/ 34 | * for more information. 35 | * 36 | */ 37 | public void consumeOptions( OptionSet options ) throws Exception; 38 | 39 | /** 40 | * Called to output a usage message to the command line window. This 41 | * message should contain information on how to call the formatter. 42 | * 43 | * @param out where to put the usage message. 44 | * 45 | */ 46 | public void usage( PrintStream out ); 47 | 48 | 49 | /** 50 | * Outputs a header for a query. This is called before any data is 51 | * output. 52 | * 53 | * @param out where to put header output. 54 | * @param metaData the ResultSetMetaData for the output. 55 | * 56 | */ 57 | public void formatHeader( PrintStream out, ResultSetMetaData metaData ) throws Exception; 58 | 59 | /** 60 | * Called to output the data. 61 | * 62 | * @param out where to put output data. 63 | * @param resultSet the ResultSet for the row. 64 | * @param metaData the ResultSetMetaData for the row. 65 | * 66 | */ 67 | public void formatData( PrintStream out, ResultSet resultSet, ResultSetMetaData metaData ) throws Exception; 68 | 69 | /** 70 | * Outputs a footer for a query. This is called after all data has been 71 | * exhausted. 72 | * 73 | * @param out where to put footer output. 74 | * @param metaData the ResultSetMetaData for the output. 75 | * 76 | */ 77 | public void formatFooter( PrintStream out, ResultSetMetaData metaData ) throws Exception; 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/xigole/util/sql/outputformatter/NullFormatter.java: -------------------------------------------------------------------------------- 1 | package com.xigole.util.sql.outputformatter; 2 | 3 | import java.io.PrintStream; 4 | import java.sql.ResultSet; 5 | import java.sql.ResultSetMetaData; 6 | 7 | import joptsimple.OptionParser; 8 | import joptsimple.OptionSet; 9 | 10 | 11 | /** 12 | * This is the "null" formatter - it simply throws away any output 13 | * This is useful on rare occasions - e.g. when benchmarking how quickly data can be 14 | * fetched from a database without wanting to view the data itself 15 | * 16 | */ 17 | public class NullFormatter implements JisqlFormatter { 18 | 19 | private boolean fetchData = false; 20 | 21 | /** 22 | * Sets a the option list for this formatter. 23 | * 24 | * @param parser the OptionParser to use. 25 | * 26 | */ 27 | public void setSupportedOptions( OptionParser parser ) { 28 | parser.accepts( "fetch" ); 29 | } 30 | 31 | /** 32 | * Consumes any options that were specified on the command line. 33 | * 34 | * @param options the OptionSet that the main driver is using. 35 | * 36 | * @throws Exception if there is a problem parsing the command line arguments. 37 | * 38 | */ 39 | public void consumeOptions( OptionSet options ) throws Exception { 40 | if( options.has( "fetch" ) ) 41 | fetchData = true; 42 | } 43 | 44 | /** 45 | * Called to output a usage message to the command line window. This 46 | * message should contain information on how to call the formatter. 47 | * 48 | */ 49 | public void usage( PrintStream out ) { 50 | out.println("\t-fetch Fetches the data even though we don't output it - useful for benchmarking." ); 51 | } 52 | 53 | 54 | /** 55 | * Outputs a header for a query. For the NullFormatter this is a no-op. 56 | * 57 | * @param out a PrintStream to send any output to. 58 | * @param metaData the ResultSetMetaData for the output. 59 | * 60 | */ 61 | public void formatHeader( PrintStream out, ResultSetMetaData metaData ) throws Exception { 62 | /* no output for the NullFormatter */ 63 | } 64 | 65 | 66 | /** 67 | * Called to output the data. 68 | * 69 | * @param out the PrintStream to output data to. 70 | * @param resultSet the ResultSet for the row. 71 | * @param metaData the ResultSetMetaData for the row. 72 | * 73 | */ 74 | public void formatData( PrintStream out, ResultSet resultSet, ResultSetMetaData metaData ) throws Exception { 75 | if (fetchData) { 76 | while( resultSet.next() ) { 77 | // Fetch the data even though we don't output it - otherwise the query 78 | // stops after the first block is fetched (based on fetchsize) 79 | } 80 | } 81 | } 82 | 83 | 84 | /** 85 | * Outputs a footer for a query. This method isn't used in the NullFormatter. 86 | * 87 | * @param out the PrintStream to output data to. 88 | * @param metaData the ResultSetMetaData for the output. 89 | * 90 | */ 91 | public void formatFooter( PrintStream out, ResultSetMetaData metaData ) throws Exception { 92 | /* no output for the NullFormatter */ 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/com/xigole/util/sql/outputformatter/XMLFormatter.java: -------------------------------------------------------------------------------- 1 | package com.xigole.util.sql.outputformatter; 2 | 3 | import java.io.PrintStream; 4 | import java.nio.charset.Charset; 5 | import java.sql.ResultSet; 6 | import java.sql.ResultSetMetaData; 7 | 8 | import joptsimple.OptionParser; 9 | import joptsimple.OptionSet; 10 | 11 | 12 | /** 13 | * This is the default XML formatter for Jisql. It outputs data in an 14 | * XML format. 15 | * 16 | */ 17 | public class XMLFormatter implements JisqlFormatter { 18 | 19 | /** 20 | * Sets a the option list for this formatter. This is a no-op in the 21 | * XMLFormatter. 22 | * 23 | * @param parser the OptionParser to use. 24 | * 25 | */ 26 | public void setSupportedOptions( OptionParser parser ) { 27 | /* no options for the XMLFormatter */ 28 | } 29 | 30 | /** 31 | * Consumes any options that were specified on the command line. There are 32 | * no options to set for the XMLFormatter so this method is a no-op. 33 | * 34 | * @param options the OptionSet that the main driver is using. 35 | * 36 | * @throws Exception if there is a problem parsing the command line arguments. 37 | * 38 | */ 39 | public void consumeOptions( OptionSet options ) throws Exception { 40 | /* no options for the XMLFormatter */ 41 | } 42 | 43 | /** 44 | * Called to output a usage message to the command line window. This 45 | * message should contain information on how to call the formatter. 46 | * There are no options to set for the XMLFormatter so this method is 47 | * a no-op. 48 | * 49 | */ 50 | public void usage( PrintStream out ) { 51 | /* no options for the XMLFormatter */ 52 | } 53 | 54 | 55 | /** 56 | * Outputs a header for a query. For the XMLFormater this outputs the XML 57 | * pre-amble. The character encoding defaults to the current character 58 | * encoding in use. 59 | * 60 | * @param out a PrintStream to send any output to. 61 | * @param metaData the ResultSetMetaData for the output. 62 | * 63 | */ 64 | public void formatHeader( PrintStream out, ResultSetMetaData metaData ) throws Exception { 65 | out.print( "" ); 68 | } 69 | 70 | 71 | /** 72 | * Called to output the data. Note that for the XMLFormatter null fields are 73 | * just output as an empty field. 74 | * 75 | * @param out the PrintStream to output data to. 76 | * @param resultSet the ResultSet for the row. 77 | * @param metaData the ResultSetMetaData for the row. 78 | * 79 | */ 80 | public void formatData( PrintStream out, ResultSet resultSet, ResultSetMetaData metaData ) throws Exception { 81 | 82 | while( resultSet.next() ) { 83 | int numColumns = metaData.getColumnCount(); 84 | 85 | for (int i = 1; i <= numColumns; i++) { 86 | out.print( "<" ); 87 | out.print( metaData.getColumnName( i ).trim() ); 88 | out.print( ">" ); 89 | String result = resultSet.getString(i); 90 | if( !resultSet.wasNull() ) 91 | out.print( result.trim() ); 92 | out.print( "" ); 95 | } 96 | 97 | out.println(); 98 | } 99 | } 100 | 101 | 102 | /** 103 | * Outputs a footer for a query. This method isn't used in the XMLFormatter. 104 | * 105 | * @param out the PrintStream to output data to. 106 | * @param metaData the ResultSetMetaData for the output. 107 | * 108 | */ 109 | public void formatFooter( PrintStream out, ResultSetMetaData metaData ) throws Exception { 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/main/scripts/runit: -------------------------------------------------------------------------------- 1 | java -cp target/jisql-jar-with-dependencies.jar:/home/postgresql/lib/postgresql-9.4-1201.jdbc4.jar com.xigole.util.sql.Jisql -user scott -password scott -driver org.postgresql.Driver -cstring jdbc:postgresql://localhost:5432/mydb 2 | -------------------------------------------------------------------------------- /src/main/scripts/runit.bat: -------------------------------------------------------------------------------- 1 | java -classpath lib/jisql.jar;lib/jopt-simple-3.2.jar;lib/javacsv.jar;C:/Oracle/product/10.1.0/Client_1/jdbc/lib/ojdbc14.jar com.xigole.util.sql.Jisql -user scott -password blah -driver oraclethin -cstring jdbc:oracle:thin:@hostname.tld:1521:orasid -c ; 2 | -------------------------------------------------------------------------------- /src/main/scripts/runit_query: -------------------------------------------------------------------------------- 1 | java -classpath lib/jisql.jar:lib/jopt-simple-3.2.jar:lib/javacsv.jar:/home/scott/postgresql/postgresql-8.4-701.jdbc4.jar com.xigole.util.sql.Jisql -user scott -password blah -driver postgresql -cstring jdbc:postgresql://localhost:5432/scott -c \; -query "select * from test;" 2 | 3 | --------------------------------------------------------------------------------