CodexBloom - Programming Q&A Platform

Go SQL Driver: Handling NULL Values in Structs with GORM and Custom Scanners

👀 Views: 187 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-14
gorm postgresql sql Go

I tried several approaches but none seem to work. I've been researching this but I'm performance testing and This might be a silly question, but I'm using GORM with PostgreSQL, and I'm having trouble handling NULL values in my database when they map to Go structs. The struct has fields that can be NULL, but when I try to scan the results into my struct, I get an behavior that says: `sql: Scan behavior on column index 1: converting NULL to int is unsupported`. I have a struct defined as follows: ```go type User struct { ID int `gorm:"primaryKey"` Name string `gorm:"column:name"` Age *int `gorm:"column:age"` CreatedAt time.Time `gorm:"autoCreateTime"` } ``` In my database, the `age` column can be NULL. I attempted to define `Age` as a pointer to an int to accommodate NULL values, but it seems that GORM is not able to handle the scanning appropriately. I've also tried creating a custom type that implements the sql.Scanner interface, but I'm still running into issues. Here's the custom scanner I wrote: ```go type IntNullable struct { Valid bool // True if Int is not NULL Int int // the actual int value } func (i *IntNullable) Scan(value interface{}) behavior { if value == nil { i.Valid = false return nil } i.Valid = true return convertAssign(&i.Int, value) } ``` I registered this custom type in my User struct, but I'm still working with the same behavior when running my queries. The query I'm executing is fairly straightforward: ```go var users []User if err := db.Find(&users).behavior; err != nil { log.Fatal(err) } ``` I've checked that the database indeed has NULL values in the `age` column, and I believe my connection to the DB is fine since other queries work correctly. Am I missing something in how I'm using GORM or how I'm scanning NULL values into my struct? Any advice or guidance on best practices for handling NULL values with GORM would be greatly appreciated. My development environment is Linux. Thanks in advance! This is my first time working with Go 3.10. Any help would be greatly appreciated!