Package org.jpox.store.query

Source Code of org.jpox.store.query.Query$SubqueryDefinition

/**********************************************************************
Copyright (c) 2002 Kelly Grizzle (TJDO) and others. All rights reserved.
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.

Contributors:
2003 Andy Jefferson - commented and localised
2003 Andy Jefferson - coding standards
2004 Andy Jefferson - addition of setUnique() and setRange()
2005 Andy Jefferson - added timeout support.
    ...
**********************************************************************/
package org.jpox.store.query;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;

import org.jpox.FetchPlan;
import org.jpox.ObjectManager;
import org.jpox.ObjectManagerFactoryImpl;
import org.jpox.exceptions.ClassNotResolvedException;
import org.jpox.exceptions.JPOXException;
import org.jpox.exceptions.JPOXUserException;
import org.jpox.jdo.exceptions.TransactionNotActiveException;
import org.jpox.jdo.exceptions.TransactionNotReadableException;
import org.jpox.management.runtime.QueryRuntime;
import org.jpox.metadata.QueryResultMetaData;
import org.jpox.store.Extent;
import org.jpox.store.StoreManager;
import org.jpox.util.Imports;
import org.jpox.util.Localiser;
import org.jpox.util.StringUtils;

/**
* Abstract implementation for all queries in JPOX.
* Implementations of JDOQL, SQL, JPQL, etc should extend this.
*
* @version $Revision: 1.82 $
*/
public abstract class Query implements Serializable
{
    /** Localiser for messages. */
    protected static final Localiser LOCALISER=Localiser.getInstance("org.jpox.store.Localisation",
        ObjectManagerFactoryImpl.class.getClassLoader());

    /** Object Manager managing this query. */
    protected final transient ObjectManager om;

    public static final short SELECT = 0;
    public static final short BULK_UPDATE = 1;
    public static final short BULK_DELETE = 2;

    /** Type of query. */
    protected short type = SELECT;

    /** The candidate class for this query. */
    protected Class candidateClass;

    /** Name of the candidate class (used when specified via Single-String). */
    protected String candidateClassName;

    /** Whether to allow subclasses of the candidate class be returned. */
    protected boolean subclasses = true;

    /** Whether to return single value, or collection from the query. */
    protected boolean unique = false;

    /** From clause of the query (optional). */
    protected transient String from = null;

    /** UPDATE clause of a query (JPQL). */
    protected transient String update = null;

    /** Specification of the result of the query e.g aggregates etc. */
    protected String result = null;   

    /** User-defined class that best represents the results of a query. Populated if specified via setResultClass(). */
    protected Class resultClass = null;

    /** Name of user-defined class to use as the result class. */
    protected String resultClassName = null;

    /** The filter for the query. */
    protected String filter;

    /** Any import declarations for the types used in the query. */
    protected String imports;

    /** Any explicit variables defined for this query. */
    protected String explicitVariables;

    /** Any explicit parameters defined for this query. */
    protected String explicitParameters;

    /** Ordering clause for the query, governing the order objects are returned. */
    protected String ordering;

    /** Grouping clause for the query, for use with aggregate expressions. */
    protected String grouping;

    /** Having clause for the query */
    protected String having;

    /** String form of the query result range. Only populated if specified via String. */
    protected String range;

    /** Query result range start position (included). Either specified, or compiled from "range". */
    protected long fromInclNo = 0;

    /** Query result range end position (excluded). Either specified, or compiled from "range". */
    protected long toExclNo = Long.MAX_VALUE;

    /** Whether the query can be modified */
    protected boolean unmodifiable = false;

    /** Whether to ignore dirty instances in the query. */
    protected boolean ignoreCache = false;

    /** Fetch Plan to use for the query. */
    private FetchPlan fetchPlan;

    /** Any JPOX extensions */
    protected Map extensions = null;

    /** Any subqueries, keyed by the variable name that they represent. */
    protected Map subqueries = null;

    /** State variable for the compilation state */
    protected transient boolean isCompiled = false;

    /** Map of implicit parameters, keyed by the name/number(as String). */
    protected transient HashMap implicitParameters = null;

    /** The imports definition. */
    protected transient Imports parsedImports = null;

    /** Array of (explicit) parameter names. */
    protected transient String[] parameterNames = null;

    /**
     * All query results obtained from this query.
     * This is required because the query can be executed multiple times changing
     * the input slightly each time for example.
     */
    protected transient HashSet queryResults = new HashSet();

    /**
     * Constructs a new query instance that uses the given persistence manager.
     * @param om The ObjectManager for this query.
     */
    public Query(ObjectManager om)
    {
        this.om = om;
        if (om == null)
        {
            // OM should always be provided so throw exception if null
            throw new JPOXUserException(LOCALISER.msg("021012"));
        }

        // Inherit IgnoreCache from PersistenceManager (JDO 1.0 $12.6.3)
        this.ignoreCache = om.getIgnoreCache();
    }

    /**
     * Utility to remove any previous compilation of this Query.
     **/
    protected void discardCompiled()
    {
        isCompiled = false;
        parsedImports = null;
        parameterNames = null;
    }

    /**
     * Equality operator.
     * @param obj Object to compare against
     * @return Whether this and the other object are equal.
     **/
    public boolean equals(Object obj)
    {
        if (obj == this)
        {
            return true;
        }

        if (!(obj instanceof Query))
        {
            return false;
        }

        Query q = (Query)obj;

        if (candidateClass == null)
        {
            if (q.candidateClass != null)
            {
                return false;
            }
        }
        else if (!candidateClass.equals(q.candidateClass))
        {
            return false;
        }

        if (filter == null)
        {
            if (q.filter != null)
            {
                return false;
            }
        }
        else if (!filter.equals(q.filter))
        {
            return false;
        }

        if (imports == null)
        {
            if (q.imports != null)
            {
                return false;
            }
        }
        else if (!imports.equals(q.imports))
        {
            return false;
        }

        if (explicitParameters == null)
        {
            if (q.explicitParameters != null)
            {
                return false;
            }
        }
        else if (!explicitParameters.equals(q.explicitParameters))
        {
            return false;
        }

        if (explicitVariables == null)
        {
            if (q.explicitVariables != null)
            {
                return false;
            }
        }
        else if (!explicitVariables.equals(q.explicitVariables))
        {
            return false;
        }

        if (unique != q.unique)
        {
            return false;
        }

        if (unmodifiable != q.unmodifiable)
        {
            return false;
        }

        if (resultClass != q.resultClass)
        {
            return false;
        }

        if (grouping == null)
        {
            if (q.grouping != null)
            {
                return false;
            }
        }
        else if (!grouping.equals(q.grouping))
        {
            return false;
        }

        if (ordering == null)
        {
            if (q.ordering != null)
            {
                return false;
            }
        }
        else if (!ordering.equals(q.ordering))
        {
            return false;
        }

        return true;
    }

    /**
     * Hashcode generator.
     * @return The Hashcode for this object.
     */
    public int hashCode()
    {
        return (candidateClass == null ? 0 : candidateClass.hashCode()) ^
            (result == null ? 0 : result.hashCode()) ^
          (filter == null ? 0 : filter.hashCode()) ^
          (imports == null ? 0 : imports.hashCode()) ^
          (explicitParameters == null ? 0 : explicitParameters.hashCode()) ^
          (explicitVariables == null ? 0 : explicitVariables.hashCode()) ^
          (resultClass == null ? 0 : resultClass.hashCode()) ^
          (grouping == null ? 0 : grouping.hashCode()) ^
            (having == null ? 0 : having.hashCode()) ^
          (ordering == null ? 0 : ordering.hashCode()) ^
            (range == null ? 0 : range.hashCode());
    }

    /**
     * Accessor for the query type.
     * @return The query type
     */
    public short getType()
    {
        return type;
    }

    /**
     * Mutator to set the query type.
     * @param type The query type
     */
    public void setType(short type)
    {
        if (type == SELECT || type == BULK_UPDATE || type == BULK_DELETE)
        {
            this.type = type;
        }
        else
        {
            throw new JPOXUserException(
                "JPOX Query only supports types of SELECT, BULK_UPDATE, BULK_DELETE : unknown value " + type);
        }
    }

    /**
     * Accessor for the StoreManager associated with this Query.
     * @return the StoreManager associated with this Query.
     */
    public StoreManager getStoreManager()
    {
        return om.getStoreManager();
    }

    /**
     * Accessor for the PersistenceManager associated with this Query.
     * @return the PersistenceManager associated with this Query.
     * @see javax.jdo.Query#getPersistenceManager
     */
    public ObjectManager getObjectManager()
    {
        return om;
    }

    /**
     * Add a vendor-specific extension this query. The key and value
     * are not standard.
     * An implementation must ignore keys that are not recognized.
     * @param key the extension key
     * @param value the extension value
     * @since JDO 2.0
     */
    public void addExtension(String key, Object value)
    {
        if (extensions == null)
        {
            extensions = new HashMap();
        }
        extensions.put(key, value);
    }

    /**
     * Set multiple extensions, or use null to clear extensions.
     * Map keys and values are not standard.
     * An implementation must ignore entries that are not recognized.
     * @param extensions
     * @see #addExtension
     * @since 1.1
     */
    public void setExtensions(Map extensions)
    {
        this.extensions = new HashMap(extensions);
    }

    /**
     * Accessor for the value of an extension for this query.
     * @param key The key
     * @return The value (if this extension is specified)
     */
    public Object getExtension(String key)
    {
        return (extensions != null ? extensions.get(key) : null);
    }

    /**
     * This method retrieves the fetch plan associated with the Query. It always
     * returns the identical instance for the same Query instance. Any change
     * made to the fetch plan affects subsequent query execution. Fetch plan is
     * described in Section 12.7
     * @return the FetchPlan
     */
    public FetchPlan getFetchPlan()
    {
        if (fetchPlan == null)
        {
            // Copy the FetchPlan of the ObjectManager
            this.fetchPlan = om.getFetchPlan().getCopy();
        }

        return fetchPlan;
    }

