org.josql
Class Query

java.lang.Object
  extended by org.josql.Query
Direct Known Subclasses:
JoSQLAntFileSelector, JoSQLFreeChartCategoryDataset, JoSQLFreeChartPieDataset, JoSQLFreeChartXYDataset, JoSQLJRDataSource, JoSQLSwingTableModel

public class Query
extends Object

This class provides the ability for a developer to apply an arbitrary SQL statement (using suitable syntax) to a collection of Java objects.

Basic usage:

   Query q = new Query ();
   q.parse (myStatement);
   List results = q.execute (myObjects);
 

An example statement would look like:

   SELECT lastModified,
          name
   FROM   java.io.File
   WHERE  name LIKE '%.html'
 

The JoSQL functionality is large and complex, whilst basic queries like the one above are perfectly possible, very complex queries are also possible, for example:

   SELECT name,
          formatDate(lastModified),
          formatNumber(length),
          formatNumber(length - @avg_length),
          formatTimeDuration(@max_last_modified - lastModified)
   FROM   java.io.File
   WHERE  lastModified > @avg_last_modified
   AND    length > @avg_length
   AND    lower(name) LIKE '%.html'
   GROUP BY path
   ORDER BY name, lastModified DESC
   EXECUTE ON ALL avg (:_allobjs, length) avg_length,
                  avg (:_allobjs, lastModified) avg_last_modified,
                  max (:_allobjs, lastModified) max_last_modified
 

Note: the "EXECUTE ON ALL" syntax is an extension used by JoSQL because it has no notion of "aggregate functions".

For full details of how a query works and what is possible, see the JoSQL User Manual.

Please note that the package structure for JoSQL is deliberate, JoSQL is designed to be a black box and lightweight thus only the Query object and associated exceptions are exposed in the main package. Also, the class structure for JoSQL is not designed to exactly represent the SQL statement passed to it, rather the classes are optimised for ease of execution of the statement. If you wish to have a completely accurate Java object view of ANY SQL statement then please see: JSqlParser which will provide what you need.


Field Summary
static String ALL
           
static String ALL_OBJS_VAR_NAME
           
static String CURR_OBJ_VAR_NAME
           
static String GROUP_BY_RESULTS
           
static String GRPBY_OBJ_VAR_NAME
           
static String GRPBY_OBJ_VAR_NAME_SYNONYM
           
static String HAVING_RESULTS
           
static String INT_BIND_VAR_PREFIX
           
static List nullQueryList
           
static String ORDER_BY_ASC
           
static String ORDER_BY_DESC
           
static String PARENT_BIND_VAR_NAME
           
static String QUERY_BIND_VAR_NAME
           
static String RESULTS
           
static String WHERE_RESULTS
           
 
Constructor Summary
Query()
          Create a new blank Query object.
 
Method Summary
 void addBindVariableChangedListener(BindVariableChangedListener bvl)
           
 void addFunctionHandler(Object o)
           
 void addSaveValueChangedListener(SaveValueChangedListener svl)
           
protected  void addTiming(String id, double time)
           
 void doExecuteOn(List l, String t)
          Execute all the expressions for the specified type, either: ALL or: RESULTS.
 QueryResults execute(Collection objs)
          Execute this query on the specified objects.
 QueryResults execute(Iterator iter)
          Execute this query on the specified objects provided by the iterator.
 QueryResults execute(List objs)
          Execute this query on the specified objects.
protected  void fireBindVariableChangedEvent(String name, Object from, Object to)
           
protected  void fireSaveValueChangedEvent(Object id, Object from, Object to)
           
 Map getAliases()
           
 List getAllObjects()
          Get the current list of objects in context (value of the :_allobjs special bind variable).
 String getAnonymousBindVariableName()
           
 ClassLoader getClassLoader()
           
 List getColumns()
           
 Object getCurrentObject()
          Get the current object (value of the :_currobj special bind variable).
 List getDefaultFunctionHandlers()
           
 Map getExecuteOnFunctions()
           
 Expression getFrom()
           
 Class getFromObjectClass()
           
 FunctionHandler getFunctionHandler(String id)
           
 List getFunctionHandlers()
           
 List getGroupByColumns()
           
 Object getGroupBySaveValue(Object id, List gbs)
          Get the save value for a particular key and group by list.
 Map getGroupBySaveValues(List gbs)
          Get the save values for the specified group bys.
 Object getGroupByVariable(int ind)
          Get the value of a group by variable from the current group bys.
 Expression getHavingClause()
          Return the HAVING clause expression.
 Limit getLimit()
          Get the object that represents the limit clause.
 List getOrderByColumns()
          Get the "order bys".
 Comparator getOrderByComparator()
          Return the Comparator we will use to do the ordering of the results, may be null.
 Query getParent()
          Get the parent query.
 String getQuery()
          Get the query string that this Query object represents.
 QueryResults getQueryResults()
          Get the results of executing this query.
 Object getSaveValue(Object id)
          Get the save values for a particular key.
 Query getTopLevelQuery()
          Get the top level query if "this" is a sub-query, the query chain is traversed until the top level query is found, i.e.
 Object getVariable(int index)
          Get the value of an indexed bind variable.
 Object getVariable(String name)
          Get the value of a named bind variable.
 Class getVariableClass(String name)
          Get the class that the named variable has.
 Map getVariables()
          Get all the bind variables as a Map.
 Expression getWhereClause()
          Return the WHERE clause expression.
 char getWildcardCharacter()
          Get the character that represents a wildcard in LIKE searches.
 void init()
           
 void initOrderByComparator()
          Will cause the order by comparator used to order the results to be initialized.
 boolean isWantObjects()
          Return whether the query should return objects.
 boolean isWhereTrue(Object o)
          A helper method that will evaluate the WHERE clause for the object passed in.
 Class loadClass(String name)
           
 void parse(String q)
          Parse the JoSQL query.
static QueryResults parseAndExec(String query, List objs)
           
 boolean parsed()
          Return whether this Query object has had a statement applied to it and has been parsed.
 void removeBindVariableChangedListener(BindVariableChangedListener bvl)
           
 void removeSaveValueChangedListener(SaveValueChangedListener svl)
           
 QueryResults reorder(List objs, SortedMap dirs)
          Re-order the objects according to the columns supplied in the dirs Map.
 QueryResults reorder(List objs, String orderBys)
          Allows the re-ordering of the results via a textual representation of the order bys.
 void setAllObjects(List objs)
           
 void setClassLoader(ClassLoader cl)
           
 void setClassName(String n)
           
 void setColumns(List cols)
           
 void setCurrentGroupByObjects(List objs)
           
 void setCurrentObject(Object o)
           
 void setExecuteOnFunctions(Map ex)
           
 void setFrom(Expression exp)
           
 void setFromObjectClass(Class c)
          Set the "FROM" object class.
 void setGroupByColumns(List cols)
           
 void setGroupByLimit(Limit g)
           
 void setGroupByOrderColumns(List cols)
           
 void setHaving(Expression be)
          Set the expression for the HAVING clause.
 void setLimit(Limit l)
          Set the object that represents the limit clause.
 void setOrderByColumns(List cols)
           
 void setParent(Query q)
          Set the parent query.
 void setSaveValue(Object id, Object value)
           
 void setSaveValues(Map s)
           
 void setVariable(int index, Object v)
          Set the value of an indexed bind variable.
 void setVariable(String name, Object v)
          Set the value of a named bind variable.
 void setVariables(Map bVars)
          Set the bind variables in one go.
 void setWantDistinctResults(boolean v)
          Indicate whether "distinct" results are required.
 void setWantObjects(boolean v)
          Set whether the query should return objects (use true).
 void setWantTimings(boolean v)
           
 void setWhere(Expression be)
          Set the expression for the WHERE clause.
 void setWildcardCharacter(char c)
          Set the character that represents a wildcard in LIKE searches.
 String toString()
          Get a string version of this query suitable for debugging.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

QUERY_BIND_VAR_NAME

public static String QUERY_BIND_VAR_NAME

PARENT_BIND_VAR_NAME

public static String PARENT_BIND_VAR_NAME

CURR_OBJ_VAR_NAME

public static String CURR_OBJ_VAR_NAME

ALL_OBJS_VAR_NAME

public static String ALL_OBJS_VAR_NAME

GRPBY_OBJ_VAR_NAME

public static String GRPBY_OBJ_VAR_NAME

GRPBY_OBJ_VAR_NAME_SYNONYM

public static String GRPBY_OBJ_VAR_NAME_SYNONYM

INT_BIND_VAR_PREFIX

public static final String INT_BIND_VAR_PREFIX
See Also:
Constant Field Values

ALL

public static final String ALL
See Also:
Constant Field Values

RESULTS

public static final String RESULTS
See Also:
Constant Field Values

GROUP_BY_RESULTS

public static final String GROUP_BY_RESULTS
See Also:
Constant Field Values

WHERE_RESULTS

public static final String WHERE_RESULTS
See Also:
Constant Field Values

HAVING_RESULTS

public static final String HAVING_RESULTS
See Also:
Constant Field Values

ORDER_BY_ASC

public static final String ORDER_BY_ASC
See Also:
Constant Field Values

ORDER_BY_DESC

public static final String ORDER_BY_DESC
See Also:
Constant Field Values

nullQueryList

public static final List nullQueryList
Constructor Detail

Query

public Query()
Create a new blank Query object.

Method Detail

getWhereClause

public Expression getWhereClause()
Return the WHERE clause expression.

Returns:
The WHERE clause as an expression.

getHavingClause

public Expression getHavingClause()
Return the HAVING clause expression.

Returns:
The HAVING clause as an expression.

getOrderByComparator

public Comparator getOrderByComparator()
Return the Comparator we will use to do the ordering of the results, may be null.

Returns:
The Comparator.

getFunctionHandler

public FunctionHandler getFunctionHandler(String id)

getExecuteOnFunctions

public Map getExecuteOnFunctions()

setExecuteOnFunctions

public void setExecuteOnFunctions(Map ex)

getAnonymousBindVariableName

public String getAnonymousBindVariableName()

getDefaultFunctionHandlers

public List getDefaultFunctionHandlers()

getFunctionHandlers

public List getFunctionHandlers()

addFunctionHandler

public void addFunctionHandler(Object o)

setFrom

public void setFrom(Expression exp)

getFrom

public Expression getFrom()

setClassName

public void setClassName(String n)

setOrderByColumns

public void setOrderByColumns(List cols)

setGroupByLimit

public void setGroupByLimit(Limit g)

setGroupByOrderColumns

public void setGroupByOrderColumns(List cols)

getGroupByColumns

public List getGroupByColumns()

setGroupByColumns

public void setGroupByColumns(List cols)

getColumns

public List getColumns()

setColumns

public void setColumns(List cols)

setHaving

public void setHaving(Expression be)
Set the expression for the HAVING clause. Caution: do NOT use this method unless you are sure about what you are doing!

Parameters:
be - The expression.

setWhere

public void setWhere(Expression be)
Set the expression for the WHERE clause. Caution: do NOT use this method unless you are sure about what you are doing!

Parameters:
be - The expression.

setWantTimings

public void setWantTimings(boolean v)

addTiming

protected void addTiming(String id,
                         double time)

getVariable

public Object getVariable(int index)
Get the value of an indexed bind variable.

Parameters:
index - The index.
Returns:
The value.

getVariableClass

public Class getVariableClass(String name)
Get the class that the named variable has.

Parameters:
name - The name of the variable.
Returns:
The Class.

getGroupByVariable

public Object getGroupByVariable(int ind)
Get the value of a group by variable from the current group bys.

Parameters:
ind - The variable index.
Returns:
The value.

getVariable

public Object getVariable(String name)
Get the value of a named bind variable.

Parameters:
name - The name of the bind variable.
Returns:
The value.

setVariable

public void setVariable(String name,
                        Object v)
Set the value of a named bind variable.

Parameters:
name - The name.
v - The value.

setVariable

public void setVariable(int index,
                        Object v)
Set the value of an indexed bind variable.

Parameters:
index - The index.
v - The value.

getVariables

public Map getVariables()
Get all the bind variables as a Map.

Returns:
The name/value mappings of the bind variables.

isWhereTrue

public boolean isWhereTrue(Object o)
                    throws QueryExecutionException
A helper method that will evaluate the WHERE clause for the object passed in.

Parameters:
o - The object to evaluate the WHERE clause against.
Returns:
The result of calling: Expression.isTrue(Object,Query) for the WHERE clause.
Throws:
QueryExecutionException

setVariables

public void setVariables(Map bVars)
Set the bind variables in one go.

Parameters:
bVars - The bind variable name/value mappings.

doExecuteOn

public void doExecuteOn(List l,
                        String t)
                 throws QueryExecutionException
Execute all the expressions for the specified type, either: ALL or: RESULTS. If the expressions are aliased then the results will be available in the save results upon completion.

Parameters:
l - The List of objects to execute the functions on.
t - The type of expressions to execute.
Throws:
QueryExecutionException - If there is an issue with executing one of the expressions or if the Query hasn't been inited yet.

execute

public QueryResults execute(Iterator iter)
                     throws QueryExecutionException
Execute this query on the specified objects provided by the iterator. It should be noted that the iterator is first traversed and the objects it returns converted to a List and then passed to the execute(List) method for execution.

Parameters:
iter - The iterator to use to get the objects.
Returns:
The list of objects that match the query.
Throws:
QueryExecutionException - If the query cannot be executed.

execute

public QueryResults execute(Collection objs)
                     throws QueryExecutionException
Execute this query on the specified objects. It should be noted that the collection is first converted to a List and then passed to the execute(List) method for execution.

Parameters:
objs - The collection of objects to execute the query on.
Returns:
The list of objects that match the query.
Throws:
QueryExecutionException - If the query cannot be executed.

execute

public QueryResults execute(List objs)
                     throws QueryExecutionException
Execute this query on the specified objects.

Parameters:
objs - The list of objects to execute the query on.
Returns:
The list of objects that match the query.
Throws:
QueryExecutionException - If the query cannot be executed.

setCurrentGroupByObjects

public void setCurrentGroupByObjects(List objs)

getAllObjects

public List getAllObjects()
Get the current list of objects in context (value of the :_allobjs special bind variable). Note: the value of the :_allobjs bind variable will change depending upon where the query execution is up to.

Returns:
The list of objects in context.

setAllObjects

public void setAllObjects(List objs)

setCurrentObject

public void setCurrentObject(Object o)

getCurrentObject

public Object getCurrentObject()
Get the current object (value of the :_currobj special bind variable). Note: the value of the :_currobj bind variable will change depending upon where the query execution is up to.

Returns:
The current object in context.

setSaveValues

public void setSaveValues(Map s)

setSaveValue

public void setSaveValue(Object id,
                         Object value)

fireSaveValueChangedEvent

protected void fireSaveValueChangedEvent(Object id,
                                         Object from,
                                         Object to)

fireBindVariableChangedEvent

protected void fireBindVariableChangedEvent(String name,
                                            Object from,
                                            Object to)

getGroupBySaveValue

public Object getGroupBySaveValue(Object id,
                                  List gbs)
Get the save value for a particular key and group by list.

Parameters:
id - The id of the save value.
gbs - The group by list key.
Returns:
The object the key maps to.

getGroupBySaveValues

public Map getGroupBySaveValues(List gbs)
Get the save values for the specified group bys.

Parameters:
gbs - The group bys.
Returns:
The save values (name/value pairs).

getSaveValue

public Object getSaveValue(Object id)
Get the save values for a particular key.

Returns:
The object the key maps to.

getQuery

public String getQuery()
Get the query string that this Query object represents.

Returns:
The query string.

initOrderByComparator

public void initOrderByComparator()
                           throws QueryParseException
Will cause the order by comparator used to order the results to be initialized. This is generally only useful if you are specifying the the order bys yourself via: setOrderByColumns(List). Usage of this method is NOT supported, so don't use unless you really know what you are doing!

Throws:
QueryParseException

reorder

public QueryResults reorder(List objs,
                            SortedMap dirs)
                     throws QueryExecutionException,
                            QueryParseException
Re-order the objects according to the columns supplied in the dirs Map. The Map should be keyed on an Integer and map to a String value, the String value should be either: ORDER_BY_ASC for the column to be in ascending order or: ORDER_BY_DESC for the column to be in descending order. The Integer refers to a column in the SELECT part of the statement.

For example:

   SELECT name,
          directory,
          file
          length
   FROM   java.io.File
 
Can be (re)ordered via the following code:
   Query q = new Query ();
   q.parse (sql);
   
   Map reorderBys = new TreeMap ();
   reorderBys.put (new Integer (2), Query.ORDER_BY_ASC);
   reorderBys.put (new Integer (3), Query.ORDER_BY_DESC);
   reorderBys.put (new Integer (1), Query.ORDER_BY_ASC);
   reorderBys.put (new Integer (4), Query.ORDER_BY_DESC);

   // Note: this call will cause the entire statement to be executed.
   q.reorder (myFiles,
              reorderBys);
 

Parameters:
objs - The objects you wish to reorder.
dirs - The order bys.
Returns:
The QueryResults.
Throws:
QueryParseException - If the statement can be parsed, i.e. if any of the order by columns is out of range.
QueryExecutionException - If the call to: execute(List) fails.
See Also:
reorder(List,String)

reorder

public QueryResults reorder(List objs,
                            String orderBys)
                     throws QueryParseException,
                            QueryExecutionException
Allows the re-ordering of the results via a textual representation of the order bys. This is effectively like providing a new ORDER BY clause to the sql.

For example:

   SELECT name,
          directory,
          file
          length
   FROM   java.io.File
 
Can be (re)ordered via the following code:
   Query q = new Query ();
   q.parse (sql);
   
   // Note: this call will cause the entire statement to be executed.
   q.reorder (myFiles,
              "name DESC, 3 ASC, length, 1 DESC");
 

Parameters:
objs - The objects you wish to re-order.
orderBys - The order bys.
Returns:
The execution results.
Throws:
QueryParseException - If the statement can be parsed, i.e. if any of the order by columns is out of range or the order bys cannot be parsed.
QueryExecutionException - If the call to: execute(List) fails.
See Also:
reorder(List,SortedMap)

setClassLoader

public void setClassLoader(ClassLoader cl)

getClassLoader

public ClassLoader getClassLoader()

loadClass

public Class loadClass(String name)
                throws Exception
Throws:
Exception

parse

public void parse(String q)
           throws QueryParseException
Parse the JoSQL query.

Parameters:
q - The query string.
Throws:
QueryParseException - If the query cannot be parsed and/or inited.

init

public void init()
          throws QueryParseException
Throws:
QueryParseException

setFromObjectClass

public void setFromObjectClass(Class c)
Set the "FROM" object class. It is advised that you NEVER call this method, do so at your own risk, dragons will swoop from the sky and crisp your innards if you do so!!! Seriously though ;), this method should ONLY be called by those who know what they are doing, whatever you think you know about how this method operates is irrelevant which is why the dangers of calling this method are not documented...

YOU HAVE BEEN WARNED!!! NO BUGS WILL BE ACCEPTED THAT ARISE FROM THE CALLING OF THIS METHOD!!!

Parameters:
c - The FROM class.

getFromObjectClass

public Class getFromObjectClass()

removeBindVariableChangedListener

public void removeBindVariableChangedListener(BindVariableChangedListener bvl)

addBindVariableChangedListener

public void addBindVariableChangedListener(BindVariableChangedListener bvl)

removeSaveValueChangedListener

public void removeSaveValueChangedListener(SaveValueChangedListener svl)

addSaveValueChangedListener

public void addSaveValueChangedListener(SaveValueChangedListener svl)

getAliases

public Map getAliases()

isWantObjects

public boolean isWantObjects()
Return whether the query should return objects.

Returns:
true if the query should return objects.

setWantObjects

public void setWantObjects(boolean v)
Set whether the query should return objects (use true). Caution: Do NOT use unless you are sure about what you are doing!

Parameters:
v - Set to true to indicate that the query should return objects.

getWildcardCharacter

public char getWildcardCharacter()
Get the character that represents a wildcard in LIKE searches.

Returns:
The char.

setWildcardCharacter

public void setWildcardCharacter(char c)
Set the character that represents a wildcard in LIKE searches.

Parameters:
c - The char.

setLimit

public void setLimit(Limit l)
Set the object that represents the limit clause. Caution: Do NOT use unless you are sure about what you are doing!

Parameters:
l - The object.

getLimit

public Limit getLimit()
Get the object that represents the limit clause.

Returns:
The object.

parsed

public boolean parsed()
Return whether this Query object has had a statement applied to it and has been parsed.

Returns:
Whether the query is associated with a statement.

setWantDistinctResults

public void setWantDistinctResults(boolean v)
Indicate whether "distinct" results are required.

Parameters:
v - Set to true to make the results distinct.

getQueryResults

public QueryResults getQueryResults()
Get the results of executing this query.

Returns:
The query results.

getOrderByColumns

public List getOrderByColumns()
Get the "order bys". This will return a List of OrderBy objects. This is generally only useful when you want to reorder(List,String) the search and wish to get access to the textual representation of the order bys.

It is therefore possible to modify the orderbys in place, perhaps by using a different expression or changing the direction (since the objects are not cloned before being returned). However do so at YOUR OWN RISK. If you do so, then ensure you call: setOrderByColumns(List), then: initOrderByComparator() before re-executing the statement, otherwise nothing will happen!

Returns:
The order bys.

setParent

public void setParent(Query q)
Set the parent query. Caution: Do NOT use unless you are sure about what you are doing!

Parameters:
q - The parent query.

getParent

public Query getParent()
Get the parent query.

Returns:
The query, will be null if there is no parent.

getTopLevelQuery

public Query getTopLevelQuery()
Get the top level query if "this" is a sub-query, the query chain is traversed until the top level query is found, i.e. when getParent() returns null.

Returns:
The top level query, will be null if there is no parent.

toString

public String toString()
Get a string version of this query suitable for debugging. This will reconstruct the query based on the objects it holds that represent the various clauses.

Overrides:
toString in class Object
Returns:
The reconstructed query.

parseAndExec

public static QueryResults parseAndExec(String query,
                                        List objs)
                                 throws QueryParseException,
                                        QueryExecutionException
Throws:
QueryParseException
QueryExecutionException


  Copyright © 2008 Gary Bentley. All Rights Reserved.