ExpressionOr.java

package org.microspace.table.query.sql;

import org.microspace.table.Entry;
import org.microspace.table.column.Accessor;
import org.microspace.table.column.ColumnReferences;
import org.microspace.table.column.IndexedMap;
import org.microspace.table.query.SqlFormat;

/**
 *
 * @author Gaspar Sinai - {@literal gaspar.sinai@microspace.org}
 * @version 2017-09-29
 * @param <T> The type of the Table.
 */
public class ExpressionOr<T> implements Expression<T> {
	
	private static final long serialVersionUID = -1435528585171213537L;
	
	Expression<T> left;
	Expression<T> right;
	boolean needsBracket = false;
	
	public void setNeedsBracket (boolean needsBracket) {
		this.needsBracket = needsBracket;
	}

	public ExpressionOr (Expression<T> left, Expression<T> right) {
		this.left = left;
		this.right = right;
	}
	
	public IndexedMap<Object, Entry<T>> apply (Accessor<T> accessor, IndexedMap<Object, 
			Entry<T>> entries,
			ColumnReferences<T>[] indexedColumns, InnerSelectContext<?> innerSelectContext) {
		IndexedMap<Object, Entry<T>> lmap = left.apply(accessor, entries, indexedColumns, innerSelectContext);
		IndexedMap<Object, Entry<T>> result = right.apply(accessor, entries, indexedColumns, innerSelectContext);
		result.putAll (lmap);
		return result;
	}
	
	public boolean match(T object, Accessor<T> accessor) {
		return left.match(object, accessor) 
				|| right.match(object, accessor);
	}
	
	@Override
	public String formatSqlQuery (SqlFormat format) {
		String leftBracket = needsBracket ? "( " : "";
		String rightBracket = needsBracket ? " )" : "";
		return leftBracket + left.formatSqlQuery(format) 
		   + " OR " + right.formatSqlQuery(format) + rightBracket;
	}

}