Create database version tracking

This commit is contained in:
2026-01-25 21:34:25 +01:00
parent 1834a4fafa
commit 5112090718
3 changed files with 65 additions and 2 deletions
+22 -1
View File
@@ -11,9 +11,30 @@ func MigrateStructure(db ...*gorm.DB) error {
targetDB = DB
}
err := targetDB.AutoMigrate()
err := targetDB.AutoMigrate(
&SchemaVersion{},
&MigrationHistory{},
)
if err != nil {
return err
}
return nil
}
func MigrateDataIfNeeded(db *gorm.DB) error {
// Implement data migration logic here if needed
schemaVersion := SchemaVersion{}
err := db.First(&schemaVersion, "version = ?", "0.1.37").Error
if err != nil {
// No initial version found, assume no migration needed
schemaVersion.Version = "0.1.37"
schemaVersion.MigrationNumber = 1
schemaVersion.BackendVersion = "0.1.37"
schemaVersion.Description = "Initial schema version"
err = db.Create(&schemaVersion).Error
if err != nil {
return err
}
}
return nil
}
+36
View File
@@ -0,0 +1,36 @@
package database
// SchemaVersion represents the schema_version table
type SchemaVersion struct {
ID uint `gorm:"primaryKey;autoIncrement"`
Version string `gorm:"size:20;not null;index"`
MigrationNumber int `gorm:"not null;index"`
AppliedAt int64 `gorm:"autoCreateTime"`
BackendVersion string `gorm:"size:20;not null"`
Description string `gorm:"type:text"`
Checksum string `gorm:"size:64"`
}
// TableName sets the table name for SchemaVersion
func (SchemaVersion) TableName() string {
return "schema_version"
}
// MigrationHistory represents the migration_history table
type MigrationHistory struct {
ID uint `gorm:"primaryKey;autoIncrement"`
MigrationNumber int `gorm:"not null;uniqueIndex"`
Version string `gorm:"size:20;not null;index"`
Description string `gorm:"type:text;not null"`
AppliedAt int64 `gorm:"autoCreateTime"`
AppliedBy string `gorm:"size:100"`
ExecutionTimeMs int64
Success bool `gorm:"default:true"`
ErrorMessage string `gorm:"type:text"`
RollbackAvailable bool `gorm:"default:true"`
}
// TableName sets the table name for MigrationHistory
func (MigrationHistory) TableName() string {
return "migration_history"
}
+7 -1
View File
@@ -63,9 +63,15 @@ func migrateAllStructures(db *gorm.DB) error {
func migrateDataIfNeeded(db *gorm.DB) error {
logger.Debug("Starte Datenmigration falls erforderlich...")
err := database.MigrateDataIfNeeded(db)
if err != nil {
logger.Error("Fehler beim Migrieren der Datenbankdaten: %s", err.Error())
return fmt.Errorf("failed to migrate database data: %w", err)
}
// Kopiere categorie nach learning_category für Spells, wenn learning_category leer ist
logger.Debug("Migriere Spell Learning Categories...")
err := migrateSpellLearningCategories(db)
err = migrateSpellLearningCategories(db)
if err != nil {
logger.Error("Fehler beim Migrieren der Spell Learning Categories: %s", err.Error())
return fmt.Errorf("failed to migrate spell learning categories: %w", err)