show.go 18.3 KB
Newer Older
martianzhang's avatar
martianzhang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*
 * Copyright 2018 Xiaomi, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package database

import (
	"fmt"
	"regexp"
	"strconv"
	"strings"
24 25

	"github.com/XiaoMi/soar/common"
martianzhang's avatar
martianzhang 已提交
26 27 28 29 30 31 32 33 34 35 36 37
)

// SHOW TABLE STATUS Syntax
// https://dev.mysql.com/doc/refman/5.7/en/show-table-status.html

// TableStatInfo 用以保存 show table status 之后获取的table信息
type TableStatInfo struct {
	Name string
	Rows []tableStatusRow
}

// tableStatusRow 用于 show table status value
38
// use []byte instead of string, because []byte allow to be null, string not
martianzhang's avatar
martianzhang 已提交
39 40
type tableStatusRow struct {
	Name         string // 表名
41 42 43
	Engine       []byte // 该表使用的存储引擎
	Version      []byte // 该表的 .frm 文件版本号
	RowFormat    []byte // 该表使用的行存储格式
44 45
	Rows         uint64 // 表行数, InnoDB 引擎中为预估值,甚至可能会有40%~50%的数值偏差
	AvgRowLength uint64 // 平均行长度
martianzhang's avatar
martianzhang 已提交
46 47 48 49

	// MyISAM: Data_length 为数据文件的大小,单位为 bytes
	// InnoDB: Data_length 为聚簇索引分配的近似内存量,单位为 bytes, 计算方式为聚簇索引数量乘以 InnoDB 页面大小
	// 其他不同的存储引擎中该值的意义可能不尽相同
50
	DataLength uint64
martianzhang's avatar
martianzhang 已提交
51 52 53 54

	// MyISAM: Max_data_length 为数据文件长度的最大值。这是在给定使用的数据指针大小的情况下,可以存储在表中的数据的最大字节数
	// InnoDB: 未使用
	// 其他不同的存储引擎中该值的意义可能不尽相同
55
	MaxDataLength uint64
martianzhang's avatar
martianzhang 已提交
56 57 58 59

	// MyISAM: Index_length 为 index 文件的大小,单位为 bytes
	// InnoDB: Index_length 为非聚簇索引分配的近似内存量,单位为 bytes,计算方式为非聚簇索引数量乘以 InnoDB 页面大小
	// 其他不同的存储引擎中该值的意义可能不尽相同
60
	IndexLength uint64
martianzhang's avatar
martianzhang 已提交
61

62
	DataFree      uint64 // 已分配但未使用的字节数
63 64 65 66 67 68 69 70
	AutoIncrement []byte // 下一个自增值
	CreateTime    []byte // 创建时间
	UpdateTime    []byte // 最近一次更新时间,该值不准确
	CheckTime     []byte // 上次检查时间
	Collation     []byte // 字符集及排序规则信息
	Checksum      []byte // 校验和
	CreateOptions []byte // 创建表的时候的时候一切其他属性
	Comment       []byte // 注释
martianzhang's avatar
martianzhang 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
}

// newTableStat 构造 table Stat 对象
func newTableStat(tableName string) *TableStatInfo {
	return &TableStatInfo{
		Name: tableName,
		Rows: make([]tableStatusRow, 0),
	}
}

// ShowTables 执行 show tables
func (db *Connector) ShowTables() ([]string, error) {
	defer func() {
		err := recover()
		if err != nil {
86
			common.Log.Error("recover ShowTables()", err)
martianzhang's avatar
martianzhang 已提交
87 88 89 90 91 92 93 94 95 96 97
		}
	}()

	// 执行 show table status
	res, err := db.Query("show tables")
	if err != nil {
		return []string{}, err
	}

	// 获取值
	var tables []string
98 99 100 101
	for res.Rows.Next() {
		var table string
		err = res.Rows.Scan(&table)
		if err != nil {
martianzhang's avatar
martianzhang 已提交
102
			break
103 104
		}
		tables = append(tables, table)
martianzhang's avatar
martianzhang 已提交
105
	}
martianzhang's avatar
martianzhang 已提交
106
	res.Rows.Close()
martianzhang's avatar
martianzhang 已提交
107 108 109 110 111 112
	return tables, err
}

