Feature model postgresql (#842)

* Support postgresql generate

* Update template Var

* Support to generate postgresql model

* Support to generate postgresql model

* Update template

Co-authored-by: anqiansong <anqiansong@xiaoheiban.cn>
This commit is contained in:
anqiansong
2021-07-23 11:45:15 +08:00
committed by GitHub
parent 476026e393
commit 089cdaa75f
19 changed files with 484 additions and 59 deletions

View File

@@ -3,6 +3,7 @@ package builderx
import (
"fmt"
"reflect"
"strings"
"github.com/go-xorm/builder"
)
@@ -81,13 +82,18 @@ func FieldNames(in interface{}) []string {
}
// RawFieldNames converts golang struct field into slice string
func RawFieldNames(in interface{}) []string {
func RawFieldNames(in interface{}, postgresSql ...bool) []string {
out := make([]string, 0)
v := reflect.ValueOf(in)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
var pg bool
if len(postgresSql) > 0 {
pg = postgresSql[0]
}
// we only accept structs
if v.Kind() != reflect.Struct {
panic(fmt.Errorf("ToMap only accepts structs; got %T", v))
@@ -98,11 +104,32 @@ func RawFieldNames(in interface{}) []string {
// gets us a StructField
fi := typ.Field(i)
if tagv := fi.Tag.Get(dbTag); tagv != "" {
out = append(out, fmt.Sprintf("`%s`", tagv))
if pg {
out = append(out, fmt.Sprintf("%s", tagv))
} else {
out = append(out, fmt.Sprintf("`%s`", tagv))
}
} else {
out = append(out, fmt.Sprintf(`"%s"`, fi.Name))
if pg {
out = append(out, fmt.Sprintf("%s", fi.Name))
} else {
out = append(out, fmt.Sprintf("`%s`", fi.Name))
}
}
}
return out
}
func PostgreSqlJoin(elems []string) string {
var b = new(strings.Builder)
for index, e := range elems {
b.WriteString(fmt.Sprintf("%s = $%d, ", e, index+1))
}
if b.Len() == 0 {
return b.String()
}
return b.String()[0 : b.Len()-2]
}

View File

@@ -118,3 +118,8 @@ func TestBuildSqlLike(t *testing.T) {
assert.Equal(t, sql, actualSQL)
assert.Equal(t, args, actualArgs)
}
func TestJoin(t *testing.T) {
ret := PostgreSqlJoin([]string{"name", "age"})
assert.Equal(t, "name = $1, age = $2", ret)
}