about summary refs log tree commit diff
path: root/src/db/connection.go
diff options
context:
space:
mode:
authorhanemile <mail@emile.space>2020-07-19 01:56:09 +0200
committerhanemile <mail@emile.space>2020-07-19 01:56:09 +0200
commitfc63adf55849f748a37cef4c425a19a1c0f0e76e (patch)
tree034c6ab3abb08fe15c702298f294226f1b0071c2 /src/db/connection.go
initial commit
Diffstat (limited to 'src/db/connection.go')
-rw-r--r--src/db/connection.go50
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
+}