2022-05-19 07:49:32 +00:00
|
|
|
package sqlite
|
2019-02-09 12:30:49 +00:00
|
|
|
|
|
|
|
import (
|
2022-07-13 06:30:54 +00:00
|
|
|
"context"
|
2023-07-26 03:54:33 +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"
|
2022-09-30 00:00:50 +00:00
|
|
|
"path/filepath"
|
2020-03-22 21:07:15 +00:00
|
|
|
"time"
|
2019-11-14 18:28:17 +00:00
|
|
|
|
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"
|
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
|
|
|
)
|
|
|
|
|
2023-03-13 02:45:13 +00:00
|
|
|
const (
|
|
|
|
// Number of database connections to use
|
|
|
|
// The same value is used for both the maximum and idle limit,
|
|
|
|
// to prevent opening connections on the fly which has a notieable performance penalty.
|
|
|
|
// Fewer connections use less memory, more connections increase performance,
|
|
|
|
// but have diminishing returns.
|
|
|
|
// 10 was found to be a good tradeoff.
|
|
|
|
dbConns = 10
|
|
|
|
// Idle connection timeout, in seconds
|
|
|
|
// Closes a connection after a period of inactivity, which saves on memory and
|
|
|
|
// causes the sqlite -wal and -shm files to be automatically deleted.
|
|
|
|
dbConnTimeout = 30
|
|
|
|
)
|
|
|
|
|
2023-09-01 00:04:56 +00:00
|
|
|
var appSchemaVersion uint = 49
|
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 (
|
|
|
|
// ErrDatabaseNotInitialized indicates that the database is not
|
|
|
|
// initialized, usually due to an incomplete configuration.
|
|
|
|
ErrDatabaseNotInitialized = errors.New("database not initialized")
|
|
|
|
)
|
|
|
|
|
2022-05-19 07:49:32 +00:00
|
|
|
// ErrMigrationNeeded indicates that a database migration is needed
|
|
|
|
// before the database can be initialized
|
|
|
|
type MigrationNeededError struct {
|
|
|
|
CurrentSchemaVersion uint
|
|
|
|
RequiredSchemaVersion uint
|
|
|
|
}
|
2019-10-30 13:37:21 +00:00
|
|
|
|
2022-05-19 07:49:32 +00:00
|
|
|
func (e *MigrationNeededError) Error() string {
|
|
|
|
return fmt.Sprintf("database schema version %d does not match required schema version %d", e.CurrentSchemaVersion, e.RequiredSchemaVersion)
|
|
|
|
}
|
2021-04-11 23:31:33 +00:00
|
|
|
|
2022-05-19 07:49:32 +00:00
|
|
|
type MismatchedSchemaVersionError struct {
|
|
|
|
CurrentSchemaVersion uint
|
|
|
|
RequiredSchemaVersion uint
|
2021-04-11 23:31:33 +00:00
|
|
|
}
|
|
|
|
|
2022-05-19 07:49:32 +00:00
|
|
|
func (e *MismatchedSchemaVersionError) Error() string {
|
|
|
|
return fmt.Sprintf("schema version %d is incompatible with required schema version %d", e.CurrentSchemaVersion, e.RequiredSchemaVersion)
|
|
|
|
}
|
|
|
|
|
|
|
|
type Database struct {
|
2023-06-15 02:46:09 +00:00
|
|
|
Blobs *BlobStore
|
|
|
|
File *FileStore
|
|
|
|
Folder *FolderStore
|
|
|
|
Image *ImageStore
|
|
|
|
Gallery *GalleryStore
|
|
|
|
GalleryChapter *GalleryChapterStore
|
|
|
|
Scene *SceneStore
|
|
|
|
SceneMarker *SceneMarkerStore
|
|
|
|
Performer *PerformerStore
|
2023-09-01 00:04:56 +00:00
|
|
|
SavedFilter *SavedFilterStore
|
2023-06-15 02:46:09 +00:00
|
|
|
Studio *StudioStore
|
|
|
|
Tag *TagStore
|
|
|
|
Movie *MovieStore
|
2022-07-13 06:30:54 +00:00
|
|
|
|
2022-05-19 07:49:32 +00:00
|
|
|
db *sqlx.DB
|
|
|
|
dbPath string
|
|
|
|
|
|
|
|
schemaVersion uint
|
|
|
|
|
2022-11-20 19:49:10 +00:00
|
|
|
lockChan chan struct{}
|
2022-05-19 07:49:32 +00:00
|
|
|
}
|
|
|
|
|
2022-07-13 06:30:54 +00:00
|
|
|
func NewDatabase() *Database {
|
2022-08-11 06:14:57 +00:00
|
|
|
fileStore := NewFileStore()
|
|
|
|
folderStore := NewFolderStore()
|
2023-03-16 23:52:49 +00:00
|
|
|
blobStore := NewBlobStore(BlobStoreOptions{})
|
2022-08-11 06:14:57 +00:00
|
|
|
|
|
|
|
ret := &Database{
|
2023-06-15 02:46:09 +00:00
|
|
|
Blobs: blobStore,
|
|
|
|
File: fileStore,
|
|
|
|
Folder: folderStore,
|
|
|
|
Scene: NewSceneStore(fileStore, blobStore),
|
|
|
|
SceneMarker: NewSceneMarkerStore(),
|
|
|
|
Image: NewImageStore(fileStore),
|
|
|
|
Gallery: NewGalleryStore(fileStore, folderStore),
|
|
|
|
GalleryChapter: NewGalleryChapterStore(),
|
|
|
|
Performer: NewPerformerStore(blobStore),
|
|
|
|
Studio: NewStudioStore(blobStore),
|
|
|
|
Tag: NewTagStore(blobStore),
|
|
|
|
Movie: NewMovieStore(blobStore),
|
|
|
|
SavedFilter: NewSavedFilterStore(),
|
|
|
|
lockChan: make(chan struct{}, 1),
|
2022-07-13 06:30:54 +00:00
|
|
|
}
|
2022-08-11 06:14:57 +00:00
|
|
|
|
|
|
|
return ret
|
2022-07-13 06:30:54 +00:00
|
|
|
}
|
|
|
|
|
2023-03-16 23:52:49 +00:00
|
|
|
func (db *Database) SetBlobStoreOptions(options BlobStoreOptions) {
|
|
|
|
*db.Blobs = *NewBlobStore(options)
|
|
|
|
}
|
|
|
|
|
2022-05-19 07:49:32 +00:00
|
|
|
// Ready returns an error if the database is not ready to begin transactions.
|
|
|
|
func (db *Database) Ready() error {
|
|
|
|
if db.db == nil {
|
|
|
|
return ErrDatabaseNotInitialized
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Open initializes the database. If the database is new, then it
|
2020-08-06 01:21:14 +00:00
|
|
|
// 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.
|
2022-05-19 07:49:32 +00:00
|
|
|
func (db *Database) Open(dbPath string) error {
|
2022-11-20 19:49:10 +00:00
|
|
|
db.lockNoCtx()
|
|
|
|
defer db.unlock()
|
2022-05-19 07:49:32 +00:00
|
|
|
|
|
|
|
db.dbPath = dbPath
|
2020-03-22 21:07:15 +00:00
|
|
|
|
2022-05-19 07:49:32 +00:00
|
|
|
databaseSchemaVersion, err := db.getDatabaseSchemaVersion()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("getting database schema version: %w", err)
|
2020-03-22 21:07:15 +00:00
|
|
|
}
|
|
|
|
|
2022-05-19 07:49:32 +00:00
|
|
|
db.schemaVersion = databaseSchemaVersion
|
|
|
|
|
2020-03-22 21:07:15 +00:00
|
|
|
if databaseSchemaVersion == 0 {
|
|
|
|
// new database, just run the migrations
|
2022-05-19 07:49:32 +00:00
|
|
|
if err := db.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
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if databaseSchemaVersion > appSchemaVersion {
|
2022-05-19 07:49:32 +00:00
|
|
|
return &MismatchedSchemaVersionError{
|
|
|
|
CurrentSchemaVersion: databaseSchemaVersion,
|
|
|
|
RequiredSchemaVersion: appSchemaVersion,
|
|
|
|
}
|
2020-03-22 21:07:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// if migration is needed, then don't open the connection
|
2022-05-19 07:49:32 +00:00
|
|
|
if db.needsMigration() {
|
|
|
|
return &MigrationNeededError{
|
|
|
|
CurrentSchemaVersion: databaseSchemaVersion,
|
|
|
|
RequiredSchemaVersion: appSchemaVersion,
|
|
|
|
}
|
2020-03-22 21:07:15 +00:00
|
|
|
}
|
|
|
|
}
|
2019-10-30 13:37:21 +00:00
|
|
|
|
2022-05-19 07:49:32 +00:00
|
|
|
// RunMigrations may have opened a connection already
|
|
|
|
if db.db == nil {
|
|
|
|
const disableForeignKeys = false
|
|
|
|
db.db, err = db.open(disableForeignKeys)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2020-08-06 01:21:14 +00:00
|
|
|
|
2021-04-11 23:31:33 +00:00
|
|
|
return nil
|
2020-04-22 01:22:14 +00:00
|
|
|
}
|
|
|
|
|
2022-11-20 19:49:10 +00:00
|
|
|
// lock locks the database for writing.
|
|
|
|
// This method will block until the lock is acquired of the context is cancelled.
|
|
|
|
func (db *Database) lock(ctx context.Context) error {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
|
|
|
case db.lockChan <- struct{}{}:
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// lock locks the database for writing. This method will block until the lock is acquired.
|
|
|
|
func (db *Database) lockNoCtx() {
|
|
|
|
db.lockChan <- struct{}{}
|
|
|
|
}
|
|
|
|
|
|
|
|
// unlock unlocks the database
|
|
|
|
func (db *Database) unlock() {
|
|
|
|
// will block the caller if the lock is not held, so check first
|
|
|
|
select {
|
|
|
|
case <-db.lockChan:
|
|
|
|
return
|
|
|
|
default:
|
|
|
|
panic("database is not locked")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-19 07:49:32 +00:00
|
|
|
func (db *Database) Close() error {
|
2022-11-20 19:49:10 +00:00
|
|
|
db.lockNoCtx()
|
|
|
|
defer db.unlock()
|
2021-09-07 04:28:40 +00:00
|
|
|
|
2022-05-19 07:49:32 +00:00
|
|
|
if db.db != nil {
|
|
|
|
if err := db.db.Close(); err != nil {
|
2021-09-21 11:57:50 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-05-19 07:49:32 +00:00
|
|
|
db.db = nil
|
2021-09-21 11:57:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
2021-09-07 04:28:40 +00:00
|
|
|
}
|
|
|
|
|
2022-05-19 07:49:32 +00:00
|
|
|
func (db *Database) open(disableForeignKeys bool) (*sqlx.DB, error) {
|
2019-02-09 12:30:49 +00:00
|
|
|
// https://github.com/mattn/go-sqlite3
|
2023-03-25 01:37:17 +00:00
|
|
|
url := "file:" + db.dbPath + "?_journal=WAL&_sync=NORMAL&_busy_timeout=50"
|
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)
|
2023-03-13 02:45:13 +00:00
|
|
|
conn.SetMaxOpenConns(dbConns)
|
|
|
|
conn.SetMaxIdleConns(dbConns)
|
|
|
|
conn.SetConnMaxIdleTime(dbConnTimeout * time.Second)
|
2019-02-09 12:30:49 +00:00
|
|
|
if err != nil {
|
2022-05-19 07:49:32 +00:00
|
|
|
return nil, fmt.Errorf("db.Open(): %w", err)
|
2019-02-09 12:30:49 +00:00
|
|
|
}
|
2020-04-22 01:22:14 +00:00
|
|
|
|
2022-05-19 07:49:32 +00:00
|
|
|
return conn, nil
|
2019-02-09 12:30:49 +00:00
|
|
|
}
|
|
|
|
|
2022-12-22 22:15:27 +00:00
|
|
|
func (db *Database) Remove() error {
|
2022-05-19 07:49:32 +00:00
|
|
|
databasePath := db.dbPath
|
|
|
|
err := db.Close()
|
2019-11-17 21:39:33 +00:00
|
|
|
|
|
|
|
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())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-22 22:15:27 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (db *Database) Reset() error {
|
|
|
|
databasePath := db.dbPath
|
|
|
|
if err := db.Remove(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-05-19 07:49:32 +00:00
|
|
|
if err := db.Open(databasePath); err != nil {
|
2021-09-23 07:15:50 +00:00
|
|
|
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.
|
2022-05-19 07:49:32 +00:00
|
|
|
func (db *Database) Backup(backupPath string) error {
|
|
|
|
thisDB := db.db
|
|
|
|
if thisDB == nil {
|
2021-01-21 11:02:09 +00:00
|
|
|
var err error
|
2022-05-19 07:49:32 +00:00
|
|
|
thisDB, err = sqlx.Connect(sqlite3Driver, "file:"+db.dbPath+"?_fk=true")
|
2021-01-21 11:02:09 +00:00
|
|
|
if err != nil {
|
2022-05-19 07:49:32 +00:00
|
|
|
return fmt.Errorf("open database %s failed: %v", db.dbPath, err)
|
2021-01-21 11:02:09 +00:00
|
|
|
}
|
2022-05-19 07:49:32 +00:00
|
|
|
defer thisDB.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)
|
2022-05-19 07:49:32 +00:00
|
|
|
_, err := thisDB.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
|
|
|
|
}
|
|
|
|
|
2022-12-22 22:15:27 +00:00
|
|
|
func (db *Database) Anonymise(outPath string) error {
|
|
|
|
anon, err := NewAnonymiser(db, outPath)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return anon.Anonymise(context.Background())
|
|
|
|
}
|
|
|
|
|
2022-05-19 07:49:32 +00:00
|
|
|
func (db *Database) RestoreFromBackup(backupPath string) error {
|
|
|
|
logger.Infof("Restoring backup database %s into %s", backupPath, db.dbPath)
|
|
|
|
return os.Rename(backupPath, db.dbPath)
|
2020-04-22 01:22:14 +00:00
|
|
|
}
|
|
|
|
|
2019-02-09 12:30:49 +00:00
|
|
|
// Migrate the database
|
2022-05-19 07:49:32 +00:00
|
|
|
func (db *Database) needsMigration() bool {
|
|
|
|
return db.schemaVersion != appSchemaVersion
|
2020-03-22 21:07:15 +00:00
|
|
|
}
|
|
|
|
|
2022-05-19 07:49:32 +00:00
|
|
|
func (db *Database) AppSchemaVersion() uint {
|
2020-03-22 21:07:15 +00:00
|
|
|
return appSchemaVersion
|
|
|
|
}
|
|
|
|
|
2022-05-19 07:49:32 +00:00
|
|
|
func (db *Database) DatabasePath() string {
|
|
|
|
return db.dbPath
|
2021-04-11 23:31:33 +00:00
|
|
|
}
|
|
|
|
|
2022-09-30 00:00:50 +00:00
|
|
|
func (db *Database) DatabaseBackupPath(backupDirectoryPath string) string {
|
2022-09-30 10:57:28 +00:00
|
|
|
fn := fmt.Sprintf("%s.%d.%s", filepath.Base(db.dbPath), db.schemaVersion, time.Now().Format("20060102_150405"))
|
2022-09-30 00:00:50 +00:00
|
|
|
|
|
|
|
if backupDirectoryPath != "" {
|
|
|
|
return filepath.Join(backupDirectoryPath, fn)
|
|
|
|
}
|
|
|
|
|
|
|
|
return fn
|
2020-03-22 21:07:15 +00:00
|
|
|
}
|
|
|
|
|
2022-12-22 22:15:27 +00:00
|
|
|
func (db *Database) AnonymousDatabasePath(backupDirectoryPath string) string {
|
|
|
|
fn := fmt.Sprintf("%s.anonymous.%d.%s", filepath.Base(db.dbPath), db.schemaVersion, time.Now().Format("20060102_150405"))
|
|
|
|
|
|
|
|
if backupDirectoryPath != "" {
|
|
|
|
return filepath.Join(backupDirectoryPath, fn)
|
|
|
|
}
|
|
|
|
|
|
|
|
return fn
|
|
|
|
}
|
|
|
|
|
2022-05-19 07:49:32 +00:00
|
|
|
func (db *Database) Version() uint {
|
|
|
|
return db.schemaVersion
|
2020-03-22 21:07:15 +00:00
|
|
|
}
|
|
|
|
|
2022-05-19 07:49:32 +00:00
|
|
|
func (db *Database) getMigrate() (*migrate.Migrate, error) {
|
2021-09-22 03:08:34 +00:00
|
|
|
migrations, err := iofs.New(migrationsBox, "migrations")
|
|
|
|
if err != nil {
|
2022-07-13 06:30:54 +00:00
|
|
|
return nil, err
|
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
|
2022-05-19 07:49:32 +00:00
|
|
|
conn, err := db.open(disableForeignKeys)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
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,
|
2022-05-19 07:49:32 +00:00
|
|
|
db.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
|
|
|
}
|
|
|
|
|
2022-05-19 07:49:32 +00:00
|
|
|
func (db *Database) getDatabaseSchemaVersion() (uint, error) {
|
|
|
|
m, err := db.getMigrate()
|
2020-03-22 21:07:15 +00:00
|
|
|
if err != nil {
|
2022-05-19 07:49:32 +00:00
|
|
|
return 0, err
|
2020-03-22 21:07:15 +00:00
|
|
|
}
|
2022-05-19 07:49:32 +00:00
|
|
|
defer m.Close()
|
2020-03-22 21:07:15 +00:00
|
|
|
|
2022-05-19 07:49:32 +00:00
|
|
|
ret, _, _ := m.Version()
|
|
|
|
return ret, nil
|
2020-03-22 21:07:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Migrate the database
|
2022-05-19 07:49:32 +00:00
|
|
|
func (db *Database) RunMigrations() error {
|
2022-07-13 06:30:54 +00:00
|
|
|
ctx := context.Background()
|
|
|
|
|
2022-05-19 07:49:32 +00:00
|
|
|
m, err := db.getMigrate()
|
2019-02-09 12:30:49 +00:00
|
|
|
if err != nil {
|
2022-05-19 07:49:32 +00:00
|
|
|
return err
|
2019-02-09 12:30:49 +00:00
|
|
|
}
|
2021-09-20 23:34:25 +00:00
|
|
|
defer m.Close()
|
2019-02-09 12:30:49 +00:00
|
|
|
|
2022-05-19 07:49:32 +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)
|
2022-07-13 06:30:54 +00:00
|
|
|
|
|
|
|
// run each migration individually, and run custom migrations as needed
|
|
|
|
var i uint = 1
|
|
|
|
for ; i <= stepNumber; i++ {
|
|
|
|
newVersion := databaseSchemaVersion + i
|
|
|
|
|
|
|
|
// run pre migrations as needed
|
|
|
|
if err := db.runCustomMigrations(ctx, preMigrations[newVersion]); err != nil {
|
|
|
|
return fmt.Errorf("running pre migrations for schema version %d: %w", newVersion, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
err = m.Steps(1)
|
|
|
|
if err != nil {
|
|
|
|
// migration failed
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// run post migrations as needed
|
|
|
|
if err := db.runCustomMigrations(ctx, postMigrations[newVersion]); err != nil {
|
|
|
|
return fmt.Errorf("running post migrations for schema version %d: %w", newVersion, 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
|
|
|
|
2022-05-19 07:49:32 +00:00
|
|
|
// update the schema version
|
|
|
|
db.schemaVersion, _, _ = m.Version()
|
|
|
|
|
2020-03-22 21:07:15 +00:00
|
|
|
// re-initialise the database
|
2022-05-19 07:49:32 +00:00
|
|
|
const disableForeignKeys = false
|
|
|
|
db.db, err = db.open(disableForeignKeys)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("re-initializing the database: %w", err)
|
2021-09-23 07:15:50 +00:00
|
|
|
}
|
2020-03-22 21:07:15 +00:00
|
|
|
|
2022-09-13 23:15:36 +00:00
|
|
|
// optimize database after migration
|
2023-07-28 01:23:18 +00:00
|
|
|
err = db.Optimise(ctx)
|
|
|
|
if err != nil {
|
|
|
|
logger.Warnf("error while performing post-migration optimisation: %v", err)
|
|
|
|
}
|
2022-12-22 22:15:27 +00:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-07-28 01:23:18 +00:00
|
|
|
func (db *Database) Optimise(ctx context.Context) error {
|
|
|
|
logger.Info("Optimising database")
|
|
|
|
|
|
|
|
err := db.Analyze(ctx)
|
2022-09-13 23:15:36 +00:00
|
|
|
if err != nil {
|
2023-07-28 01:23:18 +00:00
|
|
|
return fmt.Errorf("performing optimization: %w", err)
|
2022-09-13 23:15:36 +00:00
|
|
|
}
|
2023-07-28 01:23:18 +00:00
|
|
|
|
|
|
|
err = db.Vacuum(ctx)
|
2020-06-22 23:19:19 +00:00
|
|
|
if err != nil {
|
2023-07-28 01:23:18 +00:00
|
|
|
return fmt.Errorf("performing vacuum: %w", err)
|
2020-06-22 23:19:19 +00:00
|
|
|
}
|
2023-07-28 01:23:18 +00:00
|
|
|
|
|
|
|
return nil
|
2019-02-14 22:53:32 +00:00
|
|
|
}
|
2019-10-30 13:37:21 +00:00
|
|
|
|
2023-03-16 23:52:49 +00:00
|
|
|
// Vacuum runs a VACUUM on the database, rebuilding the database file into a minimal amount of disk space.
|
|
|
|
func (db *Database) Vacuum(ctx context.Context) error {
|
|
|
|
_, err := db.db.ExecContext(ctx, "VACUUM")
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-07-28 01:23:18 +00:00
|
|
|
// Analyze runs an ANALYZE on the database to improve query performance.
|
|
|
|
func (db *Database) Analyze(ctx context.Context) error {
|
|
|
|
_, err := db.db.ExecContext(ctx, "ANALYZE")
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-07-26 03:54:33 +00:00
|
|
|
func (db *Database) ExecSQL(ctx context.Context, query string, args []interface{}) (*int64, *int64, error) {
|
|
|
|
wrapper := dbWrapper{}
|
|
|
|
|
|
|
|
result, err := wrapper.Exec(ctx, query, args...)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
var rowsAffected *int64
|
|
|
|
ra, err := result.RowsAffected()
|
|
|
|
if err == nil {
|
|
|
|
rowsAffected = &ra
|
|
|
|
}
|
|
|
|
|
|
|
|
var lastInsertId *int64
|
|
|
|
li, err := result.LastInsertId()
|
|
|
|
if err == nil {
|
|
|
|
lastInsertId = &li
|
|
|
|
}
|
|
|
|
|
|
|
|
return rowsAffected, lastInsertId, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (db *Database) QuerySQL(ctx context.Context, query string, args []interface{}) ([]string, [][]interface{}, error) {
|
|
|
|
wrapper := dbWrapper{}
|
|
|
|
|
|
|
|
rows, err := wrapper.QueryxContext(ctx, query, args...)
|
|
|
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
defer rows.Close()
|
|
|
|
|
|
|
|
cols, err := rows.Columns()
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
var ret [][]interface{}
|
|
|
|
|
|
|
|
for rows.Next() {
|
|
|
|
row, err := rows.SliceScan()
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
ret = append(ret, row)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := rows.Err(); err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return cols, ret, nil
|
|
|
|
}
|
|
|
|
|
2022-07-13 06:30:54 +00:00
|
|
|
func (db *Database) runCustomMigrations(ctx context.Context, fns []customMigrationFunc) error {
|
|
|
|
for _, fn := range fns {
|
|
|
|
if err := db.runCustomMigration(ctx, fn); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (db *Database) runCustomMigration(ctx context.Context, fn customMigrationFunc) error {
|
|
|
|
const disableForeignKeys = false
|
|
|
|
d, err := db.open(disableForeignKeys)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
defer d.Close()
|
|
|
|
if err := fn(ctx, d); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|