2023-03-14 15:22:52 +00:00
|
|
|
package models
|
|
|
|
|
|
|
|
import (
|
2023-04-17 12:25:39 +00:00
|
|
|
"errors"
|
|
|
|
"github.com/mattn/go-sqlite3"
|
2023-03-14 15:22:52 +00:00
|
|
|
"gorm.io/driver/sqlite"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
"gorm.io/gorm/logger"
|
|
|
|
)
|
|
|
|
|
|
|
|
var db *gorm.DB
|
|
|
|
|
|
|
|
func Setup(dbpath string) error {
|
|
|
|
var err error
|
|
|
|
|
|
|
|
if db, err = gorm.Open(sqlite.Open(dbpath+"?_fk=true"), &gorm.Config{
|
|
|
|
Logger: logger.Default.LogMode(logger.Silent),
|
|
|
|
}); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-04-16 22:17:06 +00:00
|
|
|
if err = db.AutoMigrate(&User{}, &SSHKey{}, &Gist{}, &AdminSetting{}); err != nil {
|
2023-03-14 15:22:52 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-04-18 00:33:19 +00:00
|
|
|
ApplyMigrations(db)
|
|
|
|
|
2023-04-16 22:17:06 +00:00
|
|
|
// Default admin setting values
|
|
|
|
return initAdminSettings(map[string]string{
|
2023-05-12 10:06:55 +00:00
|
|
|
SettingDisableSignup: "0",
|
|
|
|
SettingRequireLogin: "0",
|
|
|
|
SettingDisableLoginForm: "0",
|
2023-04-16 22:17:06 +00:00
|
|
|
})
|
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
|
|
|
|
}
|
2023-04-17 12:25:39 +00:00
|
|
|
|
|
|
|
func IsUniqueConstraintViolation(err error) bool {
|
|
|
|
var sqliteErr sqlite3.Error
|
|
|
|
if errors.As(err, &sqliteErr) && sqliteErr.ExtendedCode == sqlite3.ErrConstraintUnique {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|