<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to you under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!DOCTYPE document PUBLIC "-//APACHE//DTD Documentation V2.0//EN" "http://forrest.apache.org/dtd/document-v20.dtd">
<document> 
  <header> 
    <title>Using DdlUtils to Migrate Databases to Derby</title> 
  </header> 
  <body> 

<section>
  <title>Overview</title>
<p>
<a href="http://db.apache.org/ddlutils">DdlUtils</a>, an Apache DB subproject,
provides utilities for creating and working with Database Definition (DDL) files
and for exporting and importing data in XML format
<em>via</em> Ant tasks or programmatically in Java.
</p>

<p>
Among other uses, DdlUtils makes it easier to migrate 
from one database vendor to another.
This paper provides a simple example for using DdlUtils to migrate a database 
to Derby using the
<a href="http://db.apache.org/ddlutils/ant/index.all.html">DdlUtils Ant tasks</a>.
</p>

<p>
This example features Derby as both the source and target database
because Derby is easily available and is what the author knows, but it can
be used with any of the databases that 
<a href="http://db.apache.org/ddlutils/database-support.html">DdlUtils 
supports</a>.
Usually there's an even easier way to migrate a Derby database from 
one machine to another: just copy the Derby database files. 
If the source and target machines use official Derby releases
you don't need to export/import the schema and data, not even for 
machines with different architectures,
because the files that make up a Derby database are platform-independent.
However, if you want to upgrade a Derby database to or from an alpha
version of Derby to an official release, 
you must export the schema and data because Derby doesn't support
<a href="https://cwiki.apache.org/confluence/display/DERBY/UpgradingTen">upgrading</a> 
an alpha database.
DdlUtils makes this migration easier.
</p>

   <section>
      <title>Target Audience</title>

   <p>DdlUtils doesn't have an official release yet, 
      so this example is intended for developers -- and for users who have a 
      developer spirit.
      This project walks
      you through checking the DdlUtils code out of the Apache Subversion
      repository and building it using the Ant build tool.
      You don't need to be a java developer, in fact you don't need
      to know any Java at all, 
      but you should be comfortable installing software, setting environment
      variables, and troubleshooting
      any problems that might occur.
   </p>
   </section>
   <section>
      <title>Prerequisites</title>

      <p>This project assumes a basic knowledge of Derby.
         If you're new, start with the on-line
         <a href="http://db.apache.org/derby/papers/DerbyTut/index.html">Apache
         Derby Tutorial</a>.
         Familiarity with XML is helpful, but not necessary.  
         You also need the software listed below:
      </p>
      <ul>
         <li>Install the most current official release of
            <a href="http://db.apache.org/derby/derby_downloads.html">Apache Derby</a>. </li>
         <li>Install <a href="http://ant.apache.org/">Apache Ant</a> version
         1.6.
         Set the <code>ANT_HOME</code> environment variable and
         add the Ant <code>bin</code> directory to your <code>PATH</code>.
         </li>
         <li> Install <a href="http://subversion.tigris.org/">Subversion</a>
              and add the Subversion <code>bin</code> directory to your 
              <code>PATH</code>.
         </li>
      </ul>

   </section>
</section>

<section>
  <title>Step 1: Setup a working directory</title>
  <p>
  Somewhere on your computer create a working directory, then <code>cd</code> 
  into it. 
  This is where you'll check out and build DdlUtils, 
  create the Derby databases,
  <em>etc</em>.
  Also create a <code>lib</code> subdirectory; this is where you'll install
  the DdlUtils software.
  </p>
  <p class="code-block">mkdir DdlUtils-test
cd DdlUtils-test
mkdir lib</p>
</section>

<section>
  <title>Step 2: Build and Install DdlUtils</title>

   <p>
     Check out the DdlUtils repository as shown below:
   </p>

   <p class="code-block">svn co http://svn.apache.org/repos/asf/db/ddlutils/trunk ddlutils</p>

   <p>After this command completes, you should have a local working copy of the
    DdlUtils code in a subdirectory called <code>ddlutils</code>.
    Change directory into that subdirectory and build the DdlUtils jar file
    as shown below:
   </p>

   <p class="code-block">cd ddlutils
ant jar</p>

   <p>You might see some deprecation warnings in the build output, but don't
   worry about those as long as at the end you see a 
   <code>BUILD SUCCESSFUL</code> message.
   The resulting jar will be output to a newly created 
    <code>dist</code> subdirectory:
   </p>

   <p class="code-block"><strong>UNIX</strong>
$ ls dist
DdlUtils-1.0-dev.jar 

