memos/store/db/mysql/mysql.go

111 lines
2.3 KiB
Go
Raw Normal View History

package mysql
import (
"context"
"database/sql"
2023-09-29 12:47:49 +08:00
"fmt"
"github.com/go-sql-driver/mysql"
"github.com/pkg/errors"
"github.com/usememos/memos/common/log"
"github.com/usememos/memos/server/profile"
"github.com/usememos/memos/store"
)
2023-10-05 23:11:29 +08:00
type DB struct {
db *sql.DB
profile *profile.Profile
config *mysql.Config
}
2023-10-05 23:11:29 +08:00
func NewDB(profile *profile.Profile) (store.Driver, error) {
2023-09-29 12:47:49 +08:00
// Open MySQL connection with parameter.
// multiStatements=true is required for migration.
// See more in: https://github.com/go-sql-driver/mysql#multistatements
dsn := fmt.Sprintf("%s?multiStatements=true", profile.DSN)
var err error
driver := DB{profile: profile}
driver.config, err = mysql.ParseDSN(dsn)
if err != nil {
log.Error(fmt.Sprintf("DSN parse error: %s", dsn))
return nil, errors.New("Parse DSN eroor")
}
driver.db, err = sql.Open("mysql", dsn)
if err != nil {
2023-09-29 09:15:54 +08:00
return nil, errors.Wrapf(err, "failed to open db: %s", profile.DSN)
}
return &driver, nil
}
2023-10-05 23:11:29 +08:00
func (d *DB) GetDB() *sql.DB {
2023-09-29 09:15:54 +08:00
return d.db
}
2023-10-05 23:11:29 +08:00
func (d *DB) Vacuum(ctx context.Context) error {
tx, err := d.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if err := vacuumMemo(ctx, tx); err != nil {
return err
}
if err := vacuumResource(ctx, tx); err != nil {
return err
}
if err := vacuumUserSetting(ctx, tx); err != nil {
return err
}
if err := vacuumMemoOrganizer(ctx, tx); err != nil {
return err
}
if err := vacuumMemoRelations(ctx, tx); err != nil {
return err
}
if err := vacuumTag(ctx, tx); err != nil {
// Prevent revive warning.
return err
}
return tx.Commit()
}
2023-10-05 23:11:29 +08:00
func (*DB) BackupTo(context.Context, string) error {
return errors.New("Please use mysqldump to backup")
}
func (d *DB) GetCurrentDBSize(ctx context.Context) (int64, error) {
query := "SELECT SUM(`data_length` + `index_length`) AS `size` " +
" FROM information_schema.TABLES" +
" WHERE `table_schema` = ?" +
" GROUP BY `table_schema`"
rows, err := d.db.QueryContext(ctx, query, d.config.DBName)
if err != nil {
log.Error("Query db size error, make sure you have enough privilege")
return 0, err
}
defer rows.Close()
var size int64
for rows.Next() {
if err := rows.Scan(&size); err != nil {
return 0, err
}
}
if rows.Err() != nil {
return 0, rows.Err()
}
return size, nil
}
2023-10-05 23:11:29 +08:00
func (d *DB) Close() error {
return d.db.Close()
}