Skip to content
Snippets Groups Projects
Commit b1340891 authored by Jonas Leder's avatar Jonas Leder
Browse files

move createInstance to a seperate file

parent 7fd01df0
No related branches found
No related tags found
1 merge request!1WIP: write values to a database
Pipeline #54566 failed
package database
import (
"os"
"gorm.io/gorm"
"jonasled.dev/jonasled/ems-esp-logger/database/tables"
"jonasled.dev/jonasled/ems-esp-logger/log"
)
func CreateInstance() {
instanceName := os.Getenv("INSTANCE_NAME")
instanceDescription := os.Getenv("INSTANCE_DESCRIPTION")
if instanceName == "" || instanceDescription == "" {
log.Log.Fatal("INSTANCE_NAME and INSTANCE_DESCRIPTION must be set")
}
var instance tables.Instance
err := Db.Where("name = ?", instanceName).First(&instance).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
// Create a new instance if it doesn't exist
instance = tables.Instance{
Name: instanceName,
Description: instanceDescription,
}
if err := Db.Create(&instance).Error; err != nil {
log.Log.Fatalf("Failed to create instance: %v", err)
}
log.Log.Infof("Created new instance: %+v\n", instance)
} else {
log.Log.Fatalf("Failed to query database: %v", err)
}
} else {
// Update the description if the instance exists
instance.Description = instanceDescription
if err := Db.Save(&instance).Error; err != nil {
log.Log.Fatalf("Failed to update instance description: %v", err)
}
log.Log.Infof("Updated instance description: %+v\n", instance)
}
}
......@@ -53,36 +53,3 @@ func Init() {
Db.AutoMigrate(&tables.Instance{}, &tables.ValueType{}, &tables.Value{})
}
}
func CreateInstance() {
instanceName := os.Getenv("INSTANCE_NAME")
instanceDescription := os.Getenv("INSTANCE_DESCRIPTION")
if instanceName == "" || instanceDescription == "" {
log.Log.Fatal("INSTANCE_NAME and INSTANCE_DESCRIPTION must be set")
}
var instance tables.Instance
err := Db.Where("name = ?", instanceName).First(&instance).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
// Create a new instance if it doesn't exist
instance = tables.Instance{
Name: instanceName,
Description: instanceDescription,
}
if err := Db.Create(&instance).Error; err != nil {
log.Log.Fatalf("Failed to create instance: %v", err)
}
log.Log.Infof("Created new instance: %+v\n", instance)
} else {
log.Log.Fatalf("Failed to query database: %v", err)
}
} else {
// Update the description if the instance exists
instance.Description = instanceDescription
if err := Db.Save(&instance).Error; err != nil {
log.Log.Fatalf("Failed to update instance description: %v", err)
}
log.Log.Infof("Updated instance description: %+v\n", instance)
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment