This commit is contained in:
52
src/locsrv/database/database.go
Normal file
52
src/locsrv/database/database.go
Normal file
@ -0,0 +1,52 @@
|
||||
package database
|
||||
|
||||
|
||||
import (
|
||||
"log"
|
||||
//"time"
|
||||
"fmt"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type DatabaseHandle struct {
|
||||
initialized bool
|
||||
dbh *gorm.DB
|
||||
}
|
||||
|
||||
func New() *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) GetPersonById(id string) (string, error) {
|
||||
if ! self.initialized {
|
||||
err := fmt.Errorf("Database connection not initialized")
|
||||
return "", err
|
||||
}
|
||||
|
||||
var person Person
|
||||
result := self.dbh.
|
||||
Where("persons.id = ?", id).
|
||||
First(&person)
|
||||
|
||||
if result.Error != nil {
|
||||
err := fmt.Errorf("Query failed: %s", result.Error)
|
||||
return "", err
|
||||
}
|
||||
|
||||
return person.Name, nil
|
||||
}
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user