pg icon indicating copy to clipboard operation
pg copied to clipboard

BeforeConnect Hook

Open justcompile opened this issue 3 years ago • 5 comments

As per discussions in https://github.com/go-pg/pg/discussions/1848

This PR adds a new hook into Options to facilitate the use of secret providers / dynamic / one-time passwords. It has been added as BeforeConnect in order for the usage to be generic; whether it is for secret providers or simply logging when database connections are established.

Example

some error handling removed for readability

package main

imports (
    "context"
    "github.com/go-pg/pg/v10"

    "github.com/fake-user/supersecrets"
)

func main() {
    opts, _ := pg.ParseURL("postgresql://dbUser@dbhost/accounts")
   
    opts.BeforeConnect = func(ctx context.Context, o *pg.Options) error {
        token, err := supersecrets.GetToken("accounts-db-password")
        if err != nil {
            return err
        }

        o.Password = token

        return nil
    }

    db := pg.Connect(opts)

    // business logic
}


justcompile avatar Apr 20 '21 19:04 justcompile

Thanks for the feedback, I'll work the suggestions into this PR over the coming days

justcompile avatar Apr 21 '21 14:04 justcompile

@vmihailenco any way I'd be able to take this over? Still very interested in it

elliotcourant avatar Sep 28 '21 19:09 elliotcourant

@elliotcourant sure, go ahead :+1:

vmihailenco avatar Sep 29 '21 07:09 vmihailenco

@vmihailenco sorry for the horrendous delay in this. Before I get around to resolve the testing points from @elliotcourant, could I confirm whether the current changes align with your expectations around cloning Options?

justcompile avatar Oct 29 '21 12:10 justcompile

@justcompile I will take a look at the diff again this weekend and double check it!

elliotcourant avatar Oct 29 '21 16:10 elliotcourant