Ignore fields that are zero value

This commit is contained in:
Maximilian 2024-01-20 16:32:07 -06:00
parent b30af86e58
commit e497f4d2f0

View File

@ -9,7 +9,8 @@ import (
"reflect" "reflect"
) )
// Migrate given a dummy object of any type, it will create a table with the same name as the type and create columns with the same name as the fields of the object // Migrate given a dummy object of any type, it will create a table with the same name
// as the type and create columns with the same name as the fields of the object
func Migrate(app *app.App, anyStruct interface{}) error { func Migrate(app *app.App, anyStruct interface{}) error {
valueOfStruct := reflect.ValueOf(anyStruct) valueOfStruct := reflect.ValueOf(anyStruct)
typeOfStruct := valueOfStruct.Type() typeOfStruct := valueOfStruct.Type()
@ -23,10 +24,15 @@ func Migrate(app *app.App, anyStruct interface{}) error {
for i := 0; i < valueOfStruct.NumField(); i++ { for i := 0; i < valueOfStruct.NumField(); i++ {
fieldType := typeOfStruct.Field(i) fieldType := typeOfStruct.Field(i)
fieldName := fieldType.Name fieldName := fieldType.Name
if fieldName != "Id" && fieldName != "id" {
err := createColumn(app, tableName, fieldName, fieldType.Type.Name()) // Create column if dummy for migration is NOT zero value
if err != nil { fieldValue := valueOfStruct.Field(i).Interface()
return err if !reflect.ValueOf(fieldValue).IsZero() {
if fieldName != "Id" && fieldName != "id" {
err := createColumn(app, tableName, fieldName, fieldType.Type.Name())
if err != nil {
return err
}
} }
} }
} }