Compare commits

1 Commits

56 changed files with 1013 additions and 1341 deletions

3
.gitmodules vendored
View File

@@ -4,6 +4,3 @@
[submodule "redkitty"]
path = redkitty
url = git@gitea.redkit-lab.work:redkit-lab/redkitty.git
[submodule "external_libs/quazip"]
path = external_libs/quazip
url = https://github.com/stachenov/quazip.git

View File

@@ -1,34 +0,0 @@
import qbs
PSLibrary {
name: "quazip"
property string quazipPath: path + "/quazip" // Путь к исходникам QuaZip
property string noname: {
console.error("noname" + exportedIncludePaths)
return "noname"
}
Depends { name: "zlib" }
Group {
name: "h"
id: qh
files: [
quazipPath + "/quazip/*.h",
]
}
Group {
name: "cpp"
files: [
quazipPath + "/quazip/*.cpp",
quazipPath + "/quazip/*.c"
]
}
// Export {
// Depends { name:"cpp" }
// cpp.includePaths: qh
// }
}

View File

@@ -15,11 +15,6 @@ Project {
"src/cpp-opds.qbs",
"src/database/database.qbs",
"src/model/model.qbs",
"src/restapi/restapi.qbs",
"src/utils/utils.qbs",
"src/repository/repository.qbs",
"external_libs/quazip.qbs",
]
}

View File

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

64
src/database/author_s.h Normal file
View File

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

64
src/database/book_s.h Normal file
View File

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

View File

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

View File

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

View File

@@ -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;
}
}

View File

@@ -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/books/author_book_s-odb.hxx>
#include <model/books/author_book_s.h>
#include <model/books/author_s-odb.hxx>
#include <model/books/author_s.h>
#include <model/books/book_s-odb.hxx>
#include <model/books/book_s.h>
void DATABASE_EXPORT addBook(oDBase& db, const QString title, const QVector<QString>& authors);

View File

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

56
src/model/author.h Normal file
View 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

65
src/model/book.h Normal file
View 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

View File

@@ -1,47 +0,0 @@
#ifndef AUTHOR_BOOK_H
#define AUTHOR_BOOK_H
#include <model/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:
public:
#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

View File

@@ -1,42 +0,0 @@
#ifndef AUTHOR_S_H
#define AUTHOR_S_H
#include <model/model_global.h>
#pragma db object
class MODEL_EXPORT Author_S
{
public:
Author_S() = default;
Author_S(const QString& fullName) :
m_fullName(fullName) {}
quint64 id() const { return m_id; }
void setId(quint64 newId) { m_id = newId; }
QString fullName() const { return m_fullName; }
void setFullName(const QString& newFullName) { m_fullName = newFullName; }
QString langCode() const { return m_langCode; }
void setLangCode(const QString& newLangCode) { m_langCode = newLangCode; }
private:
friend class odb::access;
private:
public:
#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

View File

@@ -1,43 +0,0 @@
#ifndef BOOK_S_H
#define BOOK_S_H
#include <model/model_global.h>
#include <QDateTime>
#pragma db object
class MODEL_EXPORT Book_S
{
public:
Book_S() = default;
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; }
quint8 year() const { return m_year; }
void setYear(const quint8& newYear) { m_year = newYear; }
QDateTime lastModified() const { return m_lastModified; }
void setLastModified(const QDateTime& newLastModified) { m_lastModified = newLastModified; }
QString lang() const { return m_lang; }
void setLang(const QString& newLang) { m_lang = newLang; }
private:
friend class odb::access;
private:
public:
#pragma db id auto
quint64 m_id;
QString m_title;
quint8 m_year;
QDateTime m_lastModified;
QString m_lang;
};
#endif // BOOK_S_H

View File

@@ -1,46 +0,0 @@
#ifndef GENRE_BOOK_S_H
#define GENRE_BOOK_S_H
#include <model/model_global.h>
#include "book_s.h"
#include "genre_s.h"
#pragma db object
class GenreBook_S
{
private:
GenreBook_S() = default;
public:
GenreBook_S(const SH<Genre_S>& genreId, const SH<Book_S>& bookId) :
m_genreId(genreId),
m_bookId(bookId) {}
quint64 id() const { return m_id; }
void setId(quint64 newId) { m_id = newId; }
SH<Genre_S> genreId() const { return m_genreId; }
void setGenreId(const SH<Genre_S>& newGenreId) { m_genreId = newGenreId; }
SH<Book_S> bookId() const { return m_bookId; }
void setBookId(const SH<Book_S>& newBookId) { m_bookId = newBookId; }
private:
friend class odb::access;
private:
public:
#pragma db id auto
quint64 m_id;
#pragma db not_null
SH<Genre_S> m_genreId;
#pragma db not_null
SH<Book_S> m_bookId;
#pragma db index("genre_book_unique") member(m_genreId) member(m_bookId) unique
};
#endif // GENRE_BOOK_S_H

View File

@@ -1,29 +0,0 @@
#ifndef GENRE_H
#define GENRE_H
#include <model/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:
public:
#pragma db id auto
quint64 m_id;
QString m_name;
};
#endif // GENRE_H

View File

@@ -1,10 +0,0 @@
#ifndef MANUTOMANYBASE_H
#define MANUTOMANYBASE_H
class ManuToManyBase
{
public:
ManuToManyBase();
};
#endif // MANUTOMANYBASE_H

View File

@@ -1,46 +0,0 @@
#ifndef SERIES_BOOK_S_H
#define SERIES_BOOK_S_H
#include <model/model_global.h>
#include "book_s.h"
#include "series_s.h"
#pragma db object
class MODEL_EXPORT SeriesBook_S
{
private:
SeriesBook_S() = default;
public:
SeriesBook_S(const SH<Series_S>& serieId, const SH<Book_S>& bookId) :
m_serieId(serieId),
m_bookId(bookId) {}
quint64 id() const { return m_id; }
void setId(quint64 newId) { m_id = newId; }
SH<Series_S> serieId() const { return m_serieId; }
void setSerieId(const SH<Series_S>& newSerieId) { m_serieId = newSerieId; }
SH<Book_S> bookId() const { return m_bookId; }
void setBookId(const SH<Book_S>& newBookId) { m_bookId = newBookId; }
private:
friend class odb::access;
private:
public:
#pragma db id auto
quint64 m_id;
#pragma db not_null
SH<Series_S> m_serieId;
#pragma db not_null
SH<Book_S> m_bookId;
#pragma db index("series_book_unique") member(m_serieId) member(m_bookId) unique
};
#endif // SERIES_BOOK_S_H

View File

@@ -1,29 +0,0 @@
#ifndef SERIES_H
#define SERIES_H
#include <model/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 name() const { return m_serName; }
void setName(const QString& newSerName) { m_serName = newSerName; }
private:
friend class odb::access;
private:
public:
#pragma db id auto
quint64 m_id;
QString m_serName;
};
#endif // SERIES_H

View File

@@ -1,53 +1,15 @@
/*!
\qmltype cpp-opds
\inherits Project
\brief Описание
*/
import qbs
PSLibrary {
cpp.defines: [
// You can make your code fail to compile if it uses deprecated APIs.
// In order to do so, uncomment the following line.
//"QT_DISABLE_DEPRECATED_BEFORE=0x060000" // disables all the APIs deprecated before Qt 6.0.0
"DATABASE_SQLITE",
"MODEL_LIBRARY"
]
consoleApplication: true
Depends { name: "Qt"; submodules: "core", "sql"}
Depends { name: "Qt"; submodules: [ "core", "network" ] }
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"
Depends { name: "sql_builder" }
Group {
id: headers
name: "headers"
name: "cpp"
files: [
"model_global.h",
"*.h",
"*.cpp"
]
}
Group {
id: odbs
name: "odb"
files: [
"**/*.h",
]
excludeFiles: headers.files
fileTags: ["hpp", "odbxx", "rgen"]
}
cpp.dynamicLibraries: [
"odb-sqlite",
"odb-qt",
"odb",
"sqlite3"
]
}

