Merge pull request #42 from HamedMasafi/wip/shared_pointer

Wip/shared pointer
This commit is contained in:
Hamed Masafi 2019-06-19 11:34:26 +04:30 committed by GitHub
commit f77e5e0794
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
27 changed files with 221 additions and 115 deletions

2
3rdparty/serializer vendored

@ -1 +1 @@
Subproject commit e2d8a726ef1396c47bf35347ea8b55ca47c6af3b
Subproject commit f9d81fcc6244271b3926891b0c86554e1e6b967e

View File

@ -3,7 +3,7 @@
src_dir="src"
namespace_name="nut"
ns=$(echo $namespace_name|awk '{print tolower($0)}')
#ns=$(echo $namespace_name|awk '{print tolower($0)}')
Ns="Nut"
NS=$(echo $namespace_name|awk '{print toupper($0)}')

View File

@ -3,6 +3,7 @@ QT += core sql
CONFIG += c++11
INCLUDEPATH += $$PWD/include
DEFINES += NUT_SHARED_POINTER
include(3rdparty/serializer/src/src.pri)
HEADERS += \

View File

@ -4,4 +4,3 @@ SUBDIRS += \
src \
test

View File

@ -278,7 +278,7 @@ bool DatabasePrivate::getCurrectScheema()
DatabaseModel DatabasePrivate::getLastScheema()
{
ChangeLogTable *u = changeLogs->query()
Row<ChangeLogTable> u = changeLogs->query()
->orderBy(!ChangeLogTable::idField())
->first();
@ -321,7 +321,7 @@ bool DatabasePrivate::putModelToDatabase()
DatabaseModel current = currentModel;
/*current.remove(__CHANGE_LOG_TABLE_NAME)*/;
auto *changeLog = new ChangeLogTable();
auto changeLog = create<ChangeLogTable>();
changeLog->setData(QJsonDocument(current.toJson()).toJson(QJsonDocument::Compact));
changeLog->setVersion(current.version());
changeLogs->append(changeLog);

View File

@ -209,6 +209,15 @@ inline Row<T> create() {
return QSharedPointer<T>(new T);
}
template<class T>
inline T *get(T *row) {
return row;
}
template<class T>
inline T *get(const QSharedPointer<T> row) {
return row.data();
}
#else
template <typename T>
using RowList = QList<T*>;
@ -223,6 +232,17 @@ template<class T>
inline Row<T> create() {
return new T;
}
template<class T>
inline T *get(const Row<T> row) {
return row;
}
template<class T>
inline T *get(const QSharedPointer<T> row) {
return row.data();
}
#endif
NUT_END_NAMESPACE

View File

@ -834,6 +834,9 @@ QString SqlGeneratorBase::escapeValue(const QVariant &v) const
return QString();
}
if (v.type() == QVariant::List)
return serialized;
return "'" + serialized + "'";
}

View File

