sqlline-1.0.2/0000755000175000017500000000000010313510646013054 5ustar drazzibdrazzibsqlline-1.0.2/project.properties0000644000175000017500000000070410313510362016634 0ustar drazzibdrazzib name: sqlline author: Marc Prud'hommeaux author.mail: mwp1@cornell.edu software.name: SQLLine key.alias: mwp1@cornell.edu sf.userid: mprudhom sf.project.name: ${name} sf.project.firstchar: s sf.project.secondchar: q version.major: 1 version.minor: 0 version.patch: 2 software.license: BSD javadoc.skip: 1 tests.skip: 1 checkstyle.skip: 1 jars.example.skip: 1 jars.native.skip: 1 software.main.class: sqlline.SqlLine software.class.path: jline.jar sqlline-1.0.2/LICENSE0000644000175000017500000004313107201771736014076 0ustar drazzibdrazzib GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. sqlline-1.0.2/build.xml0000644000175000017500000003355110274702324014706 0ustar drazzibdrazzib project.properties does not exist for this project "name" undefined "author" undefined "author.mail" undefined "software.name" undefined "key.alias" undefined "sf.userid" undefined "sf.project.name" undefined "sf.project.firstchar" undefined "sf.project.secondchar" undefined "version.major" undefined "version.minor" undefined "version.patch" undefined "software.license" undefined ${version.title} Building jnlp properties "software.main.class" undefined "software.class.path" undefined ${software.name} ${author.mail} ${software.description} ]]> Uploading files to FTP server... Copying documentation files to web site via scp... "software.main.class" undefined "software.class.path" undefined
Signing jars... Tagging CVS tree with: ${version.name} Tests has errors Tests had failures
sqlline-1.0.2/native/0000755000175000017500000000000010313510646014342 5ustar drazzibdrazzibsqlline-1.0.2/doc-build/0000755000175000017500000000000010313510646014716 5ustar drazzibdrazzibsqlline-1.0.2/doc-build/manual.html0000644000175000017500000032002610313510320017051 0ustar drazzibdrazzib SQLLine 1.0.2

SQLLine 1.0.2


SQLLine Manual

Introduction

SQLLine is a pure-Java console based utility for connecting to relational databases and executing SQL commands. It is similiar to other command-line database access utilities like sqlplus for Oracle, mysql for MySQL, and isql for Sybase/SQL Server. Since it is pure-Java, it is platform independant, and will run on any platform that can run Java 1.3 or higher.

License and Terms of Use

SQLLine is distributed under the BSD License, meaning that you are free to redistribute, modify, or sell the software with almost no restrictions. For the text of the license, see the license text.

For information on obtaining the software under another license, contact the copyright holder: mwp1@cornell.edu.

Obtaining SQLLine

SQLLine is hosted on SourceForge, and is located at http://sqlline.sf.net. The latest release can be downloaded from http://sqlline.sf.net/download.html.

Installation

Required software

SQLLine depends on the following software:

  • Java™ Virtual Machine - SQLLine is a pure java program, and requires Java version 1.3 or higher in order to run. The latest JVM can be downloaded from http://java.sun.com.

  • JLine - SQLLine uses the JLine console reader for command line editing, tab-completion, and command history. It can be downloaded from http://jline.sf.net. Version 0.8.1 or higher is required.

  • JDBC™ Driver(s) - Since SQLLine uses the Java Database Connectivity package to connect to your database, you need to obtain the correct JDBC driver libraries for your database. Any JDBC compliant driver can be used for this purpose. Drivers can be located by referring to the section on known JDBC drivers, or else by referring to your database vendor's web site.

Installing SQLLine

There are currently no set standards for installing Java software on different platforms. The simplest method for installing SQLLine in a platform independant way is as follows:

  1. Create a new directory/folder where you like. This will be referred to as sqllinedir.

  2. Download sqlline.jar into sqllinedir.

  3. Download the latest jline.jar from http://jline.sf.net into sqllinedir.

  4. Download your database's JDBC driver files into sqllinedir. Note that some JDBC drivers require some installation, such as uncompressing or unzipping.

Using SQLLine

Running SQLLine

SQLLine can be run with the following command:

java {-Djava.ext.dirs=sqllinedir} {sqllinedir/sqlline.jar} [options...] [properties files...]

For example, if your sqllinedir is /usr/share/java/ (this is typical for Debian Linux), then you might run:
java -Djava.ext.dirs=/usr/share/java/ /usr/share/java/sqlline.jar
				

Once you have started SQLLine, you will a prompt that reads "sqlline> ". From here, you can enter either SQLLine commands (beginning with a "!" character), or a SQL statement (if you are currently connected to a database). For example, entering "!help" will display a list of all the available commands.

Connecting to a database

SQLLine is only useful once you are connected to a database. In order to do so, you need to use the "!connect" command, with the JDBC URL of the database you are going to connect to, followed by the username and password (followed optionally by the driver class name). The JDBC URL is specific to the JDBC driver that you are using for your database, but will always start with "jdbc:", and usually has the machine name of the database and the name of the database itself as part of the string. Consult your driver's documentation for details on the URL to use.

For example, to connect to an Oracle database, you might enter:


sqlline> !connect jdbc:oracle:thin:@localhost:1521:mydb scott tiger oracle.jdbc.driver.OracleDriver

Connected to: Oracle (version Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production
With the Partitioning, OLAP and Oracle Data Mining options
JServer Release 9.2.0.1.0 - Production)
Driver: Oracle JDBC driver (version 9.0.1.0.0)
Autocommit status: true

0: jdbc:oracle:thin:@localhost:1521:mydb>
				
Once you are connected, the prompt will change the reflect URL of the current connection.

SQLLine can also accept command line options to connect to a database. If a file is specified on the command line, it will be treated as a properties file, and try to connect to the database specified therein. For details, see the properties command documentation.

SQLLine allows you to have multiple connections to databases (either the same database, or a different database) open at the same time. Issuing the connect command multiple times will add the new connection to the list of open connections. The "current" connection (against which all SQL statements will be executed) can be switched with the go command. The currently open connections can be listed with the list command.

Issuing SQL commands

Once you are connected to a database, you can begin SQL statements against the current connection. For example:

Example 1. Issuing SQL commands

0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM MYTABLE;

+-----+
| ID  |
+-----+
| 1   |
| 2   |
| 3   |
| 4   |
+-----+
4 rows selected (0.012 seconds)
0: jdbc:oracle:thin:@localhost:1521:mydb>
				

Command Completion

On UNIX systems, SQLLine allows command-line completion using the tab key. This will be familiar for users of such popular shells as bash and tcsh. In general, hitting the TAB key when part of the way through typing a command will fill in the rest of the command, or else will display a selection of appropriate possibilities.

Command Reference

all

Name

all — Execute SQL against all active connections

Synopsis

!all {SQL statement}

Description

Execute the specified SQL against all the current connections.

Example of "all" command

1: jdbc:mysql://localhost/mydb> !list

2 active connections:
 #0  open     jdbc:oracle:thin:@localhost:1521:mydb
 #1  open     jdbc:mysql://localhost/mydb

1: jdbc:mysql://localhost/mydb> !all DELETE FROM COMPANY;

Executing SQL against: jdbc:oracle:thin:@localhost:1521:mydb
4 rows affected (0.004 seconds)

Executing SQL against: jdbc:mysql://localhost/mydb
1 row affected (3.187 seconds)

1: jdbc:mysql://localhost/mydb>
					

autocommit

Name

autocommit — Enable or disable automatic transaction commit mode

Synopsis

!autocommit {on/off}

Description

Set autocommit mode on or off. When autocommit is on, every individual SQL statement will be committed after it is issued. Otherwise, the commit command will need to be issued in order to commit any changes to the database.

Example of "autocommit" command

1: jdbc:mysql://localhost/mydb> !autocommit off

Autocommit status: false

1: jdbc:mysql://localhost/mydb>
					

batch

Name

batch — Start or execute a batch of SQL statements

Synopsis

!batch

Description

Start or execute a batch of SQL statements. The first time the statement is issued, subsequent SQL statements will be deferred until the batch command is issued again. Databases can frequently optimize multiple batched statements (e.g., for bulk data loading) in order to speed up execution.

Example of "batch" command

0: jdbc:oracle:thin:@localhost:1521:mydb> !batch

Batching SQL statements. Run "batch" again to execute the batch.

0: jdbc:oracle:thin:@localhost:1521:mydb> INSERT INTO MYTABLE (ID) VALUES (1);
0: jdbc:oracle:thin:@localhost:1521:mydb> INSERT INTO MYTABLE (ID) VALUES (2);
0: jdbc:oracle:thin:@localhost:1521:mydb> INSERT INTO MYTABLE (ID) VALUES (3);
0: jdbc:oracle:thin:@localhost:1521:mydb> INSERT INTO MYTABLE (ID) VALUES (4);
0: jdbc:oracle:thin:@localhost:1521:mydb> !batch

Running batched SQL statements...
COUNT   STATEMENT
1       INSERT INTO MYTABLE (ID) VALUES (1)
1       INSERT INTO MYTABLE (ID) VALUES (2)
1       INSERT INTO MYTABLE (ID) VALUES (3)
1       INSERT INTO MYTABLE (ID) VALUES (4)

0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM MYTABLE;

+-----+
| ID  |
+-----+
| 1   |
| 2   |
| 3   |
| 4   |
+-----+
4 rows selected (0.012 seconds)
0: jdbc:oracle:thin:@localhost:1521:mydb>
					

brief

Name

brief — Enable terse output mode

Synopsis

!brief

Description

Set verbose mode off. This will prevent printing of stack traces when errors occur.

Example of "brief" command

0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM BOGUS_TABLE;

Error: ORA-00942: table or view does not exist (state=42000,code=942)
java.sql.SQLException: ORA-00942: table or view does not exist

        at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:180)
        at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:208)
        at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:543)
        at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1451)
        at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteDescribe(TTC7Protocol.java:651)
        at oracle.jdbc.driver.OracleStatement.doExecuteQuery(OracleStatement.java:2110)
        at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2324)
        at oracle.jdbc.driver.OracleStatement.execute(OracleStatement.java:909)
        at sqlline.SqlLine$Commands.sql(SqlLine.java:3183)
        at sqlline.SqlLine.dispatch(SqlLine.java:771)
        at sqlline.SqlLine.begin(SqlLine.java:634)
        at sqlline.SqlLine.main(SqlLine.java:332)

0: jdbc:oracle:thin:@localhost:1521:mydb> !brief

verbose: off

0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM BOGUS_TABLE;

Error: ORA-00942: table or view does not exist (state=42000,code=942)

0: jdbc:oracle:thin:@localhost:1521:mydb>
					

close

Name

close — Close the active connection

Synopsis

!close

Description

Close the current connection and remote it from the connection list.

Example of "close" command

0: jdbc:oracle:thin:@localhost:1521:mydb> !list

1 active connection:
 #0  open     jdbc:oracle:thin:@localhost:1521:mydb

0: jdbc:oracle:thin:@localhost:1521:mydb> !close

Closing: oracle.jdbc.driver.OracleConnection

sqlline> !list

No active connections

sqlline>
					

columns

Name

columns — Display columns of a table

Synopsis

!columns {table name}

Description

List the columns in the specified table.

Example of "columns" command

0: jdbc:oracle:thin:@localhost:1521:mydb> !columns EMPLOYEE

+-------------+--------------+------------+------------+
| TABLE_NAME  | COLUMN_NAME  | DATA_TYPE  | TYPE_NAME  |
+-------------+--------------+------------+------------+
| EMPLOYEE    | ID           | 3          | NUMBER     |
| EMPLOYEE    | FIRST_NAME   | 12         | VARCHAR2   |
| EMPLOYEE    | LAST_NAME    | 12         | VARCHAR2   |
+-------------+--------------+------------+------------+

0: jdbc:oracle:thin:@localhost:1521:mydb>
					

commit

Name

commit — Commit the current transaction

Synopsis

!commit

Description

Commit the current transaction, if autocommit is off.

Example of "commit" command

0: jdbc:oracle:thin:@localhost:1521:mydb> !autocommit off

Autocommit status: false

0: jdbc:oracle:thin:@localhost:1521:mydb> INSERT INTO EMPLOYEE (ID, FIRST_NAME, LAST_NAME) VALUES (1, 'Bob', 'Smith');
1 row affected (1.254 seconds)

0: jdbc:oracle:thin:@localhost:1521:mydb> !commit

Commit complete (0.661 seconds)

0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM EMPLOYEE;

+--------------+-------------+------------+
| ID           | FIRST_NAME  | LAST_NAME  |
+--------------+-------------+------------+
| 1            | Bob         | Smith      |
+--------------+-------------+------------+
1 row selected (0.309 seconds)

0: jdbc:oracle:thin:@localhost:1521:mydb>
					

connect

Name

connect — Connect to a database

Synopsis

!connect {url} {username} {password} [driver class]

Description

Connect to a database.

Example of "commit" command

sqlline> !connect jdbc:oracle:thin:@localhost:1521:mydb scott tiger oracle.jdbc.driver.OracleDriver

Connected to: Oracle (version Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production
With the Partitioning, OLAP and Oracle Data Mining options
JServer Release 9.2.0.1.0 - Production)
Driver: Oracle JDBC driver (version 9.0.1.0.0)
Autocommit status: true

0: jdbc:oracle:thin:@localhost:1521:mydb>
					

dbinfo

Name

dbinfo — Provide information about the current database

Synopsis

!dbinfo

Description

List metadata information about the current connection.

Example of "dbinfo" command

0: jdbc:oracle:thin:@localhost:1521:mydb> !dbinfo

allProceduresAreCallable                          false
allTablesAreSelectable                            false
dataDefinitionCausesTransactionCommit             true
dataDefinitionIgnoredInTransactions               false
doesMaxRowSizeIncludeBlobs                        true
getCatalogSeparator
getCatalogTerm
getDatabaseProductName                            Oracle
getDatabaseProductVersion                         Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production
With the Partitioning, OLAP and Oracle Data Mining options
JServer Release 9.2.0.1.0 - Production
getDefaultTransactionIsolation                    2
getDriverMajorVersion                             9
getDriverMinorVersion                             0
getDriverName                                     Oracle JDBC driver
getDriverVersion                                  9.0.1.0.0
getExtraNameCharacters                            $#
getIdentifierQuoteString                          "
getMaxBinaryLiteralLength                         1000
getMaxCatalogNameLength                           0
getMaxCharLiteralLength                           2000
getMaxColumnNameLength                            30
getMaxColumnsInGroupBy                            0
getMaxColumnsInIndex                              32
getMaxColumnsInOrderBy                            0
getMaxColumnsInSelect                             0
getMaxColumnsInTable                              1000
getMaxConnections                                 0
getMaxCursorNameLength                            0
getMaxIndexLength                                 0
getMaxProcedureNameLength                         30
getMaxRowSize                                     2000
getMaxSchemaNameLength                            30
getMaxStatementLength                             65535
getMaxStatements                                  0
getMaxTableNameLength                             30
getMaxTablesInSelect                              0
getMaxUserNameLength                              30
getNumericFunctions                               ABS,CEIL,COS,COSH,EXP,FLOOR,
                                                  LN,LOG,MOD,POWER,ROUND,SIGN,
                                                  SIN,SINH,SQRT,TAN,TANH,TRUNC,
                                                  AVG,COUNT,GLB,LUB,MAX,MIN,
                                                  STDDEV,SUM,VARIANCE
getProcedureTerm                                  procedure
getSchemaTerm                                     schema
getSearchStringEscape                             //
getSQLKeywords                                    ACCESS, ADD, ALTER, AUDIT,
                                                  CLUSTER, COLUMN, COMMENT,
                                                  COMPRESS, CONNECT, DATE, DROP,
                                                  EXCLUSIVE, FILE, IDENTIFIED,
                                                  IMMEDIATE, INCREMENT, INDEX,
                                                  INITIAL, INTERSECT,
                                                  LEVEL, LOCK, LONG, MAXEXTENTS,
                                                  MINUS, MODE, NOAUDIT,
                                                  NOCOMPRESS, NOWAIT, NUMBER,
                                                  OFFLINE, ONLINE, PCTFREE,
                                                  PRIOR,
                                                  all_PL_SQL_reserved_ words
getStringFunctions                                CHR, INITCAP, LOWER, LPAD,
                                                  LTRIM, NLS,_INITCAP,
                                                  NLS,_LOWER, NLS,_UPPER,
                                                  REPLACE, RPAD, RTRIM, SOUNDEX,
                                                  SUBSTR, SUBSTRB, TRANSLATE,
                                                  UPPER, ASCII, INSTR, INSTRB,
                                                  LENGTH, LENGTHB, NLSSORT,
                                                  CHARTOROWID, CONVERT,
                                                  HEXTORAW, RAWTOHEX,
                                                  ROWIDTOCHAR,
                                                  TO_CHAR, TO_DATE, TO_LABEL,
                                                  TO_MULTI_BYTE, TO_NUMBER,
                                                  TO_SINGLE_BYTE
getSystemFunctions                                DUMP, GREATEST, GREATEST_LB,
                                                  LEAST, LEAST_UB, NVL, UID,
                                                  USER, USERENV, VSIZE
getTimeDateFunctions                              ADD_MONTHS, LAST_DAY,
                                                  MONTHS_BETWEEN, NEW_TIME,
                                                  NEXT_DAY, ROUND, SYSDATE,
                                                  TRUNC
getURL                                            jdbc:oracle:thin:@localhost:1521:mydb
getUserName                                       MYDB
isCatalogAtStart                                  false
isReadOnly                                        false
nullPlusNonNullIsNull                             true
nullsAreSortedAtEnd                               false
nullsAreSortedAtStart                             false
nullsAreSortedHigh                                false
nullsAreSortedLow                                 true
storesLowerCaseIdentifiers                        false
storesLowerCaseQuotedIdentifiers                  false
storesMixedCaseIdentifiers                        false
storesMixedCaseQuotedIdentifiers                  true
storesUpperCaseIdentifiers                        true
storesUpperCaseQuotedIdentifiers                  false
supportsAlterTableWithAddColumn                   true
supportsAlterTableWithDropColumn                  false
supportsANSI92EntryLevelSQL                       true
supportsANSI92FullSQL                             false
supportsANSI92IntermediateSQL                     false
supportsBatchUpdates                              true
supportsCatalogsInDataManipulation                false
supportsCatalogsInIndexDefinitions                false
supportsCatalogsInPrivilegeDefinitions            false
supportsCatalogsInProcedureCalls                  false
supportsCatalogsInTableDefinitions                false
supportsColumnAliasing                            true
supportsConvert                                   true
supportsCoreSQLGrammar                            true
supportsCorrelatedSubqueries                      true
supportsDataDefinitionAndDataManipulationTransactionstrue
supportsDataManipulationTransactionsOnly          true
supportsDifferentTableCorrelationNames            true
supportsExpressionsInOrderBy                      true
supportsExtendedSQLGrammar                        true
supportsFullOuterJoins                            true
supportsGroupBy                                   true
supportsGroupByBeyondSelect                       true
supportsGroupByUnrelated                          true
supportsIntegrityEnhancementFacility              true
supportsLikeEscapeClause                          true
supportsLimitedOuterJoins                         true
supportsMinimumSQLGrammar                         true
supportsMixedCaseIdentifiers                      false
supportsMixedCaseQuotedIdentifiers                true
supportsMultipleResultSets                        false
supportsMultipleTransactions                      true
supportsNonNullableColumns                        true
supportsOpenCursorsAcrossCommit                   false
supportsOpenCursorsAcrossRollback                 false
supportsOpenStatementsAcrossCommit                false
supportsOpenStatementsAcrossRollback              false
supportsOrderByUnrelated                          true
supportsOuterJoins                                true
supportsPositionedDelete                          true
supportsPositionedUpdate                          true
supportsSchemasInDataManipulation                 true
supportsSchemasInIndexDefinitions                 true
supportsSchemasInPrivilegeDefinitions             true
supportsSchemasInProcedureCalls                   true
supportsSchemasInTableDefinitions                 true
supportsSelectForUpdate                           true
supportsStoredProcedures                          true
supportsSubqueriesInComparisons                   true
supportsSubqueriesInExists                        true
supportsSubqueriesInIns                           true
supportsSubqueriesInQuantifieds                   true
supportsTableCorrelationNames                     true
supportsTransactions                              true
supportsUnion                                     true
supportsUnionAll                                  true
usesLocalFilePerTable                             false
usesLocalFiles                                    false

0: jdbc:oracle:thin:@localhost:1521:mydb>
					

describe

Name

describe — Describe a table

Synopsis

!describe [table name]

Description

Synonym for columns (if an argument is specified) or tables (if no argument is specified).

Example of "describe" command

0: jdbc:oracle:thin:@localhost:1521:mydb> !describe EMPLOYEE

+--------------+------------+-------------+-----------+------------+
| TABLE_SCHEM  | TABLE_NAME | COLUMN_NAME | DATA_TYPE | TYPE_NAME  |
+--------------+------------+-------------+-----------+------------+
| MYDB         | EMPLOYEE   | ID          | 3         | NUMBER     |
| MYDB         | EMPLOYEE   | FIRST_NAME  | 12        | VARCHAR2   |
| MYDB         | EMPLOYEE   | LAST_NAME   | 12        | VARCHAR2   |
+--------------+------------+-------------+-----------+------------+

0: jdbc:oracle:thin:@localhost:1521:mydb>
					

dropall

Name

dropall — Drop all tables in the database

Synopsis

!dropall

Description

Drop every table in the database.

Example of "dropall" command

0: jdbc:oracle:thin:@localhost:1521:mydb> !dropall

Really drop every table in the database? (y/n) y

1/5         DROP TABLE COMPANY;
2/5         DROP TABLE EMPLOYEE;
3/5         DROP TABLE PROJECTS;
4/5         DROP TABLE EMPLOYEE_PROJECTS;
5/5         DROP TABLE COMPANYEMPLOYEES;

0: jdbc:oracle:thin:@localhost:1521:mydb>
					

Warning on using "dropall"

Warning

This command will destroy all data in the database (subject to access restrictions). Use with extreme caution.

exportedkeys

Name

exportedkeys — List exported foreign keys for a database

Synopsis

!exportedkeys {table name}

Description

List all the foreign keys that are exported by the specified table.

Example of "exportedkeys" command

0: jdbc:hsqldb:db-hypersonic> !exportedkeys COMPANY

+----------------+---------------+----------------+-------------+
| PKTABLE_SCHEM  | PKTABLE_NAME  | PKCOLUMN_NAME  | FKTABLE_CAT |
+----------------+---------------+----------------+-------------+
|                | COMPANY       | COMPANY_ID     |             |
+----------------+---------------+----------------+-------------+

0: jdbc:hsqldb:db-hypersonic>
					

go

Name

go — Change to a different active connection

Synopsis

!go {connection number}

Description

Switch to the specified connection.

Example of "go" command

0: jdbc:oracle:thin:@localhost:1521:mydb> !list

2 active connections:
 #0  open     jdbc:oracle:thin:@localhost:1521:mydb
 #1  open     jdbc:mysql://localhost/mydb

0: jdbc:oracle:thin:@localhost:1521:mydb> !go 1

1: jdbc:mysql://localhost/mydb> !go 0

0: jdbc:oracle:thin:@localhost:1521:mydb>

					

help

Name

help — Display help information

Synopsis

!help

Description

Display information about allowed commands.

Example of "help" command

sqlline> !help

!all              Execute the specified SQL against all the current connections
!autocommit       Set autocommit mode on or off
!batch            Start or execute a batch of statements
!brief            Set verbose mode off
!close            Close the current connection to the database
!columns          List all the columns for the specified table
!commit           Commit the current transaction (if autocommit is off)
!connect          Open a new connection to the database.
!dbinfo           Give metadata information about the database
!describe         Describe a table
!dropall          Drop all tables in the current database
!exportedkeys     List all the exported keys for the specified table
!go               Select the current connection
!help             Print a summary of command usage
!history          Display the command history
!importedkeys     List all the imported keys for the specified table
!indexes          List all the indexes for the specified table
!isolation        Set the transaction isolation for this connection
!list             List the current connections
!metadata         Obtain metadata information
!outputformat     Set the output format for displaying results
                  (table,vertical,csv,tsv,xmlattrs,xmlelements)
!properties       Connect to the database specified in the properties file(s)
!primarykeys      List all the primary keys for the specified table
!procedures       List all the procedures
!quit             Exits the program
!reconnect        Reconnect to the database
!record           Record all output to the specified file
!rehash           Fetch table and column names for command completion
!rollback         Roll back the current transaction (if autocommit is off)
!run              Run a script from the specified file
!save             Save the current variabes and aliases
!scan             Scan for installed JDBC drivers
!script           Start saving a script to a file
!set              Set a sqlline variable
!sql              Execute a SQL command
!tables           List all the tables in the database
!verbose          Set verbose mode on

Comments, bug reports, and patches go to mwp1@cornell.edu

sqlline> 

					

history

Name

history — Display the command history

Synopsis

!history

Description

Display the command history.

Example of "history" command

sqlline> !history

1.  !outputformat xmlelements 
2.  SELECT * FROM PCPOINT;
3.  !outputformat vertical 
4.  SELECT * FROM PCPOINT;
5.  !tables 

sqlline> 

					

importedkeys

Name

importedkeys — List imported foreign keys for a database

Synopsis

!importedkeys {table name}

Description

List all the foreign keys that are imported by the specified table.

Example of "importedkeys" command

0: jdbc:hsqldb:db-hypersonic> !importedkeys EMPLOYEE

+----------------+---------------+----------------+-------------+
| PKTABLE_SCHEM  | PKTABLE_NAME  | PKCOLUMN_NAME  | FKTABLE_CAT |
+----------------+---------------+----------------+-------------+
|                | COMPANY       | COMPANY_ID     |             |
+----------------+---------------+----------------+-------------+

0: jdbc:hsqldb:db-hypersonic>
					

indexes

Name

indexes — Display indexes for a table

Synopsis

!indexes {table name}

Description

List all the indexes on the specified table name.

Example of "indexes" command

0: jdbc:oracle:thin:@localhost:1521:mydb> !indexes EMPLOYEE

+-------------+-------------+-----------------+-------+--------------+
| TABLE_NAME  | NON_UNIQUE  |   INDEX_NAME    | TYPE  | COLUMN_NAME  |
+-------------+-------------+-----------------+-------+--------------+
| EMPLOYEE    | 0           |                 | 0     |              |
| EMPLOYEE    | 0           | SYS_C003115849  | 1     | ID           |
| EMPLOYEE    | 1           | FIRST_NAME      | 1     | FIRST_NAME   |
| EMPLOYEE    | 1           | LAST_NAME       | 1     | LAST_NAME    |
+-------------+-------------+-----------------+-------+--------------+

0: jdbc:oracle:thin:@localhost:1521:mydb>
					

isolation

Name

isolation — Set the transaction isolation mode for the active connection

Synopsis

!isolation {isolation level}

Description

Set the isolation level for the current transaction. For a description of the different isolation levels, see http://java.sun.com/j2se/1.3/docs/api/java/sql/Connection.html#field_detail.

Example of "isolation" command

0: jdbc:oracle:thin:@localhost:1521:mydb> !isolation TRANSACTION_READ_UNCOMMITTED

Error: READ_COMMITTED and SERIALIZABLE are the only valid transaction levels (state=,code=17030)

0: jdbc:oracle:thin:@localhost:1521:mydb> !isolation TRANSACTION_SERIALIZABLE

Transaction isolation: TRANSACTION_SERIALIZABLE

0: jdbc:oracle:thin:@localhost:1521:mydb>
					

list

Name

list — Display all active connections

Synopsis

!list

Description

List all the current connections.

Example of "list" command

0: jdbc:oracle:thin:@localhost:1521:mydb> !list

2 active connections:
 #0  open     jdbc:oracle:thin:@localhost:1521:mydb
 #1  open     jdbc:mysql://localhost/mydb

0: jdbc:oracle:thin:@localhost:1521:mydb>
					

metadata

Name

metadata — Invoke arbitrary metadata commands

Synopsis

!metadata {methodname} {params...}

Description

Execute an arbitrary metadata method agains the current connection. refpurpose are separated by spaces. Use "" for a blank String, and null for a null parameter. For information on available metadata methods, see http://java.sun.com/j2se/1.3/docs/api/java/sql/DatabaseMetaData.html.

Example of "metadata" command

0: jdbc:oracle:thin:@localhost:1521:mydb> !metadata supportsSelectForUpdate

true

0: jdbc:oracle:thin:@localhost:1521:mydb> !metadata getTypeInfo

+------------+------------+-------------+-----------------+-----------------+
| TYPE_NAME  | DATA_TYPE  |  PRECISION  | LITERAL_PREFIX  | LITERAL_SUFFIX  |
+------------+------------+-------------+-----------------+-----------------+
| NUMBER     | -7         | 1           |                 |                 |
| NUMBER     | -6         | 3           |                 |                 |
| NUMBER     | -5         | 38          |                 |                 |
| LONG RAW   | -4         | 2147483647  | '               | '               |
| RAW        | -3         | 2000        | '               | '               |
| LONG       | -1         | 2147483647  | '               | '               |
| CHAR       | 1          | 2000        | '               | '               |
| NUMBER     | 2          | 38          |                 |                 |
| NUMBER     | 4          | 10          |                 |                 |
| NUMBER     | 5          | 5           |                 |                 |
| FLOAT      | 6          | 63          |                 |                 |
| REAL       | 7          | 63          |                 |                 |
| VARCHAR2   | 12         | 4000        | '               | '               |
| DATE       | 93         | 7           |                 |                 |
| STRUCT     | 2002       | 0           | '               | '               |
| ARRAY      | 2003       | 0           | '               | '               |
| BLOB       | 2004       | 4294967295  |                 |                 |
| CLOB       | 2005       | 4294967295  | '               | '               |
| REF        | 2006       | 0           | '               | '               |
+------------+------------+-------------+-----------------+-----------------+

0: jdbc:oracle:thin:@localhost:1521:mydb> !meta getProcedureColumns null % %JAVA% %

+----------------+------------------+------------------------+--------------+
| PROCEDURE_CAT  | PROCEDURE_SCHEM  |     PROCEDURE_NAME     | COLUMN_NAME  |
+----------------+------------------+------------------------+--------------+
| DBMS_JAVA      | SYS              | DROPJAVA               | OPTIONS      |
| XMLPARSER      | SYS              | GETJAVARELEASEVERSION  |              |
| DBMS_JAVA      | SYS              | LOADJAVA               | OPTIONS      |
| DBMS_JAVA      | SYS              | LOADJAVA               | OPTIONS      |
| DBMS_JAVA      | SYS              | LOADJAVA               | RESOLVER     |
+----------------+------------------+------------------------+--------------+

0: jdbc:oracle:thin:@localhost:1521:mydb>
					

outputformat

Name

outputformat — Change the method for displaying SQL results

Synopsis

!outputformat {format name}

Description

Set the mode for displaying results from statements. This is useful for saving output from SQL statements to either a visually pleasing format or an easily parseable format.

Example of table output formatting

0: jdbc:oracle:thin:@localhost:1521:mydb> !outputformat table
0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY;
+-------------+------------+
| COMPANY_ID  |    NAME    |
+-------------+------------+
| 1           | Apple      |
| 2           | Sun        |
| 3           | IBM        |
| 4           | Microsoft  |
+-------------+------------+
4 rows selected (0.012 seconds)
					

Example of vertical output formatting

0: jdbc:oracle:thin:@localhost:1521:mydb> !outputformat vertical
0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY;
COMPANY_ID  1
NAME        Apple

COMPANY_ID  2
NAME        Sun

COMPANY_ID  3
NAME        IBM

COMPANY_ID  4
NAME        Microsoft

4 rows selected (0.011 seconds)
					

Example of CSV output formatting

0: jdbc:oracle:thin:@localhost:1521:mydb> !outputformat csv
0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY;
'COMPANY_ID','NAME'
'1','Apple'
'2','Sun'
'3','IBM'
'4','Microsoft'
4 rows selected (0.012 seconds)
					

Example of TSV output formatting

0: jdbc:oracle:thin:@localhost:1521:mydb> !outputformat tsv
0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY;
'COMPANY_ID'    'NAME'
'1'     'Apple'
'2'     'Sun'
'3'     'IBM'
'4'     'Microsoft'
4 rows selected (0.013 seconds)
					

Example of XML attribute output formatting

0: jdbc:oracle:thin:@localhost:1521:mydb> !outputformat xmlattr
0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY;
<resultset>
  <result COMPANY_ID="1" NAME="Apple"/>
  <result COMPANY_ID="2" NAME="Sun"/>
  <result COMPANY_ID="3" NAME="IBM"/>
  <result COMPANY_ID="4" NAME="Microsoft"/>
</resultset>
4 rows selected (0.012 seconds)
					

Example of XML element output formatting

0: jdbc:oracle:thin:@localhost:1521:mydb> !outputformat xmlelements
0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY
<resultset>
  <result>
    <COMPANY_ID>1</COMPANY_ID>
    <NAME>Apple</NAME>
  </result>
  <result>
    <COMPANY_ID>2</COMPANY_ID>
    <NAME>Sun</NAME>
  </result>
  <result>
    <COMPANY_ID>3</COMPANY_ID>
    <NAME>IBM</NAME>
  </result>
  <result>
    <COMPANY_ID>4</COMPANY_ID>
    <NAME>Microsoft</NAME>
  </result>
</resultset>
4 rows selected (0.02 seconds)
0: jdbc:oracle:thin:@localhost:1521:mydb>
					

primarykeys

Name

primarykeys — Display the primary key columns for a table

Synopsis

!primarykeys {table name}

Description

List all the primary keys for the specified table.

Example of "primarykeys" command

0: jdbc:hsqldb:db-hypersonic> !primarykeys COMPANY

+--------------+-------------+--------------+----------+----------+
| TABLE_SCHEM  | TABLE_NAME  | COLUMN_NAME  | KEY_SEQ  |     PK_N |
+--------------+-------------+--------------+----------+----------+
|              | COMPANY     | COMPANY_ID   | 1        | SYS_PK_C |
+--------------+-------------+--------------+----------+----------+

0: jdbc:hsqldb:db-hypersonic>
					

procedures

Name

procedures — List stored procedures

Synopsis

!procedures [procedure name pattern]

Description

Display a list of all the stored procedures that are exposed by the current database.

Example of "procedures" command

0: jdbc:oracle:thin:@localhost:1521:mydb> !procedures %JDBC%

+----------------+------------------+------------------+
| PROCEDURE_CAT  | PROCEDURE_SCHEM  |  PROCEDURE_NAME  |
+----------------+------------------+------------------+
| WK_ADM         | WKSYS            | GET_JDBC_DRIVER  |
| WK_ADM         | WKSYS            | SET_JDBC_DRIVER  |
+----------------+------------------+------------------+

0: jdbc:oracle:thin:@localhost:1521:mydb>
					

properties

Name

properties — Connect to the database defined in the specified properties file.

Synopsis

!properties {file}

Description

Connect to the database defined in the specified properties file. The properties file is expected to have the following values:

  • url: the database URL to which to connect

  • driver: the driver class that handles the URL. If unspecifed, SQLLine with automatically scan the CLASSPATH for an appropriate driver

  • user: the username to use to connect to the database. If unspecified, SQLLine will prompt for it.

  • password: the password to use to connect to the database. If unspecified, SQLLine will prompt for it.

The key names in the properties file can also use JDO semantics for the properties. These properties are "javax.jdo.option.ConnectionURL", "javax.jdo.option.ConnectionDriverName", "javax.jdo.option.ConnectionUserName", and "javax.jdo.option.ConnectionPassword". Furthermore, any properties that end with "ConnectionURL", "ConnectionDriverName", "ConnectionUserName", and "ConnectionPassword" will be used for the connection.

Example of "properties" command

sqlline> !properties test.properties 

Connecting to jdbc:mysql://localhost/mydb

Enter password for jdbc:mysql://localhost/mydb: *****

Connected to: MySQL (version 3.23.52-log)
Driver: MySQL-AB JDBC Driver (version 3.0.8-stable ( $Date: 2005/09/19 19:17:14 $, $Revision: 1.9 $ ))
Autocommit status: true
Transaction isolation: TRANSACTION_READ_COMMITTED

0: jdbc:mysql://localhost/mydb> 
					

quit

Name

quit — Exit SQLLine

Synopsis

!quit

Description

Exit SQLLine.

Example of "reconnect" command

0: jdbc:hsqldb:db-hypersonic> !quit

Closing: org.hsqldb.jdbcConnection
					

reconnect

Name

reconnect — Reconnect to the current database

Synopsis

!reconnect

Description

Reconnect to the current database.

Example of "reconnect" command

0: jdbc:oracle:thin:@localhost:1521:mydb> !reconnect

Reconnecting to "jdbc:oracle:thin:@localhost:1521:mydb"...

Closing: oracle.jdbc.driver.OracleConnection@4428d3

Connected to: Oracle (version Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production
With the Partitioning, OLAP and Oracle Data Mining options
JServer Release 9.2.0.1.0 - Production)
Driver: Oracle JDBC driver (version 9.0.1.0.0)
Autocommit status: true

0: jdbc:oracle:thin:@localhost:1521:mydb>
					

record

Name

record — Begin recording all output from SQL commands

Synopsis

!record {file name}

Description

Save all output from the session to the specified file.

Example of "record" command

0: jdbc:oracle:thin:@localhost:1521:mydb> !record /tmp/mysession.out

Saving all output to "/tmp/mysession.out". Enter "record" with no arguments to stop it.

0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY;
+-------------+------------+
| COMPANY_ID  |    NAME    |
+-------------+------------+
| 3           | IBM        |
| 4           | Microsoft  |
| 1           | Apple      |
| 2           | Sun        |
+-------------+------------+
4 rows selected (0.011 seconds)

0: jdbc:oracle:thin:@localhost:1521:mydb> !record

Recording stopped.

0: jdbc:oracle:thin:@localhost:1521:mydb>
					

rehash

Name

rehash — Obtain a list of all tables and columns from the database

Synopsis

!rehash

Description

Get a list of all tables and columns from the database in order to include them in the list for tab-completion of SQL statements. This is done automatically on connect when the fastconnect option is enabled.

Example of "rehash" command

0: jdbc:hsqldb:db-hypersonic> !rehash

Building list of tables and columns for tab-completion (set fastconnect to true to skip)...
7/7 (100%) Done
Done

0: jdbc:hsqldb:db-hypersonic>

					

Warning on using "rehash"

Caution

This operation can be extremely slow for some databases.

rollback

Name

rollback — Roll back the current transaction

Synopsis

!rollback

Description

Rollback the current transaction, if autocommit is off.

Example of "rollback" command

0: jdbc:oracle:thin:@localhost:1521:mydb> !autocommit off

Autocommit status: false

0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY;

+-------------+------------+
| COMPANY_ID  |    NAME    |
+-------------+------------+
| 3           | IBM        |
| 4           | Microsoft  |
| 1           | Apple      |
| 2           | Sun        |
+-------------+------------+
4 rows selected (0.011 seconds)

0: jdbc:oracle:thin:@localhost:1521:mydb> DELETE FROM COMPANY;

4 rows affected (0.004 seconds)

0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY;

+-------------+-------+
| COMPANY_ID  | NAME  |
+-------------+-------+
+-------------+-------+
No rows selected (0.01 seconds)

0: jdbc:oracle:thin:@localhost:1521:mydb> !rollback

Rollback complete (0.016 seconds)

0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY;

+-------------+------------+
| COMPANY_ID  |    NAME    |
+-------------+------------+
| 3           | IBM        |
| 4           | Microsoft  |
| 1           | Apple      |
| 2           | Sun        |
+-------------+------------+
4 rows selected (0.01 seconds)

0: jdbc:oracle:thin:@localhost:1521:mydb>
					

run

Name

run — Execute a command script

Synopsis

!run {file name}

Description

Run the individual commands specified in the file name. The file should consist of individual SQL statements or SQLLine commands. Lines beginning with "#" are interpreted as comments and ignored. If any errors occur while running the script, the script will be aborted, unless the force preference is set to true.

Example of "run" command

0: jdbc:hsqldb:db-hypersonic> !run example.sql
1/11         CREATE TABLE COMPANY (COMPANY_ID INT, NAME VARCHAR(255));
No rows affected (0.001 seconds)
2/11         INSERT INTO COMPANY VALUES (1, 'Apple');
1 row affected (0 seconds)
3/11         INSERT INTO COMPANY VALUES (2, 'Sun');
1 row affected (0 seconds)
4/11         INSERT INTO COMPANY VALUES (3, 'IBM');
1 row affected (0.001 seconds)
5/11         INSERT INTO COMPANY VALUES (4, 'Microsoft');
1 row affected (0.015 seconds)
6/11         CREATE TABLE EMPLOYEE (ID INT, FIRST_NAME VARCHAR(255), LAST_NAME VARCHAR(255), COMPANY INT);
No rows affected (0.004 seconds)
7/11         CREATE INDEX FIRST_NAME ON EMPLOYEE(FIRST_NAME);
No rows affected (0 seconds)
8/11         CREATE INDEX LAST_NAME ON EMPLOYEE(LAST_NAME);
No rows affected (0.001 seconds)
9/11         ALTER TABLE EMPLOYEE ADD CONSTRAINT EMP_COMPANY FOREIGN KEY (COMPANY) REFERENCES COMPANY (COMPANY_ID);
No rows affected (0 seconds)
10/11        INSERT INTO EMPLOYEE (ID, FIRST_NAME, LAST_NAME, COMPANY) VALUES (234, 'William', 'Gates', 4);
1 row affected (0.001 seconds)
11/11        SELECT * FROM COMPANY,EMPLOYEE WHERE EMPLOYEE.COMPANY = COMPANY.COMPANY_ID;
+------------+-----------+--------------+-------------+------------+---------+
| COMPANY_ID |    NAME   | ID           | FIRST_NAME  | LAST_NAME  | COMPANY |
+------------+-----------+--------------+-------------+------------+---------+
| 4          | Microsoft | 234          | William     | Gates      | 4       |
+------------+-----------+--------------+-------------+------------+---------+
1 row selected (0.001 seconds)
0: jdbc:hsqldb:db-hypersonic>

					

save

Name

save — Save the current preferences

Synopsis

!save

Description

Save the current preferences.

Example of "save" command

0: jdbc:oracle:thin:@localhost:1521:mydb> !save

Saving preferences to: /Users/mprudhom/.sqlline/sqlline.properties

0: jdbc:oracle:thin:@localhost:1521:mydb>
					

scan

Name

scan — Scan class path for JDBC drivers

Synopsis

!scan

Description

Scans all the jar files in the CLASSPATH for any JDBC drivers, and prints the class names of the drivers.

Example of "scan" command

sqlline> !scan

35 driver classes found
Compliant Version Driver Class
no        4.0     COM.cloudscape.core.JDBCDriver
no        1.0     COM.cloudscape.core.RmiJdbcDriver
yes       7.1     COM.ibm.db2.jdbc.net.DB2Driver
yes       3.2     com.ddtek.jdbc.db2.DB2Driver
yes       3.2     com.ddtek.jdbc.informix.InformixDriver
yes       3.2     com.ddtek.jdbc.oracle.OracleDriver
yes       3.2     com.ddtek.jdbc.sqlserver.SQLServerDriver
yes       3.2     com.ddtek.jdbc.sybase.SybaseDriver
yes       1.0     com.ibm.db2.jcc.DB2Driver
yes       2.21    com.informix.jdbc.IfxDriver
no        0.2     com.internetcds.jdbc.tds.Driver
no        0.2     com.internetcds.jdbc.tds.SybaseDriver
yes       2.2715  com.jnetdirect.jsql.JSQLDriver
yes       3.2     com.merant.datadirect.jdbc.db2.DB2Driver
yes       3.2     com.merant.datadirect.jdbc.informix.InformixDriver
yes       3.2     com.merant.datadirect.jdbc.oracle.OracleDriver
yes       3.2     com.merant.datadirect.jdbc.sqlserver.SQLServerDriver
yes       3.2     com.merant.datadirect.jdbc.sybase.SybaseDriver
yes       2.2     com.microsoft.jdbc.sqlserver.SQLServerDriver
no        3.0     com.mysql.jdbc.Driver
no        3.0     com.mysql.jdbc.NonRegisteringDriver
yes       4.4     com.pointbase.jdbc.jdbcDriver
yes       4.4     com.pointbase.jdbc.jdbcEmbeddedDriver
yes       4.4     com.pointbase.jdbc.jdbcUniversalDriver
no        5.5     com.sybase.jdbc2.jdbc.SybDriver
yes       1.0     in.co.daffodil.db.jdbc.DaffodilDBDriver
no        2.0     interbase.interclient.Driver
no        0.5     net.sourceforge.jtds.jdbc.Driver
yes       1.0     oracle.jdbc.OracleDriver
yes       1.0     oracle.jdbc.driver.OracleDriver
no        3.26    org.enhydra.instantdb.jdbc.idbDriver
no        3.0     org.gjt.mm.mysql.Driver
no        1.7     org.hsqldb.jdbcDriver
no        7.3     org.postgresql.Driver
yes       0.9     org.sourceforge.jxdbcon.JXDBConDriver

sqlline>
					

script

Name

script — Save executed commands to a file

Synopsis

!script {filename}

Description

Start saving all commands entered to the specified file. Once scripting on, it can be finished by entering the script command again with no arguments. Saved scripts can be re-run using the run command.

Example of "script" command

0: jdbc:hsqldb:db-hypersonic> !script /tmp/mysession.script

Saving command script to "/tmp/mysession.script". Enter "script" with no arguments to stop it.

0: jdbc:hsqldb:db-hypersonic> !autocommit off

Autocommit status: false

0: jdbc:hsqldb:db-hypersonic> SELECT * FROM COMPANY;

+-------------+------------+
| COMPANY_ID  |    NAME    |
+-------------+------------+
| 1           | Apple      |
| 2           | Sun        |
| 3           | IBM        |
| 4           | Microsoft  |
+-------------+------------+
4 rows selected (0.001 seconds)

0: jdbc:hsqldb:db-hypersonic> UPDATE COMPANY SET NAME='Apple, Inc.' WHERE NAME='Apple';

1 row affected (0.005 seconds)

0: jdbc:hsqldb:db-hypersonic> !commit

Commit complete (0 seconds)

0: jdbc:hsqldb:db-hypersonic> !script

Script closed. Enter "run /tmp/mysession.script" to replay it.

0: jdbc:hsqldb:db-hypersonic>
					

set

Name

set — Set a preference

Synopsis

!set {preference} {value}

Description

Set the specified preference to the specified value. If autosave is on, then this will cause preferences to be immediately saved. Otherwise, changed setting can be saved for future SQLLine session eith the save command.

Example of "set" command

0: jdbc:hsqldb:db-hypersonic> !set color on
					

sql

Name

sql — Execute a SQL against a database

Synopsis

!sql {statement}

Description

Issue the specified SQL statement. This is equivalent to entering the statement by itself from the command line.

Example of "sql" command

0: jdbc:hsqldb:db-hypersonic> !sql DELETE FROM COMPANY;

4 rows affected (0.005 seconds)

0: jdbc:hsqldb:db-hypersonic>
					

tables

Name

tables — List all the tables in the database

Synopsis

!tables

Description

List all the tables in the database of the current connection.

Example of "tables" command

0: jdbc:oracle:thin:@localhost:1521:mydb> !tables

+------------+--------------+---------------------------------+-------------+
| TABLE_CAT  | TABLE_SCHEM  |           TABLE_NAME            | TABLE_TYPE  |
+------------+--------------+---------------------------------+-------------+
|            | MYDB         | COMPANY                         | TABLE       |
|            | MYDB         | EMPLOYEE                        | TABLE       |
+------------+--------------+---------------------------------+-------------+

0: jdbc:oracle:thin:@localhost:1521:mydb>
					

verbose

Name

verbose — Enable verbose output

Synopsis

!verbose

Description

Enable verbose mode, which causes stack traces to be printed when errors occur, and enabled outputting of debug information.

Example of "verbose" command

0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM BOGUS_TABLE;

Error: ORA-00942: table or view does not exist (state=42000,code=942)

0: jdbc:oracle:thin:@localhost:1521:mydb> !verbose

verbose: on

0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM BOGUS_TABLE;

Error: ORA-00942: table or view does not exist (state=42000,code=942)
java.sql.SQLException: ORA-00942: table or view does not exist

        at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:180)
        at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:208)
        at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:543)
        at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1451)
        at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteDescribe(TTC7Protocol.java:651)
        at oracle.jdbc.driver.OracleStatement.doExecuteQuery(OracleStatement.java:2110)
        at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2324)
        at oracle.jdbc.driver.OracleStatement.execute(OracleStatement.java:909)
        at sqlline.SqlLine$Commands.sql(SqlLine.java:3183)
        at sqlline.SqlLine.dispatch(SqlLine.java:771)
        at sqlline.SqlLine.begin(SqlLine.java:634)
        at sqlline.SqlLine.main(SqlLine.java:332)

0: jdbc:oracle:thin:@localhost:1521:mydb>
					

Parameter Reference

autocommit

If true, then new connections will have autocommit set, otherwise, transactions will need to be explicitely committed or rolled back. Defaults to true. To change the autocommit status for a connection that is already open and active, use the autocommit command instead.

autosave

When set to true, any changes to preferences using the set command will cause the preferences to be saved. Otherwise, preferences will need to be explicitely saved using the save command. Defaults to false.

color

If true, then output to the terminal will use color for a more pleasing visual experience. Requires that the terminal support ANSI control codes (most do). Defaults to false.

fastconnect

When false, any new connection will cause SQLLine to access information about the available tables and columns in order to provide them as candidates for tab-completion. This can be a very slow operation for some databases, do by default it is off. Table and column information can always be explicitely retrieved using the rehash command.

force

When set to false, any failures during the execution of the run or record commands will cause execution to abort, preventing the execution of subsequent commands. When set to true, errors will be displayed but otherwise ignored. Defaults to false.

headerinterval

The interval between which the column headers will be redisplayed when using the "table" outputformat. Defaults to 100.

historyfile

The file to which SQLLine will save a record of all the commands issued. Defaults to HOME/sqlline/history on Windows, and HOME/.sqlline/history on all other platforms.

incremental

When set to false, the entire result set is fetched and buffered before being displayed, yielding optimal display column sizing. When set to true, result rows are displayed immediately as they are fetched, yielding lower latency and memory usage at the price of extra display column padding. Defaults to false.

isolation

The default transaction isolation that will be used for new connections. To change the isolation level of the currently active connection, use the isolation command instead.

maxcolumnwidth

The maximum column width to display for each colummn before truncating data when using the "table" outputformat. Defaults to 15.

maxwidth

The maximum width to display before truncating data when using the "table" outputformat. Defaults to attempting to query the terminal for the current width, falls back to 80.

outputformat

The format for how results are displayed. For details, see the information on the outputformat command.

showheader

If true, display the names of the columns when displaying results. Defaults to true.

showwarnings

If true, display any warnings that are reported on the connection after issuing any database commands. Defaults to false.

silent

If true, then reduce the amount of informational messages displayed. Useful for redirecting a sqlline command to a file for later parsing. Defaults to false.

verbose

If true, then print out the entire java stack trace whenever an error occurs, as well as displaying debugging information. Defaults to false.

JDBC Driver Support

Project Information

sqlline-1.0.2/doc-build/styles.css0000644000175000017500000001360010274700602016752 0ustar drazzibdrazzibBODY { font-family: verdana; } DIV.ABSTRACT { border: solid 2px; padding-left: 10pt; padding-right: 10pt; } PRE.SCREEN { font-family:monospace; white-space: pre; width: 100%; background-color: #ffffcc; border:solid; color: #000000; border-color: #009999; border-left: solid #009999 2px; border-right: solid #009999 2px; border-top: solid #009999 2px; border-bottom: solid #009999 2px; padding-left: 15pt; } PRE.PROGRAMLISTING { font-family:monospace; white-space: pre; width: 100%; background-color: #ffffcc; border:solid; color: #000000; border-color: #009999; border-left: solid #009999 2px; border-right: solid #009999 2px; border-top: solid #009999 2px; border-bottom: solid #009999 2px; padding-left: 15pt; } H1 { color: #ffffff; border: solid 3px #a0a0d0; background-color: #606090; font-variant: small-caps; width: 100%; } H1.TITLE { color: #ffffff; border: solid 3px #a0a0d0; background-color: #606090; font-variant: small-caps; width: 100%; } .TITLE a { color: #ffffff; text-decoration: none; } .TITLE a:active { color: #ffffff; text-decoration: none; } .TITLE a:visited { color: #ffffff; text-decoration: none; } H2 { COLOR: #ffffff ; font-style: italic; BACKGROUND-color: #a0a0d0; BORDER: solid 3px #606090; PADDING: 1px } TABLE.IMPORTANT { font-style:italic; border: solid 2px #ff0000; width: 70%; margin-left: 15%; } TABLE.CAUTION { font-style:italic; border: ridge 2px #ffff00; width: 70%; margin-left: 15%; } TABLE.NOTE { font-style:italic; border: solid 1px #000000; width: 70%; margin-left: 15%; } TABLE.TIP { font-style:italic; border: solid 1px #000000; width: 70%; margin-left: 15%; } TABLE.WARNING { font-style:italic; font-weight: bold; border: ridge 4px #ff0000; width: 70%; margin-left: 15%; } DIV.VARIABLELIST { font-family: sans-serif; font-style: normal; font-weight: normal; padding-left: 20px; } .VARLISTENTRY { font-weight: bold; margin-top: 10px; COLOR: #ffffff ; BACKGROUND-color: #a0a0d0; BORDER: solid 1px #606090; PADDING: 1px } /* * See http://diveintoaccessibility.org/day_26_using_relative_font_sizes.html * for an explanation of the following few commands. * They are really too complicated to explain here in all depth. ;-) */ P { font-size: 12px; } /*/*/A{} BODY P { font-size: x-small; voice-family: "\"}\""; voice-family: inherit; font-size: small; } HTML>BODY P { font-size: small; } /* */ A { text-decoration : none; } A:link,A:active,A:visited { color : #006699; } A:hover { text-decoration: underline; color : #DD6900; } /* Add an external-link icon to absolute links */ a[href^="http:"] { background: url(images/remote.gif) right center no-repeat; padding-right: 12px; } a[href^="http:"]:hover { background: url(images/remote_a.gif) right center no-repeat; } /* Add a note icon to footnote links */ a[href^="#FTN"] { background: url(images/qbullet-note.gif) right center no-repeat; padding-right: 12px; } a[href^="#FTN"]:hover { background: url(images/qbullet-note_a.gif) right center no-repeat; } /* ...and a back icon to the backlinks in the footnotes themselves */ a[name^="FTN"] { background: url(images/scrollup.gif) right center no-repeat; padding-right: 12px; } a[name^="FTN"]:hover { background: url(images/scrollup_a.gif) right center no-repeat; } /* Add a download icon to .gz links */ a[href$=".gz"],a[href$=".tar"],a[href$=".zip"],a[href$=".tgz"] { background: url(images/disk.gif) right center no-repeat; padding-right: 12px; } /* Add an Acrobat Reader icon to PDF links */ a[href$=".pdf"] { background: url(images/acrobat.gif) right center no-repeat; padding-right: 12px; } a[href$=".pdf"]:hover { background: url(images/acrobat_a.gif) right center no-repeat; } /* Add a Word icon to RTF links */ a[href$=".rtf"] { background: url(images/word.gif) right center no-repeat; padding-right: 12px; } /* ...but not to absolute links in this domain... */ a[href^="http://www.karakas-online.de"] { background: transparent; padding-right: 0px; } a[href^="http://www.karakas-online.de"]:hover { background: transparent; } /* ...or to the translation links on each page */ DIV.translatelink > a[href^="http:"] { background: transparent; padding-right: 0px; } DIV.translatelink > a[href^="http:"]:hover { background: transparent; } /* ...or to any images */ DIV.imagelink a[href^="http:"] { background: transparent; padding-right: 0px; } DIV.imagelink a[href^="http:"]:hover { background: transparent; } P.C2 { COLOR: #ffffff ; BACKGROUND-color: #a0a0d0; BORDER: solid 1px #606090; PADDING: 1px } DIV.NAVFOOTER { color: #000000; background-color: #EFEFF8; padding: 5px; margin-top: 10px; width: 100%; border: thin solid #a0a0d0; } DIV.NUKEFOOTER { color: #000000; background-color: #B0E0E6; padding: 5px; margin-top: 10px; width: 100%; border: thin solid #a0a0d0; } DIV.NAVHEADER { color: #000000; background-color: #EFEFF8; padding: 5px; margin-bottom: 10px; width: 100%; border: thin solid #a0a0d0; } DIV.SECT1,DIV.SECT2,DIV.SECT3 { margin-left: 20px; } DIV.EXAMPLE,DIV.TOC { border: thin dotted #70AAE5; padding-left: 10px; padding-right: 10px; color: #000000; background-color: #EFF8F8; } DIV.TOC { margin-left: 20px; margin-right: 20px; width: 95%; } UL { list-style: url("images/tux-bullet.png") disc; } sqlline-1.0.2/doc-build/manual.txt0000644000175000017500000017130210313510644016736 0ustar drazzibdrazzib SQLLine 1.0.2 Copyright (c) 2002, 2003, 2004, 2005 Marc Prud'hommeaux ---------------------------------------------------------------------- Table of Contents SQLLine Manual Introduction License and Terms of Use Obtaining SQLLine Installation Required software Installing SQLLine Using SQLLine Running SQLLine Connecting to a database Issuing SQL commands Command Completion Command Reference all autocommit batch brief close columns commit connect dbinfo describe dropall exportedkeys go help history importedkeys indexes isolation list metadata outputformat primarykeys procedures properties quit reconnect record rehash rollback run save scan script set sql tables verbose Parameter Reference autocommit autosave color fastconnect force headerinterval historyfile incremental isolation maxcolumnwidth maxwidth outputformat showheader showwarnings silent verbose JDBC Driver Support Project Information SQLLine Manual Table of Contents Introduction License and Terms of Use Obtaining SQLLine Installation Required software Installing SQLLine Using SQLLine Running SQLLine Connecting to a database Issuing SQL commands Command Completion Command Reference all autocommit batch brief close columns commit connect dbinfo describe dropall exportedkeys go help history importedkeys indexes isolation list metadata outputformat primarykeys procedures properties quit reconnect record rehash rollback run save scan script set sql tables verbose Parameter Reference autocommit autosave color fastconnect force headerinterval historyfile incremental isolation maxcolumnwidth maxwidth outputformat showheader showwarnings silent verbose JDBC Driver Support Introduction SQLLine is a pure-Java console based utility for connecting to relational databases and executing SQL commands. It is similiar to other command-line database access utilities like sqlplus for Oracle, mysql for MySQL, and isql for Sybase/SQL Server. Since it is pure-Java, it is platform independant, and will run on any platform that can run Java 1.3 or higher. License and Terms of Use SQLLine is distributed under the BSD License, meaning that you are free to redistribute, modify, or sell the software with almost no restrictions. For the text of the license, see the license text. For information on obtaining the software under another license, contact the copyright holder: mwp1@cornell.edu. Obtaining SQLLine SQLLine is hosted on SourceForge, and is located at http://sqlline.sf.net. The latest release can be downloaded from http://sqlline.sf.net/download.html. Installation Required software Installing SQLLine Required software SQLLine depends on the following software: o Java(TM) Virtual Machine - SQLLine is a pure java program, and requires Java version 1.3 or higher in order to run. The latest JVM can be downloaded from http://java.sun.com. o JLine - SQLLine uses the JLine console reader for command line editing, tab-completion, and command history. It can be downloaded from http://jline.sf.net. Version 0.8.1 or higher is required. o JDBC(TM) Driver(s) - Since SQLLine uses the Java Database Connectivity package to connect to your database, you need to obtain the correct JDBC driver libraries for your database. Any JDBC compliant driver can be used for this purpose. Drivers can be located by referring to the section on known JDBC drivers, or else by referring to your database vendor's web site. Installing SQLLine There are currently no set standards for installing Java software on different platforms. The simplest method for installing SQLLine in a platform independant way is as follows: 1. Create a new directory/folder where you like. This will be referred to as sqllinedir. 2. Download sqlline.jar into sqllinedir. 3. Download the latest jline.jar from http://jline.sf.net into sqllinedir. 4. Download your database's JDBC driver files into sqllinedir. Note that some JDBC drivers require some installation, such as uncompressing or unzipping. Using SQLLine Running SQLLine Connecting to a database Issuing SQL commands Command Completion Running SQLLine SQLLine can be run with the following command: java {-Djava.ext.dirs=sqllinedir} {sqllinedir/sqlline.jar} [options...] [properties files...] For example, if your sqllinedir is /usr/share/java/ (this is typical for Debian Linux), then you might run: java -Djava.ext.dirs=/usr/share/java/ /usr/share/java/sqlline.jar Once you have started SQLLine, you will a prompt that reads "sqlline> ". From here, you can enter either SQLLine commands (beginning with a "!" character), or a SQL statement (if you are currently connected to a database). For example, entering "!help" will display a list of all the available commands. Connecting to a database SQLLine is only useful once you are connected to a database. In order to do so, you need to use the "!connect" command, with the JDBC URL of the database you are going to connect to, followed by the username and password (followed optionally by the driver class name). The JDBC URL is specific to the JDBC driver that you are using for your database, but will always start with "jdbc:", and usually has the machine name of the database and the name of the database itself as part of the string. Consult your driver's documentation for details on the URL to use. For example, to connect to an Oracle database, you might enter: sqlline> !connect jdbc:oracle:thin:@localhost:1521:mydb scott tiger oracle.jdbc.driver.OracleDriver Connected to: Oracle (version Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production With the Partitioning, OLAP and Oracle Data Mining options JServer Release 9.2.0.1.0 - Production) Driver: Oracle JDBC driver (version 9.0.1.0.0) Autocommit status: true 0: jdbc:oracle:thin:@localhost:1521:mydb> Once you are connected, the prompt will change the reflect URL of the current connection. SQLLine can also accept command line options to connect to a database. If a file is specified on the command line, it will be treated as a properties file, and try to connect to the database specified therein. For details, see the properties command documentation. SQLLine allows you to have multiple connections to databases (either the same database, or a different database) open at the same time. Issuing the connect command multiple times will add the new connection to the list of open connections. The "current" connection (against which all SQL statements will be executed) can be switched with the go command. The currently open connections can be listed with the list command. Issuing SQL commands Once you are connected to a database, you can begin SQL statements against the current connection. For example: Example 1. Issuing SQL commands 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM MYTABLE; +-----+ | ID | +-----+ | 1 | | 2 | | 3 | | 4 | +-----+ 4 rows selected (0.012 seconds) 0: jdbc:oracle:thin:@localhost:1521:mydb> Command Completion On UNIX systems, SQLLine allows command-line completion using the tab key. This will be familiar for users of such popular shells as bash and tcsh. In general, hitting the TAB key when part of the way through typing a command will fill in the rest of the command, or else will display a selection of appropriate possibilities. Command Reference all autocommit batch brief close columns commit connect dbinfo describe dropall exportedkeys go help history importedkeys indexes isolation list metadata outputformat primarykeys procedures properties quit reconnect record rehash rollback run save scan script set sql tables verbose all Name all - Execute SQL against all active connections Synopsis !all {SQL statement} Description Execute the specified SQL against all the current connections. Example of "all" command 1: jdbc:mysql://localhost/mydb> !list 2 active connections: #0 open jdbc:oracle:thin:@localhost:1521:mydb #1 open jdbc:mysql://localhost/mydb 1: jdbc:mysql://localhost/mydb> !all DELETE FROM COMPANY; Executing SQL against: jdbc:oracle:thin:@localhost:1521:mydb 4 rows affected (0.004 seconds) Executing SQL against: jdbc:mysql://localhost/mydb 1 row affected (3.187 seconds) 1: jdbc:mysql://localhost/mydb> autocommit Name autocommit - Enable or disable automatic transaction commit mode Synopsis !autocommit {on/off} Description Set autocommit mode on or off. When autocommit is on, every individual SQL statement will be committed after it is issued. Otherwise, the commit command will need to be issued in order to commit any changes to the database. Example of "autocommit" command 1: jdbc:mysql://localhost/mydb> !autocommit off Autocommit status: false 1: jdbc:mysql://localhost/mydb> batch Name batch - Start or execute a batch of SQL statements Synopsis !batch Description Start or execute a batch of SQL statements. The first time the statement is issued, subsequent SQL statements will be deferred until the batch command is issued again. Databases can frequently optimize multiple batched statements (e.g., for bulk data loading) in order to speed up execution. Example of "batch" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !batch Batching SQL statements. Run "batch" again to execute the batch. 0: jdbc:oracle:thin:@localhost:1521:mydb> INSERT INTO MYTABLE (ID) VALUES (1); 0: jdbc:oracle:thin:@localhost:1521:mydb> INSERT INTO MYTABLE (ID) VALUES (2); 0: jdbc:oracle:thin:@localhost:1521:mydb> INSERT INTO MYTABLE (ID) VALUES (3); 0: jdbc:oracle:thin:@localhost:1521:mydb> INSERT INTO MYTABLE (ID) VALUES (4); 0: jdbc:oracle:thin:@localhost:1521:mydb> !batch Running batched SQL statements... COUNT STATEMENT 1 INSERT INTO MYTABLE (ID) VALUES (1) 1 INSERT INTO MYTABLE (ID) VALUES (2) 1 INSERT INTO MYTABLE (ID) VALUES (3) 1 INSERT INTO MYTABLE (ID) VALUES (4) 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM MYTABLE; +-----+ | ID | +-----+ | 1 | | 2 | | 3 | | 4 | +-----+ 4 rows selected (0.012 seconds) 0: jdbc:oracle:thin:@localhost:1521:mydb> brief Name brief - Enable terse output mode Synopsis !brief Description Set verbose mode off. This will prevent printing of stack traces when errors occur. Example of "brief" command 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM BOGUS_TABLE; Error: ORA-00942: table or view does not exist (state=42000,code=942) java.sql.SQLException: ORA-00942: table or view does not exist at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:180) at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:208) at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:543) at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1451) at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteDescribe(TTC7Protocol.java:651) at oracle.jdbc.driver.OracleStatement.doExecuteQuery(OracleStatement.java:2110) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2324) at oracle.jdbc.driver.OracleStatement.execute(OracleStatement.java:909) at sqlline.SqlLine$Commands.sql(SqlLine.java:3183) at sqlline.SqlLine.dispatch(SqlLine.java:771) at sqlline.SqlLine.begin(SqlLine.java:634) at sqlline.SqlLine.main(SqlLine.java:332) 0: jdbc:oracle:thin:@localhost:1521:mydb> !brief verbose: off 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM BOGUS_TABLE; Error: ORA-00942: table or view does not exist (state=42000,code=942) 0: jdbc:oracle:thin:@localhost:1521:mydb> close Name close - Close the active connection Synopsis !close Description Close the current connection and remote it from the connection list. Example of "close" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !list 1 active connection: #0 open jdbc:oracle:thin:@localhost:1521:mydb 0: jdbc:oracle:thin:@localhost:1521:mydb> !close Closing: oracle.jdbc.driver.OracleConnection sqlline> !list No active connections sqlline> columns Name columns - Display columns of a table Synopsis !columns {table name} Description List the columns in the specified table. Example of "columns" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !columns EMPLOYEE +-------------+--------------+------------+------------+ | TABLE_NAME | COLUMN_NAME | DATA_TYPE | TYPE_NAME | +-------------+--------------+------------+------------+ | EMPLOYEE | ID | 3 | NUMBER | | EMPLOYEE | FIRST_NAME | 12 | VARCHAR2 | | EMPLOYEE | LAST_NAME | 12 | VARCHAR2 | +-------------+--------------+------------+------------+ 0: jdbc:oracle:thin:@localhost:1521:mydb> commit Name commit - Commit the current transaction Synopsis !commit Description Commit the current transaction, if autocommit is off. Example of "commit" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !autocommit off Autocommit status: false 0: jdbc:oracle:thin:@localhost:1521:mydb> INSERT INTO EMPLOYEE (ID, FIRST_NAME, LAST_NAME) VALUES (1, 'Bob', 'Smith'); 1 row affected (1.254 seconds) 0: jdbc:oracle:thin:@localhost:1521:mydb> !commit Commit complete (0.661 seconds) 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM EMPLOYEE; +--------------+-------------+------------+ | ID | FIRST_NAME | LAST_NAME | +--------------+-------------+------------+ | 1 | Bob | Smith | +--------------+-------------+------------+ 1 row selected (0.309 seconds) 0: jdbc:oracle:thin:@localhost:1521:mydb> connect Name connect - Connect to a database Synopsis !connect {url} {username} {password} [driver class] Description Connect to a database. Example of "commit" command sqlline> !connect jdbc:oracle:thin:@localhost:1521:mydb scott tiger oracle.jdbc.driver.OracleDriver Connected to: Oracle (version Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production With the Partitioning, OLAP and Oracle Data Mining options JServer Release 9.2.0.1.0 - Production) Driver: Oracle JDBC driver (version 9.0.1.0.0) Autocommit status: true 0: jdbc:oracle:thin:@localhost:1521:mydb> dbinfo Name dbinfo - Provide information about the current database Synopsis !dbinfo Description List metadata information about the current connection. Example of "dbinfo" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !dbinfo allProceduresAreCallable false allTablesAreSelectable false dataDefinitionCausesTransactionCommit true dataDefinitionIgnoredInTransactions false doesMaxRowSizeIncludeBlobs true getCatalogSeparator getCatalogTerm getDatabaseProductName Oracle getDatabaseProductVersion Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production With the Partitioning, OLAP and Oracle Data Mining options JServer Release 9.2.0.1.0 - Production getDefaultTransactionIsolation 2 getDriverMajorVersion 9 getDriverMinorVersion 0 getDriverName Oracle JDBC driver getDriverVersion 9.0.1.0.0 getExtraNameCharacters $# getIdentifierQuoteString " getMaxBinaryLiteralLength 1000 getMaxCatalogNameLength 0 getMaxCharLiteralLength 2000 getMaxColumnNameLength 30 getMaxColumnsInGroupBy 0 getMaxColumnsInIndex 32 getMaxColumnsInOrderBy 0 getMaxColumnsInSelect 0 getMaxColumnsInTable 1000 getMaxConnections 0 getMaxCursorNameLength 0 getMaxIndexLength 0 getMaxProcedureNameLength 30 getMaxRowSize 2000 getMaxSchemaNameLength 30 getMaxStatementLength 65535 getMaxStatements 0 getMaxTableNameLength 30 getMaxTablesInSelect 0 getMaxUserNameLength 30 getNumericFunctions ABS,CEIL,COS,COSH,EXP,FLOOR, LN,LOG,MOD,POWER,ROUND,SIGN, SIN,SINH,SQRT,TAN,TANH,TRUNC, AVG,COUNT,GLB,LUB,MAX,MIN, STDDEV,SUM,VARIANCE getProcedureTerm procedure getSchemaTerm schema getSearchStringEscape // getSQLKeywords ACCESS, ADD, ALTER, AUDIT, CLUSTER, COLUMN, COMMENT, COMPRESS, CONNECT, DATE, DROP, EXCLUSIVE, FILE, IDENTIFIED, IMMEDIATE, INCREMENT, INDEX, INITIAL, INTERSECT, LEVEL, LOCK, LONG, MAXEXTENTS, MINUS, MODE, NOAUDIT, NOCOMPRESS, NOWAIT, NUMBER, OFFLINE, ONLINE, PCTFREE, PRIOR, all_PL_SQL_reserved_ words getStringFunctions CHR, INITCAP, LOWER, LPAD, LTRIM, NLS,_INITCAP, NLS,_LOWER, NLS,_UPPER, REPLACE, RPAD, RTRIM, SOUNDEX, SUBSTR, SUBSTRB, TRANSLATE, UPPER, ASCII, INSTR, INSTRB, LENGTH, LENGTHB, NLSSORT, CHARTOROWID, CONVERT, HEXTORAW, RAWTOHEX, ROWIDTOCHAR, TO_CHAR, TO_DATE, TO_LABEL, TO_MULTI_BYTE, TO_NUMBER, TO_SINGLE_BYTE getSystemFunctions DUMP, GREATEST, GREATEST_LB, LEAST, LEAST_UB, NVL, UID, USER, USERENV, VSIZE getTimeDateFunctions ADD_MONTHS, LAST_DAY, MONTHS_BETWEEN, NEW_TIME, NEXT_DAY, ROUND, SYSDATE, TRUNC getURL jdbc:oracle:thin:@localhost:1521:mydb getUserName MYDB isCatalogAtStart false isReadOnly false nullPlusNonNullIsNull true nullsAreSortedAtEnd false nullsAreSortedAtStart false nullsAreSortedHigh false nullsAreSortedLow true storesLowerCaseIdentifiers false storesLowerCaseQuotedIdentifiers false storesMixedCaseIdentifiers false storesMixedCaseQuotedIdentifiers true storesUpperCaseIdentifiers true storesUpperCaseQuotedIdentifiers false supportsAlterTableWithAddColumn true supportsAlterTableWithDropColumn false supportsANSI92EntryLevelSQL true supportsANSI92FullSQL false supportsANSI92IntermediateSQL false supportsBatchUpdates true supportsCatalogsInDataManipulation false supportsCatalogsInIndexDefinitions false supportsCatalogsInPrivilegeDefinitions false supportsCatalogsInProcedureCalls false supportsCatalogsInTableDefinitions false supportsColumnAliasing true supportsConvert true supportsCoreSQLGrammar true supportsCorrelatedSubqueries true supportsDataDefinitionAndDataManipulationTransactionstrue supportsDataManipulationTransactionsOnly true supportsDifferentTableCorrelationNames true supportsExpressionsInOrderBy true supportsExtendedSQLGrammar true supportsFullOuterJoins true supportsGroupBy true supportsGroupByBeyondSelect true supportsGroupByUnrelated true supportsIntegrityEnhancementFacility true supportsLikeEscapeClause true supportsLimitedOuterJoins true supportsMinimumSQLGrammar true supportsMixedCaseIdentifiers false supportsMixedCaseQuotedIdentifiers true supportsMultipleResultSets false supportsMultipleTransactions true supportsNonNullableColumns true supportsOpenCursorsAcrossCommit false supportsOpenCursorsAcrossRollback false supportsOpenStatementsAcrossCommit false supportsOpenStatementsAcrossRollback false supportsOrderByUnrelated true supportsOuterJoins true supportsPositionedDelete true supportsPositionedUpdate true supportsSchemasInDataManipulation true supportsSchemasInIndexDefinitions true supportsSchemasInPrivilegeDefinitions true supportsSchemasInProcedureCalls true supportsSchemasInTableDefinitions true supportsSelectForUpdate true supportsStoredProcedures true supportsSubqueriesInComparisons true supportsSubqueriesInExists true supportsSubqueriesInIns true supportsSubqueriesInQuantifieds true supportsTableCorrelationNames true supportsTransactions true supportsUnion true supportsUnionAll true usesLocalFilePerTable false usesLocalFiles false 0: jdbc:oracle:thin:@localhost:1521:mydb> describe Name describe - Describe a table Synopsis !describe [table name] Description Synonym for columns (if an argument is specified) or tables (if no argument is specified). Example of "describe" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !describe EMPLOYEE +--------------+------------+-------------+-----------+------------+ | TABLE_SCHEM | TABLE_NAME | COLUMN_NAME | DATA_TYPE | TYPE_NAME | +--------------+------------+-------------+-----------+------------+ | MYDB | EMPLOYEE | ID | 3 | NUMBER | | MYDB | EMPLOYEE | FIRST_NAME | 12 | VARCHAR2 | | MYDB | EMPLOYEE | LAST_NAME | 12 | VARCHAR2 | +--------------+------------+-------------+-----------+------------+ 0: jdbc:oracle:thin:@localhost:1521:mydb> dropall Name dropall - Drop all tables in the database Synopsis !dropall Description Drop every table in the database. Example of "dropall" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !dropall Really drop every table in the database? (y/n) y 1/5 DROP TABLE COMPANY; 2/5 DROP TABLE EMPLOYEE; 3/5 DROP TABLE PROJECTS; 4/5 DROP TABLE EMPLOYEE_PROJECTS; 5/5 DROP TABLE COMPANYEMPLOYEES; 0: jdbc:oracle:thin:@localhost:1521:mydb> Warning on using "dropall" Warning This command will destroy all data in the database (subject to access restrictions). Use with extreme caution. exportedkeys Name exportedkeys - List exported foreign keys for a database Synopsis !exportedkeys {table name} Description List all the foreign keys that are exported by the specified table. Example of "exportedkeys" command 0: jdbc:hsqldb:db-hypersonic> !exportedkeys COMPANY +----------------+---------------+----------------+-------------+ | PKTABLE_SCHEM | PKTABLE_NAME | PKCOLUMN_NAME | FKTABLE_CAT | +----------------+---------------+----------------+-------------+ | | COMPANY | COMPANY_ID | | +----------------+---------------+----------------+-------------+ 0: jdbc:hsqldb:db-hypersonic> go Name go - Change to a different active connection Synopsis !go {connection number} Description Switch to the specified connection. Example of "go" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !list 2 active connections: #0 open jdbc:oracle:thin:@localhost:1521:mydb #1 open jdbc:mysql://localhost/mydb 0: jdbc:oracle:thin:@localhost:1521:mydb> !go 1 1: jdbc:mysql://localhost/mydb> !go 0 0: jdbc:oracle:thin:@localhost:1521:mydb> help Name help - Display help information Synopsis !help Description Display information about allowed commands. Example of "help" command sqlline> !help !all Execute the specified SQL against all the current connections !autocommit Set autocommit mode on or off !batch Start or execute a batch of statements !brief Set verbose mode off !close Close the current connection to the database !columns List all the columns for the specified table !commit Commit the current transaction (if autocommit is off) !connect Open a new connection to the database. !dbinfo Give metadata information about the database !describe Describe a table !dropall Drop all tables in the current database !exportedkeys List all the exported keys for the specified table !go Select the current connection !help Print a summary of command usage !history Display the command history !importedkeys List all the imported keys for the specified table !indexes List all the indexes for the specified table !isolation Set the transaction isolation for this connection !list List the current connections !metadata Obtain metadata information !outputformat Set the output format for displaying results (table,vertical,csv,tsv,xmlattrs,xmlelements) !properties Connect to the database specified in the properties file(s) !primarykeys List all the primary keys for the specified table !procedures List all the procedures !quit Exits the program !reconnect Reconnect to the database !record Record all output to the specified file !rehash Fetch table and column names for command completion !rollback Roll back the current transaction (if autocommit is off) !run Run a script from the specified file !save Save the current variabes and aliases !scan Scan for installed JDBC drivers !script Start saving a script to a file !set Set a sqlline variable !sql Execute a SQL command !tables List all the tables in the database !verbose Set verbose mode on Comments, bug reports, and patches go to mwp1@cornell.edu sqlline> history Name history - Display the command history Synopsis !history Description Display the command history. Example of "history" command sqlline> !history 1. !outputformat xmlelements 2. SELECT * FROM PCPOINT; 3. !outputformat vertical 4. SELECT * FROM PCPOINT; 5. !tables sqlline> importedkeys Name importedkeys - List imported foreign keys for a database Synopsis !importedkeys {table name} Description List all the foreign keys that are imported by the specified table. Example of "importedkeys" command 0: jdbc:hsqldb:db-hypersonic> !importedkeys EMPLOYEE +----------------+---------------+----------------+-------------+ | PKTABLE_SCHEM | PKTABLE_NAME | PKCOLUMN_NAME | FKTABLE_CAT | +----------------+---------------+----------------+-------------+ | | COMPANY | COMPANY_ID | | +----------------+---------------+----------------+-------------+ 0: jdbc:hsqldb:db-hypersonic> indexes Name indexes - Display indexes for a table Synopsis !indexes {table name} Description List all the indexes on the specified table name. Example of "indexes" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !indexes EMPLOYEE +-------------+-------------+-----------------+-------+--------------+ | TABLE_NAME | NON_UNIQUE | INDEX_NAME | TYPE | COLUMN_NAME | +-------------+-------------+-----------------+-------+--------------+ | EMPLOYEE | 0 | | 0 | | | EMPLOYEE | 0 | SYS_C003115849 | 1 | ID | | EMPLOYEE | 1 | FIRST_NAME | 1 | FIRST_NAME | | EMPLOYEE | 1 | LAST_NAME | 1 | LAST_NAME | +-------------+-------------+-----------------+-------+--------------+ 0: jdbc:oracle:thin:@localhost:1521:mydb> isolation Name isolation - Set the transaction isolation mode for the active connection Synopsis !isolation {isolation level} Description Set the isolation level for the current transaction. For a description of the different isolation levels, see http://java.sun.com/j2se/1.3/docs/api/java/sql/Connection.html#field_detail. Example of "isolation" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !isolation TRANSACTION_READ_UNCOMMITTED Error: READ_COMMITTED and SERIALIZABLE are the only valid transaction levels (state=,code=17030) 0: jdbc:oracle:thin:@localhost:1521:mydb> !isolation TRANSACTION_SERIALIZABLE Transaction isolation: TRANSACTION_SERIALIZABLE 0: jdbc:oracle:thin:@localhost:1521:mydb> list Name list - Display all active connections Synopsis !list Description List all the current connections. Example of "list" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !list 2 active connections: #0 open jdbc:oracle:thin:@localhost:1521:mydb #1 open jdbc:mysql://localhost/mydb 0: jdbc:oracle:thin:@localhost:1521:mydb> metadata Name metadata - Invoke arbitrary metadata commands Synopsis !metadata {methodname} {params...} Description Execute an arbitrary metadata method agains the current connection. refpurpose are separated by spaces. Use "" for a blank String, and null for a null parameter. For information on available metadata methods, see http://java.sun.com/j2se/1.3/docs/api/java/sql/DatabaseMetaData.html. Example of "metadata" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !metadata supportsSelectForUpdate true 0: jdbc:oracle:thin:@localhost:1521:mydb> !metadata getTypeInfo +------------+------------+-------------+-----------------+-----------------+ | TYPE_NAME | DATA_TYPE | PRECISION | LITERAL_PREFIX | LITERAL_SUFFIX | +------------+------------+-------------+-----------------+-----------------+ | NUMBER | -7 | 1 | | | | NUMBER | -6 | 3 | | | | NUMBER | -5 | 38 | | | | LONG RAW | -4 | 2147483647 | ' | ' | | RAW | -3 | 2000 | ' | ' | | LONG | -1 | 2147483647 | ' | ' | | CHAR | 1 | 2000 | ' | ' | | NUMBER | 2 | 38 | | | | NUMBER | 4 | 10 | | | | NUMBER | 5 | 5 | | | | FLOAT | 6 | 63 | | | | REAL | 7 | 63 | | | | VARCHAR2 | 12 | 4000 | ' | ' | | DATE | 93 | 7 | | | | STRUCT | 2002 | 0 | ' | ' | | ARRAY | 2003 | 0 | ' | ' | | BLOB | 2004 | 4294967295 | | | | CLOB | 2005 | 4294967295 | ' | ' | | REF | 2006 | 0 | ' | ' | +------------+------------+-------------+-----------------+-----------------+ 0: jdbc:oracle:thin:@localhost:1521:mydb> !meta getProcedureColumns null % %JAVA% % +----------------+------------------+------------------------+--------------+ | PROCEDURE_CAT | PROCEDURE_SCHEM | PROCEDURE_NAME | COLUMN_NAME | +----------------+------------------+------------------------+--------------+ | DBMS_JAVA | SYS | DROPJAVA | OPTIONS | | XMLPARSER | SYS | GETJAVARELEASEVERSION | | | DBMS_JAVA | SYS | LOADJAVA | OPTIONS | | DBMS_JAVA | SYS | LOADJAVA | OPTIONS | | DBMS_JAVA | SYS | LOADJAVA | RESOLVER | +----------------+------------------+------------------------+--------------+ 0: jdbc:oracle:thin:@localhost:1521:mydb> outputformat Name outputformat - Change the method for displaying SQL results Synopsis !outputformat {format name} Description Set the mode for displaying results from statements. This is useful for saving output from SQL statements to either a visually pleasing format or an easily parseable format. Example of table output formatting 0: jdbc:oracle:thin:@localhost:1521:mydb> !outputformat table 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY; +-------------+------------+ | COMPANY_ID | NAME | +-------------+------------+ | 1 | Apple | | 2 | Sun | | 3 | IBM | | 4 | Microsoft | +-------------+------------+ 4 rows selected (0.012 seconds) Example of vertical output formatting 0: jdbc:oracle:thin:@localhost:1521:mydb> !outputformat vertical 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY; COMPANY_ID 1 NAME Apple COMPANY_ID 2 NAME Sun COMPANY_ID 3 NAME IBM COMPANY_ID 4 NAME Microsoft 4 rows selected (0.011 seconds) Example of CSV output formatting 0: jdbc:oracle:thin:@localhost:1521:mydb> !outputformat csv 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY; 'COMPANY_ID','NAME' '1','Apple' '2','Sun' '3','IBM' '4','Microsoft' 4 rows selected (0.012 seconds) Example of TSV output formatting 0: jdbc:oracle:thin:@localhost:1521:mydb> !outputformat tsv 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY; 'COMPANY_ID' 'NAME' '1' 'Apple' '2' 'Sun' '3' 'IBM' '4' 'Microsoft' 4 rows selected (0.013 seconds) Example of XML attribute output formatting 0: jdbc:oracle:thin:@localhost:1521:mydb> !outputformat xmlattr 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY; 4 rows selected (0.012 seconds) Example of XML element output formatting 0: jdbc:oracle:thin:@localhost:1521:mydb> !outputformat xmlelements 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY 1 Apple 2 Sun 3 IBM 4 Microsoft 4 rows selected (0.02 seconds) 0: jdbc:oracle:thin:@localhost:1521:mydb> primarykeys Name primarykeys - Display the primary key columns for a table Synopsis !primarykeys {table name} Description List all the primary keys for the specified table. Example of "primarykeys" command 0: jdbc:hsqldb:db-hypersonic> !primarykeys COMPANY +--------------+-------------+--------------+----------+----------+ | TABLE_SCHEM | TABLE_NAME | COLUMN_NAME | KEY_SEQ | PK_N | +--------------+-------------+--------------+----------+----------+ | | COMPANY | COMPANY_ID | 1 | SYS_PK_C | +--------------+-------------+--------------+----------+----------+ 0: jdbc:hsqldb:db-hypersonic> procedures Name procedures - List stored procedures Synopsis !procedures [procedure name pattern] Description Display a list of all the stored procedures that are exposed by the current database. Example of "procedures" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !procedures %JDBC% +----------------+------------------+------------------+ | PROCEDURE_CAT | PROCEDURE_SCHEM | PROCEDURE_NAME | +----------------+------------------+------------------+ | WK_ADM | WKSYS | GET_JDBC_DRIVER | | WK_ADM | WKSYS | SET_JDBC_DRIVER | +----------------+------------------+------------------+ 0: jdbc:oracle:thin:@localhost:1521:mydb> properties Name properties - Connect to the database defined in the specified properties file. Synopsis !properties {file} Description Connect to the database defined in the specified properties file. The properties file is expected to have the following values: o url: the database URL to which to connect o driver: the driver class that handles the URL. If unspecifed, SQLLine with automatically scan the CLASSPATH for an appropriate driver o user: the username to use to connect to the database. If unspecified, SQLLine will prompt for it. o password: the password to use to connect to the database. If unspecified, SQLLine will prompt for it. The key names in the properties file can also use JDO semantics for the properties. These properties are "javax.jdo.option.ConnectionURL", "javax.jdo.option.ConnectionDriverName", "javax.jdo.option.ConnectionUserName", and "javax.jdo.option.ConnectionPassword". Furthermore, any properties that end with "ConnectionURL", "ConnectionDriverName", "ConnectionUserName", and "ConnectionPassword" will be used for the connection. Example of "properties" command sqlline> !properties test.properties Connecting to jdbc:mysql://localhost/mydb Enter password for jdbc:mysql://localhost/mydb: ***** Connected to: MySQL (version 3.23.52-log) Driver: MySQL-AB JDBC Driver (version 3.0.8-stable ( $Date: 2005/09/19 19:17:14 $, $Revision: 1.9 $ )) Autocommit status: true Transaction isolation: TRANSACTION_READ_COMMITTED 0: jdbc:mysql://localhost/mydb> quit Name quit - Exit SQLLine Synopsis !quit Description Exit SQLLine. Example of "reconnect" command 0: jdbc:hsqldb:db-hypersonic> !quit Closing: org.hsqldb.jdbcConnection reconnect Name reconnect - Reconnect to the current database Synopsis !reconnect Description Reconnect to the current database. Example of "reconnect" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !reconnect Reconnecting to "jdbc:oracle:thin:@localhost:1521:mydb"... Closing: oracle.jdbc.driver.OracleConnection@4428d3 Connected to: Oracle (version Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production With the Partitioning, OLAP and Oracle Data Mining options JServer Release 9.2.0.1.0 - Production) Driver: Oracle JDBC driver (version 9.0.1.0.0) Autocommit status: true 0: jdbc:oracle:thin:@localhost:1521:mydb> record Name record - Begin recording all output from SQL commands Synopsis !record {file name} Description Save all output from the session to the specified file. Example of "record" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !record /tmp/mysession.out Saving all output to "/tmp/mysession.out". Enter "record" with no arguments to stop it. 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY; +-------------+------------+ | COMPANY_ID | NAME | +-------------+------------+ | 3 | IBM | | 4 | Microsoft | | 1 | Apple | | 2 | Sun | +-------------+------------+ 4 rows selected (0.011 seconds) 0: jdbc:oracle:thin:@localhost:1521:mydb> !record Recording stopped. 0: jdbc:oracle:thin:@localhost:1521:mydb> rehash Name rehash - Obtain a list of all tables and columns from the database Synopsis !rehash Description Get a list of all tables and columns from the database in order to include them in the list for tab-completion of SQL statements. This is done automatically on connect when the fastconnect option is enabled. Example of "rehash" command 0: jdbc:hsqldb:db-hypersonic> !rehash Building list of tables and columns for tab-completion (set fastconnect to true to skip)... 7/7 (100%) Done Done 0: jdbc:hsqldb:db-hypersonic> Warning on using "rehash" Caution This operation can be extremely slow for some databases. rollback Name rollback - Roll back the current transaction Synopsis !rollback Description Rollback the current transaction, if autocommit is off. Example of "rollback" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !autocommit off Autocommit status: false 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY; +-------------+------------+ | COMPANY_ID | NAME | +-------------+------------+ | 3 | IBM | | 4 | Microsoft | | 1 | Apple | | 2 | Sun | +-------------+------------+ 4 rows selected (0.011 seconds) 0: jdbc:oracle:thin:@localhost:1521:mydb> DELETE FROM COMPANY; 4 rows affected (0.004 seconds) 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY; +-------------+-------+ | COMPANY_ID | NAME | +-------------+-------+ +-------------+-------+ No rows selected (0.01 seconds) 0: jdbc:oracle:thin:@localhost:1521:mydb> !rollback Rollback complete (0.016 seconds) 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY; +-------------+------------+ | COMPANY_ID | NAME | +-------------+------------+ | 3 | IBM | | 4 | Microsoft | | 1 | Apple | | 2 | Sun | +-------------+------------+ 4 rows selected (0.01 seconds) 0: jdbc:oracle:thin:@localhost:1521:mydb> run Name run - Execute a command script Synopsis !run {file name} Description Run the individual commands specified in the file name. The file should consist of individual SQL statements or SQLLine commands. Lines beginning with "#" are interpreted as comments and ignored. If any errors occur while running the script, the script will be aborted, unless the force preference is set to true. Example of "run" command 0: jdbc:hsqldb:db-hypersonic> !run example.sql 1/11 CREATE TABLE COMPANY (COMPANY_ID INT, NAME VARCHAR(255)); No rows affected (0.001 seconds) 2/11 INSERT INTO COMPANY VALUES (1, 'Apple'); 1 row affected (0 seconds) 3/11 INSERT INTO COMPANY VALUES (2, 'Sun'); 1 row affected (0 seconds) 4/11 INSERT INTO COMPANY VALUES (3, 'IBM'); 1 row affected (0.001 seconds) 5/11 INSERT INTO COMPANY VALUES (4, 'Microsoft'); 1 row affected (0.015 seconds) 6/11 CREATE TABLE EMPLOYEE (ID INT, FIRST_NAME VARCHAR(255), LAST_NAME VARCHAR(255), COMPANY INT); No rows affected (0.004 seconds) 7/11 CREATE INDEX FIRST_NAME ON EMPLOYEE(FIRST_NAME); No rows affected (0 seconds) 8/11 CREATE INDEX LAST_NAME ON EMPLOYEE(LAST_NAME); No rows affected (0.001 seconds) 9/11 ALTER TABLE EMPLOYEE ADD CONSTRAINT EMP_COMPANY FOREIGN KEY (COMPANY) REFERENCES COMPANY (COMPANY_ID); No rows affected (0 seconds) 10/11 INSERT INTO EMPLOYEE (ID, FIRST_NAME, LAST_NAME, COMPANY) VALUES (234, 'William', 'Gates', 4); 1 row affected (0.001 seconds) 11/11 SELECT * FROM COMPANY,EMPLOYEE WHERE EMPLOYEE.COMPANY = COMPANY.COMPANY_ID; +------------+-----------+--------------+-------------+------------+---------+ | COMPANY_ID | NAME | ID | FIRST_NAME | LAST_NAME | COMPANY | +------------+-----------+--------------+-------------+------------+---------+ | 4 | Microsoft | 234 | William | Gates | 4 | +------------+-----------+--------------+-------------+------------+---------+ 1 row selected (0.001 seconds) 0: jdbc:hsqldb:db-hypersonic> save Name save - Save the current preferences Synopsis !save Description Save the current preferences. Example of "save" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !save Saving preferences to: /Users/mprudhom/.sqlline/sqlline.properties 0: jdbc:oracle:thin:@localhost:1521:mydb> scan Name scan - Scan class path for JDBC drivers Synopsis !scan Description Scans all the jar files in the CLASSPATH for any JDBC drivers, and prints the class names of the drivers. Example of "scan" command sqlline> !scan 35 driver classes found Compliant Version Driver Class no 4.0 COM.cloudscape.core.JDBCDriver no 1.0 COM.cloudscape.core.RmiJdbcDriver yes 7.1 COM.ibm.db2.jdbc.net.DB2Driver yes 3.2 com.ddtek.jdbc.db2.DB2Driver yes 3.2 com.ddtek.jdbc.informix.InformixDriver yes 3.2 com.ddtek.jdbc.oracle.OracleDriver yes 3.2 com.ddtek.jdbc.sqlserver.SQLServerDriver yes 3.2 com.ddtek.jdbc.sybase.SybaseDriver yes 1.0 com.ibm.db2.jcc.DB2Driver yes 2.21 com.informix.jdbc.IfxDriver no 0.2 com.internetcds.jdbc.tds.Driver no 0.2 com.internetcds.jdbc.tds.SybaseDriver yes 2.2715 com.jnetdirect.jsql.JSQLDriver yes 3.2 com.merant.datadirect.jdbc.db2.DB2Driver yes 3.2 com.merant.datadirect.jdbc.informix.InformixDriver yes 3.2 com.merant.datadirect.jdbc.oracle.OracleDriver yes 3.2 com.merant.datadirect.jdbc.sqlserver.SQLServerDriver yes 3.2 com.merant.datadirect.jdbc.sybase.SybaseDriver yes 2.2 com.microsoft.jdbc.sqlserver.SQLServerDriver no 3.0 com.mysql.jdbc.Driver no 3.0 com.mysql.jdbc.NonRegisteringDriver yes 4.4 com.pointbase.jdbc.jdbcDriver yes 4.4 com.pointbase.jdbc.jdbcEmbeddedDriver yes 4.4 com.pointbase.jdbc.jdbcUniversalDriver no 5.5 com.sybase.jdbc2.jdbc.SybDriver yes 1.0 in.co.daffodil.db.jdbc.DaffodilDBDriver no 2.0 interbase.interclient.Driver no 0.5 net.sourceforge.jtds.jdbc.Driver yes 1.0 oracle.jdbc.OracleDriver yes 1.0 oracle.jdbc.driver.OracleDriver no 3.26 org.enhydra.instantdb.jdbc.idbDriver no 3.0 org.gjt.mm.mysql.Driver no 1.7 org.hsqldb.jdbcDriver no 7.3 org.postgresql.Driver yes 0.9 org.sourceforge.jxdbcon.JXDBConDriver sqlline> script Name script - Save executed commands to a file Synopsis !script {filename} Description Start saving all commands entered to the specified file. Once scripting on, it can be finished by entering the script command again with no arguments. Saved scripts can be re-run using the run command. Example of "script" command 0: jdbc:hsqldb:db-hypersonic> !script /tmp/mysession.script Saving command script to "/tmp/mysession.script". Enter "script" with no arguments to stop it. 0: jdbc:hsqldb:db-hypersonic> !autocommit off Autocommit status: false 0: jdbc:hsqldb:db-hypersonic> SELECT * FROM COMPANY; +-------------+------------+ | COMPANY_ID | NAME | +-------------+------------+ | 1 | Apple | | 2 | Sun | | 3 | IBM | | 4 | Microsoft | +-------------+------------+ 4 rows selected (0.001 seconds) 0: jdbc:hsqldb:db-hypersonic> UPDATE COMPANY SET NAME='Apple, Inc.' WHERE NAME='Apple'; 1 row affected (0.005 seconds) 0: jdbc:hsqldb:db-hypersonic> !commit Commit complete (0 seconds) 0: jdbc:hsqldb:db-hypersonic> !script Script closed. Enter "run /tmp/mysession.script" to replay it. 0: jdbc:hsqldb:db-hypersonic> set Name set - Set a preference Synopsis !set {preference} {value} Description Set the specified preference to the specified value. If autosave is on, then this will cause preferences to be immediately saved. Otherwise, changed setting can be saved for future SQLLine session eith the save command. Example of "set" command 0: jdbc:hsqldb:db-hypersonic> !set color on sql Name sql - Execute a SQL against a database Synopsis !sql {statement} Description Issue the specified SQL statement. This is equivalent to entering the statement by itself from the command line. Example of "sql" command 0: jdbc:hsqldb:db-hypersonic> !sql DELETE FROM COMPANY; 4 rows affected (0.005 seconds) 0: jdbc:hsqldb:db-hypersonic> tables Name tables - List all the tables in the database Synopsis !tables Description List all the tables in the database of the current connection. Example of "tables" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !tables +------------+--------------+---------------------------------+-------------+ | TABLE_CAT | TABLE_SCHEM | TABLE_NAME | TABLE_TYPE | +------------+--------------+---------------------------------+-------------+ | | MYDB | COMPANY | TABLE | | | MYDB | EMPLOYEE | TABLE | +------------+--------------+---------------------------------+-------------+ 0: jdbc:oracle:thin:@localhost:1521:mydb> verbose Name verbose - Enable verbose output Synopsis !verbose Description Enable verbose mode, which causes stack traces to be printed when errors occur, and enabled outputting of debug information. Example of "verbose" command 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM BOGUS_TABLE; Error: ORA-00942: table or view does not exist (state=42000,code=942) 0: jdbc:oracle:thin:@localhost:1521:mydb> !verbose verbose: on 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM BOGUS_TABLE; Error: ORA-00942: table or view does not exist (state=42000,code=942) java.sql.SQLException: ORA-00942: table or view does not exist at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:180) at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:208) at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:543) at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1451) at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteDescribe(TTC7Protocol.java:651) at oracle.jdbc.driver.OracleStatement.doExecuteQuery(OracleStatement.java:2110) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2324) at oracle.jdbc.driver.OracleStatement.execute(OracleStatement.java:909) at sqlline.SqlLine$Commands.sql(SqlLine.java:3183) at sqlline.SqlLine.dispatch(SqlLine.java:771) at sqlline.SqlLine.begin(SqlLine.java:634) at sqlline.SqlLine.main(SqlLine.java:332) 0: jdbc:oracle:thin:@localhost:1521:mydb> Parameter Reference autocommit autosave color fastconnect force headerinterval historyfile incremental isolation maxcolumnwidth maxwidth outputformat showheader showwarnings silent verbose autocommit If true, then new connections will have autocommit set, otherwise, transactions will need to be explicitely committed or rolled back. Defaults to true. To change the autocommit status for a connection that is already open and active, use the autocommit command instead. autosave When set to true, any changes to preferences using the set command will cause the preferences to be saved. Otherwise, preferences will need to be explicitely saved using the save command. Defaults to false. color If true, then output to the terminal will use color for a more pleasing visual experience. Requires that the terminal support ANSI control codes (most do). Defaults to false. fastconnect When false, any new connection will cause SQLLine to access information about the available tables and columns in order to provide them as candidates for tab-completion. This can be a very slow operation for some databases, do by default it is off. Table and column information can always be explicitely retrieved using the rehash command. force When set to false, any failures during the execution of the run or record commands will cause execution to abort, preventing the execution of subsequent commands. When set to true, errors will be displayed but otherwise ignored. Defaults to false. headerinterval The interval between which the column headers will be redisplayed when using the "table" outputformat. Defaults to 100. historyfile The file to which SQLLine will save a record of all the commands issued. Defaults to HOME/sqlline/history on Windows, and HOME/.sqlline/history on all other platforms. incremental When set to false, the entire result set is fetched and buffered before being displayed, yielding optimal display column sizing. When set to true, result rows are displayed immediately as they are fetched, yielding lower latency and memory usage at the price of extra display column padding. Defaults to false. isolation The default transaction isolation that will be used for new connections. To change the isolation level of the currently active connection, use the isolation command instead. maxcolumnwidth The maximum column width to display for each colummn before truncating data when using the "table" outputformat. Defaults to 15. maxwidth The maximum width to display before truncating data when using the "table" outputformat. Defaults to attempting to query the terminal for the current width, falls back to 80. outputformat The format for how results are displayed. For details, see the information on the outputformat command. showheader If true, display the names of the columns when displaying results. Defaults to true. showwarnings If true, display any warnings that are reported on the connection after issuing any database commands. Defaults to false. silent If true, then reduce the amount of informational messages displayed. Useful for redirecting a sqlline command to a file for later parsing. Defaults to false. verbose If true, then print out the entire java stack trace whenever an error occurs, as well as displaying debugging information. Defaults to false. JDBC Driver Support Project Information sqlline-1.0.2/test/0000755000175000017500000000000010313510646014033 5ustar drazzibdrazzibsqlline-1.0.2/src/0000755000175000017500000000000010313510646013643 5ustar drazzibdrazzibsqlline-1.0.2/src/sqlline/0000755000175000017500000000000010311260312015300 5ustar drazzibdrazzibsqlline-1.0.2/src/sqlline/SqlLine.properties0000644000175000017500000001565610074775302021022 0ustar drazzibdrazzibapp-introduction: {0} version {1} by {2} jline-version: The version of the required {0} library is too old. Version \ "{1}" was found, but "{2}" is required. enter-for-more: [ Hit "enter" for more ("q" to exit) ] no-manual: Could not find manual resource. executing-command: Executing command: {0} unknown-command: Unknown command: {0} autocommit-needs-off: Operation requires that autocommit be turned off. no-current-connection: No current connection connection-is-closed: Connection is closed reconnecting: Reconnecting to "{0}"... connecting: Connecting to "{0}"... no-driver: No known driver to handle "{0}" setting-prop: Setting property: {0} saving-options: Saving preferences to: {0} loaded-options: Loaded preferences from: {0} jdbc-level: JDBC level compliant: Compliant jdbc-version: Version driver-class: Driver Class help-quit: Exits the program help-dropall: Drop all tables in the current database help-connect: Open a new connection to the database. help-manual: Display the SQLLine manual help-typeinfo: Display the type map for the current connection help-describe: Describe a table help-reconnect: Reconnect to the database help-metadata: Obtain metadata information help-dbinfo: Give metadata information about the database help-rehash: Fetch table and column names for command completion help-verbose: Set verbose mode on help-run: Run a script from the specified file help-list: List the current connections help-all: Execute the specified SQL against all the current connections help-go: Select the current connection help-script: Start saving a script to a file help-brief: Set verbose mode off help-close: Close the current connection to the database help-closeall: Close all current open connections help-isolation: Set the transaction isolation for this connection help-nativesql: Show the native SQL for the specified statement help-call: Execute a callable statement help-autocommit: Set autocommit mode on or off help-commit: Commit the current transaction (if autocommit is off) help-rollback: Roll back the current transaction (if autocommit is off) help-batch: Start or execute a batch of statements help-help: Print a summary of command usage help-set: Set a sqlline variable help-save: Save the current variabes and aliases help-native: Show the database''s native SQL for a command help-alias: Create a new command alias help-unalias: Unset a command alias help-scan: Scan for installed JDBC drivers help-sql: Execute a SQL command help-history: Display the command history help-record: Record all output to the specified file help-indexes: List all the indexes for the specified table help-primarykeys: List all the primary keys for the specified table help-exportedkeys: List all the exported keys for the specified table help-importedkeys: List all the imported keys for the specified table help-procedures: List all the procedures help-tables: List all the tables in the database help-columns: List all the columns for the specified table help-properties: Connect to the database specified in the properties file(s) help-outputformat: Set the output format for displaying results (table,vertical,csv,tsv,xmlattrs,xmlelements) jline-missing: The JLine jar was not found. Please ensure it is installed. batch-start: Batching SQL statements. Run "batch" again to execute the batch. running-batch: Running batched SQL statements... arg-usage: Usage: {0} <{1}> scanning: Scanning {0}... no-such-method: No such method "{0}" possible-methods: Possible methods: closing: Closing: {0} already-closed: Connection is already closed. error-setting: Error setting configuration: {0}: {1} no-method: No method matching "{0}" was found in {1}. connected: Connected to: {0} (version {1}) driver: Driver: {0} (version {1}) autocommit-status: Autocommit status: {0} isolation-status: Transaction isolation: {0} unknown-format: Unknown output format "{0}". Possible values: {1} closed: closed open: open executing-con: Executing SQL against: {0} comments: Comments, bug reports, and patches go to {0} building-tables: Building list of tables and columns for tab-completion \ (set fastconnect to true to skip)... done: Done state: state code: code invalid-connections: Invalid connection: {0} script-closed: Script closed. Enter "run {0}" to replay it. script-already-running: Script ({0}) is already running. Enter "script" with no arguments to stop it. script-started: Saving command script to "{0}". Enter "script" with no arguments to stop it. record-closed: Recording stopped. record-already-running: Output already being saved to ({0}). Enter "record" with no arguments to stop it. record-started: Saving all output to "{0}". Enter "record" with no arguments to stop it. autoloading-known-drivers: No known driver to handle "{0}". Searching for known drivers... Warning: Warning: {0} (state={1},code={2,number,#}) Error: Error: {0} (state={1},code={2,number,#}) commit-complete: Commit complete rollback-complete: Rollback complete abort-on-error: Aborting command set because "force" is false and \ command failed: "{0}" multiple-matches: Ambiguous command: {0} really-drop-all: Really drop every table in the database? (y/n)\ abort-drop-all: Aborting drop all tables. drivers-found-count: 0#No driver classes found|1#{0} driver class found|1<{0} driver classes found rows-selected: 0#No rows selected|1#{0} row selected|1<{0} rows selected rows-affected: 0#No rows affected|1#{0} row affected|1<{0} rows affected|0>Unknown rows affected active-connections: 0#No active connections|1#{0} active connection:|1<{0} active connections: time-ms: ({0,number,#.###} seconds) cmd-usage: Usage: java sqlline.SqlLine \n \ \ -u the JDBC URL to connect to\n \ \ -n the username to connect as\n \ \ -p the password to connect as\n \ \ -d the driver class to use\n \ \ --color=[true/false] control whether color is used for display\n \ \ --showHeader=[true/false] show column names in query results\n \ \ --headerInterval=ROWS; the interval between which heades are displayed\n \ \ --fastConnect=[true/false] skip building table/column list for tab-completion\n \ \ --autoCommit=[true/false] enable/disable automatic transaction commit\n \ \ --verbose=[true/false] show verbose error messages and debug info\n \ \ --showWarnings=[true/false] display connection warnings\n \ \ --force=[true/false] continue running script even after errors\n \ \ --maxWidth=MAXWIDTH the maximum width of the terminal\n \ \ --maxColumnWidth=MAXCOLWIDTH the maximum width to use when displaying columns\n \ \ --silent=[true/false] be more silent\n \ \ --autosave=[true/false] automatically save preferences\n \ \ --outputformat=[table/vertical/csv/tsv] format mode for result display\n \ \ --isolation=LEVEL set the transaction isolation level\n \ \ --help display this message sqlline-1.0.2/src/sqlline/SqlLine.java0000644000175000017500000034605610311260302017527 0ustar drazzibdrazzib/* * Copyright (c) 2002,2003,2004,2005 Marc Prud'hommeaux * All rights reserved. * * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * Neither the name of the nor the names * of its contributors may be used to endorse or promote * products derived from this software without specific * prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS * AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software is hosted by SourceForge. * SourceForge is a trademark of VA Linux Systems, Inc. */ package sqlline; import jline.*; import java.io.*; import java.net.*; import java.text.*; import java.sql.*; import java.util.*; import java.lang.reflect.*; import java.util.zip.*; import java.util.jar.*; /** * A console SQL shell with command completion. *

* TODO: *

    *
  • User-friendly connection prompts
  • *
  • Page results
  • *
  • Handle binary data (blob fields)
  • *
  • Implement command aliases
  • *
  • Stored procedure execution
  • *
  • Binding parameters to prepared statements
  • *
  • Scripting language
  • *
  • XA transactions
  • *
* * @author Marc Prud'hommeaux */ public class SqlLine { private static final ResourceBundle loc = ResourceBundle.getBundle ( SqlLine.class.getName ()); /* public static final String APP_NAME = "sqlline"; public static final String APP_VERSION = "0.7.3"; public static final String APP_AUTHOR = "Marc Prud'hommeaux"; public static final String APP_AUTHOR_EMAIL = "marc@apocalypse.org"; public static final String APP_TITLE = APP_NAME + " " + APP_VERSION + " by " + APP_AUTHOR; */ private static final String sep = System.getProperty ("line.separator"); private boolean exit = false; private final SqlLine sqlline = this; private Collection drivers = null; private Connections connections = new Connections (); public static final String COMMAND_PREFIX = "!"; private Completor sqlLineCommandCompletor; private Map completions = new HashMap (); private Opts opts = new Opts (System.getProperties ()); String lastProgress = null; String prompt = "sqlline"; private Map seenWarnings = new HashMap (); private final Commands command = new Commands (); private OutputFile script = null; private OutputFile record = null; private ConsoleReader reader; private List batch = null; private final Map formats = map (new Object [] { "vertical", new VerticalOutputFormat (), "table", new TableOutputFormat (), "csv", new SeparatedValuesOutputFormat (','), "tsv", new SeparatedValuesOutputFormat ('\t'), "xmlattr", new XMLAttributeOutputFormat (), "xmlelements", new XMLElementOutputFormat (), }); private CommandHandler [] commands = new CommandHandler [] { new ReflectiveCommandHandler (new String [] { "quit", "done", "exit" }, null), new ReflectiveCommandHandler (new String [] { "connect", "open" }, new Completor [] { new SimpleCompletor (getConnectionURLExamples ())}), new ReflectiveCommandHandler (new String [] { "describe" }, new Completor [] { new TableNameCompletor ()}), new ReflectiveCommandHandler (new String [] { "indexes" }, new Completor [] { new TableNameCompletor ()}), new ReflectiveCommandHandler (new String [] { "primarykeys" }, new Completor [] { new TableNameCompletor ()}), new ReflectiveCommandHandler (new String [] { "exportedkeys" }, new Completor [] { new TableNameCompletor ()}), new ReflectiveCommandHandler (new String [] { "manual" }, null), new ReflectiveCommandHandler (new String [] { "importedkeys" }, new Completor [] { new TableNameCompletor ()}), new ReflectiveCommandHandler (new String [] { "procedures" }, null), new ReflectiveCommandHandler (new String [] { "tables" }, null), new ReflectiveCommandHandler (new String [] { "typeinfo" }, null), new ReflectiveCommandHandler (new String [] { "columns" }, new Completor [] { new TableNameCompletor ()}), new ReflectiveCommandHandler (new String [] { "reconnect" }, null), new ReflectiveCommandHandler (new String [] { "dropall" }, new Completor [] { new TableNameCompletor ()}), new ReflectiveCommandHandler (new String [] { "history" }, null), new ReflectiveCommandHandler (new String [] { "metadata" }, new Completor [] { new SimpleCompletor (getMetadataMethodNames ())}), new ReflectiveCommandHandler (new String [] { "nativesql" }, null), new ReflectiveCommandHandler (new String [] { "dbinfo" }, null), new ReflectiveCommandHandler (new String [] { "rehash" }, null), new ReflectiveCommandHandler (new String [] { "verbose" }, null), new ReflectiveCommandHandler (new String [] { "run" }, new Completor [] { new FileNameCompletor ()}), new ReflectiveCommandHandler (new String [] { "batch" }, null), new ReflectiveCommandHandler (new String [] { "list" }, null), new ReflectiveCommandHandler (new String [] { "all" }, null), new ReflectiveCommandHandler (new String [] { "go", "#" }, null), new ReflectiveCommandHandler (new String [] { "script" }, new Completor [] { new FileNameCompletor ()}), new ReflectiveCommandHandler (new String [] { "record" }, new Completor [] { new FileNameCompletor ()}), new ReflectiveCommandHandler (new String [] { "brief" }, null), new ReflectiveCommandHandler (new String [] { "close" }, null), new ReflectiveCommandHandler (new String [] { "closeall" }, null), new ReflectiveCommandHandler (new String [] { "isolation" }, new Completor [] { new SimpleCompletor (getIsolationLevels ())}), new ReflectiveCommandHandler (new String [] { "outputformat" }, new Completor [] { new SimpleCompletor ( (String [])formats.keySet ().toArray (new String [0]) )}), new ReflectiveCommandHandler (new String [] { "autocommit" }, null), new ReflectiveCommandHandler (new String [] { "commit" }, null), new ReflectiveCommandHandler (new String [] { "properties" }, new Completor [] { new FileNameCompletor ()}), new ReflectiveCommandHandler (new String [] { "rollback" }, null), new ReflectiveCommandHandler (new String [] { "help", "?" }, null), new ReflectiveCommandHandler (new String [] { "set" }, opts.optionCompletors ()), new ReflectiveCommandHandler (new String [] { "save" }, null), new ReflectiveCommandHandler (new String [] { "scan" }, null), new ReflectiveCommandHandler (new String [] { "sql" }, null), new ReflectiveCommandHandler (new String [] { "call" }, null), }; static final SortedSet KNOWN_DRIVERS = new TreeSet (Arrays.asList ( new String [] { "com.merant.datadirect.jdbc.sqlserver.SQLServerDriver", "com.microsoft.jdbc.sqlserver.SQLServerDriver", "com.ddtek.jdbc.informix.InformixDriver", "org.sourceforge.jxdbcon.JXDBConDriver", "com.ddtek.jdbc.oracle.OracleDriver", "net.sourceforge.jtds.jdbc.Driver", "com.pointbase.jdbc.jdbcDriver", "com.internetcds.jdbc.tds.SybaseDriver", "org.enhydra.instantdb.jdbc.idbDriver", "com.sybase.jdbc2.jdbc.SybDriver", "com.ddtek.jdbc.sybase.SybaseDriver", "COM.cloudscape.core.JDBCDriver", "in.co.daffodil.db.jdbc.DaffodilDBDriver", "com.jnetdirect.jsql.JSQLDriver", "COM.ibm.db2.jdbc.net.DB2Driver", "org.hsqldb.jdbcDriver", "com.pointbase.jdbc.jdbcUniversalDriver", "com.ddtek.jdbc.sqlserver.SQLServerDriver", "com.ddtek.jdbc.db2.DB2Driver", "com.merant.datadirect.jdbc.oracle.OracleDriver", "oracle.jdbc.OracleDriver", "com.informix.jdbc.IfxDriver", "com.merant.datadirect.jdbc.informix.InformixDriver", "com.ibm.db2.jcc.DB2Driver", "com.pointbase.jdbc.jdbcEmbeddedDriver", "org.gjt.mm.mysql.Driver", "org.postgresql.Driver", "com.mysql.jdbc.Driver", "oracle.jdbc.driver.OracleDriver", "interbase.interclient.Driver", "com.mysql.jdbc.NonRegisteringDriver", "com.merant.datadirect.jdbc.db2.DB2Driver", "com.merant.datadirect.jdbc.sybase.SybaseDriver", "com.internetcds.jdbc.tds.Driver", "org.hsqldb.jdbcDriver", "org.hsql.jdbcDriver", "COM.cloudscape.core.JDBCDriver", "in.co.daffodil.db.jdbc.DaffodilDBDriver", "com.ddtek.jdbc.db2.DB2Driver", "interbase.interclient.Driver", "com.mysql.jdbc.Driver", "com.ddtek.jdbc.oracle.OracleDriver", "org.postgresql.Driver", "com.pointbase.jdbc.jdbcUniversalDriver", "org.sourceforge.jxdbcon.JXDBConDriver", "com.ddtek.jdbc.sqlserver.SQLServerDriver", "com.jnetdirect.jsql.JSQLDriver", "com.microsoft.jdbc.sqlserver.SQLServerDriver", "weblogic.jdbc.mssqlserver4.Driver", "com.ddtek.jdbc.sybase.SybaseDriver", "oracle.jdbc.pool.OracleDataSource", "org.axiondb.jdbc.AxionDriver", "COM.ibm.db2.jdbc.app.DB2Driver", "com.ibm.as400.access.AS400JDBCDriver", "COM.FirstSQL.Dbcp.DbcpDriver", "COM.ibm.db2.jdbc.net.DB2Driver", "org.enhydra.instantdb.jdbc.idbDriver", "com.informix.jdbc.IfxDriver", "com.microsoft.jdbc.sqlserver.SQLServerDriver", "com.imaginary.sql.msql.MsqlDriver", "sun.jdbc.odbc.JdbcOdbcDriver", "oracle.jdbc.driver.OracleDriver", "intersolv.jdbc.sequelink.SequeLinkDriver", "openlink.jdbc2.Driver", "com.pointbase.jdbc.jdbcUniversalDriver", "postgres95.PGDriver", "postgresql.Driver", "solid.jdbc.SolidDriver", "centura.java.sqlbase.SqlbaseDriver", "interbase.interclient.Driver", "com.mckoi.JDBCDriver", "com.inet.tds.TdsDriver", "com.microsoft.jdbc.sqlserver.SQLServerDriver", "com.thinweb.tds.Driver", "weblogic.jdbc.mssqlserver4.Driver", "com.mysql.jdbc.DatabaseMetaData", "org.gjt.mm.mysql.Driver", "com.sap.dbtech.jdbc.DriverSapDB", "com.sybase.jdbc2.jdbc.SybDriver", "com.sybase.jdbc.SybDriver", "com.internetcds.jdbc.tds.Driver", "weblogic.jdbc.pool.Driver", })); static { Class jline; try { jline = Class.forName ("jline.ConsoleReader"); } catch (Throwable t) { throw new ExceptionInInitializerError (loc ("jline-missing")); } /* System.out.println ("JLine package: " + jline.getPackage ()); String required = "1.0.3"; if (!(jline.getPackage ().isCompatibleWith (required))) throw new ExceptionInInitializerError (loc ("jline-version", new Object [] { jline.getPackage ().getSpecificationTitle (), jline.getPackage ().getSpecificationVersion (), required, })); */ } static Manifest getManifest () throws IOException { URL base = SqlLine.class.getResource ("/META-INF/MANIFEST.MF"); URLConnection c = base.openConnection (); if (c instanceof JarURLConnection) return ((JarURLConnection)c).getManifest (); return null; } static String getManifestAttribute (String name) { try { Manifest m = getManifest (); if (m == null) return "??"; Attributes attrs = m.getAttributes ("sqlline"); if (attrs == null) return "???"; String val = attrs.getValue (name); if (val == null || "".equals (val)) return "????"; return val; } catch (Exception e) { e.printStackTrace (); return "?????"; } } static String getApplicationTitle () { Package pack = SqlLine.class.getPackage (); return loc ("app-introduction", new Object [] { pack.getImplementationTitle () == null ? "sqlline" : pack.getImplementationTitle (), pack.getImplementationVersion () == null ? "???" : pack.getImplementationVersion (), pack.getImplementationVendor () == null ? "Marc Prud'hommeaux" : pack.getImplementationVendor (), // getManifestAttribute ("Specification-Title"), // getManifestAttribute ("Implementation-Version"), // getManifestAttribute ("Implementation-ReleaseDate"), // getManifestAttribute ("Implementation-Vendor"), // getManifestAttribute ("Implementation-License"), }); } static String getApplicationContactInformation () { return getManifestAttribute ("Implementation-Vendor"); } static String loc (String res) { return loc (res, new Object [0]); } static String loc (String res, int param) { try { return MessageFormat.format ( new ChoiceFormat (loc.getString (res)).format (param), new Object [] { new Integer (param) }); } catch (Exception e) { return res + ": " + param; } } static String loc (String res, Object param1) { return loc (res, new Object [] { param1 }); } static String loc (String res, Object param1, Object param2) { return loc (res, new Object [] { param1, param2 }); } static String loc (String res, Object [] params) { try { return MessageFormat.format (loc.getString (res), params); } catch (Exception e) { e.printStackTrace (); try { return res + ": " + Arrays.asList (params); } catch (Exception e2) { return res; } } } /** * Starts the program. */ public static void main (String [] args) throws IOException { mainWithInputRedirection (args, null); } /** * Starts the program with redirected input. For redirected output, * System.setOut and System.setErr can be used, but System.setIn * will not work. * * @param args same as main() * * @param inputStream redirected input, or null to use standard input */ public static void mainWithInputRedirection ( String [] args, InputStream inputStream) throws IOException { SqlLine sqlline = new SqlLine (); sqlline.begin (args, inputStream); // exit the system: useful for Hypersonic and other // badly-behaving systems if (!Boolean.getBoolean (Opts.PROPERTY_NAME_EXIT)) System.exit (0); } SqlLine () { // registerKnownDrivers (); sqlLineCommandCompletor = new SQLLineCommandCompletor (); } DatabaseConnection con () { return connections.current (); } Connection conn () { if (connections.current () == null) throw new IllegalArgumentException (loc ("no-current-connection")); if (connections.current ().connection == null) throw new IllegalArgumentException (loc ("no-current-connection")); return connections.current ().connection; } DatabaseMetaData meta () { if (connections.current () == null) throw new IllegalArgumentException (loc ("no-current-connection")); if (connections.current ().meta == null) throw new IllegalArgumentException (loc ("no-current-connection")); return connections.current ().meta; } public String [] getIsolationLevels () { return new String [] { "TRANSACTION_NONE", "TRANSACTION_READ_COMMITTED", "TRANSACTION_READ_UNCOMMITTED", "TRANSACTION_REPEATABLE_READ", "TRANSACTION_SERIALIZABLE", }; } public String [] getMetadataMethodNames () { try { TreeSet mnames = new TreeSet (); Method [] m = DatabaseMetaData.class.getDeclaredMethods (); for (int i = 0; m != null && i < m.length; i++) mnames.add (m [i].getName ()); return (String [])mnames.toArray (new String [0]); } catch (Throwable t) { return new String [0]; } } public String [] getConnectionURLExamples () { return new String [] { "jdbc:JSQLConnect:///database=", "jdbc:cloudscape:;create=true", "jdbc:twtds:sqlserver:///", "jdbc:daffodilDB_embedded:;create=true", "jdbc:datadirect:db2://:50000;databaseName=", "jdbc:inetdae::1433", "jdbc:datadirect:oracle://:1521;SID=;" + "MaxPooledStatements=0", "jdbc:datadirect:sqlserver://:1433;SelectMethod=cursor;" + "DatabaseName=", "jdbc:datadirect:sybase://:5000", "jdbc:db2:///", "jdbc:hsqldb:", "jdbc:idb:.properties", "jdbc:informix-sqli://:1526/:INFORMIXSERVER" + "=", "jdbc:interbase:////.gdb", "jdbc:microsoft:sqlserver://:1433;" + "DatabaseName=;SelectMethod=cursor", "jdbc:mysql:///?autoReconnect=true", "jdbc:oracle:thin:@:1521:", "jdbc:pointbase:,database.home=,create=true", "jdbc:postgresql://:5432/", "jdbc:postgresql:net///", "jdbc:sybase:Tds::4100/?ServiceName=", "jdbc:weblogic:mssqlserver4:@:1433", "jdbc:odbc:", "jdbc:sequelink://:4003/[Oracle]", "jdbc:sequelink://:4004/[Informix];Database=", "jdbc:sequelink://:4005/[Sybase];Database=", "jdbc:sequelink://:4006/[SQLServer];Database=", "jdbc:sequelink://:4011/[ODBC MS Access];" + "Database=", "jdbc:openlink:///DSN=SQLServerDB/UID=sa/PWD=", "jdbc:solid://://", "jdbc:dbaw://:8889/", }; } /** * Entry point to creating a {@link ColorBuffer} with color * enabled or disabled depending on the calue of * {@link Opts#getColor}. */ ColorBuffer color () { return new ColorBuffer (opts.getColor ()); } /** * Entry point to creating a {@link ColorBuffer} with color * enabled or disabled depending on the calue of * {@link Opts#getColor}. */ ColorBuffer color (String msg) { return new ColorBuffer (msg, opts.getColor ()); } /* public String nameToDriverClass (String name) { if (name.startsWith ("jdbc:")) return null; // ### FIXME: other drivers if (name.indexOf ("oracle") != -1) return "oracle.jdbc.OracleDriver"; return null; } */ /* public boolean connectByPrompt (String className) throws Exception { return false; } */ /** * Currently does nothing, because very few drivers actually support * {@link DriverPropertyInfo}. */ /* public boolean connectByDriverPropertyInfo (String className) throws Exception { Driver driver = (Driver)Class.forName (className).newInstance (); String url = "jdbc:oracle:thin:@10.0.0.50:1521:ora92"; Properties props = new Properties (); DriverPropertyInfo [] info = driver.getPropertyInfo (url, props); while (info != null && info.length > 0) { for (int i = 0; info != null && i < info.length; i++) { output (info [i].description + " (" + info [i].name + "): " + info [i].value + " [" + Arrays.asList (info [i].choices) + "]"); } info = driver.getPropertyInfo (url, props); } return false; } */ /** * Walk through all the known drivers and try to register them. */ void registerKnownDrivers () { for (Iterator i = KNOWN_DRIVERS.iterator (); i.hasNext (); ) { try { Class.forName (i.next ().toString ()); } catch (Throwable t) { } } } boolean initArgs (String [] args) { List commands = new LinkedList (); List files = new LinkedList (); String driver = null, user = null, pass = null, url = null, cmd = null; for (int i = 0; i < args.length; i++) { if (args [i].equals ("--help") || args [i].equals ("-h")) { usage (); return false; } // -- arguments are treated as properties if (args [i].startsWith ("--")) { String [] parts = split (args [i].substring (2), "="); debug (loc ("setting-prop", Arrays.asList (parts))); if (parts.length > 0) { boolean ret; if (parts.length >= 2) ret = opts.set (parts [0], parts [1], true); else ret = opts.set (parts [0], "true", true); if (!ret) return false; } continue; } if (args [i].equals ("-d")) driver = args [i++ + 1]; else if (args [i].equals ("-n")) user = args [i++ + 1]; else if (args [i].equals ("-p")) pass = args [i++ + 1]; else if (args [i].equals ("-u")) url = args [i++ + 1]; else if (args [i].equals ("-e")) commands.add (args [i++ + 1]); else files.add (args [i]); } if (url != null) { String com = "!connect " + url + " " + (user == null || user.length () == 0 ? "''" : user) + " " + (pass == null || pass.length () == 0 ? "''" : pass) + " " + (driver == null ? "" : driver); debug ("issuing: " + com); dispatch (com); } // now load properties files for (Iterator i = files.iterator (); i.hasNext (); ) dispatch ("!properties " + i.next ()); if (commands.size () > 0) { // for single commane execute, disable color opts.setColor (false); opts.setHeaderInterval (-1); for (Iterator i = commands.iterator (); i.hasNext (); ) { String command = i.next ().toString (); debug (loc ("executing-command", command)); dispatch (command); } exit = true; // execute and exit } return true; } /** * Start accepting input from stdin, and dispatch it * to the appropriate {@link CommandHandler} until the * global variable exit is true. */ void begin (String [] args, InputStream inputStream) throws IOException { try { // load the options first, so we can override on the command line opts.load (); } catch (Exception e) { } ConsoleReader reader = getConsoleReader (inputStream); if (!(initArgs (args))) { usage (); return; } try { info (getApplicationTitle ()); } catch (Exception e) { } while (!exit) { try { dispatch (reader.readLine (getPrompt ())); } catch (EOFException eof) { // CTRL-D command.quit (null); } catch (Throwable t) { handleException (t); } } // ### NOTE jvs 10-Aug-2004: Clean up any outstanding // connections automatically. command.closeall (null); } public ConsoleReader getConsoleReader (InputStream inputStream) throws IOException { Terminal terminal = Terminal.setupTerminal (); if (inputStream != null) { // ### NOTE: fix for sf.net bug 879425. reader = new ConsoleReader ( inputStream, new PrintWriter (System.out)); } else { reader = new ConsoleReader (); } // setup history ByteArrayInputStream historyBuffer = null; if (new File (opts.getHistoryFile ()).isFile ()) { try { // save the current contents of the history buffer. This gets // around a bug in JLine where setting the output before the // input will clobber the history input, but setting the // input before the output will cause the previous commands // to not be saved to the buffer. FileInputStream historyIn = new FileInputStream ( opts.getHistoryFile ()); ByteArrayOutputStream hist = new ByteArrayOutputStream (); int n; while ((n = historyIn.read ()) != -1) hist.write (n); historyIn.close (); historyBuffer = new ByteArrayInputStream (hist.toByteArray ()); } catch (Exception e) { handleException (e); } } try { // now set the output for the history PrintWriter historyOut = new PrintWriter (new FileWriter ( opts.getHistoryFile ())); reader.getHistory ().setOutput (historyOut); } catch (Exception e) { handleException (e); } try { // now load in the previous history if (historyBuffer != null) reader.getHistory ().load (historyBuffer); } catch (Exception e) { handleException (e); } reader.addCompletor (new SQLLineCompletor ()); return reader; } void usage () { output (loc ("cmd-usage")); } /** * Dispatch the specified line to the appropriate * {@link CommandHandler}. * * @param line the commmand-line to dispatch * @return true if the command was "successful" */ boolean dispatch (String line) { if (line == null) { // exit exit = true; return true; } if (line.trim ().length () == 0) return true; if (isComment (line)) return true; line = line.trim (); // save it to the current script, if any if (script != null) script.addLine (line); if (isHelpRequest (line)) line = "!help"; if (line.startsWith (COMMAND_PREFIX)) { Map cmdMap = new TreeMap (); line = line.substring (1); for (int i = 0; i < commands.length; i++) { String match = commands [i].matches (line); if (match != null) cmdMap.put (match, commands [i]); } if (cmdMap.size () == 0) return error (loc ("unknown-command", line)); else if (cmdMap.size () > 1) return error (loc ("multiple-matches", cmdMap.keySet ().toString ())); else return ((CommandHandler)cmdMap.values ().iterator ().next ()) .execute (line); } else return command.sql (line); } /** * Test whether a line requires a continuation. * * @param line the line to be tested * * @return true if continuation required */ boolean needsContinuation (String line) { if (isHelpRequest (line)) return false; if (line.startsWith (COMMAND_PREFIX)) return false; if (isComment (line)) return false; String trimmed = line.trim(); if (trimmed.length () == 0) return false; return !trimmed.endsWith (";"); } /** * Test whether a line is a help request other than !help. * * @param line the line to be tested * * @return true if a help request */ boolean isHelpRequest (String line) { return line.equals ("?") || line.equalsIgnoreCase ("help"); } /** * Test whether a line is a comment. * * @param line the line to be tested * * @return true if a comment */ boolean isComment (String line) { // SQL92 comment prefix is "--" // sqlline also supports shell-style "#" prefix return line.startsWith ("#") || line.startsWith ("--"); } /** * Print the specified message to the console * * @param msg the message to print */ void output (String msg) { output (msg, true); } void info (String msg) { if (!(opts.getSilent ())) output (msg, true, System.err); } void info (ColorBuffer msg) { if (!(opts.getSilent ())) output (msg, true, System.err); } /** * Issue the specified error message * * @param msg the message to issue * @return false always */ boolean error (String msg) { output (color ().red (msg), true, System.err); return false; } boolean error (Throwable t) { handleException (t); return false; } void debug (String msg) { if (opts.getVerbose ()) output (color ().blue (msg), true, System.err); } void output (ColorBuffer msg) { output (msg, true); } void output (String msg, boolean newline, PrintStream out) { output (color (msg), newline, out); } void output (ColorBuffer msg, boolean newline) { output (msg, newline, System.out); } void output (ColorBuffer msg, boolean newline, PrintStream out) { if (newline) out.println (msg.getColor ()); else out.print (msg.getColor ()); if (record == null) return; // only write to the record file if we are writing a line ... // otherwise we might get garbage from backspaces and such. if (newline) record.addLine (msg.getMono ()); // always just write mono } /** * Print the specified message to the console * * @param msg the message to print * @param newline if false, do not append a newline */ void output (String msg, boolean newline) { output (color (msg), newline); } void autocommitStatus (Connection c) throws SQLException { info (loc ("autocommit-status", c.getAutoCommit () + "")); } /** * Ensure that autocommit is on for the current connection * * @return true if autocommit is set */ boolean assertAutoCommit () { if (!(assertConnection ())) return false; try { if (con ().connection.getAutoCommit ()) return error (loc ("autocommit-needs-off")); } catch (Exception e) { return error (e); } return true; } /** * Assert that we have an active, living connection. Print * an error message if we do not. * * @return true if there is a current, active connection */ boolean assertConnection () { try { if (con () == null || con ().connection == null) return error (loc ("no-current-connection")); if (con ().connection.isClosed ()) return error (loc ("connection-is-closed")); } catch (SQLException sqle) { return error (loc ("no-current-connection")); } return true; } /** * Print out any warnings that exist for the current connection. */ void showWarnings () { if (con ().connection == null) return; if (!opts.getVerbose ()) return; try { showWarnings (con ().connection.getWarnings ()); } catch (Exception e) { handleException (e); } } /** * Print the specified warning on the console, as well as * any warnings that are returned from * {@link SQLWarning#getNextWarning}. * * @param warn the {@link SQLWarning} to print */ void showWarnings (SQLWarning warn) { if (warn == null) return; if (seenWarnings.get (warn) == null) { // don't re-display warnings we have already seen seenWarnings.put (warn, new java.util.Date ()); handleSQLException (warn); } SQLWarning next = warn.getNextWarning (); if (next != warn) showWarnings (next); } String getPrompt () { if (con () == null || con ().url == null) return "sqlline> "; else return getPrompt (connections.getIndex () + ": " + con ().url) + "> "; } static String getPrompt (String url) { if (url == null || url.length () == 0) url = "sqlline"; if (url.indexOf (";") > -1) url = url.substring (0, url.indexOf (";")); if (url.indexOf ("?") > -1) url = url.substring (0, url.indexOf ("?")); if (url.length () > 45) url = url.substring (0, 45); return url; } /** * Try to obtain the current size of the specified {@link ResultSet} * by jumping to the last row and getting the row number. * * @param rs the {@link ResultSet} to get the size for * @return the size, or -1 if it could not be obtained */ int getSize (ResultSet rs) { try { if (rs.getType () == rs.TYPE_FORWARD_ONLY) return -1; rs.last (); int total = rs.getRow (); rs.beforeFirst (); return total; } catch (SQLException sqle) { return -1; } // JDBC 1 driver error catch (AbstractMethodError ame) { return -1; } } ResultSet getColumns (String table) throws SQLException { if (!(assertConnection ())) return null; return con ().meta.getColumns ( con ().meta.getConnection ().getCatalog (), null, table, "%"); } ResultSet getTables () throws SQLException { if (!(assertConnection ())) return null; return con ().meta.getTables ( con ().meta.getConnection ().getCatalog (), null, "%", new String [] { "TABLE" }); } String [] getColumnNames (DatabaseMetaData meta) throws SQLException { Set names = new HashSet (); info (loc ("building-tables")); try { ResultSet columns = getColumns ("%"); try { int total = getSize (columns); int index = 0; while (columns.next ()) { // add the following strings: // 1. column name // 2. table name // 3. tablename.columnname progress (index++, total); String name = columns.getString ("TABLE_NAME"); names.add (name); names.add (columns.getString ("COLUMN_NAME")); names.add (columns.getString ("TABLE_NAME") + "." + columns.getString ("COLUMN_NAME")); } progress (index, index); } finally { columns.close (); } info (loc ("done")); return (String [])names.toArray (new String [0]); } catch (Throwable t) { handleException (t); return new String [0]; } } //////////////////// // String utilities //////////////////// /** * Split the line into an array by tokenizing on space characters * * @param line the line to break up * @return an array of individual words */ String [] split (String line) { return split (line, " "); } String dequote (String str) { if (str == null) return null; while ((str.startsWith ("'") && str.endsWith ("'")) || (str.startsWith ("\"") && str.endsWith ("\""))) str = str.substring (1, str.length () - 1); return str; } String [] split (String line, String delim) { StringTokenizer tok = new StringTokenizer (line, delim); String [] ret = new String [tok.countTokens ()]; int index = 0; while (tok.hasMoreTokens ()) { String t = tok.nextToken (); t = dequote (t); ret [index++] = t; } return ret; } static Map map (Object [] obs) { Map m = new HashMap (); for (int i = 0; i < obs.length - 1; i+=2) m.put (obs [i], obs [i + 1]); return Collections.unmodifiableMap (m); } static boolean getMoreResults (Statement stmnt) { try { return stmnt.getMoreResults (); } catch (Throwable t) { return false; } } static String xmlattrencode (String str) { str = replace (str, "\"", """); str = replace (str, "<", "<"); return str; } static String replace (String source, String from, String to) { if (source == null) return null; if (from.equals (to)) return source; StringBuffer replaced = new StringBuffer (); int index = -1; while ((index = source.indexOf (from)) != -1) { replaced.append (source.substring (0, index)); replaced.append (to); source = source.substring (index + from.length ()); } replaced.append (source); return replaced.toString (); } /** * Split the line based on spaces, asserting that the * number of words is correct. * * @param line the line to split * @param assertLen the number of words to assure * @param usage the message to output if there are an incorrect * number of words. * @return the split lines, or null if the assertion failed. */ String [] split (String line, int assertLen, String usage) { String [] ret = split (line); if (ret.length != assertLen) { error (usage); return null; } return ret; } /** * Wrap the specified string by breaking on space characters. * * @param toWrap the string to wrap * @param len the maximum length of any line * @param start the number of spaces to pad at the * beginning of a line * @return the wrapped string */ String wrap (String toWrap, int len, int start) { String cur = toWrap; StringBuffer buff = new StringBuffer (); StringBuffer line = new StringBuffer (); char [] head = new char [start]; Arrays.fill (head, ' '); for (StringTokenizer tok = new StringTokenizer (toWrap, " "); tok.hasMoreTokens (); ) { String next = tok.nextToken (); if (line.length () + next.length () > len) { buff.append (line).append (sep).append (head); line.setLength (0); } line.append (line.length () == 0 ? "" : " ").append (next); } buff.append (line); return buff.toString (); } /** * Output a progress indicator to the console. * * @param cur the current progress * @param max the maximum progress, or -1 if unknown */ void progress (int cur, int max) { StringBuffer out = new StringBuffer (); if (lastProgress != null) { char [] back = new char [lastProgress.length ()]; Arrays.fill (back, '\b'); out.append (back); } String progress = cur + "/" + (max == -1 ? "?" : "" + max) + " " + (max == -1 ? "(??%)" : ("(" + (cur * 100 / (max == 0 ? 1 : max)) + "%)"));; if (cur >= max && max != -1) { progress += " " + loc ("done") + sep; lastProgress = null; } else { lastProgress = progress; } out.append (progress); System.out.print (out.toString ()); System.out.flush (); } /////////////////////////////// // Exception handling routines /////////////////////////////// void handleException (Throwable e) { while (e instanceof InvocationTargetException) { e = ((InvocationTargetException)e).getTargetException (); } if (e instanceof SQLException) { handleSQLException ((SQLException)e); } else if (!(opts.getVerbose ())) { if (e.getMessage () == null) error (e.getClass ().getName ()); else error (e.getMessage ()); } else { e.printStackTrace (System.err); } } void handleSQLException (SQLException e) { if (e instanceof SQLWarning && !(opts.getShowWarnings ())) return; String type = e instanceof SQLWarning ? loc ("Warning") : loc ("Error"); error (loc (e instanceof SQLWarning ? "Warning" : "Error", new Object [] { e.getMessage () == null ? "" : e.getMessage ().trim (), e.getSQLState () == null ? "" : e.getSQLState ().trim (), new Integer (e.getErrorCode ()) })); if (opts.getVerbose ()) e.printStackTrace (); for (SQLException nested = e.getNextException (); nested != null && nested != e; nested = nested.getNextException ()) handleSQLException (nested); } private boolean scanForDriver (String url) { try { // already registered if (findRegisteredDriver (url) != null) return true; // first try known drivers... scanDrivers (true); if (findRegisteredDriver (url) != null) return true; // now really scan... scanDrivers (false); if (findRegisteredDriver (url) != null) return true; return false; } catch (Exception e) { debug (e.toString ()); return false; } } private Driver findRegisteredDriver (String url) { for (Enumeration drivers = DriverManager.getDrivers (); drivers != null && drivers.hasMoreElements (); ) { Driver driver = (Driver)drivers.nextElement (); try { if (driver.acceptsURL (url)) return driver; } catch (Exception e) { } } return null; } Driver [] scanDrivers (String line) throws IOException { return scanDrivers (false); } Driver [] scanDrivers (boolean knownOnly) throws IOException { long start = System.currentTimeMillis (); Set classNames = new HashSet (); if (!knownOnly) classNames.addAll (Arrays.asList ( ClassNameCompletor.getClassNames ())); classNames.addAll (KNOWN_DRIVERS); Set driverClasses = new HashSet (); for (Iterator i = classNames.iterator (); i.hasNext (); ) { String className = i.next ().toString (); if (className.toLowerCase ().indexOf ("driver") == -1) continue; try { Class c = Class.forName (className, false, Thread.currentThread ().getContextClassLoader ()); if (!Driver.class.isAssignableFrom (c)) continue; if (Modifier.isAbstract (c.getModifiers ())) continue; // now instantiate and initialize it driverClasses.add (c.newInstance ()); } catch (Throwable t) { } } info ("scan complete in " + (System.currentTimeMillis () - start) + "ms"); return (Driver [])driverClasses.toArray (new Driver [0]); } Driver [] scanDriversOLD (String line) { long start = System.currentTimeMillis (); Set paths = new HashSet (); Set driverClasses = new HashSet (); for (StringTokenizer tok = new StringTokenizer ( System.getProperty ("java.ext.dirs"), System.getProperty ("path.separator")); tok.hasMoreTokens (); ) { File [] files = new File (tok.nextToken ()).listFiles (); for (int i = 0; files != null && i < files.length; i++) paths.add (files [i].getAbsolutePath ()); } for (StringTokenizer tok = new StringTokenizer ( System.getProperty ("java.class.path"), System.getProperty ("path.separator")); tok.hasMoreTokens (); ) { paths.add (new File (tok.nextToken ()).getAbsolutePath ()); } for (Iterator i = paths.iterator (); i.hasNext (); ) { File f = new File ((String)i.next ()); output (color ().pad (loc ("scanning", f.getAbsolutePath ()), 60), false); try { ZipFile zf = new ZipFile (f); int total = zf.size (); int index = 0; for (Enumeration enum = zf.entries (); enum.hasMoreElements (); ) { ZipEntry entry = (ZipEntry)enum.nextElement (); String name = entry.getName (); progress (index++, total); if (name.endsWith (".class")) { name = name.replace ('/', '.'); name = name.substring (0, name.length () - 6); try { // check for the string "driver" in the class // to see if we should load it. Not perfect, but // it is far too slow otherwise. if (name.toLowerCase ().indexOf ("driver") != -1) { Class c = Class.forName (name, false, getClass ().getClassLoader ()); if (Driver.class.isAssignableFrom (c) && !(Modifier.isAbstract ( c.getModifiers ()))) { try { // load and initialize Class.forName (name); } catch (Exception e) { } driverClasses.add (c.newInstance ()); } } } catch (Throwable t) { } } } progress (total, total); } catch (Exception e) { } } info ("scan complete in " + (System.currentTimeMillis () - start) + "ms"); return (Driver [])driverClasses.toArray (new Driver [0]); } /////////////////////////////////////// // ResultSet output formatting classes /////////////////////////////////////// int print (ResultSet rs) throws SQLException { String format = opts.getOutputFormat (); OutputFormat f = (OutputFormat)formats.get (format); if (f == null) { error (loc ("unknown-format", new Object [] { format, formats.keySet () })); f = new TableOutputFormat (); } Rows rows; if (opts.getIncremental ()) rows = new IncrementalRows (rs); else rows = new BufferedRows (rs); return f.print (rows); } interface OutputFormat { int print (SqlLine.Rows rows); } /** * Abstract OutputFormat. * * @author Marc Prud'hommeaux */ abstract class AbstractOutputFormat implements OutputFormat { public int print (Rows rows) { int count = 0; Rows.Row header = (Rows.Row)rows.next (); printHeader (header); while (rows.hasNext ()) { printRow (rows, header, (Rows.Row)rows.next ()); count++; } printFooter (header); return count; } abstract void printHeader (Rows.Row header); abstract void printFooter (Rows.Row header); abstract void printRow (Rows rows, Rows.Row header, Rows.Row row); } class XMLAttributeOutputFormat extends AbstractOutputFormat { public void printHeader (Rows.Row header) { output (""); } public void printFooter (Rows.Row header) { output (""); } public void printRow (Rows rows, Rows.Row header, Rows.Row row) { String [] head = header.values; String [] vals = row.values; StringBuffer result = new StringBuffer (" "); output (result.toString ()); } } class XMLElementOutputFormat extends AbstractOutputFormat { public void printHeader (Rows.Row header) { output (""); } public void printFooter (Rows.Row header) { output (""); } public void printRow (Rows rows, Rows.Row header, Rows.Row row) { String [] head = header.values; String [] vals = row.values; output (" "); for (int i = 0; i < head.length && i < vals.length; i++) { output (" <" + head [i] + ">" + (xmlattrencode (vals [i])) + ""); } output (" "); } } /** * OutputFormat for vertical column name: value format. * * @author Marc Prud'hommeaux */ class VerticalOutputFormat implements OutputFormat { public int print (Rows rows) { int count = 0; Rows.Row header = (Rows.Row)rows.next (); while (rows.hasNext ()) { printRow (rows, header, (Rows.Row)rows.next ()); count++; } return count; } public void printRow (Rows rows, Rows.Row header, Rows.Row row) { String [] head = header.values; String [] vals = row.values; int headwidth = 0; for (int i = 0; i < head.length && i < vals.length; i++) headwidth = Math.max (headwidth, head [i].length ()); headwidth += 2; for (int i = 0; i < head.length && i < vals.length; i++) output (color ().bold ( color ().pad (head [i], headwidth).getMono ()) .append (vals [i] == null ? "" : vals [i])); output (""); // spacing } } /** * OutputFormat for values separated by a delimiter. * * TODO: Handle character escaping * * @author Marc Prud'hommeaux */ class SeparatedValuesOutputFormat implements OutputFormat { private char separator; public SeparatedValuesOutputFormat (char separator) { setSeparator (separator); } public int print (Rows rows) { int count = 0; while (rows.hasNext ()) { printRow (rows, (Rows.Row)rows.next ()); count++; } return count - 1; // sans header row } public void printRow (Rows rows, Rows.Row row) { String [] vals = row.values; StringBuffer buf = new StringBuffer (); for (int i = 0; i < vals.length; i++) buf.append (buf.length () == 0 ? "" : "" + getSeparator ()) .append ('\'') .append (vals [i] == null ? "" : vals [i]) .append ('\''); output (buf.toString ()); } public void setSeparator (char separator) { this.separator = separator; } public char getSeparator () { return this.separator; } } /** * OutputFormat for a pretty, table-like format. * * @author Marc Prud'hommeaux */ class TableOutputFormat implements OutputFormat { public int print (Rows rows) { int index = 0; ColorBuffer header = null; ColorBuffer headerCols = null; final int width = opts.getMaxWidth () - 4; // normalize the columns sizes rows.normalizeWidths (); for (; rows.hasNext (); ) { Rows.Row row = (Rows.Row)rows.next (); ColorBuffer cbuf = getOutputString (rows, row); cbuf = cbuf.truncate (width); if (index == 0) { StringBuffer h = new StringBuffer (); for (int j = 0; j < row.sizes.length; j++) { for (int k = 0; k < row.sizes [j]; k++) h.append ('-'); h.append ("-+-"); } headerCols = cbuf; header = color ().green (h.toString ()).truncate ( headerCols.getVisibleLength ()); } if (index == 0 || (opts.getHeaderInterval () > 0 && index % opts.getHeaderInterval () == 0 && opts.getShowHeader ())) { printRow (header, true); printRow (headerCols, false); printRow (header, true); } if (index != 0) // don't output the header twice printRow (cbuf, false); index++; } if (header != null && opts.getShowHeader ()) printRow (header, true); return index - 1; } void printRow (ColorBuffer cbuff, boolean header) { if (header) output (color ().green ("+-").append (cbuff).green ("-+")); else output (color ().green ("| ").append (cbuff).green (" |")); } public ColorBuffer getOutputString (Rows rows, Rows.Row row) { return getOutputString (rows, row, " | "); } ColorBuffer getOutputString (Rows rows, Rows.Row row, String delim) { ColorBuffer buf = color (); for (int i = 0; i < row.values.length; i++) { if (buf.getVisibleLength () > 0) buf.green (delim); ColorBuffer v; if (row.isMeta) { v = color ().center (row.values [i], row.sizes [i]); if (rows.isPrimaryKey (i)) buf.cyan (v.getMono ()); else buf.bold (v.getMono ()); } else { v = color ().pad (row.values [i], row.sizes [i]); if (rows.isPrimaryKey (i)) buf.cyan (v.getMono ()); else buf.append (v.getMono ()); } } if (row.deleted) // make deleted rows red buf = color ().red (buf.getMono ()); else if (row.updated) // make updated rows blue buf = color ().blue (buf.getMono ()); else if (row.inserted) // make new rows green buf = color ().green (buf.getMono ()); return buf; } } private Statement createStatement () throws SQLException { Statement stmnt = con ().connection.createStatement (); if (opts.timeout > -1) stmnt.setQueryTimeout (opts.timeout); return stmnt; } void runBatch (List statements) { try { Statement stmnt = createStatement (); try { for (Iterator i = statements.iterator (); i.hasNext (); ) stmnt.addBatch (i.next ().toString ()); int [] counts = stmnt.executeBatch (); output (color ().pad (color ().bold ("COUNT"), 8) .append (color ().bold ("STATEMENT"))); for (int i = 0; counts != null && i < counts.length; i++) output (color ().pad (counts [i] + "", 8) .append (statements.get (i).toString ())); } finally { try { stmnt.close (); } catch (Exception e) { } } } catch (Exception e) { handleException (e); } } public int runCommands (List cmds) { int successCount = 0; try { int index = 1; int size = cmds.size (); for (Iterator i = cmds.iterator (); i.hasNext (); ) { String cmd = i.next ().toString (); info (color ().pad ((index++) + "/" + (size), 13).append (cmd)); boolean success = dispatch (cmd); // if we do not force script execution, abort // when a failure occurs. if (!success && !opts.getForce ()) { error (loc ("abort-on-error", cmd)); return successCount; } successCount += success == true ? 1 : 0; } } catch (Exception e) { handleException (e); } return successCount; } /** * Abstract base class representing a set of rows to be displayed. */ abstract class Rows implements Iterator { final ResultSetMetaData rsMeta; final Boolean [] primaryKeys; Rows (ResultSet rs) throws SQLException { rsMeta = rs.getMetaData (); int count = rsMeta.getColumnCount (); primaryKeys = new Boolean [count]; } public void remove () { throw new UnsupportedOperationException (); } /** * Update all of the rows to have the same size, set to the * maximum length of each column in the Rows. */ abstract void normalizeWidths (); /** * Return whether the specified column (0-based index) is * a primary key. Since this method depends on whether the * JDBC driver property implements * {@link ResultSetMetaData#getTableName} (many do not), it * is not reliable for all databases. */ boolean isPrimaryKey (int col) { if (primaryKeys [col] != null) return primaryKeys [col].booleanValue (); try { // this doesn't always work, since some JDBC drivers (e.g., // Oracle's) return a blank string from getTableName. String table = rsMeta.getTableName (col + 1); String column = rsMeta.getColumnName (col + 1); if (table == null || table.length () == 0 || column == null || column.length () == 0) { return (primaryKeys [col] = new Boolean (false)) .booleanValue (); } ResultSet pks = con ().meta.getPrimaryKeys ( con ().meta.getConnection ().getCatalog (), null, table); try { while (pks.next ()) { if (column.equalsIgnoreCase ( pks.getString ("COLUMN_NAME"))) return (primaryKeys [col] = new Boolean (true)) .booleanValue (); } } finally { pks.close (); } return (primaryKeys [col] = new Boolean (false)) .booleanValue (); } catch (SQLException sqle) { return (primaryKeys [col] = new Boolean (false)) .booleanValue (); } } class Row { final String [] values; final boolean isMeta; private boolean deleted; private boolean inserted; private boolean updated; private int [] sizes; Row (int size) throws SQLException { isMeta = true; values = new String [size]; sizes = new int [size]; for (int i = 0; i < size; i++) { values [i] = rsMeta.getColumnLabel (i + 1); sizes [i] = values [i] == null ? 1 : values [i].length (); } deleted = false; updated = false; inserted = false; } Row (int size, ResultSet rs) throws SQLException { isMeta = false; values = new String [size]; sizes = new int [size]; try { deleted = rs.rowDeleted (); } catch (Throwable t) { } try { updated = rs.rowUpdated (); } catch (Throwable t) { } try { inserted = rs.rowInserted (); } catch (Throwable t) { } for (int i = 0; i < size; i++) { values [i] = rs.getString (i + 1); sizes [i] = values [i] == null ? 1 : values [i].length (); } } } } /** * Rows implementation which buffers all rows in a linked list. */ class BufferedRows extends Rows { private final LinkedList list; private final Iterator iterator; BufferedRows (ResultSet rs) throws SQLException { super (rs); list = new LinkedList (); int count = rsMeta.getColumnCount (); list.add (new Row (count)); while (rs.next ()) list.add (new Row (count, rs)); iterator = list.iterator (); } public boolean hasNext () { return iterator.hasNext (); } public Object next () { return iterator.next (); } void normalizeWidths () { int [] max = null; for (int i = 0; i < list.size (); i++) { Row row = (Row)list.get (i); if (max == null) max = new int [row.values.length]; for (int j = 0; j < max.length; j++) { max [j] = Math.max (max [j], row.sizes [j] + 1); } } for (int i = 0; i < list.size (); i++) { Row row = (Row)list.get (i); row.sizes = max; } } } /** * Rows implementation which returns rows incrementally from result set * without any buffering. */ class IncrementalRows extends Rows { private final ResultSet rs; private Row labelRow; private Row maxRow; private Row nextRow; private boolean endOfResult; private boolean normalizingWidths; IncrementalRows (ResultSet rs) throws SQLException { super (rs); this.rs = rs; labelRow = new Row (rsMeta.getColumnCount ()); maxRow = new Row (rsMeta.getColumnCount ()); // pre-compute normalization so we don't have to deal // with SQLExceptions later for (int i = 0; i < maxRow.sizes.length; ++i) { // normalized display width is based on maximum of display size // and label size maxRow.sizes [i] = Math.max( maxRow.sizes [i], rsMeta.getColumnDisplaySize (i + 1)); } nextRow = labelRow; endOfResult = false; } public boolean hasNext () { if (endOfResult) { return false; } if (nextRow == null) { try { if (rs.next ()) { nextRow = new Row (labelRow.sizes.length, rs); if (normalizingWidths) { // perform incremental normalization nextRow.sizes = labelRow.sizes; } } else { endOfResult = true; } } catch (SQLException ex) { throw new RuntimeException (ex.toString ()); } } return (nextRow != null); } public Object next () { if (!hasNext ()) { throw new NoSuchElementException (); } Object ret = nextRow; try { if (rs.next ()) { nextRow = new Row (labelRow.sizes.length, rs); if (normalizingWidths) { // perform incremental normalization nextRow.sizes = labelRow.sizes; } } else { nextRow = null; } return ret; } catch (SQLException e) { throw new NoSuchElementException (e.toString ()); } } void normalizeWidths () { // normalize label row labelRow.sizes = maxRow.sizes; // and remind ourselves to perform incremental normalization // for each row as it is produced normalizingWidths = true; } } /////////////////////////////// // Console interaction classes /////////////////////////////// /** * A buffer that can output segments using ANSI color. * * @author Marc Prud'hommeaux */ final static class ColorBuffer implements Comparable { private static final ColorAttr BOLD = new ColorAttr ("\033[1m"); private static final ColorAttr NORMAL = new ColorAttr ("\033[m"); private static final ColorAttr REVERS = new ColorAttr ("\033[7m"); private static final ColorAttr LINED = new ColorAttr ("\033[4m"); private static final ColorAttr GREY = new ColorAttr ("\033[1;30m"); private static final ColorAttr RED = new ColorAttr ("\033[1;31m"); private static final ColorAttr GREEN = new ColorAttr ("\033[1;32m"); private static final ColorAttr BLUE = new ColorAttr ("\033[1;34m"); private static final ColorAttr CYAN = new ColorAttr ("\033[1;36m"); private static final ColorAttr YELLOW = new ColorAttr ("\033[1;33m"); private static final ColorAttr MAGENTA = new ColorAttr ("\033[1;35m"); private static final ColorAttr INVISIBLE = new ColorAttr ("\033[8m"); private final List parts = new LinkedList (); private final boolean useColor; public ColorBuffer (boolean useColor) { this.useColor = useColor; append (""); } public ColorBuffer (String str, boolean useColor) { this.useColor = useColor; append (str); } /** * Pad the specified String with spaces to the indicated length * * @param str the String to pad * @param len the length we want the return String to be * @return the passed in String with spaces appended until the * length matches the specified length. */ ColorBuffer pad (ColorBuffer str, int len) { while (str.getVisibleLength () < len) str.append (" "); return append (str); } ColorBuffer center (String str, int len) { StringBuffer buf = new StringBuffer (str); while (buf.length () < len) { buf.append (" "); if (buf.length () < len) buf.insert (0, " "); } return append (buf.toString ()); } ColorBuffer pad (String str, int len) { if (str == null) str = ""; return pad (new ColorBuffer (str, false), len); } public String getColor () { return getBuffer (useColor); } public String getMono () { return getBuffer (false); } String getBuffer (boolean color) { StringBuffer buf = new StringBuffer (); for (Iterator i = parts.iterator (); i.hasNext (); ) { Object next = i.next (); if (!color && next instanceof ColorAttr) continue; buf.append (next.toString ()); } return buf.toString (); } /** * Truncate the ColorBuffer to the specified length and return * the new ColorBuffer. Any open color tags will be closed. */ public ColorBuffer truncate (int len) { ColorBuffer cbuff = new ColorBuffer (useColor); ColorAttr lastAttr = null; for (Iterator i = parts.iterator (); cbuff.getVisibleLength () < len && i.hasNext (); ) { Object next = i.next (); if (next instanceof ColorAttr) { lastAttr = (ColorAttr)next; cbuff.append ((ColorAttr)next); continue; } String val = next.toString (); if (cbuff.getVisibleLength () + val.length () > len) { int partLen = len - cbuff.getVisibleLength (); val = val.substring (0, partLen); } cbuff.append (val); } // close off the buffer with a normal tag if (lastAttr != null && lastAttr != NORMAL) { cbuff.append (NORMAL); } return cbuff; } public String toString () { return getColor (); } public ColorBuffer append (String str) { parts.add (str); return this; } public ColorBuffer append (ColorBuffer buf) { parts.addAll (buf.parts); return this; } public ColorBuffer append (ColorAttr attr) { parts.add (attr); return this; } public int getVisibleLength () { return getMono ().length (); } public ColorBuffer append (ColorAttr attr, String val) { parts.add (attr); parts.add (val); parts.add (NORMAL); return this; } public ColorBuffer bold (String str) { return append (BOLD, str); } public ColorBuffer lined (String str) { return append (LINED, str); } public ColorBuffer grey (String str) { return append (GREY, str); } public ColorBuffer red (String str) { return append (RED, str); } public ColorBuffer blue (String str) { return append (BLUE, str); } public ColorBuffer green (String str) { return append (GREEN, str); } public ColorBuffer cyan (String str) { return append (CYAN, str); } public ColorBuffer yellow (String str) { return append (YELLOW, str); } public ColorBuffer magenta (String str) { return append (MAGENTA, str); } private static class ColorAttr { private final String attr; public ColorAttr (String attr) { this.attr = attr; } public String toString () { return attr; } } public int compareTo (Object other) { return getMono ().compareTo (((ColorBuffer)other).getMono ()); } } //////////////////////////// // Command handling classes //////////////////////////// /** * A generic command to be executed. Execution of the command * should be dispatched to the {@link #execute(java.lang.String)} * method after determining that the command is appropriate with * the {@link #matches(java.lang.String)} method. * * @author Marc Prud'hommeaux */ interface CommandHandler { /** * @return the name of the command */ public String getName (); /** * @return all the possible names of this command. */ public String [] getNames (); /** * @return the short help description for this command. */ public String getHelpText (); /** * Check to see if the specified string can be dispatched to this * command. * * @param line the command line to check. * @return the command string that matches, or null if it no match */ public String matches (String line); /** * Execute the specified command. * * @param line the full command line to execute. */ public boolean execute (String line); /** * Returns the completors that can handle parameters. */ public Completor [] getParameterCompletors (); } /** * An abstract implementation of CommandHandler. * * @author Marc Prud'hommeaux */ public abstract class AbstractCommandHandler implements CommandHandler { private final String name; private final String [] names; private final String helpText; private Completor [] parameterCompletors = new Completor [0]; public AbstractCommandHandler (String [] names, String helpText, Completor [] completors) { this.name = names [0]; this.names = names; this.helpText = helpText; if (completors == null || completors.length == 0) { this.parameterCompletors = new Completor [] { new NullCompletor () }; } else { List c = new LinkedList (Arrays.asList (completors)); c.add (new NullCompletor ()); this.parameterCompletors = (Completor [])c.toArray (new Completor [0]); } } public String getHelpText () { return helpText; } public String getName () { return this.name; } public String [] getNames () { return this.names; } public String matches (String line) { if (line == null || line.length () == 0) return null; String [] parts = split (line); if (parts == null || parts.length == 0) return null; for (int i = 0; i < names.length; i++) { if (names [i].startsWith (parts [0])) return names [i]; } return null; } public void setParameterCompletors (Completor [] parameterCompletors) { this.parameterCompletors = parameterCompletors; } public Completor [] getParameterCompletors () { return this.parameterCompletors; } } /** * A {@link Command} implementation that uses reflection to * determine the method to dispatch the command. * * @author Marc Prud'hommeaux */ public class ReflectiveCommandHandler extends AbstractCommandHandler { public ReflectiveCommandHandler (String [] cmds, Completor [] completor) { super (cmds, loc ("help-" + cmds [0]), completor); } public boolean execute (String line) { try { Object ob = command.getClass ().getMethod (getName (), new Class [] { String.class }) .invoke (command, new Object [] { line }); return ob != null && ob instanceof Boolean && ((Boolean)ob).booleanValue (); } catch (Throwable e) { return error (e); } } } ////////////////////////// // Command methods follow ////////////////////////// public class Commands { public boolean metadata (String line) { debug (line); String [] parts = split (line); List params = new LinkedList (Arrays.asList (parts)); if (parts == null || parts.length == 0) return dbinfo (""); params.remove (0); params.remove (0); debug (params.toString ()); return metadata (parts [1], (String [])params.toArray (new String [0])); } public boolean metadata (String cmd, String [] args) { try { Method [] m = con ().meta.getClass ().getMethods (); Set methodNames = new TreeSet (); Set methodNamesUpper = new TreeSet (); for (int i = 0; i < m.length; i++) { methodNames.add (m [i].getName ()); methodNamesUpper.add (m [i].getName ().toUpperCase ()); } if (!methodNamesUpper.contains (cmd.toUpperCase ())) { error (loc ("no-such-method", cmd)); error (loc ("possible-methods")); for (Iterator i = methodNames.iterator (); i.hasNext (); ) error (" " + i.next ()); return false; } Object res = Reflector.invoke (con ().meta, DatabaseMetaData.class, cmd, Arrays.asList (args)); if (res instanceof ResultSet) { ResultSet rs = (ResultSet)res; if (rs != null) { try { print (rs); } finally { rs.close (); } } } else if (res != null) { output (res.toString ()); } } catch (Exception e) { return error (e); } return true; } public boolean history (String line) { List hist = reader.getHistory ().getHistoryList (); int index = 1; for (Iterator i = hist.iterator (); i.hasNext (); index++) { output (color ().pad (index + ".", 6) .append (i.next ().toString ())); } return true; } String arg1 (String line, String paramname) { return arg1 (line, paramname, null); } String arg1 (String line, String paramname, String def) { String [] ret = split (line); if (ret == null || ret.length != 2) { if (def != null) return def; throw new IllegalArgumentException (loc ("arg-usage", new Object [] { ret.length == 0 ? "" : ret [0], paramname })); } return ret [1]; } public boolean indexes (String line) throws Exception { return metadata ("getIndexInfo", new String [] { conn ().getCatalog (), null, arg1 (line, "table name"), false + "", true + "" }); } public boolean primarykeys (String line) throws Exception { return metadata ("getPrimaryKeys", new String [] { conn ().getCatalog (), null, arg1 (line, "table name"), }); } public boolean exportedkeys (String line) throws Exception { return metadata ("getExportedKeys", new String [] { conn ().getCatalog (), null, arg1 (line, "table name"), }); } public boolean importedkeys (String line) throws Exception { return metadata ("getImportedKeys", new String [] { conn ().getCatalog (), null, arg1 (line, "table name"), }); } public boolean procedures (String line) throws Exception { return metadata ("getProcedures", new String [] { conn ().getCatalog (), null, arg1 (line, "procedure name pattern", "%"), }); } public boolean tables (String line) throws Exception { return metadata ("getTables", new String [] { conn ().getCatalog (), null, arg1 (line, "table name", "%"), null }); } public boolean typeinfo (String line) throws Exception { return metadata ("getTypeInfo", new String[0]); } public boolean nativesql (String sql) throws Exception { if (sql.startsWith (COMMAND_PREFIX)) sql = sql.substring (1); if (sql.startsWith ("native")) sql = sql.substring ("native".length () + 1); String nat = con ().getConnection ().nativeSQL (sql); output (nat); return true; } public boolean columns (String line) throws Exception { return metadata ("getColumns", new String [] { conn ().getCatalog (), null, arg1 (line, "table name"), "%" }); } public boolean dropall (String line) { if (con () == null || con ().url == null) return error (loc ("no-current-connection")); try { if (!(reader.readLine (loc ("really-drop-all")).equals ("y"))) return error ("abort-drop-all"); List cmds = new LinkedList (); ResultSet rs = getTables (); try { while (rs.next ()) cmds.add ("DROP TABLE " + rs.getString ("TABLE_NAME") + ";"); } finally { try { rs.close (); } catch (Exception e) { } } // run as a batch return runCommands (cmds) == cmds.size (); } catch (Exception e) { return error (e); } } public boolean reconnect (String line) { if (con () == null || con ().url == null) return error (loc ("no-current-connection")); info (loc ("reconnecting", con ().url)); try { con ().reconnect (); } catch (Exception e) { return error (e); } return true; } public boolean scan (String line) throws IOException { TreeSet names = new TreeSet (); if (drivers == null) drivers = Arrays.asList (scanDrivers (line)); info (loc ("drivers-found-count", drivers.size ())); // unique the list for (Iterator i = drivers.iterator (); i.hasNext (); ) names.add (((Driver)i.next ()).getClass ().getName ()); output (color () .bold (color ().pad (loc ("compliant"), 10).getMono ()) .bold (color ().pad (loc ("jdbc-version"), 8).getMono ()) .bold (color (loc ("driver-class")).getMono ())); for (Iterator i = names.iterator (); i.hasNext (); ) { String name = i.next ().toString (); try { Driver driver = (Driver)Class.forName (name).newInstance (); ColorBuffer msg = color () .pad (driver.jdbcCompliant () ? "yes" : "no", 10) .pad (driver.getMajorVersion () + "." + driver.getMinorVersion (), 8) .append (name); if (driver.jdbcCompliant ()) output (msg); else output (color ().red (msg.getMono ())); } catch (Throwable t) { output (color ().red (name)); // error with driver } } return true; } public boolean save (String line) throws IOException { info (loc ("saving-options", opts.rcFile)); opts.save (); return true; } public boolean load (String line) throws IOException { opts.load (); info (loc ("loaded-options", opts.rcFile)); return true; } public boolean config (String line) { try { Properties props = opts.toProperties (); Set keys = new TreeSet (props.keySet ()); for (Iterator i = keys.iterator (); i.hasNext (); ) { String key = (String)i.next (); output (color () .green (color ().pad (key.substring ( opts.PROPERTY_PREFIX.length ()), 20) .getMono ()) .append (props.getProperty (key))); } } catch (Exception e) { return error (e); } return true; } public boolean set (String line) { if (line == null || line.trim ().equals ("set") || line.length () == 0) { return config (null); } String [] parts = split (line, 3, "Usage: set "); if (parts == null) return false; String key = parts [1]; String value = parts [2]; boolean success = opts.set (key, value, false); // if we autosave, then save if (success && opts.getAutosave ()) { try { opts.save (); } catch (Exception saveException) { } } return success; } public boolean commit (String line) throws SQLException { if (!(assertConnection ())) return false; if (!(assertAutoCommit ())) return false; try { long start = System.currentTimeMillis (); con ().connection.commit (); long end = System.currentTimeMillis (); showWarnings (); info (loc ("commit-complete") + " " + loc ("time-ms", new Object [] { new Double ((end - start) / 1000d) })); return true; } catch (Exception e) { return error (e); } } public boolean rollback (String line) throws SQLException { if (!(assertConnection ())) return false; if (!(assertAutoCommit ())) return false; try { long start = System.currentTimeMillis (); con ().connection.rollback (); long end = System.currentTimeMillis (); showWarnings (); info (loc ("rollback-complete") + " " + loc ("time-ms", new Object [] { new Double ((end - start) / 1000d) })); return true; } catch (Exception e) { return error (e); } } public boolean autocommit (String line) throws SQLException { if (!(assertConnection ())) return false; if (line.endsWith ("on")) con ().connection.setAutoCommit (true); else if (line.endsWith ("off")) con ().connection.setAutoCommit (false); showWarnings (); autocommitStatus (con ().connection); return true; } public boolean dbinfo (String line) { if (!(assertConnection ())) return false; showWarnings (); int padlen = 50; String [] m = new String [] { "allProceduresAreCallable", "allTablesAreSelectable", "dataDefinitionCausesTransactionCommit", "dataDefinitionIgnoredInTransactions", "doesMaxRowSizeIncludeBlobs", "getCatalogSeparator", "getCatalogTerm", "getDatabaseProductName", "getDatabaseProductVersion", "getDefaultTransactionIsolation", "getDriverMajorVersion", "getDriverMinorVersion", "getDriverName", "getDriverVersion", "getExtraNameCharacters", "getIdentifierQuoteString", "getMaxBinaryLiteralLength", "getMaxCatalogNameLength", "getMaxCharLiteralLength", "getMaxColumnNameLength", "getMaxColumnsInGroupBy", "getMaxColumnsInIndex", "getMaxColumnsInOrderBy", "getMaxColumnsInSelect", "getMaxColumnsInTable", "getMaxConnections", "getMaxCursorNameLength", "getMaxIndexLength", "getMaxProcedureNameLength", "getMaxRowSize", "getMaxSchemaNameLength", "getMaxStatementLength", "getMaxStatements", "getMaxTableNameLength", "getMaxTablesInSelect", "getMaxUserNameLength", "getNumericFunctions", "getProcedureTerm", "getSchemaTerm", "getSearchStringEscape", "getSQLKeywords", "getStringFunctions", "getSystemFunctions", "getTimeDateFunctions", "getURL", "getUserName", "isCatalogAtStart", "isReadOnly", "nullPlusNonNullIsNull", "nullsAreSortedAtEnd", "nullsAreSortedAtStart", "nullsAreSortedHigh", "nullsAreSortedLow", "storesLowerCaseIdentifiers", "storesLowerCaseQuotedIdentifiers", "storesMixedCaseIdentifiers", "storesMixedCaseQuotedIdentifiers", "storesUpperCaseIdentifiers", "storesUpperCaseQuotedIdentifiers", "supportsAlterTableWithAddColumn", "supportsAlterTableWithDropColumn", "supportsANSI92EntryLevelSQL", "supportsANSI92FullSQL", "supportsANSI92IntermediateSQL", "supportsBatchUpdates", "supportsCatalogsInDataManipulation", "supportsCatalogsInIndexDefinitions", "supportsCatalogsInPrivilegeDefinitions", "supportsCatalogsInProcedureCalls", "supportsCatalogsInTableDefinitions", "supportsColumnAliasing", "supportsConvert", "supportsCoreSQLGrammar", "supportsCorrelatedSubqueries", "supportsDataDefinitionAndDataManipulationTransactions", "supportsDataManipulationTransactionsOnly", "supportsDifferentTableCorrelationNames", "supportsExpressionsInOrderBy", "supportsExtendedSQLGrammar", "supportsFullOuterJoins", "supportsGroupBy", "supportsGroupByBeyondSelect", "supportsGroupByUnrelated", "supportsIntegrityEnhancementFacility", "supportsLikeEscapeClause", "supportsLimitedOuterJoins", "supportsMinimumSQLGrammar", "supportsMixedCaseIdentifiers", "supportsMixedCaseQuotedIdentifiers", "supportsMultipleResultSets", "supportsMultipleTransactions", "supportsNonNullableColumns", "supportsOpenCursorsAcrossCommit", "supportsOpenCursorsAcrossRollback", "supportsOpenStatementsAcrossCommit", "supportsOpenStatementsAcrossRollback", "supportsOrderByUnrelated", "supportsOuterJoins", "supportsPositionedDelete", "supportsPositionedUpdate", "supportsSchemasInDataManipulation", "supportsSchemasInIndexDefinitions", "supportsSchemasInPrivilegeDefinitions", "supportsSchemasInProcedureCalls", "supportsSchemasInTableDefinitions", "supportsSelectForUpdate", "supportsStoredProcedures", "supportsSubqueriesInComparisons", "supportsSubqueriesInExists", "supportsSubqueriesInIns", "supportsSubqueriesInQuantifieds", "supportsTableCorrelationNames", "supportsTransactions", "supportsUnion", "supportsUnionAll", "usesLocalFilePerTable", "usesLocalFiles", }; for (int i = 0; i < m.length; i++) { try { output (color ().pad (m [i], padlen).append ( "" + Reflector.invoke (con ().meta, m [i], new Object [0]))); } catch (Exception e) { handleException (e); } } return true; } public boolean verbose (String line) { info ("verbose: on"); return set ("set verbose true"); } public boolean outputformat (String line) { return set ("set " + line); } public boolean brief (String line) { info ("verbose: off"); return set ("set verbose false"); } public boolean isolation (String line) throws SQLException { if (!(assertConnection ())) return false; int i; if (line.endsWith ("TRANSACTION_NONE")) i = Connection.TRANSACTION_NONE; else if (line.endsWith ("TRANSACTION_READ_COMMITTED")) i = Connection.TRANSACTION_READ_COMMITTED; else if (line.endsWith ("TRANSACTION_READ_UNCOMMITTED")) i = Connection.TRANSACTION_READ_UNCOMMITTED; else if (line.endsWith ("TRANSACTION_REPEATABLE_READ")) i = Connection.TRANSACTION_REPEATABLE_READ; else if (line.endsWith ("TRANSACTION_SERIALIZABLE")) i = Connection.TRANSACTION_SERIALIZABLE; else return error ("Usage: isolation "); con ().connection.setTransactionIsolation (i); int isol = con ().connection.getTransactionIsolation (); final String isoldesc; switch (i) { case Connection.TRANSACTION_NONE: isoldesc = "TRANSACTION_NONE"; break; case Connection.TRANSACTION_READ_COMMITTED: isoldesc = "TRANSACTION_READ_COMMITTED"; break; case Connection.TRANSACTION_READ_UNCOMMITTED: isoldesc = "TRANSACTION_READ_UNCOMMITTED"; break; case Connection.TRANSACTION_REPEATABLE_READ: isoldesc = "TRANSACTION_REPEATABLE_READ"; break; case Connection.TRANSACTION_SERIALIZABLE: isoldesc = "TRANSACTION_SERIALIZABLE"; break; default: isoldesc = "UNKNOWN"; } info (loc ("isolation-status", isoldesc)); return true; } public boolean batch (String line) { if (!(assertConnection ())) return false; if (batch == null) { batch = new LinkedList (); info (loc ("batch-start")); return true; } else { info (loc ("running-batch")); try { runBatch (batch); return true; } catch (Exception e) { return error (e); } finally { batch = null; } } } public boolean sql (String line) { return execute (line, false); } public boolean call (String line) { return execute (line, true); } private boolean execute (String line, boolean call) { if (line == null || line.length () == 0) return false; // ??? // ### FIXME: doing the multi-line handling down here means // higher-level logic never sees the extra lines. So, // for example, if a script is being saved, it won't include // the continuation lines! This is logged as sf.net // bug 879518. // use multiple lines for statements not terminated by ";" try { while (!(line.trim ().endsWith (";"))) { StringBuffer prompt = new StringBuffer (getPrompt ()); for (int i = 0; i < prompt.length () - 1; i++) { if (prompt.charAt (i) != '>') prompt.setCharAt (i, i % 2 == 0 ? '.' : ' '); } String extra = reader.readLine (prompt.toString ()); if (!isComment (extra)) { line += " " + extra; } } } catch (Exception e) { handleException (e); } if (line.endsWith (";")) line = line.substring (0, line.length () - 1); if (!(assertConnection ())) return false; String sql = line; if (sql.startsWith (COMMAND_PREFIX)) sql = sql.substring (1); String prefix = call ? "call" : "sql"; if (sql.startsWith (prefix)) sql = sql.substring (prefix.length ()); // batch statements? if (batch != null) { batch.add (sql); return true; } try { Statement stmnt = null; boolean hasResults; try { long start = System.currentTimeMillis (); if (call) { stmnt = con ().connection.prepareCall (sql); hasResults = ((CallableStatement)stmnt).execute (); } else { stmnt = createStatement (); hasResults = stmnt.execute (sql); } showWarnings (); if (hasResults) { do { ResultSet rs = stmnt.getResultSet (); try { int count = print (rs); long end = System.currentTimeMillis (); info (loc ("rows-selected", count) + " " + loc ("time-ms", new Object [] { new Double ((end - start) / 1000d) })); } finally { rs.close (); } } while (getMoreResults (stmnt)); } else { int count = stmnt.getUpdateCount (); long end = System.currentTimeMillis (); info (loc ("rows-affected", count) + " " + loc ("time-ms", new Object [] { new Double ((end - start) / 1000d) })); } } finally { if (stmnt != null) stmnt.close (); } } catch (Exception e) { return error (e); } showWarnings (); return true; } public boolean quit (String line) { exit = true; close (null); return true; } /** * Close all connections. */ public boolean closeall (String line) { if (close (null)) { while (close (null)); return true; } return false; } /** * Close the current connection. */ public boolean close (String line) { if (con () == null) return false; try { if (con ().connection != null && !(con ().connection.isClosed ())) { info (loc ("closing", con ().connection.getClass ().getName ())); con ().connection.close (); } else { info (loc ("already-closed")); } } catch (Exception e) { return error (e); } connections.remove (); return true; } /** * Connect to the database defined in the specified properties file. */ public boolean properties (String line) throws Exception { String example = ""; example += "Usage: properties " + sep; String [] parts = split (line); if (parts.length < 2) return error (example); int successes = 0; for (int i = 1; i < parts.length; i++) { Properties props = new Properties (); props.load (new FileInputStream (parts[i])); if (connect (props)) successes++; } if (successes != (parts.length - 1)) return false; else return true; } public boolean connect (String line) throws Exception { String example = ""; example += "Usage: connect [driver]" + sep; String [] parts = split (line); if (parts == null) return false; if (parts.length < 2) return error (example); /* if (parts.length == 2) { String cname = nameToDriverClass (parts [1]); if (cname != null) return connectByPrompt (cname); } */ String url = parts.length < 2 ? null : parts [1]; String user = parts.length < 3 ? null : parts [2]; String pass = parts.length < 4 ? null : parts [3]; String driver = parts.length < 5 ? null : parts [4]; Properties props = new Properties (); if (url != null) props.setProperty ("url", url); if (driver != null) props.setProperty ("driver", driver); if (user != null) props.setProperty ("user", user); if (pass != null) props.setProperty ("password", pass); return connect (props); } private String getProperty (Properties props, String[] keys) { for (int i = 0; i < keys.length; i++) { String val = props.getProperty (keys[i]); if (val != null) return val; } for (Iterator i = props.keySet ().iterator (); i.hasNext (); ) { String key = (String)i.next (); for (int j = 0; j < keys.length; j++) { if (key.endsWith (keys[j])) { return props.getProperty (key); } } } return null; } public boolean connect (Properties props) throws IOException { String url = getProperty (props, new String[] { "url", "javax.jdo.option.ConnectionURL", "ConnectionURL", }); String driver = getProperty (props, new String[] { "driver", "javax.jdo.option.ConnectionDriverName", "ConnectionDriverName", }); String username = getProperty (props, new String[] { "user", "javax.jdo.option.ConnectionUserName", "ConnectionUserName", }); String password = getProperty (props, new String[] { "password", "javax.jdo.option.ConnectionPassword", "ConnectionPassword", }); if (url == null || url.length () == 0) return error ("Property \"url\" is required"); if (driver == null || driver.length () == 0) { if (!scanForDriver (url)) return error (loc ("no-driver", url)); } info ("Connecting to " + url); if (username == null) username = reader.readLine ("Enter username for " + url + ": "); if (password == null) password = reader.readLine ("Enter password for " + url + ": ", new Character ('*')); try { // clear old completions completions.clear (); connections.setConnection ( new DatabaseConnection (driver, url, username, password)); con ().getConnection (); setCompletions (); return true; } catch (SQLException sqle) { return error (sqle); } catch (IOException ioe) { return error (ioe); } } public boolean rehash (String line) { try { if (!(assertConnection ())) return false; completions.clear (); if (con () != null) con ().setCompletions (false); return true; } catch (Exception e) { return error (e); } } /** * List the current connections */ public boolean list (String line) { int index = 0; info (loc ("active-connections", connections.size ())); for (Iterator i = connections.iterator (); i.hasNext (); index++) { DatabaseConnection c = (DatabaseConnection)i.next (); boolean closed = false; try { closed = c.connection.isClosed (); } catch (Exception e) { closed = true; } output (color ().pad (" #" + index + "", 5) .pad (closed ? loc ("closed") : loc ("open"), 9) .append (c.url)); } return true; } public boolean all (String line) { int index = connections.getIndex (); boolean success = true; for (int i = 0; i < connections.size (); i++) { connections.setIndex (i); output (loc ("executing-con", con ())); // ### FIXME: this is broken for multi-line SQL success = sql (line.substring ("all ".length ())) && success; } // restore index connections.setIndex (index); return success; } public boolean go (String line) { String [] parts = split (line, 2, "Usage: go "); if (parts == null) return false; int index = Integer.parseInt (parts [1]); if (!(connections.setIndex (index))) { error (loc ("invalid-connection", "" + index)); list (""); // list the current connections return false; } return true; } /** * Save or stop saving a script to a file */ public boolean script (String line) { if (script == null) return startScript (line); else return stopScript (line); } /** * Stop writing to the script file and close the script. */ private boolean stopScript (String line) { try { script.close (); } catch (Exception e) { handleException (e); } output (loc ("script-closed", script)); script = null; return true; } /** * Start writing to the specified script file. */ private boolean startScript (String line) { if (script != null) return error (loc ("script-already-running", script)); String [] parts = split (line, 2, "Usage: script "); if (parts == null) return false; try { script = new OutputFile (parts [1]); output (loc ("script-started", script)); return true; } catch (Exception e) { return error (e); } } /** * Run a script from the specified file. */ public boolean run (String line) { String [] parts = split (line, 2, "Usage: run "); if (parts == null) return false; List cmds = new LinkedList (); try { BufferedReader reader = new BufferedReader (new FileReader ( parts [1])); try { // ### NOTE: fix for sf.net bug 879427 StringBuffer cmd = null; for (;;) { String scriptLine = reader.readLine (); if (scriptLine == null) break; if (cmd != null) { // we're continuing an existing command scriptLine = scriptLine.trim (); cmd.append (" \n"); cmd.append (scriptLine); if (scriptLine.endsWith (";")) { // this command has terminated cmds.add( cmd.toString ()); cmd = null; } } else { // we're starting a new command if (needsContinuation (scriptLine)) { // multi-line cmd = new StringBuffer (scriptLine); } else { // single-line cmds.add (scriptLine); } } } if (cmd != null) { // ### REVIEW: oops, somebody left the last command // unterminated; should we fix it for them or complain? // For now be nice and fix it. cmd.append (";"); cmds.add (cmd.toString ()); } } finally { reader.close (); } // success only if all the commands were successful return runCommands (cmds) == cmds.size (); } catch (Exception e) { return error (e); } } /** * Save or stop saving all output to a file. */ public boolean record (String line) { if (record == null) return startRecording (line); else return stopRecording (line); } /** * Stop writing output to the record file. */ private boolean stopRecording (String line) { try { record.close (); } catch (Exception e) { handleException (e); } output (loc ("record-closed", record)); record = null; return true; } /** * Start writing to the specified record file. */ private boolean startRecording (String line) { if (record != null) return error (loc ("record-already-running", record)); String [] parts = split (line, 2, "Usage: record "); if (parts == null) return false; try { record = new OutputFile (parts [1]); output (loc ("record-started", record)); return true; } catch (Exception e) { return error (e); } } public boolean describe (String line) throws SQLException { String [] table = split (line, 2, "Usage: describe "); if (table == null) return false; ResultSet rs; if (table [1].equals ("tables")) { rs = getTables (); } else { rs = getColumns (table [1]); } if (rs == null) return false; print (rs); rs.close (); return true; } public boolean help (String line) { String [] parts = split (line); String cmd = parts.length > 1 ? parts [1] : ""; int count = 0; TreeSet clist = new TreeSet (); for (int i = 0; i < commands.length; i++) { if (cmd.length () == 0 || Arrays.asList (commands [i].getNames ()).contains (cmd)) { clist.add (color ().pad ("!" + commands [i].getName (), 20) .append (wrap (commands [i].getHelpText (), 60, 20))); } } for (Iterator i = clist.iterator (); i.hasNext (); ) output ((ColorBuffer)i.next ()); if (cmd.length () == 0) { output (""); output (loc ("comments", getApplicationContactInformation ())); } return true; } public boolean manual (String line) throws IOException { InputStream in = SqlLine.class.getResourceAsStream ("manual.txt"); if (in == null) return error (loc ("no-manual")); BufferedReader breader = new BufferedReader ( new InputStreamReader (in)); String man; int index = 0; while ((man = breader.readLine ()) != null) { index++; output (man); // silly little pager if (index % (opts.getMaxHeight () - 1) == 0) { String ret = reader.readLine (loc ("enter-for-more")); if (ret != null && ret.startsWith ("q")) break; } } breader.close (); return true; } } private void setCompletions () throws SQLException, IOException { if (con () != null) con ().setCompletions (opts.getFastConnect ()); } /** * Completor for SQLLine. It dispatches to sub-completors based on the * current arguments. * * @author Marc Prud'hommeaux */ class SQLLineCompletor implements Completor { public int complete (String buf, int pos, List cand) { if (buf != null && buf.startsWith (COMMAND_PREFIX) && !buf.startsWith (COMMAND_PREFIX + "all") && !buf.startsWith (COMMAND_PREFIX + "sql")) { return sqlLineCommandCompletor.complete (buf, pos, cand); } else { if (con () != null && con ().sqlLineSQLCompletor != null) return con ().sqlLineSQLCompletor.complete (buf, pos, cand); else return -1; } } } class SQLLineCommandCompletor extends MultiCompletor { public SQLLineCommandCompletor () { List completors = new LinkedList (); for (int i = 0; i < commands.length; i++) { String [] cmds = commands [i].getNames (); for (int j = 0; cmds != null && j < cmds.length; j++) { Completor [] comps = commands [i].getParameterCompletors (); List compl = new LinkedList (); compl.add (new SimpleCompletor (COMMAND_PREFIX + cmds [j])); compl.addAll (Arrays.asList (comps)); compl.add (new NullCompletor ()); // last param no complete completors.add (new ArgumentCompletor ( (Completor [])compl.toArray (new Completor [0]))); } } setCompletors ((Completor [])completors .toArray (new Completor [0])); } } class TableNameCompletor implements Completor { public int complete (String buf, int pos, List cand) { if (con () == null) return -1; return new SimpleCompletor (con ().getTableNames (true)) .complete (buf, pos, cand); } } class SQLLineSQLCompletor extends SimpleCompletor { public SQLLineSQLCompletor (boolean skipmeta) throws IOException, SQLException { super (new String [0]); Set completions = new TreeSet (); // add the default SQL completions String keywords = new BufferedReader (new InputStreamReader ( SQLLineSQLCompletor.class.getResourceAsStream ( "sql-keywords.properties"))).readLine (); // now add the keywords from the current connection try { keywords += "," + con ().meta.getSQLKeywords (); } catch (Throwable t) { } try { keywords += "," + con ().meta.getStringFunctions (); } catch (Throwable t) { } try { keywords += "," + con ().meta.getNumericFunctions (); } catch (Throwable t) { } try { keywords += "," + con ().meta.getSystemFunctions (); } catch (Throwable t) { } try { keywords += "," + con ().meta.getTimeDateFunctions (); } catch (Throwable t) { } // also allow lower-case versions of all the keywords keywords += "," + keywords.toLowerCase (); for (StringTokenizer tok = new StringTokenizer (keywords, ", "); tok.hasMoreTokens (); completions.add (tok.nextToken ())); // now add the tables and columns from the current connection if (!(skipmeta)) { String [] columns = getColumnNames (con ().meta); for (int i = 0; columns != null && i < columns.length; i++) completions.add (columns [i++]); } // set the Strings that will be completed setCandidateStrings ( (String [])completions.toArray (new String [0])); } } private static class Connections { private final List connections = new ArrayList (); private int index = -1; public SqlLine.DatabaseConnection current () { if (index != -1) return (SqlLine.DatabaseConnection)connections.get (index); return null; } public int size () { return connections.size (); } public Iterator iterator () { return connections.iterator (); } public void remove () { if (index != -1) { connections.remove (index); } while (index >= connections.size ()) index--; } public void addConnection (SqlLine.DatabaseConnection connection) { connections.add (connection); } public void setConnection (SqlLine.DatabaseConnection connection) { if (connections.indexOf (connection) == -1) connections.add (connection); index = connections.indexOf (connection); } public int getIndex () { return index; } public boolean setIndex (int index) { if (index < 0 || index >= connections.size ()) return false; this.index = index; return true; } } private class DatabaseConnection { Connection connection; DatabaseMetaData meta; private final String driver; private final String url; private final String username; private final String password; private Schema schema = null; private Completor sqlLineSQLCompletor = null; public DatabaseConnection (String driver, String url, String username, String password) throws SQLException { this.driver = driver; this.url = url; this.username = username; this.password = password; } public String toString () { return url + ""; } private void setCompletions (boolean skipmeta) throws SQLException, IOException { final String extraNameCharacters = meta == null || meta.getExtraNameCharacters () == null ? "" : meta.getExtraNameCharacters (); // setup the completor for the database sqlLineSQLCompletor = new ArgumentCompletor ( new SQLLineSQLCompletor (skipmeta), new ArgumentCompletor.AbstractArgumentDelimiter () { // deleimiters for SQL statements are any // non-letter-or-number characters, except // underscore and characters that are specified // by the database to be valid name identifiers. public boolean isDelimiterChar (String buf, int pos) { char c = buf.charAt (pos); if (Character.isWhitespace (c)) return true; return !(Character.isLetterOrDigit (c)) && c != '_' && extraNameCharacters.indexOf (c) == -1; } }); // not all argument elements need to hold true ((ArgumentCompletor)sqlLineSQLCompletor).setStrict (false); } /** * Connection to the specified data source. * * @param driver the driver class * @param url the connection URL * @param username the username * @param password the password */ boolean connect () throws SQLException { try { if (driver != null && driver.length () != 0) Class.forName (driver); } catch (ClassNotFoundException cnfe) { return error (cnfe); } boolean foundDriver = false; try { foundDriver = DriverManager.getDriver (url) != null; } catch (Exception e) { } if (!(foundDriver)) { output (loc ("autoloading-known-drivers", url)); registerKnownDrivers (); } try { close (); } catch (Exception e) { return error (e); } connection = DriverManager.getConnection (url, username, password); meta = connection.getMetaData (); try { info (loc ("connected", new Object [] { meta.getDatabaseProductName (), meta.getDatabaseProductVersion () })); } catch (Exception e) { handleException (e); } try { info (loc ("driver", new Object [] { meta.getDriverName (), meta.getDriverVersion () })); } catch (Exception e) { handleException (e); } try { connection.setAutoCommit (opts.getAutoCommit ()); autocommitStatus (connection); } catch (Exception e) { handleException (e); } try { command.isolation ("isolation: " + opts.getIsolation ()); } catch (Exception e) { handleException (e); } return true; } public Connection getConnection () throws SQLException { if (connection != null) return connection; connect (); return connection; } public void reconnect () throws Exception { close (); getConnection (); } public void close () { try { try { if (connection != null && !connection.isClosed ()) { output (loc ("closing", connection)); connection.close (); } } catch (Exception e) { handleException (e); } } finally { connection = null; meta = null; } } public String [] getTableNames (boolean force) { Schema.Table [] t = getSchema ().getTables (); Set names = new TreeSet (); for (int i = 0; t != null && i < t.length; i++) names.add (t [i].getName ()); return (String [])names.toArray (new String [names.size ()]); } Schema getSchema () { if (schema == null) schema = new Schema (); return schema; } class Schema { private Table [] tables = null; Table [] getTables () { if (tables != null) return tables; List tnames = new LinkedList (); try { ResultSet rs = meta.getTables (connection.getCatalog (), null, "%", new String [] { "TABLE" }); try { while (rs.next ()) tnames.add (new Table ( rs.getString ("TABLE_NAME"))); } finally { try { rs.close (); } catch (Exception e) { } } } catch (Throwable t) { } return tables = (Table [])tnames.toArray (new Table [0]); } Table getTable (String name) { Table [] t = getTables (); for (int i = 0; t != null && i < t.length; i++) { if (name.equalsIgnoreCase (t [i].getName ())) return t [i]; } return null; } class Table { final String name; Column [] columns; public Table (String name) { this.name = name; } public String getName () { return name; } class Column { final String name; boolean isPrimaryKey; public Column (String name) { this.name = name; } } } } } class Opts implements Completor { private boolean autosave = false; private boolean silent = false; private boolean color = false; private boolean showHeader = true; private int headerInterval = 100; private boolean fastConnect = true; private boolean autoCommit = true; private boolean verbose = false; private boolean force = false; private boolean incremental = false; private boolean showWarnings = false; private int maxWidth = Terminal.setupTerminal ().getTerminalWidth (); private int maxHeight = Terminal.setupTerminal ().getTerminalHeight (); private int maxColumnWidth = 15; private int timeout = -1; private String isolation = "TRANSACTION_REPEATABLE_READ"; private String outputFormat = "table"; public static final String PROPERTY_PREFIX = "sqlline."; public static final String PROPERTY_NAME_EXIT = PROPERTY_PREFIX + "system.exit"; private File rcFile = new File (saveDir (), "sqlline.properties"); private String historyFile = new File (saveDir (), "history") .getAbsolutePath (); public Opts (Properties props) { loadProperties (props); } public Completor [] optionCompletors () { return new Completor [] { this, // new SimpleCompletor (possibleSettingValues ()), }; } public String [] possibleSettingValues () { List vals = new LinkedList (); vals.addAll (Arrays.asList (new String [] { "yes", "no", })); return (String [])vals.toArray (new String [vals.size ()]); } /** * The save directory if HOME/.sqlline/ on UNIX, and * HOME/sqlline/ on Windows. */ public File saveDir () { String dir = System.getProperty ("sqlline.rcfile"); if (dir != null && dir.length () > 0) return new File (dir); File f = new File (System.getProperty ("user.home"), (System.getProperty ("os.name").toLowerCase () .indexOf ("windows") != -1 ? "" : ".") + "sqlline") .getAbsoluteFile (); try { f.mkdirs (); } catch (Exception e) { } return f; } public int complete (String buf, int pos, List cand) { try { return new SimpleCompletor (propertyNames ()) .complete (buf, pos, cand); } catch (Throwable t) { return -1; } } public void save () throws IOException { OutputStream out = new FileOutputStream (rcFile); save (out); out.close (); } public void save (OutputStream out) throws IOException { try { Properties props = toProperties (); // don't save maxwidth: it is automatically set based on // the terminal configuration props.remove (PROPERTY_PREFIX + "maxwidth"); props.store (out, getApplicationTitle ()); } catch (Exception e) { handleException (e); } } String [] propertyNames () throws IllegalAccessException, InvocationTargetException { TreeSet names = new TreeSet (); // get all the values from getXXX methods Method [] m = getClass ().getDeclaredMethods (); for (int i = 0; m != null && i < m.length; i++) { if (!(m [i].getName ().startsWith ("get"))) continue; if (m [i].getParameterTypes ().length != 0) continue; String propName = m [i].getName ().substring (3).toLowerCase (); names.add (propName); } return (String [])names.toArray (new String [names.size ()]); } public Properties toProperties () throws IllegalAccessException, InvocationTargetException, ClassNotFoundException { Properties props = new Properties (); String [] names = propertyNames (); for (int i = 0; names != null && i < names.length; i++) { props.setProperty (PROPERTY_PREFIX + names [i], Reflector.invoke (this, "get" + names [i], new Object [0]) .toString ()); } debug ("properties: " + props.toString ()); return props; } public void load () throws IOException { InputStream in = new FileInputStream (rcFile); load (in); in.close (); } public void load (InputStream fin) throws IOException { Properties p = new Properties (); p.load (fin); loadProperties (p); } public void loadProperties (Properties props) { for (Iterator i = props.keySet ().iterator (); i.hasNext (); ) { String key = i.next ().toString (); if (key.equals (PROPERTY_NAME_EXIT)) { // fix for sf.net bug 879422 continue; } if (key.startsWith (PROPERTY_PREFIX)) { set (key.substring (PROPERTY_PREFIX.length ()), props.getProperty (key)); } } } public void set (String key, String value) { set (key, value, false); } public boolean set (String key, String value, boolean quiet) { try { Reflector.invoke (this, "set" + key, new Object [] { value }); return true; } catch (Exception e) { if (!quiet) error (loc ("error-setting", new Object [] { key, e })); return false; } } public void setFastConnect (boolean fastConnect) { this.fastConnect = fastConnect; } public boolean getFastConnect () { return this.fastConnect; } public void setAutoCommit (boolean autoCommit) { this.autoCommit = autoCommit; } public boolean getAutoCommit () { return this.autoCommit; } public void setVerbose (boolean verbose) { this.verbose = verbose; } public boolean getVerbose () { return this.verbose; } public void setShowWarnings (boolean showWarnings) { this.showWarnings = showWarnings; } public boolean getShowWarnings () { return this.showWarnings; } public void setMaxWidth (int maxWidth) { this.maxWidth = maxWidth; } public int getMaxWidth () { return this.maxWidth; } public void setMaxColumnWidth (int maxColumnWidth) { this.maxColumnWidth = maxColumnWidth; } public int getMaxColumnWidth () { return this.maxColumnWidth; } public void setTimeout (int timeout) { this.timeout = timeout; } public int getTimeout () { return this.timeout; } public void setIsolation (String isolation) { this.isolation = isolation; } public String getIsolation () { return this.isolation; } public void setHistoryFile (String historyFile) { this.historyFile = historyFile; } public String getHistoryFile () { return this.historyFile; } public void setColor (boolean color) { this.color = color; } public boolean getColor () { return this.color; } public void setShowHeader (boolean showHeader) { this.showHeader = showHeader; } public boolean getShowHeader () { return this.showHeader; } public void setHeaderInterval (int headerInterval) { this.headerInterval = headerInterval; } public int getHeaderInterval () { return this.headerInterval; } public void setForce (boolean force) { this.force = force; } public boolean getForce () { return this.force; } public void setIncremental (boolean incremental) { this.incremental = incremental; } public boolean getIncremental () { return this.incremental; } public void setSilent (boolean silent) { this.silent = silent; } public boolean getSilent () { return this.silent; } public void setAutosave (boolean autosave) { this.autosave = autosave; } public boolean getAutosave () { return this.autosave; } public void setOutputFormat (String outputFormat) { this.outputFormat = outputFormat; } public String getOutputFormat () { return this.outputFormat; } public void setMaxHeight (int maxHeight) { this.maxHeight = maxHeight; } public int getMaxHeight () { return this.maxHeight; } } static class Reflector { public static Object invoke (Object on, String method, Object [] args) throws InvocationTargetException, IllegalAccessException, ClassNotFoundException { return invoke (on, method, Arrays.asList (args)); } public static Object invoke (Object on, String method, List args) throws InvocationTargetException, IllegalAccessException, ClassNotFoundException { return invoke (on, on == null ? null : on.getClass (), method, args); } public static Object invoke (Object on, Class defClass, String method, List args) throws InvocationTargetException, IllegalAccessException, ClassNotFoundException { Class c = defClass != null ? defClass : on.getClass (); List candidateMethods = new LinkedList (); Method [] m = c.getMethods (); for (int i = 0; i < m.length; i++) { if (m [i].getName ().equalsIgnoreCase (method)) candidateMethods.add (m [i]); } if (candidateMethods.size () == 0) throw new IllegalArgumentException (loc ("no-method", new Object [] { method, c.getName () })); for (Iterator i = candidateMethods.iterator (); i.hasNext (); ) { Method meth = (Method)i.next (); Class [] ptypes = meth.getParameterTypes (); if (!(ptypes.length == args.size ())) continue; Object [] converted = convert (args, ptypes); if (converted == null) continue; if (!Modifier.isPublic (meth.getModifiers ())) continue; return meth.invoke (on, converted); } return null; } public static Object [] convert (List objects, Class [] toTypes) throws ClassNotFoundException { Object [] converted = new Object [objects.size ()]; for (int i = 0; i < converted.length; i++) converted [i] = convert (objects.get (i), toTypes [i]); return converted; } public static Object convert (Object ob, Class toType) throws ClassNotFoundException { if (ob == null || ob.toString ().equals ("null")) return null; if (toType == String.class) return new String (ob.toString ()); else if (toType == Byte.class || toType == byte.class) return new Byte (ob.toString ()); else if (toType == Character.class || toType == char.class) return new Character (ob.toString ().charAt (0)); else if (toType == Short.class || toType == short.class) return new Short (ob.toString ()); else if (toType == Integer.class || toType == int.class) return new Integer (ob.toString ()); else if (toType == Long.class || toType == long.class) return new Long (ob.toString ()); else if (toType == Double.class || toType == double.class) return new Double (ob.toString ()); else if (toType == Float.class || toType == float.class) return new Float (ob.toString ()); else if (toType == Boolean.class || toType == boolean.class) return new Boolean (ob.toString ().equals ("true") || ob.toString ().equals (true + "") || ob.toString ().equals ("1") || ob.toString ().equals ("on") || ob.toString ().equals ("yes")); else if (toType == Class.class) return Class.forName (ob.toString ()); return null; } } public class OutputFile { final File file; final PrintWriter out; public OutputFile (String filename) throws IOException { file = new File (filename); out = new PrintWriter (new FileWriter (file)); } public String toString () { return file.getAbsolutePath (); } public void addLine (String command) { out.println (command); } public void close () throws IOException { out.close (); } } static class DriverInfo { public String sampleURL; public DriverInfo (String name) throws IOException { Properties props = new Properties (); props.load (DriverInfo.class.getResourceAsStream (name)); fromProperties (props); } public DriverInfo (Properties props) { fromProperties (props); } public void fromProperties (Properties props) { } } } sqlline-1.0.2/src/sqlline/sql-keywords.properties0000644000175000017500000000435007702544706022112 0ustar drazzibdrazzibABSOLUTE,ACTION,ADD,ALL,ALLOCATE,ALTER,AND,ANY,ARE,AS,ASC,ASSERTION,AT,AUTHORIZATION,AVG,BEGIN,BETWEEN,BIT,BIT_LENGTH,BOTH,BY,CASCADE,CASCADED,CASE,CAST,CATALOG,CHAR,CHARACTER,CHAR_LENGTH,CHARACTER_LENGTH,CHECK,CLOSE,COALESCE,COLLATE,COLLATION,COLUMN,COMMIT,CONNECT,CONNECTION,CONSTRAINT,CONSTRAINTS,CONTINUE,CONVERT,CORRESPONDING,COUNT,CREATE,CROSS,CURRENT,CURRENT_DATE,CURRENT_TIME,CURRENT_TIMESTAMP,CURRENT_USER,CURSOR,DATE,DAY,DEALLOCATE,DEC,DECIMAL,DECLARE,DEFAULT,DEFERRABLE,DEFERRED,DELETE,DESC,DESCRIBE,DESCRIPTOR,DIAGNOSTICS,DISCONNECT,DISTINCT,DOMAIN,DOUBLE,DROP,ELSE,END,END-EXEC,ESCAPE,EXCEPT,EXCEPTION,EXEC,EXECUTE,EXISTS,EXTERNAL,EXTRACT,FALSE,FETCH,FIRST,FLOAT,FOR,FOREIGN,FOUND,FROM,FULL,GET,GLOBAL,GO,GOTO,GRANT,GROUP,HAVING,HOUR,IDENTITY,IMMEDIATE,IN,INDICATOR,INITIALLY,INNER,INPUT,INSENSITIVE,INSERT,INT,INTEGER,INTERSECT,INTERVAL,INTO,IS,ISOLATION,JOIN,KEY,LANGUAGE,LAST,LEADING,LEFT,LEVEL,LIKE,LOCAL,LOWER,MATCH,MAX,MIN,MINUTE,MODULE,MONTH,NAMES,NATIONAL,NATURAL,NCHAR,NEXT,NO,NOT,NULL,NULLIF,NUMERIC,OCTET_LENGTH,OF,ON,ONLY,OPEN,OPTION,OR,ORDER,OUTER,OUTPUT,OVERLAPS,PAD,PARTIAL,POSITION,PRECISION,PREPARE,PRESERVE,PRIMARY,PRIOR,PRIVILEGES,PROCEDURE,PUBLIC,READ,REAL,REFERENCES,RELATIVE,RESTRICT,REVOKE,RIGHT,ROLLBACK,ROWS,SCHEMA,SCROLL,SECOND,SECTION,SELECT,SESSION,SESSION_USER,SET,SIZE,SMALLINT,SOME,SPACE,SQL,SQLCODE,SQLERROR,SQLSTATE,SUBSTRING,SUM,SYSTEM_USER,TABLE,TEMPORARY,THEN,TIME,TIMESTAMP,TIMEZONE_HOUR,TIMEZONE_MINUTE,TO,TRAILING,TRANSACTION,TRANSLATE,TRANSLATION,TRIM,TRUE,UNION,UNIQUE,UNKNOWN,UPDATE,UPPER,USAGE,USER,USING,VALUE,VALUES,VARCHAR,VARYING,VIEW,WHEN,WHENEVER,WHERE,WITH,WORK,WRITE,YEAR,ZONE,ADA,C,CATALOG_NAME,CHARACTER_SET_CATALOG,CHARACTER_SET_NAME,CHARACTER_SET_SCHEMA,CLASS_ORIGIN,COBOL,COLLATION_CATALOG,COLLATION_NAME,COLLATION_SCHEMA,COLUMN_NAME,COMMAND_FUNCTION,COMMITTED,CONDITION_NUMBER,CONNECTION_NAME,CONSTRAINT_CATALOG,CONSTRAINT_NAME,CONSTRAINT_SCHEMA,CURSOR_NAME,DATA,DATETIME_INTERVAL_CODE,DATETIME_INTERVAL_PRECISION,DYNAMIC_FUNCTION,FORTRAN,LENGTH,MESSAGE_LENGTH,MESSAGE_OCTET_LENGTH,MESSAGE_TEXT,MORE,MUMPS,NAME,NULLABLE,NUMBER,PASCAL,PLI,REPEATABLE,RETURNED_LENGTH,RETURNED_OCTET_LENGTH,RETURNED_SQLSTATE,ROW_COUNT,SCALE,SCHEMA_NAME,SERIALIZABLE,SERVER_NAME,SUBCLASS_ORIGIN,TABLE_NAME,TYPE,UNCOMMITTED,UNNAMED sqlline-1.0.2/src/sqlline/drivers/0000755000175000017500000000000007705066776017015 5ustar drazzibdrazzibsqlline-1.0.2/src/sqlline/drivers/com.thinweb.tds.Driver.properties0000644000175000017500000000002707703600230025343 0ustar drazzibdrazzibcom.thinweb.tds.Driver sqlline-1.0.2/src/sqlline/drivers/COM.ibm.db2.jdbc.net.DB2Driver.properties0000644000175000017500000000003707703600230026146 0ustar drazzibdrazzibCOM.ibm.db2.jdbc.net.DB2Driver sqlline-1.0.2/src/sqlline/drivers/com.merant.datadirect.jdbc.informix.InformixDriver.properties0000644000175000017500000000006307703600230032752 0ustar drazzibdrazzibcom.merant.datadirect.jdbc.informix.InformixDriver sqlline-1.0.2/src/sqlline/drivers/COM.cloudscape.core.RmiJdbcDriver.properties0000644000175000017500000000004207703600230027253 0ustar drazzibdrazzibCOM.cloudscape.core.RmiJdbcDriver sqlline-1.0.2/src/sqlline/drivers/com.sybase.jdbc.SybDriver.properties0000644000175000017500000000003207703600230025753 0ustar drazzibdrazzibcom.sybase.jdbc.SybDriver sqlline-1.0.2/src/sqlline/drivers/sun.jdbc.odbc.JdbcOdbcDriver.properties0000644000175000017500000000003507703600230026323 0ustar drazzibdrazzibsun.jdbc.odbc.JdbcOdbcDriver sqlline-1.0.2/src/sqlline/drivers/com.ddtek.jdbc.informix.InformixDriver.properties0000644000175000017500000000004707703600230030456 0ustar drazzibdrazzibcom.ddtek.jdbc.informix.InformixDriver sqlline-1.0.2/src/sqlline/drivers/com.merant.datadirect.jdbc.sqlserver.SQLServerDriver.properties0000644000175000017500000000006507703600230033202 0ustar drazzibdrazzibcom.merant.datadirect.jdbc.sqlserver.SQLServerDriver sqlline-1.0.2/src/sqlline/drivers/org.hsqldb.jdbcDriver.properties0000644000175000017500000000002607703600230025222 0ustar drazzibdrazziborg.hsqldb.jdbcDriver sqlline-1.0.2/src/sqlline/drivers/COM.cloudscape.core.JDBCDriver.properties0000644000175000017500000000003707703600230026447 0ustar drazzibdrazzibCOM.cloudscape.core.JDBCDriver sqlline-1.0.2/src/sqlline/drivers/com.internetcds.jdbc.tds.SybaseDriver.properties0000644000175000017500000000004607703600230030276 0ustar drazzibdrazzibcom.internetcds.jdbc.tds.SybaseDriver sqlline-1.0.2/src/sqlline/drivers/openlink.jdbc2.Driver.properties0000644000175000017500000000002607703600230025136 0ustar drazzibdrazzibopenlink.jdbc2.Driver sqlline-1.0.2/src/sqlline/drivers/com.ibm.db2.jcc.DB2Driver.properties0000644000175000017500000000003207703600230025351 0ustar drazzibdrazzibcom.ibm.db2.jcc.DB2Driver sqlline-1.0.2/src/sqlline/drivers/com.microsoft.jdbc.sqlserver.SQLServerDriver.properties0000644000175000017500000000005507703600230031615 0ustar drazzibdrazzibcom.microsoft.jdbc.sqlserver.SQLServerDriver sqlline-1.0.2/src/sqlline/drivers/com.pointbase.jdbc.jdbcDriver.properties0000644000175000017500000000003607703600230026622 0ustar drazzibdrazzibcom.pointbase.jdbc.jdbcDriver sqlline-1.0.2/src/sqlline/drivers/org.sourceforge.jxdbcon.JXDBConDriver.properties0000644000175000017500000000004607703600230030205 0ustar drazzibdrazziborg.sourceforge.jxdbcon.JXDBConDriver sqlline-1.0.2/src/sqlline/drivers/solid.jdbc.SolidDriver.properties0000644000175000017500000000002707703600230025343 0ustar drazzibdrazzibsolid.jdbc.SolidDriver sqlline-1.0.2/src/sqlline/drivers/com.pointbase.jdbc.jdbcEmbeddedDriver.properties0000644000175000017500000000004607703600230030235 0ustar drazzibdrazzibcom.pointbase.jdbc.jdbcEmbeddedDriver sqlline-1.0.2/src/sqlline/drivers/weblogic.jdbc.mssqlserver4.Driver.properties0000644000175000017500000000004207703600230027477 0ustar drazzibdrazzibweblogic.jdbc.mssqlserver4.Driver sqlline-1.0.2/src/sqlline/drivers/com.mysql.jdbc.DatabaseMetaData.properties0000644000175000017500000000004007703600230027025 0ustar drazzibdrazzibcom.mysql.jdbc.DatabaseMetaData sqlline-1.0.2/src/sqlline/drivers/oracle.jdbc.OracleDriver.properties0000644000175000017500000000003107703600230025624 0ustar drazzibdrazziboracle.jdbc.OracleDriver sqlline-1.0.2/src/sqlline/drivers/com.merant.datadirect.jdbc.db2.DB2Driver.properties0000644000175000017500000000005107703600230030337 0ustar drazzibdrazzibcom.merant.datadirect.jdbc.db2.DB2Driver sqlline-1.0.2/src/sqlline/drivers/com.sybase.jdbc2.jdbc.SybDriver.properties0000644000175000017500000000004007703600230026735 0ustar drazzibdrazzibcom.sybase.jdbc2.jdbc.SybDriver sqlline-1.0.2/src/sqlline/drivers/com.ddtek.jdbc.oracle.OracleDriver.properties0000644000175000017500000000004307703600230027476 0ustar drazzibdrazzibcom.ddtek.jdbc.oracle.OracleDriver sqlline-1.0.2/src/sqlline/drivers/com.ddtek.jdbc.db2.DB2Driver.properties0000644000175000017500000000003507703600230026043 0ustar drazzibdrazzibcom.ddtek.jdbc.db2.DB2Driver sqlline-1.0.2/src/sqlline/drivers/com.merant.datadirect.jdbc.oracle.OracleDriver.properties0000644000175000017500000000005707703600230032001 0ustar drazzibdrazzibcom.merant.datadirect.jdbc.oracle.OracleDriver sqlline-1.0.2/src/sqlline/drivers/intersolv.jdbc.sequelink.SequeLinkDriver.properties0000644000175000017500000000005107703600230031100 0ustar drazzibdrazzibintersolv.jdbc.sequelink.SequeLinkDriver sqlline-1.0.2/src/sqlline/drivers/COM.ibm.db2.jdbc.app.DB2Driver.properties0000644000175000017500000000003707703600230026140 0ustar drazzibdrazzibCOM.ibm.db2.jdbc.app.DB2Driver sqlline-1.0.2/src/sqlline/drivers/com.ddtek.jdbc.sqlserver.SQLServerDriver.properties0000644000175000017500000000005107703600230030677 0ustar drazzibdrazzibcom.ddtek.jdbc.sqlserver.SQLServerDriver sqlline-1.0.2/src/sqlline/drivers/org.gjt.mm.mysql.Driver.properties0000644000175000017500000000003007703600230025455 0ustar drazzibdrazziborg.gjt.mm.mysql.Driver sqlline-1.0.2/src/sqlline/drivers/com.mysql.jdbc.NonRegisteringDriver.properties0000644000175000017500000000004407703600230030035 0ustar drazzibdrazzibcom.mysql.jdbc.NonRegisteringDriver sqlline-1.0.2/src/sqlline/drivers/org.enhydra.instantdb.jdbc.idbDriver.properties0000644000175000017500000000004507703600230030122 0ustar drazzibdrazziborg.enhydra.instantdb.jdbc.idbDriver sqlline-1.0.2/src/sqlline/drivers/com.imaginary.sql.msql.MsqlDriver.properties0000644000175000017500000000004207703600230027475 0ustar drazzibdrazzibcom.imaginary.sql.msql.MsqlDriver sqlline-1.0.2/src/sqlline/drivers/postgres95.PGDriver.properties0000644000175000017500000000002407703600230024605 0ustar drazzibdrazzibpostgres95.PGDriver sqlline-1.0.2/src/sqlline/drivers/weblogic.jdbc.pool.Driver.properties0000644000175000017500000000003207703600230025775 0ustar drazzibdrazzibweblogic.jdbc.pool.Driver sqlline-1.0.2/src/sqlline/drivers/COM.FirstSQL.Dbcp.DbcpDriver.properties0000644000175000017500000000003507703600230026060 0ustar drazzibdrazzibCOM.FirstSQL.Dbcp.DbcpDriver sqlline-1.0.2/src/sqlline/drivers/com.mckoi.JDBCDriver.properties0000644000175000017500000000002507703600230024635 0ustar drazzibdrazzibcom.mckoi.JDBCDriver sqlline-1.0.2/src/sqlline/drivers/com.informix.jdbc.IfxDriver.properties0000644000175000017500000000003407703600230026313 0ustar drazzibdrazzibcom.informix.jdbc.IfxDriver sqlline-1.0.2/src/sqlline/drivers/oracle.jdbc.pool.OracleDataSource.properties0000644000175000017500000000004207703600230027375 0ustar drazzibdrazziboracle.jdbc.pool.OracleDataSource sqlline-1.0.2/src/sqlline/drivers/org.axiondb.jdbc.AxionDriver.properties0000644000175000017500000000003507703600230026446 0ustar drazzibdrazziborg.axiondb.jdbc.AxionDriver sqlline-1.0.2/src/sqlline/drivers/in.co.daffodil.db.jdbc.DaffodilDBDriver.properties0000644000175000017500000000005007703600230030232 0ustar drazzibdrazzibin.co.daffodil.db.jdbc.DaffodilDBDriver sqlline-1.0.2/src/sqlline/drivers/com.sap.dbtech.jdbc.DriverSapDB.properties0000644000175000017500000000004007703600230026673 0ustar drazzibdrazzibcom.sap.dbtech.jdbc.DriverSapDB sqlline-1.0.2/src/sqlline/drivers/centura.java.sqlbase.SqlbaseDriver.properties0000644000175000017500000000004307703600230027660 0ustar drazzibdrazzibcentura.java.sqlbase.SqlbaseDriver sqlline-1.0.2/src/sqlline/drivers/interbase.interclient.Driver.properties0000644000175000017500000000003507703600230026627 0ustar drazzibdrazzibinterbase.interclient.Driver sqlline-1.0.2/src/sqlline/drivers/com.inet.tds.TdsDriver.properties0000644000175000017500000000002707703600230025315 0ustar drazzibdrazzibcom.inet.tds.TdsDriver sqlline-1.0.2/src/sqlline/drivers/com.merant.datadirect.jdbc.sybase.SybaseDriver.properties0000644000175000017500000000005707703600230032043 0ustar drazzibdrazzibcom.merant.datadirect.jdbc.sybase.SybaseDriver sqlline-1.0.2/src/sqlline/drivers/com.pointbase.jdbc.jdbcUniversalDriver.properties0000644000175000017500000000004707703600230030515 0ustar drazzibdrazzibcom.pointbase.jdbc.jdbcUniversalDriver sqlline-1.0.2/src/sqlline/drivers/postgresql.Driver.properties0000644000175000017500000000002207703600230024533 0ustar drazzibdrazzibpostgresql.Driver sqlline-1.0.2/src/sqlline/drivers/oracle.jdbc.driver.OracleDriver.properties0000644000175000017500000000004007703600230027116 0ustar drazzibdrazziboracle.jdbc.driver.OracleDriver sqlline-1.0.2/src/sqlline/drivers/org.hsql.jdbcDriver.properties0000644000175000017500000000002407703600230024712 0ustar drazzibdrazziborg.hsql.jdbcDriver sqlline-1.0.2/src/sqlline/drivers/com.ibm.as400.access.AS400JDBCDriver.properties0000644000175000017500000000004507703600230027042 0ustar drazzibdrazzibcom.ibm.as400.access.AS400JDBCDriver sqlline-1.0.2/src/sqlline/drivers/net.sourceforge.jtds.jdbc.Driver.properties0000644000175000017500000000004107703600230027305 0ustar drazzibdrazzibnet.sourceforge.jtds.jdbc.Driver sqlline-1.0.2/src/sqlline/drivers/com.internetcds.jdbc.tds.Driver.properties0000644000175000017500000000004007703600230027121 0ustar drazzibdrazzibcom.internetcds.jdbc.tds.Driver sqlline-1.0.2/src/sqlline/drivers/com.jnetdirect.jsql.JSQLDriver.properties0000644000175000017500000000003707703600230026710 0ustar drazzibdrazzibcom.jnetdirect.jsql.JSQLDriver sqlline-1.0.2/src/sqlline/drivers/com.ddtek.jdbc.sybase.SybaseDriver.properties0000644000175000017500000000004307703600230027540 0ustar drazzibdrazzibcom.ddtek.jdbc.sybase.SybaseDriver sqlline-1.0.2/src/sqlline/drivers/org.postgresql.Driver.properties0000644000175000017500000000002607703600230025325 0ustar drazzibdrazziborg.postgresql.Driver sqlline-1.0.2/src/sqlline/drivers/com.mysql.jdbc.Driver.properties0000644000175000017500000000002607703600230025157 0ustar drazzibdrazzibcom.mysql.jdbc.Driver sqlline-1.0.2/src/sqlline/drivers.list0000644000175000017500000000345007703163742017701 0ustar drazzibdrazzibCOM.FirstSQL.Dbcp.DbcpDriver COM.cloudscape.core.JDBCDriver COM.cloudscape.core.RmiJdbcDriver COM.ibm.db2.jdbc.app.DB2Driver COM.ibm.db2.jdbc.net.DB2Driver centura.java.sqlbase.SqlbaseDriver com.ddtek.jdbc.db2.DB2Driver com.ddtek.jdbc.informix.InformixDriver com.ddtek.jdbc.oracle.OracleDriver com.ddtek.jdbc.sqlserver.SQLServerDriver com.ddtek.jdbc.sybase.SybaseDriver com.ibm.as400.access.AS400JDBCDriver com.ibm.db2.jcc.DB2Driver com.imaginary.sql.msql.MsqlDriver com.inet.tds.TdsDriver com.informix.jdbc.IfxDriver com.internetcds.jdbc.tds.Driver com.internetcds.jdbc.tds.SybaseDriver com.jnetdirect.jsql.JSQLDriver com.mckoi.JDBCDriver com.merant.datadirect.jdbc.db2.DB2Driver com.merant.datadirect.jdbc.informix.InformixDriver com.merant.datadirect.jdbc.oracle.OracleDriver com.merant.datadirect.jdbc.sqlserver.SQLServerDriver com.merant.datadirect.jdbc.sybase.SybaseDriver com.microsoft.jdbc.sqlserver.SQLServerDriver com.mysql.jdbc.DatabaseMetaData com.mysql.jdbc.Driver com.mysql.jdbc.NonRegisteringDriver com.pointbase.jdbc.jdbcDriver com.pointbase.jdbc.jdbcEmbeddedDriver com.pointbase.jdbc.jdbcUniversalDriver com.sap.dbtech.jdbc.DriverSapDB com.sybase.jdbc.SybDriver com.sybase.jdbc2.jdbc.SybDriver com.thinweb.tds.Driver in.co.daffodil.db.jdbc.DaffodilDBDriver interbase.interclient.Driver intersolv.jdbc.sequelink.SequeLinkDriver net.sourceforge.jtds.jdbc.Driver openlink.jdbc2.Driver oracle.jdbc.OracleDriver oracle.jdbc.driver.OracleDriver oracle.jdbc.pool.OracleDataSource org.axiondb.jdbc.AxionDriver org.enhydra.instantdb.jdbc.idbDriver org.gjt.mm.mysql.Driver org.hsql.jdbcDriver org.hsqldb.jdbcDriver org.postgresql.Driver org.sourceforge.jxdbcon.JXDBConDriver postgres95.PGDriver postgresql.Driver solid.jdbc.SolidDriver sun.jdbc.odbc.JdbcOdbcDriver weblogic.jdbc.mssqlserver4.Driver weblogic.jdbc.pool.Driver sqlline-1.0.2/doc/0000755000175000017500000000000010313510646013621 5ustar drazzibdrazzibsqlline-1.0.2/doc/styles.css.old0000644000175000017500000000416307704206700016442 0ustar drazzibdrazzibbody { /* background-color: #F1F1F1; */ color: #000000; font-family: verdana,arial,helvetica,sans-serif; /* font-size: 14; */ margin-left: 8%; margin-right: 4%; } hr { margin-left: -4%; } a:link { /* color: blue; */ color: #511112; /* text-decoration: none; */ } a:visited { color:green; text-decoration: none; } a:active { color:green; text-decoration: none; } a:hover { color:red; text-decoration: underline; } pre.programlisting { font-family: monospace; background-color: #E0E0E0; border: thin solid gray; /* width: 80%; */ /* margin-left: 10%; */ font-size: 12; padding: 10px; } pre.screen { font-family: monospace; background-color: #E0E0E0; border: thin solid gray; /* width: 80%; */ /* margin-left: 10%; */ font-size: 12; padding: 10px; } div.note { border: 1px solid green; text-align: center: } div.important { color: red; border: 1px solid red; text-align: center: } div.warning { color: red; border: 2px solid red; text-align: center: } div.caution { border: 1px solid #1111BB; text-align: center: } div.table { font-family: monospace; background-color: #E0E0E0; border: thin solid gray; font-size: 12; margin-top: 5px; margin-bottom: 5px; } h1 { font-family: verdana,arial,helvetica,sans-serif; font-size: 24px; margin-left: -4%; } pre.programlisting { border: thin solid gray; } h2 { font-family: verdana,arial,helvetica,sans-serif; font-size: 20px; } h2.appendix { font-family: verdana,arial,helvetica,sans-serif; font-size: 24px; margin-left: -4%; color: gray; text-align: center: } .title { font-family: Arial, Helvetica, sans-serif; font-variant: small-caps; color: #511111; text-align: center; } h2.title { border: thin solid gray; } .author { font-family: verdana,arial,helvetica,sans-serif; font-size: 12px; text-align: center; } .editedby { font-family: verdana,arial,helvetica,sans-serif; font-size: 12px; text-align: center; } .editor { font-family: verdana,arial,helvetica,sans-serif; font-size: 12px; text-align: center; } div.chapter-divider { font-family: verdana,arial,helvetica,sans-serif; font-size: 9px; } sqlline-1.0.2/doc/.manual.xml.swp0000644000175000017500000032000010313506766016511 0ustar drazzibdrazzibb0VIM 6.3f /C‘V€mprudhomchance.local~mprudhom/projects/sqlline/doc/manual.xml0123 !"#Uptÿkbl΀M„Í‚Q =Ó @ rP  sQrÄl6j¢ {“›p+i› j ‘e û9 `da ÊkñÁ‘TÛ°­¦š{pb8 õ á Á À ¢ ƒ y : ý ¼ u 2 ó » ° £ ¢ ‰ ^ T /  Ò ” ˆ C )   Ø ­ j _ R Q 6  Цw?4'&éÞ¹®~jSËŽdK4üÄ›iF-â½JÙ¶wB2øìá»°s6òàÊÈ installing SQLLine in a platform independant way is as follows: software on different platforms. The simplest method for There are currently no set standards for installing Java Installing SQLLine web site. or else by referring to your database vendor's known JDBC drivers, referring to the section on used for this purpose. Drivers can be located by for your database. Any JDBC compliant driver can be need to obtain the correct JDBC driver libraries Connectivity package to connect to your database, you SQLLine uses the Java Database JDBC Driver(s) - Since 0.8.1 or higher is required. . Version history. It can be downloaded from command line editing, tab-completion, and command JLine - SQLLine uses the JLine console reader for . in order to run. The latest JVM can be downloaded from java program, and requires Java version 1.3 or higher SQLLine is a pure Java Virtual Machine - SQLLine depends on the following software: Required software Installation . The latest release can be downloaded from . SQLLine is hosted on SourceForge, and is located at Obtaining SQLLine mwp1@cornell.edu. license, contact the copyright holder: For information on obtaining the software under another license text. see the with almost no restrictions. For the text of the license, you are free to redistribute, modify, or sell the software BSD License, meaning that SQLLine is distributed under the License and Terms of Use run on any platform that can run Java 1.3 or higher. Since it is pure-Java, it is platform independant, and will for MySQL, and isql for Sybase/SQL Server. sqlplus for Oracle, mysql similiar to other command-line database access utilities like to relational databases and executing SQL commands. It is SQLLine is a pure-Java console based utility for connecting Introduction SQLLine Manual Marc Prud'hommeaux 2002, 2003, 2004, 2005 SQLLine &VERSION; � <bookinfo>�<book>�]>� <!ENTITY VERSION SYSTEM "../VERSION.txt">� <!-- external version reference, generated by ant -->� <!-- "file:/sw/share/xml/dtd/docbookx/4.2.0/docbookx.dtd" -->� <!-- "http://www.docbook.org/xml/4.2/docbookx.dtd" -->�[� "http://www.docbook.org/xml/4.2/docbookx.dtd"� PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"�<!DOCTYPE book�da���� X�� P������9��É��´��¨��œ��y��[��P����ä��Æ��º��®��‰��i��^��(�� ñ�� É�� ª�� ž�� ’�� s�� Y�� N�� �� Õ�� •�� v�� j�� ^�� >�� #�� �� ä�� ­�� {�� P�� D�� 8�� +�� *�� �� å�� Û�� Ð�� Ã�� Â�� ¹�� ¸�� ·�� š�� v�� n�� e�� Y�� Q�� P�� O�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������</book>�</appendix>� </para>� <para>� <title>Project Information JDBC Driver Support Defaults to false. as well as displaying debugging information. entire java stack trace whenever an error occurs, If true, then print out the verbose false. a sqlline command to a file for later parsing. Defaults to of informational messages displayed. Useful for redirecting If true, then reduce the amount silent false. any database commands. Defaults to that are reported on the connection after issuing If true, display any warnings showwarnings true. columns when displaying results. Defaults to If true, display the names of the showheader command. outputformatdaªbÈ‹s])ëÕ˜kE- â ¨ j W ? ,    ï Ï ± Ž ƒ P = Í ~ 1 Û Ç Æ Š K $  Õ Ç » º ¯ u 6ô³ug[O4ý¼}FÏ•Z!ꯟ“ˆD76ÒÑx=æÎÍ£•”]2&ߦo9 ôƺµª© >properties command documentation. reflect URL of the current connection. Once you are connected, the prompt will change the 0: jdbc:oracle:thin:@localhost:1521:mydb>Autocommit status: trueDriver: Oracle JDBC driver (version 9.0.1.0.0)JServer Release 9.2.0.1.0 - Production)With the Partitioning, OLAP and Oracle Data Mining optionsConnected to: Oracle (version Oracle9i Enterprise Edition Release 9.2.0.1.0 - Productionsqlline> !connect jdbc:oracle:thin:@localhost:1521:mydb scott tiger oracle.jdbc.driver.OracleDriver For example, to connect to an Oracle database, you might enter: URL to use. Consult your driver's documentation for details on the name of the database itself as part of the string. usually has the machine name of the database and the your database, but will always start with "jdbc:", and is specific to the JDBC driver that you are using for optionally by the driver class name). The JDBC URL connect to, followed by the username and password (followed with the JDBC URL of the database you are going to In order to do so, you need to use the "!connect" command, SQLLine is only useful once you are connected to a database. Connecting to a database commands. entering "!help" will display a list of all the available (if you are currently connected to a database). For example, commands (beginning with a "!" character), or a SQL statement reads "sqlline> ". From here, you can enter either SQLLine Once you have started SQLLine, you will a prompt that java -Djava.ext.dirs=/usr/share/java/ /usr/share/java/sqlline.jar Debian Linux), then you might run: /usr/share/java/ (this is typical for For example, if your sqllinedir is properties files options sqllinedir/sqlline.jar -Djava.ext.dirs=sqllinedir java SQLLine can be run with the following command: Running SQLLine Using SQLLine or unzipping. drivers require some installation, such as uncompressing sqllinedir. Note that some JDBC Download your database's JDBC driver files into sqllinedir. into Download the latest jline.jar from sqllinedir. Download sqlline.jar into will be referred to as sqllinedir. Create a new directory/folder where you like. Thisda+;¿‚`%ê©k' û Å ¹ ­ ‘ i ^ / ñ ß À ˜ ‹ J I A 9 1 ) !   é ¿ ± ¢ – Š o I >  Ã Š L ß Ó Ç º ¹ Ÿ { z W A " íÐÁ°”‚R?-袎xiI=ôç×È›gfPòñ·¶yYX%åÖÆ·©¨~a;-ÿâÓÒÑÀ‹R?-,à¡wgG;: Description on/off !autocommit Enable or disable automatic transaction commit mode autocommit 1 autocommit autocommit
1: jdbc:mysql://localhost/mydb>1 row affected (3.187 seconds)Executing SQL against: jdbc:mysql://localhost/mydb4 rows affected (0.004 seconds)Executing SQL against: jdbc:oracle:thin:@localhost:1521:mydb1: jdbc:mysql://localhost/mydb> !all DELETE FROM COMPANY; #1 open jdbc:mysql://localhost/mydb #0 open jdbc:oracle:thin:@localhost:1521:mydb2 active connections:1: jdbc:mysql://localhost/mydb> !list Example of "all" command
current connections. Execute the specified SQL against all the Description SQL statement !all Execute SQL against all active connections all 1 all all
Command Reference a selection of appropriate possibilities. will fill in the rest of the command, or else will display the TAB key when part of the way through typing a command popular shells as bash and tcsh. In general, hitting using the tab key. This will be familiar for users of such On UNIX systems, SQLLine allows command-line completion Command Completion 0: jdbc:oracle:thin:@localhost:1521:mydb>4 rows selected (0.012 seconds)+-----+| 4 || 3 || 2 || 1 |+-----+| ID |+-----+0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM MYTABLE; Issuing SQL commands For example: can begin SQL statements against the current connection. Once you are connected to a database, you Issuing SQL commands list command. open connections can be listed with the the go command. The currently all SQL statements will be executed) can be switched with of open connections. The "current" connection (against which multiple times will add the new connection to the list connect command at the same time. Issuing the (either the same database, or a different database) open SQLLine allows you to have multiple connections to databasesda-€Ég5úÜÏ¿°|n>=$# ô ã Ô Æ Å   ˆ g Y 0     ñ Ó Á ‘ ~ l k V C $  ú ê Ê ¾ ~ A  Ï • | o _ P !  â á   Ÿ P ²c21ýÑ¥yML  úòêâÚÒʪ€q`QCBäÖ­€nP>  ûúåÒ³Ÿ‰yYMïâÒÔ†A@ú»ºn-, at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:208) at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:180)java.sql.SQLException: ORA-00942: table or view does not existError: ORA-00942: table or view does not exist (state=42000,code=942)0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM BOGUS_TABLE; Example of "brief" command of stack traces when errors occur. Set verbose mode off. This will prevent printing Description !brief Enable terse output mode brief 1 brief brief
0: jdbc:oracle:thin:@localhost:1521:mydb>4 rows selected (0.012 seconds)+-----+| 4 || 3 || 2 || 1 |+-----+| ID |+-----+0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM MYTABLE;1 INSERT INTO MYTABLE (ID) VALUES (4)1 INSERT INTO MYTABLE (ID) VALUES (3)1 INSERT INTO MYTABLE (ID) VALUES (2)1 INSERT INTO MYTABLE (ID) VALUES (1)COUNT STATEMENTRunning batched SQL statements...0: jdbc:oracle:thin:@localhost:1521:mydb> !batch0: jdbc:oracle:thin:@localhost:1521:mydb> INSERT INTO MYTABLE (ID) VALUES (4);0: jdbc:oracle:thin:@localhost:1521:mydb> INSERT INTO MYTABLE (ID) VALUES (3);0: jdbc:oracle:thin:@localhost:1521:mydb> INSERT INTO MYTABLE (ID) VALUES (2);0: jdbc:oracle:thin:@localhost:1521:mydb> INSERT INTO MYTABLE (ID) VALUES (1);Batching SQL statements. Run "batch" again to execute the batch.0: jdbc:oracle:thin:@localhost:1521:mydb> !batch Example of "batch" command speed up execution. statements (e.g., for bulk data loading) in order to Databases can frequently optimize multiple batched be deferred until the batch command is issued again. the statement is issued, subsequent SQL statements will Start or execute a batch of SQL statements. The first time Description !batch Start or execute a batch of SQL statements batch 1 batch batch
1: jdbc:mysql://localhost/mydb>Autocommit status: false1: jdbc:mysql://localhost/mydb> !autocommit off Example of "autocommit" command changes to the database. command will need to be issued in order to commit any commit after it is issued. Otherwise, the on, every individual SQL statement will be committed Set autocommit mode on or off. When autocommit isda 1„Æ}(Ðr" ç ± ~ L K   Æ Å  ~ T E 4 %   ñ Ù ¸ ª d U T S B $  ñ Þ Ì Ë ¶ £ „ p Z J *  å Ï Â ² £ t f 6 5 ì뺹Œ‹|{ed[L;,öܹ«€cTSRA!ïÜÊÉ´¡€=)ãשœŒ}L>ÈVä«rqG8'  ãʨšpSDCB10 1 commit commit
0: jdbc:oracle:thin:@localhost:1521:mydb>+-------------+--------------+------------+------------+| EMPLOYEE | LAST_NAME | 12 | VARCHAR2 || EMPLOYEE | FIRST_NAME | 12 | VARCHAR2 || EMPLOYEE | ID | 3 | NUMBER |+-------------+--------------+------------+------------+| TABLE_NAME | COLUMN_NAME | DATA_TYPE | TYPE_NAME |+-------------+--------------+------------+------------+0: jdbc:oracle:thin:@localhost:1521:mydb> !columns EMPLOYEE Example of "columns" command List the columns in the specified table. Description table name !columns Display columns of a table columns 1 columns columns
sqlline>No active connectionssqlline> !listClosing: oracle.jdbc.driver.OracleConnection0: jdbc:oracle:thin:@localhost:1521:mydb> !close #0 open jdbc:oracle:thin:@localhost:1521:mydb1 active connection:0: jdbc:oracle:thin:@localhost:1521:mydb> !list Example of "close" command connection list. Close the current connection and remote it from the Description !close Close the active connection close 1 close close
0: jdbc:oracle:thin:@localhost:1521:mydb>Error: ORA-00942: table or view does not exist (state=42000,code=942)0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM BOGUS_TABLE;verbose: off0: jdbc:oracle:thin:@localhost:1521:mydb> !brief at sqlline.SqlLine.main(SqlLine.java:332) at sqlline.SqlLine.begin(SqlLine.java:634) at sqlline.SqlLine.dispatch(SqlLine.java:771) at sqlline.SqlLine$Commands.sql(SqlLine.java:3183) at oracle.jdbc.driver.OracleStatement.execute(OracleStatement.java:909) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2324) at oracle.jdbc.driver.OracleStatement.doExecuteQuery(OracleStatement.java:2110) at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteDescribe(TTC7Protocol.java:651) at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1451) at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:543)da )‚áÏ«˜†…p]=)ãלp@2 ø ÷ Þ Ý f G F   ó ò ° ¯ ƒ W + ÿ Ó ´ ³ ‰ z i Z L K $ ç Ù ® ‘ ‚ € o O = "  ý ü ç Ô ³ w 6õ°œ†vVJ.!ÒÄ`_Ë£t\[1"ôóÍ´’„Z=.-,üê¶£‘{hH4î⥘ˆyI; Иa)(dataDefinitionIgnoredInTransactions falsedataDefinitionCausesTransactionCommit trueallTablesAreSelectable falseallProceduresAreCallable false0: jdbc:oracle:thin:@localhost:1521:mydb> !dbinfo Example of "dbinfo" command List metadata information about the current connection. Description !dbinfo Provide information about the current database dbinfo 1 dbinfo dbinfo
0: jdbc:oracle:thin:@localhost:1521:mydb>Autocommit status: trueDriver: Oracle JDBC driver (version 9.0.1.0.0)JServer Release 9.2.0.1.0 - Production)With the Partitioning, OLAP and Oracle Data Mining optionsConnected to: Oracle (version Oracle9i Enterprise Edition Release 9.2.0.1.0 - Productionsqlline> !connect jdbc:oracle:thin:@localhost:1521:mydb scott tiger oracle.jdbc.driver.OracleDriver Example of "commit" command Connect to a database. Description driver class password username url !connect Connect to a database connect 1 connect connect
0: jdbc:oracle:thin:@localhost:1521:mydb>1 row selected (0.309 seconds)+--------------+-------------+------------+| 1 | Bob | Smith |+--------------+-------------+------------+| ID | FIRST_NAME | LAST_NAME |+--------------+-------------+------------+0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM EMPLOYEE;Commit complete (0.661 seconds)0: jdbc:oracle:thin:@localhost:1521:mydb> !commit1 row affected (1.254 seconds)0: jdbc:oracle:thin:@localhost:1521:mydb> INSERT INTO EMPLOYEE (ID, FIRST_NAME, LAST_NAME) VALUES (1, 'Bob', 'Smith');Autocommit status: false0: jdbc:oracle:thin:@localhost:1521:mydb> !autocommit off Example of "commit" command Commit the current transaction, if autocommit is off. Description !commit Commit the current transaction commitda (=ɵ¦mÅžj6 ½ L  á ­ v A Ø ¤ p 9  Ñ h 1 ü Ä [ 'ò£T·q5üÇz.ÝŽ?ù¨`Æ@ó¬bÃt(' LENGTH, LENGTHB, NLSSORT, UPPER, ASCII, INSTR, INSTRB, SUBSTR, SUBSTRB, TRANSLATE, REPLACE, RPAD, RTRIM, SOUNDEX, NLS,_LOWER, NLS,_UPPER, LTRIM, NLS,_INITCAP,getStringFunctions CHR, INITCAP, LOWER, LPAD, all_PL_SQL_reserved_ words PRIOR, OFFLINE, ONLINE, PCTFREE, NOCOMPRESS, NOWAIT, NUMBER, MINUS, MODE, NOAUDIT, LEVEL, LOCK, LONG, MAXEXTENTS, INITIAL, INTERSECT, IMMEDIATE, INCREMENT, INDEX, EXCLUSIVE, FILE, IDENTIFIED, COMPRESS, CONNECT, DATE, DROP, CLUSTER, COLUMN, COMMENT,getSQLKeywords ACCESS, ADD, ALTER, AUDIT,getSearchStringEscape //getSchemaTerm schemagetProcedureTerm procedure STDDEV,SUM,VARIANCE AVG,COUNT,GLB,LUB,MAX,MIN, SIN,SINH,SQRT,TAN,TANH,TRUNC, LN,LOG,MOD,POWER,ROUND,SIGN,getNumericFunctions ABS,CEIL,COS,COSH,EXP,FLOOR,getMaxUserNameLength 30getMaxTablesInSelect 0getMaxTableNameLength 30getMaxStatements 0getMaxStatementLength 65535getMaxSchemaNameLength 30getMaxRowSize 2000getMaxProcedureNameLength 30getMaxIndexLength 0getMaxCursorNameLength 0getMaxConnections 0getMaxColumnsInTable 1000getMaxColumnsInSelect 0getMaxColumnsInOrderBy 0getMaxColumnsInIndex 32getMaxColumnsInGroupBy 0getMaxColumnNameLength 30getMaxCharLiteralLength 2000getMaxCatalogNameLength 0getMaxBinaryLiteralLength 1000getIdentifierQuoteString "getExtraNameCharacters $#getDriverVersion 9.0.1.0.0getDriverName Oracle JDBC drivergetDriverMinorVersion 0getDriverMajorVersion 9getDefaultTransactionIsolation 2JServer Release 9.2.0.1.0 - ProductionWith the Partitioning, OLAP and Oracle Data Mining optionsgetDatabaseProductVersion Oracle9i Enterprise Edition Release 9.2.0.1.0 - ProductiongetDatabaseProductName OraclegetCatalogTermgetCatalogSeparatordoesMaxRowSizeIncludeBlobs trueda.@¸r3å™X ¼ u - á • ]  Î – ^ ' ï ·  H  Ø   i 2úËTä­u=Í•^'ð¹HÚ£l5þÇY"ë³|D Öžf.-supportsOpenStatementsAcrossCommit falsesupportsOpenCursorsAcrossRollback falsesupportsOpenCursorsAcrossCommit falsesupportsNonNullableColumns truesupportsMultipleTransactions truesupportsMultipleResultSets falsesupportsMixedCaseQuotedIdentifiers truesupportsMixedCaseIdentifiers falsesupportsMinimumSQLGrammar truesupportsLimitedOuterJoins truesupportsLikeEscapeClause truesupportsIntegrityEnhancementFacility truesupportsGroupByUnrelated truesupportsGroupByBeyondSelect truesupportsGroupBy truesupportsFullOuterJoins truesupportsExtendedSQLGrammar truesupportsExpressionsInOrderBy truesupportsDifferentTableCorrelationNames truesupportsDataManipulationTransactionsOnly truesupportsDataDefinitionAndDataManipulationTransactionstruesupportsCorrelatedSubqueries truesupportsCoreSQLGrammar truesupportsConvert truesupportsColumnAliasing truesupportsCatalogsInTableDefinitions falsesupportsCatalogsInProcedureCalls falsesupportsCatalogsInPrivilegeDefinitions falsesupportsCatalogsInIndexDefinitions falsesupportsCatalogsInDataManipulation falsesupportsBatchUpdates truesupportsANSI92IntermediateSQL falsesupportsANSI92FullSQL falsesupportsANSI92EntryLevelSQL truesupportsAlterTableWithDropColumn falsesupportsAlterTableWithAddColumn truestoresUpperCaseQuotedIdentifiers falsestoresUpperCaseIdentifiers truestoresMixedCaseQuotedIdentifiers truestoresMixedCaseIdentifiers falsestoresLowerCaseQuotedIdentifiers falsestoresLowerCaseIdentifiers falsenullsAreSortedLow truenullsAreSortedHigh falsenullsAreSortedAtStart falsenullsAreSortedAtEnd falsenullPlusNonNullIsNull trueisReadOnly falseisCatalogAtStart falsegetUserName MYDBgetURL jdbc:oracle:thin:@localhost:1521:mydb TRUNC NEXT_DAY, ROUND, SYSDATE, MONTHS_BETWEEN, NEW_TIME,getTimeDateFunctions ADD_MONTHS, LAST_DAY, USER, USERENV, VSIZE LEAST, LEAST_UB, NVL, UID,getSystemFunctions DUMP, GREATEST, GREATEST_LB, TO_SINGLE_BYTE TO_MULTI_BYTE, TO_NUMBER, TO_CHAR, TO_DATE, TO_LABEL, ROWIDTOCHAR, HEXTORAW, RAWTOHEX, CHARTOROWID, CONVERT,daàrÈ‘Z#ìµ~G Ù ¢ k 4 ý Æ X ! ê ³ { C B  ø é Û Ú ² — s e 9  û Ú È ² Ÿ Œ w d BÿëÕÔĤ˜‡O0ûÖɹªxj-,ç¢]ÓŽIHþýîà߸ž{mB%ãѬ™‡†q^=)ã×°£“„SEàReally drop every table in the database? (y/n) y0: jdbc:oracle:thin:@localhost:1521:mydb> !dropall Example of "dropall" command Drop every table in the database. Description !dropall Drop all tables in the database dropall 1 dropall dropall
0: jdbc:oracle:thin:@localhost:1521:mydb>+--------------+------------+-------------+-----------+------------+| MYDB | EMPLOYEE | LAST_NAME | 12 | VARCHAR2 || MYDB | EMPLOYEE | FIRST_NAME | 12 | VARCHAR2 || MYDB | EMPLOYEE | ID | 3 | NUMBER |+--------------+------------+-------------+-----------+------------+| TABLE_SCHEM | TABLE_NAME | COLUMN_NAME | DATA_TYPE | TYPE_NAME |+--------------+------------+-------------+-----------+------------+0: jdbc:oracle:thin:@localhost:1521:mydb> !describe EMPLOYEE Example of "describe" command (if no argument is specified). or tables an argument is specified) columns (if Synonym for Description table name !describe Describe a table describe 1 describe describe
0: jdbc:oracle:thin:@localhost:1521:mydb>usesLocalFiles falseusesLocalFilePerTable falsesupportsUnionAll truesupportsUnion truesupportsTransactions truesupportsTableCorrelationNames truesupportsSubqueriesInQuantifieds truesupportsSubqueriesInIns truesupportsSubqueriesInExists truesupportsSubqueriesInComparisons truesupportsStoredProcedures truesupportsSelectForUpdate truesupportsSchemasInTableDefinitions truesupportsSchemasInProcedureCalls truesupportsSchemasInPrivilegeDefinitions truesupportsSchemasInIndexDefinitions truesupportsSchemasInDataManipulation truesupportsPositionedUpdate truesupportsPositionedDelete truesupportsOuterJoins truesupportsOrderByUnrelated truesupportsOpenStatementsAcrossRollback falseda^ÿß¾sJIÿïÀ¬}I. ø ê é ½ ž v h 8  ù Ô Â “ € n m X E  Ü È ² ¢ ‚ v > (  ü Æ ¸ „ ƒ A ÿ ½ { 9 8  úëÝܺ¥‡yS6'&%ù级•”lPòÜ̬ wjZKáàÊ–lk;:éèÙȹ«ª†oOAüíìëÚ½«zhgR?! ÷çÇ»Š}m^] Display information about allowed commands. Description !help Display help information help 1 help help
0: jdbc:oracle:thin:@localhost:1521:mydb>1: jdbc:mysql://localhost/mydb> !go 00: jdbc:oracle:thin:@localhost:1521:mydb> !go 1 #1 open jdbc:mysql://localhost/mydb #0 open jdbc:oracle:thin:@localhost:1521:mydb2 active connections:0: jdbc:oracle:thin:@localhost:1521:mydb> !list Example of "go" command Switch to the specified connection. Description connection number !go Change to a different active connection go 1 go go
0: jdbc:hsqldb:db-hypersonic>+----------------+---------------+----------------+-------------+| | COMPANY | COMPANY_ID | |+----------------+---------------+----------------+-------------+| PKTABLE_SCHEM | PKTABLE_NAME | PKCOLUMN_NAME | FKTABLE_CAT |+----------------+---------------+----------------+-------------+0: jdbc:hsqldb:db-hypersonic> !exportedkeys COMPANY Example of "exportedkeys" command specified table. List all the foreign keys that are exported by the Description table name !exportedkeys List exported foreign keys for a database exportedkeys 1 exportedkeys exportedkeys
with extreme caution. database (subject to access restrictions). Use This command will destroy all data in the Warning on using "dropall"
0: jdbc:oracle:thin:@localhost:1521:mydb>5/5 DROP TABLE COMPANYEMPLOYEES;4/5 DROP TABLE EMPLOYEE_PROJECTS;3/5 DROP TABLE PROJECTS;2/5 DROP TABLE EMPLOYEE;1/5 DROP TABLE COMPANY;daåsÒĵ´d4ûÔ•V Õ – s 9 ô Ä ‘ c  ß › l > ÿ ¿ q -  ß ³ y 3è±yGìÄŽhg-,"!òäã¼¢qF)çÕ´¡ŽyfE1 êÞ¼¯Ÿ_Q?>èÍÀ¿µ´¥”…wvJ+õŨ™˜—†aO  ûúåä List imported foreign keys for a database importedkeys 1 importedkeys importedkeys
sqlline> 5. !tables 4. SELECT * FROM PCPOINT;3. !outputformat vertical 2. SELECT * FROM PCPOINT;1. !outputformat xmlelements sqlline> !history Example of "history" command Display the command history. Description
!history Display the command history history 1 history history
sqlline> Comments, bug reports, and patches go to mwp1@cornell.edu!verbose Set verbose mode on!tables List all the tables in the database!sql Execute a SQL command!set Set a sqlline variable!script Start saving a script to a file!scan Scan for installed JDBC drivers!save Save the current variabes and aliases!run Run a script from the specified file!rollback Roll back the current transaction (if autocommit is off)!rehash Fetch table and column names for command completion!record Record all output to the specified file!reconnect Reconnect to the database!quit Exits the program!procedures List all the procedures!primarykeys List all the primary keys for the specified table!properties Connect to the database specified in the properties file(s) (table,vertical,csv,tsv,xmlattrs,xmlelements)!outputformat Set the output format for displaying results!metadata Obtain metadata information!list List the current connections!isolation Set the transaction isolation for this connection!indexes List all the indexes for the specified table!importedkeys List all the imported keys for the specified table!history Display the command history!help Print a summary of command usage!go Select the current connection!exportedkeys List all the exported keys for the specified table!dropall Drop all tables in the current database!describe Describe a table!dbinfo Give metadata information about the database!connect Open a new connection to the database.!commit Commit the current transaction (if autocommit is off)!columns List all the columns for the specified table!close Close the current connection to the database!brief Set verbose mode off!batch Start or execute a batch of statements!autocommit Set autocommit mode on or off!all Execute the specified SQL against all the current connectionssqlline> !help Example of "help" commanddaöríÇ„pZJ*êÐó¤n`+* è ¦ d " à ß Á ² ¡ ’ „ ƒ \ B   æ É º ¹ ¸ § ‡ u T A / .   å ¢ Ž x h H <  ø è Ù ¨ š ^ ] ψAú³l%$úëÚ˽¼“wRDúëê騶¤bO=<'ñ©•oOCË û칫YX÷öõError: READ_COMMITTED and SERIALIZABLE are the only valid transaction levels (state=,code=17030)0: jdbc:oracle:thin:@localhost:1521:mydb> !isolation TRANSACTION_READ_UNCOMMITTED Example of "isolation" command http://java.sun.com/j2se/1.3/docs/api/java/sql/Connection.html#field_detail. a description of the different isolation levels, see Set the isolation level for the current transaction. For Description
isolation level !isolation Set the transaction isolation mode for the active connection isolation 1 isolation isolation
0: jdbc:oracle:thin:@localhost:1521:mydb>+-------------+-------------+-----------------+-------+--------------+| EMPLOYEE | 1 | LAST_NAME | 1 | LAST_NAME || EMPLOYEE | 1 | FIRST_NAME | 1 | FIRST_NAME || EMPLOYEE | 0 | SYS_C003115849 | 1 | ID || EMPLOYEE | 0 | | 0 | |+-------------+-------------+-----------------+-------+--------------+| TABLE_NAME | NON_UNIQUE | INDEX_NAME | TYPE | COLUMN_NAME |+-------------+-------------+-----------------+-------+--------------+0: jdbc:oracle:thin:@localhost:1521:mydb> !indexes EMPLOYEE Example of "indexes" command List all the indexes on the specified table name. Description
table name !indexes Display indexes for a table indexes 1 indexes indexes
0: jdbc:hsqldb:db-hypersonic>+----------------+---------------+----------------+-------------+| | COMPANY | COMPANY_ID | |+----------------+---------------+----------------+-------------+| PKTABLE_SCHEM | PKTABLE_NAME | PKCOLUMN_NAME | FKTABLE_CAT |+----------------+---------------+----------------+-------------+0: jdbc:hsqldb:db-hypersonic> !importedkeys EMPLOYEE Example of "importedkeys" command the specified table. List all the foreign keys that are imported by Description
table name !importedkeys daNl²±€VG6'ôݽ¯‡j[ZYH+ õ â Ð Ï º § ‰ u _ O / # ü ï ß Ð ¢ ” d c M  ï î Ä µ ¤ • ‡ † ^ C   å È ¹ ¸ · ¦ … s J 7 %  ý Û ˜ L 8 " òæ©sr3ûVI9*øêž˜—WVºlЂ4æ˜Jü®`| FLOAT | 6 | 63 | | || NUMBER | 5 | 5 | | || NUMBER | 4 | 10 | | || NUMBER | 2 | 38 | | || CHAR | 1 | 2000 | ' | ' || LONG | -1 | 2147483647 | ' | ' || RAW | -3 | 2000 | ' | ' || LONG RAW | -4 | 2147483647 | ' | ' || NUMBER | -5 | 38 | | || NUMBER | -6 | 3 | | || NUMBER | -7 | 1 | | |+------------+------------+-------------+-----------------+-----------------+| TYPE_NAME | DATA_TYPE | PRECISION | LITERAL_PREFIX | LITERAL_SUFFIX |+------------+------------+-------------+-----------------+-----------------+0: jdbc:oracle:thin:@localhost:1521:mydb> !metadata getTypeInfotrue0: jdbc:oracle:thin:@localhost:1521:mydb> !metadata supportsSelectForUpdate Example of "metadata" command http://java.sun.com/j2se/1.3/docs/api/java/sql/DatabaseMetaData.html. For information on available metadata methods, see Use "" for a blank String, and null for a null parameter. connection. refpurpose are separated by spaces. Execute an arbitrary metadata method agains the current Description params methodname !metadata Invoke arbitrary metadata commands metadata 1 metadata metadata
0: jdbc:oracle:thin:@localhost:1521:mydb> #1 open jdbc:mysql://localhost/mydb #0 open jdbc:oracle:thin:@localhost:1521:mydb2 active connections:0: jdbc:oracle:thin:@localhost:1521:mydb> !list Example of "list" command List all the current connections. Description
!list Display all active connections list 1 list list
0: jdbc:oracle:thin:@localhost:1521:mydb>Transaction isolation: TRANSACTION_SERIALIZABLE0: jdbc:oracle:thin:@localhost:1521:mydb> !isolation TRANSACTION_SERIALIZABLEdaÄj²dÈz, Þ B A í ì ž P  ´ f  Ê | . -  ô ã Ô Æ Å ™ z R D ÷èçæÕ°žlYGF1ø´ Š‰yYMÖ¢‹~n_(Ü›~aD' íг“„sd*ÛšŒzyk[ZL<;-öç×È“…IôèÞÔÄÃ'4','Microsoft''3','IBM''2','Sun''1','Apple''COMPANY_ID','NAME'0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY;0: jdbc:oracle:thin:@localhost:1521:mydb> !outputformat csv Example of CSV output formatting 4 rows selected (0.011 seconds)NAME MicrosoftCOMPANY_ID 4NAME IBMCOMPANY_ID 3NAME SunCOMPANY_ID 2NAME AppleCOMPANY_ID 10: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY;0: jdbc:oracle:thin:@localhost:1521:mydb> !outputformat vertical Example of vertical output formatting 4 rows selected (0.012 seconds)+-------------+------------+| 4 | Microsoft || 3 | IBM || 2 | Sun || 1 | Apple |+-------------+------------+| COMPANY_ID | NAME |+-------------+------------+0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY;0: jdbc:oracle:thin:@localhost:1521:mydb> !outputformat table Example of table output formatting parseable format. either a visually pleasing format or an easily This is useful for saving output from SQL statements to Set the mode for displaying results from statements. Description
format name !outputformat Change the method for displaying SQL results outputformat 1 outputformat outputformat
0: jdbc:oracle:thin:@localhost:1521:mydb>+----------------+------------------+------------------------+--------------+| DBMS_JAVA | SYS | LOADJAVA | RESOLVER || DBMS_JAVA | SYS | LOADJAVA | OPTIONS || DBMS_JAVA | SYS | LOADJAVA | OPTIONS || XMLPARSER | SYS | GETJAVARELEASEVERSION | || DBMS_JAVA | SYS | DROPJAVA | OPTIONS |+----------------+------------------+------------------------+--------------+| PROCEDURE_CAT | PROCEDURE_SCHEM | PROCEDURE_NAME | COLUMN_NAME |+----------------+------------------+------------------------+--------------+0: jdbc:oracle:thin:@localhost:1521:mydb> !meta getProcedureColumns null % %JAVA% %+------------+------------+-------------+-----------------+-----------------+| REF | 2006 | 0 | ' | ' || CLOB | 2005 | 4294967295 | ' | ' || BLOB | 2004 | 4294967295 | | || ARRAY | 2003 | 0 | ' | ' || STRUCT | 2002 | 0 | ' | ' || DATE | 93 | 7 | | || VARCHAR2 | 12 | 4000 | ' | ' || REAL | 7 | 63 | | |da'àÑÁ²}o3òÛ˽¯›{l\M À  p E  ó Ä ´ ” … u f )  × — ˆ z U 8 )  ö Û Ì ¾ ™ ~ o a <  ü Ý ³ ¤ ” … w v K - øÉ¬œ›ŠfT#þýèÕ°mYC3ϲ£n`-,è¤`Ø×¹ª™Š|{Q4Òµ¦¥¤“p^B/ôÐmWG'& Description
procedure name pattern !procedures List stored procedures procedures 1 procedures procedures
0: jdbc:hsqldb:db-hypersonic>+--------------+-------------+--------------+----------+----------+| | COMPANY | COMPANY_ID | 1 | SYS_PK_C |+--------------+-------------+--------------+----------+----------+| TABLE_SCHEM | TABLE_NAME | COLUMN_NAME | KEY_SEQ | PK_N |+--------------+-------------+--------------+----------+----------+0: jdbc:hsqldb:db-hypersonic> !primarykeys COMPANY Example of "primarykeys" command List all the primary keys for the specified table. Description
table name !primarykeys Display the primary key columns for a table primarykeys 1 primarykeys primarykeys
0: jdbc:oracle:thin:@localhost:1521:mydb>4 rows selected (0.02 seconds)</resultset> </result> <NAME>Microsoft</NAME> <COMPANY_ID>4</COMPANY_ID> <result> </result> <NAME>IBM</NAME> <COMPANY_ID>3</COMPANY_ID> <result> </result> <NAME>Sun</NAME> <COMPANY_ID>2</COMPANY_ID> <result> </result> <NAME>Apple</NAME> <COMPANY_ID>1</COMPANY_ID> <result><resultset>0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY0: jdbc:oracle:thin:@localhost:1521:mydb> !outputformat xmlelements Example of XML element output formatting 4 rows selected (0.012 seconds)</resultset> <result COMPANY_ID="4" NAME="Microsoft"/> <result COMPANY_ID="3" NAME="IBM"/> <result COMPANY_ID="2" NAME="Sun"/> <result COMPANY_ID="1" NAME="Apple"/><resultset>0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY;0: jdbc:oracle:thin:@localhost:1521:mydb> !outputformat xmlattr Example of XML attribute output formatting 4 rows selected (0.013 seconds)'4' 'Microsoft''3' 'IBM''2' 'Sun''1' 'Apple''COMPANY_ID' 'NAME'0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY;0: jdbc:oracle:thin:@localhost:1521:mydb> !outputformat tsv Example of TSV output formatting 4 rows selected (0.012 seconds)da  {ôº”‡wh4&éè¯v= Ë ’ ‘ g X G 8 * ) ( þ á » ­  b S R Q @  ß ¿ ¬ š ™ „ q M  ü æ Ö ¶ ª ~ G   ð ¿ ¦ V 'òÙÂ_H/ᱚl_Síׯ€SI콃aTD5óÍÌ¢¡kj@ÙÁŽm^M>0/ ôÔÆžrqp_B0 
Exit SQLLine quit 1 quit quit
0: jdbc:mysql://localhost/mydb> Transaction isolation: TRANSACTION_READ_COMMITTEDAutocommit status: trueDriver: MySQL-AB JDBC Driver (version 3.0.8-stable ( $Date: 2005/08/06 00:39:24 $, $Revision: 1.8 $ ))Connected to: MySQL (version 3.23.52-log)Enter password for jdbc:mysql://localhost/mydb: *****Connecting to jdbc:mysql://localhost/mydbsqlline> !properties test.properties Example of "properties" command be used for the connection. "ConnectionUserName", and "ConnectionPassword" will "ConnectionURL", "ConnectionDriverName", Furthermore, any properties that end with "javax.jdo.option.ConnectionPassword". and "javax.jdo.option.ConnectionUserName", "javax.jdo.option.ConnectionDriverName", "javax.jdo.option.ConnectionURL", properties are use JDO semantics for the properties. These The key names in the properties file can also prompt for it. database. If unspecified, SQLLine will password: the password to use to connect to the prompt for it. database. If unspecified, SQLLine will user: the username to use to connect to the scan the CLASSPATH for an appropriate driver unspecifed, SQLLine with automatically driver: the driver class that handles the URL. If url: the database URL to which to connect expected to have the following values: specified properties file. The properties file is Connect to the database defined in the Description
file !properties specified properties file. Connect to the database defined in the properties 1 properties properties
0: jdbc:oracle:thin:@localhost:1521:mydb>+----------------+------------------+------------------+| WK_ADM | WKSYS | SET_JDBC_DRIVER || WK_ADM | WKSYS | GET_JDBC_DRIVER |+----------------+------------------+------------------+| PROCEDURE_CAT | PROCEDURE_SCHEM | PROCEDURE_NAME |+----------------+------------------+------------------+0: jdbc:oracle:thin:@localhost:1521:mydb> !procedures %JDBC% Example of "procedures" command exposed by the current database. Display a list of all the stored procedures that are dah“îíØÅ§“}|lL@- ÎÀœ›xiXI;:9 ô Ï Á ” w h g f U 3 ! ú ç Õ Ô ¿ ¬ ‰ u _ O / # û î Þ Ï œ Ž Y X   è ç Ž S + ü ä ã ¹ ª ™ Š | { U <  âŶµ´£„r@-òÒ|fV6*íàÐÁ‘ƒ>=å䣆iL/õØ»›šhgTS) úìëŬŠ|R5&%$ôâ£~}hg
Obtain a list of all tables and columns from the database rehash 1 rehash rehash
0: jdbc:oracle:thin:@localhost:1521:mydb>Recording stopped.0: jdbc:oracle:thin:@localhost:1521:mydb> !record4 rows selected (0.011 seconds)+-------------+------------+| 2 | Sun || 1 | Apple || 4 | Microsoft || 3 | IBM |+-------------+------------+| COMPANY_ID | NAME |+-------------+------------+0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY;Saving all output to "/tmp/mysession.out". Enter "record" with no arguments to stop it.0: jdbc:oracle:thin:@localhost:1521:mydb> !record /tmp/mysession.out Example of "record" command Save all output from the session to the specified file. Description
file name !record Begin recording all output from SQL commands record 1 record record
0: jdbc:oracle:thin:@localhost:1521:mydb>Autocommit status: trueDriver: Oracle JDBC driver (version 9.0.1.0.0)JServer Release 9.2.0.1.0 - Production)With the Partitioning, OLAP and Oracle Data Mining optionsConnected to: Oracle (version Oracle9i Enterprise Edition Release 9.2.0.1.0 - ProductionClosing: oracle.jdbc.driver.OracleConnection@4428d3Reconnecting to "jdbc:oracle:thin:@localhost:1521:mydb"...0: jdbc:oracle:thin:@localhost:1521:mydb> !reconnect Example of "reconnect" command Reconnect to the current database. Description
!reconnect Reconnect to the current database reconnect 1 reconnect reconnect
Closing: org.hsqldb.jdbcConnection0: jdbc:hsqldb:db-hypersonic> !quit Example of "reconnect" command Exit SQLLine. Description
!quit da$xí͹£¢’rf*í¯¡eM@0! ñ ã ½ ¼ ` P K J , +  û Í ¿ ³ t g X G 8 * )  æ  ´ ˆ k \ [ Z I (  ï Ü Ê É ´ ¡  k U E %  Ü Ï ¿ ° ~ p 6 5  ÚÙ¼Ÿ‚eH+ñÑБpo.-ýåÍ­¬xwUTõØ»ždG*  àÑÀ±£¢iJ<øéèçÖº¨ŠweP= ÞÊ´¤„xw Description file name !run Execute a command script run 1 run run
0: jdbc:oracle:thin:@localhost:1521:mydb>4 rows selected (0.01 seconds)+-------------+------------+| 2 | Sun || 1 | Apple || 4 | Microsoft || 3 | IBM |+-------------+------------+| COMPANY_ID | NAME |+-------------+------------+0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY;Rollback complete (0.016 seconds)0: jdbc:oracle:thin:@localhost:1521:mydb> !rollbackNo rows selected (0.01 seconds)+-------------+-------++-------------+-------+| COMPANY_ID | NAME |+-------------+-------+0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY;4 rows affected (0.004 seconds)0: jdbc:oracle:thin:@localhost:1521:mydb> DELETE FROM COMPANY;4 rows selected (0.011 seconds)+-------------+------------+| 2 | Sun || 1 | Apple || 4 | Microsoft || 3 | IBM |+-------------+------------+| COMPANY_ID | NAME |+-------------+------------+0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY;Autocommit status: false0: jdbc:oracle:thin:@localhost:1521:mydb> !autocommit off Example of "rollback" command Rollback the current transaction, if autocommit is off. Description
!rollback Roll back the current transaction rollback 1 rollback rollback
This operation can be extremely slow for some databases. Warning on using "rehash" 0: jdbc:hsqldb:db-hypersonic>Done7/7 (100%) DoneBuilding list of tables and columns for tab-completion (set fastconnect to true to skip)...0: jdbc:hsqldb:db-hypersonic> !rehash Example of "rehash" command option is enabled. fastconnect when the of SQL statements. This is done automatically on connect in order to include them in the list for tab-completion Get a list of all tables and columns from the database Description
!rehash da6 pÔZ!åÉ‹fYI: ÿ Ð ‰ h 2  ã È ” u ;  ± R 5 ù Ø d G Û ¼ c Åv'ع›š‹zk]\8!óË®ŸžŒo];(íÏ»¥•uiF9)ìÞ®­ji?0ÝÆ¦˜pSDCB1ÜÉ·¶¡Žp\F6  Description !scan Scan class path for JDBC drivers scan 1 scan scan
0: jdbc:oracle:thin:@localhost:1521:mydb>Saving preferences to: /Users/mprudhom/.sqlline/sqlline.properties0: jdbc:oracle:thin:@localhost:1521:mydb> !save Example of "save" command Save the current preferences. Description
!save Save the current preferences save 1 save save
0: jdbc:hsqldb:db-hypersonic>1 row selected (0.001 seconds)+------------+-----------+--------------+-------------+------------+---------+| 4 | Microsoft | 234 | William | Gates | 4 |+------------+-----------+--------------+-------------+------------+---------+| COMPANY_ID | NAME | ID | FIRST_NAME | LAST_NAME | COMPANY |+------------+-----------+--------------+-------------+------------+---------+11/11 SELECT * FROM COMPANY,EMPLOYEE WHERE EMPLOYEE.COMPANY = COMPANY.COMPANY_ID;1 row affected (0.001 seconds)10/11 INSERT INTO EMPLOYEE (ID, FIRST_NAME, LAST_NAME, COMPANY) VALUES (234, 'William', 'Gates', 4);No rows affected (0 seconds)9/11 ALTER TABLE EMPLOYEE ADD CONSTRAINT EMP_COMPANY FOREIGN KEY (COMPANY) REFERENCES COMPANY (COMPANY_ID);No rows affected (0.001 seconds)8/11 CREATE INDEX LAST_NAME ON EMPLOYEE(LAST_NAME);No rows affected (0 seconds)7/11 CREATE INDEX FIRST_NAME ON EMPLOYEE(FIRST_NAME);No rows affected (0.004 seconds)6/11 CREATE TABLE EMPLOYEE (ID INT, FIRST_NAME VARCHAR(255), LAST_NAME VARCHAR(255), COMPANY INT);1 row affected (0.015 seconds)5/11 INSERT INTO COMPANY VALUES (4, 'Microsoft');1 row affected (0.001 seconds)4/11 INSERT INTO COMPANY VALUES (3, 'IBM');1 row affected (0 seconds)3/11 INSERT INTO COMPANY VALUES (2, 'Sun');1 row affected (0 seconds)2/11 INSERT INTO COMPANY VALUES (1, 'Apple');No rows affected (0.001 seconds)1/11 CREATE TABLE COMPANY (COMPANY_ID INT, NAME VARCHAR(255));0: jdbc:hsqldb:db-hypersonic> !run example.sql Example of "run" command set to true. force preference is be aborted, unless the errors occur while running the script, the script will "#" are interpreted as comments and ignored. If any statements or SQLLine commands. Lines beginning with The file should consist of individual SQL Run the individual commands specified in the file name.daÇiÊŒo`2$üݬxG ß ª o :  à ® v E Å „ = ü ½ • _ / ÷ ¾ Œ R #ðÅ“\2 ⪩ ‘€qcb<#óɬœ›ŠkY3  øåÅ„pZJ*æµxM ûì¼®rqãâÉÈ“’uX;äÇÆ| 4 | Microsoft || 3 | IBM || 2 | Sun || 1 | Apple |+-------------+------------+| COMPANY_ID | NAME |+-------------+------------+0: jdbc:hsqldb:db-hypersonic> SELECT * FROM COMPANY;Autocommit status: false0: jdbc:hsqldb:db-hypersonic> !autocommit offSaving command script to "/tmp/mysession.script". Enter "script" with no arguments to stop it.0: jdbc:hsqldb:db-hypersonic> !script /tmp/mysession.script Example of "script" command run command. Saved scripts can be re-run using the by entering the script command again with no arguments. file. Once scripting on, it can be finished Start saving all commands entered to the specified Description
filename !script Save executed commands to a file script 1 script script
sqlline>yes 0.9 org.sourceforge.jxdbcon.JXDBConDriverno 7.3 org.postgresql.Driverno 1.7 org.hsqldb.jdbcDriverno 3.0 org.gjt.mm.mysql.Driverno 3.26 org.enhydra.instantdb.jdbc.idbDriveryes 1.0 oracle.jdbc.driver.OracleDriveryes 1.0 oracle.jdbc.OracleDriverno 0.5 net.sourceforge.jtds.jdbc.Driverno 2.0 interbase.interclient.Driveryes 1.0 in.co.daffodil.db.jdbc.DaffodilDBDriverno 5.5 com.sybase.jdbc2.jdbc.SybDriveryes 4.4 com.pointbase.jdbc.jdbcUniversalDriveryes 4.4 com.pointbase.jdbc.jdbcEmbeddedDriveryes 4.4 com.pointbase.jdbc.jdbcDriverno 3.0 com.mysql.jdbc.NonRegisteringDriverno 3.0 com.mysql.jdbc.Driveryes 2.2 com.microsoft.jdbc.sqlserver.SQLServerDriveryes 3.2 com.merant.datadirect.jdbc.sybase.SybaseDriveryes 3.2 com.merant.datadirect.jdbc.sqlserver.SQLServerDriveryes 3.2 com.merant.datadirect.jdbc.oracle.OracleDriveryes 3.2 com.merant.datadirect.jdbc.informix.InformixDriveryes 3.2 com.merant.datadirect.jdbc.db2.DB2Driveryes 2.2715 com.jnetdirect.jsql.JSQLDriverno 0.2 com.internetcds.jdbc.tds.SybaseDriverno 0.2 com.internetcds.jdbc.tds.Driveryes 2.21 com.informix.jdbc.IfxDriveryes 1.0 com.ibm.db2.jcc.DB2Driveryes 3.2 com.ddtek.jdbc.sybase.SybaseDriveryes 3.2 com.ddtek.jdbc.sqlserver.SQLServerDriveryes 3.2 com.ddtek.jdbc.oracle.OracleDriveryes 3.2 com.ddtek.jdbc.informix.InformixDriveryes 3.2 com.ddtek.jdbc.db2.DB2Driveryes 7.1 COM.ibm.db2.jdbc.net.DB2Driverno 1.0 COM.cloudscape.core.RmiJdbcDriverno 4.0 COM.cloudscape.core.JDBCDriverCompliant Version Driver Class35 driver classes foundsqlline> !scan Example of "scan" command JDBC drivers, and prints the class names of the drivers. Scans all the jar files in the CLASSPATH for anyda.vãÃÂjiJI#"ßÞŸž€q`QCB ê Ü µ ˜ ‰ ˆ ‡ v Z H 2  ÷ ä Ç „ F 2  ì à £ j : Ñ š } n A 3  ø ç Ø Ê É ¦ q c <    ýáÏ©–„ƒn[>üèÒ¢–Xþï´|{[Z<- ÿþØ¿eH987&õ̹§¦‘~^J4$øÈ¯¢’ƒSEÄvu| TABLE_CAT | TABLE_SCHEM | TABLE_NAME | TABLE_TYPE |+------------+--------------+---------------------------------+-------------+0: jdbc:oracle:thin:@localhost:1521:mydb> !tables Example of "tables" command current connection. List all the tables in the database of the Description
!tables List all the tables in the database tables 1 tables tables
0: jdbc:hsqldb:db-hypersonic>4 rows affected (0.005 seconds)0: jdbc:hsqldb:db-hypersonic> !sql DELETE FROM COMPANY; Example of "sql" command entering the statement by itself from the command line. Issue the specified SQL statement. This is equivalent to Description
statement !sql Execute a SQL against a database sql 1 sql sql
0: jdbc:hsqldb:db-hypersonic> !set color on Example of "set" command save command. saved for future SQLLine session eith the immediately saved. Otherwise, changed setting can be on, then this will cause preferences to be autosave is Set the specified preference to the specified value. If Description
value preference !set Set a preference set 1 set set
0: jdbc:hsqldb:db-hypersonic>Script closed. Enter "run /tmp/mysession.script" to replay it.0: jdbc:hsqldb:db-hypersonic> !scriptCommit complete (0 seconds)0: jdbc:hsqldb:db-hypersonic> !commit1 row affected (0.005 seconds)0: jdbc:hsqldb:db-hypersonic> UPDATE COMPANY SET NAME='Apple, Inc.' WHERE NAME='Apple';4 rows selected (0.001 seconds)+-------------+------------+daÚj²dÈÇŽ}n`_8 û í  ¥ – • ” ƒ c Q 6 #   û è Ç ³ m a - ð Õ È ¸ © x j % $ Þ Ý ª © œ W V  Ñ Ð „ C Àkµe*ôÁŽdUD5'&%ý×´–‹@Êf=ȱ¥™x\Qý¾€TòæÚÙ Defaults to false. save command. need to be explicitely saved using the the preferences to be saved. Otherwise, preferences will set command will cause to preferences using the When set to true, any changes autosave command instead. autocommit a connection that is already open and active, use the To change the autocommit status for Defaults to true. rolled back. committed or set, otherwise, transactions will need to be explicitely If true, then new connections will have autocommit autocommit Parameter Reference
0: jdbc:oracle:thin:@localhost:1521:mydb> at sqlline.SqlLine.main(SqlLine.java:332) at sqlline.SqlLine.begin(SqlLine.java:634) at sqlline.SqlLine.dispatch(SqlLine.java:771) at sqlline.SqlLine$Commands.sql(SqlLine.java:3183) at oracle.jdbc.driver.OracleStatement.execute(OracleStatement.java:909) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2324) at oracle.jdbc.driver.OracleStatement.doExecuteQuery(OracleStatement.java:2110) at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteDescribe(TTC7Protocol.java:651) at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1451) at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:543) at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:208) at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:180)java.sql.SQLException: ORA-00942: table or view does not existError: ORA-00942: table or view does not exist (state=42000,code=942)0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM BOGUS_TABLE;verbose: on0: jdbc:oracle:thin:@localhost:1521:mydb> !verboseError: ORA-00942: table or view does not exist (state=42000,code=942)0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM BOGUS_TABLE; Example of "verbose" command
of debug information. to be printed when errors occur, and enabled outputting Enable verbose mode, which causes stack traces Description !verbose Enable verbose output verbose 1 verbose verbose
0: jdbc:oracle:thin:@localhost:1521:mydb>+------------+--------------+---------------------------------+-------------+| | MYDB | EMPLOYEE | TABLE || | MYDB | COMPANY | TABLE |+------------+--------------+---------------------------------+-------------+da5ÝeâɾŽi/ûÐĸ”uj3 Ù ™ [  ð µ ©  f [ 0  Ö ˜ [ 2 ß ´ ¨ œ u S H å ¦ „ x T 5 *í³sg[7 â¯y?ÒŸth\:Þ§p8" ãÁ¶|I õéݼ •\@Ç¡•‰dD9ýÝÜ see the information on the The format for how results are displayed. For details, outputformat current width, falls back to 80. Defaults to attempting to query the terminal for the outputformat. when using the "table" The maximum width to display before truncating data maxwidth Defaults to 15. outputformat. before truncating data when using the "table" The maximum column width to display for each colummn maxcolumnwidth command instead. isolation level of the currently active connection, use the used for new connections. To change the isolation The default transaction isolation that will be isolation Defaults to false. at the price of extra display column padding. fetched, yielding lower latency and memory usage result rows are displayed immediately as they are column sizing. When set to true, before being displayed, yielding optimal display the entire result set is fetched and buffered When set to false, incremental Windows, and HOME/.sqlline/history on all other platforms. commands issued. Defaults to HOME/sqlline/history on The file to which SQLLine will save a record of all the historyfile Defaults to 100. outputformat. redisplayed when using the "table" The interval between which the column headers will be headerinterval Defaults to false. will be displayed but otherwise ignored. true, errors of subsequent commands. When set to will cause execution to abort, preventing the execution or record commands execution of the run any failures during the When set to false, force rehash command. always be explicitely retrieved using the by default it is off. Table and column information can This can be a very slow operation for some databases, do in order to provide them as candidates for tab-completion. access information about the available tables and columns will cause SQLLine to When false, any new connection fastconnect Defaults to false. terminal support ANSI control codes (most do). a more pleasing visual experience. Requires that the the terminal will use color for If true, then output to color sqlline-1.0.2/doc/styles.css.old20000644000175000017500000000465707756702202016541 0ustar drazzibdrazzibbody { background-color: #F1F1F1; color: #000000; font-family: helvetica,sans-serif; font-size: 13; margin-left: 8%; margin-right: 4%; } .title { font-size: small; background-color: #CCCCCC; border-style: inset; color: #163433; padding: 3px; } pre.programlisting { border: thin solid gray; font-family: monospace; background-color: #E0E0E0; border: thin solid gray; font-size: 11px; padding: 10px; margin-left: 10%; margin-right: 10%; } pre.screen { border: thin solid gray; font-family: monospace; background-color: #E0E0E0; border: thin solid gray; font-size: 11px; padding: 10px; } div.note { border: 1px solid green; } div.important { color: red; border: 1px solid red; } div.warning { color: red; border: 2px solid red; } div.caution { color: #1111BB; border: 1px solid #1111BB; } /* hr { margin-left: -4%; } a:link { color: blue; text-decoration: none; } a:visited { color:green; text-decoration: none; } a:active { color:green; text-decoration: none; } a:hover { color:red; text-decoration: underline; } pre.programlisting { border: thin solid gray; font-family: monospace; background-color: #E0E0E0; border: thin solid gray; font-size: 11px; padding: 10px; } div.note { border: 1px solid green; } div.important { color: red; border: 1px solid red; } div.warning { color: red; border: 2px solid red; } div.caution { color: #1111BB; border: 1px solid #1111BB; } div.table { font-family: monospace; background-color: #E0E0E0; border: thin solid gray; font-size: 12; margin-top: 5px; margin-bottom: 5px; } table { width: 100%; } h1 { font-family: verdana,arial,helvetica,sans-serif; font-size: 24px; margin-left: -4%; } h2 { font-family: verdana,arial,helvetica,sans-serif; font-size: 20px; } h2.appendix { font-family: verdana,arial,helvetica,sans-serif; font-size: 24px; margin-left: -4%; color: gray; text-align: center; } .title { font-family: Arial, Helvetica, sans-serif; font-variant: small-caps; color: #330099; text-align: center; } .author { font-family: verdana,arial,helvetica,sans-serif; font-size: 12px; text-align: center; } .editedby { font-family: verdana,arial,helvetica,sans-serif; font-size: 12px; text-align: center; } .editor { font-family: verdana,arial,helvetica,sans-serif; font-size: 12px; text-align: center; } div.chapter-divider { font-family: verdana,arial,helvetica,sans-serif; font-size: 9px; } */ sqlline-1.0.2/doc/html.xsl0000644000175000017500000000331710274676246015340 0ustar drazzibdrazzib styles.css 1 5 appendix toc article toc book toc,fig chapter toc part toc preface toc qandadiv toc qandaset toc reference toc refentry toc section toc set toc sqlline-1.0.2/doc/styles.css0000644000175000017500000001360010144432364015660 0ustar drazzibdrazzibBODY { font-family: verdana; } DIV.ABSTRACT { border: solid 2px; padding-left: 10pt; padding-right: 10pt; } PRE.SCREEN { font-family:monospace; white-space: pre; width: 100%; background-color: #ffffcc; border:solid; color: #000000; border-color: #009999; border-left: solid #009999 2px; border-right: solid #009999 2px; border-top: solid #009999 2px; border-bottom: solid #009999 2px; padding-left: 15pt; } PRE.PROGRAMLISTING { font-family:monospace; white-space: pre; width: 100%; background-color: #ffffcc; border:solid; color: #000000; border-color: #009999; border-left: solid #009999 2px; border-right: solid #009999 2px; border-top: solid #009999 2px; border-bottom: solid #009999 2px; padding-left: 15pt; } H1 { color: #ffffff; border: solid 3px #a0a0d0; background-color: #606090; font-variant: small-caps; width: 100%; } H1.TITLE { color: #ffffff; border: solid 3px #a0a0d0; background-color: #606090; font-variant: small-caps; width: 100%; } .TITLE a { color: #ffffff; text-decoration: none; } .TITLE a:active { color: #ffffff; text-decoration: none; } .TITLE a:visited { color: #ffffff; text-decoration: none; } H2 { COLOR: #ffffff ; font-style: italic; BACKGROUND-color: #a0a0d0; BORDER: solid 3px #606090; PADDING: 1px } TABLE.IMPORTANT { font-style:italic; border: solid 2px #ff0000; width: 70%; margin-left: 15%; } TABLE.CAUTION { font-style:italic; border: ridge 2px #ffff00; width: 70%; margin-left: 15%; } TABLE.NOTE { font-style:italic; border: solid 1px #000000; width: 70%; margin-left: 15%; } TABLE.TIP { font-style:italic; border: solid 1px #000000; width: 70%; margin-left: 15%; } TABLE.WARNING { font-style:italic; font-weight: bold; border: ridge 4px #ff0000; width: 70%; margin-left: 15%; } DIV.VARIABLELIST { font-family: sans-serif; font-style: normal; font-weight: normal; padding-left: 20px; } .VARLISTENTRY { font-weight: bold; margin-top: 10px; COLOR: #ffffff ; BACKGROUND-color: #a0a0d0; BORDER: solid 1px #606090; PADDING: 1px } /* * See http://diveintoaccessibility.org/day_26_using_relative_font_sizes.html * for an explanation of the following few commands. * They are really too complicated to explain here in all depth. ;-) */ P { font-size: 12px; } /*/*/A{} BODY P { font-size: x-small; voice-family: "\"}\""; voice-family: inherit; font-size: small; } HTML>BODY P { font-size: small; } /* */ A { text-decoration : none; } A:link,A:active,A:visited { color : #006699; } A:hover { text-decoration: underline; color : #DD6900; } /* Add an external-link icon to absolute links */ a[href^="http:"] { background: url(images/remote.gif) right center no-repeat; padding-right: 12px; } a[href^="http:"]:hover { background: url(images/remote_a.gif) right center no-repeat; } /* Add a note icon to footnote links */ a[href^="#FTN"] { background: url(images/qbullet-note.gif) right center no-repeat; padding-right: 12px; } a[href^="#FTN"]:hover { background: url(images/qbullet-note_a.gif) right center no-repeat; } /* ...and a back icon to the backlinks in the footnotes themselves */ a[name^="FTN"] { background: url(images/scrollup.gif) right center no-repeat; padding-right: 12px; } a[name^="FTN"]:hover { background: url(images/scrollup_a.gif) right center no-repeat; } /* Add a download icon to .gz links */ a[href$=".gz"],a[href$=".tar"],a[href$=".zip"],a[href$=".tgz"] { background: url(images/disk.gif) right center no-repeat; padding-right: 12px; } /* Add an Acrobat Reader icon to PDF links */ a[href$=".pdf"] { background: url(images/acrobat.gif) right center no-repeat; padding-right: 12px; } a[href$=".pdf"]:hover { background: url(images/acrobat_a.gif) right center no-repeat; } /* Add a Word icon to RTF links */ a[href$=".rtf"] { background: url(images/word.gif) right center no-repeat; padding-right: 12px; } /* ...but not to absolute links in this domain... */ a[href^="http://www.karakas-online.de"] { background: transparent; padding-right: 0px; } a[href^="http://www.karakas-online.de"]:hover { background: transparent; } /* ...or to the translation links on each page */ DIV.translatelink > a[href^="http:"] { background: transparent; padding-right: 0px; } DIV.translatelink > a[href^="http:"]:hover { background: transparent; } /* ...or to any images */ DIV.imagelink a[href^="http:"] { background: transparent; padding-right: 0px; } DIV.imagelink a[href^="http:"]:hover { background: transparent; } P.C2 { COLOR: #ffffff ; BACKGROUND-color: #a0a0d0; BORDER: solid 1px #606090; PADDING: 1px } DIV.NAVFOOTER { color: #000000; background-color: #EFEFF8; padding: 5px; margin-top: 10px; width: 100%; border: thin solid #a0a0d0; } DIV.NUKEFOOTER { color: #000000; background-color: #B0E0E6; padding: 5px; margin-top: 10px; width: 100%; border: thin solid #a0a0d0; } DIV.NAVHEADER { color: #000000; background-color: #EFEFF8; padding: 5px; margin-bottom: 10px; width: 100%; border: thin solid #a0a0d0; } DIV.SECT1,DIV.SECT2,DIV.SECT3 { margin-left: 20px; } DIV.EXAMPLE,DIV.TOC { border: thin dotted #70AAE5; padding-left: 10px; padding-right: 10px; color: #000000; background-color: #EFF8F8; } DIV.TOC { margin-left: 20px; margin-right: 20px; width: 95%; } UL { list-style: url("images/tux-bullet.png") disc; } sqlline-1.0.2/doc/manual.xml0000644000175000017500000024404510313510052015620 0ustar drazzibdrazzib ]> SQLLine &VERSION; 2002, 2003, 2004, 2005 Marc Prud'hommeaux SQLLine Manual Introduction SQLLine is a pure-Java console based utility for connecting to relational databases and executing SQL commands. It is similiar to other command-line database access utilities like sqlplus for Oracle, mysql for MySQL, and isql for Sybase/SQL Server. Since it is pure-Java, it is platform independant, and will run on any platform that can run Java 1.3 or higher. License and Terms of Use SQLLine is distributed under the BSD License, meaning that you are free to redistribute, modify, or sell the software with almost no restrictions. For the text of the license, see the license text. For information on obtaining the software under another license, contact the copyright holder: mwp1@cornell.edu. Obtaining SQLLine SQLLine is hosted on SourceForge, and is located at . The latest release can be downloaded from . Installation Required software SQLLine depends on the following software: Java Virtual Machine - SQLLine is a pure java program, and requires Java version 1.3 or higher in order to run. The latest JVM can be downloaded from . JLine - SQLLine uses the JLine console reader for command line editing, tab-completion, and command history. It can be downloaded from . Version 0.8.1 or higher is required. JDBC Driver(s) - Since SQLLine uses the Java Database Connectivity package to connect to your database, you need to obtain the correct JDBC driver libraries for your database. Any JDBC compliant driver can be used for this purpose. Drivers can be located by referring to the section on known JDBC drivers, or else by referring to your database vendor's web site. Installing SQLLine There are currently no set standards for installing Java software on different platforms. The simplest method for installing SQLLine in a platform independant way is as follows: Create a new directory/folder where you like. This will be referred to as sqllinedir. Download sqlline.jar into sqllinedir. Download the latest jline.jar from into sqllinedir. Download your database's JDBC driver files into sqllinedir. Note that some JDBC drivers require some installation, such as uncompressing or unzipping. Using SQLLine Running SQLLine SQLLine can be run with the following command: java -Djava.ext.dirs=sqllinedir sqllinedir/sqlline.jar options properties files For example, if your sqllinedir is /usr/share/java/ (this is typical for Debian Linux), then you might run: java -Djava.ext.dirs=/usr/share/java/ /usr/share/java/sqlline.jar Once you have started SQLLine, you will a prompt that reads "sqlline> ". From here, you can enter either SQLLine commands (beginning with a "!" character), or a SQL statement (if you are currently connected to a database). For example, entering "!help" will display a list of all the available commands. Connecting to a database SQLLine is only useful once you are connected to a database. In order to do so, you need to use the "!connect" command, with the JDBC URL of the database you are going to connect to, followed by the username and password (followed optionally by the driver class name). The JDBC URL is specific to the JDBC driver that you are using for your database, but will always start with "jdbc:", and usually has the machine name of the database and the name of the database itself as part of the string. Consult your driver's documentation for details on the URL to use. For example, to connect to an Oracle database, you might enter: sqlline> !connect jdbc:oracle:thin:@localhost:1521:mydb scott tiger oracle.jdbc.driver.OracleDriver Connected to: Oracle (version Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production With the Partitioning, OLAP and Oracle Data Mining options JServer Release 9.2.0.1.0 - Production) Driver: Oracle JDBC driver (version 9.0.1.0.0) Autocommit status: true 0: jdbc:oracle:thin:@localhost:1521:mydb> Once you are connected, the prompt will change the reflect URL of the current connection. SQLLine can also accept command line options to connect to a database. If a file is specified on the command line, it will be treated as a properties file, and try to connect to the database specified therein. For details, see the properties command documentation. SQLLine allows you to have multiple connections to databases (either the same database, or a different database) open at the same time. Issuing the connect command multiple times will add the new connection to the list of open connections. The "current" connection (against which all SQL statements will be executed) can be switched with the go command. The currently open connections can be listed with the list command. Issuing SQL commands Once you are connected to a database, you can begin SQL statements against the current connection. For example: Issuing SQL commands 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM MYTABLE; +-----+ | ID | +-----+ | 1 | | 2 | | 3 | | 4 | +-----+ 4 rows selected (0.012 seconds) 0: jdbc:oracle:thin:@localhost:1521:mydb> Command Completion On UNIX systems, SQLLine allows command-line completion using the tab key. This will be familiar for users of such popular shells as bash and tcsh. In general, hitting the TAB key when part of the way through typing a command will fill in the rest of the command, or else will display a selection of appropriate possibilities. Command Reference
all all 1 all Execute SQL against all active connections !all SQL statement Description Execute the specified SQL against all the current connections. Example of "all" command 1: jdbc:mysql://localhost/mydb> !list 2 active connections: #0 open jdbc:oracle:thin:@localhost:1521:mydb #1 open jdbc:mysql://localhost/mydb 1: jdbc:mysql://localhost/mydb> !all DELETE FROM COMPANY; Executing SQL against: jdbc:oracle:thin:@localhost:1521:mydb 4 rows affected (0.004 seconds) Executing SQL against: jdbc:mysql://localhost/mydb 1 row affected (3.187 seconds) 1: jdbc:mysql://localhost/mydb>
autocommit autocommit 1 autocommit Enable or disable automatic transaction commit mode !autocommit on/off Description Set autocommit mode on or off. When autocommit is on, every individual SQL statement will be committed after it is issued. Otherwise, the commit command will need to be issued in order to commit any changes to the database. Example of "autocommit" command 1: jdbc:mysql://localhost/mydb> !autocommit off Autocommit status: false 1: jdbc:mysql://localhost/mydb>
batch batch 1 batch Start or execute a batch of SQL statements !batch Description Start or execute a batch of SQL statements. The first time the statement is issued, subsequent SQL statements will be deferred until the batch command is issued again. Databases can frequently optimize multiple batched statements (e.g., for bulk data loading) in order to speed up execution. Example of "batch" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !batch Batching SQL statements. Run "batch" again to execute the batch. 0: jdbc:oracle:thin:@localhost:1521:mydb> INSERT INTO MYTABLE (ID) VALUES (1); 0: jdbc:oracle:thin:@localhost:1521:mydb> INSERT INTO MYTABLE (ID) VALUES (2); 0: jdbc:oracle:thin:@localhost:1521:mydb> INSERT INTO MYTABLE (ID) VALUES (3); 0: jdbc:oracle:thin:@localhost:1521:mydb> INSERT INTO MYTABLE (ID) VALUES (4); 0: jdbc:oracle:thin:@localhost:1521:mydb> !batch Running batched SQL statements... COUNT STATEMENT 1 INSERT INTO MYTABLE (ID) VALUES (1) 1 INSERT INTO MYTABLE (ID) VALUES (2) 1 INSERT INTO MYTABLE (ID) VALUES (3) 1 INSERT INTO MYTABLE (ID) VALUES (4) 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM MYTABLE; +-----+ | ID | +-----+ | 1 | | 2 | | 3 | | 4 | +-----+ 4 rows selected (0.012 seconds) 0: jdbc:oracle:thin:@localhost:1521:mydb>
brief brief 1 brief Enable terse output mode !brief Description Set verbose mode off. This will prevent printing of stack traces when errors occur. Example of "brief" command 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM BOGUS_TABLE; Error: ORA-00942: table or view does not exist (state=42000,code=942) java.sql.SQLException: ORA-00942: table or view does not exist at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:180) at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:208) at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:543) at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1451) at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteDescribe(TTC7Protocol.java:651) at oracle.jdbc.driver.OracleStatement.doExecuteQuery(OracleStatement.java:2110) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2324) at oracle.jdbc.driver.OracleStatement.execute(OracleStatement.java:909) at sqlline.SqlLine$Commands.sql(SqlLine.java:3183) at sqlline.SqlLine.dispatch(SqlLine.java:771) at sqlline.SqlLine.begin(SqlLine.java:634) at sqlline.SqlLine.main(SqlLine.java:332) 0: jdbc:oracle:thin:@localhost:1521:mydb> !brief verbose: off 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM BOGUS_TABLE; Error: ORA-00942: table or view does not exist (state=42000,code=942) 0: jdbc:oracle:thin:@localhost:1521:mydb>
close close 1 close Close the active connection !close Description Close the current connection and remote it from the connection list. Example of "close" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !list 1 active connection: #0 open jdbc:oracle:thin:@localhost:1521:mydb 0: jdbc:oracle:thin:@localhost:1521:mydb> !close Closing: oracle.jdbc.driver.OracleConnection sqlline> !list No active connections sqlline>
columns columns 1 columns Display columns of a table !columns table name Description List the columns in the specified table. Example of "columns" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !columns EMPLOYEE +-------------+--------------+------------+------------+ | TABLE_NAME | COLUMN_NAME | DATA_TYPE | TYPE_NAME | +-------------+--------------+------------+------------+ | EMPLOYEE | ID | 3 | NUMBER | | EMPLOYEE | FIRST_NAME | 12 | VARCHAR2 | | EMPLOYEE | LAST_NAME | 12 | VARCHAR2 | +-------------+--------------+------------+------------+ 0: jdbc:oracle:thin:@localhost:1521:mydb>
commit commit 1 commit Commit the current transaction !commit Description Commit the current transaction, if autocommit is off. Example of "commit" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !autocommit off Autocommit status: false 0: jdbc:oracle:thin:@localhost:1521:mydb> INSERT INTO EMPLOYEE (ID, FIRST_NAME, LAST_NAME) VALUES (1, 'Bob', 'Smith'); 1 row affected (1.254 seconds) 0: jdbc:oracle:thin:@localhost:1521:mydb> !commit Commit complete (0.661 seconds) 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM EMPLOYEE; +--------------+-------------+------------+ | ID | FIRST_NAME | LAST_NAME | +--------------+-------------+------------+ | 1 | Bob | Smith | +--------------+-------------+------------+ 1 row selected (0.309 seconds) 0: jdbc:oracle:thin:@localhost:1521:mydb>
connect connect 1 connect Connect to a database !connect url username password driver class Description Connect to a database. Example of "commit" command sqlline> !connect jdbc:oracle:thin:@localhost:1521:mydb scott tiger oracle.jdbc.driver.OracleDriver Connected to: Oracle (version Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production With the Partitioning, OLAP and Oracle Data Mining options JServer Release 9.2.0.1.0 - Production) Driver: Oracle JDBC driver (version 9.0.1.0.0) Autocommit status: true 0: jdbc:oracle:thin:@localhost:1521:mydb>
dbinfo dbinfo 1 dbinfo Provide information about the current database !dbinfo Description List metadata information about the current connection. Example of "dbinfo" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !dbinfo allProceduresAreCallable false allTablesAreSelectable false dataDefinitionCausesTransactionCommit true dataDefinitionIgnoredInTransactions false doesMaxRowSizeIncludeBlobs true getCatalogSeparator getCatalogTerm getDatabaseProductName Oracle getDatabaseProductVersion Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production With the Partitioning, OLAP and Oracle Data Mining options JServer Release 9.2.0.1.0 - Production getDefaultTransactionIsolation 2 getDriverMajorVersion 9 getDriverMinorVersion 0 getDriverName Oracle JDBC driver getDriverVersion 9.0.1.0.0 getExtraNameCharacters $# getIdentifierQuoteString " getMaxBinaryLiteralLength 1000 getMaxCatalogNameLength 0 getMaxCharLiteralLength 2000 getMaxColumnNameLength 30 getMaxColumnsInGroupBy 0 getMaxColumnsInIndex 32 getMaxColumnsInOrderBy 0 getMaxColumnsInSelect 0 getMaxColumnsInTable 1000 getMaxConnections 0 getMaxCursorNameLength 0 getMaxIndexLength 0 getMaxProcedureNameLength 30 getMaxRowSize 2000 getMaxSchemaNameLength 30 getMaxStatementLength 65535 getMaxStatements 0 getMaxTableNameLength 30 getMaxTablesInSelect 0 getMaxUserNameLength 30 getNumericFunctions ABS,CEIL,COS,COSH,EXP,FLOOR, LN,LOG,MOD,POWER,ROUND,SIGN, SIN,SINH,SQRT,TAN,TANH,TRUNC, AVG,COUNT,GLB,LUB,MAX,MIN, STDDEV,SUM,VARIANCE getProcedureTerm procedure getSchemaTerm schema getSearchStringEscape // getSQLKeywords ACCESS, ADD, ALTER, AUDIT, CLUSTER, COLUMN, COMMENT, COMPRESS, CONNECT, DATE, DROP, EXCLUSIVE, FILE, IDENTIFIED, IMMEDIATE, INCREMENT, INDEX, INITIAL, INTERSECT, LEVEL, LOCK, LONG, MAXEXTENTS, MINUS, MODE, NOAUDIT, NOCOMPRESS, NOWAIT, NUMBER, OFFLINE, ONLINE, PCTFREE, PRIOR, all_PL_SQL_reserved_ words getStringFunctions CHR, INITCAP, LOWER, LPAD, LTRIM, NLS,_INITCAP, NLS,_LOWER, NLS,_UPPER, REPLACE, RPAD, RTRIM, SOUNDEX, SUBSTR, SUBSTRB, TRANSLATE, UPPER, ASCII, INSTR, INSTRB, LENGTH, LENGTHB, NLSSORT, CHARTOROWID, CONVERT, HEXTORAW, RAWTOHEX, ROWIDTOCHAR, TO_CHAR, TO_DATE, TO_LABEL, TO_MULTI_BYTE, TO_NUMBER, TO_SINGLE_BYTE getSystemFunctions DUMP, GREATEST, GREATEST_LB, LEAST, LEAST_UB, NVL, UID, USER, USERENV, VSIZE getTimeDateFunctions ADD_MONTHS, LAST_DAY, MONTHS_BETWEEN, NEW_TIME, NEXT_DAY, ROUND, SYSDATE, TRUNC getURL jdbc:oracle:thin:@localhost:1521:mydb getUserName MYDB isCatalogAtStart false isReadOnly false nullPlusNonNullIsNull true nullsAreSortedAtEnd false nullsAreSortedAtStart false nullsAreSortedHigh false nullsAreSortedLow true storesLowerCaseIdentifiers false storesLowerCaseQuotedIdentifiers false storesMixedCaseIdentifiers false storesMixedCaseQuotedIdentifiers true storesUpperCaseIdentifiers true storesUpperCaseQuotedIdentifiers false supportsAlterTableWithAddColumn true supportsAlterTableWithDropColumn false supportsANSI92EntryLevelSQL true supportsANSI92FullSQL false supportsANSI92IntermediateSQL false supportsBatchUpdates true supportsCatalogsInDataManipulation false supportsCatalogsInIndexDefinitions false supportsCatalogsInPrivilegeDefinitions false supportsCatalogsInProcedureCalls false supportsCatalogsInTableDefinitions false supportsColumnAliasing true supportsConvert true supportsCoreSQLGrammar true supportsCorrelatedSubqueries true supportsDataDefinitionAndDataManipulationTransactionstrue supportsDataManipulationTransactionsOnly true supportsDifferentTableCorrelationNames true supportsExpressionsInOrderBy true supportsExtendedSQLGrammar true supportsFullOuterJoins true supportsGroupBy true supportsGroupByBeyondSelect true supportsGroupByUnrelated true supportsIntegrityEnhancementFacility true supportsLikeEscapeClause true supportsLimitedOuterJoins true supportsMinimumSQLGrammar true supportsMixedCaseIdentifiers false supportsMixedCaseQuotedIdentifiers true supportsMultipleResultSets false supportsMultipleTransactions true supportsNonNullableColumns true supportsOpenCursorsAcrossCommit false supportsOpenCursorsAcrossRollback false supportsOpenStatementsAcrossCommit false supportsOpenStatementsAcrossRollback false supportsOrderByUnrelated true supportsOuterJoins true supportsPositionedDelete true supportsPositionedUpdate true supportsSchemasInDataManipulation true supportsSchemasInIndexDefinitions true supportsSchemasInPrivilegeDefinitions true supportsSchemasInProcedureCalls true supportsSchemasInTableDefinitions true supportsSelectForUpdate true supportsStoredProcedures true supportsSubqueriesInComparisons true supportsSubqueriesInExists true supportsSubqueriesInIns true supportsSubqueriesInQuantifieds true supportsTableCorrelationNames true supportsTransactions true supportsUnion true supportsUnionAll true usesLocalFilePerTable false usesLocalFiles false 0: jdbc:oracle:thin:@localhost:1521:mydb>
describe describe 1 describe Describe a table !describe table name Description Synonym for columns (if an argument is specified) or tables (if no argument is specified). Example of "describe" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !describe EMPLOYEE +--------------+------------+-------------+-----------+------------+ | TABLE_SCHEM | TABLE_NAME | COLUMN_NAME | DATA_TYPE | TYPE_NAME | +--------------+------------+-------------+-----------+------------+ | MYDB | EMPLOYEE | ID | 3 | NUMBER | | MYDB | EMPLOYEE | FIRST_NAME | 12 | VARCHAR2 | | MYDB | EMPLOYEE | LAST_NAME | 12 | VARCHAR2 | +--------------+------------+-------------+-----------+------------+ 0: jdbc:oracle:thin:@localhost:1521:mydb>
dropall dropall 1 dropall Drop all tables in the database !dropall Description Drop every table in the database. Example of "dropall" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !dropall Really drop every table in the database? (y/n) y 1/5 DROP TABLE COMPANY; 2/5 DROP TABLE EMPLOYEE; 3/5 DROP TABLE PROJECTS; 4/5 DROP TABLE EMPLOYEE_PROJECTS; 5/5 DROP TABLE COMPANYEMPLOYEES; 0: jdbc:oracle:thin:@localhost:1521:mydb> Warning on using "dropall" This command will destroy all data in the database (subject to access restrictions). Use with extreme caution.
exportedkeys exportedkeys 1 exportedkeys List exported foreign keys for a database !exportedkeys table name Description List all the foreign keys that are exported by the specified table. Example of "exportedkeys" command 0: jdbc:hsqldb:db-hypersonic> !exportedkeys COMPANY +----------------+---------------+----------------+-------------+ | PKTABLE_SCHEM | PKTABLE_NAME | PKCOLUMN_NAME | FKTABLE_CAT | +----------------+---------------+----------------+-------------+ | | COMPANY | COMPANY_ID | | +----------------+---------------+----------------+-------------+ 0: jdbc:hsqldb:db-hypersonic>
go go 1 go Change to a different active connection !go connection number Description Switch to the specified connection. Example of "go" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !list 2 active connections: #0 open jdbc:oracle:thin:@localhost:1521:mydb #1 open jdbc:mysql://localhost/mydb 0: jdbc:oracle:thin:@localhost:1521:mydb> !go 1 1: jdbc:mysql://localhost/mydb> !go 0 0: jdbc:oracle:thin:@localhost:1521:mydb>
help help 1 help Display help information !help Description Display information about allowed commands. Example of "help" command sqlline> !help !all Execute the specified SQL against all the current connections !autocommit Set autocommit mode on or off !batch Start or execute a batch of statements !brief Set verbose mode off !close Close the current connection to the database !columns List all the columns for the specified table !commit Commit the current transaction (if autocommit is off) !connect Open a new connection to the database. !dbinfo Give metadata information about the database !describe Describe a table !dropall Drop all tables in the current database !exportedkeys List all the exported keys for the specified table !go Select the current connection !help Print a summary of command usage !history Display the command history !importedkeys List all the imported keys for the specified table !indexes List all the indexes for the specified table !isolation Set the transaction isolation for this connection !list List the current connections !metadata Obtain metadata information !outputformat Set the output format for displaying results (table,vertical,csv,tsv,xmlattrs,xmlelements) !properties Connect to the database specified in the properties file(s) !primarykeys List all the primary keys for the specified table !procedures List all the procedures !quit Exits the program !reconnect Reconnect to the database !record Record all output to the specified file !rehash Fetch table and column names for command completion !rollback Roll back the current transaction (if autocommit is off) !run Run a script from the specified file !save Save the current variabes and aliases !scan Scan for installed JDBC drivers !script Start saving a script to a file !set Set a sqlline variable !sql Execute a SQL command !tables List all the tables in the database !verbose Set verbose mode on Comments, bug reports, and patches go to mwp1@cornell.edu sqlline>
history history 1 history Display the command history !history Description Display the command history. Example of "history" command sqlline> !history 1. !outputformat xmlelements 2. SELECT * FROM PCPOINT; 3. !outputformat vertical 4. SELECT * FROM PCPOINT; 5. !tables sqlline>
importedkeys importedkeys 1 importedkeys List imported foreign keys for a database !importedkeys table name Description List all the foreign keys that are imported by the specified table. Example of "importedkeys" command 0: jdbc:hsqldb:db-hypersonic> !importedkeys EMPLOYEE +----------------+---------------+----------------+-------------+ | PKTABLE_SCHEM | PKTABLE_NAME | PKCOLUMN_NAME | FKTABLE_CAT | +----------------+---------------+----------------+-------------+ | | COMPANY | COMPANY_ID | | +----------------+---------------+----------------+-------------+ 0: jdbc:hsqldb:db-hypersonic>
indexes indexes 1 indexes Display indexes for a table !indexes table name Description List all the indexes on the specified table name. Example of "indexes" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !indexes EMPLOYEE +-------------+-------------+-----------------+-------+--------------+ | TABLE_NAME | NON_UNIQUE | INDEX_NAME | TYPE | COLUMN_NAME | +-------------+-------------+-----------------+-------+--------------+ | EMPLOYEE | 0 | | 0 | | | EMPLOYEE | 0 | SYS_C003115849 | 1 | ID | | EMPLOYEE | 1 | FIRST_NAME | 1 | FIRST_NAME | | EMPLOYEE | 1 | LAST_NAME | 1 | LAST_NAME | +-------------+-------------+-----------------+-------+--------------+ 0: jdbc:oracle:thin:@localhost:1521:mydb>
isolation isolation 1 isolation Set the transaction isolation mode for the active connection !isolation isolation level Description Set the isolation level for the current transaction. For a description of the different isolation levels, see http://java.sun.com/j2se/1.3/docs/api/java/sql/Connection.html#field_detail. Example of "isolation" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !isolation TRANSACTION_READ_UNCOMMITTED Error: READ_COMMITTED and SERIALIZABLE are the only valid transaction levels (state=,code=17030) 0: jdbc:oracle:thin:@localhost:1521:mydb> !isolation TRANSACTION_SERIALIZABLE Transaction isolation: TRANSACTION_SERIALIZABLE 0: jdbc:oracle:thin:@localhost:1521:mydb>
list list 1 list Display all active connections !list Description List all the current connections. Example of "list" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !list 2 active connections: #0 open jdbc:oracle:thin:@localhost:1521:mydb #1 open jdbc:mysql://localhost/mydb 0: jdbc:oracle:thin:@localhost:1521:mydb>
metadata metadata 1 metadata Invoke arbitrary metadata commands !metadata methodname params Description Execute an arbitrary metadata method agains the current connection. refpurpose are separated by spaces. Use "" for a blank String, and null for a null parameter. For information on available metadata methods, see http://java.sun.com/j2se/1.3/docs/api/java/sql/DatabaseMetaData.html. Example of "metadata" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !metadata supportsSelectForUpdate true 0: jdbc:oracle:thin:@localhost:1521:mydb> !metadata getTypeInfo +------------+------------+-------------+-----------------+-----------------+ | TYPE_NAME | DATA_TYPE | PRECISION | LITERAL_PREFIX | LITERAL_SUFFIX | +------------+------------+-------------+-----------------+-----------------+ | NUMBER | -7 | 1 | | | | NUMBER | -6 | 3 | | | | NUMBER | -5 | 38 | | | | LONG RAW | -4 | 2147483647 | ' | ' | | RAW | -3 | 2000 | ' | ' | | LONG | -1 | 2147483647 | ' | ' | | CHAR | 1 | 2000 | ' | ' | | NUMBER | 2 | 38 | | | | NUMBER | 4 | 10 | | | | NUMBER | 5 | 5 | | | | FLOAT | 6 | 63 | | | | REAL | 7 | 63 | | | | VARCHAR2 | 12 | 4000 | ' | ' | | DATE | 93 | 7 | | | | STRUCT | 2002 | 0 | ' | ' | | ARRAY | 2003 | 0 | ' | ' | | BLOB | 2004 | 4294967295 | | | | CLOB | 2005 | 4294967295 | ' | ' | | REF | 2006 | 0 | ' | ' | +------------+------------+-------------+-----------------+-----------------+ 0: jdbc:oracle:thin:@localhost:1521:mydb> !meta getProcedureColumns null % %JAVA% % +----------------+------------------+------------------------+--------------+ | PROCEDURE_CAT | PROCEDURE_SCHEM | PROCEDURE_NAME | COLUMN_NAME | +----------------+------------------+------------------------+--------------+ | DBMS_JAVA | SYS | DROPJAVA | OPTIONS | | XMLPARSER | SYS | GETJAVARELEASEVERSION | | | DBMS_JAVA | SYS | LOADJAVA | OPTIONS | | DBMS_JAVA | SYS | LOADJAVA | OPTIONS | | DBMS_JAVA | SYS | LOADJAVA | RESOLVER | +----------------+------------------+------------------------+--------------+ 0: jdbc:oracle:thin:@localhost:1521:mydb>
outputformat outputformat 1 outputformat Change the method for displaying SQL results !outputformat format name Description Set the mode for displaying results from statements. This is useful for saving output from SQL statements to either a visually pleasing format or an easily parseable format. Example of table output formatting 0: jdbc:oracle:thin:@localhost:1521:mydb> !outputformat table 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY; +-------------+------------+ | COMPANY_ID | NAME | +-------------+------------+ | 1 | Apple | | 2 | Sun | | 3 | IBM | | 4 | Microsoft | +-------------+------------+ 4 rows selected (0.012 seconds) Example of vertical output formatting 0: jdbc:oracle:thin:@localhost:1521:mydb> !outputformat vertical 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY; COMPANY_ID 1 NAME Apple COMPANY_ID 2 NAME Sun COMPANY_ID 3 NAME IBM COMPANY_ID 4 NAME Microsoft 4 rows selected (0.011 seconds) Example of CSV output formatting 0: jdbc:oracle:thin:@localhost:1521:mydb> !outputformat csv 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY; 'COMPANY_ID','NAME' '1','Apple' '2','Sun' '3','IBM' '4','Microsoft' 4 rows selected (0.012 seconds) Example of TSV output formatting 0: jdbc:oracle:thin:@localhost:1521:mydb> !outputformat tsv 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY; 'COMPANY_ID' 'NAME' '1' 'Apple' '2' 'Sun' '3' 'IBM' '4' 'Microsoft' 4 rows selected (0.013 seconds) Example of XML attribute output formatting 0: jdbc:oracle:thin:@localhost:1521:mydb> !outputformat xmlattr 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY; <resultset> <result COMPANY_ID="1" NAME="Apple"/> <result COMPANY_ID="2" NAME="Sun"/> <result COMPANY_ID="3" NAME="IBM"/> <result COMPANY_ID="4" NAME="Microsoft"/> </resultset> 4 rows selected (0.012 seconds) Example of XML element output formatting 0: jdbc:oracle:thin:@localhost:1521:mydb> !outputformat xmlelements 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY <resultset> <result> <COMPANY_ID>1</COMPANY_ID> <NAME>Apple</NAME> </result> <result> <COMPANY_ID>2</COMPANY_ID> <NAME>Sun</NAME> </result> <result> <COMPANY_ID>3</COMPANY_ID> <NAME>IBM</NAME> </result> <result> <COMPANY_ID>4</COMPANY_ID> <NAME>Microsoft</NAME> </result> </resultset> 4 rows selected (0.02 seconds) 0: jdbc:oracle:thin:@localhost:1521:mydb>
primarykeys primarykeys 1 primarykeys Display the primary key columns for a table !primarykeys table name Description List all the primary keys for the specified table. Example of "primarykeys" command 0: jdbc:hsqldb:db-hypersonic> !primarykeys COMPANY +--------------+-------------+--------------+----------+----------+ | TABLE_SCHEM | TABLE_NAME | COLUMN_NAME | KEY_SEQ | PK_N | +--------------+-------------+--------------+----------+----------+ | | COMPANY | COMPANY_ID | 1 | SYS_PK_C | +--------------+-------------+--------------+----------+----------+ 0: jdbc:hsqldb:db-hypersonic>
procedures procedures 1 procedures List stored procedures !procedures procedure name pattern Description Display a list of all the stored procedures that are exposed by the current database. Example of "procedures" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !procedures %JDBC% +----------------+------------------+------------------+ | PROCEDURE_CAT | PROCEDURE_SCHEM | PROCEDURE_NAME | +----------------+------------------+------------------+ | WK_ADM | WKSYS | GET_JDBC_DRIVER | | WK_ADM | WKSYS | SET_JDBC_DRIVER | +----------------+------------------+------------------+ 0: jdbc:oracle:thin:@localhost:1521:mydb>
properties properties 1 properties Connect to the database defined in the specified properties file. !properties file Description Connect to the database defined in the specified properties file. The properties file is expected to have the following values: url: the database URL to which to connect driver: the driver class that handles the URL. If unspecifed, SQLLine with automatically scan the CLASSPATH for an appropriate driver user: the username to use to connect to the database. If unspecified, SQLLine will prompt for it. password: the password to use to connect to the database. If unspecified, SQLLine will prompt for it. The key names in the properties file can also use JDO semantics for the properties. These properties are "javax.jdo.option.ConnectionURL", "javax.jdo.option.ConnectionDriverName", "javax.jdo.option.ConnectionUserName", and "javax.jdo.option.ConnectionPassword". Furthermore, any properties that end with "ConnectionURL", "ConnectionDriverName", "ConnectionUserName", and "ConnectionPassword" will be used for the connection. Example of "properties" command sqlline> !properties test.properties Connecting to jdbc:mysql://localhost/mydb Enter password for jdbc:mysql://localhost/mydb: ***** Connected to: MySQL (version 3.23.52-log) Driver: MySQL-AB JDBC Driver (version 3.0.8-stable ( $Date: 2005/09/19 19:17:14 $, $Revision: 1.9 $ )) Autocommit status: true Transaction isolation: TRANSACTION_READ_COMMITTED 0: jdbc:mysql://localhost/mydb>
quit quit 1 quit Exit SQLLine !quit Description Exit SQLLine. Example of "reconnect" command 0: jdbc:hsqldb:db-hypersonic> !quit Closing: org.hsqldb.jdbcConnection
reconnect reconnect 1 reconnect Reconnect to the current database !reconnect Description Reconnect to the current database. Example of "reconnect" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !reconnect Reconnecting to "jdbc:oracle:thin:@localhost:1521:mydb"... Closing: oracle.jdbc.driver.OracleConnection@4428d3 Connected to: Oracle (version Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production With the Partitioning, OLAP and Oracle Data Mining options JServer Release 9.2.0.1.0 - Production) Driver: Oracle JDBC driver (version 9.0.1.0.0) Autocommit status: true 0: jdbc:oracle:thin:@localhost:1521:mydb>
record record 1 record Begin recording all output from SQL commands !record file name Description Save all output from the session to the specified file. Example of "record" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !record /tmp/mysession.out Saving all output to "/tmp/mysession.out". Enter "record" with no arguments to stop it. 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY; +-------------+------------+ | COMPANY_ID | NAME | +-------------+------------+ | 3 | IBM | | 4 | Microsoft | | 1 | Apple | | 2 | Sun | +-------------+------------+ 4 rows selected (0.011 seconds) 0: jdbc:oracle:thin:@localhost:1521:mydb> !record Recording stopped. 0: jdbc:oracle:thin:@localhost:1521:mydb>
rehash rehash 1 rehash Obtain a list of all tables and columns from the database !rehash Description Get a list of all tables and columns from the database in order to include them in the list for tab-completion of SQL statements. This is done automatically on connect when the fastconnect option is enabled. Example of "rehash" command 0: jdbc:hsqldb:db-hypersonic> !rehash Building list of tables and columns for tab-completion (set fastconnect to true to skip)... 7/7 (100%) Done Done 0: jdbc:hsqldb:db-hypersonic> Warning on using "rehash" This operation can be extremely slow for some databases.
rollback rollback 1 rollback Roll back the current transaction !rollback Description Rollback the current transaction, if autocommit is off. Example of "rollback" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !autocommit off Autocommit status: false 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY; +-------------+------------+ | COMPANY_ID | NAME | +-------------+------------+ | 3 | IBM | | 4 | Microsoft | | 1 | Apple | | 2 | Sun | +-------------+------------+ 4 rows selected (0.011 seconds) 0: jdbc:oracle:thin:@localhost:1521:mydb> DELETE FROM COMPANY; 4 rows affected (0.004 seconds) 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY; +-------------+-------+ | COMPANY_ID | NAME | +-------------+-------+ +-------------+-------+ No rows selected (0.01 seconds) 0: jdbc:oracle:thin:@localhost:1521:mydb> !rollback Rollback complete (0.016 seconds) 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM COMPANY; +-------------+------------+ | COMPANY_ID | NAME | +-------------+------------+ | 3 | IBM | | 4 | Microsoft | | 1 | Apple | | 2 | Sun | +-------------+------------+ 4 rows selected (0.01 seconds) 0: jdbc:oracle:thin:@localhost:1521:mydb>
run run 1 run Execute a command script !run file name Description Run the individual commands specified in the file name. The file should consist of individual SQL statements or SQLLine commands. Lines beginning with "#" are interpreted as comments and ignored. If any errors occur while running the script, the script will be aborted, unless the force preference is set to true. Example of "run" command 0: jdbc:hsqldb:db-hypersonic> !run example.sql 1/11 CREATE TABLE COMPANY (COMPANY_ID INT, NAME VARCHAR(255)); No rows affected (0.001 seconds) 2/11 INSERT INTO COMPANY VALUES (1, 'Apple'); 1 row affected (0 seconds) 3/11 INSERT INTO COMPANY VALUES (2, 'Sun'); 1 row affected (0 seconds) 4/11 INSERT INTO COMPANY VALUES (3, 'IBM'); 1 row affected (0.001 seconds) 5/11 INSERT INTO COMPANY VALUES (4, 'Microsoft'); 1 row affected (0.015 seconds) 6/11 CREATE TABLE EMPLOYEE (ID INT, FIRST_NAME VARCHAR(255), LAST_NAME VARCHAR(255), COMPANY INT); No rows affected (0.004 seconds) 7/11 CREATE INDEX FIRST_NAME ON EMPLOYEE(FIRST_NAME); No rows affected (0 seconds) 8/11 CREATE INDEX LAST_NAME ON EMPLOYEE(LAST_NAME); No rows affected (0.001 seconds) 9/11 ALTER TABLE EMPLOYEE ADD CONSTRAINT EMP_COMPANY FOREIGN KEY (COMPANY) REFERENCES COMPANY (COMPANY_ID); No rows affected (0 seconds) 10/11 INSERT INTO EMPLOYEE (ID, FIRST_NAME, LAST_NAME, COMPANY) VALUES (234, 'William', 'Gates', 4); 1 row affected (0.001 seconds) 11/11 SELECT * FROM COMPANY,EMPLOYEE WHERE EMPLOYEE.COMPANY = COMPANY.COMPANY_ID; +------------+-----------+--------------+-------------+------------+---------+ | COMPANY_ID | NAME | ID | FIRST_NAME | LAST_NAME | COMPANY | +------------+-----------+--------------+-------------+------------+---------+ | 4 | Microsoft | 234 | William | Gates | 4 | +------------+-----------+--------------+-------------+------------+---------+ 1 row selected (0.001 seconds) 0: jdbc:hsqldb:db-hypersonic>
save save 1 save Save the current preferences !save Description Save the current preferences. Example of "save" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !save Saving preferences to: /Users/mprudhom/.sqlline/sqlline.properties 0: jdbc:oracle:thin:@localhost:1521:mydb>
scan scan 1 scan Scan class path for JDBC drivers !scan Description Scans all the jar files in the CLASSPATH for any JDBC drivers, and prints the class names of the drivers. Example of "scan" command sqlline> !scan 35 driver classes found Compliant Version Driver Class no 4.0 COM.cloudscape.core.JDBCDriver no 1.0 COM.cloudscape.core.RmiJdbcDriver yes 7.1 COM.ibm.db2.jdbc.net.DB2Driver yes 3.2 com.ddtek.jdbc.db2.DB2Driver yes 3.2 com.ddtek.jdbc.informix.InformixDriver yes 3.2 com.ddtek.jdbc.oracle.OracleDriver yes 3.2 com.ddtek.jdbc.sqlserver.SQLServerDriver yes 3.2 com.ddtek.jdbc.sybase.SybaseDriver yes 1.0 com.ibm.db2.jcc.DB2Driver yes 2.21 com.informix.jdbc.IfxDriver no 0.2 com.internetcds.jdbc.tds.Driver no 0.2 com.internetcds.jdbc.tds.SybaseDriver yes 2.2715 com.jnetdirect.jsql.JSQLDriver yes 3.2 com.merant.datadirect.jdbc.db2.DB2Driver yes 3.2 com.merant.datadirect.jdbc.informix.InformixDriver yes 3.2 com.merant.datadirect.jdbc.oracle.OracleDriver yes 3.2 com.merant.datadirect.jdbc.sqlserver.SQLServerDriver yes 3.2 com.merant.datadirect.jdbc.sybase.SybaseDriver yes 2.2 com.microsoft.jdbc.sqlserver.SQLServerDriver no 3.0 com.mysql.jdbc.Driver no 3.0 com.mysql.jdbc.NonRegisteringDriver yes 4.4 com.pointbase.jdbc.jdbcDriver yes 4.4 com.pointbase.jdbc.jdbcEmbeddedDriver yes 4.4 com.pointbase.jdbc.jdbcUniversalDriver no 5.5 com.sybase.jdbc2.jdbc.SybDriver yes 1.0 in.co.daffodil.db.jdbc.DaffodilDBDriver no 2.0 interbase.interclient.Driver no 0.5 net.sourceforge.jtds.jdbc.Driver yes 1.0 oracle.jdbc.OracleDriver yes 1.0 oracle.jdbc.driver.OracleDriver no 3.26 org.enhydra.instantdb.jdbc.idbDriver no 3.0 org.gjt.mm.mysql.Driver no 1.7 org.hsqldb.jdbcDriver no 7.3 org.postgresql.Driver yes 0.9 org.sourceforge.jxdbcon.JXDBConDriver sqlline>
script script 1 script Save executed commands to a file !script filename Description Start saving all commands entered to the specified file. Once scripting on, it can be finished by entering the script command again with no arguments. Saved scripts can be re-run using the run command. Example of "script" command 0: jdbc:hsqldb:db-hypersonic> !script /tmp/mysession.script Saving command script to "/tmp/mysession.script". Enter "script" with no arguments to stop it. 0: jdbc:hsqldb:db-hypersonic> !autocommit off Autocommit status: false 0: jdbc:hsqldb:db-hypersonic> SELECT * FROM COMPANY; +-------------+------------+ | COMPANY_ID | NAME | +-------------+------------+ | 1 | Apple | | 2 | Sun | | 3 | IBM | | 4 | Microsoft | +-------------+------------+ 4 rows selected (0.001 seconds) 0: jdbc:hsqldb:db-hypersonic> UPDATE COMPANY SET NAME='Apple, Inc.' WHERE NAME='Apple'; 1 row affected (0.005 seconds) 0: jdbc:hsqldb:db-hypersonic> !commit Commit complete (0 seconds) 0: jdbc:hsqldb:db-hypersonic> !script Script closed. Enter "run /tmp/mysession.script" to replay it. 0: jdbc:hsqldb:db-hypersonic>
set set 1 set Set a preference !set preference value Description Set the specified preference to the specified value. If autosave is on, then this will cause preferences to be immediately saved. Otherwise, changed setting can be saved for future SQLLine session eith the save command. Example of "set" command 0: jdbc:hsqldb:db-hypersonic> !set color on
sql sql 1 sql Execute a SQL against a database !sql statement Description Issue the specified SQL statement. This is equivalent to entering the statement by itself from the command line. Example of "sql" command 0: jdbc:hsqldb:db-hypersonic> !sql DELETE FROM COMPANY; 4 rows affected (0.005 seconds) 0: jdbc:hsqldb:db-hypersonic>
tables tables 1 tables List all the tables in the database !tables Description List all the tables in the database of the current connection. Example of "tables" command 0: jdbc:oracle:thin:@localhost:1521:mydb> !tables +------------+--------------+---------------------------------+-------------+ | TABLE_CAT | TABLE_SCHEM | TABLE_NAME | TABLE_TYPE | +------------+--------------+---------------------------------+-------------+ | | MYDB | COMPANY | TABLE | | | MYDB | EMPLOYEE | TABLE | +------------+--------------+---------------------------------+-------------+ 0: jdbc:oracle:thin:@localhost:1521:mydb>
verbose verbose 1 verbose Enable verbose output !verbose Description Enable verbose mode, which causes stack traces to be printed when errors occur, and enabled outputting of debug information. Example of "verbose" command 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM BOGUS_TABLE; Error: ORA-00942: table or view does not exist (state=42000,code=942) 0: jdbc:oracle:thin:@localhost:1521:mydb> !verbose verbose: on 0: jdbc:oracle:thin:@localhost:1521:mydb> SELECT * FROM BOGUS_TABLE; Error: ORA-00942: table or view does not exist (state=42000,code=942) java.sql.SQLException: ORA-00942: table or view does not exist at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:180) at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:208) at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:543) at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1451) at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteDescribe(TTC7Protocol.java:651) at oracle.jdbc.driver.OracleStatement.doExecuteQuery(OracleStatement.java:2110) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2324) at oracle.jdbc.driver.OracleStatement.execute(OracleStatement.java:909) at sqlline.SqlLine$Commands.sql(SqlLine.java:3183) at sqlline.SqlLine.dispatch(SqlLine.java:771) at sqlline.SqlLine.begin(SqlLine.java:634) at sqlline.SqlLine.main(SqlLine.java:332) 0: jdbc:oracle:thin:@localhost:1521:mydb>
Parameter Reference autocommit If true, then new connections will have autocommit set, otherwise, transactions will need to be explicitely committed or rolled back. Defaults to true. To change the autocommit status for a connection that is already open and active, use the autocommit command instead. autosave When set to true, any changes to preferences using the set command will cause the preferences to be saved. Otherwise, preferences will need to be explicitely saved using the save command. Defaults to false. color If true, then output to the terminal will use color for a more pleasing visual experience. Requires that the terminal support ANSI control codes (most do). Defaults to false. fastconnect When false, any new connection will cause SQLLine to access information about the available tables and columns in order to provide them as candidates for tab-completion. This can be a very slow operation for some databases, do by default it is off. Table and column information can always be explicitely retrieved using the rehash command. force When set to false, any failures during the execution of the run or record commands will cause execution to abort, preventing the execution of subsequent commands. When set to true, errors will be displayed but otherwise ignored. Defaults to false. headerinterval The interval between which the column headers will be redisplayed when using the "table" outputformat. Defaults to 100. historyfile The file to which SQLLine will save a record of all the commands issued. Defaults to HOME/sqlline/history on Windows, and HOME/.sqlline/history on all other platforms. incremental When set to false, the entire result set is fetched and buffered before being displayed, yielding optimal display column sizing. When set to true, result rows are displayed immediately as they are fetched, yielding lower latency and memory usage at the price of extra display column padding. Defaults to false. isolation The default transaction isolation that will be used for new connections. To change the isolation level of the currently active connection, use the isolation command instead. maxcolumnwidth The maximum column width to display for each colummn before truncating data when using the "table" outputformat. Defaults to 15. maxwidth The maximum width to display before truncating data when using the "table" outputformat. Defaults to attempting to query the terminal for the current width, falls back to 80. outputformat The format for how results are displayed. For details, see the information on the outputformat command. showheader If true, display the names of the columns when displaying results. Defaults to true. showwarnings If true, display any warnings that are reported on the connection after issuing any database commands. Defaults to false. silent If true, then reduce the amount of informational messages displayed. Useful for redirecting a sqlline command to a file for later parsing. Defaults to false. verbose If true, then print out the entire java stack trace whenever an error occurs, as well as displaying debugging information. Defaults to false. JDBC Driver Support
Project Information
sqlline-1.0.2/AUTHORS0000644000175000017500000000005107702643302014124 0ustar drazzibdrazzibMarc Prud'hommeaux