// ShowTableStatus 执行 show table status
func (db *Connector) ShowTableStatus(tableName string) (*TableStatInfo, error) {
	// 初始化struct
113
	tbStatus := newTableStat(tableName)
martianzhang's avatar
martianzhang 已提交
114 115

	// 执行 show table status
martianzhang's avatar
martianzhang 已提交
116
	res, err := db.Query(fmt.Sprintf("show table status where name = '%s'", Escape(tbStatus.Name, false)))
martianzhang's avatar
martianzhang 已提交
117
	if err != nil {
118 119
		return tbStatus, err
	}
martianzhang's avatar
martianzhang 已提交
120

121
	// columns info
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
	ts := tableStatusRow{}
	statusFields := make([]interface{}, 0)
	fields := map[string]interface{}{
		"Name":            &ts.Name,
		"Engine":          &ts.Engine,
		"Version":         &ts.Version,
		"Row_format":      &ts.RowFormat,
		"Rows":            &ts.Rows,
		"Avg_row_length":  &ts.AvgRowLength,
		"Data_length":     &ts.DataLength,
		"Max_data_length": &ts.MaxDataLength,
		"Index_length":    &ts.IndexLength,
		"Data_free":       &ts.DataFree,
		"Auto_increment":  &ts.AutoIncrement,
		"Create_time":     &ts.CreateTime,
		"Update_time":     &ts.UpdateTime,
		"Check_time":      &ts.CheckTime,
		"Collation":       &ts.Collation,
		"Checksum":        &ts.Checksum,
		"Create_options":  &ts.CreateOptions,
		"Comment":         &ts.Comment,
	}
	cols, err := res.Rows.Columns()
	common.LogIfError(err, "")
martianzhang's avatar
martianzhang 已提交
146
	var colByPass []byte
147
	for _, col := range cols {
martianzhang's avatar
martianzhang 已提交
148 149 150 151 152 153
		if _, ok := fields[col]; ok {
			statusFields = append(statusFields, fields[col])
		} else {
			common.Log.Debug("ShowTableStatus by pass column %s", col)
			statusFields = append(statusFields, &colByPass)
		}
154
	}
martianzhang's avatar
martianzhang 已提交
155
	// 获取值
156
	for res.Rows.Next() {
157 158 159
		err := res.Rows.Scan(statusFields...)
		if err != nil {
			common.Log.Debug(err.Error())
martianzhang's avatar
martianzhang 已提交
160
		}
161
		tbStatus.Rows = append(tbStatus.Rows, ts)
martianzhang's avatar
martianzhang 已提交
162
	}
martianzhang's avatar
martianzhang 已提交
163
	res.Rows.Close()
164
	return tbStatus, err
martianzhang's avatar
martianzhang 已提交
165 166 167 168 169 170 171
}

// https://dev.mysql.com/doc/refman/5.7/en/show-index.html

// TableIndexInfo 用以保存 show index 之后获取的 index 信息
type TableIndexInfo struct {
	TableName string
172
	Rows      []TableIndexRow
martianzhang's avatar
martianzhang 已提交
173 174
}

martianzhang's avatar
martianzhang 已提交
175
// TableIndexRow 用以存放show index 之后获取的每一条 index 信息
martianzhang's avatar
martianzhang 已提交
176 177 178 179 180 181 182 183 184 185 186 187 188 189
type TableIndexRow struct {
	Table        string // 表名
	NonUnique    int    // 0:unique key,1:not unique
	KeyName      string // index的名称,如果是主键则为 "PRIMARY"
	SeqInIndex   int    // 该列在索引中的位置。计数从 1 开始
	ColumnName   string // 列名
	Collation    string // A or Null
	Cardinality  int    // 索引中唯一值的数量,"ANALYZE TABLE" 可更新该值
	SubPart      int    // 索引前缀字节数
	Packed       int
	Null         string // 表示该列是否可以为空,如果可以为 'YES',反之''
	IndexType    string // BTREE, FULLTEXT, HASH, RTREE
	Comment      string
	IndexComment string
190
	Visible      string
191
	Expression   []byte
martianzhang's avatar
martianzhang 已提交
192 193 194 195 196 197
}

// NewTableIndexInfo 构造 TableIndexInfo
func NewTableIndexInfo(tableName string) *TableIndexInfo {
	return &TableIndexInfo{
		TableName: tableName,
198
		Rows:      make([]TableIndexRow, 0),
martianzhang's avatar
martianzhang 已提交
199 200 201 202 203 204 205
	}
}

