Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: #2924 #3177

Merged
merged 4 commits into from
Dec 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 29 additions & 2 deletions cmd/gf/internal/cmd/cmd_z_init_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,33 @@

package cmd

import "context"
import (
"context"
"fmt"

var ctx = context.Background()
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/test/gtest"
)

var (
ctx = context.Background()
testDB gdb.DB
link = "mysql:root:12345678@tcp(127.0.0.1:3306)/test?loc=Local&parseTime=true"
)

func init() {
var err error
testDB, err = gdb.New(gdb.ConfigNode{
Link: link,
})
if err != nil {
panic(err)
}
}

func dropTableWithDb(db gdb.DB, table string) {
dropTableStmt := fmt.Sprintf("DROP TABLE IF EXISTS `%s`", table)
if _, err := db.Exec(ctx, dropTableStmt); err != nil {
gtest.Error(err)
}
}
24 changes: 4 additions & 20 deletions cmd/gf/internal/cmd/cmd_z_unit_gen_dao_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,30 +12,18 @@ import (
"testing"

"github.com/gogf/gf/cmd/gf/v2/internal/cmd/gendao"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/test/gtest"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/guid"
"github.com/gogf/gf/v2/util/gutil"
)

func dropTableWithDb(db gdb.DB, table string) {
dropTableStmt := fmt.Sprintf("DROP TABLE IF EXISTS `%s`", table)
if _, err := db.Exec(ctx, dropTableStmt); err != nil {
gtest.Error(err)
}
}