View File

@@ -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

View File

@@ -1,23 +0,0 @@
#ifndef SETTINGS_S_H
#define SETTINGS_S_H
#include <model/model_global.h>
#pragma db object
class MODEL_EXPORT Settings_S
{
public:
Settings_S() = default;
quint64 id() const { return m_id; }
void setId(const quint64& newId) { m_id = newId; }
private:
friend class odb::access;
private:
#pragma db id auto
quint64 m_id;
};
#endif // SETTINGS_S_H

View 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;
}

View 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 записи
};

View 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;
}

View 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);
};

View 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"]
}
}

View File

@@ -1,81 +0,0 @@
#include "authorrepository.h"
#include <model/books/author_book_s-odb.hxx>
#include <model/books/author_book_s.h>
#include <model/books/author_s-odb.hxx>
#include <model/books/author_s.h>
#include <model/books/book_s-odb.hxx>
#include <model/books/book_s.h>
#include <odb/core.hxx>
#include <odb/database.hxx>
#include <odb/query.hxx>
namespace repository
{
AuthorRepository::AuthorRepository(odb::core::database& db) :
m_db(db)
{}
QVector<Author_S> AuthorRepository::findAll()
{
odb::transaction t(m_db.begin());
odb::result<Author_S> res(m_db.query<Author_S>());
QVector<Author_S> authors;
for (auto it = res.begin(); it != res.end(); ++it)
{
const auto& author = *it;
authors.push_back(author);
}
t.commit();
return authors;
}
Author_S AuthorRepository::findById(int id)
{
odb::transaction t(m_db.begin());
odb::result<Author_S> res(m_db.query<Author_S>(odb::query<Author_S>::id == id));
Author_S author;
res.value(author);
t.commit();
return author;
}
QVector<Author_S> AuthorRepository::findByBook(const int& bookId)
{
odb::transaction t(m_db.begin());
QVector<Author_S> authors;
using ABQuery = odb::query<AuthorBook_S>;
using ABResult = odb::result<AuthorBook_S>;
ABResult abResult(m_db.query<AuthorBook_S>(ABQuery::book == bookId));
for (const AuthorBook_S& ab : abResult)
{
// Загружаем каждую книгу по ID
SH<Author_S> author(m_db.load<Author_S>(ab.author()->id()));
authors.push_back(*author.data());
}
t.commit();
return authors;
}
QVector<Author_S> AuthorRepository::findByBook(const QString& book_name)
{
odb::transaction t(m_db.begin());
auto book_s = m_db.query<Book_S>(odb::query<Book_S>::title == book_name).one();
return findByBook(book_s->id());
}
} // namespace repository

View File

@@ -1,41 +0,0 @@
#ifndef AUTHORREPOSITORY_H
#define AUTHORREPOSITORY_H
#include "repository_global.h"
#include <model/books/author_s.h>
#include <QString>
#include <QVector>
namespace repository
{
class REPOSITORY_EXPORT AuthorRepository
{
public:
AuthorRepository(odb::core::database& db);
// Получить всех авторов
QVector<Author_S> findAll();
// Найти автора по id
Author_S findById(int id);
// Сохранить книгу (создать или обновить)
// void save(const Book_S& book);
// Удалить автора
// void remove(int id);
// Найти авторов по книге
QVector<Author_S> findByBook(const int& book_id);
QVector<Author_S> findByBook(const QString& bookName);
private:
odb::core::database& m_db;
};
} // namespace repository
#endif // AUTHORREPOSITORY_H

View File

