Search code examples
go-gorm

Get table name from struct in gorm.io


How do we get the name of the table for an arbitrary struct (that may or may not have a custom naming strategy)? For example, the name of the Users table, that doesn't have a TableName function. In v1 I could do tableName := db.NewScope(&User{}).TableName() but that is no longer supported in the current version v2.

How can I get the table name?

I have found a way to do it by running a finaliser:

table_name := db.First(&WantToKnowTheTableForThisStruct{}).Statement.Table

This seems like a bad hack. Running a finaliser seems clunky and unnecessary. I don't want to run a query for items in the table, I just want to know the table name.


Solution

  • It looks like gorm.Statement provides access to the schema.

    func GetSchema(table any) *schema.Schema {
        stmt := &gorm.Statement{DB: DB}
        stmt.Parse(table)
        return stmt.Schema
    }
    
    func main() {
        tableSchema := GetSchema(MyTable{})
        fmt.Println(tableSchema.Table)
    }
    

    Gorm Playground link: https://github.com/twocs/playground/tree/tablename