Some more example database interface code
This commit is contained in:
parent
60e7b73f66
commit
ce1ce89b00
2 changed files with 32 additions and 0 deletions
|
@ -58,3 +58,18 @@ func (d *Db) RemoveUser(username string) error {
|
||||||
_, err := d.Exec("DELETE FROM users WHERE username = ?", username)
|
_, err := d.Exec("DELETE FROM users WHERE username = ?", username)
|
||||||
return err
|
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
|
||||||
|
}
|
||||||
|
|
|
@ -4,6 +4,9 @@ import (
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Tests are not guaranteed to be sequential
|
||||||
|
// Writing tests like this will bite you, eventually
|
||||||
|
|
||||||
func TestDbConnect(t *testing.T) {
|
func TestDbConnect(t *testing.T) {
|
||||||
db := DbConnect()
|
db := DbConnect()
|
||||||
_ = db
|
_ = 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) {
|
func TestDbRemoveUser(t *testing.T) {
|
||||||
db := DbConnect()
|
db := DbConnect()
|
||||||
err := db.RemoveUser("test")
|
err := db.RemoveUser("test")
|
||||||
|
|
Loading…
Reference in a new issue