opengist/internal/models/db.go

60 lines
1.4 KiB
Go
Raw Normal View History

2023-03-14 15:22:52 +00:00
package models
import (
"errors"
"strings"
"github.com/glebarez/sqlite"
2023-06-09 13:25:41 +00:00
"github.com/rs/zerolog/log"
"github.com/thomiceli/opengist/internal/config"
"github.com/thomiceli/opengist/internal/utils"
2023-03-14 15:22:52 +00:00
"gorm.io/gorm"
"gorm.io/gorm/logger"
msqlite "modernc.org/sqlite"
2023-03-14 15:22:52 +00:00
)
var db *gorm.DB
2023-06-09 13:25:41 +00:00
func Setup(dbPath string) error {
2023-03-14 15:22:52 +00:00
var err error
2023-06-09 13:25:41 +00:00
journalMode := strings.ToUpper(config.C.SqliteJournalMode)
2023-03-14 15:22:52 +00:00
2023-06-09 13:25:41 +00:00
if !utils.SliceContains([]string{"DELETE", "TRUNCATE", "PERSIST", "MEMORY", "WAL", "OFF"}, journalMode) {
log.Warn().Msg("Invalid SQLite journal mode: " + journalMode)
}
if db, err = gorm.Open(sqlite.Open(dbPath+"?_fk=true&_journal_mode="+journalMode), &gorm.Config{
2023-03-14 15:22:52 +00:00
Logger: logger.Default.LogMode(logger.Silent),
}); err != nil {
return err
}
if err = db.AutoMigrate(&User{}, &SSHKey{}, &Gist{}, &AdminSetting{}); err != nil {
2023-03-14 15:22:52 +00:00
return err
}
ApplyMigrations(db)
// Default admin setting values
return initAdminSettings(map[string]string{
SettingDisableSignup: "0",
SettingRequireLogin: "0",
SettingDisableLoginForm: "0",
SettingDisableGravatar: "0",
})
2023-03-14 15:22:52 +00:00
}
func CountAll(table interface{}) (int64, error) {
var count int64
err := db.Model(table).Count(&count).Error
return count, err
}
func IsUniqueConstraintViolation(err error) bool {
var sqliteErr *msqlite.Error
if errors.As(err, &sqliteErr) && sqliteErr.Code() == 2067 {
return true
}
return false
}