    /**
     * Mutator for the FetchPlan of the query.
     * This is called when applying a named FetchPlan.
     * @param fp The FetchPlan
     */
    public void setFetchPlan(FetchPlan fp)
    {
        // Update the FetchPlan
        this.fetchPlan = fp;
    }

    /**
     * Set the UPDATE clause of the query.
     * @param update the update clause
     */
    public void setUpdate(String update)
    {
        discardCompiled();
        assertIsModifiable();
   
        this.update = update;
    }

    /**
     * Accessor for the UPDATE clause of the JPQL query.
     * @return Update clause
     */
    public String getUpdate()
    {
        return update;
    }

    /**
     * Accessor for the class of the candidate instances of the query.
     * @return the Class of the candidate instances.
     * @see javax.jdo.Query#setClass
     */
    public Class getCandidateClass()
    {
        return candidateClass;
    }

    /**
     * Mutator for the class of the candidate instances of the query.
     * @param candidateClass the Class of the candidate instances.
     * @see javax.jdo.Query#setClass
     */
    public void setClass(Class candidateClass)
    {
        discardCompiled();
        assertIsModifiable();

        this.candidateClassName = (candidateClass != null ? candidateClass.getName() : null);
        this.candidateClass = candidateClass;
    }

    /**
     * Convenience method to set the name of the candidate class.
     * @param candidateClassName Name of the candidate class
     */
    public void setCandidateClassName(String candidateClassName)
    {
        this.candidateClassName = (candidateClassName != null ? candidateClassName.trim() : null);
    }

    /**
     * Accessor for the candidate class name.
     * @return Name of the candidate class (if any)
     */
    public String getCandidateClassName()
    {
        return candidateClassName;
    }

    /**
     * Set the candidates to the query.
     * @param from the candidates
     */
    public void setFrom(String from)
    {
        discardCompiled();
        assertIsModifiable();
   
        this.from = from;
    }

    /**
     * Accessor for the FROM clause of the query.
     * @return From clause
     */
    public String getFrom()
    {
        return from;
    }

    /**
     * Set the candidate Extent to query. To be implemented by extensions.
     * @param pcs the Candidate Extent.
     * @see javax.jdo.Query#setCandidates(javax.jdo.Extent)
     */
    public abstract void setCandidates(Extent pcs);

    /**
     * Set the candidate Collection to query. To be implemented by extensions.
     * @param pcs the Candidate collection.
     * @see javax.jdo.Query#setCandidates(java.util.Collection)
     */
    public abstract void setCandidates(Collection pcs);

    /**
     * Set the filter for the query.
     * @param filter the query filter.
     * @see javax.jdo.Query#setFilter
     */
    public void setFilter(String filter)
    {
        discardCompiled();
        assertIsModifiable();

        this.filter = (filter != null ? filter.trim() : null);
    }

    /**
     * Accessor for the filter specification.
     * @return Filter specification
     */
    public String getFilter()
    {
        return filter;
    }

    /**
     * Set the import statements to be used to identify the fully qualified name
     * of variables or parameters.
     * @param imports import statements separated by semicolons.
     * @see javax.jdo.Query#declareImports
     */
    public void declareImports(String imports)
    {
        discardCompiled();
        assertIsModifiable();

        this.imports = (imports != null ? imports.trim() : null);
    }

    /**
     * Accessor for the imports specification.
     * @return Imports specification
     */
    public String getImports()
    {
        return imports;
    }

    /**
     * Method to define the explicit parameters.
     * @param parameters the list of parameters separated by commas
     */
    public void declareExplicitParameters(String parameters)
    {
        discardCompiled();
        assertIsModifiable();

        this.explicitParameters = (StringUtils.isWhitespace(parameters) ? null : parameters.trim());
    }

    /**
     * Accessor for the explicit parameters specification.
     * @return Explicit parameters specification
     */
    public String getExplicitParameters()
    {
        return explicitParameters;
    }

    /**
     * Method to set the value of a named implicit parameter where known before execution.
     * @param name Name of the parameter
     * @param value Value of the parameter
     * @throws JPOXQueryInvalidParametersException if the parameter is invalid
     */
    public void setImplicitParameter(String name, Object value)
    {
        if (implicitParameters == null)
        {
            implicitParameters = new HashMap();
        }
        implicitParameters.put(name, value);
        discardCompiled();
        compileInternal(false, implicitParameters);
    }

    /**
     * Method to set the value of a numbered implicit parameter where known before execution.
     * @param position Position of the parameter
     * @param value Value of the parameter
     * @throws JPOXQueryInvalidParametersException if the parameter is invalid
     */
    public void setImplicitParameter(int position, Object value)
    {
        if (implicitParameters == null)
        {
            implicitParameters = new HashMap();
        }
        implicitParameters.put(new Integer(position), value);
        discardCompiled();
        compileInternal(false, implicitParameters);
    }

