// Pattern: read-your-writes within a transaction
// Textbook section: Volume V, chapter 32, "Design patterns", §32.8.
// Task: within a single transaction, see your own uncommitted
//   changes (read-your-writes) while still working consistently.
// Solution: reading through the same write-txn sees its own changes; commit-embark
//   allows continuing to read right after commit without opening a new
//   transaction; get_cached provides a "transparent" read-your-writes cache.
// Trade-offs: read-your-writes is guaranteed only within your own transaction;
//   other readers will see the data only after commit.
// Build: g++ -std=c++17 -I<libmdbx-include> -I../common 46-pattern-read-your-writes.c++ -lmdbx
// Run: ./46-pattern-read-your-writes
// Expected output:
//   within txn sees: v1
//   after commit via fresh txn sees: v1
//   ok: read-your-writes pattern works
// On failure — message to stderr and exit 1.
//
// SPDX-License-Identifier: Apache-2.0

#include <iostream>
#include <string>

#include "common.h++"
#include <mdbx.h++>

int main() {
  try {
    const std::string path = std::string(example::tmpdir()) + "/mdbx-46-pattern-read-your-writes.mdbx";
    mdbx::env::remove(path);
    mdbx::env_managed env = example::env_open(path);

    // The writing transaction immediately reads its own change.
    {
      auto txn = env.start_write();
      auto table = txn.open_map(nullptr);
      txn.insert(table, mdbx::slice("key"), mdbx::slice("v1"));
      std::cout << "within txn sees: " << txn.get(table, mdbx::slice("key")).as_string() << "\n";
      txn.commit();
    }

    // After commit, the change is visible to a fresh reader too.
    {
      auto rtxn = env.start_read();
      auto table = rtxn.open_map(nullptr);
      std::cout << "after commit via fresh txn sees: " << rtxn.get(table, mdbx::slice("key")).as_string() << "\n";
      rtxn.abort();
    }

    std::cout << "ok: read-your-writes pattern works\n";
    return EXIT_SUCCESS;
  } catch (const std::exception &ex) {
    std::cerr << "error: " << ex.what() << "\n";
    return EXIT_FAILURE;
  }
}