/* 
 * © 2007-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */
#include "stdafx.h"

#include "db_sql_editor_be.h"
#include "recordset_be.h"
#include "recordset_cdbc_storage_be.h"


using namespace bec;
using namespace grt;


Db_sql_editor::Db_sql_editor(GRTManager *grtm)
:
_grtm(grtm)
{
  _stored_connection= db_mgmt_ConnectionRef::cast_from(_grtm->get_grt()->get("/wb/rdbmsMgmt/storedConns/0"));//!
}


Db_sql_editor::~Db_sql_editor()
{
  reset();
}


void Db_sql_editor::stored_connection(db_mgmt_ConnectionRef val)
{
  _stored_connection= val;
}


db_mgmt_ConnectionRef Db_sql_editor::stored_connection()
{
  return _stored_connection;
}


db_mgmt_RdbmsRef Db_sql_editor::rdbms()
{
  return db_mgmt_RdbmsRef::cast_from(stored_connection()->driver()->owner());
}


Sql_editor * Db_sql_editor::sql_editor()
{
  if (!_sql_editor.get())
    _sql_editor= Sql_editor::create_sql_editor(rdbms());
  return _sql_editor.get();
}


void Db_sql_editor::reset()
{
  for (size_t n= 0, count= _recordsets.size(); n < count; ++n)
    delete _recordsets[n];
  _recordsets.clear();
}


int Db_sql_editor::recordset_count()
{
  return _recordsets.size();
}


Recordset * Db_sql_editor::recordset(int index)
{
  return _recordsets.at(index);
}


void Db_sql_editor::connect()
{
  sql::DriverManager *dbc_drv_man= sql::DriverManager::getDriverManager();
  _dbc_conn= dbc_drv_man->getConnection(stored_connection());
}


void Db_sql_editor::exec_sql(const std::string &sql)
{
  reset();

  if (!_dbc_conn.get())
    connect();

  std::auto_ptr<sql::Statement> dbc_statement(_dbc_conn->createStatement());
  //dbc_statement->setFetchSize(100); //! setFetchSize is not implemented. param value to be customized.
  std::auto_ptr<sql::ResultSet> dbc_rs(dbc_statement->executeQuery(sql));

  std::auto_ptr<Recordset> rs(new Recordset());
  Recordset_cdbc_storage data_storage(_grtm);
  data_storage.dbc_rs(dbc_rs.get());
  rs->reset(&data_storage);
  _recordsets.push_back(rs.get());
  rs.release();
}
