database/sql2go/generate_dao.go

56 lines
1.3 KiB
Go
Raw Normal View History

2022-05-16 12:38:32 +08:00
// Package sql2go...
//
// Description : sql2go...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2021-11-17 10:14 上午
package sql2go
import (
"strings"
)
// GenerateDao 根据sql自动生成dao
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 10:15 上午 2021/11/17
2023-02-28 16:18:20 +08:00
func GenerateDao(sql string, packageName string, withGetTableNameFunc bool) (string, error) {
2022-05-16 12:38:32 +08:00
if len(packageName) == 0 {
packageName = "dao"
}
2023-02-28 16:18:20 +08:00
dataStruct, basic, err := ParseCreateTableSql(sql, withGetTableNameFunc)
2022-05-16 12:38:32 +08:00
if nil != err {
return "", err
}
replaceTable := map[string]string{
"{PACKAGE}": packageName,
"{DATA_STRUCT_DAO}": basic.ModelStruct + "Dao",
"{DATA_STRUCT_NAME}": basic.ModelStruct,
"{DATA_STRUCT}": dataStruct,
"{DAO_RECEIVER}": getDaoReceiver(basic.TableName),
"{DB_TABLE_NAME}": basic.TableName,
"{PRIMARY_KEY}": "ID",
"{PRIMARY_KEY_TYPE}": basic.PrimaryFieldType,
}
2022-05-16 14:06:41 +08:00
tpl := DaoTpl
2022-05-16 12:38:32 +08:00
for oldVal, newVal := range replaceTable {
tpl = strings.ReplaceAll(tpl, oldVal, newVal)
}
return tpl, nil
}
func getDaoReceiver(tableName string) string {
nameArr := strings.Split(tableName, "_")
result := ""
for _, item := range nameArr {
if len(item) > 0 {
result += string([]byte(item)[0])
}
}
result += "d"
return result
}