v1.2.0: back: add DropUnusedColumns

Signed-off-by: GnomeZworc <nicolas.boufidjeline@g3e.fr>
This commit is contained in:
GnomeZworc 2024-03-31 00:05:22 +01:00
commit 82a057f131
Signed by: nicolas.boufideline
GPG key ID: 4406BBBF8845D632

View file

@ -11,6 +11,28 @@ type Users struct {
Password string `gorm:""` Password string `gorm:""`
} }
func DropUnusedColumns(DB *gorm.DB, values ...interface{}) {
for _, dst := range values {
stmt := &gorm.Statement{DB: DB}
stmt.Parse(dst)
fields := stmt.Schema.Fields
columns, _ := DB.Debug().Migrator().ColumnTypes(dst)
for i := range columns {
found := false
for j := range fields {
if columns[i].Name() == fields[j].DBName {
found = true
break
}
}
if !found {
DB.Migrator().DropColumn(dst, columns[i].Name())
}
}
}
}
func Init_database() { func Init_database() {
dsn := "postgres://acc:totor@postgres:5432/accounts?sslmode=disable" dsn := "postgres://acc:totor@postgres:5432/accounts?sslmode=disable"
@ -18,4 +40,5 @@ func Init_database() {
if err != nil { if err != nil {
} }
db.AutoMigrate(&Users{}) db.AutoMigrate(&Users{})
DropUnusedColumns(db, &Users{})
} }