vikunja-api/pkg/models/models.go

93 lines
2.1 KiB
Go
Raw Permalink Normal View History

2018-06-10 11:11:41 +02:00
package models
import (
"fmt"
_ "github.com/go-sql-driver/mysql" // Because.
"github.com/go-xorm/core"
"github.com/go-xorm/xorm"
2018-09-13 19:53:03 +02:00
xrc "github.com/go-xorm/xorm-redis-cache"
2018-09-13 22:14:53 +02:00
_ "github.com/mattn/go-sqlite3" // Because.
2018-09-13 19:53:03 +02:00
"encoding/gob"
2018-09-13 22:14:53 +02:00
"github.com/spf13/viper"
2018-06-10 11:11:41 +02:00
)
2018-06-10 14:14:10 +02:00
var (
x *xorm.Engine
tables []interface{}
)
2018-06-10 11:11:41 +02:00
func getEngine() (*xorm.Engine, error) {
// Use Mysql if set
if viper.GetString("database.type") == "mysql" {
connStr := fmt.Sprintf(
"%s:%s@tcp(%s)/%s?charset=utf8&parseTime=true",
viper.GetString("database.user"),
viper.GetString("database.password"),
viper.GetString("database.host"),
viper.GetString("database.database"))
e, err := xorm.NewEngine("mysql", connStr)
e.SetMaxOpenConns(viper.GetInt("database.openconnections"))
return e, err
2018-06-10 11:11:41 +02:00
}
// Otherwise use sqlite
path := viper.GetString("database.path")
2018-06-10 11:11:41 +02:00
if path == "" {
path = "./db.db"
}
return xorm.NewEngine("sqlite3", path)
}
2018-06-10 14:14:10 +02:00
func init() {
tables = append(tables,
new(User),
new(List),
2018-08-30 08:09:17 +02:00
new(ListTask),
new(Team),
new(TeamMember),
new(TeamList),
new(TeamNamespace),
new(Namespace),
new(ListUser),
2018-09-04 20:15:24 +02:00
new(NamespaceUser),
2018-06-10 14:14:10 +02:00
)
}
2018-06-10 11:11:41 +02:00
// SetEngine sets the xorm.Engine
func SetEngine() (err error) {
x, err = getEngine()
if err != nil {
return fmt.Errorf("Failed to connect to database: %v", err)
}
// Cache
2018-09-13 19:53:03 +02:00
if viper.GetBool("cache.enabled") {
switch viper.GetString("cache.type") {
case "memory":
cacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), viper.GetInt("cache.maxelementsize"))
x.SetDefaultCacher(cacher)
break
case "redis":
cacher := xrc.NewRedisCacher(viper.GetString("cache.redishost"), viper.GetString("cache.redispassword"), xrc.DEFAULT_EXPIRATION, x.Logger())
x.SetDefaultCacher(cacher)
gob.Register(tables)
break
default:
fmt.Println("Did not find a valid cache type. Caching disabled. Please refer to the docs for poosible cache types.")
}
}
2018-06-10 11:11:41 +02:00
x.SetMapper(core.GonicMapper{})
// Sync dat shit
2018-06-10 14:14:10 +02:00
if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
return fmt.Errorf("sync database struct error: %v", err)
}
2018-06-10 11:11:41 +02:00
x.ShowSQL(viper.GetBool("database.showqueries"))
2018-06-10 11:11:41 +02:00
return nil
}