From 06076f93b7500dcd000d8660f90f9bd9ce3729e0 Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Tue, 27 Feb 2024 05:00:04 +0100 Subject: [PATCH] Database interactions demo --- backend/internal/database/db.go | 36 ++++++++++++++++++++++++---- backend/internal/database/db_test.go | 16 +++++++++++++ 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/backend/internal/database/db.go b/backend/internal/database/db.go index d99efde..48ea95c 100644 --- a/backend/internal/database/db.go +++ b/backend/internal/database/db.go @@ -7,26 +7,54 @@ import ( _ "github.com/mattn/go-sqlite3" ) -func DbConnect() *sqlx.DB { +// This struct is a wrapper type that holds the database connection +// Internally DB holds a connection pool, so it's safe for concurrent use +type Db struct { + *sqlx.DB +} + +const userInsert = "INSERT INTO users (username, password) VALUES (?, ?)" + +// DbConnect connects to the database +func DbConnect() *Db { // Check for the environment variable dbpath := os.Getenv("SQLITE_DB_PATH") // Default to something reasonable if dbpath == "" { - dbpath = "./db.sqlite3" + // This should obviously not be like this + dbpath = "../../db.sqlite3" // This is disaster waiting to happen + // WARNING + + // If the file doesn't exist, panic + if _, err := os.Stat(dbpath); os.IsNotExist(err) { + panic("Database file does not exist: " + dbpath) + } } // Open the database - // db, err := sqlx.Connect("sqlite3", ":memory:") db, err := sqlx.Connect("sqlite3", dbpath) if err != nil { panic(err) } + // Ping forces the connection to be established err = db.Ping() if err != nil { panic(err) } - return db + return &Db{db} +} + +// AddUser adds a user to the database +func (d *Db) AddUser(username string, password string) error { + _, err := d.Exec(userInsert, username, password) + return err +} + +// Removes a user from the database +func (d *Db) RemoveUser(username string) error { + _, err := d.Exec("DELETE FROM users WHERE username = ?", username) + return err } diff --git a/backend/internal/database/db_test.go b/backend/internal/database/db_test.go index d7b26c9..6027ad1 100644 --- a/backend/internal/database/db_test.go +++ b/backend/internal/database/db_test.go @@ -8,3 +8,19 @@ func TestDbConnect(t *testing.T) { db := DbConnect() _ = db } + +func TestDbAddUser(t *testing.T) { + db := DbConnect() + err := db.AddUser("test", "password") + if err != nil { + t.Error("AddUser failed:", err) + } +} + +func TestDbRemoveUser(t *testing.T) { + db := DbConnect() + err := db.RemoveUser("test") + if err != nil { + t.Error("RemoveUser failed:", err) + } +}