go-pg / pg

Golang ORM with focus on PostgreSQL features and performance
https://pg.uptrace.dev/
BSD 2-Clause "Simplified" License
5.67k stars 404 forks source link

Tables created with "on update" or "on delete" struct tags don't have these options actually set #1859

Closed antipopp closed 3 years ago

antipopp commented 3 years ago

Expected Behavior

When creating a model that has on_update or on_delete tags I would expect that the resulting table would have these options set for the respective foreign key.

Current Behavior

It doesn't set the foreign key with on_delete or on_update options.

Code example

type DossierRule struct {
    ID              string `json:"id"`
    Description     string `json:"description"`
    DossierTypeName string      `json:"dossier_type_fk"`
    DossierType     DossierType `pg:"rel:has-one,on_delete:CASCADE"`
}

type DossierType struct {
    Name         string         `pg:",pk"`
    CreatedAt    *time.Time     `json:"createdAt"`
    DossierRules []*DossierRule `pg:"rel:has-many"`
}

func createSchema() error {

    models := []interface{}{
        (*DossierType)(nil),
        (*DossierRule)(nil),
    }

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

    return nil
}

func main() {
        connectionOptions := &pg.Options{
                Addr: "",
        Database: "",
        User: "",
        Password: "",
    }

        DB = pg.Connect(connectionOptions)

        err := createSchema()
    if err != nil {
        log.Println(err)
    }
}
antipopp commented 3 years ago

Well, my bad. Apparently the on_update or on_delete tag goes (quite obviously now that I know) on the FK field (the one that actually generates the FK column). Like this:

type DossierRule struct {
    ID              string `json:"id"`
    Description     string `json:"description"`
    DossierTypeName string      `json:"dossier_type_fk" pg:"on_delete:CASCADE"`
    DossierType     DossierType `pg:"rel:has-one"`
}

Maybe the docs could be clearer when explaining FK constraints.