From be3cf9a04e998d2b244be6aec32972e35d4ab616 Mon Sep 17 00:00:00 2001 From: sentriz Date: Tue, 24 Mar 2020 14:48:30 +0000 Subject: [PATCH] transcode pref: use uniq user & client, not client & profile closes #48 --- db/db.go | 1 + db/migrations.go | 41 +++++++++++++++++++++++++++++++++++++++++ db/model.go | 6 +++--- 3 files changed, 45 insertions(+), 3 deletions(-) diff --git a/db/db.go b/db/db.go index e458114..13b6a65 100644 --- a/db/db.go +++ b/db/db.go @@ -42,6 +42,7 @@ func New(path string) (*DB, error) { &migrationMergePlaylist, &migrationCreateTranscode, &migrationAddGenre, + &migrationUpdateTranscodePrefIDX, }) if err = migr.Migrate(); err != nil { return nil, errors.Wrap(err, "migrating to latest version") diff --git a/db/migrations.go b/db/migrations.go index 394c4a0..6decad6 100644 --- a/db/migrations.go +++ b/db/migrations.go @@ -2,6 +2,8 @@ package db import ( + "fmt" + "github.com/jinzhu/gorm" "gopkg.in/gormigrate.v1" ) @@ -91,3 +93,42 @@ var migrationAddGenre = gormigrate.Migration{ Error }, } + +var migrationUpdateTranscodePrefIDX = gormigrate.Migration{ + ID: "202003241509", + Migrate: func(tx *gorm.DB) error { + var hasIDX int + tx. + Select("1"). + Table("sqlite_master"). + Where("type = ?", "index"). + Where("name = ?", "idx_user_id_client"). + Count(&hasIDX) + if hasIDX == 1 { + // index already exists + return nil + } + step := tx.Exec(` + ALTER TABLE transcode_preferences RENAME TO transcode_preferences_orig; + `) + if err := step.Error; err != nil { + return fmt.Errorf("step rename: %w", err) + } + step = tx.AutoMigrate( + TranscodePreference{}, + ) + if err := step.Error; err != nil { + return fmt.Errorf("step create: %w", err) + } + step = tx.Exec(` + INSERT INTO transcode_preferences (user_id, client, profile) + SELECT user_id, client, profile + FROM transcode_preferences_orig; + DROP TABLE transcode_preferences_orig; + `) + if err := step.Error; err != nil { + return fmt.Errorf("step copy: %w", err) + } + return nil + }, +} diff --git a/db/model.go b/db/model.go index 89e9204..2a4e0e7 100644 --- a/db/model.go +++ b/db/model.go @@ -203,7 +203,7 @@ func (p *PlayQueue) SetItems(items []int) { type TranscodePreference struct { User *User - UserID int `sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"` - Client string `gorm:"not null; unique_index:idx_client_profile" sql:"default: null"` - Profile string `gorm:"not null; unique_index:idx_client_profile" sql:"default: null"` + UserID int `gorm:"not null; unique_index:idx_user_id_client" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"` + Client string `gorm:"not null; unique_index:idx_user_id_client" sql:"default: null"` + Profile string `gorm:"not null" sql:"default: null"` }