driver_test.go 28 KB

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