Plan stuff. Log stuff.
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.

76 lines
1.7 KiB

5 years ago
  1. package bolt
  2. import (
  3. "errors"
  4. "github.com/gisle/stufflog/config"
  5. "github.com/gisle/stufflog/database/repositories"
  6. "go.etcd.io/bbolt"
  7. "time"
  8. "unsafe"
  9. )
  10. // A Database is a database.Database implementation using a bolt backend.
  11. type Database struct {
  12. users repositories.UserRepository
  13. userSessions repositories.UserSessionRepository
  14. activities repositories.ActivityRepository
  15. periods repositories.PeriodRepository
  16. }
  17. func (database *Database) Users() repositories.UserRepository {
  18. return database.users
  19. }
  20. func (database *Database) UserSessions() repositories.UserSessionRepository {
  21. return database.userSessions
  22. }
  23. func (database *Database) Activities() repositories.ActivityRepository {
  24. return database.activities
  25. }
  26. func (database *Database) Periods() repositories.PeriodRepository {
  27. return database.periods
  28. }
  29. func Init(cfg config.Database) (*Database, error) {
  30. opts := *bbolt.DefaultOptions
  31. opts.Timeout = time.Second * 5
  32. db, err := bbolt.Open(cfg.Path, 0700, &opts)
  33. if err != nil {
  34. return nil, err
  35. }
  36. users, err := newUserRepository(db)
  37. if err != nil {
  38. return nil, err
  39. }
  40. userSessions, err := newUserSessionRepository(db)
  41. if err != nil {
  42. return nil, err
  43. }
  44. periods, err := newPeriodRepository(db)
  45. if err != nil {
  46. return nil, err
  47. }
  48. activities, err := newActivityRepository(db)
  49. if err != nil {
  50. return nil, err
  51. }
  52. database := &Database{
  53. users: users,
  54. userSessions: userSessions,
  55. periods: periods,
  56. activities: activities,
  57. }
  58. return database, nil
  59. }
  60. // unsafeStringToBytes makes a byte array, mutation is punishable by segfault.
  61. func unsafeStringToBytes(s string) []byte {
  62. return *(*[]byte)(unsafe.Pointer(&s))
  63. }
  64. var errUnchanged = errors.New("database/bolt: unchanged")