driver_test.go 27 KB

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