package store import ( "fmt" "time" "github.com/globalsign/mgo" ) var db *mgo.Database var dbInits []func(db *mgo.Database) // ConnectDB connects to a mongodb database. func ConnectDB(host string, port int, database, username, password, mechanism string) error { session, err := mgo.DialWithInfo(&mgo.DialInfo{ Addrs: []string{fmt.Sprintf("%s:%d", host, port)}, Timeout: 30 * time.Second, Database: database, Username: username, Password: password, Mechanism: mechanism, Source: database, }) if err != nil { return err } db = session.DB(database) return setupDB() } // HandleInit handles the initialization of the database func HandleInit(function func(db *mgo.Database)) { dbInits = append(dbInits, function) } func setupDB() error { db.C("common.characters").EnsureIndexKey("name") db.C("common.characters").EnsureIndexKey("shortName") db.C("common.characters").EnsureIndexKey("author") err := db.C("common.characters").EnsureIndex(mgo.Index{ Key: []string{"nicks"}, Unique: true, DropDups: true, }) if err != nil { return err } db.C("logbot3.logs").EnsureIndexKey("date") db.C("logbot3.logs").EnsureIndexKey("channel") db.C("logbot3.logs").EnsureIndexKey("channel", "open") db.C("logbot3.logs").EnsureIndexKey("open") db.C("logbot3.logs").EnsureIndexKey("oldId") db.C("logbot3.logs").EnsureIndexKey("characterIds") db.C("logbot3.logs").EnsureIndexKey("event") db.C("logbot3.logs").EnsureIndexKey("$text:channel", "$text:title", "$text:event", "$text:description", "$text:posts.nick", "$text:posts.text") err = db.C("server.changes").EnsureIndex(mgo.Index{ Key: []string{"date"}, ExpireAfter: time.Hour * (24 * 14), }) if err != nil { return err } for _, dbInit := range dbInits { dbInit(db) } return nil }