-
Notifications
You must be signed in to change notification settings - Fork 125
/
utils_mysql.go
170 lines (150 loc) · 5.1 KB
/
utils_mysql.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
package db2struct
import (
"database/sql"
"errors"
"fmt"
"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, []string, error) {
var err error
var db *sql.DB
if strings.HasPrefix(mariadbHost, "unix:") {
parts := strings.SplitN(mariadbHost, ":", 2)
socketPath := parts[1]
db, err = sql.Open("mysql", mariadbUser+":"+mariadbPassword+"@unix("+socketPath+")"+"/"+mariadbDatabase+"?charset=utf8&parseTime=True")
// Cite: https://dev.mysql.com/doc/mysql-shell/8.0/en/mysql-shell-connection-socket.html
// Cite: https://stackoverflow.com/a/67867865/71978
} else {
if mariadbPassword != "" {
db, err = sql.Open("mysql", mariadbUser+":"+mariadbPassword+"@tcp("+mariadbHost+":"+strconv.Itoa(mariadbPort)+")/"+mariadbDatabase+"?&parseTime=True")
} else {
db, err = sql.Open("mysql", mariadbUser+"@tcp("+mariadbHost+":"+strconv.Itoa(mariadbPort)+")/"+mariadbDatabase+"?&parseTime=True")
}
}
defer db.Close()
// 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, 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, COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND table_name = ? order by ordinal_position asc"
if Debug {
fmt.Println("running: " + columnDataTypeQuery)
}
rows, err := db.Query(columnDataTypeQuery, mariadbDatabase, mariadbTable)
if err != nil {
fmt.Println("Error selecting from db: " + err.Error())
return nil, nil, err
}
if rows != nil {
defer rows.Close()
} else {
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
var comment string
rows.Scan(&column, &columnKey, &dataType, &nullable, &comment)
columnDataTypes[column] = map[string]string{"value": dataType, "nullable": nullable, "primary": columnKey, "comment": comment}
columnNamesSorted = append(columnNamesSorted, column)
}
return &columnDataTypes, columnNamesSorted, err
}
// Generate go struct entries for a map[string]interface{} structure
func generateMysqlTypes(obj map[string]map[string]string, columnsSorted []string, depth int, jsonAnnotation bool, gormAnnotation bool, gureguTypes bool) string {
structure := "struct {"
for _, key := range columnsSorted {
mysqlType := obj[key]
nullable := false
if mysqlType["nullable"] == "YES" {
nullable = true
}
primary := ""
if mysqlType["primary"] == "PRI" {
primary = ";primary_key"
}
// Get the corresponding go value type for this mysql type
var valueType string
// If the guregu (https://github.com/guregu/null) CLI option is passed use its types, otherwise use go's sql.NullX
valueType = mysqlTypeToGoType(mysqlType["value"], nullable, gureguTypes)
fieldName := fmtFieldName(stringifyFirstChar(key))
var annotations []string
if gormAnnotation == true {
annotations = append(annotations, fmt.Sprintf("gorm:\"column:%s%s\"", key, primary))
}
if jsonAnnotation == true {
annotations = append(annotations, fmt.Sprintf("json:\"%s\"", key))
}
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)
}
}
return structure
}
// mysqlTypeToGoType converts the mysql types to go compatible sql.Nullable (https://golang.org/pkg/database/sql/) types
func mysqlTypeToGoType(mysqlType string, nullable bool, gureguTypes bool) string {
switch mysqlType {
case "tinyint", "int", "smallint", "mediumint":
if nullable {
if gureguTypes {
return gureguNullInt
}
return sqlNullInt
}
return golangInt
case "bigint":
if nullable {
if gureguTypes {
return gureguNullInt
}
return sqlNullInt
}
return golangInt64
case "char", "enum", "varchar", "longtext", "mediumtext", "text", "tinytext", "json":
if nullable {
if gureguTypes {
return gureguNullString
}
return sqlNullString
}
return "string"
case "date", "datetime", "time", "timestamp":
if nullable && gureguTypes {
return gureguNullTime
}
return golangTime
case "decimal", "double":
if nullable {
if gureguTypes {
return gureguNullFloat
}
return sqlNullFloat
}
return golangFloat64
case "float":
if nullable {
if gureguTypes {
return gureguNullFloat
}
return sqlNullFloat
}
return golangFloat32
case "binary", "blob", "longblob", "mediumblob", "varbinary":
return golangByteArray
}
return ""
}