/* Copyright 2025 linux.do Modified by Arctel.net, 2026 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package migrator 提供数据库迁移功能 package migrator import ( "context" "embed" "log" "github.com/Rain-kl/Wavelet/internal/config" "github.com/Rain-kl/Wavelet/internal/db" "github.com/Rain-kl/Wavelet/internal/model" "github.com/pressly/goose/v3" ) // migrationFS contains SQL migrations under goose/. // //go:embed goose/postgres/*.sql goose/sqlite/*.sql var migrationFS embed.FS // dbType 返回当前数据库类型名称(用于日志输出) func dbType() string { if !config.Config.Database.Enabled { return "SQLite" } return "PostgreSQL" } func gooseDialect() string { if !config.Config.Database.Enabled { return "sqlite3" } return "postgres" } func migrationDir() string { if !config.Config.Database.Enabled { return "goose/sqlite" } return "goose/postgres" } // Migrate 执行数据库迁移 func Migrate() { gormDB := db.DB(context.Background()) if gormDB == nil { log.Fatalf("[%s] database not initialized\n", dbType()) } sqlDB, err := gormDB.DB() if err != nil { log.Fatalf("[%s] load sql db failed: %v\n", dbType(), err) } goose.SetBaseFS(migrationFS) if err := goose.SetDialect(gooseDialect()); err != nil { log.Fatalf("[%s] set goose dialect failed: %v\n", dbType(), err) } if err := goose.Up(sqlDB, migrationDir()); err != nil { log.Fatalf("[%s] goose migrate failed: %v\n", dbType(), err) } clearSystemConfigCache() log.Printf("[%s] goose migrate success\n", dbType()) } func clearSystemConfigCache() { if db.Redis == nil { return } if err := db.Redis.Del(context.Background(), db.PrefixedKey(model.SystemConfigRedisHashKey)).Err(); err != nil { log.Printf("[%s] clear system config cache failed: %v\n", dbType(), err) } }