db-torque-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From tfisc...@apache.org
Subject svn commit: r1206426 [2/7] - in /db/torque/torque4/trunk: torque-runtime/src/main/java/org/apache/torque/ torque-runtime/src/main/java/org/apache/torque/avalon/ torque-runtime/src/main/java/org/apache/torque/dsfactory/ torque-runtime/src/main/java/org/...
Date Sat, 26 Nov 2011 10:59:52 GMT
Modified: db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/sql/SqlBuilder.java
URL: http://svn.apache.org/viewvc/db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/sql/SqlBuilder.java?rev=1206426&r1=1206425&r2=1206426&view=diff
==============================================================================
--- db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/sql/SqlBuilder.java
(original)
+++ db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/sql/SqlBuilder.java
Sat Nov 26 10:59:15 2011
@@ -20,13 +20,15 @@ package org.apache.torque.sql;
  */
 
 import java.util.ArrayList;
-import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 
 import org.apache.commons.lang.StringUtils;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
+import org.apache.torque.Column;
+import org.apache.torque.ColumnImpl;
+import org.apache.torque.Database;
 import org.apache.torque.Torque;
 import org.apache.torque.TorqueException;
 import org.apache.torque.adapter.DB;
@@ -37,6 +39,7 @@ import org.apache.torque.om.ObjectKey;
 import org.apache.torque.util.Criteria;
 import org.apache.torque.util.Criteria.Criterion;
 import org.apache.torque.util.SqlEnum;
