-
Notifications
You must be signed in to change notification settings - Fork 1
/
table_meta_cache.go
263 lines (227 loc) · 7.91 KB
/
table_meta_cache.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
package mysql
import (
"database/sql"
"database/sql/driver"
"fmt"
"strings"
"time"
"github.com/google/go-cmp/cmp"
"github.com/patrickmn/go-cache"
"github.com/pkg/errors"
"github.com/cectc/mysql/schema"
)
var EXPIRE_TIME = 15 * time.Minute
var tableMetaCaches map[string]*TableMetaCache = make(map[string]*TableMetaCache, 0)
type TableMetaCache struct {
tableMetaCache *cache.Cache
dbName string
}
func InitTableMetaCache(dbName string) {
tableMetaCache := &TableMetaCache{
tableMetaCache: cache.New(EXPIRE_TIME, 10*EXPIRE_TIME),
dbName: dbName,
}
tableMetaCaches[dbName] = tableMetaCache
}
func GetTableMetaCache(dbName string) *TableMetaCache {
return tableMetaCaches[dbName]
}
func (cache *TableMetaCache) GetTableMeta(conn *mysqlConn, tableName string) (schema.TableMeta, error) {
if tableName == "" {
return schema.TableMeta{}, errors.New("TableMeta cannot be fetched without tableName")
}
cacheKey := cache.GetCacheKey(tableName)
tMeta, found := cache.tableMetaCache.Get(cacheKey)
if found {
meta := tMeta.(schema.TableMeta)
return meta, nil
} else {
meta, err := cache.FetchSchema(conn, tableName)
if err != nil {
return schema.TableMeta{}, errors.WithStack(err)
}
cache.tableMetaCache.Set(cacheKey, meta, EXPIRE_TIME)
return meta, nil
}
}
func (cache *TableMetaCache) Refresh(conn *mysqlConn, resourceID string) {
for k, v := range cache.tableMetaCache.Items() {
meta := v.Object.(schema.TableMeta)
key := cache.GetCacheKey(meta.TableName)
if k == key {
tMeta, err := cache.FetchSchema(conn, meta.TableName)
if err != nil {
errLog.Print("get table meta error:%s", err.Error())
}
if !cmp.Equal(tMeta, meta) {
cache.tableMetaCache.Set(key, tMeta, EXPIRE_TIME)
}
}
}
}
func (cache *TableMetaCache) GetCacheKey(tableName string) string {
return fmt.Sprintf("%s.%s", cache.dbName, escape(tableName, "`"))
}
func (cache *TableMetaCache) FetchSchema(conn *mysqlConn, tableName string) (schema.TableMeta, error) {
tm := schema.TableMeta{TableName: tableName,
AllColumns: make(map[string]schema.ColumnMeta),
AllIndexes: make(map[string]schema.IndexMeta),
}
columnMetas, err := GetColumns(conn, cache.dbName, tableName)
if err != nil {
return schema.TableMeta{}, errors.Wrapf(err, "Could not found any index in the table: %s", tableName)
}
columns := make([]string, 0)
for _, column := range columnMetas {
tm.AllColumns[column.ColumnName] = column
columns = append(columns, column.ColumnName)
}
tm.Columns = columns
indexes, err := GetIndexes(conn, cache.dbName, tableName)
if err != nil {
return schema.TableMeta{}, errors.Wrapf(err, "Could not found any index in the table: %s", tableName)
}
for _, index := range indexes {
col := tm.AllColumns[index.ColumnName]
idx, ok := tm.AllIndexes[index.IndexName]
if ok {
idx.Values = append(idx.Values, col)
} else {
index.Values = append(index.Values, col)
tm.AllIndexes[index.IndexName] = index
}
}
if len(tm.AllIndexes) == 0 {
return schema.TableMeta{}, errors.Errorf("Could not found any index in the table: %s", tableName)
}
return tm, nil
}
func GetColumns(conn *mysqlConn, dbName, tableName string) ([]schema.ColumnMeta, error) {
var tn = escape(tableName, "`")
args := []driver.Value{dbName, tn}
//`TABLE_CATALOG`, `TABLE_SCHEMA`, `TABLE_NAME`, `COLUMN_NAME`, `ORDINAL_POSITION`, `COLUMN_DEFAULT`,
//`IS_NULLABLE`, `DATA_TYPE`, `CHARACTER_MAXIMUM_LENGTH`, `CHARACTER_OCTET_LENGTH`, `NUMERIC_PRECISION`,
//`NUMERIC_SCALE`, `DATETIME_PRECISION`, `CHARACTER_SET_NAME`, `COLLATION_NAME`, `COLUMN_TYPE`, `COLUMN_KEY',
//`EXTRA`, `PRIVILEGES`, `COLUMN_COMMENT`, `GENERATION_EXPRESSION`, `SRS_ID`
s := "SELECT `TABLE_CATALOG`, `TABLE_SCHEMA`, `TABLE_NAME`, `COLUMN_NAME`, `DATA_TYPE`, `CHARACTER_MAXIMUM_LENGTH`, " +
"`NUMERIC_PRECISION`, `NUMERIC_SCALE`, `IS_NULLABLE`, `COLUMN_COMMENT`, `COLUMN_DEFAULT`, `CHARACTER_OCTET_LENGTH`, " +
"`ORDINAL_POSITION`, `COLUMN_KEY`, `EXTRA` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA` = ? AND " +
"`TABLE_NAME` = ? ORDER BY ORDINAL_POSITION ASC"
rows, err := conn.prepareQuery(s, args)
if err != nil {
return nil, err
}
defer rows.Close()
result := make([]schema.ColumnMeta, 0)
var tableCat, tScheme, tName, columnName, dataType, isNullable, remark, colDefault, colKey, extra sql.NullString
var columnSize, decimalDigits, numPreRadix, charOctetLength, ordinalPosition sql.NullInt32
vals := make([]driver.Value, 15)
dest := []interface{}{
&tableCat, &tScheme, &tName, &columnName, &dataType,
&columnSize, &decimalDigits, &numPreRadix, &isNullable,
&remark, &colDefault, &charOctetLength, &ordinalPosition,
&colKey, &extra,
}
for {
err := rows.Next(vals)
if err != nil {
break
}
for i, sv := range vals {
err := convertAssignRows(dest[i], sv)
if err != nil {
return nil, fmt.Errorf(`sql: Scan error on column index %d, name %q: %v`, i, rows.Columns()[i], err)
}
}
col := schema.ColumnMeta{}
col.TableCat = tableCat.String
col.TableSchemeName = tScheme.String
col.TableName = tName.String
col.ColumnName = strings.Trim(columnName.String, "` ")
col.DataTypeName = dataType.String
col.DataType = GetSqlDataType(dataType.String)
col.ColumnSize = columnSize.Int32
col.DecimalDigits = decimalDigits.Int32
col.NumPrecRadix = numPreRadix.Int32
col.IsNullable = isNullable.String
if strings.ToLower(isNullable.String) == "yes" {
col.Nullable = 1
} else {
col.Nullable = 0
}
col.Remarks = remark.String
col.ColumnDef = colDefault.String
col.SqlDataType = 0
col.SqlDatetimeSub = 0
col.CharOctetLength = charOctetLength.Int32
col.OrdinalPosition = ordinalPosition.Int32
col.IsAutoIncrement = extra.String
result = append(result, col)
}
return result, nil
}
func GetIndexes(conn *mysqlConn, dbName, tableName string) ([]schema.IndexMeta, error) {
var tn = escape(tableName, "`")
args := []driver.Value{dbName, tn}
//`TABLE_CATALOG`, `TABLE_SCHEMA`, `TABLE_NAME`, `NON_UNIQUE`, `INDEX_SCHEMA`, `INDEX_NAME`, `SEQ_IN_INDEX`,
//`COLUMN_NAME`, `COLLATION`, `CARDINALITY`, `SUB_PART`, `PACKED`, `NULLABLE`, `INDEX_TYPE`, `COMMENT`,
//`INDEX_COMMENT`, `IS_VISIBLE`, `EXPRESSION`
s := "SELECT `INDEX_NAME`, `COLUMN_NAME`, `NON_UNIQUE`, `INDEX_TYPE`, `SEQ_IN_INDEX`, `COLLATION`, `CARDINALITY` " +
"FROM `INFORMATION_SCHEMA`.`STATISTICS` WHERE `TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?"
rows, err := conn.prepareQuery(s, args)
if err != nil {
return nil, err
}
defer rows.Close()
result := make([]schema.IndexMeta, 0)
var indexName, columnName, nonUnique, indexType, collation sql.NullString
var ordinalPosition, cardinality sql.NullInt32
vals := make([]driver.Value, 7)
dest := []interface{}{
&indexName, &columnName, &nonUnique, &indexType,
&ordinalPosition, &collation, &cardinality,
}
for {
err := rows.Next(vals)
if err != nil {
break
}
for i, sv := range vals {
err := convertAssignRows(dest[i], sv)
if err != nil {
return nil, fmt.Errorf(`sql: Scan error on column index %d, name %q: %v`, i, rows.Columns()[i], err)
}
}
index := schema.IndexMeta{
Values: make([]schema.ColumnMeta, 0),
}
index.IndexName = indexName.String
index.ColumnName = columnName.String
if "yes" == strings.ToLower(nonUnique.String) || nonUnique.String == "1" {
index.NonUnique = true
}
index.OrdinalPosition = ordinalPosition.Int32
index.AscOrDesc = collation.String
index.Cardinality = cardinality.Int32
if "primary" == strings.ToLower(indexName.String) {
index.IndexType = schema.IndexType_PRIMARY
} else if !index.NonUnique {
index.IndexType = schema.IndexType_UNIQUE
} else {
index.IndexType = schema.IndexType_NORMAL
}
result = append(result, index)
}
return result, nil
}
func escape(tableName, cutset string) string {
var tn = tableName
if strings.Contains(tableName, ".") {
idx := strings.LastIndex(tableName, ".")
tName := tableName[idx+1:]
tn = strings.Trim(tName, cutset)
} else {
tn = strings.Trim(tableName, cutset)
}
return tn
}