driver_test.go 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370
  1. // Go MySQL Driver - A MySQL-Driver for Go's database/sql package
  2. //
  3. // Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved.
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public
  6. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  7. // You can obtain one at http://mozilla.org/MPL/2.0/.
  8. package mysql
  9. import (
  10. "crypto/tls"
  11. "database/sql"
  12. "database/sql/driver"
  13. "fmt"
  14. "io"
  15. "io/ioutil"
  16. "net"
  17. "net/url"
  18. "os"
  19. "strings"
  20. "sync"
  21. "sync/atomic"
  22. "testing"
  23. "time"
  24. )
  25. var (
  26. user string
  27. pass string
  28. prot string
  29. addr string
  30. dbname string
  31. dsn string
  32. netAddr string
  33. available bool
  34. )
  35. var (
  36. tDate = time.Date(2012, 6, 14, 0, 0, 0, 0, time.UTC)
  37. sDate = "2012-06-14"
  38. tDateTime = time.Date(2011, 11, 20, 21, 27, 37, 0, time.UTC)
  39. sDateTime = "2011-11-20 21:27:37"
  40. tDate0 = time.Time{}
  41. sDate0 = "0000-00-00"
  42. sDateTime0 = "0000-00-00 00:00:00"
  43. )
  44. // See https://github.com/go-sql-driver/mysql/wiki/Testing
  45. func init() {
  46. // get environment variables
  47. env := func(key, defaultValue string) string {
  48. if value := os.Getenv(key); value != "" {
  49. return value
  50. }
  51. return defaultValue
  52. }
  53. user = env("MYSQL_TEST_USER", "root")
  54. pass = env("MYSQL_TEST_PASS", "")
  55. prot = env("MYSQL_TEST_PROT", "tcp")
  56. addr = env("MYSQL_TEST_ADDR", "localhost:3306")
  57. dbname = env("MYSQL_TEST_DBNAME", "gotest")
  58. netAddr = fmt.Sprintf("%s(%s)", prot, addr)
  59. dsn = fmt.Sprintf("%s:%s@%s/%s?timeout=30s&strict=true", user, pass, netAddr, dbname)
  60. c, err := net.Dial(prot, addr)
  61. if err == nil {
  62. available = true
  63. c.Close()
  64. }
  65. }
  66. type DBTest struct {
  67. *testing.T
  68. db *sql.DB
  69. }
  70. func runTests(t *testing.T, dsn string, tests ...func(dbt *DBTest)) {
  71. if !available {
  72. t.Skipf("MySQL-Server not running on %s", netAddr)
  73. }
  74. db, err := sql.Open("mysql", dsn)
  75. if err != nil {
  76. t.Fatalf("Error connecting: %s", err.Error())
  77. }
  78. defer db.Close()
  79. db.Exec("DROP TABLE IF EXISTS test")
  80. dbt := &DBTest{t, db}
  81. for _, test := range tests {
  82. test(dbt)
  83. dbt.db.Exec("DROP TABLE IF EXISTS test")
  84. }
  85. }
  86. func (dbt *DBTest) fail(method, query string, err error) {
  87. if len(query) > 300 {
  88. query = "[query too large to print]"
  89. }
  90. dbt.Fatalf("Error on %s %s: %s", method, query, err.Error())
  91. }
  92. func (dbt *DBTest) mustExec(query string, args ...interface{}) (res sql.Result) {
  93. res, err := dbt.db.Exec(query, args...)
  94. if err != nil {
  95. dbt.fail("Exec", query, err)
  96. }
  97. return res
  98. }
  99. func (dbt *DBTest) mustQuery(query string, args ...interface{}) (rows *sql.Rows) {
  100. rows, err := dbt.db.Query(query, args...)
  101. if err != nil {
  102. dbt.fail("Query", query, err)
  103. }
  104. return rows
  105. }
  106. func TestCRUD(t *testing.T) {
  107. runTests(t, dsn, func(dbt *DBTest) {
  108. // Create Table
  109. dbt.mustExec("CREATE TABLE test (value BOOL)")
  110. // Test for unexpected data
  111. var out bool
  112. rows := dbt.mustQuery("SELECT * FROM test")
  113. if rows.Next() {
  114. dbt.Error("unexpected data in empty table")
  115. }
  116. // Create Data
  117. res := dbt.mustExec("INSERT INTO test VALUES (1)")
  118. count, err := res.RowsAffected()
  119. if err != nil {
  120. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  121. }
  122. if count != 1 {
  123. dbt.Fatalf("Expected 1 affected row, got %d", count)
  124. }
  125. id, err := res.LastInsertId()
  126. if err != nil {
  127. dbt.Fatalf("res.LastInsertId() returned error: %s", err.Error())
  128. }
  129. if id != 0 {
  130. dbt.Fatalf("Expected InsertID 0, got %d", id)
  131. }
  132. // Read
  133. rows = dbt.mustQuery("SELECT value FROM test")
  134. if rows.Next() {
  135. rows.Scan(&out)
  136. if true != out {
  137. dbt.Errorf("true != %t", out)
  138. }
  139. if rows.Next() {
  140. dbt.Error("unexpected data")
  141. }
  142. } else {
  143. dbt.Error("no data")
  144. }
  145. // Update
  146. res = dbt.mustExec("UPDATE test SET value = ? WHERE value = ?", false, true)
  147. count, err = res.RowsAffected()
  148. if err != nil {
  149. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  150. }
  151. if count != 1 {
  152. dbt.Fatalf("Expected 1 affected row, got %d", count)
  153. }
  154. // Check Update
  155. rows = dbt.mustQuery("SELECT value FROM test")
  156. if rows.Next() {
  157. rows.Scan(&out)
  158. if false != out {
  159. dbt.Errorf("false != %t", out)
  160. }
  161. if rows.Next() {
  162. dbt.Error("unexpected data")
  163. }
  164. } else {
  165. dbt.Error("no data")
  166. }
  167. // Delete
  168. res = dbt.mustExec("DELETE FROM test WHERE value = ?", false)
  169. count, err = res.RowsAffected()
  170. if err != nil {
  171. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  172. }
  173. if count != 1 {
  174. dbt.Fatalf("Expected 1 affected row, got %d", count)
  175. }
  176. // Check for unexpected rows
  177. res = dbt.mustExec("DELETE FROM test")
  178. count, err = res.RowsAffected()
  179. if err != nil {
  180. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  181. }
  182. if count != 0 {
  183. dbt.Fatalf("Expected 0 affected row, got %d", count)
  184. }
  185. })
  186. }
  187. func TestInt(t *testing.T) {
  188. runTests(t, dsn, func(dbt *DBTest) {
  189. types := [5]string{"TINYINT", "SMALLINT", "MEDIUMINT", "INT", "BIGINT"}
  190. in := int64(42)
  191. var out int64
  192. var rows *sql.Rows
  193. // SIGNED
  194. for _, v := range types {
  195. dbt.mustExec("CREATE TABLE test (value " + v + ")")
  196. dbt.mustExec("INSERT INTO test VALUES (?)", in)
  197. rows = dbt.mustQuery("SELECT value FROM test")
  198. if rows.Next() {
  199. rows.Scan(&out)
  200. if in != out {
  201. dbt.Errorf("%s: %d != %d", v, in, out)
  202. }
  203. } else {
  204. dbt.Errorf("%s: no data", v)
  205. }
  206. dbt.mustExec("DROP TABLE IF EXISTS test")
  207. }
  208. // UNSIGNED ZEROFILL
  209. for _, v := range types {
  210. dbt.mustExec("CREATE TABLE test (value " + v + " ZEROFILL)")
  211. dbt.mustExec("INSERT INTO test VALUES (?)", in)
  212. rows = dbt.mustQuery("SELECT value FROM test")
  213. if rows.Next() {
  214. rows.Scan(&out)
  215. if in != out {
  216. dbt.Errorf("%s ZEROFILL: %d != %d", v, in, out)
  217. }
  218. } else {
  219. dbt.Errorf("%s ZEROFILL: no data", v)
  220. }
  221. dbt.mustExec("DROP TABLE IF EXISTS test")
  222. }
  223. })
  224. }
  225. func TestFloat(t *testing.T) {
  226. runTests(t, dsn, func(dbt *DBTest) {
  227. types := [2]string{"FLOAT", "DOUBLE"}
  228. in := float32(42.23)
  229. var out float32
  230. var rows *sql.Rows
  231. for _, v := range types {
  232. dbt.mustExec("CREATE TABLE test (value " + v + ")")
  233. dbt.mustExec("INSERT INTO test VALUES (?)", in)
  234. rows = dbt.mustQuery("SELECT value FROM test")
  235. if rows.Next() {
  236. rows.Scan(&out)
  237. if in != out {
  238. dbt.Errorf("%s: %g != %g", v, in, out)
  239. }
  240. } else {
  241. dbt.Errorf("%s: no data", v)
  242. }
  243. dbt.mustExec("DROP TABLE IF EXISTS test")
  244. }
  245. })
  246. }
  247. func TestString(t *testing.T) {
  248. runTests(t, dsn, func(dbt *DBTest) {
  249. types := [6]string{"CHAR(255)", "VARCHAR(255)", "TINYTEXT", "TEXT", "MEDIUMTEXT", "LONGTEXT"}
  250. in := "κόσμε üöäßñóùéàâÿœ'îë Árvíztűrő いろはにほへとちりぬるを イロハニホヘト דג סקרן чащах น่าฟังเอย"
  251. var out string
  252. var rows *sql.Rows
  253. for _, v := range types {
  254. dbt.mustExec("CREATE TABLE test (value " + v + ") CHARACTER SET utf8")
  255. dbt.mustExec("INSERT INTO test VALUES (?)", in)
  256. rows = dbt.mustQuery("SELECT value FROM test")
  257. if rows.Next() {
  258. rows.Scan(&out)
  259. if in != out {
  260. dbt.Errorf("%s: %s != %s", v, in, out)
  261. }
  262. } else {
  263. dbt.Errorf("%s: no data", v)
  264. }
  265. dbt.mustExec("DROP TABLE IF EXISTS test")
  266. }
  267. // BLOB
  268. dbt.mustExec("CREATE TABLE test (id int, value BLOB) CHARACTER SET utf8")
  269. id := 2
  270. in = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, " +
  271. "sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, " +
  272. "sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. " +
  273. "Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. " +
  274. "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, " +
  275. "sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, " +
  276. "sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. " +
  277. "Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."
  278. dbt.mustExec("INSERT INTO test VALUES (?, ?)", id, in)
  279. err := dbt.db.QueryRow("SELECT value FROM test WHERE id = ?", id).Scan(&out)
  280. if err != nil {
  281. dbt.Fatalf("Error on BLOB-Query: %s", err.Error())
  282. } else if out != in {
  283. dbt.Errorf("BLOB: %s != %s", in, out)
  284. }
  285. })
  286. }
  287. func TestDateTime(t *testing.T) {
  288. type testmode struct {
  289. selectSuffix string
  290. args []interface{}
  291. }
  292. type timetest struct {
  293. in interface{}
  294. sOut string
  295. tOut time.Time
  296. tIsZero bool
  297. }
  298. type tester func(dbt *DBTest, rows *sql.Rows,
  299. test *timetest, sqltype, resulttype, mode string)
  300. type setup struct {
  301. vartype string
  302. dsnSuffix string
  303. test tester
  304. }
  305. var (
  306. modes = map[string]*testmode{
  307. "text": &testmode{},
  308. "binary": &testmode{" WHERE 1 = ?", []interface{}{1}},
  309. }
  310. timetests = map[string][]*timetest{
  311. "DATE": {
  312. {sDate, sDate, tDate, false},
  313. {sDate0, sDate0, tDate0, true},
  314. {tDate, sDate, tDate, false},
  315. {tDate0, sDate0, tDate0, true},
  316. },
  317. "DATETIME": {
  318. {sDateTime, sDateTime, tDateTime, false},
  319. {sDateTime0, sDateTime0, tDate0, true},
  320. {tDateTime, sDateTime, tDateTime, false},
  321. {tDate0, sDateTime0, tDate0, true},
  322. },
  323. }
  324. setups = []*setup{
  325. {"string", "&parseTime=false", func(
  326. dbt *DBTest, rows *sql.Rows, test *timetest, sqltype, resulttype, mode string) {
  327. var sOut string
  328. if err := rows.Scan(&sOut); err != nil {
  329. dbt.Errorf("%s (%s %s): %s", sqltype, resulttype, mode, err.Error())
  330. } else if test.sOut != sOut {
  331. dbt.Errorf("%s (%s %s): %s != %s", sqltype, resulttype, mode, test.sOut, sOut)
  332. }
  333. }},
  334. {"time.Time", "&parseTime=true", func(
  335. dbt *DBTest, rows *sql.Rows, test *timetest, sqltype, resulttype, mode string) {
  336. var tOut time.Time
  337. if err := rows.Scan(&tOut); err != nil {
  338. dbt.Errorf("%s (%s %s): %s", sqltype, resulttype, mode, err.Error())
  339. } else if test.tOut != tOut || test.tIsZero != tOut.IsZero() {
  340. dbt.Errorf("%s (%s %s): %s [%t] != %s [%t]", sqltype, resulttype, mode, test.tOut, test.tIsZero, tOut, tOut.IsZero())
  341. }
  342. }},
  343. }
  344. )
  345. var s *setup
  346. testTime := func(dbt *DBTest) {
  347. var rows *sql.Rows
  348. for sqltype, tests := range timetests {
  349. dbt.mustExec("CREATE TABLE test (value " + sqltype + ")")
  350. for _, test := range tests {
  351. for mode, q := range modes {
  352. dbt.mustExec("TRUNCATE test")
  353. dbt.mustExec("INSERT INTO test VALUES (?)", test.in)
  354. rows = dbt.mustQuery("SELECT value FROM test"+q.selectSuffix, q.args...)
  355. if rows.Next() {
  356. s.test(dbt, rows, test, sqltype, s.vartype, mode)
  357. } else {
  358. if err := rows.Err(); err != nil {
  359. dbt.Errorf("%s (%s %s): %s",
  360. sqltype, s.vartype, mode, err.Error())
  361. } else {
  362. dbt.Errorf("%s (%s %s): no data",
  363. sqltype, s.vartype, mode)
  364. }
  365. }
  366. }
  367. }
  368. dbt.mustExec("DROP TABLE IF EXISTS test")
  369. }
  370. }
  371. timeDsn := dsn + "&sql_mode=ALLOW_INVALID_DATES"
  372. for _, v := range setups {
  373. s = v
  374. runTests(t, timeDsn+s.dsnSuffix, testTime)
  375. }
  376. }
  377. func TestNULL(t *testing.T) {
  378. runTests(t, dsn, func(dbt *DBTest) {
  379. nullStmt, err := dbt.db.Prepare("SELECT NULL")
  380. if err != nil {
  381. dbt.Fatal(err)
  382. }
  383. defer nullStmt.Close()
  384. nonNullStmt, err := dbt.db.Prepare("SELECT 1")
  385. if err != nil {
  386. dbt.Fatal(err)
  387. }
  388. defer nonNullStmt.Close()
  389. // NullBool
  390. var nb sql.NullBool
  391. // Invalid
  392. if err = nullStmt.QueryRow().Scan(&nb); err != nil {
  393. dbt.Fatal(err)
  394. }
  395. if nb.Valid {
  396. dbt.Error("Valid NullBool which should be invalid")
  397. }
  398. // Valid
  399. if err = nonNullStmt.QueryRow().Scan(&nb); err != nil {
  400. dbt.Fatal(err)
  401. }
  402. if !nb.Valid {
  403. dbt.Error("Invalid NullBool which should be valid")
  404. } else if nb.Bool != true {
  405. dbt.Errorf("Unexpected NullBool value: %t (should be true)", nb.Bool)
  406. }
  407. // NullFloat64
  408. var nf sql.NullFloat64
  409. // Invalid
  410. if err = nullStmt.QueryRow().Scan(&nf); err != nil {
  411. dbt.Fatal(err)
  412. }
  413. if nf.Valid {
  414. dbt.Error("Valid NullFloat64 which should be invalid")
  415. }
  416. // Valid
  417. if err = nonNullStmt.QueryRow().Scan(&nf); err != nil {
  418. dbt.Fatal(err)
  419. }
  420. if !nf.Valid {
  421. dbt.Error("Invalid NullFloat64 which should be valid")
  422. } else if nf.Float64 != float64(1) {
  423. dbt.Errorf("Unexpected NullFloat64 value: %f (should be 1.0)", nf.Float64)
  424. }
  425. // NullInt64
  426. var ni sql.NullInt64
  427. // Invalid
  428. if err = nullStmt.QueryRow().Scan(&ni); err != nil {
  429. dbt.Fatal(err)
  430. }
  431. if ni.Valid {
  432. dbt.Error("Valid NullInt64 which should be invalid")
  433. }
  434. // Valid
  435. if err = nonNullStmt.QueryRow().Scan(&ni); err != nil {
  436. dbt.Fatal(err)
  437. }
  438. if !ni.Valid {
  439. dbt.Error("Invalid NullInt64 which should be valid")
  440. } else if ni.Int64 != int64(1) {
  441. dbt.Errorf("Unexpected NullInt64 value: %d (should be 1)", ni.Int64)
  442. }
  443. // NullString
  444. var ns sql.NullString
  445. // Invalid
  446. if err = nullStmt.QueryRow().Scan(&ns); err != nil {
  447. dbt.Fatal(err)
  448. }
  449. if ns.Valid {
  450. dbt.Error("Valid NullString which should be invalid")
  451. }
  452. // Valid
  453. if err = nonNullStmt.QueryRow().Scan(&ns); err != nil {
  454. dbt.Fatal(err)
  455. }
  456. if !ns.Valid {
  457. dbt.Error("Invalid NullString which should be valid")
  458. } else if ns.String != `1` {
  459. dbt.Error("Unexpected NullString value:" + ns.String + " (should be `1`)")
  460. }
  461. // nil-bytes
  462. var b []byte
  463. // Read nil
  464. if err = nullStmt.QueryRow().Scan(&b); err != nil {
  465. dbt.Fatal(err)
  466. }
  467. if b != nil {
  468. dbt.Error("Non-nil []byte wich should be nil")
  469. }
  470. // Read non-nil
  471. if err = nonNullStmt.QueryRow().Scan(&b); err != nil {
  472. dbt.Fatal(err)
  473. }
  474. if b == nil {
  475. dbt.Error("Nil []byte wich should be non-nil")
  476. }
  477. // Insert nil
  478. b = nil
  479. success := false
  480. if err = dbt.db.QueryRow("SELECT ? IS NULL", b).Scan(&success); err != nil {
  481. dbt.Fatal(err)
  482. }
  483. if !success {
  484. dbt.Error("Inserting []byte(nil) as NULL failed")
  485. }
  486. // Check input==output with input==nil
  487. b = nil
  488. if err = dbt.db.QueryRow("SELECT ?", b).Scan(&b); err != nil {
  489. dbt.Fatal(err)
  490. }
  491. if b != nil {
  492. dbt.Error("Non-nil echo from nil input")
  493. }
  494. // Check input==output with input!=nil
  495. b = []byte("")
  496. if err = dbt.db.QueryRow("SELECT ?", b).Scan(&b); err != nil {
  497. dbt.Fatal(err)
  498. }
  499. if b == nil {
  500. dbt.Error("nil echo from non-nil input")
  501. }
  502. // Insert NULL
  503. dbt.mustExec("CREATE TABLE test (dummmy1 int, value int, dummy2 int)")
  504. dbt.mustExec("INSERT INTO test VALUES (?, ?, ?)", 1, nil, 2)
  505. var out interface{}
  506. rows := dbt.mustQuery("SELECT * FROM test")
  507. if rows.Next() {
  508. rows.Scan(&out)
  509. if out != nil {
  510. dbt.Errorf("%v != nil", out)
  511. }
  512. } else {
  513. dbt.Error("no data")
  514. }
  515. })
  516. }
  517. func TestLongData(t *testing.T) {
  518. runTests(t, dsn, func(dbt *DBTest) {
  519. var maxAllowedPacketSize int
  520. err := dbt.db.QueryRow("select @@max_allowed_packet").Scan(&maxAllowedPacketSize)
  521. if err != nil {
  522. dbt.Fatal(err)
  523. }
  524. maxAllowedPacketSize--
  525. // don't get too ambitious
  526. if maxAllowedPacketSize > 1<<25 {
  527. maxAllowedPacketSize = 1 << 25
  528. }
  529. dbt.mustExec("CREATE TABLE test (value LONGBLOB)")
  530. in := strings.Repeat(`a`, maxAllowedPacketSize+1)
  531. var out string
  532. var rows *sql.Rows
  533. // Long text data
  534. const nonDataQueryLen = 28 // length query w/o value
  535. inS := in[:maxAllowedPacketSize-nonDataQueryLen]
  536. dbt.mustExec("INSERT INTO test VALUES('" + inS + "')")
  537. rows = dbt.mustQuery("SELECT value FROM test")
  538. if rows.Next() {
  539. rows.Scan(&out)
  540. if inS != out {
  541. dbt.Fatalf("LONGBLOB: length in: %d, length out: %d", len(inS), len(out))
  542. }
  543. if rows.Next() {
  544. dbt.Error("LONGBLOB: unexpexted row")
  545. }
  546. } else {
  547. dbt.Fatalf("LONGBLOB: no data")
  548. }
  549. // Empty table
  550. dbt.mustExec("TRUNCATE TABLE test")
  551. // Long binary data
  552. dbt.mustExec("INSERT INTO test VALUES(?)", in)
  553. rows = dbt.mustQuery("SELECT value FROM test WHERE 1=?", 1)
  554. if rows.Next() {
  555. rows.Scan(&out)
  556. if in != out {
  557. dbt.Fatalf("LONGBLOB: length in: %d, length out: %d", len(in), len(out))
  558. }
  559. if rows.Next() {
  560. dbt.Error("LONGBLOB: unexpexted row")
  561. }
  562. } else {
  563. if err = rows.Err(); err != nil {
  564. dbt.Fatalf("LONGBLOB: no data (err: %s)", err.Error())
  565. } else {
  566. dbt.Fatal("LONGBLOB: no data (err: <nil>)")
  567. }
  568. }
  569. })
  570. }
  571. func TestLoadData(t *testing.T) {
  572. runTests(t, dsn, func(dbt *DBTest) {
  573. verifyLoadDataResult := func() {
  574. rows, err := dbt.db.Query("SELECT * FROM test")
  575. if err != nil {
  576. dbt.Fatal(err.Error())
  577. }
  578. i := 0
  579. values := [4]string{
  580. "a string",
  581. "a string containing a \t",
  582. "a string containing a \n",
  583. "a string containing both \t\n",
  584. }
  585. var id int
  586. var value string
  587. for rows.Next() {
  588. i++
  589. err = rows.Scan(&id, &value)
  590. if err != nil {
  591. dbt.Fatal(err.Error())
  592. }
  593. if i != id {
  594. dbt.Fatalf("%d != %d", i, id)
  595. }
  596. if values[i-1] != value {
  597. dbt.Fatalf("%s != %s", values[i-1], value)
  598. }
  599. }
  600. err = rows.Err()
  601. if err != nil {
  602. dbt.Fatal(err.Error())
  603. }
  604. if i != 4 {
  605. dbt.Fatalf("Rows count mismatch. Got %d, want 4", i)
  606. }
  607. }
  608. file, err := ioutil.TempFile("", "gotest")
  609. defer os.Remove(file.Name())
  610. if err != nil {
  611. dbt.Fatal(err)
  612. }
  613. file.WriteString("1\ta string\n2\ta string containing a \\t\n3\ta string containing a \\n\n4\ta string containing both \\t\\n\n")
  614. file.Close()
  615. dbt.db.Exec("DROP TABLE IF EXISTS test")
  616. dbt.mustExec("CREATE TABLE test (id INT NOT NULL PRIMARY KEY, value TEXT NOT NULL) CHARACTER SET utf8")
  617. // Local File
  618. RegisterLocalFile(file.Name())
  619. dbt.mustExec(fmt.Sprintf("LOAD DATA LOCAL INFILE '%q' INTO TABLE test", file.Name()))
  620. verifyLoadDataResult()
  621. // negative test
  622. _, err = dbt.db.Exec("LOAD DATA LOCAL INFILE 'doesnotexist' INTO TABLE test")
  623. if err == nil {
  624. dbt.Fatal("Load non-existent file didn't fail")
  625. } else if err.Error() != "Local File 'doesnotexist' is not registered. Use the DSN parameter 'allowAllFiles=true' to allow all files" {
  626. dbt.Fatal(err.Error())
  627. }
  628. // Empty table
  629. dbt.mustExec("TRUNCATE TABLE test")
  630. // Reader
  631. RegisterReaderHandler("test", func() io.Reader {
  632. file, err = os.Open(file.Name())
  633. if err != nil {
  634. dbt.Fatal(err)
  635. }
  636. return file
  637. })
  638. dbt.mustExec("LOAD DATA LOCAL INFILE 'Reader::test' INTO TABLE test")
  639. verifyLoadDataResult()
  640. // negative test
  641. _, err = dbt.db.Exec("LOAD DATA LOCAL INFILE 'Reader::doesnotexist' INTO TABLE test")
  642. if err == nil {
  643. dbt.Fatal("Load non-existent Reader didn't fail")
  644. } else if err.Error() != "Reader 'doesnotexist' is not registered" {
  645. dbt.Fatal(err.Error())
  646. }
  647. })
  648. }
  649. func TestFoundRows(t *testing.T) {
  650. runTests(t, dsn, func(dbt *DBTest) {
  651. dbt.mustExec("CREATE TABLE test (id INT NOT NULL ,data INT NOT NULL)")
  652. dbt.mustExec("INSERT INTO test (id, data) VALUES (0, 0),(0, 0),(1, 0),(1, 0),(1, 1)")
  653. res := dbt.mustExec("UPDATE test SET data = 1 WHERE id = 0")
  654. count, err := res.RowsAffected()
  655. if err != nil {
  656. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  657. }
  658. if count != 2 {
  659. dbt.Fatalf("Expected 2 affected rows, got %d", count)
  660. }
  661. res = dbt.mustExec("UPDATE test SET data = 1 WHERE id = 1")
  662. count, err = res.RowsAffected()
  663. if err != nil {
  664. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  665. }
  666. if count != 2 {
  667. dbt.Fatalf("Expected 2 affected rows, got %d", count)
  668. }
  669. })
  670. runTests(t, dsn+"&clientFoundRows=true", func(dbt *DBTest) {
  671. dbt.mustExec("CREATE TABLE test (id INT NOT NULL ,data INT NOT NULL)")
  672. dbt.mustExec("INSERT INTO test (id, data) VALUES (0, 0),(0, 0),(1, 0),(1, 0),(1, 1)")
  673. res := dbt.mustExec("UPDATE test SET data = 1 WHERE id = 0")
  674. count, err := res.RowsAffected()
  675. if err != nil {
  676. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  677. }
  678. if count != 2 {
  679. dbt.Fatalf("Expected 2 matched rows, got %d", count)
  680. }
  681. res = dbt.mustExec("UPDATE test SET data = 1 WHERE id = 1")
  682. count, err = res.RowsAffected()
  683. if err != nil {
  684. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  685. }
  686. if count != 3 {
  687. dbt.Fatalf("Expected 3 matched rows, got %d", count)
  688. }
  689. })
  690. }
  691. func TestStrict(t *testing.T) {
  692. // ALLOW_INVALID_DATES to get rid of stricter modes - we want to test for warnings, not errors
  693. relaxedDsn := dsn + "&sql_mode=ALLOW_INVALID_DATES"
  694. runTests(t, relaxedDsn, func(dbt *DBTest) {
  695. dbt.mustExec("CREATE TABLE test (a TINYINT NOT NULL, b CHAR(4))")
  696. var queries = [...]struct {
  697. in string
  698. codes []string
  699. }{
  700. {"DROP TABLE IF EXISTS no_such_table", []string{"1051"}},
  701. {"INSERT INTO test VALUES(10,'mysql'),(NULL,'test'),(300,'Open Source')", []string{"1265", "1048", "1264", "1265"}},
  702. }
  703. var err error
  704. var checkWarnings = func(err error, mode string, idx int) {
  705. if err == nil {
  706. dbt.Errorf("Expected STRICT error on query [%s] %s", mode, queries[idx].in)
  707. }
  708. if warnings, ok := err.(MySQLWarnings); ok {
  709. var codes = make([]string, len(warnings))
  710. for i := range warnings {
  711. codes[i] = warnings[i].Code
  712. }
  713. if len(codes) != len(queries[idx].codes) {
  714. dbt.Errorf("Unexpected STRICT error count on query [%s] %s: Wanted %v, Got %v", mode, queries[idx].in, queries[idx].codes, codes)
  715. }
  716. for i := range warnings {
  717. if codes[i] != queries[idx].codes[i] {
  718. dbt.Errorf("Unexpected STRICT error codes on query [%s] %s: Wanted %v, Got %v", mode, queries[idx].in, queries[idx].codes, codes)
  719. return
  720. }
  721. }
  722. } else {
  723. dbt.Errorf("Unexpected error on query [%s] %s: %s", mode, queries[idx].in, err.Error())
  724. }
  725. }
  726. // text protocol
  727. for i := range queries {
  728. _, err = dbt.db.Exec(queries[i].in)
  729. checkWarnings(err, "text", i)
  730. }
  731. var stmt *sql.Stmt
  732. // binary protocol
  733. for i := range queries {
  734. stmt, err = dbt.db.Prepare(queries[i].in)
  735. if err != nil {
  736. dbt.Errorf("Error on preparing query %s: %s", queries[i].in, err.Error())
  737. }
  738. _, err = stmt.Exec()
  739. checkWarnings(err, "binary", i)
  740. err = stmt.Close()
  741. if err != nil {
  742. dbt.Errorf("Error on closing stmt for query %s: %s", queries[i].in, err.Error())
  743. }
  744. }
  745. })
  746. }
  747. func TestTLS(t *testing.T) {
  748. tlsTest := func(dbt *DBTest) {
  749. if err := dbt.db.Ping(); err != nil {
  750. if err == ErrNoTLS {
  751. dbt.Skip("Server does not support TLS")
  752. } else {
  753. dbt.Fatalf("Error on Ping: %s", err.Error())
  754. }
  755. }
  756. rows := dbt.mustQuery("SHOW STATUS LIKE 'Ssl_cipher'")
  757. var variable, value *sql.RawBytes
  758. for rows.Next() {
  759. if err := rows.Scan(&variable, &value); err != nil {
  760. dbt.Fatal(err.Error())
  761. }
  762. if value == nil {
  763. dbt.Fatal("No Cipher")
  764. }
  765. }
  766. }
  767. runTests(t, dsn+"&tls=skip-verify", tlsTest)
  768. // Verify that registering / using a custom cfg works
  769. RegisterTLSConfig("custom-skip-verify", &tls.Config{
  770. InsecureSkipVerify: true,
  771. })
  772. runTests(t, dsn+"&tls=custom-skip-verify", tlsTest)
  773. }
  774. func TestReuseClosedConnection(t *testing.T) {
  775. // this test does not use sql.database, it uses the driver directly
  776. if !available {
  777. t.Skipf("MySQL-Server not running on %s", netAddr)
  778. }
  779. md := &MySQLDriver{}
  780. conn, err := md.Open(dsn)
  781. if err != nil {
  782. t.Fatalf("Error connecting: %s", err.Error())
  783. }
  784. stmt, err := conn.Prepare("DO 1")
  785. if err != nil {
  786. t.Fatalf("Error preparing statement: %s", err.Error())
  787. }
  788. _, err = stmt.Exec(nil)
  789. if err != nil {
  790. t.Fatalf("Error executing statement: %s", err.Error())
  791. }
  792. err = conn.Close()
  793. if err != nil {
  794. t.Fatalf("Error closing connection: %s", err.Error())
  795. }
  796. defer func() {
  797. if err := recover(); err != nil {
  798. t.Errorf("Panic after reusing a closed connection: %v", err)
  799. }
  800. }()
  801. _, err = stmt.Exec(nil)
  802. if err != nil && err != driver.ErrBadConn {
  803. t.Errorf("Unexpected error '%s', expected '%s'",
  804. err.Error(), driver.ErrBadConn.Error())
  805. }
  806. }
  807. func TestCharset(t *testing.T) {
  808. if !available {
  809. t.Skipf("MySQL-Server not running on %s", netAddr)
  810. }
  811. mustSetCharset := func(charsetParam, expected string) {
  812. runTests(t, dsn+"&"+charsetParam, func(dbt *DBTest) {
  813. rows := dbt.mustQuery("SELECT @@character_set_connection")
  814. defer rows.Close()
  815. if !rows.Next() {
  816. dbt.Fatalf("Error getting connection charset: %s", rows.Err())
  817. }
  818. var got string
  819. rows.Scan(&got)
  820. if got != expected {
  821. dbt.Fatalf("Expected connection charset %s but got %s", expected, got)
  822. }
  823. })
  824. }
  825. // non utf8 test
  826. mustSetCharset("charset=ascii", "ascii")
  827. // when the first charset is invalid, use the second
  828. mustSetCharset("charset=none,utf8", "utf8")
  829. // when the first charset is valid, use it
  830. mustSetCharset("charset=ascii,utf8", "ascii")
  831. mustSetCharset("charset=utf8,ascii", "utf8")
  832. }
  833. func TestFailingCharset(t *testing.T) {
  834. runTests(t, dsn+"&charset=none", func(dbt *DBTest) {
  835. // run query to really establish connection...
  836. _, err := dbt.db.Exec("SELECT 1")
  837. if err == nil {
  838. dbt.db.Close()
  839. t.Fatalf("Connection must not succeed without a valid charset")
  840. }
  841. })
  842. }
  843. func TestCollation(t *testing.T) {
  844. if !available {
  845. t.Skipf("MySQL-Server not running on %s", netAddr)
  846. }
  847. defaultCollation := "utf8_general_ci"
  848. testCollations := []string{
  849. "", // do not set
  850. defaultCollation, // driver default
  851. "latin1_general_ci",
  852. "binary",
  853. "utf8_unicode_ci",
  854. "utf8mb4_general_ci",
  855. }
  856. for _, collation := range testCollations {
  857. var expected, tdsn string
  858. if collation != "" {
  859. tdsn = dsn + "&collation=" + collation
  860. expected = collation
  861. } else {
  862. tdsn = dsn
  863. expected = defaultCollation
  864. }
  865. runTests(t, tdsn, func(dbt *DBTest) {
  866. var got string
  867. if err := dbt.db.QueryRow("SELECT @@collation_connection").Scan(&got); err != nil {
  868. dbt.Fatal(err)
  869. }
  870. if got != expected {
  871. dbt.Fatalf("Expected connection collation %s but got %s", expected, got)
  872. }
  873. })
  874. }
  875. }
  876. func TestRawBytesResultExceedsBuffer(t *testing.T) {
  877. runTests(t, dsn, func(dbt *DBTest) {
  878. // defaultBufSize from buffer.go
  879. expected := strings.Repeat("abc", defaultBufSize)
  880. rows := dbt.mustQuery("SELECT '" + expected + "'")
  881. defer rows.Close()
  882. if !rows.Next() {
  883. dbt.Error("expected result, got none")
  884. }
  885. var result sql.RawBytes
  886. rows.Scan(&result)
  887. if expected != string(result) {
  888. dbt.Error("result did not match expected value")
  889. }
  890. })
  891. }
  892. func TestTimezoneConversion(t *testing.T) {
  893. zones := []string{"UTC", "US/Central", "US/Pacific", "Local"}
  894. // Regression test for timezone handling
  895. tzTest := func(dbt *DBTest) {
  896. // Create table
  897. dbt.mustExec("CREATE TABLE test (ts TIMESTAMP)")
  898. // Insert local time into database (should be converted)
  899. usCentral, _ := time.LoadLocation("US/Central")
  900. now := time.Now().In(usCentral)
  901. dbt.mustExec("INSERT INTO test VALUE (?)", now)
  902. // Retrieve time from DB
  903. rows := dbt.mustQuery("SELECT ts FROM test")
  904. if !rows.Next() {
  905. dbt.Fatal("Didn't get any rows out")
  906. }
  907. var nowDB time.Time
  908. err := rows.Scan(&nowDB)
  909. if err != nil {
  910. dbt.Fatal("Err", err)
  911. }
  912. // Check that dates match
  913. if now.Unix() != nowDB.Unix() {
  914. dbt.Errorf("Times don't match.\n")
  915. dbt.Errorf(" Now(%v)=%v\n", usCentral, now)
  916. dbt.Errorf(" Now(UTC)=%v\n", nowDB)
  917. }
  918. }
  919. for _, tz := range zones {
  920. runTests(t, dsn+"&parseTime=true&loc="+url.QueryEscape(tz), tzTest)
  921. }
  922. }
  923. // This tests for https://github.com/go-sql-driver/mysql/pull/139
  924. //
  925. // An extra (invisible) nil byte was being added to the beginning of positive
  926. // time strings.
  927. func TestTimeSign(t *testing.T) {
  928. runTests(t, dsn, func(dbt *DBTest) {
  929. var sTimes = []struct {
  930. value string
  931. fieldType string
  932. }{
  933. {"12:34:56", "TIME"},
  934. {"-12:34:56", "TIME"},
  935. // As described in http://dev.mysql.com/doc/refman/5.6/en/fractional-seconds.html
  936. // they *should* work, but only in 5.6+.
  937. // { "12:34:56.789", "TIME(3)" },
  938. // { "-12:34:56.789", "TIME(3)" },
  939. }
  940. for _, sTime := range sTimes {
  941. dbt.db.Exec("DROP TABLE IF EXISTS test")
  942. dbt.mustExec("CREATE TABLE test (id INT, time_field " + sTime.fieldType + ")")
  943. dbt.mustExec("INSERT INTO test (id, time_field) VALUES(1, '" + sTime.value + "')")
  944. rows := dbt.mustQuery("SELECT time_field FROM test WHERE id = ?", 1)
  945. if rows.Next() {
  946. var oTime string
  947. rows.Scan(&oTime)
  948. if oTime != sTime.value {
  949. dbt.Errorf(`time values differ: got %q, expected %q.`, oTime, sTime.value)
  950. }
  951. } else {
  952. dbt.Error("expecting at least one row.")
  953. }
  954. }
  955. })
  956. }
  957. // Special cases
  958. func TestRowsClose(t *testing.T) {
  959. runTests(t, dsn, func(dbt *DBTest) {
  960. rows, err := dbt.db.Query("SELECT 1")
  961. if err != nil {
  962. dbt.Fatal(err)
  963. }
  964. err = rows.Close()
  965. if err != nil {
  966. dbt.Fatal(err)
  967. }
  968. if rows.Next() {
  969. dbt.Fatal("Unexpected row after rows.Close()")
  970. }
  971. err = rows.Err()
  972. if err != nil {
  973. dbt.Fatal(err)
  974. }
  975. })
  976. }
  977. // dangling statements
  978. // http://code.google.com/p/go/issues/detail?id=3865
  979. func TestCloseStmtBeforeRows(t *testing.T) {
  980. runTests(t, dsn, func(dbt *DBTest) {
  981. stmt, err := dbt.db.Prepare("SELECT 1")
  982. if err != nil {
  983. dbt.Fatal(err)
  984. }
  985. rows, err := stmt.Query()
  986. if err != nil {
  987. stmt.Close()
  988. dbt.Fatal(err)
  989. }
  990. defer rows.Close()
  991. err = stmt.Close()
  992. if err != nil {
  993. dbt.Fatal(err)
  994. }
  995. if !rows.Next() {
  996. dbt.Fatal("Getting row failed")
  997. } else {
  998. err = rows.Err()
  999. if err != nil {
  1000. dbt.Fatal(err)
  1001. }
  1002. var out bool
  1003. err = rows.Scan(&out)
  1004. if err != nil {
  1005. dbt.Fatalf("Error on rows.Scan(): %s", err.Error())
  1006. }
  1007. if out != true {
  1008. dbt.Errorf("true != %t", out)
  1009. }
  1010. }
  1011. })
  1012. }
  1013. // It is valid to have multiple Rows for the same Stmt
  1014. // http://code.google.com/p/go/issues/detail?id=3734
  1015. func TestStmtMultiRows(t *testing.T) {
  1016. runTests(t, dsn, func(dbt *DBTest) {
  1017. stmt, err := dbt.db.Prepare("SELECT 1 UNION SELECT 0")
  1018. if err != nil {
  1019. dbt.Fatal(err)
  1020. }
  1021. rows1, err := stmt.Query()
  1022. if err != nil {
  1023. stmt.Close()
  1024. dbt.Fatal(err)
  1025. }
  1026. defer rows1.Close()
  1027. rows2, err := stmt.Query()
  1028. if err != nil {
  1029. stmt.Close()
  1030. dbt.Fatal(err)
  1031. }
  1032. defer rows2.Close()
  1033. var out bool
  1034. // 1
  1035. if !rows1.Next() {
  1036. dbt.Fatal("1st rows1.Next failed")
  1037. } else {
  1038. err = rows1.Err()
  1039. if err != nil {
  1040. dbt.Fatal(err)
  1041. }
  1042. err = rows1.Scan(&out)
  1043. if err != nil {
  1044. dbt.Fatalf("Error on rows.Scan(): %s", err.Error())
  1045. }
  1046. if out != true {
  1047. dbt.Errorf("true != %t", out)
  1048. }
  1049. }
  1050. if !rows2.Next() {
  1051. dbt.Fatal("1st rows2.Next failed")
  1052. } else {
  1053. err = rows2.Err()
  1054. if err != nil {
  1055. dbt.Fatal(err)
  1056. }
  1057. err = rows2.Scan(&out)
  1058. if err != nil {
  1059. dbt.Fatalf("Error on rows.Scan(): %s", err.Error())
  1060. }
  1061. if out != true {
  1062. dbt.Errorf("true != %t", out)
  1063. }
  1064. }
  1065. // 2
  1066. if !rows1.Next() {
  1067. dbt.Fatal("2nd rows1.Next failed")
  1068. } else {
  1069. err = rows1.Err()
  1070. if err != nil {
  1071. dbt.Fatal(err)
  1072. }
  1073. err = rows1.Scan(&out)
  1074. if err != nil {
  1075. dbt.Fatalf("Error on rows.Scan(): %s", err.Error())
  1076. }
  1077. if out != false {
  1078. dbt.Errorf("false != %t", out)
  1079. }
  1080. if rows1.Next() {
  1081. dbt.Fatal("Unexpected row on rows1")
  1082. }
  1083. err = rows1.Close()
  1084. if err != nil {
  1085. dbt.Fatal(err)
  1086. }
  1087. }
  1088. if !rows2.Next() {
  1089. dbt.Fatal("2nd rows2.Next failed")
  1090. } else {
  1091. err = rows2.Err()
  1092. if err != nil {
  1093. dbt.Fatal(err)
  1094. }
  1095. err = rows2.Scan(&out)
  1096. if err != nil {
  1097. dbt.Fatalf("Error on rows.Scan(): %s", err.Error())
  1098. }
  1099. if out != false {
  1100. dbt.Errorf("false != %t", out)
  1101. }
  1102. if rows2.Next() {
  1103. dbt.Fatal("Unexpected row on rows2")
  1104. }
  1105. err = rows2.Close()
  1106. if err != nil {
  1107. dbt.Fatal(err)
  1108. }
  1109. }
  1110. })
  1111. }
  1112. // Regression test for
  1113. // * more than 32 NULL parameters (issue 209)
  1114. // * more parameters than fit into the buffer (issue 201)
  1115. func TestPreparedManyCols(t *testing.T) {
  1116. const numParams = defaultBufSize
  1117. runTests(t, dsn, func(dbt *DBTest) {
  1118. query := "SELECT ?" + strings.Repeat(",?", numParams-1)
  1119. stmt, err := dbt.db.Prepare(query)
  1120. if err != nil {
  1121. dbt.Fatal(err)
  1122. }
  1123. defer stmt.Close()
  1124. // create more parameters than fit into the buffer
  1125. // which will take nil-values
  1126. params := make([]interface{}, numParams)
  1127. rows, err := stmt.Query(params...)
  1128. if err != nil {
  1129. stmt.Close()
  1130. dbt.Fatal(err)
  1131. }
  1132. defer rows.Close()
  1133. })
  1134. }
  1135. func TestConcurrent(t *testing.T) {
  1136. if enabled, _ := readBool(os.Getenv("MYSQL_TEST_CONCURRENT")); !enabled {
  1137. t.Skip("MYSQL_TEST_CONCURRENT env var not set")
  1138. }
  1139. runTests(t, dsn, func(dbt *DBTest) {
  1140. var max int
  1141. err := dbt.db.QueryRow("SELECT @@max_connections").Scan(&max)
  1142. if err != nil {
  1143. dbt.Fatalf("%s", err.Error())
  1144. }
  1145. dbt.Logf("Testing up to %d concurrent connections \r\n", max)
  1146. var remaining, succeeded int32 = int32(max), 0
  1147. var wg sync.WaitGroup
  1148. wg.Add(max)
  1149. var fatalError string
  1150. var once sync.Once
  1151. fatalf := func(s string, vals ...interface{}) {
  1152. once.Do(func() {
  1153. fatalError = fmt.Sprintf(s, vals...)
  1154. })
  1155. }
  1156. for i := 0; i < max; i++ {
  1157. go func(id int) {
  1158. defer wg.Done()
  1159. tx, err := dbt.db.Begin()
  1160. atomic.AddInt32(&remaining, -1)
  1161. if err != nil {
  1162. if err.Error() != "Error 1040: Too many connections" {
  1163. fatalf("Error on Conn %d: %s", id, err.Error())
  1164. }
  1165. return
  1166. }
  1167. // keep the connection busy until all connections are open
  1168. for remaining > 0 {
  1169. if _, err = tx.Exec("DO 1"); err != nil {
  1170. fatalf("Error on Conn %d: %s", id, err.Error())
  1171. return
  1172. }
  1173. }
  1174. if err = tx.Commit(); err != nil {
  1175. fatalf("Error on Conn %d: %s", id, err.Error())
  1176. return
  1177. }
  1178. // everything went fine with this connection
  1179. atomic.AddInt32(&succeeded, 1)
  1180. }(i)
  1181. }
  1182. // wait until all conections are open
  1183. wg.Wait()
  1184. if fatalError != "" {
  1185. dbt.Fatal(fatalError)
  1186. }
  1187. dbt.Logf("Reached %d concurrent connections\r\n", succeeded)
  1188. })
  1189. }
  1190. // Tests custom dial functions
  1191. func TestCustomDial(t *testing.T) {
  1192. if !available {
  1193. t.Skipf("MySQL-Server not running on %s", netAddr)
  1194. }
  1195. // our custom dial function which justs wraps net.Dial here
  1196. RegisterDial("mydial", func(addr string) (net.Conn, error) {
  1197. return net.Dial(prot, addr)
  1198. })
  1199. db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@mydial(%s)/%s?timeout=30s&strict=true", user, pass, addr, dbname))
  1200. if err != nil {
  1201. t.Fatalf("Error connecting: %s", err.Error())
  1202. }
  1203. defer db.Close()
  1204. if _, err = db.Exec("DO 1"); err != nil {
  1205. t.Fatalf("Connection failed: %s", err.Error())
  1206. }
  1207. }