Matrix/entities/device/keyDatabaseConnector.go

129 lines
2 KiB
Go
Raw Permalink Normal View History

package device
import (
"fmt"
2020-10-12 14:16:28 +00:00
"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 {
2020-10-17 10:07:39 +00:00
tx.Rollback()
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 {
2020-10-17 10:07:39 +00:00
tx.Rollback()
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
}
2020-10-17 10:07:39 +00:00
_, err = tx.Exec(queryStmt)
if err != nil {
2020-10-17 10:07:39 +00:00
tx.Rollback()
return
}
tx.Commit()
return
}