Derby Tools
Derby Tools
Version 10.16
Contents
Copyright................................................................................................................................5
License................................................................................................................................... 6
About this guide..................................................................................................................10
Purpose of this document...................................................................................... 10
Audience................................................................................................................... 10
How this guide is organized...................................................................................10
What are the Derby tools and utilities?............................................................................12
Overview................................................................................................................... 12
Environment setup and the Derby tools..............................................................12
About Derby databases...........................................................................................12
JDBC connection basics.........................................................................................13
JDBC drivers overview........................................................................................ 13
Database connection URLs.................................................................................13
Tools and localization............................................................................................. 14
About locales....................................................................................................... 14
Database locale...................................................................................................14
Specifying an alternate codeset.......................................................................... 15
Formatting display of locale-sensitive data......................................................... 15
Using ij................................................................................................................................. 16
Starting ij.................................................................................................................. 16
Creating a database using ij.................................................................................. 17
Starting ij using properties.....................................................................................17
Getting started with ij..............................................................................................18
Connecting to a Derby database........................................................................ 18
Using ij commands.............................................................................................. 20
Running ij scripts................................................................................................. 20
ij properties reference........................................................................................................ 22
ij.connection.connectionName property............................................................... 22
ij.database property................................................................................................. 22
ij.dataSource property............................................................................................. 23
ij.exceptionTrace property...................................................................................... 24
ij.maximumDisplayWidth property......................................................................... 25
ij.outfile property......................................................................................................25
ij.password property................................................................................................25
ij.protocol property.................................................................................................. 25
ij.protocol.protocolName property......................................................................... 26
ij.showErrorCode property......................................................................................26
ij.showNoConnectionsAtStart property................................................................. 27
ij.showNoCountForSelect property........................................................................27
ij.URLCheck property.............................................................................................. 28
ij.user property......................................................................................................... 29
derby.ui.codeset property....................................................................................... 29
derby.ui.locale property.......................................................................................... 30
ij commands and errors reference....................................................................................32
ij commands............................................................................................................. 32
Conventions for ij examples................................................................................ 32
ij SQL command behavior...................................................................................32
Absolute command..................................................................................................33
After Last command................................................................................................ 33
i
Version 10.16 Derby Tools and Utilities Guide
Async command...................................................................................................... 34
Autocommit command............................................................................................ 34
Before First command.............................................................................................35
Close command....................................................................................................... 35
Commit command....................................................................................................36
Connect command...................................................................................................36
Describe command.................................................................................................. 37
Disconnect command..............................................................................................37
Driver command.......................................................................................................38
Elapsedtime command............................................................................................ 38
Execute command................................................................................................... 39
Exit command.......................................................................................................... 40
First command......................................................................................................... 40
Get Cursor command.............................................................................................. 41
Get Scroll Insensitive Cursor command............................................................... 42
Help command......................................................................................................... 44
HoldForConnection command................................................................................44
Last command..........................................................................................................44
LocalizedDisplay command.................................................................................... 45
MaximumDisplayWidth command..........................................................................45
Next command......................................................................................................... 45
NoHoldForConnection command...........................................................................46
Prepare command....................................................................................................46
Previous command.................................................................................................. 47
Protocol command...................................................................................................47
Readonly command................................................................................................. 48
Relative command................................................................................................... 48
Remove command................................................................................................... 49
Rollback command.................................................................................................. 49
Run command.......................................................................................................... 50
Set Connection command...................................................................................... 50
Show command........................................................................................................50
Wait For command.................................................................................................. 54
Syntax for comments in ij commands...................................................................55
Syntax for identifiers in ij commands................................................................... 56
Syntax for strings in ij commands........................................................................ 56
ij errors......................................................................................................................57
ERROR SQLState............................................................................................... 57
WARNING SQLState...........................................................................................57
IJ ERROR............................................................................................................57
IJ WARNING....................................................................................................... 57
JAVA ERROR......................................................................................................57
sysinfo.................................................................................................................................. 58
sysinfo example....................................................................................................... 58
Using sysinfo to check the classpath................................................................... 59
dblook................................................................................................................................... 60
Using dblook............................................................................................................ 60
dblook options......................................................................................................... 60
Generating the DDL for a database....................................................................... 61
dblook examples...................................................................................................... 62
SignatureChecker................................................................................................................ 64
Using SignatureChecker......................................................................................... 64
PlanExporter........................................................................................................................ 65
Using PlanExporter..................................................................................................65
ii
Version 10.16 Derby Tools and Utilities Guide
PlanExporter XML format........................................................................................66
PlanExporter example............................................................................................. 67
Optional tools...................................................................................................................... 69
Using the databaseMetaData optional tool........................................................... 69
Using the foreignViews optional tool.................................................................... 69
Using the luceneSupport optional tool................................................................. 70
Creating an index................................................................................................ 72
Updating an index............................................................................................... 75
Querying an index............................................................................................... 75
Dropping an index............................................................................................... 76
Listing indexes.....................................................................................................77
Using the simpleJson optional tool.......................................................................77
Using the rawDBReader optional tool................................................................... 79
Trademarks.......................................................................................................................... 83
iii
Derby Tools and Utilities Guide
Apache Software FoundationDerby Tools and Utilities GuideApache Derby
4
Derby Tools and Utilities Guide
Copyright
5
Derby Tools and Utilities Guide
License
The Apache License, Version 2.0
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
1. Definitions.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under
common control with that entity. For the purposes of this
definition, "control" means (i) the power, direct or indirect,
to cause the direction or management of such entity, whether by
contract or otherwise, or (ii) ownership of fifty percent (50%)
or more of the outstanding shares, or (iii) beneficial ownership
of such entity.
6
Derby Tools and Utilities Guide
that are managed by, or on behalf of, the Licensor for the
purpose of discussing and improving the Work, but excluding
communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a
Contribution."
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
7
Derby Tools and Utilities Guide
and may provide additional or different license terms and
conditions for use, reproduction, or distribution of Your
modifications, or for any such Derivative Works as a whole,
provided Your use, reproduction, and distribution of the Work
otherwise complies with the conditions stated in this License.
8
Derby Tools and Utilities Guide
Copyright [yyyy] [name of copyright owner]
http://www.apache.org/licenses/LICENSE-2.0
9
Derby Tools and Utilities Guide
Audience
The audience for this guide includes several groups.
• Developers, who might use the tools when developing applications
• System administrators, who might use the tools to run scripts that perform
administrative tasks such as backups or importing and exporting data
• End-users, who might use one of the tools to run ad-hoc queries against a database
10
Derby Tools and Utilities Guide
Reference information for a tool that identifies any SQL functions and procedures in
a database that do not follow the SQL Standard argument matching rules.
• PlanExporter
Reference information for a tool that exports query plan data for further analysis.
• Optional tools
Reference information for optional tools.
11
Derby Tools and Utilities Guide
Overview
Derby is a database management system (DBMS), accessed by applications through the
JDBC API. Included with the product are some standalone Java tools and utilities that
make it easier to use and develop applications for Derby.
These tools and utilities include:
• ij
ij is Derby's interactive JDBC scripting tool. It is a simple utility for running scripts
against a Derby database. You can also use it interactively to run ad hoc queries.
ij provides several commands for ease in accessing a variety of JDBC features.
ij can be used in an embedded or a client/server environment.
• sysinfo
sysinfo provides information about your version of Derby and your environment.
• dblook
dblook is Derby's Data Definition Language (DDL) Generation Utility, more
informally called a schema dump tool. It is a simple utility that dumps the DDL of a
user-specified database to either a console or a file. The generated DDL can then
be used for such things as recreating all or parts of a database, viewing a subset
of a database's objects (for example, those which pertain to specific tables and
schemas), or documenting a database's schema.
• SignatureChecker
The SignatureChecker tool identifies any SQL functions and procedures in a
database that do not follow the SQL Standard argument matching rules.
12
Derby Tools and Utilities Guide
13
Derby Tools and Utilities Guide
• databaseName
The name of the database you want to connect to. The databaseName value can
be either an absolute path name or a path name relative to derby.system.home, the
system directory. The path separator in the connection URL is a forward slash (/),
even in Windows path names. The database name value cannot contain a colon
(:), except for the colon after the drive name in a Windows path name.
• URLAttributes
One or more of the supported attributes of the database connection URL, such as
upgrade=true, create=true or territory=ll_CC. For more information, see "Setting
attributes for the database connection URL" in the Derby Reference Manual.
• host
The name of the machine where the server is running. It can be the name of the
machine or the address.
• port
The port number used by the server framework
About Protocols
Officially, the portion of the database connection URL called the protocol is jdbc:,
just as http:// is a protocol in web URLs. After that, derby: is officially the
subprotocol, and anything else between jdbc:derby: and databaseName is called
the subsubprotocol. See "Syntax of database connection URLs for applications with
embedded databases" in the Derby Reference Manual for details. However, the
subprotocol and subsubprotocol are informally considered part of the protocol. When you
see references to the protocol in this manual, consider the protocol to be everything that
comes before databaseName.
About locales
The Derby documentation refers to three locales.
• Java system locale
This is the locale of your machine, which is automatically detected by your JVM. For
Derby and Derby tools, the Java system locale determines the default locale.
• Database locale
This is the locale associated with your database when it is created. By default,
this is the same as the Java system locale. The database locale determines the
language of database errors.
• Tools session locale
This locale is associated with your session, when using Derby tools such as ij
or dblook. This locale determines the language of messages, as well as the
localized display format for numbers, dates, times, and timestamps. You can use
the derby.ui.locale property to specify the session locale that should be used.
14
Derby Tools and Utilities Guide
Database locale
To specify a database locale, use the territory=ll_CC attribute on the URL connection
when creating the database.
Note: You cannot modify a database's locale after the database has been created.
For information about database locales, see "Localizing Derby" in the Derby Developer's
Guide.
15
Derby Tools and Utilities Guide
Using ij
ij is Derby's interactive JDBC scripting tool. It is a simple utility for running scripts or
interactive queries against a Derby database.
ij is a Java application, which you start from a command window such as a Windows
command prompt or a UNIX shell. ij provides several non-SQL commands for ease in
accessing a variety of JDBC features for testing.
Starting ij
Derby provides batch and shell scripts for users in Windows and UNIX environments that
can be used to start ij.
By calling the appropriate script, you can start ij and be able to connect with a simple
command. The scripts are found in the bin directory of your Derby installation. You can
also customize the ij scripts to suit your environment.
If you are using Derby as a client/server environment, start the Network Server before
connecting to the Derby database. (See "Starting the Network Server" in the Derby
Server and Administration Guide for details.) You can start ij by running the ij scripts
for your environment. Follow the instructions in "Setting up your environment" in Getting
Started with Derby to set the DERBY_HOME and JAVA_HOME environment variables and
to add DERBY_HOME/bin to your path. Then use the following command:
Alternatively, set the DERBY_HOME environment variable, then use one of these
commands:
Note that you cannot use the -cp argument or the CLASSPATH environment variable to
set CLASSPATH variables when you are using the -jar argument to start the ij tool.
That is, if you want to run the ij tool with a custom classpath, then you cannot use the
-jar argument. Instead, you have to use the full class name to start the ij tool (java
org.apache.derby.tools.ij).
You can also run the ij by setting the CLASSPATH or MODULEPATH variables via the
setNetworkServerCP or setNetworkServerCP.bat scripts. Note that you first need
to set DERBY_HOME variable. To run ij from the CLASSPATH, type
16
Derby Tools and Utilities Guide
• java
Start the JVM.
• options
The options that the JVM uses. You can use the -D option to set ij properties (see
Starting ij using properties) or system properties, such as Derby properties.
• propertyFile
A file you can use to set ij properties (instead of the -D option). The property file
should be in the format created by the java.tools.Properties.save methods,
which is the same format as the derby.properties file.
• inputFile
A file from which to read commands. The ij tool exits at the end of the file or an
exit command. Using an input file causes ij to print out the commands as it runs
them. If you reroute standard input, ij does not print out the commands. If you do
not supply an input file, ij reads from the standard input.
For detailed information about ij commands, see ij commands and errors reference.
17
Derby Tools and Utilities Guide
java -Dij.connection.sample=jdbc:derby:sample \
-Dij.connection.History=jdbc:derby:History \
-Dderby.system.home=c:\derby\demo\databases \
-jar c:\derby\lib\derbyrun.jar
To see a list of connection names and the URLs used to connect to them, use the
following command. (If there is a currently active connection, it will appear with an
asterisk (*) after its name.)
ij version 10.16
ij(HISTORY)> show connections;
HISTORY* - jdbc:derby:History
SAMPLE - jdbc:derby:sample
* = current connection
ij(HISTORY)>
java org.apache.derby.tools.ij
ij version 10.16
ij> connect 'jdbc:derby:sample';
ij>
If the URL entered contains Network Client information, the Connect command loads
the Network Client driver:
java org.apache.derby.tools.ij
ij version 10.16
ij> connect 'jdbc:derby://localhost:1527/sample';
ij>
Note: In these and subsequent examples, the databases are created in the
derby.system.home directory. For more information on the System Directory, see the
Derby Developer's Guide.
ij provides alternate methods of specifying part or all of a connection URL: the
ij.protocol, ij.database, and ij.connection.connectionName properties.
These properties are often used when a script is being used and the database path name
or the driver name is not known until runtime. The properties can also to used to shorten
the amount of information that must be provided with the connection URL. The following
are some examples of different ways to supply the connection information:
• Supplying full connection information on the command line
Specifying one of the following properties along with a valid connection URL on the
ij command line starts ij with the connection already active. This mechanism
18
Derby Tools and Utilities Guide
is often used when running a SQL script, so that the database path name can be
specified at runtime.
• ij.database: Opens a connection using the URL provided
• ij.connection.connectionName: Used to open one or more
connections. The property can appear multiple times on the command line
with different connectionNames and the same or different URLs.
This example shows how to create the database myTours and run the script
ToursDB_schema.sql by specifying the database URL using the ij.database
property.
java -Dij.database=jdbc:derby:myTours;create=true \
org.apache.derby.tools.ij \
%DERBY_HOME%\demo\programs\toursdb\ToursDB_schema.sql
ij version 10.16
CONNECTION0* - jdbc:derby:myTours
* = current connection
ij> -- Licensed to the Apache Software Foundation (ASF) under one or
more
-- contributor license agreements. See the NOTICE file distributed
with
...output removed...
ij> CREATE TRIGGER TRIG2 AFTER DELETE ON FLIGHTS FOR EACH STATEMENT
MODE DB2SQL
INSERT INTO FLIGHTS_HISTORY (STATUS) VALUES ('INSERTED FROM TRIG2');
0 rows inserted/updated/deleted
ij>
• Defining a Protocol and using a "short form" URL
You can specify a default URL protocol and subprotocol by setting the property
ij.protocol or using the Protocol command. This allows you to make a
connection by specifying only the database name. This "short form" of the database
connection URL defaults the protocol (For more information, see About Protocols).
This example uses the Protocol command and a "short form" connection URL:
java org.apache.derby.tools.ij
ij version 10.16
ij> protocol 'jdbc:derby:';
ij> connect 'sample';
ij>
• Specifying an alternate driver
If you are using the drivers supplied by Derby, you can specify the driver names
listed in JDBC drivers overview. However, the Derby drivers are implicitly loaded
when a supported protocol is used, so specifying them is usually redundant. You
may find it useful to specify the driver if you need to reload it after you have shut
down the Derby engine and deregistered the driver.
To load a driver explicitly, use the ij command Driver or specify the JVM system
property jdbc.drivers.
The ij Driver name and connection URL
The following table summarizes the different ways to specify the driver name and
database connection URL.
Table 1. Specifying the driver name and database connection URL
19
Derby Tools and Utilities Guide
System
Action Property ij Property ij Command
Loading the None ij.connection.connectionName Protocol,
driver implicitly (plus full URL), ij.database Connect (plus
(plus full URL), ij.protocol, full URL)
ij.protocol.protocolName
(plus protocol clause in Connect
command)
Loading the None
jdbc.drivers Driver
driver explicitly
Specifying None ij.connection.connectionName, Connect
the database ij.database
connection URL
Using ij commands
The primary purpose of ij is to allow the execution of Derby SQL statements
interactively or by means of scripts.
Since SQL statements can be quite long, ij uses the semicolon to mark the end of
a statement or command. All statements and commands must be terminated with a
semicolon. If you press Return before terminating a statement or command, ij places a
continuation character (>) at the beginning of the next line.
ij uses properties, listed in ij properties reference, to simplify its use.
ij also recognizes specialized commands that provide additional features, such as the
ability to create and test cursors and prepared statements, transaction control, and more.
For complete information about ij commands, see ij commands and errors reference.
Other uses for ij
ij is a JDBC-neutral scripting tool with a small command set. It can be used to access
any JDBC driver and any database accessible through that driver.
The main benefit of a tool such as ij is that it is easy to run scripts for creating a
database schema and automating other repetitive database tasks.
In addition, ij accepts and processes SQL commands interactively for ad hoc database
access.
Running ij scripts
You can run scripts in ij in any of the following ways.
• Name an input file as a command-line argument.
For example:
20
Derby Tools and Utilities Guide
ij> run 'myscript.sql';
Note: If you name an input file as a command-line argument or if you use the Run
command, ij echoes input from a file. If you redirect standard input to come from a file,
ij does not echo commands.
You can save output in any of the following ways:
• By redirecting output to a file:
21
Derby Tools and Utilities Guide
ij properties reference
When starting up ij, you can specify properties on the command line or in a properties
file.
See Starting ij using properties for details.
ij.connection.connectionName property
The ij.connection.connectionName property creates a named connection to the
given database connection URL when ij starts up.
The property is equivalent to the Connect AS Identifier command. The database
connection URL can be of the short form if an ij.protocol is specified. This property
can be specified more than once per session, creating multiple connections. When ij
starts, it displays the names of all the connections created in this way. It also displays the
name of the current connection, if there is more than one, in the ij prompt.
Syntax
ij.connection.connectionName=databaseConnectionURL
java -Dij.connection.sample1=jdbc:derby:sample \
-Dij.connection.anotherConn=jdbc:derby:anotherDB;create=true \
org.apache.derby.tools.ij
ij version 10.16
ANOTHERCONN* - jdbc:derby:anotherDB;create=true
SAMPLE1 - jdbc:derby:sample
* = current connection
ij(ANOTHERCONN)>
See also
• Connect command
ij.database property
The ij.database property creates a connection to the database specified by the
property when ij starts up.
You can specify the complete connection URL (including protocol) with this property,
or you can specify just the database path name and URL attributes if you also specify
ij.protocol on the command line. After it boots, ij displays the generated name of
the connection made with this property.
Syntax
ij.database=databaseConnectionURL
The database path name value in the databaseConnectionURL can be either an absolute
path name or a path name relative to derby.system.home. For example, thisDB,
22
Derby Tools and Utilities Guide
databases/thisDB, and c:/databases/2014/january/thisDB can all be valid
values.
The path separator in the connection URL is a forward slash (/), even in Windows path
names. The database name value cannot contain a colon (:), except for the colon after
the drive name in a Windows path name.
When specified on the command line, the databaseConnectionURL should not be
enclosed in single quotes. However, if the connection URL contains special characters
(such as a space, or a semicolon on a UNIX system), it must be enclosed in double
quotes.
Example
java -Dij.protocol=jdbc:derby: \
-Dij.database="wombat;create=true" org.apache.derby.tools.ij
ij version 10.16
CONNECTION0* - jdbc:derby:wombat
* = current connection
ij>
ij.dataSource property
The ij.dataSource property specifies the datasource to be used to access the
database.
When specifying a datasource, ij does not use the DriverManager mechanism to
establish connections.
Syntax
When you set the ij.dataSource property, ij will automatically try to
connect to a database. To establish a connection to a specific database using
ij.dataSource, set the ij.dataSource.databaseName property. If you
do not set this property, ij will start with an error. If you want to create the
database, specify the ij.dataSource.createDatabase property as well as
ij.dataSource.databaseName. Do not specify ij.protocol when setting
ij.dataSource, as that would activate the DriverManager mechanism.
ij.dataSource=datasourceClassName
ij.dataSource.databaseName=databaseName
[ij.dataSource.createDatabase=create]
java -Dij.dataSource=org.apache.derby.jdbc.EmbeddedDataSource \
-Dij.dataSource.databaseName=sample \
-Dij.dataSource.createDatabase=create org.apache.derby.tools.ij
ij version 10.16
CONNECTION0*
* = current connection
ij>
See also
23
Derby Tools and Utilities Guide
For more information about DataSources, refer to the JDBC documentation in the Derby
API documentation and to "JDBC reference" in the Derby Reference Manual, and to
"Using Derby as a Java EE Resource Manager" in the Derby Developer's Guide.
ij.exceptionTrace property
The ij.exceptionTrace property specifies whether ij should display a full exception
stack trace when exceptions occur.
The default setting is false.
Syntax
Example
In the following example, ij is started with the ij.exceptionTrace property set to
true.
24
Derby Tools and Utilities Guide
... 22 more
ij>
ij.maximumDisplayWidth property
The ij.maximumDisplayWidth property specifies the maximum number of characters
used to display any column.
The default value is 128. Values with display widths longer than the maximum are
truncated and terminated with an ampersand (&) character.
Syntax
ij.maximumDisplayWidth=numberOfCharacters
Example
See also
• MaximumDisplayWidth command
ij.outfile property
The ij.outfile property specifies a file to which the system should direct output for a
session.
Specify the file name relative to the current directory, or specify the absolute path.
Syntax
ij.outfile=fileName
Example
ij.password property
The ij.password property specifies the password used to make connections.
This property is used in conjunction with the ij.user property to authenticate a
connection. If authentication is not active, these properties are ignored.
Syntax
ij.password=password
Example
See also
See the Derby Security Guide for more information on Derby authentication and security.
ij.protocol property
The ij.protocol property specifies the default protocol and subprotocol portions of the
database connection URL for connections.
The Derby protocol is:
25
Derby Tools and Utilities Guide
jdbc:derby:
The property allows you to use a short form of a database name in a connection URL.
Syntax
ij.protocol=protocolForEnvironment
Example
See also
• Protocol command
ij.protocol.protocolName property
The ij.protocol.protocolName property is similar to the ij.protocol property.
The only difference is that it associates a name with the value, thus allowing you to define
and use more than one protocol.
Syntax
ij.protocol.protocolName=protocolForEnvironment
Example
java -Dij.protocol.derby=jdbc:derby: \
-Dij.protocol.emp=jdbc:derby: org.apache.derby.tools.ij
ij version 10.16
ij> Connect 'newDB' protocol derby as new;
ij>
See also
• ij.protocol property
• Protocol command
• Connect command
ij.showErrorCode property
The ij.showErrorCode property specifies whether ij should display the
SQLException ErrorCode value with error messages.
The default value is false.
Error codes denote the severity of the error.
Syntax
Example
26
Derby Tools and Utilities Guide
See also
See "Derby exception messages and SQL states" in the Derby Reference Manual.
ij.showNoConnectionsAtStart property
The ij.showNoConnectionsAtStart property specifies whether the connections
message should be displayed when ij is started.
The default is false; that is, a message is displayed that indicates the current
connections, if any.
Syntax
Example
In the following example, ij connects to a previously created database named sample
using an EmbeddedDataSource. The property ij.showNoConnectionsAtStart is
set to true in the first session of the example and to false in the second session.
java -Dij.dataSource=org.apache.derby.jdbc.EmbeddedDataSource \
-Dij.dataSource.databaseName=sample -Dij.showNoConnectionsAtStart=true \
org.apache.derby.tools.ij
ij version 10.16
ij> disconnect;
ij> exit;
java -Dij.dataSource=org.apache.derby.jdbc.EmbeddedDataSource \
-Dij.dataSource.databaseName=sample -Dij.showNoConnectionsAtStart=false \
org.apache.derby.tools.ij
ij version 10.16
CONNECTION0*
* = current connection
ij> disconnect;
ij> exit;
ij.showNoCountForSelect property
The ij.showNoCountForSelect property specifies whether to display messages
indicating the number of rows selected.
The default is false; that is, if the property is not set, select count messages are
displayed.
Syntax
Example
In the following example, ij is first started with the ij.showNoCountForSelect
property set to true, then with the property set to false.
27
Derby Tools and Utilities Guide
1
2
3
ij> disconnect;
ij> exit;
3 rows selected
ij>
ij.URLCheck property
The ij.URLCheck property specifies whether ij should check for invalid or non-Derby
URL attributes when you are using the embedded driver.
Set this property to false to prevent ij from validating URL attributes. The default value
is true.
When the ij.URLCheck property is set to true, you are notified whenever a connection
URL contains an incorrectly specified attribute. For example, if the attribute name is
misspelled or has an incorrect case, ij prints a message.
Note: ij checks attribute values if the attribute has pre-defined values. For example,
the attribute shutdown has the pre-defined values of true or false. If you try to set
the attribute shutdown to a value other than true or false, ij displays an error. For
example:
Syntax
Example
By default, ij displays messages about invalid attributes:
java org.apache.derby.tools.ij
ij version 10.16
ij> connect 'mydb;uSer=naomi';
URL Attribute [uSer=naomi]
Case of the Derby attribute is incorrect.
The following command line turns off URL attribute checking in ij.
Typically, you would only explicitly turn off the URL checker if you were using ij with a
non-Derby JDBC driver or database.
Notes
28
Derby Tools and Utilities Guide
The URL checker does not check the validity of properties, only database connection
URL attributes.
For a list of attributes, see "Setting attributes for the database connection URL" in the
Derby Reference Manual. Because the ij.URLCheck property is valid only with the
embedded driver, it does not apply to attributes such as securityMechanism=value,
ssl=sslMode, and the attributes related to tracing.
ij.user property
The ij.user property specifies the login name used to establish the connection.
This property is used in conjunction with the ij.password property to authenticate a
connection. If authentication is not active, these properties are ignored.
When you supply a username, you need to be aware of the database schema. When
you connect using ij.user, the default database schema applied to all SQL statements
is the same as the user ID provided, even if the schema does not exist. Use the SET
SCHEMA statement to change the default when the schema does not match the
username. Alternately, you can fully qualify the database objects referred to in the SQL
statements. If no user is specified, no SET SCHEMA statement has been issued, or SQL
statements do not include the schema name, all database objects are assumed to be
under the APP schema.
Syntax
ij.user=username
Example
See also
See the Derby Security Guide for more information on Derby authentication and security.
derby.ui.codeset property
The derby.ui.codeset property specifies an alternative supported character encoding
value when you use one of the Derby tools with a language not supported by your default
system.
This property is commonly used in conjunction with the derby.ui.locale property.
Syntax
derby.ui.codeset=derbyval
where derbyval is a supported character encoding value, such as UTF8 (see the table
later in this topic).
Example
The following command runs ij using the Japanese locale
(derby.ui.locale=ja_JP) and Japanese Latin Kanji mixed encoding
(derby.ui.codeset=Cp939):
29
Derby Tools and Utilities Guide
The following table contains a sampling of character encodings. Supported encodings
vary from product to product. For example, to see the full list of character encodings that
are supported by the Java Platform, Standard Edition 7 Software Development Kit, go to
http://docs.oracle.com/javase/7/docs/technotes/guides/intl/encoding.doc.html.
Table 2. Sample character encodings
derby.ui.locale property
The derby.ui.locale property specifies an alternative supported locale name when
you use one of the Derby tools with a language not supported by your default system.
The locale determines the localized display format for numbers, dates, times, and
timestamps, as well as the language of the messages from the Derby tools.
This property is commonly used in conjunction with the derby.ui.codeset property.
Syntax
derby.ui.locale=derbyval
where derbyval is a supported locale name, in the form ll_CC, where ll is the two-letter
language code, and CC is the two-letter country code; for example, ja_JP.
Example
The following command runs ij using the Japanese locale
(derby.ui.locale=ja_JP) and Japanese Latin Kanji mixed encoding
(derby.ui.codeset=Cp939):
Language codes consist of a pair of lowercase letters that conform to ISO 639-1. The
following table shows some examples.
30
Derby Tools and Utilities Guide
Table 3. Sample language codes
31
Derby Tools and Utilities Guide
ij commands
ij accepts several commands to control its use of JDBC.
It recognizes a semicolon as the end of an ij or SQL command; it treats semicolons
within SQL comments, strings, and delimited identifiers as part of those constructs, not as
the end of the command. A semicolon is required at the end of an ij or SQL statement.
All ij commands, identifiers, and keywords are case-insensitive.
Commands can span multiple lines without any special escaping for the ends of lines.
This means that if a string spans a line, the new lines will appear in the value in the
string.
ij treats any command that it does not recognize as an SQL command to be passed
to the underlying connection, so syntactic errors in ij commands will cause them to be
handed to the SQL engine and will probably result in SQL parsing errors.
32
Derby Tools and Utilities Guide
To display a result set, ij formats a banner based on the JDBC ResultSetMetaData
information returned from getColumnLabel and getColumnWidth. Long columns wrap the
screen width, using multiple lines. An & character denotes truncation (ij limits displayed
width of a column to 128 characters by default; see MaximumDisplayWidth command).
ij displays rows as it fetches them. If the underlying DBMS materializes rows only as
they are requested, ij displays a partial result followed by an error message if there is a
error in fetching a row partway through the result set.
ij verifies that a connection exists before issuing statements against it and does not
execute SQL when no connection has yet been made.
There is no support in ij for the JDBC feature multiple result sets.
ij command example
3 rows selected
ij>
Absolute command
The Absolute command moves the cursor to the row specified by the int argument,
then fetches the row.
The command displays a banner and the values of the row. The cursor must have been
created with the Get Scroll Insensitive Cursor command.
Syntax
Example
Example
33
Derby Tools and Utilities Guide
ij> get scroll insensitive cursor scrollCursor as
'SELECT * FROM menu FOR UPDATE OF price';
ij> after last scrollcursor;
No current row
Async command
The Async command lets you execute an SQL statement in a separate thread.
This command is used in conjunction with the Wait For command to get the results.
Syntax
You supply the SQL statement, which is any valid SQL statement, as a String. The
Identifier you must supply for the async SQL statement is used in the Wait For
command and is a case-insensitive ij identifier. An identifier that does not specify a
connectionName must not be the same as any other identifier for an async statement
on the current connection; an identifier that specifies a connectionName must not be
the same as any other identifier for an async statement on the designated connection.
You cannot reference a statement previously prepared and named by the ijPrepare
command in this command.
ij creates a new thread in the current or designated connection to issue the SQL
statement. The separate thread is closed once the statement completes.
Examples
3 rows selected
ij(FRED_CONN)>
Autocommit command
The Autocommit command turns the connection's auto-commit mode on or off.
JDBC specifies that the default auto-commit mode is ON. Certain types of processing
require that auto-commit mode be OFF. For information about auto-commit, see the
Derby Developer's Guide.
If auto-commit mode is changed from off to on when there is a transaction outstanding,
that work is committed when the current transaction commits, not at the time auto-commit
34
Derby Tools and Utilities Guide
is turned on. Use Commit or Rollback before turning on auto-commit when there
is a transaction outstanding, so that all prior work is completed before the return to
auto-commit mode.
Syntax
AUTOCOMMIT { ON | OFF }
Example
Example
Close command
The Close command closes the named cursor.
The cursor must have previously been successfully created with ij's Get Cursor or
Get Scroll Insensitive Cursor command.
Syntax
CLOSE Identifier
Example
35
Derby Tools and Utilities Guide
dessert |creme brulee |6
ij> close menuCursor;
ij>
Commit command
The Commit command issues a java.sql.Connection.commit request.
Use this command only if auto-commit is off. A java.sql.Connection.commit request
commits the currently active transaction and initiates a new transaction.
Syntax
COMMIT
Example
ij> commit;
ij>
Connect command
The Connect command connects to the database indicated by the ConnectionURLString
argument.
Specifically, the command takes the value of the ConnectionURLString (the database
connection URL) and issues a getConnection request using java.sql.DriverManager or
a javax.sql.DataSource implementation (see the ij.dataSource property) to set the
current connection to that database connection URL.
You have the option of specifying a name for your connection. Use the Set
Connection command to switch between connections. If you do not name a connection,
the system generates a name automatically.
You also have the option of specifying a named protocol previously created with the
Protocol command or the ij.protocol.protocolName property.
If the connection requires a user name and password, supply those with the optional user
and password parameters.
If the command succeeds, the connection becomes the current one, and ij displays
a new prompt for the next command to be entered. If you have more than one open
connection, the name of the connection appears in the prompt.
All further commands are processed against the new, current connection.
Syntax
Examples
36
Derby Tools and Utilities Guide
ij> connect 'jdbc:derby:sample' user 'sa' password 'cloud3x9';
ij>
Describe command
The Describe command provides a decription of the specified table or view.
For a list of tables in the current schema, use the Show Tables command. For a list
of views in the current schema, use the Show Views command. For a list of available
schemas, use the Show Schemas command.
If the table or view is in a particular schema, qualify it with the schema name. If the
table or view name is case-sensitive, enclose it in single quotes. You can display all the
columns from all the tables and views in a single schema in a single display by using the
wildcard character '*'. See the examples below.
Syntax
Examples
Disconnect command
The Disconnect command disconnects from the database.
Specifically, Disconnect issues a java.sql.Connection.close request against the
connection indicated on the command line. There must be a current connection at the
time the request is made.
Syntax
37
Derby Tools and Utilities Guide
If ALL is specified, all known connections are closed, and there will be no current
connection.
Disconnect CURRENT is the same as Disconnect without indicating a connection:
the default connection is closed.
If a connection name is specified with a ConnectionIdentifier, the command disconnects
the named connection. The name must be the name of a connection in the current
session provided with the ij.connection.connectionName property or with the
Connect command.
If the ij.database property or the Connect command without the AS clause was
used, you can supply the name the system generated for the connection. If the current
connection is the named connection, when the command completes, there will be no
current connection, and you must issue a Set Connection or Connect command.
A Disconnect command issued against a Derby connection does not shut down the
database or Derby (but the Exit command does).
Example
Driver command
The Driver command takes the value of the DriverNameString argument and issues a
Class.forName request to load the named class.
The class is expected to be a JDBC driver that registers itself with
java.sql.DriverManager.
You may find this command useful if you need to reload the driver after you have shut
down the Derby engine and deregistered the driver.
If the Driver command succeeds, a new ij prompt appears for the next command.
Syntax
DRIVER DriverNameString
Example
38
Derby Tools and Utilities Guide
Elapsedtime command
The Elapsedtime command, if set to ON, displays the total time elapsed during
statement execution.
The default value is OFF.
Syntax
ELAPSEDTIME { ON | OFF }
Example
Execute command
The Execute command executes an SQL statement or a named prepared statement.
Syntax
39
Derby Tools and Utilities Guide
ij> commit;
3 rows selected
ij> connect 'jdbc:derby:seconddb;create=true';
ij(CONNECTION1)> create table newtable (newid int primary key,
newname varchar(12));
0 rows inserted/updated/deleted
ij(CONNECTION1)> prepare src@connection0 as 'select * from firsttable';
ij(CONNECTION1)> autocommit off;
ij(CONNECTION1)> execute 'insert into newtable(newid, newname)
values(?,?)' using src@connection0;
1 row inserted/updated/deleted
1 row inserted/updated/deleted
1 row inserted/updated/deleted
ij(CONNECTION1)> commit;
ij(CONNECTION1)> select * from newtable;
NEWID |NEWNAME
------------------------
10 |TEN
20 |TWENTY
30 |THIRTY
3 rows selected
ij(CONNECTION1)> show connections;
CONNECTION0 - jdbc:derby:firstdb
CONNECTION1* - jdbc:derby:seconddb
ij(CONNECTION1)> disconnect connection0;
ij>
Exit command
The Exit command causes the ij application to complete and processing to halt.
Issuing this command from within a file started with the Run command or on the
command line causes the outermost input loop to halt.
ij automatically shuts down a Derby database running in an embedded environment
(that is, it issues a Connect 'jdbc:derby:;shutdown=true' request) on exit.
ij exits when the Exit command is entered or, if given a command file on the Java
invocation line, when the end of the command file is reached.
Syntax
EXIT
Example
ij> disconnect;
ij> exit;
40
Derby Tools and Utilities Guide
First command
The First command moves the cursor to the first row in the ResultSet, then fetches the
row.
The command displays a banner and the values of the row. The cursor must have been
created with the Get Scroll Insensitive Cursor command.
Syntax
FIRST Identifier
Example
WITH HOLD is the default attribute of the cursor. For a non-holdable cursor, use the WITH
NOHOLD option.
Examples
41
Derby Tools and Utilities Guide
appetizer |baby greens salad |7
ij> close menuCursor;
ij> commit;
ij>
42
Derby Tools and Utilities Guide
GET SCROLL INSENSITIVE [ WITH { HOLD | NOHOLD } ]
CURSOR Identifier AS String
WITH HOLD is the default attribute of the cursor. For a non-holdable cursor, use the WITH
NOHOLD option.
Examples
43
Derby Tools and Utilities Guide
-----------
1
ij(FRED_CONN)> after last john_cursor@john_conn;
No current row
ij(FRED_CONN)> before first john_cursor@john_conn;
No current row
ij(FRED_CONN)> relative 2 john_cursor@john_conn;
C
-----------
2
ij(FRED_CONN)> absolute 1 john_cursor@john_conn;
C
-----------
1
ij(FRED_CONN)> close john_cursor@john_conn;
ij(FRED_CONN)> disconnect all;
ij>
Help command
The Help command prints out a brief list of the ij commands.
Syntax
HELP
HoldForConnection command
The HoldForConnection command sets the default holdability for a connection to the
default ResultSet.HOLD_CURSORS_OVER_COMMIT.
Syntax
HOLDFORCONNECTION
Example
ij> HOLDFORCONNECTION;
Last command
The Last command moves the cursor to the last row in the ResultSet, then fetches the
row.
The command displays a banner and the values of the row. The cursor must have been
created with the Get Scroll Insensitive Cursor command.
Syntax
LAST Identifier
Example
44
Derby Tools and Utilities Guide
LocalizedDisplay command
The LocalizedDisplay command specifies that ij should display locale-sensitive
data (such as dates) in the native format for the ij locale.
The ij locale is the same as the Java system locale.
Syntax
LOCALIZEDDISPLAY { on | off }
Example
The following demonstrates LocalizedDisplay in an English locale:
1 row selected
ij> localizeddisplay on;
ij> VALUES CURRENT_DATE;
1
------------------
July 1, 2014
1 row selected
MaximumDisplayWidth command
The MaximumDisplayWidth command sets the largest display width for columns to the
specified value.
This command is generally used to increase the default value in order to display large
blocks of text.
Syntax
MAXIMUMDISPLAYWIDTH integer_value
Example
ij> maximumdisplaywidth 3;
ij> VALUES 'NOW IS THE TIME!';
1
---
NOW
ij> maximumdisplaywidth 30;
ij> VALUES 'NOW IS THE TIME!';
1
----------------
NOW IS THE TIME!
Next command
The Next command fetches the next row from the specified named cursor.
The command displays a banner and the values of the row. The cursor must have been
created with the Get Cursor or Get Scroll Insensitive Cursor command.
Syntax
NEXT Identifier
45
Derby Tools and Utilities Guide
Example
NoHoldForConnection command
The NoHoldForConnection command changes the default holdability
for a connection from ResultSet.HOLD_CURSORS_OVER_COMMIT to
ResultSet.CLOSE_CURSORS_AT_COMMIT.
Syntax
NOHOLDFORCONNECTION
Example
ij> NOHOLDFORCONNECTION;
Prepare command
The Prepare command creates a java.sql.PreparedStatement using the value of the
specified String, accessible in ij by the Identifier given to it.
If a prepared statement with that name already exists in ij, an error will be returned, and
the previous prepared statement will remain. Use the Remove command to remove the
previous statement first. If there are any errors in preparing the statement, no prepared
statement is created.
Any SQL statements allowed in the underlying connection's prepared statement can be
prepared with this command.
If the Identifier specifies a connectionName, the statement is prepared on the specified
connection.
Syntax
Examples
2 rows selected
ij>
46
Derby Tools and Utilities Guide
------------------------
10 |TEN
20 |TWENTY
30 |THIRTY
3 rows selected
ij> connect 'jdbc:derby:seconddb;create=true';
ij(CONNECTION1)> create table newtable (newid int primary key,
newname varchar(12));
0 rows inserted/updated/deleted
ij(CONNECTION1)> prepare src@connection0 as 'select * from firsttable';
ij>
Previous command
The Previous command moves the cursor to the row previous to the current one, then
fetches the row.
The command displays a banner and the values of the row. The cursor must have been
created with the Get Scroll Insensitive Cursor command.
Syntax
PREVIOUS Identifier
Example
Protocol command
The Protocol command specifies the protocol for establishing connections and
automatically loads the appropriate driver.
Providing a protocol allows you to use a shortened database connection URL for
connections. You can provide only the database name (and a subsubprotocol name
if needed) instead of the full protocol. In addition, you do not need to use the Driver
command or specify a driver at start-up, since the driver is loaded automatically.
Syntax
The protocol specified by the String is the part of the database connection URL syntax
appropriate for your environment, including the JDBC protocol and the protocol specific to
Derby. For further information about the Derby database connection URL, see Database
connection URLs. Only Derby protocols are supported. Those protocols are listed in
ij.protocol property.
If you name the protocol by specifying an Identifier, you can refer to the protocol name in
the Connect command.
Examples
47
Derby Tools and Utilities Guide
ij> connect 'sample';
Readonly command
The Readonly command sets the current connection to a "read-only" connection, as if
the current user were defined as a readOnlyAccess user.
For more information about database authorization, see "Configuring user authorization"
in the Derby Security Guide.
Syntax
READONLY { ON | OFF }
Example
Relative command
The Relative command moves the cursor to the row that is the specified number of
rows relative to the current row, then fetches the row.
The command displays a banner and the values of the row. The cursor must have been
created with the Get Scroll Insensitive Cursor command.
Syntax
Example
48
Derby Tools and Utilities Guide
ij> relative 1 scrollcursor;
COURSE |ITEM |PRICE
-----------------------------------------------
dessert |creme brulee |6
Remove command
The Remove command removes a previously prepared statement from ij.
Syntax
REMOVE Identifier
The specified Identifier is the name by which the statement was prepared. The statement
is closed to release its database resources.
Example
2 rows selected
ij> remove seeMenu;
ij> execute seeMenu;
IJ ERROR: Unable to establish prepared statement SEEMENU
ij>
Rollback command
The Rollback command issues a java.sql.Connection.rollback request.
Use this command only if auto-commit is off. A java.sql.Connection.rollback request
undoes the currently active transaction and initiates a new transaction.
Syntax
ROLLBACK
Example
4 rows selected
ij> rollback;
ij> SELECT * FROM menu;
COURSE |ITEM |PRICE
-----------------------------------------------
entree |lamb chop |14
dessert |creme brulee |7
appetizer |baby greens |7
3 rows selected
ij>
49
Derby Tools and Utilities Guide
Run command
The Run command redirects ij processing to read from a specified file.
The command assumes that the value of the specified String is a valid file name. It
reads from that file until it ends or an Exit command is executed. If the end of the file is
reached without ij exiting, reading will continue from the previous input source once the
end of the file is reached. Files can contain additional Run commands.
ij prints out the statements in the file as it executes them.
Any changes made to the ij environment by the file are visible in the environment when
processing resumes.
Syntax
RUN String
Example
Example
Show command
The Show command displays information about active connections and database objects.
Syntax
SHOW
50
Derby Tools and Utilities Guide
{
CONNECTIONS |
FUNCTIONS [ IN schemaName ] |
INDEXES [ IN schemaName | FROM tableName ] |
PROCEDURES [ IN schemaName ] |
ROLES |
ENABLED_ROLES |
SETTABLE_ROLES |
SCHEMAS |
SYNONYMS [ IN schemaName ] |
TABLES [ IN schemaName ] |
VIEWS [ IN schemaName ] |
SHOW CONNECTIONS
If there are no connections, the SHOW CONNECTIONS command returns "No connections
available".
Otherwise, the command displays a list of connection names and the URLs used to
connect to them. The currently active connection, if there is one, is marked with an
asterisk (*) after its name.
SHOW CONNECTIONS Example
SHOW FUNCTIONS
The SHOW FUNCTIONS command displays all functions in the database. By default, both
system functions and user-defined functions appear in the output.
If IN schemaName is specified, only the functions in the specified schema are displayed.
SHOW FUNCTIONS Example
If you created the TO_DEGREES function described in "CREATE FUNCTION statement"
in the Derby Reference Manual, the output of the CREATE FUNCTION statement and
the SHOW FUNCTIONS command would look something like the following:
1 row selected
SHOW INDEXES
The SHOW INDEXES command displays all the indexes in the database.
If IN schemaName is specified, only the indexes in the specified schema are displayed.
If FROM tableName is specified, only the indexes on the specified table are displayed.
51
Derby Tools and Utilities Guide
SHOW INDEXES Examples
16 rows selected
ij> show indexes from flights;
TABLE_NAME |COLUMN_NAME |NON_U&|TYPE|ASC&|CARDINA&|PAGES
-------------------------------------------------------------------------
---
FLIGHTS |FLIGHT_ID |false |3 |A |NULL |NULL
FLIGHTS |SEGMENT_NUMBER |false |3 |A |NULL |NULL
FLIGHTS |DEST_AIRPORT |true |3 |A |NULL |NULL
FLIGHTS |ORIG_AIRPORT |true |3 |A |NULL |NULL
4 rows selected
SHOW PROCEDURES
The SHOW PROCEDURES command displays all the procedures in the database that have
been created with the CREATE PROCEDURE statement, as well as system procedures.
If IN schemaName is specified, only procedures in the specified schema are displayed.
SHOW PROCEDURES Example
18 rows selected
52
Derby Tools and Utilities Guide
The SHOW ROLES command displays the names of all roles created, whether settable for
the current session or not.
The SHOW ENABLED_ROLES command displays the names of all the roles whose
privileges are available for the current session. That is, it shows the current role and any
role contained in the current role. (For a definition of role containment, see "Using SQL
roles" in the Derby Security Guide.)
The SHOW SETTABLE_ROLES command displays all the roles that the current session
can set, that is, all roles that have been granted to the current user or to PUBLIC.
The roles shown by these commands are sorted in ascending order.
SHOW ROLES, SHOW ENABLED_ROLES, and SHOW SETTABLE_ROLES
Examples
In the following examples, both CASUALUSER and POWERUSER contain ANYUSER,
but ANYUSER is not settable directly.
3 rows selected
ij> show enabled_roles;
ROLEID
------------------------------
ANYUSER
CASUALUSER
2 rows selected
ij> show settable_roles;
ROLEID
------------------------------
CASUALUSER
POWERUSER
2 rows selected
SHOW SCHEMAS
The SHOW SCHEMAS command displays all of the schemas in the current connection.
SHOW SCHEMAS Example
11 rows selected
SHOW SYNONYMS
53
Derby Tools and Utilities Guide
The SHOW SYNONYMS command displays all the synonyms in the database that have
been created with the CREATE SYNONYMS statement.
If IN schemaName is specified, only synonyms in the specified schema are displayed.
SHOW SYNONYMS Example
SHOW TABLES
The SHOW TABLES command displays all of the tables in the current schema.
If IN schemaName is specified, the tables in the given schema are displayed.
SHOW TABLES Example
7 rows selected
SHOW VIEWS
The SHOW VIEWS command displays all of the views in the current schema.
If IN schemaName is specified, the views in the given schema are displayed.
SHOW VIEWS Example
1 row selected
Example
See Async command.
54
Derby Tools and Utilities Guide
-- Text
/* Text */
You can use a double dash to create a comment anywhere within an ij command line
and as permitted by the underlying connection within SQL commands. The comment is
ended at the first new line encountered in the text.
Comments are ignored on input and have no effect on the output displayed.
You can also enclose text in /* */ characters to create either one-line or multi-line
comments. Nested comments are permitted. For example, you could put lines like the
following into a script named comment.sql:
/* start the file with a /* nested comment */ and see what happens */
connect 'jdbc:derby:newdb;create=true';
values 'hi!';
create table t (x int);
/* use a multi-line comment */
/*
insert into t values 1, 2, 3;
insert into t values 4, 5, 6;
*/
/* end the file with a comment */
values 'This is a test';
/* This is also a test */
Examples
1 row selected
ij> create table t (x int);
0 rows inserted/updated/deleted
ij> /* use a multi-line comment */
/*
insert into t values 1, 2, 3;
insert into t values 4, 5, 6;
*/
/* end the file with a comment */
values 'This is a test';
1
--------------
This is a test
1 row selected
ij> /* This is also a test */
;
55
Derby Tools and Utilities Guide
ij>
Identifier [ @ connectionName ]
These ij identifiers are case-insensitive. They must begin with a letter in the range A-Z,
and they can consist of any number of letters in the range A-Z, digits in the range 0-9,
and underscore (_) characters.
An identifier can optionally use an at sign (@) followed by a connectionName. Spaces on
either side of the @ sign are optional. If you specify a connectionName, you can refer to
databases on different connections. This capability enables you to perform tasks such
as copying data from one database to another. For an example of copying data between
databases, see Execute command. For other examples, see Async command, Get
Cursor command, and Get Scroll Insensitive Cursor command.
Examples
These are valid ij identifiers:
foo1
exampleIdentifier12345
another_one
myId@connection0
id2 @ connection1
'Text'
ij strings are represented by the same literal format as SQL strings and are delimited
by single quotation marks. To include a single quotation mark in a string, you must use
two single quotation marks, as shown in the examples below. ij places no limitation on
the lengths of strings, and will treat embedded new lines in the string as characters in the
string.
Some ij commands execute SQL commands specified as strings. Therefore, you must
double any single quotation marks within such strings, as shown in the second example
below.
The cases of letters within a string are preserved.
Examples
56
Derby Tools and Utilities Guide
--returns Joe's
execute 'VALUES ''Joe''''s''';
ij errors
ij might issue messages to inform the user of errors during processing of statements.
ERROR SQLState
When the underlying JDBC driver returns an SQLException, ij displays the
SQLException message with the prefix "ERROR SQLState". If the SQLException has no
SQLState associated with it, the prefix "ERROR (no SQLState)" is used.
WARNING SQLState
Upon completion of execution of any JDBC request, ij issues a getWarnings request
and displays the SQLWarnings that are returned.
Each SQLWarning message is displayed with the prefix "WARNING SQLState". If an
SQLWarning has no SQLState associated with it, the prefix "WARNING (no SQLState)"
is used.
IJ ERROR
When ij runs into errors processing user commands, it prints out a message with the
prefix "IJ ERROR".
Examples of errors include being unable to open the file named in a Run command and
not having a connection to disconnect from.
IJ WARNING
ij displays warning messages to let the user know if behavior might be unexpected. ij
warnings are prefixed with "IJ WARNING".
JAVA ERROR
When an unexpected Java exception occurs, ij prints a message with the prefix "JAVA
ERROR".
57
Derby Tools and Utilities Guide
sysinfo
Use the sysinfo utility to display information about your Java environment and Derby
(including version information).
To use sysinfo, do one of the following:
• If you are relatively new to the Java programming language, follow the
instructions in "Setting up your environment" in Getting Started with Derby
to set the DERBY_HOME and JAVA_HOME environment variables and to add
DERBY_HOME/bin to your path. Then use the following command:
sysinfo
• If you are a regular Java user but are new to Derby, set the DERBY_HOME
environment variable, then use a java command to invoke the derbyrun.jar file:
java org.apache.derby.tools.sysinfo
sysinfo example
When you run the sysinfo command using the derbyrun.jar file, the output looks
something like this.
58
Derby Tools and Utilities Guide
Found support for locale: [it]
version: 10.11.0.0 - (2222222)
Found support for locale: [ja_JP]
version: 10.11.0.0 - (2222222)
Found support for locale: [ko_KR]
version: 10.11.0.0 - (2222222)
Found support for locale: [pl]
version: 10.11.0.0 - (2222222)
Found support for locale: [pt_BR]
version: 10.11.0.0 - (2222222)
Found support for locale: [ru]
version: 10.11.0.0 - (2222222)
Found support for locale: [zh_CN]
version: 10.11.0.0 - (2222222)
Found support for locale: [zh_TW]
version: 10.11.0.0 - (2222222)
------------------------------------------------------
When you request help for a problem by posting to the derby-user mailing list, include a
copy of the information provided by the sysinfo utility.
If your environment is set up correctly, the utility shows output indicating success.
You can provide optional arguments with -cp to test different environments. Optional
arguments to -cp are:
• embedded
• server
• client
• tools
• classname.class
If something is missing from your classpath, the utility indicates what is missing.
For example, if you neglected to include the directory containing the class named
SimpleApp in your classpath, the utility would indicate this when the following command
line was issued (enter all on one line):
59
Derby Tools and Utilities Guide
dblook
Use the dblook utility to view all or parts of the Data Definition Language (DDL) for a
given database.
To use the dblook utility, do one of the following:
• If you are relatively new to the Java programming language, follow the
instructions in "Setting up your environment" in Getting Started with Derby
to set the DERBY_HOME and JAVA_HOME environment variables and to add
DERBY_HOME/bin to your path. Then use the following command:
Using dblook
The syntax for the command to launch the dblook utility is as follows.
The value for connectionURL is the complete URL for the database. Where appropriate,
the URL includes any connection URL attributes that might be required to access the
database. For complete information on connection URL attributes, see "Setting attributes
for the database connection URL" in the Derby Reference Manual.
For example, to connect to the database myDB, the URL would simply be
'jdbc:derby:myDB'. To connect using the Network Server to the database
'C:\private\tmp\myDB' on a remote server (port 1527), the URL would be:
'jdbc:derby://localhost:1527/
"C:\private\tmp\myDB";user=someusr;password=somepwd'
As with other Derby utilities, you must ensure that no other JVMs are started against the
database when you call the dblook utility, or an exception will occur and will print to the
dblook.log file. If this exception is thrown, the dblook utility will exit. To recover, you
must ensure that no other Derby applications running in a separate JVM are connected
to the source database. These connections need to be shut down. Once all existing
JVMs running against the database have been shut down, the dblook utility will execute
successfully.
You can also start the Derby Network Server and run the dblook utility as a client
application while other clients are connected to the server.
60
Derby Tools and Utilities Guide
dblook options
The dblook utility options include the following.
-z schemaName
Specifies the schema to which the DDL should be restricted. Only objects with the
specified schema are included in the DDL file.
-t tableOne tableTwo ...
Specifies the tables to which the DDL should be restricted. All tables with a name
from this list will be included in the DDL file subject to -z limitations, as will the DDL
for any keys, checks, or indexes on which the table definitions depend.
Additionally, if the statement text of any triggers or views includes a reference to
any of the listed table names, the DDL for that trigger/view will also be generated,
subject to -z limitations. If a table is not included in this list, then neither the table nor
any of its keys, checks, or indexes will be included in the final DDL. If this option is
not provided, all database objects will be generated, subject to -z limitations. Table
names are separated by whitespace.
-td
Specifies a statement delimiter for SQL statements generated by dblook. If a
statement delimiter option is not specified, the default is the semicolon (;). At the end
of each DDL statement, the delimiter is printed, followed by a new line.
-o filename
Specifies the file where the generated DDL is written. If this file is not specified, it
defaults to the console (that is, standard System.out).
-append
Prevents overwriting the DDL output (-o option, if specified) and dblook.log
files. If this option is specified, and execution of the dblook command leads to
the creation of files with names identical to existing files in the current directory,
dblook will append to the existing files. If this option is not set, the existing files will
be overwritten.
-verbose
Specifies that all errors and warnings (both SQL and internal to dblook) should be
echoed to the console (through System.err), in addition to being printed to the
dblook.log file. If this option is not set, the errors and warnings go only to the
dblook.log file.
-noview
Specifies that CREATE VIEW statements should not be generated.
61
Derby Tools and Utilities Guide
• Stored procedures
• Triggers
• Tables
• Views
• Roles
• User-defined types
• User-defined aggregates
When dblook runs against a database that has jar files installed, it creates a new
directory, called DERBYJARS, within the current directory, where it keeps copies of all of
the jar files it encounters. In order to run the generated DDL as a script, this DERBYJARS
directory must either
• Exist within the directory in which it was created, or
• Be moved manually to another directory, in which case the path in the generated
DDL file must be manually changed to reflect to the new location
The dblook utility ignores any objects that have system schemas (for example, SYS),
since DDL is not able to directly create or modify system objects.
dblook examples
The following examples demonstrate how the various dblook utility options can be
specified from a command line. These examples use the sample database.
Note: The quotation marks shown in these examples are part of the command argument
and must be passed to dblook. The way in which quotation marks are passed depends
on the operating system and command line that you are using. With some systems it
might be necessary to escape the quotation marks by using a forward slash before the
quotation mark. For example:
"\"My Table"\"
Status messages are written to the output (either a -o filename, if specified, or the
console) as SQL script comments. These status messages serve as headers to show
which types of database objects are being, or have been, processed by the dblook
utility.
Writing the DDL to the console
You can write the DDL to the console for everything that is in the sample database. In
this example, the database is in the current directory. For example:
62
Derby Tools and Utilities Guide
If the database or file is not in the current directory, you must specify the directory path.
For example:
java org.apache.derby.tools.dblook -d
'jdbc:derby:c:\private\stuff\sample'
-o 'C:\temp\newDB.sql'
java org.apache.derby.tools.dblook
-d 'jdbc:derby://localhost:1527/"C:\temp\sample";
user=someusername;password=somepassword' -z samp
Specifying a schema and a table within the database in the dblook command
You can specify that only the objects in the sample database that are associated with
the SAMP and the My Table table are written to the console. For example:
63
Derby Tools and Utilities Guide
SignatureChecker
Use the SignatureChecker tool to identify any SQL functions and procedures in a
database that do not follow the SQL argument matching rules described in "Argument
matching" in the Derby Reference Manual.
If your application uses SQL functions and/or procedures, you should run this tool against
your databases.
Using SignatureChecker
Before you run the SignatureChecker tool, make sure that your classpath contains the
Derby jar files, including derbytools.jar.
On a Java SE platform, run the SignatureChecker tool as follows, where
connection-url-to-database is the connection URL you would use in order to obtain a
connection by calling DriverManager.getConnection():
Alternatively, you can invoke the tool using derbyrun.jar. For example:
The tool examines every routine registered in the database and displays results like the
following:
In the example above, the SignatureChecker tool found matches for all routines
except for the functions app.iDontExist and app.tabFuncDoesntExist. If the tool cannot
find a match for one of your functions or procedures, it tells you what signature it
expected to find. You need to adjust your application in one of the following ways:
• Method: Change the signature of your Java method to match the signature
suggested by the SignatureChecker tool.
• Routine: Drop and recreate your function or procedure so that its arguments and
return type match your Java method according to the SQL Standard rules described
in "Argument matching" in the Derby Reference Manual.
64
Derby Tools and Utilities Guide
PlanExporter
Use the PlanExporter tool to export query plan data for further analysis.
The query plan data can be exported in a variety of formats:
• XML, the base format for exported query plan data
• HTML, which helps you view graphically the execution plans of complex queries you
have executed
By using this tool, you can avoid querying XPLAIN style tables to get a basic idea of the
query plan followed by the optimizer.
You can specify other query plan export formats by specifying an appropriate XSL
stylesheet to transform the query plan data, or you can export the query plan data as
XML, then reformat it as appropriate using any external XML-aware tool of your choice.
Note: The PlanExporter tool is in an experimental stage. The Derby team welcomes
feedback on how to improve it.
Using PlanExporter
Before you run the PlanExporter tool, make sure that your classpath contains the
Derby jar files, including derbytools.jar/
Before you run the PlanExporter tool, you must capture the stmt_id of the query you
have executed from SYSXPLAIN_STATEMENTS system table. To do so, follow these
steps:
1. Use XPLAIN styles to capture the runtime statistics.
Refer to "SYSCS_UTIL.SYSCS_SET_XPLAIN_SCHEMA system procedure" in the
Derby Reference Manual to see how to do this.
Note: You must remember the schema_name.
2. Query the SYSXPLAIN_STATEMENTS system table to obtain the stmt_id of
the query you have executed.
Refer to "SYSXPLAIN_STATEMENTS system table" in the Derby Reference
Manual for information about the SYSXPLAIN_STATEMENTS system table.
You can run the tool as follows in the directory where your database is located (all on one
line).
The options can be passed according to your requirements. Consider the following
possible scenarios:
• To generate an XML file of the query plan, specify the following option:
-xml path
The path can be either absolute or relative. If the root filename does not have a
suffix, the tool appends .xml.
• To generate a plain HTML file of the query plan, you can use the default simple
style sheet provided with Derby. Specify the following option:
-html path
If the root filename does not have a suffix, the tool appends .html.
65
Derby Tools and Utilities Guide
To generate the XML file as well, specify the following options:
To use a different style sheet that does not contain any Javascript functions, specify
the following options:
Note:
• Before you use the -adv feature, you must copy the advanced XSL style
sheet into the current directory. Thus, you must specify only the name of the
style sheet, not the path.
• Generating HTML is not supported when you use the -adv option of the
PlanExporter tool. But if you open the generated XML file in a web browser,
the browser will do the necessary transformation.
<time>2010-07-13 14:27:59.405</time>
• The stmt_id element:
66
Derby Tools and Utilities Guide
This element has only its value. That value implies the statement ID of the query
executed, as retrieved from the STMT_ID row of the SYSXPLAIN_STATEMENTS
table.
For example:
<stmt_id>9ac8804c-0129-cc31-ca9a-00000047f1e8</stmt_id>
• The details element:
This element contains the query plan, as a tree structure of plan nodes.
For a particular query there is only one root plan node.
• A node element:
Contains the details of a plan node of the query plan. This element can contain zero
or many child elements of the same type (node elements).
This element contains one or more attributes, given that they are not null. The
possible attributes and their meanings are shown in the following table.
Table 5. Attributes of the node element
For example:
PlanExporter example
67
Derby Tools and Utilities Guide
This example shows the steps that you must follow in order to use the PlanExporter
tool.
1. Move to the directory where your database was created.
2. Run the ij tool:
java org.apache.derby.tools.ij
3. Create a connection to the database:
CONNECT 'jdbc:derby:myDb;create=false';
CALL SYSCS_UTIL.SYSCS_SET_RUNTIMESTATISTICS(1);
CALL SYSCS_UTIL.SYSCS_SET_XPLAIN_SCHEMA('MY_SCHEMA');
select * from my_table;
CALL SYSCS_UTIL.SYSCS_SET_RUNTIMESTATISTICS(0);
CALL SYSCS_UTIL.SYSCS_SET_XPLAIN_SCHEMA('');
5. Obtain the stmt_id of the query:
Now find the stmt_id of the executed query in the displayed results and note it
down. It looks something like this:
9ac8804c-0129-cc31-ca9a-00000047f1e8
6. Run the PlanExporter tool in the same location:
This command uses the default style sheet provided with Derby, and the HTML
file will be generated at the same location, since the command does not specify a
different path. The name of the HTML file generated is plain_html.html.
68
Derby Tools and Utilities Guide
Optional tools
Derby supports optional tools, which you can load and unload by using the
SYSCS_UTIL.SYSCS_REGISTER_TOOL system procedure as described in the Derby
Reference Manual.
This command creates metadata functions and table functions in the current schema.
The functions and table functions have the same names as the corresponding
java.sql.DatabaseMetaData methods which they wrap. Once you have loaded this tool,
you can filter and join these functions to create powerful metadata queries. For instance,
the following query lists the column names and datatypes for all columns in tables
created by users:
69
Derby Tools and Utilities Guide
The foreignViews optional tool creates schemas, table functions, and convenience
views for all user tables in a foreign database. This can be useful for bulk-importing
foreign data.
Before you run the foreignViews optional tool, make sure that your classpath contains
the Derby jar files, including derbytools.jar.
You can load and unload the foreignViews tool by using the
SYSCS_UTIL.SYSCS_REGISTER_TOOL system procedure. See the Derby Reference
Manual for information about this procedure.
To load the foreignViews tool, use a statement like the following:
'jdbc:derby:db3;user=fred;password=fredpassword'
• 'XYZ_' is a string prefixed to the names of all schemas created by this tool. This
argument may be omitted. If it is omitted, the tool will create schemas which have
the same names as the schemas in the foreign database.
For example, suppose that the foreign database has two schemas, S1 and S2. S1
contains two user tables, T1 and T2. S2 contains two user tables, U1 and U2. Loading
the tool as shown above will create the following objects in your Derby database:
schema XYZ_S1
table function XYZ_S1.T1, which reads S1.T1 from the foreign database
table function XYZ_S1.T2, which reads S1.T2 from the foreign database
view XYZ_S1.T1, which wraps the corresponding table function
view XYZ_S1.T2, which wraps the corresponding table function
schema XYZ_S2
table function XYZ_S2.U1, which reads S2.U1 from the foreign database
table function XYZ_S2.U2, which reads S2.U2 from the foreign database
view XYZ_S2.U1, which wraps the corresponding table function
view XYZ_S2.U2, which wraps the corresponding table function
The views hide the arguments to the table functions. You can then populate your local
schema by using the following SELECT statements:
When you have finished bulk-importing the foreign data, you can drop this package of
schemas, table functions and views as follows:
70
Derby Tools and Utilities Guide
The mainline API documentation for Apache Lucene at
https://builds.apache.org/job/Lucene-Artifacts-trunk/javadoc/ is a useful starting point for
understanding Lucene's capabilities.
Note: The luceneSupport plugin can be used only after a database has been fully
upgraded to Derby Release 10.11 or higher. (See "Upgrading a database" in the Derby
Developer's Guide for more information.) The plugin cannot be used on a database that
is at Release 10.10 or lower.
Terminology
The following concepts are important to an understanding of the luceneSupport plugin.
• Analyzer: An analyzer is an implementation of
org.apache.lucene.analysis.Analyzer. It extracts indexable terms from a
block of text. The same analyzer should be used to index the text and to query it. An
analyzer may perform language-specific tasks such as stemming and filtering. More
information on analyzers can be found in the Lucene API documentation. Users can
extend the existing Lucene analyzers or write their own custom analyzers.
• Filtering: Filtering is the language-specific task of throwing away insignificant words
such as articles and conjunctions.
• Query-parsing: Query-parsing is the process of interpreting a Lucene query
string. Lucene has its own query language. By extending the default Lucene
QueryParser class, users can enhance the Lucene query language or replace it
with some other query language.
• Score: The score measures how well a query matches a block of text (a text
column value). The higher the score, the better the match. The score is a float
value. There is no minimum or maximum value.
• Stemming: Stemming is the language-specific task of reducing related words to
their common root. For instance, an English stemmer might map all of the following
words onto the common root "house": "house", "houses", "housed", and "housing".
Classpath for running the luceneSupport optional tool
Before you run the luceneSupport optional tool, make sure that your
classpath/modulepath contains the following jar files:
• derbyshared.jar
• derbytools.jar
• derby.jar
• derbyoptionaltools.jar
• core: The core Lucene machinery. For Lucene 4.5.0, this is
lucene-core-4.5.0.jar.
• analyzers-common: The common Lucene analyzers. For Lucene 4.5.0, this is
lucene-analyzers-common-4.5.0.jar.
• queryparser: The basic Lucene logic for query-parsing. For Lucene 4.5.0, this is
lucene-queryparser-4.5.0.jar.
The Lucene jar files are included in the Derby source tree; alternatively, you can
download them from http://lucene.apache.org/.
Loading and unloading the luceneSupport optional tool
In a database protected by SQL authorization, only the database owner can issue the
commands which load and unload the Lucene plugin. (See "Database Owner" in the
Derby Security Guide for more information.)
Loading the plugin looks very much like loading any other optional tool. You call the
SYSCS_UTIL.SYSCS_REGISTER_TOOL system procedure in a statement like the
following:
71
Derby Tools and Utilities Guide
call syscs_util.syscs_register_tool( 'luceneSupport', true );
This command creates the LUCENESUPPORT schema, which contains the following
objects:
• CREATEINDEX: A database procedure for indexing Derby text columns. See
Creating an index for details.
• UPDATEINDEX: A database procedure for refreshing an index built by
CREATEINDEX. See Updating an index for details.
• DROPINDEX: A database procedure for dropping an index built by CREATEINDEX.
See Dropping an index for details.
• LISTINDEXES: A table function for listing the indexes created by CREATEINDEX.
See Listing indexes for details.
Removing the plugin also looks much like unloading other optional tools. Call the
SYSCS_UTIL.SYSCS_REGISTER_TOOL system procedure in a statement like the
following:
Creating an index
The luceneSupport optional tool lets you use Apache Lucene to perform full-text
indexing and searching of the contents of Derby text columns.
72
Derby Tools and Utilities Guide
After the luceneSupport tool has been loaded, a user can index a text column in a
table or view which that user owns. If SQL authorization is enabled, then the database
owner is the only account which can index a text column in another user's table. The
following procedure makes this possible:
LUCENESUPPORT.CREATEINDEX
(
SCHEMANAME VARCHAR( 128 ),
TABLENAME VARCHAR( 128 ),
TEXTCOLUMN VARCHAR( 128 ),
INDEXDESCRIPTORMAKER VARCHAR( 32672 ),
KEYCOLUMNS VARCHAR( 32672 ) ...
)
73
Derby Tools and Utilities Guide
74
Derby Tools and Utilities Guide
-- index the POEMTEXT column of the POEMS table,
-- using its primary key and the default IndexDescriptor maker
CALL LUCENESUPPORT.CREATEINDEX( 'ruth', 'poems', 'poemText', null );
Updating an index
After an index has been created, a user can perform a bulk reindexing of the text column.
If SQL authorization is enabled, the database owner is the only account which can
reindex a text column in another user's table. The following procedure reindexes the
column across the whole table:
LUCENESUPPORT.UPDATEINDEX
(
SCHEMANAME VARCHAR( 128 ),
TABLENAME VARCHAR( 128 ),
TEXTCOLUMN VARCHAR( 128 ),
INDEXDESCRIPTORMAKER VARCHAR( 32672 )
)
The first three arguments identify the column to be reindexed. The last argument lets you
override how the text is indexed and how queries are parsed.
This release of the luceneSupport tool does not support the incremental reindexing of
data. Updating the index is a bulk operation, which reindexes an entire data set. For this
reason, this release of the luceneSupport tool is not appropriate for update-intensive
applications where the results of full-text queries must be current. The luceneSupport
tool is better suited to applications for which yesterday's full-text query results are good
enough:
• Read-mostly: Applications which analyze static text data
• Fuzzy: Applications which can perform a bulk reindexing of the text data periodically
(for example, once a day), and which can tolerate that amount of fuzziness in query
results
Example
Querying an index
To query an index, use the table function created by CREATEINDEX.
The table function created by CREATEINDEX has the following shape:
$SCHEMANAME.$TABLENAME__TEXTCOL
(
QUERY VARCHAR( 32672 ),
WINDOWSIZE INT,
SCORECEILING REAL
75
Derby Tools and Utilities Guide
)
RETURNS TABLE
(
$keyColumn1 $keyColumn1datatype,
...
$keyColumnN $keyColumnNdatatype,
DOCUMENTID INT,
SCORE REAL
)
-- Selects the primary key and score for the best 3 matches for
-- the text.
select presidentID, speechID, score
from table
(
us.presidentsSpeeches__speechText
(
'When in the course of human events',
3,
null
)
) t;
76
Derby Tools and Utilities Guide
Dropping an index
A Lucene index can be dropped by the table owner.
If SQL authorization is enabled, the database owner is the only account which can drop
an index on another user's table. The following procedure makes this possible:
LUCENESUPPORT.DROPINDEX
(
SCHEMANAME VARCHAR( 128 ),
TABLENAME VARCHAR( 128 ),
TEXTCOLUMN VARCHAR( 128 )
)
The arguments are the same as those for CREATEINDEX. See Creating an index for
details.
Example
-- drop an index
CALL LUCENESUPPORT.DROPINDEX
(
'ruth', 'poemView', 'poemText'
);
Listing indexes
You can use a table function to list all Lucene indexes.
After the luceneSupport tool has been loaded, anyone can list the Lucene indexes by
selecting from the following table function:
LUCENESUPPORT.LISTINDEXES()
RETURNS TABLE
(
SCHEMANAME VARCHAR( 128 ),
TABLENAME VARCHAR( 128 ),
COLUMNNAME VARCHAR( 128 ),
LASTUPDATED TIMESTAMP,
LUCENEVERSION VARCHAR( 20 ),
ANALYZER VARCHAR( 32672 ),
INDEXDESCRIPTORMAKER VARCHAR( 32672 )
)
Example
77
Derby Tools and Utilities Guide
To load the simpleJson tool, use the following statement:
The first three functions can then be used to turn JSON documents into tabular data sets
using org.apache.derby.optional.api.SimpleJsonVTI. That class is documented in Derby's
public api too. Using this technique, you can join JSON data with other relational data.
You can also exploit this technique to import JSON data into Derby tables. Here's an
example of how to use these functions to import data:
78
Derby Tools and Utilities Guide
thermostatReadings
(
readArrayFromURL( 'https://thermostat.feed.org', 'UTF-8' )
)
) t;
After running that query, the contents of the target table might look something like this:
id |temperature |fanOn
------------------------------------------
1 |70.3 |true
2 |65.5 |false
toJSON() prepares the query, plugs the optional queryArgs into the query's ?
parameters, executes the query, and returns the results packed into a JSONArray. Here's
an example of how to use this function:
[
{ "id": 1, "temperature": 70.3, "fanOn": true }
]
The tool can be unloaded via the following command. This command drops the
JSONArray type and all of the functions discussed above:
79
Derby Tools and Utilities Guide
extract some data out of the corrupt database by using the rawDBReader optional tool.
The rawDBReader tool is not guaranteed to retrieve all of the data. In some situations,
the tool may retrieve data which was deleted before the database became unbootable.
The rawDBReader optional tool is a last resort to salvage something.
When running the rawDBReader tool, you will work with two databases. Both of these
databases must be on the machine where you are running the tool.
• corruptDB - This is the corrupt or unbootable database whose data you are trying
to salvage.
• healthyDB - This is a new database which you create in order to hold the retrieved
data.
The rawDBReader tool works by copying all of your user data from the corrupt database
into a totally separate, healthy database. Each table in the corrupt database will be
copied to a fresh table in the healthy database. The healthy target table will have the
same schema name, the same table name, and the same column names as the original,
corrupt table.
There are three steps to using rawDBReader:
• load - You call SYSCS_REGISTER_TOOL with arguments specific to your
situation. This will prepare the healthy database to accept data from the corrupt
database. This will also generate a text file containing a series of commands. This is
the recovery script.
• extract - You then run the recovery script in order to retrieve your data from the
corrupt database and copy the data into the healthy database.
• unload - Finally, you can remove the tool via another call to
SYSCS_REGISTER_TOOL.
These steps are described in greater detail below.
Loading the tool
To run the rawDBReader tool, you must be signed on to the machine where the
corrupt database resides. Your classpath must contain derby.jar, derbytools.jar, and
derbyoptionaltools.jar.
To load the rawDBReader tool, connect to the healthy database and issue the following
statement:
call syscs_util.syscs_register_tool
(
'rawDBReader',
true,
$recoveryScript,
$controlSchema,
$schemaPrefix,
$corruptDBPath,
$corruptEncryptionAttributes,
$corruptDatabaseOwner,
$corruptDatabaseOwnerPassword
);
80
Derby Tools and Utilities Guide
schemas will hold functions and views which can be used to extract data out of the
corrupt database.
• $corruptDBPath - The file path to the corrupt database directory.
• $corruptEncryptionAttributes - The encryption directives with which the corrupt
database was created. May be null.
• $corruptDatabaseOwner - The name of the owner of the corrupt database.
• $corruptDatabaseOwnerPassword - The password of the owner of the corrupt
database. May be null.
The schema prefix is just a tag which helps the tool create unique schema names that
won't conflict with the names of user schemas. The control schema is a separate schema
whose name should not conflict with any user schemas. If the corrupt database has the
following user schemas...
S1
S2
...then the healthy database will have the following schemas after loading the
rawDBReader tool and after running the recovery script:
S1
S2
$controlSchema
$schemaPrefixS1
$schemaPrefixS2
For instance, if the corrupt database was created without encryption and without
specifying a database owner, then the following command would load the rawDBReader
optional tool:
call syscs_util.syscs_register_tool
(
'rawDBReader',
true,
'recoverMyData.sql',
'CONTROL',
'BAD_',
'tmpdbs/corruptDB',
null,
'APP',
null
);
If, on the other hand, the corrupt database was created with encryption and with
credentials for a database owner, then you would load the tool with a command like the
following statement:
call syscs_util.syscs_register_tool
(
'rawDBReader',
true,
'recoverMyData.sql',
'CONTROL',
'BAD_',
'tmpdbs/corruptDB',
'bootPassword=DBpassword',
'dbo',
'DBO_password'
);
81
Derby Tools and Utilities Guide
Loading the tool will write a recovery script containing statements which will create
schemas and tables in the healthy database. The schemas and tables correspond to the
user schemas and tables in the corrupt database. The script will also contain statements
which extract data out of the corrupt tables into their healthy counterparts. Here's a
sample recovery script:
connect 'jdbc:derby:tmpdbs/healthyDB';
call syscs_util.syscs_register_tool
(
'rawDBReader',
false,
'CONTROL',
'BAD_'
);
82
Derby Tools and Utilities Guide
Trademarks
The following terms are trademarks or registered trademarks of other companies and
have been used in at least one of the documents in the Apache Derby documentation
library:
Cloudscape, DB2, DB2 Universal Database, DRDA, and IBM are trademarks of
International Business Machines Corporation in the United States, other countries, or
both.
Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft
Corporation in the United States, other countries, or both.
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names
may be trademarks of their respective owners.
UNIX is a registered trademark of The Open Group in the United States and other
countries.
Other company, product, or service names may be trademarks or service marks of
others.
83