Otfe/models/model.go

79 lines
1.2 KiB
Go

package models
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres" //
)
const (
host = "localhost"
port = 5432
user = "test"
password = "test"
dbname = "test"
)
var psqlInfo string
var db *gorm.DB
func init() {
psqlInfo = fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
DB()
}
func DB() (*gorm.DB, error) {
if db == nil {
db, err := gorm.Open("postgres", psqlInfo)
db.LogMode(true)
return db, err
}
return db, nil
}
func create(m interface{}) error {
db, err := DB()
if err != nil {
return err
}
return db.Create(m).Error
}
func read(m interface{}) error {
db, err := DB()
if err != nil {
return err
}
return db.Where(m).First(m).Error
}
func readAll(m interface{}) error {
db, err := DB()
if err != nil {
return err
}
return db.Find(m).Error
}
func update(m interface{}) error {
db, err := DB()
defer db.Close()
if err != nil {
return err
}
return db.Save(m).Error
}
func delete(m interface{}) error {
db, err := DB()
defer db.Close()
if err != nil {
return err
}
return db.Delete(m).Error
}