-
Notifications
You must be signed in to change notification settings - Fork 0
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.
-
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 thetableshash map
Signature:createTable(db: *@This(), name: []const u8, comptime T: type) !void
-
dropTablePurpose: remove fortablesand deinit table Signature:pub fn dropTable(db: *@This(), name: []const u8) !void
-
getTable
Purpose: retrieves a table pointer by its name from thetablesmap
Signature:getTable(db: @This(), name: []const u8) ?*Table
-
iteratorPurpose: 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
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var db = try ddb.DB().init("DB.db", allocator);
defer db.deinit();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);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();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();// 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
}