Skip to content

Commit

Permalink
调整数据库迁移方案
Browse files Browse the repository at this point in the history
  • Loading branch information
steden committed Jan 6, 2025
1 parent 5d79be8 commit cfc4725
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 8 deletions.
3 changes: 3 additions & 0 deletions dbConfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package data

import (
"fmt"

"github.com/farseer-go/fs/container"
"gorm.io/gorm"
)
Expand All @@ -14,6 +15,8 @@ type dbConfig struct {
PoolMinSize int
ConnectionString string
databaseName string // 数据库名称
Migrate string // code first
migrated bool // 是否包含自动创建数据库
}

// GetDriver 获取对应驱动
Expand Down
7 changes: 4 additions & 3 deletions internalContext.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ type IGetInternalContext interface {
type internalContext struct {
dbConfig *dbConfig // 数据库配置
IsolationLevel sql.IsolationLevel // 事务等级
dbName string // 库名
nameReplacer *strings.Replacer // 替换dbName、tableName
//dbName string // 库名
nameReplacer *strings.Replacer // 替换dbName、tableName
}

// RegisterInternalContext 注册内部上下文
Expand All @@ -56,6 +56,7 @@ func RegisterInternalContext(key string, configString string) {
}
config.DataType = strings.ToLower(config.DataType)
config.keyName = key
config.migrated = strings.Contains(configString, "Migrate=")

// 获取数据库名称
switch config.DataType {
Expand Down Expand Up @@ -96,7 +97,7 @@ func RegisterInternalContext(key string, configString string) {

// 注册上下文
ins := &internalContext{dbConfig: &config}
ins.dbName = config.databaseName
//ins.dbName = config.databaseName
ins.nameReplacer = strings.NewReplacer("{database}", config.databaseName)
container.RegisterInstance[core.ITransaction](ins, key)

Expand Down
12 changes: 7 additions & 5 deletions tableSet.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,7 @@ func (receiver *TableSet[Table]) Init(dbContext *internalContext, param map[stri
//_ = db.Statement.Parse(t) // db.Statement.Model
//tableName := db.Statement.Schema.Table
tableName := reflect.TypeOf(t).Name()
if strings.HasSuffix(tableName, "PO") {
tableName = tableName[:len(tableName)-2]
}
tableName = strings.TrimSuffix(tableName, "PO")
tableName = schema.NamingStrategy{IdentifierMaxLength: 64}.ColumnName("", tableName)
//tableName = snakeString(tableName)
receiver.tableName = tableName
Expand All @@ -73,8 +71,12 @@ func (receiver *TableSet[Table]) Init(dbContext *internalContext, param map[stri
ts.dbName = receiver.dbName
ts.nameReplacer = receiver.nameReplacer

// 自动创建表
if migrate, exists := param["migrate"]; exists {
migrate, exists := param["migrate"]
if !exists {
exists = receiver.dbContext.dbConfig.migrated
migrate = receiver.dbContext.dbConfig.Migrate
}
if exists {
// 创建表
ts.CreateTable(migrate)
// 创建索引
Expand Down

0 comments on commit cfc4725

Please sign in to comment.