// ShowIndex show Index
func (db *Connector) ShowIndex(tableName string) (*TableIndexInfo, error) {
	tbIndex := NewTableIndexInfo(tableName)

206 207 208 209
	if db.Database == "" || tableName == "" {
		return nil, fmt.Errorf("database('%s') or table('%s') name should not empty", db.Database, tableName)
	}

martianzhang's avatar
martianzhang 已提交
210
	// 执行 show create table
martianzhang's avatar
martianzhang 已提交
211
	res, err := db.Query(fmt.Sprintf("show index from `%s`.`%s`", Escape(db.Database, false), Escape(tableName, false)))
martianzhang's avatar
martianzhang 已提交
212 213 214 215
	if err != nil {
		return nil, err
	}

216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
	// columns info
	ti := TableIndexRow{}
	indexFields := make([]interface{}, 0)
	fields := map[string]interface{}{
		"Table":         &ti.Table,
		"Non_unique":    &ti.NonUnique,
		"Key_name":      &ti.KeyName,
		"Seq_in_index":  &ti.SeqInIndex,
		"Column_name":   &ti.ColumnName,
		"Collation":     &ti.Collation,
		"Cardinality":   &ti.Cardinality,
		"Sub_part":      &ti.SubPart,
		"Packed":        &ti.Packed,
		"Null":          &ti.Null,
		"Index_type":    &ti.IndexType,
		"Comment":       &ti.Comment,
		"Index_comment": &ti.IndexComment,
		"Visible":       &ti.Visible,
		"Expression":    &ti.Expression,
	}
	cols, err := res.Rows.Columns()
	common.LogIfError(err, "")
martianzhang's avatar
martianzhang 已提交
238
	var colByPass []byte
239
	for _, col := range cols {
martianzhang's avatar
martianzhang 已提交
240 241 242 243 244 245
		if _, ok := fields[col]; ok {
			indexFields = append(indexFields, fields[col])
		} else {
			common.Log.Debug("ShowIndex by pass column %s", col)
			indexFields = append(indexFields, &colByPass)
		}
246
	}
martianzhang's avatar
martianzhang 已提交
247
	// 获取值
248
	for res.Rows.Next() {
249 250 251
		err := res.Rows.Scan(indexFields...)
		if err != nil {
			common.Log.Debug(err.Error())
martianzhang's avatar
martianzhang 已提交
252
		}
253
		tbIndex.Rows = append(tbIndex.Rows, ti)
martianzhang's avatar
martianzhang 已提交
254
	}
martianzhang's avatar
martianzhang 已提交
255
	res.Rows.Close()
martianzhang's avatar
martianzhang 已提交
256 257 258 259 260 261 262 263 264 265 266 267 268 269
	return tbIndex, err
}

// IndexSelectKey 用以对 TableIndexInfo 进行查询
type IndexSelectKey string

// 索引相关
const (
	IndexKeyName    = IndexSelectKey("KeyName")    // 索引名称
	IndexColumnName = IndexSelectKey("ColumnName") // 索引列名称
	IndexIndexType  = IndexSelectKey("IndexType")  // 索引类型
	IndexNonUnique  = IndexSelectKey("NonUnique")  // 唯一索引
)

270
// FindIndex 获取 TableIndexInfo 中需要的索引
martianzhang's avatar
martianzhang 已提交
271 272 273 274 275 276 277 278 279 280
func (tbIndex *TableIndexInfo) FindIndex(arg IndexSelectKey, value string) []TableIndexRow {
	var result []TableIndexRow
	if tbIndex == nil {
		return result
	}

	value = strings.ToLower(value)

	switch arg {
	case IndexKeyName:
281
		for _, index := range tbIndex.Rows {
martianzhang's avatar
martianzhang 已提交
282 283 284 285 286 287
			if strings.ToLower(index.KeyName) == value {
				result = append(result, index)
			}
		}

	case IndexColumnName:
288
		for _, index := range tbIndex.Rows {
martianzhang's avatar
martianzhang 已提交
289 290 291 292 293 294
			if strings.ToLower(index.ColumnName) == value {
				result = append(result, index)
			}
		}

	case IndexIndexType:
295
		for _, index := range tbIndex.Rows {
martianzhang's avatar
martianzhang 已提交
296 297 298 299 300 301
			if strings.ToLower(index.IndexType) == value {
				result = append(result, index)
			}
		}

	case IndexNonUnique:
302
		for _, index := range tbIndex.Rows {
martianzhang's avatar
martianzhang 已提交
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
			unique := strconv.Itoa(index.NonUnique)
			if unique == value {
				result = append(result, index)
			}
		}

	default:
		common.Log.Error("no such args: TableIndexRow")
	}

	return result
}

