index_test.go 12.4 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
/*
 * 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 advisor

import (
	"fmt"
	"os"
W
wu.sphinx 已提交
22
	"strings"
martianzhang's avatar
martianzhang 已提交
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
	"testing"

	"github.com/XiaoMi/soar/common"
	"github.com/XiaoMi/soar/env"

	"github.com/kr/pretty"
	"vitess.io/vitess/go/vt/sqlparser"
)

func init() {
	common.BaseDir = common.DevPath
	err := common.ParseConfig("")
	if err != nil {
		fmt.Println(err.Error())
	}
	vEnv, rEnv := env.BuildEnv()
	if _, err = vEnv.Version(); err != nil {
		fmt.Println(err.Error(), ", By pass all advisor test cases")
		os.Exit(0)
	}

	if _, err := rEnv.Version(); err != nil {
		fmt.Println(err.Error(), ", By pass all advisor test cases")
		os.Exit(0)
	}
}

// ARG.003
func TestRuleImplicitConversion(t *testing.T) {
	common.Log.Debug("Entering function: %s", common.GetFunctionName())
	dsn := common.Config.OnlineDSN
	common.Config.OnlineDSN = common.Config.TestDSN
	vEnv, rEnv := env.BuildEnv()
	defer vEnv.CleanUp()

	initSQLs := []string{
		`CREATE TABLE t1 (id int, title varchar(255) CHARSET utf8 COLLATE utf8_general_ci);`,
		`CREATE TABLE t2 (id int, title varchar(255) CHARSET utf8mb4);`,
		`CREATE TABLE t3 (id int, title varchar(255) CHARSET utf8 COLLATE utf8_bin);`,
	}
	for _, sql := range initSQLs {
		vEnv.BuildVirtualEnv(rEnv, sql)
	}

	sqls := []string{
		"SELECT * FROM t1 WHERE title >= 60;",
		"SELECT * FROM t1, t2 WHERE t1.title = t2.title;",
		"SELECT * FROM t1, t3 WHERE t1.title = t3.title;",
martianzhang's avatar
fix #87  
martianzhang 已提交
71 72
		"SELECT * FROM t1 WHERE title in (60, '60');",
		"SELECT * FROM t1 WHERE title in (60);",
martianzhang's avatar
martianzhang 已提交
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 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 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 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
	}
	for _, sql := range sqls {
		stmt, syntaxErr := sqlparser.Parse(sql)
		if syntaxErr != nil {
			common.Log.Critical("Syntax Error: %v, SQL: %s", syntaxErr, sql)
		}

		q := &Query4Audit{Query: sql, Stmt: stmt}

		idxAdvisor, err := NewAdvisor(vEnv, *rEnv, *q)
		if err != nil {
			t.Error("NewAdvisor Error: ", err, "SQL: ", sql)
		}

		if idxAdvisor != nil {
			rule := idxAdvisor.RuleImplicitConversion()
			if rule.Item != "ARG.003" {
				t.Error("Rule not match:", rule, "Expect : ARG.003, SQL:", sql)
			}
		}
	}
	common.Log.Debug("Exiting function: %s", common.GetFunctionName())
	common.Config.OnlineDSN = dsn
}

// JOI.003 & JOI.004
func TestRuleImpossibleOuterJoin(t *testing.T) {
	common.Log.Debug("Entering function: %s", common.GetFunctionName())
	sqls := []string{
		`select city_id, city, country from city left outer join country using(country_id) WHERE city.city_id=59 and country.country='Algeria'`,
		`select city_id, city, country from city left outer join country using(country_id) WHERE country.country='Algeria'`,
		`select city_id, city, country from city left outer join country on city.country_id=country.country_id WHERE city.city_id IS NULL`,
	}

	vEnv, rEnv := env.BuildEnv()
	defer vEnv.CleanUp()

	for _, sql := range sqls {
		stmt, syntaxErr := sqlparser.Parse(sql)
		if syntaxErr != nil {
			common.Log.Critical("Syntax Error: %v, SQL: %s", syntaxErr, sql)
		}

		q := &Query4Audit{Query: sql, Stmt: stmt}

		if vEnv.BuildVirtualEnv(rEnv, q.Query) {
			idxAdvisor, err := NewAdvisor(vEnv, *rEnv, *q)
			if err != nil {
				t.Error("NewAdvisor Error: ", err, "SQL: ", sql)
			}

			if idxAdvisor != nil {
				rule := idxAdvisor.RuleImpossibleOuterJoin()
				if rule.Item != "JOI.003" && rule.Item != "JOI.004" {
					t.Error("Rule not match:", rule, "Expect : JOI.003 || JOI.004")
				}
			}
		}
	}
	common.Log.Debug("Exiting function: %s", common.GetFunctionName())
}

// GRP.001
func TestIndexAdvisorRuleGroupByConst(t *testing.T) {
	common.Log.Debug("Entering function: %s", common.GetFunctionName())
	sqls := [][]string{
		{
			`select film_id, title from film where release_year='2006' group by release_year`,
			`select film_id, title from film where release_year in ('2006') group by release_year`,
		},
		{
			// 反面的例子
			`select film_id, title from film where release_year in ('2006', '2007') group by release_year`,
		},
	}

	vEnv, rEnv := env.BuildEnv()
	defer vEnv.CleanUp()

	for _, sql := range sqls[0] {
		stmt, syntaxErr := sqlparser.Parse(sql)
		if syntaxErr != nil {
			common.Log.Critical("Syntax Error: %v, SQL: %s", syntaxErr, sql)
		}

		q := &Query4Audit{Query: sql, Stmt: stmt}

		if vEnv.BuildVirtualEnv(rEnv, q.Query) {
			idxAdvisor, err := NewAdvisor(vEnv, *rEnv, *q)
			if err != nil {
				t.Error("NewAdvisor Error: ", err, "SQL: ", sql)
			}

			if idxAdvisor != nil {
				rule := idxAdvisor.RuleGroupByConst()
				if rule.Item != "GRP.001" {
					t.Error("Rule not match:", rule, "Expect : GRP.001")
				}
			}
		}
	}

	for _, sql := range sqls[1] {
		stmt, syntaxErr := sqlparser.Parse(sql)
		if syntaxErr != nil {
			common.Log.Critical("Syntax Error: %v, SQL: %s", syntaxErr, sql)
		}

		q := &Query4Audit{Query: sql, Stmt: stmt}

		if vEnv.BuildVirtualEnv(rEnv, q.Query) {
			idxAdvisor, err := NewAdvisor(vEnv, *rEnv, *q)
			if err != nil {
				t.Error("NewAdvisor Error: ", err, "SQL: ", sql)
			}

			if idxAdvisor != nil {
				rule := idxAdvisor.RuleGroupByConst()
				if rule.Item != "OK" {
					t.Error("Rule not match:", rule, "Expect : OK")
				}
			}
		}
	}
	common.Log.Debug("Exiting function: %s", common.GetFunctionName())
}

// CLA.005
func TestIndexAdvisorRuleOrderByConst(t *testing.T) {
	common.Log.Debug("Entering function: %s", common.GetFunctionName())
	sqls := [][]string{
		{
			`select film_id, title from film where release_year='2006' order by release_year;`,
			`select film_id, title from film where release_year in ('2006') order by release_year;`,
		},
		{
			// 反面的例子
			`select film_id, title from film where release_year in ('2006', '2007') order by release_year;`,
		},
	}

	vEnv, rEnv := env.BuildEnv()
	defer vEnv.CleanUp()

	for _, sql := range sqls[0] {
		stmt, syntaxErr := sqlparser.Parse(sql)
		if syntaxErr != nil {
			common.Log.Critical("Syntax Error: %v, SQL: %s", syntaxErr, sql)
		}

		q := &Query4Audit{Query: sql, Stmt: stmt}

		if vEnv.BuildVirtualEnv(rEnv, q.Query) {
			idxAdvisor, err := NewAdvisor(vEnv, *rEnv, *q)
			if err != nil {
				t.Error("NewAdvisor Error: ", err, "SQL: ", sql)
			}

			if idxAdvisor != nil {
				rule := idxAdvisor.RuleOrderByConst()
				if rule.Item != "CLA.005" {
					t.Error("Rule not match:", rule, "Expect : CLA.005")
				}
			}
		}
	}

	for _, sql := range sqls[1] {
		stmt, syntaxErr := sqlparser.Parse(sql)
		if syntaxErr != nil {
			common.Log.Critical("Syntax Error: %v, SQL: %s", syntaxErr, sql)
		}

		q := &Query4Audit{Query: sql, Stmt: stmt}

		if vEnv.BuildVirtualEnv(rEnv, q.Query) {
			idxAdvisor, err := NewAdvisor(vEnv, *rEnv, *q)
			if err != nil {
				t.Error("NewAdvisor Error: ", err, "SQL: ", sql)
			}

			if idxAdvisor != nil {
				rule := idxAdvisor.RuleOrderByConst()
				if rule.Item != "OK" {
					t.Error("Rule not match:", rule, "Expect : OK")
				}
			}
		}
	}
	common.Log.Debug("Exiting function: %s", common.GetFunctionName())
}

// CLA.016
func TestRuleUpdatePrimaryKey(t *testing.T) {
	common.Log.Debug("Entering function: %s", common.GetFunctionName())
	sqls := [][]string{
		{
			`update film set film_id = 1 where title='a';`,
		},
		{
			// 反面的例子
			`select film_id, title from film where release_year in ('2006', '2007') order by release_year;`,
		},
	}

	vEnv, rEnv := env.BuildEnv()
	defer vEnv.CleanUp()

	for _, sql := range sqls[0] {
		stmt, syntaxErr := sqlparser.Parse(sql)
		if syntaxErr != nil {
			common.Log.Critical("Syntax Error: %v, SQL: %s", syntaxErr, sql)
		}

		q := &Query4Audit{Query: sql, Stmt: stmt}

		if vEnv.BuildVirtualEnv(rEnv, q.Query) {
			idxAdvisor, err := NewAdvisor(vEnv, *rEnv, *q)
			if err != nil {
				t.Error("NewAdvisor Error: ", err, "SQL: ", sql)
			}

			if idxAdvisor != nil {
				rule := idxAdvisor.RuleUpdatePrimaryKey()
				if rule.Item != "CLA.016" {
					t.Error("Rule not match:", rule.Item, "Expect : CLA.016")
				}
			}
		}
	}

	for _, sql := range sqls[1] {
		stmt, syntaxErr := sqlparser.Parse(sql)
		if syntaxErr != nil {
			common.Log.Critical("Syntax Error: %v, SQL: %s", syntaxErr, sql)
		}

		q := &Query4Audit{Query: sql, Stmt: stmt}

		if vEnv.BuildVirtualEnv(rEnv, q.Query) {
			idxAdvisor, err := NewAdvisor(vEnv, *rEnv, *q)
			if err != nil {
				t.Error("NewAdvisor Error: ", err, "SQL: ", sql)
			}

			if idxAdvisor != nil {
				rule := idxAdvisor.RuleUpdatePrimaryKey()
				if rule.Item != "OK" {
					t.Error("Rule not match:", rule, "Expect : OK")
				}
			}
		}
	}
	common.Log.Debug("Exiting function: %s", common.GetFunctionName())
}

func TestIndexAdvise(t *testing.T) {
	common.Log.Debug("Entering function: %s", common.GetFunctionName())
	vEnv, rEnv := env.BuildEnv()
	defer vEnv.CleanUp()

	for _, sql := range common.TestSQLs {
		stmt, syntaxErr := sqlparser.Parse(sql)
		if syntaxErr != nil {
			common.Log.Critical("Syntax Error: %v, SQL: %s", syntaxErr, sql)
		}

		q := &Query4Audit{Query: sql, Stmt: stmt}

		if vEnv.BuildVirtualEnv(rEnv, q.Query) {
			idxAdvisor, err := NewAdvisor(vEnv, *rEnv, *q)
			if err != nil {
				t.Error("NewAdvisor Error: ", err, "SQL: ", sql)
			}

			if idxAdvisor != nil {
				rule := idxAdvisor.IndexAdvise().Format()
				if len(rule) > 0 {
					pretty.Println(rule)
				}
			}
		}
	}
	common.Log.Debug("Exiting function: %s", common.GetFunctionName())
}

func TestIndexAdviseNoEnv(t *testing.T) {
	common.Log.Debug("Entering function: %s", common.GetFunctionName())
martianzhang's avatar
martianzhang 已提交
361 362
	orgOnlineDSNStatus := common.Config.OnlineDSN.Disable
	common.Config.OnlineDSN.Disable = true
martianzhang's avatar
martianzhang 已提交
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
	vEnv, rEnv := env.BuildEnv()
	defer vEnv.CleanUp()

	for _, sql := range common.TestSQLs {
		stmt, syntaxErr := sqlparser.Parse(sql)
		if syntaxErr != nil {
			common.Log.Critical("Syntax Error: %v, SQL: %s", syntaxErr, sql)
		}

		q := &Query4Audit{Query: sql, Stmt: stmt}

		if vEnv.BuildVirtualEnv(rEnv, q.Query) {
			idxAdvisor, err := NewAdvisor(vEnv, *rEnv, *q)
			if err != nil {
				t.Error("NewAdvisor Error: ", err, "SQL: ", sql)
			}

			if idxAdvisor != nil {
				rule := idxAdvisor.IndexAdvise().Format()
				if len(rule) > 0 {
					pretty.Println(rule)
				}
			}
		}
	}
martianzhang's avatar
martianzhang 已提交
388
	common.Config.OnlineDSN.Disable = orgOnlineDSNStatus
martianzhang's avatar
martianzhang 已提交
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
	common.Log.Debug("Exiting function: %s", common.GetFunctionName())
}

func TestDuplicateKeyChecker(t *testing.T) {
	common.Log.Debug("Entering function: %s", common.GetFunctionName())
	_, rEnv := env.BuildEnv()
	rule := DuplicateKeyChecker(rEnv, "sakila")
	if len(rule) != 0 {
		t.Errorf("got rules: %s", pretty.Sprint(rule))
	}
}

func TestMergeAdvices(t *testing.T) {
	dst := []IndexInfo{
		{
			Name:     "test",
			Database: "db",
			Table:    "tb",
			ColumnDetails: []*common.Column{
				{
					Name: "test",
				},
			},
		},
	}

	src := dst[0]

	advise := mergeAdvices(dst, src)
	if len(advise) != 1 {
		t.Error(pretty.Sprint(advise))
	}
}

func TestIdxColsTypeCheck(t *testing.T) {
	common.Log.Debug("Entering function: %s", common.GetFunctionName())
	sqls := []string{
		`select city_id, city, country from city left outer join country using(country_id) WHERE city.city_id=59 and country.country='Algeria'`,
	}

	vEnv, rEnv := env.BuildEnv()
	defer vEnv.CleanUp()

	for _, sql := range sqls {
		stmt, syntaxErr := sqlparser.Parse(sql)
		if syntaxErr != nil {
			common.Log.Critical("Syntax Error: %v, SQL: %s", syntaxErr, sql)
		}

		q := &Query4Audit{Query: sql, Stmt: stmt}

		if vEnv.BuildVirtualEnv(rEnv, q.Query) {
			idxAdvisor, err := NewAdvisor(vEnv, *rEnv, *q)
			if err != nil {
				t.Error("NewAdvisor Error: ", err, "SQL: ", sql)
			}

			idxList := []IndexInfo{
				{
					Name:     "idx_fk_country_id",
					Database: "sakila",
					Table:    "city",
					ColumnDetails: []*common.Column{
						{
							Name:      "country_id",
							Character: "utf8",
							DataType:  "varchar(3000)",
						},
					},
				},
			}

			if idxAdvisor != nil {
				rule := idxAdvisor.idxColsTypeCheck(idxList)
				if !(len(rule) > 0 && rule[0].DDL == "alter table `sakila`.`city` add index `idx_country_id` (`country_id`(N))") {
					t.Error(pretty.Sprint(rule))
				}
			}
		}
	}
}
W
wu.sphinx 已提交
470 471 472 473 474 475 476 477 478

func TestGetRandomIndexSuffix(t *testing.T) {
	for i := 0; i < 5; i++ {
		r := getRandomIndexSuffix()
		if !(strings.HasPrefix(r, "_") && len(r) == 5) {
			t.Errorf("getRandomIndexSuffix should return a string with prefix `_` and 5 length, but got:%s", r)
		}
	}
}