66 lines
1.3 KiB
Go
66 lines
1.3 KiB
Go
|
package store
|
||
|
|
||
|
import (
|
||
|
"github.com/rs/zerolog"
|
||
|
"github.com/rs/zerolog/log"
|
||
|
"go.uber.org/fx"
|
||
|
"gorm.io/gorm"
|
||
|
"sneak.berlin/go/directory/internal/config"
|
||
|
"sneak.berlin/go/directory/internal/database"
|
||
|
"sneak.berlin/go/directory/internal/logger"
|
||
|
)
|
||
|
|
||
|
const (
|
||
|
UsersTableName string = "users"
|
||
|
UserAttributesTableName string = "userattributes"
|
||
|
)
|
||
|
|
||
|
type StoreParams struct {
|
||
|
fx.In
|
||
|
Logger *logger.Logger
|
||
|
Config *config.Config
|
||
|
Database *database.Database
|
||
|
}
|
||
|
|
||
|
type Store struct {
|
||
|
dbdir string
|
||
|
dbfn string
|
||
|
db *gorm.DB
|
||
|
logger *logger.Logger
|
||
|
log *zerolog.Logger
|
||
|
params *StoreParams
|
||
|
}
|
||
|
|
||
|
func New(lc fx.Lifecycle, params *StoreParams) (*Store, error) {
|
||
|
s := new(Store)
|
||
|
|
||
|
s.logger = params.Logger
|
||
|
s.log = params.Logger.Get()
|
||
|
|
||
|
var err error
|
||
|
s.db, err = params.Database.Get()
|
||
|
if err != nil {
|
||
|
log.Error().Err(err).Msg("failed to get database object")
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
// Auto migrate the schema
|
||
|
err = s.db.AutoMigrate(&User{}, &UserAttribute{})
|
||
|
if err != nil {
|
||
|
log.Error().Err(err).Msg("failed to migrate database schema")
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
return s, nil
|
||
|
}
|
||
|
|
||
|
func (s *Store) Close() {
|
||
|
log.Info().Msg("closing store db")
|
||
|
db, err := s.db.DB()
|
||
|
if err != nil {
|
||
|
log.Error().Err(err).Msg("failed to get generic database object from gorm")
|
||
|
return
|
||
|
}
|
||
|
db.Close()
|
||
|
}
|