127 lines
2.1 KiB
Go
127 lines
2.1 KiB
Go
package device
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"nutfactory.org/Matrix/utils/database"
|
|
)
|
|
|
|
func CreateDevice(device *Device, userId string) (err error) {
|
|
sqlStmt := fmt.Sprintf(`INSERT INTO device
|
|
(id, name, userId)
|
|
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(device.Id, device.Name, userId)
|
|
if err != nil {
|
|
return
|
|
}
|
|
tx.Commit()
|
|
return
|
|
}
|
|
|
|
func ReadDevice(id string) (foundDevice *Device, err error) {
|
|
queryStmt := fmt.Sprintf(`SELECT id, name
|
|
FROM device
|
|
WHERE id = '%s'`, id)
|
|
|
|
rows, err := database.DB.Query(queryStmt)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
defer rows.Close()
|
|
|
|
if rows.Next() {
|
|
foundDevice = &Device{}
|
|
err = rows.Scan(&foundDevice.Id, &foundDevice.Name)
|
|
if err != nil {
|
|
return
|
|
}
|
|
foundDevice.Keys, err = ReadKeysForDevice(foundDevice.Id)
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
func ReadDevicesForUser(userId string) (devices map[string]*Device, err error) {
|
|
queryStmt := fmt.Sprintf(`SELECT id, name
|
|
FROM device
|
|
WHERE userId = '%s'`, userId)
|
|
|
|
rows, err := database.DB.Query(queryStmt)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
defer rows.Close()
|
|
|
|
devices = make(map[string]*Device)
|
|
|
|
for rows.Next() {
|
|
foundDevice := &Device{}
|
|
err = rows.Scan(&foundDevice.Id, &foundDevice.Name)
|
|
if err != nil {
|
|
return
|
|
}
|
|
foundDevice.Keys, err = ReadKeysForDevice(foundDevice.Id)
|
|
devices[foundDevice.Id] = foundDevice
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
func UpdateDevice(device *Device, userId string) (err error) {
|
|
sqlStmt := fmt.Sprintf(`UPDATE device SET
|
|
name = ?,
|
|
userId = ?
|
|
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(device.Name, userId, device.Id)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
tx.Commit()
|
|
return
|
|
}
|
|
|
|
func DeleteDevice(id string) (err error) {
|
|
queryStmt := fmt.Sprintf(`DELETE FROM device
|
|
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
|
|
}
|