+import org.apache.torque.util.UniqueColumnList;
 import org.apache.torque.util.UniqueList;
 
 /**
@@ -71,164 +74,6 @@ public final class SqlBuilder
     }
 
     /**
-     * Fully qualify a table name with an optional schema reference
-     *
-     * @param table The table name to use. If null is passed in, null is returned.
-     * @param dbName The name of the database to which this tables belongs.
-     *               If null is passed, the default database is used.
-     *
-     * @return The table name to use inside the SQL statement. If null is passed
-     *         into this method, null is returned.
-     * @exception TorqueException if an error occurs
-     */
-    public static String getFullTableName(
-            final String table,
-            final String dbName)
-        throws TorqueException
-    {
-        if (table != null)
-        {
-            int dotIndex = table.indexOf(".");
-
-            if (dotIndex == -1) // No schema given
-            {
-                String targetDBName = (dbName == null)
-                        ? Torque.getDefaultDB()
-                        : dbName;
-
-                String targetSchema = Torque.getSchema(targetDBName);
-
-                // If we have a default schema, fully qualify the
-                // table and return.
-                if (StringUtils.isNotEmpty(targetSchema))
-                {
-                    return new StringBuffer()
-                            .append(targetSchema)
-                            .append(".")
-                            .append(table)
-                            .toString();
-                }
-            }
-        }
-
-        return table;
-    }
-
-    /**
-     * Remove a possible schema name from the table name.
-     *
-     * @param table The table name to use
-     *
-     * @return The table name with a possible schema name
-     *         stripped off
-     */
-    public static String getUnqualifiedTableName(final String table)
-    {
-        if (table != null)
-        {
-            int dotIndex = table.lastIndexOf("."); // Do we have a dot?
-
-            if (++dotIndex > 0) // Incrementation allows for better test _and_ substring...
-            {
-                return table.substring(dotIndex);
-            }
-        }
-
-        return table;
-    }
-
-    /**
-     * Removes a possible function name or clause from a column name
-     *
-     * @param name The column name, possibly containing a clause
-     *
-     * @return The column name
-     *
-     * @throws TorqueException If the column name was malformed
-     */
-    private static String removeSQLFunction(final String name)
-            throws TorqueException
-    {
-        // Empty name => return it
-        if (StringUtils.isEmpty(name))
-        {
-            return name;
-        }
-
-        // Find Table.Column
-        int dotIndex = name.indexOf('.');
-        if (dotIndex == -1)
-        {
-            dotIndex = name.indexOf("*");
-        }
-        if (dotIndex == -1)
-        {
-            throw new TorqueException("removeSQLFunction() : Column name "
-                    + name
-                    + " does not contain a . or a *");
-        }
-        String pre = name.substring(0, dotIndex);
-        String post = name.substring(dotIndex + 1, name.length());
-        int startIndex = StringUtils.lastIndexOfAny(pre, FUNCTION_DELIMITERS);
-        int endIndex = StringUtils.indexOfAny(post, FUNCTION_DELIMITERS);
-        if (startIndex < 0 && endIndex < 0)
-        {
-            return name;
-        }
-        else
-        {
-            if (endIndex < 0)
-            {
-                endIndex = post.length();
-            }
-            // if startIndex == -1 the formula is correct
-            return name.substring(startIndex + 1, dotIndex + 1 + endIndex);
-        }
-    }
-
-    /**
-     * Returns a table name from an identifier. Each identifier is
-     * to be qualified as [schema.]table.column.
-     * This could also contain FUNCTION([schema.]table.column).
-     *
-     * @param name The (possible fully qualified) identifier name
-     *
-     * @return the fully qualified table name
-     *
-     * @throws TorqueException If the identifier name was malformed
-     */
-    public static String getTableName(final String name, final String dbName)
-            throws TorqueException
-    {
-        final String testName = removeSQLFunction(name);
-
-        if (StringUtils.isEmpty(testName))
-        {
-            throwMalformedColumnNameException(
-                    "getTableName",
-                    name);
-        }
-
-        // Everything before the last dot is the table name
-        int rightDotIndex = testName.lastIndexOf('.');
-
-        if (rightDotIndex < 0)
-        {
-            if ("*".equals(testName))
-            {
-                return null;
-            }
-
-            throwMalformedColumnNameException(
-                    "getTableName",
-                    name);
-        }
-
-        return getFullTableName(testName.substring(0, rightDotIndex), dbName);
-    }
-
-
-    /**
      * Builds a Query from a criteria.
      *
      * @param crit the criteria to build the query from, not null.
@@ -244,16 +89,16 @@ public final class SqlBuilder
 
         final String dbName = crit.getDbName();
         final DB db = Torque.getDB(dbName);
-        final DatabaseMap dbMap = Torque.getDatabaseMap(dbName);
+        final Database database = Torque.getDatabase(dbName);
 
-        JoinBuilder.processJoins(db, dbMap, crit, sqlStatement);
+        JoinBuilder.processJoins(database, crit, sqlStatement);
         processModifiers(crit, sqlStatement);
-        processSelectColumns(crit, sqlStatement, dbName);
-        processAsColumns(crit, sqlStatement, dbName);
-        processCriterions(db, dbMap, crit, sqlStatement);
+        processSelectColumns(crit, sqlStatement, database);
+        processAsColumns(crit, sqlStatement, database);
+        processCriterions(db, database, crit, sqlStatement);
         processGroupBy(crit, sqlStatement);
         processHaving(crit, sqlStatement);
-        processOrderBy(db, dbMap, crit, sqlStatement);
+        processOrderBy(db, database, crit, sqlStatement);
         processLimits(crit, sqlStatement);
 
         return sqlStatement;
@@ -272,17 +117,25 @@ public final class SqlBuilder
     private static void processSelectColumns(
                 final Criteria criteria,
                 final Query query,
-                final String dbName)
+                final Database database)
             throws TorqueException
     {
         UniqueList<String> selectClause = query.getSelectClause();
-        UniqueList<String> select = criteria.getSelectColumns();
+        UniqueColumnList selectColumns = criteria.getSelectColumns();
 
-        for (String identifier : select)
+        for (Column column : selectColumns)
         {
-            selectClause.add(identifier);
+            String sqlExpression = column.getSqlExpression();
+            Column resolvedAlias = criteria.getAsColumns().get(sqlExpression);
+            if (resolvedAlias != null)
+            {
+                // will be handled by processAsColumns
+                continue;
+            }
+            selectClause.add(sqlExpression);
             addTableToFromClause(
-                    getTableName(identifier, dbName),
+                    column,
+                    database,
                     criteria,
                     query);
         }
@@ -296,26 +149,29 @@ public final class SqlBuilder
      *        not null.
      * @param query the query to which the As-columns should be added,
      *        not null.
-     * @param dbName the name of the database to use.
+     * @param database the database to use.
      *
      * @throws TorqueException if the as columns can not be processed.
      */
     private static void processAsColumns(
                 final Criteria criteria,
                 final Query query,
-                final String dbName)
+                final Database database)
             throws TorqueException
     {
         UniqueList<String> querySelectClause = query.getSelectClause();
-        Map<String, String> criteriaAsColumns = criteria.getAsColumns();
+        Map<String, Column> criteriaAsColumns = criteria.getAsColumns();
 
-        for (Map.Entry<String, String> entry : criteriaAsColumns.entrySet())
+        for (Map.Entry<String, Column> entry : criteriaAsColumns.entrySet())
         {
-            String identifier = entry.getValue();
+            Column column = entry.getValue();
             querySelectClause.add(
-                    identifier + SqlEnum.AS + entry.getKey());
+                    column.getSqlExpression()
+                        + SqlEnum.AS
+                        + entry.getKey());
             addTableToFromClause(
-                    getTableName(identifier, dbName),
+                    column,
+                    database,
                     criteria,
                     query);
         }
@@ -345,8 +201,7 @@ public final class SqlBuilder
      * Adds the Criterions from the criteria to the query.
      *
      * @param db the database for which the query should be created.
-     * @param dbMap the database map for the database in which the query
-     *        should run.
+     * @param database the database in which the query should run.
      * @param criteria the criteria from which the Criterion-objects are taken
      * @param query the query to which the Criterion-objects should be added.
      *
