database

package
Version: v0.8.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 23, 2018 License: Apache-2.0 Imports: 17 Imported by: 29

Documentation

Overview

Package database will take cover of communicate with mysql database.

Index

Constants

View Source
const (
	TraditionalFormatExplain = iota // 默认输出
	JSONFormatExplain               // JSON格式输出
)

format_type 支持的输出格式 https://dev.mysql.com/doc/refman/5.7/en/explain-output.html

View Source
const (
	TraditionalExplainType = iota // 默认转出
	ExtendedExplainType           // EXTENDED输出
	PartitionsExplainType         // PARTITIONS输出
)

explain_type

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

索引相关

Variables

View Source
var ExplainAccessType = map[string]string{
	"system":          "这是const连接类型的一种特例, 该表仅有一行数据(=系统表).",
	"const":           `const用于使用常数值比较PRIMARY KEY时, 当查询的表仅有一行时, 使用system. 例:SELECT * FROM tbl WHERE col =1.`,
	"eq_ref":          `除const类型外最好的可能实现的连接类型. 它用在一个索引的所有部分被连接使用并且索引是UNIQUE或PRIMARY KEY, 对于每个索引键, 表中只有一条记录与之匹配. 例:'SELECT * FROM ref_table,tbl WHERE ref_table.key_column=tbl.column;'.`,
	"ref":             `连接不能基于关键字选择单个行, 可能查找到多个符合条件的行. 叫做ref是因为索引要跟某个参考值相比较. 这个参考值或者是一个数, 或者是来自一个表里的多表查询的结果值. 例:'SELECT * FROM tbl WHERE idx_col=expr;'.`,
	"fulltext":        "查询时使用 FULLTEXT 索引.",
	"ref_or_null":     "如同ref, 但是MySQL必须在初次查找的结果里找出null条目, 然后进行二次查找.",
	"index_merge":     `表示使用了索引合并优化方法. 在这种情况下. key列包含了使用的索引的清单, key_len包含了使用的索引的最长的关键元素. 详情请见 8.2.1.4, “Index Merge Optimization”.`,
	"unique_subquery": `在某些IN查询中使用此种类型,而不是常规的ref:'value IN (SELECT primary_key FROM single_table WHERE some_expr)'.`,
	"index_subquery":  "在某些IN查询中使用此种类型, 与unique_subquery类似, 但是查询的是非唯一索引性索引.",
	"range":           `只检索给定范围的行, 使用一个索引来选择行. key列显示使用了哪个索引. key_len包含所使用索引的最长关键元素.`,
	"index":           "全表扫描, 只是扫描表的时候按照索引次序进行而不是行. 主要优点就是避免了排序, 但是开销仍然非常大.",
	"ALL":             `最坏的情况, 从头到尾全表扫描.`,
}

ExplainAccessType EXPLAIN中ACCESS TYPE会出现的类型

View Source
var ExplainColumnIndent = map[string]string{
	"id":            "id为SELECT的标识符. 它是在SELECT查询中的顺序编号. 如果这一行表示其他行的union结果, 这个值可以为空. 在这种情况下, table列会显示为形如<union M,N>, 表示它是id为M和N的查询行的联合结果.",
	"select_type":   "表示查询的类型. ",
	"table":         "输出行所引用的表.",
	"type":          "type显示连接使用的类型, 有关不同类型的描述, 请参见解释连接类型.",
	"possible_keys": "指出MySQL能在该表中使用哪些索引有助于查询. 如果为空, 说明没有可用的索引.",
	"key":           "MySQL实际从possible_keys选择使用的索引. 如果为NULL, 则没有使用索引. 很少情况下, MySQL会选择优化不足的索引. 这种情况下, 可以在select语句中使用USE INDEX (indexname)来强制使用一个索引或者用IGNORE INDEX (indexname)来强制MySQL忽略索引.",
	"key_len":       "显示MySQL使用索引键的长度. 如果key是NULL, 则key_len为NULL. 使用的索引的长度. 在不损失精确性的情况下, 长度越短越好.",
	"ref":           "显示索引的哪一列被使用了.",
	"rows":          "表示MySQL认为必须检查的用来返回请求数据的行数.",
	"filtered":      "表示返回结果的行占需要读到的行(rows列的值)的百分比.",
	"Extra":         "该列显示MySQL在查询过程中的一些详细信息, MySQL查询优化器执行查询的过程中对查询计划的重要补充信息.",
}

