From 7a4b8b5584e1539ac734a66bf8b027fa6a4b017d Mon Sep 17 00:00:00 2001 From: Warwick Date: Mon, 18 Nov 2024 13:21:18 +0000 Subject: [PATCH] Started adding sqlite3 stuff --- SQLite.zig | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ build.zig | 2 ++ 2 files changed, 56 insertions(+) create mode 100644 SQLite.zig diff --git a/SQLite.zig b/SQLite.zig new file mode 100644 index 0000000..418c7dc --- /dev/null +++ b/SQLite.zig @@ -0,0 +1,54 @@ +const std = @import("std"); +const c = @cImport({ + @cInclude("sqlite3.h"); +}); + +const ZBoardDB = struct { + db: *c.sqlite3, + + fn init() !ZBoardDB { + var db: ?*c.sqlite3 = undefined; + if (c.SQLITE_OK != c.sqlite3_open(":memory:", &db)) { + std.debug.print("Could not open SQLite3 DB"); + return error.execError; + } + + var zboard_db: ZBoardDB = .{ .db = db }; + try zboard_db.execute( + \\ CREATE TABLE IF NOT EXISTS users ( + \\ id INTEGER PRIMARY KEY, + \\ username VARCHAR(255) NOT NULL UNIQUE + \\ ); + \\ CREATE TABLE IF NOT EXISTS topics ( + \\ id INTEGER PRIMARY KEY, + \\ topic VARCHAR(255) NOT NULL UNIQUE + \\ ); + \\ CREATE TABLE IF NOT EXISTS threads ( + \\ id INTEGER PRIMARY KEY, + \\ title VARCHAR(255) NOT NULL UNIQUE, + \\ topic INTEGER NOT NULL + \\ ); + \\ CREATE TABLE IF NOT EXISTS posts ( + \\ id INTEGER PRIMARY KEY, + \\ user_id INTEGER NOT NULL, + \\ post TEXT NOT NULL, + \\ thread INTEGER NOT NULL, + \\ datetime INTEGER NOT NULL + \\ ); + ); + } + + fn deinit(self: ZBoardDB) void { + _ = c.sqlite3_close(self.db); + } + + fn execute(self: ZBoardDB, query: [:0]const u8) !void { + var errmsg: [*c]u8 = undefined; + if (c.SQLITE_OK != c.sqlite3_exec(self.db, query, null, null, &errmsg)) { + defer c.sqlite3_free(errmsg); + std.debug.print("Failed to execute SQLite3 queury: {s}\n", .{errmsg}); + return error.execError; + } + return; + } +}; diff --git a/build.zig b/build.zig index ea8562d..c369b2c 100644 --- a/build.zig +++ b/build.zig @@ -25,6 +25,8 @@ pub fn build(b: *std.Build) void { // Add Vaxis - tui library const vaxis = b.dependency("vaxis", .{ .target = target, .optimize = optimize }); exe.root_module.addImport("vaxis", vaxis.module("vaxis")); + exe.linkSystemLibrary("c"); + exe.linkSystemLibrary("sqlite3"); // This declares intent for the executable to be installed into the // standard location when the user invokes the "install" step (the default