fin-check-api/db/db.go

63 lines
1.3 KiB
Go
Raw Normal View History

2024-08-01 23:02:55 +02:00
package db
import (
"errors"
"log"
"os"
"sync"
"time"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
var udb *gorm.DB
var conMu sync.Mutex
var (
ERROR_DB_NOT_INIT = errors.New("Database connection is not initialized")
)
func Connect() *gorm.DB {
conMu.Lock()
defer conMu.Unlock()
if udb != nil {
return udb
}
2024-11-08 16:05:23 +01:00
logFile, err := os.OpenFile("db.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
panic(err)
}
2024-08-01 23:02:55 +02:00
newLogger := logger.New(
2024-11-08 16:05:23 +01:00
log.New(logFile, "\r\n", log.LstdFlags),
2024-08-01 23:02:55 +02:00
logger.Config{
SlowThreshold: time.Second,
LogLevel: logger.Error,
IgnoreRecordNotFoundError: true,
ParameterizedQueries: true,
Colorful: false,
},
)
gormDB, err := gorm.Open(sqlite.Open("gonuts.db"), &gorm.Config{
Logger: newLogger,
})
if err != nil {
log.Panic(err)
}
newUDB := gormDB
2024-08-03 07:05:46 +02:00
gormDB.AutoMigrate(&Card{})
2024-08-01 23:02:55 +02:00
gormDB.AutoMigrate(&Category{})
gormDB.AutoMigrate(&Item{})
gormDB.AutoMigrate(&ItemPrice{})
gormDB.AutoMigrate(&Payment{})
gormDB.AutoMigrate(&ItemBought{})
gormDB.AutoMigrate(&Income{})
gormDB.AutoMigrate(&Debt{})
2024-08-03 07:15:39 +02:00
gormDB.AutoMigrate(&Transfer{})
2024-08-02 22:37:05 +02:00
gormDB.AutoMigrate(&User{})
2024-10-29 11:24:46 +01:00
gormDB.AutoMigrate(&Type{})
2024-11-06 18:47:12 +01:00
gormDB.AutoMigrate(&Session{})
2024-08-01 23:02:55 +02:00
return newUDB
}