Skip to content

Commit

Permalink
Merge pull request #39 from zhangxiaodel/master
Browse files Browse the repository at this point in the history
Improve the code to make the order of the model's fields consistent w…
  • Loading branch information
Shelnutt2 authored Dec 7, 2020
2 parents 2234744 + 3ff7ec5 commit 175db63
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 30 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,4 @@ _testmain.go
*.exe
*.test
*.prof
.idea/
4 changes: 2 additions & 2 deletions cmd/db2struct/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ func main() {
return
}

columnDataTypes, err := db2struct.GetColumnsFromMysqlTable(*mariadbUser, *mariadbPassword, mariadbHost, *mariadbPort, *mariadbDatabase, *mariadbTable)
columnDataTypes, columnsSorted, err := db2struct.GetColumnsFromMysqlTable(*mariadbUser, *mariadbPassword, mariadbHost, *mariadbPort, *mariadbDatabase, *mariadbTable)

if err != nil {
fmt.Println("Error in selecting column data information from mysql information schema")
Expand All @@ -100,7 +100,7 @@ func main() {
*packageName = "newpackage"
}
// Generate struct string based on columnDataTypes
struc, err := db2struct.Generate(*columnDataTypes, *mariadbTable, *structName, *packageName, *jsonAnnotation, *gormAnnotation, *gureguTypes)
struc, err := db2struct.Generate(*columnDataTypes, columnsSorted, *mariadbTable, *structName, *packageName, *jsonAnnotation, *gormAnnotation, *gureguTypes)

if err != nil {
fmt.Println("Error in creating struct from json: " + err.Error())
Expand Down
6 changes: 3 additions & 3 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,10 @@ var Debug = false

// Generate Given a Column map with datatypes and a name structName,
// attempts to generate a struct definition
func Generate(columnTypes map[string]map[string]string, tableName string, structName string, pkgName string, jsonAnnotation bool, gormAnnotation bool, gureguTypes bool) ([]byte, error) {
func Generate(columnTypes map[string]map[string]string, columnsSorted []string, tableName string, structName string, pkgName string, jsonAnnotation bool, gormAnnotation bool, gureguTypes bool) ([]byte, error) {
var dbTypes string
dbTypes = generateMysqlTypes(columnTypes, 0, jsonAnnotation, gormAnnotation, gureguTypes)
src := fmt.Sprintf("package %s\ntype %s %s}",
dbTypes = generateMysqlTypes(columnTypes, columnsSorted, 0, jsonAnnotation, gormAnnotation, gureguTypes)
src := fmt.Sprintf("package %s\ntype %s %s\n}",
pkgName,
structName,
dbTypes)
Expand Down
45 changes: 20 additions & 25 deletions utils_mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@ import (
"database/sql"
"errors"
"fmt"
"sort"
"strconv"
"strings"
)

// GetColumnsFromMysqlTable Select column details from information schema and return map of map
func GetColumnsFromMysqlTable(mariadbUser string, mariadbPassword string, mariadbHost string, mariadbPort int, mariadbDatabase string, mariadbTable string) (*map[string]map[string]string, error) {
func GetColumnsFromMysqlTable(mariadbUser string, mariadbPassword string, mariadbHost string, mariadbPort int, mariadbDatabase string, mariadbTable string) (*map[string]map[string]string, []string, error) {

var err error
var db *sql.DB
Expand All @@ -24,13 +23,15 @@ func GetColumnsFromMysqlTable(mariadbUser string, mariadbPassword string, mariad
// Check for error in db, note this does not check connectivity but does check uri
if err != nil {
fmt.Println("Error opening mysql db: " + err.Error())
return nil, err
return nil, nil, err
}

columnNamesSorted := []string{}

// Store colum as map of maps
columnDataTypes := make(map[string]map[string]string)
// Select columnd data from INFORMATION_SCHEMA
columnDataTypeQuery := "SELECT COLUMN_NAME, COLUMN_KEY, DATA_TYPE, IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND table_name = ?"
columnDataTypeQuery := "SELECT COLUMN_NAME, COLUMN_KEY, DATA_TYPE, IS_NULLABLE, COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND table_name = ?"

if Debug {
fmt.Println("running: " + columnDataTypeQuery)
Expand All @@ -40,38 +41,34 @@ func GetColumnsFromMysqlTable(mariadbUser string, mariadbPassword string, mariad

if err != nil {
fmt.Println("Error selecting from db: " + err.Error())
return nil, err
return nil, nil, err
}
if rows != nil {
defer rows.Close()
} else {
return nil, errors.New("No results returned for table")
return nil, nil, errors.New("No results returned for table")
}

for rows.Next() {
var column string
var columnKey string
var dataType string
var nullable string
rows.Scan(&column, &columnKey, &dataType, &nullable)
var comment string
rows.Scan(&column, &columnKey, &dataType, &nullable, &comment)

columnDataTypes[column] = map[string]string{"value": dataType, "nullable": nullable, "primary": columnKey}
columnDataTypes[column] = map[string]string{"value": dataType, "nullable": nullable, "primary": columnKey, "comment": comment}
columnNamesSorted = append(columnNamesSorted, column)
}

return &columnDataTypes, err
return &columnDataTypes, columnNamesSorted, err
}

// Generate go struct entries for a map[string]interface{} structure
func generateMysqlTypes(obj map[string]map[string]string, depth int, jsonAnnotation bool, gormAnnotation bool, gureguTypes bool) string {
func generateMysqlTypes(obj map[string]map[string]string, columnsSorted []string, depth int, jsonAnnotation bool, gormAnnotation bool, gureguTypes bool) string {
structure := "struct {"

keys := make([]string, 0, len(obj))
for key := range obj {
keys = append(keys, key)
}
sort.Strings(keys)

for _, key := range keys {
for _, key := range columnsSorted {
mysqlType := obj[key]
nullable := false
if mysqlType["nullable"] == "YES" {
Expand All @@ -97,16 +94,14 @@ func generateMysqlTypes(obj map[string]map[string]string, depth int, jsonAnnotat
if jsonAnnotation == true {
annotations = append(annotations, fmt.Sprintf("json:\"%s\"", key))
}
if len(annotations) > 0 {
structure += fmt.Sprintf("\n%s %s `%s`",
fieldName,
valueType,
strings.Join(annotations, " "))

if len(annotations) > 0 {
// add colulmn comment
comment:=mysqlType["comment"]
structure += fmt.Sprintf("\n%s %s `%s` //%s", fieldName, valueType, strings.Join(annotations, " "), comment)
//structure += fmt.Sprintf("\n%s %s `%s`", fieldName, valueType, strings.Join(annotations, " "))
} else {
structure += fmt.Sprintf("\n%s %s",
fieldName,
valueType)
structure += fmt.Sprintf("\n%s %s",fieldName,valueType)
}
}
return structure
Expand Down

0 comments on commit 175db63

Please sign in to comment.