I'm trying to migrate to v2 and I'm having problems with a string field that should default to NULL if it is empty. In v1 this worked:
type Invitation struct {
ID string `json:"id"`
Value string `json:"value" gorm:"default:null"`
}
In v2, using the same type, when I save a struct with empty to_user, it is set to "null" (a string with "null" value...). Is this intended? Has GORM dropped support for NULL default values?
I've read about using pointers or sql.NullString, but this would deeply break my code.
Reproduction steps
Pull request: https://github.com/go-gorm/playground/pull/102
package main
import (
"fmt"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type Foo struct {
ID string `json:"id"`
Value string `json:"value" gorm:"default:null"`
}
const DSN = "postgres://user:pass@127.0.0.1:5432/db?sslmode=disable"
func main() {
db, _ := gorm.Open(postgres.New(postgres.Config{DSN: DSN}), &gorm.Config{})
db.AutoMigrate(&Foo{})
foo := &Foo{
ID: "001",
Value: "",
}
err := db.Create(foo).Error
if err != nil {
fmt.Printf("Error: %s", err.Error())
}
db.Model(foo).First(foo)
fmt.Printf("foo.Value -> %q", foo.Value)
db.Delete(foo)
}
This should store in database a record with value = "null".
Comment From: github-actions[bot]
This issue has been automatically marked as stale as it missing playground pull request link, checkout https://github.com/go-gorm/playground for details, it will be closed in 2 days if no further activity occurs.
Comment From: flusflas
I checked my code with the new changes and now it is raising Error: sql: Scan error on column index 0, name "value": converting NULL to string is unsupported. I assume this is happening when the struct is being reloaded after creating the record.
Comment From: jeffwalsh
The functionality is still broken with a sql.NullString. It inserts a string of "null".
Comment From: Bexanderthebex
@flusflas you can use a string pointer
Comment From: annlumia
use sql.NullString without set default value is worked.
gorm.io/driver/postgres v1.3.1
gorm.io/driver/sqlite v1.3.1
gorm.io/gorm v1.23.3
Or you can utilize Omit function.