Matrix/entities/device/keyDatabaseConnector.go
2020-10-12 16:16:28 +02:00

125 lines
1.9 KiB
Go

package device
import (
"fmt"
"git.nutfactory.org/hoernschen/Matrix/utils/database"
)
func CreateKey(key *Key, deviceId string) (err error) {
sqlStmt := fmt.Sprintf(`INSERT INTO key
(id, type, key, deviceId)
VALUES
(?, ?, ?, ?)`)
tx, err := database.DB.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(key.Id, key.Type, key.Key, deviceId)
if err != nil {
return
}
tx.Commit()
return
}
func ReadKey(id string) (foundKey *Key, err error) {
queryStmt := fmt.Sprintf(`SELECT id, type, key
FROM key
WHERE id = '%s'`, id)
rows, err := database.DB.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
if rows.Next() {
foundKey = &Key{}
err = rows.Scan(&foundKey.Id, &foundKey.Type, &foundKey.Key)
if err != nil {
return
}
}
return
}
func ReadKeysForDevice(deviceId string) (keys map[string]*Key, err error) {
queryStmt := fmt.Sprintf(`SELECT id, type, key
FROM key
WHERE deviceId = '%s'`, deviceId)
rows, err := database.DB.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
keys = make(map[string]*Key)
for rows.Next() {
foundKey := &Key{}
err = rows.Scan(&foundKey.Id, &foundKey.Type, &foundKey.Key)
if err != nil {
return
}
keys[foundKey.Id] = foundKey
}
return
}
func UpdateKey(key *Key) (err error) {
sqlStmt := fmt.Sprintf(`UPDATE key SET
type = ?,
key = ?
WHERE id = ?`)
tx, err := database.DB.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(key.Type, key.Key, key.Id)
if err != nil {
return
}
tx.Commit()
return
}
func DeleteKey(id string) (err error) {
queryStmt := fmt.Sprintf(`DELETE FROM key
WHERE id = '%s'`, id)
tx, err := database.DB.Begin()
if err != nil {
return
}
_, err = database.DB.Exec(queryStmt)
if err != nil {
return
}
tx.Commit()
return
}