package db import ( "farga/db/types" "farga/lib" "os" "time" "gorm.io/driver/sqlite" "gorm.io/gorm" "gorm.io/gorm/logger" ) type DB struct { *gorm.DB } func New() (*DB, error) { db, err := gorm.Open(sqlite.Open(os.Getenv("SQLITE_PATH")), &gorm.Config{ Logger: logger.Default.LogMode(logger.Error), // only errors to console }) if err != nil { return nil, err } db.Exec("PRAGMA foreign_keys = ON;") // doesn't allow ignoring foreign keys. db.Exec("PRAGMA journal_mode = WAL;") // enables write-ahead log. db.Exec("PRAGMA synchronous = NORMAL;") // https://mort.coffee/home/sqlite-editions/ db.Exec("PRAGMA busy_timeout = 5000;") // timeout for writers waiting for sqlite to unlock. db.AutoMigrate(&types.User{}) db.AutoMigrate(&types.UserConfig{}) db.AutoMigrate(&types.Session{}) db.AutoMigrate(&types.Repo{}) db.AutoMigrate(&types.RepoConfig{}) db.AutoMigrate(&types.Issue{}) db.AutoMigrate(&types.IssueComment{}) db.AutoMigrate(&types.SSHPubKey{}) db.AutoMigrate(&types.OAuthState{}) return &DB{db}, nil } func (db *DB) CleanupTicker() { ticker := time.NewTicker(lib.DatabaseCleanupMinutes * time.Minute) defer ticker.Stop() for range ticker.C { db.RemoveExpiredSessions() db.RemoveExpiredOAuthStates() } }