-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathservice.go
92 lines (88 loc) · 2.64 KB
/
service.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
package main
import (
"sort"
"strings"
)
//将表名赋值给结构对象, 供其它方法使用
func (m *ModelS) GetTableNameAndComment() (err error) {
//读取所有表列表
if len(m.Tables) == 0 {
m.Tables, err = m.findDbTables()
if err != nil {
return
}
}
//如果正在处理表数据为空,则将所有的表赋值给它
if len(m.DoTables) == 0 {
m.DoTables = m.Tables
}
return
}
//向数据库里读取所有的表
func (m *ModelS) findDbTables() (NameAndComment []TableNameAndComment, err error) {
m.l.Lock()
defer m.l.Unlock()
result, err := m.Find("SELECT `TABLE_NAME` AS 'table_name', `TABLE_COMMENT` AS 'table_comment' FROM "+
"information_schema.tables WHERE `TABLE_SCHEMA` = ?", m.DBName)
if err != nil {
return
}
//获取表名 与 表注释
NameAndComment = make([]TableNameAndComment, 0)
//获取库里所有的表名
for idx, info := range result {
idx++
NameAndComment = append(NameAndComment, TableNameAndComment{
Index: idx,
Name: info["table_name"].(string),
Comment: info["table_comment"].(string),
})
}
//排序, 采用升序
sort.Slice(NameAndComment, func(i, j int) bool {
return strings.ToLower(NameAndComment[i].Name) < strings.ToLower(NameAndComment[j].Name)
})
return
}
// 获取表结构详情
func (m *ModelS) GetTableDesc(tableName string) (reply []*TableDesc, err error) {
m.l.Lock()
defer m.l.Unlock()
result, err := m.Find("select `COLUMN_NAME` AS column_name,`DATA_TYPE` AS data_type, `COLUMN_KEY` AS column_key, "+
"`IS_NULLABLE` AS is_nullable, `COLUMN_DEFAULT` AS column_default,`COLUMN_TYPE` AS column_type, `COLUMN_COMMENT` "+
"AS column_comment from information_schema.columns where table_name = ? and table_schema = ?",
tableName, m.DBName)
if err != nil {
return
}
reply = make([]*TableDesc, 0)
i := 0
for _, row := range result {
var keyBool bool
if strings.ToUpper(row["column_key"].(string)) == "PRI" {
keyBool = true
}
oriType := row["data_type"].(string)
var columnDefault string
val, ok := row["column_default"].(string)
if ok {
columnDefault = val
}
reply = append(reply, &TableDesc{
Index: i,
ColumnName: row["column_name"].(string),
GoColumnName: m.T.Capitalize(row["column_name"].(string)),
OriMysqlType: oriType,
UpperMysqlType: strings.ToUpper(oriType),
GolangType: MysqlTypeToGoType[oriType],
MysqlNullType: MysqlTypeToGoNullType[oriType],
ColumnComment: row["column_comment"].(string),
IsNull: row["is_nullable"].(string),
DefaultValue: columnDefault,
ColumnTypeNumber: row["column_type"].(string),
PrimaryKey: keyBool,
})
i++
}
return
}