relynolli-server/internal/database.go

67 lines
1.0 KiB
Go
Raw Normal View History

2024-03-15 21:27:45 +03:00
package internal
import (
"database/sql"
"fmt"
2024-03-23 21:16:41 +03:00
"github.com/uptrace/bun/extra/bundebug"
2024-03-15 21:27:45 +03:00
"log"
"os"
"sync"
2024-03-22 20:10:42 +03:00
_ "github.com/go-sql-driver/mysql"
2024-03-23 21:16:41 +03:00
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/mysqldialect"
2024-03-15 21:27:45 +03:00
)
type database struct {
2024-03-23 21:16:41 +03:00
instance *bun.DB
2024-03-15 21:27:45 +03:00
}
type Database interface {
2024-03-23 21:16:41 +03:00
GetInstance() *bun.DB
2024-03-15 21:27:45 +03:00
}
var (
instance *database = nil
once sync.Once
)
func initialize() {
2024-03-23 21:16:41 +03:00
db, err := sql.Open("mysql", fmt.Sprintf(
2024-03-15 21:27:45 +03:00
"%s:%s@tcp(%s)/%s",
os.Getenv("MYSQL_USER"),
os.Getenv("MYSQL_PASSWORD"),
os.Getenv("MYSQL_HOST"),
os.Getenv("MYSQL_DATABASE")))
if err != nil {
panic(err)
}
2024-03-23 21:16:41 +03:00
// Resolve instances of bun
ormDb := bun.NewDB(db, mysqldialect.New())
ormDb.AddQueryHook(bundebug.NewQueryHook())
// Check Connection
conErr := ormDb.Ping()
2024-03-22 20:10:42 +03:00
if conErr != nil {
panic(conErr)
2024-03-15 21:27:45 +03:00
}
log.Println("Connection to db succeded")
2024-03-23 21:16:41 +03:00
instance = &database{instance: ormDb}
2024-03-15 21:27:45 +03:00
}
func InitDatabase() Database {
if instance == nil {
once.Do(initialize)
}
return instance
}
2024-03-23 21:16:41 +03:00
func (d *database) GetInstance() *bun.DB {
return d.instance
2024-03-15 21:27:45 +03:00
}