add Sql and subsys::Database

This commit is contained in:
falsycat 2023-09-03 08:25:15 +09:00
parent 78eb81d7a8
commit 47c75c4564
3 changed files with 110 additions and 0 deletions

View File

@ -17,6 +17,8 @@ target_sources(nf7_iface
common/leak_detector.hh
common/mutex.hh
common/observer.hh
common/observer.hh
common/sql.hh
common/task.hh
common/task_context.hh
common/value.hh
@ -25,6 +27,7 @@ target_sources(nf7_iface
data/interface.hh
data/wrap.hh
subsys/concurrency.hh
subsys/database.hh
subsys/interface.hh
subsys/logger.hh
subsys/parallelism.hh

63
iface/common/sql.hh Normal file
View File

@ -0,0 +1,63 @@
// No copyright
#pragma once
#include <cstdint>
#include <functional>
#include <string>
#include <variant>
#include <vector>
#include "iface/common/future.hh"
#include "iface/common/void.hh"
namespace nf7 {
class Sql {
public:
class Command;
public:
struct Null final { };
using Value = std::variant<Null, int64_t, double, std::string>;
enum Result {
kRow,
kDone,
};
public:
Sql() = default;
virtual ~Sql() = default;
Sql(const Sql&) = delete;
Sql(Sql&&) = delete;
Sql& operator=(const Sql&) = delete;
Sql& operator=(Sql&&) = delete;
public:
virtual void Bind(uint64_t idx, const Value&) = 0;
virtual Value Fetch(uint64_t idx) const = 0;
virtual void Reset() = 0;
virtual Result Exec() = 0;
};
class Sql::Command {
public:
using Handler = std::function<void(Sql&)>;
public:
Command() = default;
virtual ~Command() = default;
Command(const Command&) = delete;
Command(Command&&) = delete;
Command& operator=(const Command&) = delete;
Command& operator=(Command&&) = delete;
public:
virtual Future<Void> Run(Handler&&) noexcept = 0;
};
} // namespace nf7

44
iface/subsys/database.hh Normal file
View File

@ -0,0 +1,44 @@
// No copyright
#pragma once
#include <functional>
#include <memory>
#include <string_view>
#include <utility>
#include "iface/common/future.hh"
#include "iface/common/observer.hh"
#include "iface/common/sql.hh"
#include "iface/common/void.hh"
#include "iface/subsys/interface.hh"
namespace nf7::subsys {
class Database : public Interface, public Observer<Void>::Target {
public:
using ColumnHandler = std::function<bool(const Sql&)>;
public:
using Interface::Interface;
public:
virtual Future<std::shared_ptr<Sql::Command>> Compile(
std::string_view) noexcept = 0;
virtual Future<Void> Exec(
std::string_view cmd, ColumnHandler&& f = {}) noexcept {
return Compile(cmd)
.ThenAnd([f = std::move(f)](auto& x) mutable {
return !f?
Future<Void> {Void {}}:
x->Run([f = std::move(f)](auto& x) mutable {
while (Sql::kRow == x.Exec()) {
f(x);
}
});
});
}
};
} // namespace nf7::subsys