|
| 1 | +package migrate |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "os" |
| 8 | + "path/filepath" |
| 9 | + "strings" |
| 10 | + |
| 11 | + "github.com/eddieowens/opts" |
| 12 | + "github.com/golang-migrate/migrate/v4" |
| 13 | + _ "github.com/golang-migrate/migrate/v4/database/mysql" |
| 14 | + _ "github.com/golang-migrate/migrate/v4/database/pgx/v5" |
| 15 | + "github.com/golang-migrate/migrate/v4/source/file" |
| 16 | + "github.com/pkg/errors" |
| 17 | + "github.com/zeromicro/go-zero/core/logx" |
| 18 | + "github.com/zeromicro/go-zero/core/stores/sqlx" |
| 19 | +) |
| 20 | + |
| 21 | +type MigrateOpts struct { |
| 22 | + PreProcessSqlFunc func(content string) string |
| 23 | + PluginsSort []string // 插件执行 sql_migration 排序 |
| 24 | + CustomDir []SqlMigrationCustomDir // 自定义目录 |
| 25 | +} |
| 26 | + |
| 27 | +type SqlMigrationCustomDir struct { |
| 28 | + Name string `json:"name"` // 自定义目录名称 e.g. saas 则自动迁移 desc/sql_migration/saas 下的 sql 文件 |
| 29 | + Enabled bool `json:"enabled"` // 是否启用 |
| 30 | +} |
| 31 | + |
| 32 | +func (opts MigrateOpts) DefaultOptions() MigrateOpts { |
| 33 | + return MigrateOpts{} |
| 34 | +} |
| 35 | + |
| 36 | +func WithPluginsSort(pluginsSort []string) opts.Opt[MigrateOpts] { |
| 37 | + return func(opts *MigrateOpts) { |
| 38 | + opts.PluginsSort = pluginsSort |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +func WithCustomDir(customDir []SqlMigrationCustomDir) opts.Opt[MigrateOpts] { |
| 43 | + return func(opts *MigrateOpts) { |
| 44 | + opts.CustomDir = customDir |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +func WithPreProcessSqlFunc(f func(string) string) opts.Opt[MigrateOpts] { |
| 49 | + return func(opts *MigrateOpts) { |
| 50 | + opts.PreProcessSqlFunc = f |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +func Migrate(ctx context.Context, c sqlx.SqlConf, op ...opts.Opt[MigrateOpts]) error { |
| 55 | + ops := opts.DefaultApply(op...) |
| 56 | + |
| 57 | + var ( |
| 58 | + // sql_migration 路径 |
| 59 | + coreSource, pluginSource, selfSource string |
| 60 | + |
| 61 | + // 数据库连接字符串 |
| 62 | + databaseUrl string |
| 63 | + |
| 64 | + // 参数连接符号, ? or & |
| 65 | + paramConnector string |
| 66 | + ) |
| 67 | + |
| 68 | + switch c.DriverName { |
| 69 | + case "mysql": |
| 70 | + coreSource = "file://desc/sql_migration/core" |
| 71 | + pluginSource = "file://plugins/%s/desc/sql_migration" |
| 72 | + selfSource = "file://desc/sql_migration" |
| 73 | + databaseUrl = "mysql://" + c.DataSource |
| 74 | + case "pgx": |
| 75 | + coreSource = "file://desc/sql_migration/core/postgresql" |
| 76 | + pluginSource = "file://plugins/%s/desc/sql_migration/postgresql" |
| 77 | + selfSource = "file://desc/sql_migration/postgresql" |
| 78 | + databaseUrl = "pgx5://" + strings.TrimPrefix(c.DataSource, "postgres://") |
| 79 | + } |
| 80 | + |
| 81 | + // 通过 config.Sqlx.DataSource 判断 |
| 82 | + if strings.Contains(c.DataSource, "?") { |
| 83 | + paramConnector = "&" |
| 84 | + } else { |
| 85 | + paramConnector = "?" |
| 86 | + } |
| 87 | + |
| 88 | + logx.WithContext(ctx).Info("start migrate core") |
| 89 | + if err := sqlMigrate(coreSource, fmt.Sprintf("%s%sx-migrations-table=%s", databaseUrl, paramConnector, "schema_migrations_core"), c, ops); err != nil { |
| 90 | + return err |
| 91 | + } |
| 92 | + |
| 93 | + // 获取所有插件目录 |
| 94 | + plugins, err := os.ReadDir("plugins") |
| 95 | + if err != nil { |
| 96 | + return nil |
| 97 | + } |
| 98 | + |
| 99 | + // 记录已执行的插件 |
| 100 | + executedPlugins := make(map[string]bool) |
| 101 | + |
| 102 | + // 先按配置的 plugins_sort 顺序执行插件迁移 |
| 103 | + if ops.PluginsSort != nil { |
| 104 | + for _, pluginName := range ops.PluginsSort { |
| 105 | + pluginPath := filepath.Join("plugins", pluginName) |
| 106 | + if _, err = os.Stat(pluginPath); err == nil { |
| 107 | + logx.WithContext(ctx).Infof("start migrate plugins %s", pluginName) |
| 108 | + if err = sqlMigrate(fmt.Sprintf(pluginSource, pluginName), fmt.Sprintf("%s%sx-migrations-table=%s", databaseUrl, paramConnector, "schema_migrations_plugin_"+pluginName), c, ops); err != nil { |
| 109 | + return err |
| 110 | + } |
| 111 | + executedPlugins[pluginName] = true |
| 112 | + } |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + // 然后执行未在 plugins_sort 中配置的其他插件 |
| 117 | + for _, plugin := range plugins { |
| 118 | + if plugin.IsDir() && !executedPlugins[plugin.Name()] { |
| 119 | + logx.WithContext(ctx).Infof("start migrate plugins %s", plugin.Name()) |
| 120 | + if err = sqlMigrate(fmt.Sprintf(pluginSource, plugin.Name()), fmt.Sprintf("%s%sx-migrations-table=%s", databaseUrl, paramConnector, "schema_migrations_plugin_"+plugin.Name()), c, ops); err != nil { |
| 121 | + return err |
| 122 | + } |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + // 执行自定义目录迁移 |
| 127 | + if ops.CustomDir != nil { |
| 128 | + for _, customDir := range ops.CustomDir { |
| 129 | + if customDir.Name == "" { |
| 130 | + return errors.New("custom dir name is empty") |
| 131 | + } |
| 132 | + if customDir.Name == "core" { |
| 133 | + return errors.New("custom dir name cannot be core") |
| 134 | + } |
| 135 | + if customDir.Enabled { |
| 136 | + customPath := fmt.Sprintf("file://desc/sql_migration/%s", customDir.Name) |
| 137 | + if c.DriverName == "pgx" { |
| 138 | + customPath = fmt.Sprintf("file://desc/sql_migration/%s/postgresql", customDir.Name) |
| 139 | + } |
| 140 | + logx.WithContext(ctx).Infof("start migrate custom dir %s", customDir.Name) |
| 141 | + if err = sqlMigrate(customPath, fmt.Sprintf("%s%sx-migrations-table=%s", databaseUrl, paramConnector, "schema_migrations_custom_"+customDir.Name), c, ops); err != nil { |
| 142 | + return err |
| 143 | + } |
| 144 | + } |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + logx.WithContext(ctx).Info("start migrate self") |
| 149 | + if err = sqlMigrate(selfSource, databaseUrl, c, ops); err != nil { |
| 150 | + return err |
| 151 | + } |
| 152 | + |
| 153 | + return nil |
| 154 | +} |
| 155 | + |
| 156 | +type customFileSource struct { |
| 157 | + *file.File |
| 158 | + driverName string |
| 159 | + preProcessSqlFunc func(content string) string |
| 160 | +} |
| 161 | + |
| 162 | +func (c *customFileSource) ReadUp(version uint) (r io.ReadCloser, identifier string, err error) { |
| 163 | + rc, id, err := c.File.ReadUp(version) |
| 164 | + if err != nil { |
| 165 | + return nil, "", err |
| 166 | + } |
| 167 | + |
| 168 | + content, err := io.ReadAll(rc) |
| 169 | + if err != nil { |
| 170 | + return nil, "", err |
| 171 | + } |
| 172 | + |
| 173 | + if err = rc.Close(); err != nil { |
| 174 | + return nil, "", err |
| 175 | + } |
| 176 | + return io.NopCloser(strings.NewReader(c.preProcessSqlFunc(string(content)))), id, nil |
| 177 | +} |
| 178 | + |
| 179 | +func (c *customFileSource) ReadDown(version uint) (r io.ReadCloser, identifier string, err error) { |
| 180 | + rc, id, err := c.File.ReadDown(version) |
| 181 | + if err != nil { |
| 182 | + return nil, "", err |
| 183 | + } |
| 184 | + |
| 185 | + content, err := io.ReadAll(rc) |
| 186 | + if err != nil { |
| 187 | + return nil, "", err |
| 188 | + } |
| 189 | + |
| 190 | + if err = rc.Close(); err != nil { |
| 191 | + return nil, "", err |
| 192 | + } |
| 193 | + |
| 194 | + modifiedContent := c.preProcessSqlFunc(string(content)) |
| 195 | + return io.NopCloser(strings.NewReader(modifiedContent)), id, nil |
| 196 | +} |
| 197 | + |
| 198 | +func sqlMigrate(sourceUrl, databaseUrl string, c sqlx.SqlConf, ops MigrateOpts) error { |
| 199 | + fileDriver := &file.File{} |
| 200 | + fileSource, err := fileDriver.Open(sourceUrl) |
| 201 | + if err != nil { |
| 202 | + if errors.Is(err, os.ErrNotExist) { |
| 203 | + return nil |
| 204 | + } |
| 205 | + return err |
| 206 | + } |
| 207 | + |
| 208 | + customSource := &customFileSource{ |
| 209 | + File: fileSource.(*file.File), |
| 210 | + driverName: c.DriverName, |
| 211 | + preProcessSqlFunc: ops.PreProcessSqlFunc, |
| 212 | + } |
| 213 | + |
| 214 | + m, err := migrate.NewWithSourceInstance("file", customSource, databaseUrl) |
| 215 | + if err != nil { |
| 216 | + return err |
| 217 | + } |
| 218 | + |
| 219 | + if err = m.Up(); err != nil { |
| 220 | + if errors.Is(err, migrate.ErrNoChange) { |
| 221 | + return nil |
| 222 | + } |
| 223 | + } |
| 224 | + |
| 225 | + sourceErr, databaseErr := m.Close() |
| 226 | + if sourceErr != nil { |
| 227 | + return sourceErr |
| 228 | + } |
| 229 | + if databaseErr != nil { |
| 230 | + return databaseErr |
| 231 | + } |
| 232 | + return nil |
| 233 | +} |
0 commit comments