81 lines
1.6 KiB
Go
81 lines
1.6 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
|
|
ConfirmBundle(ctx context.Context, barcode string) error
|
|
}
|
|
|
|
type storage struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
type DBConfig struct {
|
|
Username string
|
|
Password string
|
|
Host string
|
|
Port int
|
|
Name string
|
|
}
|
|
|
|
// ConfirmBundle implements Storager.
|
|
func (s *storage) ConfirmBundle(ctx context.Context, barcode string) error {
|
|
return s.db.Model(&types.BundleData{}).Where("nromatricula = ?", barcode).Update("confirmed", true).Error
|
|
}
|
|
|
|
// 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
|
|
}
|