Database interactions demo

This commit is contained in:
Imbus 2024-02-27 05:00:04 +01:00
parent 5be29d86af
commit 06076f93b7
2 changed files with 48 additions and 4 deletions

View file

@ -7,26 +7,54 @@ import (
_ "github.com/mattn/go-sqlite3" _ "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 // Check for the environment variable
dbpath := os.Getenv("SQLITE_DB_PATH") dbpath := os.Getenv("SQLITE_DB_PATH")
// Default to something reasonable // Default to something reasonable
if dbpath == "" { 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 // Open the database
// db, err := sqlx.Connect("sqlite3", ":memory:")
db, err := sqlx.Connect("sqlite3", dbpath) db, err := sqlx.Connect("sqlite3", dbpath)
if err != nil { if err != nil {
panic(err) panic(err)
} }
// Ping forces the connection to be established
err = db.Ping() err = db.Ping()
if err != nil { if err != nil {
panic(err) 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
} }

View file

@ -8,3 +8,19 @@ func TestDbConnect(t *testing.T) {
db := DbConnect() db := DbConnect()
_ = db _ = 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)
}
}