Skip to content

Commit

Permalink
fix(cmd/gf): table and field names converted to its lower case before…
Browse files Browse the repository at this point in the history
… CamelCase converting in command `gen dao` (#3801)
  • Loading branch information
gqcn authored Sep 25, 2024
1 parent 76783fd commit ab2c3b0
Show file tree
Hide file tree
Showing 12 changed files with 284 additions and 9 deletions.
71 changes: 71 additions & 0 deletions cmd/gf/internal/cmd/cmd_z_unit_gen_dao_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -691,3 +691,74 @@ func Test_Gen_Dao_Issue3459(t *testing.T) {
}
})
}

// https://github.com/gogf/gf/issues/3749
func Test_Gen_Dao_Issue3749(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var (
err error
db = testDB
table = "table_user"
sqlContent = fmt.Sprintf(
gtest.DataContent(`issue`, `3749`, `user.tpl.sql`),
table,
)
)
dropTableWithDb(db, table)
array := gstr.SplitAndTrim(sqlContent, ";")
for _, v := range array {
if _, err = db.Exec(ctx, v); err != nil {
t.AssertNil(err)
}
}
defer dropTableWithDb(db, table)

var (
path = gfile.Temp(guid.S())
group = "test"
in = gendao.CGenDaoInput{
Path: path,
Link: link,
Group: group,
}
)

err = gutil.FillStructWithDefault(&in)
t.AssertNil(err)

err = gfile.Mkdir(path)
t.AssertNil(err)

// for go mod import path auto retrieve.
err = gfile.Copy(
gtest.DataPath("gendao", "go.mod.txt"),
gfile.Join(path, "go.mod"),
)
t.AssertNil(err)

_, err = gendao.CGenDao{}.Dao(ctx, in)
t.AssertNil(err)
defer gfile.Remove(path)

// files
files, err := gfile.ScanDir(path, "*.go", true)
t.AssertNil(err)
t.Assert(files, []string{
filepath.FromSlash(path + "/dao/internal/table_user.go"),
filepath.FromSlash(path + "/dao/table_user.go"),
filepath.FromSlash(path + "/model/do/table_user.go"),
filepath.FromSlash(path + "/model/entity/table_user.go"),
})
// content
testPath := gtest.DataPath(`issue`, `3749`)
expectFiles := []string{
filepath.FromSlash(testPath + "/dao/internal/table_user.go"),
filepath.FromSlash(testPath + "/dao/table_user.go"),
filepath.FromSlash(testPath + "/model/do/table_user.go"),
filepath.FromSlash(testPath + "/model/entity/table_user.go"),
}
for i, _ := range files {
t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i]))
}
})
}
8 changes: 4 additions & 4 deletions cmd/gf/internal/cmd/gendao/gendao_dao.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ func generateDaoSingle(ctx context.Context, in generateDaoSingleInput) {
mlog.Fatalf(`fetching tables fields failed for table "%s": %+v`, in.TableName, err)
}
var (
tableNameCamelCase = gstr.CaseCamel(strings.ToLower(in.NewTableName))
tableNameCamelLowerCase = gstr.CaseCamelLower(strings.ToLower(in.NewTableName))
tableNameCamelCase = formatFieldName(in.NewTableName, FieldNameCaseCamel)
tableNameCamelLowerCase = formatFieldName(in.NewTableName, FieldNameCaseCamelLower)
tableNameSnakeCase = gstr.CaseSnake(in.NewTableName)
importPrefix = in.ImportPrefix
)
Expand Down Expand Up @@ -179,7 +179,7 @@ func generateColumnNamesForDao(fieldMap map[string]*gdb.TableField, removeFieldP
}

