SQLMethod.java

/***************************************************************************
   Copyright 2012 Emily Estes

   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 net.metanotion.sqlc;


import java.sql.Connection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import net.metanotion.functor.Block;

public final class SQLMethod implements Block<Iterable<Object>,Object> {
	public final String name;
	public final String[] pList;
	public final QueryExpr<? extends Object> body;
	public final Map<String,String> parameterTypes;
	public final String modifier;
	public final String finalType;

	/** Define a method to wrap a QueryExpr.
	@param name The name of the method.
	@param pList An array of the parameter names in order.
	@param body The QueryExpr representing the body of the function.
	@param parameterTypes A map whose keys are parameter names and values are the name of the parameter data type(Java types).
	@param modifier If null, the return type is finalType, other wise, it is modifer<finalType>. Currently acceptable
		values are java.util.Iterator, java.util.List.
	@param finalType  The (Java) return type of the method.
	*/
	public SQLMethod(final String name,
			final String[] pList,
			final QueryExpr<? extends Object> body,
			final Map<String,String> parameterTypes,
			final String modifier,
			final String finalType) {
		this.name = name;
		this.pList = pList;
		this.body = body;
		this.parameterTypes = parameterTypes;
		this.modifier = modifier;
		this.finalType = finalType;
	}

	@Override public Object eval(final Iterable<Object> params) throws Exception {
		final Iterator<Object> it = params.iterator();
		final Connection conn = (Connection) it.next();
		final HashMap<String,Object> env = new HashMap<String,Object>();
		for(final String param: pList) {
			env.put(param, it.next());
		}
		return body.eval(conn, env);
	}
}