7 September 2020

go-pg is PostgreSQL client and ORM for Golang. To show generated queries we have to implement some hooks. There are multiple posts about this in issues, this is an exact working example of it.

Source code viewer
  1. import (
  2. "fmt"
  3. "context"
  4. )
  5.  
  6.  
  7. type dbLogger struct { }
  8.  
  9. func (d dbLogger) BeforeQuery(c context.Context, q *pg.QueryEvent) (context.Context, error) {
  10. return c, nil
  11. }
  12.  
  13. func (d dbLogger) AfterQuery(c context.Context, q *pg.QueryEvent) error {
  14. fmt.Println(q.FormattedQuery())
  15. return nil
  16. }
  17.  
  18.  
  19. func main() {
  20. // ...
  21. // After add after database connection "db := pg.Connect(options)'
  22. db.AddQueryHook(dbLogger{})
  23. // ...
Programming Language: Go