GraphQL API and utilities for the rpdata project
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
1.8 KiB

  1. package store
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/globalsign/mgo"
  6. )
  7. var db *mgo.Database
  8. var dbInits []func(db *mgo.Database)
  9. // ConnectDB connects to a mongodb database.
  10. func ConnectDB(host string, port int, database, username, password, mechanism string) error {
  11. session, err := mgo.DialWithInfo(&mgo.DialInfo{
  12. Addrs: []string{fmt.Sprintf("%s:%d", host, port)},
  13. Timeout: 30 * time.Second,
  14. Database: database,
  15. Username: username,
  16. Password: password,
  17. Mechanism: mechanism,
  18. Source: database,
  19. })
  20. if err != nil {
  21. return err
  22. }
  23. db = session.DB(database)
  24. return setupDB()
  25. }
  26. // HandleInit handles the initialization of the database
  27. func HandleInit(function func(db *mgo.Database)) {
  28. dbInits = append(dbInits, function)
  29. }
  30. func setupDB() error {
  31. db.C("common.characters").EnsureIndexKey("name")
  32. db.C("common.characters").EnsureIndexKey("shortName")
  33. db.C("common.characters").EnsureIndexKey("author")
  34. err := db.C("common.characters").EnsureIndex(mgo.Index{
  35. Key: []string{"nicks"},
  36. Unique: true,
  37. DropDups: true,
  38. })
  39. if err != nil {
  40. return err
  41. }
  42. db.C("logbot3.logs").EnsureIndexKey("date")
  43. db.C("logbot3.logs").EnsureIndexKey("channel")
  44. db.C("logbot3.logs").EnsureIndexKey("channel", "open")
  45. db.C("logbot3.logs").EnsureIndexKey("open")
  46. db.C("logbot3.logs").EnsureIndexKey("oldId")
  47. db.C("logbot3.logs").EnsureIndexKey("characterIds")
  48. db.C("logbot3.logs").EnsureIndexKey("event")
  49. db.C("logbot3.logs").EnsureIndexKey("$text:channel", "$text:title", "$text:event", "$text:description", "$text:posts.nick", "$text:posts.text")
  50. err = db.C("server.changes").EnsureIndex(mgo.Index{
  51. Key: []string{"date"},
  52. ExpireAfter: time.Hour * (24 * 14),
  53. })
  54. if err != nil {
  55. return err
  56. }
  57. for _, dbInit := range dbInits {
  58. dbInit(db)
  59. }
  60. return nil
  61. }