⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sqlbuilder.java

📁 另外一种持久性o/m软件
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
package org.apache.torque.util;/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *     http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */import java.io.Serializable;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Set;import org.apache.commons.lang.StringUtils;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.torque.Torque;import org.apache.torque.TorqueException;import org.apache.torque.adapter.DB;import org.apache.torque.map.ColumnMap;import org.apache.torque.map.DatabaseMap;import org.apache.torque.util.Criteria.Criterion;/** * Factored out code that is used to process SQL tables. This code comes * from BasePeer and is put here to reduce complexity in the BasePeer class. * You should not use the methods here directly! * * @author <a href="mailto:hps@intermeta.de">Henning P. Schmiedehausen</a> * @author <a href="mailto:fischer@seitenbau.de">Thomas Fischer</a> * @version $Id: SQLBuilder.java,v 1.6 2005/07/02 15:22:32 tfischer Exp $ */public abstract class SQLBuilder        implements Serializable{    /** Logging */    protected static Log log = LogFactory.getLog(SQLBuilder.class);    /**     * 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 final 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 final 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;        }        final int leftParent = name.lastIndexOf('(');        final int rightParent = name.indexOf(')');        // Do we have Parentheses?        if (leftParent < 0)        {            if (rightParent < 0)            {                // No left, no right => No function ==> return it                return name;            }        }        // We have a left parenthesis. Is the right one behind it?        if (rightParent > leftParent)        {            // Yes. Strip off the function, return the column name            return name.substring(leftParent + 1, rightParent);        }        // Bracket mismatch or wrong order ==> Exception        throwMalformedColumnNameException(                "removeSQLFunction",                name);        return null; // Ugh    }        /**     * Removes possible qualifiers (like DISTINCT) from a column name     *     * @param name The column name, possibly containing qualifiers     *     * @return The column name     *     * @throws TorqueException If the column name was malformed     */    private static String removeQualifiers(final String name)            throws TorqueException    {        // Empty name => return it        if (StringUtils.isEmpty(name))        {            return name;        }        final int spacePos = name.trim().lastIndexOf(' ');        // Do we have spaces, indicating that qualifiers are used ?        if (spacePos > 0)        {            // Qualifiers are first, tablename is piece after last space            return name.trim().substring(spacePos + 1);        }                // no spaces, nothing changed        return name;    }        /**     * 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 = removeQualifiers(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);    }                            /**     * Returns a set of all tables and possible aliases referenced     * from a criterion. The resulting Set can be directly used to     * build a WHERE clause     *     * @param crit A Criteria object     * @param tableCallback A Callback Object     * @return A Set of tables.     */    public static final Set getTableSet(            final Criteria crit,            final TableCallback tableCallback)    {        HashSet tables = new HashSet();        // Loop over all the Criterions        for (Iterator it = crit.keySet().iterator(); it.hasNext(); )        {            String key = (String) it.next();            Criteria.Criterion c = crit.getCriterion(key);            List tableNames = c.getAllTables();            // Loop over all Tables referenced in this criterion.             for (Iterator it2 = tableNames.iterator(); it2.hasNext(); )            {                String name = (String) it2.next();                String aliasName = crit.getTableForAlias(name);                // If the tables have an alias, add an "<xxx> AS <yyy> statement"                if (StringUtils.isNotEmpty(aliasName))                {                    String newName =                             new StringBuffer(name.length() + aliasName.length() + 4)                            .append(aliasName)                            .append(" AS ")                            .append(name)                            .toString();                    name = newName;                }                tables.add(name);            }            if (tableCallback != null)            {                tableCallback.process(tables, key, crit);            }        }                return tables;    }    /**     * Builds a Query clause for Updating and deleting     *     * @param crit a <code>Criteria</code> value     * @param params a <code>List</code> value     * @param qc a <code>QueryCallback</code> value     * @return a <code>Query</code> value     * @exception TorqueException if an error occurs     */    public static final Query buildQueryClause(final Criteria crit,            final List params,             final QueryCallback qc)            throws TorqueException    {        Query query = new Query();        final String dbName = crit.getDbName();        final DB db = Torque.getDB(dbName);        final DatabaseMap dbMap = Torque.getDatabaseMap(dbName);        JoinBuilder.processJoins(db, dbMap, crit, query);        processModifiers(crit, query);        processSelectColumns(crit, query, dbName);        processAsColumns(crit, query);        processCriterions(db, dbMap, dbName, crit, query,  params, qc);        processGroupBy(crit, query);        processHaving(crit, query);        processOrderBy(db, dbMap, crit, query);        LimitHelper.buildLimit(crit, query);        if (log.isDebugEnabled())        {            log.debug(query.toString());        }        return query;    }    /**     * adds the select columns from the criteria to the query     * @param criteria the criteria from which the select columns are taken     * @param query the query to which the select columns should be added     * @throws TorqueException if the select columns can not be processed      */    private static final void processSelectColumns(            final Criteria criteria,            final Query query,            final String dbName)        throws TorqueException    {        UniqueList selectClause = query.getSelectClause();        UniqueList select = criteria.getSelectColumns();                for (int i = 0; i < select.size(); i++)        {            String identifier = (String) select.get(i);            selectClause.add(identifier);            addTableToFromClause(getTableName(identifier, dbName), criteria, query);         }    }        /**     * adds the As-columns from the criteria to the query.     * @param criteria the criteria from which the As-columns are taken     * @param query the query to which the As-columns should be added     */    private static final void processAsColumns(            final Criteria criteria,            final Query query)     {        UniqueList querySelectClause = query.getSelectClause();        Map criteriaAsColumns = criteria.getAsColumns();              for (Iterator it = criteriaAsColumns.keySet().iterator(); it.hasNext(); )        {            String key = (String) it.next();            querySelectClause.add(                    new StringBuffer()                    .append(criteriaAsColumns.get(key))                    .append(SqlEnum.AS)                    .append(key)                    .toString());        }    }        /**     * adds the Modifiers from the criteria to the query     * @param criteria the criteria from which the Modifiers are taken     * @param query the query to which the Modifiers should be added     */    private static final void processModifiers(            final Criteria criteria,            final Query query)     {        UniqueList selectModifiers = query.getSelectModifiers();        UniqueList modifiers = criteria.getSelectModifiers();        for (int i = 0; i < modifiers.size(); i++)        {            selectModifiers.add(modifiers.get(i));        }    }    

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -