memos/store/db/db.go

273 lines
7.0 KiB
Go
Raw Normal View History

2022-05-21 19:59:22 +03:00
package db
2022-02-03 10:32:03 +03:00
import (
"context"
2022-02-03 10:32:03 +03:00
"database/sql"
"embed"
"errors"
"fmt"
"io/fs"
2022-05-01 06:06:29 +03:00
"os"
"regexp"
2022-02-03 10:32:03 +03:00
"sort"
2022-07-22 18:21:12 +03:00
"time"
2022-02-03 10:32:03 +03:00
2022-06-27 17:09:06 +03:00
"github.com/usememos/memos/common"
"github.com/usememos/memos/server/profile"
2022-02-03 10:32:03 +03:00
_ "github.com/mattn/go-sqlite3"
)
2022-03-28 18:38:12 +03:00
//go:embed migration
var migrationFS embed.FS
2022-02-03 10:32:03 +03:00
//go:embed seed
var seedFS embed.FS
type DB struct {
2022-05-22 04:29:34 +03:00
// sqlite db connection instance
2022-07-22 18:21:12 +03:00
Db *sql.DB
profile *profile.Profile
2022-02-03 10:32:03 +03:00
}
// NewDB returns a new instance of DB associated with the given datasource name.
2022-05-22 04:29:34 +03:00
func NewDB(profile *profile.Profile) *DB {
2022-02-03 10:32:03 +03:00
db := &DB{
2022-07-22 18:21:12 +03:00
profile: profile,
2022-02-03 10:32:03 +03:00
}
return db
}
func (db *DB) Open(ctx context.Context) (err error) {
2022-02-03 10:32:03 +03:00
// Ensure a DSN is set before attempting to open the database.
2022-07-22 18:21:12 +03:00
if db.profile.DSN == "" {
2022-02-03 10:32:03 +03:00
return fmt.Errorf("dsn required")
}
// Connect to the database.
2022-07-22 18:21:12 +03:00
sqlDB, err := sql.Open("sqlite3", db.profile.DSN)
2022-05-01 06:06:29 +03:00
if err != nil {
2022-07-22 18:21:12 +03:00
return fmt.Errorf("failed to open db with dsn: %s, err: %w", db.profile.DSN, err)
2022-02-03 10:32:03 +03:00
}
2022-05-01 06:06:29 +03:00
db.Db = sqlDB
// If mode is dev, we should migrate and seed the database.
2022-07-22 18:21:12 +03:00
if db.profile.Mode == "dev" {
if err := db.applyLatestSchema(ctx); err != nil {
return fmt.Errorf("failed to apply latest schema: %w", err)
2022-03-28 18:38:12 +03:00
}
if err := db.seed(ctx); err != nil {
return fmt.Errorf("failed to seed: %w", err)
2022-02-06 05:37:09 +03:00
}
2022-05-01 06:06:29 +03:00
} else {
// If db file not exists, we should migrate the database.
2022-07-22 18:21:12 +03:00
if _, err := os.Stat(db.profile.DSN); errors.Is(err, os.ErrNotExist) {
err := db.applyLatestSchema(ctx)
if err != nil {
return fmt.Errorf("failed to apply latest schema: %w", err)
}
} else {
err := db.createMigrationHistoryTable(ctx)
if err != nil {
return fmt.Errorf("failed to create migration_history table: %w", err)
}
2022-07-22 18:21:12 +03:00
currentVersion := common.GetCurrentVersion(db.profile.Mode)
migrationHistory, err := db.FindMigrationHistory(ctx, &MigrationHistoryFind{})
if err != nil {
return err
}
if migrationHistory == nil {
migrationHistory, err = db.UpsertMigrationHistory(ctx, &MigrationHistoryUpsert{
Version: currentVersion,
})
if err != nil {
return err
}
2022-05-01 06:06:29 +03:00
}
if common.IsVersionGreaterThan(currentVersion, migrationHistory.Version) {
minorVersionList := getMinorVersionList()
2022-07-22 18:21:12 +03:00
// backup the raw database file before migration
2022-08-24 15:40:56 +03:00
rawBytes, err := os.ReadFile(db.profile.DSN)
2022-07-22 18:21:12 +03:00
if err != nil {
return fmt.Errorf("failed to read raw database file, err: %w", err)
}
backupDBFilePath := fmt.Sprintf("%s/memos_%s_%d_backup.db", db.profile.Data, db.profile.Version, time.Now().Unix())
2022-08-24 15:40:56 +03:00
if err := os.WriteFile(backupDBFilePath, rawBytes, 0644); err != nil {
2022-07-22 18:21:12 +03:00
return fmt.Errorf("failed to write raw database file, err: %w", err)
}
println("succeed to copy a backup database file")
println("start migrate")
for _, minorVersion := range minorVersionList {
normalizedVersion := minorVersion + ".0"
if common.IsVersionGreaterThan(normalizedVersion, migrationHistory.Version) && common.IsVersionGreaterOrEqualThan(currentVersion, normalizedVersion) {
println("applying migration for", normalizedVersion)
if err := db.applyMigrationForMinorVersion(ctx, minorVersion); err != nil {
return fmt.Errorf("failed to apply minor version migration: %w", err)
}
}
}
2022-07-22 18:21:12 +03:00
println("end migrate")
2022-07-22 18:21:12 +03:00
// remove the created backup db file after migrate succeed
if err := os.Remove(backupDBFilePath); err != nil {
println(fmt.Sprintf("Failed to remove temp database file, err %v", err))
}
2022-05-01 06:06:29 +03:00
}
}
2022-02-03 10:32:03 +03:00
}
return err
}
const (
latestSchemaFileName = "LATEST__SCHEMA.sql"
)
func (db *DB) applyLatestSchema(ctx context.Context) error {
2022-07-25 16:17:46 +03:00
latestSchemaPath := fmt.Sprintf("%s/%s/%s", "migration", db.profile.Mode, latestSchemaFileName)
buf, err := migrationFS.ReadFile(latestSchemaPath)
2022-05-21 19:59:22 +03:00
if err != nil {
return fmt.Errorf("failed to read latest schema %q, error %w", latestSchemaPath, err)
2022-05-21 19:59:22 +03:00
}
stmt := string(buf)
if err := db.execute(ctx, stmt); err != nil {
return fmt.Errorf("migrate error: statement:%s err=%w", stmt, err)
}
return nil
}
func (db *DB) applyMigrationForMinorVersion(ctx context.Context, minorVersion string) error {
2022-07-25 16:17:46 +03:00
filenames, err := fs.Glob(migrationFS, fmt.Sprintf("%s/%s/*.sql", "migration/prod", minorVersion))
2022-03-28 18:38:12 +03:00
if err != nil {
return err
}
sort.Strings(filenames)
migrationStmt := ""
2022-03-28 18:38:12 +03:00
// Loop over all migration files and execute them in order.
for _, filename := range filenames {
buf, err := migrationFS.ReadFile(filename)
if err != nil {
return fmt.Errorf("failed to read minor version migration file, filename=%s err=%w", filename, err)
}
stmt := string(buf)
migrationStmt += stmt
if err := db.execute(ctx, stmt); err != nil {
return fmt.Errorf("migrate error: statement:%s err=%w", stmt, err)
2022-03-28 18:38:12 +03:00
}
}
tx, err := db.Db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
// upsert the newest version to migration_history
if _, err = upsertMigrationHistory(ctx, tx, &MigrationHistoryUpsert{
Version: minorVersion + ".0",
}); err != nil {
return err
}
if err := tx.Commit(); err != nil {
return err
}
2022-03-28 18:38:12 +03:00
return nil
}
func (db *DB) seed(ctx context.Context) error {
2022-02-03 10:32:03 +03:00
filenames, err := fs.Glob(seedFS, fmt.Sprintf("%s/*.sql", "seed"))
if err != nil {
return err
}
sort.Strings(filenames)
// Loop over all seed files and execute them in order.
for _, filename := range filenames {
buf, err := seedFS.ReadFile(filename)
if err != nil {
return fmt.Errorf("failed to read seed file, filename=%s err=%w", filename, err)
}
stmt := string(buf)
if err := db.execute(ctx, stmt); err != nil {
return fmt.Errorf("seed error: statement:%s err=%w", stmt, err)
2022-02-03 10:32:03 +03:00
}
}
return nil
}
// excecute runs a single SQL statement within a transaction.
func (db *DB) execute(ctx context.Context, stmt string) error {
2022-02-03 10:32:03 +03:00
tx, err := db.Db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, stmt); err != nil {
return err
}
if err := tx.Commit(); err != nil {
2022-02-03 10:32:03 +03:00
return err
}
return nil
2022-02-03 10:32:03 +03:00
}
// minorDirRegexp is a regular expression for minor version directory.
2022-07-25 16:17:46 +03:00
var minorDirRegexp = regexp.MustCompile(`^migration/prod/[0-9]+\.[0-9]+$`)
func getMinorVersionList() []string {
minorVersionList := []string{}
if err := fs.WalkDir(migrationFS, "migration", func(path string, file fs.DirEntry, err error) error {
if err != nil {
2022-07-01 15:08:25 +03:00
return err
}
if file.IsDir() && minorDirRegexp.MatchString(path) {
minorVersionList = append(minorVersionList, file.Name())
}
2022-02-03 10:32:03 +03:00
return nil
}); err != nil {
panic(err)
2022-07-01 20:06:28 +03:00
}
sort.Strings(minorVersionList)
return minorVersionList
}
// createMigrationHistoryTable creates the migration_history table if it doesn't exist.
func (db *DB) createMigrationHistoryTable(ctx context.Context) error {
tx, err := db.Db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
if err := createTable(ctx, tx, `
CREATE TABLE IF NOT EXISTS migration_history (
version TEXT NOT NULL PRIMARY KEY,
created_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now'))
);
`); err != nil {
return err
}
if err := tx.Commit(); err != nil {
return err
}
2022-05-22 04:29:34 +03:00
return nil
2022-02-03 10:32:03 +03:00
}