func Test_Gen_Dao_Default(t *testing.T) {
link := "mysql:root:12345678@tcp(127.0.0.1:3306)/test?loc=Local&parseTime=true"
db, err := gdb.New(gdb.ConfigNode{
Link: link,
})
gtest.AssertNil(err)

gtest.C(t, func(t *gtest.T) {
var (
err error
db = testDB
table = "table_user"
sqlContent = fmt.Sprintf(
gtest.DataContent(`gendao`, `user.tpl.sql`),
Expand Down Expand Up @@ -123,14 +111,10 @@ func Test_Gen_Dao_Default(t *testing.T) {
}

func Test_Gen_Dao_TypeMapping(t *testing.T) {
link := "mysql:root:12345678@tcp(127.0.0.1:3306)/test?loc=Local&parseTime=true"
db, err := gdb.New(gdb.ConfigNode{
Link: link,
})
gtest.AssertNil(err)

gtest.C(t, func(t *gtest.T) {
var (
err error
db = testDB
table = "table_user"
sqlContent = fmt.Sprintf(
gtest.DataContent(`gendao`, `user.tpl.sql`),
Expand Down
70 changes: 70 additions & 0 deletions cmd/gf/internal/cmd/cmd_z_unit_gen_pbentity_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https:/gogf/gf.

package cmd

import (
"fmt"
"os"
"path/filepath"
"testing"

"github.com/gogf/gf/v2/os/gcmd"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/test/gtest"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/guid"
)

func Test_Gen_Pbentity_NameCase(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var (
err error
db = testDB
table = "table_user"
sqlContent = fmt.Sprintf(
gtest.DataContent(`genpbentity`, `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())
err = gfile.Mkdir(path)
t.AssertNil(err)
defer gfile.Remove(path)

root, err := gcmd.NewFromObject(GF)
t.AssertNil(err)
err = root.AddObject(
Gen,
)
t.AssertNil(err)
os.Args = []string{"gf", "gen", "pbentity", "-l", link, "-p", path, "-package=unittest", "-nameCase=SnakeScreaming"}

err = root.RunWithError(ctx)
t.AssertNil(err)

files := []string{
filepath.FromSlash(path + "/table_user.proto"),
}

testPath := gtest.DataPath("genpbentity", "generated_user")
expectFiles := []string{
filepath.FromSlash(testPath + "/table_user.proto"),
}
// check files content
for i := range files {
t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i]))
}
})
}
29 changes: 4 additions & 25 deletions cmd/gf/internal/cmd/genpbentity/genpbentity.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ type (
RemovePrefix string `name:"removePrefix" short:"r" brief:"{CGenPbEntityBriefRemovePrefix}"`
RemoveFieldPrefix string `name:"removeFieldPrefix" short:"rf" brief:"{CGenPbEntityBriefRemoveFieldPrefix}"`
NameCase string `name:"nameCase" short:"n" brief:"{CGenPbEntityBriefNameCase}" d:"Camel"`
JsonCase string `name:"jsonCase" short:"j" brief:"{CGenPbEntityBriefJsonCase}" d:"CamelLower"`
JsonCase string `name:"jsonCase" short:"j" brief:"{CGenPbEntityBriefJsonCase}" d:"none"`
Option string `name:"option" short:"o" brief:"{CGenPbEntityBriefOption}"`
}
CGenPbEntityOutput struct{}
Expand Down Expand Up @@ -342,6 +342,7 @@ func generateMessageFieldForPbEntity(index int, field *gdb.TableField, in CGenPb
comment = gstr.Replace(comment, `\n`, " ")
comment, _ = gregex.ReplaceString(`\s{2,}`, ` `, comment)
if jsonTagName := formatCase(field.Name, in.JsonCase); jsonTagName != "" {
jsonTagStr = fmt.Sprintf(`[json_name = "%s"]`, jsonTagName)
// beautiful indent.
if index < 10 {
// 3 spaces
Expand Down Expand Up @@ -378,32 +379,10 @@ func getTplPbEntityContent(tplEntityPath string) string {

// formatCase call gstr.Case* function to convert the s to specified case.
func formatCase(str, caseStr string) string {
switch gstr.ToLower(caseStr) {
case gstr.ToLower("Camel"):
return gstr.CaseCamel(str)

case gstr.ToLower("CamelLower"):
return gstr.CaseCamelLower(str)

case gstr.ToLower("Kebab"):
return gstr.CaseKebab(str)

case gstr.ToLower("KebabScreaming"):
return gstr.CaseKebabScreaming(str)

case gstr.ToLower("Snake"):
return gstr.CaseSnake(str)

case gstr.ToLower("SnakeFirstUpper"):
return gstr.CaseSnakeFirstUpper(str)

case gstr.ToLower("SnakeScreaming"):
return gstr.CaseSnakeScreaming(str)

case "none":
if caseStr == "none" {
return ""
}
return str
return gstr.CaseConvert(str, gstr.CaseTypeMatch(caseStr))
}

func sortFieldKeyForPbEntity(fieldMap map[string]*gdb.TableField) []string {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// ==========================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// ==========================================================================

syntax = "proto3";

package unittest;

option go_package = "unittest";

import "google/protobuf/timestamp.proto";

message TableUser {
uint32 ID = 1; // User ID
string PASSPORT = 2; // User Passport
string PASSWORD = 3; // User Password
string NICKNAME = 4; // User Nickname
string SCORE = 5; // Total score amount.
google.protobuf.Timestamp CREATE_AT = 6; // Created Time
google.protobuf.Timestamp UPDATE_AT = 7; // Updated Time
}
10 changes: 10 additions & 0 deletions cmd/gf/internal/cmd/testdata/genpbentity/user.tpl.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
CREATE TABLE `%s` (
`id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'User ID',
`passport` varchar(45) NOT NULL COMMENT 'User Passport',
`password` varchar(45) NOT NULL COMMENT 'User Password',
`nickname` varchar(45) NOT NULL COMMENT 'User Nickname',
`score` decimal(10,2) unsigned DEFAULT NULL COMMENT 'Total score amount.',
`create_at` datetime DEFAULT NULL COMMENT 'Created Time',
`update_at` datetime DEFAULT NULL COMMENT 'Updated Time',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Loading