1

Let's s say I have struct with a field like:

FinishedAt   sql.NullTime `json:"finished_at"`
var out models.Job
err := client.QueryRow(ctx, updateQuery,
    &job.FinishedAt,
).Scan(
    &out.FinishedAt,
)

Above I use "github.com/jackc/pgx/v4" to work with PG.

There is no error during the update but the field is set to null after the request.

Using &job.FinishedAt.Time as an argument works appropriately but I want to understand why the sql.Nulltime type doesn't work.

Is that just related to how the library works?

Himanshu
  • 12,071
  • 7
  • 46
  • 61
Don Draper
  • 463
  • 7
  • 21
  • Is `job.FinishedAt` valid? What is its `job.FinishedAt.Valid` value? – mkopriva Aug 01 '22 at 14:21
  • This is the value it receives: `FinishedAt: sql.NullTime{Time: now}` – Don Draper Aug 01 '22 at 14:24
  • Oh, I just noticed that the `Valid` value is false for some reason – Don Draper Aug 01 '22 at 14:25
  • So `Valid` is `false` and therefore the `Value() (driver.Value, error)` will return `NULL`. – mkopriva Aug 01 '22 at 14:25
  • *"for some reason"* -- `false` is the *zero* value of the `bool` type, i.e. any bool value not explicitly initialized will be implicitly initialized to `false`. https://go.dev/ref/spec#The_zero_value – mkopriva Aug 01 '22 at 14:27
  • That makes sense. Well, in such a case it's a bit clumsy because converting a `time.Time instance to `sql.NullTime` requires setting both fields of the struct. But at least that is correct :) – Don Draper Aug 01 '22 at 14:30
  • 2
    You could also just use a pointer instead of `sql.NullTime`. i.e. `FinishedAt *time.Time \`json:"finished_at"\``. Then if the field is `nil` it will be stored as `NULL`, if it's not `nil` then the `time.Time`'s value will be stored. – mkopriva Aug 01 '22 at 14:33
  • Does this answer your question? [How can I work with SQL NULL values and JSON in a good way?](https://stackoverflow.com/questions/33072172/how-can-i-work-with-sql-null-values-and-json-in-a-good-way) – Brits Aug 01 '22 at 20:22

0 Answers0