2021-11-21 14:05:07 +01:00
|
|
|
package entity
|
|
|
|
|
2022-01-05 18:15:39 +01:00
|
|
|
import (
|
2022-03-29 00:21:50 +02:00
|
|
|
"os"
|
2022-01-05 18:15:39 +01:00
|
|
|
"time"
|
2022-03-29 00:21:50 +02:00
|
|
|
|
|
|
|
"github.com/photoprism/photoprism/pkg/sanitize"
|
2022-01-05 18:15:39 +01:00
|
|
|
)
|
|
|
|
|
2021-11-21 14:05:07 +01:00
|
|
|
// MigrateDb creates database tables and inserts default fixtures as needed.
|
2021-11-28 13:52:27 +01:00
|
|
|
func MigrateDb(dropDeprecated, runFailed bool) {
|
2022-01-05 18:15:39 +01:00
|
|
|
start := time.Now()
|
|
|
|
|
2021-11-21 14:05:07 +01:00
|
|
|
if dropDeprecated {
|
2021-11-28 13:52:27 +01:00
|
|
|
DeprecatedTables.Drop(Db())
|
2021-11-21 14:05:07 +01:00
|
|
|
}
|
|
|
|
|
2021-11-28 13:52:27 +01:00
|
|
|
Entities.Migrate(Db(), runFailed)
|
|
|
|
Entities.WaitForMigration(Db())
|
2021-11-21 14:05:07 +01:00
|
|
|
|
|
|
|
CreateDefaultFixtures()
|
2022-01-05 18:15:39 +01:00
|
|
|
|
|
|
|
log.Debugf("entity: successfully initialized [%s]", time.Since(start))
|
2021-11-21 14:05:07 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// InitTestDb connects to and completely initializes the test database incl fixtures.
|
|
|
|
func InitTestDb(driver, dsn string) *Gorm {
|
|
|
|
if HasDbProvider() {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-03-29 00:21:50 +02:00
|
|
|
// Set default test database driver.
|
2021-11-21 14:05:07 +01:00
|
|
|
if driver == "test" || driver == "sqlite" || driver == "" || dsn == "" {
|
2022-03-29 00:21:50 +02:00
|
|
|
driver = SQLite3
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set default database DSN.
|
|
|
|
if driver == SQLite3 {
|
|
|
|
if dsn == "" {
|
|
|
|
dsn = SQLiteMemoryDSN
|
|
|
|
} else if dsn != SQLiteTestDB {
|
|
|
|
// Continue.
|
|
|
|
} else if err := os.Remove(dsn); err == nil {
|
|
|
|
log.Debugf("sqlite: test file %s removed", sanitize.Log(dsn))
|
|
|
|
}
|
2021-11-21 14:05:07 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
log.Infof("initializing %s test db in %s", driver, dsn)
|
|
|
|
|
2022-03-29 00:21:50 +02:00
|
|
|
// Create ORM instance.
|
2021-11-21 14:05:07 +01:00
|
|
|
db := &Gorm{
|
|
|
|
Driver: driver,
|
|
|
|
Dsn: dsn,
|
|
|
|
}
|
|
|
|
|
2022-03-29 00:21:50 +02:00
|
|
|
// Insert test fixtures.
|
2021-11-21 14:05:07 +01:00
|
|
|
SetDbProvider(db)
|
|
|
|
ResetTestFixtures()
|
|
|
|
|
|
|
|
return db
|
|
|
|
}
|