ExplainColumnIndent EXPLAIN表头

View Source
var ExplainExtra = map[string]string{
	"Using temporary":                   "表示MySQL在对查询结果排序时使用临时表. 常见于排序order by和分组查询group by.",
	"Using filesort":                    "MySQL会对结果使用一个外部索引排序,而不是从表里按照索引次序读到相关内容. 可能在内存或者磁盘上进行排序. MySQL中无法利用索引完成的排序操作称为'文件排序'.",
	"Using index condition":             "在5.6版本后加入的新特性(Index Condition Pushdown)。Using index condition 会先条件过滤索引,过滤完索引后找到所有符合索引条件的数据行,随后用 WHERE 子句中的其他条件去过滤这些数据行。",
	"Range checked for each record":     "MySQL没有发现好的可以使用的索引,但发现如果来自前面的表的列值已知,可能部分索引可以使用。",
	"Using where with pushed condition": "这是一个仅仅在NDBCluster存储引擎中才会出现的信息,打开condition pushdown优化功能才可能被使用。",
	"Using MRR":                         "使用了 MRR Optimization IO 层面进行了优化,减少 IO 方面的开销。",
	"Skip_open_table":                   "Tables are read using the Multi-Range Read optimization strategy.",
	"Open_frm_only":                     "Table files do not need to be opened. The information is already available from the data dictionary.",
	"Open_full_table":                   "Unoptimized information lookup. Table information must be read from the data dictionary and by reading table files.",
	"Scanned":                           "This indicates how many directory scans the server performs when processing a query for INFORMATION_SCHEMA tables.",
	"Using index for group-by":          "Similar to the Using index table access method, Using index for group-by indicates that MySQL found an index that can be used to retrieve all columns of a GROUP BY or DISTINCT query without any extra disk access to the actual table. Additionally, the index is used in the most efficient way so that for each group, only a few index entries are read.",
	"Start temporary":                   "This indicates temporary table use for the semi-join Duplicate Weedout strategy.Start",
	"End temporary":                     "This indicates temporary table use for the semi-join Duplicate Weedout strategy.End",
	"FirstMatch":                        "The semi-join FirstMatch join shortcutting strategy is used for tbl_name.",
	"Materialize":                       "Materialized subquery",
	"Start materialize":                 "Materialized subquery Start",
	"End materialize":                   "Materialized subquery End",
	"unique row not found":              "For a query such as SELECT ... FROM tbl_name, no rows satisfy the condition for a UNIQUE index or PRIMARY KEY on the table.",

	"Index dive skipped due to FORCE":                     "This item applies to NDB tables only. It means that MySQL Cluster is using the Condition Pushdown optimization to improve the efficiency of a direct comparison between a nonindexed column and a constant. In such cases, the condition is “pushed down” to the cluster's data nodes and is evaluated on all data nodes simultaneously. This eliminates the need to send nonmatching rows over the network, and can speed up such queries by a factor of 5 to 10 times over cases where Condition Pushdown could be but is not used.",
	"Impossible WHERE noticed after reading const tables": "查询了所有const(和system)表, 但发现WHERE查询条件不起作用.",
	"Using where":                              "WHERE条件用于筛选出与下一个表匹配的数据然后返回给客户端. 除非故意做的全表扫描, 否则连接类型是ALL或者是index, 且在Extra列的值中没有Using Where, 则该查询可能是有问题的.",
	"Using join buffer":                        "从已有连接中找被读入缓存的数据, 并且通过缓存来完成与当前表的连接.",
	"Using index":                              "只需通过索引就可以从表中获取列的信息, 无需额外去读取真实的行数据. 如果查询使用的列值仅仅是一个简单索引的部分值, 则会使用这种策略来优化查询.",
	"const row not found":                      "空表做类似 SELECT ... FROM tbl_name 的查询操作.",
	"Distinct":                                 "MySQL is looking for distinct values, so it stops searching for more rows for the current row combination after it has found the first matching row.",
	"Full scan on NULL key":                    "子查询中的一种优化方式, 常见于无法通过索引访问null值.",
	"Impossible HAVING":                        "HAVING条件过滤没有效果, 返回已有查询的结果集.",
	"Impossible WHERE":                         "WHERE条件过滤没有效果, 最终是全表扫描.",
	"LooseScan":                                "使用半连接LooseScan策略.",
	"No matching min/max row":                  "没有行满足查询的条件, 如 SELECT MIN(...) FROM ... WHERE condition.",
	"no matching row in const table":           "对于连接查询, 列未满足唯一索引的条件或表为空.",
	"No matching rows after partition pruning": "对于DELETE 或 UPDATE, 优化器在分区之后, 未发现任何要删除或更新的内容. 类似查询 Impossible WHERE.",
	"No tables used":                           "查询没有FROM子句, 或者有一个 FROM DUAL子句.",
	"Not exists":                               "MySQL能够对LEFT JOIN查询进行优化, 并且在查找到符合LEFT JOIN条件的行后, 则不再查找更多的行.",
	"Plan isn't ready yet":                     "This value occurs with EXPLAIN FOR CONNECTION when the optimizer has not finished creating the execution plan for the statement executing in the named connection. If execution plan output comprises multiple lines, any or all of them could have this Extra value, depending on the progress of the optimizer in determining the full execution plan.",
	"Using intersect":                          "开启了index merge,即:对多个索引分别进行条件扫描,然后将它们各自的结果进行合并,使用的算法为:index_merge_intersection",
	"Using union":                              "开启了index merge,即:对多个索引分别进行条件扫描,然后将它们各自的结果进行合并,使用的算法为:index_merge_union",
	"Using sort_union":                         "开启了index merge,即:对多个索引分别进行条件扫描,然后将它们各自的结果进行合并,使用的算法为:index_merge_sort_union",
}

