worklog/internal/database/connection.go

66 lines
1.3 KiB
Go
Raw Normal View History

2023-01-27 17:09:18 +01:00
package database
import (
"io"
"os"
"time"
"velvettear/worklog/internal/config"
"velvettear/worklog/internal/log"
"velvettear/worklog/internal/tools"
defaultLog "log"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
var connection *gorm.DB
// exported function(s)
func Initialize() {
tmp, error := connect(config.Database())
if error != nil {
log.Fatal("encountered an error connecting to file database '"+config.Database()+"'", error.Error())
}
connection = tmp
}
func Connection() *gorm.DB {
return connection
}
// unexported function(s)
func createLogger() logger.Interface {
if !config.Debug() {
return logger.New(defaultLog.New(io.Discard, "", defaultLog.LstdFlags), logger.Config{})
}
return logger.New(
defaultLog.New(os.Stdout, "\r\n", defaultLog.LstdFlags),
logger.Config{
SlowThreshold: time.Second,
LogLevel: logger.Warn,
IgnoreRecordNotFoundError: true,
Colorful: true,
},
)
}
func connect(path string) (*gorm.DB, error) {
if !tools.Exists(path) {
tools.CreateFile(path)
}
connection, error := gorm.Open(sqlite.Open(path), &gorm.Config{
Logger: createLogger(),
})
if error != nil {
return connection, error
}
migrateSchema(connection)
return connection, nil
}
func migrateSchema(connection *gorm.DB) {
connection.AutoMigrate(&Timestamp{})
}