store sellers with state == NEW

This commit is contained in:
Martin Brodbeck 2018-07-11 15:58:09 +02:00
parent ddfb9471a8
commit 976dcbcbeb
2 changed files with 54 additions and 2 deletions

View file

@ -41,7 +41,7 @@ void Database::createNew()
"seller_no INTEGER, " "seller_no INTEGER, "
"first_name TEXT, " "first_name TEXT, "
"last_name TEXT, " "last_name TEXT, "
"offered_articles INTEGER, " "num_offered_articles INTEGER, "
"UNIQUE (seller_no)" "UNIQUE (seller_no)"
");"}; ");"};
sqlStrings.push_back(sqlCreateSellers); sqlStrings.push_back(sqlCreateSellers);
@ -143,4 +143,53 @@ int Database::getVersion()
void Database::beginTransaction() { exec("BEGIN TRANSACTION"); } void Database::beginTransaction() { exec("BEGIN TRANSACTION"); }
void Database::endTransaction() { exec("END TRANSACTION"); } void Database::endTransaction() { exec("END TRANSACTION"); }
unsigned int Database::storeSellers(std::vector<Seller>& sellers)
{
int retCode{};
int count{};
sqlite3_stmt* stmt;
beginTransaction();
for (auto& seller : sellers) {
if (seller.getState() == Entity::State::NEW) {
retCode = sqlite3_prepare_v2(
db_,
"INSERT INTO sellers"
" (id, seller_no, first_name, last_name, num_offered_articles)"
" VALUES (:uuid, :seller_no, :first_name, :last_name, :num_offered_articles)",
-1, &stmt, nullptr);
if (retCode != SQLITE_OK)
throw std::runtime_error(sqlite3_errmsg(db_));
sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, ":uuid"),
boost::uuids::to_string(seller.getUuid()).c_str(), -1, nullptr);
sqlite3_bind_int(stmt, sqlite3_bind_parameter_index(stmt, ":seller_no"),
seller.getSellerNo());
sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, ":first_name"),
seller.getFirstName().c_str(), -1, nullptr);
sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, ":last_name"),
seller.getLastName().c_str(), -1, nullptr);
sqlite3_bind_int(stmt, sqlite3_bind_parameter_index(stmt, ":num_offered_articles"),
seller.getNumberOfOfferedArticles());
retCode = sqlite3_step(stmt);
if (retCode != SQLITE_DONE) {
std::string errMsg(sqlite3_errmsg(db_));
sqlite3_finalize(stmt);
throw std::runtime_error(errMsg);
}
seller.setState(Seller::State::CLEAN);
++count;
sqlite3_finalize(stmt);
}
}
endTransaction();
return count;
}

View file

@ -1,6 +1,8 @@
#ifndef DATABASE_H #ifndef DATABASE_H
#define DATABASE_H #define DATABASE_H
#include "seller.h"
#include <string> #include <string>
#include <sqlite3.h> #include <sqlite3.h>
@ -14,6 +16,7 @@ public:
Database& operator=(const Database&) = delete; Database& operator=(const Database&) = delete;
void exec(const std::string& sql); void exec(const std::string& sql);
void init(); void init();
unsigned int storeSellers(std::vector<Seller>& sellers);
private: private:
sqlite3 *db_; sqlite3 *db_;
std::string dbname_; std::string dbname_;