Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix insert method #68

Merged
merged 3 commits into from
Nov 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/public/database.h
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,29 @@ class HEARTSHARED_EXPORT DataBase: public QObject
return false;
};

/**
* @brief insert a new value into database, and save into @a resultId autoincremented id of inserted object.
*
* @tparam Object The type of object to save.
* @param obj The object to save.
* @return true if the object is successfully saved, false otherwise.
*
* Example:
*
* @code{cpp}
* auto&& id = QSharedPointe<unsigned int>:: create();
insertObj(role.dynamicCast<Role>(), id.toWeekRef());
* @endcode
*/
template <class Object>
bool insertObj(const Object& obj, const QWeakPointer<unsigned int>& resultId = {}) {
if (auto&& database = db()) {
return database->insertObject(obj, !resultId.isNull(), resultId);
}

return false;
};

/**
* @brief Get a list of all objects from a specified table.
*
Expand Down
8 changes: 6 additions & 2 deletions src/public/iobjectprovider.h
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,13 @@ class HEARTSHARED_EXPORT iObjectProvider
* @note This method insert object into database only. IF object is exits in the database then this method return false.
* @param saveObject This is object for inserting.
* @param wait This arguments force current thread wait for the function finishing.
* @return true if objects is saved successful else false.
* @param autoincrementIdResult is id of the insert query to the Table with autoincrement id field.
* @return true if objects is saved successful else false. Note return two value. First is boolean result, second is id of inserted value.
* @note id will be returned only for the autoincement records.
*/
virtual bool insertObject(const QSharedPointer<PKG::DBObject>& saveObject, bool wait) = 0;
virtual bool insertObject(const QSharedPointer<PKG::DBObject>& saveObject,
bool wait,
const QWeakPointer<unsigned int>& autoincrementIdResult) = 0;

