2019-02-09 12:30:49 +00:00
|
|
|
package database
|
|
|
|
|
|
|
|
import (
|
2019-10-30 13:37:21 +00:00
|
|
|
"database/sql"
|
2021-09-22 03:08:34 +00:00
|
|
|
"embed"
|
2019-11-17 21:39:33 +00:00
|
|
|
"errors"
|
2019-02-09 12:30:49 +00:00
|
|
|
"fmt"
|
2019-11-14 18:28:17 +00:00
|
|
|
"os"
|
2021-03-18 10:45:01 +00:00
|
|
|
"sync"
|
2020-03-22 21:07:15 +00:00
|
|
|
"time"
|
2019-11-14 18:28:17 +00:00
|
|
|
|
2020-11-25 09:09:07 +00:00
|
|
|
"github.com/fvbommel/sortorder"
|
2019-02-09 12:30:49 +00:00
|
|
|
"github.com/golang-migrate/migrate/v4"
|
2020-04-22 01:22:14 +00:00
|
|
|
sqlite3mig "github.com/golang-migrate/migrate/v4/database/sqlite3"
|
2021-09-22 03:08:34 +00:00
|
|
|
"github.com/golang-migrate/migrate/v4/source/iofs"
|
2019-02-09 12:30:49 +00:00
|
|
|
"github.com/jmoiron/sqlx"
|
2019-10-30 13:37:21 +00:00
|
|
|
sqlite3 "github.com/mattn/go-sqlite3"
|
2021-01-25 23:37:42 +00:00
|
|
|
|
2019-02-14 23:42:52 +00:00
|
|
|
"github.com/stashapp/stash/pkg/logger"
|
|
|
|
"github.com/stashapp/stash/pkg/utils"
|
2019-02-09 12:30:49 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var DB *sqlx.DB
|
2021-09-21 11:57:50 +00:00
|
|
|
var WriteMu sync.Mutex
|
2020-03-22 21:07:15 +00:00
|
|
|
var dbPath string
|
2021-09-21 01:48:52 +00:00
|
|
|
var appSchemaVersion uint = 28
|
2020-03-22 21:07:15 +00:00
|
|
|
var databaseSchemaVersion uint
|
2019-02-09 12:30:49 +00:00
|
|
|
|
2021-09-22 03:08:34 +00:00
|
|
|
//go:embed migrations/*.sql
|
|
|
|
var migrationsBox embed.FS
|
|
|
|
|
2021-04-11 23:31:33 +00:00
|
|
|
var (
|
|
|
|
// ErrMigrationNeeded indicates that a database migration is needed
|
|
|
|
// before the database can be initialized
|
|
|
|
ErrMigrationNeeded = errors.New("database migration required")
|
|
|
|
|
|
|
|
// ErrDatabaseNotInitialized indicates that the database is not
|
|
|
|
// initialized, usually due to an incomplete configuration.
|
|
|
|
ErrDatabaseNotInitialized = errors.New("database not initialized")
|
|
|
|
)
|
|
|
|
|
2020-04-22 01:22:14 +00:00
|
|
|
const sqlite3Driver = "sqlite3ex"
|
2019-10-30 13:37:21 +00:00
|
|
|
|
2021-04-11 23:31:33 +00:00
|
|
|
// Ready returns an error if the database is not ready to begin transactions.
|
|
|
|
func Ready() error {
|
|
|
|
if DB == nil {
|
|
|
|
return ErrDatabaseNotInitialized
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-11-14 18:28:17 +00:00
|
|
|
func init() {
|
2019-10-30 13:37:21 +00:00
|
|
|
// register custom driver with regexp function
|
2020-04-22 01:22:14 +00:00
|
|
|
registerCustomDriver()
|
2019-11-14 18:28:17 +00:00
|
|
|
}
|
|
|
|
|
2020-08-06 01:21:14 +00:00
|
|
|
// Initialize initializes the database. If the database is new, then it
|
|
|
|
// performs a full migration to the latest schema version. Otherwise, any
|
|
|
|
// necessary migrations must be run separately using RunMigrations.
|
|
|
|
// Returns true if the database is new.
|
2021-04-11 23:31:33 +00:00
|
|
|
func Initialize(databasePath string) error {
|
2020-03-22 21:07:15 +00:00
|
|
|
dbPath = databasePath
|
|
|
|
|
|
|
|
if err := getDatabaseSchemaVersion(); err != nil {
|
Errorlint sweep + minor linter tweaks (#1796)
* Replace error assertions with Go 1.13 style
Use `errors.As(..)` over type assertions. This enables better use of
wrapped errors in the future, and lets us pass some errorlint checks
in the process.
The rewrite is entirely mechanical, and uses a standard idiom for
doing so.
* Use Go 1.13's errors.Is(..)
Rather than directly checking for error equality, use errors.Is(..).
This protects against error wrapping issues in the future.
Even though something like sql.ErrNoRows doesn't need the wrapping, do
so anyway, for the sake of consistency throughout the code base.
The change almost lets us pass the `errorlint` Go checker except for
a missing case in `js.go` which is to be handled separately; it isn't
mechanical, like these changes are.
* Remove goconst
goconst isn't a useful linter in many cases, because it's false positive
rate is high. It's 100% for the current code base.
* Avoid direct comparison of errors in recover()
Assert that we are catching an error from recover(). If we are,
check that the error caught matches errStop.
* Enable the "errorlint" checker
Configure the checker to avoid checking for errorf wraps. These are
often false positives since the suggestion is to blanket wrap errors
with %w, and that exposes the underlying API which you might not want
to do.
The other warnings are good however, and with the current patch stack,
the code base passes all these checks as well.
* Configure rowserrcheck
The project uses sqlx. Configure rowserrcheck to include said package.
* Mechanically rewrite a large set of errors
Mechanically search for errors that look like
fmt.Errorf("...%s", err.Error())
and rewrite those into
fmt.Errorf("...%v", err)
The `fmt` package is error-aware and knows how to call err.Error()
itself.
The rationale is that this is more idiomatic Go; it paves the
way for using error wrapping later with %w in some sites.
This patch only addresses the entirely mechanical rewriting caught by
a project-side search/replace. There are more individual sites not
addressed by this patch.
2021-10-12 03:03:08 +00:00
|
|
|
return fmt.Errorf("error getting database schema version: %v", err)
|
2020-03-22 21:07:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if databaseSchemaVersion == 0 {
|
|
|
|
// new database, just run the migrations
|
|
|
|
if err := RunMigrations(); err != nil {
|
Errorlint sweep + minor linter tweaks (#1796)
* Replace error assertions with Go 1.13 style
Use `errors.As(..)` over type assertions. This enables better use of
wrapped errors in the future, and lets us pass some errorlint checks
in the process.
The rewrite is entirely mechanical, and uses a standard idiom for
doing so.
* Use Go 1.13's errors.Is(..)
Rather than directly checking for error equality, use errors.Is(..).
This protects against error wrapping issues in the future.
Even though something like sql.ErrNoRows doesn't need the wrapping, do
so anyway, for the sake of consistency throughout the code base.
The change almost lets us pass the `errorlint` Go checker except for
a missing case in `js.go` which is to be handled separately; it isn't
mechanical, like these changes are.
* Remove goconst
goconst isn't a useful linter in many cases, because it's false positive
rate is high. It's 100% for the current code base.
* Avoid direct comparison of errors in recover()
Assert that we are catching an error from recover(). If we are,
check that the error caught matches errStop.
* Enable the "errorlint" checker
Configure the checker to avoid checking for errorf wraps. These are
often false positives since the suggestion is to blanket wrap errors
with %w, and that exposes the underlying API which you might not want
to do.
The other warnings are good however, and with the current patch stack,
the code base passes all these checks as well.
* Configure rowserrcheck
The project uses sqlx. Configure rowserrcheck to include said package.
* Mechanically rewrite a large set of errors
Mechanically search for errors that look like
fmt.Errorf("...%s", err.Error())
and rewrite those into
fmt.Errorf("...%v", err)
The `fmt` package is error-aware and knows how to call err.Error()
itself.
The rationale is that this is more idiomatic Go; it paves the
way for using error wrapping later with %w in some sites.
This patch only addresses the entirely mechanical rewriting caught by
a project-side search/replace. There are more individual sites not
addressed by this patch.
2021-10-12 03:03:08 +00:00
|
|
|
return fmt.Errorf("error running initial schema migrations: %v", err)
|
2020-03-22 21:07:15 +00:00
|
|
|
}
|
|
|
|
// RunMigrations calls Initialise. Just return
|
2021-04-11 23:31:33 +00:00
|
|
|
return nil
|
2020-03-22 21:07:15 +00:00
|
|
|
} else {
|
|
|
|
if databaseSchemaVersion > appSchemaVersion {
|
|
|
|
panic(fmt.Sprintf("Database schema version %d is incompatible with required schema version %d", databaseSchemaVersion, appSchemaVersion))
|
|
|
|
}
|
|
|
|
|
|
|
|
// if migration is needed, then don't open the connection
|
|
|
|
if NeedsMigration() {
|
|
|
|
logger.Warnf("Database schema version %d does not match required schema version %d.", databaseSchemaVersion, appSchemaVersion)
|
2021-04-11 23:31:33 +00:00
|
|
|
return nil
|
2020-03-22 21:07:15 +00:00
|
|
|
}
|
|
|
|
}
|
2019-10-30 13:37:21 +00:00
|
|
|
|
2020-04-22 01:22:14 +00:00
|
|
|
const disableForeignKeys = false
|
|
|
|
DB = open(databasePath, disableForeignKeys)
|
2020-08-06 01:21:14 +00:00
|
|
|
|
2021-09-21 01:48:52 +00:00
|
|
|
if err := runCustomMigrations(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-04-11 23:31:33 +00:00
|
|
|
return nil
|
2020-04-22 01:22:14 +00:00
|
|
|
}
|
|
|
|
|
2021-09-07 04:28:40 +00:00
|
|
|
func Close() error {
|
|
|
|
WriteMu.Lock()
|
|
|
|
defer WriteMu.Unlock()
|
|
|
|
|
2021-09-21 11:57:50 +00:00
|
|
|
if DB != nil {
|
|
|
|
if err := DB.Close(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
DB = nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
2021-09-07 04:28:40 +00:00
|
|
|
}
|
|
|
|
|
2020-04-22 01:22:14 +00:00
|
|
|
func open(databasePath string, disableForeignKeys bool) *sqlx.DB {
|
2019-02-09 12:30:49 +00:00
|
|
|
// https://github.com/mattn/go-sqlite3
|
2021-09-21 01:38:56 +00:00
|
|
|
url := "file:" + databasePath + "?_journal=WAL&_sync=NORMAL"
|
2020-04-22 01:22:14 +00:00
|
|
|
if !disableForeignKeys {
|
2021-01-18 01:23:20 +00:00
|
|
|
url += "&_fk=true"
|
2020-04-22 01:22:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
conn, err := sqlx.Open(sqlite3Driver, url)
|
2019-02-10 20:47:34 +00:00
|
|
|
conn.SetMaxOpenConns(25)
|
|
|
|
conn.SetMaxIdleConns(4)
|
2021-03-18 10:45:01 +00:00
|
|
|
conn.SetConnMaxLifetime(30 * time.Second)
|
2019-02-09 12:30:49 +00:00
|
|
|
if err != nil {
|
|
|
|
logger.Fatalf("db.Open(): %q\n", err)
|
|
|
|
}
|
2020-04-22 01:22:14 +00:00
|
|
|
|
|
|
|
return conn
|
2019-02-09 12:30:49 +00:00
|
|
|
}
|
|
|
|
|
2019-11-17 21:39:33 +00:00
|
|
|
func Reset(databasePath string) error {
|
|
|
|
err := DB.Close()
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return errors.New("Error closing database: " + err.Error())
|
|
|
|
}
|
|
|
|
|
|
|
|
err = os.Remove(databasePath)
|
|
|
|
if err != nil {
|
|
|
|
return errors.New("Error removing database: " + err.Error())
|
|
|
|
}
|
|
|
|
|
2021-01-25 23:37:42 +00:00
|
|
|
// remove the -shm, -wal files ( if they exist )
|
|
|
|
walFiles := []string{databasePath + "-shm", databasePath + "-wal"}
|
|
|
|
for _, wf := range walFiles {
|
|
|
|
if exists, _ := utils.FileExists(wf); exists {
|
|
|
|
err = os.Remove(wf)
|
|
|
|
if err != nil {
|
|
|
|
return errors.New("Error removing database: " + err.Error())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-23 07:15:50 +00:00
|
|
|
if err := Initialize(databasePath); err != nil {
|
|
|
|
return fmt.Errorf("[reset DB] unable to initialize: %w", err)
|
|
|
|
}
|
|
|
|
|
2019-11-17 21:39:33 +00:00
|
|
|
return nil
|
2019-02-09 12:30:49 +00:00
|
|
|
}
|
|
|
|
|
2021-01-21 11:02:09 +00:00
|
|
|
// Backup the database. If db is nil, then uses the existing database
|
|
|
|
// connection.
|
|
|
|
func Backup(db *sqlx.DB, backupPath string) error {
|
|
|
|
if db == nil {
|
|
|
|
var err error
|
|
|
|
db, err = sqlx.Connect(sqlite3Driver, "file:"+dbPath+"?_fk=true")
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Open database %s failed:%s", dbPath, err)
|
|
|
|
}
|
|
|
|
defer db.Close()
|
2020-03-22 21:07:15 +00:00
|
|
|
}
|
|
|
|
|
2020-06-22 23:19:19 +00:00
|
|
|
logger.Infof("Backing up database into: %s", backupPath)
|
2021-01-21 11:02:09 +00:00
|
|
|
_, err := db.Exec(`VACUUM INTO "` + backupPath + `"`)
|
2020-03-22 21:07:15 +00:00
|
|
|
if err != nil {
|
2021-09-08 01:23:10 +00:00
|
|
|
return fmt.Errorf("vacuum failed: %s", err)
|
2020-03-22 21:07:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-04-22 01:22:14 +00:00
|
|
|
func RestoreFromBackup(backupPath string) error {
|
2020-06-22 23:19:19 +00:00
|
|
|
logger.Infof("Restoring backup database %s into %s", backupPath, dbPath)
|
2020-04-22 01:22:14 +00:00
|
|
|
return os.Rename(backupPath, dbPath)
|
|
|
|
}
|
|
|
|
|
2019-02-09 12:30:49 +00:00
|
|
|
// Migrate the database
|
2020-03-22 21:07:15 +00:00
|
|
|
func NeedsMigration() bool {
|
|
|
|
return databaseSchemaVersion != appSchemaVersion
|
|
|
|
}
|
|
|
|
|
|
|
|
func AppSchemaVersion() uint {
|
|
|
|
return appSchemaVersion
|
|
|
|
}
|
|
|
|
|
2021-04-11 23:31:33 +00:00
|
|
|
func DatabasePath() string {
|
|
|
|
return dbPath
|
|
|
|
}
|
|
|
|
|
2020-03-22 21:07:15 +00:00
|
|
|
func DatabaseBackupPath() string {
|
|
|
|
return fmt.Sprintf("%s.%d.%s", dbPath, databaseSchemaVersion, time.Now().Format("20060102_150405"))
|
|
|
|
}
|
|
|
|
|
|
|
|
func Version() uint {
|
|
|
|
return databaseSchemaVersion
|
|
|
|
}
|
|
|
|
|
|
|
|
func getMigrate() (*migrate.Migrate, error) {
|
2021-09-22 03:08:34 +00:00
|
|
|
migrations, err := iofs.New(migrationsBox, "migrations")
|
|
|
|
if err != nil {
|
|
|
|
panic(err.Error())
|
2019-02-09 12:30:49 +00:00
|
|
|
}
|
2019-02-10 00:50:06 +00:00
|
|
|
|
2020-04-22 01:22:14 +00:00
|
|
|
const disableForeignKeys = true
|
2021-09-22 03:08:34 +00:00
|
|
|
conn := open(dbPath, disableForeignKeys)
|
2020-04-22 01:22:14 +00:00
|
|
|
|
|
|
|
driver, err := sqlite3mig.WithInstance(conn.DB, &sqlite3mig.Config{})
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// use sqlite3Driver so that migration has access to durationToTinyInt
|
|
|
|
return migrate.NewWithInstance(
|
2021-09-22 03:08:34 +00:00
|
|
|
"iofs",
|
|
|
|
migrations,
|
|
|
|
dbPath,
|
2020-04-22 01:22:14 +00:00
|
|
|
driver,
|
2019-02-09 12:30:49 +00:00
|
|
|
)
|
2020-03-22 21:07:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func getDatabaseSchemaVersion() error {
|
|
|
|
m, err := getMigrate()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
databaseSchemaVersion, _, _ = m.Version()
|
|
|
|
m.Close()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Migrate the database
|
|
|
|
func RunMigrations() error {
|
|
|
|
m, err := getMigrate()
|
2019-02-09 12:30:49 +00:00
|
|
|
if err != nil {
|
|
|
|
panic(err.Error())
|
|
|
|
}
|
2021-09-20 23:34:25 +00:00
|
|
|
defer m.Close()
|
2019-02-09 12:30:49 +00:00
|
|
|
|
2020-03-22 21:07:15 +00:00
|
|
|
databaseSchemaVersion, _, _ = m.Version()
|
2019-02-10 00:50:06 +00:00
|
|
|
stepNumber := appSchemaVersion - databaseSchemaVersion
|
|
|
|
if stepNumber != 0 {
|
2020-06-22 23:19:19 +00:00
|
|
|
logger.Infof("Migrating database from version %d to %d", databaseSchemaVersion, appSchemaVersion)
|
2019-02-10 00:50:06 +00:00
|
|
|
err = m.Steps(int(stepNumber))
|
|
|
|
if err != nil {
|
2020-04-22 01:22:14 +00:00
|
|
|
// migration failed
|
2020-03-22 21:07:15 +00:00
|
|
|
return err
|
2019-02-10 00:50:06 +00:00
|
|
|
}
|
2019-02-09 12:30:49 +00:00
|
|
|
}
|
2020-06-22 23:19:19 +00:00
|
|
|
|
2020-03-22 21:07:15 +00:00
|
|
|
// re-initialise the database
|
2021-09-23 07:15:50 +00:00
|
|
|
if err = Initialize(dbPath); err != nil {
|
|
|
|
logger.Warnf("Error re-initializing the database: %v", err)
|
|
|
|
}
|
2020-03-22 21:07:15 +00:00
|
|
|
|
2020-06-22 23:19:19 +00:00
|
|
|
// run a vacuum on the database
|
|
|
|
logger.Info("Performing vacuum on database")
|
|
|
|
_, err = DB.Exec("VACUUM")
|
|
|
|
if err != nil {
|
2021-09-20 23:34:25 +00:00
|
|
|
logger.Warnf("error while performing post-migration vacuum: %v", err)
|
2020-06-22 23:19:19 +00:00
|
|
|
}
|
|
|
|
|
2020-03-22 21:07:15 +00:00
|
|
|
return nil
|
2019-02-14 22:53:32 +00:00
|
|
|
}
|
2019-10-30 13:37:21 +00:00
|
|
|
|
2020-04-22 01:22:14 +00:00
|
|
|
func registerCustomDriver() {
|
2019-10-30 13:37:21 +00:00
|
|
|
sql.Register(sqlite3Driver,
|
|
|
|
&sqlite3.SQLiteDriver{
|
|
|
|
ConnectHook: func(conn *sqlite3.SQLiteConn) error {
|
2020-04-22 01:22:14 +00:00
|
|
|
funcs := map[string]interface{}{
|
|
|
|
"regexp": regexFn,
|
|
|
|
"durationToTinyInt": durationToTinyIntFn,
|
|
|
|
}
|
|
|
|
|
|
|
|
for name, fn := range funcs {
|
|
|
|
if err := conn.RegisterFunc(name, fn, true); err != nil {
|
2021-09-08 01:23:10 +00:00
|
|
|
return fmt.Errorf("error registering function %s: %s", name, err.Error())
|
2020-04-22 01:22:14 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-25 09:09:07 +00:00
|
|
|
// COLLATE NATURAL_CS - Case sensitive natural sort
|
|
|
|
err := conn.RegisterCollation("NATURAL_CS", func(s string, s2 string) int {
|
|
|
|
if sortorder.NaturalLess(s, s2) {
|
|
|
|
return -1
|
|
|
|
} else {
|
|
|
|
return 1
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
Errorlint sweep + minor linter tweaks (#1796)
* Replace error assertions with Go 1.13 style
Use `errors.As(..)` over type assertions. This enables better use of
wrapped errors in the future, and lets us pass some errorlint checks
in the process.
The rewrite is entirely mechanical, and uses a standard idiom for
doing so.
* Use Go 1.13's errors.Is(..)
Rather than directly checking for error equality, use errors.Is(..).
This protects against error wrapping issues in the future.
Even though something like sql.ErrNoRows doesn't need the wrapping, do
so anyway, for the sake of consistency throughout the code base.
The change almost lets us pass the `errorlint` Go checker except for
a missing case in `js.go` which is to be handled separately; it isn't
mechanical, like these changes are.
* Remove goconst
goconst isn't a useful linter in many cases, because it's false positive
rate is high. It's 100% for the current code base.
* Avoid direct comparison of errors in recover()
Assert that we are catching an error from recover(). If we are,
check that the error caught matches errStop.
* Enable the "errorlint" checker
Configure the checker to avoid checking for errorf wraps. These are
often false positives since the suggestion is to blanket wrap errors
with %w, and that exposes the underlying API which you might not want
to do.
The other warnings are good however, and with the current patch stack,
the code base passes all these checks as well.
* Configure rowserrcheck
The project uses sqlx. Configure rowserrcheck to include said package.
* Mechanically rewrite a large set of errors
Mechanically search for errors that look like
fmt.Errorf("...%s", err.Error())
and rewrite those into
fmt.Errorf("...%v", err)
The `fmt` package is error-aware and knows how to call err.Error()
itself.
The rationale is that this is more idiomatic Go; it paves the
way for using error wrapping later with %w in some sites.
This patch only addresses the entirely mechanical rewriting caught by
a project-side search/replace. There are more individual sites not
addressed by this patch.
2021-10-12 03:03:08 +00:00
|
|
|
return fmt.Errorf("error registering natural sort collation: %v", err)
|
2020-11-25 09:09:07 +00:00
|
|
|
}
|
|
|
|
|
2020-04-22 01:22:14 +00:00
|
|
|
return nil
|
2019-10-30 13:37:21 +00:00
|
|
|
},
|
2020-04-22 01:22:14 +00:00
|
|
|
},
|
|
|
|
)
|
2019-10-30 13:37:21 +00:00
|
|
|
}
|