ExplainExtra Extra信息解读 https://dev.mysql.com/doc/refman/8.0/en/explain-output.html sql/opt_explain_traditional.cc:traditional_extra_tags

View Source
var ExplainFormatType = map[string]int{
	"traditional": 0,
	"json":        1,
}

ExplainFormatType EXPLAIN支持的FORMAT_TYPE

View Source
var ExplainKeyWords = []string{
	"access_type",
	"attached_condition",
	"attached_subqueries",
	"buffer_result",
	"cacheable",
	"cost_info",
	"data_read_per_join",
	"dependent",
	"duplicates_removal",
	"eval_cost",
	"filtered",
	"group_by_subqueries",
	"grouping_operation",
	"having_subqueries",
	"key",
	"key_length",
	"materialized_from_subquery",
	"message",
	"nested_loop",
	"optimized_away_subqueries",
	"order_by_subqueries",
	"ordering_operation",
	"possible_keys",
	"prefix_cost",
	"query_block",
	"query_cost",
	"query_specifications",
	"read_cost",
	"ref",
	"rows_examined_per_scan",
	"rows_produced_per_join",
	"select_id",
	"select_list_subqueries",
	"sort_cost",
	"table",
	"table_name",
	"union_result",
	"update_value_subqueries",
	"used_columns",
	"used_key_parts",
	"using_filesort",
	"using_index",
	"using_index_for_group_by",
	"using_temporary_table",
}

ExplainKeyWords 需要解释的关键字

View Source
var ExplainScalability = map[string]string{
	"ALL":             "O(n)",
	"index":           "O(n)",
	"range":           "O(log n)+",
	"index_subquery":  "O(log n)+",
	"unique_subquery": "O(log n)+",
	"index_merge":     "O(log n)+",
	"ref_or_null":     "O(log n)+",
	"fulltext":        "O(log n)+",
	"ref":             "O(log n)",
	"eq_ref":          "O(log n)",
	"const":           "O(1)",
	"system":          "O(1)",
}

ExplainScalability ACCESS TYPE对应的运算复杂度 [AccessType]scalability map

