Skip to content

DB stuctur

Golub Egor edited this page Apr 18, 2026 · 5 revisions

The DB type is provided as a function that returns the same named type (@This()), which has the following fields:

  • path — used to store the file path where our database will be saved.
  • tables — a hash map that holds all the tables.
  • allocator — stores the memory allocator used by the database.
  • metadata_buffer — a buffer used to guarantee proper memory cleanup / release.

Function breakdown

  • init
    Purpose: initializes the database
    Signature:

    init(name_file: []const u8, allocator: std.mem.Allocator) !@This()
  • deinit
    Purpose: correctly frees all resources and prevents memory leaks
    Signature:

    deinit(db: *@This()) void
  • createTable
    Purpose: creates a new table and registers it in the tables hash map
    Signature:

    createTable(db: *@This(), name: []const u8, comptime T: type) !void
  • dropTable Purpose: remove for tables and deinit table Signature:

    pub fn dropTable(db: *@This(), name: []const u8) !void
  • getTable
    Purpose: retrieves a table pointer by its name from the tables map
    Signature:

    getTable(db: @This(), name: []const u8) ?*Table
  • iterator Purpose: returns an iterator for easily traversing all tables.
    Signature:

    pub fn iterator(db: *@This()) DBIterator
  • save
    Purpose: saves the entire database structure to disk
    Signature:

    save(db: @This()) !void
  • load
    Purpose: fully restores the database structure from the file
    Signature:

    load(db: *@This()) !void

Basic usage example

var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();

var db = try ddb.DB().init("DB.db", allocator);
defer db.deinit();

Examples

1. Adding a Table

var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();

var db = try DB().init("DB.db", allocator);
defer db.deinit();

const Users = struct {
    id:   i32,
    name: []const u8,
};

try db.createTable("users", Users);

2. Saving the database

var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();

var db = try DB().init("DB.db", allocator);
defer db.deinit();

const Users = struct {
    id:   i32,
    name: []const u8,
};

try db.createTable("users", Users);
try db.save();

3. Loading the database

var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();

var db = try DB().init("DB.db", allocator);  // path must match the saved file
defer db.deinit();

try db.load();

4. Usage database iterator

// Base init database

const Users = struct {
    id: i32,
    name: []const u8,
};

const Item = struct {
    name: []const u8,
};

try db.createTable("users", Users);
try db.createTable("items", Item);

var it = db.iterator();

while (it.next()) |*t| {
    // t - Mut Table 
}

Clone this wiki locally