FB::AutoPtr<CursorSync> IndexSync::openCursor(const optional<KeyRange>& range, const Cursor::Direction direction, const bool dataArePrimaryKeys) { try { FB::AutoPtr<CursorSync> cursor = new CursorSync(host, *this, transactionFactory, range, direction, dataArePrimaryKeys); openCursors.add(cursor); return cursor; } catch(ImplementationException& e) { throw DatabaseException(e); } }
void Statement::AssignNextParameter(ParamBuffer *buffer) { if (buffer == NULL) { throw DatabaseException("Error in Statement::AssignNextParameter", 0, "----", "Buffer cannot be null"); } unsigned int pos = _params.size(); if (pos >= ParameterCount()) { delete buffer; throw DatabaseException("Error in Statement::AssignNextParameter", 0, "----", "Have already assigned all possible input parameters"); } _params.push_back(buffer); _bind[pos].buffer_type = buffer->BufferType(); _bind[pos].buffer = buffer->Buffer(); _bind[pos].buffer_length = buffer->BufferSize(); _bind[pos].is_null = buffer->IsNull(); _bind[pos].length = buffer->BufferLength(); _bind[pos].is_unsigned = buffer->IsUnsigned(); }
void Sqlite3Database::addTag(const bigint_t note_id, const bigint_t tag_id) { clearStatement(); stmt_cache_ << "INSERT INTO tags_nm VALUES(" << std::to_string(tag_id) << ", " << std::to_string(note_id) << ")"; auto result = prepareStatement(stmt_cache_.str()); if (isError(executeStep(result))) throw DatabaseException("adding tag " + std::to_string(tag_id) + " to " + std::to_string(note_id) + " failed"); }
Database::Statement::type_t Database::Statement::type(int column) const { switch(sqlite3_column_type(mStmt, column)) { case SQLITE_INTEGER: return Integer; case SQLITE_FLOAT: return Float; case SQLITE_TEXT: return Text; case SQLITE_BLOB: return Blob; case SQLITE_NULL: return Null; default: throw DatabaseException(mDb, "Unable to retrieve column type"); } }
//Delete a whole table from the database int Database::drop(string tableName) { if(debug) cout<<"input is:\n"<<tableName<<endl; if (findTable(tableName) == NULL) { throw DatabaseException(10, tableName + " does not exist."); } map<string, Table*>::iterator it = tableList.find(tableName); tableList.erase(it); return 0; }
/* * returns 1 if table is succesfully deleted */ int Database::deleteTable(string tableName) { if (findTable(tableName) == NULL) { throw DatabaseException(10, tableName + " does not exist."); } drop(tableName); if (tableList[tableName] != NULL) { cout << "REMOVING " << tableName << endl; tableList[tableName] = NULL; } return 1; }
void Sqlite3Database::deleteNotebook(const bigint_t notebook_id) { clearStatement(); stmt_cache_ << "DELETE FROM notebooks WHERE id=" << std::to_string(notebook_id); auto result = prepareStatement(stmt_cache_.str()); if (isError(executeStep(result))) throw DatabaseException("deleting notebook failed: " + std::to_string(notebook_id)); }
void Statement::GetDataInRow(unsigned int column, Nullable<Julian> &result) { if (column >= _resultParams.size()) { throw DatabaseException("Error in Statement::GetDataInRow", 0, "----", "column out of range"); } if ((_resultBind[column].buffer_type != MYSQL_TYPE_TIMESTAMP) && (_resultBind[column].buffer_type != MYSQL_TYPE_DATE) && (_resultBind[column].buffer_type != MYSQL_TYPE_TIME) && (_resultBind[column].buffer_type != MYSQL_TYPE_DATETIME)) { throw DatabaseException("Error in Statement::GetDataInRow", 0, "----", "column not of correct type"); } MYSQL_TIME time; if (! (*(_resultParams[column]->IsNull()))) { time = *((MYSQL_TIME *) _resultParams[column]->Buffer()); GregorianBreakdown gb(time, 0); result = Julian(gb); } else { result.ClearValue(); } }
QSqlQuery Database::query(string q) { QSqlQuery query; if(!query.exec(QString(q.c_str()))) { QString e=QString("Erreur lors de l'exécution de la requête "); e+=QString(q.c_str()); e+=" Erreur : "+query.lastError().databaseText(); throw DatabaseException(e.toStdString()); } return query; }
void Sqlite3Database::renameNotebook(const bigint_t notebook_id, const std::string &new_title) { clearStatement(); stmt_cache_ << "UPDATE notebooks SET title='" << new_title << "' WHERE id=" << notebook_id; auto result = prepareStatement(stmt_cache_.str()); if (isError(executeStep(result))) throw DatabaseException("updating notebook title for notebook " + new_title); }
Database::Database(const String &filename) : mDb(NULL) { Assert(sqlite3_threadsafe()); if(sqlite3_open(filename.c_str(), &mDb) != SQLITE_OK) throw DatabaseException(mDb, String("Unable to open database file \"")+filename+"\""); // TODO: close ? execute("PRAGMA synchronous = OFF"); execute("PRAGMA journal_mode = TRUNCATE"); execute("PRAGMA case_sensitive_like = 1"); }
int DBConn::execute(const char *sql, DBDataSet *ds /* = NULL */, bool retryQueryOnFail /* = true */) { assert(sql && *sql); assert(isOpened()); { bool failure; if ((failure = mysql_query(m_conn, sql))) { if (retryQueryOnFail) { for (int count = 0; count < m_maxRetryOpenOnFail; count++) { open(m_server, m_connectTimeout, m_readTimeout); failure = mysql_query(m_conn, sql); if (!failure) break; } } if (failure) { int code = mysql_errno(m_conn); throw DatabaseException(code, "Failed to execute SQL '%s': %s (%d)", sql, mysql_error(m_conn), code); } } } MYSQL_RES *result = mysql_store_result(m_conn); if (!result) { int code = mysql_errno(m_conn); if (code) { throw DatabaseException(code, "Failed to execute SQL '%s': %s (%d)", sql, mysql_error(m_conn), code); } } int affected = mysql_affected_rows(m_conn); if (ds) { ds->addResult(m_conn, result); } else { mysql_free_result(result); } return affected; }
bool Database::Statement::step(void) { int status = sqlite3_step(mStmt); if(status != SQLITE_DONE && status != SQLITE_ROW) throw DatabaseException(mDb, "Statement execution failed"); mInputColumn = 0; mOutputParameter = 1; mInputLevel = 0; mOutputLevel = 0; return (status == SQLITE_ROW); }
void BR::Database::load(std::string filename) { this->filename = filename; size_t dir_pos = filename.find_last_of("\\/"); std::string filename_prefix = dir_pos == std::string::npos ? "" : filename.substr(0, dir_pos + 1); std::string book_image_filename; std::string book_info_filename; TiXmlDocument document(filename.c_str()); if (!document.LoadFile()) { throw DatabaseException("unable to load file: " + filename); } //get books TiXmlElement * element = document.RootElement()->FirstChildElement("book"); do { Book * book = new Book(); //read XML TiXmlElement * child = element->FirstChildElement("isbn"); ASSERT_NOTNULL(child, "Unknown file stucture. No ISBN Element."); book->isbn = child->GetText(); child = child->NextSiblingElement("title"); ASSERT_NOTNULL(child, "Unknown file stucture. No title element."); book->title = child->GetText(); child = child->NextSiblingElement("author"); ASSERT_NOTNULL(child, "Unknown file stucture. No author element."); book->author = child->GetText(); child = child->NextSiblingElement("image_filename"); ASSERT_NOTNULL(child, "Unknown file stucture. No image filename."); book_image_filename = filename_prefix + child->GetText(); child = child->NextSiblingElement("image_info_filename"); ASSERT_NOTNULL(child, "Unknown file stucture. No image info filename."); book_info_filename = filename_prefix + child->GetText(); //load structures cv::FileStorage fs(book_info_filename, cv::FileStorage::READ); cv::read(fs["keypoints"], book->keypoints); fs["descriptors"] >> book->descriptors; fs.release(); //load image book->image = cv::imread(book_image_filename); books.push_back(book); } while( (element = element->NextSiblingElement("book")) != NULL); }
//Column constructor- checks validity of type given Column::Column(string type) { varcharMaxLength = 100; isPrimary = false; if (type == "int" || type == "float" || type == "date" || type == "time") { colType = type; } else { string number = ""; int newLength; colType = "varchar"; for (int i = 0; i < type.length(); i++) { if (type[i] == '(') { i++; while (type[i] != ')') { number += type[i]; i++; } break; } } //Make sure the varchar length is valid if ((number.size() > 0) && (type.compare(0, 7, "varchar") == 0)) { newLength = atoi(number.c_str()); if (newLength <= 0) { throw DatabaseException(31); } else if (newLength > varcharMaxLength) { throw DatabaseException(32); } else { varcharMaxLength = newLength; } } else { cout << "COLUMN TYPE IS " << type << endl; throw DatabaseException(30); } } }
void Transaction::open() { if(transactionsDisabled) return; if(QSqlDatabase::database().transaction() == false) { QString error = QString("SQL transaction open has failed!\n" "\t* Error text: %1\n") .arg(QSqlDatabase::database().lastError().text()); throw DatabaseException(error); } opened = true; }
void Database::ResetPassword() { stringstream ss; ss << "REPLACE INTO credentials VALUES (\"nova\", \"934c96e6b77e5b52c121c2a9d9fa7de3fbf9678d\", \"root\")"; char *zErrMsg = 0; int state = sqlite3_exec(db, ss.str().c_str(), callback, 0, &zErrMsg); if (state != SQLITE_OK) { string errorMessage(zErrMsg); sqlite3_free(zErrMsg); throw DatabaseException(string(errorMessage)); } }
// implementation of NotebookDatabase interface std::vector<Notebook> Sqlite3Database::listNotebooks() { auto result = prepareStatement("SELECT * FROM notebooks"); int status = executeStep(result); if (isError(status)) throw DatabaseException("listing notebooks failed, invalid result"); std::vector<Notebook> result_vec; while (status != SQLITE_DONE) { result_vec.emplace_back(getInt(result, 0), getString(result, 1)); status = executeStep(result); } return result_vec; }
Database::Database(string path, string dbname) { this->db = QSqlDatabase::addDatabase(QString(dbname.c_str())); databaseName=path; this->db.setDatabaseName(QString(databaseName.c_str())); if(db.open()) { cout << "Vous êtes maintenant connecté à " << q2c(db.hostName()) << endl; } else { throw DatabaseException("La connexion a échoué."); } }
FB::variant IndexSync::put(FB::variant value, const FB::CatchAll& args) { const FB::VariantList& values = args.value; if(keyPath.is_initialized()) throw DatabaseException("CONSTRAINT_ERR", DatabaseException::CONSTRAINT_ERR); else if(values.size() < 1) throw FB::invalid_arguments(); else if(values.size() > 2) throw FB::invalid_arguments(); else if(values.size() == 2 && !values[1].is_of_type<bool>()) throw FB::invalid_arguments(); FB::variant key = values[0]; bool noOverwrite = values.size() == 2 ? values[1].cast<bool>() : false; try { implementation->put(Convert::toKey(host, key), Convert::toData(host, value), noOverwrite, transactionFactory.getTransactionContext()); } catch(ImplementationException& e) { throw DatabaseException(e); } return key; }
bool Database::Connect() { LOG(DEBUG, "Opening database " + m_databaseFile, ""); int rc; rc = sqlite3_open(m_databaseFile.c_str(), &db); if (rc) { throw DatabaseException(string(sqlite3_errmsg(db))); } else { return true; } }
bool Sqlite3Database::checkResult(int result, int expected, const std::string &msg, bool do_throw) const { if (result != expected) { auto errmsg = msg + ": " + std::to_string(result) + " " + std::string(sqlite3_errmsg(connection_.ptr())); if (do_throw) { throw DatabaseException(errmsg); } else { std::cout << errmsg << std::endl; } return false; } return true; }
std::string Convert::stringify(const FB::BrowserHostPtr& host, const FB::JSObjectPtr& object) { if(host == NULL) throw DatabaseException("Browser host was null.", DatabaseException::NOT_FOUND_ERR); else if(!host->getDOMWindow()->getProperty<FB::variant>("JSON").is_of_type<FB::JSObjectPtr>()) throw DatabaseException("Could not cast window.JSON to type object.", DatabaseException::UNKNOWN_ERR); FB::JSObjectPtr json = host->getDOMWindow()->getProperty<FB::JSObjectPtr>("JSON"); if(json == NULL) throw DatabaseException("window.JSON support not available.", DatabaseException::NOT_FOUND_ERR); else if(json->HasMethod("stringify")) { FB::VariantList arguments(1, object); FB::variant result = json->Invoke("stringify", arguments); if(result.empty()) throw DatabaseException("JSON Stringification failed.", DatabaseException::RECOVERABLE_ERR); else return result.cast<std::string>(); } else throw DatabaseException("window.JSON missing method stringify().", DatabaseException::NOT_FOUND_ERR); }
Sqlite3Database::Sqlite3Database(const std::string &connection_info) : connection_info_(connection_info), connection_{nullptr} { sqlite3 *conn; int result = sqlite3_open(connection_info.c_str(), &conn); if (result == SQLITE_OK) { // enable foreign key checking ... sqlite3_exec(conn, "PRAGMA foreign_keys = ON;", nullptr, nullptr, nullptr); connection_ = sqlite_conn(conn); } else { throw DatabaseException("Error opening SQLite database " + connection_info + " (error: " + std::to_string(result) + ")"); } }
void TdbDatabase::truncate() { if (m_tdbFile) { tdb_close(m_tdbFile); } m_tdbFile = tdb_open(m_databaseName.c_str(), 512, 0, O_RDWR | O_CREAT | O_TRUNC, S_IRWXU | S_IRGRP | S_IROTH); if (m_tdbFile == NULL) { string message; message += "Error opening tdb database: "; message += m_databaseName; throw DatabaseException(CONNECT_ERROR, message.c_str()); } }
Notebook Sqlite3Database::loadNotebook(const bigint_t notebook_id) { clearStatement(); stmt_cache_ << "SELECT * FROM notebooks WHERE id=" << std::to_string(notebook_id); auto result = prepareStatement(stmt_cache_.str()); if (isError(executeStep(result))) throw DatabaseException("loading notebook id " + std::to_string(notebook_id) + " failed, invalid result"); Notebook nb(getInt(result, 0), getString(result, 1)); return nb; }
Data::ECMAType Convert::getType(const FB::variant& variant) { if(variant.is_of_type<wstring>()) return Data::String; else if(variant.is_of_type<string>()) return Data::String; else if (variant.can_be_type<int>()) return Data::Integer; else if(variant.is_of_type<double>()) return Data::Number; else if(variant.is_of_type<FB::JSObjectPtr>()) return Data::Object; else if(variant.empty()) return Data::Undefined; else throw DatabaseException("An unexpected variant type was encountered.", DatabaseException::UNKNOWN_ERR); }
/* Makes sure that val is the correct type according to the column type */ bool Column::valValid(string val) { const char * valC = val.c_str(); if (colType == "int") { stringstream typecast(val); int intVal = 0; typecast >> intVal; stringstream back; back << intVal; string temp; back >> temp; //atoi returns 0 if not successful if (temp != val) { throw DatabaseException(33, val + " not a valid integer."); } } else if (colType == "float") {
Note Sqlite3Database::loadNote(const bigint_t note_id) { clearStatement(); stmt_cache_ << "SELECT title,content,notebook,last_change,reminder" " FROM notes WHERE (id=" << std::to_string(note_id) << ")"; auto result = prepareStatement(stmt_cache_.str()); if (isError(executeStep(result))) { throw DatabaseException("loading note id " + std::to_string(note_id) + " failed, invalid result"); } return Note(note_id, getString(result, 0), // title getString(result, 1), // content getInt(result, 2), // notebook getTimestamp(result, 3), // last change getTimestamp(result, 4) // reminder ); }
/* Count the number of rows */ int Database::countStatement(Query_parser* p) { string tableName = p->tables[0]; vector<LogicExpression::ExpressionTree*> expTree = p->trees; Table * table = findTable(tableName); if (table == NULL) { throw DatabaseException(10, tableName + " does not exist."); } vector<string> columnNames = table->columnNames(); int count = 0; //Loop through the rows. //If each row passes the test, then remove it from the table for (int i = 0; i < table->rowCount(); i++) { vector<string> thisRow = table->getRow(i); //Make sure the row passes each exression bool rowPasses = false; for (int k = 0; k < expTree.size(); k++) { //FIXX: IS THIS RIGHT? rowPasses = expTree[k]->isTrue(columnNames, thisRow); if (!rowPasses) { break; } } //If there's not comparators, then it auto passes! if (expTree.size() == 0) { rowPasses = true; } //Now if they used the AS operator, then we need to //assign the values to the new column names if (rowPasses) { count++; } } return count; }