package org.seamframework.sql;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

public class ExecutableQuery extends ExecutableStatement {

	final List<Expression<?>> selections;
	
	public ExecutableQuery(Query query, Session session) {
		super(query, session);
		selections = query.getSelections();
	}
	
	public ExecutableQuery(String query, Session session) {
		super(query, session);
		selections = null;
	}
	
	@Override
	public <T> ExecutableQuery set(Parameter<T> param, T value) {
		super.set(param, value);
		return this;
	}
	
	@Override
	public <T> ExecutableQuery set(int index, T value, Type<T> type) {
		super.set(index, value, type);
		return this;
	}
	
	public Iterable<Tuple> result() {
		try {
			PreparedStatement ps = getPreparedStatement();
			int columns = selections==null ?
				ps.getMetaData().getColumnCount() : selections.size();
			
			return new Result( ps.executeQuery(), columns, selections );
		}
		catch (SQLException sqle) {
			throw new RuntimeException(sqle);
		}
	}
	
}
