DataReelDataReelC++ Transition Guide

Examples › Database Examples

database_database

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

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

Modern equivalent of the 32-bit/64-bit engine comparison. The engine is chosen when the library is built (DATAREEL_64BIT_DATABASE); this program shows which one it was built with through the size of FAU_t and std::numeric_limits, adds objects to a file with a static area, reads every one back by walking the blocks, and times both with std::chrono::steady_clock (the legacy program used clock(), which measures CPU time, not elapsed time). Names are made with C++20 std::format instead of sprintf() into a fixed buffer.

Legacy calls in this program

LegacyModern C++StandardNotes
gxString / UStringstd::string, std::string_viewC++98 / C++17string_view looks at text without copying it.
SetWidth(), SetFill(), Precision(), sprintf()std::format("{:*>10} {:.3f}", ...)C++20C++17 and older: <iomanip> setw, setfill, setprecision.
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
clock(), SysTime, GetSystemTime()std::chrono::steady_clock (elapsed), system_clock (calendar)C++11clock() is CPU time, not elapsed time.
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.

From the transition tables.

Side by side

DataReel 6.4 (legacy)

examples_database/database/testprog.cpp 246 lines
#include "gxdlcode.h"

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

#include <string.h>
#include <time.h>
#include "gxfloat.h"
#include "gxdbase.h"
#include "gxdstats.h"
#include "ustring.h"

// Various static data area sizes used to test large files
const FAU_t STATIC_AREA_SIZE = (FAU_t)255*255;

// 1 GIG file test                              
// WARNING: This test requires 1.1 GIG of free disk space
// const FAU_t STATIC_AREA_SIZE = (FAU_t)1100000000;

// 2.1 GIG file test                              
// WARNING: This test requires 2.1 GIG of free disk space
// const FAU_t STATIC_AREA_SIZE = (FAU_t)2100000000;
                                                   
// 2.1 GIG large file test                               
// WARNING: This test requires 2.3 GIG of free disk space
// const FAU_t_ STATIC_AREA_SIZE = (__LLWORD__)2147483647;

// 4 GIG large file test
// WARNING: This test requires 4.3 GIG of free disk space
// const FAU_t_ STATIC_AREA_SIZE = (__LLWORD__)4294967290;

const int NAME_LENGTH = 64;

class DatabaseObject
{ 
public:
  DatabaseObject() { name[0] = 0; oid = (FAU)0, cid = (gxFLOAT64)0; }
  DatabaseObject(const char *s, long i, double d);

public:
  void DisplayObject();
  
public: // Platform independent data members
  char name[NAME_LENGTH]; // Fixed string type
  FAU oid;                // Integer type
  gxFLOAT64 cid;          // Floating point type
};

DatabaseObject::DatabaseObject(const char *s, long i, double d)
{
  for(int j = 0; j < NAME_LENGTH; j++) name[j] = 0; // Clear the name string
  strcpy(name, s);
  oid = i;  
  cid = d;
}

void DatabaseObject::DisplayObject()
{
  UString intbuf;
  cout << "Database object name: " << name << "\n";
  intbuf << (FAU_t)oid;
  cout << "Database object OID:  " << intbuf.c_str() << "\n";
  cout.setf(ios::showpoint | ios::fixed);
  cout.precision(3);
  cout << "Database object CID:  " << cid << "\n";
}

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