<strong>Windows</strong>
C:\jta\DdlUtils-test\ddlutils&gt;dir dist
 Volume in drive C has no label.
 Volume Serial Number is 8017-F8A8

 Directory of C:\jta\DdlUtils-test\ddlutils\dist

03/10/2006  12:38 PM    &lt;DIR&gt;          .
03/10/2006  12:38 PM    &lt;DIR&gt;          ..
03/10/2006  12:38 PM           252,846 DdlUtils-1.0-dev.jar
               1 File(s)        252,846 bytes
               2 Dir(s)  66,830,884,864 bytes free</p>

   <p>Copy files from the <code>dist</code> and <code>lib</code> directories
      into the <code>lib</code> directory you created in
       Step 1, then <code>cd</code> back up to your working directory:</p>

   <p class="code-block"><strong>UNIX</strong>
cp dist/*.jar ../lib
cp lib/*.jar ../lib
cd ..

<strong>Windows</strong>
copy dist\*.jar ..\lib
copy lib\*.jar ..\lib
cd ..  </p>
</section>


<section>
  <title>Step 3: Create a sample database: Books1 </title>

<p>
This section creates the database that the
<a href="http://db.apache.org/torque/releases/torque-3.2/releases/torque-3.2/tutorial/index.html">Apache Torque Tutorial</a>
uses,
but you'll use Derby's <code>ij</code> utility to create it instead.
</p>

<p>
Include <code>derby.jar</code> and 
<code>derbytools.jar</code> in your <code>CLASSPATH</code>
(<a href="http://db.apache.org/derby/papers/DerbyTut/install_software.html#derby_configure">the on-line Derby tutorial shows how to do this</a>), then create the
database:
</p>

<p class="code-block">java org.apache.derby.tools.ij
connect 'jdbc:derby:Books1;create=true'; </p>

<p>
Cut and paste the statements below to create the tables:
</p>

<p class="code-block">CREATE TABLE publisher
(
    publisher_id INTEGER NOT NULL,
    name VARCHAR(128) NOT NULL,
    PRIMARY KEY(publisher_id));

CREATE TABLE author
(
    author_id INTEGER NOT NULL,
    first_name VARCHAR(128) NOT NULL,
    last_name VARCHAR(128) NOT NULL,
    PRIMARY KEY(author_id));

CREATE TABLE book
(
    book_id INTEGER NOT NULL,
    title VARCHAR(255) NOT NULL,
    isbn VARCHAR(24) NOT NULL,
    publisher_id INTEGER NOT NULL,
    author_id INTEGER NOT NULL,
    PRIMARY KEY(book_id),
    FOREIGN KEY (publisher_id) REFERENCES publisher (publisher_id)
    ,
    FOREIGN KEY (author_id) REFERENCES author (author_id)
    );</p>

<p>
Cut and paste the statements below to insert some data:
</p>

<p class="code-block">insert into publisher 
   values (1, 'Addison Wesley Professional');
insert into author 
   values (11, 'Joshua', 'Bloch');
insert into author 
   values (12, 'W.', 'Stevens');
insert into book 
   values (101, 'Effective Java Programming Language Guide', '0-201-31005-8', 1, 11);
insert into book 
   values (102, 'TCP/IP Illustrated, Volume 1', '0-201-63346-9', 1, 12);
</p>

<p>
Finally, exit the database:
</p>

<p class="code-block">exit;</p>

</section>

<section>
  <title>Step 4: Books1 -- Export Schema and Data </title>

<p>
This step uses the DdlUtils <code>DatabaseToDdlTask</code>
to dump the <code>Books1</code> database to disk.
You'll use the
<a href="http://db.apache.org/ddlutils/ant/index.all.html">DdlUtils Ant tasks</a>
to execute the export.
</p>

<section>
  <title>Create an Ant build.xml file with an export target</title>
<p>
Complete source for the Ant build file is below.
Cut and paste it into a file called <code>build.xml</code>:
</p>

<p class="code-block">&lt;?xml version="1.0"?&gt;
&lt;project name="MigrateToDerby" basedir="."&gt;

   &lt;path id="classpath"&gt;
      &lt;fileset dir="./lib"&gt;
         &lt;include name="**/*.jar"/&gt;
      &lt;/fileset&gt;
   &lt;/path&gt;

   &lt;target name="export-source-db" description="Dumps db structure and data"&gt;
      &lt;taskdef name="databaseToDdl"
              classname="org.apache.ddlutils.task.DatabaseToDdlTask"&gt;
         &lt;classpath refid="classpath"/&gt;
      &lt;/taskdef&gt;

      &lt;databaseToDdl modelName="MigrateTest"&gt;
         &lt;database url="jdbc:derby:Books1"
                 driverClassName="org.apache.derby.jdbc.EmbeddedDriver"
                 username=""
                 password=""/&gt;

         &lt;writeSchemaToFile outputFile="db-schema.xml"/&gt;
         &lt;writeDataToFile outputFile="data.xml"/&gt;
      &lt;/databaseToDdl&gt;

   &lt;/target&gt;

