Files
universal-data-ingest/src/udi/database/database.go
Wolfgang Hottgenroth ea9db110a5
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
model parser
2023-12-08 17:13:56 +01:00

70 lines
1.6 KiB
Go

package database
import (
"log"
//"time"
"fmt"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type DatabaseHandle struct {
initialized bool
dbh *gorm.DB
}
func NewDatabaseHandle(dsn string) *DatabaseHandle {
var db DatabaseHandle
conn, err := gorm.Open(postgres.Open(dsn))
if err != nil {
log.Printf("Unable to open database connection: %s", err)
db.initialized = false
} else {
db.dbh = conn
db.initialized = true
log.Println("Database connection opened")
}
return &db
}
func (self *DatabaseHandle) StoreMeasurement(measurement *Measurement) {
if ! self.initialized {
log.Printf("Database connection not initialized, can not store, measurement %s lost", measurement)
return
}
result := self.dbh.Create(measurement)
if result.Error != nil {
log.Printf("Unable to insert, measurement %s lost, error: %s", measurement, result.Error)
return
}
log.Println("Successfully stored measurement")
}
func (self *DatabaseHandle) GetDeviceByLabelAndApplication(applicationLabel string, deviceLabel string) (*Device, error) {
if ! self.initialized {
err := fmt.Errorf("Database connection not initialized")
return nil, err
}
var device Device
result := self.dbh.
Preload("Application").
Preload("DeviceType").
Joins("JOIN applications ON devices.application_id = applications.id").
Where("devices.label = ? AND applications.label = ?", deviceLabel, applicationLabel).
First(&device)
if result.Error != nil {
err := fmt.Errorf("Query failed: %s", result.Error)
return nil, err
}
return &device, nil
}