mysql.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package mysql
  2. import (
  3. "context"
  4. "database/sql"
  5. "log/slog"
  6. "github.com/go-sql-driver/mysql"
  7. "github.com/pkg/errors"
  8. "github.com/usememos/memos/server/profile"
  9. "github.com/usememos/memos/store"
  10. )
  11. type DB struct {
  12. db *sql.DB
  13. profile *profile.Profile
  14. config *mysql.Config
  15. }
  16. func NewDB(profile *profile.Profile) (store.Driver, error) {
  17. // Open MySQL connection with parameter.
  18. // multiStatements=true is required for migration.
  19. // See more in: https://github.com/go-sql-driver/mysql#multistatements
  20. dsn, err := mergeDSN(profile.DSN)
  21. if err != nil {
  22. return nil, err
  23. }
  24. driver := DB{profile: profile}
  25. driver.config, err = mysql.ParseDSN(dsn)
  26. if err != nil {
  27. return nil, errors.New("Parse DSN eroor")
  28. }
  29. driver.db, err = sql.Open("mysql", dsn)
  30. if err != nil {
  31. return nil, errors.Wrapf(err, "failed to open db: %s", profile.DSN)
  32. }
  33. return &driver, nil
  34. }
  35. func (d *DB) GetDB() *sql.DB {
  36. return d.db
  37. }
  38. func (d *DB) GetCurrentDBSize(ctx context.Context) (int64, error) {
  39. query := "SELECT SUM(`data_length` + `index_length`) AS `size` " +
  40. " FROM information_schema.TABLES" +
  41. " WHERE `table_schema` = ?" +
  42. " GROUP BY `table_schema`"
  43. rows, err := d.db.QueryContext(ctx, query, d.config.DBName)
  44. if err != nil {
  45. slog.Error("Query db size error, make sure you have enough privilege", err)
  46. return 0, err
  47. }
  48. defer rows.Close()
  49. var size int64
  50. for rows.Next() {
  51. if err := rows.Scan(&size); err != nil {
  52. return 0, err
  53. }
  54. }
  55. if rows.Err() != nil {
  56. return 0, rows.Err()
  57. }
  58. return size, nil
  59. }
  60. func (d *DB) Close() error {
  61. return d.db.Close()
  62. }
  63. func mergeDSN(baseDSN string) (string, error) {
  64. config, err := mysql.ParseDSN(baseDSN)
  65. if err != nil {
  66. return "", errors.Wrapf(err, "failed to parse DSN: %s", baseDSN)
  67. }
  68. config.MultiStatements = true
  69. return config.FormatDSN(), nil
  70. }