54 lines
1.1 KiB
Go
54 lines
1.1 KiB
Go
package database
|
|
|
|
|
|
import (
|
|
"log"
|
|
//"time"
|
|
//"fmt"
|
|
"ma/counter"
|
|
"gorm.io/driver/postgres"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type DatabaseHandle struct {
|
|
initialized bool
|
|
dbh *gorm.DB
|
|
}
|
|
|
|
func NewDatabaseHandle() *DatabaseHandle {
|
|
var db DatabaseHandle
|
|
// inject the whole database configuration via the well-known PG* env variables
|
|
conn, err := gorm.Open(postgres.Open(""))
|
|
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) StoreMessage(message *Message) {
|
|
if ! self.initialized {
|
|
log.Printf("Database connection not initialized, can not store, message %s lost", message)
|
|
counter.F("Stored")
|
|
return
|
|
}
|
|
|
|
result := self.dbh.Create(message)
|
|
if result.Error != nil {
|
|
log.Printf("Unable to insert, message %s lost, error: %s", message, result.Error)
|
|
counter.F("Stored")
|
|
return
|
|
}
|
|
|
|
//log.Println("Successfully stored message")
|
|
counter.S("Stored")
|
|
}
|
|
|
|
|
|
|
|
|