forked from Shelnutt2/db2struct
/
utils_mysql.go
235 lines (204 loc) · 6.83 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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package db2struct
import (
"database/sql"
"errors"
"fmt"
"strconv"
"strings"
)
func connect(mariadbUser string, mariadbPassword string, mariadbHost string, mariadbPort int, mariadbDatabase string) (*sql.DB, error) {
if mariadbPassword != "" {
return sql.Open("mysql", mariadbUser+":"+mariadbPassword+"@tcp("+mariadbHost+":"+strconv.Itoa(mariadbPort)+")/"+mariadbDatabase+"?&parseTime=True")
}
return sql.Open("mysql", mariadbUser+"@tcp("+mariadbHost+":"+strconv.Itoa(mariadbPort)+")/"+mariadbDatabase+"?&parseTime=True")
}
// GetTablesFromMysqlSchema Select table details from information schema
func GetTablesFromMysqlSchema(mariadbUser string, mariadbPassword string, mariadbHost string, mariadbPort int, mariadbDatabase string) ([]string, error) {
db, err := connect(mariadbUser, mariadbPassword, mariadbHost, mariadbPort, mariadbDatabase)
// 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
}
defer db.Close()
tableNamesSorted := []string{}
// Select table data from INFORMATION_SCHEMA
tableDataTypeQuery := "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ? order by TABLE_NAME asc"
if Debug {
fmt.Println("running: " + tableDataTypeQuery)
}
rows, err := db.Query(tableDataTypeQuery, mariadbDatabase)
if err != nil {
fmt.Println("Error selecting from db: " + err.Error())
return nil, err
}
if rows != nil {
defer rows.Close()
} else {
return nil, errors.New("No results returned for table")
}
for rows.Next() {
var tableName string
rows.Scan(&tableName)
tableNamesSorted = append(tableNamesSorted, tableName)
}
return tableNamesSorted, err
}
// 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) {
db, err := connect(mariadbUser, mariadbPassword, mariadbHost, mariadbPort, mariadbDatabase)
// 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
}
defer db.Close()
columnNamesSorted := []string{}
// Store column as map of maps
columnDataTypes := make(map[string]map[string]string)
// Select column data from INFORMATION_SCHEMA
columnDataTypeQuery := "SELECT COLUMN_TYPE, 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 columnType string
var column string
var columnKey string
var dataType string
var nullable string
var comment string
rows.Scan(&columnType, &column, &columnKey, &dataType, &nullable, &comment)
columnDataTypes[column] = map[string]string{"columnType": columnType, "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, dbAnnotation 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, mysqlType["columnType"])
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 dbAnnotation == true {
annotations = append(annotations, fmt.Sprintf("db:\"%s\"", key))
}
if len(annotations) > 0 {
// add colulmn comment
comment := mysqlType["comment"]
structure += fmt.Sprintf("\n%s %s `%s`", fieldName, valueType, strings.Join(annotations, " "))
if comment != "" {
structure += fmt.Sprintf(" // %s", comment)
}
} else {
structure += fmt.Sprintf("\n%s %s", fieldName, valueType)
}
}
return structure
}
func isSigned(columnType string) bool {
return !strings.Contains(columnType, "unsigned")
}
// 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, columnType string) string {
signed := isSigned(columnType)
switch mysqlType {
case "tinyint", "int", "smallint", "mediumint":
if nullable {
if gureguTypes {
return gureguNullInt
}
return sqlNullInt // Unsiged will fit in this 64 bit number
}
return golangInt
case "bigint":
// Until they support this https://go-review.googlesource.com/c/go/+/344410/
if !signed {
if nullable {
return golangNullUint64
}
return golangUint64
}
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 {
if gureguTypes {
return gureguNullTime
}
return golangNullTime
}
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":
// This assumes that any binary(16) is a uuid
if columnType == "binary(16)" {
if nullable {
return skyhopNullBinaryUUID
}
return skyhopBinaryUUID
}
if nullable {
return golangNullByteArray
}
return golangByteArray
}
return ""
}