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
|
|
|
|
2022-03-17 00:33:59 +00:00
|
|
|
"github.com/stashapp/stash/pkg/fsutil"
|
2019-02-14 23:42:52 +00:00
|
|
|
"github.com/stashapp/stash/pkg/logger"
|
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
|
2022-05-06 01:59:28 +00:00
|
|
|
var appSchemaVersion uint = 31
|
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 {
|
2022-03-17 00:33:59 +00:00
|
|
|
if exists, _ := fsutil.FileExists(wf); exists {
|
2021-01-25 23:37:42 +00:00
|
|
|
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 {
|
Toward better context handling (#1835)
* Use the request context
The code uses context.Background() in a flow where there is a
http.Request. Use the requests context instead.
* Use a true context in the plugin example
Let AddTag/RemoveTag take a context and use that context throughout
the example.
* Avoid the use of context.Background
Prefer context.TODO over context.Background deep in the call chain.
This marks the site as something which we need to context-handle
later, and also makes it clear to the reader that the context is
sort-of temporary in the code base.
While here, be consistent in handling the `act` variable in each
branch of the if .. { .. } .. check.
* Prefer context.TODO over context.Background
For the different scraping operations here, there is a context
higher up the call chain, which we ought to use. Mark the call-sites
as TODO for now, so we can come back later on a sweep of which parts
can be context-lifted.
* Thread context upwards
Initialization requires context for transactions. Thread the context
upward the call chain.
At the intialization call, add a context.TODO since we can't break this
yet. The singleton assumption prevents us from pulling it up into main for
now.
* make tasks context-aware
Change the task interface to understand contexts.
Pass the context down in some of the branches where it is needed.
* Make QueryStashBoxScene context-aware
This call naturally sits inside the request-context. Use it.
* Introduce a context in the JS plugin code
This allows us to use a context for HTTP calls inside the system.
Mark the context with a TODO at top level for now.
* Nitpick error formatting
Use %v rather than %s for error interfaces.
Do not begin an error strong with a capital letter.
* Avoid the use of http.Get in FFMPEG download chain
Since http.Get has no context, it isn't possible to break out or have
policy induced. The call will block until the GET completes. Rewrite
to use a http Request and provide a context.
Thread the context through the call chain for now. provide
context.TODO() at the top level of the initialization chain.
* Make getRemoteCDPWSAddress aware of contexts
Eliminate a call to http.Get and replace it with a context-aware
variant.
Push the context upwards in the call chain, but plug it before the
scraper interface so we don't have to rewrite said interface yet.
Plugged with context.TODO()
* Scraper: make the getImage function context-aware
Use a context, and pass it upwards. Plug it with context.TODO()
up the chain before the rewrite gets too much out of hand for now.
Minor tweaks along the way, remove a call to context.Background()
deep in the call chain.
* Make NOTIFY request context-aware
The call sits inside a Request-handler. So it's natural to use the
requests context as the context for the outgoing HTTP request.
* Use a context in the url scraper code
We are sitting in code which has a context, so utilize it for the
request as well.
* Use a context when checking versions
When we check the version of stash on Github, use a context. Thread
the context up to the initialization routine of the HTTP/GraphQL
server and plug it with a context.TODO() for now.
This paves the way for providing a context to the HTTP server code in a
future patch.
* Make utils func ReadImage context-aware
In almost all of the cases, there is a context in the call chain which
is a natural use. This is true for all the GraphQL mutations.
The exception is in task_stash_box_tag, so plug that task with
context.TODO() for now.
* Make stash-box get context-aware
Thread a context through the call chain until we hit the Client API.
Plug it with context.TODO() there for now.
* Enable the noctx linter
The code is now free of any uncontexted HTTP request. This means we
pass the noctx linter, and we can enable it in the code base.
2021-10-14 04:32:41 +00:00
|
|
|
return fmt.Errorf("open database %s failed: %v", dbPath, err)
|
2021-01-21 11:02:09 +00:00
|
|
|
}
|
|
|
|
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 {
|
Toward better context handling (#1835)
* Use the request context
The code uses context.Background() in a flow where there is a
http.Request. Use the requests context instead.
* Use a true context in the plugin example
Let AddTag/RemoveTag take a context and use that context throughout
the example.
* Avoid the use of context.Background
Prefer context.TODO over context.Background deep in the call chain.
This marks the site as something which we need to context-handle
later, and also makes it clear to the reader that the context is
sort-of temporary in the code base.
While here, be consistent in handling the `act` variable in each
branch of the if .. { .. } .. check.
* Prefer context.TODO over context.Background
For the different scraping operations here, there is a context
higher up the call chain, which we ought to use. Mark the call-sites
as TODO for now, so we can come back later on a sweep of which parts
can be context-lifted.
* Thread context upwards
Initialization requires context for transactions. Thread the context
upward the call chain.
At the intialization call, add a context.TODO since we can't break this
yet. The singleton assumption prevents us from pulling it up into main for
now.
* make tasks context-aware
Change the task interface to understand contexts.
Pass the context down in some of the branches where it is needed.
* Make QueryStashBoxScene context-aware
This call naturally sits inside the request-context. Use it.
* Introduce a context in the JS plugin code
This allows us to use a context for HTTP calls inside the system.
Mark the context with a TODO at top level for now.
* Nitpick error formatting
Use %v rather than %s for error interfaces.
Do not begin an error strong with a capital letter.
* Avoid the use of http.Get in FFMPEG download chain
Since http.Get has no context, it isn't possible to break out or have
policy induced. The call will block until the GET completes. Rewrite
to use a http Request and provide a context.
Thread the context through the call chain for now. provide
context.TODO() at the top level of the initialization chain.
* Make getRemoteCDPWSAddress aware of contexts
Eliminate a call to http.Get and replace it with a context-aware
variant.
Push the context upwards in the call chain, but plug it before the
scraper interface so we don't have to rewrite said interface yet.
Plugged with context.TODO()
* Scraper: make the getImage function context-aware
Use a context, and pass it upwards. Plug it with context.TODO()
up the chain before the rewrite gets too much out of hand for now.
Minor tweaks along the way, remove a call to context.Background()
deep in the call chain.
* Make NOTIFY request context-aware
The call sits inside a Request-handler. So it's natural to use the
requests context as the context for the outgoing HTTP request.
* Use a context in the url scraper code
We are sitting in code which has a context, so utilize it for the
request as well.
* Use a context when checking versions
When we check the version of stash on Github, use a context. Thread
the context up to the initialization routine of the HTTP/GraphQL
server and plug it with a context.TODO() for now.
This paves the way for providing a context to the HTTP server code in a
future patch.
* Make utils func ReadImage context-aware
In almost all of the cases, there is a context in the call chain which
is a natural use. This is true for all the GraphQL mutations.
The exception is in task_stash_box_tag, so plug that task with
context.TODO() for now.
* Make stash-box get context-aware
Thread a context through the call chain until we hit the Client API.
Plug it with context.TODO() there for now.
* Enable the noctx linter
The code is now free of any uncontexted HTTP request. This means we
pass the noctx linter, and we can enable it in the code base.
2021-10-14 04:32:41 +00:00
|
|
|
return fmt.Errorf("vacuum failed: %v", 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
|
|
|
}
|