44 lines
1.2 KiB
Go
44 lines
1.2 KiB
Go
package database
|
|
|
|
import (
|
|
entity "RenewCMS/internal/infrastructure/persistence/models"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
const (
|
|
articleStoriesMarker = "article_stories"
|
|
articleStoryLanguageIndex = "idx_articles_story_lang"
|
|
articleStoryLanguageIndexSQL = "CREATE UNIQUE INDEX idx_articles_story_lang ON articles (story_id, lang)"
|
|
)
|
|
|
|
func BackfillArticleStories(db *gorm.DB) error {
|
|
return db.Transaction(func(tx *gorm.DB) error {
|
|
applied, err := markerApplied(tx, articleStoriesMarker)
|
|
if err != nil || applied {
|
|
return err
|
|
}
|
|
var ids []uint32
|
|
if err := tx.Unscoped().Model(&entity.Article{}).Where("story_id = ?", 0).Order("id ASC").Pluck("id", &ids).Error; err != nil {
|
|
return err
|
|
}
|
|
for _, id := range ids {
|
|
story := entity.Story{}
|
|
if err := tx.Create(&story).Error; err != nil {
|
|
return err
|
|
}
|
|
if err := tx.Unscoped().Model(&entity.Article{}).Where("id = ?", id).UpdateColumn("story_id", story.ID).Error; err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return applyMarker(tx, articleStoriesMarker)
|
|
})
|
|
}
|
|
|
|
func ensureArticleStoryLanguageIndex(db *gorm.DB) error {
|
|
if db.Migrator().HasIndex(&entity.Article{}, articleStoryLanguageIndex) {
|
|
return nil
|
|
}
|
|
return db.Exec(articleStoryLanguageIndexSQL).Error
|
|
}
|