Matrix/utils/database/userDatabaseConnector.go
2020-10-01 17:45:57 +02:00

119 lines
1.9 KiB
Go

package database
import (
"database/sql"
"fmt"
"log"
"nutfactory.org/Matrix/entities/user"
)
func initUserTable(db *sql.DB) (err error) {
log.Printf("Init User Table")
statement, err := db.Prepare(`CREATE TABLE IF NOT EXISTS user (
id TEXT PRIMARY KEY,
name TEXT,
password TEXT
)`)
if err != nil {
return
}
statement.Exec()
//TODO: Test Queries
return
}
func createUser(db *sql.DB, user *user.User) (err error) {
sqlStmt := fmt.Sprintf(`INSERT INTO user
(id, name, password)
VALUES
(?, ?, ?)`)
tx, err := db.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(user.Id, user.Name, user.Password)
if err != nil {
return
}
tx.Commit()
return
}
func readUser(db *sql.DB, id string) (foundUser *user.User, err error) {
queryStmt := fmt.Sprintf(`SELECT id, name, password
FROM user
WHERE id = '%s'`, id)
rows, err := db.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
if rows.Next() {
foundUser = &user.User{}
err = rows.Scan(&foundUser.Id, &foundUser.Name, &foundUser.Password)
if err != nil {
return
}
foundUser.Devices, err = ReadDevicesForUser(db, foundUser.Id)
}
return
}
func updateUser(db *sql.DB, user *user.User) (err error) {
sqlStmt := fmt.Sprintf(`UPDATE user SET
name = ?,
password = ?
WHERE id = ?`)
tx, err := db.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(user.Name, user.Password, user.Id)
if err != nil {
return
}
tx.Commit()
return
}
func deleteUser(db *sql.DB, id string) (err error) {
queryStmt := fmt.Sprintf(`DELETE FROM user
WHERE id = '%s'`, id)
tx, err := db.Begin()
if err != nil {
return
}
_, err = db.Exec(queryStmt)
if err != nil {
return
}
tx.Commit()
return
}