driver_test.go 31 KB

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