// desc table
// https://dev.mysql.com/doc/refman/5.7/en/show-columns.html

// TableDesc show columns from rental;
type TableDesc struct {
	Name       string
	DescValues []TableDescValue
}

// TableDescValue 含有每一列的属性
type TableDescValue struct {
	Field      string // 列名
	Type       string // 数据类型
329
	Collation  []byte // 字符集
martianzhang's avatar
martianzhang 已提交
330 331
	Null       string // 是否有NULL(NO、YES)
	Key        string // 键类型
332
	Default    []byte // 默认值
martianzhang's avatar
martianzhang 已提交
333
	Extra      string // 其他
334
	Privileges string // 权限
martianzhang's avatar
martianzhang 已提交
335 336 337 338 339 340 341 342 343 344 345
	Comment    string // 备注
}

// NewTableDesc 初始化一个*TableDesc
func NewTableDesc(tableName string) *TableDesc {
	return &TableDesc{
		Name:       tableName,
		DescValues: make([]TableDescValue, 0),
	}
}

martianzhang's avatar
martianzhang 已提交
346
// ShowColumns 获取 DB 中所有的 columns
martianzhang's avatar
martianzhang 已提交
347 348 349 350
func (db *Connector) ShowColumns(tableName string) (*TableDesc, error) {
	tbDesc := NewTableDesc(tableName)

	// 执行 show create table
martianzhang's avatar
martianzhang 已提交
351
	res, err := db.Query(fmt.Sprintf("show full columns from `%s`.`%s`", Escape(db.Database, false), Escape(tableName, false)))
martianzhang's avatar
martianzhang 已提交
352 353 354 355
	if err != nil {
		return nil, err
	}

356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
	// columns info
	tc := TableDescValue{}
	columnFields := make([]interface{}, 0)
	fields := map[string]interface{}{
		"Field":      &tc.Field,
		"Type":       &tc.Type,
		"Collation":  &tc.Collation,
		"Null":       &tc.Null,
		"Key":        &tc.Key,
		"Default":    &tc.Default,
		"Extra":      &tc.Extra,
		"Privileges": &tc.Privileges,
		"Comment":    &tc.Comment,
	}
	cols, err := res.Rows.Columns()
	common.LogIfError(err, "")
martianzhang's avatar
martianzhang 已提交
372
	var colByPass []byte
373
	for _, col := range cols {
martianzhang's avatar
martianzhang 已提交
374 375 376 377 378 379
		if _, ok := fields[col]; ok {
			columnFields = append(columnFields, fields[col])
		} else {
			common.Log.Debug("ShowColumns by pass column %s", col)
			columnFields = append(columnFields, &colByPass)
		}
380
	}
martianzhang's avatar
martianzhang 已提交
381
	// 获取值
382
	for res.Rows.Next() {
383 384 385
		err := res.Rows.Scan(columnFields...)
		if err != nil {
			common.Log.Debug(err.Error())
martianzhang's avatar
martianzhang 已提交
386
		}
387
		tbDesc.DescValues = append(tbDesc.DescValues, tc)
martianzhang's avatar
martianzhang 已提交
388
	}
martianzhang's avatar
martianzhang 已提交
389
	res.Rows.Close()
martianzhang's avatar
martianzhang 已提交
390 391 392 393 394 395 396 397 398 399 400 401 402 403
	return tbDesc, err
}

// Columns 用于获取TableDesc中所有列的名称
func (td TableDesc) Columns() []string {
	var cols []string
	for _, col := range td.DescValues {
		cols = append(cols, col.Field)
	}
	return cols
}