@@ -1,96 +0,0 @@
#include "bookrepository.h"
#include <QDebug>
#include <model/books/author_book_s-odb.hxx>
#include <model/books/author_book_s.h>
#include <model/books/author_s-odb.hxx>
#include <model/books/author_s.h>
#include <model/books/book_s-odb.hxx>
#include <model/books/book_s.h>
#include <odb/core.hxx>
#include <odb/database.hxx>
#include <odb/query.hxx>
namespace repository
{
BookRepository::BookRepository(odb::core::database& db) :
m_db(db)
{}
QVector<Book_S> BookRepository::findAll()
{
odb::transaction t(m_db.begin());
odb::result<Book_S> res(m_db.query<Book_S>());
QVector<Book_S> books;
for (auto it = res.begin(); it != res.end(); ++it)
{
const auto& book = *it;
books.push_back(book);
}
t.commit();
return books;
}
Book_S BookRepository::findById(int id)
{
odb::transaction t(m_db.begin());
odb::result<Book_S> res(m_db.query<Book_S>(odb::query<Book_S>::id == id));
Book_S book;
res.value(book);
t.commit();
return book;
}
// void BookRepository::save(const Book_S& book)
// {
// }
void BookRepository::remove(int id)
{
odb::transaction t(m_db.begin());
odb::result<Book_S> res(m_db.query<Book_S>(odb::query<Book_S>::id == id));
res.one().reset();
t.commit();
}
QVector<Book_S> BookRepository::findByAuthor(const int& authorId)
{
odb::transaction t(m_db.begin());
QVector<Book_S> books;
using ABQuery = odb::query<AuthorBook_S>;
using ABResult = odb::result<AuthorBook_S>;
ABResult abResult(m_db.query<AuthorBook_S>(ABQuery::author == authorId));
for (const AuthorBook_S& ab : abResult)
{
// Загружаем каждую книгу по ID
SH<Book_S> book(m_db.load<Book_S>(ab.book()->id()));
books.push_back(*book.data());
}
t.commit();
return books;
}
QVector<Book_S> BookRepository::findByAuthor(const QString& author)
{
odb::transaction t(m_db.begin());
auto author_s = m_db.query<Author_S>(odb::query<Author_S>::fullName == author).one();
return findByAuthor(author_s->id());
}
} // namespace repository

View File

@@ -1,41 +0,0 @@
#ifndef BOOKREPOSITORY_H
#define BOOKREPOSITORY_H
#include "repository_global.h"
#include <model/books/book_s.h>
#include <QString>
#include <QVector>
namespace repository
{
class REPOSITORY_EXPORT BookRepository
{
public:
BookRepository(odb::core::database& db);
// Получить все книги
QVector<Book_S> findAll();
// Найти книгу по ID
Book_S findById(int id);
// Сохранить книгу (создать или обновить)
// void save(const Book_S& book);
// Удалить книгу
void remove(int id);
// Найти книги по автору
QVector<Book_S> findByAuthor(const QString& authorName);
QVector<Book_S> findByAuthor(const int& authorId);
private:
odb::core::database& m_db;
};
} // namespace repository
#endif // BOOKREPOSITORY_H

View File

@@ -1,33 +0,0 @@
/*!
\qmltype cpp-opds
\inherits Project
\brief Описание
*/
PSLibrary {
name: "repository"
cpp.defines: [
"REPOSITORY_LIBRARY"
]
Depends { name: "Qt"; submodules: [ "core" ] }
Depends { name: "model" }
Depends { name: "rdbase" }
Depends { name: "odb.gen" }
Depends { name: "database" }
Group {
name: "cpp"
files: [
"**/*.h",
"**/*.cpp",
]
}
cpp.dynamicLibraries: [
"odb-sqlite",
"odb-qt",
"odb",
"sqlite3"
]
}

View File

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

View File

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

View File

