Is it possible to create a model but specify a custom table name? If so, how does one do so?
Yes, it is possible:
type MyStruct struct {
TableName struct{} `sql:"custom_table_name"`
Id int
...
}
I need to add an example.
Thanks! Is it possible to specify the table name directly at query time? There are cases like sharding where one may have multiple tables with the same schema (model) but different names.
I have slightly different approach implemented in https://github.com/go-pg/sharding using named params, e.g.
type User struct {
TableName string `sql:"?shard.users"`
Id int64
AccountId int64
Name string
Emails []string
}
then in Shard wrapper I set value for ?shard variable - https://github.com/go-pg/sharding/blob/v4/shard.go#L29-L30
That way you can use named param in all queries (without ORM), e.g.
cluster.Shard(accountId).DB.Query("SELECT * FROM ?shard.table WHERE shard_id = ?shard_id")
Most helpful comment
Yes, it is possible:
I need to add an example.