    /**
     * Method to define the explicit variables for the query.
     * @param variables the variables separated by semicolons.
     */
    public void declareExplicitVariables(String variables)
    {
        discardCompiled();
        assertIsModifiable();

        this.explicitVariables = (StringUtils.isWhitespace(variables) ? null : variables.trim());
    }

    /**
     * Accessor for the explicit variables specification.
     * @return Explicit variables specification
     */
    public String getExplicitVariables()
    {
        return explicitVariables;
    }

    /**
     * Set the ordering specification for the result Collection.
     * @param ordering the ordering specification.
     * @see javax.jdo.Query#setOrdering
     */
    public void setOrdering(String ordering)
    {
        discardCompiled();
        assertIsModifiable();

        this.ordering = (ordering != null ? ordering.trim() : null);
    }

    /**
     * Accessor for the ordering string for the query.
     * @return Ordering specification
     */
    public String getOrdering()
    {
        return ordering;
    }

    /**
     * Set the grouping specification for the result Collection.
     * @param grouping the grouping specification.
     * @see javax.jdo.Query#setGrouping
     */
    public void setGrouping(String grouping)
    {
        discardCompiled();
        assertIsModifiable();

        this.grouping = (grouping != null ? grouping.trim() : null);
    }

    /**
     * Accessor for the grouping string for the query.
     * @return Grouping specification
     */
    public String getGrouping()
    {
        return grouping;
    }

    /**
     * Set the having specification for the result Collection.
     * @param having the having specification.
     */
    public void setHaving(String having)
    {
        discardCompiled();
        assertIsModifiable();

        this.having = (having != null ? having.trim() : null);
    }

    /**
     * Accessor for the having string for the query.
     * @return Having specification
     */
    public String getHaving()
    {
        return having;
    }

    /**
     * Set the uniqueness of the results. A value of true will return a single
     * value (or null) where the application knows that there are 0 or 1
     * objects to be returned. See JDO 2.0 specification section 14.6
     * @param unique whether the result is unique
     * @see javax.jdo.Query#setUnique
     * @since 1.1
     */
    public void setUnique(boolean unique)
    {
        discardCompiled();
        assertIsModifiable();

        this.unique = unique;
    }

    /**
     * Accessor for whether the query results are unique.
     * @return Whether it is unique
     */
    public boolean isUnique()
    {
        return unique;
    }

    /**
     * Set the range of the results. By default all results are returned but
     * this allows specification of a range of elements required. See JDO 2.0
     * specification section 14.6.8
     * @param fromIncl From element no (inclusive) to return
     * @param toExcl To element no (exclusive) to return
     * @see javax.jdo.Query#setRange(long, long)
     * @since 1.1
     */
    public void setRange(long fromIncl, long toExcl)
    {
        discardCompiled();

        // JDO2 spec 14.6 setRange is valid when unmodifiable so dont check it
        this.range = null;
        this.fromInclNo = fromIncl;
        this.toExclNo = toExcl;
    }

    /**
     * Set the range of the results. By default all results are returned but
     * this allows specification of a range of elements required. See JDO 2.0
     * specification section 14.6.8
     * @param range Range string
     * @see javax.jdo.Query#setRange(java.lang.String)
     * @since 1.1
     */
    public void setRange(String range)
    {
        discardCompiled();

        // JDO2 spec 14.6 setRange is valid when unmodifiable so dont check it
        // fromInclNo, toExclNo will be extracted when compiling
        this.range = (range != null ? range.trim() : null);
        fromInclNo = 0;
        toExclNo = Long.MAX_VALUE;
    }

    /**
     * Accessor for the range specification.
     * @return Range specification
     */
    public String getRange()
    {
        return range;
    }

    /**
     * Accessor for the range lower limit (inclusive).
     * @return Range lower limit
     */
    public long getRangeFromIncl()
    {
        return fromInclNo;
    }

    /**
     * Accessor for the range upper limit (exclusive).
     * @return Range upper limit
     */
    public long getRangeToExcl()
    {
        return toExclNo;
    }

    /**
     * Set the result for the results. The application might want to get results
     * from a query that are not instances of the candidate class. The results
     * might be fields of persistent instances, instances of classes other than
     * the candidate class, or aggregates of fields.
     * @param result The result parameter consists of the optional keyword
     * distinct followed by a commaseparated list of named result expressions or
     * a result class specification.
     * @see javax.jdo.Query#setResult
     * @since 1.1
     */
    public void setResult(String result)
    {
        discardCompiled();
        assertIsModifiable();

        this.result = (result != null ? result.trim() : null);
    }

    /**
     * Accessor for the result specification string.
     * @return Result specification
     */
    public String getResult()
    {
        return result;
    }

    /**
     * Set the result class for the results.
     * The result class must obey various things as per the JDO 2.0 spec 14.6.12.
     * @param result_cls The result class
     * @see javax.jdo.Query#setResultClass
     * @since 1.1
     */
    public void setResultClass(Class result_cls)
    {
        discardCompiled();

        // JDO2 spec 14.6 setResultClass is valid when unmodifiable so dont check it
        this.resultClassName = (result_cls != null ? result_cls.getName() : null);
        this.resultClass = result_cls;
    }

    /**
     * Accessor for the result class.
     * @return Result class
     */
    public Class getResultClass()
    {
        return resultClass;
    }

    /**
     * Convenience method to set the name of the result class.
     * @param resultClassName Name of the result class
     */
    public void setResultClassName(String resultClassName)
    {
        this.resultClassName = resultClassName;
    }

    /**
     * Accessor for the name of the result class.
     * @return Result class name
     */
    public String getResultClassName()
    {
        return resultClassName;
    }

    /**
     * Method to set the MetaData defining the result.
     * If the query doesn't support such a setting will throw a JPOXException.
     * @param qrmd QueryResultMetaData
     * @since 1.2
     */
    public void setResultMetaData(QueryResultMetaData qrmd)
    {
        throw new JPOXException("This query doesn't support the use of setResultMetaData()");
    }

    /**
     * Set the ignoreCache option. Currently this simply stores the ignoreCache value, and doesn't
     * necessarily use it. The parameter is a "hint" to the query engine. TODO : Implement this fully.
     * @param ignoreCache the setting of the ignoreCache option.
     * @see javax.jdo.Query#setIgnoreCache
     * @see javax.jdo.PersistenceManager#setIgnoreCache
     */
    public void setIgnoreCache(boolean ignoreCache)
    {
        discardCompiled();

        // JDO2 spec 14.6 setIgnoreCache is valid when unmodifiable so dont check it
        this.ignoreCache = ignoreCache;
    }

    /**
     * Accessor for the ignoreCache option setting.
     * @return the ignoreCache option setting
     * @see #setIgnoreCache
     * @see javax.jdo.Query#getIgnoreCache
     * @see javax.jdo.PersistenceManager#getIgnoreCache
     */
    public boolean getIgnoreCache()
    {
        return ignoreCache;
    }

    /**
     * Accessor for whether this query includes subclasses
     * @return Returns whether the query includes subclasses.
     */
    public boolean isSubclasses()
    {
        return subclasses;
    }

    /**
     * Mutator for whether this query includes subclasses
     * @param subclasses Where subclasses of the candidate class are to be included.
     */
    public void setSubclasses(boolean subclasses)
    {
        discardCompiled();
        assertIsModifiable();

        this.subclasses = subclasses;

        // Set the candidates also if the candidate has been set
        /*if (candidateClass != null)
        {
            setCandidates(om.getExtent(candidateClass, subclasses));
        }*/
    }

    /**
     * Accessor for unmodifiable.
     * @return Returns the unmodifiable.
     */
    public boolean isUnmodifiable()
    {
        return unmodifiable;
    }

    /**
     * Method to throw a JPOXUserException if the query is currently not modifiable.
     * @throws JPOXUserException Thrown when it is unmodifiable
     */
    protected void assertIsModifiable()
    {
        if (unmodifiable)
        {
            throw new JPOXUserException(LOCALISER.msg("021014"));
        }
    }

    /**
     * Mutator for unmodifiable.
     */
    public void setUnmodifiable()
    {
        this.unmodifiable = true;
    }

    /**
     * Method to add a subquery to this query.
     * @param sub The subquery
     * @param variableDecl Declaration of variables
     * @param candidateExpr Candidate expression
     * @param paramMap Map of parameters for this subquery
     */
    public void addSubquery(Query sub, String variableDecl, String candidateExpr, Map paramMap)
    {
        if (StringUtils.isWhitespace(variableDecl))
        {
            throw new JPOXUserException(LOCALISER.msg("021078"));
        }

        if (sub == null)
        {
            // No subquery so the variable is unset effectively meaning that it is an explicit variable
            if (explicitVariables == null)
            {
                explicitVariables = variableDecl;
            }
            else
            {
                explicitVariables += ";" + variableDecl;
            }
        }
        else
        {
            // Register the subquery against its variable name for later use
            if (subqueries == null)
            {
                subqueries = new HashMap();
            }
            String subqueryVariableName = variableDecl.trim();
            int sepPos = subqueryVariableName.indexOf(' ');
            subqueryVariableName = subqueryVariableName.substring(sepPos+1);
            subqueries.put(subqueryVariableName,
                new SubqueryDefinition(sub, StringUtils.isWhitespace(candidateExpr) ? null : candidateExpr,
                        variableDecl, paramMap));
        }
    }

    /**
     * Simple representation of a subquery, its candidate, params and variables.
     */
    public class SubqueryDefinition
    {
        Query query;
        String candidateExpression;
        String variableDecl;
        Map parameterMap;

        public SubqueryDefinition(Query q, String candidates, String variables, Map params)
        {
            this.query = q;
            this.candidateExpression = candidates;
            this.variableDecl = variables;
            this.parameterMap = params;
        }

