DataReelDataReelC++ Transition Guide

Examples › Database Examples

database_btree_node

C++17 or laterDataReel 6.4.3Portable C++ (tested on Linux)

Legacy: examples_database/btree_node/testprog.cpp · Modern: examples_modern/database/btree_node/modern.cpp

Modern equivalent of the B-tree node test. BtreeNode is DataReel's on-disk node, so it stays; the program inserts keys into one node in order, writes the node to a gxDatabase file and reads it back, deletes a key and splits the node. The modern parts are the key class (array storage, string_view access, correct copies), a std::vector of the keys, and a node printer that is a lambda. The node is written with BtreeNode's own sizes, not with field by field writes, and the file is removed with std::filesystem.

Legacy calls in this program

LegacyModern C++StandardNotes
new / deleteautomatic objects, containers, std::unique_ptr / std::make_uniqueC++11 / C++14Ownership is in the type, and release() shows a hand-over.
strcpy(), strncpy(), memmove() into char arraysstd::string; std::array<char, N> + string_view::copy()C++11 / C++17
gxDatabasekeep gxDatabase: a stack object, errors as exceptions, static_assert(std::is_trivially_copyable_v<Record>)C++17The standard library has no database file; the file format is DataReel's.
gxBtree, DatabaseKeyB key classeskeep gxBtree; key classes with std::array storage and correct copies (rule of three); std::set for in-memory indexesC++11 / C++17DatabaseKeyB's copy keeps the other object's db_key pointer: define the copies.

From the transition tables.

Side by side

DataReel 6.4 (legacy)

examples_database/btree_node/testprog.cpp 206 lines
#include "gxdlcode.h"

#if defined (__USE_ANSI_CPP__) // Use the ANSI Standard C++ library
#include <iostream>
using namespace std; // Use unqualified names for Standard C++ library
#else // Use the old iostream library by default
#include <iostream.h>
#endif // __USE_ANSI_CPP__

#include "btnode.h"
#include "gxdbase.h"

// Set the node order and maximum key size for this key class
const BtreeNodeOrder_t MyKeyClassOrder = 8;
const __WORD__ MyKeyNameSize = 26;

// Key class for this database
class MyKeyClass : public DatabaseKeyB
{
public:
  MyKeyClass();
  MyKeyClass(const char *name);
  void operator=(const char *name);
  ~MyKeyClass() { }

public: // Base class interface
  size_t KeySize() { return sizeof(key_name); }
  int operator==(const DatabaseKeyB& key) const;
  int operator>(const DatabaseKeyB& key) const;
  
  // NOTE: This comparison function is only used if the 
  // __USE_SINGLE_COMPARE__ preprocessor directive is 
  // defined when the program is compiled.
  int CompareKey(const DatabaseKeyB& key) const;

public: // Persistent data member
  char key_name[MyKeyNameSize];
};

MyKeyClass::MyKeyClass() : DatabaseKeyB((char *)key_name)
{
  for(int i = 0; i < MyKeyNameSize; i++) key_name[i] = 0;
}

MyKeyClass::MyKeyClass(const char *name) : DatabaseKeyB((char *)key_name)
{
  for(int i = 0; i < MyKeyNameSize; i++) key_name[i] = 0;
  strcpy(key_name, name);
}

void MyKeyClass::operator=(const char *name)
{
  for(int i = 0; i < MyKeyNameSize; i++) key_name[i] = 0;
  strcpy(key_name, name);
}

int MyKeyClass::operator==(const DatabaseKeyB& key) const
{
  const MyKeyClass *kptr = (const MyKeyClass *)(&key);
  return (strcmp(key_name, (char *)kptr->db_key) == 0);
}

int MyKeyClass::operator>(const DatabaseKeyB& key) const
{
  const MyKeyClass *kptr = (const MyKeyClass *)(&key);
  return (strcmp(key_name, (char *)kptr->db_key) > 0);
}

int MyKeyClass::CompareKey(const DatabaseKeyB& key) const
// NOTE: This comparison function is only used if the 
// __USE_SINGLE_COMPARE__ preprocessor directive is 
// defined when the program is compiled.
{
  const MyKeyClass *kptr = (const MyKeyClass *)(&key);
  return strcmp(key_name, (char *)kptr->db_key);
}

