2 Commits

Author SHA1 Message Date
3c2b8e7cf4 тудаже 2025-03-16 10:46:18 +05:00
394c55ae5c Попытка раскидать по библиотекам 2025-03-16 10:46:06 +05:00
16 changed files with 191 additions and 266 deletions

3
.gitmodules vendored
View File

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

View File

@@ -1,8 +0,0 @@
import qbs
Export {
Depends { name: "cpp" }
Depends { name: "rsc.sqlite.settings" }
rsc.sqlite.settings.includeRegexValues: exportingProduct.includeRegexValue
}

View File

@@ -1,53 +0,0 @@
import qbs
Module {
id: karchive
readonly property string karchive_path: project.sourceDirectory + "/external_libs/karchive"
readonly property string libKF5ArchivePath: karchive.karchive_path + "/lib"
+ (qbs.buildVariant == "release" ? "/Release" : "/Debug")
property bool installFiles: true
Depends { name: "glob" }
Depends { name: "cpp" }
Depends { name: "zlib" }
Properties
{
condition: qbs.targetOS.contains("linux") || qbs.targetOS.contains("astra")
cpp.includePaths: [ karchive.karchive_path + "/include/lin" ]
cpp.libraryPaths: [ karchive.libKF5ArchivePath + "/lin" ]
cpp.dynamicLibraries: "KF5Archive"
}
Properties {
condition: qbs.targetOS.contains("windows")
cpp.includePaths: [ karchive.karchive_path + "/include/win" ]
cpp.libraryPaths: [ karchive.libKF5ArchivePath + "/win" ]
cpp.dynamicLibraries: "KF5Archive"
}
InstallGroup {
name: "karchive_lin"
condition: qbs.targetOS.contains("linux") || qbs.targetOS.contains("astra")
files: [
karchive.libKF5ArchivePath + "/lin/libKF5Archive.so",
karchive.libKF5ArchivePath + "/lin/libKF5Archive.so.5",
karchive.libKF5ArchivePath + "/lin/libKF5Archive.so.5.108.0"
]
qbs.install: karchive.installFiles
qbs.installDir: glob.binInstallPrefix
}
InstallGroup {
name: "karchive_win"
condition: qbs.targetOS.contains("windows")
files: [
karchive.libKF5ArchivePath + "/win/KF5Archive.dll",
karchive.libKF5ArchivePath + "/win/KF5Archive.lib"
]
qbs.install: karchive.installFiles
qbs.installDir: glob.binInstallPrefix
}
zlib.installFiles: true
}

View File

