68 lines
1.8 KiB
Go
68 lines
1.8 KiB
Go
package db
|
|
|
|
import (
|
|
"log"
|
|
"time"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type Config struct {
|
|
gorm.Model
|
|
ID uint `gorm:"primaryKey;autoIncrement"`
|
|
Name string `gorm:"uniqueIndex;not null"`
|
|
Description string `gorm:"type:text"`
|
|
Value string `gorm:"not null"`
|
|
Enabled bool `gorm:"default:true"`
|
|
AppService string `gorm:"default:system"`
|
|
CreatedAt time.Time `gorm:"index"`
|
|
UpdatedAt time.Time `gorm:"index"`
|
|
DeletedAt gorm.DeletedAt `gorm:"index"`
|
|
}
|
|
|
|
var seedConfigData = []Config{
|
|
{Name: "serverPort", Description: "The port the server will listen on if not running in docker", Value: "4000", Enabled: true},
|
|
{Name: "server", Description: "The server we will use when connecting to the alplaprod sql", Value: "usmcd1vms006", Enabled: true},
|
|
}
|
|
|
|
func SeedConfigs(db *gorm.DB) error {
|
|
|
|
for _, cfg := range seedConfigData {
|
|
var existing Config
|
|
// Try to find config by unique name
|
|
result := db.Where("name =?", cfg.Name).First(&existing)
|
|
|
|
if result.Error != nil {
|
|
if result.Error == gorm.ErrRecordNotFound {
|
|
// not here lets add it
|
|
if err := db.Create(&cfg).Error; err != nil {
|
|
log.Printf("Failed to seed config %s: %v", cfg.Name, err)
|
|
}
|
|
log.Printf("Seeded new config: %s", cfg.Name)
|
|
} else {
|
|
// Some other error
|
|
return result.Error
|
|
}
|
|
} else {
|
|
// only update the fields we want to update.
|
|
existing.Description = cfg.Description
|
|
if err := db.Save(&existing).Error; err != nil {
|
|
log.Printf("Failed to update config %s: %v", cfg.Name, err)
|
|
return err
|
|
}
|
|
log.Printf("Updated existing config: %s", cfg.Name)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func GetAllConfigs(db *gorm.DB) ([]Config, error) {
|
|
var configs []Config
|
|
|
|
result := db.Find(&configs)
|
|
|
|
return configs, result.Error
|
|
|
|
}
|