empire-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From doeb...@apache.org
Subject svn commit: r683173 [3/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/DBColumn.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/DBColumn.java?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/DBColumn.java (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/DBColumn.java Wed Aug  6 01:47:37 2008
@@ -0,0 +1,234 @@
+/*
+ * ESTEAM Software GmbH
+ */
+package org.apache.empire.db;
+
+// Java
+import java.util.Set;
+
+import org.apache.empire.commons.Options;
+import org.apache.empire.data.Column;
+import org.apache.empire.db.expr.set.DBSetExpr;
+import org.w3c.dom.Element;
+
+
+/**
+ * This is the base class for all database columns that have a physical representation.
+ * i.e. either table or view columns (DBTableColumn oder DBViewColumn)
+ * <p>
+ * The column object describes a database column and thus provides metadata.
+ * Other non data model specific metadata may be added through attributes.
+ *
+ * @see org.apache.empire.db.DBTableColumn
+ * @see org.apache.empire.db.DBView.DBViewColumn
+ *
+ * @author ESTEAM software <A TARGET="esteam" HREF="http://www.esteam.de">www.esteam.de </A>
+ */
+public abstract class DBColumn extends DBColumnExpr
+    implements Column
+{
+    // Predefined column attributes
+    public static final String DBCOLATTR_MANDATORY = "mandatory";
+    public static final String DBCOLATTR_READONLY  = "readonly";
+
+    // basic data
+    protected final DBRowSet   rowset;
+    protected final String     name;
+    protected String           comment;
+
+    /**
+     * Constructs a DBColumn object and set the specified parameters to this object.
+     *
+     * @param rowset the rowset (i.e. Table or View) that this column belongs to
+     * @param name the column name
+     */
+    protected DBColumn(DBRowSet rowset, String name)
+    {
+        this.rowset = rowset;
+        this.name = name;
+        this.comment = null;
+    }
+
+    /**
+     * Returns the size of the column.
+     *
+     * @return Returns the size of the column
+     */
+    public abstract double getSize();
+
+    /**
+     * Returns true if the column is required.
+     *
+     * @return Returns true if the column is required
+     */
+    public abstract boolean isRequired();
+
+    /**
+     * Returns true if the column is read-only.
+     *
+     * @return Returns true if the column is read-only
+     */
+    public abstract boolean isReadOnly();
+
+
+    public abstract boolean checkValue(Object value);
+
+    @Override
+    public abstract Element addXml(Element parent, long flags);
+
+    /**
+     * @return the current DBDatabase object
+     */
+    @Override
+    public DBDatabase getDatabase()
+    {
+        return (rowset!=null ? rowset.getDatabase() : null);
+    }
+
+    /**
+     * @see org.apache.empire.db.DBExpr#addReferencedColumns(Set)
+     */
+    @Override
+    public void addReferencedColumns(Set<DBColumn> list)
+    {
+        list.add(this);
+    }
+
+    /**
+     * Adds the colunm name to the SQL-Command. <br>
+     * This can be either a qualified or unqualified name depending on the context.
+     *
+     * @param buf the SQL statment
+     * @param context the current SQL-Command context
+     */
+    @Override
+    public void addSQL(StringBuilder buf, long context)
+    { // Alias verwenden wenn nicht select
+
+        if ((context & CTX_FULLNAME) != 0 && rowset != null)
+        { // Fully Qualified Name
+            buf.append(rowset.getAlias());
+            buf.append(".");
+        }
+        buf.append(name);
+    }
+
+    /**
+     * Returns this object.
+     *
+     * @return this object
+     */
+    @Override
+    public DBColumn getUpdateColumn()
+    {
+        return this;
+    }
+
+    /**
+     * Always returns false since DBColumns cannot be aggregates.
+     *
+     * @return false
+     */
+    @Override
+    public boolean isAggregate()
+    {
+        return false;
+    }
+
+    /**
+     * Returns DBTable, DBQuery or DBView object.
+     *
+     * @return the DBTable, DBQuery or DBView object
+     */
+    public DBRowSet getRowSet()
+    {
+        return rowset;
+    }
+
+    /**
+     * Returns the column name.
+     *
+     * @return the column name
+     */
+    @Override
+    public String getName()
+    {
+        return name;
+    }
+
+    /**
+     * Returns the full qualified column name.
+     *
+     * @return the full qualified column name
+     */
+    public String getFullName()
+    {
+        if (rowset==null)
+            return name;
+        return rowset.getFullName()+"."+name;
+    }
+
+    /**
+     *  @see DBColumnExpr#getAttribute(String)
+     */
+    @Override
+    public Object getAttribute(String name)
+    {
+        return (attributes != null ? attributes.get(name) : null);
+    }
+
+    /**
+     *  @see DBColumnExpr#getOptions()
+     */
+    @Override
+    public Options getOptions()
+    {
+        return options;
+    }
+
+    /**
+     * Creates and returns a new DBSetExpr object.
+     *
+     * @see org.apache.empire.db.expr.set.DBSetExpr
+     * @param value the Object value
+     * @return the new DBSetExpr object
+     */
+    public DBSetExpr to(Object value)
+    {
+        return new DBSetExpr(this, value);
+    }
+
+    /**
+     * Override the toString method.
+     *
+     * @return the table name and the column name (e.g. CUSTOMER.ID)
+     */
+    @Override
+    public String toString()
+    {
+        if (rowset==null)
+            return name;
+        return rowset.getName()+"."+name;
+    }
+
+    /**
+     * Returns a comment describing the column in the data scheme.
+     *
+     * @return Returns the comment.
+     */
+    public String getComment()
+    {
+        return comment;
+    }
+
+    /**
+     * Sets a comment describing the current column.
+     *
+     * @param comment the column comment
+     */
+    public void setComment(String comment)
+    {
+        this.comment = comment;
+    }
+
+}
\ No newline at end of file

Added: incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/DBColumnExpr.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/DBColumnExpr.java?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/DBColumnExpr.java (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/DBColumnExpr.java Wed Aug  6 01:47:37 2008
@@ -0,0 +1,1064 @@
+/*
+ * ESTEAM Software GmbH
+ */
+package org.apache.empire.db;
+
+// java
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import org.apache.empire.commons.Attributes;
+import org.apache.empire.commons.OptionEntry;
+import org.apache.empire.commons.Options;
+import org.apache.empire.commons.StringUtils;
+import org.apache.empire.data.Column;
+import org.apache.empire.data.ColumnExpr;
+import org.apache.empire.data.DataType;
+import org.apache.empire.db.expr.column.DBAliasExpr;
+import org.apache.empire.db.expr.column.DBCalcExpr;
+import org.apache.empire.db.expr.column.DBConcatExpr;
+import org.apache.empire.db.expr.column.DBFuncExpr;
+import org.apache.empire.db.expr.column.DBValueExpr;
+import org.apache.empire.db.expr.compare.DBCompareColExpr;
+import org.w3c.dom.Element;
+
+
+/**
+ * This class is the base class for building the SQL-Commands
+ * <P>
+ * 
+ * @author ESTEAM software <A TARGET="esteam" HREF="http://www.esteam.de">www.esteam.de </A>
+ */
+public abstract class DBColumnExpr extends DBExpr
+    implements ColumnExpr
+{
+    // Predefined column expression attributes
+    public static final String DBCOLATTR_TITLE     = "title";
+    public static final String DBCOLATTR_TYPE      = "type";
+
+    // Properties
+    protected Attributes  attributes = null;
+    protected Options     options = null;
+    protected String      beanPropertyName = null;
+
+    /**
+     * Returns the data type of this column expression.
+     * @see org.apache.empire.data.DataType
+     *
+     * @return the expressions data type
+     */
+    public abstract DataType getDataType();
+
+    /**
+     * Returns the column name for this column epxression.
+     * The name must contain only alphanumerical charaters and the underscore.
+     * For SQL functions this name may be generated. However subsequent calls to this function 
+     * for the same object instance must return the same string.  
+     *
+     * @return the column name
+     */
+    public abstract String getName();
+    
+    /**
+     * Indicates wheter this function is an aggregate (sum, min, max, avg, ...) or not
+     * @return true if the column expression represents an aggregate
+     */
+    public abstract boolean isAggregate();
+
+    /**
+     * Returns the underlying physical column which may be used for updates.
+     * For functions involving none or more than one physical column this function returns null.
+     * @return the column to be used for updates if any.
+     */
+    public abstract DBColumn getUpdateColumn();
+
+    /**
+     * Add a description of this column with relevant metadata 
+     * to the supplied parent XML Element.
+     * 
+     * @param parent the parent element to which to append the column description
+     * @param flags currenly not used
+     * @return the newly created child element
+     */
+    public abstract Element addXml(Element parent, long flags);
+
+    /**
+     * Returns the value of a column attribute.
+     * Column attributes are used to provide metadata for a column.
+     * 
+     * @param name the attribute name
+     * @return value of the attribute if it exists or null otherwise
+     */
+    public synchronized Object getAttribute(String name)
+    {
+        if (attributes != null && attributes.containsKey(name))
+            return attributes.get(name);
+        // Otherwise ask expression
+        DBColumn column = getUpdateColumn();
+        if (column==null || column==this)
+            return null;
+        return column.getAttribute(name);
+    }
+
+    /**
+     * Sets the value of a column attribute.
+     * 
+     * @param name the attribute name
+     * @param value the value of the attribute
+     */
+    public synchronized void setAttribute(String name, Object value)
+    {
+        if (attributes== null)
+            attributes = new Attributes();
+        attributes.set(name, value);
+    }
+
+    /**
+     * Returns the list of options for this column
+     * containing all possbile field values.
+     * 
+     * @return the list of options
+     */
+    public synchronized Options getOptions()
+    {
+        if (options != null)
+            return options;
+        // Otherwise ask expression
+        DBColumn column = getUpdateColumn();
+        if (column==null || column==this)
+            return null;
+        return column.getOptions();
+    }
+
+    /**
+     * Sets the options for this column indicating all valid values.
+     * 
+     * @param options the list of options
+     */
+    public synchronized void setOptions(Options options)
+    {
+        this.options = options;
+    }
+
+    /**
+     * Returns the title attribute.
+     * 
+     * @return the column title
+     */
+    public final String getTitle()
+    { 
+        Object title = getAttribute(DBCOLATTR_TITLE);
+        return StringUtils.toString(title);
+    }
+
+    /**
+     * Sets the title attribute.
+     */
+    public final void setTitle(String title)
+    { 
+        setAttribute(DBCOLATTR_TITLE, title);
+    }
+
+    /**
+     * Returns the columns control type.
+     * The control type is a client specific name for the type of input control 
+     * that should be used to display and edit values for this column. 
+     * 
+     * @return the columns control type
+     */
+    public final String getControlType()
+    { 
+        Object type = getAttribute(DBCOLATTR_TYPE);
+        return StringUtils.toString(type);
+    }
+
+    /**
+     * Sets the title attribute.
+     */
+    public final void setControlType(String controlType)
+    { 
+        setAttribute(DBCOLATTR_TYPE, controlType);
+    }
+
+    /**
+     * Returns the source column.
+     * This is equivalent to the "Update Column"
+     * see getUpdateColumn()
+     */
+    public final Column getSourceColumn()
+    {
+        return getUpdateColumn();
+    }
+    
+    /**
+     * Gets the Java bean property name for this column
+     * i.e. EMPLOYEE_ID   = employeeId
+     *      DATE_OF_BIRTH = dateOfBirth
+     *      
+     * @return the name of the bean property used to get and set values 
+     */
+    public String getBeanPropertyName()
+    {
+        if (beanPropertyName==null)
+        {   // Compute bean property name
+            String res = "";
+            String name = getName().toLowerCase();
+            int beg=0;
+            while (beg<name.length())
+            {
+                int end = name.indexOf('_', beg);
+                if (end<0)
+                    end = name.length();
+                // assemble
+                if (end>beg)
+                {
+                    if (beg==0)
+                    {   // begin with all lower cases
+                        res = name.substring(beg, end);
+                    }
+                    else
+                    {   // add word where first letter is upper case 
+                        res += name.substring(beg, beg+1).toUpperCase();
+                        if (end-beg>1)
+                        {
+                            res += name.substring(beg+1, end);
+                        }
+                    }
+                }
+                // next
+                beg = end + 1;
+            }
+            // Result
+            beanPropertyName = res;
+        }
+        return beanPropertyName;
+    }
+
+    /**
+     * Sets the Java bean property name for this column.
+     *
+     * @param propertyName
+     */
+    public void setBeanPropertyName(String propertyName)
+    {
+        this.beanPropertyName = propertyName; 
+    }
+
+    /**
+     * Creates a new DBConcatExpr object with the specified value.
+     *
+     * @param value an Object value
+     * @return the new DBConcatExpr object
+     */
+    public DBColumnExpr append(Object value)
+    {
+        return new DBConcatExpr(this, value);
+    }
+
+    /**
+     * creates a new DBAliasExpr which renames the current expression to the supplied name. 
+     * <P>
+     * @param alias the alias name
+     * @return the new DBAliasExpr object
+     */
+    public DBColumnExpr as(String alias)
+    {
+        return new DBAliasExpr(this, alias);
+    }
+
+    /**
+     * creates a new DBAliasExpr which renames the current expression to the name of the supplied column.
+     * <P>
+     * @param column the column whose name serves as an alias for the current expression
+     * @return the new DBAliasExpr object
+     */
+    public DBColumnExpr as(DBColumn column)
+    {
+        return new DBAliasExpr(this, column.getName());
+    }
+
+    /**
+     * Creates and returns a new comparison object for the given comparison operator and value.
+     * 
+     * @param op the comparison operator
+     * @param value the Object value
+     * @return the new DBCompareColExpr object
+     */
+    public DBCompareColExpr cmp(DBCmpType op, Object value)
+    {
+        return new DBCompareColExpr(this, op, value);
+    }
+
+    /**
+     * Creates and returns a new comparison object for the SQL "like" operator.
+     *
+     * @param value the Object value
+     * @return the new DBCompareColExpr object
+     */
+    public DBCompareColExpr like(Object value)
+    {
+        return cmp(DBCmpType.LIKE, value);
+    }
+
+    /**
+     * Creates and returns a new comparison object for the SQL "like" operator.
+     * By converting column value and comparision value to upper case 
+     * the like is effectively case insensitive.   
+     *
+     * @param value the Object value
+     * @return the new DBCompareColExpr object
+     */
+    public DBCompareColExpr likeUpper(String value)
+    { 
+        DBValueExpr expr = new DBValueExpr(getDatabase(), value, DataType.TEXT);
+        return new DBCompareColExpr(this.upper(), DBCmpType.LIKE, expr.upper());
+    }
+
+    /**
+     * Creates and returns a new comparison object for the SQL "like" operator.
+     * By converting column value and comparision value to lower case 
+     * the like is effectively case insensitive.   
+     *
+     * @param value the Object value
+     * @return the new DBCompareColExpr object
+     */
+    public DBCompareColExpr likeLower(String value)
+    { 
+        DBValueExpr expr = new DBValueExpr(getDatabase(), value, DataType.TEXT);
+        return new DBCompareColExpr(this.lower(), DBCmpType.LIKE, expr.lower());
+    }
+
+    /**
+     * Creates and returns a new comparison object for the SQL "like" operator. 
+     *
+     * @param value the Object value
+     * @return the new DBCompareColExpr object
+     */
+    public DBCompareColExpr like(String value, char escape)
+    {
+        DBValueExpr textExpr = new DBValueExpr(getDatabase(), value, DataType.TEXT);
+        return cmp(DBCmpType.LIKE, textExpr.getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_ESCAPE,
+                                                        new Object[] { String.valueOf(escape) }, getUpdateColumn(), false));
+    }
+
+    /**
+     * Creates and returns a new comparison object for the SQL "not like" operator.
+     *
+     * @param value the Object value
+     * @return the new DBCompareColExpr object
+     */
+    public DBCompareColExpr notLike(Object value)
+    {
+        return cmp(DBCmpType.NOTLIKE, value);
+    }
+
+    /**
+     * Creates and returns a new comparison object for the SQL "=" (equal) operator.
+     *
+     * @param value the Object value
+     * @return the new DBCompareColExpr object
+     */
+    public DBCompareColExpr is(Object value)
+    {
+        return cmp(DBCmpType.EQUAL, value);
+    }
+
+    /**
+     * Creates and returns a new comparison object
+     * for the SQL "<>" (not equal) operator.
+     * 
+     * @param value the Object value
+     * @return the new DBCompareColExpr object
+     */
+    public DBCompareColExpr isNot(Object value)
+    {
+        return cmp(DBCmpType.NOTEQUAL, value);
+    }
+
+    /**
+     * Creates and returns a new comparison object
+     * for the SQL "in" operator. 
+     * 
+     * @param value the int value
+     * @return the new DBCompareColExpr object
+     */
+    public DBCompareColExpr in(Object value)
+    {
+        return cmp(DBCmpType.IN, listToArray(value));
+    }
+
+    /**
+     * Creates and returns a new comparison object
+     * for the SQL "not in" operator.
+     *
+     * @param value the int value
+     * @return the new DBCompareColExpr object
+     */
+    public DBCompareColExpr notIn(Object value)
+    {
+        return cmp(DBCmpType.NOTIN, listToArray(value));
+    }
+
+    /**
+     * Creates and returns a new comparison object 
+     * for the SQL "between" operator. 
+     *
+     * @param minValue the minimum value
+     * @param maxValue the maximum value
+     * @return the new DBCompareColExpr object
+     */
+    public DBCompareColExpr isBetween(Object minValue, Object maxValue)
+    {
+        return cmp(DBCmpType.BETWEEN, new Object[] { minValue, maxValue });
+    }
+
+    /**
+     * Creates and returns a new comparison object
+     * for the SQL "not between" operator. 
+     *
+     * @param minValue the minimum value
+     * @param maxValue the maximum value
+     * @return the new DBCompareColExpr object
+     */
+    public DBCompareColExpr isNotBetween(Object minValue, Object maxValue)
+    {
+        return cmp(DBCmpType.NOTBETWEEN, new Object[] { minValue, maxValue });
+    }
+
+    /**
+     * Creates and returns a new comparison object
+     * for the SQL ">" (greater than) operator. 
+     *
+     * @param value the Object value
+     * @return the new DBCompareColExpr object
+     */
+    public DBCompareColExpr isGreaterThan(Object value)
+    {
+        return cmp(DBCmpType.GREATERTHAN, value);
+    }
+
+    /**
+     * Creates and returns a new comparison object
+     * for the SQL ">=" (greater or equal) operator. 
+     *
+     * @param value the Object value
+     * @return the new DBCompareColExpr object
+     */
+    public DBCompareColExpr isMoreOrEqual(Object value)
+    {
+        return cmp(DBCmpType.MOREOREQUAL, value);
+    }
+
+    /**
+     * Creates and returns a new comparison object
+     * for the SQL "<=" (less or equal) operator. 
+     *
+     * @param value the Object value
+     * @return the new DBCompareColExpr object
+     */
+    public DBCompareColExpr isLessOrEqual(Object value)
+    {
+        return cmp(DBCmpType.LESSOREQUAL, value);
+    }
+
+    /**
+     * Creates and returns a new comparison object
+     * for the SQL "<" (less than) operator. 
+     *
+     * @param value the Object value
+     * @return the new DBCompareColExpr object
+     */
+    public DBCompareColExpr isSmallerThan(Object value)
+    {
+        return cmp(DBCmpType.LESSTHAN, value);
+    }
+    
+    // ------- calculations -------
+    
+    /**
+     * Creates and returns a new calculation object
+     * for the SQL "*" (multiply) operator. 
+     *
+     * @param value the multiply value
+     * @return the new DBCalcExpr object
+     */
+    public DBCalcExpr multiplyWith(Object value)
+    {
+        return new DBCalcExpr(this, "*", value);
+    }
+
+    /**
+     * Creates and returns a new calculation object
+     * for the SQL "/" (divide) operator. 
+     *
+     * @param value the divide value
+     * @return the new DBCalcExpr object
+     */
+    public DBCalcExpr divideBy(Object value)
+    {
+        return new DBCalcExpr(this, "/", value);
+    }
+
+    /**
+     * Creates and returns a new calculation object
+     * for the SQL "+" (plus) operator. 
+     *
+     * @param value the summate value
+     * @return the new DBCalcExpr object
+     */
+    public DBCalcExpr plus(Object value)
+    {
+        return new DBCalcExpr(this, "+", value);
+    }
+
+    /**
+     * Creates and returns a new calculation object
+     * for the SQL "-" (minus) operator. 
+     *
+     * @param value the subtract value
+     * @return the new DBCalcExpr object
+     */
+    public DBCalcExpr minus(Object value)
+    {
+        return new DBCalcExpr(this, "-", value);
+    }
+
+    /**
+     * Creates and returns a new calculation object
+     * for either the SQL "+" (plus) or "-" (minus) operator
+     * depending on whether the supplied integer value is positive or negative.
+     *
+     * @param value the subtract value
+     * @return the new DBCalcExpr object
+     */
+    public DBCalcExpr plus(int value)
+    {
+        return (value >= 0) ? new DBCalcExpr(this, "+", new Integer(value)) : new DBCalcExpr(this, "-", new Integer(-value));
+    }
+
+    /**
+     * Creates and returns a new calculation object
+     * for either the SQL "+" (plus) or "-" (minus) operator
+     * depending on whether the supplied integer value is negative or positive.
+     *
+     * @param value the subtract value
+     * @return the new DBCalcExpr object
+     */
+    public DBCalcExpr minus(int value)
+    {
+        return (value >= 0) ? new DBCalcExpr(this, "-", new Integer(value)) : new DBCalcExpr(this, "+", new Integer(-value));
+    }
+
+    // ----------------------------------------------------------
+    // --------------------- DBFuncExpr -------------------------
+    // ----------------------------------------------------------
+    
+    /**
+     * Creates a new DBFuncExpr from a given SQL-PRHASE and
+     * optional additional parameters.
+     *
+     * @param phrase the enum-id of the phrase (see DBDatabaseDriver.SQL_...)
+     * @param params the params to replace in the template
+     * @param isAggregate indicates whether the Function creates an aggregate
+     * @param dataType the resulting data Type
+     * @return the new DBCalcExpr object
+     */
+    public DBColumnExpr getExprFromPhrase(int phrase, Object[] params, DBColumn updateColumn, boolean isAggregate, DataType dataType)
+    {
+        DBDatabaseDriver driver = getDatabase().getDriver();
+        String template = driver.getSQLPhrase(phrase);
+        if (params != null)
+        {
+            for (int i = 0; i < params.length; i++)
+            { // Replace Params
+                // String test  =(params[i] != null) ? params[i].toString() : "";
+                String value = getObjectValue(this, params[i], DBExpr.CTX_DEFAULT, ",");
+                // template = template.replaceAll("\\{" + String.valueOf(i) + "\\}", value);
+                template = StringUtils.replaceAll(template, "{"+ String.valueOf(i) + "}", value);
+            }
+        }
+        return new DBFuncExpr(this, template, updateColumn, isAggregate, dataType);
+    }
+
+    public DBColumnExpr getExprFromPhrase(int phrase, Object[] params, DBColumn updateColumn, boolean isAggregate)
+    {
+        return getExprFromPhrase(phrase, params, updateColumn, isAggregate, getDataType());
+    }
+
+    /**
+     * Creates and returns a function object which
+     * encloses the current expression in parenthesis.
+     *
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr parenthesis()
+    { 
+        return new DBFuncExpr(this, "(?)", getUpdateColumn(), false, getDataType());
+    }
+
+    /**
+     * Creates a sql-expression for the nvl() or coalesce() function.
+     * 
+     * @param nullValue the Object value
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr coalesce(Object nullValue)
+    {
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_COALESCE, new Object[] { nullValue }, getUpdateColumn(), false);
+    }
+
+    /**
+     * Creates a sql-expression for the nvl() or coalesce() function.
+     * 
+     * @param nullValue the int value
+     * @return the new DBFuncExpr object
+     *
+     * @deprecated Outdated oracle syntax - use coalesce instead
+     */
+    @Deprecated
+    public DBColumnExpr nvl(Object nullValue)
+    {
+        return coalesce(nullValue);
+    }
+
+    /**
+     * Creates and returns a sql-expression for the substring(...) function.
+     * 
+     * @param pos the position number of the string
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr substring(DBExpr pos)
+    {   // Get Expression
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_SUBSTRING, new Object[] { pos }, getUpdateColumn(), false);
+    }
+
+    /**
+     * Overloaded. @see substring(DBExpr pos)
+     */
+    public DBColumnExpr substring(int pos)
+    {
+        return substring(new DBValueExpr(getDatabase(), pos, DataType.INTEGER));
+    }
+
+    /**
+     * Creates and returns a sql-expression for the substring(...) function.
+     * 
+     * @param pos the position number of the string
+     * @param count the length of the substring
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr substring(DBExpr pos, DBExpr count)
+    {   // Get Expression
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_SUBSTRINGEX, new Object[] { pos, count }, getUpdateColumn(), false);
+    }
+
+    /**
+     * Overloaded. @see substring(DBExpr pos, DBExpr count)
+     */
+    public DBColumnExpr substring(DBExpr pos, int count)
+    {
+        return substring(pos, new DBValueExpr(getDatabase(), count, DataType.INTEGER));
+    }
+
+    /**
+     * Overloaded. @see substring(DBExpr pos, DBExpr count)
+     */
+    public DBColumnExpr substring(int pos, DBExpr count)
+    {
+        return substring(new DBValueExpr(getDatabase(), pos, DataType.INTEGER), count);
+    }
+
+    /**
+     * Overloaded. @see substring(DBExpr pos, DBExpr count)
+     */
+    public DBColumnExpr substring(int pos, int count)
+    {
+        return substring(new DBValueExpr(getDatabase(), pos, DataType.INTEGER), 
+                         new DBValueExpr(getDatabase(), count, DataType.INTEGER));
+    }
+    
+    /**
+     * Creates and returns a sql-expression for the replace(...) function.
+     * 
+     * @param match string to replace
+     * @param replace string with replacement
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr replace(Object match, Object replace)
+    {
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_REPLACE, new Object[] { match, replace }, getUpdateColumn(), false);
+    }
+
+    /**
+     * Creates and returns a sql-expression for the reverse(...) function.
+     * 
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr reverse()
+    {
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_REVERSE, null, getUpdateColumn(), false);
+    }
+
+    /**
+     * Creates and returns a sql-expression for the trim() function.
+     * 
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr trim()
+    {
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_TRIM, null, getUpdateColumn(), false);
+    }
+
+    /**
+     * Creates and returns a sql-expression for the ltrim() function.
+     * 
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr trimLeft()
+    {
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_LTRIM, null, getUpdateColumn(), false);
+    }
+
+    /**
+     * Creates and returns a sql-expression for the rtrim() function.
+     * 
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr trimRight()
+    {
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_RTRIM, null, getUpdateColumn(), false);
+    }
+    
+    /**
+     * Creates and returns a function object which
+     * converts the current expression to upper case.
+     *
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr upper()
+    {
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_UPPER, null, getUpdateColumn(), false);
+    }
+
+    /**
+     * Creates and returns a function object which
+     * converts the current expression to lower case.
+     *
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr lower()
+    {
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_LOWER, null, getUpdateColumn(), false);
+    }
+
+    /**
+     * Creates and returns a sql-expression that returns the string length of this expression.
+
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr length()
+    {
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_LENGTH, null, getUpdateColumn(), false, DataType.INTEGER);
+    }
+
+    /**
+     * Creates and returns a sql-expression that returns the position of a string in the current column expression.
+     *
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr indexOf(Object str)
+    {
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_STRINDEX, new Object[] { str }, getUpdateColumn(), false, DataType.INTEGER);
+    }
+
+    /**
+     * Creates and returns a sql-expression that returns the position of a string in the current column expression.
+     *
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr indexOf(Object str, DBExpr fromPos)
+    {
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_STRINDEXFROM, new Object[] { str, fromPos }, getUpdateColumn(), false, DataType.INTEGER);
+    }
+
+    /**
+     * Overloaded. @see indexOf(Object str, DBExpr fromPos) 
+     */
+    public DBColumnExpr indexOf(Object str, int fromPos)
+    {
+        return indexOf(str, new DBValueExpr(getDatabase(), fromPos, DataType.INTEGER));
+    }
+
+    /**
+     * Creates and returns a sql-expression for the absolute abs() function.
+     * 
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr abs()
+    {
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_ABS, null, getUpdateColumn(), false);
+    }
+
+    /**
+     * Creates and returns an function object that
+     * rounds a number espression with the given decimals.
+     * 
+     * @param decimals the number of decimal to which to truncate the current value
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr round(int decimals)
+    {
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_ROUND, new Object[] { new Integer(decimals) }, getUpdateColumn(), false);
+    }
+
+    /**
+     * Creates and returns an function object that
+     * truncates a number espression with the given decimals.
+     * 
+     * @param decimals the number of decimal to which to truncate the current value
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr trunc(int decimals)
+    {
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_TRUNC, new Object[] { new Integer(decimals) }, getUpdateColumn(), false);
+    }
+
+    /**
+     * Creates and returns an function object that
+     * calculates the year of a date value.
+     * 
+     * @return the new DBColumnExpr object
+     */
+    public DBColumnExpr year()
+    {
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_YEAR, null, null, false);
+    }
+
+    /**
+     * Creates and returns an function object that
+     * calculates the month of a date value.
+     * 
+     * @return the new DBColumnExpr object
+     */
+    public DBColumnExpr month()
+    {
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_MONTH, null, null, false);
+    }
+
+    /**
+     * Creates and returns an function object that
+     * calculates the day of a date value.
+     * 
+     * @return the new DBColumnExpr object
+     */
+    public DBColumnExpr day()
+    {
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_DAY, null, null, false);
+    }
+
+    /**
+     * Creates and returns an aggregation function object
+     * which calculates the sum for the current expression over a group of rows.
+     *
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr sum()
+    {
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_SUM, null, null, true);
+    }
+
+    /**
+     * Creates and returns an aggregation function object
+     * which returns the minimum value for the current expression over a group of rows.
+     *
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr min()
+    {
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_MIN, null, null, true);
+    }
+
+    /**
+     * Creates and returns an aggregation function object
+     * which returns the maximum value for the current expression over a group of rows.
+     *
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr max()
+    {
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_MAX, null, null, true);
+    }
+
+    /**
+     * Creates and returns an aggregation function object
+     * which returns the average value for the current expression over a group of rows.
+     *
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr avg()
+    {
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_AVG, null, null, true);
+    }
+
+    /**
+     * Creates and returns an aggregation function object
+     * which returns the number of rows in a group of rows.
+     *
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr count()
+    {
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_COUNT, null, null, true);
+    }
+
+    /**
+     * Creates and returns a sql-expression for the replace(...) function.
+     * 
+     * @param list 
+     * @param otherwise
+     * @return the new DBFuncExpr object
+     */
+    @SuppressWarnings("unchecked")
+    public DBColumnExpr decode(Map list, Object otherwise)
+    {
+        DBDatabaseDriver driver = getDatabase().getDriver();
+        StringBuilder inner = new StringBuilder();
+        // Generate parts
+        for (Iterator i = list.keySet().iterator(); i.hasNext();)
+        {
+            Object key = i.next();
+            Object val = list.get(key);
+
+            String part = driver.getSQLPhrase(DBDatabaseDriver.SQL_FUNC_DECODE_PART);
+            // part = part.replaceAll("\\{0\\}", getObjectValue(this, key, DBExpr.CTX_DEFAULT, ""));
+            part = StringUtils.replaceAll(part, "{0}", getObjectValue(this, key, DBExpr.CTX_DEFAULT, ""));
+
+            // part = part.replaceAll("\\{1\\}", getObjectValue(this, val, DBExpr.CTX_DEFAULT, ""));
+            part = StringUtils.replaceAll(part, "{1}", getObjectValue(this, val, DBExpr.CTX_DEFAULT, ""));
+
+            inner.append(driver.getSQLPhrase(DBDatabaseDriver.SQL_FUNC_DECODE_SEP));
+            inner.append(part);
+        }
+        // Generate other
+        if (otherwise != null)
+        { // Else
+            String other = driver.getSQLPhrase(DBDatabaseDriver.SQL_FUNC_DECODE_ELSE);
+
+            // other = other.replaceAll("\\{0\\}", getObjectValue(this, otherwise, DBExpr.CTX_DEFAULT, ""));
+            other = StringUtils.replaceAll(other, "{0}", getObjectValue(this, otherwise, DBExpr.CTX_DEFAULT, ""));
+
+            inner.append(driver.getSQLPhrase(DBDatabaseDriver.SQL_FUNC_DECODE_SEP));
+            inner.append(other);
+        }
+        DBValueExpr param = new DBValueExpr(getDatabase(), inner, DataType.UNKNOWN); 
+        return getExprFromPhrase(DBDatabaseDriver.SQL_FUNC_DECODE, new Object[] { param }, null, false);
+    }
+
+    public final DBColumnExpr decode(Object key1, Object value1, Object otherwise)
+    {
+        Map<Object, Object> list = new HashMap<Object, Object>();
+        list.put(key1, value1);
+        return decode(list, otherwise);
+    }
+
+    public final DBColumnExpr decode(Object key1, Object value1, Object key2, Object value2, Object otherwise)
+    {
+        Map<Object, Object> list = new HashMap<Object, Object>();
+        list.put(key1, value1);
+        list.put(key2, value2);
+        return decode(list, otherwise);
+    }
+
+    public final DBColumnExpr decode(Object key1, Object value1, Object key2, Object value2, Object key3, Object value3,
+                               Object otherwise)
+    {
+        Map<Object, Object> list = new HashMap<Object, Object>();
+        list.put(key1, value1);
+        list.put(key2, value2);
+        list.put(key3, value3);
+        return decode(list, otherwise);
+    }
+
+    public final DBColumnExpr decode(Options options, Object otherwise)
+    {
+        int size = options.size() + (otherwise!=null ? 1 : 0);
+        Map<Object, Object> list = new HashMap<Object, Object>(size);
+        for (OptionEntry e : options)
+            list.put(e.getValue(), e.getText());
+        return decode(list, otherwise);
+    }
+
+    public final DBColumnExpr decode(Options options)
+    {
+        return decode(options, null);
+    }
+
+    // ----------------------------------------------------------
+    // --------------------- Conversion -------------------------
+    // ----------------------------------------------------------
+    
+    /**
+     * Creates a new DBFuncExpr object (to_char SQL statement)
+     * with the parameters prefix = "to_char(" and postfix = ")"
+     * 
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr toChar()
+    {
+        return convertTo(DataType.TEXT);
+    }
+
+    /**
+     * Creates a new DBFuncExpr object (to_char SQL statement)
+     * with the parameters prefix = "to_char(" and postfix = ", *
+     * '"+format+"')"
+     * 
+     * @param format the string value
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr toChar(String format)
+    {
+        return convertTo(DataType.TEXT, format);
+    }
+
+    /**
+     * Creates a new DBFuncExpr object that will convert
+     * the current column to the destination data type specivied.
+     * 
+     * @param dataType the destination data type
+     * @param format optional destination format (usually a string)
+     * @return the new DBFuncExpr object
+     */
+    public DBColumnExpr convertTo(DataType dataType, Object format)
+    {
+        DBDatabaseDriver driver = getDatabase().getDriver();
+        return new DBFuncExpr(this, driver.getConvertPhrase(dataType, getDataType(), format), getUpdateColumn(), false, dataType);
+    }
+
+    /**
+     * Creates and returns a new DBFuncExpr object that will
+     * convert the current column to the destination data type specivied.
+     * 
+     * @param dataType Data type to which to convert the current expression to.
+     * @return the new DBFuncExpr object
+     */
+    public final DBColumnExpr convertTo(DataType dataType)
+    {
+        return convertTo(dataType, null);
+    }
+
+
+    // get object Array from List
+    private Object listToArray(Object value)
+    {   // Check wether value is a list
+        /*
+        if (value != null && value instanceof java.util.List)
+        { // Convert List to array
+            return ((List)value).toArray();
+        }
+        */
+        return value;
+    }
+    
+}
\ No newline at end of file