@@ -5,13 +5,10 @@
#include <QJsonObject>
#include <QJsonValue>
#include <model/books/author_s-odb.hxx> // Должен быть здесь
#include <model/books/author_s.h>
#include <model/books/book_s-odb.hxx> // Должен быть здесь
#include <model/books/book_s.h>
#include <repository/authorrepository.h>
#include <repository/bookrepository.h>
#include <database/author_s-odb.hxx> // Должен быть здесь
#include <database/author_s.h>
#include <database/book_s-odb.hxx> // Должен быть здесь
#include <database/book_s.h>
#include <odb/core.hxx>
#include <odb/database.hxx>
@@ -66,90 +63,61 @@ QByteArray RestApiServer::processRequest(const QString& request)
if (request.startsWith("GET /books/author/"))
{
repository::BookRepository b(m_db);
QString author = request.section(' ', 1, 1).section('/', 3, 3).replace("%20", " ");
qWarning() << author;
auto books = b.findByAuthor(author);
quint64 ageReq = author.toInt();
QStringList nameParts = author.split(' ');
QString firstName = nameParts.size() > 0 ? nameParts[0] : "";
QString lastName = nameParts.size() > 1 ? nameParts[1] : "";
odb::transaction t(m_db.begin());
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["title"] = book.title();
j["name"] = book.name();
j["author"] = book.author()->full_name();
j["year"] = book.year();
jArray.push_back(j);
}
auto jDoc = QJsonDocument(jArray);
return "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n" + jDoc.toJson(QJsonDocument::Indented);
}
if (request.startsWith("GET /books/id"))
{
repository::BookRepository b(m_db);
QString book_id = request.section(' ', 1, 1).section('/', 3, 3).replace("%20", " ");
qWarning() << book_id;
auto book = b.findById(book_id.toInt());
QJsonObject j;
j["id"] = QString::number(book.id());
QJsonArray authors;
repository::AuthorRepository a(m_db);
for (const auto& author : a.findByBook(book.id()))
{
QJsonObject jj;
jj["id"] = QString::number(author.id());
jj["fullName"] = author.fullName();
authors.push_back(jj);
}
j["authors"] = authors;
j["title"] = book.title();
auto jDoc = QJsonDocument(j);
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"))
{
repository::BookRepository b(m_db);
odb::transaction t(m_db.begin());
odb::result<Book_S> res(m_db.query<Book_S>());
QJsonArray jArray;
for (const auto& book : b.findAll())
for (auto it = res.begin(); it != res.end(); ++it)
{
const auto& book = *it;
QJsonObject j;
j["id"] = QString::number(book.id());
j["title"] = book.title();
QJsonArray authors;
repository::AuthorRepository a(m_db);
for (const auto& author : a.findByBook(book.id()))
{
QJsonObject jj;
jj["id"] = QString::number(author.id());
jj["fullName"] = author.fullName();
authors.push_back(jj);
}
j["authors"] = authors;
j["title"] = 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 /authors"))
if (request.startsWith("GET /author"))
{
repository::AuthorRepository a(m_db);
auto res = a.findAll();
odb::transaction t(m_db.begin());
odb::result<Author_S> res(m_db.query<Author_S>());
QJsonArray jArray;
for (auto it = res.begin(); it != res.end(); ++it)
@@ -158,22 +126,13 @@ QByteArray RestApiServer::processRequest(const QString& request)
QJsonObject j;
j["id"] = QString::number(author.id());
j["fullName"] = author.fullName();
QJsonArray books;
repository::BookRepository b(m_db);
for (const auto& book : b.findByAuthor(author.id()))
{
QJsonObject jj;
jj["id"] = QString::number(book.id());
jj["title"] = book.title();
books.push_back(jj);
}
j["books"] = books;
j["first"] = author.firstName();
j["last"] = author.lastName();
j["age"] = author.age();
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);
}

View 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);
}

View 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);
};

View 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);
}

