package relational;

import java.util.Hashtable;
import java.util.Vector;
import java.lang.reflect.Field;
import Tools.Text;

/**
 * Used for literal comparisons like (WHERE field = 'foo').
 *
 * @classConcise true
 */
// TODO this is a big sleazy hack because it works only through
// boundConstant(); if the query isn't set up just right, you might
// fall through to the naive case, which won't be able to "guess"
// the right pseudorows that would be accepted by my includes() function.
// Need virtual tables? Need to separate FromClause's from Class'es?
public class WhereConstant
	extends Where {

	String tableName;
	Relational constant;
	FromClause pseudoFromClause;
		// "pseudo" because the constant is not really from that table,
		// it's supplied here in the query itself.

	public WhereConstant(String tableName, Relational constant) {
		this.tableName = tableName;
		this.constant = constant;

		pseudoFromClause = FromClause.create(tableName, constant.getClass());

		// this constant shouldn't be turning up in any indices or
		// objectLists, so it shouldn't hurt to mark it valid. If we
		// don't, it gets filtered out at the end of the select.
		constant.valid = true;
	}

	public boolean includes(Row ro, Database db) {
		FromClause fc = ro.getFromClause();
		int index = fc.getIndex(tableName);
		if (index<0) {
			return false;
		}
		Relational o = ro.getTable(fc, index);
		return constant.equals(o);
	}

	public String toString() {
		return "("+tableName+" =C "+constant.toString()+")";
	}

	public String indentedString(int d) {
		return Text.indent(d)+"Constant "+tableName+" = "+constant.toString();
	}

	public int getChildCount() {
		return 2;
	}

	public Object getChild(int index) {
		if (index==0) {
			return tableName;
		} else if (index==1) {
			return constant;
		} else {
			throw new IllegalArgumentException(getClass()+" has only 2 children");
		}
	}

	public void setChild(int index, Object child) {
		if (index==0) {
			tableName = (String) child;
		} else if (index==1) {
			constant = (Relational) child;
		} else {
			throw new IllegalArgumentException(getClass()+"has only 2 children");
		}
	}

	public String getShortName() { return " =C "; }
}
