store.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package store
  2. import (
  3. "context"
  4. "database/sql"
  5. "github.com/usememos/memos/api"
  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. cache api.CacheService
  13. }
  14. // New creates a new instance of Store.
  15. func New(db *sql.DB, profile *profile.Profile) *Store {
  16. cacheService := NewCacheService()
  17. return &Store{
  18. db: db,
  19. profile: profile,
  20. cache: cacheService,
  21. }
  22. }
  23. func (s *Store) Vacuum(ctx context.Context) error {
  24. tx, err := s.db.BeginTx(ctx, nil)
  25. if err != nil {
  26. return FormatError(err)
  27. }
  28. defer tx.Rollback()
  29. if err := vacuum(ctx, tx); err != nil {
  30. return err
  31. }
  32. if err := tx.Commit(); err != nil {
  33. return FormatError(err)
  34. }
  35. // Vacuum sqlite database file size after deleting resource.
  36. if _, err := s.db.Exec("VACUUM"); err != nil {
  37. return err
  38. }
  39. return nil
  40. }
  41. // Exec vacuum records in a transaction.
  42. func vacuum(ctx context.Context, tx *sql.Tx) error {
  43. if err := vacuumMemo(ctx, tx); err != nil {
  44. return err
  45. }
  46. if err := vacuumResource(ctx, tx); err != nil {
  47. return err
  48. }
  49. if err := vacuumShortcut(ctx, tx); err != nil {
  50. return err
  51. }
  52. if err := vacuumUserSetting(ctx, tx); err != nil {
  53. return err
  54. }
  55. if err := vacuumMemoOrganizer(ctx, tx); err != nil {
  56. return err
  57. }
  58. if err := vacuumMemoResource(ctx, tx); err != nil {
  59. return err
  60. }
  61. if err := vacuumTag(ctx, tx); err != nil {
  62. // Prevent revive warning.
  63. return err
  64. }
  65. return nil
  66. }