@@ -354,25 +209,22 @@ public final class SqlBuilder
      */
     private static void processCriterions(
             final DB db,
-            final DatabaseMap dbMap,
+            final Database database,
             final Criteria criteria,
             final Query query)
         throws TorqueException
     {
         UniqueList<String> whereClause = query.getWhereClause();
 
-        for (Iterator<?> it = criteria.keySet().iterator(); it.hasNext();)
+        for (Criteria.Criterion criterion : criteria.values())
         {
-            String key = (String) it.next();
-            Criteria.Criterion criterion = criteria.getCriterion(key);
-
             StringBuilder sb = new StringBuilder();
             appendCriterionToPs(
                     criterion,
                     criteria,
                     sb,
                     db,
-                    dbMap,
+                    database,
                     query);
             whereClause.add(sb.toString());
         }
@@ -383,44 +235,46 @@ public final class SqlBuilder
                 Criteria criteria,
                 StringBuilder sb,
                 DB db,
-                DatabaseMap databaseMap,
+                Database database,
                 Query query)
             throws TorqueException
     {
-        String tableName = criterion.getTable();
+        Column column = criterion.getColumn();
 
-        if (tableName != null)
-        {
-            // add the table to the from clause, if it is not already
-            // contained there
-            // it is important that this piece of code is executed AFTER
-            // the joins are processed
-            addTableToFromClause(getFullTableName(
-                    tableName,
-                    databaseMap.getDatabase().getName()),
-                    criteria,
-                    query);
-        }
+        // add the table to the from clause, if it is not already
+        // contained there
+        // it is important that this piece of code is executed AFTER
+        // the joins are processed
+        addTableToFromClause(
+            column,
+            database,
+            criteria,
+            query);
 
         boolean ignoreCase
                 = criteria.isIgnoreCase() || criterion.isIgnoreCase();
         {
-            String table = criteria.getTableForAlias(tableName);
-            if (table == null)
+            Column databaseColumn = resolveAliasAndAsColumnAndSchema(
+                    column,
+                    criteria,
+                    database);
+            ColumnMap columnMap = null;
             {
-                table = tableName;
+                DatabaseMap databaseMap = database.getDatabaseMap();
+                TableMap tableMap = databaseMap.getTable(
+                        databaseColumn.getTableName());
+                if (tableMap != null)
+                {
+                    columnMap = tableMap.getColumn(
+                            databaseColumn.getColumnName());
+                }
             }
-
-            TableMap tableMap = databaseMap.getTable(table);
-            if (tableMap != null)
+            if (columnMap != null)
             {
                 // do not use ignoreCase on columns
                 // which do not contain String values
                 ignoreCase = ignoreCase
-                    && databaseMap.getTable(table)
-                            .getColumn(criterion.getColumn())
-                            .getType()
-                        instanceof String;
+                    && columnMap.getType() instanceof String;
             }
         }
 
@@ -428,7 +282,7 @@ public final class SqlBuilder
         {
             sb.append('(');
         }
-        String columnName = criterion.getFullyQualifiedColumnName();
+        String columnName = criterion.getColumn().getSqlExpression();
         WhereClauseExpression whereClausePartInput
                 = new WhereClauseExpression(
                         columnName,
@@ -452,7 +306,7 @@ public final class SqlBuilder
                     criteria,
                     sb,
                     db,
-                    databaseMap,
+                    database,
                     query);
             sb.append(')');
         }
@@ -466,7 +320,7 @@ public final class SqlBuilder
      */
     private static void processOrderBy(
             final DB db,
-            final DatabaseMap dbMap,
+            final Database database,
             final Criteria crit,
             final Query query)
             throws TorqueException
@@ -474,79 +328,56 @@ public final class SqlBuilder
         UniqueList<String> orderByClause = query.getOrderByClause();
         UniqueList<String> selectClause = query.getSelectClause();
 
-        UniqueList<String> orderBy = crit.getOrderByColumns();
+        UniqueList<OrderBy> orderByList = crit.getOrderByColumns();
 
