fin-check-api/db/db.go

118 lines
2.4 KiB
Go
Raw Normal View History

2024-08-01 23:02:55 +02:00
package db
import (
"errors"
"fmt"
2024-08-01 23:02:55 +02:00
"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 Init() error {
dbc := Connect()
// Seeds
if err := initStateOfDb(dbc); err != nil {
return fmt.Errorf("initStateOfDb: %w", err)
}
return nil
}
2024-08-01 23:02:55 +02:00
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-11-16 10:42:28 +01:00
gormDB.AutoMigrate(&Expense{})
2024-11-19 09:12:28 +01:00
gormDB.AutoMigrate(&Metric{})
2024-11-20 17:44:23 +01:00
gormDB.AutoMigrate(&Currency{})
2024-08-01 23:02:55 +02:00
return newUDB
}
var (
CANT_FIND_METRIC = errors.New("Can't find proper metrics in database")
)
func initMetrics(tx *gorm.DB) error {
var metrics []Metric
if err := tx.Find(&metrics).Error; err != nil {
return err
}
metricsThatNeeded := []*Metric{
&Metric{Name: "None", Short: "pcs", Value: 0},
&Metric{Name: "Gram", Short: "g", Value: 1},
&Metric{Name: "Kilogram", Short: "kg", Value: 2},
&Metric{Name: "Liter", Short: "l", Value: 3},
}
if len(metrics) == 0 {
for _, m := range metricsThatNeeded {
if err := tx.Create(m).Error; err != nil {
return err
}
}
return nil
}
for _, m := range metricsThatNeeded {
tmp := &Metric{}
if err := tx.Find(tmp, m).Error; err != nil {
return err
}
if tmp.ID == 0 {
return CANT_FIND_METRIC
}
}
return nil
}
func initStateOfDb(tx *gorm.DB) error {
if err := initMetrics(tx); err != nil {
return fmt.Errorf("initMetrics: %w", err)
}
return nil
}