&lt;/project&gt; </p>

<p>
Here are a few notes about the <code>build.xml</code> source:
</p>

<ul>
  <li>In Step 2 you copied all the jars from <code>ddlutils/lib</code> into the 
      <code>lib</code> directory of the working directory. 
      Rather than add them to the <code>CLASSPATH</code> variable,
      the Ant <code>path</code> element 
      adds all jars in that subdirectory to the runtime environment.
      The <code>path</code> element is available to any target in this file;
      right now, there's just one target
      (<code>export-source-db</code>), but Step 5 will add another.
  </li>
  <li>The <code>export-source-db</code> target exports the schema and data
      from a database. 
     <ul>
     <li><code>modelName</code> specifies a name for the model and will
       be assigned to the <code>name</code> attribute in the generated
       schema file.
     </li>
     <li><code>database url</code> specifies all the connection parameters
          for the database, including the <code>Books1</code> database.
          This example uses the Derby Embedded JDBC driver (<code>derby.jar</code>), 
          but it could just
          as easily use the Derby Network Client JDBC driver
          (<code>derbyclient.jar</code>).</li>
     <li><code>writeSchemaToFile</code> exports the schema to a file
          called <code>db-schema.xml</code>.</li>
     <li><code>writeDataToFile</code> exports the data to a file
          called <code>data.xml</code>.</li>
     </ul>
  </li>
</ul>
</section>

<section>
  <title>Execute the Ant task</title>

<p>
Now execute the task with <code>ant</code>:
</p>

<p class="code-block">ant export-source-db</p>

<p>
A <code>BUILD SUCCESSFUL</code> message indicates that that the export
succeeded and there should be two new files in your current working directory:
</p>

<ul>
  <li><code>db-schema.xml</code> contains the database schema in XML format.</li>
  <li><code>data.xml</code> contains the data in XML format.</li>
</ul>

</section>
</section>

<section>
  <title>Step 5: Books2 -- Create Database and Import Schema and Data</title>

<p>
This step uses the DdlUtils <code>DdlToDatabaseTask</code>
to import the schema and data into a new <code>Books2</code> database.
As with the export task, you'll use the
<a href="http://db.apache.org/ddlutils/ant/index.all.html">DdlUtils Ant tasks</a>
to execute the import.
</p>

<section>
  <title>Copy and (maybe) modify the db-schema.xml file </title>

<p>
The export step created a file called <code>db-schema.xml</code>. Copy that
to a new file called <code>project-schema.xml</code>:
</p>

<p class="code-block"><strong>UNIX</strong>
cp db-schema.xml project-schema.xml

<strong>Windows</strong>
copy db-schema.xml project-schema.xml</p>

<p>
Since Derby is both the source and target databases in this example, no
changes to the generated schema file are required.
However, changes might be required if the source database is not Derby, 
for example, to change the mapping of a data type:
</p>

<ul>
  <li> Derby does not support the <code>BOOLEAN</code> type
        (<a href="http://issues.apache.org/jira/browse/DERBY-499">yet</a>).
        Use a SQL <a href="http://mail-archives.apache.org/mod_mbox/db-derby-user/200412.mbox/%3c41C052AB.4050804@debrunners.com%3e"><code>SMALLINT</code></a>
        instead.
  </li>
  <li> A Derby user
       <a href="http://mail-archives.apache.org/mod_mbox/db-derby-user/200603.mbox/%3c007e01c64635$4ae17b60$dd00a8c0@itsdev.infotechsoft.com%3e">posted</a> 
       that he edited the generated schema file to change some 
       <code>LONG VARCHAR</code>s in the source database
       to a <code>VARCHAR(32672)</code> to retain search ability
       and others to <code>CLOB</code> to retain long text &gt; 32,672 
       characters.
</li>
</ul>

</section>

<section>
  <title>Add an import target to the build.xml</title>
<p>
Copy the source for the <code>import-target-db</code> target below
and add it to your <code>build.xml</code> file:
</p>

