00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00030 #include <iostream>
00031 #include <utility>
00032 #include <QSqlQuery>
00033 #include <QVariant>
00034 #include "database.h"
00035 using std::cerr;
00036 using std::make_pair;
00037
00038
00039 #include "profiling.h"
00040
00041 PROF_DECLARE(TABLE_POPULATE);
00042
00043 namespace db_planner {
00044
00046
00047 bool Table::Populate(QSqlQuery query) {
00048 PROF_TIMER_FUNC(TABLE_POPULATE);
00049 data_.clear();
00050 column_names_.clear();
00051 if (query.next()) {
00052 QSqlRecord first_record = query.record();
00053 num_columns_ = first_record.count();
00054 data_.resize(num_columns_, vector<QVariant>(query.numRowsAffected()));
00055 for (int i = 0; i < num_columns_; ++i) {
00056 column_names_.insert(make_pair(first_record.fieldName(i).toStdString(), i));
00057
00058 }
00059 do {
00060 for (int i = 0; i < num_columns_; ++i)
00061 data_[i].push_back(query.value(i));
00062 } while(query.next());
00063 if (!data_.empty()) num_rows_ = data_[0].size();
00064 return true;
00065 }
00066 return false;
00067 }
00068
00070
00072 DatabaseConnection::DatabaseConnection(const string& host_name,
00073 const int port,
00074 const string& user_name,
00075 const string& password,
00076 const string& database_name,
00077 const string& connection_type)
00078 : db_(QSqlDatabase::addDatabase(QString(connection_type.c_str()),
00079 QString::number(++connection_num_))) {
00080 db_.setHostName(QString(host_name.c_str()));
00081 db_.setPort(port);
00082 db_.setUserName(QString(user_name.c_str()));
00083 db_.setPassword(QString(password.c_str()));
00084 db_.setDatabaseName(QString(database_name.c_str()));
00085 if (!db_.open()) {
00086 cerr << "Database " << database_name << "@" << host_name
00087 << ":" << port << " could not be opened.\n";
00088 cerr << "Error: " << db_.lastError().text().latin1() << std::endl;
00089 connected_ = false;
00090 } else {
00091 cerr << "Database successfully opened.\n";
00092 connected_ = true;
00093 }
00094 }
00095
00097
00098 bool DatabaseConnection::Query(const string& sql, Table* table) const {
00099
00100 QSqlQuery query(db_);
00101 query.setForwardOnly(true);
00102 if (!query.exec(sql.c_str())) {
00103 std::cerr << "SQL Query failure on query: " << sql << std::endl;
00104 std::cerr << "Error: " << query.lastError().text().latin1() << std::endl;
00105 return false;
00106 } else {
00107 if (table) {
00108 if (!table->Populate(query)) {
00109
00110 return false;
00111 }
00112 }
00113 return true;
00114 }
00115
00116
00117
00118 }
00119
00120
00121 int DatabaseConnection::connection_num_ = 0;
00122
00123 }
00124
00125