package relational;

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

/**
 * Test for membership of a field in the list of entries (ResultSet) of
 * a subquery. Like SQL's <pre>SELECT ... WHERE X IN (SELECT ...)</pre>
 *
 * @classConcise true
 */
public class WhereIn
	extends Where {
	FieldDescriptor fd;
	Select subquery;

	public WhereIn() {
	}

	public WhereIn(FieldDescriptor fd, Select subquery) {
		this.fd = fd;
		this.subquery = subquery;
	}

	public Select getQuery() { return subquery; }
	public FieldDescriptor getFieldDescriptor() { return fd; }

	public boolean includes(Row ro, Database db) {
		// ro should have an 'f', and subquery should hasMember(f.get(ro))
		// TODO debug
		ResultSetNarrow rs = (ResultSetNarrow) subquery.evaluate(db);
		return rs.hasSingleton(fd.get(ro));
	}

	public String toString() {
		return "("+fd+" IN "+subquery+")";
	}

	public String indentedString(int d) {
		return "IN "+fd+"\n"
			+Text.indent(d, subquery.toString());
	}

	public String getShortName() { return "IN"; }

	public int getChildCount() {
		return 1;
	}

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

	public void setChild(int index, Object child) {
		if (index==0) {
			subquery = (Select) child;
		} else {
			throw new IllegalArgumentException(getClass()+" has only 1 child");
		}
	}
}