void PrintNode(BtreeNode &n)
// Print a Btree node.
{
  MyKeyClass kbuf;
  BtreeKeyLocation_t key_location = (BtreeKeyLocation_t)0;
  for(BtreeKeyCount_t i = (BtreeKeyCount_t)0; i < n.key_count; i++) {
    n.LoadKey(kbuf, key_location++);
    cout << (char *)kbuf.key_name << ' ' << (long)kbuf.right_child << ' ';
    // NOTE: The right child FAU is cast to a long for compilers
    // with native 64-bit int ostream overloads
  }
  cout << "\n";
  cout << "Key count = " << n.key_count << "\n";
  cout << "Left child = " << (long)n.left_child << "\n";
  // NOTE: The left child FAU is cast to a long for compilers
  // with native 64-bit int ostream overloads
}

void PausePrg()
// Pause the program.
{
  cout << "\n";
  cout << "Press enter to continue..." << "\n";
  cin.get();
}

gxDatabaseError WriteNode(gxDatabase *f, const BtreeNode &n, FAU_t na)
// Function used to write a Btree node to an open database file.
// Returns zero if successful or a non-zero value to indicate a
// failure. 
{
  gxDatabaseError rv;
  rv = f->Write(&n.key_count, sizeof(n.key_count), na);
  if(rv != gxDBASE_NO_ERROR) return rv;
  rv = f->Write(&n.left_child, sizeof(n.left_child));
  if(rv != gxDBASE_NO_ERROR) return rv;
  rv = f->Write(n.key_entries, (n.key_size * n.node_order));
  if(rv != gxDBASE_NO_ERROR) return rv;
  return rv;
}

gxDatabaseError ReadNode(gxDatabase *f, BtreeNode &n, FAU_t na)
// Function used to read a Btree node from an open database file.
// Returns zero if successful or a non-zero value to indicate a
// failure. 
{
  gxDatabaseError rv;
  rv = f->Read(&n.key_count, sizeof(n.key_count), na);
  if(rv != gxDBASE_NO_ERROR) return rv;
  rv = f->Read(&n.left_child, sizeof(n.left_child));
  if(rv != gxDBASE_NO_ERROR) return rv;
  rv = f->Read(n.key_entries, (n.key_size * n.node_order));
  if(rv != gxDBASE_NO_ERROR) return rv;
  return rv;
}

int main()
{
  MyKeyClass key, compare_key;

  cout << "--------- Key and B-tree Node Statistics ---------" << "\n";
  cout << "Key name size     = " << key.KeySize() << "\n";
  cout << "Database key size = " << key.SizeOfDatabaseKey() << "\n";
  cout << "Key entry size    = "
       << (key.SizeOfDatabaseKey() * (MyKeyClassOrder-1)) << "\n";
  BtreeNode n(key.SizeOfDatabaseKey(), MyKeyClassOrder);
  cout << "B-tree order      = " << n.node_order << "\n";
  cout << "B-tree node size  = " << n.SizeOfBtreeNode() << "\n";

  PausePrg();
  
  BtreeKeyLocation_t key_location = (BtreeKeyLocation_t)0;
  int i, rv;
  const char *strings[7] = { // Array matching the Btree order
    "DOG", "CAT", "PIG", "COW", "FISH", "ZEBRA", "HORSE" 
  };

  cout << "Inserting " << n.node_order << " entries into the Btree node"
       << "\n";
  for(i = 0; i < n.node_order; i++) {
    key = strings[i];

    rv = n.FindKeyLocation(key, compare_key, key_location);

    // Do not insert duplicate keys
    if(rv != 0) {
      key_location++;
      n.InsertDatabaseKey(key, key_location);
    }
  }

  cout << "Reading back the database keys" << "\n";
  PrintNode(n);

  PausePrg();
  
  cout << "Testing database read/write operations" << "\n";
  gxDatabase *f = new gxDatabase();
  f->Create("testfile.gxd");
  FAU_t node_address = f->Alloc(n.SizeOfBtreeNode());
  WriteNode(f, n, node_address);
  BtreeNode nbuf(key.SizeOfDatabaseKey(), MyKeyClassOrder);
  ReadNode(f, nbuf, node_address);
  PrintNode(nbuf);
  delete f;

  PausePrg();
  
  cout << "Testing the delete function" << "\n";
  n.DeleteDatabaseKey((BtreeKeyLocation_t)0);
  PrintNode(n);

  PausePrg();
  
  cout << "Testing the split fucntion" << "\n";
  BtreeNode r(key.SizeOfDatabaseKey(), MyKeyClassOrder);
  n.SplitNode(r, n.node_order/2);
  PrintNode(n);
  cout << "\n";
  PrintNode(r);

  cout << "\n";
  cout << "Exiting..." << "\n";
  return 0;
}
// ----------------------------------------------------------- //
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Modern C++ (C++17)

