summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
Diffstat (limited to 'pkg/database/connection.go')
-rw-r--r--pkg/database/connection.go68
1 files changed, 68 insertions, 0 deletions
diff --git a/pkg/database/connection.go b/pkg/database/connection.go
new file mode 100644
index 0000000..c5e7c7b
--- /dev/null
+++ b/pkg/database/connection.go
@@ -0,0 +1,68 @@
+// Contains utility functions around the database
+
+package database
+
+import (
+ "context"
+ "github.com/go-pg/pg/v9"
+ "github.com/go-pg/pg/v9/orm"
+ "go-gentoo/pkg/config"
+ "go-gentoo/pkg/logger"
+ "go-gentoo/pkg/models"
+ "log"
+)
+
+// DBCon is the connection handle
+// for the database
+var (
+ DBCon *pg.DB
+)
+
+// CreateSchema creates the tables in the database
+// in case they don't alreay exist
+func CreateSchema() error {
+ for _, model := range []interface{}{(*models.Link)(nil)} {
+
+ err := DBCon.CreateTable(model, &orm.CreateTableOptions{
+ IfNotExists: true,
+ })
+ if err != nil {
+ return err
+ }
+
+ }
+ return nil
+}
+
+type dbLogger struct{}
+
+func (d dbLogger) BeforeQuery(c context.Context, q *pg.QueryEvent) (context.Context, error) {
+ return c, nil
+}
+
+// AfterQuery is used to log SQL queries
+func (d dbLogger) AfterQuery(c context.Context, q *pg.QueryEvent) error {
+ logger.Debug.Println(q.FormattedQuery())
+ return nil
+}
+
+// Connect is used to connect to the database
+// and turn on logging if desired
+func Connect() {
+ DBCon = pg.Connect(&pg.Options{
+ User: config.PostgresUser(),
+ Password: config.PostgresPass(),
+ Database: config.PostgresDb(),
+ Addr: config.PostgresHost() + ":" + config.PostgresPort(),
+ })
+
+ DBCon.AddQueryHook(dbLogger{})
+
+ err := CreateSchema()
+ if err != nil {
+ logger.Error.Println("ERROR: Could not create database schema")
+ logger.Error.Println(err)
+ log.Fatalln(err)
+ }
+
+}