76 lines
1.4 KiB
Go
76 lines
1.4 KiB
Go
|
package storage
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"fmt"
|
||
|
|
||
|
"git.espin.casa/albert/cml04-falcon-system/internal/types"
|
||
|
"gorm.io/driver/postgres"
|
||
|
"gorm.io/gorm"
|
||
|
)
|
||
|
|
||
|
type Storager interface {
|
||
|
StoreBarcode(ctx context.Context, in *types.Barcode) error
|
||
|
}
|
||
|
|
||
|
type storage struct {
|
||
|
db *gorm.DB
|
||
|
}
|
||
|
|
||
|
type DBConfig struct {
|
||
|
Username string
|
||
|
Password string
|
||
|
Host string
|
||
|
Port int
|
||
|
Name string
|
||
|
}
|
||
|
|
||
|
// StoreBarcode implements IStorage.
|
||
|
func (s *storage) StoreBarcode(ctx context.Context, in *types.Barcode) error {
|
||
|
return s.db.Save(in).Error
|
||
|
}
|
||
|
|
||
|
func ProductionDataBase(conf *DBConfig) (*gorm.DB, error) {
|
||
|
// create dsn string
|
||
|
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=disable TimeZone=Europe/Madrid",
|
||
|
conf.Host,
|
||
|
conf.Username,
|
||
|
conf.Password,
|
||
|
conf.Name,
|
||
|
conf.Port,
|
||
|
)
|
||
|
|
||
|
// create open database connection
|
||
|
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
return db, nil
|
||
|
}
|
||
|
|
||
|
func Automigrate(db *gorm.DB) error {
|
||
|
return db.AutoMigrate(
|
||
|
&types.Barcode{},
|
||
|
&types.BundleData{},
|
||
|
&types.ProductionOrder{},
|
||
|
)
|
||
|
}
|
||
|
|
||
|
func New(conf *DBConfig) (Storager, error) {
|
||
|
// database holder
|
||
|
var db *gorm.DB
|
||
|
// producctio
|
||
|
db, err := ProductionDataBase(conf)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
// auto migration
|
||
|
if err := Automigrate(db); err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
// done
|
||
|
return &storage{
|
||
|
db: db,
|
||
|
}, nil
|
||
|
}
|