mysql.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package mysql
  2. import (
  3. "context"
  4. "database/sql"
  5. "fmt"
  6. "github.com/pkg/errors"
  7. "github.com/usememos/memos/server/profile"
  8. "github.com/usememos/memos/store"
  9. )
  10. type DB struct {
  11. db *sql.DB
  12. profile *profile.Profile
  13. }
  14. func NewDB(profile *profile.Profile) (store.Driver, error) {
  15. // Open MySQL connection with parameter.
  16. // multiStatements=true is required for migration.
  17. // See more in: https://github.com/go-sql-driver/mysql#multistatements
  18. db, err := sql.Open("mysql", fmt.Sprintf("%s?multiStatements=true", profile.DSN))
  19. if err != nil {
  20. return nil, errors.Wrapf(err, "failed to open db: %s", profile.DSN)
  21. }
  22. driver := DB{db: db, profile: profile}
  23. return &driver, nil
  24. }
  25. func (d *DB) GetDB() *sql.DB {
  26. return d.db
  27. }
  28. func (d *DB) Vacuum(ctx context.Context) error {
  29. tx, err := d.db.BeginTx(ctx, nil)
  30. if err != nil {
  31. return err
  32. }
  33. defer tx.Rollback()
  34. if err := vacuumMemo(ctx, tx); err != nil {
  35. return err
  36. }
  37. if err := vacuumResource(ctx, tx); err != nil {
  38. return err
  39. }
  40. if err := vacuumUserSetting(ctx, tx); err != nil {
  41. return err
  42. }
  43. if err := vacuumMemoOrganizer(ctx, tx); err != nil {
  44. return err
  45. }
  46. if err := vacuumMemoRelations(ctx, tx); err != nil {
  47. return err
  48. }
  49. if err := vacuumTag(ctx, tx); err != nil {
  50. // Prevent revive warning.
  51. return err
  52. }
  53. return tx.Commit()
  54. }
  55. func (*DB) BackupTo(context.Context, string) error {
  56. return errors.New("Please use mysqldump to backup")
  57. }
  58. func (d *DB) Close() error {
  59. return d.db.Close()
  60. }