View 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
View 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"]
}
}

View 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

View 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

View 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
View 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

View 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
View 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

View File

@@ -0,0 +1,14 @@
import qbs
PSLibrary {
Depends { name: "Qt"; submodules: "sql"}
Group {
name: "cpp"
files: [
"**/*.h",
"**/*.cpp"
]
}
}

View File

@@ -1,101 +0,0 @@
#include "fb2extractor.h"
// FB2Extractor::FB2Extractor()
// {
// }
FB2Extractor::FB2Extractor(QuaZipFile& file) :
m_file(&file)
{
}
FB2Extractor::~FB2Extractor()
{
m_file.close();
}
Fb2Metadata FB2Extractor::parse()
{
bool isOpen = m_file.open(QIODevice::ReadOnly);
// int zipError = fb2File.getZipError();
if (!isOpen)
{
qWarning() << "file in extractor is not open";
return {};
}
QXmlStreamReader xmlData(&m_file);
Fb2Metadata meta;
QString currentElement;
bool inTitleInfo = false;
bool inAuthor = false;
QString currentAuthor;
while (!xmlData.atEnd())
{
switch (xmlData.readNext())
{
case QXmlStreamReader::StartElement:
currentElement = xmlData.name().toString();
if (currentElement == "title-info")
{
inTitleInfo = true;
}
else if (inTitleInfo)
{
if (currentElement == "book-title")
{
meta.title = xmlData.readElementText();
}
else if (currentElement == "genre")
{
meta.genres << xmlData.readElementText();
}
else if (currentElement == "author")
{
inAuthor = true;
currentAuthor.clear();
}
else if (inAuthor && (currentElement == "first-name" || currentElement == "last-name" || currentElement == "middle-name"))
{
currentAuthor += xmlData.readElementText() + " ";
}
}
break;
case QXmlStreamReader::EndElement:
if (xmlData.name().toString() == "title-info")
{
inTitleInfo = false;
}
else if (xmlData.name().toString() == "author" && inAuthor)
{
meta.authors << currentAuthor.trimmed();
inAuthor = false;
}
break;
case QXmlStreamReader::Characters:
// Обработка текста уже делается в readElementText()
break;
default:
break;
}
// Прерываем парсинг, если нашли все метаданные
if (!meta.title.isEmpty() && !meta.authors.isEmpty() && !meta.genres.isEmpty())
{
break;
}
}
if (xmlData.hasError())
{
qWarning() << "XML parsing error:" << xmlData.errorString();
}
return meta;
}

View File

@@ -1,36 +0,0 @@
#ifndef FB2EXTRACTOR_H
#define FB2EXTRACTOR_H
#include "utils_global.h"
#include <QDebug>
#include <QString>
#include <QXmlStreamReader>
#include <external_libs/quazip/quazip/quazipfile.h>
struct Fb2Metadata
{
QString title; // Название книги
QVector<QString> authors; // Авторы
QStringList genres; // Жанры
};
Fb2Metadata UTILS_EXPORT parseFb2Metadata(QXmlStreamReader& sr);
class UTILS_EXPORT FB2Extractor
{
public:
FB2Extractor(QuaZipFile& file);
~FB2Extractor();
/*!
* \brief Распарсить инфу из содержимого
*/
Fb2Metadata parse();
private:
QuaZipFile m_file;
};
#endif // FB2EXTRACTOR_H

View File

@@ -1,22 +0,0 @@
/*!
\qmltype cpp-opds
\inherits Project
\brief Описание
*/
PSLibrary {
name: "utils"
cpp.defines: [
"UTILS_LIBRARY"
]
Depends { name: "Qt"; submodules: [ "core" ] }
Depends { name: "quazip" }
Group {
name: "cpp"
files: [
"**/*.h",
"**/*.cpp",
]
}
}

View File

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

View File