View Source
var ExplainSelectType = map[string]string{
	"SIMPLE":               "简单SELECT(不使用UNION或子查询等).",
	"PRIMARY":              "最外层的select.",
	"UNION":                "UNION中的第二个或后面的SELECT查询, 不依赖于外部查询的结果集.",
	"DEPENDENT":            "UNION中的第二个或后面的SELECT查询, 依赖于外部查询的结果集.",
	"UNION RESULT":         "UNION查询的结果集.",
	"SUBQUERY":             "子查询中的第一个SELECT查询, 不依赖于外部查询的结果集.",
	"DEPENDENT SUBQUERY":   "子查询中的第一个SELECT查询, 依赖于外部查询的结果集.",
	"DERIVED":              "用于from子句里有子查询的情况. MySQL会递归执行这些子查询, 把结果放在临时表里.",
	"MATERIALIZED":         "Materialized subquery.",
	"UNCACHEABLE SUBQUERY": "结果集不能被缓存的子查询, 必须重新为外层查询的每一行进行评估.",
	"UNCACHEABLE UNION":    "UNION中的第二个或后面的select查询, 属于不可缓存的子查询(类似于UNCACHEABLE SUBQUERY).",
}

ExplainSelectType EXPLAIN中SELECT TYPE会出现的类型

View Source
var ExplainType = map[string]int{
	"traditional": 0,
	"extended":    1,
	"partitions":  2,
}

ExplainType EXPLAIN命令支持的参数

Functions

func ExplainInfoTranslator

func ExplainInfoTranslator(exp *ExplainInfo) string

ExplainInfoTranslator 将explain信息翻译成人能读懂的

func FormatProfiling

func FormatProfiling(res *QueryResult) string

FormatProfiling 格式化输出Profiling信息

func FormatTrace

func FormatTrace(res *QueryResult) string

FormatTrace 格式化输出Trace信息

func MySQLExplainQueryCost

func MySQLExplainQueryCost(exp *ExplainInfo) string

MySQLExplainQueryCost 将last_query_cost信息补充到评审结果中

func MySQLExplainWarnings

func MySQLExplainWarnings(exp *ExplainInfo) string

MySQLExplainWarnings WARNINGS信息中包含的优化器信息

func PrintMarkdownExplainTable

func PrintMarkdownExplainTable(exp *ExplainInfo) string

PrintMarkdownExplainTable 打印markdown格式的explain table

func RemoveSQLComments

func RemoveSQLComments(sql []byte) []byte

RemoveSQLComments 去除SQL中的注释

Types

type Connector

type Connector struct {
	Addr     string
	User     string
	Pass     string
	Database string
	Charset  string
}

Connector 数据库连接基本对象

func (*Connector) ColumnCardinality

func (db *Connector) ColumnCardinality(tb, col string) float64

ColumnCardinality 粒度计算

func (*Connector) Explain

func (db *Connector) Explain(sql string, explainType int, formatType int) (exp *ExplainInfo, err error)

Explain 获取SQL的explain信息

func (*Connector) FindColumn

func (db *Connector) FindColumn(name, dbName string, tables ...string) ([]*common.Column, error)

FindColumn find column

func (*Connector) IsFKey

func (db *Connector) IsFKey(dbName, tbName, column string) bool

IsFKey 判断列是否是外键

func (*Connector) IsView

func (db *Connector) IsView(tbName string) bool

IsView 判断表是否是视图

func (*Connector) NewConnection

func (db *Connector) NewConnection() mysql.Conn

NewConnection 创建新连接

func (*Connector) Profiling

func (db *Connector) Profiling(sql string, params ...interface{}) (*QueryResult, error)

Profiling 执行SQL,并对其Profiling

func (*Connector) Query

func (db *Connector) Query(sql string, params ...interface{}) (*QueryResult, error)

Query 执行SQL

func (*Connector) SamplingData

func (db *Connector) SamplingData(remote Connector, tables ...string) error

SamplingData 将数据从Remote拉取到 db 中

func (*Connector) ShowColumns

func (db *Connector) ShowColumns(tableName string) (*TableDesc, error)

ShowColumns 获取DB中所有的columns

func (*Connector) ShowCreateDatabase

func (db *Connector) ShowCreateDatabase(dbName string) (string, error)

