package controllers import ( "github.com/jinzhu/gorm" _ "github.com/mattn/go-sqlite3" "github.com/revel/revel" "time" ) type User struct { Id int64 Email string `sql:"unique"` Name string `sql:"unique"` Password string Confirmed bool Alerts []Alert CreatedAt time.Time DeletedAt time.Time UpdatedAt time.Time } // Multiple accounts which are alerted type Alert struct { Id int64 UserId int64 Email string CreatedAt time.Time DeletedAt time.Time UpdatedAt time.Time } type Job struct { Id int64 UserId int64 Name string Url string Versions []Version Diff string DiffLen int64 CreatedAt time.Time DeletedAt time.Time UpdatedAt time.Time } // Save history version of jobs type Version struct { Id int64 JobId int64 Content string Hash string CreatedAt time.Time DeletedAt time.Time UpdatedAt time.Time } var db = DBInit() func DBInit() *gorm.DB { // Open database handler db, err := gorm.Open(revel.Config.String("db.driver"), revel.Config.String("db.spec")) // Set database logging to TRACE db.LogMode(true) db.SetLogger(gorm.Logger{revel.TRACE}) // Ping database to check if up if err = db.DB().Ping(); err != nil { revel.ERROR.Panicf("Failed to init database. %s \n", err) } defer db.Close() // Set Pool connections db.DB().SetMaxIdleConns(10) db.DB().SetMaxOpenConns(100) // Create tables which are defined as struct db.Debug().CreateTable(&User{}) db.Debug().CreateTable(&Alert{}) db.Debug().CreateTable(&Job{}) db.Debug().CreateTable(&Version{}) // Automigration db.Debug().AutoMigrate(&User{}, &Job{}, &Version{}, &Alert{}) // Add index on email and name to enforce uniqueness db.Debug().Model(&User{}).AddUniqueIndex("idx_user_email", "email") db.Debug().Model(&User{}).AddUniqueIndex("idx_user_name", "name") // Unique index on alert to ensure every user can specify not multiple equally alerts db.Debug().Model(&Alert{}).AddUniqueIndex("idx_alert_email_userid", "email", "user_id") // Unique index to ensure every user can have only one job with the same name db.Debug().Model(&Job{}).AddUniqueIndex("idx_job_name_userid", "name", "user_id") // Makes hash unique // db.Debug().Model(&Version{}).AddUniqueIndex("idx_version_hash", "hash") return db }