array[index] = []string{
" #" + gstr.CaseCamel(strings.ToLower(newFiledName)) + ":",
" #" + formatFieldName(newFiledName, FieldNameCaseCamel) + ":",
fmt.Sprintf(` #"%s",`, field.Name),
}
}
Expand Down Expand Up @@ -219,7 +219,7 @@ func generateColumnDefinitionForDao(fieldMap map[string]*gdb.TableField, removeF
newFiledName = gstr.TrimLeftStr(newFiledName, v, 1)
}
array[index] = []string{
" #" + gstr.CaseCamel(strings.ToLower(newFiledName)),
" #" + formatFieldName(newFiledName, FieldNameCaseCamel),
" # " + "string",
" #" + fmt.Sprintf(`// %s`, comment),
}
Expand Down
4 changes: 2 additions & 2 deletions cmd/gf/internal/cmd/gendao/gendao_do.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func generateDo(ctx context.Context, in CGenDaoInternalInput) {
structDefinition, _ = generateStructDefinition(ctx, generateStructDefinitionInput{
CGenDaoInternalInput: in,
TableName: tableName,
StructName: gstr.CaseCamel(strings.ToLower(newTableName)),
StructName: formatFieldName(newTableName, FieldNameCaseCamel),
FieldMap: fieldMap,
IsDo: true,
})
Expand All @@ -61,7 +61,7 @@ func generateDo(ctx context.Context, in CGenDaoInternalInput) {
ctx,
in,
tableName,
gstr.CaseCamel(strings.ToLower(newTableName)),
formatFieldName(newTableName, FieldNameCaseCamel),
structDefinition,
)
in.genItems.AppendGeneratedFilePath(doFilePath)
Expand Down
4 changes: 2 additions & 2 deletions cmd/gf/internal/cmd/gendao/gendao_entity.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,15 @@ func generateEntity(ctx context.Context, in CGenDaoInternalInput) {
structDefinition, appendImports = generateStructDefinition(ctx, generateStructDefinitionInput{
CGenDaoInternalInput: in,
TableName: tableName,
StructName: gstr.CaseCamel(strings.ToLower(newTableName)),
StructName: formatFieldName(newTableName, FieldNameCaseCamel),
FieldMap: fieldMap,
IsDo: false,
})
entityContent = generateEntityContent(
ctx,
in,
newTableName,
gstr.CaseCamel(strings.ToLower(newTableName)),
formatFieldName(newTableName, FieldNameCaseCamel),
structDefinition,
appendImports,
)
Expand Down
39 changes: 38 additions & 1 deletion cmd/gf/internal/cmd/gendao/gendao_structure.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ func generateStructFieldDefinition(
}

attrLines = []string{
" #" + gstr.CaseCamel(strings.ToLower(newFiledName)),
" #" + formatFieldName(newFiledName, FieldNameCaseCamel),
" #" + localTypeNameStr,
}
attrLines = append(attrLines, fmt.Sprintf(` #%sjson:"%s"`, tagKey, jsonTag))
Expand All @@ -167,6 +167,43 @@ func generateStructFieldDefinition(
return attrLines, appendImport
}

type FieldNameCase string

const (
FieldNameCaseCamel FieldNameCase = "CaseCamel"
FieldNameCaseCamelLower FieldNameCase = "CaseCamelLower"
)

// formatFieldName formats and returns a new field name that is used for golang codes generating.
func formatFieldName(fieldName string, nameCase FieldNameCase) string {
// For normal databases like mysql, pgsql, sqlite,
// field/table names of that are in normal case.
var newFieldName = fieldName
if isAllUpper(fieldName) {
// For special databases like dm, oracle,
// field/table names of that are in upper case.
newFieldName = strings.ToLower(fieldName)
}
switch nameCase {
case FieldNameCaseCamel:
return gstr.CaseCamel(newFieldName)
case FieldNameCaseCamelLower:
return gstr.CaseCamelLower(newFieldName)
default:
return ""
}
}

// isAllUpper checks and returns whether given `fieldName` all letters are upper case.
func isAllUpper(fieldName string) bool {
for _, b := range fieldName {
if b >= 'a' && b <= 'z' {
return false
}
}
return true
}

// formatComment formats the comment string to fit the golang code without any lines.
func formatComment(comment string) string {
comment = gstr.ReplaceByArray(comment, g.SliceStr{
Expand Down
85 changes: 85 additions & 0 deletions cmd/gf/internal/cmd/testdata/issue/3749/dao/internal/table_user.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

27 changes: 27 additions & 0 deletions cmd/gf/internal/cmd/testdata/issue/3749/dao/table_user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================

package dao

import (
"for-gendao-test/pkg/dao/internal"
)

// internalTableUserDao is internal type for wrapping internal DAO implements.
type internalTableUserDao = *internal.TableUserDao

// tableUserDao is the data access object for table table_user.
// You can define custom methods on it to extend its functionality as you wish.
type tableUserDao struct {
internalTableUserDao
}

var (
// TableUser is globally public accessible object for table table_user operations.
TableUser = tableUserDao{
internal.NewTableUserDao(),
}
)

// Fill with you ideas below.
22 changes: 22 additions & 0 deletions cmd/gf/internal/cmd/testdata/issue/3749/model/do/table_user.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 20 additions & 0 deletions cmd/gf/internal/cmd/testdata/issue/3749/model/entity/table_user.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions cmd/gf/internal/cmd/testdata/issue/3749/user.tpl.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
CREATE TABLE `%s` (
`Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'User ID',
`parentId` varchar(45) NOT NULL COMMENT '',
`PASSPORT` varchar(45) NOT NULL COMMENT 'User Passport',
`PASS_WORD` varchar(45) NOT NULL COMMENT 'User Password',
`NICKNAME2` varchar(45) NOT NULL COMMENT 'User Nickname',
`create_at` datetime DEFAULT NULL COMMENT 'Created Time',
`update_at` datetime DEFAULT NULL COMMENT 'Updated Time',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2 changes: 2 additions & 0 deletions text/gstr/gstr_case.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ func CaseConvert(s string, caseType CaseType) string {
//
// Example:
// CaseCamel("any_kind_of_string") -> AnyKindOfString
// CaseCamel("anyKindOfString") -> AnyKindOfString
func CaseCamel(s string) string {
return toCamelInitCase(s, true)
}
Expand All @@ -115,6 +116,7 @@ func CaseCamel(s string) string {
//
// Example:
// CaseCamelLower("any_kind_of_string") -> anyKindOfString
// CaseCamelLower("AnyKindOfString") -> anyKindOfString
func CaseCamelLower(s string) string {
if s == "" {
return s
Expand Down
1 change: 1 addition & 0 deletions text/gstr/gstr_z_unit_case_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ func Test_CaseCamel(t *testing.T) {
{"test_case", "TestCase"},
{"test", "Test"},
{"TestCase", "TestCase"},
{"testCase", "TestCase"},
{" test case ", "TestCase"},
{"userLogin_log.bak", "UserLoginLogBak"},
{"", ""},
Expand Down

0 comments on commit ab2c3b0

Please sign in to comment.