Added: incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/DBCombinedCmd.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/DBCombinedCmd.java?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/DBCombinedCmd.java (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/DBCombinedCmd.java Wed Aug  6 01:47:37 2008
@@ -0,0 +1,124 @@
+/*
+ * ESTEAM Software GmbH
+ */
+package org.apache.empire.db;
+// java
+import java.util.Set;
+
+/**
+ * This class is used for building up a partition of a SQL-Command.
+ * It handles the insert from a specified key word between two DBCommandExpr objects.
+ * <P>
+ * 
+ * @author ESTEAM software <A TARGET="esteam" HREF="http://www.esteam.de">www.esteam.de</A>
+ */
+public class DBCombinedCmd extends DBCommandExpr
+{
+   // Memebers
+   private DBCommandExpr left;
+   private DBCommandExpr right;
+   private String        keyWord;
+
+  /**
+   * Constructs a new DBFuncExpr object and
+   * sets the specified parameters to this object.
+   * 
+   * @param left the first DBCommandExpr object
+   * @param keyWord the key word between the wo DBCommandExpr objects
+   * @param right the second DBCommandExpr object
+   */
+   public DBCombinedCmd(DBCommandExpr left, String keyWord, DBCommandExpr right)
+   {
+      this.left    = left;
+      this.right   = right;
+      this.keyWord = keyWord;
+   }
+
+   @Override
+   public boolean isValid()
+   {
+       return (left.isValid() && right.isValid()); 
+   }
+
+  /**
+   * Returns the current DBDatabase object.
+   * 
+   * @return the current DBDatabase object
+   */
+   @Override
+   public DBDatabase getDatabase()
+   {
+      return left.getDatabase();
+   }
+
+   /**
+    * @see org.apache.empire.db.DBExpr#addReferencedColumns(Set)
+    */
+   @Override
+   public void addReferencedColumns(Set<DBColumn> list)
+   {
+      left .addReferencedColumns(list);
+      right.addReferencedColumns(list);
+   }
+  /**
+   * Calls the method dbDBCommandExpr.getSelectExprList from the private variable 'left'.
+   * Returns a array of all DBColumnExpr object of the Vector: 'select'.
+   * 
+   * @see org.apache.empire.db.DBCommandExpr#getSelectExprList()
+   * @return returns an array of all DBColumnExpr object of the Vector: 'select'
+   */
+   @Override
+   public DBColumnExpr[] getSelectExprList()
+   {
+      // DebugMsg(2, "Check: getSelectExprList() for DBCombinedCmd");
+      return left.getSelectExprList();
+   }
+
+  /**
+   * Creates the SQL-Command.
+   * 
+   * @param buf the SQL-Command
+   * @return true if the creation was successful
+   */
+   @Override
+   public boolean getSelect(StringBuilder buf)
+   {
+      // the left part
+      left.clearOrderBy();
+      if (!left.getSelect(buf))
+           return error(left);
+      // concat keyword     
+      buf.append( " " );
+      buf.append( keyWord );
+      buf.append( " (" );
+      // the right part
+      right.clearOrderBy();
+      if (!right.getSelect(buf))
+           return error(right);
+      // done
+      buf.append( ")" );
+      // Add optional Order by statement
+      if ( orderBy!=null )
+      {    // Having
+           buf.append("\r\nORDER BY ");
+           addListExpr(buf, orderBy, CTX_DEFAULT, ", ");
+      }
+      return success();
+   }
+  /**
+   * This helper function adds the DBColumnExpr objects to the Vector: 'orderBy'.
+   * 
+   * @param expr the first DBColumnExpr object
+   * @param desc an boolean value
+   */
+   @Override
+   public void orderBy(DBColumnExpr expr, boolean desc)
+   {
+      // set statement
+      super.orderBy(getCmdColumn(expr), desc);
+   }
+
+
+}
+
+

Added: incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/DBCommand.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/DBCommand.java?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/DBCommand.java (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/DBCommand.java Wed Aug  6 01:47:37 2008
@@ -0,0 +1,1025 @@
+/*
+ * ESTEAM Software GmbH
+ */
+package org.apache.empire.db;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.Vector;
+
+import org.apache.empire.commons.Errors;
+import org.apache.empire.data.DataType;
+import org.apache.empire.db.expr.compare.DBCompareColExpr;
+import org.apache.empire.db.expr.compare.DBCompareExpr;
+import org.apache.empire.db.expr.join.DBJoinExpr;
+import org.apache.empire.db.expr.join.DBJoinExprEx;
+import org.apache.empire.db.expr.set.DBSetExpr;
+
+
+/**
+ * This abstract class handles the creation of the SQL-Commands. 
+ * There are methods to create SQL-Commandos, like update, insert,
+ * delete and select.
+ * <P>
+ * 
+ * @author ESTEAM software <A TARGET="esteam" HREF="http://www.esteam.de">www.esteam.de </A>
+ */
+public abstract class DBCommand extends DBCommandExpr
+    implements Cloneable
+{
+    public static final class DBCmdParameter extends DBExpr
+    {
+        private DBCommand cmd;
+        protected int index; 
+        
+        protected DBCmdParameter(DBCommand cmd, int index)
+        {
+            this.cmd   = cmd;
+            this.index = index;
+        }
+        
+        @Override
+        public void addSQL(StringBuilder buf, long context)
+        {
+            buf.append("?"); //$NON-NLS-1$
+        }
+        
+        /**
+         * @see org.apache.empire.db.DBExpr#addReferencedColumns(Set)
+         */
+        @Override
+        public void addReferencedColumns(Set<DBColumn> list)
+        {
+            // Nothing to add
+        }
+        
+        @Override
+        public DBDatabase getDatabase()
+        {
+            return cmd.getDatabase();
+        }
+        
+        public Object getValue()
+        {
+            return cmd.cmdParams.get(index);
+        }
+        
+        public void setValue(Object value)
+        {
+            cmd.cmdParams.set(index, value);
+        }
+    }
+    
+    // Distinct Select
+    protected boolean                selectDistinct = false;
+    // Lists
+    protected List<DBColumnExpr>     select         = null;
+    protected List<DBSetExpr>        set            = null;
+    protected List<DBJoinExpr>       joins          = null; // Join Info
+    protected List<DBCompareExpr>    where          = null;
+    protected List<DBCompareExpr>    having         = null;
+    protected List<DBColumnExpr>     groupBy        = null;
+    // Params for prepared Statements
+    protected Vector<Object>         cmdParams      = null;
+    // Database
+    private DBDatabase               db;
+
+    /**
+     * Constructs a new DBCommand object and set the specified DBDatabase object.
+     * 
+     * @param db the current database object
+     */
+    protected DBCommand(DBDatabase db)
+    {
+        this.db = db;
+    }
+
+    /**
+     * Creates a clone of this class.
+     */
+    @Override
+    public DBCommand clone()
+    {
+        try 
+        {
+            return (DBCommand)super.clone();
+        } catch(CloneNotSupportedException e) 
+        {
+            log.error("Cloning DBCommand object failed!", e);
+            return null;
+        }
+    }
+
+    /**
+     * Returns the current DBDatabase object.
+     * 
+     * @return the current DBDatabase object
+     */
+    @Override
+    public DBDatabase getDatabase()
+    {
+        return db;
+    }
+
+    @Override
+    public boolean isValid()
+    {
+    	return isValidQuery() || isValidUpdate();
+    }
+
+    /**
+     * Returns whether the command object can produce a select sql-statement.
+     * 
+     * @return true if at least one select expression has been set
+     */
+    public boolean isValidQuery()
+    {
+    	return (select != null);
+    }
+
+    /**
+     * Returns whether the command object can produce a update sql-statement.
+     * 
+     * @return true if a set expression has been set.
+     */
+    public boolean isValidUpdate()
+    {
+        return (set != null);
+    }
+
+    /**
+     * Sets whether or not the select statement should contain
+     * the distinct directive .
+     */
+    public void selectDistinct()
+    {
+    	this.selectDistinct = true;
+    }
+
+    /**
+     * Returns whether or not the select statement will be distinct or not.
+     *  
+     * @return true if the select will contain the distinct directive or false otherwise.
+     */
+    public boolean isSelectDistinct()
+    {
+    	return selectDistinct;
+    }
+    
+    /**
+     * Adds a DBColumnExpr object to the Vector: 'select'.
+     * 
+     * @param expr the DBColumnExpr object
+     */
+    public void select(DBColumnExpr expr)
+    { // Select this column
+        if (select == null)
+            select = new ArrayList<DBColumnExpr>();
+        if (expr != null && select.contains(expr) == false)
+            select.add(expr);
+    }
+
+    /**
+     * This helper function adds two DBColumnExpr objects
+     * to the Vector: 'select'
+     * 
+     * @param expr1 the first DBColumnExpr object
+     * @param expr2 the second DBColumnExpr object
+     */
+    public void select(DBColumnExpr expr1, DBColumnExpr expr2)
+    {
+        select(expr1);
+        select(expr2);
+    }
+
+    /**
+     * This helper function adds three DBColumnExpr objects to the Vector: 'select'.
+     */
+    public void select(DBColumnExpr expr1, DBColumnExpr expr2, DBColumnExpr expr3)
+    {
+        select(expr1);
+        select(expr2);
+        select(expr3);
+    }
+
+    /**
+     * This helper function adds four DBColumnExpr objects to the Vector: 'select'.
+     */
+    public void select(DBColumnExpr expr1, DBColumnExpr expr2, DBColumnExpr expr3, DBColumnExpr expr4)
+    {
+        select(expr1);
+        select(expr2);
+        select(expr3);
+        select(expr4);
+    }
+
+    /**
+     * This helper function adds five DBColumnExpr objects
+     * to the Vector: 'select'.
+     */
+    public void select(DBColumnExpr expr1, DBColumnExpr expr2, DBColumnExpr expr3, DBColumnExpr expr4, DBColumnExpr expr5)
+    {
+        select(expr1);
+        select(expr2);
+        select(expr3);
+        select(expr4);
+        select(expr5);
+    }
+
+    /**
+     * This helper function adds an array of DBColumnExpr
+     * objects to list of select-columns.
+     */
+    public void select(DBColumnExpr[] exprList)
+    {
+        for (int i=0; i<exprList.length; i++)
+        {
+            select(exprList[i]);
+        }
+    }
+
+    /**
+     * Adds a list of column expression to the select clause
+     */
+    public void select(Collection<DBColumnExpr> columns)
+    {
+        for (DBColumnExpr expr : columns)
+            select(expr);
+    }
+
+    /**
+     * Adds a list of column expression to the select clause
+     */
+    public void select(List<DBColumn> columns)
+    {
+        for (int i = 0; i < columns.size(); i++)
+            select(columns.get(i));
+    }
+    
+    private boolean useCmdParam(DBColumn col)
+    {
+        DataType dt = col.getDataType();
+        return ( dt==DataType.BLOB || dt==DataType.CLOB );
+    }
+    
+    private Object getCmdParamValue(DBColumn col, Object value)
+    {        
+        switch (col.getDataType())
+        {
+            case BLOB:
+                if (value == null)
+                    return null;
+                if (value instanceof DBBlobData)
+                    return value;
+                if (value instanceof byte[])
+                	return new DBBlobData((byte[])value);
+                // create a blob data
+                return new DBBlobData(value.toString());
+            case CLOB:
+                if (value == null)
+                    return null;
+                if (value instanceof DBClobData)
+                    return value;
+                // create a clob data
+                return new DBClobData(value.toString());
+            default:
+                return value;
+        }
+    }
+
+    /**
+     * Inserts DBSetExpr objects to the Vector 'set'.
+     * 
+     * @param expr the DBSetExpr object(s)
+     */
+    public void set(DBSetExpr expr)
+    {
+        if (set == null)
+            set = new ArrayList<DBSetExpr>();
+        for (int i = 0; i < set.size(); i++)
+        {
+            DBSetExpr chk = set.get(i);
+            if (chk.column.equals(expr.column))
+            { // Overwrite existing value
+                if (useCmdParam(expr.column) && (expr.value instanceof DBExpr) == false
+                    && chk.value instanceof DBCmdParameter)
+                { // replace parameter
+                    int index = ((DBCmdParameter) chk.value).index;
+                    this.setCmdParam(index, getCmdParamValue(expr.column, expr.value));
+                } 
+                else
+                { // replace value
+                    chk.value = expr.value;
+                }
+                return;
+            }
+        }
+        // Replace with parameter 
+        if (useCmdParam(expr.column) && (expr.value instanceof DBExpr)==false)
+            expr.value = addCmdParam(getCmdParamValue(expr.column, expr.value));
+        // new Value!
+        set.add(expr);
+    }
+
+    /**
+     * checks whether a column is in the list of set expressions
+     * @param column
+     * @return
+     */
+    private boolean hasSetExprOn(DBColumn column)
+    {
+        if (set==null)
+            return false;
+        Iterator<DBSetExpr> i = set.iterator();
+        while (i.hasNext())
+        {
+            DBSetExpr chk = i.next();
+            if (chk.column.equals(column))
+                return true;
+        }
+        return false;
+    }
+
+    /**
+     * Sets a object to in the list of Parameters.
+     */
+    public boolean setCmdParam(int index, Object item)
+    {
+        if (index<0 || index>999)
+            return error(Errors.InvalidArg, index, "index");
+        if (cmdParams==null)
+            cmdParams= new Vector<Object>();
+        if (index>=cmdParams.size())
+        {	// extend the parameter list
+            cmdParams.setSize(index+1);
+        }
+        cmdParams.set(index, item);
+        return success();
+    }
+
+    /**
+     * Adds an object to in the list of Parameters
+     * and returns a parameter object.
+     */
+    public DBCmdParameter addCmdParam(Object item)
+    {
+        if (cmdParams==null)
+            cmdParams= new Vector<Object>();
+        // Adds the parameter 
+        int index = cmdParams.size(); 
+        if (cmdParams.add(item)==false)
+            return null; // unknown error
+        // Creates a Parameter expression
+        return new DBCmdParameter(this, index);
+    }
+    
+    /**
+     * Adds a join to the list of join expressions.
+     * 
+     * @param join the join expression
+     */
+    public void join(DBJoinExpr join)
+    {
+        if (joins == null)
+            joins = new ArrayList<DBJoinExpr>();
+        // Create a new join
+        for (int i = 0; i < joins.size(); i++)
+        { // Check whether join exists
+            DBJoinExpr item = joins.get(i);
+            if (item.equals(join))
+                return;
+        }
+        joins.add(join);
+    }
+
+    /**
+     * Adds a join based on two columns to the list of join expressions.
+     * 
+     * @param left the left join value
+     * @param right the right join
+     * @param joinType type of join (INNER, LEFT, RIGHT)
+     */
+    public DBJoinExpr join(DBColumnExpr left, DBColumn right, DBJoinType joinType)
+    {
+        DBJoinExpr join = new DBJoinExpr(left, right, joinType); 
+        join(join);
+        return join;
+    }
+
+    /**
+     * Adds an inner join based on two columns to the list of join expressions.
+     * 
+     * @param left the left join value
+     * @param right the right join
+     */
+    public DBJoinExpr join(DBColumnExpr left, DBColumn right)
+    {
+        return join(left, right, DBJoinType.INNER);
+    }
+
+    /**
+     * Adds a join based on a compare expression to the command.
+     * 
+     * @param rowset table of view which to join
+     * @param cmp the compare expression with wich to join the table
+     * @param joinType type of join (INNER, LEFT, RIGHT)
+     */
+    public DBJoinExpr join(DBRowSet rowset, DBCompareExpr cmp, DBJoinType joinType)
+    {
+        DBJoinExpr join = new DBJoinExprEx(rowset, cmp, joinType); 
+        join(join);
+        return join;
+    }
+
+    /**
+     * Adds an inner join based on a compare expression to the command.
+     * 
+     * @param rowset table of view which to join
+     * @param cmp the compare expression with wich to join the table
+     */
+    public DBJoinExpr join(DBRowSet rowset, DBCompareExpr cmp)
+    {
+        return join(rowset, cmp, DBJoinType.INNER);
+    }
+
+    /**
+     * Adds a list of join expressions to the command.
+     * 
+     * @param joinExprList list of join expressions
+     */
+    public void addJoins(List<DBJoinExpr> joinExprList)
+    {
+        if (joins == null)
+        {
+            joins = new ArrayList<DBJoinExpr>();
+        }
+        this.joins.addAll(joinExprList);
+    }
+    
+    /**
+     * Returns true if the command has a join on the given
+     * table or false otherwise.
+     * 
+     * @return true if the command has a join on the given table or false otherwise
+     */
+    public boolean hasJoinOn(DBRowSet rowset)
+    {
+        if (joins==null)
+            return false;
+        // Examine all joins
+        for (DBJoinExpr join : joins)
+        {
+            if (join.isJoinOn(rowset))
+                return true;
+        }
+        // not found
+        return false;
+    }
+
+    /**
+     * Adds a compare expression to the list of constraints.
+     * If another restriction already exists for the same column it will be replaced.
+     * 
+     * @param expr the DBCompareExpr object
+     */
+    public void where(DBCompareExpr expr)
+    {
+        if (where == null)
+            where = new ArrayList<DBCompareExpr>();
+        setCompare(where, expr);
+    }
+
+    /**
+     * Returns true if the command has constaints or false if not.
+     * 
+     * @return true if constraints have been set on the command
+     */
+    public boolean hasWhereConstraints()
+    {
+        return (where!=null && where.size()>0);
+    }
+
+    /**
+     * Returns a copy of the defined where clauses.
+     * 
+     * @return vector of where clauses
+     */
+    public List<DBCompareExpr> getWhereConstraints()
+    {
+        if (where != null)
+        {   // Return a Copy of all Where Constraints
+            return new ArrayList<DBCompareExpr>(where);
+        }
+        return null;
+    }
+
+    /**
+     * Returns a copy of the defined joins.
+     * 
+     * @return vector of joins
+     */
+    public List<DBJoinExpr> getJoins()
+    {
+        if (joins != null)
+        {
+            return new ArrayList<DBJoinExpr>(joins);
+        }
+        return null;
+    }
+
+    /**
+     * Adds a list of constraints to the command.
+     * 
+     * @param constraints list of constraints
+     */
+    public void addWhereConstraints(List<DBCompareExpr> constraints)
+    {
+        if (where == null)
+        {
+            where = new ArrayList<DBCompareExpr>();
+        }
+        this.where.addAll(constraints);
+    }
+
+    /**
+     * Sets a having contraint.
+     * 
+     * @param expr the DBCompareExpr object
+     */
+    // having
+    public void having(DBCompareExpr expr)
+    {
+        if (having == null)
+            having = new ArrayList<DBCompareExpr>();
+        setCompare(having, expr);
+    }
+
+    /**
+     * Adds a list columns to the group by phrase of an sql statement.
+     * 
+     * @param exprList array of columns by which to group the rows
+     */
+    public void groupBy(DBColumnExpr[] exprList)
+    {
+        if (groupBy == null)
+            groupBy = new ArrayList<DBColumnExpr>();
+        // group by
+        for (int i=0; i<exprList.length; i++)
+        {
+        	DBColumnExpr expr = exprList[i];
+        	if (expr.isAggregate()==false && groupBy.contains(expr)==false)
+                groupBy.add(expr);
+        }
+    }
+
+    /**
+     * Adds a column to the group by phrase of an sql statement.
+     * 
+     * @param expr the DBCompareExpr object
+     */
+    // groupBy
+    public void groupBy(DBColumnExpr expr)
+    {
+        if (expr.isAggregate())
+            return;
+        if (groupBy == null)
+            groupBy = new ArrayList<DBColumnExpr>();
+        // group by
+        groupBy.add(expr);
+    }
+
+    /**
+     * Adds two columns to the group by phrase of an sql statement.
+     */
+    // groupBy
+    public void groupBy(DBColumnExpr expr1, DBColumnExpr expr2)
+    {
+        groupBy(expr1);
+        groupBy(expr2);
+    }
+
+    /**
+     * Adds three columns to the group by phrase of an sql statement.
+     */
+    // groupBy
+    public void groupBy(DBColumnExpr expr1, DBColumnExpr expr2, DBColumnExpr expr3)
+    {
+        groupBy(expr1);
+        groupBy(expr2);
+        groupBy(expr3);
+    }
+
+    /**
+     * Returns true if the command has constaints or false if not.
+     * 
+     * @return true if constraints have been set on the command
+     */
+    public boolean hasSelectExpr()
+    {
+        return (select!=null && select.size()>0);
+    }
+    
+    @Override
+    public boolean getSelect(StringBuilder buf)
+    {
+        if (select == null)
+            return error(Errors.ObjectNotValid, getClass().getName()); // invalid!
+        // Prepares statement
+        addSelect(buf);
+        // From clause
+        addFrom(buf);
+        // Add Where
+        addWhere(buf);
+        // Add Grouping
+        addGrouping(buf);
+        // Add Order
+        addOrder(buf);
+        // done
+        return success();
+    }
+    
+    /**
+     * Returns a array of all DBColumnExpr object of the Vector: 'select'.
+     * 
+     * @return a array of all DBColumnExpr object of the Vector: 'select'
+     */
+    @Override
+    public DBColumnExpr[] getSelectExprList()
+    {
+        int count = (select != null) ? select.size() : 0;
+        if (count < 1)
+            return null;
+        // The List
+        DBColumnExpr[] exprList = new DBColumnExpr[count];
+        for (int i = 0; i < count; i++)
+            exprList[i] = select.get(i);
+        // The expression List
+        return exprList;
+    }
+
+    /**
+     * Clears the select distinct option.
+     */
+    public void clearSelectDistinct()
+    {
+        this.selectDistinct = false;
+    }
+
+    /**
+     * Clears the list of selected columns.
+     */
+    public void clearSelect()
+    {
+        select = null;
+    }
+
+    /**
+     * Clears the list of set expressions.
+     */
+    public void clearSet()
+    {
+        set = null;
+        cmdParams = null;
+    }
+
+    /**
+     * Clears the list of join expressions.
+     */
+    public void clearJoin()
+    {
+        joins = null;
+    }
+
+    /**
+     * Clears the list of where constraints.
+     */
+    public void clearWhere()
+    {
+        where = null;
+    }
+
+    /**
+     * Clears the list of having constraints.
+     */
+    public void clearHaving()
+    {
+        having = null;
+    }
+
+    /**
+     * Clears the list of group by constraints.
+     */
+    public void clearGroupBy()
+    {
+        groupBy = null;
+    }
+
+    /**
+     * Clears the entire command object.
+     */
+    public void clear()
+    {
+        clearSelectDistinct();
+        clearSelect();
+        clearSet();
+        clearJoin();
+        clearWhere();
+        clearHaving();
+        clearGroupBy();
+        clearOrderBy();
+        cmdParams = null;
+    }
+
+    /**
+     * Compares the DBCompareExpr object with the Elements
+     * of the Vector 'where' or 'having'.
+     * 
+     * @param list the Vector 'where' or 'having'
+     * @param expr the DBCompareExpr object
+     * @param expr the DBCompareExpr object
+     */
+    private void setCompare(List<DBCompareExpr> list, DBCompareExpr expr)
+    { // adds a comparison to the where or having list
+        for (int i = 0; i < list.size(); i++)
+        { // check expression
+        	DBCompareExpr other = list.get(i);
+            if (expr.isMutuallyExclusive(other)==false)
+                continue;
+            // columns match
+            list.set(i, expr);
+            return;
+        }
+        // neue expression, or possible another expression
+        // for the same column when allowMultiple == true
+        list.add(expr);
+    }
+
+    /**
+     * Gets a list of all tables referenced by the query.
+     *  
+     * @return list of all rowsets (tables or views) used by the query
+     */
+    protected List<DBRowSet> getTableList()
+    {
+        // Check all tables
+        int i = 0;
+        Set<DBColumn> columns = new HashSet<DBColumn>();
+        for (i = 0; select != null && i < select.size(); i++)
+            ((DBExpr) select.get(i)).addReferencedColumns(columns);
+        for (i = 0; joins != null && i < joins.size(); i++)
+            ((DBExpr) joins.get(i)).addReferencedColumns(columns);
+        for (i = 0; where != null && i < where.size(); i++)
+            ((DBExpr) where.get(i)).addReferencedColumns(columns);
+        for (i = 0; groupBy != null && i < groupBy.size(); i++)
+            ((DBExpr) groupBy.get(i)).addReferencedColumns(columns);
+        for (i = 0; having != null && i < having.size(); i++)
+            ((DBExpr) having.get(i)).addReferencedColumns(columns);
+        for (i = 0; orderBy != null && i < orderBy.size(); i++)
+            ((DBExpr) orderBy.get(i)).addReferencedColumns(columns);
+        // now we have all columns
+        List<DBRowSet> tables = new ArrayList<DBRowSet>();
+        Iterator<DBColumn> iterator = columns.iterator();
+        while (iterator.hasNext())
+        { // get the table
+            DBColumn col = iterator.next();
+            DBRowSet table = col.getRowSet();
+            if (table == cmdQuery)
+            { // Recursion
+                log.error("Recursive Column Selection in Command!");
+                continue;
+            }
+            if (tables.contains(table) == false && table != null)
+            { // Tabelle hinzuf├╝gen
+                tables.add(table);
+            }
+        }
+        return tables;
+    }
+    
+    /**
+     * Adds Columns
+     */
+    @Override
+    public void addReferencedColumns(Set<DBColumn> list)
+    {
+        // nothing to do!
+        return;
+    } 
+    
+    /**
+     * Returns the list of parameter values for a prepared statement.
+     * 
+     * @return the list of parameter values for a prepared statement 
+     */
+    public Object[] getCmdParams()
+    {
+        if (cmdParams==null)
+            return null;
+        // return Params
+        return cmdParams.toArray();
+    }
+
+    /**
+     * Creates the update SQL-Command.
+     * 
+     * @return the update SQL-Command
+     */
+    public String getUpdate()
+    {
+        if (set == null)
+            return null;
+        StringBuilder buf = new StringBuilder("UPDATE ");
+        // addTableExpr(buf, CTX_NAME);
+        DBRowSet table =  set.get(0).getTable();
+        table.addSQL(buf, CTX_FULLNAME);
+        // Set Expressions
+        buf.append("\r\nSET ");
+        addListExpr(buf, set, CTX_DEFAULT, ", ");
+        // Constraints
+        if (where != null)
+        { // add where condition
+            buf.append("\r\nWHERE ");
+            if (where != null)
+                addListExpr(buf, where, CTX_NAME | CTX_VALUE, " AND ");
+        }
+        return buf.toString();
+    }
+
+    /**
+     * Creates the insert SQL-Command.
+     * 
+     * @return the insert SQL-Command
+     */
+    // get Insert
+    public String getInsert()
+    {
+        if (set==null || set.get(0)==null)
+            return null;
+        StringBuilder buf = new StringBuilder("INSERT INTO ");
+        // addTableExpr(buf, CTX_NAME);
+        DBRowSet table =  set.get(0).getTable();
+        table.addSQL(buf, CTX_FULLNAME);
+        // Set Expressions
+        buf.append("( ");
+        // Set Expressions
+        ArrayList<DBCompareColExpr> compexpr = null;
+        if (where != null)
+        {   // Convert ColumnExpression List to Column List
+            compexpr = new ArrayList<DBCompareColExpr>(where.size());
+            for (DBCompareExpr expr : where)
+            {   if (expr instanceof DBCompareColExpr)
+                {   DBColumn column = ((DBCompareColExpr)expr).getColumnExpr().getUpdateColumn();
+                    if (column!=null && hasSetExprOn(column)==false)
+                        compexpr.add((DBCompareColExpr)expr);
+                }
+            }
+            // Add Column Names from where clause
+            if (compexpr.size()>0)
+            {
+                // add List
+                addListExpr(buf, compexpr, CTX_NAME, ", ");
+                // add separator
+                if (set != null)
+                    buf.append(", ");
+            }
+            else
+            {   // No columns to set
+                compexpr = null;
+            }
+        }
+        if (set != null)
+            addListExpr(buf, set, CTX_NAME, ", ");
+        // Values
+        buf.append(") VALUES ( ");
+        if (compexpr != null)
+            addListExpr(buf, compexpr, CTX_VALUE, ", ");
+        if (compexpr != null && set != null)
+            buf.append(", ");
+        if (set != null)
+            addListExpr(buf, set, CTX_VALUE, ", ");
+        // End
+        buf.append(")");
+        return buf.toString();
+    }
+    
+    /**
+     * Creates the delete SQL-Command.
+     * 
+     * @return the delete SQL-Command
+     */
+    public String getDelete(DBTable table)
+    {
+        StringBuilder buf = new StringBuilder("DELETE FROM ");
+        table.addSQL(buf, CTX_FULLNAME);
+        // Set Expressions
+        if (where != null)
+        { // add where condition
+            buf.append("\r\nWHERE ");
+            if (where != null)
+                addListExpr(buf, where, CTX_NAME|CTX_VALUE, " AND ");
+        }
+        return buf.toString();
+    }
+    
+    // ------- Select Statement Parts -------
+
+    protected void addSelect(StringBuilder buf)
+    {
+        // Prepares statement
+        buf.append("SELECT ");
+        if (selectDistinct)
+            buf.append("DISTINCT ");
+        // Add Select Expressions
+        addListExpr(buf, select, CTX_ALL, ", ");
+    }
+
+    protected void addFrom(StringBuilder buf)
+    {
+        buf.append("\r\nFROM ");
+        // Join
+        boolean sep = false;
+        List<DBRowSet> tables = getTableList();
+        if (joins!=null )
+        {   // Join
+            List<DBRowSet> joinTables = new ArrayList<DBRowSet>();
+//          for (int i=0;i<joins.size();i++)
+//               buf.append("(");
+            for (int i=0;i<joins.size();i++)
+            {    // Joins zusammenbauen
+                 long context;
+                 DBJoinExpr join = joins.get(i);
+                 if (i<1)
+                 {   // Add Join Tables
+                     joinTables.add(join.getLeft() .getUpdateColumn().getRowSet());
+                     joinTables.add(join.getRight().getUpdateColumn().getRowSet());
+                     // Remove from List
+                     tables.remove(join.getLeft() .getUpdateColumn().getRowSet());
+                     tables.remove(join.getRight().getUpdateColumn().getRowSet());
+                     // Context
+                     context = CTX_NAME|CTX_VALUE;
+                 }
+                 else
+                 {   // Extend the join                    
+                     if ( joinTables.contains(join.getRight().getUpdateColumn().getRowSet()))
+                          join.reverse();
+                     // Add Right Table     
+                     joinTables.add(join.getRight().getUpdateColumn().getRowSet());
+                     tables .remove(join.getRight().getUpdateColumn().getRowSet());
+                     // Context
+                     context = CTX_VALUE;
+                     buf.append( "\t" );
+                 }
+                 join.addSQL(buf, context);
+//               buf.append(")");
+                 if( i!=joins.size()-1 )
+                     buf.append("\r\n");
+            }
+            sep = true;
+        }
+        for (int i=0; i<tables.size(); i++)
+        {
+            if (sep) buf.append(", ");
+            DBRowSet t = tables.get(i); 
+            t.addSQL(buf, CTX_DEFAULT|CTX_ALIAS);
+            sep = true;
+        }
+    }
+
+    protected void addWhere(StringBuilder buf)
+    {
+        if (where != null)
+        {   
+            buf.append("\r\nWHERE ");
+            // add where expression
+            addListExpr(buf, where, CTX_DEFAULT, " AND ");
+        }
+    }
+
+    protected void addGrouping(StringBuilder buf)
+    {
+        if (groupBy != null)
+        { // Having
+            buf.append("\r\nGROUP BY ");
+            addListExpr(buf, groupBy, CTX_DEFAULT, ", ");
+        }
+        if (having != null)
+        { // Having
+            buf.append("\r\nHAVING ");
+            addListExpr(buf, having, CTX_DEFAULT, " AND ");
+        }
+    }
+
+    protected void addOrder(StringBuilder buf)
+    {
+        if (orderBy != null)
+        { // order By
+            buf.append("\r\nORDER BY ");
+            addListExpr(buf, orderBy, CTX_DEFAULT, ", ");
+        }
+    }
+    
+}
\ No newline at end of file



Mime
View raw message