Dabase setup widget

This commit is contained in:
Jamie Curnow committed 2026-09-28 13:03:10 +10:00
1 parent 853ef909a7
commit 741c9c982f
25 files changed
+1133 -66

No files matched your search

+46 -6
View File
@@ -20,13 +20,18 @@ var dbInstance *gorm.DB
// NewDB creates a new connection
func NewDB() {
if !config.Configuration.DB.IsConfigured() {
// The setup wizard hasn't been completed yet
return
}
if ok, err := config.Configuration.DB.IsValid(); !ok {
logger.Error("DatabaseError", eris.Wrap(err, "database configuration is invalid, check for missing environment variables"))
logger.Error("DatabaseError", eris.Wrapf(err, "database configuration is invalid, check %s or NPM_DB_* environment variables", config.GetDBConfigFile()))
return
}
logger.Info("Creating new DB instance using %s", strings.ToLower(config.Configuration.DB.Driver))
db, err := connect()
db, err := connect(&config.Configuration.DB)
if err != nil {
logger.Error("DatabaseConnectError", err)
} else if db != nil {
@@ -42,17 +47,52 @@ func GetDB() *gorm.DB {
return dbInstance
}
// TestConnection opens a connection using the given config and pings the
// server, without affecting the current instance. Used by the setup wizard
// to validate parameters before they are saved.
func TestConnection(cfg config.DBConfig) error {
if ok, err := cfg.IsValid(); !ok {
return err
}
db, err := connect(&cfg)
if err != nil {
return err
}
sqlDB, err := db.DB()
if err != nil {
return err
}
// nolint: errcheck
defer sqlDB.Close()
return sqlDB.Ping()
}
// Close closes and discards the current instance, if any
func Close() {
if dbInstance == nil {
return
}
if sqlDB, err := dbInstance.DB(); err == nil {
// nolint: errcheck, gosec
sqlDB.Close()
}
dbInstance = nil
}
// SetDB will set the dbInstance to this
// Used by unit testing to set the db to a mock database
func SetDB(db *gorm.DB) {
dbInstance = db
}
func connect() (*gorm.DB, error) {
func connect(dbCfg *config.DBConfig) (*gorm.DB, error) {
var d gorm.Dialector
dsn := config.Configuration.DB.GetGormConnectURL()
dsn := dbCfg.GetGormConnectURL()
switch strings.ToLower(config.Configuration.DB.Driver) {
switch dbCfg.GetDriver() {
case config.DatabaseSqlite:
// autocreate(dsn)
d = sqlite.Open(dsn)
@@ -64,7 +104,7 @@ func connect() (*gorm.DB, error) {
d = mysql.Open(dsn)
default:
return nil, eris.New(fmt.Sprintf("Database driver %s is not supported. Valid options are: %s, %s or %s", config.Configuration.DB.Driver, config.DatabaseSqlite, config.DatabasePostgres, config.DatabaseMysql))
return nil, eris.New(fmt.Sprintf("Database driver %s is not supported. Valid options are: %s, %s or %s", dbCfg.Driver, config.DatabaseSqlite, config.DatabasePostgres, config.DatabaseMysql))
}
// see: https://gorm.io/docs/gorm_config.html