        public Query getQuery()
        {
            return this.query;
        }

        public String getCandidateExpression()
        {
            return this.candidateExpression;
        }

        public String getVariableDeclaration()
        {
            return this.variableDecl;
        }

        public Map getParameterMap()
        {
            return this.parameterMap;
        }
    }

    /**
     * Accessor for the subquery for the supplied variable.
     * @param variableName Name of the variable
     * @return Subquery for the variable (if a subquery exists for this variable)
     */
    public SubqueryDefinition getSubqueryForVariable(String variableName)
    {
        if (subqueries == null)
        {
            return null;
        }
        return (SubqueryDefinition)subqueries.get(variableName);
    }

    /**
     * Accessor for whether there is a subquery for the specified variable name.
     * @param variableName Name of the variable
     * @return Whether there is a subquery defined
     */
    public boolean hasSubqueryForVariable(String variableName)
    {
        return (subqueries == null ? false : subqueries.containsKey(variableName));
    }

    /**
     * Convenience method that will flush any outstanding updates to the datastore.
     * This is intended to be used before execution so that the datastore has all relevant data present
     * for what the query needs.
     */
    protected void prepareDatastore()
    {
        boolean flush = false;
        if (!ignoreCache && !om.isDelayDatastoreOperationsEnabled())
        {
            flush = true;
        }
        else if (extensions != null && extensions.containsKey("org.jpox.query.flushBeforeExecution"))
        {
            flush = Boolean.valueOf((String)extensions.get("org.jpox.query.flushBeforeExecution")).booleanValue();
        }
        else if (om.getOMFContext().getPersistenceConfiguration().getBooleanProperty("org.jpox.query.flushBeforeExecution"))
        {
            flush = true;
        }
        if (flush)
        {
            // Make sure all changes are in the datastore before proceeding
            om.flushInternal(false);
        }
    }

    /**
     * Accessor for whether the query is compiled.
     * @return Whether the query is compiled.
     */
    public boolean isCompiled()
    {
        return isCompiled;
    }

    /**
     * Verify the elements of the query and provide a hint to the query to prepare and optimize an execution plan.
     */
    public void compile()
    {
        if (isCompiled)
        {
            return;
        }

        compileInternal(false, null);
    }

    /**
     * Method to compile the query. To be implemented by the query implementation.
     * @param forExecute Whether to compile the query ready for execution (using any param values)
     * @param parameterValues Param values keyed by name (when compiling for execution)
     */
    protected abstract void compileInternal(boolean forExecute, Map parameterValues);

    /**
     * Accessor for the parsed imports.
     * If no imports are set then adds candidate class and user imports.
     * @return Parsed imports
     */
    public Imports getParsedImports()
    {
        if (parsedImports == null)
        {
            parsedImports = new Imports();
            if (candidateClassName != null)
            {
                parsedImports.importPackage(candidateClassName);
            }
            if (imports != null)
            {
                parsedImports.parseImports(imports);
            }
        }
        return parsedImports;
    }

    /**
     * Utility to resolve the declaration to a particular class.
     * Takes the passed in name, together with the defined import declarations and returns the
     * class represented by the declaration.
     * @param classDecl The declaration
     * @return The class it resolves to (if any)
     * @throws JPOXUserException Thrown if the class cannot be resolved.
     */
    public Class resolveClassDeclaration(String classDecl)
    {
        try
        {
            return getParsedImports().resolveClassDeclaration(classDecl, om.getClassLoaderResolver(),
                (candidateClass == null ? null : candidateClass.getClassLoader()));
        }
        catch (ClassNotResolvedException e)
        {
            throw new JPOXUserException(LOCALISER.msg("021015", classDecl));
        }
    }

    // ----------------------------- Execute -----------------------------------

    /**
     * Execute the query and return the filtered List.
     * @return the filtered List.
     * @see javax.jdo.Query#execute()
     * @see #executeWithArray(Object[] parameters)
     */
    public Object execute()
    {
        return executeWithArray(new Object[0]);
    }

    /**
     * Execute the query and return the filtered List.
     * @param p1 the value of the first parameter declared.
     * @return the filtered List.
     * @see javax.jdo.Query#execute(Object)
     * @see #executeWithArray(Object[] parameters)
     */
    public Object execute(Object p1)
    {
        return executeWithArray(new Object[] { p1 });
    }

    /**
     * Execute the query and return the filtered List.
     * @param p1 the value of the first parameter declared.
     * @param p2 the value of the second parameter declared.
     * @return the filtered List.
     * @see javax.jdo.Query#execute(Object,Object)
     * @see #executeWithArray(Object[] parameters)
     */
    public Object execute(Object p1, Object p2)
    {
        return executeWithArray(new Object[] { p1, p2 });
    }

    /**
     * Execute the query and return the filtered List.
     * @param p1 the value of the first parameter declared.
     * @param p2 the value of the second parameter declared.
     * @param p3 the value of the third parameter declared.
     * @return the filtered List.
     * @see javax.jdo.Query#execute(Object,Object,Object)
     * @see #executeWithArray(Object[] parameters)
     */
    public Object execute(Object p1, Object p2, Object p3)
    {
        return executeWithArray(new Object[] { p1, p2, p3 });
    }