examples_modern/database/btree_node/modern.cpp 88 lines
#include <algorithm>
#include <array>
#include <cstring>
#include <filesystem>
#include <iostream>
#include <string_view>
#include <vector>

#include "btnode.h"
#include "gxdbase.h"

class NameKey : public DatabaseKeyB {
public:
  NameKey() : DatabaseKeyB(key_.data()) {}
  NameKey(const NameKey &o) : DatabaseKeyB(key_.data()), key_(o.key_) { right_child = o.right_child; }
  NameKey &operator=(const NameKey &o) { key_ = o.key_; right_child = o.right_child; return *this; }
  void assign(std::string_view s) { key_.fill(0); s.copy(key_.data(), std::min<std::size_t>(s.size(), 63)); }
  std::string_view name() const { return key_.data(); }
  size_t KeySize() override { return key_.size(); }
  int CompareKey(const DatabaseKeyB &k) const
  { return std::strncmp(key_.data(), static_cast<const char *>(k.db_key), key_.size()); }
  int operator==(const DatabaseKeyB &k) const { return CompareKey(k) == 0; }
  int operator>(const DatabaseKeyB &k) const { return CompareKey(k) > 0; }
private:
  std::array<char, 64> key_{};
};

int main()
{
  const BtreeNodeOrder_t order = 7;
  NameKey key, compare_key;
  BtreeNode n(key.SizeOfDatabaseKey(), order);
  std::cout << "Key entry size = " << key.SizeOfDatabaseKey() * (order - 1)
            << ", node size = " << n.SizeOfBtreeNode() << "\n";

  auto print = [](BtreeNode &node, const char *label) {
    NameKey k;
    std::cout << label << " (" << node.key_count << " keys):";
    for(BtreeKeyCount_t i = 0; i < node.key_count; i++) {
      node.LoadKey(k, BtreeKeyLocation_t(i));
      std::cout << ' ' << k.name();
    }
    std::cout << "\n";
  };

  const std::vector<std::string_view> names = {"DOG", "CAT", "PIG", "COW",
                                               "FISH", "ZEBRA", "HORSE"};
  for(auto s : names) {
    // BtreeNode holds order-1 keys and InsertDatabaseKey() does not
    // check: inserting into a full node writes past its buffer.
    if(n.IsFull()) { std::cout << "Node is full, " << s << " not inserted\n"; continue; }
    key.assign(s);
    BtreeKeyLocation_t loc = 0;
    if(n.FindKeyLocation(key, compare_key, loc) != 0)  // Not a duplicate
      n.InsertDatabaseKey(key, loc + 1);
  }
  print(n, "Node");

  const std::filesystem::path fname = "modern_btree_node.gxd";
  {
    gxDatabase f;
    f.Create(fname.string().c_str());
    FAU_t addr = f.Alloc(__ULWORD__(n.SizeOfBtreeNode()));
    f.Write(&n.key_count, sizeof n.key_count, addr);
    f.Write(&n.left_child, sizeof n.left_child);
    f.Write(n.key_entries, __ULWORD__(n.SizeOfBtreeNode() - sizeof n.key_count - sizeof n.left_child));
    BtreeNode back(key.SizeOfDatabaseKey(), order);
    f.Read(&back.key_count, sizeof back.key_count, addr);
    f.Read(&back.left_child, sizeof back.left_child);
    f.Read(back.key_entries, __ULWORD__(back.SizeOfBtreeNode() - sizeof back.key_count - sizeof back.left_child));
    print(back, "Read back");
    if(f.GetDatabaseError() != gxDBASE_NO_ERROR)
      std::cout << f.DatabaseExceptionMessage() << "\n";
  } // ~gxDatabase() closes the file
  std::filesystem::remove(fname);

  n.DeleteDatabaseKey(0);
  print(n, "After deleting the first key");
  BtreeNode right(key.SizeOfDatabaseKey(), order);
  n.SplitNode(right, n.node_order / 2);
  print(n, "Left half");
  print(right, "Right half");
  return 0;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Build and run

cmake -S examples_modern -B build-modern -DCMAKE_CXX_STANDARD=17
cmake --build build-modern --target database_btree_node
./build-modern/database_btree_node

Output of the modern program

From run_modern_tests.sh on RHEL 10, GCC 14, C++20.

Key entry size = 432, node size = 448
Node is full, HORSE not inserted
Node (6 keys): CAT COW DOG FISH PIG ZEBRA
Read back (6 keys): CAT COW DOG FISH PIG ZEBRA
After deleting the first key (5 keys): COW DOG FISH PIG ZEBRA
Left half (3 keys): COW DOG FISH
Right half (2 keys): PIG ZEBRA