@@ -1,142 +0,0 @@
#include "zipwrapper.h"
#include "fb2extractor.h"
#include <external_libs/quazip/quazip/quazipfile.h>
namespace
{
Fb2Metadata parse(QuaZipFile& m_file)
{
bool isOpen = m_file.open(QIODevice::ReadOnly);
// int zipError = fb2File.getZipError();
if (!isOpen)
{
qWarning() << "file in extractor is not open";
return {};
}
QXmlStreamReader xmlData(&m_file);
Fb2Metadata meta;
QString currentElement;
bool inTitleInfo = false;
bool inAuthor = false;
QString currentAuthor;
while (!xmlData.atEnd())
{
switch (xmlData.readNext())
{
case QXmlStreamReader::StartElement:
currentElement = xmlData.name().toString();
if (currentElement == "title-info")
{
inTitleInfo = true;
}
else if (inTitleInfo)
{
if (currentElement == "book-title")
{
meta.title = xmlData.readElementText();
}
else if (currentElement == "genre")
{
meta.genres << xmlData.readElementText();
}
else if (currentElement == "author")
{
inAuthor = true;
currentAuthor.clear();
}
else if (inAuthor && (currentElement == "first-name" || currentElement == "last-name" || currentElement == "middle-name"))
{
currentAuthor += xmlData.readElementText() + " ";
}
}
break;
case QXmlStreamReader::EndElement:
if (xmlData.name().toString() == "title-info")
{
inTitleInfo = false;
}
else if (xmlData.name().toString() == "author" && inAuthor)
{
meta.authors << currentAuthor.trimmed();
inAuthor = false;
}
break;
case QXmlStreamReader::Characters:
// Обработка текста уже делается в readElementText()
break;
default:
break;
}
// Прерываем парсинг, если нашли все метаданные
if (!meta.title.isEmpty() && !meta.authors.isEmpty() && !meta.genres.isEmpty())
{
break;
}
}
if (xmlData.hasError())
{
qWarning() << "XML parsing error:" << xmlData.errorString();
}
return meta;
}
} // namespace
ZipWrapper::ZipWrapper(const QString& zipFilePath) :
m_zip(zipFilePath)
{
m_zip.open(QuaZip::mdUnzip);
isOpen();
}
ZipWrapper::~ZipWrapper()
{
// В любом случае закрываем архив
m_zip.close();
}
QVector<Fb2Metadata> ZipWrapper::work()
{
if (!isOpen())
return {};
// int i = 0;
QVector<Fb2Metadata> parsedBooks;
for (bool more = m_zip.goToFirstFile(); more; more = m_zip.goToNextFile())
{
// ++i;
if (m_zip.getCurrentFileName().endsWith(".fb2"))
{
QuaZipFile fb2File(&m_zip);
auto fb2Extr = parse(fb2File);
// qWarning() << i << ":" << fb2Extr.title << fb2Extr.authors << fb2Extr.genres;
parsedBooks.push_back(fb2Extr);
}
else
qWarning() << "Неизвестный файл" << &m_zip;
}
return parsedBooks;
}
bool ZipWrapper::isOpen()
{
if (m_zip.isOpen())
return true;
qWarning() << "Не удалось открыть архив:" << m_zip.getZipName();
return false;
}

View File

@@ -1,29 +0,0 @@
#ifndef ZIPWRAPPER_H
#define ZIPWRAPPER_H
#include "utils_global.h"
#include <QDebug>
#include <QString>
#include <QXmlStreamReader>
#include <external_libs/quazip/quazip/quazip.h>
#include <external_libs/quazip/quazip/quazipfile.h> // TODO для совместимости. Временно
#include "fb2extractor.h"
class UTILS_EXPORT ZipWrapper
{
public:
ZipWrapper(const QString& zipFilePath);
~ZipWrapper();
QVector<Fb2Metadata> work();
private:
bool isOpen();
QuaZip m_zip;
};
#endif // ZIPWRAPPER_H