Pg: How to access orm.DB in Model Hooks

Created on 16 Jul 2019  路  3Comments  路  Source: go-pg/pg

Since signature of Model Hooks changed I would like to know how to port old hooks. Due to lack of documentation I can't figure out how to implement some features
Here is an example of old one:

func (c *Country) AfterInsert(db orm.DB) error {
    location := &Location{
        ID: c.LocationID,
    }

    if err := db.Model(location).WherePK().Select(); err != nil && err != pg.ErrNoRows {
        return err
    }

    c.Location = location
    return nil
}

That particular case was very useful when it is needed to add FK model to newly created object.

BTW panic when using old hooks is really annoying. Program built, runs but crashes when hooks is involved

All 3 comments

You can try to pass db in context. orm.DB was removed because these hooks are about data in models - not database. It is probably too opinionated/radical but that is what we have now.

I was using orm.DB in one place and it was causing constant unexpected performance problems. So as a rule of thumb I would not execute any queries from hooks.

BTW panic when using old hooks is really annoying

That is better than silently ignoring hooks I guess. Probably it should be replaced with log message though.

Thanks for answering

It is probably too opinionated/radical but that is what we have now.

I think it is. Performance is one thing, but removing it entirely just because performance is a bit too radical. Here's one vote toward putting it back.

You can try to pass db in context

Any guidance on this? Use db.Context() to grab the context, and then db.WithContext() to set the new context?

Man, I think I'll just revert the upgrade.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

RepentantGopher picture RepentantGopher  路  5Comments

jayschwa picture jayschwa  路  4Comments

Alireza-Ta picture Alireza-Ta  路  3Comments

eicca picture eicca  路  3Comments

noggan picture noggan  路  5Comments