/**
* @brief deleteObject This method execute a delete method of obj and remove current object from database.
Expand Down
40 changes: 21 additions & 19 deletions src/public/isqldb.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ void ISqlDB::globalUpdateDataBase(SqlDBCasheWriteMode mode) {
qint64 currentTime = QDateTime::currentMSecsSinceEpoch();

if (currentTime - lastUpdateTime > updateInterval ||
static_cast<bool>(mode & SqlDBCasheWriteMode::Force)) {
static_cast<bool>(mode & SqlDBCasheWriteMode::Force)) {

if (static_cast<bool>(mode & SqlDBCasheWriteMode::On_New_Thread)) {

Expand All @@ -48,13 +48,13 @@ void ISqlDB::globalUpdateDataBase(SqlDBCasheWriteMode mode) {
}

bool ISqlDB::updateObjectP(const QSharedPointer<DBObject> &saveObject,
bool wait) {
bool wait) {

if (updateCache(saveObject)) {

if (getMode() == SqlDBCasheWriteMode::Force) {
return _writer && _writer->isValid() &&
_writer->updateObject(saveObject, wait);
_writer->updateObject(saveObject, wait);
}

pushToQueue(saveObject, CacheAction::Update);
Expand All @@ -64,11 +64,11 @@ bool ISqlDB::updateObjectP(const QSharedPointer<DBObject> &saveObject,
}

return _writer && _writer->isValid() &&
_writer->updateObject(saveObject, wait);
_writer->updateObject(saveObject, wait);
}

bool ISqlDB::deleteObjectP(const QSharedPointer<DBObject> &delObj,
bool wait) {
bool wait) {

deleteFromCache(delObj);
pushToQueue(delObj, CacheAction::Delete);
Expand All @@ -81,14 +81,15 @@ bool ISqlDB::deleteObjectP(const QSharedPointer<DBObject> &delObj,
}

bool ISqlDB::insertObjectP(const QSharedPointer<DBObject> &saveObject,
bool wait) {
bool wait,
const QWeakPointer<unsigned int>& autoincrementIdResult) {

if (insertToCache(saveObject)) {

if (getMode() == SqlDBCasheWriteMode::Force) {

return _writer && _writer->isValid() &&
_writer->insertObject(saveObject, wait);
_writer->insertObject(saveObject, wait, autoincrementIdResult);
}

pushToQueue(saveObject, CacheAction::Update);
Expand All @@ -98,7 +99,7 @@ bool ISqlDB::insertObjectP(const QSharedPointer<DBObject> &saveObject,
}

return _writer && _writer->isValid() &&
_writer->insertObject(saveObject, wait);
_writer->insertObject(saveObject, wait, autoincrementIdResult);
}

bool ISqlDB::replaceObjectP(const QSharedPointer<PKG::DBObject> &saveObject, bool wait) {
Expand Down Expand Up @@ -129,7 +130,7 @@ void ISqlDB::setLastUpdateTime(const qint64 &value) {
}

void ISqlDB::pushToQueue(const QSharedPointer<DBObject> &obj,
CacheAction type) {
CacheAction type) {
_saveLaterMutex.lock();
_changes.insert(type, obj);
_saveLaterMutex.unlock();
Expand All @@ -155,7 +156,7 @@ void ISqlDB::setWriter(SqlDBWriter *writer) {
}

bool ISqlDB::getAllObjects(const DBObject &templateObject,
QList<QSharedPointer<QH::PKG::DBObject>> &result) {
QList<QSharedPointer<QH::PKG::DBObject>> &result) {

result = getFromCache(&templateObject);
if(result.size()) {
Expand All @@ -170,7 +171,7 @@ bool ISqlDB::getAllObjects(const DBObject &templateObject,
for (const auto &object: std::as_const(result)) {
if (object->isCached() && !insertToCache(object)) {
QuasarAppUtils::Params::log("Selected object from database can not be saved into database cache. " +
object->toString(),
object->toString(),
QuasarAppUtils::Warning);
}
}
Expand All @@ -182,7 +183,7 @@ bool ISqlDB::getAllObjects(const DBObject &templateObject,
}

bool ISqlDB::deleteObject(const QSharedPointer<DBObject> &delObj,
bool wait) {
bool wait) {

if (!delObj)
return false;
Expand All @@ -201,7 +202,7 @@ bool ISqlDB::deleteObject(const QSharedPointer<DBObject> &delObj,
}

bool ISqlDB::updateObject(const QSharedPointer<DBObject> &saveObject,
bool wait) {
bool wait) {

if (!saveObject || !saveObject->isValid()) {
return false;
Expand All @@ -216,12 +217,13 @@ bool ISqlDB::updateObject(const QSharedPointer<DBObject> &saveObject,
return true;
}

bool ISqlDB::insertObject(const QSharedPointer<DBObject> &saveObject, bool wait) {
bool ISqlDB::insertObject(const QSharedPointer<DBObject> &saveObject, bool wait,
const QWeakPointer<unsigned int>& autoincrementIdResult) {
if (!saveObject || !saveObject->isValid()) {
return false;
}

if (!insertObjectP(saveObject, wait)) {
if (!insertObjectP(saveObject, wait, autoincrementIdResult)) {
return false;
}

Expand Down Expand Up @@ -291,7 +293,7 @@ void ISqlDB::prepareForDelete() {
}

bool ISqlDB::changeObjects(const DBObject &templateObject,
const std::function<bool (const QSharedPointer<QH::PKG::DBObject>&)> &changeAction) {
const std::function<bool (const QSharedPointer<QH::PKG::DBObject>&)> &changeAction) {

QList<QSharedPointer<DBObject>> list;
if (!getAllObjects(templateObject, list)) {
Expand Down Expand Up @@ -337,7 +339,7 @@ void ISqlDB::globalUpdateDataBasePrivate(qint64 currentTime) {

QuasarAppUtils::Params::log("writeUpdateItemIntoDB failed when"
" db object is not valid! obj=" +
obj->toString(),
obj->toString(),
QuasarAppUtils::VerboseLvl::Error);
continue;
}
Expand All @@ -359,7 +361,7 @@ void ISqlDB::globalUpdateDataBasePrivate(qint64 currentTime) {
}
default: {
QuasarAppUtils::Params::log("The Object of the cache have wrong type " +
obj->toString(),
obj->toString(),
QuasarAppUtils::VerboseLvl::Warning);

continue;
Expand All @@ -369,7 +371,7 @@ void ISqlDB::globalUpdateDataBasePrivate(qint64 currentTime) {
if (!saveResult ) {
QuasarAppUtils::Params::log("writeUpdateItemIntoDB failed when"
" work globalUpdateDataRelease!!! obj=" +
obj->toString(),
obj->toString(),
QuasarAppUtils::VerboseLvl::Error);
}
} else {
Expand Down
16 changes: 9 additions & 7 deletions src/public/isqldb.h
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ class HEARTSHARED_EXPORT ISqlDB: public QObject, public iObjectProvider, public
* @param mode See the SqlDBCache::setMode method for more information.
*/
ISqlDB(qint64 updateInterval = DEFAULT_UPDATE_INTERVAL,
SqlDBCasheWriteMode mode = SqlDBCasheWriteMode::Default);
SqlDBCasheWriteMode mode = SqlDBCasheWriteMode::Default);
~ISqlDB() override;