    /**
     * Execute the query and return the filtered List.
     * @param parameterValues the Object array with all of the parameters.
     * @return the filtered List.
     * @see javax.jdo.Query#executeWithArray(Object[])
     */
    public Object executeWithArray(Object[] parameterValues)
    {
        if (om == null)
        {
            // Is checked at construction, but could have been deserialised (and serialised have no manager)
            throw new JPOXUserException(LOCALISER.msg("021017"));
        }

        // Compile the explicit parameters
        QueryCompiler c = new QueryCompiler(this, getParsedImports(), null);
        c.compile(QueryCompiler.COMPILE_EXPLICIT_PARAMETERS);
        parameterNames = c.getParameterNames();

        // Build the parameter values into a Map so we have a common interface
        HashMap parameterMap = new HashMap();
        if (parameterNames != null && parameterNames.length > 0)
        {
            // Explicit parameters defined
            for (int i = 0; i < parameterValues.length; ++i)
            {
                parameterMap.put(parameterNames[i], parameterValues[i]);
            }
        }
        else
        {
            // Must be implicit parameters, so give them dummy names for now
            for (int i = 0; i < parameterValues.length; ++i)
            {
                parameterMap.put("JPOX_" + i, parameterValues[i]);
            }
        }

        return executeWithMap(parameterMap);
    }

    /**
     * Execute the query and return the filtered result(s).
     * @param parameters the Map containing all of the parameters.
     * @return the filtered results (List, or Object)
     * @see javax.jdo.Query#executeWithMap(Map)
     * @see #executeWithArray(Object[] parameters)
     * @throws NoQueryResultsException Thrown if no results were returned from the query.
     */
    public Object executeWithMap(Map parameters)
    {
        if (om == null)
        {
            // Is checked at construction, but could have been deserialised (and serialised have no manager)
            throw new JPOXUserException(LOCALISER.msg("021017"));
        }
        if (om.isClosed())
        {
            // Throw exception if query is closed (e.g JDO2 [14.6.1])
            throw new JPOXUserException(LOCALISER.msg("021013")).setFatal();
        }
        if (!om.getTransaction().isActive() && !om.getTransaction().getNontransactionalRead())
        {
            throw new TransactionNotReadableException();
        }

        boolean failed = true; // flag to use for checking the state of the execution results
        long start = System.currentTimeMillis();

        QueryRuntime queryRuntime = om.getOMFContext().getQueryManager().getQueryRuntime();
        if (queryRuntime != null)
        {
            queryRuntime.queryBegin();
        }

        try
        {
            // Execute the query
            Collection qr = (Collection)performExecute(parameters);

            failed = false;
            if (shouldReturnSingleRow())
            {
                try
                {
                    // Single row only needed (unique specified, or using aggregates etc), so just take the first row of the results
                    if (qr == null || qr.size() == 0)
                    {
                        throw new NoQueryResultsException("No query results were returned");
                    }
                    else
                    {
                        if (applyRangeChecks() && (toExclNo - fromInclNo <= 0))
                        {
                            // JDO2 spec 14.6.8 (range excludes instances, so return null)
                            throw new NoQueryResultsException("No query results were returned in the required range");
                        }

                        Iterator qrIter = qr.iterator();
                        Object firstRow = qrIter.next();
                        if (qrIter.hasNext())
                        {
                            failed = true;
                            throw new QueryNotUniqueException();
                        }
                        return firstRow;
                    }
                }
                finally
                {
                    // can close qr right now because we don't return it,
                    // also user cannot close it otherwise except for calling closeAll()
                    if (qr != null)
                    {
                        close(qr);
                    }
                }
            }
   
            // Process any specified range
            if (applyRangeChecks())
            {
                // Range not applied in the compiled query so throw away objects outside the required range
                int i=0;
                Iterator qr_iter=qr.iterator();
                Collection res=new ArrayList();
                while (qr_iter.hasNext())
                {
                    Object obj=qr_iter.next();
                    if (i >= fromInclNo && i < toExclNo)
                    {
                        // Accept the item if within range
                        res.add(obj);
                    }
                    i++;
                }
                return res;
            }
            else
            {
                // Range applied in the compiled query (or no range) so just return it
                return qr;
            }
        }
        finally
        {
            if (queryRuntime != null)
            {
                if (failed)
                {
                    queryRuntime.queryExecutedWithError();
                }
                else
                {
                    queryRuntime.queryExecuted(System.currentTimeMillis()-start);
                }
            }
        }
    }

    /**
     * Convenience method to return whether the query should return a single row.
     * @return Whether a single row should result
     */
    protected abstract boolean shouldReturnSingleRow();

