/**
* Copyright 1999-2009 The Pegadi Team
*
* 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.
*/
package org.pegadi.sqlsearch;
import java.util.*;
import static org.apache.commons.lang.StringUtils.isNotBlank;
/**
* This is an abstract class representing a search-term.
* Search criteria are represented as a tree of seach-terms, forming a
* parse-tree used to generate the SQL query that returns the matching
* Articles.
* <p/>
* SearchTerms are represented by this class. This is an abstract class:
* subclasses implement specific math methods.
*
* @author Eirik Bjorsnos <bjorsnos@underdusken.no>
* @version $Revision$, $Date$
*/
public abstract class SearchTerm implements java.io.Serializable {
private boolean selectDistinct = false;
private String orderBy;
/**
* Generates the WHERE part of the SQL query (without including the string
* "WHERE").
*
* @return the WHERE clause
*/
public abstract String whereClause();
/**
* Returns the names of the tables involved in this search.
*
* @return A String[] containing the involved tables. The array may contain
* multiple instances of each table name.
*/
public abstract List<String> getTables();
/**
* Returns the names of tables that should be ignored
*/
public List<String> getIgnoreTables() {
return Collections.emptyList();
}
/**
* Returns the SQL query for this SearchTerm
*
* @param selectString the part following SELECT (what to select)
* @return the SQL query
*/
public String getQuery(String selectString) {
StringBuilder query = new StringBuilder();
query.append("SELECT ");
if (selectDistinct) {
query.append("distinct ");
}
query.append(selectString);
query.append(" FROM ");
Set<String> tables = new LinkedHashSet<String>(getTables());
Collection<String> ignoreTables = getIgnoreTables();
tables.removeAll(ignoreTables);
for (Iterator<String> iterator = tables.iterator(); iterator.hasNext(); ) {
String table = iterator.next();
query.append(table);
if(iterator.hasNext()){
query.append(", ");
}
}
query.append(" WHERE ");
query.append(whereClause());
if(isNotBlank(orderBy)){
query.append(" ORDER BY ");
query.append(orderBy);
}
return query.toString();
}
public void setSelectDistinct(boolean selectDistinct) {
this.selectDistinct = selectDistinct;
}
public String getOrderBy() {
return orderBy;
}
public void setOrderBy(String orderBy) {
this.orderBy = orderBy;
}
}