29 lines
847 B
Go
29 lines
847 B
Go
package common
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"github.com/gogf/gf/v2/frame/g"
|
|
)
|
|
|
|
// EnsureColumn 幂等加列:PRAGMA 查列不存在则 ALTER TABLE ADD COLUMN。
|
|
// 失败只记警告,不阻断启动(列缺失时后续查询只会取到空值)。
|
|
func EnsureColumn(ctx context.Context, table, col, sqlType string) {
|
|
cols, err := g.DB().GetAll(ctx, fmt.Sprintf("PRAGMA table_info(%s)", table))
|
|
if err != nil {
|
|
g.Log().Warningf(ctx, "migrate: %s 表结构读取失败: %v", table, err)
|
|
return
|
|
}
|
|
for _, c := range cols {
|
|
if c["name"].String() == col {
|
|
return
|
|
}
|
|
}
|
|
if _, err := g.DB().Exec(ctx, fmt.Sprintf("ALTER TABLE %s ADD COLUMN %s %s", table, col, sqlType)); err != nil {
|
|
g.Log().Warningf(ctx, "migrate: %s.%s 加列失败: %v", table, col, err)
|
|
return
|
|
}
|
|
g.Log().Infof(ctx, "migrate: %s.%s 已添加", table, col)
|
|
}
|