// showCreate show create
func (db *Connector) showCreate(createType, name string) (string, error) {
martianzhang's avatar
martianzhang 已提交
404 405 406 407 408 409 410
	// SHOW CREATE DATABASE db_name
	// SHOW CREATE EVENT event_name
	// SHOW CREATE FUNCTION func_name
	// SHOW CREATE PROCEDURE proc_name
	// SHOW CREATE TABLE tbl_name
	// SHOW CREATE TRIGGER trigger_name
	// SHOW CREATE VIEW view_name
martianzhang's avatar
martianzhang 已提交
411
	res, err := db.Query(fmt.Sprintf("SHOW CREATE %s `%s`", createType, Escape(name, false)))
martianzhang's avatar
martianzhang 已提交
412 413 414 415
	if err != nil {
		return "", err
	}

martianzhang's avatar
martianzhang 已提交
416 417 418 419
	// columns info
	var create string
	createFields := make([]interface{}, 0)
	fields := map[string]interface{}{
martianzhang's avatar
martianzhang 已提交
420 421 422 423 424 425 426
		"Create View":      &create,
		"Create Table":     &create,
		"Create Database":  &create,
		"Create Event":     &create,
		"Statement":        &create, // show create trigger
		"Create Function":  &create,
		"Create Procedure": &create,
martianzhang's avatar
martianzhang 已提交
427 428 429
	}
	cols, err := res.Rows.Columns()
	common.LogIfError(err, "")
martianzhang's avatar
martianzhang 已提交
430
	var colByPass []byte
martianzhang's avatar
martianzhang 已提交
431
	for _, col := range cols {
martianzhang's avatar
martianzhang 已提交
432 433 434
		if _, ok := fields[col]; ok {
			createFields = append(createFields, fields[col])
		} else {
435
			common.Log.Debug("showCreate Type: %s, Name: %s, by pass column `%s`", createType, name, col)
martianzhang's avatar
martianzhang 已提交
436 437
			createFields = append(createFields, &colByPass)
		}
martianzhang's avatar
martianzhang 已提交
438 439
	}

martianzhang's avatar
martianzhang 已提交
440
	// 获取 CREATE 语句
441
	for res.Rows.Next() {
442 443 444 445
		err := res.Rows.Scan(createFields...)
		if err != nil {
			common.Log.Debug(err.Error())
		}
martianzhang's avatar
martianzhang 已提交
446
	}
martianzhang's avatar
martianzhang 已提交
447
	res.Rows.Close()
martianzhang's avatar
martianzhang 已提交
448
	return create, err
martianzhang's avatar
martianzhang 已提交
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
}

// ShowCreateDatabase show create database
func (db *Connector) ShowCreateDatabase(dbName string) (string, error) {
	defer func() {
		err := recover()
		if err != nil {
			common.Log.Error("recover ShowCreateDatabase()", err)
		}
	}()
	return db.showCreate("database", dbName)
}

// ShowCreateTable show create table
func (db *Connector) ShowCreateTable(tableName string) (string, error) {
	defer func() {
		err := recover()
		if err != nil {
			common.Log.Error("recover ShowCreateTable()", err)
		}
	}()

471
	ddl, err := db.showCreate("TABLE", tableName)
martianzhang's avatar
martianzhang 已提交
472 473

	// 去除外键关联条件
martianzhang's avatar
martianzhang 已提交
474 475 476 477 478 479 480 481
	lines := strings.Split(ddl, "\n")
	// CREATE VIEW ONLY 1 LINE
	if len(lines) > 2 {
		var noConstraint []string
		relationReg, _ := regexp.Compile("CONSTRAINT")
		for _, line := range lines[1 : len(lines)-1] {
			if relationReg.Match([]byte(line)) {
				continue
martianzhang's avatar
martianzhang 已提交
482
			}
martianzhang's avatar
martianzhang 已提交
483 484
			line = strings.TrimSuffix(line, ",")
			noConstraint = append(noConstraint, line)
martianzhang's avatar
martianzhang 已提交
485 486
		}

martianzhang's avatar
martianzhang 已提交
487 488 489 490 491 492
		// 去除外键语句会使DDL中多一个','导致语法错误,要把多余的逗号去除
		ddl = fmt.Sprint(
			lines[0], "\n",
			strings.Join(noConstraint, ",\n"), "\n",
			lines[len(lines)-1],
		)
martianzhang's avatar
martianzhang 已提交
493
	}
martianzhang's avatar
martianzhang 已提交
494
	return ddl, err
martianzhang's avatar
martianzhang 已提交
495 496 497 498 499 500 501 502
}

