diff options
author | hanemile <mail@emile.space> | 2020-07-19 13:15:31 +0200 |
---|---|---|
committer | hanemile <mail@emile.space> | 2020-07-19 13:15:31 +0200 |
commit | 50500b9e8eb0b891f598e66801f5dcca55d1186e (patch) | |
tree | 5f07d91b90d95cc1634bccdb5a53aaae0d9fff9f /src/db/connection.go | |
parent | 0773cb78d1e2ae090602e5c89e7951b16dbeb21c (diff) |
src update
Diffstat (limited to 'src/db/connection.go')
-rw-r--r-- | src/db/connection.go | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/src/db/connection.go b/src/db/connection.go new file mode 100644 index 0000000..622976d --- /dev/null +++ b/src/db/connection.go @@ -0,0 +1,50 @@ +package db + +import ( + "context" + + pg "github.com/go-pg/pg/v9" + "github.com/sirupsen/logrus" + "github.com/spf13/viper" +) + +type dbLogger struct{} + +func (d dbLogger) BeforeQuery(c context.Context, q *pg.QueryEvent) (context.Context, error) { + return c, nil +} + +func (d dbLogger) AfterQuery(c context.Context, q *pg.QueryEvent) error { + query, err := q.FormattedQuery() + if err != nil { + logrus.Trace("Could not get the query") + } + logrus.Tracef("[DB] %s", query) + return nil +} + +// Connect connects to the database +func Connect() *pg.DB { + logrus.Trace("[DB] Establishing a connection to the database") + + // define the database connection + db := pg.Connect(&pg.Options{ + Addr: viper.GetString("db.addr"), + User: viper.GetString("db.user"), + Password: viper.GetString("db.password"), + Database: viper.GetString("db.database"), + }) + + db.AddQueryHook(dbLogger{}) + + logrus.Trace("[DB] Done") + + return db +} + +// Disconnect closes the database connection +func Disconnect(db *pg.DB) { + logrus.Trace("[DB] Closing the database connection") + db.Close() + return +} |