-        if (orderBy != null && orderBy.size() > 0)
-        {
-            // Check for each String/Character column and apply
-            // toUpperCase().
-            for (String orderByColumn : orderBy)
+        // Check for each String/Character column and apply
+        // toUpperCase().
+        for (OrderBy orderBy : orderByList)
+        {
+            Column column = orderBy.getColumn();
+            TableMap tableMap = database.getDatabaseMap().getTable(
+                    column.getTableName());
+            ColumnMap columnMap = null;
+            if (tableMap != null)
             {
-                String strippedColumnName
-                        = removeSQLFunction(orderByColumn);
-                int dotPos = strippedColumnName.lastIndexOf('.');
-                if (dotPos == -1)
-                {
-                    // We are not able to look up the table in the
-                    // tableMap, as no table name is given. Simply add
-                    // the orderBy and hope the user knows what he is
-                    // doing.
-                    orderByClause.add(orderByColumn);
-                    continue;
-                }
-
-                String tableName = strippedColumnName.substring(0, dotPos);
-                String table = crit.getTableForAlias(tableName);
-                if (table == null)
-                {
-                    table = tableName;
-                }
-
-                // See if there's a space (between the column list and sort
-                // order in ORDER BY table.column DESC).
-                int spacePos = strippedColumnName.indexOf(' ');
-                String columnName;
-                if (spacePos == -1)
-                {
-                    columnName =
-                            strippedColumnName.substring(dotPos + 1);
-                }
-                else
-                {
-                    columnName = strippedColumnName.substring(
-                            dotPos + 1,
-                            spacePos);
-                }
-                ColumnMap column = dbMap.getTable(table).getColumn(columnName);
+                columnMap = tableMap.getColumn(column.getColumnName());
+            }
+            String sqlExpression = column.getSqlExpression();
 
-                // only ignore case in order by for string columns
-                // which do not have a function around them
-                if (column.getType() instanceof String
-                        && orderByColumn.indexOf('(') == -1)
-                {
-                    // find space pos relative to orderByColumn
-                    spacePos = orderByColumn.indexOf(' ');
-                    if (spacePos == -1)
-                    {
-                        orderByClause.add(
-                                db.ignoreCaseInOrderBy(orderByColumn));
-                    }
-                    else
-                    {
-                        orderByClause.add(
-                                db.ignoreCaseInOrderBy(
-                                        orderByColumn.substring(0, spacePos))
-                                + orderByColumn.substring(spacePos));
-                    }
+            // Either we are not able to look up the column in the
+            // databaseMap, then simply use the case in orderBy and
+            // hope the user knows what he is
+            // doing.
+            // Or we only ignore case in order by for string columns
+            // which do not have a function around them
+            if (columnMap == null
+                    || (columnMap.getType() instanceof String
+                        && sqlExpression.indexOf('(') == -1))
+            {
+                if (orderBy.isIgnoreCase())
+                {
+                    orderByClause.add(
+                            db.ignoreCaseInOrderBy(sqlExpression)
+                                + ' ' + orderBy.getOrder());
                     selectClause.add(
-                            db.ignoreCaseInOrderBy(tableName + '.' + columnName));
+                            db.ignoreCaseInOrderBy(sqlExpression));
                 }
                 else
                 {
-                    orderByClause.add(orderByColumn);
-                    selectClause.add(tableName + '.' + columnName);
+                    orderByClause.add(sqlExpression + ' ' + orderBy.getOrder());
+                    selectClause.add(sqlExpression);
                 }
             }
+            else
+            {
+                orderByClause.add(sqlExpression + ' ' + orderBy.getOrder());
+                selectClause.add(sqlExpression);
+            }
+            addTableToFromClause(
+                   column,
+                   database,
+                   crit,
+                   query);
         }
     }
 
@@ -562,30 +393,19 @@ public final class SqlBuilder
             throws TorqueException
     {
         UniqueList<String> groupByClause = query.getGroupByClause();
-        UniqueList<String> groupBy = crit.getGroupByColumns();
+        UniqueColumnList groupBy = crit.getGroupByColumns();
 
-        // need to allow for multiple group bys
-        if (groupBy != null)
+        for (Column groupByColumn : groupBy)
         {
-            for (String columnName : groupBy)
-            {
-                String column = (String) crit.getAsColumns().get(columnName);
+            Column column = crit.getAsColumns().get(
+                    groupByColumn.getSqlExpression());
 
-                if (column == null)
-                {
-                    column = columnName;
-                }
-
-                if (column.indexOf('.') != -1)
-                {
-                    groupByClause.add(column);
-                }
-                else
-                {
-                    throwMalformedColumnNameException("group by",
-                            column);
-                }
+            if (column == null)
+            {
+                column = groupByColumn;
             }
+
+            groupByClause.add(column.getColumnName());
         }
     }
 
@@ -631,35 +451,6 @@ public final class SqlBuilder
     }
 
     /**
-     * Throws a TorqueException with the malformed column name error
-     * message.  The error message looks like this:<p>
-     *
-     * <code>
-     *     Malformed column name in Criteria [criteriaPhrase]:
-     *     '[columnName]' is not of the form 'table.column'
-     * </code>
-     *
-     * @param criteriaPhrase a String, one of "select", "join", or "order by"
-     * @param columnName a String containing the offending column name
-     * @throws TorqueException Any exceptions caught during processing will be
-     *         rethrown wrapped into a TorqueException.
-     */
-    public static void throwMalformedColumnNameException(
-        final String criteriaPhrase,
-        final String columnName)
-        throws TorqueException
-    {
-        StringBuffer sb = new StringBuffer()
-                .append("Malformed column name in Criteria ")
-                .append(criteriaPhrase)
-                .append(": '")
-                .append(StringUtils.isEmpty(columnName) ? "<empty>" : columnName)
-                .append("' is not of the form 'table.column'");
-
-        throw new TorqueException(sb.toString());
-    }
-
-    /**
      * Returns the tablename which can be added to a From Clause.
      * This takes care of any aliases that might be defined.
      * For example, if an alias "a" for the table AUTHOR is defined
@@ -672,33 +463,136 @@ public final class SqlBuilder
      *         or a String of the form "tableName tableOrAliasName"
      *         if tableOrAliasName is an alias for a table name
      */
