commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From jstrac...@apache.org
Subject cvs commit: jakarta-commons-sandbox/sql/src/schema database.xsd
Date Wed, 31 Jul 2002 17:00:04 GMT
jstrachan    2002/07/31 10:00:03

  Added:       sql/src/templates/sql/db2 columns.vm db.props foreignkey.vm
                        unique.vm index.vm drop.vm primarykey.vm table.vm
                        sequence.vm tablefk.vm
               sql/src/templates/sql/sapdb sequence.vm table.vm
                        foreignkey.vm unique.vm tablefk.vm columns.vm
                        drop.vm db.props primarykey.vm index.vm
               sql/src/templates/database-doc/html datamodel.vm table.vm
               sql/src/templates/database-load Control.vm
               sql/src/java/org/apache/commons/sql DataDTDTask.java
                        SQLExec.java CreateDatabase.java DataDumpTask.java
                        SQLTask.java JDBCTransformTask.java
                        DataModelTask.java DataSQLTask.java
                        DocumentationTask.java TypeMap.java
               sql/src/templates/database-create/oracle createdb.vm
               sql/src/templates/sql/mysql foreignkey.vm unique.vm db.props
                        index.vm primarykey.vm tablefk.vm columns.vm
                        drop.vm table.vm
               sql/src/templates/sql/oracle primarykey.vm table.vm drop.vm
                        db.props index.vm tablefk.vm foreignkey.vm
                        columns.vm unique.vm sequence.vm
               sql/src/templates/sql/interbase primarykey.vm drop.vm
                        db.props unique.vm index.vm foreignkey.vm
                        tablefk.vm columns.vm table.vm
               sql/src/java/org/apache/commons/sql/datamodel Reference.java
                        Table.java ForeignKey.java Column.java
                        Database.java
               sql/src/templates/sql/hypersonic index.vm foreignkey.vm
                        unique.vm table.vm drop.vm tablefk.vm columns.vm
                        primarykey.vm db.props
               sql/src/templates/sql/db2400 index.vm sequence.vm
                        foreignkey.vm unique.vm table.vm drop.vm tablefk.vm
                        columns.vm primarykey.vm db.props
               sql/src/templates/sql/mssql primarykey.vm db.props index.vm
                        foreignkey.vm table.vm unique.vm drop.vm tablefk.vm
                        columns.vm
               sql/src/templates/database-load/oracle val.vm row.vm
               sql/src/templates/database-load/hypersonic val.vm row.vm
               sql/src/templates/database-load/db2400 val.vm row.vm
               sql      maven.xml build.xml project.properties project.xml
               sql/src/templates/sql/sybase drop.vm table.vm foreignkey.vm
                        db.props tablefk.vm primarykey.vm columns.vm
                        index.vm unique.vm
               sql/src/templates/sql/postgresql table.vm tablefk.vm
                        columns.vm foreignkey.vm unique.vm db.props drop.vm
                        index.vm primarykey.vm
               sql/src/jelly defineTags.jelly createSql.jelly
                        createDb.jelly
               sql/xdocs/howto mssql-howto.xml oracle-howto.xml
                        sybase-howto.xml postgres-howto.xml
               sql/src/test-input datamodel.xml
               sql/src/templates/database-create/postgresql createdb.vm
               sql/xdocs index.xml
               sql/src/templates/database-doc/anakia table.vm datamodel.vm
               sql/src/templates/database-load/mssql row.vm val.vm
               sql/src/templates/database-store/dump Control.vm top.vm
                        row.vm bottom.vm
               sql/src/templates/database-create/hypersonic createdb.vm
               sql/src/templates/database-create/db2400 createdb.vm
               sql/src/templates/sql/cloudscape foreignkey.vm tablefk.vm
                        columns.vm table.vm primarykey.vm drop.vm db.props
                        unique.vm index.vm
               sql/src/templates/database-load/sybase row.vm val.vm
               sql/src/templates/database-create/sybase createdb.vm
               sql/src/templates/sql Control.vm
               sql/src/templates/database-create/mssql unix.vm windows.vm
               sql/src/templates/database-store dataset.vm table.vm
                        Control.vm
               sql/src/test/org/apache/commons/sql/datamodel
                        TestDataModelRoundTrip.java
               sql/src/templates/database-load/postgresql row.vm val.vm
               sql/src/templates/database-create/sapdb createdb.vm
               sql/src/templates/database-create Control.vm
               sql/src/ant build-sql.properties build-sql.xml
               sql/src/templates/database-load/sapdb row.vm val.vm
               sql/src/templates/database-load/mysql row.vm val.vm
               sql/src/templates/database-doc Control.vm
               sql/src/templates/database-create/mysql createdb.vm
               sql/src/schema database.xsd
  Log:
  Added initial cut of the commons-sql codebase. This originally came from Jason, then I've hacked it a little.
  
  Its essentially a simple bean library that allows a database schema to be read from XML or written to XML via Betwixt that can then be used to autogenerate code, SQL DDL etc. 
  
  I'm experimenting using Jelly to generate the DDL in some XML that can then be evaluated at will.
  Though the old Velocity scripts from Torque have been preserved.
  
  Ultimately it'd be cool if this could be packaged up as a Maven plugin so we can autocreate the generation of bean source code, OJB repository definitions, DDL, HTML documentation etc.
  
  Revision  Changes    Path
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/db2/columns.vm
  
  Index: columns.vm
  ===================================================================
  #foreach ($col in $table.Columns)
      #set ( $type = $dbprops.get($col.Type) )
      #set ( $size = $col.printSize() )
      #set ( $default = $col.DefaultSetting )
      #set ( $autoIncrement = $strings.select($col.isAutoIncrement(), $dbprops.get("AUTOINCREMENT"),"") )
      #set ( $nullString = $strings.select($col.isNotNull(), $dbprops.get("NOTNULL"),"") )
      #set ( $nullString = $strings.select($col.isAutoIncrement(), "", $dbprops.get("NOTNULL")) )
      #set ( $entry = "$col.Name $type $size $default $nullString $autoIncrement," )
      $strings.sub($strings.collapseSpaces($entry)," ,",",")
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/db2/db.props
  
  Index: db.props
  ===================================================================
  # Taken from java.sql.Types in the IBM 1.3 JDK
  # JDBC to Oracle mappings.
  
  BIT =
  TINYINT =
  SMALLINT =
  INTEGER = INT
  BIGINT =
  FLOAT =
  REAL =
  DOUBLE =
  NUMERIC =
  DECIMAL =
  CHAR = VARCHAR
  VARCHAR = VARCHAR
  LONGVARCHAR = VARCHAR
  DATE =
  TIME =
  TIMESTAMP = DATE
  BINARY =
  # For DB2/400, VARBINARY must be changed to VARCHAR (32000) FOR BIT DATA
  VARBINARY = BLOB (16777215)
  LONGVARBINARY =
  NULL =
  OTHER =
  JAVA_OBJECT =
  DISTINCT =
  STRUCT =
  ARRAY =
  BLOB =
  CLOB =
  REF =
  
  AUTOINCREMENT = GENERATED ALWAYS AS IDENTITY
  NOTNULL = NOT NULL
  
  removeNotNullWithAutoIncrement = true
  
  suppressDefaults = false
  maxColumnNameLength = 18
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/db2/foreignkey.vm
  
  Index: foreignkey.vm
  ===================================================================
  #foreach ($fk in $table.ForeignKeys)
  ALTER TABLE $table.Name
      ADD CONSTRAINT $fk.Name FOREIGN KEY ($fk.LocalColumnNames)
      REFERENCES $fk.ForeignTableName ($fk.ForeignColumnNames)
  USING INDEX;
  
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/db2/unique.vm
  
  Index: unique.vm
  ===================================================================
  #foreach ($unique in $table.Unices)
      UNIQUE ($unique.ColumnList),
  #end
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/db2/index.vm
  
  Index: index.vm
  ===================================================================
  #foreach ($index in $table.Indices)
  CREATE #if($index.Unique)UNIQUE#end INDEX $index.Name ON $table.Name ($index.ColumnList);
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/db2/drop.vm
  
  Index: drop.vm
  ===================================================================
  drop table $table.Name;
  drop sequence if exists $table.SequenceName;
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/db2/primarykey.vm
  
  Index: primarykey.vm
  ===================================================================
  ALTER TABLE $table.Name
      ADD CONSTRAINT ${table.Name}_PK 
  PRIMARY KEY ($table.printPrimaryKey());
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/db2/table.vm
  
  Index: table.vm
  ===================================================================
  
  -----------------------------------------------------------------------------
  -- $table.Name
  -----------------------------------------------------------------------------
  $generator.parse("$basepath/drop.vm", "", "table", $tbl)
  CREATE TABLE $table.Name
  (
  #set ( $cols = $generator.parse("$basepath/columns.vm", "", "table", $tbl) )
  #set ( $unique = $generator.parse("$basepath/unique.vm", "", "table", $tbl) )
  #if($strings.allEmpty([$unique]))$strings.chop($cols,2)#else$cols#end
  #if($unique.length()>0)$strings.chop($unique,2)#end
  
  );
  
  #set ( $pk = $generator.parse("$basepath/primarykey.vm", "", "table", $tbl) )
  #if($pk.length()>0)$pk#end
  
  #set ( $fk = $generator.parse("$basepath/foreignkey.vm", "", "table", $tbl) )
  #if ($fk.length()>0)$fk#end
  
  #set ( $index = $generator.parse("$basepath/index.vm", "", "table", $tbl) )
  #if($index.length() > 0)$index#end
  
  ##set $sequence = $generator.parse("$basepath/sequence.vm", "", "table", $tbl)
  ##if ($sequence.length()>0)$sequence#end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/db2/sequence.vm
  
  Index: sequence.vm
  ===================================================================
  #if ($table.IdMethod == "native")
  CREATE SEQUENCE $table.SequenceName;
  #end
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/db2/tablefk.vm
  
  	<<Binary file>>
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/sapdb/sequence.vm
  
  Index: sequence.vm
  ===================================================================
  #if ($table.IdMethod == "native")
  CREATE SEQUENCE $table.SequenceName;
  #end
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/sapdb/table.vm
  
  Index: table.vm
  ===================================================================
  
  -----------------------------------------------------------------------------
  -- $table.Name
  -----------------------------------------------------------------------------
  $generator.parse("$basepath/drop.vm", "", "table", $tbl)
  CREATE TABLE $table.Name
  (
  #set ( $cols = $generator.parse("$basepath/columns.vm", "", "table", $tbl) )
  #set ( $unique = $generator.parse("$basepath/unique.vm", "", "table", $tbl) )
  #if($strings.allEmpty([$unique]))$strings.chop($cols,2)#else$cols#end
  #if($unique.length()>0)$strings.chop($unique,2)#end
  
  );
  
  #set ( $pk = $generator.parse("$basepath/primarykey.vm", "", "table", $tbl) )
  #if($pk.length()>0)$pk#end
  
  #set ( $index = $generator.parse("$basepath/index.vm", "", "table", $tbl) )
  #if($index.length() > 0)$index#end
  
  #set ( $sequence = $generator.parse("$basepath/sequence.vm", "", "table", $tbl) )
  #if ($sequence.length()>0)$sequence#end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/sapdb/foreignkey.vm
  
  Index: foreignkey.vm
  ===================================================================
  #foreach ($fk in $table.ForeignKeys)
  ALTER TABLE $table.Name
      ADD CONSTRAINT $fk.Name FOREIGN KEY ($fk.LocalColumnNames)
      REFERENCES $fk.ForeignTableName ($fk.ForeignColumnNames)
  ;
  
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/sapdb/unique.vm
  
  Index: unique.vm
  ===================================================================
  #foreach ($unique in $table.Unices)
      UNIQUE ($unique.ColumnList),
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/sapdb/tablefk.vm
  
  Index: tablefk.vm
  ===================================================================
  #set ( $fk = $generator.parse("$basepath/foreignkey.vm", "", "table", $tbl) )
  #if ($fk.length()>0)$fk#end
  
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/sapdb/columns.vm
  
  Index: columns.vm
  ===================================================================
  #foreach ($col in $table.Columns)
      #set ( $type = $dbprops.get($col.Type) )
      #set ( $size = $col.printSize() )
      #set ( $default = $col.DefaultSetting )
      #set ( $nullString = $strings.select($col.isNotNull(), $dbprops.get("NOTNULL"),"") )
      #set ( $entry = "$col.Name $type $size $default $nullString," )
      $strings.sub($strings.collapseSpaces($entry)," ,",",")
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/sapdb/drop.vm
  
  Index: drop.vm
  ===================================================================
  drop table $table.Name cascade constraints;
  #if ($table.IdMethod == "native")
  drop sequence $table.SequenceName;
  #end
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/sapdb/db.props
  
  Index: db.props
  ===================================================================
  # Taken from java.sql.Types in the IBM 1.3 JDK
  # JDBC to SapDB mappings.
  
  BIT =
  TINYINT =
  SMALLINT =
  INTEGER = INT
  BIGINT =
  FLOAT =
  REAL =
  DOUBLE =
  NUMERIC =
  DECIMAL =
  CHAR = VARCHAR2
  VARCHAR = VARCHAR2
  LONGVARCHAR = VARCHAR2
  DATE = DATE
  TIME =
  TIMESTAMP = DATE
  BINARY =
  VARBINARY = LONG RAW
  LONGVARBINARY =
  NULL =
  OTHER =
  JAVA_OBJECT =
  DISTINCT =
  STRUCT =
  ARRAY =
  BLOB =
  CLOB =
  REF =
  
  AUTOINCREMENT = AUTO_INCREMENT
  NOTNULL = NOT NULL
  
  primaryKeyInsideTableDirective = true
  foreignKeyInsideTableDirective = true
  indexInsideTableDirective = false
  
  removeNotNullWithAutoIncrement = false
  
  suppressDefaults = false
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/sapdb/primarykey.vm
  
  Index: primarykey.vm
  ===================================================================
  ALTER TABLE $table.Name
      ADD CONSTRAINT ${table.Name}_PK 
  PRIMARY KEY ($table.printPrimaryKey());
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/sapdb/index.vm
  
  Index: index.vm
  ===================================================================
  #foreach ($index in $table.Indices)
  CREATE #if($index.Unique)UNIQUE#end INDEX $index.Name ON $table.Name ($index.ColumnList);
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-doc/html/datamodel.vm
  
  Index: datamodel.vm
  ===================================================================
  #set ( $database = $dataModel.database )
  <html>
  <header>
    <title>$dataModel.name</title>
  </header>
  
  <body>
    <table border="1">
      <tr>
        <th>Table Name</th>
        <th>OM Class</th>
        <th>Description</th>
      <tr>
    #foreach ($tbl in $database.tables)
      <tr>
        <td><a href="#$tbl.Name">$tbl.Name</a></td>
        <td>$tbl.JavaName</td>
        <td>#if ($tbl.Description) $tbl.Description#else &nbsp;#end</td>
      </tr>
    #end
    </table>
  
    #foreach ($tbl in $database.tables)
      $generator.parse("doc/html/table.vm",$outFile,"table",$tbl)
    #end
  
  </body>
  </html>
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-doc/html/table.vm
  
  Index: table.vm
  ===================================================================
  <a name="$table.Name"/>
  <h2>$table.Name</h2>
  $!table.Description
  <p/>
  <table border="1">
    <tr>
      <th>Name</th>
      <th>Type</th>
      <th>Size</th>
      <th>Default</th>
      <th>JavaName</th>
      <th>PK</th>
      <th>FK</th>
      <th>not null</th>
      <th>Description</th>
    </tr>
  #foreach ($col in $table.Columns)
    <tr>
      <td>$col.Name</td>
      <td>$col.Type</td>
      <td>#if ($col.printSize()) $col.printSize()#else &nbsp;#end</td>
      <td>#if ($col.DefaultValue) $col.DefaultValue#else &nbsp;#end</td>
      <td>$col.JavaName</td>
      <td>#if ($col.isPrimaryKey()==true)X#else &nbsp;#end</td>
      <td>#if ($col.isForeignKey()==true)X#else &nbsp;#end</td>
      <td>#if ($col.isNotNull()==true)X#else &nbsp;#end</td>
      <td>#if ($col.Description) $col.Description#else &nbsp;#end</td>
    </tr>
  #end
  </table>
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-load/Control.vm
  
  Index: Control.vm
  ===================================================================
  #set ( $fname= "sql/load/${targetDatabase}/row.vm" )
  
  #foreach ($r in $data)
  $generator.parse($fname,"","row",$r)
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/java/org/apache/commons/sql/DataDTDTask.java
  
  Index: DataDTDTask.java
  ===================================================================
  package org.apache.commons.sql;
  
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2001 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Apache" and "Apache Software Foundation" and
   *    "Apache Turbine" must not be used to endorse or promote products
   *    derived from this software without prior written permission. For
   *    written permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    "Apache Turbine", nor may "Apache" appear in their name, without
   *    prior written permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  /**
   * An extended Texen task used for generating data DTD from
   * an XML schema describing a database structure.
   *
   * @author <a href="mailto:fedor.karpelevitch@home.com"> Fedor Karpelevitch </a>
   * @author <a href="mailto:jvanzyl@zenplex.com">Jason van Zyl</a>
   * @version  $Id: TorqueDataDTDTask.java,v 1.3 2001/10/27 19:04:38 jvanzyl Exp $
   */
  public class DataDTDTask 
      extends DataModelTask
  {
  }
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/java/org/apache/commons/sql/SQLExec.java
  
  Index: SQLExec.java
  ===================================================================
  package org.apache.commons.sql;
  
  /*
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution, if
   *    any, must include the following acknowlegement:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowlegement may appear in the software itself,
   *    if and wherever such third-party acknowlegements normally appear.
   *
   * 4. The names "The Jakarta Project", "Ant", and "Apache Software
   *    Foundation" must not be used to endorse or promote products derived
   *    from this software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache"
   *    nor may "Apache" appear in their names without prior written
   *    permission of the Apache Group.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  import java.io.BufferedOutputStream;
  import java.io.BufferedReader;
  import java.io.IOException;
  import java.io.InputStreamReader;
  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileOutputStream;
  import java.io.FileReader;
  import java.io.PrintStream;
  import java.io.StringReader;
  import java.io.Reader;
  import java.util.ArrayList;
  import java.util.Iterator;
  import java.util.Enumeration;
  import java.util.Hashtable;
  import java.util.Vector;
  import java.util.Properties;
  import java.util.TreeSet;
  import java.sql.Connection;
  import java.sql.DatabaseMetaData;
  import java.sql.Driver;
  import java.sql.ResultSet;
  import java.sql.ResultSetMetaData;
  import java.sql.SQLException;
  import java.sql.SQLWarning;
  import java.sql.Statement;
  import org.apache.commons.lang.StringUtils;
  import org.apache.tools.ant.AntClassLoader;
  import org.apache.tools.ant.BuildException;
  import org.apache.tools.ant.Project;
  import org.apache.tools.ant.ProjectHelper;
  import org.apache.tools.ant.Task;
  import org.apache.tools.ant.types.EnumeratedAttribute;
  import org.apache.tools.ant.types.Path;
  import org.apache.tools.ant.types.Reference;
  
  /**
   * This task uses an SQL -> Database map in the form of a properties
   * file to insert each SQL file listed into its designated database.
   *
   * @author <a href="mailto:jeff@custommonkey.org">Jeff Martin</a>
   * @author <a href="mailto:gholam@xtra.co.nz">Michael McCallum</A>
   * @author <a href="mailto:tim.stephenson@sybase.com">Tim Stephenson</A>
   * @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</A>
   * @author <a href="mailto:mpoeschl@marmot.at">Martin Poeschl</a>
   * @version $Id: TorqueSQLExec.java,v 1.6 2002/04/11 22:02:07 mpoeschl Exp $
   */
  public class SQLExec 
      extends Task
  {
      private int goodSql = 0;
      private int totalSql = 0;
      private Path classpath;
      private AntClassLoader loader;
  
      /**
       * 
       */
      static public class DelimiterType extends EnumeratedAttribute
      {
          static public final String NORMAL = "normal";
          static public final String ROW = "row";
  
          public String[] getValues()
          {
              return new String[] {NORMAL, ROW};
          }
      }
  
      /**
       * Database connection
       */
      private Connection conn = null;
  
      /**
       * Autocommit flag. Default value is false
       */
      private boolean autocommit = false;
  
      /**
       * SQL statement
       */
      private Statement statement = null;
  
      /**
       * DB driver.
       */
      private String driver = null;
  
      /**
       * DB url.
       */
      private String url = null;
  
      /**
       * User name.
       */
      private String userId = null;
  
      /**
       * Password
       */
      private String password = null;
  
      /**
       * SQL input command
       */
      private String sqlCommand = "";
  
      /**
       * SQL transactions to perform
       */
      private Vector transactions = new Vector();
  
      /**
       * SQL Statement delimiter
       */
      private String delimiter = ";";
  
      /**
       * The delimiter type indicating whether the delimiter will
       * only be recognized on a line by itself
       */
      private String delimiterType = DelimiterType.NORMAL;
  
      /**
       * Print SQL results.
       */
      private boolean print = false;
  
      /**
       * Print header columns.
       */
      private boolean showheaders = true;
  
      /**
       * Results Output file.
       */
      private File output = null;
  
      /**
       * RDBMS Product needed for this SQL.
       **/
      private String rdbms = null;
  
      /**
       * RDBMS Version needed for this SQL.
       **/
      private String version = null;
  
      /**
       * Action to perform if an error is found
       **/
      private String onError = "abort";
  
      /**
       * Encoding to use when reading SQL statements from a file
       */
      private String encoding = null;
  
      /**
       * Src directory for the files listed in the sqldbmap.
       */
      private String srcDir;
  
      /**
       * Properties file that maps an individual SQL
       * file to a database.
       */
      private File sqldbmap;
  
      /**
       * Set the sqldbmap properties file.
       */
      public void setSqlDbMap(String sqldbmap)
      {
          this.sqldbmap = project.resolveFile(sqldbmap);
      }
  
      /**
       * Get the sqldbmap properties file.
       */
      public File getSqlDbMap()
      {
          return sqldbmap;
      }
  
      /**
       * Set the src directory for the sql files
       * listed in the sqldbmap file.
       */
      public void setSrcDir(String srcDir)
      {
          this.srcDir = project.resolveFile(srcDir).toString();
      }
  
      /**
       * Get the src directory for the sql files
       * listed in the sqldbmap file.
       */
      public String getSrcDir()
      {
          return srcDir;
      }
  
      /**
       * Set the classpath for loading the driver.
       */
      public void setClasspath(Path classpath)
      {
          if (this.classpath == null)
          {
              this.classpath = classpath;
          }
          else
          {
              this.classpath.append(classpath);
          }
      }
  
      /**
       * Create the classpath for loading the driver.
       */
      public Path createClasspath()
      {
          if (this.classpath == null)
          {
              this.classpath = new Path(project);
          }
          return this.classpath.createPath();
      }
  
      /**
       * Set the classpath for loading the driver using the classpath reference.
       */
      public void setClasspathRef(Reference r)
      {
          createClasspath().setRefid(r);
      }
  
      /**
       * Set the sql command to execute
       */
      public void addText(String sql)
      {
          this.sqlCommand += sql;
      }
  
      /**
       * Set the JDBC driver to be used.
       */
      public void setDriver(String driver)
      {
          this.driver = driver;
      }
  
      /**
       * Set the DB connection url.
       */
      public void setUrl(String url)
      {
          this.url = url;
      }
  
      /**
       * Set the user name for the DB connection.
       */
      public void setUserid(String userId)
      {
          this.userId = userId;
      }
  
      /**
       * Set the file encoding to use on the sql files read in
       *
       * @param encoding the encoding to use on the files
       */
      public void setEncoding(String encoding)
      {
          this.encoding = encoding;
      }
  
      /**
       * Set the password for the DB connection.
       */
      public void setPassword(String password)
      {
          this.password = password;
      }
  
      /**
       * Set the autocommit flag for the DB connection.
       */
      public void setAutocommit(boolean autocommit)
      {
          this.autocommit = autocommit;
      }
  
      /**
       * Set the statement delimiter.
       *
       * <p>For example, set this to "go" and delimitertype to "ROW" for
       * Sybase ASE or MS SQL Server.</p>
       */
      public void setDelimiter(String delimiter)
      {
          this.delimiter = delimiter;
      }
  
      /**
       * Set the Delimiter type for this sql task. The delimiter type takes two
       * values - normal and row. Normal means that any occurence of the delimiter
       * terminate the SQL command whereas with row, only a line containing just
       * the delimiter is recognized as the end of the command.
       */
      public void setDelimiterType(DelimiterType delimiterType)
      {
          this.delimiterType = delimiterType.getValue();
      }
  
      /**
       * Set the print flag.
       */
      public void setPrint(boolean print)
      {
          this.print = print;
      }
  
      /**
       * Set the showheaders flag.
       */
      public void setShowheaders(boolean showheaders)
      {
          this.showheaders = showheaders;
      }
  
      /**
       * Set the output file.
       */
      public void setOutput(File output)
      {
          this.output = output;
      }
  
      /**
       * Set the rdbms required
       */
      public void setRdbms(String vendor)
      {
          this.rdbms = vendor.toLowerCase();
      }
  
      /**
       * Set the version required
       */
      public void setVersion(String version)
      {
          this.version = version.toLowerCase();
      }
  
      /**
       * Set the action to perform onerror
       */
      public void setOnerror(OnError action)
      {
          this.onError = action.getValue();
      }
  
      /**
       * Load the sql file and then execute it
       */
      public void execute() throws BuildException
      {
          sqlCommand = sqlCommand.trim();
  
          if (sqldbmap == null || getSqlDbMap().exists() == false)
          {
              throw new BuildException("You haven't provided an sqldbmap, or " +
                  "the one you specified doesn't exist: " + sqldbmap);
          }
  
          if (driver == null)
          {
              throw new BuildException("Driver attribute must be set!", location);
          }
          if (userId == null)
          {
              throw new BuildException("User Id attribute must be set!", location);
          }
          if (password == null)
          {
              throw new BuildException("Password attribute must be set!", location);
          }
          if (url == null)
          {
              throw new BuildException("Url attribute must be set!", location);
          }
  
          Properties p = new Properties();
  
          try
          {
              FileInputStream fis = new FileInputStream(getSqlDbMap());
              p.load(fis);
              fis.close();
          }
          catch (IOException ioe)
          {
              throw new BuildException("Cannot open and process the sqldbmap!");
          }
  
          Hashtable h = new Hashtable();
          TreeSet keys = new TreeSet(p.keySet());
  
          for (Iterator e = keys.iterator(); e.hasNext();)
          {
              String sqlfile = (String) e.next();
              String database = p.getProperty(sqlfile);
  
              ArrayList x = (ArrayList) h.get(database);
  
              if (x == null)
              {
                  x = new ArrayList();
                  h.put(database, x);
              }
  
              // We want to make sure that the base schemas
              // are inserted first.
              if (sqlfile.indexOf("schema.sql") != -1)
              {
                  x.add(0, sqlfile);
              }
              else
              {
                  x.add(sqlfile);
              }
          }
  
          Iterator k = h.keySet().iterator();
  
          while (k.hasNext())
          {
              String db = (String) k.next();
              ArrayList l = (ArrayList) h.get(db);
              Iterator j = l.iterator();
              Vector ts = new Vector();
              while (j.hasNext())
              {
                  String s = (String) j.next();
                  Transaction t = new Transaction();
                  t.setSrc(new File(srcDir,s));
                  ts.addElement(t);
              }
  
              insertDatabaseSqlFiles(url, db, ts);
          }
      }
  
      /**
       * Take the base url, the target database and insert a set of SQL
       * files into the target database.
       */
      private void insertDatabaseSqlFiles(String url, String database, Vector transactions)
      {
          url = StringUtils.replace(url, "@DB@", database);
          System.out.println("Our new url -> " + url);
  
          Driver driverInstance = null;
          try
          {
              Class dc;
              if (classpath != null)
              {
                  log( "Loading " + driver + " using AntClassLoader with classpath " + classpath,
                       Project.MSG_VERBOSE );
  
                  loader = new AntClassLoader(project, classpath);
                  dc = loader.loadClass(driver);
              }
              else
              {
                  log("Loading " + driver + " using system loader.", Project.MSG_VERBOSE);
                  dc = Class.forName(driver);
              }
              driverInstance = (Driver) dc.newInstance();
          }
          catch (ClassNotFoundException e)
          {
              throw new BuildException("Class Not Found: JDBC driver " + driver +
                  " could not be loaded", location);
          }
          catch (IllegalAccessException e)
          {
              throw new BuildException("Illegal Access: JDBC driver " + driver +
                  " could not be loaded", location);
          }
          catch (InstantiationException e)
          {
              throw new BuildException("Instantiation Exception: JDBC driver " +
                  driver + " could not be loaded", location);
          }
  
          try
          {
              log("connecting to " + url, Project.MSG_VERBOSE );
              Properties info = new Properties();
              info.put("user", userId);
              info.put("password", password);
              conn = driverInstance.connect(url, info);
  
              if (conn == null)
              {
                  // Driver doesn't understand the URL
                  throw new SQLException("No suitable Driver for " + url);
              }
  
              if (!isValidRdbms(conn)) 
              {
                  return;
              }
  
              conn.setAutoCommit(autocommit);
              statement = conn.createStatement();
              PrintStream out = System.out;
              try
              {
                  if (output != null)
                  {
                      log("Opening PrintStream to output file " + output, 
                              Project.MSG_VERBOSE);
                      out = new PrintStream(new BufferedOutputStream(
                              new FileOutputStream(output)));
                  }
  
                  // Process all transactions
                  for (Enumeration e = transactions.elements(); 
                          e.hasMoreElements();)
                  {
                      ((Transaction) e.nextElement()).runTransaction(out);
                      if (!autocommit)
                      {
                          log("Commiting transaction", Project.MSG_VERBOSE);
                          conn.commit();
                      }
                  }
              }
              finally
              {
                  if (out != null && out != System.out)
                  {
                      out.close();
                  }
              }
          }
          catch (IOException e)
          {
              if (!autocommit && conn != null && onError.equals("abort"))
              {
                  try
                  {
                      conn.rollback();
                  }
                  catch (SQLException ex)
                  {
                      // do nothing.
                  }
              }
              throw new BuildException(e, location);
          }
          catch (SQLException e)
          {
              if (!autocommit && conn != null && onError.equals("abort"))
              {
                  try
                  {
                      conn.rollback();
                  }
                  catch (SQLException ex)
                  {
                      // do nothing.
                  }
              }
              throw new BuildException(e, location);
          }
          finally
          {
              try
              {
                  if (statement != null)
                  {
                      statement.close();
                  }
                  if (conn != null)
                  {
                      conn.close();
                  }
              }
              catch (SQLException e) {}
          }
  
          log(goodSql + " of " + totalSql +
              " SQL statements executed successfully");
      }
  
      /**
       * 
       * @param reader
       * @param out
       * @throws SQLException
       * @throws IOException
       */
      protected void runStatements(Reader reader, PrintStream out)
              throws SQLException, IOException
      {
          String sql = "";
          String line = "";
  
          BufferedReader in = new BufferedReader(reader);
  
          try
          {
              while ((line = in.readLine()) != null)
              {
                  line = line.trim();
                  line = ProjectHelper.replaceProperties(project, line,
                                                         project.getProperties());
                  if (line.startsWith("//")) continue;
                  if (line.startsWith("--")) continue;
                  if (line.length() > 2 &&
                      line.substring(0,3).equalsIgnoreCase("REM")) continue;
  
                  sql += " " + line;
                  sql = sql.trim();
  
                  // SQL defines "--" as a comment to EOL
                  // and in Oracle it may contain a hint
                  // so we cannot just remove it, instead we must end it
                  if (line.indexOf("--") >= 0) sql += "\n";
  
                  if (delimiterType.equals(DelimiterType.NORMAL) 
                          && sql.endsWith(delimiter) 
                          || delimiterType.equals(DelimiterType.ROW) 
                          && line.equals(delimiter)) 
                  {
                      log("SQL: " + sql, Project.MSG_VERBOSE);
                      execSQL(sql.substring(0, sql.length() - delimiter.length()),
                              out);
                      sql = "";
                  }
              }
  
              // Catch any statements not followed by ;
              if (!sql.equals(""))
              {
                  execSQL(sql, out);
              }
          }
          catch (SQLException e)
          {
              throw e;
          }
      }
  
      /**
       * Verify if connected to the correct RDBMS
       */
      protected boolean isValidRdbms(Connection conn)
      {
          if (rdbms == null && version == null)
          {
              return true;
          }
  
          try
          {
              DatabaseMetaData dmd = conn.getMetaData();
  
              if (rdbms != null)
              {
                  String theVendor = dmd.getDatabaseProductName().toLowerCase();
  
                  log("RDBMS = " + theVendor, Project.MSG_VERBOSE);
                  if (theVendor == null || theVendor.indexOf(rdbms) < 0)
                  {
                      log("Not the required RDBMS: " 
                              + rdbms, Project.MSG_VERBOSE);
                      return false;
                  }
              }
  
              if (version != null)
              {
                  String theVersion = dmd.getDatabaseProductVersion()
                          .toLowerCase();
  
                  log("Version = " + theVersion, Project.MSG_VERBOSE);
                  if (theVersion == null || !(theVersion.startsWith(version) 
                          || theVersion.indexOf(" " + version) >= 0))
                  {
                      log("Not the required version: \"" + version + "\"", 
                              Project.MSG_VERBOSE);
                      return false;
                  }
              }
          }
          catch (SQLException e)
          {
              // Could not get the required information
              log("Failed to obtain required RDBMS information", Project.MSG_ERR);
              return false;
          }
  
          return true;
      }
  
      /**
       * Exec the sql statement.
       */
      protected void execSQL(String sql, PrintStream out) throws SQLException
      {
          // Check and ignore empty statements
          if ("".equals(sql.trim())) return;
  
          try
          {
              totalSql++;
              if (!statement.execute(sql))
              {
                  log(statement.getUpdateCount() + " rows affected",
                          Project.MSG_VERBOSE);
              }
              else
              {
                  if (print)
                  {
                      printResults(out);
                  }
              }
  
              SQLWarning warning = conn.getWarnings();
              while (warning != null)
              {
                  log(warning + " sql warning", Project.MSG_VERBOSE);
                  warning = warning.getNextWarning();
              }
              conn.clearWarnings();
              goodSql++;
          }
          catch (SQLException e)
          {
              log("Failed to execute: " + sql, Project.MSG_ERR);
              if (!onError.equals("continue"))
              {
                  throw e;
              }
              log(e.toString(), Project.MSG_ERR);
          }
      }
  
      /**
       * print any results in the statement.
       */
      protected void printResults(PrintStream out) throws java.sql.SQLException
      {
          ResultSet rs = null;
          do
          {
              rs = statement.getResultSet();
              if (rs != null)
              {
                  log("Processing new result set.", Project.MSG_VERBOSE);
                  ResultSetMetaData md = rs.getMetaData();
                  int columnCount = md.getColumnCount();
                  StringBuffer line = new StringBuffer();
                  if (showheaders)
                  {
                      for (int col = 1; col < columnCount; col++)
                      {
                           line.append(md.getColumnName(col));
                           line.append(",");
                      }
                      line.append(md.getColumnName(columnCount));
                      out.println(line);
                      line.setLength(0);
                  }
                  while (rs.next())
                  {
                      boolean first = true;
                      for (int col = 1; col <= columnCount; col++)
                      {
                          String columnValue = rs.getString(col);
                          if (columnValue != null)
                          {
                              columnValue = columnValue.trim();
                          }
  
                          if (first)
                          {
                              first = false;
                          }
                          else
                          {
                              line.append(",");
                          }
                          line.append(columnValue);
                      }
                      out.println(line);
                      line.setLength(0);
                  }
              }
          }
          while (statement.getMoreResults());
          out.println();
      }
  
      /**
       * Enumerated attribute with the values "continue", "stop" and "abort"
       * for the onerror attribute.
       */
      public static class OnError extends EnumeratedAttribute
      {
          public String[] getValues()
          {
              return new String[] {"continue", "stop", "abort"};
          }
      }
  
      /**
       * Contains the definition of a new transaction element.
       * Transactions allow several files or blocks of statements
       * to be executed using the same JDBC connection and commit
       * operation in between.
       */
      public class Transaction
      {
          private File tSrcFile = null;
          private String tSqlCommand = "";
  
          public void setSrc(File src)
          {
              this.tSrcFile = src;
          }
  
          public void addText(String sql)
          {
              this.tSqlCommand += sql;
          }
  
          private void runTransaction(PrintStream out)
              throws IOException, SQLException
          {
              if (tSqlCommand.length() != 0)
              {
                  log("Executing commands", Project.MSG_INFO);
                  runStatements(new StringReader(tSqlCommand), out);
              }
  
              if (tSrcFile != null)
              {
                  log("Executing file: " + tSrcFile.getAbsolutePath(),
                      Project.MSG_INFO);
                  Reader reader = (encoding == null) ? new FileReader(tSrcFile)
                          : new InputStreamReader(new FileInputStream(tSrcFile), 
                          encoding);
                  runStatements(reader, out);
                  reader.close();
              }
          }
      }
  }
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/java/org/apache/commons/sql/CreateDatabase.java
  
  Index: CreateDatabase.java
  ===================================================================
  package org.apache.commons.sql;
  
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2001 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Apache" and "Apache Software Foundation" and 
   *    "Apache Turbine" must not be used to endorse or promote products 
   *    derived from this software without prior written permission. For 
   *    written permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    "Apache Turbine", nor may "Apache" appear in their name, without 
   *    prior written permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  import org.apache.velocity.context.Context;
  
  /**
   * An extended Texen task used for generating simple scripts
   * for creating databases on various platforms.
   *
   * @author <a href="mailto:jvanzyl@zenplex.com">Jason van Zyl</a>
   * @version $Id: TorqueCreateDatabase.java,v 1.6 2002/04/11 22:02:06 mpoeschl Exp $
   */
  public class CreateDatabase 
      extends DataModelTask
  {
      /**
       * The target database vendor: MySQL, Oracle.
       */
      private String targetDatabase;
  
      /**
       * Get the target database.
       *
       * @return String target database.
       */
      public String getTargetDatabase()
      {
          return targetDatabase;
      }
  
      /**
       * Set the target database.
       *
       * @param String target database(s)
       */
      public void setTargetDatabase(String v)
      {
          targetDatabase = v;
      }
  
      /**
       * Place our target database and target platform
       * values into the context for use in the
       * templates.
       */
      public Context initControlContext() throws Exception
      {   
          super.initControlContext();
          context.put("targetDatabase", targetDatabase);
          return context;
      }
  }
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/java/org/apache/commons/sql/DataDumpTask.java
  
  Index: DataDumpTask.java
  ===================================================================
  package org.apache.commons.sql;
  
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2001 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Apache" and "Apache Software Foundation" and
   *    "Apache Turbine" must not be used to endorse or promote products
   *    derived from this software without prior written permission. For
   *    written permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    "Apache Turbine", nor may "Apache" appear in their name, without
   *    prior written permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  import java.util.Iterator;
  import java.util.NoSuchElementException;
  import java.sql.Connection;
  import java.sql.DriverManager;
  import java.sql.SQLException;
  import java.sql.Statement;
  import org.apache.tools.ant.Project;
  import org.apache.velocity.context.Context;
  
  import com.workingdogs.village.QueryDataSet;
  import com.workingdogs.village.Record;
  
  /**
   * An extended Texen task used for dumping data from db into XML
   *
   * @author <a href="mailto:fedor.karpelevitch@home.com">Fedor Karpelevitch</a>
   * @author <a href="jvanzyl@zenplex.com">Jason van Zyl</a>
   * @author <a href="dlr@finemaltcoding.com">Daniel Rall</a>
   * @version $Id: TorqueDataDumpTask.java,v 1.7 2002/04/11 22:02:06 mpoeschl Exp $
   */
  public class DataDumpTask 
      extends DataModelTask
  {
      /**
       * Database name.
       */
      private String databaseName;
  
      /**
       *  Database URL used for JDBC connection.
       */
      private String databaseUrl;
  
      /**
       *  Database driver used for JDBC connection.
       */
      private String databaseDriver;
  
      /**
       *  Database user used for JDBC connection.
       */
      private String databaseUser;
  
      /**
       *  Database password used for JDBC connection.
       */
      private String databasePassword;
  
      /**
       * The database connection used to retrieve the data to dump.
       */
      private Connection conn;
  
      /**
       * The statement used to acquire the data to dump.
       */
      private Statement stmt;
  
      /**
       *  Get the database name to dump
       *
       * @return  The DatabaseName value
       */
      public String getDatabaseName()
      {
          return databaseName;
      }
  
      /**
       *  Set the database name
       *
       * @param  v The new DatabaseName value
       */
      public void setDatabaseName(String v)
      {
          databaseName = v;
      }
  
      /**
       *  Get the database url
       *
       * @return  The DatabaseUrl value
       */
      public String getDatabaseUrl()
      {
          return databaseUrl;
      }
  
      /**
       *  Set the database url
       *
       * @param  v The new DatabaseUrl value
       */
      public void setDatabaseUrl(String v)
      {
          databaseUrl = v;
      }
  
      /**
       *  Get the database driver name
       *
       * @return  String database driver name
       */
      public String getDatabaseDriver()
      {
          return databaseDriver;
      }
  
      /**
       *  Set the database driver name
       *
       * @param  v The new DatabaseDriver value
       */
      public void setDatabaseDriver(String v)
      {
          databaseDriver = v;
      }
  
      /**
       *  Get the database user
       *
       * @return  String database user
       */
      public String getDatabaseUser()
      {
          return databaseUser;
      }
  
      /**
       *  Set the database user
       *
       * @param  v The new DatabaseUser value
       */
      public void setDatabaseUser(String v)
      {
          databaseUser = v;
      }
  
      /**
       *  Get the database password
       *
       * @return  String database password
       */
      public String getDatabasePassword()
      {
          return databasePassword;
      }
  
      /**
       *  Set the database password
       *
       * @param  v The new DatabasePassword value
       */
      public void setDatabasePassword(String v)
      {
          databasePassword = v;
      }
  
      /**
       *  Initializes initial context
       *
       * @return  Description of the Returned Value
       */
      public Context initControlContext()
          throws Exception
      {
          super.initControlContext();
          
          context.put("dataset", "all");
  
          StringBuffer buf = new StringBuffer("Database settings:\n")
              .append(" driver: ").append(databaseDriver).append('\n')
              .append(" URL: ").append(databaseUrl).append('\n')
              .append(" user: ").append(databaseUser).append('\n')
              .append(" password: ").append(databasePassword).append('\n');
          log(buf.toString(), Project.MSG_DEBUG);
  
          try
          {
              Class.forName(databaseDriver);
              log("DB driver instantiated sucessfuly", Project.MSG_DEBUG);
  
              conn = DriverManager.getConnection(
                      databaseUrl, databaseUser, databasePassword);
  
              log("DB connection established", Project.MSG_DEBUG);
              context.put("tableTool", new TableTool());
          }
          catch (SQLException se)
          {
              System.err.println("SQLException while connecting to DB:");
              se.printStackTrace();
          }
          catch (ClassNotFoundException cnfe)
          {
              System.err.println("cannot load driver:");
              cnfe.printStackTrace();
          }
  
          return context;
      }
  
      /**
       * Closes <code>rs</code> and <code>conn</code>, overriding the
       * <code>cleanup()</code> hook method in <code>TexenTask</code>.
       *
       * @exception Exception Database problem while closing resource.
       */
      protected void cleanup() throws Exception
      {
          if (stmt != null)
          {
              stmt.close();
          }
  
          if (conn != null)
          {
              conn.close();
          }
      }
  
      /**
       *  A nasty do-it-all tool class. It serves as:
       *  <ul>
       *  <li>context tool to fetch a table iterator</li>
       *  <li>the abovenamed iterator which iterates over the table</li>
       *  <li>getter for the table fields</li>
       *  </ul>
       *
       * @author  fedor
       */
      public class TableTool implements Iterator
      {
          private QueryDataSet qds;
          private boolean isEmpty;
          private int curIndex = -1;
          private Record curRec = null;
  
          /**
           *  Constructor for the TableTool object
           */
          public TableTool()
          {
          }
  
          /**
           *  Constructor for the TableTool object
           *
           * @param  rs Description of Parameter
           * @exception SQLException Problem using database record set
           * cursor.
           */
          protected TableTool(QueryDataSet qds) throws Exception
          {
              this.qds = qds;
              this.qds.fetchRecords();
              this.isEmpty = !(qds.size() > 0);
          }
  
          /**
           *  Fetches an <code>Iterator</code> for the data in the named
           *  table.
           *
           * @param  tableName Description of Parameter
           * @return <code>Iterator</code> for the fetched data.
           * @exception SQLException Problem creating connection or
           * executing query.
           */
          public TableTool fetch(String tableName) throws Exception
          {
              log("Fetching data for table " + tableName, Project.MSG_INFO);
              // Set Statement object in associated TorqueDataDump
              // instance
              return new TableTool
                  (new QueryDataSet(conn, "SELECT * FROM " + tableName));
          }
  
          /**
           *  Description of the Method
           *
           * @return  Description of the Returned Value
           */
          public boolean hasNext()
          {
              try
              {
                  return ((this.curIndex < this.qds.size() - 1) && (!isEmpty));
              }
              catch (Exception se)
              {
                  System.err.println("Exception :");
                  se.printStackTrace();
              }
              return false;
          }
  
          /**
           * load the next record from the QueryDataSet
           *
           * @return Description of the Returned Value
           * @exception NoSuchElementException Description of Exception
           */
          public Object next() throws NoSuchElementException
          {
              try
              {
                  System.err.print(".");
                  this.curRec = this.qds.getRecord(++curIndex);
              }
              catch (Exception se)
              {
                  System.err.println("Exception while iterating:");
                  se.printStackTrace();
                  throw new NoSuchElementException(se.getMessage());
              }
              return this;
          }
  
          /**
           * Retruns the value for the column
           *
           * @param  columnName name of the column
           * @return  value of the column or null if it doesn't exist
           */
          public String get(String columnName)
          {
              try
              {
                  return(this.curRec.getValue(columnName).asString());
              }
              catch (Exception se)
              {
                  log("Exception fetching value " + columnName + ": " +
                      se.getMessage(), Project.MSG_ERR);
              }
              return null;
          }
  
          /**
           * unsupported! always throws Exception
           *
           * @exception UnsupportedOperationException
           */
          public void remove() throws UnsupportedOperationException
          {
              throw new UnsupportedOperationException();
          }
      }
  }
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/java/org/apache/commons/sql/SQLTask.java
  
  Index: SQLTask.java
  ===================================================================
  package org.apache.commons.sql;
  
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2001 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Apache" and "Apache Software Foundation" and 
   *    "Apache Turbine" must not be used to endorse or promote products 
   *    derived from this software without prior written permission. For 
   *    written permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    "Apache Turbine", nor may "Apache" appear in their name, without 
   *    prior written permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileOutputStream;
  import java.util.Properties;
  import java.util.Iterator;
  import org.apache.velocity.context.Context;
  import org.apache.velocity.VelocityContext;
  
  /**
   * An extended Texen task used for generating SQL source from
   * an XML schema describing a database structure.
   *
   * @author <a href="mailto:jvanzyl@periapt.com">Jason van Zyl</a>
   * @author <a href="mailto:jmcnally@collab.net>John McNally</a>
   * @version $Id: TorqueSQLTask.java,v 1.11 2002/04/10 21:08:43 dlr Exp $
   */
  public class SQLTask 
      extends DataModelTask
  {
      // if the database is set than all generated sql files
      // will be placed in the specified database, the database
      // will not be taken from the data model schema file.
  
      private String database;
      private String suffix = "";
      
      public void setDatabase(String database)
      {
          this.database = database;
      }
      
      public String getDatabase()
      {
          return database;
      }        
  
      public void setSuffix(String suffix)
      {
          this.suffix = suffix;
      }
      
      public String getSuffix()
      {
          return suffix;
      }        
  
      private void createSqlDbMap()
          throws Exception
      {
          if (getSqlDbMap() == null)
          {
              return;
          }        
          
          // Produce the sql -> database map
          Properties sqldbmap = new Properties();
          
          // Check to see if the sqldbmap has already been created.
          File file = new File(getSqlDbMap());
          
          if (file.exists())
          {
              FileInputStream fis = new FileInputStream(file);
              sqldbmap.load(fis);
              fis.close();
          }
          
          Iterator i = getDataModelDbMap().keySet().iterator();
          
          while (i.hasNext())
          {
              String dataModelName = (String) i.next();
              String sqlFile = dataModelName + suffix + ".sql";
              
              String databaseName;
              
              if (getDatabase() == null)
              {
                  databaseName = (String) getDataModelDbMap().get(dataModelName);
              }
              else
              {   
                  databaseName = getDatabase();
              }
              
              sqldbmap.setProperty(sqlFile,databaseName);
          }
          
          sqldbmap.store(new FileOutputStream(getSqlDbMap()),"Sqlfile -> Database map");
      }
  
      /**
       * Place our target database and target platform
       * values into the context for use in the
       * templates.
       */
      public Context initControlContext()
          throws Exception
      {   
          super.initControlContext();
          context.put("targetDatabase", getTargetDatabase());
          createSqlDbMap();
          return context;
      }
  }
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/java/org/apache/commons/sql/JDBCTransformTask.java
  
  Index: JDBCTransformTask.java
  ===================================================================
  package org.apache.commons.sql;
  
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2001 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Apache" and "Apache Software Foundation" and
   *    "Apache Turbine" must not be used to endorse or promote products
   *    derived from this software without prior written permission. For
   *    written permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    "Apache Turbine", nor may "Apache" appear in their name, without
   *    prior written permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  import java.io.FileOutputStream;
  import java.io.PrintWriter;
  import java.sql.Connection;
  import java.sql.DatabaseMetaData;
  import java.sql.DriverManager;
  import java.sql.ResultSet;
  import java.sql.Types;
  import java.sql.SQLException;
  import java.util.Hashtable;
  import java.util.List;
  import java.util.Vector;
  import java.util.Collection;
  import java.util.Iterator;
  import org.apache.tools.ant.BuildException;
  import org.apache.tools.ant.Task;
  import org.apache.xerces.dom.DocumentImpl;
  import org.apache.xerces.dom.DocumentTypeImpl;
  import org.apache.xml.serialize.OutputFormat;
  import org.apache.xml.serialize.Method;
  import org.apache.xml.serialize.XMLSerializer;
  import org.w3c.dom.Element;
  import org.w3c.dom.Node;
  
  /**
   * This class generates an XML schema of an existing database from
   * JDBC metadata.
   *
   * @author <a href="mailto:jason@zenplex.com">Jason van Zyl</a>
   * @author <a href="mailto:fedor.karpelevitch@barra.com">Fedor Karpelevitch</a>
   * @version $Id: TorqueJDBCTransformTask.java,v 1.7 2002/04/11 22:02:06 mpoeschl Exp $
   */
  public class JDBCTransformTask 
      extends Task
  {
      /** Name of XML database schema produced. */
      protected String xmlSchema;
  
      /** JDBC URL. */
      protected String dbUrl;
  
      /** JDBC driver. */
      protected String dbDriver;
  
      /** JDBC user name. */
      protected String dbUser;
  
      /** JDBC password. */
      protected String dbPassword;
  
      /** DB schema to use. */
      protected String dbSchema;
  
      /** DOM document produced. */
      protected DocumentImpl doc;
  
      protected Node database, appData;
  
      /** Hashtable of columns that have primary keys. */
      protected Hashtable primaryKeys;
  
      /** Hashtable to track what table a column belongs to. */
      protected Hashtable columnTableMap;
  
      protected boolean sameJavaName;
  
      XMLSerializer xmlSerializer;
  
      public String getDbSchema()
      {
          return dbSchema;
      }
  
      public void setDbSchema(String dbSchema)
      {
          this.dbSchema = dbSchema;
      }
  
      public void setDbUrl(String v)
      {
          dbUrl = v;
      }
  
      public void setDbDriver(String v)
      {
          dbDriver = v;
      }
  
      public void setDbUser(String v)
      {
          dbUser = v;
      }
  
      public void setDbPassword(String v)
      {
          dbPassword = v;
      }
  
      public void setOutputFile (String v)
      {
          xmlSchema = v;
      }
  
      public void setSameJavaName(boolean v)
      {
          this.sameJavaName = v;
      }
  
      public boolean isSameJavaName()
      {
          return this.sameJavaName;
      }
  
      /**
       * Default constructor.
       */
      public void execute() throws BuildException
      {
          System.err.println("Torque - JDBCToXMLSchema starting\n");
          System.err.println("Your DB settings are:");
          System.err.println("driver : " + dbDriver);
          System.err.println("URL : " + dbUrl);
          System.err.println("user : " + dbUser);
          System.err.println("password : " + dbPassword);
          System.err.println("schema : " + dbSchema);
  
          DocumentTypeImpl docType= new DocumentTypeImpl(null, "app-data", null,
              "http://jakarta.apache.org/turbine/dtd/database.dtd");
          doc = new DocumentImpl(docType);
          doc.appendChild(doc.createComment(" Autogenerated by JDBCToXMLSchema! "));
  
          try
          {
              generateXML();
              xmlSerializer = new XMLSerializer(
                  new PrintWriter(
                  new FileOutputStream(xmlSchema)),
                  new OutputFormat(Method.XML, null, true));
              xmlSerializer.serialize(doc);
          }
          catch (Exception e)
          {
              System.err.println(e);
              e.printStackTrace();
          }
  
          System.err.println("\nTorque - JDBCToXMLSchema finished");
      }
  
      /**
       * Generates an XML database schema from JDBC metadata.
       *
       * @exception Exception, a generic exception.
       */
      public void generateXML() throws Exception
      {
          // Load the Interbase Driver.
          Class.forName(dbDriver);
          System.err.println("DB driver sucessfuly instantiated");
  
          // Attemtp to connect to a database.
          Connection con = DriverManager.getConnection(dbUrl,
                                                       dbUser,
                                                       dbPassword);
          System.err.println("DB connection established");
  
          // Get the database Metadata.
          DatabaseMetaData dbMetaData = con.getMetaData();
  
          // The database map.
          List tableList = getTableNames(dbMetaData);
  
          appData = doc.createElement("app-data");
          database = doc.createElement("database");
  
          // Build a database-wide column -> table map.
          columnTableMap = new Hashtable();
  
          log("Building column/table map...");
          for (int i = 0; i < tableList.size(); i++)
          {
              String curTable = (String) tableList.get(i);
              List columns = getColumns(dbMetaData, curTable);
  
              for (int j = 0; j < columns.size(); j++)
              {
                  List col = (List) columns.get(j);
                  String name = (String) col.get(0);
  
                  columnTableMap.put(name, curTable);
              }
          }
  
          for (int i = 0; i < tableList.size(); i++)
          {
              // Add Table.
              String curTable = (String) tableList.get(i);
              // dbMap.addTable(curTable);
              log("Processing table: " + curTable);
  
              Element table = doc.createElement("table");
              table.setAttribute("name", curTable);
              if (isSameJavaName())
              {
                  table.setAttribute("javaName", curTable);
              }
  
              // Add Columns.
              // TableMap tblMap = dbMap.getTable(curTable);
  
              List columns = getColumns(dbMetaData, curTable);
              List primKeys = getPrimaryKeys(dbMetaData, curTable);
              Collection forgnKeys = getForeignKeys(dbMetaData, curTable);
  
              // Set the primary keys.
              primaryKeys = new Hashtable();
  
              for (int k = 0; k < primKeys.size(); k++)
              {
                  String curPrimaryKey = (String) primKeys.get(k);
                  primaryKeys.put(curPrimaryKey, curPrimaryKey);
              }
  
              for (int j = 0; j < columns.size(); j++)
              {
                  List col = (List) columns.get(j);
                  String name = (String) col.get(0);
                  Integer type = ((Integer) col.get(1));
                  int size = ((Integer) col.get(2)).intValue();
  
                  // From DatabaseMetaData.java
                  //
                  // Indicates column might not allow NULL values.  Huh?
                  // Might? Boy, that's a definitive answer.
                  /* int columnNoNulls = 0; */
  
                  // Indicates column definitely allows NULL values.
                  /* int columnNullable = 1; */
  
                  // Indicates NULLABILITY of column is unknown.
                  /* int columnNullableUnknown = 2; */
  
                  Integer nullType = (Integer) col.get(3);
                  String defValue = (String) col.get(4);
  
                  Element column = doc.createElement("column");
                  column.setAttribute("name", name);
                  if (isSameJavaName())
                  {
                      column.setAttribute("javaName", name);
                  }
                  column.setAttribute("type", TypeMap.getTorqueType(type));
  
                  if (size > 0 &&
                      (type.intValue() == Types.CHAR ||
                       type.intValue() == Types.VARCHAR ||
                       type.intValue() == Types.LONGVARCHAR))
                  {
                      column.setAttribute("size",
                              new Integer(size).toString());
                  }
  
                  if (nullType.intValue() == 0)
                  {
                      column.setAttribute("required", "true");
                  }
  
                  if (primaryKeys.containsKey(name))
                  {
                      column.setAttribute("primaryKey", "true");
                  }
  
                  if (defValue!=null)
                  {
                      // trim out parens & quotes out of def value.
                      // makes sense for MSSQL. not sure about others.
  
                      if (defValue.startsWith("(") && defValue.endsWith(")"))
                      {
                          defValue = defValue.substring(1, defValue.length() - 1);
                      }
  
                      if (defValue.startsWith("'") && defValue.endsWith("'"))
                      {
                          defValue = defValue.substring(1, defValue.length() - 1);
                      }
  
                      column.setAttribute("default", defValue);
                  }
  
                  table.appendChild(column);
              }
  
              // Foreign keys for this table.
              for (Iterator l = forgnKeys.iterator(); l.hasNext();)
              {
                  Object[] forKey = (Object[]) l.next();
                  String foreignKeyTable = (String)forKey[0];
                  List refs = (List) forKey[1];
                  Element fk = doc.createElement("foreign-key");
                  fk.setAttribute("foreignTable", foreignKeyTable);
                  for (int m = 0; m < refs.size(); m++)
                  {
                      Element ref = doc.createElement("reference");
                      String[] refData = (String[]) refs.get(m);
                      ref.setAttribute("local", refData[0]);
                      ref.setAttribute("foreign", refData[1]);
                      fk.appendChild(ref);
                  }
                  table.appendChild(fk);
              }
  
              database.appendChild(table);
          }
          appData.appendChild(database);
          doc.appendChild(appData);
      }
  
      /**
       * Get all the table names in the current database that are not
       * system tables.
       *
       * @param dbMeta JDBC database metadata.
       * @return The list of all the tables in a database.
       * @exception SQLException
       */
      public List getTableNames(DatabaseMetaData dbMeta)
          throws SQLException
      {
          log("Getting table list...");
          List tables = new Vector();
          ResultSet tableNames = null;
          // these are the entity types we want from the database
          String[] types = {"TABLE", "VIEW"};
          try
          {
              tableNames = dbMeta.getTables(null, dbSchema, "%", types);
              while (tableNames.next())
              {
                  String name = tableNames.getString(3);
                  String type = tableNames.getString(4);
                  tables.add(name);
              }
          }
          finally
          {
              if (tableNames != null)
              {
                  tableNames.close();
              }
          }
          return tables;
      }
  
      /**
       * Retrieves all the column names and types for a given table from
       * JDBC metadata.  It returns a vector of vectors.  Each element
       * of the returned vector is a vector with:
       *
       * element 0 => a String object for the column name.
       * element 1 => an Integer object for the column type.
       * element 2 => size of the column.
       * element 3 => null type.
       *
       * @param dbMeta JDBC metadata.
       * @param tableName Table from which to retrieve column
       * information.
       * @return The list of columns in <code>tableName</code>.
       */
      public List getColumns(DatabaseMetaData dbMeta, String tableName)
          throws SQLException
      {
          List columns = new Vector();
          ResultSet columnSet = null;
          try
          {
              columnSet = dbMeta.getColumns(null, dbSchema, tableName, null);
              while (columnSet.next())
              {
                  String name = columnSet.getString(4);
                  Integer sqlType = new Integer(columnSet.getString(5));
                  Integer size = new Integer(columnSet.getInt(7));
                  Integer nullType = new Integer(columnSet.getInt(11));
                  String defValue = columnSet.getString(13);
  
                  List col = new Vector(5);
                  col.add(name);
                  col.add(sqlType);
                  col.add(size);
                  col.add(nullType);
                  col.add(defValue);
                  columns.add(col);
              }
          }
          finally
          {
              if (columnSet != null)
              {
                  columnSet.close();
              }
          }
          return columns;
      }
  
      /**
       * Retrieves a list of the columns composing the primary key for a given
       * table.
       *
       * @param dbMeta JDBC metadata.
       * @param tableName Table from which to retrieve PK information.
       * @return A list of the primary key parts for <code>tableName</code>.
       */
      public List getPrimaryKeys(DatabaseMetaData dbMeta, String tableName)
          throws SQLException
      {
          List pk = new Vector();
          ResultSet parts = null;
          try
          {
              parts = dbMeta.getPrimaryKeys(null, dbSchema, tableName);
              while (parts.next())
              {
                  pk.add(parts.getString(4));
              }
          }
          finally
          {
              if (parts != null)
              {
                  parts.close();
              }
          }
          return pk;
      }
  
      /**
       * Retrieves a list of foreign key columns for a given table.
       *
       * @param dbMeta JDBC metadata.
       * @param tableName Table from which to retrieve FK information.
       * @return A list of foreign keys in <code>tableName</code>.
       */
      public Collection getForeignKeys(DatabaseMetaData dbMeta, String tableName)
          throws SQLException
      {
          Hashtable fks = new Hashtable();
          ResultSet foreignKeys = null;
          try
          {
              foreignKeys = dbMeta.getImportedKeys(null, dbSchema, tableName);
              while (foreignKeys.next())
              {
                  String fkName = foreignKeys.getString(12);
                  // if FK has no name - make it up (use tablename instead)
                  if (fkName == null)
                  {
                      fkName = foreignKeys.getString(3);
                  }
                  Object[] fk = (Object[])fks.get(fkName);
                  List refs;
                  if (fk == null)
                  {
                      fk = new Object[2];
                      fk[0] = foreignKeys.getString(3); //referenced table name
                      refs = new Vector();
                      fk[1] = refs;
                      fks.put(fkName, fk);
                  }
                  else
                  {
                      refs = (Vector)fk[1];
                  }
                  String[] ref = new String[2];
                  ref[0] = foreignKeys.getString(8); //local column
                  ref[1] = foreignKeys.getString(4); //foreign column
                  refs.add(ref);
              }
          }
          finally
          {
              if (foreignKeys != null)
              {
                  foreignKeys.close();
              }
          }
          return fks.values();
      }
  }
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/java/org/apache/commons/sql/DataModelTask.java
  
  Index: DataModelTask.java
  ===================================================================
  package org.apache.commons.sql;
  
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2001 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Apache" and "Apache Software Foundation" and
   *    "Apache Turbine" must not be used to endorse or promote products
   *    derived from this software without prior written permission. For
   *    written permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    "Apache Turbine", nor may "Apache" appear in their name, without
   *    prior written permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  import java.io.File;
  import java.util.Hashtable;
  import java.util.Iterator;
  import java.util.Vector;
  import org.apache.tools.ant.BuildException;
  import org.apache.tools.ant.DirectoryScanner;
  import org.apache.tools.ant.types.FileSet;
  import org.apache.velocity.context.Context;
  import org.apache.velocity.VelocityContext;
  import org.apache.velocity.texen.ant.TexenTask;
  
  /**
   * A base torque task that uses either a single XML schema
   * representing a data model, or a &lt;fileset&gt; of XML schemas.
   * We are making the assumption that an XML schema representing
   * a data model contains tables for a <strong>single</strong>
   * database.
   *
   * @author <a href="mailto:jvanzyl@zenplex.com">Jason van Zyl</a>
   * @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a>
   */
  public class DataModelTask
      extends TexenTask
  {
      /**
       *  XML that describes the database model, this is transformed
       *  into the application model object.
       */
      protected String xmlFile;
  
      /**
       * Fileset of XML schemas which represent our data models.
       */
      protected Vector filesets = new Vector();
      
      /**
       * Data models that we collect. One from each XML schema file.
       */
      protected Vector dataModels = new Vector();
  
      /**
       * Velocity context which exposes our objects
       * in the templates.
       */
      protected Context context;
  
      /**
       * Map of data model name to database name.
       * Should probably stick to the convention
       * of them being the same but I know right now
       * in a lot of cases they won't be.
       */
      protected Hashtable dataModelDbMap;
      
      /**
       * Hashtable containing the names of all the databases
       * in our collection of schemas.
       */
      protected Hashtable databaseNames;
  
      //!! This is probably a crappy idea having the sql file -> db map
      // here. I can't remember why I put it here at the moment ...
      // maybe I was going to map something else. It can probably 
      // move into the SQL task.
  
      /**
       * Name of the properties file that maps an SQL file
       * to a particular database.
       */
      protected String sqldbmap;
  
      /**
       * The path to properties file containing db idiosyncrasies is
       * constructed by appending the "getTargetDatabase()/db.props
       * to this path.
       */
      private String basePathToDbProps;
  
      /**
       * The target database(s) we are generating SQL
       * for. Right now we can only deal with a single
       * target, but we will support multiple targets
       * soon.
       */
      private String targetDatabase;
  
      /**
       * Set the sqldbmap.
       *
       * @param sqldbmap th db map 
       */
      public void setSqlDbMap(String sqldbmap)
      {
          //!! Make all these references files not strings.
          this.sqldbmap = project.resolveFile(sqldbmap).toString();
      }
      
      /**
       * Get the sqldbmap.
       *
       * @return String sqldbmap.
       */
      public String getSqlDbMap()
      {
          return sqldbmap;
      }        
  
      /**
       * Return the data models that have been
       * processed.
       *
       * @return Vector data models
       */
      public Vector getDataModels()
      {
          return dataModels;
      }        
  
      /**
       * Return the data model to database name map.
       *
       * @return Hashtable data model name to database name map.
       */
      public Hashtable getDataModelDbMap()
      {
          return dataModelDbMap;
      }        
  
      /**
       * Get the xml schema describing the application model.
       *
       * @return  String xml schema file.
       */
      public String getXmlFile()
      {
          return xmlFile;
      }
  
      /**
       * Set the xml schema describing the application model.
       *
       * @param xmlFile The new XmlFile value
       */
      public void setXmlFile(String xmlFile)
      {
          this.xmlFile = project.resolveFile(xmlFile).toString();
      }
  
      /**
       * Adds a set of files (nested fileset attribute).
       */
      public void addFileset(FileSet set) 
      {
          filesets.addElement(set);
      }
  
      /**
       * Get the current target package.
       *
       * @return String target database(s)
       */
      public String getTargetDatabase()
      {
          return targetDatabase;
      }
  
      /**
       * Set the current target package.  This is where
       * generated java classes will live.
       *
       * @param v target database(s)
       */
      public void setTargetDatabase(String v)
      {
          targetDatabase = v;
      }
      
      /**
       * The path to properties file containing db idiosyncrasies is
       * constructed by appending the "getTargetDatabase()/db.props
       * to this path.
       */
      public String getBasePathToDbProps() 
      {
          return basePathToDbProps;
      }
      
      /**
       * The path to properties file containing db idiosyncrasies is
       * constructed by appending the "getTargetDatabase()/db.props
       * to this path.
       */
      public void setBasePathToDbProps(String  v) 
      {
          this.basePathToDbProps = v;
      }
      
      /**
       * Set up the initialial context for generating the SQL from the XML schema.
       *
       * @return  Description of the Returned Value
       */
      public Context initControlContext() 
          throws Exception
      {
          if (xmlFile == null && filesets.isEmpty())
          {
              throw new BuildException("You must specify an XML schema or " +
                  "fileset of XML schemas!");
          }            
  
          if (xmlFile != null)
          {
              // Transform the XML database schema into
              // data model object.
              //dataModels.addElement(ad);
          } 
          else 
          { 
              // Deal with the filesets.
              for (int i = 0; i < filesets.size(); i++) 
              {
                  FileSet fs = (FileSet) filesets.elementAt(i);
                  DirectoryScanner ds = fs.getDirectoryScanner(project);
                  File srcDir = fs.getDir(project);
  
                  String[] dataModelFiles = ds.getIncludedFiles();
  
                  // Make a transaction for each file
                  for (int j = 0; j < dataModelFiles.length; j++)
                  {
                      //dataModels.addElement(ad);
                  }
              }
          }
          
          Iterator i = dataModels.iterator();
          databaseNames = new Hashtable();
          dataModelDbMap = new Hashtable();        
          
          // Different datamodels may state the same database
          // names, we just want the unique names of databases.
          
          /*
          while (i.hasNext())
          {
              AppData ad = (AppData) i.next();
              Database database = ad.getDatabase();
              databaseNames.put(database.getName(), database.getName());
              dataModelDbMap.put(ad.getName(), database.getName());
          }
          */
  
          // Create a new Velocity context.
          context = new VelocityContext();
          
          // Place our set of data models into the context along
          // with the names of the databases as a convenience for
          // now. 
          context.put("dataModels", dataModels);
          context.put("databaseNames", databaseNames);
      
          return context;
      }
  
      /**
       * Gets a name to use for the application's data model.
       *
       * @param xmlFile The path to the XML file housing the data model.
       * @return The name to use for the <code>AppData</code>.
       */
      private String grokName(String xmlFile)
      {
          // This can't be set from the file name as it is an unreliable
          // method of naming the descriptor. Not everyone uses the same
          // method as I do in the TDK. jvz.
  
          String name = "data-model";
          int i = xmlFile.lastIndexOf(System.getProperty("file.separator"));
          if (i != -1)
          {
              // Creep forward to the start of the file name.
              i++;
  
              int j = xmlFile.lastIndexOf('.');
              if (i < j)
              {
                  name = xmlFile.substring(i, j);
              }
              else
              {
                  // Weirdo
                  name = xmlFile.substring(i);
              }
          }
          return name;
      }
  }
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/java/org/apache/commons/sql/DataSQLTask.java
  
  Index: DataSQLTask.java
  ===================================================================
  package org.apache.commons.sql;
  
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2001 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Apache" and "Apache Software Foundation" and
   *    "Apache Turbine" must not be used to endorse or promote products
   *    derived from this software without prior written permission. For
   *    written permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    "Apache Turbine", nor may "Apache" appear in their name, without
   *    prior written permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  import java.io.FileInputStream;
  import java.io.FileOutputStream;
  import java.util.List;
  import java.util.Properties;
  import org.apache.velocity.context.Context;
  
  import org.apache.commons.sql.datamodel.Database;
  
  /**
   * An extended Texen task used for generating SQL source from an XML data file
   *
   * @author <a href="mailto:jason@zenplex.com"> Jason van Zyl </a>
   * @author <a href="mailto:jmcnally@collab.net"> John McNally </a>
   * @author <a href="mailto:fedor.karpelevitch@home.com"> Fedor Karpelevitch </a>
   * @version $Id: TorqueDataSQLTask.java,v 1.8 2002/04/11 22:02:06 mpoeschl Exp $
   */
  public class DataSQLTask 
      extends DataModelTask
  {
      private String dataXmlFile;
      private String dataDTD;
  
      /**
       * The target database(s) we are generating SQL for. Right now we can only
       * deal with a single target, but we will support multiple targets soon.
       */
      private String targetDatabase;
  
      /**
       * Sets the DataXmlFile attribute of the TorqueDataSQLTask object
       *
       * @param  dataXmlFile The new DataXmlFile value
       */
      public void setDataXmlFile(String dataXmlFile)
      {
          this.dataXmlFile = project.resolveFile(dataXmlFile).toString();
      }
  
      /**
       * Gets the DataXmlFile attribute of the TorqueDataSQLTask object
       *
       * @return  The DataXmlFile value
       */
      public String getDataXmlFile()
      {
          return dataXmlFile;
      }
  
      /**
       * Get the current target database.
       *
       * @return  String target database(s)
       */
      public String getTargetDatabase()
      {
          return targetDatabase;
      }
  
      /**
       * Set the current target database.  This is where generated java classes
       * will live.
       *
       * @param  v The new TargetDatabase value
       */
      public void setTargetDatabase(String v)
      {
          targetDatabase = v;
      }
  
      /**
       * Gets the DataDTD attribute of the TorqueDataSQLTask object
       *
       * @return  The DataDTD value
       */
      public String getDataDTD()
      {
          return dataDTD;
      }
  
      /**
       * Sets the DataDTD attribute of the TorqueDataSQLTask object
       *
       * @param  dataDTD The new DataDTD value
       */
      public void setDataDTD(String dataDTD)
      {
          this.dataDTD = project.resolveFile(dataDTD).toString();
      }
  
      /**
       * Set up the initialial context for generating the SQL from the XML schema.
       *
       * @return  Description of the Returned Value
       */
      public Context initControlContext()
          throws Exception
      {
          super.initControlContext();
          
          /*
          
          AppData app = (AppData) getDataModels().elementAt(0);
          Database db = app.getDatabase();
  
          try
          {
              XmlToData dataXmlParser = new XmlToData(db, dataDTD);
              List data = dataXmlParser.parseFile(dataXmlFile);
              context.put("data", data);
          }
          catch (Exception e)
          {
              throw new Exception("Exception parsing data XML:");
          }
  
          // Place our model in the context.
          context.put("appData", app);
  
          */
  
          Database db = null;
  
          // Place the target database in the context.
          context.put("targetDatabase", targetDatabase);
  
          Properties p = new Properties();
          FileInputStream fis = new FileInputStream(getSqlDbMap());
          p.load(fis);
          fis.close();
  
          p.setProperty(getOutputFile(), db.getName());
          p.store(new FileOutputStream(getSqlDbMap()), "Sqlfile -> Database map");
  
          return context;
      }
  }
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/java/org/apache/commons/sql/DocumentationTask.java
  
  Index: DocumentationTask.java
  ===================================================================
  package org.apache.commons.sql;
  
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2001 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Apache" and "Apache Software Foundation" and
   *    "Apache Turbine" must not be used to endorse or promote products
   *    derived from this software without prior written permission. For
   *    written permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    "Apache Turbine", nor may "Apache" appear in their name, without
   *    prior written permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  import org.apache.velocity.context.Context;
  
  /**
   * An ant task for generating output by using Velocity
   *
   * @author <a href="mailto:mpoeschl@marmot.at">Martin Poeschl</a>
   * @version $Id: TorqueDocumentationTask.java,v 1.2 2002/04/11 22:02:06 mpoeschl Exp $
   */
  public class DocumentationTask 
      extends DataModelTask
  {
  
      /**
       * The target database(s) we are generating SQL
       * for. Right now we can only deal with a single
       * target, but we will support multiple targets
       * soon.
       */
      private String targetDatabase;
  
      private String outputFormat;
  
  
      /**
       * Get the current target package.
       *
       * @return String target database(s)
       */
      public String getTargetDatabase()
      {
          return targetDatabase;
      }
  
      /**
       * Set the current target package.  This is where
       * generated java classes will live.
       *
       * @param v target database(s)
       */
      public void setTargetDatabase(String v)
      {
          targetDatabase = v;
      }
  
      /**
       * Get the current output format.
       *
       * @return the current output format
       */
      public String getOutputFormat()
      {
          return outputFormat;
      }
  
      /**
       * Set the current output format.
       *
       * @param v output format
       */
      public void setOutputFormat(String v)
      {
          outputFormat = v;
      }
  
      /**
       * Place our target package value into the context for use in the templates.
       */
      public Context initControlContext() throws Exception
      {
          super.initControlContext();
          context.put("targetDatabase", targetDatabase);
          context.put("outputFormat", outputFormat);
          return context;
      }
  }
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/java/org/apache/commons/sql/TypeMap.java
  
  Index: TypeMap.java
  ===================================================================
  package org.apache.commons.sql;
  
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2001 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Apache" and "Apache Software Foundation" and
   *    "Apache Turbine" must not be used to endorse or promote products
   *    derived from this software without prior written permission. For
   *    written permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    "Apache Turbine", nor may "Apache" appear in their name, without
   *    prior written permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  import java.util.Hashtable;
  import java.sql.Types;
  
  // I don't know if the peer system deals
  // with the recommended mappings.
  //
  //import java.sql.Date;
  //import java.sql.Time;
  //import java.sql.Timestamp;
  
  /**
   * A class that maps JDBC types to their corresponding
   * Java object types, and Java native types. Used
   * by Column.java to perform object/native mappings.
   *
   * These are the official SQL type to Java type mappings.
   * These don't quite correspond to the way the peer
   * system works so we'll have to make some adjustments.
   * <pre>
   * -------------------------------------------------------
   * SQL Type      | Java Type            | Peer Type
   * -------------------------------------------------------
   * CHAR          | String               | String
   * VARCHAR       | String               | String
   * LONGVARCHAR   | String               | String
   * NUMERIC       | java.math.BigDecimal | java.math.BigDecimal
   * DECIMAL       | java.math.BigDecimal | java.math.BigDecimal
   * BIT           | boolean OR Boolean   | Boolean
   * TINYINT       | byte OR Byte         | Byte
   * SMALLINT      | short OR Short       | Short
   * INTEGER       | int OR Integer       | Integer
   * BIGINT        | long OR Long         | Long
   * REAL          | float OR Float       | Float
   * FLOAT         | double OR Double     | Double
   * DOUBLE        | double OR Double     | Double
   * BINARY        | byte[]               | ?
   * VARBINARY     | byte[]               | ?
   * LONGVARBINARY | byte[]               | ?
   * DATE          | java.sql.Date        | java.util.Date
   * TIME          | java.sql.Time        | java.util.Date
   * TIMESTAMP     | java.sql.Timestamp   | java.util.Date
   *
   * -------------------------------------------------------
   * A couple variations have been introduced to cover cases
   * that may arise, but are not covered above
   * BOOLEANCHAR   | boolean OR Boolean   | String
   * BOOLEANINT    | boolean OR Boolean   | Integer
   * </pre>
   *
   * @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
   * @version $Id: TypeMap.java,v 1.5 2002/04/11 22:02:06 mpoeschl Exp $
   */
  public class TypeMap
  {
      public static final String CHAR = "CHAR";
      public static final String VARCHAR = "VARCHAR";
      public static final String LONGVARCHAR = "LONGVARCHAR";
      public static final String CLOB = "CLOB";
      public static final String NUMERIC = "NUMERIC";
      public static final String DECIMAL = "DECIMAL";
      public static final String BIT = "BIT";
      public static final String TINYINT = "TINYINT";
      public static final String SMALLINT = "SMALLINT";
      public static final String INTEGER = "INTEGER";
      public static final String BIGINT = "BIGINT";
      public static final String REAL = "REAL";
      public static final String FLOAT = "FLOAT";
      public static final String DOUBLE = "DOUBLE";
      public static final String BINARY = "BINARY";
      public static final String VARBINARY = "VARBINARY";
      public static final String LONGVARBINARY = "LONGVARBINARY";
      public static final String BLOB = "BLOB";
      public static final String DATE = "DATE";
      public static final String TIME = "TIME";
      public static final String TIMESTAMP = "TIMESTAMP";
      public static final String BOOLEANCHAR = "BOOLEANCHAR";
      public static final String BOOLEANINT = "BOOLEANINT";
      
      private static final String[] TEXT_TYPES =
      {
          CHAR, VARCHAR, LONGVARCHAR, CLOB, DATE, TIME, TIMESTAMP, BOOLEANCHAR
      };
  
      private static Hashtable torqueTypeToJdbcTypeMap = null;
      private static Hashtable jdbcToTorqueTypeMap = null;
      private static boolean isInitialized = false;
  
      /**
       * Initializes the SQL to Java map so that it
       * can be used by client code.
       */
      public synchronized static void initialize()
      {
          if (isInitialized == false)
          {
              /*
               * Create JDBC -> Java object mappings.
               */
  
              torqueTypeToJdbcTypeMap = new Hashtable();
  
              torqueTypeToJdbcTypeMap.put(CHAR, CHAR);
              torqueTypeToJdbcTypeMap.put(VARCHAR, VARCHAR);
              torqueTypeToJdbcTypeMap.put(LONGVARCHAR, LONGVARCHAR);
              torqueTypeToJdbcTypeMap.put(CLOB, CLOB);
              torqueTypeToJdbcTypeMap.put(NUMERIC, NUMERIC);
              torqueTypeToJdbcTypeMap.put(DECIMAL, DECIMAL);
              torqueTypeToJdbcTypeMap.put(BIT, BIT);
              torqueTypeToJdbcTypeMap.put(TINYINT, TINYINT);
              torqueTypeToJdbcTypeMap.put(SMALLINT, SMALLINT);
              torqueTypeToJdbcTypeMap.put(INTEGER, INTEGER);
              torqueTypeToJdbcTypeMap.put(BIGINT, BIGINT);
              torqueTypeToJdbcTypeMap.put(REAL, REAL);
              torqueTypeToJdbcTypeMap.put(FLOAT, FLOAT);
              torqueTypeToJdbcTypeMap.put(DOUBLE, DOUBLE);
              torqueTypeToJdbcTypeMap.put(BINARY, BINARY);
              torqueTypeToJdbcTypeMap.put(VARBINARY, VARBINARY);
              torqueTypeToJdbcTypeMap.put(LONGVARBINARY, LONGVARBINARY);
              torqueTypeToJdbcTypeMap.put(BLOB, BLOB);
              torqueTypeToJdbcTypeMap.put(DATE, DATE);
              torqueTypeToJdbcTypeMap.put(TIME, TIME);
              torqueTypeToJdbcTypeMap.put(TIMESTAMP, TIMESTAMP);
  
              /*
               * Create JDBC type code to torque type map.
               */
              jdbcToTorqueTypeMap = new Hashtable();
  
              jdbcToTorqueTypeMap.put(new Integer(Types.CHAR), CHAR);
              jdbcToTorqueTypeMap.put(new Integer(Types.VARCHAR), VARCHAR);
              jdbcToTorqueTypeMap.put(new Integer(Types.LONGVARCHAR), LONGVARCHAR);
              jdbcToTorqueTypeMap.put(new Integer(Types.CLOB), CLOB);
              jdbcToTorqueTypeMap.put(new Integer(Types.NUMERIC), NUMERIC);
              jdbcToTorqueTypeMap.put(new Integer(Types.DECIMAL), DECIMAL);
              jdbcToTorqueTypeMap.put(new Integer(Types.BIT), BIT);
              jdbcToTorqueTypeMap.put(new Integer(Types.TINYINT), TINYINT);
              jdbcToTorqueTypeMap.put(new Integer(Types.SMALLINT), SMALLINT);
              jdbcToTorqueTypeMap.put(new Integer(Types.INTEGER), INTEGER);
              jdbcToTorqueTypeMap.put(new Integer(Types.BIGINT), BIGINT);
              jdbcToTorqueTypeMap.put(new Integer(Types.REAL), REAL);
              jdbcToTorqueTypeMap.put(new Integer(Types.FLOAT), FLOAT);
              jdbcToTorqueTypeMap.put(new Integer(Types.DOUBLE), DOUBLE);
              jdbcToTorqueTypeMap.put(new Integer(Types.BINARY), BINARY);
              jdbcToTorqueTypeMap.put(new Integer(Types.VARBINARY), VARBINARY);
              jdbcToTorqueTypeMap.put(new Integer(Types.LONGVARBINARY), LONGVARBINARY);
              jdbcToTorqueTypeMap.put(new Integer(Types.BLOB), BLOB);
              jdbcToTorqueTypeMap.put(new Integer(Types.DATE), DATE);
              jdbcToTorqueTypeMap.put(new Integer(Types.TIME), TIME);
              jdbcToTorqueTypeMap.put(new Integer(Types.TIMESTAMP), TIMESTAMP);
  
              isInitialized = true;
          }
      }
  
      /**
       * Report whether this object has been initialized.
       */
      public static boolean isInitialized()
      {
          return isInitialized;
      }
  
      /**
       * Returns the correct jdbc type for torque added types
       */
      public static String getJdbcType(String type)
      {
          // Make sure the we are initialized.
          if (isInitialized == false)
          {
              initialize();
          }
          return (String) torqueTypeToJdbcTypeMap.get(type);
      }
  
      /**
       * Returns Torque type constant corresponding to JDBC type code.
       * Used but Torque JDBC task.
       */
      public static String getTorqueType(Integer sqlType)
      {
          // Make sure the we are initialized.
          if (isInitialized == false)
          {
              initialize();
          }
          return (String) jdbcToTorqueTypeMap.get(sqlType);
      }
  
      /**
       * Returns true if values for the type need to be quoted.
       *
       * @param type The type to check.
       */
      public static final boolean isTextType(String type)
      {
          for (int i = 0; i < TEXT_TYPES.length; i++)
          {
              if (type.equals(TEXT_TYPES[i]))
              {
                  return true;
              }
          }
  
          // If we get this far, there were no matches.
          return false;
      }
  }
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-create/oracle/createdb.vm
  
  Index: createdb.vm
  ===================================================================
  #foreach ($databaseName in $databaseNames)
  -- drop database $databaseName;
  -- create database $databaseName;
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/mysql/foreignkey.vm
  
  Index: foreignkey.vm
  ===================================================================
  #foreach ($fk in $table.ForeignKeys)
      FOREIGN KEY ($fk.LocalColumnNames) REFERENCES $fk.ForeignTableName ($fk.ForeignColumnNames),
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/mysql/unique.vm
  
  Index: unique.vm
  ===================================================================
  #foreach ($unique in $table.Unices)
      UNIQUE ($unique.ColumnList),
  #end
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/mysql/db.props
  
  Index: db.props
  ===================================================================
  # Taken from java.sql.Types in the IBM 1.3 JDK
  # JDBC to MySQL mappings.
  #
  # A good MySQL resource for determining these mappings is at
  # http://www.mysql.com/doc/C/o/Column_types.html
  
  BIT = BIT
  TINYINT = TINYINT
  SMALLINT = SMALLINT
  INTEGER = INTEGER
  BIGINT = BIGINT
  FLOAT = FLOAT
  REAL = REAL
  DOUBLE = DOUBLE
  NUMERIC = DECIMAL
  DECIMAL = DECIMAL
  CHAR = CHAR
  VARCHAR = VARCHAR
  LONGVARCHAR = MEDIUMTEXT
  DATE = DATETIME
  TIME = TIME
  TIMESTAMP = TIMESTAMP
  BINARY = BLOB
  VARBINARY = MEDIUMBLOB
  LONGVARBINARY = LONGBLOB
  NULL = NULL
  OTHER =
  JAVA_OBJECT =
  DISTINCT =
  STRUCT =
  ARRAY =
  BLOB = LONGBLOB
  CLOB = LONGTEXT
  REF =
  
  AUTOINCREMENT = AUTO_INCREMENT
  NOTNULL = NOT NULL
   
  removeNotNullWithAutoIncrement = false
  suppressDefaults = false
  maxColumnNameLength = 64
  
  
  # See mysql docs for valid table type names.
  # For example, if you wanted to use the transactional type InnoDB,
  # then specify "tableType = InnoDB"
  #tableType = MyISAM
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/mysql/index.vm
  
  Index: index.vm
  ===================================================================
  #foreach ($index in $table.Indices)
      INDEX $index.Name ($index.ColumnList),
  #end
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/mysql/primarykey.vm
  
  Index: primarykey.vm
  ===================================================================
  #if ($table.hasPrimaryKey())    
      PRIMARY KEY($table.printPrimaryKey()),
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/mysql/tablefk.vm
  
  Index: tablefk.vm
  ===================================================================
    
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/mysql/columns.vm
  
  Index: columns.vm
  ===================================================================
  #foreach ($col in $table.Columns)
      #set ( $type = $dbprops.get($col.Type) )
      #set ( $size = $col.printSize() )
      #set ( $default = $col.DefaultSetting )
      #set ( $nullString = $strings.select($col.isNotNull(), $dbprops.get("NOTNULL"),"") )
      #set ( $autoIncrement = $strings.select($col.isAutoIncrement(), $dbprops.get("AUTOINCREMENT"),"") )
      #set ( $entry = "$col.Name $type $size $default $nullString $autoIncrement," )
      $strings.sub($strings.collapseSpaces($entry)," ,",",")
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/mysql/drop.vm
  
  Index: drop.vm
  ===================================================================
  drop table if exists $table.Name;
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/mysql/table.vm
  
  Index: table.vm
  ===================================================================
  
  # -----------------------------------------------------------------------
  # $table.Name
  # -----------------------------------------------------------------------
  $generator.parse("$basepath/drop.vm", "", "table", $tbl)
  CREATE TABLE $table.Name
  (
  #set ( $cols = $generator.parse("$basepath/columns.vm", "", "table", $tbl) )
  #set ( $pk = $generator.parse("$basepath/primarykey.vm", "", "table", $tbl) )
  #set ( $fk = $generator.parse("$basepath/foreignkey.vm", "", "table", $tbl) )
  #set ( $unique = $generator.parse("$basepath/unique.vm", "", "table", $tbl) )
  #set ( $index = $generator.parse("$basepath/index.vm", "", "table", $tbl) )
  #if($strings.allEmpty([$pk,$fk,$unique,$index]))$strings.chop($cols,2)#else$cols#end
  #if($strings.allEmpty([$fk,$unique,$index]) && $pk.length()>0)$strings.chop($pk,2)#else$pk#end
  #if($strings.allEmpty([$unique,$index]) && $fk.length() >0)$strings.chop($fk,2)#else$fk#end
  #if($strings.allEmpty([$index]) && $unique.length()>0)$strings.chop($unique,2)#else$unique#end
  #if($index.length() > 0)$strings.chop($index,2)#end
  
  )#if($dbprops.get("tableType")) Type=$dbprops.get("tableType")#end;
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/oracle/primarykey.vm
  
  Index: primarykey.vm
  ===================================================================
  #set ($length = $table.Name.length())
  #if ($length > 27)#set ($length=27)#end
  #if ($table.hasPrimaryKey())
  ALTER TABLE $table.Name
      ADD CONSTRAINT ${table.Name.substring(0,$length)}_PK
  PRIMARY KEY ($table.printPrimaryKey());
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/oracle/table.vm
  
  Index: table.vm
  ===================================================================
  
  -----------------------------------------------------------------------------
  -- $table.Name
  -----------------------------------------------------------------------------
  $generator.parse("$basepath/drop.vm", "", "table", $tbl)
  CREATE TABLE $table.Name
  (
  #set ( $cols = $generator.parse("$basepath/columns.vm", "", "table", $tbl) )
  #set ( $unique = $generator.parse("$basepath/unique.vm", "", "table", $tbl) )
  #if($strings.allEmpty([$unique]))$strings.chop($cols,2)#else$cols#end
  #if($unique.length()>0)$strings.chop($unique,2)#end
  
  );
  
  #set ( $pk = $generator.parse("$basepath/primarykey.vm", "", "table", $tbl) )
  #if($pk.length()>0)$pk#end
  
  #set ( $index = $generator.parse("$basepath/index.vm", "", "table", $tbl) )
  #if($index.length() > 0)$index#end
  
  #set ( $sequence = $generator.parse("$basepath/sequence.vm", "", "table", $tbl) )
  #if ($sequence.length()>0)$sequence#end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/oracle/drop.vm
  
  Index: drop.vm
  ===================================================================
  DROP TABLE $table.Name CASCADE CONSTRAINTS;
  #if ($table.IdMethod == "native")
  DROP SEQUENCE $table.SequenceName;
  #end
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/oracle/db.props
  
  Index: db.props
  ===================================================================
  # Taken from java.sql.Types in the IBM 1.3 JDK
  # JDBC to Oracle mappings.
  #
  # Good Oracle resources for determining these mappings include:
  # http://technet.oracle.com/doc/oracle8i_816/java.816/a81354/basic3.htm
  # http://technet.oracle.com/docs/tech/migration/workbench/doc_library/MSAccess/ch3.htm
  
  BIT = NUMBER (1, 0)
  TINYINT = NUMBER (3, 0)
  SMALLINT = NUMBER (5, 0)
  INTEGER = NUMBER
  BIGINT = NUMBER (20, 0)
  FLOAT = FLOAT
  REAL = NUMBER
  DOUBLE = FLOAT
  NUMERIC = NUMBER
  DECIMAL = NUMBER
  CHAR = CHAR
  VARCHAR = VARCHAR2
  LONGVARCHAR = VARCHAR2 (2000)
  DATE = DATE
  TIME = DATE
  TIMESTAMP = DATE
  BINARY = LONG RAW
  VARBINARY = BLOB
  LONGVARBINARY = LONG RAW
  NULL =
  OTHER =
  JAVA_OBJECT =
  DISTINCT =
  STRUCT =
  ARRAY =
  BLOB = BLOB
  CLOB = CLOB
  REF =
  
  NOTNULL = NOT NULL
  
  primaryKeyInsideTableDirective = true
  foreignKeyInsideTableDirective = true
  indexInsideTableDirective = false
  
  removeNotNullWithAutoIncrement = false
  
  suppressDefaults = false
  
  maxColumnNameLength = 30
  
  idMethod=sequence
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/oracle/index.vm
  
  Index: index.vm
  ===================================================================
  #foreach ($index in $table.Indices)
  CREATE#if ($index.Unique)UNIQUE#end INDEX $index.Name ON $table.Name ($index.ColumnList);
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/oracle/tablefk.vm
  
  Index: tablefk.vm
  ===================================================================
  #set ( $fk = $generator.parse("$basepath/foreignkey.vm", "", "table", $tbl) )
  #if ($fk.length()>0)$fk#end
  
  
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/oracle/foreignkey.vm
  
  Index: foreignkey.vm
  ===================================================================
  #foreach ($fk in $table.ForeignKeys)
  ALTER TABLE $table.Name
      ADD CONSTRAINT $fk.Name FOREIGN KEY ($fk.LocalColumnNames)
      REFERENCES $fk.ForeignTableName ($fk.ForeignColumnNames)
  ;
  
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/oracle/columns.vm
  
  Index: columns.vm
  ===================================================================
  #foreach ($col in $table.Columns)
      #set ( $type = $dbprops.get($col.Type) )
      #set ( $size = $col.printSize() )
      #set ( $default = $col.DefaultSetting )
      #set ( $nullString = $strings.select($col.isNotNull(), $dbprops.get("NOTNULL"),"") )
      #set ( $entry = "$col.Name $type $size $default $nullString," )
      $strings.sub($strings.collapseSpaces($entry)," ,",",")
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/oracle/unique.vm
  
  Index: unique.vm
  ===================================================================
  #foreach ($unique in $table.Unices)
      CONSTRAINT $unique.Name UNIQUE ($unique.ColumnList),
  #end
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/oracle/sequence.vm
  
  Index: sequence.vm
  ===================================================================
  #if ($table.IdMethod == "native")
  CREATE SEQUENCE $table.SequenceName INCREMENT BY 1 START WITH 1 NOMAXVALUE NOCYCLE NOCACHE ORDER;
  #end
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/interbase/primarykey.vm
  
  Index: primarykey.vm
  ===================================================================
      PRIMARY KEY($table.printPrimaryKey()),
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/interbase/drop.vm
  
  Index: drop.vm
  ===================================================================
  drop table if exists $table.Name;
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/interbase/db.props
  
  Index: db.props
  ===================================================================
  # Taken from java.sql.Types in the IBM 1.3 JDK
  # JDBC to Interbase mappings.
  
  BIT =
  TINYINT =
  SMALLINT =
  INTEGER = INTEGER
  BIGINT =
  FLOAT =
  REAL =
  DOUBLE =
  NUMERIC =
  DECIMAL =
  CHAR = VARCHAR
  VARCHAR = VARCHAR
  LONGVARCHAR = VARCHAR
  DATE =
  TIME =
  TIMESTAMP = timestamp
  BINARY =
  VARBINARY = BLOB
  LONGVARBINARY =
  NULL =
  OTHER =
  JAVA_OBJECT =
  DISTINCT =
  STRUCT =
  ARRAY =
  BLOB =
  CLOB =
  REF =
  
  AUTOINCREMENT = IDENTITY
  NOTNULL = NOT NULL
  
  primaryKeyInsideTableDirective = true
  indexInsideTableDirective = false
  
  removeNotNullWithAutoIncrement = false
  
  suppressDefaults = true
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/interbase/unique.vm
  
  Index: unique.vm
  ===================================================================
  #foreach ($unique in $table.Unices)
      UNIQUE ($unique.ColumnList),
  #end
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/interbase/index.vm
  
  Index: index.vm
  ===================================================================
  #foreach ($index in $table.Indices)
  CREATE #if($index.Unique)UNIQUE#end INDEX $index.Name ON $table.Name ($index.ColumnList);
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/interbase/foreignkey.vm
  
  Index: foreignkey.vm
  ===================================================================
  #foreach ($fk in $table.ForeignKeys)
      FOREIGN KEY ($fk.LocalColumnNames) REFERENCES $fk.ForeignTableName ($fk.ForeignColumnNames),
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/interbase/tablefk.vm
  
  	<<Binary file>>
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/interbase/columns.vm
  
  Index: columns.vm
  ===================================================================
  #foreach ($col in $table.Columns)
      #set ( $type = $dbprops.get($col.Type) )
      #set ( $size = $col.printSize() )
      #set ( $default = $col.DefaultSetting )
      #set ( $nullString = $strings.select($col.isNotNull(), $dbprops.get("NOTNULL"),"") )
      #set ( $autoIncrement = $strings.select($col.isAutoIncrement(), $dbprops.get("AUTOINCREMENT"),"") )
      #set ( $colName = $strings.concat(['"',$col.Name,'"']) )
      #set ( $entry = "$colName $type $size $default $nullString $autoIncrement," )
      $strings.sub($strings.collapseSpaces($entry)," ,",",")
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/interbase/table.vm
  
  Index: table.vm
  ===================================================================
  
  /* --------------------------------------------------------------------------
  $table.Name
  -------------------------------------------------------------------------- */
  ##$generator.parse("$basepath/drop.vm", "", "table", $tbl)
  CREATE TABLE $table.Name
  (
  #set ( $cols = $generator.parse("$basepath/columns.vm", "", "table", $tbl) )
  #set ( $pk = $generator.parse("$basepath/primarykey.vm", "", "table", $tbl) )
  ##set ( $fk = $generator.parse("$basepath/foreignkey.vm", "", "table", $tbl) )
  #set ( $unique = $generator.parse("$basepath/unique.vm", "", "table", $tbl) )
  #set ( $index = $generator.parse("$basepath/index.vm", "", "table", $tbl) )
  #if($strings.allEmpty([$pk,$unique]))$strings.chop($cols,1)#else$cols#end
  #if($strings.allEmpty([$unique]) && $pk.length()>0)$strings.chop($pk,2)#else$pk#end
  ##if($strings.allEmpty([$unique,$index]) && $fk.length() >0)$strings.chop($fk,2)#else$fk#end
  #if($unique.length()>0)$strings.chop($unique,2)#else$unique#end
  
  );
  
  #if($index.length() > 0)$strings.chop($index,1)#end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/java/org/apache/commons/sql/datamodel/Reference.java
  
  Index: Reference.java
  ===================================================================
  package org.apache.commons.sql.datamodel;
  
  public class Reference 
  {
      private String local;
      private String foreign;
      
      public Reference() {}
      
      public String getLocal()
      {
          return local;
      }
      
      public void setLocal(String local)
      {
          this.local = local;
      }
      
      public String getForeign()
      {
          return foreign;
      }
      
      public void setForeign(String foreign)
      {
          this.foreign = foreign;
      }
  }
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/java/org/apache/commons/sql/datamodel/Table.java
  
  Index: Table.java
  ===================================================================
  package org.apache.commons.sql.datamodel;
  
  import java.util.Iterator;
  import java.util.ArrayList;
  import java.util.List;
  
  public class Table 
  {
      private String name;
      
      private List columns = new ArrayList();
      
      private List foreignKeys = new ArrayList();
      
      public Table() 
      {
      }
      
      public String getName() 
      {
          return name;
      }
      
      public void setName(String name)
      {
          this.name=name;
      }
      
      public void addColumn(Column column)
      {
          columns.add(column);
      }
      
      public List getColumns()
      {
          return columns;
      }
      
      public void addForeignKey(ForeignKey foreignKey)
      {
          foreignKeys.add(foreignKey);
      }
      
      public List getForeignKeys()
      {
          return foreignKeys;
      }
  
      public Column getColumn(int index)
      {
          return (Column) columns.get(index);
      }        
  
      public ForeignKey getForeignKey(int index)
      {
          return (ForeignKey) foreignKeys.get(index);
      }        
      
      
      // Helper methods
      
      /**
       * @return true if there is at least one primary key column
       *  on this table
       */
      public boolean hasPrimaryKey() 
      {
          for (Iterator iter = getColumns().iterator(); iter.hasNext(); ) 
          {
              Column column = (Column) iter.next();
              if ( column.isPrimaryKey() )
              {
                  return true;
              }
          }
          return false;
      }
  }
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/java/org/apache/commons/sql/datamodel/ForeignKey.java
  
  Index: ForeignKey.java
  ===================================================================
  package org.apache.commons.sql.datamodel;
  
  import java.util.Iterator;
  import java.util.ArrayList;
  import java.util.List;
  
  public class ForeignKey 
  {
      private String foreignTable;
          
      private List references = new ArrayList();
      
      public ForeignKey() {}
      
      public String getForeignTable()
      {
          return foreignTable;
      }
      
      public void setForeignTable(String foreignTable)
      {
          this.foreignTable= foreignTable;
      }
      
      public void addReference(Reference reference)
      {
          references.add(reference);
      }
      
      public List getReferences()
      {
          return references;
      }
  }
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/java/org/apache/commons/sql/datamodel/Column.java
  
  Index: Column.java
  ===================================================================
  package org.apache.commons.sql.datamodel;
  
  import java.util.Iterator;
  import java.util.ArrayList;
  import java.util.List;
  
  public class Column 
  {
      private String name;
      private boolean primaryKey = false;
      private boolean required = false;
      private String type;
      private int size = 0;
      
      public Column () {}
      
      public String getName()
      {
          return name;
      }
      
      public void setName(String name)
      {
          this.name = name;
      }
      
      public boolean isPrimaryKey()
      {
          return primaryKey;
      }
      
      public void setPrimaryKey(boolean primaryKey)
      {
          this.primaryKey = primaryKey;
      }	
      
      public boolean isRequired()
      {
          return required;
      }
  
      public void setRequired(boolean required)
      {
          this.required = required;
      }
      
      public String getType()
      {
          return type;
      }
      
      public void setType(String type)
      {
          this.type = type;
      }
      
      public int getSize()
      {
          return size;
      }
  
      public void setSize(int size)
      {
          this.size=size;
      }
  }
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/java/org/apache/commons/sql/datamodel/Database.java
  
  Index: Database.java
  ===================================================================
  package org.apache.commons.sql.datamodel;
  
  import java.util.Iterator;
  import java.util.ArrayList;
  import java.util.List;
  
  public class Database 
  {
      private String name;
      
      private String idMethod;
      
      private List tables = new ArrayList();
      
      public Database()
      {
      }
      
      public String getName()
      {
          return name;
      }
      
      public void setName(String name)
      {
          this.name=name;
      }
      
      public void setIdMethod(String idMethod)
      {
          this.idMethod=idMethod;
      }
          
          
      public void addTable(Table table)
      {
          tables.add(table);
      }	
  
      public List getTables()
      {
          return tables;
      }
  
      // Additions for PropertyUtils
      
      public void setTable(int index, Table table)
      {
          addTable(table);
      }        
  
      public Table getTable(int index)
      {
          return (Table) tables.get(index);
      }
      
      
      public String toString() 
      {
          return super.toString() + "[name=" + name + ";tableCount=" + tables.size() + "]";
      }
  }
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/hypersonic/index.vm
  
  Index: index.vm
  ===================================================================
  #foreach ($index in $table.Indices)
  CREATE #if($index.Unique)UNIQUE#end INDEX $index.Name ON $table.Name ($index.ColumnList);
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/hypersonic/foreignkey.vm
  
  Index: foreignkey.vm
  ===================================================================
  #foreach ($fk in $table.ForeignKeys)
      FOREIGN KEY ($fk.LocalColumnNames) REFERENCES $fk.ForeignTableName ($fk.ForeignColumnNames),
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/hypersonic/unique.vm
  
  Index: unique.vm
  ===================================================================
  #foreach ($unique in $table.Unices)
      UNIQUE ($unique.ColumnList),
  #end
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/hypersonic/table.vm
  
  Index: table.vm
  ===================================================================
  
  -----------------------------------------------------------------------------
  -- $table.Name
  -----------------------------------------------------------------------------
  ##$generator.parse("$basepath/drop.vm", "", "table", $tbl)
  CREATE TABLE $table.Name
  (
  #set ( $cols = $generator.parse("$basepath/columns.vm", "", "table", $tbl) )
  #set ( $pk = $generator.parse("$basepath/primarykey.vm", "", "table", $tbl) )
  ##set ( $fk = $generator.parse("$basepath/foreignkey.vm", "", "table", $tbl) )
  #set ( $unique = $generator.parse("$basepath/unique.vm", "", "table", $tbl) )
  #set ( $index = $generator.parse("$basepath/index.vm", "", "table", $tbl) )
  #if($strings.allEmpty([$pk,$fk,$unique,$index]))$strings.chop($cols,2)#else$cols#end
  #if($strings.allEmpty([$fk,$unique,$index]) && $pk.length()>0)$strings.chop($pk,2)#else$pk#end
  ##if($strings.allEmpty([$unique,$index]) && $fk.length() >0)$strings.chop($fk,2)#else$fk#end
  #if($unique.length()>0)$strings.chop($unique,2)#else$unique#end
  
  );
  
  #if($index.length() > 0)$strings.chop($index,1)#end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/hypersonic/drop.vm
  
  Index: drop.vm
  ===================================================================
  drop table if exists $table.Name;
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/hypersonic/tablefk.vm
  
  	<<Binary file>>
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/hypersonic/columns.vm
  
  Index: columns.vm
  ===================================================================
  #foreach ($col in $table.Columns)
      #set ( $type = $dbprops.get($col.Type) )
      #set ( $size = $col.printSize() )
      #set ( $default = $col.DefaultSetting )
      #set ( $nullString = $strings.select($col.isNotNull(), $dbprops.get("NOTNULL"),"") )
      #set ( $autoIncrement = $strings.select($col.isAutoIncrement(), $dbprops.get("AUTOINCREMENT"),"") )
      #set ( $entry = "$col.Name $type $size $autoIncrement," )
      $strings.sub($strings.collapseSpaces($entry)," ,",",")
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/hypersonic/primarykey.vm
  
  Index: primarykey.vm
  ===================================================================
  #if ($table.hasPrimaryKey())    
      PRIMARY KEY($table.printPrimaryKey()),
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/hypersonic/db.props
  
  Index: db.props
  ===================================================================
  # Taken from java.sql.Types in the IBM 1.3 JDK
  # JDBC to Hypersonic mappings.
  
  BIT =
  TINYINT =
  SMALLINT =
  INTEGER = integer
  BIGINT =
  FLOAT =
  REAL =
  DOUBLE =
  NUMERIC =
  DECIMAL =
  CHAR = VARCHAR
  VARCHAR = VARCHAR
  LONGVARCHAR = VARCHAR
  DATE = date
  TIME = time
  TIMESTAMP = timestamp
  BINARY =
  VARBINARY = BINARY
  LONGVARBINARY =
  NULL =
  OTHER =
  JAVA_OBJECT =
  DISTINCT =
  STRUCT =
  ARRAY =
  BLOB =
  CLOB =
  REF =
  
  AUTOINCREMENT = IDENTITY
  NOTNULL = NOT NULL
  
  primaryKeyInsideTableDirective = true
  indexInsideTableDirective = false
  
  removeNotNullWithAutoIncrement = false
  
  suppressDefaults = true
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/db2400/index.vm
  
  Index: index.vm
  ===================================================================
  #foreach ($index in $table.Indices)
  CREATE #if($index.IsUnique)UNIQUE#end INDEX $index.Name ON $table.Name ($index.IndexColumnList);
  #end
  
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/db2400/sequence.vm
  
  Index: sequence.vm
  ===================================================================
  #if ($table.IdMethod == "sequence")
  CREATE SEQUENCE $table.SequenceName;
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/db2400/foreignkey.vm
  
  Index: foreignkey.vm
  ===================================================================
  #foreach ($fk in $table.ForeignKeys)
  ALTER TABLE $table.Name
      ADD CONSTRAINT ${table.Name}_FK_${velocityCount} FOREIGN KEY ($fk.LocalColumnNames)
      REFERENCES $fk.ForeignTableName ($fk.ForeignColumnNames);
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/db2400/unique.vm
  
  Index: unique.vm
  ===================================================================
  #foreach ($unique in $table.Unices)
      UNIQUE ($unique.ColumnList),
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/db2400/table.vm
  
  Index: table.vm
  ===================================================================
  
  -----------------------------------------------------------------------------
  -- $table.Name
  -----------------------------------------------------------------------------
  $generator.parse("$basepath/drop.vm", "", "table", $tbl)
  CREATE TABLE $table.Name
  (
  #set ( $cols = $generator.parse("$basepath/columns.vm", "", "table", $tbl) )
  #set ( $unique = $generator.parse("$basepath/unique.vm", "", "table", $tbl) )
  #if($strings.allEmpty([$unique]))$strings.chop($cols,2)#else$cols#end
  #if($unique.length()>0)$strings.chop($unique,2)#end
  
  );
  
  #set ( $pk = $generator.parse("$basepath/primarykey.vm", "", "table", $tbl) )
  #if($pk.length()>0)$pk#end
  
  #set ( $fk = $generator.parse("$basepath/foreignkey.vm", "", "table", $tbl) )
  #if ($fk.length()>0)$fk#end
  
  #set ( $index = $generator.parse("$basepath/index.vm", "", "table", $tbl) )
  #if($index.length() > 0)$index#end
  
  ##set $sequence = $generator.parse("$basepath/sequence.vm", "", "table", $tbl)
  ##if ($sequence.length()>0)$sequence#end
  
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/db2400/drop.vm
  
  Index: drop.vm
  ===================================================================
  drop table $table.Name;
  #*
  
  DB2 looks like oracle but I'm not sure
  about the sequences.
  
  #foreach ($col in $table.Columns)
  #if ($col.isAutoIncrement())
  drop sequence if exists ${table.Name}_SEQ;
  #end
  #end
  *#
  
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/db2400/tablefk.vm
  
  	<<Binary file>>
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/db2400/columns.vm
  
  Index: columns.vm
  ===================================================================
  #foreach ($col in $table.Columns)
      #set ( $type = $dbprops.get($col.Type) )
      #set ( $size = $col.printSize() )
      #set ( $default = $col.DefaultSetting )
      #set ( $autoIncrement = $strings.select($col.isAutoIncrement(), $dbprops.get("AUTOINCREMENT"),"") )
      #set ( $nullString = $strings.select($col.isNotNull(), $dbprops.get("NOTNULL"),"") )
      #set ( $entry = "$col.Name $type $size $default $nullString $autoIncrement," )
      $strings.sub($strings.collapseSpaces($entry)," ,",",")
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/db2400/primarykey.vm
  
  Index: primarykey.vm
  ===================================================================
  ALTER TABLE $table.Name
      ADD CONSTRAINT ${table.Name}_PK 
  PRIMARY KEY ($table.printPrimaryKey());
  
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/db2400/db.props
  
  Index: db.props
  ===================================================================
  # Taken from java.sql.Types in the IBM 1.3 JDK
  # JDBC to DB2/400 mappings.
  
  BIT = 
  TINYINT = SMALLINT 
  SMALLINT = SMALLINT 
  INTEGER = INT
  BIGINT = BIGINT 
  FLOAT = FLOAT
  REAL = REAL 
  DOUBLE = DOUBLE PRECISION
  NUMERIC = NUMERIC
  DECIMAL = DEC
  CHAR = VARCHAR
  VARCHAR = VARCHAR
  LONGVARCHAR = LONG VARCHAR
  DATE = DATE
  TIME = TIME
  TIMESTAMP = TIMESTAMP
  BINARY =
  VARBINARY = VARCHAR (32000) FOR BIT DATA
  LONGVARBINARY =LONG VARCHAR FOR BIT DATA
  NULL =
  OTHER =
  JAVA_OBJECT =
  DISTINCT =
  STRUCT =
  ARRAY =
  BLOB =
  CLOB =
  REF =
  
  AUTOINCREMENT = 
  NOTNULL = NOT NULL
  
  removeNotNullWithAutoIncrement = true
  maxColumnNameLength = 30
  suppressDefaults = false
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/mssql/primarykey.vm
  
  Index: primarykey.vm
  ===================================================================
      CONSTRAINT ${table.Name}_PK PRIMARY KEY($table.printPrimaryKey()),
  
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/mssql/db.props
  
  Index: db.props
  ===================================================================
  BIT = BIT
  TINYINT = TINYINT
  SMALLINT = SMALLINT
  INTEGER = INT
  BIGINT = BIGINT
  FLOAT = FLOAT
  REAL = REAL
  DOUBLE = FLOAT
  NUMERIC = NUMERIC
  DECIMAL = DECIMAL
  CHAR = VARCHAR
  VARCHAR = VARCHAR
  LONGVARCHAR = TEXT
  DATE = DATETIME
  TIME = DATETIME
  TIMESTAMP = DATETIME
  BINARY = BINARY
  VARBINARY = IMAGE
  LONGVARBINARY = IMAGE
  NULL = NULL
  OTHER =
  JAVA_OBJECT =
  DISTINCT =
  STRUCT =
  ARRAY =
  BLOB =
  CLOB =
  REF =
  
  AUTOINCREMENT = IDENTITY (1,1)
  NOTNULL = NOT NULL
  
  removeNotNullWithAutoIncrement = false
  
  suppressDefaults = false
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/mssql/index.vm
  
  Index: index.vm
  ===================================================================
  #foreach ($index in $table.Indices)
  CREATE #if($index.Unique)UNIQUE#end INDEX $index.Name ON $table.Name ($index.ColumnList);
  #end
  
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/mssql/foreignkey.vm
  
  Index: foreignkey.vm
  ===================================================================
  #foreach ($fk in $table.ForeignKeys)
  BEGIN
  ALTER TABLE $table.Name
      ADD CONSTRAINT $fk.Name FOREIGN KEY ($fk.LocalColumnNames)
      REFERENCES $fk.ForeignTableName ($fk.ForeignColumnNames)
  END    
  ;
  
  #end
  
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/mssql/table.vm
  
  Index: table.vm
  ===================================================================
  
  /* ---------------------------------------------------------------------- */
  /* $table.Name                                                      */
  /* ---------------------------------------------------------------------- */
  
  $generator.parse("$basepath/drop.vm", "", "table", $tbl)
  CREATE TABLE $table.Name
  (
  #set ( $cols = $generator.parse("$basepath/columns.vm", "", "table", $tbl) )
  #set ( $pk = $generator.parse("$basepath/primarykey.vm", "", "table", $tbl) )
  #set ( $unique = $generator.parse("$basepath/unique.vm", "", "table", $tbl) )
  #if($strings.allEmpty([$pk,$unique]))$strings.chop($cols,1)#else$cols#end
  #if($strings.allEmpty([$unique]) && $pk.length()>0)$strings.chop($pk,2)#else$pk#end
  #if($unique.length()>0)$strings.chop($unique,2)#end
  );
  
  #set ( $index = $generator.parse("$basepath/index.vm", "", "table", $tbl) )
  #if($index.length() > 0)$index#end
  
  
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/mssql/unique.vm
  
  Index: unique.vm
  ===================================================================
  #foreach ($unique in $table.Unices)
      UNIQUE ($unique.ColumnList),
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/mssql/drop.vm
  
  Index: drop.vm
  ===================================================================
  #foreach ($fk in $table.ForeignKeys)
  IF EXISTS (SELECT 1 FROM sysobjects WHERE type ='RI' AND name='$fk.Name')
      ALTER TABLE $table.Name DROP CONSTRAINT $fk.Name;
  #end
  IF EXISTS (SELECT 1 FROM sysobjects WHERE type = 'U' AND name = '$table.Name')
  BEGIN
       DECLARE @reftable nvarchar(60), @constraintname nvarchar(60)
       DECLARE refcursor CURSOR FOR
       select reftables.name tablename, cons.name constraitname
        from sysobjects tables,
             sysobjects reftables,
             sysobjects cons,
             sysreferences ref
         where tables.id = ref.rkeyid
           and cons.id = ref.constid
           and reftables.id = ref.fkeyid
           and tables.name = '$table.Name'
       OPEN refcursor
       FETCH NEXT from refcursor into @reftable, @constraintname
       while @@FETCH_STATUS = 0
       BEGIN
         exec ('alter table '+@reftable+' drop constraint '+@constraintname)
         FETCH NEXT from refcursor into @reftable, @constraintname
       END
       CLOSE refcursor
       DEALLOCATE refcursor
       DROP TABLE $table.Name
  END
  
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/mssql/tablefk.vm
  
  Index: tablefk.vm
  ===================================================================
  
  /* ---------------------------------------------------------------------- */
  /* $table.Name                                                      */
  /* ---------------------------------------------------------------------- */
  
  #set ( $fk = $generator.parse("$basepath/foreignkey.vm", "", "table", $tbl) )
  #if($fk.length() >0)$fk#end
  
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/mssql/columns.vm
  
  Index: columns.vm
  ===================================================================
  #foreach ($col in $table.Columns)
      #set ( $type = $dbprops.get($col.Type) )
      #set ( $size = $col.printSize() )
      #set ( $default = $col.DefaultSetting )
      #set ( $nullString = $strings.select($col.isNotNull(), $dbprops.get("NOTNULL"),$dbprops.get("NULL")) )
      #set ( $autoIncrement = $strings.select($col.isAutoIncrement(), $dbprops.get("AUTOINCREMENT"),"") )
      #set ( $entry = "$col.Name $type $size $default $nullString $autoIncrement," )
      $strings.sub($strings.collapseSpaces($entry)," ,",",")
  #end
  
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-load/oracle/val.vm
  
  Index: val.vm
  ===================================================================
  #if($column.Column.TorqueType=="VARCHAR" || $column.Column.TorqueType=="LONGVARCHAR")'$column.Value'#else$column.Value#end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-load/oracle/row.vm
  
  Index: row.vm
  ===================================================================
  INSERT INTO $row.Table.Name (##
  #set ($comma="")#foreach($col in $row.ColumnValues)$comma${col.Column.Name}#set($comma=",")#end)
      VALUES (#set ($comma="")#foreach($col in $row.ColumnValues)$comma${generator.parse("sql/load/oracle/val.vm", "", "column", $col)}#set ($comma=",")#end);
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-load/hypersonic/val.vm
  
  Index: val.vm
  ===================================================================
  #if($column.Column.TorqueType=="VARCHAR" || $column.Column.TorqueType=="LONGVARCHAR")'$column.Value'#else$column.Value#end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-load/hypersonic/row.vm
  
  Index: row.vm
  ===================================================================
  INSERT INTO $row.Table.Name (##
  #set ($comma="")#foreach($col in $row.ColumnValues)$comma${col.Column.Name}#set($comma=",")#end)
      VALUES (#set ($comma="")#foreach($col in $row.ColumnValues)$comma${generator.parse("sql/load/hypersonic/val.vm", "", "column", $col)}#set ($comma=",")#end);
      
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-load/db2400/val.vm
  
  Index: val.vm
  ===================================================================
  #if($column.Column.TorqueType=="VARCHAR" || $column.Column.TorqueType=="LONGVARCHAR" )'$column.Value'#else$column.Value#end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-load/db2400/row.vm
  
  Index: row.vm
  ===================================================================
  INSERT INTO $row.Table.Name (##
  #set ($comma="")#foreach($col in $row.ColumnValues)$comma${col.Column.Name}#set($comma=",")#end)
      VALUES (#set ($comma="")#foreach($col in $row.ColumnValues)$comma${generator.parse("sql/load/mysql/val.vm", "", "column", $col)}#set ($comma=",")#end);
  
  
  
  1.1                  jakarta-commons-sandbox/sql/maven.xml
  
  Index: maven.xml
  ===================================================================
  <project default="java:jar" xmlns:j="jelly:core">
  
    <goal name="jelly-task" prereqs="java:compile, test:compile">
  	<path id="test.classpath">
  	    <pathelement path="${maven.build.dest}"/>
  	    <pathelement path="target/classes"/>
  	    <pathelement path="target/test-classes"/>
  	    <path refid="maven.dependency.classpath"/>
  	</path>
    </goal>
  
    <goal name="sql:generate-sql" prereqs="jelly-task" 
  	description="Generates the SQL DDL for creating and dropping the database">
  
  <!--
  	if we could set the threads context class loader to ${test.classpath} 
  	then this could work...
  	
  	<j:include uri="src/jelly/createSql.jelly"/>
  -->	
  
      <java classname="org.apache.commons.jelly.Jelly" fork="yes">
        <classpath refid="test.classpath"/>
  	  <arg value="src/jelly/createSql.jelly"/> 
      </java>
    </goal>
    
    <goal name="sql:create-db" prereqs="sql:generate-sql" 
  	description="Runs the SQL to create a new database, dropping the previous tables">
  
      <java classname="org.apache.commons.jelly.Jelly" fork="yes">
        <classpath refid="test.classpath"/>
  	  <arg value="src/jelly/createDb.jelly"/> 
      </java>
    </goal>
    
    
  </project>
  
  
  
  1.1                  jakarta-commons-sandbox/sql/build.xml
  
  Index: build.xml
  ===================================================================
  <?xml version="1.0"?>
  
  <project name="maven" default="maven:jar" basedir=".">
  
    <!-- Give user a chance to override without editing this file
         (and without typing -D each time they invoke a target) -->
  
    <!-- Allow any user specific values to override the defaults -->
    <property file="${user.home}/build.properties" />
    <!-- Allow user defaults for this project -->
    <property file="build.properties" />
    <!-- Set default values for the build -->
    <property file="project.properties" />
  
    <!-- maven:start -->
    
    <!-- ================================================================== -->
    <!-- D E L E G A T O R S                                                -->
    <!-- ================================================================== -->
          
      <target name="maven:site">
        <ant antfile="${maven.home}/build-docs.xml" target="site"/>
      </target>
  
      <target name="maven:fo">
        <ant antfile="${maven.home}/build-docs.xml" target="docs:fo"/>
      </target>
  
      <target name="maven:pdf">
        <ant antfile="${maven.home}/build-docs.xml" target="docs:pdf"/>
      </target>
          
      <target name="maven:jar">
        <ant antfile="${maven.home}/build-maven.xml" target="jar"/>
      </target>
          
      <target name="maven:install-jar">
        <ant antfile="${maven.home}/build-maven.xml" target="install-jar"/>
      </target>
          
      <target name="maven:env">
        <ant antfile="${maven.home}/build-maven.xml" target="env"/>
      </target>
          
      <target name="maven:docs">
        <ant antfile="${maven.home}/build-docs.xml" target="docs"/>
      </target>
          
      <target name="maven:test">
        <ant antfile="${maven.home}/build-test.xml" target="test"/>
      </target>
  
      <target name="maven:iutest">
        <ant antfile="${maven.home}/build-iutest.xml" target="test"/>
      </target>
  
      <target name="maven:singletest">
        <ant antfile="${maven.home}/build-test.xml" target="run-singletest"/>
      </target>
          
      <target name="maven:clean">
        <ant antfile="${maven.home}/build-maven.xml" target="clean"/>
      </target>
          
      <target name="maven:metrics">
        <ant antfile="${maven.home}/build-metrics.xml" target="metrics"/>
      </target>
          
      <target name="maven:dist">
        <ant antfile="${maven.home}/build-maven.xml" target="dist"/>
      </target>
          
      <target name="maven:deploy-site">
        <ant antfile="${maven.home}/build-docs.xml" target="deploy-site"/>
      </target>
  
      <target name="maven:deploy-dist">
        <ant antfile="${maven.home}/build-maven.xml" target="deploy-dist"/>
      </target>
          
      <target name="maven:gump-descriptor">
        <ant antfile="${maven.home}/build-maven.xml" target="gump-descriptor"/>
      </target>
  
      <target name="maven:cross-ref">
        <ant antfile="${maven.home}/build-docs.xml" target="cross-ref"/>
      </target>
      
      <target name="maven:cvs-change-log">
        <ant antfile="${maven.home}/build-docs.xml" target="cvs-change-log"/>
      </target>
          
      <target name="maven:javadocs">
        <ant antfile="${maven.home}/build-docs.xml" target="javadocs"/>
      </target>
          
      <target name="maven:compile">
        <ant antfile="${maven.home}/build-maven.xml" target="compile"/>
      </target>
      
      <target name="maven:check-source">
        <ant antfile="${maven.home}/build-maven.xml" target="check-source"/>
      </target>
          
      <target name="maven:update-jars">
        <ant antfile="${maven.home}/build-maven.xml" target="update-jars"/>
      </target>
  
      <target name="maven:announce">
        <ant antfile="${maven.home}/build-maven.xml" target="announce"/>
      </target>
  
      <target name="maven:maven-update">
        <ant antfile="${maven.home}/build-maven.xml" target="maven-update"/>
      </target>
  
      <target name="maven:validate-pom">
        <ant antfile="${maven.home}/build-maven.xml" target="validate-pom"/>
      </target>
  
    <!-- maven:end -->
  
  </project>
  
  
  
  1.1                  jakarta-commons-sandbox/sql/project.properties
  
  Index: project.properties
  ===================================================================
  # -------------------------------------------------------------------
  # B U I L D  P R O P E R T I E S
  # -------------------------------------------------------------------
  # These properties are used by the maven Torque build, you may override
  # any of these default values by placing property values in
  # your build.properties file.
  # -------------------------------------------------------------------
  
  jarResources.basedir = src/java
  
  compile.debug = on
  compile.optimize = off
  compile.deprecation = off
  
  
  
  1.1                  jakarta-commons-sandbox/sql/project.xml
  
  Index: project.xml
  ===================================================================
  <?xml version="1.0"?>
  <project>
    
    <version>3</version>
    <name>commons-sql</name>
    <id>commons-sql</id>
    <currentVersion>1.0-dev</currentVersion>
    <organization>Apache Software Foundation</organization>
    <inceptionYear>2002</inceptionYear>
    <package>org.apache.commons.sql</package>
  
    <shortDescription>Project Management Tools</shortDescription>
  
    <!-- Gump integration -->
    <gumpRepositoryId>jakarta</gumpRepositoryId>
  
    <description>
      The Commons SQL package is a set of tools for dealing with various
      databases.
    </description>
  
    <url>http://jakarta.apache.org/commons/sql/</url>
    <cvsWebUrl>http://cvs.apache.org/viewcvs/jakarta-turbine-maven/</cvsWebUrl>
    <issueTrackingUrl>http://nagoya.apache.org:8080/scarab/servlet/scarab/</issueTrackingUrl>
    <siteAddress>jakarta.apache.org</siteAddress>
    <siteDirectory>/www/jakarta.apache.org/turbine/maven/</siteDirectory>
    <distributionDirectory>/www/jakarta.apache.org/builds/jakarta-turbine-maven/</distributionDirectory>
  
    <mailingLists>
      <mailingList>
        <name>Maven User List</name>
        <subscribe>turbine-maven-user-subscribe@jakarta.apache.org</subscribe>
        <unsubscribe>turbine-maven-user-unsubscribe@jakarta.apache.org</unsubscribe>
        <archive>http://nagoya.apache.org:8080/eyebrowse/SummarizeList?listName=turbine-maven-user@jakarta.apache.org</archive>
      </mailingList>
      <mailingList>
        <name>Maven Developer List</name>
        <subscribe>turbine-maven-dev-subscribe@jakarta.apache.org</subscribe>
        <unsubscribe>turbine-maven-dev-unsubscribe@jakarta.apache.org</unsubscribe>
        <archive>http://nagoya.apache.org:8080/eyebrowse/SummarizeList?listName=turbine-maven-dev@jakarta.apache.org</archive>
      </mailingList>
    </mailingLists>
  
    <developers>
  
      <developer>
        <name>Daniel Rall</name>
        <id>dlr</id>
        <email>dlr@finemaltcoding.com</email>
        <organization>CollabNet, Inc.</organization>
      </developer>
  
      <developer>
        <name>Jason van Zyl</name>
        <id>jvanzyl</id>
        <email>jason@zenplex.com</email>
        <organization>Zenplex</organization>
      </developer>
  
      <developer>
        <name>James Strachan</name>
        <id>jstrachan</id>
        <email>jstrachan@apache.org</email>
        <organization>SpiritSoft, Inc.</organization>
      </developer>
  
    </developers>
  
  
    <!-- Need to mark these as compile-time/run-time -->
  
    <dependencies>
  
      <dependency>
        <id>commons-betwixt</id>
        <version>SNAPSHOT</version>
      </dependency>
  
      <dependency>
        <id>velocity</id>
        <version>SNAPSHOT</version>
      </dependency>
  
      <dependency>
        <id>village</id>
        <version>1.5.3</version>
      </dependency>
      
      <!-- indirect -->
  
      <dependency>
        <id>commons-logging</id>
        <version>1.0</version>
      </dependency>
  
      <dependency>
        <id>commons-beanutils</id>
        <version>1.4-dev</version>
      </dependency>
  
      <dependency>
        <id>commons-collections</id>
        <version>2.0</version>
      </dependency>
  
      <dependency>
        <id>commons-digester</id>
        <version>1.2</version>
      </dependency>
  
      <dependency>
        <id>commons-lang</id>
        <version>SNAPSHOT</version>
      </dependency>
  
  
      <dependency>
        <id>ant</id>
        <version>1.4.1</version>
      </dependency>
      
      <dependency>
        <id>ant+optional</id>
        <version>1.4.1</version>
        <jar>ant-optional-1.4.1.jar</jar>
      </dependency>
  
      <dependency>
        <id>junit</id>
        <version>3.7</version>
      </dependency>
      
      <dependency>
        <id>xml-apis</id>
        <version>2.0.2</version>
      </dependency>
      
      <dependency>
        <id>xerces</id>
        <version>2.0.0</version>
      </dependency>
  
  	<!-- for running Jelly scripts -->
      <dependency>
        <id>commons-jelly</id>
        <version>SNAPSHOT</version>
      </dependency>
  
      <dependency>
        <id>commons-jexl</id>
        <version>SNAPSHOT</version>
      </dependency>
      
      <dependency>
        <id>dom4j</id>
        <version>1.4-dev-6</version>
      </dependency>
      
      <!-- for running examples -->
      <dependency>
        <id>jdbc</id>
        <version>2.0</version>
      </dependency>
      <dependency>
        <id>hsqldb</id>
        <version>1.7.0</version>
      </dependency>
      
    </dependencies>
  
  	
  	
    <build>
  
      <nagEmailAddress>commons-dev@jakarta.apache.org</nagEmailAddress>
      <sourceDirectory>src/java</sourceDirectory>
      <unitTestSourceDirectory>src/test</unitTestSourceDirectory>
      <integrationUnitTestSourceDirectory/>
      <aspectSourceDirectory/>
  
      <!-- Unit test classes -->
      <unitTest>
        <includes>
          <include>**/Test*.java</include>
        </includes>
      </unitTest>
  
      
      <!-- Integration unit test classes -->
      <integrationUnitTestPatterns></integrationUnitTestPatterns>
  
      <!-- J A R  R E S O U R C E S -->
      <!-- Resources that are packaged up inside the JAR file -->
      <resources>
        <includes>
          <include>**/*.properties, **/*.betwixt</include>
        </includes>
      </resources>
    </build>
  </project>
  
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/sybase/drop.vm
  
  Index: drop.vm
  ===================================================================
  #foreach ($fk in $table.ForeignKeys)
  IF EXISTS (SELECT 1 FROM sysobjects WHERE type ='RI' AND name='$fk.Name')
      ALTER TABLE $table.Name DROP CONSTRAINT $fk.Name;
  #end
  IF EXISTS (SELECT 1 FROM sysobjects WHERE type = 'U' AND name = '$table.Name')
  BEGIN
  	DROP TABLE $table.Name
  END
  ;
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/sybase/table.vm
  
  Index: table.vm
  ===================================================================
  
  /* ---------------------------------------------------------------------- */
  /* $table.Name                                                      */
  /* ---------------------------------------------------------------------- */
  
  $generator.parse("$basepath/drop.vm", "", "table", $tbl)
  CREATE TABLE $table.Name
  (
  #set ( $cols = $generator.parse("$basepath/columns.vm", "", "table", $tbl) )
  #set ( $pk = $generator.parse("$basepath/primarykey.vm", "", "table", $tbl) )
  #set ( $unique = $generator.parse("$basepath/unique.vm", "", "table", $tbl) )
  #if($strings.allEmpty([$pk,$unique]))$strings.chop($cols,1)#else$cols#end
  #if($strings.allEmpty([$unique]) && $pk.length()>0)$strings.chop($pk,2)#else$pk#end
  #if($unique.length()>0)$strings.chop($unique,2)#end
  
  );
  
  #set ( $index = $generator.parse("$basepath/index.vm", "", "table", $tbl) )
  #if($index.length() > 0)$index#end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/sybase/foreignkey.vm
  
  Index: foreignkey.vm
  ===================================================================
  #foreach ($fk in $table.ForeignKeys)
  BEGIN
  ALTER TABLE $table.Name
      ADD CONSTRAINT $fk.Name FOREIGN KEY ($fk.LocalColumnNames)
      REFERENCES $fk.ForeignTableName ($fk.ForeignColumnNames)
  END    
  ;
  
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/sybase/db.props
  
  Index: db.props
  ===================================================================
  # Taken from java.sql.Types in the IBM 1.3 JDK
  # JDBC to Sybase mappings.
  
  BIT = BIT
  TINYINT =
  SMALLINT =
  INTEGER = INT
  BIGINT =
  FLOAT =
  REAL =
  DOUBLE =
  NUMERIC = NUMERIC
  DECIMAL =
  CHAR = CHAR
  VARCHAR = VARCHAR
  LONGVARCHAR = TEXT
  DATE = DATETIME
  TIME = TIMESTAMP
  TIMESTAMP = DATETIME
  BINARY = BINARY
  VARBINARY = IMAGE
  LONGVARBINARY = IMAGE
  NULL = NULL
  OTHER =
  JAVA_OBJECT =
  DISTINCT =
  STRUCT =
  ARRAY =
  BLOB =
  CLOB =
  REF =
  
  #
  # This is the autoincrement value if using native methods for
  # incrementing keys.  Most likely IDENTITIY wrt Sybase ASE.
  # Leaving the value blank should be used when Turbine's IDBroker
  # is used to autoincrement keys.
  #
  # Default: [blank]
  #
  AUTOINCREMENT =
  
  #
  # If true, the NOT NULL values will not be printed in generated 
  # SQL files if the column is set to autoincrement.  Should be true
  # when the internal IDENTITY attribute ( above ) is used in a column
  # for autoincrementing keys.
  #
  # Default: false
  #
  removeNotNullWithAutoIncrement = false
  
  #
  # If true, defaults are not included in generated SQL.
  #
  # Default: false
  #
  suppressDefaults = false
  
  #
  # The string to place in the generated SQL for columns which cannot
  # be NULL.
  #
  # Default: NOT NULL
  #
  NOTNULL = NOT NULL
  
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/sybase/tablefk.vm
  
  Index: tablefk.vm
  ===================================================================
  
  /* ---------------------------------------------------------------------- */
  /* $table.Name                                                      */
  /* ---------------------------------------------------------------------- */
  
  #set ( $fk = $generator.parse("$basepath/foreignkey.vm", "", "table", $tbl) )
  #if($fk.length() >0)$fk#end
  
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/sybase/primarykey.vm
  
  Index: primarykey.vm
  ===================================================================
      CONSTRAINT ${table.Name}_PK PRIMARY KEY($table.printPrimaryKey()),
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/sybase/columns.vm
  
  Index: columns.vm
  ===================================================================
  #foreach ($col in $table.Columns)
      #set ( $type = $dbprops.get($col.Type) )
      #set ( $size = $col.printSize() )
      #if ( $dbprops.get("suppressDefaults") == "true" )
          #set ( $default = "" )
      #else
          #set ( $default = $col.DefaultSetting )
      #end
      #if ( ($dbprops.get("removeNotNullWithAutoIncrement") == "true") && $col.isAutoIncrement() && $col.isNotNull() )
         #set ( $nullString = "" )
      #else
         #set ( $nullString = $strings.select($col.isNotNull(), $dbprops.get("NOTNULL"),"NULL") )
      #end
      #set ( $autoIncrement = $strings.select($col.isAutoIncrement(), $dbprops.get("AUTOINCREMENT"),"") )
      #set ( $entry = "$col.Name $type $size $default $nullString $autoIncrement," )
      $strings.sub($strings.collapseSpaces($entry)," ,",",")
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/sybase/index.vm
  
  Index: index.vm
  ===================================================================
  #foreach ($index in $table.Indices)
  CREATE #if($index.Unique)UNIQUE#end INDEX $index.Name ON $table.Name ($index.ColumnList);
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/sybase/unique.vm
  
  Index: unique.vm
  ===================================================================
  #foreach ($unique in $table.Unices)
      UNIQUE ($unique.ColumnList),
  #end
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/postgresql/table.vm
  
  Index: table.vm
  ===================================================================
  
  -----------------------------------------------------------------------------
  -- $table.Name
  -----------------------------------------------------------------------------
  $generator.parse("$basepath/drop.vm", "", "table", $tbl)
  CREATE TABLE $table.Name
  (
  #set ( $cols = $generator.parse("$basepath/columns.vm", "", "table",$tbl) )
  #set ( $pk = $generator.parse("$basepath/primarykey.vm", "", "table", $tbl) )
  #set ( $unique = $generator.parse("$basepath/unique.vm", "", "table", $tbl) )
  #set ( $index = $generator.parse("$basepath/index.vm", "", "table", $tbl) )
  #if($strings.allEmpty([$pk,$unique]))$strings.chop($cols,2)#else$cols#end
  #if($strings.allEmpty([$unique]) && $pk.length()>0)$strings.chop($pk,2)#else$pk#end
  #if($unique.length() > 0)$strings.chop($unique,2)#end
  
  );
  #if($index.length() > 0)$strings.chop($index,1)#end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/postgresql/tablefk.vm
  
  Index: tablefk.vm
  ===================================================================
  
  ----------------------------------------------------------------------
  -- $table.Name                                                      
  ----------------------------------------------------------------------
  
  #set ( $fk = $generator.parse("$basepath/foreignkey.vm", "", "table", $tbl) )
  #if($fk.length() >0)$fk#end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/postgresql/columns.vm
  
  Index: columns.vm
  ===================================================================
  #foreach ($col in $table.Columns)
      #if ($col.TorqueType.indexOf("BOOLEAN") != -1)
         #set ( $type = $dbprops.get($col.TorqueType) )
      #else
         #set ( $type = $dbprops.get($col.Type) )
      #end
      #if ($col.TorqueType.indexOf("INT") == -1)
          #set ( $size = $col.printSize() )
      #else
          #set ( $size = "" )
      #end
      #set ( $default = $col.DefaultSetting )
      #set ( $nullString = $strings.select($col.isNotNull(), $dbprops.get("NOTNULL"),"") )
      #set ( $entry = "$col.Name $type $size $default $nullString" )
      #set ( $autoIncrement = $dbprops.get("AUTOINCREMENT") )
      #set ( $entry = $strings.select($col.isAutoIncrement(), "$col.Name $autoIncrement", $entry) )
  ##
  ## the following works if you want to inline your foreign keys
  ## if you turn it on, be sure to comment out foreignkey.vm
  #if (false)
  #if ($col.isForeignKey())
  #set ($fk = $col.ForeignKey)
  #set ($entry = "$entry REFERENCES $fk.ForeignTableName ($fk.ForeignColumnNames)")
  #if ($fk.hasOnUpdate())
  #set ($entry = "$entry ON UPDATE $fk.OnUpdate ")
  #end
  #if ($fk.hasOnDelete())
  #set ($entry = "$entry ON DELETE $fk.OnDelete ")
  #end
  #end
  #end
  #set ( $entry = $strings.collapseSpaces("$entry,") )
      $strings.sub($entry," ,",",")
  ## add a nice comment
  #if ($col.isForeignKey())
  #set ($fk = $col.ForeignKey)
        -- REFERENCES $fk.ForeignTableName ($fk.ForeignColumnNames)
  #end
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/postgresql/foreignkey.vm
  
  Index: foreignkey.vm
  ===================================================================
  ##
  ## The following will only work for non-circular references
  ## if you have a dependancy chain, you will need to use
  ## ADD CONSTRAINT syntax (with INITIALLY DEFERRED)
  ## which is sticky and version dependant
  ##
  #foreach ($fk in $table.ForeignKeys)
  ALTER TABLE $table.Name
  ADD FOREIGN KEY ($fk.LocalColumnNames) REFERENCES $fk.ForeignTableName ($fk.ForeignColumnNames)
  #if ($fk.hasOnUpdate())
  ON UPDATE $fk.OnUpdate
  #end
  #if ($fk.hasOnDelete())
  ON DELETE $fk.OnDelete 
  #end
  ;
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/postgresql/unique.vm
  
  Index: unique.vm
  ===================================================================
  #foreach ($unique in $table.Unices)
      UNIQUE ($unique.ColumnList),
  #end
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/postgresql/db.props
  
  Index: db.props
  ===================================================================
  # Taken from java.sql.Types in the IBM 1.3 JDK
  # JDBC to PostgreSQL mappings.
  
  BIT =
  TINYINT = int2
  SMALLINT = int2
  INTEGER = integer
  BIGINT = int8
  FLOAT = float
  REAL = float
  BOOLEANCHAR = boolean
  BOOLEANINT = int2
  
  DOUBLE =
  NUMERIC =
  DECIMAL =
  CHAR = varchar
  VARCHAR = varchar
  LONGVARCHAR = bytea
  DATE = date
  TIME = time
  TIMESTAMP = timestamp
  BINARY = bytea
  VARBINARY = bytea
  LONGVARBINARY = bytea
  NULL =
  OTHER =
  JAVA_OBJECT =
  DISTINCT =
  STRUCT =
  ARRAY =
  BLOB =
  CLOB = text
  REF =
  
  AUTOINCREMENT = serial
  NOTNULL = NOT NULL
  
  primaryKeyInsideTableDirective = true
  indexInsideTableDirective = false
  
  removeNotNullWithAutoIncrement = true
  
  suppressDefaults = false
  idMethod=sequence
  
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/postgresql/drop.vm
  
  Index: drop.vm
  ===================================================================
  drop table $table.Name;
  #if ($table.IdMethod == "native")
  drop sequence $table.SequenceName;
  #end
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/postgresql/index.vm
  
  Index: index.vm
  ===================================================================
  #foreach ($index in $table.Indices)
  create #if($index.Unique)unique#end INDEX $index.Name on $table.Name ($index.ColumnList);
  #end
  
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/postgresql/primarykey.vm
  
  Index: primarykey.vm
  ===================================================================
  #if ($table.hasPrimaryKey())
      PRIMARY KEY($table.printPrimaryKey()),
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/jelly/defineTags.jelly
  
  Index: defineTags.jelly
  ===================================================================
  <?xml version="1.0"?>
  
  <j:jelly xmlns:j="jelly:core" 
  	xmlns:sqlm="jakarta.apache.org/commons/sql/tags" 
  	xmlns:define="jelly:define">
  
    <define:taglib uri="jakarta.apache.org/commons/sql/tags">  
  
      <define:tag name="dropTable">
        drop table ${table.name} <!-- add to oracle's tag 'cascade constraints' -->
      </define:tag>
  
      <define:tag name="createTable">
        create table ${table.name} (
        	<j:forEach var="column" items="${table.columns}" indexVar="i">
        	  <j:if test="${i != 0}" trim="false">, </j:if>
  		  <sqlm:column column="${column}"/>      		
        	</j:forEach>
  
  		<sqlm:primaryKeys table="${table}"/>
        )
      </define:tag>
      
      <!-- output each column in a create table-->
      <define:tag name="column">
  	  <j:whitespace>
    ${column.name} ${column.type}</j:whitespace>
    	  <j:if test="${column.required}" trim="true"> NOT NULL</j:if>
      </define:tag>
  
  	<!-- output the primary keys inside a create table script -->    
      <define:tag name="primaryKeys">
  		<j:if test="${table.hasPrimaryKey()}">
  		  <j:whitespace>,
    PRIMARY KEY(</j:whitespace>
  		  
  		  <j:set var="first" value="y"/>		  
        	  <j:forEach var="column" items="${table.columns}" indexVar="i">
        	    <j:if test="${column.primaryKey}">
  		      <j:choose>
  		        <j:when test="${first=='y'}">
  		          <j:set var="first" value="n"/>
  		        </j:when>
  		        <j:otherwise trim="false">, </j:otherwise>
  		      </j:choose>		  	  
  		      ${column.name}
        	    </j:if>
        	  </j:forEach>
  		  )
  		</j:if>
      </define:tag>
      
    </define:taglib>
      
  </j:jelly>
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/jelly/createSql.jelly
  
  Index: createSql.jelly
  ===================================================================
  <?xml version="1.0"?>
  
  <j:jelly xmlns:j="jelly:core" 
  	xmlns:sqlm="jakarta.apache.org/commons/sql/tags" 
  	xmlns:b="jelly:betwixt">
    
  <j:include uri="defineTags.jelly"/>
    
  <b:introspector var="introspector" 
    attributesForPrimitives="false" elementNameMapper="lowercase"/>
  	
  <b:parse var="database" 
    uri="../test-input/datamodel.xml" 
    introspector="${introspector}"
    rootClass="org.apache.commons.sql.datamodel.Database"/>
  
  Creating file: target/sql.xml
  
  <j:file name="target/sql.xml">  
  <database name="${database.name}" idMethod="${database.idMethod}">
    	
    <j:forEach items="${database.getTables()}" var="table">
      <table name="${table.name}">
  
      <drop>  	  
    	  <sqlm:dropTable table="${table}"/>
  	</drop>  	  
  
  	<create>		
    	  <sqlm:createTable table="${table}"/>
  	</create>  	  
  
  	</table>  	  	
    </j:forEach>
    	  
  </database>
  </j:file>
  
  </j:jelly>
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/jelly/createDb.jelly
  
  Index: createDb.jelly
  ===================================================================
  <?xml version="1.0"?>
  
  <j:jelly xmlns:j="jelly:core" 
  	xmlns:sql="jelly:sql"
  	xmlns:log="jelly:log"
  	xmlns:x="jelly:xml">
  
  <!-- lets have some senible defaults -->
  
  <j:if test="${empty databaseUrl}">
    <j:set var="databaseUrl" value="jdbc:hsqldb:target/hsql"/>
  </j:if>
  <j:if test="${empty databaseDriver}">
    <j:set var="databaseDriver" value="org.hsqldb.jdbcDriver"/>
  </j:if>
  <j:if test="${empty databaseUser}">
    <j:set var="databaseUser" value="sa"/>
  </j:if>
    
  <log:info>Connecting to database: ${databaseUrl} with driver ${databaseDriver}</log:info>
  
  <sql:setDataSource 
      url="${databaseUrl}" 
      driver="${databaseDriver}" 
      user="${databaseUser}"
      password="${databasePassword}"/>
  
  
  <x:parse var="doc" xml="target/sql.xml"/>
  
  <j:if test="${drop.flag == null || drop.flag == true}">
  
    <x:forEach select="$doc/database/table">
      <x:set var="tableName" select="string(@name)"/>
    
  	<log:info>Dropping table ${tableName}</log:info>
  	
      <j:catch var="exception">
    	  <sql:update>
    	    <x:out select="drop"/>
    	  </sql:update>
      </j:catch>
      
      <j:if test="${exception != null}">
        <log:info>Caught exception ${exception.message}" while dropping table ${tableName}</log:info>
      </j:if>
      
    </x:forEach>
  </j:if>
    
    
  <j:if test="${create.flag == null || create.flag == true}">
  
    <x:forEach select="$doc/database/table">
      <x:set var="tableName" select="string(@name)"/>
    
  	<log:info>Creating table ${tableName}</log:info>
  	
      <j:catch var="exception">
    	  <sql:update>
    	    <x:out select="create"/>
    	  </sql:update>
      </j:catch>
      
      <j:if test="${exception != null}">
        <log:info>Caught exception ${exception.message}" while creating table ${tableName}</log:info>
      </j:if>
      
    </x:forEach>
  </j:if>
      
  
  <log:info>Done</log:info>
    
  </j:jelly>
  
  
  
  1.1                  jakarta-commons-sandbox/sql/xdocs/howto/mssql-howto.xml
  
  Index: mssql-howto.xml
  ===================================================================
  <?xml version="1.0"?>
  <document>
  
   <properties>
   <title>Microsoft SQL Server&#x99; Howto</title>
   <author email="djpolito@apache.org"></author>
  </properties>
  
  <body>
  
  <section name="Microsoft SQL Server&#x99; Howto">
  
  <p>
  This howto contains configuration help on using MS SQL Server with Turbine.
  This Howto supplements the <a href="..\howto\tdk-howto.html">TDK Howto</a> page.
  </p>
  
  <p>
  We appreciate all <a href="http://jakarta.apache.org/site/source.html">patches
  and contributions</a> that improve this document.
  </p>
  
  </section>
  
  <section name="Create Microsoft SQL Server&#x99; Database">
  <p>
  Use the SQL Server Enterprise Manager to create the database. When using the TDK,
  it helps to name the database the same name as your project. If the name is not
  the same, you will need to manually change the database name in your properties
  files. After the database is created, you will need to create a new user, or
  give an existing user permissions to the new database. Create the new user with
  SQL Server Authentication, and assign the users default database to the newly
  created database. Make sure the database user has the db_owner role. Please
  refer to SQL Server documentation for further details.
  </p>
  
  </section>
  <section name="JDBC Driver">
  <p>
  Microsoft has a <a
  href="http://www.microsoft.com/sql/downloads/2000/jdbc.asp">JDBC
  driver for MS SQL Server</a> in beta. Alternately, a third party
  commercial driver from <a
  href="http://industry.java.sun.com/products/jdbc/drivers">JDBC(TM)
  Technology - Drivers</a>, the JDBC-ODBC bridge driver from Sun, or the
  free driver from <a href="http://www.freetds.org">FreeTDS</a> can be
  used.
  </p>
  
  <p>
  The driver from FreeTDS, as of version 0.51, is unstable and buggy, and not
  recommended for production environments. Use at your own risk.
  </p>
  
  <p>
  The JDBC-ODBC bridge driver from Sun is included with the Java 2 SDK
  Standard Edition as package sun.jdbc.odbc. Sun's statement on this driver is,
  &quot;Note that the bridge driver included in the SDK is appropriate only for
  experimental use or when no other driver is available.&quot; So use at your own
  risk. Also, if you are using a non-windows box to run Turbine, you will need to
  find ODBC drivers for SQL server for that platform. For UNIX environments, you
  can use <a href="http://www.odbc.org">unixODBC</a>. Please follow the ODBC
  driver instructions and setup a DSN for the new database.  You must uncheck the
  box that says, "Use ANSI nulls, paddings and warnings.".
  </p>
  
  </section>
  <section name="Edit properity files">
  <p>
  In the ...\WEB-INF\build\build.properties file make sure that;
  </p>
  
  <source><![CDATA[
  database=mssql
  database.manual.creation = true
  ]]></source>
  
  <p>
  And set the JDBC connection information:
  </p>
  
  <source><![CDATA[
  databaseDriver = [JDBC Driver]
  databaseUser = [db username]
  databasePassword = [db password]
  databaseHost = [hostname]
  databaseUrl = [Follow JDBC Driver Docs]
  ]]></source>
  
  <p>
  If you are using the Microsoft driver
  (i.e. <code>com.microsoft.jdbc.sqlserver.SQLServerDriver</code>),
  you'll need to use the <code>SelectMethod=cursor</code> parameter in
  the JDBC connection string (as outlined by <a
  href="http://forum.java.sun.com/thread.jsp?forum=48&amp;thread=184797">this
  JDC thread</a>).  Your <code>databaseUrl</code> would look something
  like the following:
  </p>
  
  <source><![CDATA[
  jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=mydb;SelectMethod=cursor
  ]]></source>
  
  <p>
  If you are using the JDBC-ODBC bridge driver:
  </p>
  
  <source><![CDATA[
  databaseUrl = jdbc:odbc:[DSN Name]
  databaseHost = [hostname]
  databaseDriver = sun.jdbc.odbc.JdbcOdbcDriver
  databaseUser = [db username]
  databasePassword = [db password]
  ]]></source>
  
  <p>
  In the ..\WEB-INF\conf\TurbineResources.properties file, set;
  </p>
  
  <source><![CDATA[
  services.DatabaseService.database.adaptor=DBMSSQL
  services.DatabaseService.database.adaptor.DBMSSQL=[JDBC Driver]
  ]]></source>
  
  
  </section>
  
  </body>
  </document>
  
  
  
  
  1.1                  jakarta-commons-sandbox/sql/xdocs/howto/oracle-howto.xml
  
  Index: oracle-howto.xml
  ===================================================================
  <?xml version="1.0"?>
  
  <document>
   <properties>
    <title>Oracle 8i Howto</title>
    <author email="a@a.com">Turbine Documentation Team</author>
   </properties>
  
  <body>
  
  <section name="Oracle Howto">
  
  <p>
  This HOWTO aims to be a simple guide to make Turbine run with an existing
  Oracle 8i database. The process of making Turbine run are not covered in
  this guide, proceed to <a href="install.html">Turbine Installation</a> for
  help on how to install Turbine.
  </p>
  
  </section>
  
  <section name="Creating the Database">
  
  <p>
  If you do not have a database already set up, you will need to create one so
  we can create the necessary tables for Turbine. The steps below are simple
  steps to take to create a new database. If you already have a database ready for
  use, you can skip this part.
  </p>
  
  <p>
  1. Open the Oracle Database Configuration assistant
  </p>
  
  <p>
  2. Create a database with the Global Database Name 'turbine.project' and
  SID 'turbine'
  </p>
    <ul>
    <li>Global Database Name : turbine.project</li>
    <li>SID : turbine</li>
    <li>SYSTEM account password : manager</li>
    <li>SYS account password : change_on_install</li>
    </ul>
  
  <p>
  3. Wait for the database to be created.
  </p>
  
  <p>
  4. Good idea to stop the services from running if the Oracle database
  isn't being used as they are memory hungry for a development desktop machine.
  Check if the Oracle TNS Listener and the correct service are running when
  trying to connect.
  </p>
  
  </section>
  
  <section name="Populating the Database from the .sql Scripts">
  
  <p>
  5. Start SQL *PLUS and login to the database using the username and
  password for the database. You may want to use the same username and password you will
  use for Turbine, or you will need to create synonyms for the tables and grant the
  necessary privilieges (SELECT, UPDATE, INSERT, etc), so Turbine can access the
  tables directly without using "user"."table_name".
  </p>
  
  <p>
  6. Run the Oracle specific scripts.  For the cvs version of Turbine,
  these can be found in turbine/src/sql .  In SQL*PLUS type :
  </p>
  <p>
  <font face="courier">@path/to/oracle-turbine.sql</font>
  </p>
  
  <p>
  7.The oracle-turbine.sql script creates an oracle sequence
  for each turbine table.  To use these sequences for primary
  key generation, the oracle-turbine-security.sql script should
  be modified.  For example, the following command from the script :
  </p>
  <p>
  <font face="courier">INSERT INTO TURBINE_USER (USER_ID, LOGIN_NAME, PASSWORD_VALUE, FIRST_NAME, LAST_NAME)
  VALUES (0, 'turbine', 'turbine', 'turbine', 'turbine');</font>
  </p>
  <p>
  would be changed to something like :
  </p>
  <p>
  <font face="courier">INSERT INTO TURBINE_USER (USER_ID, LOGIN_NAME, PASSWORD_VALUE, FIRST_NAME, LAST_NAME)
  VALUES (TURBINE_USER_SEQ.nextval, 'turbine', 'turbine', 'turbine', 'turbine');</font>
  </p>
  <p>
  When your changes, if any, are made to the script, run it from SQL*PLUS :
  </p>
  <p>
  <font face="courier">@path/to/oracle-turbine-security.sql</font>
  </p>
  
  <p>
  8.If you would rather use Turbine's id-broker to generate
  primary keys, run the following scripts to create and populate the
  id-broker table :
  </p>
  <p>
  <font face="courier">@path/to/oracle-id-table-schema.sql</font>
  </p>
  <p>
  <font face="courier">@path/to/oracle-turbine-id-table-init.sql</font>
  </p>
  
  </section>
  
  <section name="Setting up Turbine to Connect to Oracle">
  
  <p>
  9. Download and install the Oracle 8i JDBC type 4 Thin driver for JDK
  1.2.x from the Oracle website. Add the classes12_01.zip file to the
  classpath of the servlet engine. In JServ add to the jserv.properties file
  the line:
  </p>
     <ul>
     <p><font face="courier">
     wrapper.classpath=/path/to/classes12_01.zip
     </font></p>
     </ul>
  
  
  <p>
  10. Ensure that the OracleoracleTNSListener service and the
  OracleServiceTURBINE service is running before using the driver.
  </p>
  
  
  <p>
  11.  Follow the <a href="install.html">installation document</a>
  for Turbine with the following differences. To link up the Oracle
  database and driver to Turbine, edit the TurbineResources.properties file;
  </p>
  
  <ul>
    <li>Uncomment the lines:</li>
  
     <ul>
      database.default.driver=oracle.jdbc.driver.OracleDriver<br/>
      database.default.url=jdbc:oracle:thin:@localhost:1521:ORCL
     </ul>
  
      <p>
          and ensure no other database.default.driver or database.default.url
          is left uncommented.</p>
  
      <li>Edit the database.default.url to the oracle thin driver
          format drivername:@servername:portnumber:SID</li>
  
      <ul>
          database.default.driver=oracle.jdbc.driver.OracleDriver<br/>
          database.default.url=jdbc:oracle:thin:@localhost:1521:turbine
      </ul>
  
  
      <p>
      The  servername is the Oracle server name and the port is the port
      that oracle uses. It is important not to confuse the Oracle servername
      and port with the Apache server name and port. Refer to the Oracle 8i
      documentation if there are any conflicts in this regard.
      Take care to use the correct SID for the database you have set up.
      </p>
  
  
      <li>Edit the database.default.username and
          database.default.password to match the username and password of your
          database.</li>
  
      <p>
      You may need to check if a Turbine database adaptor has been setup for Oracle.
      Look for the following lines in TurbineResources.properties, and add them in
      case you do not find:
      </p>
  
      <ul>
          database.adaptor=DBOracle<br/>
          database.adaptor.DBOracle=oracle.jdbc.driver.OracleDriver
      </ul>
  
   </ul>
  
  </section>
  
  <section name="Connecting to the Oracle Database">
  
  <p>
  12. Point your web browser at http://servername:port/servlets/Turbine
  (the URL may vary depending on your servlet engine) and login as username
  turbine, password turbine. After logging in you should see the congratulatory
  "Welcome To The Default Screen".
  </p>
  
  </section>
  
  </body>
  </document>
  
  
  
  1.1                  jakarta-commons-sandbox/sql/xdocs/howto/sybase-howto.xml
  
  Index: sybase-howto.xml
  ===================================================================
  <?xml version="1.0"?>
  
  <document>
   <properties>
    <title>Sybase ASE Howto</title>
    <author email="a@a.com">Turbine Documentation Team</author>
   </properties>
  
  <body>
  
  <section name="Sybase Howto">
  
  <p>
  This text is a description of integration of Sybase ASE as the target
  database in a TDK generated application.  
  </p>
  
  </section>
  
  <section name="JDBC Driver Information">
  
  <p>
  Sybase has a pure java jdbc driver, jConnect, that is free to use, but not
  open source.  You may download this driver from 
  <a href="http://www.sybase.com/products/eaimiddleware/jconnectforjdbc/">Sybase</a>.
  </p>
  </section>
  
  <section name="Integration Steps">
  
  <OL>
  <LI>Generate your application with the TDK as normal.</LI>
  <LI>Edit the project properties as instructed by the TDK.</LI>
  <LI>
  Before you run 'build.sh init' you will need to create the
  database.  Automatic database creation for Sybase does not currently
  work, so the database must be created first.
  </LI>
  <LI>Place the jConnect jar file in your WEB-INF/lib directory.</LI>
  <LI>Run 'build.sh init' to generate and initialize the project.</LI>
  </OL>
  
  </section>
  
  <section name="Notes">
  
  <p>
  <UL>
  <LI>
  The .sql files that the TDK build process generates files with the
  sql command terminated by a ; for use in the sql directive provided by
  the Ant build system.  These scripts will not work properly if run by
  hand via the 'isql' command. 
  </LI>
  <LI>
  The .sql files to create the tables, do not correctly remove any
  constraints on the tables currently and may fail.  Drop the tables by
  hand, then re-run 'build-project.sh insert-sql' to re-create and
  populate the tables.
  </LI>
  </UL>
  </p>
  </section>
  
  </body>
  </document>
  
  
  
  1.1                  jakarta-commons-sandbox/sql/xdocs/howto/postgres-howto.xml
  
  Index: postgres-howto.xml
  ===================================================================
  <?xml version="1.0"?>
  
  <document>
   <properties>
    <title>PostgreSQL Howto</title>
    <author email="nissim@nksystems.com">Nissim Karpenstein</author>
   </properties>
  
  <body>
  
  <section name="PostgreSQL Howto">
  
  <p>
  Turbine comes with a default User implementation which utilizes some libraries,
  and code that are not 100% compatible with <a href="http://www.postgresql.org">
  PostgreSQL</a>. This document will explain  what you need to get the defaut
  Turbine User Implementation running with PostgreSQL. The user management code is
  only a small part of Turbine, and the default implementation is easily
  replacable. Rather than following the steps in this document, you can always
  create your own User implementation which does not require large object support.
  </p>
  
  </section>
  
  <section name="JDBC Driver">
  
  <p>
  First of all, the TurbineUser class which comes with Turbine uses a hashtable
  to store data relevant to the user.  Any data in this hashtable which does
  not map to one of the columns in the visitor table is written to a large
  object field in the database.  Database actions in the TurbineUserPeer and
  BasePeer classes are done through the
  <a href="http://share.whichever.com/index.php?SCREEN=village">Village API</a>.
  The village API uses the ResultSetMetaData returned by your JDBC driver to
  determine the types of the columns in a SQL result set.  Unfortunately,
  in PostgreSQL large objects are referenced using an OID column (which is a
  pointer to the data), and the metadata in the JDBC driver says that columns
  of type OID are java.sql.Types.INTEGER.
  </p>
  
  <p>
  There is also a bug in the released versions of the PostgreSQL which causes
  problems when reading and writing Timestamps.  This is fixed in CVS.  So to
  run Turbine with PostgreSQL you need to get the latest JDBC driver code from
  the PostgreSQL CVS server: :pserver:anoncvs@postgresql.org:/home/projects/pgsql/cvsroot
  the password is postgresql.  Before compiling the driver though, you must apply
  a patch so the metadata says that OID columns are java.sql.Types.VARBINARY, not
  java.sql.Types.INTEGER.  <strong>Important: If you need the metadata to report
  that OID columns are integers for another application, this patch will break
  that app.</strong>  If you've never heard of an OID before, or you only use OID's
  to reference large objects, you don't need to worry about it.
  </p>
  
  <p>
  Another problem is solved in the more recent JDBC drivers.  The test case
  JDBCToXMLSchema fails with the driver packaged with at least PostgreSQL
  7.1.3 and maybe others.  This problem is fixed in the 7.2dev1.2 version
  (build date 2001-11-25).
  That and other PostgreSQL JDBC resources can be found here:
  <a href="http://jdbc.postgresql.org/download.html">http://jdbc.postgresql.org/download.html</a>
  </p>
  
  </section>
  
  <section name="Patch">
  <p>
  This patch may or may not be necessary. If you are having problems with
  the driver, please try it out. You may also wish to try upgrading to a
  more recent version of the Postgrest driver and also make sure that you
  are using the latest released version of
  <a href="http://share.whichever.com/village/">Village</a>.
  </p>
  
  <source><![CDATA[
  /home/projects/pgsql/cvsroot/pgsql/src/interfaces/jdbc/org/postgresql/Field.java,v
  retrieving revision 1.1
  diff -r1.1 Field.java
  147c147
  <     "int4","oid",
  ---
  >     "int4",
  158a159
  >     "oid",
  172c173
  <     Types.INTEGER,Types.INTEGER,
  ---
  >     Types.INTEGER,
  183a185
  >     Types.VARBINARY,
  ]]></source>
  
  <p>
  After applying that patch, compile the driver, and you should be ready to go.
  One more problem though is that all actions involving large objects in
  PostgreSQL require transactions.  There is code in CVS now which automatically
  sets up the transaction if necessary, so make sure you're running the recent
  snapshots.
  </p>
  
  </section>
  
  </body>
  </document>
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/test-input/datamodel.xml
  
  Index: datamodel.xml
  ===================================================================
  <?xml version="1.0" encoding="ISO-8859-1" standalone="no" ?>
  <!DOCTYPE database SYSTEM "http://jakarta.apache.org/turbine/dtd/database.dtd">
  
  <database>
    <name>bookstore</name>
    
    <tables>
    
      <!-- =================================================== -->
      <!-- B O O K  T A B L E                                  -->
      <!-- =================================================== -->
    
      <table>
        <name>book</name>
      
        <columns>
          <column>
            <name>book_id</name>
            <required>true</required>
            <primaryKey>true</primaryKey>
            <type>INTEGER</type>
          </column>
          
          <column>
            <name>isbn</name>
            <required>true</required>
            <type>VARCHAR</type>
            <size>15</size>
          </column>
          
          <column>
            <name>author_id</name>
            <required>true</required>
            <type>INTEGER</type>
          </column>
          
          <column>
            <name>title</name>
            <required>true</required>
            <type>VARCHAR</type>
            <size>255</size>
          </column>
        </columns>
      
        <!-- Same deal, maybe these should be defined outside the table? -->
        <foreignKeys>
          <foreignKey>
            <foreigntable>author</foreigntable>
            <reference>
              <local>author_id</local>
              <foreign>author_id</foreign>
            </reference>
          </foreignKey>
        </foreignKeys>
      </table>
  
      <!-- =================================================== -->
      <!-- A U T H O R  T A B L E                              -->
      <!-- =================================================== -->
  
      <table>
        <name>author</name>
      
        <columns>
          <column>
            <name>author_id</name>
            <required>true</required>
            <primaryKey>true</primaryKey>
            <type>INTEGER</type>
          </column>
          
          <column>
            <name>name</name>
            <required>true</required>
            <type>VARCHAR</type>
            <size>50</size>
          </column>
        </columns>
      </table>
    
    </tables>
  </database>
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-create/postgresql/createdb.vm
  
  Index: createdb.vm
  ===================================================================
  #foreach ($databaseName in $databaseNames)
  drop database $databaseName;
  create database $databaseName;
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/xdocs/index.xml
  
  Index: index.xml
  ===================================================================
  <?xml version="1.0"?>
  
  <document>
  
    <properties>
      <title>Torque</title>
      <author email="jvanzyl@apache.com">Jason van Zyl</author>
      <author email="mpoeschl@marmot.at">Martin Poeschl</author>
    </properties>
  
    <body>
  
      <section name="What is Torque?">
        <p>
          Torque is a persistence layer. Torque generates all the database
          resources required by your application and includes a runtime
          environment to run the generated classes.
        </p>
        <p>
          Torque was developed as part of the Turbine Framework. It is now
          decoupled and can be used by itself. Starting with version 2.2 Turbine
          will use the decoupled Torque.
        </p>
  
        <subsection name="Torque's generation tasks">
          <p>
            Torque uses a single XML database schema to generate the SQL for
            your target database and Torque's Peer-based object relation model
            representing your XML database schema. Additionally, an HTML document
            describing the database can be generated if you wish to make a
            browseable version of the database schema.
          </p>
  
          <p>
            Torque offers the following <a href="http://jakarta.apache.org/ant">
            Ant</a> tasks:
            <ul>
              <li>
                <strong>TorqueCreateDatabase</strong><br/>
                generates simple scripts for creating databases on various
                platforms.
              </li>
              <p/>
              <li>
                <strong>TorqueDataDTDTask</strong><br/>
                generates data DTD from an XML schema describing a database
                structure
              </li>
              <p/>
              <li>
                <strong>TorqueDataDumpTask</strong><br/>
                dumping data from db into XML
              </li>
              <p/>
              <li>
                <strong>TorqueDataSQLTask</strong><br/>
                generates SQL source from an XML data file
              </li>
              <p/>
              <li>
                <strong>TorqueJDBCTransformTask</strong><br/>
                generates an XML schema of an existing database from JDBC metadata
              </li>
              <p/>
              <li>
                <strong>TorqueObjectModelTask</strong><br/>
                generates output by using Velocity
              </li>
              <p/>
              <li>
                <strong>TorqueSQLExecTask</strong><br/>
                inserts a SQL file into its designated database
              </li>
              <p/>
              <li>
                <strong>TorqueSQLTask</strong><br/>
                generates SQL source from an XML schema describing a database
                structure
              </li>
              <p/>
              <li>
                <strong>TorqueSQLTransformTask</strong><br/>
                generates an xml schema from an sql schema
              </li>
              <p/>
              <li>
                <strong>TorqueDocumentationTask</strong><br/>
                generates html or xml documentation for xml schemas
              </li>
            </ul>
          </p>
        </subsection>
  
        <subsection name="Torque's runtime environment">
          <p>
            Torque's runtime environment includes everything you need to use the
            generated OM/Peer classes. It includes a jdbc connection pool.
          </p>
        </subsection>
  
      </section>
  
      <section name="Supported RDBMS">
        <table>
          <tr>
            <th>RDBMS</th>
            <th>driver</th>
            <th>status</th>
            <th>tester</th>
          </tr>
          <tr>
            <td>Cloudscape</td>
            <td>COM.cloudscape.core.JDBCDriver</td>
            <td>untested</td>
            <td></td>
          </tr>
          <tr>
            <td>DB2</td>
            <td>COM.ibm.db2.jdbc.{app|net}.DB2Driver</td>
            <td>untested</td>
            <td></td>
          </tr>
          <tr>
            <td>DB2/AS400</td>
            <td>com.ibm.as400.access.AS400JDBCDriver</td>
            <td>possible case-insensitivity issues</td>
            <td><a href="mailto:Sweaver@rippe.com">Scott Weaver</a></td>
          </tr>
          <tr>
            <td>Hypersonic</td>
            <td>org.hsql.jdbcDriver</td>
            <td>untested</td>
            <td></td>
          </tr>
          <tr>
            <td>Informix</td>
            <td>???</td>
            <td>untested</td>
            <td></td>
          </tr>
          <tr>
            <td>InstantDB</td>
            <td>org.enhydra.instantdb.jdbc.idbDriver</td>
            <td>untested</td>
            <td></td>
          </tr>
          <tr>
            <td>Interbase</td>
            <td>interbase.interclient.Driver</td>
            <td>untested</td>
            <td></td>
          </tr>
          <tr>
            <td><a href="mssql-howto.html">MS SQL</a></td>
            <td>com.microsoft.jdbc.sqlserver.SQLServerDriver</td>
            <td>untested</td>
            <td></td>
          </tr>
          <tr>
            <td>Mysql</td>
            <td>org.gjt.mm.mysql.Driver</td>
            <td>no known problems</td>
            <td><a href="mailto:mpoeschl@marmot.at">Martin Poeschl</a></td>
          </tr>
          <tr>
            <td><a href="oracle-howto.html">Oracle</a></td>
            <td>oracle.jdbc.driver.OracleDriver</td>
            <td>no known problems</td>
            <td><a href="mailto:mpoeschl@marmot.at">Martin Poeschl</a></td>
          </tr>
          <tr>
            <td><a href="postgres-howto.html">Postgres</a></td>
            <td>org.postgresql.Driver</td>
            <td>no known problems</td>
            <td><a href="mailto:mpoeschl@marmot.at">Martin Poeschl</a></td>
          </tr>
          <tr>
            <td>SapDB</td>
            <td>com.sap.dbtech.jdbc.DriverSapDB</td>
            <td>untested</td>
            <td></td>
          </tr>
          <tr>
            <td><a href="sybase-howto.html">Sybase</a></td>
            <td>com.sybase.jdbc2.jdbc.SybDriver</td>
            <td>
            JDBCToXMLSchema task will not generate the schema properly.
            All other tests pass.
            </td>
            <td><a href="mailto:brekke@apache.org">Jeffrey D. Brekke</a></td>
          </tr>
          <tr>
            <td>Weblogic</td>
            <td>weblogic.jdbc.pool.Driver</td>
            <td>untested</td>
            <td></td>
          </tr>
        </table>
  
        <p>
          If your RDBMS is not listed here, please read the document about
          <a href="db-adapters.html">writing DB Adapters</a>
        </p>
        <p>
          If there is no tester for your RDBMS and you want to help, please read
          the <a href="developer-guide.html">developer-guide</a>, run the tests
          and send your results (and bugfixes ;) to the turbine-dev list.
        </p>
      </section>
  
    </body>
  </document>
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-doc/anakia/table.vm
  
  Index: table.vm
  ===================================================================
  <subsection name="$table.Name">
    <p>
      $!table.Description
    </p>
  
    <table>
      <tr>
        <th>Name</th>
        <th>Type</th>
        <th>Size</th>
        <th>Default</th>
        <th>JavaName</th>
        <th>PK</th>
        <th>FK</th>
        <th>not null</th>
        <th>Description</th>
      </tr>
    #foreach ($col in $table.Columns)
      <tr>
        <td>$col.Name</td>
        <td>$col.Type</td>
        <td>$col.printSize()</td>
        <td>$!col.DefaultValue</td>
        <td>$col.JavaName</td>
        <td>#if ($col.isPrimaryKey()==true)X#end</td>
        <td>#if ($col.isForeignKey()==true)X#end</td>
        <td>#if ($col.isNotNull()==true)X#end</td>
        <td>$!col.Description</td>
      </tr>
    #end
    </table>
  
  </subsection>
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-doc/anakia/datamodel.vm
  
  Index: datamodel.vm
  ===================================================================
  #set ( $database = $dataModel.database )
  <?xml version="1.0"?>
  
  <document>
    <properties>
      <title>$dataModel.name</title>
    </properties>
  
    <body>
  
    <section name="$dataModel.name">
    <table>
      <tr>
        <th>Table Name</th>
        <th>OM Class</th>
        <th>Description</th>
      </tr>
    #foreach ($tbl in $database.tables)
      <tr>
        <td><a href="#$tbl.Name">$tbl.Name</a></td>
        <td>$tbl.JavaName</td>
        <td>$!tbl.Description</td>
      </tr>
    #end
    </table>
    <p/>
  
    #foreach ($tbl in $database.tables)
      $generator.parse("doc/anakia/table.vm",$outFile,"table",$tbl)
    #end
  
    </section>
  </body>
  </document>
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-load/mssql/row.vm
  
  Index: row.vm
  ===================================================================
  INSERT INTO $row.Table.Name (##
  #set ($comma="")#foreach($col in $row.ColumnValues)$comma${col.Column.Name}#set($comma=",")#end)
      VALUES (#set ($comma="")#foreach($col in $row.ColumnValues)$comma${generator.parse("sql/load/mssql/val.vm", "", "column", $col)}#set ($comma=",")#end);
      
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-load/mssql/val.vm
  
  Index: val.vm
  ===================================================================
  #if($column.Column.TorqueType=="VARCHAR" || $column.Column.TorqueType=="LONGVARCHAR")'$column.Value'#else$column.Value#end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-store/dump/Control.vm
  
  Index: Control.vm
  ===================================================================
  #set ( $tfname= "data/dump/top.vm" )
  #set ( $fname= "data/dump/row.vm" )
  #set ( $bfname= "data/dump/bottom.vm" )
  #set ($q = '"')
  
  #foreach ($dataModel in $dataModels)
  #foreach ($database in $dataModel.Databases)
  
  #if ($project)
      #if ($database.Name)
          #set ($outFile="${project}-${database.Name}-${dataset}-data.xml")
      #else
          #set ( $outFile = "${project}-${dataset}-data.xml" )
      #end
  #else
      #set ( $outFile = "" )
  #end
  
  $generator.parse($tfname,$outFile,"dataset",$dataset)
  #foreach ($tbl in $database.Tables)
  fetching table $tbl.Name
      #foreach ($r in $tableTool.fetch($tbl.Name)).##
          #set ($rout = "<$tbl.JavaName")
          #foreach ($col in $tbl.Columns)
              #set ($cval = $r.get($col.Name))
              #if ($cval)
                  #set ($rout = "$rout ${col.JavaName}=$q$cval$q")
              #end
          #end
          #set ($rout = "$rout/>")
          $generator.parse($fname,$outFile,"row", $rout)
      #end
  #end
  $generator.parse($bfname,$outFile,"tables",$database.Tables)
  
  #end
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-store/dump/top.vm
  
  Index: top.vm
  ===================================================================
  <?xml version="1.0" encoding="ISO-8859-1" standalone="no" ?>
  <!DOCTYPE dataset SYSTEM "file://${project}-data.dtd">
  <dataset name="$dataset">
  
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-store/dump/row.vm
  
  Index: row.vm
  ===================================================================
      $row
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-store/dump/bottom.vm
  
  Index: bottom.vm
  ===================================================================
  </dataset>
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-create/hypersonic/createdb.vm
  
  Index: createdb.vm
  ===================================================================
  ECHO Not implemented
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-create/db2400/createdb.vm
  
  Index: createdb.vm
  ===================================================================
  ## Not implemented for DB2/400... yet ;-)
  
  #*
  #foreach ($databaseName in $databaseNames)
  drop database if exists $databaseName;
  create database $databaseName;
  #end
  *#
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/cloudscape/foreignkey.vm
  
  Index: foreignkey.vm
  ===================================================================
  #foreach ($fk in $table.ForeignKeys)
      FOREIGN KEY ($fk.LocalColumnNames) REFERENCES $fk.ForeignTableName ($fk.ForeignColumnNames),
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/cloudscape/tablefk.vm
  
  	<<Binary file>>
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/cloudscape/columns.vm
  
  Index: columns.vm
  ===================================================================
  #foreach ($col in $table.Columns)
      #set ( $type = $dbprops.get($col.Type) )
      #set ( $size = $col.printSize() )
      #set ( $default = $col.DefaultSetting )
      #set ( $nullString = $strings.select($col.isNotNull(), $dbprops.get("NOTNULL"),"") )
      #set ( $autoIncrement = $strings.select($col.isAutoIncrement(), $dbprops.get("AUTOINCREMENT"),"") )
      #set ( $entry = "$col.Name $type $size $autoIncrement," )
      $strings.sub($strings.collapseSpaces($entry)," ,",",")
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/cloudscape/table.vm
  
  Index: table.vm
  ===================================================================
  
  -----------------------------------------------------------------------------
  -- $table.Name
  -----------------------------------------------------------------------------
  ##$generator.parse("$basepath/drop.vm", "", "table", $tbl)
  CREATE TABLE $table.Name
  (
  #set ( $cols = $generator.parse("$basepath/columns.vm", "", "table", $tbl) )
  #set ( $pk = $generator.parse("$basepath/primarykey.vm", "", "table", $tbl) )
  ##set ( $fk = $generator.parse("$basepath/foreignkey.vm", "", "table", $tbl) )
  #set ( $unique = $generator.parse("$basepath/unique.vm", "", "table", $tbl) )
  #set ( $index = $generator.parse("$basepath/index.vm", "", "table", $tbl) )
  #if($strings.allEmpty([$pk,$unique]))$strings.chop($cols,1)#else$cols#end
  #if($strings.allEmpty([$unique]) && $pk.length()>0)$strings.chop($pk,2)#else$pk#end
  ##if($strings.allEmpty([$unique,$index]) && $fk.length() >0)$strings.chop($fk,2)#else$fk#end
  #if($unique.length()>0)$strings.chop($unique,2)#else$unique#end
  
  );
  
  #if($index.length() > 0)$strings.chop($index,1)#end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/cloudscape/primarykey.vm
  
  Index: primarykey.vm
  ===================================================================
      PRIMARY KEY($table.printPrimaryKey()),
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/cloudscape/drop.vm
  
  Index: drop.vm
  ===================================================================
  drop table if exists $table.Name;
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/cloudscape/db.props
  
  Index: db.props
  ===================================================================
  # Taken from java.sql.Types in the IBM 1.3 JDK
  # JDBC to Cloudscape mappings.
  
  BIT = BIT
  TINYINT = TINYINT
  SMALLINT = SMALLINT
  INTEGER = INT
  BIGINT = LONGINT
  FLOAT = FLOAT
  REAL = REAL
  DOUBLE = DOUBLE PRECISION
  NUMERIC = NUMERIC
  DECIMAL = DECIMAL
  CHAR = CHAR
  VARCHAR = VARCHAR
  LONGVARCHAR = LONG VARCHAR
  DATE = DATE
  TIME = TIME
  TIMESTAMP = TIMESTAMP
  BINARY = LONG BINARY
  VARBINARY = LONG BINARY
  LONGVARBINARY = LONG VARBINARY
  NULL =
  OTHER =
  JAVA_OBJECT = SERIALIZE
  DISTINCT =
  STRUCT =
  ARRAY =
  BLOB =
  CLOB =
  REF =
  
  AUTOINCREMENT = DEFAULT AUTOINCREMENT
  NOTNULL = NOT NULL
  
  primaryKeyInsideTableDirective = true
  indexInsideTableDirective = false
  
  removeNotNullWithAutoIncrement = false
  
  suppressDefaults = true
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/cloudscape/unique.vm
  
  Index: unique.vm
  ===================================================================
  #foreach ($unique in $table.Unices)
      UNIQUE ($unique.ColumnList),
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/cloudscape/index.vm
  
  Index: index.vm
  ===================================================================
  #foreach ($index in $table.Indices)
  CREATE #if($index.Unique)UNIQUE#end INDEX $index.Name ON $table.Name ($index.ColumnList);
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-load/sybase/row.vm
  
  Index: row.vm
  ===================================================================
  INSERT INTO $row.Table.Name (##
  #set ($comma="")#foreach($col in $row.ColumnValues)$comma${col.Column.Name}#set($comma=",")#end)
      VALUES (#set ($comma="")#foreach($col in $row.ColumnValues)$comma${generator.parse("sql/load/sybase/val.vm", "", "column", $col)}#set ($comma=",")#end);
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-load/sybase/val.vm
  
  Index: val.vm
  ===================================================================
  #if($column.Column.TorqueType=="VARCHAR" || $column.Column.TorqueType=="LONGVARCHAR")'$column.Value'#else$column.Value#end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-create/sybase/createdb.vm
  
  Index: createdb.vm
  ===================================================================
  #foreach ($databaseName in $databaseNames)
  USE MASTER
  ;
  
  DROP DATABASE $databaseName
  ;
  
  CREATE DATABASE $databaseName
  ;
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/sql/Control.vm
  
  Index: Control.vm
  ===================================================================
  #set ( $basepath = "sql/base/$targetDatabase" )
  #set ( $dbprops = $properties.load("$generator.TemplatePath/sql/base/$targetDatabase/db.props") )
  #set ( $fname= "sql/base/$targetDatabase/table.vm" )
  #set ( $fnamekeys= "sql/base/$targetDatabase/tablefk.vm" )
  #set ( $idname = "sql/id-table/idtable.$targetDatabase" )
  
  #foreach ($dataModel in $dataModels)
          
    #set ( $outFile = "${dataModel.name}.sql" )
  
    File to be created: $outFile
    
    #set ( $database = $dataModel.database )
    #foreach ($tbl in $database.tables)
      Primary Key:#if ($tbl.hasPrimaryKey()) Yes #else No #end
      #if (!$tbl.isSkipSql())
        $generator.parse($fname,$outFile,"table",$tbl)
      #end
    #end
      
    #foreach ($tbl in $database.tables)
      #if (!$tbl.isSkipSql())
        $generator.parse($fnamekeys,$outFile,"tablefk",$tbl)
      #end
    #end    
  
    #if ($idmodel)
  
      Creating id-table
  
      #set ($tbl = $idmodel.database.getTable("ID_TABLE"))
      $generator.parse($fname,$outFile,"table",$tbl)
   
      ## Generate inserts into ID-TABLE for initial ids.
      #set ( $initialID = 1 )  
      $generator.parse($idname, $outFile, "tables", $database.tables)
  
    #end
  
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-create/mssql/unix.vm
  
  Index: unix.vm
  ===================================================================
  #!/bin/sh
  
  #foreach ($databaseModel in $appData.Databases)
  dropdb $databaseModel.Name
  createdb $databaseModel.Name
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-create/mssql/windows.vm
  
  Index: windows.vm
  ===================================================================
  ECHO Not implemented
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-store/dataset.vm
  
  Index: dataset.vm
  ===================================================================
  <!ELEMENT dataset (
  #foreach($tbl in $tables)#if($velocityCount>1),
  #end
      ${tbl.JavaName}*#end
  )>
  <!ATTLIST dataset
      name CDATA #REQUIRED
  >
  
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-store/table.vm
  
  Index: table.vm
  ===================================================================
  <!ELEMENT $table.JavaName EMPTY>
  <!ATTLIST $table.JavaName
  #foreach ($col in $table.columns)
      $col.JavaName CDATA #if($col.isNotNull())#REQUIRED#else#IMPLIED#end
  
  #end
  >
  
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-store/Control.vm
  
  Index: Control.vm
  ===================================================================
  #set ( $hfname= "data/dataset.vm" )
  #set ( $fname= "data/table.vm" )
  
  #foreach ($dataModel in $dataModels)
  #foreach ($database in $dataModel.Databases)
      #if ($project)
          #if ($dataModel.MultipleDatabases)
              #set ( $outFile = "${project}-${database.Name}-data.dtd" )
          #else
              #set ( $outFile = "${project}-data.dtd" )
          #end
          $generator.parse($hfname,$outFile,"tables",$database.Tables)
          #foreach ($tbl in $database.Tables)
              $generator.parse($fname,$outFile,"table",$tbl)
          #end
      #else
          #foreach ($tbl in $database.Tables)
              $generator.parse($fname,"","table",$tbl)
          #end
      #end
  #end
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/test/org/apache/commons/sql/datamodel/TestDataModelRoundTrip.java
  
  Index: TestDataModelRoundTrip.java
  ===================================================================
  package org.apache.commons.sql.datamodel;
  
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   *
   * $Id: TestProjectRoundTrip.java,v 1.3 2002/03/10 20:16:03 jvanzyl Exp $
   */
  import java.io.InputStream;
  import java.io.IOException;
  import java.io.FileInputStream;
  
  import junit.framework.Test;
  import junit.framework.TestCase;
  import junit.framework.TestSuite;
  import junit.textui.TestRunner;
  
  import org.apache.commons.betwixt.XMLIntrospector;
  import org.apache.commons.betwixt.io.BeanReader;
  import org.apache.commons.betwixt.io.BeanWriter;
  import org.apache.commons.betwixt.strategy.DecapitalizeNameMapper;
  
  import org.apache.commons.logging.Log;
  import org.apache.commons.logging.LogFactory;
  import org.apache.commons.logging.impl.SimpleLog;
  
  /**
   * Test harness for the BeanReader that deals with project definitions.
   *
   * @author <a href="mailto:jason@zenplex.com">Jason van Zyl</a>
   * @version $Revision: 1.3 $
   */
  public class TestDataModelRoundTrip
       extends TestCase
  {
      private String TEST_DOCUMENT;
  
      /**
       * A unit test suite for JUnit
       */
      public static Test suite()
      {
          return new TestSuite(TestDataModelRoundTrip.class);
      }
  
      /**
       * Constructor for the TestDataModelRoundTrip object
       *
       * @param testName
       */
      public TestDataModelRoundTrip(String testName)
      {
          super(testName);
      }
  
      /**
       * The JUnit setup method
       */
      protected void setUp()
          throws Exception
      {
          super.setUp();
          String baseDir = System.getProperty("basedir");
          assertNotNull("The system property basedir was not defined.", baseDir);
          String fs = System.getProperty("file.separator");
          assertNotNull("The system property file.separator was not defined.", fs);
          TEST_DOCUMENT = baseDir + "/src/test-input/datamodel.xml";
      }
  
      /**
       * A unit test for JUnit
       */
      public void testBeanWriter()
          throws Exception
      {
  
          BeanReader reader = new BeanReader();
          reader.setXMLIntrospector(createXMLIntrospector());
          reader.registerBeanClass(getBeanClass());
          InputStream in = getXMLInput();
  
          try
          {
              Database database = (Database) reader.parse(in);
              assertTrue("Parsed a Database object", database != null);
              assertEquals("bookstore", database.getName());
              
              assertTrue("more than one table found", database.getTables().size() > 0 );
              
              // Test our first table which is the 'book' table
              Table t0 = database.getTable(0);
              assertEquals("book", t0.getName());
              
              Column c0 = t0.getColumn(0);
              assertEquals("book_id", c0.getName());
              assertTrue("book_id is required", c0.isRequired());
              assertTrue("book_id is primary key", c0.isPrimaryKey());
              
              Column c1 = t0.getColumn(1);
              assertEquals("isbn", c1.getName());
              assertTrue("isbn is required", c1.isRequired());
              assertTrue("isbn is not primary key", ! c1.isPrimaryKey());
              
              // Write out the bean
              //writeBean(database);
          }
          catch (Exception e)
          {
              e.printStackTrace();
              fail();
          }
          finally
          {
              if (in != null)
              {
                  in.close();
              }
          }
      }
  
      /**
       * Description of the Method
       */
      public void writeBean(Object bean)
          throws Exception
      {
          BeanWriter writer = new BeanWriter();
          writer.enablePrettyPrint();
          writer.write(bean);
      }
  
      /**
       * @return the bean class to use as the root
       */
      public Class getBeanClass()
      {
          return Database.class;
      }
  
      /**
       * Gets the xMLInput attribute of the TestDataModelRoundTrip object
       */
      protected InputStream getXMLInput()
          throws IOException
      {
          //return getClass().getResourceAsStream("datamodel.xml");
          return new FileInputStream(TEST_DOCUMENT);
      }
  
  
      /**
       * ### it would be really nice to move this somewhere shareable across Maven
       * / Turbine projects. Maybe a static helper method - question is what to
       * call it???
       */
      protected XMLIntrospector createXMLIntrospector()
      {
          XMLIntrospector introspector = new XMLIntrospector();
  
          // set elements for attributes to true
          introspector.setAttributesForPrimitives(false);
  
          // turn bean elements into lower case
          introspector.setElementNameMapper(new DecapitalizeNameMapper());
  
          return introspector;
      }
  
  }
  
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-load/postgresql/row.vm
  
  Index: row.vm
  ===================================================================
  INSERT INTO $row.Table.Name (##
  #set ($comma="")#foreach($col in $row.ColumnValues)$comma${col.Column.Name}#set($comma=",")#end)
      VALUES (#set ($comma="")#foreach($col in $row.ColumnValues)$comma${generator.parse("sql/load/postgresql/val.vm", "", "column", $col)}#set ($comma=",")#end);
      
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-load/postgresql/val.vm
  
  Index: val.vm
  ===================================================================
  #if($column.Column.TorqueType=="VARCHAR" || $column.Column.TorqueType=="LONGVARCHAR")'$column.Value'#else$column.Value#end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-create/sapdb/createdb.vm
  
  Index: createdb.vm
  ===================================================================
  #foreach ($databaseName in $databaseNames)
  -- drop database $databaseName;
  -- create database $databaseName;
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-create/Control.vm
  
  Index: Control.vm
  ===================================================================
  #set ( $fname = "sql/db-init/$targetDatabase/createdb.vm" )
  $generator.parse($fname,"")
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/ant/build-sql.properties
  
  Index: build-sql.properties
  ===================================================================
  # -------------------------------------------------------------------
  # 
  # T O R Q U E  C O N F I G U R A T I O N  F I L E
  # 
  # -------------------------------------------------------------------
  
  database = postgresql
  
  # -------------------------------------------------------------------
  #
  #  D A T A B A S E  S E T T I N G S
  #
  # -------------------------------------------------------------------
  # JDBC connection settings. This is used by the JDBCToXML task that
  # will create an XML database schema from JDBC metadata. These
  # settings are also used by the SQL Ant task to initialize your
  # Turbine system with the generated SQL.
  # -------------------------------------------------------------------
  
  createDatabaseUrl = jdbc:postgresql://127.0.0.1:5432/template1
  databaseUrl = jdbc:postgresql://127.0.0.1:5432/bookstore
  databaseDriver = org.postgresql.Driver
  databaseUser = jvanzyl
  databasePassword =
  databaseHost = 127.0.0.1
  
  # Tells JDBC task that javaName attribute for the tables and columns
  # should be made same as SQL name.
  sameJavaName=false
  
  # -------------------------------------------------------------------
  #
  #  D O C U M E N T A T I O N   S E T T I N G S
  #
  # -------------------------------------------------------------------
  # These settings will allow you to customize the way your schema
  # documentation is created.
  # Valid formats are: html, anakia (for use with jakarta-site2)
  # -------------------------------------------------------------------
  documentationFormat=html
  
  # -------------------------------------------------------------------
  # You should NOT have to edit anything below here.
  # -------------------------------------------------------------------
  
  # -------------------------------------------------------------------
  # 
  #  T E M P L A T E  P A T H
  #
  # -------------------------------------------------------------------
  
  templatePath = src/templates
  
  # -------------------------------------------------------------------
  # 
  #  C O N T R O L  T E M P L A T E S
  #
  # -------------------------------------------------------------------
  
  SQLControlTemplate = sql/base/Control.vm
  OMControlTemplate = om/Control.vm
  idTableControlTemplate = sql/id-table/Control.vm
  DataDTDControlTemplate = data/Control.vm
  DataDumpControlTemplate = data/dump/Control.vm
  DataSQLControlTemplate = sql/load/Control.vm
  DocControlTemplate = doc/Control.vm
  
  # -------------------------------------------------------------------
  # 
  #  O U T P U T  D I R E C T O R Y
  #
  # -------------------------------------------------------------------
  
  outputDirectory=src
  
  # -------------------------------------------------------------------
  # 
  #  S C H E M A  D I R E C T O R Y
  #
  # -------------------------------------------------------------------
  
  schemaDirectory=schema
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/ant/build-sql.xml
  
  Index: build-sql.xml
  ===================================================================
  <project name="Torque" default="main" basedir=".">
  
    <property name="build.properties" value="build.properties"/>
    <property file="${build.properties}"/>
  
    <!-- ================================================================ -->
    <!-- C R E A T E  T A R G E T  D A T A B A S E                        -->
    <!-- ================================================================ -->
    <!-- Most RDBMs have a facility for creating database via an SQL      -->
    <!-- interface which we will use by generating the database creation  -->
    <!-- SQL and executing it.                                            -->
    <!-- ================================================================ -->
  
    <target
      name="project-create-db"
      unless="database.manual.creation"
      description="==> generates the target database">
  
      <taskdef
        name="torque-create-db"
        classname="org.apache.commons.sql.CreateDatabase">
        <classpath refid="torque-classpath"/>
      </taskdef>
  
      <torque-create-db
        controlTemplate="sql/db-init/Control.vm"
        outputDirectory="${basedir}/${outputDirectory}/sql"
        targetDatabase="${database}"
        useClasspath="true"
        outputFile="create-db.sql">
        <fileset dir="${basedir}/${schemaDirectory}">
          <include name="*-schema.xml"/>
        </fileset>
      </torque-create-db>
  
      <sql
        driver="${databaseDriver}"
        url="${createDatabaseUrl}"
        userid="${databaseUser}"
        password="${databasePassword}"
        src="${basedir}/${outputDirectory}/sql/create-db.sql"
        autocommit="true"
        onerror="continue">
        <classpath refid="torque-classpath"/>
      </sql>
    </target>
  
    <!-- ================================================================ -->
    <!-- G E N E R A T E  P R O J E C T  S Q L                            -->
    <!-- ================================================================ -->
    <!-- Generate the SQL for your project, these are in addition         -->
    <!-- to the base Turbine tables! The tables you require for your      -->
    <!-- project should be specified in project-schema.xml.               -->
    <!-- ================================================================ -->
  
    <target
      name="project-sql-classpath"
      description="==> generates the SQL for your project">
  
      <echo message="+------------------------------------------+"/>
      <echo message="|                                          |"/>
      <echo message="| Generating SQL for YOUR Turbine project! |"/>
      <echo message="| Woo hoo!                                 |"/>
      <echo message="|                                          |"/>
      <echo message="+------------------------------------------+"/>
  
      <taskdef
        name="torque-sql"
        classname="org.apache.commons.sql.SQLTask">
        <classpath refid="torque-classpath"/>
      </taskdef>
  
      <torque-sql
        contextProperties="${build.properties}"
        controlTemplate="${SQLControlTemplate}"
        outputDirectory="${torque.home}/${outputDirectory}/sql"
        useClasspath="true"
        sqldbmap="${torque.home}/${outputDirectory}/sql/sqldb.map"
        outputFile="report.${project}.sql.generation"
        targetDatabase="${database}">
        <fileset dir="${torque.home}/${schemaDirectory}">
          <include name="*-schema.xml"/>
        </fileset>
      </torque-sql>
    </target>
  
    <!-- ================================================================ -->
    <!-- I N S E R T  P R O J E C T  S Q L  F I L E S                     -->
    <!-- ================================================================ -->
    <!--                                                                  -->
    <!-- ================================================================ -->
  
    <target
      name="project-insert-sql">
  
      <taskdef
        name="torque-insert-sql"
        classname="org.apache.commons.sql.SQLExec">
        <classpath refid="torque-classpath"/>
      </taskdef>
  
      <torque-insert-sql
        driver="${databaseDriver}"
        url="${buildDatabaseUrl}"
        userid="${databaseUser}"
        password="${databasePassword}"
        autocommit="true"
        onerror="continue"
        sqldbmap="${basedir}/${outputDirectory}/sql/sqldb.map"
        srcDir="${basedir}/${outputDirectory}/sql">
        <classpath refid="torque-classpath"/>
      </torque-insert-sql>
    </target>
  
    <!-- ================================================================ -->
    <!-- G E N E R A T E   D O C S                                        -->
    <!-- ================================================================ -->
  
    <target
      name="project-doc"
      description="==> generates documentation for your datamodel">
  
      <echo message="+------------------------------------------+"/>
      <echo message="|                                          |"/>
      <echo message="| Generating docs for YOUR datamodel!      |"/>
      <echo message="| Woo hoo!                                 |"/>
      <echo message="|                                          |"/>
      <echo message="+------------------------------------------+"/>
  
      <taskdef
        name="torque-doc"
        classname="org.apache.commons.sql.DocumentationTask">
        <classpath refid="torque-classpath"/>
      </taskdef>
  
      <torque-doc
        contextProperties="${build.properties}"
        controlTemplate="${DocControlTemplate}"
        outputDirectory="${basedir}/${outputDirectory}/doc"
        outputFormat="${documentationFormat}"
        useClasspath="true"
        sqldbmap="${basedir}/${outputDirectory}/sql/sqldb.map"
        outputFile="report.${project}.doc.generation">
        <fileset dir="${basedir}/${schemaDirectory}">
          <include name="*-schema.xml"/>
        </fileset>
      </torque-doc>
    </target>
  
    <!-- ================================================================ -->
    <!-- J D B C  TO  X M L                                               -->
    <!-- ================================================================ -->
  
    <target
      name="project-jdbc"
      description="==> jdbc to xml">
  
      <echo message="+-----------------------------------------------+"/>
      <echo message="|                                               |"/>
      <echo message="| Generating XML from JDBC connection !         |"/>
      <echo message="| Woo hoo!                                      |"/>
      <echo message="|                                               |"/>
      <echo message="+-----------------------------------------------+"/>
      <echo message=" taking build.properties from: ${build.properties}"/>
  
      <taskdef
        name="torque-jdbc"
        classname="org.apache.commons.sql.JDBCTransformTask">
        <classpath refid="torque-classpath"/>
      </taskdef>
  
      <torque-jdbc
        dbUrl="${databaseUrl}"
        dbDriver="${databaseDriver}"
        dbUser="${databaseUser}"
        dbPassword="${databasePassword}"
        dbSchema="${databaseSchema}"
        outputFile="${basedir}/${outputDirectory}/schema.xml"
        sameJavaName="${sameJavaName}"
      />
    </target>
  
    <!-- ================================================================ -->
    <!-- Generate SQL from XML data file                                  -->
    <!-- ================================================================ -->
  
    <target
      name="project-datasql"
      description="==> generates sql from data xml">
  
      <echo message="+-----------------------------------------------+"/>
      <echo message="|                                               |"/>
      <echo message="| Generating SQL from data XML !                |"/>
      <echo message="| Woo hoo!                                      |"/>
      <echo message="|                                               |"/>
      <echo message="+-----------------------------------------------+"/>
      <echo message=" taking build.properties from: ${build.properties}"/>
  
      <taskdef
        name="torque-datasql"
        classname="org.apache.commons.sql.DataSQLTask">
        <classpath refid="torque-classpath"/>
      </taskdef>
  
      <torque-datasql
        contextProperties="${build.properties}"
        controlTemplate="${DataSQLControlTemplate}"
        outputDirectory="${basedir}/${outputDirectory}"
        useClasspath="true"
        outputFile="${project}-data.sql"
        xmlFile="${basedir}/${schemaDirectory}/${project}-schema.xml"
        dataXmlFile="${basedir}/${schemaDirectory}/${project}-data.xml"
        dataDTD="${basedir}/${schemaDirectory}/${project}-data.dtd"
        targetDatabase="${database}"
        sqldbmap="${basedir}/${outputDirectory}/sql/sqldb.map"
      />
    </target>
  
    <!-- ================================================================ -->
    <!-- Dump data from database into xml file                            -->
    <!-- ================================================================ -->
  
    <target
      name="project-datadump"
      description="==> dump data from database into xml file">
  
      <echo message="+-----------------------------------------------+"/>
      <echo message="|                                               |"/>
      <echo message="| Dumping the data from database into XML       |"/>
      <echo message="| Woo hoo!                                      |"/>
      <echo message="|                                               |"/>
      <echo message="+-----------------------------------------------+"/>
      <echo message=" taking build.properties from: ${build.properties}"/>
  
      <taskdef
        name="torque-datadump"
        classname="org.apache.commons.sql.DataDumpTask">
        <classpath refid="torque-classpath"/>
      </taskdef>
  
      <torque-datadump
        contextProperties="${build.properties}"
        controlTemplate="${DataDumpControlTemplate}"
        outputDirectory="${basedir}/${outputDirectory}"
        useClasspath="true"
        outputFile="report.${project}.datadump.generation"
        xmlFile="${basedir}/${schemaDirectory}/${project}-schema.xml"
        databaseDriver="${databaseDriver}"
        databaseUrl="${databaseUrl}"
        databaseUser="${databaseUser}"
        databasePassword="${databasePassword}"
        databaseName="${databaseName}"
      />
    </target>
  
    <!-- ================================================================ -->
    <!-- G E N E R A T E  P R O J E C T  D A T A  D T D                   -->
    <!-- ================================================================ -->
    <!-- Generate the DATA DTD for your project                           -->
    <!-- ================================================================ -->
  
    <target
      name="project-datadtd"
      description="==> generates the DATA DTD for your project">
  
      <echo message="+-----------------------------------------------+"/>
      <echo message="|                                               |"/>
      <echo message="| Generating Data DTD for YOUR Turbine project! |"/>
      <echo message="| Woo hoo!                                      |"/>
      <echo message="|                                               |"/>
      <echo message="+-----------------------------------------------+"/>
  
      <taskdef
        name="torque-datadtd"
        classname="org.apache.commons.sql.DataDTDTask">
        <classpath refid="torque-classpath"/>
      </taskdef>
  
      <torque-datadtd
        contextProperties="${build.properties}"
        controlTemplate="${DataDTDControlTemplate}"
        outputDirectory="${basedir}/${outputDirectory}"
        useClasspath="true"
        outputFile="report.${project}.datadtd.generation"
        xmlFile="${basedir}/${schemaDirectory}/${project}-schema.xml"
      />
    </target>
  
  </project>
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-load/sapdb/row.vm
  
  Index: row.vm
  ===================================================================
  INSERT INTO $row.Table.Name (##
  #set ($comma="")#foreach($col in $row.ColumnValues)$comma${col.Column.Name}#set($comma=",")#end)
      VALUES (#set ($comma="")#foreach($col in $row.ColumnValues)$comma${generator.parse("sql/load/sapdb/val.vm", "", "column", $col)}#set ($comma=",")#end);
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-load/sapdb/val.vm
  
  Index: val.vm
  ===================================================================
  #if($column.Column.TorqueType=="VARCHAR" || $column.Column.TorqueType=="LONGVARCHAR")'$column.Value'#else$column.Value#end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-load/mysql/row.vm
  
  Index: row.vm
  ===================================================================
  INSERT INTO $row.Table.Name (##
  #set ($comma="")#foreach($col in $row.ColumnValues)$comma${col.Column.Name}#set($comma=",")#end)
      VALUES (#set ($comma="")#foreach($col in $row.ColumnValues)$comma${generator.parse("sql/load/mysql/val.vm", "", "column", $col)}#set ($comma=",")#end);
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-load/mysql/val.vm
  
  Index: val.vm
  ===================================================================
  #if($column.Column.TorqueType=="VARCHAR" || $column.Column.TorqueType=="LONGVARCHAR")'$column.Value'#else$column.Value#end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-doc/Control.vm
  
  Index: Control.vm
  ===================================================================
  #set ( $basepath = $generator.OutputPath)
  
  #foreach ($dataModel in $dataModels)
  
    #if ($outputFormat=="html")
      #set ( $outFile = "${dataModel.name}.html" )
    #else
      #set ( $outFile = "${dataModel.name}.xml" )
    #end
  
    File to be created: $outFile
  
    $generator.parse("doc/$outputFormat/datamodel.vm",$outFile,"dataModel",$dataModel)
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/templates/database-create/mysql/createdb.vm
  
  Index: createdb.vm
  ===================================================================
  #foreach ($databaseName in $databaseNames)
  drop database if exists $databaseName;
  create database $databaseName;
  #end
  
  
  
  1.1                  jakarta-commons-sandbox/sql/src/schema/database.xsd
  
  Index: database.xsd
  ===================================================================
  <?xml version="1.0" encoding="UTF-8"?>
  
  <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    
    <xsd:element name="database">
      <xsd:complexType>
        <xsd:sequence>
          <xsd:element ref="table" maxOccurs="unbounded"/>
        </xsd:sequence>
        <xsd:attribute name="name" use="required" type="xsd:string"/>
        <xsd:attribute name="heavyIndexing" default="false">
          <xsd:simpleType>
            <xsd:restriction base="xsd:NMTOKEN">
              <xsd:enumeration value="true"/>
              <xsd:enumeration value="false"/>
            </xsd:restriction>
          </xsd:simpleType>
        </xsd:attribute>
      </xsd:complexType>
    </xsd:element>
    
    <xsd:element name="table">
      <xsd:complexType>
        <xsd:sequence>
          <xsd:element ref="column" maxOccurs="unbounded"/>
          <xsd:choice minOccurs="0" maxOccurs="unbounded">
            <xsd:element ref="foreign-key"/>
            <xsd:element ref="index"/>
            <xsd:element ref="unique"/>
          </xsd:choice>
        </xsd:sequence>
        <xsd:attribute name="name" use="required" type="xsd:string"/>
        <xsd:attribute name="heavyIndexing" use="optional">
          <xsd:simpleType>
            <xsd:restriction base="xsd:NMTOKEN">
              <xsd:enumeration value="true"/>
              <xsd:enumeration value="false"/>
            </xsd:restriction>
          </xsd:simpleType>
        </xsd:attribute>
        <xsd:attribute name="description" use="optional" type="xsd:string"/>
      </xsd:complexType>
    </xsd:element>
    
    <xsd:element name="column">
      <xsd:complexType>
        <xsd:sequence>
          <xsd:element ref="inheritance" minOccurs="0" maxOccurs="unbounded"/>
        </xsd:sequence>
        <xsd:attribute name="name" use="required" type="xsd:string"/>
        <xsd:attribute name="primaryKey" default="false">
          <xsd:simpleType>
            <xsd:restriction base="xsd:NMTOKEN">
              <xsd:enumeration value="true"/>
              <xsd:enumeration value="false"/>
            </xsd:restriction>
          </xsd:simpleType>
        </xsd:attribute>
        <xsd:attribute name="required" default="false">
          <xsd:simpleType>
            <xsd:restriction base="xsd:NMTOKEN">
              <xsd:enumeration value="true"/>
              <xsd:enumeration value="false"/>
            </xsd:restriction>
          </xsd:simpleType>
        </xsd:attribute>
        <xsd:attribute name="type" default="VARCHAR">
          <xsd:simpleType>
            <xsd:restriction base="xsd:NMTOKEN">
              <xsd:enumeration value="BIT"/>
              <xsd:enumeration value="TINYINT"/>
              <xsd:enumeration value="SMALLINT"/>
              <xsd:enumeration value="INTEGER"/>
              <xsd:enumeration value="BIGINT"/>
              <xsd:enumeration value="FLOAT"/>
              <xsd:enumeration value="REAL"/>
              <xsd:enumeration value="NUMERIC"/>
              <xsd:enumeration value="DECIMAL"/>
              <xsd:enumeration value="CHAR"/>
              <xsd:enumeration value="VARCHAR"/>
              <xsd:enumeration value="LONGVARCHAR"/>
              <xsd:enumeration value="DATE"/>
              <xsd:enumeration value="TIME"/>
              <xsd:enumeration value="TIMESTAMP"/>
              <xsd:enumeration value="BINARY"/>
              <xsd:enumeration value="VARBINARY"/>
              <xsd:enumeration value="LONGVARBINARY"/>
              <xsd:enumeration value="NULL"/>
              <xsd:enumeration value="OTHER"/>
              <xsd:enumeration value="JAVA_OBJECT"/>
              <xsd:enumeration value="DISTINCT"/>
              <xsd:enumeration value="STRUCT"/>
              <xsd:enumeration value="ARRAY"/>
              <xsd:enumeration value="BLOB"/>
              <xsd:enumeration value="CLOB"/>
              <xsd:enumeration value="REF"/>
              <xsd:enumeration value="BOOLEANINT"/>
              <xsd:enumeration value="BOOLEANCHAR"/>
              <xsd:enumeration value="DOUBLE"/>
            </xsd:restriction>
          </xsd:simpleType>
        </xsd:attribute>
        <xsd:attribute name="size" use="optional" type="xsd:string"/>
        <xsd:attribute name="description" use="optional" type="xsd:string"/>
      </xsd:complexType>
    </xsd:element>
    
    <xsd:element name="foreign-key">
      <xsd:complexType>
        <xsd:sequence>
          <xsd:element ref="reference" maxOccurs="unbounded"/>
        </xsd:sequence>
        <xsd:attribute name="foreignTable" use="required" type="xsd:string"/>
        <xsd:attribute name="name" use="optional" type="xsd:string"/>
      </xsd:complexType>
    </xsd:element>
    
    <xsd:element name="reference">
      <xsd:complexType>
        <xsd:attribute name="local" use="required" type="xsd:string"/>
        <xsd:attribute name="foreign" use="required" type="xsd:string"/>
      </xsd:complexType>
    </xsd:element>
    
    <xsd:element name="index">
      <xsd:complexType>
        <xsd:sequence>
          <xsd:element ref="index-column" maxOccurs="unbounded"/>
        </xsd:sequence>
        <xsd:attribute name="name" use="optional" type="xsd:string"/>
      </xsd:complexType>
    </xsd:element>
    
    <xsd:element name="index-column">
      <xsd:complexType>
        <xsd:attribute name="name" use="required" type="xsd:string"/>
        <xsd:attribute name="size" use="optional" type="xsd:string"/>
      </xsd:complexType>
    </xsd:element>
    
    <xsd:element name="unique">
      <xsd:complexType>
        <xsd:sequence>
          <xsd:element ref="unique-column" maxOccurs="unbounded"/>
        </xsd:sequence>
        <xsd:attribute name="name" use="optional" type="xsd:string"/>
      </xsd:complexType>
    </xsd:element>
    
    <xsd:element name="unique-column">
      <xsd:complexType>
        <xsd:attribute name="name" use="required" type="xsd:string"/>
      </xsd:complexType>
    </xsd:element>
  
  </xsd:schema>
  
  
  

--
To unsubscribe, e-mail:   <mailto:commons-dev-unsubscribe@jakarta.apache.org>
For additional commands, e-mail: <mailto:commons-dev-help@jakarta.apache.org>


Mime
View raw message