Search code examples
mysqlgogo-gorm

query for maximum value in row returns "0" in GoRM


Using GoRM with a mySQL database, i'm having trouble returning data from a fairly simple query.

var newPrsPk struct {
        presentation_pk int `gorm:"column:presentation_pk"`
    }
    db.Raw("select max(presentation_pk) as presentation_pk from presentation").Scan(&newPrsPk)

    log.Println(newPrsPk)
    log.Println(newPrsPk.presentation_pk)

which results in the following output:

[2023-06-16 09:53:27]  [43.29ms]   select max(presentation_pk) as presentation_pk from presentation  
[1 rows affected or returned ] 
2023/06/16 09:53:27 {0}
2023/06/16 09:53:27 0

But 0 is definitely not the max value for that column, and running the query in mySQL workbench returns the appropriate value, so I have to assume there's something wrong with how i'm writing this.

GoRM's documentation isn't amazing, but this is a pretty straightforward query, so i'm flummoxed.

"presentation_pk" is an auto-incrementing int field in my table, and this query immediately follows a GoRM Create() function (since there doesn't seem to be a way to return an auto-incremented field from mySQL). given that there's no kind of explicit "commit" function that I can see, I'm assuming GoRM automatically commits changes, and that this isn't a concurrency issue.

Any help would be appreciated.


Solution

  • When working with Gorm your struct variables need to be PascalCase not snake case. Take a look at the conventions document here and then you can see about Declaring Models here.

    If you change your struct to be something like this:

    var result struct {
        PresentationPK int `gorm:"column:presentation_pk"`
    }
    

    Then your query should work, and then you can print out your results using PresentationPK