memos/store/db/db.go

168 lines
3.6 KiB
Go
Raw Normal View History

2022-05-22 00:59:22 +08:00
package db
2022-02-03 15:32:03 +08:00
import (
"database/sql"
"embed"
"errors"
"fmt"
"io/fs"
2022-03-29 20:53:43 +08:00
"memos/common"
2022-05-22 09:29:34 +08:00
"memos/server/profile"
2022-05-01 11:06:29 +08:00
"os"
2022-02-03 15:32:03 +08:00
"sort"
_ "github.com/mattn/go-sqlite3"
)
2022-03-28 23:38:12 +08:00
//go:embed migration
var migrationFS embed.FS
2022-02-03 15:32:03 +08:00
//go:embed seed
var seedFS embed.FS
type DB struct {
2022-05-22 09:29:34 +08:00
// sqlite db connection instance
2022-02-03 15:32:03 +08:00
Db *sql.DB
2022-02-06 10:37:09 +08:00
// datasource name
2022-02-03 15:32:03 +08:00
DSN string
2022-05-02 09:40:25 +08:00
// mode should be prod or dev
2022-02-06 10:37:09 +08:00
mode string
2022-02-03 15:32:03 +08:00
}
// NewDB returns a new instance of DB associated with the given datasource name.
2022-05-22 09:29:34 +08:00
func NewDB(profile *profile.Profile) *DB {
2022-02-03 15:32:03 +08:00
db := &DB{
2022-03-29 20:53:43 +08:00
DSN: profile.DSN,
mode: profile.Mode,
2022-02-03 15:32:03 +08:00
}
return db
}
func (db *DB) Open() (err error) {
// Ensure a DSN is set before attempting to open the database.
if db.DSN == "" {
return fmt.Errorf("dsn required")
}
// Connect to the database.
2022-05-01 11:06:29 +08:00
sqlDB, err := sql.Open("sqlite3", db.DSN)
if err != nil {
2022-02-06 10:37:09 +08:00
return fmt.Errorf("failed to open db with dsn: %s, err: %w", db.DSN, err)
2022-02-03 15:32:03 +08:00
}
2022-05-01 11:06:29 +08:00
db.Db = sqlDB
// If db file not exists, we should migrate and seed the database.
if _, err := os.Stat(db.DSN); errors.Is(err, os.ErrNotExist) {
2022-03-28 23:38:12 +08:00
if err := db.migrate(); err != nil {
return fmt.Errorf("failed to migrate: %w", err)
}
2022-05-19 22:29:27 +08:00
// If mode is dev, then seed the database.
if db.mode == "dev" {
if err := db.seed(); err != nil {
return fmt.Errorf("failed to seed: %w", err)
}
2022-02-06 10:37:09 +08:00
}
2022-05-01 11:06:29 +08:00
} else {
// If db file exists and mode is dev, we should migrate and seed the database.
if db.mode == "dev" {
if err := db.migrate(); err != nil {
return fmt.Errorf("failed to migrate: %w", err)
}
if err := db.seed(); err != nil {
return fmt.Errorf("failed to seed: %w", err)
}
}
2022-02-03 15:32:03 +08:00
}
return err
}
2022-03-28 23:38:12 +08:00
func (db *DB) migrate() error {
2022-05-22 09:29:34 +08:00
err := db.compareMigrationHistory()
2022-05-22 00:59:22 +08:00
if err != nil {
2022-05-22 09:29:34 +08:00
return fmt.Errorf("failed to compare migration history, err=%w", err)
2022-05-22 00:59:22 +08:00
}
2022-03-28 23:38:12 +08:00
filenames, err := fs.Glob(migrationFS, fmt.Sprintf("%s/*.sql", "migration"))
if err != nil {
return err
}
sort.Strings(filenames)
// Loop over all migration files and execute them in order.
for _, filename := range filenames {
if err := db.executeFile(migrationFS, filename); err != nil {
return fmt.Errorf("migrate error: name=%q err=%w", filename, err)
}
}
return nil
}
2022-02-03 15:32:03 +08:00
func (db *DB) seed() error {
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 {
2022-03-28 23:38:12 +08:00
if err := db.executeFile(seedFS, filename); err != nil {
2022-02-03 15:32:03 +08:00
return fmt.Errorf("seed error: name=%q err=%w", filename, err)
}
}
return nil
}
2022-03-28 23:38:12 +08:00
// executeFile runs a single seed file within a transaction.
func (db *DB) executeFile(FS embed.FS, name string) error {
2022-02-03 15:32:03 +08:00
tx, err := db.Db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
2022-03-28 23:38:12 +08:00
// Read and execute SQL file.
if buf, err := fs.ReadFile(FS, name); err != nil {
2022-02-03 15:32:03 +08:00
return err
} else if _, err := tx.Exec(string(buf)); err != nil {
return err
}
return tx.Commit()
}
2022-05-22 09:29:34 +08:00
// compareMigrationHistory compares migration history data
func (db *DB) compareMigrationHistory() error {
table, err := findTable(db, "migration_history")
if err != nil {
return err
}
if table == nil {
createTable(db, `
CREATE TABLE migration_history (
version TEXT NOT NULL PRIMARY KEY,
created_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now'))
);
`)
2022-02-03 15:32:03 +08:00
}
2022-05-22 09:29:34 +08:00
migrationHistoryList, err := findMigrationHistoryList(db)
if err != nil {
2022-02-03 15:32:03 +08:00
return err
}
2022-05-22 09:29:34 +08:00
if len(migrationHistoryList) == 0 {
createMigrationHistory(db, common.Version)
} else {
migrationHistory := migrationHistoryList[0]
if migrationHistory.Version != common.Version {
createMigrationHistory(db, common.Version)
}
}
return nil
2022-02-03 15:32:03 +08:00
}