guregu / null

reasonable handling of nullable values
BSD 2-Clause "Simplified" License
1.84k stars 238 forks source link

how use json null set sql time field to null? #70

Open ystyle opened 1 year ago

ystyle commented 1 year ago
  1. defind web api dto struct

    type Dto struct {
    Start null.Time
    }
  2. send this json to web api

    { 
    "Start": null
    }
  3. service: use gorm update entry

    gorm.Model(&MyTable).Where("id = 1").Update(&dto)
  4. Hope to generate sql

    update my_table set start = null  where id = 1

    The start field is now ignored when used in this way

guregu commented 1 year ago

Sounds like a GORM issue to me. I don't use it and I can't provide support for it. I would suggest that after you unmarshal the JSON input, check whether null.Time is properly set to null or not. If it looks OK, then it's almost certainly a GORM issue.

ystyle commented 1 year ago

The result is the same whether the time type is passed or not, how to set a zero value for the time image

oogali commented 7 months ago

I feel a better option would be to use the Golang stdlib data structures for null SQL values. Those will generally be supported by all Golang ORMs, including GORM as their documentation on model declaration specifically uses them (https://gorm.io/docs/models.html).

The relevant type here would be: sql.NullTime (https://pkg.go.dev/database/sql#NullTime)

Unfortunately, you will need to have logic to copy the data from the source type into the destination type. However, you would have incurred that "extra" step no matter what.