@@ -3,16 +3,17 @@ import qbs
Project { Project {
name: "opds++" name: "opds++"
qbsSearchPaths: [ qbsSearchPaths: [
"redkitty/qbs", "qbs",
// "redkitty/qbs",
// // "guiness/qbs",
// // "prerequisites/qbs",
// // "report/qbs",
"redkbuild", "redkbuild",
"redkitty/lib/redkit-gen-integration/qbs", // // "ext_libs/openssl/qbs",
"prerequisites/qbs", // "redkitty/lib/redkit-gen-integration/qbs",
] ]
references: [ references: [
"redkitty/lib/rsc/libs_impl/rdbaseimpl/rdbaseimpl.qbs",
"redkitty/lib/rcore/rcore.qbs",
"src/cpp-opds.qbs", "src/cpp-opds.qbs",
"src/database/database.qbs", "src/database/database.qbs",
"src/restapi/restapi.qbs", "src/restapi/restapi.qbs",

View File

@@ -0,0 +1,65 @@
import qbs
import qbs.FileInfo
Module {
Depends { name: "cpp" }
Depends { name: "Qt.core" }
FileTagger {
patterns: "*.hxx"
fileTags: ["odb"]
}
Rule {
inputs: ["odb"]
Artifact {
// filePath: FileInfo.baseName(input.fileName)+ "-odb.hxx"
filePath: FileInfo.cleanPath(input.filePath + "/../" ) + "/" + FileInfo.baseName(input.fileName) + "-odb.hxx"
fileTags: ["hpp"]
}
Artifact {
// filePath: FileInfo.baseName(input.fileName) + "-odb.cxx"
filePath: {
// console.error("THIS ART "+FileInfo.cleanPath(input.filePath + "/../") + "/" + FileInfo.baseName(input.fileName) + "-odb.cxx")
return FileInfo.cleanPath(input.filePath + "/../") + "/" + FileInfo.baseName(input.fileName) + "-odb.cxx"}
fileTags: ["cpp"]
}
prepare: {
var cmd = new Command("odb", [
"--std", "c++11",
"-d", "sqlite",
"--generate-query",
"--generate-schema",
"--generate-prepared",
// "--include-prefix", FileInfo.cleanPath(input.filePath + "/../"),
// "--output-dir", product.Qt.core.qmDir,
"--output-dir", FileInfo.cleanPath(input.filePath + "/../"),
"-I/home/uzver/qt5.15/include",
input.filePath,
]);
cmd.description = "Generating ODB files for " + input.fileName;
console.error(cmd.arguments)
return [cmd];
}
}
cpp.includePaths: [
project.sourceDirectory,
product.Qt.core.qmDir,
"/usr/include", // Общие заголовки
"/usr/include/odb" // Заголовки ODB
]
// Подключаем библиотеки ODB
cpp.libraryPaths: [
"/usr/lib" // Путь к библиотекам
]
cpp.dynamicLibraries: [
"odb",
"odb-sqlite"
]
}

Submodule redkitty deleted from 2316ddea72

View File

@@ -3,7 +3,7 @@
\inherits Project \inherits Project
\brief Описание \brief Описание
*/ */
PSApplication { Application {
// CppApplication { // CppApplication {
cpp.defines: [ cpp.defines: [
// You can make your code fail to compile if it uses deprecated APIs. // You can make your code fail to compile if it uses deprecated APIs.
@@ -16,11 +16,9 @@ PSApplication {
Depends { name: "Qt"; submodules: [ "core", "sql", "network" ] } Depends { name: "Qt"; submodules: [ "core", "sql", "network" ] }
Depends { name: "cpp" } Depends { name: "cpp" }
Depends { name: "database" } Depends { name: "database" }
Depends { name: "odb.gen" } Depends { name: "odbModule"}
Depends { name: "sqlite3" }
Depends { name: "restapi" } // Depends { name: "redkit_gen" }
Depends { name: "redkit_gen" }
Depends { name: "rdbase" }
cpp.cxxLanguageVersion: "c++20" cpp.cxxLanguageVersion: "c++20"
@@ -31,12 +29,6 @@ PSApplication {
] ]
} }
cpp.dynamicLibraries: [
"odb-sqlite",
"odb-qt",
"odb",
"sqlite3"
]
// } // }
} // Project } // Project

View File

@@ -4,48 +4,49 @@
#ifndef AUTHOR_S_H #ifndef AUTHOR_S_H
#define AUTHOR_S_H #define AUTHOR_S_H
#include "database_global.h" // #include <QtCore/QObject>
#include <QString> #include <cstddef> // std::size_t
#include <memory>
#include <string>
#include <odb/core.hxx> #include <odb/core.hxx>
#include <odb/database.hxx> #include <odb/database.hxx>
#include <odb/query.hxx> #include <odb/query.hxx>
#pragma db object #pragma db object
class DATABASE_EXPORT Author_S class __attribute__((visibility("default"))) Author_S
{ {
public: public:
Author_S() = default; Author_S() = default;
Author_S(const QString& firstN, Author_S(const std::string& first,
const QString& lastN, const std::string& last,
const unsigned short age) : const unsigned short age) :
m_firstName(firstN), m_first(first),
m_lastName(lastN), m_last(last),
m_age(age) m_age(age)
{ {
} }
unsigned long long id() const { return m_id; } unsigned long long id() const { return m_id; }
QString firstName() const { return m_firstName; } std::string first() const { return m_first; }
QString lastName() const { return m_lastName; } std::string last() const { return m_last; }
unsigned short age() const { return m_age; } unsigned short age() const { return m_age; }
QString full_name() const { return m_firstName + " " + m_lastName; } std::string full_name() const { return m_first + " " + m_last; }
void age(unsigned short age) { m_age = age; } void age(unsigned short age) { m_age = age; }
private: private:
friend class odb::access; friend class odb::access;
private:
#pragma db id auto #pragma db id auto
quint64 m_id; unsigned long long m_id;
QString m_firstName; std::string m_first;
QString m_lastName; std::string m_last;
quint8 m_age; unsigned short m_age;
}; };
#pragma db view object(Author_S) #pragma db view object(Author_S)

View File

@@ -4,23 +4,23 @@
#ifndef BOOK_S_H #ifndef BOOK_S_H
#define BOOK_S_H #define BOOK_S_H
#include "database_global.h" // #include <QtCore/QObject>
#include <memory>
#include <string>
#include <QSharedPointer>
#include <QString>
#include <odb/core.hxx> #include <odb/core.hxx>
#include <rcore/smarttypes.h>
#include "author_s.h" #include "author_s.h"
#pragma db object #pragma db object
class DATABASE_EXPORT Book_S class __attribute__((visibility("default"))) Book_S
{ {
public: public:
Book_S() = default; Book_S() = default;
Book_S(const QString& name, Book_S(const std::string& name,
const SH<Author_S>& author, const std::shared_ptr<Author_S>& author,
const int year) const int year)
{ {
m_author = author; m_author = author;
@@ -29,8 +29,8 @@ public:
}; };
unsigned long long id() const { return m_id; } unsigned long long id() const { return m_id; }
SH<Author_S> author() const { return m_author; } std::shared_ptr<Author_S> author() const { return m_author; }
QString name() const { return m_name; } std::string name() const { return m_name; }
int year() const { return m_year; } int year() const { return m_year; }
private: private:
@@ -38,27 +38,11 @@ private:
private: private:
#pragma db id auto #pragma db id auto
quint64 m_id; unsigned long long m_id;
SH<Author_S> m_author; std::shared_ptr<Author_S> m_author;
QString m_name; std::string m_name;
quint8 m_year; int 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 #endif // BOOK_S_H

View File

@@ -34,20 +34,16 @@
#include <filesystem> #include <filesystem>
#include <random> #include <random>
#include <rcore/smarttypes.h>
using oDBase = odb::sqlite::database;
using uDBase = U<oDBase>;
struct testData struct testData
{ {
QString first; std::string first;
QString last; std::string last;
int age; int age;
}; };
// Функция для генерации случайной строки (имени или фамилии) // Функция для генерации случайной строки (имени или фамилии)
QString generate_random_string(const QVector<QString>& pool) std::string generate_random_string(const std::vector<std::string>& pool)
{ {
static std::random_device rd; static std::random_device rd;
static std::mt19937 gen(rd()); static std::mt19937 gen(rd());
@@ -64,16 +60,16 @@ int generate_random_year(int min_year = 1900, int max_year = 2020)
return dis(gen); return dis(gen);
} }
QVector<testData> fillDB() std::vector<testData> fillDB()
{ {
QVector<QString> first_names = { std::vector<std::string> first_names = {
"John", "Jane", "Alex", "Chris", "Robert", "Emily", "James", "Linda", "David", "Sarah", "John", "Jane", "Alex", "Chris", "Robert", "Emily", "James", "Linda", "David", "Sarah",
"Michael", "Elizabeth", "Daniel", "Samantha", "William", "Olivia", "Ethan", "Sophia", "Joshua", "Charlotte", "Michael", "Elizabeth", "Daniel", "Samantha", "William", "Olivia", "Ethan", "Sophia", "Joshua", "Charlotte",
"Daniel", "Grace", "Benjamin", "Isabella", "Matthew", "Victoria", "Henry", "Abigail", "Samuel", "Megan", "Daniel", "Grace", "Benjamin", "Isabella", "Matthew", "Victoria", "Henry", "Abigail", "Samuel", "Megan",
"Lucas", "Lily", "Andrew", "Madison", "Jackson", "Chloe", "Aiden", "Amelia", "Thomas", "Natalie", "Lucas", "Lily", "Andrew", "Madison", "Jackson", "Chloe", "Aiden", "Amelia", "Thomas", "Natalie",
"Ryan", "Zoe", "Jack", "Harper", "Elijah", "Ava", "Isaac", "Mia", "Caleb", "Ella" "Ryan", "Zoe", "Jack", "Harper", "Elijah", "Ava", "Isaac", "Mia", "Caleb", "Ella"
}; };
QVector<QString> last_names = { std::vector<std::string> last_names = {
"Doe", "Smith", "Johnson", "Williams", "Jones", "Brown", "Davis", "Miller", "Wilson", "Moore", "Doe", "Smith", "Johnson", "Williams", "Jones", "Brown", "Davis", "Miller", "Wilson", "Moore",
"Taylor", "Anderson", "Thomas", "Jackson", "White", "Harris", "Martin", "Thompson", "Garcia", "Martinez", "Taylor", "Anderson", "Thomas", "Jackson", "White", "Harris", "Martin", "Thompson", "Garcia", "Martinez",
"Roberts", "Clark", "Lewis", "Walker", "Young", "Allen", "King", "Wright", "Scott", "Adams", "Roberts", "Clark", "Lewis", "Walker", "Young", "Allen", "King", "Wright", "Scott", "Adams",
@@ -81,12 +77,12 @@ QVector<testData> fillDB()
"Rogers", "Gutierrez", "Ramirez", "Diaz", "Perez", "Ross", "Sanders", "Price", "Howard", "Cooper" "Rogers", "Gutierrez", "Ramirez", "Diaz", "Perez", "Ross", "Sanders", "Price", "Howard", "Cooper"
}; };
QVector<testData> vecTest; std::vector<testData> vecTest;
for (int i = 0; i < 50; ++i) for (int i = 0; i < 50; ++i)
{ {
QString first_name = generate_random_string(first_names); std::string first_name = generate_random_string(first_names);
QString last_name = generate_random_string(last_names); std::string last_name = generate_random_string(last_names);
int birth_year = generate_random_year(1900, 2000); int birth_year = generate_random_year(1900, 2000);
vecTest.push_back({ first_name, last_name, birth_year }); vecTest.push_back({ first_name, last_name, birth_year });
@@ -95,23 +91,21 @@ QVector<testData> fillDB()
return vecTest; return vecTest;
} }
inline uDBase openDB(const std::string path_db) inline std::unique_ptr<odb::database> openDB(std::string path_db)
{ {
// Открыть БД, если она существует // Открыть БД, если она существует
auto db_ptr = new oDBase(path_db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);
if (std::filesystem::is_regular_file(path_db)) if (std::filesystem::is_regular_file(path_db))
return uDBase(db_ptr); return std::unique_ptr<odb::core::database>(new odb::sqlite::database(path_db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE));
// И создать новую, если не существует // И создать новую, если не существует
uDBase db(db_ptr); std::unique_ptr<odb::core::database> db(new odb::sqlite::database(path_db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE));
odb::connection_ptr connect_ptr(db->connection()); odb::core::connection_ptr connect_ptr(db->connection());
connect_ptr->execute("PRAGMA foreign_keys=OFF"); connect_ptr->execute("PRAGMA foreign_keys=OFF");
odb::transaction tans(db->begin()); odb::core::transaction tans(db->begin());
odb::schema_catalog::create_schema(*db); odb::core::schema_catalog::create_schema(*db);
tans.commit(); tans.commit();
connect_ptr->execute("PRAGMA foreign_keys=ON"); connect_ptr->execute("PRAGMA foreign_keys=ON");

View File

@@ -8,48 +8,45 @@ PSLibrary {
// You can make your code fail to compile if it uses deprecated APIs. // You can make your code fail to compile if it uses deprecated APIs.
// In order to do so, uncomment the following line. // In order to do so, uncomment the following line.
//"QT_DISABLE_DEPRECATED_BEFORE=0x060000" // disables all the APIs deprecated before Qt 6.0.0 //"QT_DISABLE_DEPRECATED_BEFORE=0x060000" // disables all the APIs deprecated before Qt 6.0.0
"DATABASE_SQLITE", "DATABASE_SQLITE"
"DATABASE_LIBRARY"
] ]
consoleApplication: true consoleApplication: true
Depends { name: "Qt"; submodules: [ "core", "sql", "network" ] } Depends { name: "Qt"; submodules: [ "core", "sql", "network" ] }
Depends { name: "cpp" } Depends { name: "cpp" }
Depends { name: "odbModule"}
Depends { name: "odb.gen" } cpp.cxxLanguageVersion: "c++20"
Depends { name: "rdbase" }
Depends { name: "redkit_gen" }
redkit_gen.includeModules: ["JsonSerializer"]
odb.gen.databases: "sqlite"
cpp.cxxLanguageVersion: "c++17"
Group { Group {
name: "cpp" name: "cpp"
files: [ files: [
"books.*",
"databasemanager.*", "databasemanager.*",
"*.cpp",
"*.h",
"*.hxx",
] ]
excludeFiles: odbs.files
} }
Group { Group {
id: odbs
name: "odb" name: "odb"
files: [ files: [
"author_s.h", "author_s.h",
"book_s.h", "book_s.h",
] ]
fileTags: ["hpp", "odbxx"] fileTags: ["odb"]
} }
cpp.includePaths: [
"/usr/include", // Общие заголовки
"/usr/include/odb" // Заголовки ODB
]
// Подключаем библиотеки ODB
cpp.libraryPaths: [
"/usr/lib" // Путь к библиотекам
]
cpp.dynamicLibraries: [ cpp.dynamicLibraries: [
"odb-sqlite",
"odb-qt",
"odb", "odb",
"sqlite3" "odb-sqlite"
] ]
} }

View File

@@ -1,12 +0,0 @@
#ifndef DATABASE_GLOBAL_H
#define DATABASE_GLOBAL_H
#include <QtCore/qglobal.h>
#if defined(DATABASE_LIBRARY)
#define DATABASE_EXPORT Q_DECL_EXPORT
#else
#define DATABASE_EXPORT Q_DECL_IMPORT
#endif
#endif // DATABASE_GLOBAL_H

View File

@@ -1,8 +1,6 @@
#ifndef DATABASEMANAGER_H #ifndef DATABASEMANAGER_H
#define DATABASEMANAGER_H #define DATABASEMANAGER_H
#include "database_global.h"
#include <QDebug> #include <QDebug>
#include <QtSql> #include <QtSql>
@@ -37,7 +35,7 @@ struct SelectBuilder
} }
}; };
class DATABASE_EXPORT DatabaseManager class Q_DECL_EXPORT DatabaseManager
{ {
public: public:
static DatabaseManager& instance(); // Singleton static DatabaseManager& instance(); // Singleton

View File

@@ -1,10 +1,5 @@
#include <QCoreApplication> #include <QCoreApplication>
#include <QPointer>
#include <QSharedPointer>
#include <QString>
#include <QVector>
#include <restapi/restapiserver.h> #include <restapi/restapiserver.h>
/* Опыты с odb */ /* Опыты с odb */
@@ -17,34 +12,36 @@
#include <iostream> #include <iostream>
void fillBooksBD(uDBase& db) using unidb = std::unique_ptr<odb::database>;
void fillBooksBD(unidb& db)
{ {
try try
{ {
QVector<SH<Author_S>> authors = { std::vector<std::shared_ptr<Author_S>> authors = {
SH<Author_S>::create("George", "Orwell", 142), std::make_shared<Author_S>("George", "Orwell", 142),
SH<Author_S>::create("J.K.", "Rowling", 56), std::make_shared<Author_S>("J.K.", "Rowling", 56),
SH<Author_S>::create("J.R.R.", "Tolkien", 81), std::make_shared<Author_S>("J.R.R.", "Tolkien", 81),
SH<Author_S>::create("Leo", "Tolstoy", 189), std::make_shared<Author_S>("Leo", "Tolstoy", 189),
SH<Author_S>::create("Fyodor", "Dostoevsky", 174), std::make_shared<Author_S>("Fyodor", "Dostoevsky", 174),
SH<Author_S>::create("Mark", "Twain", 183), std::make_shared<Author_S>("Mark", "Twain", 183),
SH<Author_S>::create("Charles", "Dickens", 208), std::make_shared<Author_S>("Charles", "Dickens", 208),
SH<Author_S>::create("Virginia", "Woolf", 134), std::make_shared<Author_S>("Virginia", "Woolf", 134),
SH<Author_S>::create("Ernest", "Hemingway", 122), std::make_shared<Author_S>("Ernest", "Hemingway", 122),
SH<Author_S>::create("Gabriel", "García Márquez", 98), std::make_shared<Author_S>("Gabriel", "García Márquez", 98),
SH<Author_S>::create("Franz", "Kafka", 100), std::make_shared<Author_S>("Franz", "Kafka", 100),
SH<Author_S>::create("Harper", "Lee", 64), std::make_shared<Author_S>("Harper", "Lee", 64),
SH<Author_S>::create("William", "Shakespeare", 459), std::make_shared<Author_S>("William", "Shakespeare", 459),
SH<Author_S>::create("Oscar", "Wilde", 155), std::make_shared<Author_S>("Oscar", "Wilde", 155),
SH<Author_S>::create("Aldous", "Huxley", 123), std::make_shared<Author_S>("Aldous", "Huxley", 123),
SH<Author_S>::create("Jane", "Austen", 210), std::make_shared<Author_S>("Jane", "Austen", 210),
SH<Author_S>::create("John", "Steinbeck", 116), std::make_shared<Author_S>("John", "Steinbeck", 116),
SH<Author_S>::create("Agatha", "Christie", 124), std::make_shared<Author_S>("Agatha", "Christie", 124),
SH<Author_S>::create("Isaac", "Asimov", 105) std::make_shared<Author_S>("Isaac", "Asimov", 105)
}; };
// Список книг // Список книг
QVector<Book_S> books = { std::vector<Book_S> books = {
Book_S("1984", authors[0], 1949), Book_S("1984", authors[0], 1949),
Book_S("Harry Potter and the Philosopher's Stone", authors[1], 1997), Book_S("Harry Potter and the Philosopher's Stone", authors[1], 1997),
Book_S("The Hobbit", authors[2], 1937), Book_S("The Hobbit", authors[2], 1937),
@@ -101,7 +98,7 @@ void fillBooksBD(uDBase& db)
{ {
odb::core::transaction t(db->begin()); odb::core::transaction t(db->begin());
for (auto& author : authors) for (auto& author : authors)
db->persist(author); // Используем get() для получения сырого указателя db->persist(author.get()); // Используем get() для получения сырого указателя
t.commit(); t.commit();
} }
@@ -126,9 +123,8 @@ int main(int argc, char* argv[])
QCoreApplication a(argc, argv); QCoreApplication a(argc, argv);
const std::string dbPath = "test_db.sqlite"; const std::string dbPath = "test_db.sqlite";
uDBase db(openDB(dbPath)); std::unique_ptr<odb::database> db(openDB(dbPath));
// TODO Как-то нужно выполнять лишь раз
// fillBooksBD(db); // fillBooksBD(db);
RestApiServer server(*db); RestApiServer server(*db);

View File

@@ -3,7 +3,7 @@
\inherits Project \inherits Project
\brief Описание \brief Описание
*/ */
WPSLibrary { PSLibrary {
cpp.defines: [ cpp.defines: [
// You can make your code fail to compile if it uses deprecated APIs. // You can make your code fail to compile if it uses deprecated APIs.
// In order to do so, uncomment the following line. // In order to do so, uncomment the following line.
@@ -15,9 +15,10 @@ WPSLibrary {
Depends { name: "Qt"; submodules: [ "core", "sql", "network" ] } Depends { name: "Qt"; submodules: [ "core", "sql", "network" ] }
Depends { name: "cpp" } Depends { name: "cpp" }
Depends { name: "database" } Depends { name: "database" }
Depends { name: "odb.gen" } Depends { name: "odbModule"}
Depends { name: "redkit_gen" }
Depends { name: "rdbase" }
// Depends { name: "redkit_gen" }
cpp.cxxLanguageVersion: "c++20" cpp.cxxLanguageVersion: "c++20"
@@ -27,12 +28,4 @@ WPSLibrary {
"restapiserver.*", "restapiserver.*",
] ]
} }
cpp.dynamicLibraries: [
"odb-sqlite",
"odb-qt",
"odb",
"sqlite3"
]
} // Project } // Project

View File

@@ -5,17 +5,14 @@
#include <QJsonObject> #include <QJsonObject>
#include <QJsonValue> #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 <database/book_s.h>
#include "database/book_s-odb.hxx"
#include <odb/core.hxx> #include <odb/core.hxx>
#include <odb/database.hxx> #include <odb/database.hxx>
#include <odb/query.hxx> #include <odb/query.hxx>
#include <redkit-gen-modules/json_serializer.h>
RestApiServer::RestApiServer(odb::database& db, QObject* parent) : RestApiServer::RestApiServer(odb::database& db, QObject* parent) :
QTcpServer(parent), m_db(db) {} QTcpServer(parent), m_db(db) {}
@@ -27,8 +24,7 @@ void RestApiServer::start(quint16 port)
} }
else else
{ {
QString addrs = "http://127.0.0.1:" + QString::number(this->serverPort()); qDebug() << "REST API сервер запущен на порту:" << port;
qDebug() << "REST API сервер запущен по адресу:" << addrs;
} }
} }
@@ -39,8 +35,6 @@ void RestApiServer::incomingConnection(qintptr socketDescriptor)
connect(socket, &QTcpSocket::readyRead, this, &RestApiServer::handleRequest); connect(socket, &QTcpSocket::readyRead, this, &RestApiServer::handleRequest);
connect(socket, &QTcpSocket::disconnected, socket, &QTcpSocket::deleteLater); connect(socket, &QTcpSocket::disconnected, socket, &QTcpSocket::deleteLater);
qWarning() << "Есть входящее подключение" << socket->socketDescriptor();
} }
void RestApiServer::handleRequest() void RestApiServer::handleRequest()
@@ -59,41 +53,28 @@ void RestApiServer::handleRequest()
QByteArray RestApiServer::processRequest(const QString& request) QByteArray RestApiServer::processRequest(const QString& request)
{ {
qWarning() << request << "\n\n";
if (request.startsWith("GET /books/author/")) if (request.startsWith("GET /books/author/"))
{ {
QString author = request.section(' ', 1, 1).section('/', 3, 3).replace("%20", " "); QString author = request.section(' ', 1, 1).section('/', 3, 3).replace("%20", " ");
quint64 ageReq = author.toInt();
QStringList nameParts = author.split(' '); // Books books;
QString firstName = nameParts.size() > 0 ? nameParts[0] : ""; // QList<BookRecord> results = books.getBooksByAuthor(author);
QString lastName = nameParts.size() > 1 ? nameParts[1] : "";
qWarning() QByteArray jsonResponse = "{ \"books\": [";
<< "author:" << author << "\n" // for (const BookRecord& book : results)
<< "firstName:" << firstName << "\n" // {
<< "lastName:" << lastName << "\n"; // jsonResponse += QString("{ \"id\": %1, \"title\": \"%2\", \"author\": \"%3\", \"year\": %4 },")
// .arg(book.id)
// .arg(book.title)
// .arg(book.author)
// .arg(book.year)
// .toUtf8();
// }
// if (results.size() > 0)
// jsonResponse.chop(1); // Убираем последнюю запятую
// jsonResponse += "] }";
odb::transaction t(m_db.begin()); return "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n" + jsonResponse;
auto books = m_db.query<Book_S>(odb::query<Book_S>::author->id == ageReq);
QJsonArray jArray;
for (const auto& book : books)
{
QJsonObject j;
j["id"] = QString::number(book.id());
j["name"] = book.name();
j["author"] = book.author()->full_name();
j["year"] = book.year();
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);
} }
if (request.startsWith("GET /books")) if (request.startsWith("GET /books"))
@@ -109,8 +90,8 @@ QByteArray RestApiServer::processRequest(const QString& request)
QJsonObject j; QJsonObject j;
j["id"] = QString::number(book.id()); j["id"] = QString::number(book.id());
j["title"] = book.name(); j["title"] = QString::fromStdString(book.name());
j["author"] = book.author()->full_name(); j["author"] = QString::fromStdString(book.author()->full_name());
j["year"] = book.year(); j["year"] = book.year();
jArray.push_back(j); jArray.push_back(j);
} }
@@ -134,8 +115,8 @@ QByteArray RestApiServer::processRequest(const QString& request)
QJsonObject j; QJsonObject j;
j["id"] = QString::number(author.id()); j["id"] = QString::number(author.id());
j["first"] = author.firstName(); j["first"] = QString::fromStdString(author.first());
j["last"] = author.lastName(); j["last"] = QString::fromStdString(author.last());
j["age"] = author.age(); j["age"] = author.age();
jArray.push_back(j); jArray.push_back(j);
} }