/*
      _______                          .__ .__   .__   .__                 
      \      \    ____   __ __ _______ |__||  |  |  |  |__|  ____    ____  
      /   |   \ _/ __ \ |  |  \\_  __ \|  ||  |  |  |  |  | /  _ \  /    \ 
     /    |    \\  ___/ |  |  / |  | \/|  ||  |__|  |__|  |(  <_> )|   |  \
     \____|__  / \___  >|____/  |__|   |__||____/|____/|__| \____/ |___|  /
    =========\/======\/=================================================\/==
  v0.01 04/JUL/2007 © Copyright 2007-2007 Scott D. Yelich SOME RIGHTS RESERVED
 .,-*~'`^`'~*-,._.,-*~'`^`'~*-,._.,-*~'`^`'~*-,._.-*~'`^`'~*-,._.,-*~'`^`'~*-,. 


  LICENSE:  Creative Commons Attribution 3.0 License.
  SEE:      http://creativecommons.org/licenses/by/3.0/


  Sun Jul 29 21:33:38 EDT 2007, v0.02 sdy

  This is a *very* simple program written to do a web page
  hit counter using sqlite3.

*/

//  LOCAL

#include "Xql3.h"

Xql3::Xql3()
{
}

Xql3::~Xql3()
{
  Xql3::close();
}

int
Xql3::open(std::string const & name)
{
  _dbname = name.c_str();
  int rc = sqlite3_open(_dbname, &_db);
  if (rc) {
    //  sqlite3_errmsg(_db)
    Xql3::close();
    exit(1);
  }
  return rc;
}

int
Xql3::close()
{
  int rc=0;
  if (_db) {
    rc=sqlite3_close(_db);
  }
  return rc;
}


int
Xql3::exec(std::string const & sql_text)
{
  int rc = sqlite3_get_table(
    _db,               /* An open database */
    sql_text.c_str(),  /* SQL to be executed */
    &_result,          /* Result written to a char *[]  that this points to */
    &_rows,            /* Number of result rows written here */
    &_cols,            /* Number of result columns written here */
    &_errm             /* Error msg written here */
  );
  _headers.clear();
  _data.clear();
  if (SQLITE_OK != rc) {
    //  std::cout << "NOT ok=(" << rc << ") = (" << errm << ") sql=(" << sql_text << ")\n";
  } else {
    for (int i=0; i<_cols; ++i) {
      _headers.push_back(_result[i]);
    }
    for(int i=0; i<_cols*_rows; ++i) {
      _data.push_back(_result[_cols+i]);  //  _cols+ --> to skip headers
    }
  }
  sqlite3_free_table(_result);
  return rc;
}

std::vector<std::string> &
Xql3::headers()
{
  return _headers;
}

std::vector<std::string> &
Xql3::data()
{
  return _data;
}
