6 Commits

20 changed files with 477 additions and 539 deletions

2
.gitmodules vendored
View File

@@ -1,6 +1,6 @@
[submodule "redkbuild"]
path = redkbuild
url = ssh://git@gitea.redkit-lab.work:57322/redkit-lab/redkbuild.git
url = git@gitea.redkit-lab.work:redkit-lab/redkbuild.git
[submodule "redkitty"]
path = redkitty
url = git@gitea.redkit-lab.work:redkit-lab/redkitty.git

View File

@@ -15,6 +15,7 @@ Project {
"src/cpp-opds.qbs",
"src/database/database.qbs",
"src/model/model.qbs",
"src/restapi/restapi.qbs",
]
}

View File

@@ -21,6 +21,7 @@ PSApplication {
Depends { name: "restapi" }
Depends { name: "redkit_gen" }
Depends { name: "rdbase" }
Depends { name: "model" }
cpp.cxxLanguageVersion: "c++20"

View File

@@ -1,64 +0,0 @@
// file : hello/person.hxx
// copyright : not copyrighted - public domain
#ifndef AUTHOR_S_H
#define AUTHOR_S_H
#include "database_global.h"
#include <QString>
#include <odb/core.hxx>
#include <odb/database.hxx>
#include <odb/query.hxx>
#pragma db object
class DATABASE_EXPORT Author_S
{
public:
Author_S() = default;
Author_S(const QString& firstN,
const QString& lastN,
const unsigned short age) :
m_firstName(firstN),
m_lastName(lastN),
m_age(age)
{
}
unsigned long long id() const { return m_id; }
QString firstName() const { return m_firstName; }
QString lastName() const { return m_lastName; }
unsigned short age() const { return m_age; }
QString full_name() const { return m_firstName + " " + m_lastName; }
void age(unsigned short age) { m_age = age; }
private:
friend class odb::access;
private:
#pragma db id auto
quint64 m_id;
QString m_firstName;
QString m_lastName;
quint8 m_age;
};
#pragma db view object(Author_S)
struct person_stat
{
#pragma db column("count(" + Author_S::m_id + ")")
std::size_t count;
#pragma db column("min(" + Author_S::m_age + ")")
unsigned short min_age;
#pragma db column("max(" + Author_S::m_age + ")")
unsigned short max_age;
};
#endif // AUTHOR_S_H

View File

@@ -1,64 +0,0 @@
// file : hello/person.hxx
// copyright : not copyrighted - public domain
#ifndef BOOK_S_H
#define BOOK_S_H
#include "database_global.h"
#include <QSharedPointer>
#include <QString>
#include <odb/core.hxx>
#include <rcore/smarttypes.h>
#include "author_s.h"
#pragma db object
class DATABASE_EXPORT Book_S
{
public:
Book_S() = default;
Book_S(const QString& name,
const SH<Author_S>& author,
const int year)
{
m_author = author;
m_name = name;
m_year = year;
};
unsigned long long id() const { return m_id; }
SH<Author_S> author() const { return m_author; }
QString name() const { return m_name; }
int year() const { return m_year; }
private:
friend class odb::access;
private:
#pragma db id auto
quint64 m_id;
SH<Author_S> m_author;
QString m_name;
quint8 m_year;
};
// #pragma db view object(Book_S) object(Author_S = author:Book_S::m_author)
// struct BookByAuthorView
// {
// #pragma db column(Book_S::m_id)
// quint64 book_id;
// #pragma db column(Book_S::m_name)
// QString book_name;
// #pragma db column(Book_S::m_year)
// qint8 year;
// #pragma db column(Author_S::m_first + " " + Author_S::m_last)
// QString author_full_name;
// };
#endif // BOOK_S_H

View File

@@ -13,87 +13,9 @@
#include <memory> // std::unique_ptr
#include <string>
#include <odb/database.hxx>
#if defined(DATABASE_MYSQL)
#include <odb/mysql/database.hxx>
#elif defined(DATABASE_SQLITE)
#include <odb/connection.hxx>
#include <odb/schema-catalog.hxx>
#include <odb/sqlite/database.hxx>
#include <odb/transaction.hxx>
#elif defined(DATABASE_PGSQL)
#include <odb/pgsql/database.hxx>
#elif defined(DATABASE_ORACLE)
#include <odb/oracle/database.hxx>
#elif defined(DATABASE_MSSQL)
#include <odb/mssql/database.hxx>
#else
#error unknown database; did you forget to define the DATABASE_* macros?
#endif
#include <filesystem>
#include <random>
#include <rcore/smarttypes.h>
using oDBase = odb::sqlite::database;
using uDBase = U<oDBase>;
struct testData
{
QString first;
QString last;
int age;
};
// Функция для генерации случайной строки (имени или фамилии)
QString generate_random_string(const QVector<QString>& pool)
{
static std::random_device rd;
static std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, pool.size() - 1);
return pool[dis(gen)];
}
// Функция для генерации случайного года
int generate_random_year(int min_year = 1900, int max_year = 2020)
{
static std::random_device rd;
static std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(min_year, max_year);
return dis(gen);
}
QVector<testData> fillDB()
{
QVector<QString> first_names = {
"John", "Jane", "Alex", "Chris", "Robert", "Emily", "James", "Linda", "David", "Sarah",
"Michael", "Elizabeth", "Daniel", "Samantha", "William", "Olivia", "Ethan", "Sophia", "Joshua", "Charlotte",
"Daniel", "Grace", "Benjamin", "Isabella", "Matthew", "Victoria", "Henry", "Abigail", "Samuel", "Megan",
"Lucas", "Lily", "Andrew", "Madison", "Jackson", "Chloe", "Aiden", "Amelia", "Thomas", "Natalie",
"Ryan", "Zoe", "Jack", "Harper", "Elijah", "Ava", "Isaac", "Mia", "Caleb", "Ella"
};
QVector<QString> last_names = {
"Doe", "Smith", "Johnson", "Williams", "Jones", "Brown", "Davis", "Miller", "Wilson", "Moore",
"Taylor", "Anderson", "Thomas", "Jackson", "White", "Harris", "Martin", "Thompson", "Garcia", "Martinez",
"Roberts", "Clark", "Lewis", "Walker", "Young", "Allen", "King", "Wright", "Scott", "Adams",
"Baker", "Gonzalez", "Nelson", "Carter", "Mitchell", "Perez", "Robinson", "Hughes", "Flores", "Cook",
"Rogers", "Gutierrez", "Ramirez", "Diaz", "Perez", "Ross", "Sanders", "Price", "Howard", "Cooper"
};
QVector<testData> vecTest;
for (int i = 0; i < 50; ++i)
{
QString first_name = generate_random_string(first_names);
QString last_name = generate_random_string(last_names);
int birth_year = generate_random_year(1900, 2000);
vecTest.push_back({ first_name, last_name, birth_year });
}
return vecTest;
}
#include "database_utils.h"
inline uDBase openDB(const std::string path_db)
{

View File

@@ -13,37 +13,22 @@ PSLibrary {
]
consoleApplication: true
Depends { name: "Qt"; submodules: [ "core", "sql", "network" ] }
Depends { name: "Qt"; submodules: [ "core", "network" ] }
Depends { name: "cpp" }
Depends { name: "odb.gen" }
Depends { name: "rdbase" }
Depends { name: "redkit_gen" }
redkit_gen.includeModules: ["JsonSerializer"]
odb.gen.databases: "sqlite"
cpp.cxxLanguageVersion: "c++17"
Group {
name: "cpp"
files: [
"databasemanager.*",
"*.cpp",
"*.h",
"*.hxx",
"**/*.h",
"**/*.hxx",
"**/*.cpp",
]
excludeFiles: odbs.files
}
Group {
id: odbs
name: "odb"
files: [
"author_s.h",
"book_s.h",
]
fileTags: ["hpp", "odbxx"]
}
cpp.dynamicLibraries: [

View File

@@ -0,0 +1,57 @@
#include "database_utils.h"
#include <random>
namespace
{
// Функция для генерации случайной строки (имени или фамилии)
QString generate_random_string(const QVector<QString>& pool)
{
static std::random_device rd;
static std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, pool.size() - 1);
return pool[dis(gen)];
}
// Функция для генерации случайного года
int generate_random_year(int min_year = 1900, int max_year = 2020)
{
static std::random_device rd;
static std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(min_year, max_year);
return dis(gen);
}
} // namespace
QVector<testData> fillAuthorDB()
{
QVector<QString> first_names = {
"John", "Jane", "Alex", "Chris", "Robert", "Emily", "James", "Linda", "David", "Sarah",
"Michael", "Elizabeth", "Daniel", "Samantha", "William", "Olivia", "Ethan", "Sophia", "Joshua", "Charlotte",
"Daniel", "Grace", "Benjamin", "Isabella", "Matthew", "Victoria", "Henry", "Abigail", "Samuel", "Megan",
"Lucas", "Lily", "Andrew", "Madison", "Jackson", "Chloe", "Aiden", "Amelia", "Thomas", "Natalie",
"Ryan", "Zoe", "Jack", "Harper", "Elijah", "Ava", "Isaac", "Mia", "Caleb", "Ella"
};
QVector<QString> last_names = {
"Doe", "Smith", "Johnson", "Williams", "Jones", "Brown", "Davis", "Miller", "Wilson", "Moore",
"Taylor", "Anderson", "Thomas", "Jackson", "White", "Harris", "Martin", "Thompson", "Garcia", "Martinez",
"Roberts", "Clark", "Lewis", "Walker", "Young", "Allen", "King", "Wright", "Scott", "Adams",
"Baker", "Gonzalez", "Nelson", "Carter", "Mitchell", "Perez", "Robinson", "Hughes", "Flores", "Cook",
"Rogers", "Gutierrez", "Ramirez", "Diaz", "Perez", "Ross", "Sanders", "Price", "Howard", "Cooper"
};
QVector<testData> vecTest;
for (int i = 0; i < 50; ++i)
{
QString first_name = generate_random_string(first_names);
QString last_name = generate_random_string(last_names);
int birth_year = generate_random_year(1900, 2000);
vecTest.push_back({ first_name, last_name, birth_year });
}
return vecTest;
}

View File

@@ -0,0 +1,37 @@
#include <QString>
#include <QVector>
#include <odb/database.hxx>
#if defined(DATABASE_MYSQL)
#include <odb/mysql/database.hxx>
#elif defined(DATABASE_SQLITE)
#include <odb/connection.hxx>
#include <odb/schema-catalog.hxx>
#include <odb/sqlite/database.hxx>
#include <odb/transaction.hxx>
#elif defined(DATABASE_PGSQL)
#include <odb/pgsql/database.hxx>
#elif defined(DATABASE_ORACLE)
#include <odb/oracle/database.hxx>
#elif defined(DATABASE_MSSQL)
#include <odb/mssql/database.hxx>
#else
#error unknown database; did you forget to define the DATABASE_* macros?
#endif
#include <rcore/smarttypes.h>
#include "database_global.h"
using oDBase = odb::sqlite::database;
using uDBase = U<oDBase>;
struct testData
{
QString first;
QString last;
int age;
};
QVector<testData> DATABASE_EXPORT fillAuthorDB();

View File

@@ -1,118 +0,0 @@
#include "databasemanager.h"
// Singleton instance
DatabaseManager& DatabaseManager::instance()
{
static DatabaseManager instance;
return instance;
}
// Конструктор: создаем подключение
DatabaseManager::DatabaseManager()
{
db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("mydatabase.db");
if (!db.open())
{
qDebug() << "Ошибка открытия БД:" << db.lastError().text();
}
else
{
qDebug() << "База данных успешно открыта";
}
}
// Деструктор: закрываем подключение
DatabaseManager::~DatabaseManager()
{
if (db.isOpen())
{
db.close();
}
}
// Возвращает ссылку на объект БД
QSqlDatabase& DatabaseManager::database()
{
return db;
}
// Выполняет SQL-запрос (без параметров)
bool DatabaseManager::executeQuery(const QString& query)
{
QSqlQuery q;
if (!q.exec(query))
{
qDebug() << "Ошибка выполнения запроса:" << q.lastError().text();
return false;
}
return true;
}
// Выполняет подготовленный SQL-запрос с параметрами
bool DatabaseManager::executePreparedQuery(const QString& query, const QStringList& values)
{
QSqlQuery q;
q.prepare(query);
for (const auto& value : values)
q.addBindValue(value);
if (!q.exec())
{
qDebug() << "Ошибка выполнения подготовленного запроса:" << q.lastError().text();
return false;
}
return true;
}
QList<QVariantList> DatabaseManager::executeSelectQuery(const QString& query, const QStringList& values)
{
QSqlQuery q;
q.prepare(query);
for (const auto& value : values)
q.addBindValue(value);
if (!q.exec())
{
qDebug() << "Ошибка выполнения SELECT запроса:" << q.lastError().text();
return {};
}
QList<QVariantList> results;
while (q.next())
{
QVariantList row;
for (int i = 0; i < q.record().count(); ++i)
row.append(q.value(i));
results.append(row);
}
return results;
}
QList<QVariantList> DatabaseManager::executeSelect(const SelectBuilder& selectBuilder)
{
const auto queryString = selectBuilder.getSelect();
qDebug() << "Подготовленный запрос: " << queryString;
QSqlQuery q;
if (!q.prepare(queryString))
qDebug() << "Ошибка при подготовке запроса:" << q.lastError().text();
if (!q.exec())
qDebug() << "Ошибка при выполнении запроса:" << q.lastError().text();
QList<QVariantList> results;
while (q.next()) // Проходимся по строкам
{
QVariantList row;
for (int i = 0; i < q.record().count(); ++i) // Проходимся по столбцам
row.append(q.value(i));
results.append(row);
}
return results;
}

View File

@@ -1,61 +0,0 @@
#ifndef DATABASEMANAGER_H
#define DATABASEMANAGER_H
#include "database_global.h"
#include <QDebug>
#include <QtSql>
struct SelectBuilder
{
QString tableName;
QStringList rows = { "*" };
QString where;
QString getSelect() const
{
QString allRows;
auto ri = rows.begin();
while (ri != rows.end())
{
allRows += (*ri++);
if (ri != rows.end())
allRows += ", ";
}
QString queryString = QString("SELECT %1").arg(allRows);
queryString += QString(" FROM %1").arg(tableName);
if (!where.isEmpty())
queryString += QString(" WHERE %1").arg(where);
queryString += ';';
return queryString;
}
};
class DATABASE_EXPORT DatabaseManager
{
public:
static DatabaseManager& instance(); // Singleton
QSqlDatabase& database();
bool executeQuery(const QString& query);
bool executePreparedQuery(const QString& query, const QStringList& values);
QList<QVariantList> executeSelectQuery(const QString& query, const QStringList& values = {});
QList<QVariantList> executeSelect(const SelectBuilder& selectBuilder);
private:
DatabaseManager();
~DatabaseManager();
QSqlDatabase db;
};
#endif // DATABASEMANAGER_H

View File

@@ -8,11 +8,11 @@
#include <restapi/restapiserver.h>
/* Опыты с odb */
#include <database/author_s-odb.hxx> // Должен быть здесь
#include <database/author_s.h>
#include <database/book_s-odb.hxx> // Должен быть здесь
#include <database/book_s.h>
#include <database/database.hxx> // create_database
#include <database/database.hxx> // create_database
#include <model/author_s-odb.hxx> // Должен быть здесь
#include <model/author_s.h>
#include <model/book_s-odb.hxx> // Должен быть здесь
#include <model/book_s.h>
#include <odb/database.hxx>
#include <iostream>
@@ -22,86 +22,86 @@ void fillBooksBD(uDBase& db)
try
{
QVector<SH<Author_S>> authors = {
SH<Author_S>::create("George", "Orwell", 142),
SH<Author_S>::create("J.K.", "Rowling", 56),
SH<Author_S>::create("J.R.R.", "Tolkien", 81),
SH<Author_S>::create("Leo", "Tolstoy", 189),
SH<Author_S>::create("Fyodor", "Dostoevsky", 174),
SH<Author_S>::create("Mark", "Twain", 183),
SH<Author_S>::create("Charles", "Dickens", 208),
SH<Author_S>::create("Virginia", "Woolf", 134),
SH<Author_S>::create("Ernest", "Hemingway", 122),
SH<Author_S>::create("Gabriel", "García Márquez", 98),
SH<Author_S>::create("Franz", "Kafka", 100),
SH<Author_S>::create("Harper", "Lee", 64),
SH<Author_S>::create("William", "Shakespeare", 459),
SH<Author_S>::create("Oscar", "Wilde", 155),
SH<Author_S>::create("Aldous", "Huxley", 123),
SH<Author_S>::create("Jane", "Austen", 210),
SH<Author_S>::create("John", "Steinbeck", 116),
SH<Author_S>::create("Agatha", "Christie", 124),
SH<Author_S>::create("Isaac", "Asimov", 105)
SH<Author_S>::create("George Orwell", "en"),
SH<Author_S>::create("J.K. Rowling", "en"),
SH<Author_S>::create("J.R.R. Tolkien", "en"),
SH<Author_S>::create("Leo Tolstoy", "ru"),
SH<Author_S>::create("Fyodor Dostoevsky", "ru"),
SH<Author_S>::create("Mark Twain", "en"),
SH<Author_S>::create("Charles Dickens", "en"),
SH<Author_S>::create("Virginia Woolf", "en"),
SH<Author_S>::create("Ernest Hemingway", "en"),
SH<Author_S>::create("Gabriel García Márquez", "en"),
SH<Author_S>::create("Franz Kafka", "de"),
SH<Author_S>::create("Harper Lee", "en"),
SH<Author_S>::create("William Shakespeare", "en"),
SH<Author_S>::create("Oscar Wilde", "en"),
SH<Author_S>::create("Aldous Huxley", "en"),
SH<Author_S>::create("Jane Austen", "en"),
SH<Author_S>::create("John Steinbeck", "en"),
SH<Author_S>::create("Agatha Christie", "en"),
SH<Author_S>::create("Isaac Asimov", "ru"),
};
// Список книг
QVector<Book_S> books = {
Book_S("1984", authors[0], 1949),
Book_S("Harry Potter and the Philosopher's Stone", authors[1], 1997),
Book_S("The Hobbit", authors[2], 1937),
Book_S("War and Peace", authors[3], 1869),
Book_S("Crime and Punishment", authors[4], 1866),
Book_S("Adventures of Huckleberry Finn", authors[5], 1884),
Book_S("A Tale of Two Cities", authors[6], 1859),
Book_S("Mrs. Dalloway", authors[7], 1925),
Book_S("The Old Man and the Sea", authors[8], 1952),
Book_S("One Hundred Years of Solitude", authors[9], 1967),
Book_S("The Trial", authors[10], 1925),
Book_S("To Kill a Mockingbird", authors[11], 1960),
Book_S("Macbeth", authors[12], 1606),
Book_S("The Picture of Dorian Gray", authors[13], 1890),
Book_S("Brave New World", authors[14], 1932),
Book_S("Pride and Prejudice", authors[15], 1813),
Book_S("The Brothers Karamazov", authors[4], 1880),
Book_S("The Grapes of Wrath", authors[16], 1939),
Book_S("Murder on the Orient Express", authors[17], 1934),
Book_S("I, Robot", authors[18], 1950),
Book_S("Animal Farm", authors[0], 1945),
Book_S("Harry Potter and the Chamber of Secrets", authors[1], 1998),
Book_S("The Lord of the Rings: The Fellowship of the Ring", authors[2], 1954),
Book_S("Anna Karenina", authors[3], 1878),
Book_S("The Idiot", authors[4], 1869),
Book_S("The Adventures of Tom Sawyer", authors[5], 1876),
Book_S("Oliver Twist", authors[6], 1837),
Book_S("To the Lighthouse", authors[7], 1927),
Book_S("For Whom the Bell Tolls", authors[8], 1940),
Book_S("Love in the Time of Cholera", authors[9], 1985),
Book_S("The Metamorphosis", authors[10], 1915),
Book_S("Go Set a Watchman", authors[11], 2015),
Book_S("King Lear", authors[12], 1605),
Book_S("The Importance of Being Earnest", authors[13], 1895),
Book_S("Brave New World Revisited", authors[14], 1958),
Book_S("Emma", authors[15], 1815),
Book_S("The Double", authors[4], 1846),
Book_S("Of Mice and Men", authors[16], 1937),
Book_S("And Then There Were None", authors[17], 1939),
Book_S("The Foundation Trilogy", authors[18], 1951),
Book_S("Down and Out in Paris and London", authors[0], 1933),
Book_S("Harry Potter and the Prisoner of Azkaban", authors[1], 1999),
Book_S("The Lord of the Rings: The Two Towers", authors[2], 1954),
Book_S("War and Peace", authors[3], 1869),
Book_S("The Brothers Karamazov", authors[4], 1880),
Book_S("The Prince and the Pauper", authors[5], 1881),
Book_S("David Copperfield", authors[6], 1850),
Book_S("The Waves", authors[7], 1931),
Book_S("A Farewell to Arms", authors[8], 1929),
Book_S("Chronicle of a Death Foretold", authors[9], 1981)
Book_S({ .author = authors[0], .title = "1984" }),
Book_S({ .author = authors[1], .title = "Harry Potter and the Philosopher's Stone" }),
Book_S({ .author = authors[2], .title = "The Hobbit" }),
Book_S({ .author = authors[3], .title = "War and Peace" }),
Book_S({ .author = authors[4], .title = "Crime and Punishment" }),
Book_S({ .author = authors[5], .title = "Adventures of Huckleberry Finn" }),
Book_S({ .author = authors[6], .title = "A Tale of Two Cities" }),
Book_S({ .author = authors[7], .title = "Mrs. Dalloway" }),
Book_S({ .author = authors[8], .title = "The Old Man and the Sea" }),
Book_S({ .author = authors[9], .title = "One Hundred Years of Solitude" }),
Book_S({ .author = authors[10], .title = "The Trial" }),
Book_S({ .author = authors[11], .title = "To Kill a Mockingbird" }),
Book_S({ .author = authors[12], .title = "Macbeth" }),
Book_S({ .author = authors[13], .title = "The Picture of Dorian Gray" }),
Book_S({ .author = authors[14], .title = "Brave New World" }),
Book_S({ .author = authors[15], .title = "Pride and Prejudice" }),
Book_S({ .author = authors[4], .title = "The Brothers Karamazov" }),
Book_S({ .author = authors[16], .title = "The Grapes of Wrath" }),
Book_S({ .author = authors[17], .title = "Murder on the Orient Express" }),
Book_S({ .author = authors[18], .title = "I, Robot" }),
Book_S({ .author = authors[0], .title = "Animal Farm" }),
Book_S({ .author = authors[1], .title = "Harry Potter and the Chamber of Secrets" }),
Book_S({ .author = authors[2], .title = "The Lord of the Rings: The Fellowship of the Ring" }),
Book_S({ .author = authors[3], .title = "Anna Karenina" }),
Book_S({ .author = authors[4], .title = "The Idiot" }),
Book_S({ .author = authors[5], .title = "The Adventures of Tom Sawyer" }),
Book_S({ .author = authors[6], .title = "Oliver Twist" }),
Book_S({ .author = authors[7], .title = "To the Lighthouse" }),
Book_S({ .author = authors[8], .title = "For Whom the Bell Tolls" }),
Book_S({ .author = authors[9], .title = "Love in the Time of Cholera" }),
Book_S({ .author = authors[10], .title = "The Metamorphosis" }),
Book_S({ .author = authors[11], .title = "Go Set a Watchman" }),
Book_S({ .author = authors[12], .title = "King Lear" }),
Book_S({ .author = authors[13], .title = "The Importance of Being Earnest" }),
Book_S({ .author = authors[14], .title = "Brave New World Revisited" }),
Book_S({ .author = authors[15], .title = "Emma" }),
Book_S({ .author = authors[4], .title = "The Double" }),
Book_S({ .author = authors[16], .title = "Of Mice and Men" }),
Book_S({ .author = authors[17], .title = "And Then There Were None" }),
Book_S({ .author = authors[18], .title = "The Foundation Trilogy" }),
Book_S({ .author = authors[0], .title = "Down and Out in Paris and London" }),
Book_S({ .author = authors[1], .title = "Harry Potter and the Prisoner of Azkaban" }),
Book_S({ .author = authors[2], .title = "The Lord of the Rings: The Two Towers" }),
Book_S({ .author = authors[3], .title = "War and Peace" }),
Book_S({ .author = authors[4], .title = "The Brothers Karamazov" }),
Book_S({ .author = authors[5], .title = "The Prince and the Pauper" }),
Book_S({ .author = authors[6], .title = "David Copperfield" }),
Book_S({ .author = authors[7], .title = "The Waves" }),
Book_S({ .author = authors[8], .title = "A Farewell to Arms" }),
Book_S({ .author = authors[9], .title = "Chronicle of a Death Foretold" }),
};
// Сохранение авторов в базу данных
{
odb::core::transaction t(db->begin());
for (auto& author : authors)
db->persist(author); // Используем get() для получения сырого указателя
db->persist(author);
t.commit();
}
@@ -129,45 +129,23 @@ int main(int argc, char* argv[])
uDBase db(openDB(dbPath));
// TODO Как-то нужно выполнять лишь раз
// fillBooksBD(db);
fillBooksBD(db);
// Сохранение дополнителньых авторов в базу данных
// {
// auto authors = fillAuthorDB();
// odb::core::transaction t(db->begin());
// for (auto& author : authors)
// {
// SH<Author_S> tempAuthor = SH<Author_S>::create(author., author.last, author.age);
// db->persist(tempAuthor);
// }
// t.commit();
// }
RestApiServer server(*db);
server.start(8080);
/* Опыты с odb */
// const std::string dbPath = "test_db.sqlite";
// std::vector<Author_S> authors;
// odb::core::transaction trans(db->begin());
// for (auto data : fillDB())
// {
// auto a = Author_S(data.first, data.last, data.age);
// db->persist(a);
// }
// trans.commit();
// try
// {
// odb::core::transaction tr(db->begin());
// odb::query<Author_S> query;
// odb::result<Author_S> result;
// odb::result<Author_S> r(db->query<Author_S>(odb::query<Author_S>::age >= 2000));
// for (const auto& author : r)
// {
// std::cout << "First: " << author.first() << ", Last: " << author.last() << ", Year: " << author.age() << std::endl;
// }
// tr.commit();
// }
// catch (const odb::exception& e)
// {
// std::cerr << "ODB error: " << e.what() << std::endl;
// return 1;
// }
// Set up code that uses the Qt event loop here.
// Call a.quit() or a.exit() to quit the application.
// A not very useful example would be including

45
src/model/author_s.h Normal file
View File

@@ -0,0 +1,45 @@
#ifndef AUTHOR_S_H
#define AUTHOR_S_H
#include "model_global.h"
#pragma db object
class MODEL_EXPORT Author_S
{
public:
Author_S() = default;
Author_S(const QString& fullName,
const QString& langCode) :
m_fullName(fullName),
m_langCode(langCode)
{}
quint64 id() const { return m_id; }
void setId(quint64 newId) { m_id = newId; }
QString fullName() const { return m_fullName; }
void setFullName(const QString& newFullName) { m_fullName = newFullName; }
QString langCode() const { return m_langCode; }
void setLangCode(const QString& newLangCode) { m_langCode = newLangCode; }
private:
friend class odb::access;
private:
#pragma db id auto
quint64 m_id;
QString m_fullName;
QString m_langCode;
};
#pragma db view object(Author_S)
struct person_stat
{
#pragma db column("count(" + Author_S::m_id + ")")
std::size_t count;
};
#endif // AUTHOR_S_H

95
src/model/book_s.h Normal file
View File

@@ -0,0 +1,95 @@
#ifndef BOOK_S_H
#define BOOK_S_H
#include "model_global.h"
#include <QDateTime>
#include "author_s.h"
#include "genre_s.h"
#include "series_s.h"
struct Book_SZ
{
SH<Author_S> author;
QString title;
SH<Series_S> series;
quint8 year;
SH<Genre_S> genre;
QDateTime lastModified = QDateTime::currentDateTime();
QString lang;
};
#pragma db object
class MODEL_EXPORT Book_S
{
public:
Book_S() = default;
Book_S(const Book_SZ& book)
{
m_author = book.author;
m_title = book.title;
m_series = book.series;
m_year = book.year;
m_genre = book.genre;
m_lastModified = book.lastModified;
m_lang = book.lang;
}
quint64 id() const { return m_id; }
void setId(const quint64& newId) { m_id = newId; }
SH<Author_S> author() const { return m_author; }
void setAuthor(const SH<Author_S>& newAuthor) { m_author = newAuthor; }
QString title() const { return m_title; }
void setTitle(const QString& newTitle) { m_title = newTitle; }
SH<Series_S> series() const { return m_series; }
void setSeries(const SH<Series_S>& newSeries) { m_series = newSeries; }
quint8 year() const { return m_year; }
void setYear(const quint8& newYear) { m_year = newYear; }
SH<Genre_S> genre() const { return m_genre; }
void setGenre(const SH<Genre_S>& newGenre) { m_genre = newGenre; }
QDateTime lastModified() const { return m_lastModified; }
void setLastModified(const QDateTime& newLastModified) { m_lastModified = newLastModified; }
QString lang() const { return m_lang; }
void setLang(const QString& newLang) { m_lang = newLang; }
private:
friend class odb::access;
private:
#pragma db id auto
quint64 m_id;
SH<Author_S> m_author;
QString m_title;
SH<Series_S> m_series;
quint8 m_year;
SH<Genre_S> m_genre;
QDateTime m_lastModified;
QString m_lang;
};
// #pragma db view object(Book_S) object(Author_S = author:Book_S::m_author)
// struct BookByAuthorView
// {
// #pragma db column(Book_S::m_id)
// quint64 book_id;
// #pragma db column(Book_S::m_name)
// QString book_name;
// #pragma db column(Book_S::m_year)
// qint8 year;
// #pragma db column(Author_S::m_first + " " + Author_S::m_last)
// QString author_full_name;
// };
#endif // BOOK_S_H

28
src/model/genre_s.h Normal file
View File

@@ -0,0 +1,28 @@
#ifndef GENRE_H
#define GENRE_H
#include "model_global.h"
#pragma db object
class MODEL_EXPORT Genre_S
{
public:
Genre_S() = default;
quint64 id() const { return m_id; }
void setId(const quint64& newId) { m_id = newId; }
QString name() const { return m_name; }
void setName(const QString& newName) { m_name = newName; }
private:
friend class odb::access;
private:
#pragma db id auto
quint64 m_id;
QString m_name;
};
#endif // GENRE_H

43
src/model/model.qbs Normal file
View File

@@ -0,0 +1,43 @@
/*!
\qmltype cpp-opds
\inherits Project
\brief Описание
*/
PSLibrary {
cpp.defines: [
// You can make your code fail to compile if it uses deprecated APIs.
// In order to do so, uncomment the following line.
//"QT_DISABLE_DEPRECATED_BEFORE=0x060000" // disables all the APIs deprecated before Qt 6.0.0
"DATABASE_SQLITE",
"MODEL_LIBRARY"
]
consoleApplication: true
Depends { name: "Qt"; submodules: [ "core", "network" ] }
Depends { name: "cpp" }
Depends { name: "odb.gen" }
Depends { name: "rdbase" }
Depends { name: "redkit_gen" }
redkit_gen.includeModules: ["JsonSerializer"]
odb.gen.databases: "sqlite"
cpp.cxxLanguageVersion: "c++17"
Group {
id: odbs
name: "odb"
files: [
"**/*.h",
]
fileTags: ["hpp", "odbxx", "rgen"]
}
cpp.dynamicLibraries: [
"odb-sqlite",
"odb-qt",
"odb",
"sqlite3"
]
}

15
src/model/model_global.h Normal file
View File

@@ -0,0 +1,15 @@
#ifndef MODEL_GLOBAL_H
#define MODEL_GLOBAL_H
#include <QtCore/qglobal.h>
#if defined(MODEL_LIBRARY)
#define MODEL_EXPORT Q_DECL_EXPORT
#else
#define MODEL_EXPORT Q_DECL_IMPORT
#endif
#include <odb/core.hxx>
#include <rcore/smarttypes.h>
#endif // MODEL_GLOBAL_H

28
src/model/series_s.h Normal file
View File

@@ -0,0 +1,28 @@
#ifndef SERIES_H
#define SERIES_H
#include "model_global.h"
#pragma db object
class MODEL_EXPORT Series_S
{
public:
Series_S() = default;
quint64 id() const { return m_id; }
void setId(const quint64& newId) { m_id = newId; }
QString serName() const { return m_serName; }
void setSerName(const QString& newSerName) { m_serName = newSerName; }
private:
friend class odb::access;
private:
#pragma db id auto
quint64 m_id;
QString m_serName;
};
#endif // SERIES_H

View File

@@ -18,6 +18,7 @@ WPSLibrary {
Depends { name: "odb.gen" }
Depends { name: "redkit_gen" }
Depends { name: "rdbase" }
Depends { name: "model" }
cpp.cxxLanguageVersion: "c++20"

View File

@@ -5,10 +5,10 @@
#include <QJsonObject>
#include <QJsonValue>
#include <database/author_s-odb.hxx> // Должен быть здесь
#include <database/author_s.h>
#include <database/book_s-odb.hxx> // Должен быть здесь
#include <database/book_s.h>
#include <model/author_s-odb.hxx> // Должен быть здесь
#include <model/author_s.h>
#include <model/book_s-odb.hxx> // Должен быть здесь
#include <model/book_s.h>
#include <odb/core.hxx>
#include <odb/database.hxx>
@@ -27,8 +27,8 @@ void RestApiServer::start(quint16 port)
}
else
{
QString addrs = "http://127.0.0.1:" + QString::number(this->serverPort());
qDebug() << "REST API сервер запущен по адресу:" << addrs;
qDebug() << "REST API сервер запущен по адресу:";
qDebug() << QString("http://127.0.0.1:%1").arg(port);
}
}
@@ -59,7 +59,7 @@ void RestApiServer::handleRequest()
QByteArray RestApiServer::processRequest(const QString& request)
{
qWarning() << request << "\n\n";
// qWarning() << request << "\n\n";
if (request.startsWith("GET /books/author/"))
{
@@ -70,11 +70,6 @@ QByteArray RestApiServer::processRequest(const QString& request)
QString firstName = nameParts.size() > 0 ? nameParts[0] : "";
QString lastName = nameParts.size() > 1 ? nameParts[1] : "";
qWarning()
<< "author:" << author << "\n"
<< "firstName:" << firstName << "\n"
<< "lastName:" << lastName << "\n";
odb::transaction t(m_db.begin());
auto books = m_db.query<Book_S>(odb::query<Book_S>::author->id == ageReq);
@@ -84,9 +79,18 @@ QByteArray RestApiServer::processRequest(const QString& request)
{
QJsonObject j;
j["id"] = QString::number(book.id());
j["name"] = book.name();
j["author"] = book.author()->full_name();
QJsonObject author;
author["id"] = QString::number(book.author()->id());
author["fullName"] = book.author()->fullName();
author["langCode"] = book.author()->langCode();
j["author"] = author;
// j["series"] = book.series()->serName();
// j["genre"] = book.genre()->name();
j["title"] = book.title();
j["year"] = book.year();
j["lastModified"] = book.lastModified().toString();
j["lang"] = book.lang();
jArray.push_back(j);
}
auto jDoc = QJsonDocument(jArray);
@@ -102,20 +106,27 @@ QByteArray RestApiServer::processRequest(const QString& request)
odb::result<Book_S> res(m_db.query<Book_S>());
QJsonArray jArray;
for (auto it = res.begin(); it != res.end(); ++it)
{
const auto& book = *it;
QJsonObject j;
j["id"] = QString::number(book.id());
j["title"] = book.name();
j["author"] = book.author()->full_name();
QJsonObject author;
author["id"] = QString::number(book.author()->id());
author["fullName"] = book.author()->fullName();
author["langCode"] = book.author()->langCode();
j["author"] = author;
// j["series"] = book.series()->serName();
// j["genre"] = book.genre()->name();
j["title"] = book.title();
j["year"] = book.year();
j["lastModified"] = book.lastModified().toString();
j["lang"] = book.lang();
jArray.push_back(j);
}
auto jDoc = QJsonDocument(jArray);
t.commit();
return "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n" + jDoc.toJson(QJsonDocument::Indented);
@@ -127,21 +138,19 @@ QByteArray RestApiServer::processRequest(const QString& request)
odb::result<Author_S> res(m_db.query<Author_S>());
QJsonArray jArray;
for (auto it = res.begin(); it != res.end(); ++it)
{
const auto& author = *it;
QJsonObject j;
j["id"] = QString::number(author.id());
j["first"] = author.firstName();
j["last"] = author.lastName();
j["age"] = author.age();
j["fullName"] = author.fullName();
j["langCode"] = author.langCode();
jArray.push_back(j);
}
auto jDoc = QJsonDocument(jArray);
t.commit();
return "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n" + jDoc.toJson(QJsonDocument::Indented);
}