/* * dbObject.cc * * Created on: July 27, 2014 * Author: Hovanes Egiyan */ #include "dbObject.hh" //QSqlDatabase dbObject::db; // Static variable for accessing databases dbObject::dbObject( string uri ) : dbURI(uri) { db = openDB( uri ); } dbObject::~dbObject() { // db.close(); } QSqlDatabase dbObject::openDB(string uri) { // Parse the URI string::size_type pos = uri.find("://"); string protocol = uri.substr(0, pos); transform(protocol.begin(), protocol.end(), protocol.begin(), ::tolower); string resource = uri.substr(pos + 3); // qDebug() << "uri = " << uri.c_str() << " protocol = " << protocol.c_str() // << " resource = " << resource.c_str() << endl; QSqlDatabase newDB; // Open appropriate DB if the connection does not already exist if (protocol.compare("sqlite") == 0) { // cout << "The DB protocol is SQLite - " << protocol << endl; if ( QSqlDatabase::contains(resource.c_str()) ) { // cout << "There was an existing DB " << resource << endl; newDB = QSqlDatabase::database(resource.c_str()); if (!newDB.isOpen()) { cout << "The existing DB " << resource << " was not open, will open." ; if (!newDB.open()) { cerr << "Can't open existing database: " << uri << endl; cerr << newDB.lastError().text().toStdString() << endl; exit(1); } } } else { cout << "There was no existing DB " << resource << endl; newDB = QSqlDatabase::addDatabase("QSQLITE", resource.c_str()); newDB.setDatabaseName(resource.c_str()); if (!newDB.open()) { cerr << "Can't open database: " << uri << endl; cerr << newDB.lastError().text().toStdString() << endl; exit(1); } } } else if (protocol.compare("mysql") == 0) { cout << "The DB protocol is MySQL - " << protocol << endl; // Still need to implement MySQL part } else { cerr << "Unsupported DB protocol - " << protocol << endl; exit(1); // FIXME::Might be a status should be risen and program should continue without this part } return newDB; } // Checks if a DB is open. If not, throws an exception. Returns otherwise void dbObject::checkDB() { // When reached the end of the branch find the crate corresponding to this leaf if( ! db.isOpen() ) { // Raise an exception if the DB has not been opened first stringstream errMsg; errMsg << "Error: Database has not been opened. Use dbSubsystem::OpenDB first!" ; qWarning() << errMsg.str().c_str() << endl; throw StringException(errMsg.str()); } return; } int dbObject::sqlSize(QSqlQuery& query) { int initialPos = query.at(); // Very strange but for no records .at() returns -2 int pos = 0; if (query.last()) pos = query.at() + 1; else pos = 0; // Important to restore initial pos query.seek(initialPos); return pos; }