ShowCreateDatabase show create database

func (*Connector) ShowCreateTable

func (db *Connector) ShowCreateTable(tableName string) (string, error)

ShowCreateTable show create table

func (*Connector) ShowIndex

func (db *Connector) ShowIndex(tableName string) (*TableIndexInfo, error)

ShowIndex show Index

func (*Connector) ShowReference

func (db *Connector) ShowReference(dbName string, tbName ...string) ([]ReferenceValue, error)

ShowReference 查找所有的外键信息

func (*Connector) ShowTableStatus

func (db *Connector) ShowTableStatus(tableName string) (*TableStatInfo, error)

ShowTableStatus 执行 show table status

func (*Connector) ShowTables

func (db *Connector) ShowTables() ([]string, error)

ShowTables 执行 show tables

func (*Connector) SingleIntValue

func (db *Connector) SingleIntValue(option string) (int, error)

SingleIntValue 获取某个int型变量的值

func (*Connector) Source

func (db *Connector) Source(file string) ([]*QueryResult, error)

Source execute sql from file

func (*Connector) Trace

func (db *Connector) Trace(sql string, params ...interface{}) (*QueryResult, error)

Trace 执行SQL,并对其Trace

func (*Connector) Version

func (db *Connector) Version() (int, error)

Version 获取MySQL数据库版本

type ExplainInfo

type ExplainInfo struct {
	SQL           string
	ExplainFormat int
	ExplainRows   []*ExplainRow
	ExplainJSON   *ExplainJSON
	Warnings      []*ExplainWarning
	QueryCost     float64
}

ExplainInfo 用于存放Explain信息

func ParseExplainResult

func ParseExplainResult(res *QueryResult, formatType int) (exp *ExplainInfo, err error)

ParseExplainResult 分析mysql执行explain的结果,返回ExplainInfo结构化数据

func ParseExplainText

func ParseExplainText(content string) (exp *ExplainInfo, err error)

ParseExplainText 解析explain文本信息(很可能是用户复制粘贴得到),返回格式化数据

type ExplainJSON

type ExplainJSON struct {
	QueryBlock ExplainJSONQueryBlock `json:"query_block"`
}

ExplainJSON 根结点

type ExplainJSONBufferResult

type ExplainJSONBufferResult struct {
	UsingTemporaryTable bool                    `json:"using_temporary_table"`
	NestedLoop          []ExplainJSONNestedLoop `json:"nested_loop"`
}

ExplainJSONBufferResult JSON

type ExplainJSONCostInfo

type ExplainJSONCostInfo struct {
	ReadCost        string `json:"read_cost"`
	EvalCost        string `json:"eval_cost"`
	PrefixCost      string `json:"prefix_cost"`
	DataReadPerJoin string `json:"data_read_per_join"`
	QueryCost       string `json:"query_cost"`
	SortCost        string `json:"sort_cost"`
}

ExplainJSONCostInfo JSON

type ExplainJSONDuplicatesRemoval

type ExplainJSONDuplicatesRemoval struct {
	UsingTemporaryTable bool                         `json:"using_temporary_table"`
	UsingFilesort       bool                         `json:"using_filesort"`
	BufferResult        ExplainJSONBufferResult      `json:"buffer_result"`
	GroupingOperation   ExplainJSONGroupingOperation `json:"grouping_operation"`
}

ExplainJSONDuplicatesRemoval JSON

type ExplainJSONGroupingOperation

type ExplainJSONGroupingOperation struct {
	UsingTemporaryTable bool                    `json:"using_temporary_table"`
	UsingFilesort       bool                    `json:"using_filesort"`
	Table               ExplainJSONTable        `json:"table"`
	CostInfo            ExplainJSONCostInfo     `json:"cost_info"`
	NestedLoop          []ExplainJSONNestedLoop `json:"nested_loop"`
	GroupBySubqueries   []ExplainJSONSubqueries `json:"group_by_subqueries"`
}

ExplainJSONGroupingOperation JSON

type ExplainJSONMaterializedFromSubquery

