store.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. db *sql.DB
  11. profile *profile.Profile
  12. userCache sync.Map // map[int]*userRaw
  13. userSettingCache sync.Map // map[string]*userSettingRaw
  14. memoCache sync.Map // map[int]*memoRaw
  15. shortcutCache sync.Map // map[int]*shortcutRaw
  16. idpCache sync.Map // map[int]*identityProviderMessage
  17. }
  18. // New creates a new instance of Store.
  19. func New(db *sql.DB, profile *profile.Profile) *Store {
  20. return &Store{
  21. db: db,
  22. profile: profile,
  23. }
  24. }
  25. func (s *Store) Vacuum(ctx context.Context) error {
  26. tx, err := s.db.BeginTx(ctx, nil)
  27. if err != nil {
  28. return FormatError(err)
  29. }
  30. defer tx.Rollback()
  31. if err := vacuum(ctx, tx); err != nil {
  32. return err
  33. }
  34. if err := tx.Commit(); err != nil {
  35. return FormatError(err)
  36. }
  37. // Vacuum sqlite database file size after deleting resource.
  38. if _, err := s.db.Exec("VACUUM"); err != nil {
  39. return err
  40. }
  41. return nil
  42. }
  43. // Exec vacuum records in a transaction.
  44. func vacuum(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 := vacuumTag(ctx, tx); err != nil {
  64. // Prevent revive warning.
  65. return err
  66. }
  67. return nil
  68. }