Skip to content

fix(scan): update Scan function to reset structs to zero values for each scan #7061

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 12, 2024

Conversation

Waldeedle
Copy link
Contributor

@Waldeedle Waldeedle commented Jun 12, 2024

  • Do only one thing
  • Non breaking API changes
  • Tested

What did this pull request do?

Accidentally closed #6938 so this is the same PR just with the final implemented solution
Addresses #6819
Adding a condition to reset the values of a struct when a scan is initialized to handle nil values from the database

User Case Description

It fixes the example from the docs where you initialize the var once:

    var datasetRow T
    for rows.Next() {
        err := db.ScanRows(rows, &datasetRow)

@Waldeedle
Copy link
Contributor Author

Waldeedle commented Jun 12, 2024

@a631807682 here's the new PR with the final solution. Appreciate all the info and time you've provided on this! 🚀 🎉

@Waldeedle
Copy link
Contributor Author

Waldeedle commented Jun 12, 2024

@a631807682 am I correct in assuming @jinzhu will be merging into master, after reviewing? or would that be you as well?

@a631807682
Copy link
Member

I usually wait for at least 2 members to review, and jinzhu will review all PRs and merge them when he is free.

@jinzhu jinzhu merged commit 73a988c into go-gorm:master Jun 12, 2024
@Jcodelove
Copy link

OMG, I've been treating this as a feature the whole time.

@ZGeomantic
Copy link

It doesn't seem like a "Non breaking API changes". Is this the expected behavior of this function itself?

@tashaX
Copy link

tashaX commented Aug 8, 2025

I'm not sure if this is related, but there's a significant change in the Scan function's behaviour. The GORM version just got a minor update, but now Scan wipes clean the whole struct. That's a pretty big change.

We used to use Scan something like this:

type SomeStruct struct {
    Name        string
    Date        null.Time
    Description string
    ID          uint64
}

data := SomeStruct{
    ID:   1,
    Date: null.TimeFrom(time.Now()),
}

db.Table("some_table").
    Select("name, description").
    Where("id = ?", data.ID).
    Scan(&data)

The intention was to fill in new data while keeping the already populated fields intact.
But now, after the update, the struct is wiped clean and only the selected data is present after Scan.
That seems like a major behavioural change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants