store.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package store
  2. import (
  3. "context"
  4. "database/sql"
  5. "sync"
  6. "github.com/usememos/memos/server/profile"
  7. )
  8. // Store provides database access to all raw objects.
  9. type Store struct {
  10. Profile *profile.Profile
  11. db *sql.DB
  12. systemSettingCache sync.Map // map[string]*systemSettingRaw
  13. userCache sync.Map // map[int]*userRaw
  14. userSettingCache sync.Map // map[string]*userSettingRaw
  15. memoCache sync.Map // map[int]*memoRaw
  16. shortcutCache sync.Map // map[int]*shortcutRaw
  17. idpCache sync.Map // map[int]*identityProviderMessage
  18. }
  19. // New creates a new instance of Store.
  20. func New(db *sql.DB, profile *profile.Profile) *Store {
  21. return &Store{
  22. Profile: profile,
  23. db: db,
  24. }
  25. }
  26. func (s *Store) Vacuum(ctx context.Context) error {
  27. tx, err := s.db.BeginTx(ctx, nil)
  28. if err != nil {
  29. return FormatError(err)
  30. }
  31. defer tx.Rollback()
  32. if err := s.vacuumImpl(ctx, tx); err != nil {
  33. return err
  34. }
  35. if err := tx.Commit(); err != nil {
  36. return FormatError(err)
  37. }
  38. // Vacuum sqlite database file size after deleting resource.
  39. if _, err := s.db.Exec("VACUUM"); err != nil {
  40. return err
  41. }
  42. return nil
  43. }
  44. func (*Store) vacuumImpl(ctx context.Context, tx *sql.Tx) error {
  45. if err := vacuumMemo(ctx, tx); err != nil {
  46. return err
  47. }
  48. if err := vacuumResource(ctx, tx); err != nil {
  49. return err
  50. }
  51. if err := vacuumShortcut(ctx, tx); err != nil {
  52. return err
  53. }
  54. if err := vacuumUserSetting(ctx, tx); err != nil {
  55. return err
  56. }
  57. if err := vacuumMemoOrganizer(ctx, tx); err != nil {
  58. return err
  59. }
  60. if err := vacuumMemoResource(ctx, tx); err != nil {
  61. return err
  62. }
  63. if err := vacuumMemoRelations(ctx, tx); err != nil {
  64. return err
  65. }
  66. if err := vacuumTag(ctx, tx); err != nil {
  67. // Prevent revive warning.
  68. return err
  69. }
  70. return nil
  71. }