// FindColumn find column
func (db *Connector) FindColumn(name, dbName string, tables ...string) ([]*common.Column, error) {
	// 执行 show create table
	var columns []*common.Column
	sql := fmt.Sprintf("SELECT "+
		"c.TABLE_NAME,c.TABLE_SCHEMA,c.COLUMN_TYPE,c.CHARACTER_SET_NAME, c.COLLATION_NAME "+
martianzhang's avatar
martianzhang 已提交
503
		"FROM `INFORMATION_SCHEMA`.`COLUMNS` as c where c.COLUMN_NAME = '%s' ", Escape(name, false))
martianzhang's avatar
martianzhang 已提交
504

505
	if dbName != "" {
martianzhang's avatar
martianzhang 已提交
506
		sql += fmt.Sprintf(" and c.table_schema = '%s'", Escape(dbName, false))
507 508
	}

martianzhang's avatar
martianzhang 已提交
509 510 511
	if len(tables) > 0 {
		var tmp []string
		for _, table := range tables {
martianzhang's avatar
martianzhang 已提交
512
			tmp = append(tmp, "'"+Escape(table, false)+"'")
martianzhang's avatar
martianzhang 已提交
513
		}
martianzhang's avatar
martianzhang 已提交
514
		sql += fmt.Sprintf(" and c.table_name in (%s)", strings.Join(tmp, ","))
martianzhang's avatar
martianzhang 已提交
515 516
	}

517
	common.Log.Debug("FindColumn, execute SQL: %s", sql)
martianzhang's avatar
martianzhang 已提交
518 519 520 521 522 523
	res, err := db.Query(sql)
	if err != nil {
		common.Log.Error("(db *Connector) FindColumn Error : ", err)
		return columns, err
	}

524 525
	var col common.Column
	for res.Rows.Next() {
martianzhang's avatar
martianzhang 已提交
526
		var character, collation []byte
martianzhang's avatar
martianzhang 已提交
527 528 529 530
		err = res.Rows.Scan(&col.Table, &col.DB, &col.DataType, &character, &collation)
		if err != nil {
			break
		}
martianzhang's avatar
martianzhang 已提交
531 532 533
		col.Name = name
		col.Character = string(character)
		col.Collation = string(collation)
martianzhang's avatar
martianzhang 已提交
534 535
		// 填充字符集和排序规则
		if col.Character == "" {
martianzhang's avatar
martianzhang 已提交
536 537 538
			// 当从 `INFORMATION_SCHEMA`.`COLUMNS` 表中查询不到相关列的 character 和 collation 的信息时
			// 认为该列使用的 character 和 collation 与其所处的表一致
			// 由于 `INFORMATION_SCHEMA`.`TABLES` 表中未找到表的 character,所以从按照 MySQL 中 collation 的规则从中截取 character
martianzhang's avatar
martianzhang 已提交
539 540

			sql = fmt.Sprintf("SELECT `t`.`TABLE_COLLATION` FROM `INFORMATION_SCHEMA`.`TABLES` AS `t` "+
martianzhang's avatar
martianzhang 已提交
541
				"WHERE `t`.`TABLE_NAME`='%s' AND `t`.`TABLE_SCHEMA` = '%s'", Escape(col.Table, false), Escape(col.DB, false))
542 543 544

			common.Log.Debug("FindColumn, execute SQL: %s", sql)
			var newRes QueryResult
martianzhang's avatar
martianzhang 已提交
545 546 547 548 549 550
			newRes, err = db.Query(sql)
			if err != nil {
				common.Log.Error("(db *Connector) FindColumn Error : ", err)
				return columns, err
			}

551
			var tbCollation []byte
552
			if newRes.Rows.Next() {
martianzhang's avatar
martianzhang 已提交
553 554 555 556
				err = newRes.Rows.Scan(&tbCollation)
				if err != nil {
					break
				}
557
			}
martianzhang's avatar
martianzhang 已提交
558
			newRes.Rows.Close()
559 560 561
			if string(tbCollation) != "" {
				col.Character = strings.Split(string(tbCollation), "_")[0]
				col.Collation = string(tbCollation)
martianzhang's avatar
martianzhang 已提交
562 563
			}
		}
564
		columns = append(columns, &col)
martianzhang's avatar
martianzhang 已提交
565
	}
martianzhang's avatar
martianzhang 已提交
566
	res.Rows.Close()
martianzhang's avatar
martianzhang 已提交
567 568 569
	return columns, err
}

