This repository has been archived by the owner on Dec 5, 2017. It is now read-only.
/
mysql.go
90 lines (83 loc) · 2.29 KB
/
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
package main
import (
"database/sql"
"errors"
"fmt"
"log"
)
type MySQL struct{}
func (m MySQL) getSchema(config Configuration) []ColumnSchema {
scheme := fmt.Sprintf("%s:%s@tcp(%s:%d)/information_schema", config.DbUser, config.DbPassword, config.DbHost, config.DbPort)
conn, err := sql.Open("mysql", scheme)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
q := `SELECT TABLE_NAME, COLUMN_NAME, IS_NULLABLE, DATA_TYPE,
CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, NUMERIC_SCALE, COLUMN_TYPE,
COLUMN_KEY FROM COLUMNS WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME, ORDINAL_POSITION`
rows, err := conn.Query(q, config.DbName)
if err != nil {
log.Fatal(err)
}
columns := []ColumnSchema{}
for rows.Next() {
cs := ColumnSchema{}
err := rows.Scan(&cs.TableName, &cs.ColumnName, &cs.IsNullable, &cs.DataType,
&cs.CharacterMaximumLength, &cs.NumericPrecision, &cs.NumericScale,
&cs.ColumnType, &cs.ColumnKey)
if err != nil {
log.Fatal(err)
}
columns = append(columns, cs)
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
return columns
}
func (m MySQL) goType(col *ColumnSchema) (string, string, error) {
requiredImport := ""
if col.IsNullable == "YES" {
requiredImport = "database/sql"
}
var gt string = ""
switch col.DataType {
case "char", "varchar", "enum", "text", "longtext", "mediumtext", "tinytext":
if col.IsNullable == "YES" {
gt = "sql.NullString"
} else {
gt = "string"
}
case "blob", "mediumblob", "longblob", "varbinary", "binary":
gt = "[]byte"
case "date", "time", "datetime", "timestamp":
gt, requiredImport = "time.Time", "time"
case "tinyint", "smallint", "int", "mediumint", "bigint":
if col.IsNullable == "YES" {
gt = "sql.NullInt64"
} else {
gt = "int64"
}
case "float", "decimal", "double":
if col.IsNullable == "YES" {
gt = "sql.NullFloat64"
} else {
gt = "float64"
}
}
if gt == "" {
n := col.TableName + "." + col.ColumnName
return "", "", errors.New("No compatible datatype (" + col.DataType + ") for " + n + " found")
}
return gt, requiredImport, nil
}
func (m MySQL) getEnvMap() map[string]string {
return map[string]string{
EnvHostKey: "MYSQL_HOST",
EnvPortKey: "MYSQL_PORT",
EnvDataBaseKey: "MYSQL_DATABASE",
EnvUserKey: "MYSQL_USER",
EnvPasswordKey: "MYSQL_PASSWORD",
}
}