-    public static String getTableNameForFromClause(
-            final String tableName,
+    static String getTableNameForFromClause(
+            final Column column,
+            final Database database,
             final Criteria criteria)
+            throws TorqueException
     {
-        String shortTableName = getUnqualifiedTableName(tableName);
-
-        // Most of the time, the alias would be for the short name...
-        String aliasName = criteria.getTableForAlias(shortTableName);
-        if (StringUtils.isEmpty(aliasName))
-        {
-            // But we should also check the FQN...
-            aliasName = criteria.getTableForAlias(tableName);
-        }
-
-        if (StringUtils.isNotEmpty(aliasName))
+        Column resolvedColumn
+                = resolveAliasAndAsColumnAndSchema(column, criteria, database);
+        String fullTableName
+                = resolvedColumn.getFullTableName();
+
+        if (!StringUtils.equals(
+                resolvedColumn.getTableName(),
+                column.getTableName()))
         {
             // If the tables have an alias, add an "<xxx> <yyy> statement"
             // <xxx> AS <yyy> causes problems on oracle
             return new StringBuffer(
-                    tableName.length() + aliasName.length() + 1)
-                    .append(aliasName)
+                fullTableName.length() + column.getTableName().length() + 1)
+                    .append(fullTableName)
                     .append(" ")
-                    .append(tableName)
-                    .toString();
+                    .append(column.getTableName())
+                .toString();
+        }
+
+        return fullTableName;
+    }
+
+    /**
+     * Fully qualify a table name with an optional schema reference.
+     *
+     * @param table The table name to use.
+     *              If null is passed in, null is returned.
+     * @param dbName The name of the database to which this tables belongs.
+     *               If null is passed, the default database is used.
+     *
+     * @return The table name to use inside the SQL statement.
+     *         If null is passed into this method, null is returned.
+     * @exception TorqueException if an error occurs
+     */
+    public static String getFullTableName(
+            final String table,
+            final String dbName)
+        throws TorqueException
+    {
+        if (table == null)
+        {
+            return table;
         }
 
-        return tableName;
+        int dotIndex = table.indexOf(".");
+        if (dotIndex == -1) // No schema given
+        {
+            String targetDBName = (dbName == null)
+                    ? Torque.getDefaultDB()
+                    : dbName;
+
+            String targetSchema = Torque.getSchema(targetDBName);
+
+            // If we have a default schema, fully qualify the
+            // table and return.
+            if (StringUtils.isNotEmpty(targetSchema))
+            {
+                return new StringBuffer()
+                        .append(targetSchema)
+                        .append(".")
+                        .append(table)
+                        .toString();
+            }
+        }
+
+        return table;
+    }
+
+    /**
+     * Returns the database name of a column
+     * @param tableName the name of a table
+     *        or the alias for a table
+     * @param criteria a criteria object to resolve a possible alias
+     * @return either the tablename itself if tableOrAliasName is not an alias,
+     *         or a String of the form "tableName tableOrAliasName"
+     *         if tableOrAliasName is an alias for a table name
+     */
+    static Column resolveAliasAndAsColumnAndSchema(
+            final Column columnToResolve,
+            final Criteria criteria,
+            Database database)
+            throws TorqueException
+    {
+        String columnNameToResolve = columnToResolve.getColumnName();
+        Column column = criteria.getAsColumns().get(columnNameToResolve);
+        boolean sqlExpressionModified = false;
+        if (column == null)
+        {
+            column = columnToResolve;
+        }
+        else
+        {
+            sqlExpressionModified = true;
+        }
+        String tableNameToResolve = column.getTableName();
+        String tableName = criteria.getAliases().get(tableNameToResolve);
+        if (tableName == null)
+        {
+            tableName = tableNameToResolve;
+        }
+        else
+        {
+            sqlExpressionModified = true;
+        }
+        String schemaName = column.getSchemaName();
+        if (schemaName == null)
+        {
+            schemaName = database.getSchema();
+        }
+        if (sqlExpressionModified)
+        {
+            return new ColumnImpl(
+                    schemaName,
+                    tableName,
+                    column.getColumnName());
+        }
+        else
+        {
+            return new ColumnImpl(
+                    schemaName,
+                    tableName,
+                    column.getColumnName(),
+                    column.getSqlExpression());
+        }
     }
 
     /**
@@ -717,16 +611,13 @@ public final class SqlBuilder
      * @return if the Tablename tableName is already contained in a from clause.
      *         If tableName is null, true is returned.
      */
