Newer
Older
//
// tank
//
// Import and Playlist Daemon for autoradio project
//
//
// Copyright (C) 2017-2019 Christian Pointner <equinox@helsinki.at>
//
// This file is part of tank.
//
// tank is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// tank is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with tank. If not, see <http://www.gnu.org/licenses/>.
//
package store
import (
"errors"
"github.com/jinzhu/gorm"
"gopkg.in/gormigrate.v1"
)
func initialMigration(tx *gorm.DB) (err error) {
err = tx.AutoMigrate(
).Error
if err != nil {
return
}
// TODO: sadly this does not work on sqlite because constraints can only be added with create table...
// unfortunately gorm does not create foreign key contstraints in AutoMigrate(), see: https://github.com/jinzhu/gorm/issues/450
if err := tx.Model(File{}).AddForeignKey("show_name", "shows (name)", "CASCADE", "CASCADE").Error; err != nil {
return err
}
if err := tx.Model(Playlist{}).AddForeignKey("show_name", "shows (name)", "CASCADE", "CASCADE").Error; err != nil {
return err
}
if err := tx.Model(PlaylistEntry{}).AddForeignKey("playlist_id", "playlists (id)", "CASCADE", "CASCADE").Error; err != nil {
return err
}
if err := tx.Model(PlaylistEntry{}).AddForeignKey("file_id", "files (id)", "RESTRICT", "CASCADE").Error; err != nil {
return err
}
return nil
}
func (st *Store) initDBModel() (err error) {
opts := gormigrate.DefaultOptions
opts.TableName = migrationsTn
m := gormigrate.New(st.db, opts, []*gormigrate.Migration{
// for now everything is done @ initialMigration()
Migrate: func(tx *gorm.DB) error { return nil },
Rollback: func(tx *gorm.DB) error { return nil },
},
{
ID: "201905160033",
Migrate: func(tx *gorm.DB) error {
type Playlist struct {
ID uint64 `json:"id" gorm:"primary_key"`
CreatedAt time.Time `json:"created"`
UpdatedAt time.Time `json:"updated"`
Description string `json:"description"`
ShowName string `json:"show" gorm:"not null;index"`
Show Show `json:"-" gorm:"association_foreignkey:Name"`
Entries []PlaylistEntry `json:"entries,omitempty"`
}
return tx.AutoMigrate(&Playlist{}).Error
},
Rollback: func(tx *gorm.DB) error {
return tx.Table("playlists").DropColumn("description").Error
},
},
m.InitSchema(initialMigration)
if err = m.Migrate(); err != nil {
return errors.New("running database migrations failed: " + err.Error())
}
if err = st.db.Table(migrationsTn).Select("id").Order("id DESC").Limit(1).Row().Scan(&st.revision); err != nil {
return errors.New("fetching current database revision failed: " + err.Error())