<p class="code-block">   &lt;target name="import-target-db" description="Creates db and loads data"&gt;
      &lt;taskdef name="ddlToDatabase"
              classname="org.apache.ddlutils.task.DdlToDatabaseTask"&gt;
         &lt;classpath refid="classpath"/&gt;
      &lt;/taskdef&gt;

      &lt;ddlToDatabase schemaFile="project-schema.xml"&gt;

         &lt;database url="jdbc:derby:Books2"
                 driverClassName="org.apache.derby.jdbc.EmbeddedDriver"
                 username=""
                 password=""/&gt;

         &lt;createDatabase failonerror="false"/&gt;
         &lt;writeSchemaToDatabase/&gt;
         &lt;writeDataToDatabase datafile="data.xml"/&gt;

      &lt;/ddlToDatabase&gt;
   &lt;/target&gt; </p>

<p>
Here are a few notes about the source:
</p>

<ul>
   <li> There is just one file for the schema, so it can be specified as an
        argument to the <code>ddlToDatabase</code> task using the
        <code>schemaFile</code> argument.
        You can also use an embedded <code>fileset</code> for multiple files --
        the 
        <a href="http://db.apache.org/ddlutils/ant/index.all.html">DdlUtils
        site</a> shows an example using that syntax.
   </li>
   <li> The <code>createDatabase</code> subtask creates the Derby database.
   </li>
   <li> The <code>writeSchemaToDatabase</code> subtask creates the schema
        from the file specified by <code>schemaFile</code>.
   </li>
   <li> The <code>writeDataToDatabase</code> subtask loads the data from the
        specified data file.
   </li>
</ul>
</section>

<section>
  <title>Execute the Ant task</title>

<p>
Execute the task with <code>ant</code>:
</p>

<p class="code-block">ant import-target-db</p>

<p>Successful execution should look something like this:</p>

<p class="code-block">ant import-target-db
Buildfile: build.xml

import-target-db:
[ddlToDatabase] Read schema file /home/jta/DerbyDb/DdlUtils/project-schema.xml
[ddlToDatabase] Created database
[ddlToDatabase] Mar 10, 2006 4:03:05 PM org.apache.ddlutils.platform.SqlBuilder alterDatabase
[ddlToDatabase] INFO: Creating table AUTHOR
[ddlToDatabase] Mar 10, 2006 4:03:05 PM org.apache.ddlutils.platform.SqlBuilder alterDatabase
[ddlToDatabase] INFO: Creating table BOOK
[ddlToDatabase] Mar 10, 2006 4:03:05 PM org.apache.ddlutils.platform.SqlBuilder alterDatabase
[ddlToDatabase] INFO: Creating table PUBLISHER
[ddlToDatabase] Mar 10, 2006 4:03:06 PM org.apache.ddlutils.platform.PlatformImplBase evaluateBatch
[ddlToDatabase] INFO: Executed 5 SQL command(s) with 0 error(s)
[ddlToDatabase] Written schema to database
[ddlToDatabase] Read data file /home/jta/DerbyDb/DdlUtils/data.xml

BUILD SUCCESSFUL
Total time: 4 seconds </p>

</section>

</section>

<section>
<title>Step 6: Verify Migration</title>

<p>
You should now have two databases.
</p>

<p>
One way to verify the schema in the target Derby database is to examine
it with <a href="http://db.apache.org/derby/docs/dev/tools/ctoolsusingdblook.html">dblook</a>:
</p>

<p class="code-block">java org.apache.derby.tools.dblook -d jdbc:derby:Books2 -o Books2_schema.sql</p>

<p>
To verify the data was imported correctly, query the data in both databases:
</p>

<p class="code-block">ij&gt; select * from publisher;
ij&gt; select * from author;
ij&gt; select * from book;
</p>

</section>

<section>
  <title>Caveats</title>

<p>
The DdlUtils model uses JDBC datatypes exclusively, 
which can be an issue for older drivers.
Be sure to review
DdlUtils database support on the
<a href="http://db.apache.org/ddlutils/database-support.html">DdlUtils site</a>.
</p>

</section>

<section>
  <title>Questions?</title>

 <p>Please post questions about this example to 
   <a href="../derby_mail.html">derby-user &lt;at&gt; db.apache.org</a>.
    Please post questions about DdlUtils to
  <a href="http://db.apache.org/ddlutils/mail-lists.html">ddlutils-user &lt;at&gt; db.apache.org</a>.
</p>

</section>

<p><em>Last Updated: March 16, 2006</em></p>

</body>
</document>
