52 lines
1.2 KiB
Go
52 lines
1.2 KiB
Go
package models
|
|
|
|
import (
|
|
"fmt"
|
|
)
|
|
|
|
type Device struct {
|
|
TOPIC string
|
|
CustomerID string
|
|
DeviceID string
|
|
ProjectName string
|
|
MAC string
|
|
SN string
|
|
LastMsg string
|
|
}
|
|
|
|
func (db *DB) AllDevices() ([]*Device, error) {
|
|
rows, err := db.Query("SELECT * FROM devices")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
devices := make([]*Device, 0)
|
|
for rows.Next() {
|
|
device := new(Device)
|
|
err := rows.Scan(&device.TOPIC, &device.CustomerID, &device.DeviceID, &device.ProjectName, &device.MAC, &device.SN, &device.LastMsg)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
devices = append(devices, device)
|
|
}
|
|
if err = rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return devices, nil
|
|
}
|
|
|
|
func (db *DB) InsertDevice(device *Device) error {
|
|
sqlStmt := `INSERT OR REPLACE INTO devices (topic, customerID, deviceID, projectName, mac, sn, lastMsg)
|
|
VALUES($1, $2, $3, $4, $5, $6, $7);`
|
|
_, err := db.Exec(sqlStmt, device.TOPIC, device.CustomerID, device.DeviceID, device.ProjectName, device.MAC, device.SN, device.LastMsg)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// DEBUG
|
|
fmt.Printf("Sucessfully inserted device with ID %s to database\n", device.TOPIC)
|
|
|
|
return err
|
|
}
|