package app import ( . "code.hoteas.com/golang/hotime" . "code.hoteas.com/golang/hotime/common" ) // MysqlCtr MySQL 特有测试控制器 var MysqlCtr = Ctr{ "tables": func(that *Context) { if that.Db.Type != "mysql" { that.Display(0, Map{"skip": true, "reason": "当前非 MySQL 数据库"}) return } tables := that.Db.Query("SHOW TABLES") that.Display(0, Map{"tables": tables}) }, "describe": func(that *Context) { if that.Db.Type != "mysql" { that.Display(0, Map{"skip": true, "reason": "当前非 MySQL 数据库"}) return } tableName := that.Req.FormValue("table") if tableName == "" { that.Display(1, "请提供 table 参数") return } columns := that.Db.Query("DESCRIBE " + tableName) data := that.Db.Select(tableName, "*", Map{"LIMIT": 10}) that.Display(0, Map{"table": tableName, "columns": columns, "sample_data": data}) }, "rawsql": func(that *Context) { if that.Db.Type != "mysql" { that.Display(0, Map{"skip": true, "reason": "当前非 MySQL 数据库"}) return } result := testMysqlRawSQL(that) that.Display(0, result) }, } func testMysqlRawSQL(that *Context) Map { result := Map{"name": "MySQL原生SQL测试", "tests": Slice{}} tests := Slice{} test1 := Map{"name": "Query 原生查询 (反引号)"} articles1 := that.Db.Query("SELECT id, title, author FROM `article` WHERE state = ? LIMIT ?", 0, 5) test1["result"] = len(articles1) >= 0 test1["count"] = len(articles1) tests = append(tests, test1) test2 := Map{"name": "Exec 原生执行 (反引号)"} testArticle := that.Db.Get("article", "id", Map{"state": 0}) if testArticle != nil { res, err := that.Db.Exec("UPDATE `article` SET modify_time = NOW() WHERE id = ?", testArticle.GetInt64("id")) if err == nil && res != nil { affected, _ := res.RowsAffected() test2["result"] = affected >= 0 test2["affected"] = affected } else { test2["result"] = false test2["error"] = err } } else { test2["result"] = true test2["note"] = "无可用测试数据" } tests = append(tests, test2) test3 := Map{"name": "IN (?) 非空数组展开"} articles3 := that.Db.Query("SELECT id, title FROM `article` WHERE id IN (?) LIMIT 10", []int{1, 2, 3, 4, 5}) test3["result"] = len(articles3) >= 0 test3["count"] = len(articles3) test3["lastQuery"] = that.Db.GetLastQuery() tests = append(tests, test3) test4 := Map{"name": "IN (?) 空数组替换为1=0"} articles4 := that.Db.Query("SELECT id, title FROM `article` WHERE id IN (?) LIMIT 10", []int{}) test4["result"] = len(articles4) == 0 test4["count"] = len(articles4) test4["lastQuery"] = that.Db.GetLastQuery() tests = append(tests, test4) test5 := Map{"name": "NOT IN (?) 空数组替换为1=1"} articles5 := that.Db.Query("SELECT id, title FROM `article` WHERE id NOT IN (?) LIMIT 10", []int{}) test5["result"] = len(articles5) > 0 test5["count"] = len(articles5) test5["lastQuery"] = that.Db.GetLastQuery() tests = append(tests, test5) result["tests"] = tests result["success"] = true return result }