Gorm: Truncate Table on dynamically named table

Created on 13 Oct 2020  路  3Comments  路  Source: go-gorm/gorm

Your Question

I have a table with arbitrary prefix defined when the application starts for the table name. I would like to truncate the table, so I am trying to run db.RAW("TRUNCATE TABLE table_name;"), however, since table_name can be changed from the runtime to the runtime, I was wondering if there is a way to dynamically get table name, so I could do something like:

db.RAW(fmt.Sprintf("TRUNCATE TABLE  %s;", db.TableName( &model{} )))

I could just get things from config directly, and hack the table name that way, but I was wondering if I could get table name dynamically

question

Most helpful comment

    stmt := &gorm.Statement{DB: DB}
    stmt.Parse(&ColumnStruct2{})
    stmt.Schema.Table

All 3 comments

Seems like there was something along those lines in v1, but I couldn't find something like that in v2:

from https://stackoverflow.com/questions/51999441/how-to-get-a-table-name-from-a-model-in-gorm:

tableName := db.NewScope(model).TableName()

    stmt := &gorm.Statement{DB: DB}
    stmt.Parse(&ColumnStruct2{})
    stmt.Schema.Table

Thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Quentin-M picture Quentin-M  路  3Comments

rfyiamcool picture rfyiamcool  路  3Comments

littletwolee picture littletwolee  路  3Comments

fieryorc picture fieryorc  路  3Comments

satb picture satb  路  3Comments