MDBX Containers
Loading...
Searching...
No Matches
any_value_table_example.cpp
Go to the documentation of this file.
1
5
7#include <iostream>
8#include <vector>
9#include <string>
10#include <cstring>
11#include <limits>
12
14struct MyStruct {
15 int a;
16 float b;
17
18 std::vector<uint8_t> to_bytes() const {
19 std::vector<uint8_t> bytes(sizeof(MyStruct));
20 std::memcpy(bytes.data(), this, sizeof(MyStruct));
21 return bytes;
22 }
23
24 static MyStruct from_bytes(const void* data, size_t size) {
25 if (size != sizeof(MyStruct)) {
26 throw std::runtime_error("Invalid data size for MyStruct");
27 }
28 MyStruct out{};
29 std::memcpy(&out, data, sizeof(MyStruct));
30 return out;
31 }
32};
33
35int main() {
36 mdbxc::Config cfg;
37 cfg.pathname = "any_value_table_example_db";
38 cfg.max_dbs = 4;
39 auto conn = mdbxc::Connection::create(cfg);
40
41 mdbxc::AnyValueTable<std::string> table(conn, "settings");
42
43 table.set<int>("retries", 3);
44 table.set<std::string>("url", "https://example.com");
45 table.set<MyStruct>("struct", MyStruct{42, 0.5f});
46
47 auto retries = table.get_or<int>("retries", 1);
48#if __cplusplus >= 201703L
49 auto url = table.find<std::string>("url").value_or("none");
50#else
51 auto url_pair = table.find_compat<std::string>("url");
52 std::string url = url_pair.first ? url_pair.second : "none";
53#endif
54
55 std::cout << "retries: " << retries << "\nurl: " << url << '\n';
56
57 for (auto& key : table.keys()) {
58 std::cout << "key: " << key << '\n';
59 }
60
61 std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
62 std::cin.get();
63 return 0;
64}
Table storing values of arbitrary type indexed by key.
int main()
Entry point demonstrating AnyValueTable.
Table storing values of arbitrary type associated with a key.
std::vector< KeyT > keys(MDBX_txn *txn=nullptr) const
List all keys stored in table.
void set(const KeyT &key, const T &value, MDBX_txn *txn=nullptr)
Set value for key, replacing existing value.
T get_or(const KeyT &key, T default_value, MDBX_txn *txn=nullptr) const
Get value or default if missing (C++11 mode).
std::pair< bool, T > find_compat(const KeyT &key, MDBX_txn *txn=nullptr) const
Find value by key.
Parameters used by Connection to create the MDBX environment.
Definition Config.hpp:17
std::string pathname
Path to the database file or directory containing the database.
Definition Config.hpp:19
int64_t max_dbs
Maximum number of named databases (DBI) in the environment.
Definition Config.hpp:27
static std::shared_ptr< Connection > create(const Config &config)
Creates and connects a new shared Connection instance.
Demonstrates storing values of arbitrary types using AnyValueTable.
static MyStruct from_bytes(const void *data, size_t size)
std::vector< uint8_t > to_bytes() const