-    public static boolean fromClauseContainsTableName(
+    static boolean fromClauseContainsTableName(
             final UniqueList<Query.FromElement> fromClause,
             final String tableName)
     {
         if (tableName == null)
         {
-            // usually this function is called to see if tableName should be
-            // added to the fromClause. As null should not be added,
-            // true is returned.
-            return true;
+            return false;
         }
         for (Query.FromElement fromElement : fromClause)
         {
@@ -743,7 +634,8 @@ public final class SqlBuilder
      * contained there.
      *
      * @param tableOrAliasName the name of a table
-     *        or the alias for a table
+     *        or the alias for a table. If null, the from clause is left
+     *        unchanged.
      * @param criteria a criteria object to resolve a possible alias
      * @param query the query where the the tablename should be added
      *        to the from clause
@@ -751,13 +643,25 @@ public final class SqlBuilder
      * @return the table in the from clause which represents the
      *         supplied tableOrAliasName
      */
-    private static String addTableToFromClause(
-            final String tableName,
-            final Criteria criteria,
-            Query query)
+    static String addTableToFromClause(
+                final Column column,
+                final Database database,
+                final Criteria criteria,
+                Query query)
+            throws TorqueException
     {
-        String tableNameForFromClause
-                = getTableNameForFromClause(tableName, criteria);
+        if (column == null)
+        {
+            return null;
+        }
+        if (column.getTableName() == null)
+        {
+            return null;
+        }
+        String tableNameForFromClause = getTableNameForFromClause(
+                column,
+                database,
+                criteria);
 
         UniqueList<Query.FromElement> queryFromClause = query.getFromClause();
 
@@ -785,7 +689,7 @@ public final class SqlBuilder
      *        differences in case.
      * @param db The database for which the SQL should be created, not null.
      */
-    public static PreparedStatementPart buildPs(
+    private static PreparedStatementPart buildPs(
                 WhereClauseExpression whereClausePart,
                 boolean ignoreCase,
                 DB db)

Modified: db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/BasePeer.java
URL: http://svn.apache.org/viewvc/db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/BasePeer.java?rev=1206426&r1=1206425&r2=1206426&view=diff
==============================================================================
--- db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/BasePeer.java
(original)
+++ db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/BasePeer.java
Sat Nov 26 10:59:15 2011
@@ -23,9 +23,7 @@ import java.io.Serializable;
 import java.sql.Connection;
 import java.util.List;
 
-import org.apache.torque.Torque;
 import org.apache.torque.TorqueException;
-import org.apache.torque.map.MapBuilder;
 import org.apache.torque.map.TableMap;
 import org.apache.torque.om.ObjectKey;
 import org.apache.torque.om.mapper.RecordMapper;
@@ -544,23 +542,6 @@ public abstract class BasePeer
     }
 
     /**
-     * This method returns the MapBuilder specified in the name
-     * parameter.  You should pass in the full path to the class, ie:
-     * org.apache.torque.util.db.map.TurbineMapBuilder.  The
-     * MapBuilder instances are cached in the TorqueInstance for speed.
-     *
-     * @param name name of the MapBuilder
-     * @return A MapBuilder, not null
-     * @throws TorqueException if the Map Builder cannot be instantiated
-     * @deprecated Use Torque.getMapBuilder(name) instead
-     */
-    public static MapBuilder getMapBuilder(String name)
-        throws TorqueException
-    {
-        return Torque.getMapBuilder(name);
-    }
-
-    /**
      * Performs a SQL <code>select</code> using a PreparedStatement.
      *
      * @param criteria A Criteria specifying the records to select, not null.

Modified: db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/BasePeerImpl.java
URL: http://svn.apache.org/viewvc/db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/BasePeerImpl.java?rev=1206426&r1=1206425&r2=1206426&view=diff
==============================================================================
--- db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/BasePeerImpl.java
(original)
+++ db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/BasePeerImpl.java
Sat Nov 26 10:59:15 2011
@@ -34,10 +34,13 @@ import java.util.Map;
 import org.apache.commons.lang.StringUtils;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
+import org.apache.torque.Column;
 import org.apache.torque.Database;
 import org.apache.torque.TooManyRowsException;
 import org.apache.torque.Torque;
 import org.apache.torque.TorqueException;
+import org.apache.torque.adapter.DB;
+import org.apache.torque.adapter.IDMethod;
 import org.apache.torque.map.ColumnMap;
 import org.apache.torque.map.DatabaseMap;
 import org.apache.torque.map.TableMap;
@@ -278,8 +281,8 @@ public class BasePeerImpl implements Ser
         throws TorqueException
     {
         Criteria.Criterion criterion
-                = (Criteria.Criterion) criteria.values().iterator().next();
-        String tableName = criterion.getTable();
+                = criteria.values().iterator().next();
+        String tableName = criterion.getColumn().getTableName();
         if (tableName == null)
         {
             throw new TorqueException("Unqualified column name in criteria");
@@ -447,10 +450,18 @@ public class BasePeerImpl implements Ser
                 Connection connection)
             throws TorqueException
     {
+        if (insertValues == null)
+        {
+            throw new TorqueException("insertValues is null");
+        }
+        if (connection == null)
+        {
+            throw new TorqueException("connection is null");
+        }
         TableMap tableMap = insertValues.getTable();
         DatabaseMap dbMap = tableMap.getDatabaseMap();
         Database database = Torque.getDatabase(dbMap.getDatabase().getName());
-        Object keyInfo = tableMap.getPrimaryKeyMethodInfo();
+        Object keyInfo = getIdMethodInfo(tableMap);
         IdGenerator keyGen
                 = database.getIdGenerator(tableMap.getPrimaryKeyMethod());
 
@@ -467,11 +478,11 @@ public class BasePeerImpl implements Ser
             // defined for the table we're inserting into.
             if (keyGen.isPriorToInsert() && primaryKey != null
                     && !insertValues.containsKey(
-                            primaryKey.getFullyQualifiedName()))
+                            primaryKey))
             {
                 id = getId(primaryKey, keyGen, connection, keyInfo);
                 insertValues.put(
-                        primaryKey.getFullyQualifiedName(),
+                        primaryKey,
                         new JdbcTypedValue(id.getValue(), id.getJdbcType()));
             }
         }
@@ -479,16 +490,11 @@ public class BasePeerImpl implements Ser
         List<String> columnNames = new ArrayList<String>();
         List<JdbcTypedValue> replacementObjects
                 = new ArrayList<JdbcTypedValue>();
-        for (Map.Entry<String, JdbcTypedValue> columnValue
+        for (Map.Entry<Column, JdbcTypedValue> columnValue
                 : insertValues.entrySet())
         {
-            String columnName = columnValue.getKey();
-            if (columnName.lastIndexOf(".") != -1)
-            {
-                columnName = columnName.substring(
-                        columnName.lastIndexOf(".") + 1);
-            }
-            columnNames.add(columnName);
+            Column column = columnValue.getKey();
+            columnNames.add(column.getColumnName());
             JdbcTypedValue value = columnValue.getValue();
             replacementObjects.add(value);
         }
@@ -586,6 +592,38 @@ public class BasePeerImpl implements Ser
     }
 
     /**
+     * Returns the idMethodInfo for a given table.
+     *
+     * @param tableMap the table map of the table, not null.
+     *
+     * @return the idMethodInfo, not null.
+     *
+     * @throws TorqueException if the database adapter for the table's database
+     *         needs to be accessed but is not configured.
+     */
+    private Object getIdMethodInfo(TableMap tableMap)
+            throws TorqueException
+    {
+        String idMethod = tableMap.getPrimaryKeyMethod();
+        if (IDMethod.NATIVE.equals(idMethod))
+        {
+            String databaseName
+                    = tableMap.getDatabaseMap().getDatabase().getName();
+            DB dbAdapter = Torque.getDB(databaseName);
+            if (dbAdapter == null)
+            {
+               throw new TorqueException(
+                   "missing adapter configuration for database "
+                       + databaseName
+                       + "check the Torque configuration");
+            }
+            idMethod = dbAdapter.getIDMethodType();
+        }
+        Object keyInfo = tableMap.getPrimaryKeyMethodInfo(idMethod);
+        return keyInfo;
+    }
+
+    /**
      * Create an Id for insertion in the Criteria
      *
      * @param pk ColumnMap for the Primary key
@@ -1156,11 +1194,11 @@ public class BasePeerImpl implements Ser
         ColumnMap pk = table.getPrimaryKey();
         Criteria selectCriteria = null;
 
-        if (pk != null && updateValues.containsKey(pk.getFullyQualifiedName()))
+        if (pk != null && updateValues.containsKey(pk.getSqlExpression()))
         {
             selectCriteria = new Criteria();
-            selectCriteria.add(pk.getFullyQualifiedName(),
-                updateValues.remove(pk.getFullyQualifiedName()));
+            selectCriteria.add(pk,
+                updateValues.remove(pk.getSqlExpression()));
         }
         else
         {
@@ -1242,16 +1280,11 @@ public class BasePeerImpl implements Ser
 
         List<JdbcTypedValue> replacementObjects
                 = new ArrayList<JdbcTypedValue>();
-        for (Map.Entry<String, JdbcTypedValue> updateValue
+        for (Map.Entry<Column, JdbcTypedValue> updateValue
                 : updateValues.entrySet())
         {
-            String columnName = updateValue.getKey();
-            if (columnName.lastIndexOf(".") != -1)
-            {
-                columnName = columnName.substring(
-                        columnName.lastIndexOf(".") + 1);
-            }
-            query.getSelectClause().add(columnName);
+            Column column = updateValue.getKey();
+            query.getSelectClause().add(column.getColumnName());
             replacementObjects.add(updateValue.getValue());
         }
 
@@ -1636,7 +1669,7 @@ public class BasePeerImpl implements Ser
                 TableMap defaultTableMap)
             throws TorqueException
     {
-        String tableName = criterion.getTable();
+        String tableName = criterion.getColumn().getTableName();
         TableMap tableMap = null;
         if (tableName != null)
         {
@@ -1668,7 +1701,7 @@ public class BasePeerImpl implements Ser
         // if no description of table available, do not modify anything
         if (tableMap != null)
         {
-            String columnName = criterion.getColumn();
+            String columnName = criterion.getColumn().getColumnName();
             ColumnMap columnMap = tableMap.getColumn(columnName);
             if (columnMap != null)
             {
@@ -1746,9 +1779,9 @@ public class BasePeerImpl implements Ser
         throws TorqueException
     {
         TableMap table = columnValues.getTable();
-        for (Map.Entry<String, JdbcTypedValue> entry : columnValues.entrySet())
+        for (Map.Entry<Column, JdbcTypedValue> entry : columnValues.entrySet())
         {
-            String columnName = entry.getKey();
+            String columnName = entry.getKey().getColumnName();
             ColumnMap column = table.getColumn(columnName);
             if (column != null)
             {

Modified: db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/ColumnValues.java
URL: http://svn.apache.org/viewvc/db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/ColumnValues.java?rev=1206426&r1=1206425&r2=1206426&view=diff
==============================================================================
--- db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/ColumnValues.java
(original)
+++ db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/ColumnValues.java
Sat Nov 26 10:59:15 2011
@@ -24,6 +24,7 @@ import java.util.HashMap;
 import java.util.Map;
 import java.util.Set;
 
+import org.apache.torque.Column;
 import org.apache.torque.map.TableMap;
 
 /**
@@ -31,13 +32,13 @@ import org.apache.torque.map.TableMap;
  *
  * @version $Id: BasePeer.java 1003834 2010-10-02 16:51:32Z tfischer $
  */
-public class ColumnValues implements Map<String, JdbcTypedValue>
+public class ColumnValues implements Map<Column, JdbcTypedValue>
 {
     /** The table to which these column values belong to. */
     private TableMap table;
 
     /** The column values, keyed by the column names. */
-    private Map<String, JdbcTypedValue> columnValues;
+    private Map<Column, JdbcTypedValue> columnValues;
 
     /**
      * The name of the database handle to use for connection opening if needed,
@@ -59,7 +60,7 @@ public class ColumnValues implements Map
             throw new NullPointerException("table must not be null");
         }
         this.table = table;
-        this.columnValues = new HashMap<String, JdbcTypedValue>();
+        this.columnValues = new HashMap<Column, JdbcTypedValue>();
     }
 
     /**
@@ -87,7 +88,7 @@ public class ColumnValues implements Map
      * @throws NullPointerException if table is null.
      */
     public ColumnValues(
-            Map<String, JdbcTypedValue> columnValues,
+            Map<Column, JdbcTypedValue> columnValues,
             TableMap table)
     {
         if (table == null)
@@ -97,7 +98,7 @@ public class ColumnValues implements Map
         this.table = table;
         if (columnValues == null)
         {
-            this.columnValues = new HashMap<String, JdbcTypedValue>();
+            this.columnValues = new HashMap<Column, JdbcTypedValue>();
         }
         else
         {
@@ -117,7 +118,7 @@ public class ColumnValues implements Map
      * @throws NullPointerException if table is null.
      */
     public ColumnValues(
-            Map<String, JdbcTypedValue> columnValues,
+            Map<Column, JdbcTypedValue> columnValues,
             TableMap table,
             String dbName)
     {
@@ -172,7 +173,7 @@ public class ColumnValues implements Map
         return columnValues.get(key);
     }
 
-    public JdbcTypedValue put(String key, JdbcTypedValue value)
+    public JdbcTypedValue put(Column key, JdbcTypedValue value)
     {
         return columnValues.put(key, value);
     }
@@ -182,7 +183,7 @@ public class ColumnValues implements Map
         return columnValues.remove(key);
     }
 
-    public void putAll(Map<? extends String, ? extends JdbcTypedValue> t)
+    public void putAll(Map<? extends Column, ? extends JdbcTypedValue> t)
     {
         columnValues.putAll(t);
     }
@@ -192,7 +193,7 @@ public class ColumnValues implements Map
         columnValues.clear();
     }
 
-    public Set<String> keySet()
+    public Set<Column> keySet()
     {
         return columnValues.keySet();
     }
@@ -202,7 +203,7 @@ public class ColumnValues implements Map
         return columnValues.values();
     }
 
-    public Set<java.util.Map.Entry<String, JdbcTypedValue>> entrySet()
+    public Set<java.util.Map.Entry<Column, JdbcTypedValue>> entrySet()
     {
         return columnValues.entrySet();
     }

Modified: db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/CountHelper.java
URL: http://svn.apache.org/viewvc/db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/CountHelper.java?rev=1206426&r1=1206425&r2=1206426&view=diff
==============================================================================
--- db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/CountHelper.java
(original)
+++ db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/CountHelper.java
Sat Nov 26 10:59:15 2011
@@ -31,6 +31,8 @@ package org.apache.torque.util;
 import java.sql.Connection;
 import java.util.List;
 
+import org.apache.torque.Column;
+import org.apache.torque.ColumnImpl;
 import org.apache.torque.TorqueException;
 import org.apache.torque.om.mapper.IntegerMapper;
 
@@ -92,6 +94,21 @@ public class CountHelper
      * Returns the number of rows in a query.
      *
      * @param c Criteria to get the count for.
+     * @param column the database Column which is counted. Preferably,
+     *        use the primary key here.
+     * @return number of rows matching the query provided
+     * @throws TorqueException if the query could not be executed
+     */
+    public int count(Criteria c, Column column)
+        throws TorqueException
+    {
+        return count(c, column.getSqlExpression());
+    }
+
+    /**
+     * Returns the number of rows in a query.
+     *
+     * @param c Criteria to get the count for.
      * @param conn Connection to use
      * @param columnName Name of database Column which is counted. Preferably,
      *        use the primary key here.
@@ -123,7 +140,7 @@ public class CountHelper
         countStr.append(columnName);
         countStr.append(")");
 
-        c.addSelectColumn(countStr.toString());
+        c.addSelectColumn(new ColumnImpl(countStr.toString()));
 
         List<Integer> result;
         if (conn == null)
@@ -137,4 +154,20 @@ public class CountHelper
 
         return result.get(0);
     }
+
+    /**
+     * Returns the number of rows in a query.
+     *
+     * @param c Criteria to get the count for.
+     * @param conn Connection to use
+     * @param column The database Column which is counted. Preferably,
+     *        use the primary key here.
+     * @return number of rows matching the query provided
+     * @throws TorqueException if the query could not be executed
+     */
+    public int count(Criteria c, Connection conn, Column column)
+        throws TorqueException
+    {
+        return count(c, conn, column.getSqlExpression());
+    }
 }



---------------------------------------------------------------------
To unsubscribe, e-mail: torque-dev-unsubscribe@db.apache.org
For additional commands, e-mail: torque-dev-help@db.apache.org


Mime
View raw message