    /**
     * Method to return if the query results should have the range checked and unnecessary rows
     * discarded. This is for where the query language has specified a range but the datastore doesnt
     * allow removal of unnecessary results in the query itself (so has to be done in post-processing).
     * This implementation returns false and so should be overridden by query languages to match their
     * capabilities.
     * @return Whether to apply range checks in post-processing of results.
     */
    protected boolean applyRangeChecks()
    {
        return false;
    }

    /**
     * Method to actually execute the query. To be implemented by extending
     * classes for the particular query language.
     * @param parameters Map containing the parameters.
     * @return Query result - QueryResult if SELECT, or Long if BULK_UPDATE, BULK_DELETE
     */
    protected abstract Object performExecute(Map parameters);

    // ------------------------- Delete Persistent -----------------------------

    /**
     * Method to delete all objects found by this query, catering for cascade changes and updates
     * to in-memory objects.
     * @return The number of deleted objects.
     * @see javax.jdo.Query#deletePersistentAll()
     */
    public long deletePersistentAll()
    {
        return deletePersistentAll(new Object[0]);
    }

    /**
     * Method to delete all objects found by this query, catering for cascade changes and updates
     * to in-memory objects.
     * @param parameters the Object array with all of the parameters.
     * @return the filtered Collection.
     * @see javax.jdo.Query#deletePersistentAll(Object[])
     */
    public long deletePersistentAll(Object[] parameters)
    {
        // Compile the explicit parameters
        QueryCompiler c = new QueryCompiler(this, getParsedImports(), null);
        c.compile(QueryCompiler.COMPILE_EXPLICIT_PARAMETERS);
        parameterNames = c.getParameterNames();

        // Build the parameter values into a Map so we have a common interface
        HashMap parameterMap = new HashMap();
        if (parameterNames != null && parameterNames.length > 0)
        {
            // Explicit parameters defined
            for (int i = 0; i < parameters.length; ++i)
            {
                parameterMap.put(parameterNames[i], parameters[i]);
            }
        }
        else
        {
            // Must be implicit parameters, so give them dummy names for now
            for (int i = 0; i < parameters.length; ++i)
            {
                parameterMap.put("JPOX_" + i, parameters[i]);
            }
        }

        return deletePersistentAll(parameterMap);
    }

    /**
     * Method to delete all objects found by this query, catering for cascade changes and updates
     * to in-memory objects.
     * @param parameters Map of parameters for the query
     * @return the number of deleted objects
     * @see javax.jdo.Query#deletePersistentAll(Map)
     */
    public long deletePersistentAll(Map parameters)
    {
        if (om.isClosed())
        {
            // Throw exception if query is closed (e.g JDO2 [14.6.1])
            throw new JPOXUserException(LOCALISER.msg("021013")).setFatal();
        }
        if (!om.getTransaction().isActive() && !om.getTransaction().getNontransactionalWrite())
        {
            // tx not active and not allowing non-tx write
            throw new TransactionNotActiveException();
        }

        // Compile the "query" for execution
        compileInternal(true, parameters);

        // Check for specification of any illegal attributes
        if (result != null)
        {
            throw new JPOXUserException(LOCALISER.msg("021029"));
        }
        if (resultClass != null)
        {
            throw new JPOXUserException(LOCALISER.msg("021030"));
        }
        if (resultClassName != null)
        {
            throw new JPOXUserException(LOCALISER.msg("021030"));
        }
        if (ordering != null)
        {
            throw new JPOXUserException(LOCALISER.msg("021027"));
        }
        if (grouping != null)
        {
            throw new JPOXUserException(LOCALISER.msg("021028"));
        }
        if (range != null)
        {
            throw new JPOXUserException(LOCALISER.msg("021031"));
        }
        if (fromInclNo >= 0 && toExclNo >= 0 && (fromInclNo != 0 || toExclNo != Long.MAX_VALUE))
        {
            throw new JPOXUserException(LOCALISER.msg("021031"));
        }

        long qr = performDeletePersistentAll(parameters);

        return qr;
    }

    /**
     * Method to actually execute the deletion of objects.
     * To be implemented by extending classes.
     * @param parameters Map containing the parameters.
     * @return The filtered QueryResult.
     */
    protected abstract long performDeletePersistentAll(Map parameters);

    // -------------------------------------------------------------------------

    /**
     * Close a query result and release any resources associated with it.
     * @param queryResult the result of execute(...) on this Query instance.
     * @see javax.jdo.Query#close
     */
    public void close(Object queryResult)
    {
        if (queryResult != null && queryResult instanceof QueryResult)
        {
            ((QueryResult)queryResult).close();
            queryResults.remove(queryResult);
        }
    }

    /**
     * Close all query results associated with this Query instance,
     * and release all resources associated with them.
     * @see javax.jdo.Query#closeAll
     */
    public void closeAll()
    {
        QueryResult[] qrs = (QueryResult[])queryResults.toArray(new QueryResult[queryResults.size()]);
        for (int i = 0; i < qrs.length; ++i)
        {
            close(qrs[i]);
        }
    }
}
TOP

Related Classes of org.jpox.store.query.Query$SubqueryDefinition

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.