type ExplainJSONMaterializedFromSubquery struct {
	UsingTemporaryTable bool                   `json:"using_temporary_table"`
	Dependent           bool                   `json:"dependent"`
	Cacheable           bool                   `json:"cacheable"`
	QueryBlock          *ExplainJSONQueryBlock `json:"query_block"`
}

ExplainJSONMaterializedFromSubquery JSON

type ExplainJSONNestedLoop

type ExplainJSONNestedLoop struct {
	Table ExplainJSONTable `json:"table"`
}

ExplainJSONNestedLoop JSON

type ExplainJSONOrderingOperation

type ExplainJSONOrderingOperation struct {
	UsingFilesort     bool                         `json:"using_filesort"`
	Table             ExplainJSONTable             `json:"table"`
	DuplicatesRemoval ExplainJSONDuplicatesRemoval `json:"duplicates_removal"`
	GroupingOperation ExplainJSONGroupingOperation `json:"grouping_operation"`
	OderbySubqueries  []ExplainJSONSubqueries      `json:"order_by_subqueries"`
}

ExplainJSONOrderingOperation JSON

type ExplainJSONQueryBlock

type ExplainJSONQueryBlock struct {
	SelectID                int                          `json:"select_id"`
	CostInfo                ExplainJSONCostInfo          `json:"cost_info"`
	Table                   ExplainJSONTable             `json:"table"`
	NestedLoop              []ExplainJSONNestedLoop      `json:"nested_loop"`
	OrderingOperation       ExplainJSONOrderingOperation `json:"ordering_operation"`
	GroupingOperation       ExplainJSONGroupingOperation `json:"grouping_operation"`
	OptimizedAwaySubqueries []ExplainJSONSubqueries      `json:"optimized_away_subqueries"`
	HavingSubqueries        []ExplainJSONSubqueries      `json:"having_subqueries"`
	SelectListSubqueries    []ExplainJSONSubqueries      `json:"select_list_subqueries"`
	UpdateValueSubqueries   []ExplainJSONSubqueries      `json:"update_value_subqueries"`
	QuerySpecifications     []ExplainJSONSubqueries      `json:"query_specifications"`
	UnionResult             ExplainJSONUnionResult       `json:"union_result"`
	Message                 string                       `json:"message"`
}

ExplainJSONQueryBlock JSON

type ExplainJSONSubqueries

type ExplainJSONSubqueries struct {
	Dependent  bool                  `json:"dependent"`
	Cacheable  bool                  `json:"cacheable"`
	QueryBlock ExplainJSONQueryBlock `json:"query_block"`
}

ExplainJSONSubqueries JSON

type ExplainJSONTable

type ExplainJSONTable struct {
	TableName                string                              `json:"table_name"`
	AccessType               string                              `json:"access_type"`
	PossibleKeys             []string                            `json:"possible_keys"`
	Key                      string                              `json:"key"`
	UsedKeyParts             []string                            `json:"used_key_parts"`
	KeyLength                string                              `json:"key_length"`
	Ref                      []string                            `json:"ref"`
	RowsExaminedPerScan      int                                 `json:"rows_examined_per_scan"`
	RowsProducedPerJoin      int                                 `json:"rows_produced_per_join"`
	Filtered                 string                              `json:"filtered"`
	UsingIndex               bool                                `json:"using_index"`
	UsingIndexForGroupBy     bool                                `json:"using_index_for_group_by"`
	CostInfo                 ExplainJSONCostInfo                 `json:"cost_info"`
	UsedColumns              []string                            `json:"used_columns"`
	AttachedCondition        string                              `json:"attached_condition"`
	AttachedSubqueries       []ExplainJSONSubqueries             `json:"attached_subqueries"`
	MaterializedFromSubquery ExplainJSONMaterializedFromSubquery `json:"materialized_from_subquery"`
}

ExplainJSONTable JSON

type ExplainJSONUnionResult

type ExplainJSONUnionResult struct {
	UsingTemporaryTable bool                    `json:"using_temporary_table"`
	TableName           string                  `json:"table_name"`
	AccessType          string                  `json:"access_type"`
	QuerySpecifications []ExplainJSONSubqueries `json:"query_specifications"`
}

ExplainJSONUnionResult JSON

type ExplainRow

type ExplainRow struct {
	ID           int
	SelectType   string
	TableName    string
	Partitions   string // explain partitions
	AccessType   string
	PossibleKeys []string
	Key          string
	KeyLen       string // 索引长度,如果发生了index_merge, KeyLen格式为N,N,所以不能定义为整型
	Ref          []string
	Rows         int
	Filtered     float64 // 5.6 JSON, 5.7+, 5.5 EXTENDED
	Scalability  string  // O(1), O(n), O(log n), O(log n)+
	Extra        string
}

ExplainRow 单行Explain

func ConvertExplainJSON2Row

func ConvertExplainJSON2Row(explainJSON *ExplainJSON) []*ExplainRow

ConvertExplainJSON2Row 将JSON格式转成ROW格式,为方便统一做优化建议 但是会损失一些JSON特有的分析结果

func FormatJSONIntoTraditional

func FormatJSONIntoTraditional(explainJSON string) []*ExplainRow

FormatJSONIntoTraditional 将JSON形式转换为TRADITIONAL形式,方便前端展现

type ExplainWarning

type ExplainWarning struct {
	Level   string
	Code    int
	Message string
}

ExplainWarning explain extended后SHOW WARNINGS输出的结果

type IndexSelectKey

type IndexSelectKey string

IndexSelectKey 用以对 TableIndexInfo 进行查询

type Profiling

type Profiling struct {
	Rows []ProfilingRow
}

Profiling show profile输出的结果

type ProfilingRow

type ProfilingRow struct {
	Status   string
	Duration float64
}

ProfilingRow show profile每一行信息

type QueryResult

type QueryResult struct {
	Rows      []mysql.Row
	Result    mysql.Result
	Error     error
	Warning   []mysql.Row
	QueryCost float64
}

QueryResult 数据库查询返回值

type Reference

type Reference map[string][]ReferenceValue

Reference 用于存储关系

type ReferenceValue

type ReferenceValue struct {
	RefDBName      string // 夫表所属数据库
	RefTable       string // 父表
	DBName         string // 子表所属数据库
	Table          string // 子表
	ConstraintName string // 关系名称
}

ReferenceValue 用于处理表之间的关系

type TableDesc

type TableDesc struct {
	Name       string
	DescValues []TableDescValue
}

TableDesc show columns from rental;

func NewTableDesc

func NewTableDesc(tableName string) *TableDesc

NewTableDesc 初始化一个*TableDesc

func (TableDesc) Columns

func (td TableDesc) Columns() []string

Columns 用于获取TableDesc中所有列的名称

type TableDescValue

type TableDescValue struct {
	Field      string // 列名
	Type       string // 数据类型
	Null       string // 是否有NULL(NO、YES)
	Collation  string // 字符集
	Privileges string // 权限s
	Key        string // 键类型
	Default    string // 默认值
	Extra      string // 其他
	Comment    string // 备注
}

TableDescValue 含有每一列的属性

type TableIndexInfo

type TableIndexInfo struct {
	TableName string
	IdxRows   []TableIndexRow
}

TableIndexInfo 用以保存 show index 之后获取的 index 信息

func NewTableIndexInfo

func NewTableIndexInfo(tableName string) *TableIndexInfo

NewTableIndexInfo 构造 TableIndexInfo

func (*TableIndexInfo) FindIndex

func (tbIndex *TableIndexInfo) FindIndex(arg IndexSelectKey, value string) []TableIndexRow

FindIndex 获取TableIndexInfo中需要的索引

type TableIndexRow

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
}

TableIndexRow 用以存放show index之后获取的每一条index信息

type TableStatInfo

type TableStatInfo struct {
	Name string
	Rows []tableStatusRow
}

TableStatInfo 用以保存 show table status 之后获取的table信息

type Trace

type Trace struct {
	Rows []TraceRow
}

Trace 用于存放 Select * From Information_Schema.Optimizer_Trace;输出的结果

type TraceRow

type TraceRow struct {
	Query                        string
	Trace                        string
	MissingBytesBeyondMaxMemSize int
	InsufficientPrivileges       int
}

TraceRow 中含有trace的基本信息

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL