empire-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From doeb...@apache.org
Subject svn commit: r683173 [9/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/oracle/DBDatabaseDriverOracle.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/oracle/DBDatabaseDriverOracle.java?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/oracle/DBDatabaseDriverOracle.java (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/oracle/DBDatabaseDriverOracle.java Wed Aug  6 01:47:37 2008
@@ -0,0 +1,888 @@
+/*
+ * ESTEAM Software GmbH, 14.12.2004
+ */
+package org.apache.empire.db.oracle;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+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.DBReader;
+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 Oracle database system.<br>
+ * Oracle Version 9 or higher is required.
+ * 
+ * @author ESTEAM software <A TARGET="esteam" HREF="http://www.esteam.de">www.esteam.de </A>
+ * 
+ */
+public class DBDatabaseDriverOracle extends DBDatabaseDriver
+{
+    // Implementation of boolean types
+    public enum BooleanType
+    {
+        CHAR,       // as CHAR(1) with 'Y' for true and 'N' for false
+        NUMBER      // as NUMBER(1) with 1 for true and 0 for false
+    }
+    
+    private BooleanType booleanType = BooleanType.NUMBER;
+
+    /**
+     * Constructor for the Oracle database driver.<br>
+     * 
+     */
+    public DBDatabaseDriverOracle()
+    {
+        // Info
+        log.info("DBDatabaseDriverOracle created. Boolean Type is " + String.valueOf(booleanType));
+    }
+
+    public BooleanType getBooleanType()
+    {
+        return booleanType;
+    }
+
+    public void setBooleanType(BooleanType booleanType)
+    {
+        this.booleanType = booleanType;
+        log.info("DBDatabaseDriverOracle Boolean Type set to " + String.valueOf(booleanType));
+    }
+
+    /**
+     * 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;
+    }
+
+    /**
+     * Creates a new Oracle command object.
+     * 
+     * @return the new DBCommandOracle object
+     */
+    @Override
+    public DBCommand createCommand(DBDatabase db)
+    {
+        if (db == null)
+            return null;
+        // create oracle command
+        return new DBCommandOracle(db);
+    }
+
+    /**
+     * 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 (booleanType==BooleanType.CHAR) ? "'Y'" : "1";
+            case SQL_BOOLEAN_FALSE:             return (booleanType==BooleanType.CHAR) ? "'N'" : "0";
+            case SQL_CURRENT_DATE:              return "sysdate";
+            case SQL_DATE_PATTERN:              return "yyyy-MM-dd";
+            case SQL_DATE_TEMPLATE:             return "TO_DATE('{0}', 'YYYY-MM-DD')";
+            case SQL_CURRENT_DATETIME:          return "sysdate";
+            case SQL_DATETIME_PATTERN:          return "yyyy-MM-dd HH:mm:ss";
+            case SQL_DATETIME_TEMPLATE:         return "TO_DATE('{0}', 'YYYY-MM-DD HH24:MI:SS')";
+            // functions
+            case SQL_FUNC_COALESCE:             return "nvl(?, {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 "instr(?, {0})"; 
+            case SQL_FUNC_STRINDEXFROM:         return "instr(?, {0}, {1})"; 
+            case SQL_FUNC_LENGTH:               return "length(?)";
+            case SQL_FUNC_UPPER:                return "upper(?)";
+            case SQL_FUNC_LOWER:                return "lower(?)";
+            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 "trunc(?,{0})";
+            case SQL_FUNC_CEILING:              return "ceil(?)";
+            case SQL_FUNC_FLOOR:                return "floor(?)";
+            // Date
+            case SQL_FUNC_DAY:                  return "TO_CHAR(?,'DD')";
+            case SQL_FUNC_MONTH:                return "TO_CHAR(?,'MM')";
+            case SQL_FUNC_YEAR:                 return "TO_CHAR(?,'YYYY')";
+            // 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 "decode(? {0})";
+            case SQL_FUNC_DECODE_SEP:           return ",";
+            case SQL_FUNC_DECODE_PART:          return "{0}, {1}";
+            case SQL_FUNC_DECODE_ELSE:          return "{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:
+            case CLOB:
+                if (format != null)
+                { // Convert using a format string
+                    return "to_char(?, '"+format.toString()+"')";
+                }
+                return "to_char(?)";
+            // Convert to number
+            case INTEGER:
+            case DOUBLE:
+            case DECIMAL:
+                if (format != null)
+                { // Convert using a format string
+                    return "to_number(?, '"+format.toString()+"')";
+                }
+                return "to_number(?)";
+            // Convert to date
+            case DATE:
+            case DATETIME:
+                if (format != null)
+                { // Convert using a format string
+                    return "to_date(?, '"+format.toString()+"')";
+                }
+                return "to_date(?)";
+            // Unknown Type
+            default:
+                log.error("getConvertPhrase: unknown type (" + String.valueOf(destType));
+                return "?";
+        }
+    }
+
+    /**
+     * Extracts native error message of an sqlExeption.
+     * 
+     * @param sqle the SQLException
+     * @return the error message of the database 
+     */
+    @Override
+    public String extractErrorMessage(SQLException sqle)
+    {
+        String msg = sqle.getMessage();
+        msg = msg.substring(msg.indexOf(':') + 1);
+        // Find End
+        int end = msg.indexOf("ORA");
+        if (end >= 0)
+            msg = msg.substring(0, end - 1);
+        return msg;
+    }
+    
+    /**
+     * Gets the value of a sql ResultSet.
+     * Gives the driver the oportunity to change the value
+     * i.e. to simulate missing data types with other types.
+     * 
+     * @param rset the sql Resultset with the current data row
+     * @param columnIndex one based column Index of the desired column
+     * @param dataType the desired data type
+     * @return the value of the column 
+     */
+    @Override
+    public Object getResultValue(ResultSet rset, int columnIndex, DataType dataType)
+        throws SQLException
+    {
+        // Check for character large object
+        if (dataType == DataType.BOOL)
+        {   // Get character large object
+            String val = rset.getString(columnIndex);
+            if (val==null || rset.wasNull())
+                return null;
+            // Check Value
+            if (val.equalsIgnoreCase("Y") || val.equals("1"))
+                return Boolean.TRUE;
+            return Boolean.FALSE;    
+        }
+        // Default
+        return super.getResultValue(rset, columnIndex, dataType);
+    }
+
+    /**
+     * @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 ");
+        db.appendQualifiedName(sql, seqName);
+        sql.append(".NEXTVAL FROM DUAL");
+        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(), "USER", 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
+        ResultSet rs = null;
+        try
+        {   // Oracle Timestamp query
+            rs = executeQuery("select sysdate from dual", null, false, conn);
+            return (rs.next() ? rs.getTimestamp(1) : null);
+        } catch (Exception e)
+        {
+            log.error("getUpdateTimestamp exception: " + e);
+            error(e);
+            return null;
+        } finally
+        { // Cleanup
+            try
+            { // ResultSet close
+                Statement stmt = (rs!=null) ?  rs.getStatement() : null;
+                if (rs != null)
+                    rs.close();
+                if (stmt != null)
+                    stmt.close();
+            } catch (SQLException sqle)
+            {
+                log.error("getUpdateTimestamp close exception: " + sqle);
+            }
+        }
+    }
+
+    /**
+     * Returns true if the database has been created successfully.
+     * 
+     * @return true if the database has been created successfully
+     */
+    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))
+                if (getErrorType()!=Errors.NotImplemented)
+                    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.getFullName());
+        sql.append(" --\r\n");
+        sql.append("CREATE SEQUENCE ");
+        db.appendQualifiedName(sql, seqName);
+        sql.append(" INCREMENT BY 1 START WITH 1 MINVALUE 0 NOCYCLE NOCACHE NOORDER");
+        // 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
+        DBDatabase db = t.getDatabase();
+        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());
+                sql.append("");
+                addSeparator = true;
+            }
+            sql.append(")");
+            // Create Index
+            if (script.addStmt(sql) == false)
+                return false;
+        }
+        // add Comments
+        createComment(db, "TABLE", t.getFullName(), t.getComment(), script);
+        columns = t.getColumns().iterator();
+        while (columns.hasNext())
+        {
+            DBColumn c = columns.next();
+            String com = c.getComment();
+            if (com != null)
+                createComment(db, "COLUMN", c.getFullName(), com, script);
+        }
+        // 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("VARCHAR2(");
+                sql.append(String.valueOf(size));
+                sql.append(" char)");
+            }
+                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:
+                if ( booleanType==BooleanType.CHAR )
+                     sql.append("CHAR(1)");
+                else sql.append("NUMBER(1,0)");
+                break;
+            case DOUBLE:
+                sql.append("FLOAT(80)");
+                break;
+            case DECIMAL:
+            {
+                sql.append("NUMBER(");
+                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;
+    }
+
+    /**
+     * Create a sql string for creating a relation and appends it to the supplied buffer
+     * @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(")");
+        // done
+        return script.addStmt(sql);
+    }
+
+    /**
+     * 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 OR REPLACE 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 comment has been created successfully.
+     * 
+     * @return true if the comment has been created successfully
+     */
+    private boolean createComment(DBDatabase db, String type, String objName, String comment, DBSQLScript script)
+    {
+        if (comment==null || comment.length()==0)
+            return true;
+        StringBuilder sql = new StringBuilder();
+        sql.append("COMMENT ON ");
+        sql.append(type);
+        sql.append(" ");
+        sql.append(objName);
+        sql.append(" IS '");
+        sql.append(comment);
+        sql.append("'");
+        // Create Index
+        return script.addStmt(sql);
+    }
+    
+    /**
+     * 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);
+    }
+
+    
+    /**
+     * Checks whether the database defintion matches the real database structure.
+     * 
+     * @return true if the database defintion matches the real database structure.
+     */
+    @Override
+    public boolean checkDatabase(DBDatabase db, String owner, Connection conn)
+    {
+        // Check Params
+        if (owner==null || owner.length()==0)
+            return error(Errors.InvalidArg, owner, "owner");
+        // Datebase definition
+        OracleSYSDatabase sysDB = new OracleSYSDatabase(this);
+        // Check Columns
+        DBCommand sysDBCommand = sysDB.createCommand();
+        sysDBCommand.select(sysDB.CI.getColumns());
+        sysDBCommand.where (sysDB.CI.C_OWNER.is(owner));
+        
+        OracleDataDictionnary dataDictionnary = new OracleDataDictionnary();
+        DBReader rd = new DBReader();
+        try
+        {
+            if (rd.open(sysDBCommand, conn))
+            {
+                log.info("---------------------------------------------------------------------------------");
+                log.info("checkDatabase start: " + db.getClass().getName());
+                String skipTable = "";
+                while (rd.moveNext())
+                {
+                    String tableName = rd.getString(sysDB.CI.C_TABLE_NAME);
+
+                    // if a table wasn't found before, skip it
+                    if (tableName.equals(skipTable))
+                        continue;
+
+                    // check if the found table exists in the DBDatabase object
+                    String columnName = rd.getString(sysDB.CI.C_COLUMN_NAME);
+                    DBTable dbTable = db.getTable(tableName);
+                    DBView  dbView  = db.getView(tableName);
+                    
+                    String dataType = rd.getString(sysDB.CI.C_DATA_TYPE);
+                    int charLength = rd.getInt(sysDB.CI.C_CHAR_LENGTH);
+                    int dataLength = rd.getInt(sysDB.CI.C_DATA_LENGTH);
+                    int dataPrecision = rd.getInt(sysDB.CI.C_DATA_PRECISION);
+                    int dataScale = rd.getInt(sysDB.CI.C_DATA_SCALE);
+                    String nullable = rd.getString(sysDB.CI.C_NULLABLE);
+                    
+                    dataDictionnary.fillDataDictionnary(tableName, columnName, dataType, 
+                                                        charLength, dataLength, dataPrecision, dataScale, nullable);
+                    
+                    if (dbTable != null)
+                    {
+                        
+                        // check if the found column exists in the found DBTable
+                        DBColumn col = dbTable.getColumn(columnName);
+                        if (col == null)
+                        {
+                            log.warn("COLUMN NOT FOUND IN " + db.getClass().getName() + "\t: [" + tableName + "]["
+                                           + columnName + "][" + dataType + "][" + dataLength + "]");
+                            continue;
+                        }
+                        /*
+                        else
+                        {   // check the DBTableColumn definition
+                            int length = (charLength>0) ? charLength : dataLength;
+                            dataDictionnary.checkColumnDefinition(col, dataType, length, dataPrecision, dataScale, nullable.equals("N"));
+                        }
+                        */
+                    } 
+                    else if (dbView!=null)
+                    {
+                        log.debug("Column check for view " + tableName + " not yet implemented.");
+                    } 
+                    else
+                    {
+                        log.debug("TABLE OR VIEW NOT FOUND IN " + db.getClass().getName() + "\t: [" + tableName + "]");
+                        // skip this table
+                        skipTable = tableName;
+                        continue;
+                    }
+                }
+                // check Tables
+                dataDictionnary.checkDBTableDefinition(db.getTables());
+                // check Views
+                dataDictionnary.checkDBViewDefinition (db.getViews()); 
+            }
+            else {
+                return error(Errors.NotAuthorized);
+            }
+            log.info("checkDatabase end: " + db.getClass().getName());
+            log.info("---------------------------------------------------------------------------------");
+            return success();
+        } finally
+        {
+            rd.close();
+        }
+    }
+
+}
+

