Pg: Custom table name?

Created on 3 Apr 2016  路  3Comments  路  Source: go-pg/pg

Is it possible to create a model but specify a custom table name? If so, how does one do so?

Most helpful comment

Yes, it is possible:

type MyStruct struct {
    TableName struct{} `sql:"custom_table_name"`

    Id int
    ...
}

I need to add an example.

All 3 comments

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")
Was this page helpful?
0 / 5 - 0 ratings

Related issues

enchantner picture enchantner  路  3Comments

AbooJan picture AbooJan  路  5Comments

owentran picture owentran  路  6Comments

Alireza-Ta picture Alireza-Ta  路  3Comments

NinaLeven picture NinaLeven  路  6Comments