From ce1ce89b000f2d991e038f5df0e4696b1936d04c Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Tue, 27 Feb 2024 05:51:16 +0100 Subject: [PATCH] Some more example database interface code --- backend/internal/database/db.go | 15 +++++++++++++++ backend/internal/database/db_test.go | 17 +++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/backend/internal/database/db.go b/backend/internal/database/db.go index 48ea95c..335a4ea 100644 --- a/backend/internal/database/db.go +++ b/backend/internal/database/db.go @@ -58,3 +58,18 @@ func (d *Db) RemoveUser(username string) error { _, err := d.Exec("DELETE FROM users WHERE username = ?", username) return err } + +func (d *Db) GetUserId(username string) (int, error) { + var id int + err := d.Get(&id, "SELECT id FROM users WHERE username = ?", username) + return id, err +} + +func (d *Db) AddProject(name string, description string, username string) error { + userId, err := d.GetUserId(username) + if err != nil { + return err + } + _, err = d.Exec("INSERT INTO projects (name, description, user_id) VALUES (?, ?, ?)", name, description, userId) + return err +} diff --git a/backend/internal/database/db_test.go b/backend/internal/database/db_test.go index 6027ad1..bad7dac 100644 --- a/backend/internal/database/db_test.go +++ b/backend/internal/database/db_test.go @@ -4,6 +4,9 @@ import ( "testing" ) +// Tests are not guaranteed to be sequential +// Writing tests like this will bite you, eventually + func TestDbConnect(t *testing.T) { db := DbConnect() _ = db @@ -17,6 +20,20 @@ func TestDbAddUser(t *testing.T) { } } +func TestDbGetUserId(t *testing.T) { + db := DbConnect() + + var id int + + id, err := db.GetUserId("test") + if err != nil { + t.Error("GetUserId failed:", err) + } + if id != 1 { + t.Error("GetUserId failed: expected 1, got", id) + } +} + func TestDbRemoveUser(t *testing.T) { db := DbConnect() err := db.RemoveUser("test")