/**
Expand All @@ -103,10 +103,11 @@ class HEARTSHARED_EXPORT ISqlDB: public QObject, public iObjectProvider, public
bool deleteObject(const QSharedPointer<QH::PKG::DBObject>& delObj,
bool wait = false) override;
bool insertObject(const QSharedPointer<QH::PKG::DBObject>& saveObject,
bool wait = false) override;
bool wait = false,
const QWeakPointer<unsigned int>& autoincrementIdResult = {}) override;

bool replaceObject(const QSharedPointer<QH::PKG::DBObject>& saveObject,
bool wait = false) override;
bool wait = false) override;

bool doQuery(const QString &query, const QVariantMap& bindValues,
bool wait = false, QSqlQuery* result = nullptr) const override;
Expand Down Expand Up @@ -231,13 +232,14 @@ class HEARTSHARED_EXPORT ISqlDB: public QObject, public iObjectProvider, public
private:

bool updateObjectP(const QSharedPointer<QH::PKG::DBObject>& saveObject,
bool wait = false);
bool wait = false);
bool deleteObjectP(const QSharedPointer<QH::PKG::DBObject>& delObj,
bool wait = false);
bool wait = false);
bool insertObjectP(const QSharedPointer<QH::PKG::DBObject>& saveObject,
bool wait = false);
bool wait,
const QWeakPointer<unsigned int>& autoincrementIdResult);
bool replaceObjectP(const QSharedPointer<QH::PKG::DBObject>& saveObject,
bool wait = false);
bool wait = false);

qint64 lastUpdateTime = 0;
qint64 updateInterval = DEFAULT_UPDATE_INTERVAL;
Expand Down
12 changes: 10 additions & 2 deletions src/public/packages/dbobject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,11 @@ PrepareResult DBObject::prepareInsertQuery(QSqlQuery &q, bool replace) const {

for (auto it = map.begin(); it != map.end(); ++it) {

if (!bool(it.value().type & MemberType::Insert)) {
if (!static_cast<bool>(it.value().type & MemberType::Insert)) {
continue;
}

if (static_cast<bool>(it.value().type & MemberType::Autoincement) && !replace) {
continue;
}

Expand All @@ -99,7 +103,11 @@ PrepareResult DBObject::prepareInsertQuery(QSqlQuery &q, bool replace) const {
if (q.prepare(queryString)) {

for (auto it = map.begin(); it != map.end(); ++it) {
if (!bool(it.value().type & MemberType::Insert)) {
if (!static_cast<bool>(it.value().type & MemberType::Insert)) {
continue;
}

if (static_cast<bool>(it.value().type & MemberType::Autoincement) && !replace) {
continue;
}

Expand Down
5 changes: 4 additions & 1 deletion src/public/packages/dbobject.h
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,17 @@ enum class MemberType {
/// The Field with this type can not be duplicate on a table. If a Database object do not have a primary key then default implementation for select query try get object by fields with unique type.
Unique = 0x4,

/// The field with this atribute automaticaly incemented into database, and will not to added into insert reqests, but it can be used with replace request as a key.
Autoincement = 0x8,

/// The Field With This type can be inserted and updated.
InsertUpdate = Insert | Update,

/// The primary key field without autoincrement.
PrimaryKey = Insert | Unique,

//// The primary key field with autoincrement.
PrimaryKeyAutoIncrement = Unique
PrimaryKeyAutoIncrement = PrimaryKey | Autoincement
};

constexpr inline uint qHash(MemberType type) {
Expand Down
36 changes: 27 additions & 9 deletions src/public/sqldbwriter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ bool SqlDBWriter::initDbPrivate(const QVariantMap &params) {
delete _db;

_db = new QSqlDatabase(initSqlDataBasse(_config["DBDriver"].toString(),
_config["DBFilePath"].toString()));
_config["DBFilePath"].toString()));

if (_config.contains("DBFilePath")) {

Expand Down Expand Up @@ -311,14 +311,24 @@ bool SqlDBWriter::deleteObject(const QSharedPointer<DBObject> &ptr, bool wait) {
return asyncLauncher(job, wait);
}

bool SqlDBWriter::insertObject(const QSharedPointer<DBObject> &ptr, bool wait) {
bool SqlDBWriter::insertObject(const QSharedPointer<DBObject> &ptr,
bool wait,
const QWeakPointer<unsigned int>& autoincrementIdResult) {

Async::Job job = [this, ptr]() {
return insertQuery(ptr);
};
if (wait) {
auto resultId = QSharedPointer<int>::create();
Async::Job job = [this, ptr, autoincrementIdResult]() {
return insertQuery(ptr, autoincrementIdResult);
};

return asyncLauncher(job, wait);
return asyncLauncher(job, wait);
} else {
Async::Job job = [this, ptr]() {
return insertQuery(ptr);
};

return asyncLauncher(job, wait);
}
}

bool SqlDBWriter::replaceObject(const QSharedPointer<PKG::DBObject> &ptr, bool wait) {
Expand Down Expand Up @@ -354,7 +364,8 @@ SqlDBWriter::~SqlDBWriter() {

}

bool SqlDBWriter::insertQuery(const QSharedPointer<DBObject> &ptr) const {
bool SqlDBWriter::insertQuery(const QSharedPointer<DBObject> &ptr,
const QWeakPointer<unsigned int>& autoincrementIdResult) const {
if (!ptr)
return false;

Expand All @@ -368,7 +379,14 @@ bool SqlDBWriter::insertQuery(const QSharedPointer<DBObject> &ptr) const {
return ptr->prepareInsertQuery(q, false);
};

auto cb = [](){return true;};
auto cb = [&q, autoincrementIdResult]() {

if (auto&& ptr = autoincrementIdResult.lock()) {
*ptr = q.lastInsertId().toInt();
}

return true;
};

return workWithQuery(q, prepare, cb);
}
Expand Down Expand Up @@ -438,7 +456,7 @@ bool SqlDBWriter::selectQuery(const DBObject& requestObject,
if (!newObject->fromSqlRecord(q.record())) {
QuasarAppUtils::Params::log("Select query finished successful but, "
"the fromSqlRecord method return false." +
newObject->toString(),
newObject->toString(),
QuasarAppUtils::Error);
return false;
}
Expand Down
8 changes: 6 additions & 2 deletions src/public/sqldbwriter.h
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ class HEARTSHARED_EXPORT SqlDBWriter : public Async, public iObjectProvider
QList<QSharedPointer<PKG::DBObject>> &result) override;
bool updateObject(const QSharedPointer<PKG::DBObject> &ptr, bool wait = false) override;
bool deleteObject(const QSharedPointer<PKG::DBObject> &ptr, bool wait = false) override;
bool insertObject(const QSharedPointer<PKG::DBObject> &ptr, bool wait = false) override;
bool insertObject(const QSharedPointer<PKG::DBObject> &ptr, bool wait = false,
const QWeakPointer<unsigned int>& autoincrementIdResult = {}) override;
bool replaceObject(const QSharedPointer<PKG::DBObject> &ptr, bool wait = false) override;

void setSQLSources(const QStringList &list) override;
Expand Down Expand Up @@ -110,9 +111,12 @@ class HEARTSHARED_EXPORT SqlDBWriter : public Async, public iObjectProvider
/**
* @brief insertQuery This method prepare the insert object query.
* @param insertObject This is strong pointer of object for generate the insert query.
* @param autoIncrementID Week pointer to result id of new inserteed record.
* @return true if query generated successful.
* @note Works only of the int autoincrement ids...
*/
virtual bool insertQuery(const QSharedPointer<QH::PKG::DBObject>& insertObject) const;
virtual bool insertQuery(const QSharedPointer<QH::PKG::DBObject>& insertObject,
const QWeakPointer<unsigned int>& autoIncrementID = {}) const;

/**
* @brief replaceQuery This method prepare the replce object query.
Expand Down