Define Postgresql Column as Serial in go-pg ORM

956 Views Asked by At

I want to create different tables in a postgresql db. For now I am using the go-pg ORM package. I already found a possible way to this using the following code:

func set_up_tables(db *pg.DB) error {
    models := []interface{}{
        (*User)(nil),
        (*Account)(nil),
        (*Transaction)(nil),
    }

    for _, model := range models {
        err := db.Model(model).CreateTable(&orm.CreateTableOptions{
            IfNotExists: true,
        })
        if err != nil {
            return err
        }
    }
    return nil
}

For now lets just look at the user struct which I defined like this:

type User struct {
    UserId    string `json:"userId"`
    Email     string `json:"emailAddress"`
    Firstname string `json:"firstName"`
    Lastname  string `json:"lastName"`
    Address   string `json:"address"`
}

I want the userId Column to be a Serial, which means being unique, not null, and autoincremented. Is there a way to do this using the ORM, or Go code? I have already been able to change it in pgadmin by hand but there are more structs with Ids that should be changed and I do not want to do it by hand ofc. And as additional question is this a good way to implement it?

1

There are 1 best solutions below

2
On

If you review the documentation you'll find that you need to be using pg struct tags for your model, not json tags; and that PG is an ORM, but not a migration tool. You don't use PG to define your schema, only to map your schema to your data structures.