
#include "stdafx.h"

#include "connection_helpers.h"

#define VERBOSE_TESTING 0

using namespace std;

BEGIN_TEST_DATA_CLASS(module_dbc_general_test)
public:
  GRT grt;
END_TEST_DATA_CLASS

TEST_MODULE(module_dbc_general_test, "DBC: general tests");

TEST_FUNCTION(1)
{
  // load structs
  grt.scan_metaclasses_in("../../res/grt/");
  grt.end_loading_metaclasses();

  ensure_equals("load structs", grt.get_metaclasses().size(), 142);
}

TEST_FUNCTION(2)
{
  db_mgmt_ConnectionRef connectionProperties(&grt);

  setup_env(&grt, connectionProperties);

  sql::DriverManager *dm= sql::DriverManager::getDriverManager();
  std::auto_ptr<sql::Connection> conn= dm->getConnection(connectionProperties);
  sql::DatabaseMetaData *meta(conn->getMetaData());
  std::auto_ptr<sql::ResultSet> rset(meta->getSchemata());

  while (rset->next())
  {
#if VERBOSE_TESTING
    std::cout << rset->getString("schema_name") << std::endl;
    std::cout << "  Schema Objects:" << std::endl;

#endif
    
    std::auto_ptr<sql::ResultSet> rset2(meta->getSchemaObjects("", rset->getString("schema_name")));
    while (rset2->next())
    {
#if VERBOSE_TESTING
      std::cout << rset2->getString("object_type") << ": " << rset2->getString("name") << "," << 
        rset2->getString("ddl") << std::endl;
#endif
    }
  }
}

TEST_FUNCTION(3)
{
  db_mgmt_ConnectionRef connectionProperties(&grt);

  setup_env(&grt, connectionProperties);

  sql::DriverManager *dm= sql::DriverManager::getDriverManager();
  std::auto_ptr<sql::Connection> conn= dm->getConnection(connectionProperties);

  std::auto_ptr<sql::Statement> stmt(conn->createStatement());

  stmt->execute("DROP TABLE IF EXISTS test.product");
  stmt->execute("CREATE TABLE test.product(idproduct INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(80))");

  conn->setAutoCommit(0);

#if VERBOSE_TESTING
  std::cout << "Insert Data." << std:endl;
#endif

  std::auto_ptr<sql::PreparedStatement> prepStmt(conn->prepareStatement("INSERT INTO test.product(idproduct, name)  VALUES(?, ?)"));
  prepStmt->setInt(1, 1);
  prepStmt->setString(2, "Harry Potter");
  prepStmt->executeUpdate();

#if VERBOSE_TESTING
  std::cout << "Display Data." << std::endl;
#endif

  std::auto_ptr<sql::ResultSet> rset1(stmt->executeQuery("SELECT * FROM test.product"));

  int i = 0;
  while (rset1->next())
  {
#if VERBOSE_TESTING
    std::cout << rset1->getString(2) << ", " << rset1->getString("name") << std::endl;
#endif
    i++;
  }
#if VERBOSE_TESTING
  printf("%d row(s)", i);

  printf("Rollback");
#endif

  conn->rollback();

#if VERBOSE_TESTING
  printf("Display Data Again.\n");
#endif
  std::auto_ptr<sql::ResultSet> rset2(stmt->executeQuery("SELECT * FROM test.product"));

  i = 0;
  while (rset2->next())
  {
#if VERBOSE_TESTING
    std::cout << rset2->getString(2) << ", " << rset2->getString("name") << std::endl;
#endif
    i++;
  }
#if VERBOSE_TESTING
  std::cout << i << " row(s)" << std::endl;
#endif
}

END_TESTS
