package net.sourceforge.javautil.database.query.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import net.sourceforge.javautil.common.exception.ThrowableManagerRegistry;
import net.sourceforge.javautil.database.query.IQueryExecutor;
import net.sourceforge.javautil.database.query.IQueryFragmentCriteriaParameter;
import net.sourceforge.javautil.database.query.QuerySnapshot;
/**
* This will execute queryies built by a {@link QueryBuilderSelectSQL}.
*
* @author elponderador
* @author $Author: ponderator $
* @version $Id: QueryExecutorSQL.java 2479 2010-10-25 03:47:57Z ponderator $
*/
public class QueryExecutorSQL implements IQueryExecutor<QueryBuilderSelectSQL, List<Map>> {
protected final DataSource dataSource;
public QueryExecutorSQL(DataSource dataSource) {
this.dataSource = dataSource;
}
public List<Map> execute(QueryBuilderSelectSQL builder) {
Connection connection = null;
Statement statement = null;
ResultSet set = null;
try {
connection = dataSource.getConnection();
QuerySnapshot snapshot = builder.build();
if (builder.getParameters().size() > 0) {
PreparedStatement prepared = connection.prepareStatement(snapshot.getQueryString());
int index = 1;
for (IQueryFragmentCriteriaParameter parameter : snapshot.getArguments()) {
for (String name : parameter.getNamedParameters()) {
prepared.setObject(index++, builder.getParameters().get(name));
}
}
return translate( prepared.executeQuery() );
} else {
statement = connection.createStatement();
return translate( statement.executeQuery( snapshot.getQueryString() ) );
}
} catch (SQLException e) {
throw ThrowableManagerRegistry.caught(e);
} finally {
if (set != null) try { set.close(); } catch (SQLException e) {
ThrowableManagerRegistry.caught(e);
}
if (statement != null) try { statement.close(); } catch (SQLException e) {
ThrowableManagerRegistry.caught(e);
}
if (connection != null) try { connection.close(); } catch (SQLException e) {
ThrowableManagerRegistry.caught(e);
}
}
}
protected List<Map> translate (ResultSet set) throws SQLException {
List<Map> records = new ArrayList<Map>();
ResultSetMetaData meta = set.getMetaData();
set.beforeFirst();
while (set.next()) {
Map<String, Object> row = new LinkedHashMap<String, Object>();
for (int i=1; i<=meta.getColumnCount(); i++) {
row.put(meta.getColumnName(i), set.getObject(i));
}
records.add(row);
}
return records;
}
}