package com.fuse.projects.fuse_light.examples;

/*
	FUSE Light Server - multiuser server application
	Copyright (C) 2000 Aapo Kyrola / Sulake Oy  Helsinki, Finland

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

import java.util.*;
import java.io.*;
import java.sql.*;

import com.fuse.*;
import com.fuse.net.*;
import com.fuse.storage.sql.*;


/**
  * ExampleSQLQuery performs any sql-query and returns results as a 
  * vector of vectors. This shows how one can implement new
  * database queries with FUSE Light by just making new
  * SQLObjectQueryBeans.
  * @see com.fuse.projects.fuse_light.examples.ExampleConnection
  * @see com.fuse.storage.sql.SQLDatabaseImpl
  * @author Aapo Kyrola
  */
  

public class ExampleSQLQuery implements SQLObjectQueryBean {
	String query;
	
	ExampleSQLQuery(String query) {
		this.query = query;
	}
	
	/**
	  * Called by SQLDatabaseImpl.query()
	  */
	public Vector execute(Connection connection) {
		Statement stmt = null;
		ResultSet rset = null;
		try {
			stmt = connection.createStatement();
			rset = stmt.executeQuery(query);
			
			Vector results = new Vector();
			/* Go through results */
			int columnCount = rset.getMetaData().getColumnCount();
			while (rset.next() == true) {
				Vector row = new Vector(columnCount);
				for(int j=1; j<=columnCount; j++) {
					row.addElement(rset.getObject(j));
				}
				results.addElement(row);
			}	
			return results;
		} catch (Exception e) {
			Log.error(e);
			return null;
		} finally {
			/* Remember always to close statement and resultset */
			try { if (stmt != null) stmt.close(); } catch (Exception e) {;}
			try { if (rset != null) rset.close(); } catch (Exception e) {;}
		}
	}	
}