570 571
// IsForeignKey 判断列是否是外键
func (db *Connector) IsForeignKey(dbName, tbName, column string) bool {
martianzhang's avatar
martianzhang 已提交
572 573 574 575
	sql := fmt.Sprintf("SELECT REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE C "+
		"WHERE REFERENCED_TABLE_SCHEMA <> 'NULL' AND"+
		" TABLE_NAME='%s' AND"+
		" TABLE_SCHEMA='%s' AND"+
martianzhang's avatar
martianzhang 已提交
576
		" COLUMN_NAME='%s'", Escape(tbName, false), Escape(dbName, false), Escape(column, false))
martianzhang's avatar
martianzhang 已提交
577

578
	common.Log.Debug("IsForeignKey, execute SQL: %s", sql)
martianzhang's avatar
martianzhang 已提交
579
	res, err := db.Query(sql)
580 581 582 583 584 585 586
	if err != nil {
		common.Log.Error("IsForeignKey, Error: %s", err.Error())
		return false
	}
	if res.Rows.Next() {
		return true
	}
martianzhang's avatar
martianzhang 已提交
587

588
	return false
martianzhang's avatar
martianzhang 已提交
589 590 591 592 593 594 595
}

// Reference 用于存储关系
type Reference map[string][]ReferenceValue

// ReferenceValue 用于处理表之间的关系
type ReferenceValue struct {
596 597 598 599 600
	ReferencedTableSchema string // 夫表所属数据库
	ReferencedTableName   string // 父表
	TableSchema           string // 子表所属数据库
	TableName             string // 子表
	ConstraintName        string // 关系名称
martianzhang's avatar
martianzhang 已提交
601 602 603 604 605
}

// ShowReference 查找所有的外键信息
func (db *Connector) ShowReference(dbName string, tbName ...string) ([]ReferenceValue, error) {
	var referenceValues []ReferenceValue
606
	sql := `SELECT DISTINCT C.REFERENCED_TABLE_SCHEMA,C.REFERENCED_TABLE_NAME,C.TABLE_SCHEMA,C.TABLE_NAME,C.CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE C JOIN INFORMATION_SCHEMA. TABLES T ON T.TABLE_NAME = C.TABLE_NAME WHERE C.REFERENCED_TABLE_NAME IS NOT NULL`
martianzhang's avatar
martianzhang 已提交
607
	sql = sql + fmt.Sprintf(` AND C.TABLE_SCHEMA = "%s"`, Escape(dbName, false))
martianzhang's avatar
martianzhang 已提交
608

martianzhang's avatar
martianzhang 已提交
609 610
	var tables []string
	for _, tb := range tbName {
martianzhang's avatar
martianzhang 已提交
611
		tables = append(tables, "'"+Escape(tb, false)+"'")
martianzhang's avatar
martianzhang 已提交
612
	}
martianzhang's avatar
martianzhang 已提交
613
	if len(tbName) > 0 {
martianzhang's avatar
martianzhang 已提交
614
		extra := fmt.Sprintf(` AND C.TABLE_NAME IN ("%s")`, strings.Join(tables, ","))
martianzhang's avatar
martianzhang 已提交
615 616 617
		sql = sql + extra
	}

618
	common.Log.Debug("ShowReference, execute SQL: %s", sql)
martianzhang's avatar
martianzhang 已提交
619 620 621 622 623 624 625
	// 执行SQL查找外键关联关系
	res, err := db.Query(sql)
	if err != nil {
		return referenceValues, err
	}

	// 获取值
626 627
	for res.Rows.Next() {
		var rv ReferenceValue
martianzhang's avatar
martianzhang 已提交
628 629 630 631
		err = res.Rows.Scan(&rv.ReferencedTableSchema, &rv.ReferencedTableName, &rv.TableSchema, &rv.TableName, &rv.ConstraintName)
		if err != nil {
			break
		}
632
		referenceValues = append(referenceValues, rv)
martianzhang's avatar
martianzhang 已提交
633
	}
martianzhang's avatar
martianzhang 已提交
634
	res.Rows.Close()
martianzhang's avatar
martianzhang 已提交
635 636
	return referenceValues, err
}