Added: incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/oracle/OracleDataDictionnary.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/oracle/OracleDataDictionnary.java?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/oracle/OracleDataDictionnary.java (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/oracle/OracleDataDictionnary.java Wed Aug  6 01:47:37 2008
@@ -0,0 +1,260 @@
+package org.apache.empire.db.oracle;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.empire.data.DataType;
+import org.apache.empire.db.DBColumn;
+import org.apache.empire.db.DBTable;
+import org.apache.empire.db.DBView;
+
+
+public class OracleDataDictionnary {
+    
+    private class ColumnInfo {
+
+        private String dataType;
+        private int charLength;
+        private int dataLength;
+        private int dataPrecision;
+        private int dataScale;
+        private String nullable;
+        
+        public ColumnInfo(String dataType, int charLength, int dataLength, int dataPrecision, int dataScale, String nullable)
+        {
+            super();
+            this.dataType = dataType;
+            this.charLength = charLength;
+            this.dataLength = dataLength;
+            this.dataPrecision = dataPrecision;
+            this.dataScale = dataScale;
+            this.nullable = nullable;
+        }
+
+        public int getCharLength()
+        {
+            return charLength;
+        }
+
+        public int getDataLength()
+        {
+            return dataLength;
+        }
+
+        public int getDataPrecision()
+        {
+            return dataPrecision;
+        }
+
+        public int getDataScale()
+        {
+            return dataScale;
+        }
+
+        public String getDataType()
+        {
+            return dataType;
+        }
+
+        public String getNullable()
+        {
+            return nullable;
+        }
+
+    }
+    
+    protected static Log log = LogFactory.getLog(OracleDataDictionnary.class);
+    HashMap<String, HashMap<String, ColumnInfo>> dictionnary = new HashMap<String, HashMap<String, ColumnInfo>>();
+    private Map<String, DataType[]> dataTypeMapping    = null;
+
+    /**
+     * Defines mapping of the Empire-db data types with the oracle data types.
+     */
+    public OracleDataDictionnary() {
+        dataTypeMapping = new HashMap<String, DataType[]>();
+        dataTypeMapping.put("VARCHAR2", new DataType[] { DataType.TEXT });
+        dataTypeMapping.put("CHAR",     new DataType[] { DataType.CHAR, DataType.BOOL });
+        dataTypeMapping.put("NUMBER",   new DataType[] { DataType.DECIMAL, DataType.DOUBLE, 
+                                                         DataType.INTEGER, DataType.AUTOINC, DataType.BOOL });
+        dataTypeMapping.put("DATE",     new DataType[] { DataType.DATE, DataType.DATETIME });
+        dataTypeMapping.put("CLOB",     new DataType[] { DataType.CLOB });
+        dataTypeMapping.put("BLOB",     new DataType[] { DataType.BLOB });
+    }
+    
+    public HashMap<String, HashMap<String, ColumnInfo>> getDictionnary() {
+        return dictionnary;
+    }
+
+
+    public void fillDataDictionnary(String tableName, String columnName, String dataType, int charLength, int dataLength, int dataPrecision, int dataScale, String nullable) {
+        ColumnInfo colInfo = new ColumnInfo(dataType, charLength, dataLength, dataPrecision, dataScale, nullable);
+        HashMap<String, ColumnInfo> columns = new HashMap<String, ColumnInfo>();
+        
+        if(dictionnary.containsKey(tableName)) {
+            columns = dictionnary.get(tableName);
+        }
+        columns.put(columnName, colInfo);
+        dictionnary.put(tableName, columns);
+    }
+    
+    /**
+     * Checks if the ORACLE datatype can be mapped with a DBTable data type.
+     * 
+     * @param dbDatatype ORACLE datatype
+     * @param colDataType DBTableColumn datatype
+     * @return true if the type can be mapped, false otherwise
+     */
+    private boolean checkMapping(String dbDatatype, DataType colDataType)
+    {
+        DataType[] colTypes = dataTypeMapping.get(dbDatatype);
+        if(colTypes == null) 
+        {
+            log.warn("MAPPING NOT DEFINED FOR " + dbDatatype + " -> " + colDataType);
+            return false;
+        }
+        for (int i = 0; i < colTypes.length; i++)
+        {
+            if (colTypes[i] == colDataType)
+                return true;
+        }
+        return false;
+    }
+    
+    /**
+     * Checks a DBTableColumn definition. The set attributes must fint to the overgiven db attributes.
+     * 
+     * @param col Column to check
+     * @param dbDataType Datatype of db column
+     * @param dbDataLength Datalength of db column
+     * @param dbDataPrecision Data precision of db column
+     * @param dbDataScale Data scale of db column
+     * @param dbRequired Is nullable of the db column
+     * @return true if the column definition fits, false otherwise
+
+    private boolean checkColumnDefinition(DBColumn col, String dbDataType, int dbDataLength, int dbDataPrecision,
+                                          int dbDataScale, boolean dbRequired)
+    {
+        // FUTURE find a way to check the precision for numbers
+
+        boolean result = true;
+        DataType colDataType = col.getDataType();
+        int size = (int) col.getSize();
+
+        // check if the column data type can be mapped with the db column data type
+        if (checkMapping(dbDataType, colDataType) == false)
+        {
+            log.warn("WRONG DATATYPE \t\t\t\t\t\t: [" + col.getRowSet().getName() + "][" + col.getName() + "] -> DB : ["
+                           + dbDataType + "]" + "[" + dbDataLength + "]");
+            result = false;
+        }
+
+        // check if the column is required and if the column is defined as required
+        if (dbRequired && col.isRequired() == false)
+        {
+            log.warn("COLUMN IS REQUIRED \t\t\t\t\t: [" + col.getRowSet().getName() + "][" + col.getName() + "]");
+            result = false;
+        } 
+        else if (dbRequired == false && col.isRequired() == true)
+        {
+            log.warn("COLUMN IS NOT REQUIRED \t\t\t\t: [" + col.getRowSet().getName() + "][" + col.getName() + "]");
+            result = false;
+        }
+
+        // check the data length if the column is a varchar2
+        if (dbDataType.equals("VARCHAR2") && (dbDataLength != size))
+        {
+            log.warn("WRONG COLUMN SIZE \t\t\t\t\t: [" + col.getRowSet().getName() + "][" + col.getName() + "] -> DB : ["
+                           + dbDataType + "][" + dbDataLength + "]");
+            result = false;
+        }
+
+        return result;
+    }
+     */
+    
+    private void checkColumn(DBColumn column, ColumnInfo colInfo)
+    {
+        if(checkMapping(colInfo.getDataType(), column.getDataType()) == false) {
+            log.warn("WRONG DATA TYPE: \t" + column.getFullName() + " is set to " + column.getDataType() +
+                     " instead of " + colInfo.getDataType());
+        }
+        if(colInfo.getDataType().equals("VARCHAR2") && (column.getSize() != colInfo.getCharLength())) {
+            log.warn("WRONG COLUMN SIZE: \t" + column.getFullName() + " is set to " + (int)column.getSize() +
+                     " instead of " + colInfo.getCharLength()); 
+        }    
+        if(column.isRequired() != colInfo.getNullable().equals("N")) {
+            log.warn("WRONG NULLABLE FLAG: \t" + column.getFullName() + " is set to " + column.isRequired() +
+                     " instead of " + colInfo.getNullable().equals("N")); 
+        }
+    }
+    
+    public void checkDBTableDefinition(List<DBTable> dbTables) {
+        // go through all tables defined in the Java code
+        for(DBTable currentTable: dbTables) {
+            String dbTableName = currentTable.getName();
+            // check if the table name is in the data dictionnary
+            if(this.dictionnary.containsKey(dbTableName)) {
+                // go through all columns of the table
+                for(DBColumn currentColumn : currentTable.getColumns()) {
+                    Collection<String> dictColumns = this.dictionnary.get(dbTableName).keySet();
+                    // check if the column name is in the data dictionnary
+                    if(dictColumns.contains(currentColumn.getName())) {
+                        // go through all columns of the table in the data dictionnary
+                        for(String dictColumn : dictColumns) {
+                            // compare the columnnames
+                            if(currentColumn.getName().equals(dictColumn)) {
+                                ColumnInfo colInfo = this.dictionnary.get(currentTable.getName()).get(dictColumn);
+                                checkColumn(currentColumn, colInfo);
+                            }
+                        }
+                    }
+                    else {
+                        log.warn("MISSING COLUMN: \t" + currentColumn.getFullName() + " does not exist in database"); 
+                    }
+                }
+            }
+            else {
+                log.warn("MISSING TABLE: \t" + currentTable.getName() + " does not exist in database"); 
+            }
+        }
+    }
+    
+    public void checkDBViewDefinition(List<DBView> dbViews) {
+//      go through all views defined in the Java code
+        for(DBView currentView: dbViews) {
+            String dbviewName = currentView.getName();
+            // check if the view name is in the data dictionnary
+            if(this.dictionnary.containsKey(dbviewName)) {
+                // go through all columns of the table
+                for(DBColumn currentColumn : currentView.getColumns()) {
+                    Collection<String> dictColumns = this.dictionnary.get(dbviewName).keySet();
+                    // check if the column name is in the data dictionnary
+                    if(dictColumns.contains(currentColumn.getName())) {
+                        // go through all columns of the view in the data dictionnary
+                        for(String dictColumn : dictColumns) {
+                            // compare the columnnames                           
+                            if(currentColumn.getName().equals(dictColumn)) {
+                                ColumnInfo colInfo = this.dictionnary.get(currentView.getName()).get(dictColumn);
+                                if(checkMapping(colInfo.getDataType(), currentColumn.getDataType()) == false) {
+                                    log.warn("WRONG DATA TYPE: \t" + currentColumn.getFullName() + " is set to " + currentColumn.getDataType() +
+                                             " instead of " + colInfo.getDataType());
+                                }
+                            }
+                        }
+                    }
+                    else {
+                        log.warn("MISSING COLUMN: \t" + currentColumn.getFullName() + " does not exist in database."); 
+                    }
+                }
+            }
+            else {
+                log.warn("MISSING VIEW: \t" + currentView.getName() + " does not exist in database."); 
+            }
+        }
+    }
+    
+}

Added: incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/oracle/OracleSYSDatabase.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/oracle/OracleSYSDatabase.java?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/oracle/OracleSYSDatabase.java (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/oracle/OracleSYSDatabase.java Wed Aug  6 01:47:37 2008
@@ -0,0 +1,155 @@
+/*
+ * ESTEAM Software GmbH
+ */
+package org.apache.empire.db.oracle;
+
+// java
+import org.apache.empire.data.DataType;
+import org.apache.empire.db.*;
+
+/**
+ * Represents the data model of the system tables.
+ * They are required to parse the data models.
+ * <P>
+ * 
+ * @author ESTEAM software <A TARGET="esteam" HREF="http://www.esteam.de">www.esteam.de</A>
+ */
+public class OracleSYSDatabase extends DBDatabase 
+{
+
+    // Table for all tables of a schema with their comments
+    public static class DBTabComments extends DBTable
+    {
+      public DBTableColumn C_OWNER;
+      public DBTableColumn C_TABLE_NAME;
+      public DBTableColumn C_TABLE_TYPE;
+      public DBTableColumn C_COMMENTS;
+      // Constructor
+      public DBTabComments(DBDatabase db)
+      {
+        super("ALL_TAB_COMMENTS", db);
+        // add all Colums
+        C_OWNER       = addColumn("OWNER",      DataType.TEXT, 50, false);
+        C_TABLE_NAME  = addColumn("TABLE_NAME", DataType.TEXT, 50, false);
+        C_TABLE_TYPE  = addColumn("TABLE_TYPE", DataType.TEXT, 50, false);
+        C_COMMENTS    = addColumn("COMMENTS",   DataType.TEXT, 500, false);
+      }
+    }
+
+    // Table for all constraints
+    public static class DBConstraints extends DBTable
+    {
+      public DBTableColumn C_CONSTRAINT_NAME;
+      public DBTableColumn C_TABLE_NAME;
+      public DBTableColumn C_R_CONSTRAINT_NAME;
+      public DBTableColumn C_CONSTRAINT_TYPE;
+      public DBTableColumn C_STATUS;
+      // Constructor
+      public DBConstraints(DBDatabase db)
+      {
+        super("ALL_CONSTRAINTS", db);
+        // add all Colums
+      
+        C_CONSTRAINT_NAME    = addColumn("CONSTRAINT_NAME",     DataType.TEXT, 100, false);
+        C_TABLE_NAME         = addColumn("TABLE_NAME",          DataType.TEXT, 100, false);
+        C_R_CONSTRAINT_NAME  = addColumn("R_CONSTRAINT_NAME",   DataType.TEXT, 100, false);
+        C_CONSTRAINT_TYPE    = addColumn("CONSTRAINT_TYPE",     DataType.TEXT, 1, false);
+        C_STATUS             = addColumn("STATUS",              DataType.TEXT, 20, false);
+      }
+    }
+
+    // Table for Columns and Tables a constraint is associated to
+    public static class DBUserConCol extends DBTable
+    {
+      public DBTableColumn C_CONSTRAINT_NAME;
+      public DBTableColumn C_TABLE_NAME;
+      public DBTableColumn C_COLUMN_NAME;
+      public DBTableColumn C_OWNER;
+      // Constructor
+      public DBUserConCol(DBDatabase db)
+      {
+        super("USER_CONS_COLUMNS", db);
+        // add all Colums
+      
+        C_CONSTRAINT_NAME = addColumn("CONSTRAINT_NAME",    DataType.TEXT, 100, false);
+        C_TABLE_NAME      = addColumn("TABLE_NAME",         DataType.TEXT, 100, false);
+        C_COLUMN_NAME     = addColumn("COLUMN_NAME",        DataType.TEXT, 100, false);
+        C_OWNER           = addColumn("OWNER",              DataType.TEXT, 100, false);
+        setPrimaryKey(C_CONSTRAINT_NAME);
+      }
+    }
+
+    // Table for all columns of a schema with their comments
+    public static class DBColInfo extends DBTable
+    {
+      public DBTableColumn C_OWNER;
+      public DBTableColumn C_TABLE_NAME;
+      public DBTableColumn C_COLUMN_NAME;
+      public DBTableColumn C_DATA_TYPE;
+      public DBTableColumn C_DATA_TYPE_MOD;
+      public DBTableColumn C_DATA_TYPE_OWNER;
+      public DBTableColumn C_NULLABLE;
+      public DBTableColumn C_DATA_LENGTH;
+      public DBTableColumn C_DATA_PRECISION;
+      public DBTableColumn C_DATA_SCALE;
+      public DBTableColumn C_CHAR_LENGTH;
+
+      // Constructor
+      public DBColInfo(DBDatabase db)
+      {
+        super("ALL_TAB_COLUMNS", db);
+        // add all Colums
+        C_OWNER           = addColumn("OWNER",           DataType.TEXT,   30, false);
+        C_TABLE_NAME      = addColumn("TABLE_NAME",      DataType.TEXT,   30, false);
+        C_COLUMN_NAME     = addColumn("COLUMN_NAME",     DataType.TEXT,   30, false);
+        C_DATA_TYPE       = addColumn("DATA_TYPE",       DataType.TEXT,   50, false);
+        C_DATA_TYPE_MOD   = addColumn("DATA_TYPE_MOD",   DataType.TEXT,   50, false);
+        C_DATA_TYPE_OWNER = addColumn("DATA_TYPE_OWNER", DataType.TEXT,   50, false);
+        C_NULLABLE        = addColumn("NULLABLE",        DataType.TEXT,    1, false);
+        C_DATA_LENGTH     = addColumn("DATA_LENGTH",     DataType.DECIMAL, 0, false);
+        C_DATA_PRECISION  = addColumn("DATA_PRECISION",  DataType.DECIMAL, 0, false);
+        C_DATA_SCALE      = addColumn("DATA_SCALE",      DataType.DECIMAL, 0, false);
+        C_CHAR_LENGTH     = addColumn("CHAR_LENGTH",     DataType.DECIMAL, 0, false);
+      }
+    }
+
+    // Table for all columns of a schema with their comments
+    public static class DBColComments extends DBTable
+    {
+      public DBTableColumn C_OWNER;
+      public DBTableColumn C_TABLE_NAME;
+      public DBTableColumn C_COLUMN_NAME;
+      public DBTableColumn C_COMMENTS;
+      // Constructor
+      public DBColComments(DBDatabase db)
+      {
+        super("ALL_COL_COMMENTS", db);
+        // add all Colums
+        C_OWNER        = addColumn("OWNER",       DataType.TEXT, 50, false);
+        C_TABLE_NAME   = addColumn("TABLE_NAME",  DataType.TEXT, 50, false);
+        C_COLUMN_NAME  = addColumn("COLUMN_NAME", DataType.TEXT, 50, false);
+        C_COMMENTS     = addColumn("COMMENTS",    DataType.TEXT, 500, false);
+      }
+    }
+
+    public DBTabComments  TC = null;
+    public DBColInfo      CI = null;
+    public DBColComments  CC = null;  
+    public DBConstraints  CO = null;  
+    public DBUserConCol   UC = null;  
+
+    public OracleSYSDatabase(DBDatabaseDriverOracle driver)
+    {
+       // System schema
+       super("SYS");
+       // Set Driver (do not use open(...)!)
+       this.driver = driver; 
+       // Add Tables
+       TC = new DBTabComments (this); 
+       CI = new DBColInfo     (this);  
+       CC = new DBColComments (this); 
+       CO = new DBConstraints (this);  
+       UC = new DBUserConCol  (this);  
+    }
+
+}
\ No newline at end of file

Added: incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/oracle/package.html
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/oracle/package.html?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/oracle/package.html (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/oracle/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 classes necessary to support the Oracle database system.
+Only Version 9 or higher is supported.
+
+</body></html>
\ No newline at end of file

Added: incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/package.html
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/package.html?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/package.html (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/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 the core Empire-DB implementation classes.
+
+</body></html>
\ No newline at end of file

Added: incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/sqlserver/DBDatabaseDriverMSSQL.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/sqlserver/DBDatabaseDriverMSSQL.java?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/sqlserver/DBDatabaseDriverMSSQL.java (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/sqlserver/DBDatabaseDriverMSSQL.java Wed Aug  6 01:47:37 2008
@@ -0,0 +1,703 @@
+/*
+ * ESTEAM Software GmbH, 14.12.2004
+ */
+package org.apache.empire.db.sqlserver;
+
+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 Microsoft SQL-Server database system.
+ * 
+ * @author ESTEAM software <A TARGET="esteam" HREF="http://www.esteam.de">www.esteam.de </A>
+ * 
+ */
+public class DBDatabaseDriverMSSQL extends DBDatabaseDriver
+{
+    /**
+     * Defines the Microsoft SQL-Server command type.
+     */ 
+    public static class DBCommandMSSQL extends DBCommand
+    {
+    	public DBCommandMSSQL(DBDatabase db)
+    	{
+    		super(db);
+    	}
+    }
+	
+    // Properties
+    private String databaseName = null;
+    private String objectOwner = "dbo";
+    private String sequenceTableName = "Sequences";
+    
+    /**
+     * Constructor for the MSSQL database driver.<br>
+     */
+    public DBDatabaseDriverMSSQL()
+    {
+        // Default Constructor
+    }
+
+    public String getDatabaseName()
+    {
+        return databaseName;
+    }
+
+    public void setDatabaseName(String databaseName)
+    {
+        this.databaseName = databaseName;
+    }
+
+    public String getObjectOwner()
+    {
+        return objectOwner;
+    }
+
+    public void setObjectOwner(String objectOwner)
+    {
+        this.objectOwner = objectOwner;
+    }
+
+    /**
+     * 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.
+     * @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);
+            // Set Dateformat
+            executeSQL("SET DATEFORMAT ymd", null, conn);
+            // Sequence Table
+            if (db.getTable(sequenceTableName)==null)
+                new DBSeqTable(sequenceTableName, db);
+            // Check Schema
+            String schema = db.getSchema();
+            if (StringUtils.isValid(schema) && schema.indexOf('.')<0 && StringUtils.isValid(objectOwner))
+            {   // append database owner
+                db.setSchema(schema + "." + objectOwner);
+            }
+            // call Base implementation
+            return super.attachDatabase(db, conn);
+            
+        } catch (SQLException e)
+        {
+            return error(e);
+        }
+    }
+
+    /**
+     * Creates a new Microsoft SQL-Server command object.
+     * 
+     * @return the new DBCommandMSSQL object
+     */
+    @Override
+    public DBCommand createCommand(DBDatabase db)
+    {
+        if (db == null)
+            return null;
+        // create command object
+        return new DBCommandMSSQL(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 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 "1";
+            case SQL_BOOLEAN_FALSE:           return "0";
+            case SQL_CURRENT_DATE:            return "convert(char, getdate(), 111)";
+            case SQL_DATE_PATTERN:            return "yyyy-MM-dd";
+            case SQL_DATE_TEMPLATE:           return "'{0}'";
+            case SQL_CURRENT_DATETIME:        return "getdate()";
+            case SQL_DATETIME_PATTERN:        return "yyyy-MM-dd HH:mm:ss.SSS";
+            case SQL_DATETIME_TEMPLATE:       return "'{0}'";
+            // functions
+            case SQL_FUNC_COALESCE:           return "coalesce(?, {0})";
+            case SQL_FUNC_SUBSTRING:          return "substring(?, {0}, 4000)";
+            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 "charindex({0}, ?)"; 
+            case SQL_FUNC_STRINDEXFROM:       return "charindex({0}, ?, {1})"; 
+            case SQL_FUNC_LENGTH:             return "len(?)";
+            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 "trunc(?,{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 "convert(bit, ?)";
+           case INTEGER:   return "convert(int, ?)";
+           case DECIMAL:   return "convert(decimal, ?)";
+           case DOUBLE:    return "convert(float, ?)";
+           case DATE:      return "convert(datetime, ?, 111)";
+           case DATETIME:  return "convert(datetime, ?, 120)";
+           // Convert to text
+           case TEXT:
+                // Date-Time-Format "YYYY-MM-DD hh.mm.ss"
+                if (srcType==DataType.DATE)
+                    return "replace(convert(nvarchar, ?, 111), '/', '-')";
+                if (srcType==DataType.DATETIME)
+                    return "convert(nvarchar, ?, 120)";
+                return "convert(nvarchar, ?)";
+           case BLOB:
+                return "convert(varbinary, ?)";
+           // 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
+        DBTable t = db.getTable(sequenceTableName);
+        return ((DBSeqTable)t).getNextValue(seqName, minValue, 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, "getDDLCommand."+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("USE master");
+            script.addStmt("CREATE DATABASE " + databaseName);
+            script.addStmt("USE " + databaseName);
+            script.addStmt("SET DATEFORMAT ymd");
+            // Sequence Table
+            if (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(",\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());
+                sql.append("");
+                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("[int]");
+                break;
+            case AUTOINC:
+                sql.append("[int]");
+                break;
+            case TEXT:
+            { // Check fixed or variable length
+                int size = Math.abs((int) c.getSize());
+                if (size == 0)
+                    size = 100;
+                sql.append("[nvarchar](");
+                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("[datetime]");
+                break;
+            case DATETIME:
+                sql.append("[datetime]");
+                break;
+            case BOOL:
+                sql.append("[bit]");
+                break;
+            case DOUBLE:
+                sql.append("[float]");
+                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("[ntext]");
+                break;
+            case BLOB:
+                sql.append("[image]");
+                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(" ALTER COLUMN ");
+                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/sqlserver/package.html
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/sqlserver/package.html?rev=683173&view=auto
==============================================================================
--- incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/sqlserver/package.html (added)
+++ incubator/empire-db/trunk/core/Empire-db/src/org/apache/empire/db/sqlserver/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 Microsoft SQL-Server database system.
+
+</body></html>
\ No newline at end of file



Mime
View raw message