Compare commits
1 Commits
8cb56837f5
...
docker
| Author | SHA1 | Date | |
|---|---|---|---|
| 689b8dea7c |
3
.gitmodules
vendored
3
.gitmodules
vendored
@@ -1,6 +1,3 @@
|
|||||||
[submodule "redkbuild"]
|
[submodule "redkbuild"]
|
||||||
path = redkbuild
|
path = redkbuild
|
||||||
url = git@gitea.redkit-lab.work: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
|
|
||||||
|
|||||||
33
Dockerfile
Normal file
33
Dockerfile
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
# Используем образ с поддержкой Qt и инструментов сборки
|
||||||
|
FROM nexus.redkit-lab.ru:8084/rkl/dev-scada-debian-10:v1.1
|
||||||
|
|
||||||
|
RUN apt update && apt upgrade -y && apt-get clean -y && apt-get autoremove --purge -y
|
||||||
|
|
||||||
|
# Создаем пользователя, дабы выходящие файлы не были под root
|
||||||
|
# ENV USER_NAME=ubuilder
|
||||||
|
# RUN adduser $USER_NAME; \
|
||||||
|
# usermod -aG sudo $USER_NAME; \
|
||||||
|
# echo "$USER_NAME:123" | chpasswd
|
||||||
|
# USER $USER_NAME
|
||||||
|
# ENV HOME=/home/$USER_NAME
|
||||||
|
# WORKDIR $HOME
|
||||||
|
|
||||||
|
RUN qbs config defaultProfile qt_clang19_51513
|
||||||
|
|
||||||
|
# Создаем рабочую директорию
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Копируем локальный код в контейнер
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# Собираем проект
|
||||||
|
# RUN qbs setup-toolchains --type gcc /usr/bin/g++ gcc && \
|
||||||
|
# qbs setup-qt /usr/lib/qt5/bin/qmake qt5 && \
|
||||||
|
# qbs resolve && \
|
||||||
|
# qbs build --jobs $(nproc)
|
||||||
|
|
||||||
|
# Указываем команду для запуска приложения
|
||||||
|
# CMD ["./dockertools/run.sh"]
|
||||||
|
# CMD ["/bin/bash"]
|
||||||
|
|
||||||
|
|
||||||
16
docker-compose.yml
Normal file
16
docker-compose.yml
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
services:
|
||||||
|
cpp_opds:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
image: cpp_opds:latest
|
||||||
|
container_name: cpp_opds
|
||||||
|
ports:
|
||||||
|
- "8000:80"
|
||||||
|
volumes:
|
||||||
|
- .:/app
|
||||||
|
environment:
|
||||||
|
- ENV_VAR=value
|
||||||
|
restart: unless-stopped
|
||||||
0
dockertools/run.sh
Normal file
0
dockertools/run.sh
Normal file
@@ -1,8 +0,0 @@
|
|||||||
import qbs
|
|
||||||
|
|
||||||
Export {
|
|
||||||
Depends { name: "cpp" }
|
|
||||||
Depends { name: "rsc.sqlite.settings" }
|
|
||||||
|
|
||||||
rsc.sqlite.settings.includeRegexValues: exportingProduct.includeRegexValue
|
|
||||||
}
|
|
||||||
@@ -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
|
|
||||||
}
|
|
||||||
13
project.qbs
13
project.qbs
@@ -3,19 +3,16 @@ import qbs
|
|||||||
Project {
|
Project {
|
||||||
name: "opds++"
|
name: "opds++"
|
||||||
qbsSearchPaths: [
|
qbsSearchPaths: [
|
||||||
"redkitty/qbs",
|
"redkbuild"
|
||||||
"redkbuild",
|
|
||||||
"redkitty/lib/redkit-gen-integration/qbs",
|
|
||||||
"prerequisites/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/model/model.qbs",
|
|
||||||
"src/restapi/restapi.qbs",
|
"src/restapi/restapi.qbs",
|
||||||
|
"src/model/model.qbs",
|
||||||
|
"src/repositories/repositories.qbs",
|
||||||
|
"src/services/services.qbs",
|
||||||
|
"src/sql_builder/sql_builder.qbs",
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
Submodule redkbuild updated: 3adf92aad6...9f3a81cc23
1
redkitty
1
redkitty
Submodule redkitty deleted from 2316ddea72
@@ -1,43 +1,27 @@
|
|||||||
/*!
|
/*!
|
||||||
\qmltype cpp-opds
|
\qmltype cpp-opds
|
||||||
\inherits Project
|
\inherits Application
|
||||||
\brief Описание
|
\brief Описание
|
||||||
*/
|
*/
|
||||||
PSApplication {
|
PSApplication {
|
||||||
// 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.
|
// 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"
|
consoleApplication: true
|
||||||
|
|
||||||
|
// Depends { name: "Qt"; submodules: [ "core", "sql", "network" ] }
|
||||||
|
Depends { name: "Qt"; submodules: ["core", "sql", "network"] }
|
||||||
|
Depends { name: "cpp" }
|
||||||
|
Depends { name: "database" }
|
||||||
|
Depends { name: "services" }
|
||||||
|
Depends { name: "restapi" }
|
||||||
|
|
||||||
|
Group {
|
||||||
|
name: "cpp"
|
||||||
|
files: [
|
||||||
|
"main.cpp",
|
||||||
]
|
]
|
||||||
consoleApplication: true
|
}
|
||||||
|
} // Application
|
||||||
Depends { name: "Qt"; submodules: [ "core", "sql", "network" ] }
|
|
||||||
Depends { name: "cpp" }
|
|
||||||
Depends { name: "database" }
|
|
||||||
Depends { name: "odb.gen" }
|
|
||||||
Depends { name: "sqlite3" }
|
|
||||||
Depends { name: "restapi" }
|
|
||||||
Depends { name: "redkit_gen" }
|
|
||||||
Depends { name: "rdbase" }
|
|
||||||
Depends { name: "model" }
|
|
||||||
|
|
||||||
cpp.cxxLanguageVersion: "c++20"
|
|
||||||
|
|
||||||
Group {
|
|
||||||
name: "cpp"
|
|
||||||
files: [
|
|
||||||
"main.cpp",
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
cpp.dynamicLibraries: [
|
|
||||||
"odb-sqlite",
|
|
||||||
"odb-qt",
|
|
||||||
"odb",
|
|
||||||
"sqlite3"
|
|
||||||
]
|
|
||||||
|
|
||||||
// }
|
|
||||||
} // Project
|
|
||||||
|
|||||||
@@ -1,105 +0,0 @@
|
|||||||
// file : hello/database.hxx
|
|
||||||
// copyright : not copyrighted - public domain
|
|
||||||
|
|
||||||
//
|
|
||||||
// Create concrete database instance based on the DATABASE_* macros.
|
|
||||||
//
|
|
||||||
|
|
||||||
#ifndef DATABASE_HXX
|
|
||||||
#define DATABASE_HXX
|
|
||||||
|
|
||||||
#include <cstdlib> // std::exit
|
|
||||||
#include <iostream>
|
|
||||||
#include <memory> // std::unique_ptr
|
|
||||||
#include <string>
|
|
||||||
|
|
||||||
#include <filesystem>
|
|
||||||
|
|
||||||
#include "database_utils.h"
|
|
||||||
|
|
||||||
inline uDBase openDB(const 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))
|
|
||||||
return uDBase(db_ptr);
|
|
||||||
|
|
||||||
// И создать новую, если не существует
|
|
||||||
uDBase db(db_ptr);
|
|
||||||
|
|
||||||
odb::connection_ptr connect_ptr(db->connection());
|
|
||||||
|
|
||||||
connect_ptr->execute("PRAGMA foreign_keys=OFF");
|
|
||||||
|
|
||||||
odb::transaction tans(db->begin());
|
|
||||||
odb::schema_catalog::create_schema(*db);
|
|
||||||
tans.commit();
|
|
||||||
|
|
||||||
connect_ptr->execute("PRAGMA foreign_keys=ON");
|
|
||||||
|
|
||||||
return db;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline std::unique_ptr<odb::database> create_database(int& argc, char* argv[])
|
|
||||||
{
|
|
||||||
using namespace std;
|
|
||||||
using namespace odb::core;
|
|
||||||
|
|
||||||
if (argc > 1 && argv[1] == string("--help"))
|
|
||||||
{
|
|
||||||
cout << "Usage: " << argv[0] << " [options]" << endl
|
|
||||||
<< "Options:" << endl;
|
|
||||||
|
|
||||||
#if defined(DATABASE_MYSQL)
|
|
||||||
odb::mysql::database::print_usage(cout);
|
|
||||||
#elif defined(DATABASE_SQLITE)
|
|
||||||
odb::sqlite::database::print_usage(cout);
|
|
||||||
#elif defined(DATABASE_PGSQL)
|
|
||||||
odb::pgsql::database::print_usage(cout);
|
|
||||||
#elif defined(DATABASE_ORACLE)
|
|
||||||
odb::oracle::database::print_usage(cout);
|
|
||||||
#elif defined(DATABASE_MSSQL)
|
|
||||||
odb::mssql::database::print_usage(cout);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
exit(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
#if defined(DATABASE_MYSQL)
|
|
||||||
unique_ptr<database> db(new odb::mysql::database(argc, argv));
|
|
||||||
#elif defined(DATABASE_SQLITE)
|
|
||||||
|
|
||||||
unique_ptr<database> db(new odb::sqlite::database(argc,
|
|
||||||
argv,
|
|
||||||
false,
|
|
||||||
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE));
|
|
||||||
|
|
||||||
// Create the database schema. Due to bugs in SQLite foreign key
|
|
||||||
// support for DDL statements, we need to temporarily disable
|
|
||||||
// foreign keys.
|
|
||||||
//
|
|
||||||
{
|
|
||||||
connection_ptr connect_ptr(db->connection());
|
|
||||||
|
|
||||||
connect_ptr->execute("PRAGMA foreign_keys=OFF");
|
|
||||||
|
|
||||||
transaction tans(connect_ptr->begin());
|
|
||||||
schema_catalog::create_schema(*db);
|
|
||||||
tans.commit();
|
|
||||||
|
|
||||||
connect_ptr->execute("PRAGMA foreign_keys=ON");
|
|
||||||
}
|
|
||||||
#elif defined(DATABASE_PGSQL)
|
|
||||||
unique_ptr<database> db(new odb::pgsql::database(argc, argv));
|
|
||||||
#elif defined(DATABASE_ORACLE)
|
|
||||||
unique_ptr<database> db(new odb::oracle::database(argc, argv));
|
|
||||||
#elif defined(DATABASE_MSSQL)
|
|
||||||
unique_ptr<database> db(
|
|
||||||
new odb::mssql::database(argc, argv, false, "TrustServerCertificate=yes"));
|
|
||||||
#endif
|
|
||||||
|
|
||||||
return db;
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif // DATABASE_HXX
|
|
||||||
@@ -1,43 +1,16 @@
|
|||||||
/*!
|
import qbs
|
||||||
\qmltype cpp-opds
|
|
||||||
\inherits Project
|
|
||||||
\brief Описание
|
|
||||||
*/
|
|
||||||
PSLibrary {
|
PSLibrary {
|
||||||
cpp.defines: [
|
Depends { name: "Qt"; submodules: "sql"}
|
||||||
// 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",
|
|
||||||
"DATABASE_LIBRARY"
|
|
||||||
]
|
|
||||||
consoleApplication: true
|
|
||||||
|
|
||||||
Depends { name: "Qt"; submodules: [ "core", "network" ] }
|
|
||||||
Depends { name: "cpp" }
|
|
||||||
|
|
||||||
Depends { name: "odb.gen" }
|
|
||||||
Depends { name: "rdbase" }
|
|
||||||
Depends { name: "model" }
|
Depends { name: "model" }
|
||||||
|
Depends { name: "sql_builder" }
|
||||||
Depends { name: "redkit_gen" }
|
|
||||||
|
|
||||||
odb.gen.databases: "sqlite"
|
|
||||||
cpp.cxxLanguageVersion: "c++17"
|
|
||||||
|
|
||||||
Group {
|
Group {
|
||||||
name: "cpp"
|
name: "cpp"
|
||||||
files: [
|
files: [
|
||||||
"**/*.h",
|
"**/*.h",
|
||||||
"**/*.hxx",
|
"**/*.cpp"
|
||||||
"**/*.cpp",
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
cpp.dynamicLibraries: [
|
|
||||||
"odb-sqlite",
|
|
||||||
"odb-qt",
|
|
||||||
"odb",
|
|
||||||
"sqlite3"
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
#include "database_utils.h"
|
|
||||||
|
|
||||||
void addBook(oDBase& db, const QString title, const QVector<QString>& authors)
|
|
||||||
{
|
|
||||||
odb::transaction t(db.begin());
|
|
||||||
try
|
|
||||||
{
|
|
||||||
// 1. Создаем/получаем книгу
|
|
||||||
auto books = db.query<Book_S>(odb::query<Book_S>::title == title);
|
|
||||||
SH<Book_S> book;
|
|
||||||
|
|
||||||
if (books.empty())
|
|
||||||
{
|
|
||||||
book = SH<Book_S>::create();
|
|
||||||
book->setTitle(title);
|
|
||||||
|
|
||||||
db.persist(book);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
book = books.begin().load(); // Берем первую найденную книгу
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. Обрабатываем авторов
|
|
||||||
for (const auto& name : authors)
|
|
||||||
{
|
|
||||||
auto authors = db.query<Author_S>(odb::query<Author_S>::fullName == name);
|
|
||||||
SH<Author_S> author = authors.empty() ? SH<Author_S>::create() : authors.begin().load();
|
|
||||||
|
|
||||||
if (authors.empty())
|
|
||||||
{
|
|
||||||
author->setFullName(name);
|
|
||||||
db.persist(author);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Проверяем и создаем связь
|
|
||||||
|
|
||||||
auto links = db.query<AuthorBook_S>(
|
|
||||||
odb::query<AuthorBook_S>::author->id == author->id()
|
|
||||||
&& odb::query<AuthorBook_S>::book->id == book->id());
|
|
||||||
|
|
||||||
if (links.empty())
|
|
||||||
{
|
|
||||||
db.persist(SH<AuthorBook_S>::create(author, book));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
t.commit();
|
|
||||||
}
|
|
||||||
catch (...)
|
|
||||||
{
|
|
||||||
t.rollback();
|
|
||||||
throw;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
#include <QDebug>
|
|
||||||
#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>;
|
|
||||||
|
|
||||||
#include <model/author_book_s-odb.hxx>
|
|
||||||
#include <model/author_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>
|
|
||||||
|
|
||||||
void DATABASE_EXPORT addBook(oDBase& db, const QString title, const QVector<QString>& authors);
|
|
||||||
38
src/database/databasemanager.cpp
Normal file
38
src/database/databasemanager.cpp
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
#include "databasemanager.h"
|
||||||
|
|
||||||
|
#include <model/author.h>
|
||||||
|
#include <model/book.h>
|
||||||
|
|
||||||
|
DatabaseManager::DatabaseManager() {}
|
||||||
|
|
||||||
|
DatabaseManager::~DatabaseManager()
|
||||||
|
{
|
||||||
|
if (db.isOpen())
|
||||||
|
db.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
DatabaseManager& DatabaseManager::instance()
|
||||||
|
{
|
||||||
|
static DatabaseManager instance;
|
||||||
|
return instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool DatabaseManager::connect(const QString& dbPath)
|
||||||
|
{
|
||||||
|
db = QSqlDatabase::addDatabase("QSQLITE");
|
||||||
|
db.setDatabaseName(dbPath);
|
||||||
|
return db.open();
|
||||||
|
}
|
||||||
|
|
||||||
|
QSqlDatabase& DatabaseManager::database()
|
||||||
|
{
|
||||||
|
return db;
|
||||||
|
}
|
||||||
|
|
||||||
|
void DatabaseManager::initializeDatabase()
|
||||||
|
{
|
||||||
|
QSqlQuery query;
|
||||||
|
|
||||||
|
query.exec(model::createTableBook());
|
||||||
|
query.exec(model::createTableAuthor());
|
||||||
|
}
|
||||||
21
src/database/databasemanager.h
Normal file
21
src/database/databasemanager.h
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
#ifndef DATABASEMANAGER_H
|
||||||
|
#define DATABASEMANAGER_H
|
||||||
|
|
||||||
|
#include <QDebug>
|
||||||
|
#include <QtSql>
|
||||||
|
|
||||||
|
class Q_DECL_EXPORT DatabaseManager
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
static DatabaseManager& instance();
|
||||||
|
bool connect(const QString& dbPath);
|
||||||
|
QSqlDatabase& database();
|
||||||
|
void initializeDatabase();
|
||||||
|
|
||||||
|
private:
|
||||||
|
DatabaseManager();
|
||||||
|
~DatabaseManager();
|
||||||
|
QSqlDatabase db;
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif // DATABASEMANAGER_H
|
||||||
143
src/main.cpp
143
src/main.cpp
@@ -1,122 +1,53 @@
|
|||||||
#include <QCoreApplication>
|
#include <QCoreApplication>
|
||||||
|
|
||||||
#include <QPointer>
|
|
||||||
#include <QSharedPointer>
|
|
||||||
#include <QString>
|
|
||||||
#include <QVector>
|
|
||||||
|
|
||||||
#include <restapi/restapiserver.h>
|
#include <restapi/restapiserver.h>
|
||||||
|
|
||||||
/* Опыты с odb */
|
#include <database/databasemanager.h>
|
||||||
#include <database/database.hxx> // create_database
|
|
||||||
#include <database/database_utils.h>
|
|
||||||
#include <odb/database.hxx>
|
|
||||||
|
|
||||||
#include <iostream>
|
#include <services/author_service.h>
|
||||||
|
#include <services/book_service.h>
|
||||||
|
|
||||||
void fillBooksBD(uDBase& db)
|
#include <QDebug>
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
QVector<Author_S> authors = {
|
|
||||||
Author_S("George Orwell", "en"),
|
|
||||||
Author_S("J.K. Rowling", "en"),
|
|
||||||
Author_S("J.R.R. Tolkien", "en"),
|
|
||||||
Author_S("Leo Tolstoy", "ru"),
|
|
||||||
Author_S("Fyodor Dostoevsky", "ru"),
|
|
||||||
Author_S("Mark Twain", "en"),
|
|
||||||
Author_S("Charles Dickens", "en"),
|
|
||||||
Author_S("Virginia Woolf", "en"),
|
|
||||||
Author_S("Ernest Hemingway", "en"),
|
|
||||||
Author_S("Gabriel García Márquez", "en"),
|
|
||||||
Author_S("Franz Kafka", "de"),
|
|
||||||
Author_S("Harper Lee", "en"),
|
|
||||||
Author_S("William Shakespeare", "en"),
|
|
||||||
Author_S("Oscar Wilde", "en"),
|
|
||||||
Author_S("Aldous Huxley", "en"),
|
|
||||||
Author_S("Jane Austen", "en"),
|
|
||||||
Author_S("John Steinbeck", "en"),
|
|
||||||
Author_S("Agatha Christie", "en"),
|
|
||||||
Author_S("Isaac Asimov", "ru"),
|
|
||||||
};
|
|
||||||
|
|
||||||
addBook(*db, "Очень странная книжка", { "Автор 1", "Автор 2", "Авторк 3" });
|
|
||||||
|
|
||||||
addBook(*db, "1984", { authors[0].fullName() });
|
|
||||||
addBook(*db, "Harry Potter and the Philosopher's Stone", { authors[1].fullName() });
|
|
||||||
addBook(*db, "The Hobbit", { authors[2].fullName() });
|
|
||||||
addBook(*db, "War and Peace", { authors[3].fullName() });
|
|
||||||
addBook(*db, "Crime and Punishment", { authors[4].fullName() });
|
|
||||||
addBook(*db, "Adventures of Huckleberry Finn", { authors[5].fullName() });
|
|
||||||
addBook(*db, "A Tale of Two Cities", { authors[6].fullName() });
|
|
||||||
addBook(*db, "Mrs. Dalloway", { authors[7].fullName() });
|
|
||||||
addBook(*db, "The Old Man and the Sea", { authors[8].fullName() });
|
|
||||||
addBook(*db, "One Hundred Years of Solitude", { authors[9].fullName() });
|
|
||||||
addBook(*db, "The Trial", { authors[10].fullName() });
|
|
||||||
addBook(*db, "To Kill a Mockingbird", { authors[11].fullName() });
|
|
||||||
addBook(*db, "Macbeth", { authors[12].fullName() });
|
|
||||||
addBook(*db, "The Picture of Dorian Gray", { authors[13].fullName() });
|
|
||||||
addBook(*db, "Brave New World", { authors[14].fullName() });
|
|
||||||
addBook(*db, "Pride and Prejudice", { authors[15].fullName() });
|
|
||||||
addBook(*db, "The Brothers Karamazov", { authors[4].fullName() });
|
|
||||||
addBook(*db, "The Grapes of Wrath", { authors[16].fullName() });
|
|
||||||
addBook(*db, "Murder on the Orient Express", { authors[17].fullName() });
|
|
||||||
addBook(*db, "I, Robot", { authors[18].fullName() });
|
|
||||||
addBook(*db, "Animal Farm", { authors[0].fullName() });
|
|
||||||
addBook(*db, "Harry Potter and the Chamber of Secrets", { authors[1].fullName() });
|
|
||||||
addBook(*db, "The Lord of the Rings: The Fellowship of the Ring", { authors[2].fullName() });
|
|
||||||
addBook(*db, "Anna Karenina", { authors[3].fullName() });
|
|
||||||
addBook(*db, "The Idiot", { authors[4].fullName() });
|
|
||||||
addBook(*db, "The Adventures of Tom Sawyer", { authors[5].fullName() });
|
|
||||||
addBook(*db, "Oliver Twist", { authors[6].fullName() });
|
|
||||||
addBook(*db, "To the Lighthouse", { authors[7].fullName() });
|
|
||||||
addBook(*db, "For Whom the Bell Tolls", { authors[8].fullName() });
|
|
||||||
addBook(*db, "Love in the Time of Cholera", { authors[9].fullName() });
|
|
||||||
addBook(*db, "The Metamorphosis", { authors[10].fullName() });
|
|
||||||
addBook(*db, "Go Set a Watchman", { authors[11].fullName() });
|
|
||||||
addBook(*db, "King Lear", { authors[12].fullName() });
|
|
||||||
addBook(*db, "The Importance of Being Earnest", { authors[13].fullName() });
|
|
||||||
addBook(*db, "Brave New World Revisited", { authors[14].fullName() });
|
|
||||||
addBook(*db, "Emma", { authors[15].fullName() });
|
|
||||||
addBook(*db, "The Double", { authors[4].fullName() });
|
|
||||||
addBook(*db, "Of Mice and Men", { authors[16].fullName() });
|
|
||||||
addBook(*db, "And Then There Were None", { authors[17].fullName() });
|
|
||||||
addBook(*db, "The Foundation Trilogy", { authors[18].fullName() });
|
|
||||||
addBook(*db, "Down and Out in Paris and London", { authors[0].fullName() });
|
|
||||||
addBook(*db, "Harry Potter and the Prisoner of Azkaban", { authors[1].fullName() });
|
|
||||||
addBook(*db, "The Lord of the Rings: The Two Towers", { authors[2].fullName() });
|
|
||||||
addBook(*db, "War and Peace", { authors[3].fullName() });
|
|
||||||
addBook(*db, "The Brothers Karamazov", { authors[4].fullName() });
|
|
||||||
addBook(*db, "The Prince and the Pauper", { authors[5].fullName() });
|
|
||||||
addBook(*db, "David Copperfield", { authors[6].fullName() });
|
|
||||||
addBook(*db, "The Waves", { authors[7].fullName() });
|
|
||||||
addBook(*db, "A Farewell to Arms", { authors[8].fullName() });
|
|
||||||
addBook(*db, "Chronicle of a Death Foretold", { authors[9].fullName() });
|
|
||||||
|
|
||||||
addBook(*db, "1984", { "George Orwell" });
|
|
||||||
addBook(*db, "Harry Potter and the Philosopher's Stone", { "J.K. Rowling" });
|
|
||||||
|
|
||||||
addBook(*db, "Очень странная книжка 2", { "Автор 4", "Авторк 3" });
|
|
||||||
|
|
||||||
std::cout << "Test data added successfully." << std::endl;
|
|
||||||
}
|
|
||||||
catch (const odb::exception& e)
|
|
||||||
{
|
|
||||||
std::cerr << "Error adding test data: " << e.what() << std::endl;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
int main(int argc, char* argv[])
|
int main(int argc, char* argv[])
|
||||||
{
|
{
|
||||||
QCoreApplication a(argc, argv);
|
QCoreApplication a(argc, argv);
|
||||||
|
|
||||||
const std::string dbPath = "test_db.sqlite";
|
if (!DatabaseManager::instance().connect("library.db"))
|
||||||
uDBase db(openDB(dbPath));
|
{
|
||||||
|
qCritical() << "Ошибка: не удалось подключиться к базе данных!";
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
// TODO Как-то нужно выполнять лишь раз
|
DatabaseManager::instance().initializeDatabase();
|
||||||
fillBooksBD(db);
|
|
||||||
|
|
||||||
RestApiServer server(*db);
|
if (BookService::add({ .title = "Война и мир",
|
||||||
|
.author = { .name = "Лев Толстой" },
|
||||||
|
.filePath = "/books/war_and_peace.epub" }))
|
||||||
|
{
|
||||||
|
qDebug() << "Книга успешно добавлена!";
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
qCritical() << "Ошибка при добавлении книги!";
|
||||||
|
}
|
||||||
|
|
||||||
|
QVector<model::Book> books = BookService::fetchAll();
|
||||||
|
|
||||||
|
for (const model::Book& book : books)
|
||||||
|
{
|
||||||
|
qDebug() << "ID:" << book.id << "Название:" << book.title
|
||||||
|
<< "Автор:" << book.author.name << "Файл:" << book.filePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
QVector<model::Author> authors = AuthorService::fetchAll();
|
||||||
|
|
||||||
|
for (const model::Author& author : authors)
|
||||||
|
{
|
||||||
|
qDebug() << "ID:" << author.id << "Имя:" << author.name;
|
||||||
|
}
|
||||||
|
|
||||||
|
RestApiServer server;
|
||||||
server.start(8080);
|
server.start(8080);
|
||||||
|
|
||||||
// Set up code that uses the Qt event loop here.
|
// Set up code that uses the Qt event loop here.
|
||||||
|
|||||||
56
src/model/author.h
Normal file
56
src/model/author.h
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
#ifndef AUTHOR_H
|
||||||
|
#define AUTHOR_H
|
||||||
|
|
||||||
|
#include <sql_builder/create_table.h>
|
||||||
|
|
||||||
|
#include <QString>
|
||||||
|
|
||||||
|
namespace model
|
||||||
|
{
|
||||||
|
|
||||||
|
namespace authorconst
|
||||||
|
{
|
||||||
|
|
||||||
|
const QString TABLE = "authors";
|
||||||
|
|
||||||
|
const QString ID = "id";
|
||||||
|
const QString NAME = "name";
|
||||||
|
|
||||||
|
// const QString M_AUTHOR_ID = "id";
|
||||||
|
// const QString M_AUTHOR_FIRST_NAME = "first_name";
|
||||||
|
// const QString M_AUTHOR_LAST_NAME = "last_name";
|
||||||
|
// const QString M_AUTHOR_YEAR = "year";
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Author
|
||||||
|
{
|
||||||
|
int id = 0;
|
||||||
|
QString name;
|
||||||
|
// QString firstName;
|
||||||
|
// QString lastName;
|
||||||
|
// QString birthdayYear;
|
||||||
|
};
|
||||||
|
|
||||||
|
static inline QString createTableAuthor()
|
||||||
|
{
|
||||||
|
// query.exec("CREATE TABLE IF NOT EXISTS authors ("
|
||||||
|
// "id INTEGER PRIMARY KEY AUTOINCREMENT,"
|
||||||
|
// "name TEXT UNIQUE NOT NULL"
|
||||||
|
// ")");
|
||||||
|
|
||||||
|
Builder::TableSchema tBuilder(model::authorconst::TABLE);
|
||||||
|
tBuilder.addColumn({ .name = model::authorconst::ID,
|
||||||
|
.type = "INTEGER",
|
||||||
|
.primaryKey = true });
|
||||||
|
|
||||||
|
tBuilder.addColumn({ .name = model::authorconst::NAME,
|
||||||
|
.type = "TEXT",
|
||||||
|
.notNull = true,
|
||||||
|
.unique = true });
|
||||||
|
return tBuilder.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace model
|
||||||
|
|
||||||
|
#endif // AUTHOR_H
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
#ifndef AUTHOR_BOOK_H
|
|
||||||
#define AUTHOR_BOOK_H
|
|
||||||
|
|
||||||
#include "model_global.h"
|
|
||||||
|
|
||||||
#include "author_s.h"
|
|
||||||
#include "book_s.h"
|
|
||||||
|
|
||||||
#pragma db object
|
|
||||||
class MODEL_EXPORT AuthorBook_S
|
|
||||||
{
|
|
||||||
private:
|
|
||||||
AuthorBook_S() = default;
|
|
||||||
|
|
||||||
public:
|
|
||||||
AuthorBook_S(SH<Author_S> author,
|
|
||||||
SH<Book_S> book) :
|
|
||||||
m_author(author),
|
|
||||||
m_book(book) {}
|
|
||||||
|
|
||||||
quint64 id() const { return m_id; }
|
|
||||||
void setId(quint64 newId) { m_id = newId; }
|
|
||||||
|
|
||||||
SH<Author_S> author() const { return m_author; }
|
|
||||||
void setAuthor(const SH<Author_S>& newAuthor) { m_author = newAuthor; }
|
|
||||||
|
|
||||||
SH<Book_S> book() const { return m_book; }
|
|
||||||
void setBook(const SH<Book_S>& newBook) { m_book = newBook; }
|
|
||||||
|
|
||||||
private:
|
|
||||||
friend class odb::access;
|
|
||||||
|
|
||||||
private:
|
|
||||||
#pragma db id auto
|
|
||||||
quint64 m_id;
|
|
||||||
|
|
||||||
#pragma db not_null
|
|
||||||
SH<Author_S> m_author;
|
|
||||||
|
|
||||||
#pragma db not_null
|
|
||||||
SH<Book_S> m_book;
|
|
||||||
|
|
||||||
#pragma db index("author_book_unique") member(m_author) member(m_book) unique
|
|
||||||
};
|
|
||||||
|
|
||||||
#endif // AUTHOR_BOOK_H
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
#ifndef AUTHOR_S_H
|
|
||||||
#define AUTHOR_S_H
|
|
||||||
|
|
||||||
#include "model_global.h"
|
|
||||||
|
|
||||||
// @JsonSerializer
|
|
||||||
class Author_S;
|
|
||||||
|
|
||||||
#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;
|
|
||||||
|
|
||||||
public: // for Redkit-gen
|
|
||||||
#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
|
|
||||||
65
src/model/book.h
Normal file
65
src/model/book.h
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
#ifndef BOOK_H
|
||||||
|
#define BOOK_H
|
||||||
|
|
||||||
|
#include <model/author.h>
|
||||||
|
|
||||||
|
#include <sql_builder/create_table.h>
|
||||||
|
|
||||||
|
#include <QString>
|
||||||
|
|
||||||
|
namespace model
|
||||||
|
{
|
||||||
|
|
||||||
|
namespace bookconst
|
||||||
|
{
|
||||||
|
|
||||||
|
const QString TABLE = "books";
|
||||||
|
|
||||||
|
const QString ID = "id";
|
||||||
|
const QString TITLE = "title";
|
||||||
|
const QString AUTHOR_ID = "author_id";
|
||||||
|
const QString FILEPATH = "file_path";
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Book
|
||||||
|
{
|
||||||
|
int id = 0;
|
||||||
|
QString title;
|
||||||
|
Author author;
|
||||||
|
QString filePath;
|
||||||
|
};
|
||||||
|
|
||||||
|
static inline QString createTableBook()
|
||||||
|
{
|
||||||
|
// query.exec("CREATE TABLE IF NOT EXISTS books ("
|
||||||
|
// "id INTEGER PRIMARY KEY AUTOINCREMENT,"
|
||||||
|
// "title TEXT NOT NULL,"
|
||||||
|
// "file_path TEXT NOT NULL,"
|
||||||
|
// "author_id INTEGER NOT NULL,"
|
||||||
|
// "FOREIGN KEY (author_id) REFERENCES authors(id) ON DELETE CASCADE"
|
||||||
|
// ");");
|
||||||
|
|
||||||
|
Builder::TableSchema tBuilder(model::bookconst::TABLE);
|
||||||
|
tBuilder.addColumn({ .name = model::bookconst::ID,
|
||||||
|
.type = "INTEGER",
|
||||||
|
.primaryKey = true });
|
||||||
|
|
||||||
|
tBuilder.addColumn({ .name = model::bookconst::TITLE,
|
||||||
|
.type = "TEXT",
|
||||||
|
.notNull = true });
|
||||||
|
|
||||||
|
tBuilder.addColumn({ .name = model::bookconst::FILEPATH,
|
||||||
|
.type = "TEXT",
|
||||||
|
.notNull = true });
|
||||||
|
|
||||||
|
tBuilder.addColumn({ .name = model::bookconst::AUTHOR_ID,
|
||||||
|
.type = "INTEGER",
|
||||||
|
.notNull = true,
|
||||||
|
.foreignKeyTable = model::authorconst::TABLE,
|
||||||
|
.foreignKeyColumn = model::authorconst::ID });
|
||||||
|
return tBuilder.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace model
|
||||||
|
#endif // BOOK_H
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
#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
|
|
||||||
{
|
|
||||||
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_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; }
|
|
||||||
|
|
||||||
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;
|
|
||||||
|
|
||||||
// public: // for Redkit-gen
|
|
||||||
private:
|
|
||||||
#pragma db id auto
|
|
||||||
quint64 m_id;
|
|
||||||
|
|
||||||
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
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
#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
|
|
||||||
@@ -1,44 +1,15 @@
|
|||||||
/*!
|
import qbs
|
||||||
\qmltype cpp-opds
|
|
||||||
\inherits Project
|
|
||||||
\brief Описание
|
|
||||||
*/
|
|
||||||
PSLibrary {
|
PSLibrary {
|
||||||
cpp.defines: [
|
Depends { name: "Qt"; submodules: "core", "sql"}
|
||||||
// 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: "sql_builder" }
|
||||||
Depends { name: "cpp" }
|
|
||||||
|
|
||||||
Depends { name: "odb.gen" }
|
|
||||||
Depends { name: "rdbase" }
|
|
||||||
|
|
||||||
Depends { name: "redkit_gen" }
|
|
||||||
redkit_gen.includeModules: [redkit_gen.module.JsonSerializer,
|
|
||||||
redkit_gen.module.SettingsSerializer,]
|
|
||||||
|
|
||||||
odb.gen.databases: "sqlite"
|
|
||||||
cpp.cxxLanguageVersion: "c++17"
|
|
||||||
|
|
||||||
Group {
|
Group {
|
||||||
id: odbs
|
name: "cpp"
|
||||||
name: "odb"
|
|
||||||
files: [
|
files: [
|
||||||
"**/*.h",
|
"*.h",
|
||||||
|
"*.cpp"
|
||||||
]
|
]
|
||||||
fileTags: ["hpp", "odbxx", "rgen"]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
cpp.dynamicLibraries: [
|
|
||||||
"odb-sqlite",
|
|
||||||
"odb-qt",
|
|
||||||
"odb",
|
|
||||||
"sqlite3"
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
#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
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
#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
|
|
||||||
78
src/repositories/author_repository.cpp
Normal file
78
src/repositories/author_repository.cpp
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
// #define BUILD_REPOSITORIES
|
||||||
|
#include "author_repository.h"
|
||||||
|
|
||||||
|
#include <sql_builder/insert.h>
|
||||||
|
#include <sql_builder/select.h>
|
||||||
|
|
||||||
|
#include <QDebug>
|
||||||
|
|
||||||
|
QVector<model::Author> AuthorRepository::getAll()
|
||||||
|
{
|
||||||
|
QVector<model::Author> authors;
|
||||||
|
|
||||||
|
Builder::Select sBuilder({ .tableName = model::authorconst::TABLE, .rows = { model::authorconst::ID, model::authorconst::NAME } });
|
||||||
|
QSqlQuery query(sBuilder.get());
|
||||||
|
|
||||||
|
qDebug() << query.lastError().text();
|
||||||
|
|
||||||
|
while (query.next())
|
||||||
|
{
|
||||||
|
authors.append({ query.value(0).toInt(),
|
||||||
|
query.value(1).toString() });
|
||||||
|
}
|
||||||
|
|
||||||
|
return authors;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<model::Author> AuthorRepository::getByName(const QString& name)
|
||||||
|
{
|
||||||
|
Q_UNUSED(name);
|
||||||
|
Builder::Select sBuilder({ .tableName = model::authorconst::TABLE, .rows = { model::authorconst::ID, model::authorconst::NAME } });
|
||||||
|
QString qResult = sBuilder.get() + QString(" WHERE %1 = \"%2\"").arg(model::authorconst::NAME).arg(name);
|
||||||
|
|
||||||
|
QSqlQuery query(qResult);
|
||||||
|
|
||||||
|
if (query.next())
|
||||||
|
{
|
||||||
|
model::Author author({ .id = query.value(0).toInt(),
|
||||||
|
.name = query.value(1).toString() });
|
||||||
|
return { author };
|
||||||
|
}
|
||||||
|
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool AuthorRepository::insert(const model::Author& author)
|
||||||
|
{
|
||||||
|
QSqlQuery query(DatabaseManager::instance().database());
|
||||||
|
Builder::Insert iBuild({ model::authorconst::TABLE,
|
||||||
|
{ model::authorconst::NAME },
|
||||||
|
true });
|
||||||
|
|
||||||
|
query.prepare(iBuild.get());
|
||||||
|
query.bindValue(":name", author.name);
|
||||||
|
int authorId = 0;
|
||||||
|
Q_UNUSED(authorId);
|
||||||
|
|
||||||
|
if (!query.exec())
|
||||||
|
{
|
||||||
|
qDebug() << query.lastError().text();
|
||||||
|
if (query.lastError().nativeErrorCode() == 19)
|
||||||
|
{
|
||||||
|
// Автор уже есть, ищем его ID
|
||||||
|
QSqlQuery findQuery(DatabaseManager::instance().database());
|
||||||
|
findQuery.prepare("SELECT id FROM authors WHERE name = :name");
|
||||||
|
findQuery.bindValue(":name", author.name);
|
||||||
|
if (findQuery.exec() && findQuery.next())
|
||||||
|
{
|
||||||
|
authorId = findQuery.value(0).toInt();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
qCritical() << "Ошибка добавления автора:" << query.lastError().text();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
authorId = query.lastInsertId().toInt();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
29
src/repositories/author_repository.h
Normal file
29
src/repositories/author_repository.h
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <model/author.h>
|
||||||
|
|
||||||
|
#include <database/databasemanager.h>
|
||||||
|
|
||||||
|
#include <QSqlDatabase>
|
||||||
|
#include <QSqlError>
|
||||||
|
#include <QSqlQuery>
|
||||||
|
#include <QString>
|
||||||
|
#include <QVariant>
|
||||||
|
#include <QVector>
|
||||||
|
#include <optional>
|
||||||
|
|
||||||
|
#ifdef BUILD_REPOSITORIES
|
||||||
|
#define REPOSITORIES_EXPORT Q_DECL_EXPORT
|
||||||
|
#else
|
||||||
|
#define REPOSITORIES_EXPORT Q_DECL_IMPORT
|
||||||
|
#endif
|
||||||
|
|
||||||
|
class REPOSITORIES_EXPORT AuthorRepository
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
static QVector<model::Author> getAll();
|
||||||
|
static std::optional<model::Author> getByName(const QString& name);
|
||||||
|
static bool insert(const model::Author& author);
|
||||||
|
|
||||||
|
// TODO Возвращать не bool - а номер id записи
|
||||||
|
};
|
||||||
59
src/repositories/book_repository.cpp
Normal file
59
src/repositories/book_repository.cpp
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
// #define BUILD_REPOSITORIES
|
||||||
|
#include "book_repository.h"
|
||||||
|
|
||||||
|
#include <QDebug>
|
||||||
|
#include <qsqlerror.h>
|
||||||
|
|
||||||
|
#include <sql_builder/insert.h>
|
||||||
|
#include <sql_builder/select.h>
|
||||||
|
|
||||||
|
QVector<model::Book> BookRepository::getAll()
|
||||||
|
{
|
||||||
|
QVector<model::Book> books;
|
||||||
|
Builder::Select qBuilder {
|
||||||
|
model::bookconst::TABLE,
|
||||||
|
{ model::bookconst::ID,
|
||||||
|
model::bookconst::TITLE,
|
||||||
|
model::bookconst::AUTHOR_ID,
|
||||||
|
model::bookconst::FILEPATH }
|
||||||
|
};
|
||||||
|
|
||||||
|
QSqlQuery query(qBuilder.get());
|
||||||
|
|
||||||
|
qDebug() << query.lastError().text();
|
||||||
|
|
||||||
|
while (query.next())
|
||||||
|
{
|
||||||
|
books.append({ query.value(0).toInt(),
|
||||||
|
query.value(1).toString(),
|
||||||
|
{ query.value(2).toInt() },
|
||||||
|
query.value(3).toString() });
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO получить так же авторов как строку
|
||||||
|
|
||||||
|
return books;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool BookRepository::insert(const model::Book& book)
|
||||||
|
{
|
||||||
|
QSqlQuery query(DatabaseManager::instance().database());
|
||||||
|
|
||||||
|
Builder::Insert iBuilder {
|
||||||
|
model::bookconst::TABLE,
|
||||||
|
{ model::bookconst::TITLE,
|
||||||
|
model::bookconst::FILEPATH,
|
||||||
|
model::bookconst::AUTHOR_ID }
|
||||||
|
};
|
||||||
|
|
||||||
|
query.prepare(iBuilder.get());
|
||||||
|
query.bindValue(":" + model::bookconst::TITLE, book.title);
|
||||||
|
query.bindValue(":" + model::bookconst::FILEPATH, book.filePath);
|
||||||
|
query.bindValue(":" + model::bookconst::AUTHOR_ID, book.author.id);
|
||||||
|
|
||||||
|
bool res = query.exec();
|
||||||
|
if (!res)
|
||||||
|
qDebug() << query.lastError().text();
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
22
src/repositories/book_repository.h
Normal file
22
src/repositories/book_repository.h
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <model/book.h>
|
||||||
|
|
||||||
|
#include <database/databasemanager.h>
|
||||||
|
|
||||||
|
#include <QSqlQuery>
|
||||||
|
#include <QVariant>
|
||||||
|
#include <QVector>
|
||||||
|
|
||||||
|
#ifdef BUILD_REPOSITORIES
|
||||||
|
#define REPOSITORIES_EXPORT Q_DECL_EXPORT
|
||||||
|
#else
|
||||||
|
#define REPOSITORIES_EXPORT Q_DECL_IMPORT
|
||||||
|
#endif
|
||||||
|
|
||||||
|
class REPOSITORIES_EXPORT BookRepository
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
static QVector<model::Book> getAll();
|
||||||
|
static bool insert(const model::Book& book);
|
||||||
|
};
|
||||||
21
src/repositories/repositories.qbs
Normal file
21
src/repositories/repositories.qbs
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import qbs
|
||||||
|
|
||||||
|
PSLibrary {
|
||||||
|
Depends { name: "Qt"; submodules: "core", "sql"}
|
||||||
|
|
||||||
|
Depends { name: "database" }
|
||||||
|
Depends { name: "sql_builder" }
|
||||||
|
|
||||||
|
Group {
|
||||||
|
name: "cpp"
|
||||||
|
files: [
|
||||||
|
"*.h",
|
||||||
|
"*.cpp"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
Properties {
|
||||||
|
condition: qbs.buildVariant === "debug"
|
||||||
|
cpp.defines: ["BUILD_REPOSITORIES"]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,39 +1,15 @@
|
|||||||
/*!
|
import qbs
|
||||||
\qmltype cpp-opds
|
|
||||||
\inherits Project
|
|
||||||
\brief Описание
|
|
||||||
*/
|
|
||||||
WPSLibrary {
|
|
||||||
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"
|
|
||||||
]
|
|
||||||
consoleApplication: true
|
|
||||||
|
|
||||||
Depends { name: "Qt"; submodules: [ "core", "sql", "network" ] }
|
PSLibrary {
|
||||||
Depends { name: "cpp" }
|
Depends { name: "Qt"; submodules: ["core", "sql", "network"] }
|
||||||
Depends { name: "database" }
|
|
||||||
Depends { name: "odb.gen" }
|
|
||||||
Depends { name: "redkit_gen" }
|
|
||||||
Depends { name: "rdbase" }
|
|
||||||
Depends { name: "model" }
|
|
||||||
|
|
||||||
cpp.cxxLanguageVersion: "c++20"
|
Depends { name: "services" }
|
||||||
|
|
||||||
Group {
|
Group {
|
||||||
name: "cpp"
|
name: "cpp"
|
||||||
files: [
|
files: [
|
||||||
"restapiserver.*",
|
"*.h",
|
||||||
|
"*.cpp"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
}
|
||||||
cpp.dynamicLibraries: [
|
|
||||||
"odb-sqlite",
|
|
||||||
"odb-qt",
|
|
||||||
"odb",
|
|
||||||
"sqlite3"
|
|
||||||
]
|
|
||||||
|
|
||||||
} // Project
|
|
||||||
|
|||||||
@@ -1,23 +1,15 @@
|
|||||||
#include "restapiserver.h"
|
#include "restapiserver.h"
|
||||||
|
|
||||||
|
#include <services/author_service.h>
|
||||||
|
#include <services/book_service.h>
|
||||||
|
|
||||||
#include <QJsonArray>
|
#include <QJsonArray>
|
||||||
#include <QJsonDocument>
|
#include <QJsonDocument>
|
||||||
#include <QJsonObject>
|
#include <QJsonObject>
|
||||||
#include <QJsonValue>
|
#include <QJsonValue>
|
||||||
|
|
||||||
#include <model/author_s-odb.hxx> // Должен быть здесь
|
RestApiServer::RestApiServer(QObject* parent) :
|
||||||
#include <model/author_s.h>
|
QTcpServer(parent) {}
|
||||||
#include <model/book_s-odb.hxx> // Должен быть здесь
|
|
||||||
#include <model/book_s.h>
|
|
||||||
|
|
||||||
#include <odb/core.hxx>
|
|
||||||
#include <odb/database.hxx>
|
|
||||||
#include <odb/query.hxx>
|
|
||||||
|
|
||||||
#include <redkit-gen-modules/json_serializer.h>
|
|
||||||
|
|
||||||
RestApiServer::RestApiServer(odb::database& db, QObject* parent) :
|
|
||||||
QTcpServer(parent), m_db(db) {}
|
|
||||||
|
|
||||||
void RestApiServer::start(quint16 port)
|
void RestApiServer::start(quint16 port)
|
||||||
{
|
{
|
||||||
@@ -27,7 +19,7 @@ void RestApiServer::start(quint16 port)
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
qDebug() << "REST API сервер запущен по адресу:";
|
qDebug() << "REST API сервер запущен на порту:" << port;
|
||||||
qDebug() << QString("http://127.0.0.1:%1").arg(port);
|
qDebug() << QString("http://127.0.0.1:%1").arg(port);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -39,8 +31,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,97 +49,70 @@ 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] : "";
|
|
||||||
|
|
||||||
odb::transaction t(m_db.begin());
|
QByteArray jsonResponse = "{ \"books\": [";
|
||||||
|
// for (const BookRecord& book : results)
|
||||||
// auto books = m_db.query<Book_S>(odb::query<Book_S>::author->id == ageReq);
|
|
||||||
|
|
||||||
QJsonArray jArray;
|
|
||||||
// for (const auto& book : books)
|
|
||||||
// {
|
// {
|
||||||
// QJsonObject j;
|
// jsonResponse += QString("{ \"id\": %1, \"title\": \"%2\", \"author\": \"%3\", \"year\": %4 },")
|
||||||
// j["id"] = QString::number(book.id());
|
// .arg(book.id)
|
||||||
|
// .arg(book.title)
|
||||||
// QJsonObject author;
|
// .arg(book.author)
|
||||||
// author["id"] = QString::number(book.author()->id());
|
// .arg(book.year)
|
||||||
// author["fullName"] = book.author()->fullName();
|
// .toUtf8();
|
||||||
// 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);
|
// if (results.size() > 0)
|
||||||
|
// jsonResponse.chop(1); // Убираем последнюю запятую
|
||||||
|
// jsonResponse += "] }";
|
||||||
|
|
||||||
t.commit();
|
return "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n" + jsonResponse;
|
||||||
|
|
||||||
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"))
|
||||||
{
|
{
|
||||||
odb::transaction t(m_db.begin());
|
auto books = BookService::fetchAll();
|
||||||
odb::result<Book_S> res(m_db.query<Book_S>());
|
|
||||||
|
|
||||||
QJsonArray jArray;
|
QJsonArray jArray;
|
||||||
for (auto it = res.begin(); it != res.end(); ++it)
|
|
||||||
|
for (auto it = books.begin(); it != books.end(); ++it)
|
||||||
{
|
{
|
||||||
const auto& book = *it;
|
const auto& book = *it;
|
||||||
|
|
||||||
QJsonObject j;
|
QJsonObject j;
|
||||||
j["id"] = QString::number(book.id());
|
j["id"] = QString::number(book.id);
|
||||||
|
j["title"] = QString(book.title);
|
||||||
// QJsonObject author;
|
j["author"] = QString(book.author.name);
|
||||||
// author["id"] = QString::number(book.author()->id());
|
j["local_path"] = book.filePath;
|
||||||
// author["fullName"] = book.author()->fullName();
|
jArray.push_back(j);
|
||||||
// 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);
|
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);
|
return "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n" + jDoc.toJson(QJsonDocument::Indented);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (request.startsWith("GET /author"))
|
if (request.startsWith("GET /author"))
|
||||||
{
|
{
|
||||||
odb::transaction t(m_db.begin());
|
// auto books = BookService::fetchAll();
|
||||||
odb::result<Author_S> res(m_db.query<Author_S>());
|
auto authors = AuthorService::fetchAll();
|
||||||
|
|
||||||
QJsonArray jArray;
|
QJsonArray jArray;
|
||||||
for (auto it = res.begin(); it != res.end(); ++it)
|
for (auto it = authors.begin(); it != authors.end(); ++it)
|
||||||
{
|
{
|
||||||
const auto& author = *it;
|
const auto& author = *it;
|
||||||
|
|
||||||
QJsonObject j;
|
QJsonObject j;
|
||||||
j["id"] = QString::number(author.id());
|
j["id"] = QString::number(author.id);
|
||||||
j["fullName"] = author.fullName();
|
j["name"] = QString(author.name);
|
||||||
j["langCode"] = author.langCode();
|
// j["last"] = QString::fromStdString(author.last());
|
||||||
|
// j["age"] = author.age();
|
||||||
jArray.push_back(j);
|
jArray.push_back(j);
|
||||||
}
|
}
|
||||||
auto jDoc = QJsonDocument(jArray);
|
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);
|
return "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n" + jDoc.toJson(QJsonDocument::Indented);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
#ifndef RESTAPISERVER_H
|
#ifndef RESTAPISERVER_H
|
||||||
#define RESTAPISERVER_H
|
#define RESTAPISERVER_H
|
||||||
|
|
||||||
#include <odb/database.hxx>
|
|
||||||
|
|
||||||
#include <QObject>
|
|
||||||
#include <QTcpServer>
|
#include <QTcpServer>
|
||||||
#include <QTcpSocket>
|
#include <QTcpSocket>
|
||||||
|
|
||||||
@@ -11,7 +8,7 @@ class Q_DECL_EXPORT RestApiServer : public QTcpServer
|
|||||||
{
|
{
|
||||||
Q_OBJECT
|
Q_OBJECT
|
||||||
public:
|
public:
|
||||||
explicit RestApiServer(odb::core::database& db, QObject* parent = nullptr);
|
explicit RestApiServer(QObject* parent = nullptr);
|
||||||
void start(quint16 port = 8080);
|
void start(quint16 port = 8080);
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
@@ -22,8 +19,6 @@ private slots:
|
|||||||
|
|
||||||
private:
|
private:
|
||||||
QByteArray processRequest(const QString& request);
|
QByteArray processRequest(const QString& request);
|
||||||
|
|
||||||
odb::core::database& m_db;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
#endif // RESTAPISERVER_H
|
#endif // RESTAPISERVER_H
|
||||||
|
|||||||
12
src/services/author_service.cpp
Normal file
12
src/services/author_service.cpp
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
// #define BUILD_SERVICES
|
||||||
|
#include "author_service.h"
|
||||||
|
|
||||||
|
QVector<model::Author> AuthorService::fetchAll()
|
||||||
|
{
|
||||||
|
return AuthorRepository::getAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool AuthorService::add(const model::Author& author)
|
||||||
|
{
|
||||||
|
return AuthorRepository::insert(author);
|
||||||
|
}
|
||||||
20
src/services/author_service.h
Normal file
20
src/services/author_service.h
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <model/author.h>
|
||||||
|
|
||||||
|
#include <repositories/author_repository.h>
|
||||||
|
|
||||||
|
#include <QVector>
|
||||||
|
|
||||||
|
#ifdef BUILD_SERVICES
|
||||||
|
#define SERVICES_EXPORT Q_DECL_EXPORT
|
||||||
|
#else
|
||||||
|
#define SERVICES_EXPORT Q_DECL_IMPORT
|
||||||
|
#endif
|
||||||
|
|
||||||
|
class SERVICES_EXPORT AuthorService
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
static QVector<model::Author> fetchAll();
|
||||||
|
static bool add(const model::Author& name);
|
||||||
|
};
|
||||||
28
src/services/book_service.cpp
Normal file
28
src/services/book_service.cpp
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
// #define BUILD_SERVICES
|
||||||
|
#include "book_service.h"
|
||||||
|
#include "author_service.h"
|
||||||
|
|
||||||
|
QVector<model::Book> BookService::fetchAll()
|
||||||
|
{
|
||||||
|
return BookRepository::getAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool BookService::add(const model::Book& book)
|
||||||
|
{
|
||||||
|
auto res = AuthorRepository::getByName(book.author.name);
|
||||||
|
|
||||||
|
if (!res.has_value())
|
||||||
|
{
|
||||||
|
if (!AuthorService::add(book.author))
|
||||||
|
{
|
||||||
|
qCritical() << "Ошибка добавления автора!";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
res = AuthorRepository::getByName(book.author.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
model::Book BookAuthor = book;
|
||||||
|
BookAuthor.author = res.value();
|
||||||
|
return BookRepository::insert(BookAuthor);
|
||||||
|
}
|
||||||
20
src/services/book_service.h
Normal file
20
src/services/book_service.h
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <model/book.h>
|
||||||
|
|
||||||
|
#include <repositories/book_repository.h>
|
||||||
|
|
||||||
|
#include <QVector>
|
||||||
|
|
||||||
|
#ifdef BUILD_SERVICES
|
||||||
|
#define SERVICES_EXPORT Q_DECL_EXPORT
|
||||||
|
#else
|
||||||
|
#define SERVICES_EXPORT Q_DECL_IMPORT
|
||||||
|
#endif
|
||||||
|
|
||||||
|
class SERVICES_EXPORT BookService
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
static QVector<model::Book> fetchAll();
|
||||||
|
static bool add(const model::Book& book);
|
||||||
|
};
|
||||||
22
src/services/services.qbs
Normal file
22
src/services/services.qbs
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import qbs
|
||||||
|
|
||||||
|
PSLibrary {
|
||||||
|
Depends { name: "Qt"; submodules: "core", "sql"}
|
||||||
|
|
||||||
|
Depends { name: "repositories" }
|
||||||
|
|
||||||
|
Group {
|
||||||
|
name: "cpp"
|
||||||
|
files: [
|
||||||
|
"*.h",
|
||||||
|
"*.cpp"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Properties {
|
||||||
|
condition: qbs.buildVariant === "debug"
|
||||||
|
cpp.defines: ["BUILD_SERVICES"]
|
||||||
|
}
|
||||||
|
}
|
||||||
45
src/sql_builder/create_table.cpp
Normal file
45
src/sql_builder/create_table.cpp
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
#include "create_table.h"
|
||||||
|
|
||||||
|
#include <QDebug>
|
||||||
|
|
||||||
|
namespace Builder
|
||||||
|
{
|
||||||
|
|
||||||
|
QString Column::toSQL() const
|
||||||
|
{
|
||||||
|
QString columnDef = name + " " + type;
|
||||||
|
if (primaryKey)
|
||||||
|
columnDef += " PRIMARY KEY";
|
||||||
|
if (notNull)
|
||||||
|
columnDef += " NOT NULL";
|
||||||
|
if (unique)
|
||||||
|
columnDef += " UNIQUE";
|
||||||
|
if (defaultValue)
|
||||||
|
columnDef += " DEFAULT " + *defaultValue;
|
||||||
|
if (foreignKeyTable && foreignKeyColumn)
|
||||||
|
{
|
||||||
|
columnDef += " REFERENCES " + *foreignKeyTable + "(" + *foreignKeyColumn + ")";
|
||||||
|
}
|
||||||
|
return columnDef;
|
||||||
|
}
|
||||||
|
|
||||||
|
TableSchema& TableSchema::addColumn(const Column& column)
|
||||||
|
{
|
||||||
|
columns.push_back(column);
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
QString TableSchema::get() const
|
||||||
|
{
|
||||||
|
QStringList columnDefs;
|
||||||
|
for (const auto& col : columns)
|
||||||
|
{
|
||||||
|
columnDefs.append(col.toSQL());
|
||||||
|
}
|
||||||
|
|
||||||
|
QString result = "CREATE TABLE IF NOT EXISTS " + name + " ( " + columnDefs.join(", ") + " );";
|
||||||
|
// qDebug() << result;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Builder
|
||||||
50
src/sql_builder/create_table.h
Normal file
50
src/sql_builder/create_table.h
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <QString>
|
||||||
|
#include <QStringList>
|
||||||
|
#include <QVector>
|
||||||
|
|
||||||
|
#include <optional>
|
||||||
|
|
||||||
|
namespace Builder
|
||||||
|
{
|
||||||
|
|
||||||
|
struct Column
|
||||||
|
{
|
||||||
|
QString name; // Имя колонки
|
||||||
|
QString type; // Тип колонки
|
||||||
|
bool primaryKey = false; // Является ли колонка первичным ключом?
|
||||||
|
bool notNull = false; // Колонка не должна быть пуста
|
||||||
|
bool unique = false; // Значение в колонке должны быть уникальны
|
||||||
|
std::optional<QString> defaultValue;
|
||||||
|
std::optional<QString> foreignKeyTable;
|
||||||
|
std::optional<QString> foreignKeyColumn;
|
||||||
|
|
||||||
|
/*!
|
||||||
|
* \brief Сформировать SQL код для колонки
|
||||||
|
*/
|
||||||
|
QString toSQL() const;
|
||||||
|
};
|
||||||
|
|
||||||
|
class Q_DECL_EXPORT TableSchema
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
TableSchema(QString tableName) :
|
||||||
|
name(std::move(tableName)) {}
|
||||||
|
|
||||||
|
/*!
|
||||||
|
* \brief Добавить колонку
|
||||||
|
*/
|
||||||
|
TableSchema& addColumn(const Column& column);
|
||||||
|
|
||||||
|
/*!
|
||||||
|
* \brief Сформировать SQL код для создания таблицы
|
||||||
|
*/
|
||||||
|
QString get() const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
QString name; // Имя таблицы
|
||||||
|
QVector<Column> columns; // Список колонок таблицы
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Builder
|
||||||
39
src/sql_builder/insert.cpp
Normal file
39
src/sql_builder/insert.cpp
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
#include "insert.h"
|
||||||
|
|
||||||
|
#include <QDebug>
|
||||||
|
|
||||||
|
namespace Builder
|
||||||
|
{
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
|
||||||
|
const QString INSERT = QStringLiteral("INSERT");
|
||||||
|
const QString INTO = QStringLiteral("INTO");
|
||||||
|
const QString VALUES = QStringLiteral("VALUES");
|
||||||
|
const QString IGNORE = QStringLiteral("IGNORE");
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
QString Insert::get() const
|
||||||
|
{
|
||||||
|
QString resultString = QString("%1 ").arg(INSERT);
|
||||||
|
if (orIgnore)
|
||||||
|
resultString += QString("OR %1 ").arg(IGNORE);
|
||||||
|
resultString += QString("%1 %2 ").arg(INTO).arg(tableName);
|
||||||
|
|
||||||
|
resultString += QString("( %1 ) ").arg(rows.join(", "));
|
||||||
|
|
||||||
|
// TODO как будто бы проще сразу это заполнить значениями
|
||||||
|
QStringList allValue;
|
||||||
|
for (const auto& row : rows)
|
||||||
|
allValue.push_back(QString(":%1").arg(row));
|
||||||
|
|
||||||
|
resultString += QString("%1 ( %2 )").arg(VALUES).arg(allValue.join(", "));
|
||||||
|
|
||||||
|
resultString += ';';
|
||||||
|
// qDebug() << resultString;
|
||||||
|
return resultString;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Builder
|
||||||
22
src/sql_builder/insert.h
Normal file
22
src/sql_builder/insert.h
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <QString>
|
||||||
|
#include <QStringList>
|
||||||
|
|
||||||
|
namespace Builder
|
||||||
|
{
|
||||||
|
|
||||||
|
struct Q_DECL_EXPORT Insert
|
||||||
|
{
|
||||||
|
QString tableName; // Имя таблицы
|
||||||
|
QStringList rows; // Именования колонок
|
||||||
|
// QStringList params;
|
||||||
|
bool orIgnore = false;
|
||||||
|
|
||||||
|
/*!
|
||||||
|
* \brief Сформировать SQL код для выполнения
|
||||||
|
*/
|
||||||
|
QString get() const;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Builder
|
||||||
32
src/sql_builder/select.cpp
Normal file
32
src/sql_builder/select.cpp
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
#include "select.h"
|
||||||
|
|
||||||
|
#include <QDebug>
|
||||||
|
|
||||||
|
namespace Builder
|
||||||
|
{
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
|
||||||
|
const QString SELECT = QStringLiteral("SELECT");
|
||||||
|
const QString FROM = QStringLiteral("FROM");
|
||||||
|
const QString WHERE = QStringLiteral("WHERE");
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
QString Select::get() const
|
||||||
|
{
|
||||||
|
QString allRows = rows.join(", ");
|
||||||
|
|
||||||
|
QString resultString = QString("%1 %2").arg(SELECT).arg(allRows);
|
||||||
|
|
||||||
|
resultString += QString(" %1 %2").arg(FROM).arg(tableName);
|
||||||
|
|
||||||
|
if (!where.isEmpty())
|
||||||
|
resultString += QString(" %1 %2").arg(WHERE).arg(where);
|
||||||
|
|
||||||
|
// resultString += ';';
|
||||||
|
return resultString;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Builder
|
||||||
21
src/sql_builder/select.h
Normal file
21
src/sql_builder/select.h
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <QString>
|
||||||
|
#include <QStringList>
|
||||||
|
|
||||||
|
namespace Builder
|
||||||
|
{
|
||||||
|
|
||||||
|
struct Q_DECL_EXPORT Select
|
||||||
|
{
|
||||||
|
QString tableName; // Имя таблицы
|
||||||
|
QStringList rows = { "*" }; // Колонки
|
||||||
|
QString where = {}; // Условие поиска
|
||||||
|
|
||||||
|
/*!
|
||||||
|
* \brief Сформировать SQL код для выполнения
|
||||||
|
*/
|
||||||
|
QString get() const;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Builder
|
||||||
14
src/sql_builder/sql_builder.qbs
Normal file
14
src/sql_builder/sql_builder.qbs
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import qbs
|
||||||
|
|
||||||
|
PSLibrary {
|
||||||
|
Depends { name: "Qt"; submodules: "sql"}
|
||||||
|
|
||||||
|
|
||||||
|
Group {
|
||||||
|
name: "cpp"
|
||||||
|
files: [
|
||||||
|
"**/*.h",
|
||||||
|
"**/*.cpp"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user