empire-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From doeb...@apache.org
Subject svn commit: r683173 [8/10] - in /incubator/empire-db/trunk/core/Empire-db: ./ .settings/ bin/ lib/ src/ src/META-INF/ src/org/ src/org/apache/ src/org/apache/empire/ src/org/apache/empire/commons/ src/org/apache/empire/data/ src/org/apache/empire/data/...
Date Wed, 06 Aug 2008 08:47:43 GMT
Added: incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/expr/join/DBJoinExpr.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/expr/join/DBJoinExpr.java?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/expr/join/DBJoinExpr.java (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/expr/join/DBJoinExpr.java Wed Aug  6 01:47:37 2008
@@ -0,0 +1,197 @@
+/*
+ * ESTEAM Software GmbH
+ */
+package org.apache.empire.db.expr.join;
+
+import java.util.*;
+
+import org.apache.empire.db.DBColumn;
+import org.apache.empire.db.DBColumnExpr;
+import org.apache.empire.db.DBDatabase;
+import org.apache.empire.db.DBExpr;
+import org.apache.empire.db.DBJoinType;
+import org.apache.empire.db.DBRowSet;
+import org.apache.empire.db.expr.compare.DBCompareExpr;
+
+
+/**
+ * This class is used for building a join expression of an SQL statement.
+ * <P>
+ * There is no need to explicitly create instances of this class.<BR>
+ * Instead use @link {@link org.apache.empire.db.DBCommand#join(DBColumnExpr, DBColumn, DBJoinType)}
+ * <P>
+ * @author ESTEAM software <A TARGET="esteam" HREF="http://www.esteam.de">www.esteam.de </A>
+ */
+public class DBJoinExpr extends DBExpr
+{
+    protected DBColumnExpr  left;
+    protected DBColumnExpr  right;
+    protected DBJoinType    type;
+
+    // Additional
+    public DBCompareExpr compExpr = null;
+
+    /**
+     * Constructs a new DBJoinExpr object initialize this object with
+     * the left and right column and the data type of the join
+     * expression.
+     * 
+     * @param left left value
+     * @param right right value
+     * @param type data type (JOIN_INNER, JOIN_LEFT or JOIN_RIGHT)
+     */
+    public DBJoinExpr(DBColumnExpr left, DBColumnExpr right, DBJoinType type)
+    {
+        this.left = left;
+        this.right = right;
+        this.type = type;
+    }
+
+    /**
+     * Returns the current DBDatabase object.
+     * 
+     * @return the current DBDatabase object
+     */
+    @Override
+    public DBDatabase getDatabase()
+    {
+        return left.getDatabase();
+    }
+
+    public DBColumnExpr getLeft()
+    {
+        return left;
+    }
+
+    public DBColumnExpr getRight()
+    {
+        return right;
+    }
+
+    public DBJoinType getType()
+    {
+        return type;
+    }
+    
+    public boolean isJoinOn(DBRowSet rowset)
+    {
+        if (rowset==null)
+            return false;
+        DBColumn l = (left !=null ? left .getUpdateColumn() : null);
+        DBColumn r = (right!=null ? right.getUpdateColumn() : null);
+        DBRowSet rsl = (l!=null ? l.getRowSet() : null);
+        DBRowSet rsr = (r!=null ? r.getRowSet() : null);
+        return rowset.equals(rsl) || rowset.equals(rsr);
+    }
+
+    /**
+     * Returns the left table name if the data type= JOIN_LEFT and returns
+     * the right table if the data type= JOIN_RIGHT. If the
+     * data type = JOIN_INNER the return value is null.
+     * 
+     * @return the current DBDatabase object
+     */
+    public DBRowSet getOuterTable()
+    {
+        switch(type)
+        {
+            case LEFT:  return right.getUpdateColumn().getRowSet();
+            case RIGHT: return left .getUpdateColumn().getRowSet();
+            default:    return null; // no outer table!
+        }
+    }
+
+    /**
+     * This function swaps the left and the right statements of the join expression.
+     */
+    public void reverse()
+    { // Swap Type of Join
+        DBColumnExpr swap = left;
+        left = right;
+        right = swap;
+        type = DBJoinType.reversed(type); // (type * -1);
+    }
+
+    /**
+     * This function adds an additional constraint to the join.
+     */
+    public void where(DBCompareExpr expr)
+    { // Set Compare Expression
+        compExpr = expr;
+    }
+
+    /**
+     * This function adds an additional constraint to the join.
+     */
+    public DBCompareExpr and(DBColumnExpr c1, DBColumnExpr c2)
+    { // Set Compare Expression
+        compExpr = c1.is(c2);
+        return compExpr;
+    }
+
+    /**
+     * @see org.apache.empire.db.DBExpr#addReferencedColumns(Set)
+     */
+    @Override
+    public void addReferencedColumns(Set<DBColumn> list)
+    {
+        left.addReferencedColumns(list);
+        right.addReferencedColumns(list);
+        // Compare Expression
+        if (compExpr != null)
+            compExpr.addReferencedColumns(list);
+    }
+
+    /** Not allowed, this operation have to be done in the DBCommand object. */
+    @Override
+    public void addSQL(StringBuilder buf, long context)
+    {
+        if ((context & CTX_NAME) != 0)
+            left.getUpdateColumn().getRowSet().addSQL(buf, CTX_DEFAULT | CTX_ALIAS);
+        if ((context & CTX_VALUE) != 0)
+        { // Join Type
+            switch(type)
+            {
+                case LEFT:  buf.append(" LEFT JOIN ");break;
+                case INNER: buf.append(" INNER JOIN ");break;
+                case RIGHT: buf.append(" RIGHT JOIN ");break;
+                default:    buf.append(" JOIN "); // should not come here!
+            }
+            right.getUpdateColumn().getRowSet().addSQL(buf, CTX_DEFAULT | CTX_ALIAS);
+            // compare equal
+            buf.append(" ON ");
+            right.addSQL(buf, CTX_DEFAULT);
+            buf.append(" = ");
+            left.addSQL(buf, CTX_DEFAULT);
+            // Compare Expression
+            if (compExpr != null)
+            {
+                buf.append(" AND ");
+                compExpr.addSQL(buf, CTX_DEFAULT);
+            }
+        }
+    }
+
+    /**
+     * Compares two DBJoinExpr objects.
+     * 
+     * @param obj other DBJoinExpr object
+     * @return true if the other DBJoinExpr object is equal to this object
+     */
+    @Override
+    public boolean equals(Object obj)
+    {
+        if (obj==null || obj.getClass()!=getClass())
+            return super.equals(obj);
+        // object
+        DBJoinExpr other = (DBJoinExpr) obj;
+        if (left.equals(other.left) && right.equals(other.right) && type == other.type)
+            return true;
+        // reversed
+        if (left.equals(other.right) && right.equals(other.left) && type == DBJoinType.reversed(other.type))
+            return true;
+        // not equal
+        return false;
+    }
+
+}
\ No newline at end of file

Added: incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/expr/join/DBJoinExprEx.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/expr/join/DBJoinExprEx.java?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/expr/join/DBJoinExprEx.java (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/expr/join/DBJoinExprEx.java Wed Aug  6 01:47:37 2008
@@ -0,0 +1,78 @@
+/*
+ * ESTEAM Software GmbH, 07.03.2005
+ */
+package org.apache.empire.db.expr.join;
+
+import org.apache.empire.db.DBColumnExpr;
+import org.apache.empire.db.DBJoinType;
+import org.apache.empire.db.DBRowSet;
+import org.apache.empire.db.expr.compare.DBCompareAndOrExpr;
+import org.apache.empire.db.expr.compare.DBCompareColExpr;
+import org.apache.empire.db.expr.compare.DBCompareExpr;
+
+/**
+ * This class is used for building a join expression of an SQL statement.
+ * <P>
+ * There is no need to explicitly create instances of this class.<BR>
+ * Instead use @link {@link org.apache.empire.db.DBCommand#join(DBRowSet, DBCompareExpr, DBJoinType)}
+ * <P>
+ * @author ESTEAM software <A TARGET="esteam" HREF="http://www.esteam.de">www.esteam.de </A>
+ */
+public class DBJoinExprEx extends DBJoinExpr
+{
+    private final DBCompareExpr cmp;
+    
+    private static DBColumnExpr findFirstColumn(DBCompareExpr expr)
+    {
+        // DBCompareORExpr 
+        while (expr instanceof DBCompareAndOrExpr)
+               expr = ((DBCompareAndOrExpr)expr).getLeft();
+        // Get Colum Expr
+        if (expr instanceof DBCompareColExpr)
+            return ((DBCompareColExpr)expr).getColumnExpr();
+        // Error
+        log.error("Unknown class found for building a valid JOIN Expression");
+        return null;
+    }
+    
+    /**
+     * Constructor
+     */
+    public DBJoinExprEx(DBRowSet rset, DBCompareExpr cmp, DBJoinType joinType)
+    {
+        super(rset.getColumn(0), findFirstColumn(cmp), joinType);
+        this.cmp = cmp;
+    }
+    
+    public DBCompareExpr getJoinConstraint()
+    {
+        return cmp;
+    }
+
+    @Override
+    public void addSQL(StringBuilder buf, long context)
+    {
+        if ((context & CTX_NAME) != 0)
+            left.getUpdateColumn().getRowSet().addSQL(buf, CTX_DEFAULT | CTX_ALIAS);
+        if ((context & CTX_VALUE) != 0)
+        { // Join Type
+            switch(type)
+            {
+                case LEFT:  buf.append(" LEFT JOIN ");break;
+                case INNER: buf.append(" INNER JOIN ");break;
+                case RIGHT: buf.append(" RIGHT JOIN ");break;
+                default:    buf.append(" JOIN "); // should not come here!
+            }
+            right.getUpdateColumn().getRowSet().addSQL(buf, CTX_DEFAULT | CTX_ALIAS);
+            // compare equal
+            buf.append(" ON ");
+            cmp.addSQL(buf, CTX_DEFAULT);
+            // Compare Expression
+            if (compExpr != null)
+            {
+                buf.append(" AND ");
+                compExpr.addSQL(buf, CTX_DEFAULT);
+            }
+        }
+    }
+}
\ No newline at end of file

Added: incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/expr/join/package.html
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/expr/join/package.html?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/expr/join/package.html (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/expr/join/package.html Wed Aug  6 01:47:37 2008
@@ -0,0 +1,15 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<html>
+<head>
+<!--
+/*
+ * ESTEAM Software GmbH, 12.12.2007
+ */
+-->
+</head>
+<body>
+
+This package contains SQL-generator classes for join expressions used in the from clause.
+There is no need to use these classes directly. They are internally created through functions on the DBCommand object.
+
+</body></html>
\ No newline at end of file

Added: incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/expr/set/DBSetExpr.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/expr/set/DBSetExpr.java?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/expr/set/DBSetExpr.java (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/expr/set/DBSetExpr.java Wed Aug  6 01:47:37 2008
@@ -0,0 +1,111 @@
+/*
+ * ESTEAM Software GmbH
+ */
+package org.apache.empire.db.expr.set;
+
+import java.util.*;
+
+import org.apache.empire.db.DBColumn;
+import org.apache.empire.db.DBDatabase;
+import org.apache.empire.db.DBExpr;
+import org.apache.empire.db.DBRowSet;
+
+
+/**
+ * This class is used for building a set expression of an SQL update statement.
+ * <P>
+ * There is no need to explicitly create instances of this class.<BR>
+ * Instead use {@link DBColumn#to(Object)} factory method.
+ * <P>
+ * For the SQL fragment "set name="foo"<BR>
+ * you should write: cmd.set( TABLE.NAME.to( "foo" ));
+ * <P>
+ * 
+ * @author ESTEAM software <A TARGET="esteam" HREF="http://www.esteam.de">www.esteam.de</A>
+ */
+public class DBSetExpr extends DBExpr
+{
+    public final DBColumn column;
+    public Object         value;
+
+    /**
+     * Constructs a new DBSetExpr object. Sets the specified parameters to this object.
+     */
+    public DBSetExpr(DBColumn expr, Object value)
+    {
+        this.column = expr;
+        this.value = value;
+    }
+
+    /**
+     * Returns the current DBDatabase object.
+     * 
+     * @return the current DBDatabase object
+     */
+    @Override
+    public DBDatabase getDatabase()
+    {
+        return column.getDatabase();
+    }
+
+    /**
+     * Returns the current DBDatabase object.
+     * 
+     * @return the current DBDatabase object
+     */
+    public DBRowSet getTable()
+    {
+        return column.getRowSet();
+    }
+
+    /**
+     * @return the column which value should be set
+     */
+    public DBColumn getColumn()
+    {
+        return column;
+    }
+
+    /**
+     * @return the value to which to set the column to
+     */
+    public Object getValue()
+    {
+        return value;
+    }
+
+    /**
+     * The value to which to set the column
+     * @param value the new column value 
+     */
+    public void setValue(Object value)
+    {
+        this.value = value;
+    }
+
+    /**
+     * @see org.apache.empire.db.DBExpr#addReferencedColumns(Set)
+     */
+    @Override
+    public void addReferencedColumns(Set<DBColumn> list)
+    {
+        list.add(column);
+    }
+
+    /**
+     * Creates the SQL-Command.
+     * 
+     * @param buf the SQL-Command
+     * @param context the current SQL-Command context
+     */
+    @Override
+    public void addSQL(StringBuilder buf, long context)
+    {
+        if ((context & CTX_NAME) != 0)
+            column.addSQL(buf, CTX_NAME);
+        if ((context & CTX_NAME) != 0 && (context & CTX_VALUE) != 0)
+            buf.append("=");
+        if ((context & CTX_VALUE) != 0)
+            buf.append(getObjectValue(column, value, CTX_NAME | CTX_VALUE, "+"));
+    }
+}

Added: incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/expr/set/package.html
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/expr/set/package.html?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/expr/set/package.html (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/expr/set/package.html Wed Aug  6 01:47:37 2008
@@ -0,0 +1,15 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<html>
+<head>
+<!--
+/*
+ * ESTEAM Software GmbH, 12.12.2007
+ */
+-->
+</head>
+<body>
+
+This package contains SQL-generator classes for set expressions used in the set clause.
+There is no need to use these classes directly. They are internally created through functions on the DBColumnExpr object.
+
+</body></html>
\ No newline at end of file

Added: incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/hsql/DBDatabaseDriverHSql.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/hsql/DBDatabaseDriverHSql.java?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/hsql/DBDatabaseDriverHSql.java (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/hsql/DBDatabaseDriverHSql.java Wed Aug  6 01:47:37 2008
@@ -0,0 +1,660 @@
+/*
+ * ESTEAM Software GmbH, 14.12.2004
+ */
+package org.apache.empire.db.hsql;
+
+import java.sql.Connection;
+import java.util.GregorianCalendar;
+import java.util.Iterator;
+
+import org.apache.empire.commons.Errors;
+import org.apache.empire.data.DataType;
+import org.apache.empire.db.DBCmdType;
+import org.apache.empire.db.DBColumn;
+import org.apache.empire.db.DBCommand;
+import org.apache.empire.db.DBCommandExpr;
+import org.apache.empire.db.DBDatabase;
+import org.apache.empire.db.DBDatabaseDriver;
+import org.apache.empire.db.DBDriverFeature;
+import org.apache.empire.db.DBExpr;
+import org.apache.empire.db.DBIndex;
+import org.apache.empire.db.DBObject;
+import org.apache.empire.db.DBRelation;
+import org.apache.empire.db.DBSQLScript;
+import org.apache.empire.db.DBTable;
+import org.apache.empire.db.DBTableColumn;
+import org.apache.empire.db.DBView;
+
+
+/**
+ * This class provides support for the HSQLDB database system.<br>
+ * 
+ * @author ESTEAM software <A TARGET="esteam" HREF="http://www.esteam.de">www.esteam.de </A>
+ * 
+ */
+public class DBDatabaseDriverHSql extends DBDatabaseDriver
+{
+    /**
+     * Defines the HSQLDB command type.
+     */ 
+	public static class DBCommandHSql extends DBCommand
+	{
+	    /**
+	     * @see org.apache.empire.db.DBCommand
+	     */
+	    public DBCommandHSql(DBDatabase db)
+	    {
+	        super(db);
+	    }
+	}
+	
+    /**
+     * Constructor for the HSQLDB database driver.
+     */
+    public DBDatabaseDriverHSql()
+    {
+        // Default Constructor
+    }
+
+    /**
+     * Creates a new HSQLDB command object.
+     * 
+     * @return the new DBCommandHSql object
+     */
+    @Override
+    public DBCommand createCommand(DBDatabase db)
+    {
+        if (db == null)
+            return null;
+        // create command object
+        return new DBCommandHSql(db);
+    }
+
+    /**
+     * Returns whether or not a particular feature is supported by this driver
+     * @param type type of requrested feature. @see DBDriverFeature
+     * @return true if the features is supported or false otherwise
+     */
+    @Override
+    public boolean isSupported(DBDriverFeature type)
+    {
+        switch (type)
+        {   // return support info 
+            case CREATE_SCHEMA: return false;
+            case SEQUENCES:     return true;    
+        }
+        return false;
+    }
+    
+    /**
+     * Gets an sql phrase template for this database system.<br>
+     * @see DBDatabaseDriver#getSQLPhrase(int)
+     * @return the phrase template
+     */
+    @Override
+    public String getSQLPhrase(int phrase)
+    {
+        switch (phrase)
+        {
+            // sql-phrases
+            case SQL_NULL_VALUE:        return "null";
+            case SQL_RENAME_COLUMN:     return " AS ";
+            case SQL_PARAMETER:         return " ? ";
+            case SQL_CONCAT_EXPR:       return " + ";
+            case SQL_RENAME_TABLE:      return " ";
+            case SQL_DATABASE_LINK:     return "@";
+            // data types
+            case SQL_BOOLEAN_TRUE:      return String.valueOf(Boolean.TRUE);
+            case SQL_BOOLEAN_FALSE:     return String.valueOf(Boolean.FALSE);
+            case SQL_CURRENT_DATE:      return "CURRENT_DATE";
+            case SQL_DATE_PATTERN:      return "yyyy-MM-dd";
+            case SQL_DATE_TEMPLATE:     return "'{0}'";
+            case SQL_CURRENT_DATETIME:  return "CURRENT_TIMESTAMP";
+            case SQL_DATETIME_PATTERN:  return "yyyy-MM-dd HH:mm:ss.S";
+            case SQL_DATETIME_TEMPLATE: return "'{0}'";
+            // functions
+            case SQL_FUNC_COALESCE:     return "coalesce(?, {0})";
+            case SQL_FUNC_SUBSTRING:    return "substr(?, {0})";
+            case SQL_FUNC_SUBSTRINGEX:  return "substr(?, {0}, {1})";
+            case SQL_FUNC_REPLACE:      return "replace(?, {0}, {1})";
+            case SQL_FUNC_REVERSE:      return "?"; // "reverse(?)"; 
+            case SQL_FUNC_STRINDEX:     return "locate({0}, ?)"; 
+            case SQL_FUNC_STRINDEXFROM: return "locate({0}, ?, {1})"; 
+            case SQL_FUNC_UPPER:        return "ucase(?)";
+            case SQL_FUNC_LOWER:        return "lcase(?)";
+            case SQL_FUNC_LENGTH:       return "length(?)";
+            case SQL_FUNC_TRIM:         return "trim(?)";
+            case SQL_FUNC_LTRIM:        return "ltrim(?)";
+            case SQL_FUNC_RTRIM:        return "rtrim(?)";
+            case SQL_FUNC_ESCAPE:       return "? escape '{0}'";
+            // Numeric
+            case SQL_FUNC_ABS:          return "abs(?)";
+            case SQL_FUNC_ROUND:        return "round(?,{0})";
+            case SQL_FUNC_TRUNC:        return "truncate(?,{0})";
+            case SQL_FUNC_CEILING:      return "ceiling(?)";
+            case SQL_FUNC_FLOOR:        return "floor(?)";
+            // Date
+            case SQL_FUNC_DAY:          return "day(?)";
+            case SQL_FUNC_MONTH:        return "month(?)";
+            case SQL_FUNC_YEAR:         return "year(?)";
+            // Aggregation
+            case SQL_FUNC_SUM:          return "sum(?)";
+            case SQL_FUNC_COUNT:        return "count(?)";
+            case SQL_FUNC_MAX:          return "max(?)";
+            case SQL_FUNC_MIN:          return "min(?)";
+            case SQL_FUNC_AVG:          return "avg(?)";
+            // Others
+            case SQL_FUNC_DECODE:       return "case ?{0} end";
+            case SQL_FUNC_DECODE_SEP:   return " ";
+            case SQL_FUNC_DECODE_PART:  return "when {0} then {1}";
+            case SQL_FUNC_DECODE_ELSE:  return "else {0}";
+            // Not defined
+            default:
+                log.error("SQL phrase " + String.valueOf(phrase) + " is not defined!");
+                return "?";
+        }
+    }
+
+    /**
+     * @see DBDatabaseDriver#getConvertPhrase(DataType, DataType, Object)
+     */
+    @Override
+    public String getConvertPhrase(DataType destType, DataType srcType, Object format)
+    {
+        switch (destType)
+        {
+            /*
+             * case DBExpr.DT_BOOL: return "convert(bit, ?)"; case DBExpr.DT_INTEGER: return "convert(int, ?)"; case
+             * DBExpr.DT_DECIMAL: return "convert(decimal, ?)"; case DBExpr.DT_NUMBER: return "convert(float, ?)"; case
+             * DBExpr.DT_DATE: return "convert(datetime, ?, 111)"; case DBExpr.DT_DATETIME: return "convert(datetime, ?, 120)";
+             */
+            // Convert to text
+            case TEXT:
+            case CHAR:
+                if (format != null)
+                { // Convert using a format string
+                    return "to_char(?, '"+format.toString()+"')";
+                }
+                return "to_char(?)";
+            // Unknown Type
+            default:
+                log.error("getConvertPhrase: unknown type (" + String.valueOf(destType));
+                return "?";
+        }
+    }
+
+    /**
+     * @see DBDatabaseDriver#getNextSequenceValue(DBDatabase, String, int, Connection)
+     */
+    @Override
+    public Object getNextSequenceValue(DBDatabase db, String seqName, int minValue, Connection conn)
+    { 	//Use Oracle Sequences
+        StringBuilder sql = new StringBuilder(80);
+        sql.append("SELECT ");
+        sql.append("NEXT VALUE FOR ");
+        db.appendQualifiedName(sql, seqName);
+        sql.append(" FROM INFORMATION_SCHEMA.SYSTEM_SEQUENCES WHERE SEQUENCE_NAME='"+ seqName + "'");
+        	
+        Object val = db.querySingleValue(sql.toString(), conn);
+        if (val == null)
+        { // Error!
+            log.error("getNextSequenceValue: Invalid sequence value for sequence " + seqName);
+        }
+        // Done
+        
+        return val;
+    }
+
+    /**
+     * @see DBDatabaseDriver#getDDLScript(DBCmdType, DBObject, DBSQLScript)  
+     */
+    @Override
+    public boolean getDDLScript(DBCmdType type, DBObject dbo, DBSQLScript script)
+    {
+        // The Object's database must be attached to this driver
+        if (dbo==null || dbo.getDatabase().getDriver()!=this)
+            return error(Errors.InvalidArg, dbo, "dbo");
+        // Check Type of object
+        if (dbo instanceof DBDatabase)
+        { // Database
+            switch (type)
+            {
+                case CREATE:
+                    return createDatabase((DBDatabase) dbo, script);
+                case DROP:
+                    return dropObject(((DBDatabase) dbo).getSchema(), "DATABASE", script);
+                default:
+                    return error(Errors.NotImplemented, "getDDLScript."+dbo.getClass().getName()+"."+String.valueOf(type));
+            }
+        } 
+        else if (dbo instanceof DBTable)
+        { // Table
+            switch (type)
+            {
+                case CREATE:
+                    return createTable((DBTable) dbo, script);
+                case DROP:
+                    return dropObject(((DBTable) dbo).getName(), "TABLE", script);
+                default:
+                    return error(Errors.NotImplemented, "getDDLCommand."+dbo.getClass().getName()+"."+String.valueOf(type));
+            }
+        } 
+        else if (dbo instanceof DBView)
+        { // View
+            switch (type)
+            {
+                case CREATE:
+                    return createView((DBView) dbo, script);
+                case DROP:
+                    return dropObject(((DBView) dbo).getName(), "VIEW", script);
+                default:
+                    return error(Errors.NotImplemented, "getDDLCommand."+dbo.getClass().getName()+"."+String.valueOf(type));
+            }
+        } 
+        else if (dbo instanceof DBRelation)
+        { // Relation
+            switch (type)
+            {
+                case CREATE:
+                    return createRelation((DBRelation) dbo, script);
+                case DROP:
+                    return dropObject(((DBRelation) dbo).getName(), "CONSTRAINT", script);
+                default:
+                    return error(Errors.NotImplemented, "getDDLCommand."+dbo.getClass().getName()+"."+String.valueOf(type));
+            }
+        } 
+        else if (dbo instanceof DBTableColumn)
+        { // Table Column
+            return alterTable((DBTableColumn) dbo, type, script);
+        } 
+        else
+        { // an invalid argument has been supplied
+            return error(Errors.InvalidArg, dbo, "dbo");
+        }
+    }
+
+    /**
+     * Overridden. Returns a timestamp that is used for record updates created by the database server.
+     * 
+     * @return the current date and time of the database server.
+     */
+    @Override
+    public java.sql.Timestamp getUpdateTimestamp(Connection conn)
+    {
+        // Default implementation
+    	GregorianCalendar cal = new GregorianCalendar();
+    	return new java.sql.Timestamp(cal.getTimeInMillis());
+    }
+
+    /*
+     * return the sql for creating a Database
+     */
+    private boolean createDatabase(DBDatabase db, DBSQLScript script)
+    {
+        // Create all Sequences
+        Iterator<DBTable> seqtabs = db.getTables().iterator();
+        while (seqtabs.hasNext())
+        {
+            DBTable table = seqtabs.next();
+            Iterator<DBColumn> cols = table.getColumns().iterator();
+            while (cols.hasNext())
+            {
+                DBTableColumn c = (DBTableColumn) cols.next();
+                if (c.getDataType() == DataType.AUTOINC)
+                {
+                    createSequence(db, c, script);
+                }
+            }
+        }
+        // Create all Tables
+        Iterator<DBTable> tables = db.getTables().iterator();
+        while (tables.hasNext())
+        {
+            if (!createTable(tables.next(), script))
+                return false;
+        }
+        // Create Relations
+        Iterator<DBRelation> relations = db.getRelations().iterator();
+        while (relations.hasNext())
+        {
+            if (!createRelation(relations.next(), script))
+                return false;
+        }
+        // Create Views
+        Iterator<DBView> views = db.getViews().iterator();
+        while (views.hasNext())
+        {
+            if (!createView(views.next(), script))
+                return false;
+        }
+        // Done
+        return true;
+    }
+
+    /**
+     * Returns true if the sequence has been created successfully.
+     * 
+     * @return true if the sequence has been created successfully
+     */
+    private boolean createSequence(DBDatabase db, DBTableColumn c, DBSQLScript script)
+    {
+        Object defValue = c.getDefaultValue();
+        String seqName = (defValue != null) ? defValue.toString() : c.toString();
+        // createSQL
+        StringBuilder sql = new StringBuilder();
+        sql.append("-- creating sequence for column ");
+        sql.append(c.toString());
+        sql.append(" --\r\n");
+        sql.append("CREATE SEQUENCE ");
+        db.appendQualifiedName(sql, seqName);
+        sql.append(" START WITH 1");
+        // executeDLL
+        return script.addStmt(sql);
+    }
+    
+    /**
+     * Returns true if the table has been created successfully.
+     * 
+     * @return true if the table has been created successfully
+     */
+    private boolean createTable(DBTable t, DBSQLScript script)
+    {
+        StringBuilder sql = new StringBuilder();
+        sql.append("-- creating table ");
+        sql.append(t.getName());
+        sql.append(" --\r\n");
+        sql.append("CREATE TABLE ");
+        sql.append(t.getFullName());
+        sql.append(" (");
+        boolean addSeparator = false;
+        Iterator<DBColumn> columns = t.getColumns().iterator();
+        while (columns.hasNext())
+        {
+            DBTableColumn c = (DBTableColumn) columns.next();
+            sql.append((addSeparator) ? ",\r\n   " : "\r\n   ");
+            if (appendColumnDesc(c, sql)==false)
+                continue; // Ignore and continue;
+            addSeparator = true;
+        }
+        // Primary Key
+        DBIndex pk = t.getPrimaryKey();
+        if (pk != null)
+        { // add the primary key
+            sql.append(",\r\n CONSTRAINT ");
+            sql.append(pk.getName());
+            sql.append(" PRIMARY KEY (");
+            addSeparator = false;
+            // columns
+            DBColumn[] keyColumns = pk.getColumns();
+            for (int i = 0; i < keyColumns.length; i++)
+            {
+                sql.append((addSeparator) ? ", " : "");
+                sql.append(keyColumns[i].getName());
+                addSeparator = true;
+            }
+            sql.append(")");
+        }
+        sql.append(")");
+        // Create the table
+        if (script.addStmt(sql) == false)
+            return false;
+        // Create other Indizes (except primary key)
+        Iterator<DBIndex> indexes = t.getIndexes().iterator();
+        while (indexes.hasNext())
+        {
+            DBIndex idx = indexes.next();
+            if (idx == pk || idx.getType() == DBIndex.PRIMARYKEY)
+                continue;
+
+            // Cretae Index
+            sql.setLength(0);
+            sql.append((idx.getType() == DBIndex.UNIQUE) ? "CREATE UNIQUE INDEX " : "CREATE INDEX ");
+            sql.append(idx.getFullName());
+            sql.append(" ON ");
+            sql.append(t.getFullName());
+            sql.append(" (");
+            addSeparator = false;
+
+            // columns
+            DBColumn[] idxColumns = idx.getColumns();
+            for (int i = 0; i < idxColumns.length; i++)
+            {
+                sql.append((addSeparator) ? ", " : "");
+                sql.append(idxColumns[i].getName());
+                addSeparator = true;
+            }
+            sql.append(")");
+            // Create Index
+            if (script.addStmt(sql) == false)
+                return false;
+        }
+        // done
+        return success();
+    }
+    
+    /**
+     * Appends a table column defintion to a ddl statement
+     * @param c the column which description to append
+     * @param sql the sql builder object
+     * @return true if the column was successfully appended or false otherwise
+     */
+    private boolean appendColumnDesc(DBTableColumn c, StringBuilder sql)
+    {
+        sql.append(c.getName());
+        sql.append(" ");
+        switch (c.getDataType())
+        {
+            case INTEGER:
+                sql.append("INTEGER");
+                break;
+            case AUTOINC:
+                sql.append("INTEGER");
+                break;
+            case TEXT:
+            { // Check fixed or variable length
+                int size = Math.abs((int) c.getSize());
+                if (size == 0)
+                    size = 100;
+                sql.append("VARCHAR(");
+                sql.append(String.valueOf(size));
+                sql.append(")");
+            }
+                break;
+            case CHAR:
+            { // Check fixed or variable length
+                int size = Math.abs((int) c.getSize());
+                if (size == 0)
+                    size = 1;
+                sql.append("CHAR(");
+                sql.append(String.valueOf(size));
+                sql.append(")");
+            }
+                break;
+            case DATE:
+                sql.append("DATE");
+                break;
+            case DATETIME:
+                sql.append("DATE");
+                break;
+            case BOOL:
+                sql.append("BOOLEAN");
+                break;
+            case DOUBLE:
+                sql.append("FLOAT(80)");
+                break;
+            case DECIMAL:
+            {
+                sql.append("DECIMAL(");
+                int prec = (int) c.getSize();
+                int scale = (int) ((c.getSize() - prec) * 10 + 0.5);
+                // sql.append((prec+scale).ToString());sql.append(",");
+                sql.append(String.valueOf(prec));
+                sql.append(",");
+                sql.append(String.valueOf(scale));
+                sql.append(")");
+            }
+                break;
+            case CLOB:
+                sql.append("CLOB");
+                break;
+            case BLOB:
+                sql.append("BLOB");
+                if (c.getSize() > 0)
+                    sql.append(" (" + String.valueOf((long) c.getSize()) + ") ");
+                break;
+            case UNKNOWN:
+                 log.error("Cannot append column of Data-Type 'UNKNOWN'");
+                 return false;
+        }
+        // Default Value
+        if (isDDLColumnDefaults() && c.getDataType()!=DataType.AUTOINC && c.getDefaultValue()!=null)
+        {   sql.append(" DEFAULT ");
+            sql.append(getValueString(c.getDefaultValue(), c.getDataType()));
+        }
+        // Nullable
+        if (c.isRequired())
+            sql.append(" NOT NULL");
+        // Done
+        return true;
+    }
+
+    /**
+     * Returns true if the relation has been created successfully.
+     * 
+     * @return true if the relation has been created successfully
+     */
+    private boolean createRelation(DBRelation r, DBSQLScript script)
+    {
+        DBTable sourceTable = (DBTable) r.getReferences()[0].getSourceColumn().getRowSet();
+        DBTable targetTable = (DBTable) r.getReferences()[0].getTargetColumn().getRowSet();
+
+        StringBuilder sql = new StringBuilder();
+        sql.append("-- creating foreign key constraint ");
+        sql.append(r.getName());
+        sql.append(" --\r\n");
+        sql.append("ALTER TABLE ");
+        sql.append(sourceTable.getFullName());
+        sql.append(" ADD CONSTRAINT ");
+        sql.append(r.getFullName());
+        sql.append(" FOREIGN KEY (");
+        // Source Names
+        boolean addSeparator = false;
+        DBRelation.DBReference[] refs = r.getReferences();
+        for (int i = 0; i < refs.length; i++)
+        {
+            sql.append((addSeparator) ? ", " : "");
+            sql.append(refs[i].getSourceColumn().getName());
+            addSeparator = true;
+        }
+        // References
+        sql.append(") REFERENCES ");
+        sql.append(targetTable.getFullName());
+        sql.append(" (");
+        // Target Names
+        addSeparator = false;
+        for (int i = 0; i < refs.length; i++)
+        {
+            sql.append((addSeparator) ? ", " : "");
+            sql.append(refs[i].getTargetColumn().getName());
+            addSeparator = true;
+        }
+        // done
+        sql.append(")");
+        if (script.addStmt(sql.toString()) == false)
+            return false;
+        // done
+        return success();
+    }
+
+    /**
+     * Creates an alter table dll statement for adding, modifiying or droping a column.
+     * @param col the column which to add, modify or drop
+     * @param type the type of operation to perform
+     * @param buf buffer to which to append the sql statement to
+     * @return true if the statement was successfully appended to the buffer
+     */
+    private boolean alterTable(DBTableColumn col, DBCmdType type, DBSQLScript script)
+    {
+        StringBuilder sql = new StringBuilder();
+        sql.append("ALTER TABLE ");
+        sql.append(col.getRowSet().getName());
+        switch(type)
+        {
+            case CREATE:
+                sql.append(" ADD ");
+                appendColumnDesc(col, sql);
+                break;
+            case ALTER:
+                sql.append(" ALTER COLUMN ");
+                appendColumnDesc(col, sql);
+                break;
+            case DROP:
+                sql.append(" DROP COLUMN ");
+                sql.append(col.getName());
+                break;
+        }
+        // done
+        return script.addStmt(sql.toString());
+    }
+
+    /**
+     * Returns true if the view has been created successfully.
+     * 
+     * @return true if the view has been created successfully
+     */
+    private boolean createView(DBView v, DBSQLScript script)
+    {
+        // Create the Command
+        DBCommandExpr cmd = v.createCommand();
+        if (cmd==null)
+        {   // Check whether Error information is available
+            log.error("No command has been supplied for view " + v.getName());
+            if (v.hasError())
+                return error(v);
+            // No error information available: Use Errors.NotImplemented
+            return error(Errors.NotImplemented, v.getName() + ".createCommand");
+        }
+        // Make sure there is no OrderBy
+        cmd.clearOrderBy();
+
+        // Build String
+        StringBuilder sql = new StringBuilder();
+        sql.append( "CREATE VIEW ");
+        sql.append( v.getName() );
+        sql.append( " (" );
+        boolean addSeparator = false;
+        for(DBColumn c : v.getColumns())
+        {
+            if (addSeparator)
+                sql.append(", ");
+            sql.append(c.getName());
+            // next
+            addSeparator = true;
+        }
+        sql.append(")\r\nAS\r\n");
+        cmd.addSQL( sql, DBExpr.CTX_DEFAULT);
+        // done
+        return script.addStmt(sql.toString());
+    }
+    
+    /**
+     * Returns true if the object has been dropped successfully.
+     * 
+     * @return true if the object has been dropped successfully
+     */
+    private boolean dropObject(String name, String objType, DBSQLScript script)
+    {
+        if (name == null || name.length() == 0)
+            return error(Errors.InvalidArg, name, "name");
+        // Create Drop Statement
+        StringBuilder sql = new StringBuilder();
+        sql.append("DROP ");
+        sql.append(objType);
+        sql.append(" ");
+        sql.append(name);
+        // Done
+        return script.addStmt(sql);
+    }
+
+}
+

Added: incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/hsql/package.html
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/hsql/package.html?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/hsql/package.html (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/hsql/package.html Wed Aug  6 01:47:37 2008
@@ -0,0 +1,14 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<html>
+<head>
+<!--
+/*
+ * ESTEAM Software GmbH, 12.12.2007
+ */
+-->
+</head>
+<body>
+
+This package contains classes necessary to support the HSQLDB database system.
+
+</body></html>
\ No newline at end of file

Added: incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/mysql/DBDatabaseDriverMySQL.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/mysql/DBDatabaseDriverMySQL.java?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/mysql/DBDatabaseDriverMySQL.java (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/mysql/DBDatabaseDriverMySQL.java Wed Aug  6 01:47:37 2008
@@ -0,0 +1,743 @@
+/*
+ * ESTEAM Software GmbH, 14.12.2004
+ */
+package org.apache.empire.db.mysql;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.GregorianCalendar;
+import java.util.Iterator;
+
+import org.apache.empire.commons.Errors;
+import org.apache.empire.commons.StringUtils;
+import org.apache.empire.data.DataType;
+import org.apache.empire.db.DBCmdType;
+import org.apache.empire.db.DBColumn;
+import org.apache.empire.db.DBCommand;
+import org.apache.empire.db.DBCommandExpr;
+import org.apache.empire.db.DBDatabase;
+import org.apache.empire.db.DBDatabaseDriver;
+import org.apache.empire.db.DBDriverFeature;
+import org.apache.empire.db.DBExpr;
+import org.apache.empire.db.DBIndex;
+import org.apache.empire.db.DBObject;
+import org.apache.empire.db.DBRelation;
+import org.apache.empire.db.DBSQLScript;
+import org.apache.empire.db.DBTable;
+import org.apache.empire.db.DBTableColumn;
+import org.apache.empire.db.DBView;
+
+
+/**
+ * This class provides support for the MySQL database system.
+ * 
+ * @author ESTEAM software <A TARGET="esteam" HREF="http://www.esteam.de">www.esteam.de </A>
+ */
+public class DBDatabaseDriverMySQL extends DBDatabaseDriver
+{
+    /**
+     * Defines the MySQL command type.
+     */ 
+    public static class DBCommandMySQL extends DBCommand
+    {
+        public DBCommandMySQL(DBDatabase db)
+        {
+            super(db);
+        }
+    }
+    
+    // Properties
+    private String databaseName = null;
+    private String characterSet = "utf8";
+    // Sequence treatment
+    // When set to 'false' (default) MySQL's autoincrement feature is used.
+    private boolean useSequenceTable = false;
+    private String sequenceTableName = "Sequences";
+    
+    /**
+     * Constructor for the MySQL database driver.<br>
+     */
+    public DBDatabaseDriverMySQL()
+    {
+        // Default Constructor
+    }
+
+    /**
+     * returns the name for the database / schema
+     * @return the database / schema name
+     */
+    public String getDatabaseName()
+    {
+        return databaseName;
+    }
+
+    /**
+     * Sets the name for the database / schema<br>
+     * This names is required for creating a database.<br>
+     * When a name is set, the driver will automatically execute 'USE dbname' when the database is opened.
+     * @param databaseName the name of the database
+     */
+    public void setDatabaseName(String databaseName)
+    {
+        this.databaseName = databaseName;
+    }
+
+    /**
+     * returns whether a sequence table is used for record identiy management.<br>
+     * Default is false. In this case the AutoIncrement feature of MySQL is used.
+     * @return true if a sequence table is used instead of identity columns.
+     */
+    public boolean isUseSequenceTable()
+    {
+        return useSequenceTable;
+    }
+
+    /**
+     * If set to true a special table is used for sequence number generation.<br>
+     * Otherwise the AutoIncrement feature of MySQL is used identiy fields. 
+     * @param useSequenceTable true to use a sequence table or false otherwise.
+     */
+    public void setUseSequenceTable(boolean useSequenceTable)
+    {
+        this.useSequenceTable = useSequenceTable;
+    }
+
+    /**
+     * returns the name of the sequence table
+     * @return the name of the table used for sequence number generation
+     */
+    public String getSequenceTableName()
+    {
+        return sequenceTableName;
+    }
+
+    /**
+     * Sets the name of the sequence table.
+     * Only applicable if useSequenceTable is set to true.
+     * @param sequenceTableName the name of the table used for sequence number generation
+     */
+    public void setSequenceTableName(String sequenceTableName)
+    {
+        this.sequenceTableName = sequenceTableName;
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.apache.empire.db.DBDatabaseDriver#openDatabase(org.apache.empire.db.DBDatabase, java.sql.Connection)
+     */
+    @Override
+    public boolean attachDatabase(DBDatabase db, Connection conn)
+    {
+        // Prepare
+        try
+        {   // Set Database
+            if (StringUtils.isValid(databaseName))
+                executeSQL("USE " + databaseName, null, conn);
+            // Sequence Table
+            if (useSequenceTable && db.getTable(sequenceTableName)==null)
+                new DBSeqTable(sequenceTableName, db);
+            // call Base implementation
+            return super.attachDatabase(db, conn);
+            
+        } catch (SQLException e)
+        {
+            return error(e);
+        }
+    }
+
+    /**
+     * Creates a new MySQL command object.
+     * 
+     * @return the new DBCommandMySQL object
+     */
+    @Override
+    public DBCommand createCommand(DBDatabase db)
+    {
+        if (db == null)
+            return null;
+        // create command object
+        return new DBCommandMySQL(db);
+    }
+
+    /**
+     * Returns whether or not a particular feature is supported by this driver
+     * @param type type of requrested feature. @see DBDriverFeature
+     * @return true if the features is supported or false otherwise
+     */
+    @Override
+    public boolean isSupported(DBDriverFeature type)
+    {
+        switch (type)
+        {   // return support info 
+            case CREATE_SCHEMA: return true;
+            case SEQUENCES:     return useSequenceTable;    
+        }
+        return false;
+    }
+    
+    /**
+     * Gets an sql phrase template for this database system.<br>
+     * @see DBDatabaseDriver#getSQLPhrase(int)
+     * @return the phrase template
+     */
+    @Override
+    public String getSQLPhrase(int phrase)
+    {
+        switch (phrase)
+        {
+            // sql-phrases
+            case SQL_NULL_VALUE:              return "null";
+            case SQL_RENAME_COLUMN:           return " AS ";
+            case SQL_PARAMETER:               return " ? ";
+            case SQL_CONCAT_EXPR:             return "concat(?, {0})";
+            case SQL_RENAME_TABLE:            return " ";
+            case SQL_DATABASE_LINK:           return "@";
+            // data types
+            case SQL_BOOLEAN_TRUE:            return "1";
+            case SQL_BOOLEAN_FALSE:           return "0";
+            case SQL_CURRENT_DATE:            return "CURRENT_DATE()";
+            case SQL_DATE_PATTERN:            return "yyyy-MM-dd";
+            case SQL_DATE_TEMPLATE:           return "'{0}'";
+            case SQL_CURRENT_DATETIME:        return "NOW()";
+            case SQL_DATETIME_PATTERN:        return "yyyy-MM-dd HH:mm:ss";
+            case SQL_DATETIME_TEMPLATE:       return "'{0}'";
+            // functions
+            case SQL_FUNC_COALESCE:           return "coalesce(?, {0})";
+            case SQL_FUNC_SUBSTRING:          return "substring(?, {0})";
+            case SQL_FUNC_SUBSTRINGEX:        return "substring(?, {0}, {1})";
+            case SQL_FUNC_REPLACE:            return "replace(?, {0}, {1})";
+            case SQL_FUNC_REVERSE:            return "reverse(?)"; 
+            case SQL_FUNC_STRINDEX:           return "instr(?, {0})"; 
+            case SQL_FUNC_STRINDEXFROM:       return "locate({0}, ?, {1})"; 
+            case SQL_FUNC_LENGTH:             return "length(?)";
+            case SQL_FUNC_UPPER:              return "upper(?)";
+            case SQL_FUNC_LOWER:              return "lcase(?)";
+            case SQL_FUNC_TRIM:               return "trim(?)";
+            case SQL_FUNC_LTRIM:              return "ltrim(?)";
+            case SQL_FUNC_RTRIM:              return "rtrim(?)";
+            case SQL_FUNC_ESCAPE:             return "? escape '{0}'";
+            // Numeric
+            case SQL_FUNC_ABS:                return "abs(?)";
+            case SQL_FUNC_ROUND:              return "round(?,{0})";
+            case SQL_FUNC_TRUNC:              return "truncate(?,{0})";
+            case SQL_FUNC_CEILING:            return "ceiling(?)";
+            case SQL_FUNC_FLOOR:              return "floor(?)";
+            // Date
+            case SQL_FUNC_DAY:                return "day(?)";
+            case SQL_FUNC_MONTH:              return "month(?)";
+            case SQL_FUNC_YEAR:               return "year(?)";
+            // Aggregation
+            case SQL_FUNC_SUM:                return "sum(?)";
+            case SQL_FUNC_COUNT:              return "count(?)";
+            case SQL_FUNC_MAX:                return "max(?)";
+            case SQL_FUNC_MIN:                return "min(?)";
+            case SQL_FUNC_AVG:                return "avg(?)";
+            // Others
+            case SQL_FUNC_DECODE:             return "case ? {0} end";
+            case SQL_FUNC_DECODE_SEP:         return " ";
+            case SQL_FUNC_DECODE_PART:        return "when {0} then {1}";
+            case SQL_FUNC_DECODE_ELSE:        return "else {0}";
+            // Not defined
+            default:
+                log.error("SQL phrase " + String.valueOf(phrase) + " is not defined!");
+                return "?";
+        }
+    }
+
+    /**
+     * @see DBDatabaseDriver#getConvertPhrase(DataType, DataType, Object)
+     */
+    @Override
+    public String getConvertPhrase(DataType destType, DataType srcType, Object format)
+    {
+        switch(destType)
+        {
+           case BOOL:      return "CAST(? AS UNSIGNED)";
+           case INTEGER:   return "CAST(? AS SIGNED)";
+           case DECIMAL:   return "CAST(? AS DECIMAL)";
+           case DOUBLE:    return "CAST(? AS DECIMAL)";
+           case DATE:      return "CAST(? AS DATE)";
+           case DATETIME:  return "CAST(? AS DATETIME)";
+           // Convert to text
+           case TEXT:
+                return "CAST(? AS CHAR)";
+           case BLOB:
+                return "CAST(? AS BLOB)";
+           // Unknown Type                                       
+           default:
+                log.error("getConvertPhrase: unknown type (" + String.valueOf(destType));
+                return "?";
+        }
+    }
+    
+    /**
+     * @see DBDatabaseDriver#getNextSequenceValue(DBDatabase, String, int, Connection)
+     */
+    @Override
+    public Object getNextSequenceValue(DBDatabase db, String seqName, int minValue, Connection conn)
+    {   //Use Oracle Sequences
+        if (useSequenceTable)
+        {   // Use a sequence Table to generate Sequences
+            DBTable t = db.getTable(sequenceTableName);
+            return ((DBSeqTable)t).getNextValue(seqName, minValue, conn);
+        }
+        else
+        {   // Post Detection
+            return null;
+        }
+    }
+    
+    @Override
+    public Object getPostInsertAutoIncValue(DBDatabase db, Connection conn)
+    {
+        return db.querySingleInt("SELECT LAST_INSERT_ID()", conn);
+    }
+
+    /**
+     * @see DBDatabaseDriver#getDDLScript(DBCmdType, DBObject, DBSQLScript)  
+     */
+    @Override
+    public boolean getDDLScript(DBCmdType type, DBObject dbo, DBSQLScript script)
+    {
+        // The Object's database must be attached to this driver
+        if (dbo==null || dbo.getDatabase().getDriver()!=this)
+            return error(Errors.InvalidArg, dbo, "dbo");
+        // Check Type of object
+        if (dbo instanceof DBDatabase)
+        { // Database
+            switch (type)
+            {
+                case CREATE:
+                    return createDatabase((DBDatabase) dbo, script, true);
+                case DROP:
+                    return dropObject(((DBDatabase) dbo).getSchema(), "DATABASE", script);
+                default:
+                    return error(Errors.NotImplemented, "getDDLScript."+dbo.getClass().getName()+"."+String.valueOf(type));
+            }
+        } 
+        else if (dbo instanceof DBTable)
+        { // Table
+            switch (type)
+            {
+                case CREATE:
+                    return createTable((DBTable) dbo, script);
+                case DROP:
+                    return dropObject(((DBTable) dbo).getName(), "TABLE", script);
+                default:
+                    return error(Errors.NotImplemented, "getDDLCommand."+dbo.getClass().getName()+"."+String.valueOf(type));
+            }
+        } 
+        else if (dbo instanceof DBView)
+        { // View
+            switch (type)
+            {
+                case CREATE:
+                    return createView((DBView) dbo, script);
+                case DROP:
+                    return dropObject(((DBView) dbo).getName(), "VIEW", script);
+                default:
+                    return error(Errors.NotImplemented, "getDDLCommand."+dbo.getClass().getName()+"."+String.valueOf(type));
+            }
+        } 
+        else if (dbo instanceof DBRelation)
+        { // Relation
+            switch (type)
+            {
+                case CREATE:
+                    return createRelation((DBRelation) dbo, script);
+                case DROP:
+                    return dropObject(((DBRelation) dbo).getName(), "CONSTRAINT", script);
+                default:
+                    return error(Errors.NotImplemented, "getDDLCommand."+dbo.getClass().getName()+"."+String.valueOf(type));
+            }
+        } 
+        else if (dbo instanceof DBTableColumn)
+        { // Table Column
+            return alterTable((DBTableColumn) dbo, type, script);
+        } 
+        else
+        { // an invalid argument has been supplied
+            return error(Errors.InvalidArg, dbo, "dbo");
+        }
+    }
+
+    /**
+     * Overridden. Returns a timestamp that is used for record updates created by the database server.
+     * 
+     * @return the current date and time of the database server.
+     */
+    @Override
+    public java.sql.Timestamp getUpdateTimestamp(Connection conn)
+    {
+        // Default implementation
+        GregorianCalendar cal = new GregorianCalendar();
+        return new java.sql.Timestamp(cal.getTimeInMillis());
+    }
+
+    /*
+     * return the sql for creating a Database
+     */
+    private boolean createDatabase(DBDatabase db, DBSQLScript script, boolean createSchema)
+    {
+        // User Master to create Database
+        if (createSchema)
+        {   // check database Name
+            if (StringUtils.isValid(databaseName)==false)
+                return error(Errors.InvalidProperty, "databaseName");
+            // Create Database
+            script.addStmt("CREATE DATABASE " + databaseName + " CHARACTER SET " + characterSet);
+            script.addStmt("USE " + databaseName);
+            // appendDDLStmt(db, "SET DATEFORMAT ymd", buf);
+            // Sequence Table
+            if (useSequenceTable && db.getTable(sequenceTableName)==null)
+                new DBSeqTable(sequenceTableName, db);
+        }
+        // Create all Tables
+        Iterator<DBTable> tables = db.getTables().iterator();
+        while (tables.hasNext())
+        {
+            if (!createTable(tables.next(), script))
+                return false;
+        }
+        // Create Relations
+        Iterator<DBRelation> relations = db.getRelations().iterator();
+        while (relations.hasNext())
+        {
+            if (!createRelation(relations.next(), script))
+                return false;
+        }
+        // Create Views
+        Iterator<DBView> views = db.getViews().iterator();
+        while (views.hasNext())
+        {
+            if (!createView(views.next(), script))
+                return false;
+        }
+        // Done
+        return true;
+    }
+    
+    /**
+     * Returns true if the table has been created successfully.
+     * 
+     * @return true if the table has been created successfully
+     */
+    private boolean createTable(DBTable t, DBSQLScript script)
+    {
+        StringBuilder sql = new StringBuilder();
+        sql.append("-- creating table ");
+        sql.append(t.getName());
+        sql.append(" --\r\n");
+        sql.append("CREATE TABLE ");
+        sql.append(t.getFullName());
+        sql.append(" (");
+        boolean addSeparator = false;
+        Iterator<DBColumn> columns = t.getColumns().iterator();
+        while (columns.hasNext())
+        {
+            DBTableColumn c = (DBTableColumn) columns.next();
+            sql.append((addSeparator) ? ",\r\n   " : "\r\n   ");
+            if (appendColumnDesc(c, sql)==false)
+                continue; // Ignore and continue;
+            addSeparator = true;
+        }
+        // Primary Key
+        DBIndex pk = t.getPrimaryKey();
+        if (pk != null)
+        { // add the primary key
+            sql.append(", PRIMARY KEY (");
+            addSeparator = false;
+            // columns
+            DBColumn[] keyColumns = pk.getColumns();
+            for (int i = 0; i < keyColumns.length; i++)
+            {
+                sql.append((addSeparator) ? ", " : "");
+                sql.append(keyColumns[i].getName());
+                addSeparator = true;
+            }
+            sql.append(")");
+        }
+        sql.append(")");
+        // Comment?
+        String comment = t.getComment();
+        if (StringUtils.isValid(comment))
+        {   // Add the table comment
+            sql.append(" COMMENT = '");
+            sql.append(comment);
+            sql.append("'");
+        }
+        // Create the table
+        if (script.addStmt(sql) == false)
+            return false;
+        // Create other Indizes (except primary key)
+        Iterator<DBIndex> indexes = t.getIndexes().iterator();
+        while (indexes.hasNext())
+        {
+            DBIndex idx = indexes.next();
+            if (idx == pk || idx.getType() == DBIndex.PRIMARYKEY)
+                continue;
+
+            // Cretae Index
+            sql.setLength(0);
+            sql.append((idx.getType() == DBIndex.UNIQUE) ? "CREATE UNIQUE INDEX " : "CREATE INDEX ");
+            sql.append(idx.getFullName());
+            sql.append(" ON ");
+            sql.append(t.getFullName());
+            sql.append(" (");
+            addSeparator = false;
+
+            // columns
+            DBColumn[] idxColumns = idx.getColumns();
+            for (int i = 0; i < idxColumns.length; i++)
+            {
+                sql.append((addSeparator) ? ", " : "");
+                sql.append(idxColumns[i].getName());
+                addSeparator = true;
+            }
+            sql.append(")");
+            // Create Index
+            if (script.addStmt(sql) == false)
+                return false;
+        }
+        // done
+        return success();
+    }
+    
+    /**
+     * Appends a table column defintion to a ddl statement
+     * @param c the column which description to append
+     * @param sql the sql builder object
+     * @return true if the column was successfully appended or false otherwise
+     */
+    private boolean appendColumnDesc(DBTableColumn c, StringBuilder sql)
+    {
+        sql.append(c.getName());
+        sql.append(" ");
+        switch (c.getDataType())
+        {
+            case INTEGER:
+            { // Integer type
+                sql.append("INT");
+                int size = (int)c.getSize();
+                if (size>0)
+                {   // Set Integer length
+                    sql.append("(");
+                    sql.append(String.valueOf(size));
+                    sql.append(")");
+                }
+                break;
+            }    
+            case AUTOINC:
+            { // Auto increment
+                sql.append("INT");
+                if (useSequenceTable==false)
+                    sql.append(" AUTO_INCREMENT");
+                break;
+            }    
+            case TEXT:
+            { // Check fixed or variable length
+                int size = Math.abs((int) c.getSize());
+                if (size == 0)
+                    size = 100;
+                sql.append("VARCHAR(");
+                sql.append(String.valueOf(size));
+                sql.append(")");
+            }
+                break;
+            case CHAR:
+            { // Check fixed or variable length
+                int size = Math.abs((int) c.getSize());
+                if (size == 0)
+                    size = 1;
+                sql.append("CHAR(");
+                sql.append(String.valueOf(size));
+                sql.append(")");
+            }
+                break;
+            case DATE:
+                sql.append("DATE");
+                break;
+            case DATETIME:
+                sql.append("DATETIME");
+                break;
+            case BOOL:
+                sql.append("BIT");
+                break;
+            case DOUBLE:
+                sql.append("DOUBLE");
+                break;
+            case DECIMAL:
+            { // Decimal
+                sql.append("DECIMAL(");
+                int prec = (int) c.getSize();
+                int scale = (int) ((c.getSize() - prec) * 10 + 0.5);
+                // sql.append((prec+scale).ToString());sql.append(",");
+                sql.append(String.valueOf(prec));
+                sql.append(",");
+                sql.append(String.valueOf(scale));
+                sql.append(")");
+            }
+                break;
+            case CLOB:
+                sql.append("LONGTEXT");
+                break;
+            case BLOB:
+                sql.append("BLOB");
+                if (c.getSize() > 0)
+                    sql.append(" (" + String.valueOf((long) c.getSize()) + ") ");
+                break;
+            case UNKNOWN:
+                 log.error("Cannot append column of Data-Type 'UNKNOWN'");
+                 return false;
+        }
+        // Default Value
+        if (isDDLColumnDefaults() && c.getDataType()!=DataType.AUTOINC && c.getDefaultValue()!=null)
+        {   sql.append(" DEFAULT ");
+            sql.append(getValueString(c.getDefaultValue(), c.getDataType()));
+        }
+        // Nullable
+        if (c.isRequired())
+            sql.append(" NOT NULL");
+        // Done
+        return true;
+    }
+
+    /**
+     * Returns true if the relation has been created successfully.
+     * 
+     * @return true if the relation has been created successfully
+     */
+    private boolean createRelation(DBRelation r, DBSQLScript script)
+    {
+        DBTable sourceTable = (DBTable) r.getReferences()[0].getSourceColumn().getRowSet();
+        DBTable targetTable = (DBTable) r.getReferences()[0].getTargetColumn().getRowSet();
+
+        StringBuilder sql = new StringBuilder();
+        sql.append("-- creating foreign key constraint ");
+        sql.append(r.getName());
+        sql.append(" --\r\n");
+        sql.append("ALTER TABLE ");
+        sql.append(sourceTable.getFullName());
+        sql.append(" ADD CONSTRAINT ");
+        sql.append(r.getFullName());
+        sql.append(" FOREIGN KEY (");
+        // Source Names
+        boolean addSeparator = false;
+        DBRelation.DBReference[] refs = r.getReferences();
+        for (int i = 0; i < refs.length; i++)
+        {
+            sql.append((addSeparator) ? ", " : "");
+            sql.append(refs[i].getSourceColumn().getName());
+            addSeparator = true;
+        }
+        // References
+        sql.append(") REFERENCES ");
+        sql.append(targetTable.getFullName());
+        sql.append(" (");
+        // Target Names
+        addSeparator = false;
+        for (int i = 0; i < refs.length; i++)
+        {
+            sql.append((addSeparator) ? ", " : "");
+            sql.append(refs[i].getTargetColumn().getName());
+            addSeparator = true;
+        }
+        // done
+        sql.append(")");
+        if (script.addStmt(sql) == false)
+            return false;
+        // done
+        return success();
+    }
+
+    /**
+     * Creates an alter table dll statement for adding, modifiying or droping a column.
+     * @param col the column which to add, modify or drop
+     * @param type the type of operation to perform
+     * @param buf buffer to which to append the sql statement to
+     * @return true if the statement was successfully appended to the buffer
+     */
+    private boolean alterTable(DBTableColumn col, DBCmdType type, DBSQLScript script)
+    {
+        StringBuilder sql = new StringBuilder();
+        sql.append("ALTER TABLE ");
+        sql.append(col.getRowSet().getName());
+        switch(type)
+        {
+            case CREATE:
+                sql.append(" ADD ");
+                appendColumnDesc(col, sql);
+                break;
+            case ALTER:
+                sql.append(" MODIFY ");
+                appendColumnDesc(col, sql);
+                break;
+            case DROP:
+                sql.append(" DROP COLUMN ");
+                sql.append(col.getName());
+                break;
+        }
+        // done
+        return script.addStmt(sql);
+    }
+
+    /**
+     * Returns true if the view has been created successfully.
+     * 
+     * @return true if the view has been created successfully
+     */
+    private boolean createView(DBView v, DBSQLScript script)
+    {
+        // Create the Command
+        DBCommandExpr cmd = v.createCommand();
+        if (cmd==null)
+        {   // Check whether Error information is available
+            log.error("No command has been supplied for view " + v.getName());
+            if (v.hasError())
+                return error(v);
+            // No error information available: Use Errors.NotImplemented
+            return error(Errors.NotImplemented, v.getName() + ".createCommand");
+        }
+        // Make sure there is no OrderBy
+        cmd.clearOrderBy();
+
+        // Build String
+        StringBuilder sql = new StringBuilder();
+        sql.append( "CREATE VIEW ");
+        sql.append( v.getName() );
+        sql.append( " (" );
+        boolean addSeparator = false;
+        for(DBColumn c : v.getColumns())
+        {
+            if (addSeparator)
+                sql.append(", ");
+            sql.append(c.getName());
+            // next
+            addSeparator = true;
+        }
+        sql.append(")\r\nAS\r\n");
+        cmd.addSQL( sql, DBExpr.CTX_DEFAULT);
+        // done
+        return script.addStmt(sql.toString());
+    }
+    
+    /**
+     * Returns true if the object has been dropped successfully.
+     * 
+     * @return true if the object has been dropped successfully
+     */
+    private boolean dropObject(String name, String objType, DBSQLScript script)
+    {
+        if (name == null || name.length() == 0)
+            return error(Errors.InvalidArg, name, "name");
+        // Create Drop Statement
+        StringBuilder sql = new StringBuilder();
+        sql.append("DROP ");
+        sql.append(objType);
+        sql.append(" ");
+        sql.append(name);
+        return script.addStmt(sql);
+    }
+
+}

Added: incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/mysql/package.html
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/mysql/package.html?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/mysql/package.html (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/mysql/package.html Wed Aug  6 01:47:37 2008
@@ -0,0 +1,14 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<html>
+<head>
+<!--
+/*
+ * ESTEAM Software GmbH, 12.12.2007
+ */
+-->
+</head>
+<body>
+
+This package contains classes necessary to support the MySQL database system.
+
+</body></html>
\ No newline at end of file

Added: incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/oracle/DBCommandOracle.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/oracle/DBCommandOracle.java?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/oracle/DBCommandOracle.java (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/oracle/DBCommandOracle.java Wed Aug  6 01:47:37 2008
@@ -0,0 +1,158 @@
+/*
+ * ESTEAM Software GmbH
+ */
+package org.apache.empire.db.oracle;
+
+// Imports
+import org.apache.empire.commons.Errors;
+import org.apache.empire.db.DBCommand;
+import org.apache.empire.db.DBDatabase;
+import org.apache.empire.db.DBTable;
+import org.apache.empire.db.expr.compare.DBCompareExpr;
+
+/**
+ * This class handles the special features of an oracle database.
+ * 
+ * @author ESTEAM software <A TARGET="esteam" HREF="http://www.esteam.de">www.esteam.de </A>
+ */
+public class DBCommandOracle extends DBCommand
+{
+    // Oracle Connect By / Start With
+    protected DBCompareExpr connectBy  = null;
+    protected DBCompareExpr startWith  = null;
+    // optimizerHint
+    protected String        optimizerHint  = null;
+
+    /**
+     * Constructs an oracle command object.
+     * 
+     * @see org.apache.empire.db.DBCommand
+     * 
+     * @param db the oracle database object this command belongs to
+     */
+    public DBCommandOracle(DBDatabase db)
+    {
+        super(db);
+    }
+
+    public String getOptimizerHint()
+    {
+        return optimizerHint;
+    }
+
+    public void setOptimizerHint(String optimizerHint)
+    {
+        this.optimizerHint = optimizerHint;
+    }
+
+    /**
+     * @see DBCommand#clear()
+     */
+    @Override
+    public void clear()
+    {
+        super.clear();
+        // Clear oracle specific properties
+        clearConnectBy();
+        optimizerHint = null;
+    }
+
+    /**
+     * Clears the connectBy Expression.
+     */
+    public void clearConnectBy()
+    {
+        connectBy = startWith = null;
+    }
+
+    public void connectByPrior(DBCompareExpr expr)
+    {
+        this.connectBy = expr;
+    }
+
+    public void startWith(DBCompareExpr expr)
+    {
+        this.startWith = expr;
+    }
+
+    /**
+     * Creates the SQL statement the special characteristics of
+     * the Oracle database are supported.
+     * 
+     * @param buf the SQL statment
+     * @return true if the creation was successful
+     */
+    @Override
+    public boolean getSelect(StringBuilder buf)
+    {
+        if (select == null)
+            return error(Errors.ObjectNotValid, getClass().getName()); // invalid!
+        // Prepares statement
+        buf.append("SELECT ");
+        if (optimizerHint != null)
+        {
+            // Append an optimizer hint to the select statement e.g. SELECT /*+ RULE */
+            buf.append("/*+ ").append(optimizerHint).append(" */ ");
+        }
+        if (selectDistinct)
+            buf.append("DISTINCT ");
+        // Add Select Expressions
+        addListExpr(buf, select, CTX_ALL, ", ");
+        // Join
+        addFrom(buf);
+        // Where
+        addWhere(buf);
+        // Connect By
+        if (connectBy != null)
+        {   // Add 'Connect By Prior' Expression
+        	buf.append("\r\nCONNECT BY PRIOR ");
+            connectBy.addSQL(buf, CTX_DEFAULT | CTX_NOPARENTHESES);
+            // Start With
+            if (startWith != null)
+            {	// Add 'Start With' Expression
+            	buf.append("\r\nSTART WITH ");
+                startWith.addSQL(buf, CTX_DEFAULT);
+            }
+        }
+        // Grouping
+        addGrouping(buf);
+        // Order
+        if (orderBy != null)
+        { // Having
+            if (connectBy != null)
+                buf.append("\r\nORDER SIBLINGS BY ");
+            else
+                buf.append("\r\nORDER BY ");
+            // Add List of Order By Expressions
+            addListExpr(buf, orderBy, CTX_DEFAULT, ", ");
+        }
+        // Done
+        return success();
+    }
+    
+    /**
+     * Creates the delete SQL-Command.
+     * 
+     * @return the delete SQL-Command
+     */
+    @Override
+    public String getDelete(DBTable table)
+    {
+        StringBuilder buf = new StringBuilder("DELETE ");
+        if (optimizerHint != null)
+        {   // Append an optimizer hint to the select statement e.g. SELECT /*+ RULE */
+            buf.append("/*+ ").append(optimizerHint).append(" */ ");
+        }
+        buf.append("FROM ");
+        table.addSQL(buf, CTX_FULLNAME);
+        // Set Expressions
+        if (where != null || having != null)
+        { // add where condition
+            buf.append("\r\nWHERE ");
+            if (where != null)
+                addListExpr(buf, where, CTX_NAME|CTX_VALUE, " AND ");
+        }
+        return buf.toString();
+    }
+
+}
\ No newline at end of file



Mime
View raw message