summaryrefslogtreecommitdiff
path: root/internal/api/database/database.go
blob: 4470c581511c695f1c2eceabaf91f76d6eee15be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package database

import (
	"gorm.io/driver/postgres"
	"gorm.io/gorm"

	"errors"
)

// Global variable but private
var db *gorm.DB = nil

// Init the database from a DSN string which must be a valid PostgreSQL dsn.
// Also, auto migrate all the models.
func InitDb(dsn string) (*gorm.DB, error) {
	var err error
	db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})

	if err == nil {
		db.AutoMigrate(&User{}, &Game{})
	}

	return db, err
}

// Return the instance or error if the config is not laoded yet
func GetDb() (*gorm.DB, error) {
	if db == nil {
		return nil, errors.New("You must call `InitDb()` first.")
	}
	return db, nil
}