int main(int argv, char **argc)
{
  const char *fname = "simple.gxd"; // File name of this database
  char rev_letter = gxDatabaseRevisionLetter; // Set the default rev letter
  if(argv == 2) { // Set a specified revision letter
    rev_letter = *argc[1];
    if(rev_letter == '0') rev_letter = '\0';
    // Valid rev letters are:
    // Rev 0
    // Rev 'A' or 'a'
    // Rev 'B' or 'b'
    // Rev 'C' or 'c'
    // Rev 'D' or 'd'
    // Rev 'E' or 'e'
    // NOTE: The gxDatabase class will set invalid revision letters
    // to the version set by the gxDatabaseRevisionLetter constant.  
  }

  // Adjust this number to set the number of insertions
  const unsigned long INSERTIONS = 1 * 1000;       // 1K test
  // const unsigned long INSERTIONS = 10 * 1000;      // 10K test
  // const unsigned long INSERTIONS = 100 * 1000;     // 100K test
  // const unsigned long INSERTIONS = 1000 * 1000;    // 1MEG test
  // const unsigned long INSERTIONS = 10000 * 1000;   // 10MEG test
  // const unsigned long INSERTIONS = 100000 * 1000;  // 100MEG test
  // const unsigned long INSERTIONS = 1000000 * 1000; // 1GIG test

  gxDatabase *f = new gxDatabase(); 
  unsigned long i;
  FAU_t static_area_size(STATIC_AREA_SIZE);
  DatabaseObject buf;
  
  cout << "\n";
  cout << "Insertion time benchmark of the database engine." << "\n";
  
  cout << "Creating new file..." << "\n";
  f->Create(fname, static_area_size, rev_letter);
  if(CheckError(f) != 0) {
    delete f;
    return 1;
  }

  PausePrg();
  DatabaseStats(f);
  PausePrg();

  cout << "Adding " << INSERTIONS << " objects to the database file..." 
       << "\n";
  cout << "Size of each object = " << sizeof(DatabaseObject) << "\n";
  PausePrg();
  
  unsigned long curr_count = 0;
  double insert_time = 0;
  
  // Get CPU clock cycles before entering loop
  clock_t begin = clock();

  for(i = 0; i < INSERTIONS; i++) {
    // Construct the datbase object
    char name[NAME_LENGTH];
    sprintf(name, "Mouse %i", (int)i);
    DatabaseObject ob(name, (FAU_t)i, 5000.101);

    clock_t begin_insert = clock();  
    f->Alloc(sizeof(DatabaseObject));
    if(CheckError(f) != 0) {
      delete f; 
      // The gxDatabase destructor will close the database file
      // but in an application the Close() call should be tested 
      // to prevent any possible data corruption. 
      return 1;
    }
    f->Write(&ob, sizeof(DatabaseObject));
    if(CheckError(f) != 0) {
      delete f;
      return 1;
    }
    clock_t end_insert = clock();
    insert_time += (double)(end_insert - begin_insert) / CLOCKS_PER_SEC;
    curr_count++;

    if(CheckError(f) != 0) {
      delete f;
      return 1;
    }
    
    if(curr_count == 10000) {
      curr_count = 0;
      cout << "Inserted " << i << " objects in " << insert_time
	   << " seconds" << "\n";
    }
  }
  
  // Get CPU clock cycles after loop is completed 
  clock_t end = clock();

  // Calculate the elapsed time in seconds. 
  double elapsed_time = (double)(end - begin) / CLOCKS_PER_SEC;
  cout.precision(3); 
  cout << "Inserted " << i << " values in " 
       << elapsed_time << " seconds" << "\n";
  double avg_insert_time = (insert_time/(double)i) * 1000;
  cout << "Average insert time = " << avg_insert_time << " milliseconds"  
       << "\n"; 
  
  PausePrg();

  cout << "Testing the flush the function following batch insert" << "\n";
  f->Flush();

  PausePrg();
  
  cout << "Reading " << INSERTIONS << " objects from the database file..." 
       << "\n";
  PausePrg();

  double search_time = 0;  
  curr_count = 0;
  FAU_t offset = f->GetHeapStart() + f->BlockHeaderSize();
  begin = clock();

  for(i = 0; i < INSERTIONS; i++) {
    clock_t begin_search = clock();
    f->Read(&buf, sizeof(buf), offset);
    clock_t end_search = clock();
    search_time += (double)(end_search - begin_search) / CLOCKS_PER_SEC;
    if(CheckError(f) != 0) {
      delete f;
      return 1;
    }
    curr_count++;
    offset += (f->BlockHeaderSize() + sizeof(buf)); 
    if(curr_count == 10000) {
      curr_count = 0;
      cout << "Read " << i << " objects in " << search_time
	   << " seconds" << "\n";
    }
  }
  
  end =clock();
  elapsed_time = (double)(end - begin) / CLOCKS_PER_SEC;
  cout.precision(3);
  cout << "Verified " << i << " values in " 
       << elapsed_time << " seconds" << "\n";
  double avg_search_time = (search_time/(double)i) * 1000;
  cout << "Average search time = " << avg_search_time << " milliseconds"
       << "\n";

  PausePrg();
  DatabaseStats(f);
  PausePrg();

  cout << "Exiting..." << "\n";
  f->Close();
  if(CheckError(f) != 0) {
    delete f;
    return 1;
  }

  delete f;
  return 0; 
}
// ----------------------------------------------------------- //
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Modern C++ (C++20)

examples_modern/database/database/modern.cpp 88 lines
#include <array>
#include <chrono>
#include <cstdint>
#include <filesystem>
#include <format>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <string>
#include <type_traits>

#include "gxdbase.h"

struct DatabaseObject {
  std::array<char, 64> name{};
  std::int64_t oid = 0;
  double cid = 0;
};
static_assert(std::is_trivially_copyable_v<DatabaseObject>);

void check(gxDatabase &f)
{
  if(f.GetDatabaseError() != gxDBASE_NO_ERROR)
    throw std::runtime_error(f.DatabaseExceptionMessage());
}

int main()
{
  using clock = std::chrono::steady_clock;
  const std::filesystem::path fname = "modern_database.gxd";
  const unsigned long INSERTIONS = 1000;
  const FAU_t STATIC_AREA_SIZE = FAU_t(255) * 255;

#if defined(__64_BIT_DATABASE_ENGINE__)
  std::cout << "Database engine: 64-bit (DATAREEL_64BIT_DATABASE=ON)\n";
#else
  std::cout << "Database engine: 32-bit (DATAREEL_64BIT_DATABASE=OFF)\n";
#endif
  std::cout << std::format("FAU_t: {} bytes in memory, max {}\n",
                           sizeof(FAU_t), std::numeric_limits<FAU_t>::max());
  try {
    gxDatabase f;
    f.Create(fname.string().c_str(), STATIC_AREA_SIZE);
    check(f);

    auto start = clock::now();
    for(unsigned long i = 0; i < INSERTIONS; i++) {
      DatabaseObject ob;
      std::format_to_n(ob.name.data(), ob.name.size() - 1, "Mouse {}", i);
      ob.oid = std::int64_t(i);
      ob.cid = 5000.101;
      f.Alloc(sizeof ob);
      check(f);
      f.Write(&ob, sizeof ob);         // At the address Alloc() returned
      check(f);
    }
    auto insert_time = std::chrono::duration<double>(clock::now() - start);
    std::cout << std::format("Inserted {} objects in {:.4f} s\n", INSERTIONS,
                             insert_time.count());

    start = clock::now();
    unsigned long found = 0;
    for(FAU_t addr = f.FindFirstBlock(); addr; addr = f.FindNextBlock(addr)) {
      DatabaseObject ob;
      f.Read(&ob, sizeof ob, addr + FAU_t(f.BlockHeaderSize()));
      check(f);
      if(ob.oid != std::int64_t(found)) throw std::runtime_error("bad object");
      found++;
    }
    auto read_time = std::chrono::duration<double>(clock::now() - start);
    std::cout << std::format("Read {} objects back in {:.4f} s\n", found,
                             read_time.count());
    std::cout << std::format("File size: {} bytes\n",
                             std::filesystem::file_size(fname));
    f.Close();
    check(f);
    std::filesystem::remove(fname);
    return found == INSERTIONS ? 0 : 1;
  }
  catch(const std::exception &e) {
    std::cout << "Database error: " << e.what() << "\n";
    return 1;
  }
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Build and run

cmake -S examples_modern -B build-modern -DCMAKE_CXX_STANDARD=20
cmake --build build-modern --target database_database
./build-modern/database_database

Output of the modern program

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

Database engine: 32-bit (DATAREEL_64BIT_DATABASE=OFF)
FAU_t: 8 bytes in memory, max 9223372036854775807
Inserted 1000 objects in 0.0048 s
Read 1000 objects back in 0.0031 s
File size: 177121 bytes