@ -95,7 +95,7 @@ QString SqliteGenerator::fieldDeclare(FieldModel *field)
if (type.isEmpty())
return type;
if (field->isPrimaryKey) {
if (isNumeric(field->type) && field->isPrimaryKey) {
type = "INTEGER PRIMARY KEY";
if (field->isAutoIncrement)
type.append(" AUTOINCREMENT");

View File

@ -185,7 +185,7 @@ Q_OUTOFLINE_TEMPLATE RowList<T> Query<T>::toList(int count)
d->sql = d->database->sqlGenertor()->selectCommand(
d->tableName, d->fieldPhrase, d->wherePhrase, d->orderPhrase,
d->relations, d->skip, d->take);
qDebug()<<d->sql;
QSqlQuery q = d->database->exec(d->sql);
if (q.lastError().isValid()) {
qDebug() << q.lastError().text();
@ -346,7 +346,6 @@ Q_OUTOFLINE_TEMPLATE RowList<T> Query<T>::toList(int count)
if (m_autoDelete)
deleteLater();
#endif
return returnList;
}

View File

@ -23,8 +23,9 @@
#include "phrase.h"
#include <QList>
#include <QString>
#include <QtCore/QList>
#include <QtCore/QString>
#include <QtCore/QSharedData>
NUT_BEGIN_NAMESPACE
@ -32,7 +33,7 @@ class Database;
class TableSetBase;
class QueryBase;
struct RelationModel;
class QueryPrivate{
class QueryPrivate : public QSharedData {
QueryBase *q_ptr;
Q_DECLARE_PUBLIC(QueryBase)

View File

@ -11,9 +11,9 @@ QueryBase::QueryBase(QObject *parent) : QObject(parent)
}
void QueryBase::addTableToSet(TableSetBase *set, Table *table)
{
set->add(table);
}
//void QueryBase::addTableToSet(TableSetBase *set, Table *table)
//{
// set->add(table);
//}
NUT_END_NAMESPACE

View File

@ -23,7 +23,10 @@
#include <QtCore/QObject>
#include <QtCore/qglobal.h>
#include <QtCore/QExplicitlySharedDataPointer>
#include "defines.h"
#include "query_p.h"
NUT_BEGIN_NAMESPACE
@ -33,11 +36,15 @@ class TableSetBase;
class QueryBase : public QObject
{
Q_OBJECT
protected:
QExplicitlySharedDataPointer<QueryPrivate> d;
public:
explicit QueryBase(QObject *parent = 0);
protected:
void addTableToSet(TableSetBase *set, Table *table);
// void addTableToSet(TableSetBase *set, Table *table);
public slots:
};

View File

@ -1,6 +1,7 @@
#ifndef SQLMODEL_P_H
#define SQLMODEL_P_H
#include <QSharedPointer>
#include <QString>
#include "defines.h"
@ -17,7 +18,7 @@ public:
QString tableName;
QList<Table*> rows;
RowList<Table> rows;
TableModel *model;
};

View File

@ -1,9 +1,12 @@
DEFINES += NUT_SHARED_POINTER
HEADERS += \
$$PWD/generators/sqlgeneratorbase_p.h \
$$PWD/generators/postgresqlgenerator.h \
$$PWD/generators/mysqlgenerator.h \
$$PWD/generators/sqlitegenerator.h \
$$PWD/generators/sqlservergenerator.h \
$$PWD/tablesetbasedata.h \
$$PWD/types/dbgeography.h \
$$PWD/tableset.h \
$$PWD/defines_p.h \

View File

@ -30,8 +30,8 @@
#include "tablesetbase_p.h"
#include "table.h"
#include "bulkinserter.h"
//#include "database.h"
#include "databasemodel.h"
#include "tablesetbasedata.h"
NUT_BEGIN_NAMESPACE
@ -40,20 +40,23 @@ class Query;
class BulkInserter;
class Database;
template<class T>
class NUT_EXPORT TableSet : public TableSetBase
{
public:
typedef T value_type;
typedef T *pointer;
typedef T &reference;
explicit TableSet(Database *parent);
explicit TableSet(Table *parent);
void append(T *t);
void append(QList<T *> t);
void append(Row<T> t);
void append(RowList<T> t);
void remove(T *t);
void remove(QList<T *> t);
inline T *type() const {}
int length() const;
T *at(int i) const;
const T &operator[](int i) const;
@ -65,19 +68,19 @@ public:
template<class T>
Q_OUTOFLINE_TEMPLATE TableSet<T>::TableSet(Database *parent) : TableSetBase(parent)
{
_childClassName = T::staticMetaObject.className();
data->childClassName = T::staticMetaObject.className();
}
template<class T>
Q_OUTOFLINE_TEMPLATE TableSet<T>::TableSet(Table *parent) : TableSetBase(parent)
{
_childClassName = T::staticMetaObject.className();
data->childClassName = T::staticMetaObject.className();
}
template<class T>
Q_OUTOFLINE_TEMPLATE Query<T> *TableSet<T>::query(bool autoDelete)
{
Query<T> *q = new Query<T>(_database, this, autoDelete);
Query<T> *q = new Query<T>(data->database, this, autoDelete);
return q;
}
@ -85,34 +88,36 @@ Q_OUTOFLINE_TEMPLATE Query<T> *TableSet<T>::query(bool autoDelete)
template<class T>
Q_OUTOFLINE_TEMPLATE BulkInserter *TableSet<T>::bulkInserter()
{
BulkInserter *bi = new BulkInserter(_database, _childClassName);
BulkInserter *bi = new BulkInserter(data->database, data->childClassName);
return bi;
}
template<class T>
Q_OUTOFLINE_TEMPLATE int TableSet<T>::length() const
{
return _tables.count();
return data->tables.count();
}
template<class T>
Q_OUTOFLINE_TEMPLATE T *TableSet<T >::at(int i) const
{
return reinterpret_cast<T*>(_childRows.at(i));
//TODO: check
return reinterpret_cast<T*>(data->childRows.at(i));
}
template<class T>
Q_OUTOFLINE_TEMPLATE const T &TableSet<T>::operator[](int i) const
{
return _childRows[i];
return data->childRows[i];
}
template<class T>
Q_OUTOFLINE_TEMPLATE void TableSet<T>::append(T *t)
Q_OUTOFLINE_TEMPLATE void TableSet<T>::append(Row<T> t)
{
_tables.insert(t);
_childRows.append(t);
data.detach();
data->childs.append(t);
data->tables.insert(t.data());
data->childRows.append(t.data());
// if (_database)
// t->setModel(_database->model().tableByClassName(t->metaObject()->className()));
@ -123,16 +128,18 @@ Q_OUTOFLINE_TEMPLATE void TableSet<T>::append(T *t)
}
template<class T>
Q_OUTOFLINE_TEMPLATE void TableSet<T>::append(QList<T *> t)
Q_OUTOFLINE_TEMPLATE void TableSet<T>::append(RowList<T> t)
{
foreach (T* i, t)
foreach (Row<T> i, t)
append(i);
}
template<class T>
Q_OUTOFLINE_TEMPLATE void TableSet<T>::remove(T *t)
{
_tables.remove(t);
data.detach();
data->childs.removeOne(t);
data->tables.remove(t);
t->setStatus(Table::Deleted);
}

View File

@ -22,24 +22,25 @@
#include "database.h"
#include "tablesetbase_p.h"
#include "databasemodel.h"
#include "tablesetbasedata.h"
NUT_BEGIN_NAMESPACE
TableSetBase::TableSetBase(Database *parent) : QObject(parent),
_database(parent), _table(nullptr)//, _tableName(QString())
data(new TableSetBaseData(parent))
{
parent->add(this);
}
TableSetBase::TableSetBase(Table *parent) : QObject(parent),
_database(nullptr), _table(parent)//, _tableName(QString())
data(new TableSetBaseData(parent))
{
parent->add(this);
}
TableSetBase::~TableSetBase()
{
foreach (Table *t, _tables)
foreach (Table *t, data->tables)
t->setParentTableSet(nullptr);
}
@ -47,12 +48,13 @@ int TableSetBase::save(Database *db, bool cleanUp)
{
int rowsAffected = 0;
TableModel *masterModel = nullptr;
if (_table)
masterModel = db->model().tableByClassName(_table->metaObject()->className());
if (data->table)
masterModel = db->model().tableByClassName(data->table->metaObject()->className());
foreach (Table *t, _childRows) {
if(_table)
t->setParentTable(_table, masterModel,
foreach (Table *t, data->childRows) {
if(data->table)
t->setParentTable(data->table,
masterModel,
db->model().tableByClassName(t->metaObject()->className()));
if(t->status() == Table::Added
@ -66,45 +68,50 @@ int TableSetBase::save(Database *db, bool cleanUp)
}
if (cleanUp)
_childRows.clear();
data->childRows.clear();
return rowsAffected;
}
void TableSetBase::clearChilds()
{
foreach (Table *t, _childRows)
#ifndef NUT_SHARED_POINTER
foreach (Table *t, data->_childRows)
t->deleteLater();
_childRows.clear();
#endif
data->childRows.clear();
}
void TableSetBase::add(Table *t)
{
if(!_tables.contains(t)){
_tables.insert(t);
_childRows.append(t);
if(!data->tables.contains(get(t))){
data.detach();
data->tables.insert(get(t));
data->childRows.append(get(t));
}
}
void TableSetBase::remove(Table *t)
{
_tables.remove(t);
_childRows.removeOne(t);
data.detach();
data->tables.remove(get(t));
data->childRows.removeOne(get(t));
}
QString TableSetBase::childClassName() const
{
return _childClassName;
return data->childClassName;
}
Database *TableSetBase::database() const
{
return _database;
return data->database;
}
void TableSetBase::setDatabase(Database *database)
{
_database = database;
data.detach();
data->database = database;
}
NUT_END_NAMESPACE

View File

@ -24,6 +24,7 @@
#include <QtCore/QObject>
#include <QtCore/qglobal.h>
#include <QtCore/QSet>
#include <QExplicitlySharedDataPointer>
#include "defines.h"
@ -31,6 +32,7 @@ NUT_BEGIN_NAMESPACE
class Table;
class Database;
class TableSetBaseData;
class TableSetBase : public QObject
{
@ -47,16 +49,17 @@ public:
void setDatabase(Database *database);
protected:
QSet<Table*> _tables;
QList<Table*> _childRows;
Database *_database;
Table *_table;
// QString _tableName;
QString _childClassName;
// QSet<Table*> _tables;
// RowList<Table> _childRows;
// Database *_database;
// Table *_table;
//// QString _tableName;
// QString _childClassName;
QExplicitlySharedDataPointer<TableSetBaseData> data;
private:
void add(Table* t);
void remove(Table* t);
void remove(Table *t);
friend class Table;
friend class QueryBase;

53
src/tablesetbasedata.h Normal file
View File

@ -0,0 +1,53 @@
/**************************************************************************
**
** This file is part of Nut project.
** https://github.com/HamedMasafi/Nut
**
** Nut is free software: you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** Nut is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with Nut. If not, see <http://www.gnu.org/licenses/>.
**
**************************************************************************/
#ifndef TABLESETBASEDATA_H
#define TABLESETBASEDATA_H
#include <QSharedData>
#include "defines.h"
NUT_BEGIN_NAMESPACE
class Table;
class Database;
class TableSetBaseData : public QSharedData
{
public:
TableSetBaseData(Database *parent) :
database(parent), table(nullptr)
{ }
TableSetBaseData(Table *parent) :
database(nullptr), table(parent)
{ }
QSet<Table*> tables;
QList<Table*> childRows;
RowList<Table> childs;
Database *database;
Table *table;
QString childClassName;
};
NUT_END_NAMESPACE
#endif // TABLESETBASEDATA_H

View File

@ -11,7 +11,7 @@
.arg(timer.elapsed() / 1000.) \
.arg(__func__)
#define DRIVER "QPSQL"
#define DRIVER "QSQLITE"
#define DATABASE QString("nut_test_%1_db").arg(metaObject()->className()).toLower()
#define HOST "127.0.0.1"
#define USERNAME "postgres"

View File

@ -8,3 +8,5 @@ win32 {
LIBS += -L$$LIBDIR -lnut
INCLUDEPATH += $$PWD/../../src $$PWD/../common
#include(../../src/src.pri)
DEFINES += NUT_SHARED_POINTER

View File

@ -56,7 +56,7 @@ void BasicTest::dataScheema()
void BasicTest::createUser()
{
user = new User;
user = Nut::create<User>();
user->setUsername("admin");
user->setPassword("123456");
db.users()->append(user);
@ -66,7 +66,7 @@ void BasicTest::createUser()
void BasicTest::createPost()
{
TIC();
Post *newPost = new Post;
auto newPost = Nut::create<Post>();
newPost->setTitle("post title");
newPost->setSaveDate(QDateTime::currentDateTime());
newPost->setPublic(false);
@ -74,14 +74,14 @@ void BasicTest::createPost()
db.posts()->append(newPost);
for(int i = 0 ; i < 3; i++){
auto *comment = new Comment;
auto comment = Nut::create<Comment>();
comment->setMessage("comment #" + QString::number(i));
comment->setSaveDate(QDateTime::currentDateTime());
comment->setAuthorId(user->id());
newPost->comments()->append(comment);
db.comments()->append(comment);
}
for (int i = 0; i < 10; ++i) {
auto *score = new Score;
auto score = Nut::create<Score>();
score->setScore(i % 5);
newPost->scores()->append(score);
}
@ -106,7 +106,7 @@ void BasicTest::createPost2()
int postId = postIdVar.toInt();
for(int i = 0 ; i < 3; i++){
auto *comment = new Comment;
auto comment = Nut::create<Comment>();
comment->setMessage("comment #" + QString::number(i + 2));
comment->setSaveDate(QDateTime::currentDateTime());
comment->setAuthor(user);
@ -205,7 +205,7 @@ void BasicTest::testDate()
QTime t = QTime(d.time().hour(), d.time().minute(), d.time().second());
d.setTime(t);
Post *newPost = new Post;
auto newPost = Nut::create<Post>();
newPost->setTitle("post title");
newPost->setSaveDate(d);
@ -249,7 +249,7 @@ void BasicTest::modifyPost()
auto q = db.posts()->query();
q->setWhere(Post::idField() == postId);
Post *post = q->first();
Nut::Row<Post> post = q->first();
QTEST_ASSERT(post != nullptr);

View File

@ -12,8 +12,8 @@ class BasicTest : public QObject
Q_OBJECT
WeblogDatabase db;
int postId;
Post *post;
User *user;
Nut::Row<Post> post;
Nut::Row<User> user;
public:
explicit BasicTest(QObject *parent = nullptr);

View File

@ -45,7 +45,7 @@ void BenchmarkTest::insert1kPost()
t.start();
for (int i = 0; i < 100; ++i) {
Post *newPost = new Post;
auto newPost = Nut::create<Post>();
newPost->setTitle("post title");
newPost->setSaveDate(QDateTime::currentDateTime());

View File

@ -85,53 +85,54 @@ void DataTypesTest::initTestCase()
void DataTypesTest::insert()
{
SampleTable t;
t.setInt8(f_int8);
t.setInt16(f_int16);
t.setInt32(f_int32);
t.setInt64(f_int64);
auto t = Nut::create<SampleTable>();
t.setUint8(f_uint8);
t.setUint16(f_uint16);
t.setUint32(f_uint32);
t.setUint64(f_uint64);
t->setInt8(f_int8);
t->setInt16(f_int16);
t->setInt32(f_int32);
t->setInt64(f_int64);
t.setReal(f_real);
t.setFloat(f_float);
t->setUint8(f_uint8);
t->setUint16(f_uint16);
t->setUint32(f_uint32);
t->setUint64(f_uint64);
t.setUrl(f_url);
t->setReal(f_real);
t->setFloat(f_float);
t.setTime(f_time);
t.setDate(f_date);
t.setDateTime(f_dateTime);
t.setUuid(f_uuid);
t->setUrl(f_url);
t.setJsonDoc(f_jsonDoc);
t.setJsonObj(f_jsonObj);
t.setJsonArray(f_jsonArray);
t.setJsonValue(f_jsonValue);
t->setTime(f_time);
t->setDate(f_date);
t->setDateTime(f_dateTime);
t->setUuid(f_uuid);
t.setString(f_string);
t.setStringList(f_stringList);
t.setQchar(f_qchar);
t->setJsonDoc(f_jsonDoc);
t->setJsonObj(f_jsonObj);
t->setJsonArray(f_jsonArray);
t->setJsonValue(f_jsonValue);
t->setString(f_string);
t->setStringList(f_stringList);
t->setQchar(f_qchar);
#ifdef QT_GUI_LIB
t.setColor(f_color);
t->setColor(f_color);
t.setPoint(f_point);
t.setPointf(f_pointf);
t->setPoint(f_point);
t->setPointf(f_pointf);
t.setPolygon(f_polygon);
t.setPolygonf(f_polygonf);
t->setPolygon(f_polygon);
t->setPolygonf(f_polygonf);
#endif
db.sampleTables()->append(&t);
db.sampleTables()->append(t);
db.saveChanges();
}
void DataTypesTest::retrive()
{
QList<SampleTable*> list = db.sampleTables()->query()->toList();
Nut::RowList<SampleTable> list = db.sampleTables()->query()->toList();
QTEST_ASSERT(list.count() == 1);
SampleTable *t = list.first();
Nut::Row<SampleTable> t = list.first();
QTEST_ASSERT(t->f_int8() == f_int8);
QTEST_ASSERT(t->f_int16() == f_int16);

View File

@ -39,7 +39,7 @@ void TestJson::store()
db.open();
Table *t = new Table;
auto t = Nut::create<Table>();
QJsonParseError e;
QJsonDocument doc = QJsonDocument::fromJson(R"({"a": 4, "b":3.14})", &e);
qDebug() << e.errorString();

View File

@ -41,14 +41,13 @@ void UuidTest::initTestCase()
void UuidTest::save()
{
TIC();
Test t;
t.setId(QUuid::createUuid());
t.setUuid(uuid);
db.tests()->append(&t);
auto t = Nut::create<Test>();
t->setId(QUuid::createUuid());
t->setUuid(uuid);
db.tests()->append(t);
int n = db.saveChanges();
TOC();
TOC();
QTEST_ASSERT(n == 1);
}

View File

@ -58,11 +58,11 @@ void Upgrades::version2()
initDb(db);
QTEST_ASSERT(db.open());
Table2 t;
t.setStr("0");
db.sampleTable()->append(&t);
auto t = Nut::create<Table2>();
t->setStr("0");
db.sampleTable()->append(t);
db.saveChanges();
id = t.id();
id = t->id();
}
void Upgrades::version3()