mirror of
https://github.com/zhufuyi/sponge.git
synced 2025-12-24 10:40:55 +08:00
mongodb json tag
This commit is contained in:
@@ -64,16 +64,16 @@ var mgoTypeToGo = map[bsontype.Type]string{
|
||||
bson.TypeJavaScript: goTypeString,
|
||||
}
|
||||
|
||||
var jsonTagFormat int32 // 0: camel case, 1: snake case
|
||||
var jsonTagFormat int32 = 1 // 0: snake case, 1: camel case
|
||||
|
||||
// SetJSONTagSnakeCase set json tag format to snake case
|
||||
func SetJSONTagSnakeCase() {
|
||||
atomic.AddInt32(&jsonTagFormat, 1)
|
||||
atomic.AddInt32(&jsonTagFormat, -jsonTagFormat)
|
||||
}
|
||||
|
||||
// SetJSONTagCamelCase set json tag format to camel case
|
||||
func SetJSONTagCamelCase() {
|
||||
atomic.AddInt32(&jsonTagFormat, -jsonTagFormat)
|
||||
atomic.AddInt32(&jsonTagFormat, 1)
|
||||
}
|
||||
|
||||
// MgoField mongo field
|
||||
@@ -172,9 +172,9 @@ func parseObject(name string, elements []bson.RawElement) (goTypeStr string, goO
|
||||
|
||||
var jsonTag string
|
||||
if jsonTagFormat == 0 {
|
||||
jsonTag = toLowerFirst(xstrings.ToCamelCase(k))
|
||||
} else {
|
||||
jsonTag = xstrings.ToSnakeCase(k)
|
||||
} else {
|
||||
jsonTag = toLowerFirst(xstrings.ToCamelCase(k))
|
||||
}
|
||||
|
||||
goObjStr += fmt.Sprintf(" %s %s `bson:\"%s\" json:\"%s\"`\n", xstrings.ToCamelCase(k), t, k, jsonTag)
|
||||
|
||||
@@ -320,6 +320,14 @@ func makeCode(stmt *ast.CreateTableStmt, opt options) (*codeText, error) {
|
||||
if opt.ForceTableName || data.RawTableName != inflection.Plural(data.RawTableName) {
|
||||
data.NameFunc = true
|
||||
}
|
||||
switch opt.DBDriver {
|
||||
case DBDriverMongodb:
|
||||
if opt.JSONNamedType != 0 {
|
||||
SetJSONTagCamelCase()
|
||||
} else {
|
||||
SetJSONTagSnakeCase()
|
||||
}
|
||||
}
|
||||
|
||||
data.TableName = toCamel(data.TableName)
|
||||
data.TName = firstLetterToLow(data.TableName)
|
||||
|
||||
@@ -345,6 +345,7 @@ func Test_getMongodbTableFields(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
SetJSONTagCamelCase()
|
||||
goStructs := MgoFieldToGoStruct("foobar", fields)
|
||||
t.Log(goStructs)
|
||||
|
||||
@@ -363,6 +364,7 @@ func Test_getMongodbTableFields(t *testing.T) {
|
||||
_ = codes
|
||||
//printCode(codes)
|
||||
|
||||
SetJSONTagSnakeCase()
|
||||
sql, fieldsMap = ConvertToSQLByMgoFields("foobar", fields)
|
||||
t.Log(sql)
|
||||
opts = []Option{
|
||||
|
||||
Reference in New Issue
Block a user