driver_test.go 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996
  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. "bytes"
  11. "context"
  12. "crypto/tls"
  13. "database/sql"
  14. "database/sql/driver"
  15. "fmt"
  16. "io"
  17. "io/ioutil"
  18. "log"
  19. "math"
  20. "net"
  21. "net/url"
  22. "os"
  23. "reflect"
  24. "strings"
  25. "sync"
  26. "sync/atomic"
  27. "testing"
  28. "time"
  29. )
  30. // Ensure that all the driver interfaces are implemented
  31. var (
  32. _ driver.Rows = &binaryRows{}
  33. _ driver.Rows = &textRows{}
  34. )
  35. var (
  36. user string
  37. pass string
  38. prot string
  39. addr string
  40. dbname string
  41. dsn string
  42. netAddr string
  43. available bool
  44. )
  45. var (
  46. tDate = time.Date(2012, 6, 14, 0, 0, 0, 0, time.UTC)
  47. sDate = "2012-06-14"
  48. tDateTime = time.Date(2011, 11, 20, 21, 27, 37, 0, time.UTC)
  49. sDateTime = "2011-11-20 21:27:37"
  50. tDate0 = time.Time{}
  51. sDate0 = "0000-00-00"
  52. sDateTime0 = "0000-00-00 00:00:00"
  53. )
  54. // See https://github.com/go-sql-driver/mysql/wiki/Testing
  55. func init() {
  56. // get environment variables
  57. env := func(key, defaultValue string) string {
  58. if value := os.Getenv(key); value != "" {
  59. return value
  60. }
  61. return defaultValue
  62. }
  63. user = env("MYSQL_TEST_USER", "root")
  64. pass = env("MYSQL_TEST_PASS", "")
  65. prot = env("MYSQL_TEST_PROT", "tcp")
  66. addr = env("MYSQL_TEST_ADDR", "localhost:3306")
  67. dbname = env("MYSQL_TEST_DBNAME", "gotest")
  68. netAddr = fmt.Sprintf("%s(%s)", prot, addr)
  69. dsn = fmt.Sprintf("%s:%s@%s/%s?timeout=30s", user, pass, netAddr, dbname)
  70. c, err := net.Dial(prot, addr)
  71. if err == nil {
  72. available = true
  73. c.Close()
  74. }
  75. }
  76. type DBTest struct {
  77. *testing.T
  78. db *sql.DB
  79. }
  80. type netErrorMock struct {
  81. temporary bool
  82. timeout bool
  83. }
  84. func (e netErrorMock) Temporary() bool {
  85. return e.temporary
  86. }
  87. func (e netErrorMock) Timeout() bool {
  88. return e.timeout
  89. }
  90. func (e netErrorMock) Error() string {
  91. return fmt.Sprintf("mock net error. Temporary: %v, Timeout %v", e.temporary, e.timeout)
  92. }
  93. func runTestsWithMultiStatement(t *testing.T, dsn string, tests ...func(dbt *DBTest)) {
  94. if !available {
  95. t.Skipf("MySQL server not running on %s", netAddr)
  96. }
  97. dsn += "&multiStatements=true"
  98. var db *sql.DB
  99. if _, err := ParseDSN(dsn); err != errInvalidDSNUnsafeCollation {
  100. db, err = sql.Open("mysql", dsn)
  101. if err != nil {
  102. t.Fatalf("error connecting: %s", err.Error())
  103. }
  104. defer db.Close()
  105. }
  106. dbt := &DBTest{t, db}
  107. for _, test := range tests {
  108. test(dbt)
  109. dbt.db.Exec("DROP TABLE IF EXISTS test")
  110. }
  111. }
  112. func runTests(t *testing.T, dsn string, tests ...func(dbt *DBTest)) {
  113. if !available {
  114. t.Skipf("MySQL server not running on %s", netAddr)
  115. }
  116. db, err := sql.Open("mysql", dsn)
  117. if err != nil {
  118. t.Fatalf("error connecting: %s", err.Error())
  119. }
  120. defer db.Close()
  121. db.Exec("DROP TABLE IF EXISTS test")
  122. dsn2 := dsn + "&interpolateParams=true"
  123. var db2 *sql.DB
  124. if _, err := ParseDSN(dsn2); err != errInvalidDSNUnsafeCollation {
  125. db2, err = sql.Open("mysql", dsn2)
  126. if err != nil {
  127. t.Fatalf("error connecting: %s", err.Error())
  128. }
  129. defer db2.Close()
  130. }
  131. dsn3 := dsn + "&multiStatements=true"
  132. var db3 *sql.DB
  133. if _, err := ParseDSN(dsn3); err != errInvalidDSNUnsafeCollation {
  134. db3, err = sql.Open("mysql", dsn3)
  135. if err != nil {
  136. t.Fatalf("error connecting: %s", err.Error())
  137. }
  138. defer db3.Close()
  139. }
  140. dbt := &DBTest{t, db}
  141. dbt2 := &DBTest{t, db2}
  142. dbt3 := &DBTest{t, db3}
  143. for _, test := range tests {
  144. test(dbt)
  145. dbt.db.Exec("DROP TABLE IF EXISTS test")
  146. if db2 != nil {
  147. test(dbt2)
  148. dbt2.db.Exec("DROP TABLE IF EXISTS test")
  149. }
  150. if db3 != nil {
  151. test(dbt3)
  152. dbt3.db.Exec("DROP TABLE IF EXISTS test")
  153. }
  154. }
  155. }
  156. func (dbt *DBTest) fail(method, query string, err error) {
  157. if len(query) > 300 {
  158. query = "[query too large to print]"
  159. }
  160. dbt.Fatalf("error on %s %s: %s", method, query, err.Error())
  161. }
  162. func (dbt *DBTest) mustExec(query string, args ...interface{}) (res sql.Result) {
  163. res, err := dbt.db.Exec(query, args...)
  164. if err != nil {
  165. dbt.fail("exec", query, err)
  166. }
  167. return res
  168. }
  169. func (dbt *DBTest) mustQuery(query string, args ...interface{}) (rows *sql.Rows) {
  170. rows, err := dbt.db.Query(query, args...)
  171. if err != nil {
  172. dbt.fail("query", query, err)
  173. }
  174. return rows
  175. }
  176. func maybeSkip(t *testing.T, err error, skipErrno uint16) {
  177. mySQLErr, ok := err.(*MySQLError)
  178. if !ok {
  179. return
  180. }
  181. if mySQLErr.Number == skipErrno {
  182. t.Skipf("skipping test for error: %v", err)
  183. }
  184. }
  185. func TestEmptyQuery(t *testing.T) {
  186. runTests(t, dsn, func(dbt *DBTest) {
  187. // just a comment, no query
  188. rows := dbt.mustQuery("--")
  189. defer rows.Close()
  190. // will hang before #255
  191. if rows.Next() {
  192. dbt.Errorf("next on rows must be false")
  193. }
  194. })
  195. }
  196. func TestCRUD(t *testing.T) {
  197. runTests(t, dsn, func(dbt *DBTest) {
  198. // Create Table
  199. dbt.mustExec("CREATE TABLE test (value BOOL)")
  200. // Test for unexpected data
  201. var out bool
  202. rows := dbt.mustQuery("SELECT * FROM test")
  203. if rows.Next() {
  204. dbt.Error("unexpected data in empty table")
  205. }
  206. rows.Close()
  207. // Create Data
  208. res := dbt.mustExec("INSERT INTO test VALUES (1)")
  209. count, err := res.RowsAffected()
  210. if err != nil {
  211. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  212. }
  213. if count != 1 {
  214. dbt.Fatalf("expected 1 affected row, got %d", count)
  215. }
  216. id, err := res.LastInsertId()
  217. if err != nil {
  218. dbt.Fatalf("res.LastInsertId() returned error: %s", err.Error())
  219. }
  220. if id != 0 {
  221. dbt.Fatalf("expected InsertId 0, got %d", id)
  222. }
  223. // Read
  224. rows = dbt.mustQuery("SELECT value FROM test")
  225. if rows.Next() {
  226. rows.Scan(&out)
  227. if true != out {
  228. dbt.Errorf("true != %t", out)
  229. }
  230. if rows.Next() {
  231. dbt.Error("unexpected data")
  232. }
  233. } else {
  234. dbt.Error("no data")
  235. }
  236. rows.Close()
  237. // Update
  238. res = dbt.mustExec("UPDATE test SET value = ? WHERE value = ?", false, true)
  239. count, err = res.RowsAffected()
  240. if err != nil {
  241. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  242. }
  243. if count != 1 {
  244. dbt.Fatalf("expected 1 affected row, got %d", count)
  245. }
  246. // Check Update
  247. rows = dbt.mustQuery("SELECT value FROM test")
  248. if rows.Next() {
  249. rows.Scan(&out)
  250. if false != out {
  251. dbt.Errorf("false != %t", out)
  252. }
  253. if rows.Next() {
  254. dbt.Error("unexpected data")
  255. }
  256. } else {
  257. dbt.Error("no data")
  258. }
  259. rows.Close()
  260. // Delete
  261. res = dbt.mustExec("DELETE FROM test WHERE value = ?", false)
  262. count, err = res.RowsAffected()
  263. if err != nil {
  264. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  265. }
  266. if count != 1 {
  267. dbt.Fatalf("expected 1 affected row, got %d", count)
  268. }
  269. // Check for unexpected rows
  270. res = dbt.mustExec("DELETE FROM test")
  271. count, err = res.RowsAffected()
  272. if err != nil {
  273. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  274. }
  275. if count != 0 {
  276. dbt.Fatalf("expected 0 affected row, got %d", count)
  277. }
  278. })
  279. }
  280. func TestMultiQuery(t *testing.T) {
  281. runTestsWithMultiStatement(t, dsn, func(dbt *DBTest) {
  282. // Create Table
  283. dbt.mustExec("CREATE TABLE `test` (`id` int(11) NOT NULL, `value` int(11) NOT NULL) ")
  284. // Create Data
  285. res := dbt.mustExec("INSERT INTO test VALUES (1, 1)")
  286. count, err := res.RowsAffected()
  287. if err != nil {
  288. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  289. }
  290. if count != 1 {
  291. dbt.Fatalf("expected 1 affected row, got %d", count)
  292. }
  293. // Update
  294. res = dbt.mustExec("UPDATE test SET value = 3 WHERE id = 1; UPDATE test SET value = 4 WHERE id = 1; UPDATE test SET value = 5 WHERE id = 1;")
  295. count, err = res.RowsAffected()
  296. if err != nil {
  297. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  298. }
  299. if count != 1 {
  300. dbt.Fatalf("expected 1 affected row, got %d", count)
  301. }
  302. // Read
  303. var out int
  304. rows := dbt.mustQuery("SELECT value FROM test WHERE id=1;")
  305. if rows.Next() {
  306. rows.Scan(&out)
  307. if 5 != out {
  308. dbt.Errorf("5 != %d", out)
  309. }
  310. if rows.Next() {
  311. dbt.Error("unexpected data")
  312. }
  313. } else {
  314. dbt.Error("no data")
  315. }
  316. rows.Close()
  317. })
  318. }
  319. func TestInt(t *testing.T) {
  320. runTests(t, dsn, func(dbt *DBTest) {
  321. types := [5]string{"TINYINT", "SMALLINT", "MEDIUMINT", "INT", "BIGINT"}
  322. in := int64(42)
  323. var out int64
  324. var rows *sql.Rows
  325. // SIGNED
  326. for _, v := range types {
  327. dbt.mustExec("CREATE TABLE test (value " + v + ")")
  328. dbt.mustExec("INSERT INTO test VALUES (?)", in)
  329. rows = dbt.mustQuery("SELECT value FROM test")
  330. if rows.Next() {
  331. rows.Scan(&out)
  332. if in != out {
  333. dbt.Errorf("%s: %d != %d", v, in, out)
  334. }
  335. } else {
  336. dbt.Errorf("%s: no data", v)
  337. }
  338. rows.Close()
  339. dbt.mustExec("DROP TABLE IF EXISTS test")
  340. }
  341. // UNSIGNED ZEROFILL
  342. for _, v := range types {
  343. dbt.mustExec("CREATE TABLE test (value " + v + " ZEROFILL)")
  344. dbt.mustExec("INSERT INTO test VALUES (?)", in)
  345. rows = dbt.mustQuery("SELECT value FROM test")
  346. if rows.Next() {
  347. rows.Scan(&out)
  348. if in != out {
  349. dbt.Errorf("%s ZEROFILL: %d != %d", v, in, out)
  350. }
  351. } else {
  352. dbt.Errorf("%s ZEROFILL: no data", v)
  353. }
  354. rows.Close()
  355. dbt.mustExec("DROP TABLE IF EXISTS test")
  356. }
  357. })
  358. }
  359. func TestFloat32(t *testing.T) {
  360. runTests(t, dsn, func(dbt *DBTest) {
  361. types := [2]string{"FLOAT", "DOUBLE"}
  362. in := float32(42.23)
  363. var out float32
  364. var rows *sql.Rows
  365. for _, v := range types {
  366. dbt.mustExec("CREATE TABLE test (value " + v + ")")
  367. dbt.mustExec("INSERT INTO test VALUES (?)", in)
  368. rows = dbt.mustQuery("SELECT value FROM test")
  369. if rows.Next() {
  370. rows.Scan(&out)
  371. if in != out {
  372. dbt.Errorf("%s: %g != %g", v, in, out)
  373. }
  374. } else {
  375. dbt.Errorf("%s: no data", v)
  376. }
  377. rows.Close()
  378. dbt.mustExec("DROP TABLE IF EXISTS test")
  379. }
  380. })
  381. }
  382. func TestFloat64(t *testing.T) {
  383. runTests(t, dsn, func(dbt *DBTest) {
  384. types := [2]string{"FLOAT", "DOUBLE"}
  385. var expected float64 = 42.23
  386. var out float64
  387. var rows *sql.Rows
  388. for _, v := range types {
  389. dbt.mustExec("CREATE TABLE test (value " + v + ")")
  390. dbt.mustExec("INSERT INTO test VALUES (42.23)")
  391. rows = dbt.mustQuery("SELECT value FROM test")
  392. if rows.Next() {
  393. rows.Scan(&out)
  394. if expected != out {
  395. dbt.Errorf("%s: %g != %g", v, expected, out)
  396. }
  397. } else {
  398. dbt.Errorf("%s: no data", v)
  399. }
  400. rows.Close()
  401. dbt.mustExec("DROP TABLE IF EXISTS test")
  402. }
  403. })
  404. }
  405. func TestFloat64Placeholder(t *testing.T) {
  406. runTests(t, dsn, func(dbt *DBTest) {
  407. types := [2]string{"FLOAT", "DOUBLE"}
  408. var expected float64 = 42.23
  409. var out float64
  410. var rows *sql.Rows
  411. for _, v := range types {
  412. dbt.mustExec("CREATE TABLE test (id int, value " + v + ")")
  413. dbt.mustExec("INSERT INTO test VALUES (1, 42.23)")
  414. rows = dbt.mustQuery("SELECT value FROM test WHERE id = ?", 1)
  415. if rows.Next() {
  416. rows.Scan(&out)
  417. if expected != out {
  418. dbt.Errorf("%s: %g != %g", v, expected, out)
  419. }
  420. } else {
  421. dbt.Errorf("%s: no data", v)
  422. }
  423. rows.Close()
  424. dbt.mustExec("DROP TABLE IF EXISTS test")
  425. }
  426. })
  427. }
  428. func TestString(t *testing.T) {
  429. runTests(t, dsn, func(dbt *DBTest) {
  430. types := [6]string{"CHAR(255)", "VARCHAR(255)", "TINYTEXT", "TEXT", "MEDIUMTEXT", "LONGTEXT"}
  431. in := "κόσμε üöäßñóùéàâÿœ'îë Árvíztűrő いろはにほへとちりぬるを イロハニホヘト דג סקרן чащах น่าฟังเอย"
  432. var out string
  433. var rows *sql.Rows
  434. for _, v := range types {
  435. dbt.mustExec("CREATE TABLE test (value " + v + ") CHARACTER SET utf8")
  436. dbt.mustExec("INSERT INTO test VALUES (?)", in)
  437. rows = dbt.mustQuery("SELECT value FROM test")
  438. if rows.Next() {
  439. rows.Scan(&out)
  440. if in != out {
  441. dbt.Errorf("%s: %s != %s", v, in, out)
  442. }
  443. } else {
  444. dbt.Errorf("%s: no data", v)
  445. }
  446. rows.Close()
  447. dbt.mustExec("DROP TABLE IF EXISTS test")
  448. }
  449. // BLOB
  450. dbt.mustExec("CREATE TABLE test (id int, value BLOB) CHARACTER SET utf8")
  451. id := 2
  452. in = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, " +
  453. "sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, " +
  454. "sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. " +
  455. "Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. " +
  456. "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, " +
  457. "sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, " +
  458. "sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. " +
  459. "Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."
  460. dbt.mustExec("INSERT INTO test VALUES (?, ?)", id, in)
  461. err := dbt.db.QueryRow("SELECT value FROM test WHERE id = ?", id).Scan(&out)
  462. if err != nil {
  463. dbt.Fatalf("Error on BLOB-Query: %s", err.Error())
  464. } else if out != in {
  465. dbt.Errorf("BLOB: %s != %s", in, out)
  466. }
  467. })
  468. }
  469. func TestRawBytes(t *testing.T) {
  470. runTests(t, dsn, func(dbt *DBTest) {
  471. v1 := []byte("aaa")
  472. v2 := []byte("bbb")
  473. rows := dbt.mustQuery("SELECT ?, ?", v1, v2)
  474. defer rows.Close()
  475. if rows.Next() {
  476. var o1, o2 sql.RawBytes
  477. if err := rows.Scan(&o1, &o2); err != nil {
  478. dbt.Errorf("Got error: %v", err)
  479. }
  480. if !bytes.Equal(v1, o1) {
  481. dbt.Errorf("expected %v, got %v", v1, o1)
  482. }
  483. if !bytes.Equal(v2, o2) {
  484. dbt.Errorf("expected %v, got %v", v2, o2)
  485. }
  486. // https://github.com/go-sql-driver/mysql/issues/765
  487. // Appending to RawBytes shouldn't overwrite next RawBytes.
  488. o1 = append(o1, "xyzzy"...)
  489. if !bytes.Equal(v2, o2) {
  490. dbt.Errorf("expected %v, got %v", v2, o2)
  491. }
  492. } else {
  493. dbt.Errorf("no data")
  494. }
  495. })
  496. }
  497. type testValuer struct {
  498. value string
  499. }
  500. func (tv testValuer) Value() (driver.Value, error) {
  501. return tv.value, nil
  502. }
  503. func TestValuer(t *testing.T) {
  504. runTests(t, dsn, func(dbt *DBTest) {
  505. in := testValuer{"a_value"}
  506. var out string
  507. var rows *sql.Rows
  508. dbt.mustExec("CREATE TABLE test (value VARCHAR(255)) CHARACTER SET utf8")
  509. dbt.mustExec("INSERT INTO test VALUES (?)", in)
  510. rows = dbt.mustQuery("SELECT value FROM test")
  511. if rows.Next() {
  512. rows.Scan(&out)
  513. if in.value != out {
  514. dbt.Errorf("Valuer: %v != %s", in, out)
  515. }
  516. } else {
  517. dbt.Errorf("Valuer: no data")
  518. }
  519. rows.Close()
  520. dbt.mustExec("DROP TABLE IF EXISTS test")
  521. })
  522. }
  523. type testValuerWithValidation struct {
  524. value string
  525. }
  526. func (tv testValuerWithValidation) Value() (driver.Value, error) {
  527. if len(tv.value) == 0 {
  528. return nil, fmt.Errorf("Invalid string valuer. Value must not be empty")
  529. }
  530. return tv.value, nil
  531. }
  532. func TestValuerWithValidation(t *testing.T) {
  533. runTests(t, dsn, func(dbt *DBTest) {
  534. in := testValuerWithValidation{"a_value"}
  535. var out string
  536. var rows *sql.Rows
  537. dbt.mustExec("CREATE TABLE testValuer (value VARCHAR(255)) CHARACTER SET utf8")
  538. dbt.mustExec("INSERT INTO testValuer VALUES (?)", in)
  539. rows = dbt.mustQuery("SELECT value FROM testValuer")
  540. defer rows.Close()
  541. if rows.Next() {
  542. rows.Scan(&out)
  543. if in.value != out {
  544. dbt.Errorf("Valuer: %v != %s", in, out)
  545. }
  546. } else {
  547. dbt.Errorf("Valuer: no data")
  548. }
  549. if _, err := dbt.db.Exec("INSERT INTO testValuer VALUES (?)", testValuerWithValidation{""}); err == nil {
  550. dbt.Errorf("Failed to check valuer error")
  551. }
  552. if _, err := dbt.db.Exec("INSERT INTO testValuer VALUES (?)", nil); err != nil {
  553. dbt.Errorf("Failed to check nil")
  554. }
  555. if _, err := dbt.db.Exec("INSERT INTO testValuer VALUES (?)", map[string]bool{}); err == nil {
  556. dbt.Errorf("Failed to check not valuer")
  557. }
  558. dbt.mustExec("DROP TABLE IF EXISTS testValuer")
  559. })
  560. }
  561. type timeTests struct {
  562. dbtype string
  563. tlayout string
  564. tests []timeTest
  565. }
  566. type timeTest struct {
  567. s string // leading "!": do not use t as value in queries
  568. t time.Time
  569. }
  570. type timeMode byte
  571. func (t timeMode) String() string {
  572. switch t {
  573. case binaryString:
  574. return "binary:string"
  575. case binaryTime:
  576. return "binary:time.Time"
  577. case textString:
  578. return "text:string"
  579. }
  580. panic("unsupported timeMode")
  581. }
  582. func (t timeMode) Binary() bool {
  583. switch t {
  584. case binaryString, binaryTime:
  585. return true
  586. }
  587. return false
  588. }
  589. const (
  590. binaryString timeMode = iota
  591. binaryTime
  592. textString
  593. )
  594. func (t timeTest) genQuery(dbtype string, mode timeMode) string {
  595. var inner string
  596. if mode.Binary() {
  597. inner = "?"
  598. } else {
  599. inner = `"%s"`
  600. }
  601. return `SELECT cast(` + inner + ` as ` + dbtype + `)`
  602. }
  603. func (t timeTest) run(dbt *DBTest, dbtype, tlayout string, mode timeMode) {
  604. var rows *sql.Rows
  605. query := t.genQuery(dbtype, mode)
  606. switch mode {
  607. case binaryString:
  608. rows = dbt.mustQuery(query, t.s)
  609. case binaryTime:
  610. rows = dbt.mustQuery(query, t.t)
  611. case textString:
  612. query = fmt.Sprintf(query, t.s)
  613. rows = dbt.mustQuery(query)
  614. default:
  615. panic("unsupported mode")
  616. }
  617. defer rows.Close()
  618. var err error
  619. if !rows.Next() {
  620. err = rows.Err()
  621. if err == nil {
  622. err = fmt.Errorf("no data")
  623. }
  624. dbt.Errorf("%s [%s]: %s", dbtype, mode, err)
  625. return
  626. }
  627. var dst interface{}
  628. err = rows.Scan(&dst)
  629. if err != nil {
  630. dbt.Errorf("%s [%s]: %s", dbtype, mode, err)
  631. return
  632. }
  633. switch val := dst.(type) {
  634. case []uint8:
  635. str := string(val)
  636. if str == t.s {
  637. return
  638. }
  639. if mode.Binary() && dbtype == "DATETIME" && len(str) == 26 && str[:19] == t.s {
  640. // a fix mainly for TravisCI:
  641. // accept full microsecond resolution in result for DATETIME columns
  642. // where the binary protocol was used
  643. return
  644. }
  645. dbt.Errorf("%s [%s] to string: expected %q, got %q",
  646. dbtype, mode,
  647. t.s, str,
  648. )
  649. case time.Time:
  650. if val == t.t {
  651. return
  652. }
  653. dbt.Errorf("%s [%s] to string: expected %q, got %q",
  654. dbtype, mode,
  655. t.s, val.Format(tlayout),
  656. )
  657. default:
  658. fmt.Printf("%#v\n", []interface{}{dbtype, tlayout, mode, t.s, t.t})
  659. dbt.Errorf("%s [%s]: unhandled type %T (is '%v')",
  660. dbtype, mode,
  661. val, val,
  662. )
  663. }
  664. }
  665. func TestDateTime(t *testing.T) {
  666. afterTime := func(t time.Time, d string) time.Time {
  667. dur, err := time.ParseDuration(d)
  668. if err != nil {
  669. panic(err)
  670. }
  671. return t.Add(dur)
  672. }
  673. // NOTE: MySQL rounds DATETIME(x) up - but that's not included in the tests
  674. format := "2006-01-02 15:04:05.999999"
  675. t0 := time.Time{}
  676. tstr0 := "0000-00-00 00:00:00.000000"
  677. testcases := []timeTests{
  678. {"DATE", format[:10], []timeTest{
  679. {t: time.Date(2011, 11, 20, 0, 0, 0, 0, time.UTC)},
  680. {t: t0, s: tstr0[:10]},
  681. }},
  682. {"DATETIME", format[:19], []timeTest{
  683. {t: time.Date(2011, 11, 20, 21, 27, 37, 0, time.UTC)},
  684. {t: t0, s: tstr0[:19]},
  685. }},
  686. {"DATETIME(0)", format[:21], []timeTest{
  687. {t: time.Date(2011, 11, 20, 21, 27, 37, 0, time.UTC)},
  688. {t: t0, s: tstr0[:19]},
  689. }},
  690. {"DATETIME(1)", format[:21], []timeTest{
  691. {t: time.Date(2011, 11, 20, 21, 27, 37, 100000000, time.UTC)},
  692. {t: t0, s: tstr0[:21]},
  693. }},
  694. {"DATETIME(6)", format, []timeTest{
  695. {t: time.Date(2011, 11, 20, 21, 27, 37, 123456000, time.UTC)},
  696. {t: t0, s: tstr0},
  697. }},
  698. {"TIME", format[11:19], []timeTest{
  699. {t: afterTime(t0, "12345s")},
  700. {s: "!-12:34:56"},
  701. {s: "!-838:59:59"},
  702. {s: "!838:59:59"},
  703. {t: t0, s: tstr0[11:19]},
  704. }},
  705. {"TIME(0)", format[11:19], []timeTest{
  706. {t: afterTime(t0, "12345s")},
  707. {s: "!-12:34:56"},
  708. {s: "!-838:59:59"},
  709. {s: "!838:59:59"},
  710. {t: t0, s: tstr0[11:19]},
  711. }},
  712. {"TIME(1)", format[11:21], []timeTest{
  713. {t: afterTime(t0, "12345600ms")},
  714. {s: "!-12:34:56.7"},
  715. {s: "!-838:59:58.9"},
  716. {s: "!838:59:58.9"},
  717. {t: t0, s: tstr0[11:21]},
  718. }},
  719. {"TIME(6)", format[11:], []timeTest{
  720. {t: afterTime(t0, "1234567890123000ns")},
  721. {s: "!-12:34:56.789012"},
  722. {s: "!-838:59:58.999999"},
  723. {s: "!838:59:58.999999"},
  724. {t: t0, s: tstr0[11:]},
  725. }},
  726. }
  727. dsns := []string{
  728. dsn + "&parseTime=true",
  729. dsn + "&parseTime=false",
  730. }
  731. for _, testdsn := range dsns {
  732. runTests(t, testdsn, func(dbt *DBTest) {
  733. microsecsSupported := false
  734. zeroDateSupported := false
  735. var rows *sql.Rows
  736. var err error
  737. rows, err = dbt.db.Query(`SELECT cast("00:00:00.1" as TIME(1)) = "00:00:00.1"`)
  738. if err == nil {
  739. rows.Scan(&microsecsSupported)
  740. rows.Close()
  741. }
  742. rows, err = dbt.db.Query(`SELECT cast("0000-00-00" as DATE) = "0000-00-00"`)
  743. if err == nil {
  744. rows.Scan(&zeroDateSupported)
  745. rows.Close()
  746. }
  747. for _, setups := range testcases {
  748. if t := setups.dbtype; !microsecsSupported && t[len(t)-1:] == ")" {
  749. // skip fractional second tests if unsupported by server
  750. continue
  751. }
  752. for _, setup := range setups.tests {
  753. allowBinTime := true
  754. if setup.s == "" {
  755. // fill time string wherever Go can reliable produce it
  756. setup.s = setup.t.Format(setups.tlayout)
  757. } else if setup.s[0] == '!' {
  758. // skip tests using setup.t as source in queries
  759. allowBinTime = false
  760. // fix setup.s - remove the "!"
  761. setup.s = setup.s[1:]
  762. }
  763. if !zeroDateSupported && setup.s == tstr0[:len(setup.s)] {
  764. // skip disallowed 0000-00-00 date
  765. continue
  766. }
  767. setup.run(dbt, setups.dbtype, setups.tlayout, textString)
  768. setup.run(dbt, setups.dbtype, setups.tlayout, binaryString)
  769. if allowBinTime {
  770. setup.run(dbt, setups.dbtype, setups.tlayout, binaryTime)
  771. }
  772. }
  773. }
  774. })
  775. }
  776. }
  777. func TestTimestampMicros(t *testing.T) {
  778. format := "2006-01-02 15:04:05.999999"
  779. f0 := format[:19]
  780. f1 := format[:21]
  781. f6 := format[:26]
  782. runTests(t, dsn, func(dbt *DBTest) {
  783. // check if microseconds are supported.
  784. // Do not use timestamp(x) for that check - before 5.5.6, x would mean display width
  785. // and not precision.
  786. // Se last paragraph at http://dev.mysql.com/doc/refman/5.6/en/fractional-seconds.html
  787. microsecsSupported := false
  788. if rows, err := dbt.db.Query(`SELECT cast("00:00:00.1" as TIME(1)) = "00:00:00.1"`); err == nil {
  789. rows.Scan(&microsecsSupported)
  790. rows.Close()
  791. }
  792. if !microsecsSupported {
  793. // skip test
  794. return
  795. }
  796. _, err := dbt.db.Exec(`
  797. CREATE TABLE test (
  798. value0 TIMESTAMP NOT NULL DEFAULT '` + f0 + `',
  799. value1 TIMESTAMP(1) NOT NULL DEFAULT '` + f1 + `',
  800. value6 TIMESTAMP(6) NOT NULL DEFAULT '` + f6 + `'
  801. )`,
  802. )
  803. if err != nil {
  804. dbt.Error(err)
  805. }
  806. defer dbt.mustExec("DROP TABLE IF EXISTS test")
  807. dbt.mustExec("INSERT INTO test SET value0=?, value1=?, value6=?", f0, f1, f6)
  808. var res0, res1, res6 string
  809. rows := dbt.mustQuery("SELECT * FROM test")
  810. defer rows.Close()
  811. if !rows.Next() {
  812. dbt.Errorf("test contained no selectable values")
  813. }
  814. err = rows.Scan(&res0, &res1, &res6)
  815. if err != nil {
  816. dbt.Error(err)
  817. }
  818. if res0 != f0 {
  819. dbt.Errorf("expected %q, got %q", f0, res0)
  820. }
  821. if res1 != f1 {
  822. dbt.Errorf("expected %q, got %q", f1, res1)
  823. }
  824. if res6 != f6 {
  825. dbt.Errorf("expected %q, got %q", f6, res6)
  826. }
  827. })
  828. }
  829. func TestNULL(t *testing.T) {
  830. runTests(t, dsn, func(dbt *DBTest) {
  831. nullStmt, err := dbt.db.Prepare("SELECT NULL")
  832. if err != nil {
  833. dbt.Fatal(err)
  834. }
  835. defer nullStmt.Close()
  836. nonNullStmt, err := dbt.db.Prepare("SELECT 1")
  837. if err != nil {
  838. dbt.Fatal(err)
  839. }
  840. defer nonNullStmt.Close()
  841. // NullBool
  842. var nb sql.NullBool
  843. // Invalid
  844. if err = nullStmt.QueryRow().Scan(&nb); err != nil {
  845. dbt.Fatal(err)
  846. }
  847. if nb.Valid {
  848. dbt.Error("valid NullBool which should be invalid")
  849. }
  850. // Valid
  851. if err = nonNullStmt.QueryRow().Scan(&nb); err != nil {
  852. dbt.Fatal(err)
  853. }
  854. if !nb.Valid {
  855. dbt.Error("invalid NullBool which should be valid")
  856. } else if nb.Bool != true {
  857. dbt.Errorf("Unexpected NullBool value: %t (should be true)", nb.Bool)
  858. }
  859. // NullFloat64
  860. var nf sql.NullFloat64
  861. // Invalid
  862. if err = nullStmt.QueryRow().Scan(&nf); err != nil {
  863. dbt.Fatal(err)
  864. }
  865. if nf.Valid {
  866. dbt.Error("valid NullFloat64 which should be invalid")
  867. }
  868. // Valid
  869. if err = nonNullStmt.QueryRow().Scan(&nf); err != nil {
  870. dbt.Fatal(err)
  871. }
  872. if !nf.Valid {
  873. dbt.Error("invalid NullFloat64 which should be valid")
  874. } else if nf.Float64 != float64(1) {
  875. dbt.Errorf("unexpected NullFloat64 value: %f (should be 1.0)", nf.Float64)
  876. }
  877. // NullInt64
  878. var ni sql.NullInt64
  879. // Invalid
  880. if err = nullStmt.QueryRow().Scan(&ni); err != nil {
  881. dbt.Fatal(err)
  882. }
  883. if ni.Valid {
  884. dbt.Error("valid NullInt64 which should be invalid")
  885. }
  886. // Valid
  887. if err = nonNullStmt.QueryRow().Scan(&ni); err != nil {
  888. dbt.Fatal(err)
  889. }
  890. if !ni.Valid {
  891. dbt.Error("invalid NullInt64 which should be valid")
  892. } else if ni.Int64 != int64(1) {
  893. dbt.Errorf("unexpected NullInt64 value: %d (should be 1)", ni.Int64)
  894. }
  895. // NullString
  896. var ns sql.NullString
  897. // Invalid
  898. if err = nullStmt.QueryRow().Scan(&ns); err != nil {
  899. dbt.Fatal(err)
  900. }
  901. if ns.Valid {
  902. dbt.Error("valid NullString which should be invalid")
  903. }
  904. // Valid
  905. if err = nonNullStmt.QueryRow().Scan(&ns); err != nil {
  906. dbt.Fatal(err)
  907. }
  908. if !ns.Valid {
  909. dbt.Error("invalid NullString which should be valid")
  910. } else if ns.String != `1` {
  911. dbt.Error("unexpected NullString value:" + ns.String + " (should be `1`)")
  912. }
  913. // nil-bytes
  914. var b []byte
  915. // Read nil
  916. if err = nullStmt.QueryRow().Scan(&b); err != nil {
  917. dbt.Fatal(err)
  918. }
  919. if b != nil {
  920. dbt.Error("non-nil []byte which should be nil")
  921. }
  922. // Read non-nil
  923. if err = nonNullStmt.QueryRow().Scan(&b); err != nil {
  924. dbt.Fatal(err)
  925. }
  926. if b == nil {
  927. dbt.Error("nil []byte which should be non-nil")
  928. }
  929. // Insert nil
  930. b = nil
  931. success := false
  932. if err = dbt.db.QueryRow("SELECT ? IS NULL", b).Scan(&success); err != nil {
  933. dbt.Fatal(err)
  934. }
  935. if !success {
  936. dbt.Error("inserting []byte(nil) as NULL failed")
  937. }
  938. // Check input==output with input==nil
  939. b = nil
  940. if err = dbt.db.QueryRow("SELECT ?", b).Scan(&b); err != nil {
  941. dbt.Fatal(err)
  942. }
  943. if b != nil {
  944. dbt.Error("non-nil echo from nil input")
  945. }
  946. // Check input==output with input!=nil
  947. b = []byte("")
  948. if err = dbt.db.QueryRow("SELECT ?", b).Scan(&b); err != nil {
  949. dbt.Fatal(err)
  950. }
  951. if b == nil {
  952. dbt.Error("nil echo from non-nil input")
  953. }
  954. // Insert NULL
  955. dbt.mustExec("CREATE TABLE test (dummmy1 int, value int, dummy2 int)")
  956. dbt.mustExec("INSERT INTO test VALUES (?, ?, ?)", 1, nil, 2)
  957. var out interface{}
  958. rows := dbt.mustQuery("SELECT * FROM test")
  959. defer rows.Close()
  960. if rows.Next() {
  961. rows.Scan(&out)
  962. if out != nil {
  963. dbt.Errorf("%v != nil", out)
  964. }
  965. } else {
  966. dbt.Error("no data")
  967. }
  968. })
  969. }
  970. func TestUint64(t *testing.T) {
  971. const (
  972. u0 = uint64(0)
  973. uall = ^u0
  974. uhigh = uall >> 1
  975. utop = ^uhigh
  976. s0 = int64(0)
  977. sall = ^s0
  978. shigh = int64(uhigh)
  979. stop = ^shigh
  980. )
  981. runTests(t, dsn, func(dbt *DBTest) {
  982. stmt, err := dbt.db.Prepare(`SELECT ?, ?, ? ,?, ?, ?, ?, ?`)
  983. if err != nil {
  984. dbt.Fatal(err)
  985. }
  986. defer stmt.Close()
  987. row := stmt.QueryRow(
  988. u0, uhigh, utop, uall,
  989. s0, shigh, stop, sall,
  990. )
  991. var ua, ub, uc, ud uint64
  992. var sa, sb, sc, sd int64
  993. err = row.Scan(&ua, &ub, &uc, &ud, &sa, &sb, &sc, &sd)
  994. if err != nil {
  995. dbt.Fatal(err)
  996. }
  997. switch {
  998. case ua != u0,
  999. ub != uhigh,
  1000. uc != utop,
  1001. ud != uall,
  1002. sa != s0,
  1003. sb != shigh,
  1004. sc != stop,
  1005. sd != sall:
  1006. dbt.Fatal("unexpected result value")
  1007. }
  1008. })
  1009. }
  1010. func TestLongData(t *testing.T) {
  1011. runTests(t, dsn+"&maxAllowedPacket=0", func(dbt *DBTest) {
  1012. var maxAllowedPacketSize int
  1013. err := dbt.db.QueryRow("select @@max_allowed_packet").Scan(&maxAllowedPacketSize)
  1014. if err != nil {
  1015. dbt.Fatal(err)
  1016. }
  1017. maxAllowedPacketSize--
  1018. // don't get too ambitious
  1019. if maxAllowedPacketSize > 1<<25 {
  1020. maxAllowedPacketSize = 1 << 25
  1021. }
  1022. dbt.mustExec("CREATE TABLE test (value LONGBLOB)")
  1023. in := strings.Repeat(`a`, maxAllowedPacketSize+1)
  1024. var out string
  1025. var rows *sql.Rows
  1026. // Long text data
  1027. const nonDataQueryLen = 28 // length query w/o value
  1028. inS := in[:maxAllowedPacketSize-nonDataQueryLen]
  1029. dbt.mustExec("INSERT INTO test VALUES('" + inS + "')")
  1030. rows = dbt.mustQuery("SELECT value FROM test")
  1031. defer rows.Close()
  1032. if rows.Next() {
  1033. rows.Scan(&out)
  1034. if inS != out {
  1035. dbt.Fatalf("LONGBLOB: length in: %d, length out: %d", len(inS), len(out))
  1036. }
  1037. if rows.Next() {
  1038. dbt.Error("LONGBLOB: unexpexted row")
  1039. }
  1040. } else {
  1041. dbt.Fatalf("LONGBLOB: no data")
  1042. }
  1043. // Empty table
  1044. dbt.mustExec("TRUNCATE TABLE test")
  1045. // Long binary data
  1046. dbt.mustExec("INSERT INTO test VALUES(?)", in)
  1047. rows = dbt.mustQuery("SELECT value FROM test WHERE 1=?", 1)
  1048. defer rows.Close()
  1049. if rows.Next() {
  1050. rows.Scan(&out)
  1051. if in != out {
  1052. dbt.Fatalf("LONGBLOB: length in: %d, length out: %d", len(in), len(out))
  1053. }
  1054. if rows.Next() {
  1055. dbt.Error("LONGBLOB: unexpexted row")
  1056. }
  1057. } else {
  1058. if err = rows.Err(); err != nil {
  1059. dbt.Fatalf("LONGBLOB: no data (err: %s)", err.Error())
  1060. } else {
  1061. dbt.Fatal("LONGBLOB: no data (err: <nil>)")
  1062. }
  1063. }
  1064. })
  1065. }
  1066. func TestLoadData(t *testing.T) {
  1067. runTests(t, dsn, func(dbt *DBTest) {
  1068. verifyLoadDataResult := func() {
  1069. rows, err := dbt.db.Query("SELECT * FROM test")
  1070. if err != nil {
  1071. dbt.Fatal(err.Error())
  1072. }
  1073. i := 0
  1074. values := [4]string{
  1075. "a string",
  1076. "a string containing a \t",
  1077. "a string containing a \n",
  1078. "a string containing both \t\n",
  1079. }
  1080. var id int
  1081. var value string
  1082. for rows.Next() {
  1083. i++
  1084. err = rows.Scan(&id, &value)
  1085. if err != nil {
  1086. dbt.Fatal(err.Error())
  1087. }
  1088. if i != id {
  1089. dbt.Fatalf("%d != %d", i, id)
  1090. }
  1091. if values[i-1] != value {
  1092. dbt.Fatalf("%q != %q", values[i-1], value)
  1093. }
  1094. }
  1095. err = rows.Err()
  1096. if err != nil {
  1097. dbt.Fatal(err.Error())
  1098. }
  1099. if i != 4 {
  1100. dbt.Fatalf("rows count mismatch. Got %d, want 4", i)
  1101. }
  1102. }
  1103. dbt.db.Exec("DROP TABLE IF EXISTS test")
  1104. dbt.mustExec("CREATE TABLE test (id INT NOT NULL PRIMARY KEY, value TEXT NOT NULL) CHARACTER SET utf8")
  1105. // Local File
  1106. file, err := ioutil.TempFile("", "gotest")
  1107. defer os.Remove(file.Name())
  1108. if err != nil {
  1109. dbt.Fatal(err)
  1110. }
  1111. RegisterLocalFile(file.Name())
  1112. // Try first with empty file
  1113. dbt.mustExec(fmt.Sprintf("LOAD DATA LOCAL INFILE %q INTO TABLE test", file.Name()))
  1114. var count int
  1115. err = dbt.db.QueryRow("SELECT COUNT(*) FROM test").Scan(&count)
  1116. if err != nil {
  1117. dbt.Fatal(err.Error())
  1118. }
  1119. if count != 0 {
  1120. dbt.Fatalf("unexpected row count: got %d, want 0", count)
  1121. }
  1122. // Then fille File with data and try to load it
  1123. 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")
  1124. file.Close()
  1125. dbt.mustExec(fmt.Sprintf("LOAD DATA LOCAL INFILE %q INTO TABLE test", file.Name()))
  1126. verifyLoadDataResult()
  1127. // Try with non-existing file
  1128. _, err = dbt.db.Exec("LOAD DATA LOCAL INFILE 'doesnotexist' INTO TABLE test")
  1129. if err == nil {
  1130. dbt.Fatal("load non-existent file didn't fail")
  1131. } else if err.Error() != "local file 'doesnotexist' is not registered" {
  1132. dbt.Fatal(err.Error())
  1133. }
  1134. // Empty table
  1135. dbt.mustExec("TRUNCATE TABLE test")
  1136. // Reader
  1137. RegisterReaderHandler("test", func() io.Reader {
  1138. file, err = os.Open(file.Name())
  1139. if err != nil {
  1140. dbt.Fatal(err)
  1141. }
  1142. return file
  1143. })
  1144. dbt.mustExec("LOAD DATA LOCAL INFILE 'Reader::test' INTO TABLE test")
  1145. verifyLoadDataResult()
  1146. // negative test
  1147. _, err = dbt.db.Exec("LOAD DATA LOCAL INFILE 'Reader::doesnotexist' INTO TABLE test")
  1148. if err == nil {
  1149. dbt.Fatal("load non-existent Reader didn't fail")
  1150. } else if err.Error() != "Reader 'doesnotexist' is not registered" {
  1151. dbt.Fatal(err.Error())
  1152. }
  1153. })
  1154. }
  1155. func TestFoundRows(t *testing.T) {
  1156. runTests(t, dsn, func(dbt *DBTest) {
  1157. dbt.mustExec("CREATE TABLE test (id INT NOT NULL ,data INT NOT NULL)")
  1158. dbt.mustExec("INSERT INTO test (id, data) VALUES (0, 0),(0, 0),(1, 0),(1, 0),(1, 1)")
  1159. res := dbt.mustExec("UPDATE test SET data = 1 WHERE id = 0")
  1160. count, err := res.RowsAffected()
  1161. if err != nil {
  1162. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  1163. }
  1164. if count != 2 {
  1165. dbt.Fatalf("Expected 2 affected rows, got %d", count)
  1166. }
  1167. res = dbt.mustExec("UPDATE test SET data = 1 WHERE id = 1")
  1168. count, err = res.RowsAffected()
  1169. if err != nil {
  1170. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  1171. }
  1172. if count != 2 {
  1173. dbt.Fatalf("Expected 2 affected rows, got %d", count)
  1174. }
  1175. })
  1176. runTests(t, dsn+"&clientFoundRows=true", func(dbt *DBTest) {
  1177. dbt.mustExec("CREATE TABLE test (id INT NOT NULL ,data INT NOT NULL)")
  1178. dbt.mustExec("INSERT INTO test (id, data) VALUES (0, 0),(0, 0),(1, 0),(1, 0),(1, 1)")
  1179. res := dbt.mustExec("UPDATE test SET data = 1 WHERE id = 0")
  1180. count, err := res.RowsAffected()
  1181. if err != nil {
  1182. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  1183. }
  1184. if count != 2 {
  1185. dbt.Fatalf("Expected 2 matched rows, got %d", count)
  1186. }
  1187. res = dbt.mustExec("UPDATE test SET data = 1 WHERE id = 1")
  1188. count, err = res.RowsAffected()
  1189. if err != nil {
  1190. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  1191. }
  1192. if count != 3 {
  1193. dbt.Fatalf("Expected 3 matched rows, got %d", count)
  1194. }
  1195. })
  1196. }
  1197. func TestTLS(t *testing.T) {
  1198. tlsTestReq := func(dbt *DBTest) {
  1199. if err := dbt.db.Ping(); err != nil {
  1200. if err == ErrNoTLS {
  1201. dbt.Skip("server does not support TLS")
  1202. } else {
  1203. dbt.Fatalf("error on Ping: %s", err.Error())
  1204. }
  1205. }
  1206. rows := dbt.mustQuery("SHOW STATUS LIKE 'Ssl_cipher'")
  1207. defer rows.Close()
  1208. var variable, value *sql.RawBytes
  1209. for rows.Next() {
  1210. if err := rows.Scan(&variable, &value); err != nil {
  1211. dbt.Fatal(err.Error())
  1212. }
  1213. if (*value == nil) || (len(*value) == 0) {
  1214. dbt.Fatalf("no Cipher")
  1215. } else {
  1216. dbt.Logf("Cipher: %s", *value)
  1217. }
  1218. }
  1219. }
  1220. tlsTestOpt := func(dbt *DBTest) {
  1221. if err := dbt.db.Ping(); err != nil {
  1222. dbt.Fatalf("error on Ping: %s", err.Error())
  1223. }
  1224. }
  1225. runTests(t, dsn+"&tls=preferred", tlsTestOpt)
  1226. runTests(t, dsn+"&tls=skip-verify", tlsTestReq)
  1227. // Verify that registering / using a custom cfg works
  1228. RegisterTLSConfig("custom-skip-verify", &tls.Config{
  1229. InsecureSkipVerify: true,
  1230. })
  1231. runTests(t, dsn+"&tls=custom-skip-verify", tlsTestReq)
  1232. }
  1233. func TestReuseClosedConnection(t *testing.T) {
  1234. // this test does not use sql.database, it uses the driver directly
  1235. if !available {
  1236. t.Skipf("MySQL server not running on %s", netAddr)
  1237. }
  1238. md := &MySQLDriver{}
  1239. conn, err := md.Open(dsn)
  1240. if err != nil {
  1241. t.Fatalf("error connecting: %s", err.Error())
  1242. }
  1243. stmt, err := conn.Prepare("DO 1")
  1244. if err != nil {
  1245. t.Fatalf("error preparing statement: %s", err.Error())
  1246. }
  1247. _, err = stmt.Exec(nil)
  1248. if err != nil {
  1249. t.Fatalf("error executing statement: %s", err.Error())
  1250. }
  1251. err = conn.Close()
  1252. if err != nil {
  1253. t.Fatalf("error closing connection: %s", err.Error())
  1254. }
  1255. defer func() {
  1256. if err := recover(); err != nil {
  1257. t.Errorf("panic after reusing a closed connection: %v", err)
  1258. }
  1259. }()
  1260. _, err = stmt.Exec(nil)
  1261. if err != nil && err != driver.ErrBadConn {
  1262. t.Errorf("unexpected error '%s', expected '%s'",
  1263. err.Error(), driver.ErrBadConn.Error())
  1264. }
  1265. }
  1266. func TestCharset(t *testing.T) {
  1267. if !available {
  1268. t.Skipf("MySQL server not running on %s", netAddr)
  1269. }
  1270. mustSetCharset := func(charsetParam, expected string) {
  1271. runTests(t, dsn+"&"+charsetParam, func(dbt *DBTest) {
  1272. rows := dbt.mustQuery("SELECT @@character_set_connection")
  1273. defer rows.Close()
  1274. if !rows.Next() {
  1275. dbt.Fatalf("error getting connection charset: %s", rows.Err())
  1276. }
  1277. var got string
  1278. rows.Scan(&got)
  1279. if got != expected {
  1280. dbt.Fatalf("expected connection charset %s but got %s", expected, got)
  1281. }
  1282. })
  1283. }
  1284. // non utf8 test
  1285. mustSetCharset("charset=ascii", "ascii")
  1286. // when the first charset is invalid, use the second
  1287. mustSetCharset("charset=none,utf8", "utf8")
  1288. // when the first charset is valid, use it
  1289. mustSetCharset("charset=ascii,utf8", "ascii")
  1290. mustSetCharset("charset=utf8,ascii", "utf8")
  1291. }
  1292. func TestFailingCharset(t *testing.T) {
  1293. runTests(t, dsn+"&charset=none", func(dbt *DBTest) {
  1294. // run query to really establish connection...
  1295. _, err := dbt.db.Exec("SELECT 1")
  1296. if err == nil {
  1297. dbt.db.Close()
  1298. t.Fatalf("connection must not succeed without a valid charset")
  1299. }
  1300. })
  1301. }
  1302. func TestCollation(t *testing.T) {
  1303. if !available {
  1304. t.Skipf("MySQL server not running on %s", netAddr)
  1305. }
  1306. defaultCollation := "utf8mb4_general_ci"
  1307. testCollations := []string{
  1308. "", // do not set
  1309. defaultCollation, // driver default
  1310. "latin1_general_ci",
  1311. "binary",
  1312. "utf8_unicode_ci",
  1313. "cp1257_bin",
  1314. }
  1315. for _, collation := range testCollations {
  1316. var expected, tdsn string
  1317. if collation != "" {
  1318. tdsn = dsn + "&collation=" + collation
  1319. expected = collation
  1320. } else {
  1321. tdsn = dsn
  1322. expected = defaultCollation
  1323. }
  1324. runTests(t, tdsn, func(dbt *DBTest) {
  1325. var got string
  1326. if err := dbt.db.QueryRow("SELECT @@collation_connection").Scan(&got); err != nil {
  1327. dbt.Fatal(err)
  1328. }
  1329. if got != expected {
  1330. dbt.Fatalf("expected connection collation %s but got %s", expected, got)
  1331. }
  1332. })
  1333. }
  1334. }
  1335. func TestColumnsWithAlias(t *testing.T) {
  1336. runTests(t, dsn+"&columnsWithAlias=true", func(dbt *DBTest) {
  1337. rows := dbt.mustQuery("SELECT 1 AS A")
  1338. defer rows.Close()
  1339. cols, _ := rows.Columns()
  1340. if len(cols) != 1 {
  1341. t.Fatalf("expected 1 column, got %d", len(cols))
  1342. }
  1343. if cols[0] != "A" {
  1344. t.Fatalf("expected column name \"A\", got \"%s\"", cols[0])
  1345. }
  1346. rows = dbt.mustQuery("SELECT * FROM (SELECT 1 AS one) AS A")
  1347. defer rows.Close()
  1348. cols, _ = rows.Columns()
  1349. if len(cols) != 1 {
  1350. t.Fatalf("expected 1 column, got %d", len(cols))
  1351. }
  1352. if cols[0] != "A.one" {
  1353. t.Fatalf("expected column name \"A.one\", got \"%s\"", cols[0])
  1354. }
  1355. })
  1356. }
  1357. func TestRawBytesResultExceedsBuffer(t *testing.T) {
  1358. runTests(t, dsn, func(dbt *DBTest) {
  1359. // defaultBufSize from buffer.go
  1360. expected := strings.Repeat("abc", defaultBufSize)
  1361. rows := dbt.mustQuery("SELECT '" + expected + "'")
  1362. defer rows.Close()
  1363. if !rows.Next() {
  1364. dbt.Error("expected result, got none")
  1365. }
  1366. var result sql.RawBytes
  1367. rows.Scan(&result)
  1368. if expected != string(result) {
  1369. dbt.Error("result did not match expected value")
  1370. }
  1371. })
  1372. }
  1373. func TestTimezoneConversion(t *testing.T) {
  1374. zones := []string{"UTC", "US/Central", "US/Pacific", "Local"}
  1375. // Regression test for timezone handling
  1376. tzTest := func(dbt *DBTest) {
  1377. // Create table
  1378. dbt.mustExec("CREATE TABLE test (ts TIMESTAMP)")
  1379. // Insert local time into database (should be converted)
  1380. usCentral, _ := time.LoadLocation("US/Central")
  1381. reftime := time.Date(2014, 05, 30, 18, 03, 17, 0, time.UTC).In(usCentral)
  1382. dbt.mustExec("INSERT INTO test VALUE (?)", reftime)
  1383. // Retrieve time from DB
  1384. rows := dbt.mustQuery("SELECT ts FROM test")
  1385. defer rows.Close()
  1386. if !rows.Next() {
  1387. dbt.Fatal("did not get any rows out")
  1388. }
  1389. var dbTime time.Time
  1390. err := rows.Scan(&dbTime)
  1391. if err != nil {
  1392. dbt.Fatal("Err", err)
  1393. }
  1394. // Check that dates match
  1395. if reftime.Unix() != dbTime.Unix() {
  1396. dbt.Errorf("times do not match.\n")
  1397. dbt.Errorf(" Now(%v)=%v\n", usCentral, reftime)
  1398. dbt.Errorf(" Now(UTC)=%v\n", dbTime)
  1399. }
  1400. }
  1401. for _, tz := range zones {
  1402. runTests(t, dsn+"&parseTime=true&loc="+url.QueryEscape(tz), tzTest)
  1403. }
  1404. }
  1405. // Special cases
  1406. func TestRowsClose(t *testing.T) {
  1407. runTests(t, dsn, func(dbt *DBTest) {
  1408. rows, err := dbt.db.Query("SELECT 1")
  1409. if err != nil {
  1410. dbt.Fatal(err)
  1411. }
  1412. err = rows.Close()
  1413. if err != nil {
  1414. dbt.Fatal(err)
  1415. }
  1416. if rows.Next() {
  1417. dbt.Fatal("unexpected row after rows.Close()")
  1418. }
  1419. err = rows.Err()
  1420. if err != nil {
  1421. dbt.Fatal(err)
  1422. }
  1423. })
  1424. }
  1425. // dangling statements
  1426. // http://code.google.com/p/go/issues/detail?id=3865
  1427. func TestCloseStmtBeforeRows(t *testing.T) {
  1428. runTests(t, dsn, func(dbt *DBTest) {
  1429. stmt, err := dbt.db.Prepare("SELECT 1")
  1430. if err != nil {
  1431. dbt.Fatal(err)
  1432. }
  1433. rows, err := stmt.Query()
  1434. if err != nil {
  1435. stmt.Close()
  1436. dbt.Fatal(err)
  1437. }
  1438. defer rows.Close()
  1439. err = stmt.Close()
  1440. if err != nil {
  1441. dbt.Fatal(err)
  1442. }
  1443. if !rows.Next() {
  1444. dbt.Fatal("getting row failed")
  1445. } else {
  1446. err = rows.Err()
  1447. if err != nil {
  1448. dbt.Fatal(err)
  1449. }
  1450. var out bool
  1451. err = rows.Scan(&out)
  1452. if err != nil {
  1453. dbt.Fatalf("error on rows.Scan(): %s", err.Error())
  1454. }
  1455. if out != true {
  1456. dbt.Errorf("true != %t", out)
  1457. }
  1458. }
  1459. })
  1460. }
  1461. // It is valid to have multiple Rows for the same Stmt
  1462. // http://code.google.com/p/go/issues/detail?id=3734
  1463. func TestStmtMultiRows(t *testing.T) {
  1464. runTests(t, dsn, func(dbt *DBTest) {
  1465. stmt, err := dbt.db.Prepare("SELECT 1 UNION SELECT 0")
  1466. if err != nil {
  1467. dbt.Fatal(err)
  1468. }
  1469. rows1, err := stmt.Query()
  1470. if err != nil {
  1471. stmt.Close()
  1472. dbt.Fatal(err)
  1473. }
  1474. defer rows1.Close()
  1475. rows2, err := stmt.Query()
  1476. if err != nil {
  1477. stmt.Close()
  1478. dbt.Fatal(err)
  1479. }
  1480. defer rows2.Close()
  1481. var out bool
  1482. // 1
  1483. if !rows1.Next() {
  1484. dbt.Fatal("first rows1.Next failed")
  1485. } else {
  1486. err = rows1.Err()
  1487. if err != nil {
  1488. dbt.Fatal(err)
  1489. }
  1490. err = rows1.Scan(&out)
  1491. if err != nil {
  1492. dbt.Fatalf("error on rows.Scan(): %s", err.Error())
  1493. }
  1494. if out != true {
  1495. dbt.Errorf("true != %t", out)
  1496. }
  1497. }
  1498. if !rows2.Next() {
  1499. dbt.Fatal("first rows2.Next failed")
  1500. } else {
  1501. err = rows2.Err()
  1502. if err != nil {
  1503. dbt.Fatal(err)
  1504. }
  1505. err = rows2.Scan(&out)
  1506. if err != nil {
  1507. dbt.Fatalf("error on rows.Scan(): %s", err.Error())
  1508. }
  1509. if out != true {
  1510. dbt.Errorf("true != %t", out)
  1511. }
  1512. }
  1513. // 2
  1514. if !rows1.Next() {
  1515. dbt.Fatal("second rows1.Next failed")
  1516. } else {
  1517. err = rows1.Err()
  1518. if err != nil {
  1519. dbt.Fatal(err)
  1520. }
  1521. err = rows1.Scan(&out)
  1522. if err != nil {
  1523. dbt.Fatalf("error on rows.Scan(): %s", err.Error())
  1524. }
  1525. if out != false {
  1526. dbt.Errorf("false != %t", out)
  1527. }
  1528. if rows1.Next() {
  1529. dbt.Fatal("unexpected row on rows1")
  1530. }
  1531. err = rows1.Close()
  1532. if err != nil {
  1533. dbt.Fatal(err)
  1534. }
  1535. }
  1536. if !rows2.Next() {
  1537. dbt.Fatal("second rows2.Next failed")
  1538. } else {
  1539. err = rows2.Err()
  1540. if err != nil {
  1541. dbt.Fatal(err)
  1542. }
  1543. err = rows2.Scan(&out)
  1544. if err != nil {
  1545. dbt.Fatalf("error on rows.Scan(): %s", err.Error())
  1546. }
  1547. if out != false {
  1548. dbt.Errorf("false != %t", out)
  1549. }
  1550. if rows2.Next() {
  1551. dbt.Fatal("unexpected row on rows2")
  1552. }
  1553. err = rows2.Close()
  1554. if err != nil {
  1555. dbt.Fatal(err)
  1556. }
  1557. }
  1558. })
  1559. }
  1560. // Regression test for
  1561. // * more than 32 NULL parameters (issue 209)
  1562. // * more parameters than fit into the buffer (issue 201)
  1563. // * parameters * 64 > max_allowed_packet (issue 734)
  1564. func TestPreparedManyCols(t *testing.T) {
  1565. numParams := 65535
  1566. runTests(t, dsn, func(dbt *DBTest) {
  1567. query := "SELECT ?" + strings.Repeat(",?", numParams-1)
  1568. stmt, err := dbt.db.Prepare(query)
  1569. if err != nil {
  1570. dbt.Fatal(err)
  1571. }
  1572. defer stmt.Close()
  1573. // create more parameters than fit into the buffer
  1574. // which will take nil-values
  1575. params := make([]interface{}, numParams)
  1576. rows, err := stmt.Query(params...)
  1577. if err != nil {
  1578. dbt.Fatal(err)
  1579. }
  1580. rows.Close()
  1581. // Create 0byte string which we can't send via STMT_LONG_DATA.
  1582. for i := 0; i < numParams; i++ {
  1583. params[i] = ""
  1584. }
  1585. rows, err = stmt.Query(params...)
  1586. if err != nil {
  1587. dbt.Fatal(err)
  1588. }
  1589. rows.Close()
  1590. })
  1591. }
  1592. func TestConcurrent(t *testing.T) {
  1593. if enabled, _ := readBool(os.Getenv("MYSQL_TEST_CONCURRENT")); !enabled {
  1594. t.Skip("MYSQL_TEST_CONCURRENT env var not set")
  1595. }
  1596. runTests(t, dsn, func(dbt *DBTest) {
  1597. var max int
  1598. err := dbt.db.QueryRow("SELECT @@max_connections").Scan(&max)
  1599. if err != nil {
  1600. dbt.Fatalf("%s", err.Error())
  1601. }
  1602. dbt.Logf("testing up to %d concurrent connections \r\n", max)
  1603. var remaining, succeeded int32 = int32(max), 0
  1604. var wg sync.WaitGroup
  1605. wg.Add(max)
  1606. var fatalError string
  1607. var once sync.Once
  1608. fatalf := func(s string, vals ...interface{}) {
  1609. once.Do(func() {
  1610. fatalError = fmt.Sprintf(s, vals...)
  1611. })
  1612. }
  1613. for i := 0; i < max; i++ {
  1614. go func(id int) {
  1615. defer wg.Done()
  1616. tx, err := dbt.db.Begin()
  1617. atomic.AddInt32(&remaining, -1)
  1618. if err != nil {
  1619. if err.Error() != "Error 1040: Too many connections" {
  1620. fatalf("error on conn %d: %s", id, err.Error())
  1621. }
  1622. return
  1623. }
  1624. // keep the connection busy until all connections are open
  1625. for remaining > 0 {
  1626. if _, err = tx.Exec("DO 1"); err != nil {
  1627. fatalf("error on conn %d: %s", id, err.Error())
  1628. return
  1629. }
  1630. }
  1631. if err = tx.Commit(); err != nil {
  1632. fatalf("error on conn %d: %s", id, err.Error())
  1633. return
  1634. }
  1635. // everything went fine with this connection
  1636. atomic.AddInt32(&succeeded, 1)
  1637. }(i)
  1638. }
  1639. // wait until all conections are open
  1640. wg.Wait()
  1641. if fatalError != "" {
  1642. dbt.Fatal(fatalError)
  1643. }
  1644. dbt.Logf("reached %d concurrent connections\r\n", succeeded)
  1645. })
  1646. }
  1647. func testDialError(t *testing.T, dialErr error, expectErr error) {
  1648. RegisterDialContext("mydial", func(ctx context.Context, addr string) (net.Conn, error) {
  1649. return nil, dialErr
  1650. })
  1651. db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@mydial(%s)/%s?timeout=30s", user, pass, addr, dbname))
  1652. if err != nil {
  1653. t.Fatalf("error connecting: %s", err.Error())
  1654. }
  1655. defer db.Close()
  1656. _, err = db.Exec("DO 1")
  1657. if err != expectErr {
  1658. t.Fatalf("was expecting %s. Got: %s", dialErr, err)
  1659. }
  1660. }
  1661. func TestDialUnknownError(t *testing.T) {
  1662. testErr := fmt.Errorf("test")
  1663. testDialError(t, testErr, testErr)
  1664. }
  1665. func TestDialNonRetryableNetErr(t *testing.T) {
  1666. testErr := netErrorMock{}
  1667. testDialError(t, testErr, testErr)
  1668. }
  1669. func TestDialTemporaryNetErr(t *testing.T) {
  1670. testErr := netErrorMock{temporary: true}
  1671. testDialError(t, testErr, driver.ErrBadConn)
  1672. }
  1673. // Tests custom dial functions
  1674. func TestCustomDial(t *testing.T) {
  1675. if !available {
  1676. t.Skipf("MySQL server not running on %s", netAddr)
  1677. }
  1678. // our custom dial function which justs wraps net.Dial here
  1679. RegisterDialContext("mydial", func(ctx context.Context, addr string) (net.Conn, error) {
  1680. var d net.Dialer
  1681. return d.DialContext(ctx, prot, addr)
  1682. })
  1683. db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@mydial(%s)/%s?timeout=30s", user, pass, addr, dbname))
  1684. if err != nil {
  1685. t.Fatalf("error connecting: %s", err.Error())
  1686. }
  1687. defer db.Close()
  1688. if _, err = db.Exec("DO 1"); err != nil {
  1689. t.Fatalf("connection failed: %s", err.Error())
  1690. }
  1691. }
  1692. func TestSQLInjection(t *testing.T) {
  1693. createTest := func(arg string) func(dbt *DBTest) {
  1694. return func(dbt *DBTest) {
  1695. dbt.mustExec("CREATE TABLE test (v INTEGER)")
  1696. dbt.mustExec("INSERT INTO test VALUES (?)", 1)
  1697. var v int
  1698. // NULL can't be equal to anything, the idea here is to inject query so it returns row
  1699. // This test verifies that escapeQuotes and escapeBackslash are working properly
  1700. err := dbt.db.QueryRow("SELECT v FROM test WHERE NULL = ?", arg).Scan(&v)
  1701. if err == sql.ErrNoRows {
  1702. return // success, sql injection failed
  1703. } else if err == nil {
  1704. dbt.Errorf("sql injection successful with arg: %s", arg)
  1705. } else {
  1706. dbt.Errorf("error running query with arg: %s; err: %s", arg, err.Error())
  1707. }
  1708. }
  1709. }
  1710. dsns := []string{
  1711. dsn,
  1712. dsn + "&sql_mode='NO_BACKSLASH_ESCAPES'",
  1713. }
  1714. for _, testdsn := range dsns {
  1715. runTests(t, testdsn, createTest("1 OR 1=1"))
  1716. runTests(t, testdsn, createTest("' OR '1'='1"))
  1717. }
  1718. }
  1719. // Test if inserted data is correctly retrieved after being escaped
  1720. func TestInsertRetrieveEscapedData(t *testing.T) {
  1721. testData := func(dbt *DBTest) {
  1722. dbt.mustExec("CREATE TABLE test (v VARCHAR(255))")
  1723. // All sequences that are escaped by escapeQuotes and escapeBackslash
  1724. v := "foo \x00\n\r\x1a\"'\\"
  1725. dbt.mustExec("INSERT INTO test VALUES (?)", v)
  1726. var out string
  1727. err := dbt.db.QueryRow("SELECT v FROM test").Scan(&out)
  1728. if err != nil {
  1729. dbt.Fatalf("%s", err.Error())
  1730. }
  1731. if out != v {
  1732. dbt.Errorf("%q != %q", out, v)
  1733. }
  1734. }
  1735. dsns := []string{
  1736. dsn,
  1737. dsn + "&sql_mode='NO_BACKSLASH_ESCAPES'",
  1738. }
  1739. for _, testdsn := range dsns {
  1740. runTests(t, testdsn, testData)
  1741. }
  1742. }
  1743. func TestUnixSocketAuthFail(t *testing.T) {
  1744. runTests(t, dsn, func(dbt *DBTest) {
  1745. // Save the current logger so we can restore it.
  1746. oldLogger := errLog
  1747. // Set a new logger so we can capture its output.
  1748. buffer := bytes.NewBuffer(make([]byte, 0, 64))
  1749. newLogger := log.New(buffer, "prefix: ", 0)
  1750. SetLogger(newLogger)
  1751. // Restore the logger.
  1752. defer SetLogger(oldLogger)
  1753. // Make a new DSN that uses the MySQL socket file and a bad password, which
  1754. // we can make by simply appending any character to the real password.
  1755. badPass := pass + "x"
  1756. socket := ""
  1757. if prot == "unix" {
  1758. socket = addr
  1759. } else {
  1760. // Get socket file from MySQL.
  1761. err := dbt.db.QueryRow("SELECT @@socket").Scan(&socket)
  1762. if err != nil {
  1763. t.Fatalf("error on SELECT @@socket: %s", err.Error())
  1764. }
  1765. }
  1766. t.Logf("socket: %s", socket)
  1767. badDSN := fmt.Sprintf("%s:%s@unix(%s)/%s?timeout=30s", user, badPass, socket, dbname)
  1768. db, err := sql.Open("mysql", badDSN)
  1769. if err != nil {
  1770. t.Fatalf("error connecting: %s", err.Error())
  1771. }
  1772. defer db.Close()
  1773. // Connect to MySQL for real. This will cause an auth failure.
  1774. err = db.Ping()
  1775. if err == nil {
  1776. t.Error("expected Ping() to return an error")
  1777. }
  1778. // The driver should not log anything.
  1779. if actual := buffer.String(); actual != "" {
  1780. t.Errorf("expected no output, got %q", actual)
  1781. }
  1782. })
  1783. }
  1784. // See Issue #422
  1785. func TestInterruptBySignal(t *testing.T) {
  1786. runTestsWithMultiStatement(t, dsn, func(dbt *DBTest) {
  1787. dbt.mustExec(`
  1788. DROP PROCEDURE IF EXISTS test_signal;
  1789. CREATE PROCEDURE test_signal(ret INT)
  1790. BEGIN
  1791. SELECT ret;
  1792. SIGNAL SQLSTATE
  1793. '45001'
  1794. SET
  1795. MESSAGE_TEXT = "an error",
  1796. MYSQL_ERRNO = 45001;
  1797. END
  1798. `)
  1799. defer dbt.mustExec("DROP PROCEDURE test_signal")
  1800. var val int
  1801. // text protocol
  1802. rows, err := dbt.db.Query("CALL test_signal(42)")
  1803. if err != nil {
  1804. dbt.Fatalf("error on text query: %s", err.Error())
  1805. }
  1806. for rows.Next() {
  1807. if err := rows.Scan(&val); err != nil {
  1808. dbt.Error(err)
  1809. } else if val != 42 {
  1810. dbt.Errorf("expected val to be 42")
  1811. }
  1812. }
  1813. rows.Close()
  1814. // binary protocol
  1815. rows, err = dbt.db.Query("CALL test_signal(?)", 42)
  1816. if err != nil {
  1817. dbt.Fatalf("error on binary query: %s", err.Error())
  1818. }
  1819. for rows.Next() {
  1820. if err := rows.Scan(&val); err != nil {
  1821. dbt.Error(err)
  1822. } else if val != 42 {
  1823. dbt.Errorf("expected val to be 42")
  1824. }
  1825. }
  1826. rows.Close()
  1827. })
  1828. }
  1829. func TestColumnsReusesSlice(t *testing.T) {
  1830. rows := mysqlRows{
  1831. rs: resultSet{
  1832. columns: []mysqlField{
  1833. {
  1834. tableName: "test",
  1835. name: "A",
  1836. },
  1837. {
  1838. tableName: "test",
  1839. name: "B",
  1840. },
  1841. },
  1842. },
  1843. }
  1844. allocs := testing.AllocsPerRun(1, func() {
  1845. cols := rows.Columns()
  1846. if len(cols) != 2 {
  1847. t.Fatalf("expected 2 columns, got %d", len(cols))
  1848. }
  1849. })
  1850. if allocs != 0 {
  1851. t.Fatalf("expected 0 allocations, got %d", int(allocs))
  1852. }
  1853. if rows.rs.columnNames == nil {
  1854. t.Fatalf("expected columnNames to be set, got nil")
  1855. }
  1856. }
  1857. func TestRejectReadOnly(t *testing.T) {
  1858. runTests(t, dsn, func(dbt *DBTest) {
  1859. // Create Table
  1860. dbt.mustExec("CREATE TABLE test (value BOOL)")
  1861. // Set the session to read-only. We didn't set the `rejectReadOnly`
  1862. // option, so any writes after this should fail.
  1863. _, err := dbt.db.Exec("SET SESSION TRANSACTION READ ONLY")
  1864. // Error 1193: Unknown system variable 'TRANSACTION' => skip test,
  1865. // MySQL server version is too old
  1866. maybeSkip(t, err, 1193)
  1867. if _, err := dbt.db.Exec("DROP TABLE test"); err == nil {
  1868. t.Fatalf("writing to DB in read-only session without " +
  1869. "rejectReadOnly did not error")
  1870. }
  1871. // Set the session back to read-write so runTests() can properly clean
  1872. // up the table `test`.
  1873. dbt.mustExec("SET SESSION TRANSACTION READ WRITE")
  1874. })
  1875. // Enable the `rejectReadOnly` option.
  1876. runTests(t, dsn+"&rejectReadOnly=true", func(dbt *DBTest) {
  1877. // Create Table
  1878. dbt.mustExec("CREATE TABLE test (value BOOL)")
  1879. // Set the session to read only. Any writes after this should error on
  1880. // a driver.ErrBadConn, and cause `database/sql` to initiate a new
  1881. // connection.
  1882. dbt.mustExec("SET SESSION TRANSACTION READ ONLY")
  1883. // This would error, but `database/sql` should automatically retry on a
  1884. // new connection which is not read-only, and eventually succeed.
  1885. dbt.mustExec("DROP TABLE test")
  1886. })
  1887. }
  1888. func TestPing(t *testing.T) {
  1889. runTests(t, dsn, func(dbt *DBTest) {
  1890. if err := dbt.db.Ping(); err != nil {
  1891. dbt.fail("Ping", "Ping", err)
  1892. }
  1893. })
  1894. }
  1895. // See Issue #799
  1896. func TestEmptyPassword(t *testing.T) {
  1897. if !available {
  1898. t.Skipf("MySQL server not running on %s", netAddr)
  1899. }
  1900. dsn := fmt.Sprintf("%s:%s@%s/%s?timeout=30s", user, "", netAddr, dbname)
  1901. db, err := sql.Open("mysql", dsn)
  1902. if err == nil {
  1903. defer db.Close()
  1904. err = db.Ping()
  1905. }
  1906. if pass == "" {
  1907. if err != nil {
  1908. t.Fatal(err.Error())
  1909. }
  1910. } else {
  1911. if err == nil {
  1912. t.Fatal("expected authentication error")
  1913. }
  1914. if !strings.HasPrefix(err.Error(), "Error 1045") {
  1915. t.Fatal(err.Error())
  1916. }
  1917. }
  1918. }
  1919. // static interface implementation checks of mysqlConn
  1920. var (
  1921. _ driver.ConnBeginTx = &mysqlConn{}
  1922. _ driver.ConnPrepareContext = &mysqlConn{}
  1923. _ driver.ExecerContext = &mysqlConn{}
  1924. _ driver.Pinger = &mysqlConn{}
  1925. _ driver.QueryerContext = &mysqlConn{}
  1926. )
  1927. // static interface implementation checks of mysqlStmt
  1928. var (
  1929. _ driver.StmtExecContext = &mysqlStmt{}
  1930. _ driver.StmtQueryContext = &mysqlStmt{}
  1931. )
  1932. // Ensure that all the driver interfaces are implemented
  1933. var (
  1934. // _ driver.RowsColumnTypeLength = &binaryRows{}
  1935. // _ driver.RowsColumnTypeLength = &textRows{}
  1936. _ driver.RowsColumnTypeDatabaseTypeName = &binaryRows{}
  1937. _ driver.RowsColumnTypeDatabaseTypeName = &textRows{}
  1938. _ driver.RowsColumnTypeNullable = &binaryRows{}
  1939. _ driver.RowsColumnTypeNullable = &textRows{}
  1940. _ driver.RowsColumnTypePrecisionScale = &binaryRows{}
  1941. _ driver.RowsColumnTypePrecisionScale = &textRows{}
  1942. _ driver.RowsColumnTypeScanType = &binaryRows{}
  1943. _ driver.RowsColumnTypeScanType = &textRows{}
  1944. _ driver.RowsNextResultSet = &binaryRows{}
  1945. _ driver.RowsNextResultSet = &textRows{}
  1946. )
  1947. func TestMultiResultSet(t *testing.T) {
  1948. type result struct {
  1949. values [][]int
  1950. columns []string
  1951. }
  1952. // checkRows is a helper test function to validate rows containing 3 result
  1953. // sets with specific values and columns. The basic query would look like this:
  1954. //
  1955. // SELECT 1 AS col1, 2 AS col2 UNION SELECT 3, 4;
  1956. // SELECT 0 UNION SELECT 1;
  1957. // SELECT 1 AS col1, 2 AS col2, 3 AS col3 UNION SELECT 4, 5, 6;
  1958. //
  1959. // to distinguish test cases the first string argument is put in front of
  1960. // every error or fatal message.
  1961. checkRows := func(desc string, rows *sql.Rows, dbt *DBTest) {
  1962. expected := []result{
  1963. {
  1964. values: [][]int{{1, 2}, {3, 4}},
  1965. columns: []string{"col1", "col2"},
  1966. },
  1967. {
  1968. values: [][]int{{1, 2, 3}, {4, 5, 6}},
  1969. columns: []string{"col1", "col2", "col3"},
  1970. },
  1971. }
  1972. var res1 result
  1973. for rows.Next() {
  1974. var res [2]int
  1975. if err := rows.Scan(&res[0], &res[1]); err != nil {
  1976. dbt.Fatal(err)
  1977. }
  1978. res1.values = append(res1.values, res[:])
  1979. }
  1980. cols, err := rows.Columns()
  1981. if err != nil {
  1982. dbt.Fatal(desc, err)
  1983. }
  1984. res1.columns = cols
  1985. if !reflect.DeepEqual(expected[0], res1) {
  1986. dbt.Error(desc, "want =", expected[0], "got =", res1)
  1987. }
  1988. if !rows.NextResultSet() {
  1989. dbt.Fatal(desc, "expected next result set")
  1990. }
  1991. // ignoring one result set
  1992. if !rows.NextResultSet() {
  1993. dbt.Fatal(desc, "expected next result set")
  1994. }
  1995. var res2 result
  1996. cols, err = rows.Columns()
  1997. if err != nil {
  1998. dbt.Fatal(desc, err)
  1999. }
  2000. res2.columns = cols
  2001. for rows.Next() {
  2002. var res [3]int
  2003. if err := rows.Scan(&res[0], &res[1], &res[2]); err != nil {
  2004. dbt.Fatal(desc, err)
  2005. }
  2006. res2.values = append(res2.values, res[:])
  2007. }
  2008. if !reflect.DeepEqual(expected[1], res2) {
  2009. dbt.Error(desc, "want =", expected[1], "got =", res2)
  2010. }
  2011. if rows.NextResultSet() {
  2012. dbt.Error(desc, "unexpected next result set")
  2013. }
  2014. if err := rows.Err(); err != nil {
  2015. dbt.Error(desc, err)
  2016. }
  2017. }
  2018. runTestsWithMultiStatement(t, dsn, func(dbt *DBTest) {
  2019. rows := dbt.mustQuery(`DO 1;
  2020. SELECT 1 AS col1, 2 AS col2 UNION SELECT 3, 4;
  2021. DO 1;
  2022. SELECT 0 UNION SELECT 1;
  2023. SELECT 1 AS col1, 2 AS col2, 3 AS col3 UNION SELECT 4, 5, 6;`)
  2024. defer rows.Close()
  2025. checkRows("query: ", rows, dbt)
  2026. })
  2027. runTestsWithMultiStatement(t, dsn, func(dbt *DBTest) {
  2028. queries := []string{
  2029. `
  2030. DROP PROCEDURE IF EXISTS test_mrss;
  2031. CREATE PROCEDURE test_mrss()
  2032. BEGIN
  2033. DO 1;
  2034. SELECT 1 AS col1, 2 AS col2 UNION SELECT 3, 4;
  2035. DO 1;
  2036. SELECT 0 UNION SELECT 1;
  2037. SELECT 1 AS col1, 2 AS col2, 3 AS col3 UNION SELECT 4, 5, 6;
  2038. END
  2039. `,
  2040. `
  2041. DROP PROCEDURE IF EXISTS test_mrss;
  2042. CREATE PROCEDURE test_mrss()
  2043. BEGIN
  2044. SELECT 1 AS col1, 2 AS col2 UNION SELECT 3, 4;
  2045. SELECT 0 UNION SELECT 1;
  2046. SELECT 1 AS col1, 2 AS col2, 3 AS col3 UNION SELECT 4, 5, 6;
  2047. END
  2048. `,
  2049. }
  2050. defer dbt.mustExec("DROP PROCEDURE IF EXISTS test_mrss")
  2051. for i, query := range queries {
  2052. dbt.mustExec(query)
  2053. stmt, err := dbt.db.Prepare("CALL test_mrss()")
  2054. if err != nil {
  2055. dbt.Fatalf("%v (i=%d)", err, i)
  2056. }
  2057. defer stmt.Close()
  2058. for j := 0; j < 2; j++ {
  2059. rows, err := stmt.Query()
  2060. if err != nil {
  2061. dbt.Fatalf("%v (i=%d) (j=%d)", err, i, j)
  2062. }
  2063. checkRows(fmt.Sprintf("prepared stmt query (i=%d) (j=%d): ", i, j), rows, dbt)
  2064. }
  2065. }
  2066. })
  2067. }
  2068. func TestMultiResultSetNoSelect(t *testing.T) {
  2069. runTestsWithMultiStatement(t, dsn, func(dbt *DBTest) {
  2070. rows := dbt.mustQuery("DO 1; DO 2;")
  2071. defer rows.Close()
  2072. if rows.Next() {
  2073. dbt.Error("unexpected row")
  2074. }
  2075. if rows.NextResultSet() {
  2076. dbt.Error("unexpected next result set")
  2077. }
  2078. if err := rows.Err(); err != nil {
  2079. dbt.Error("expected nil; got ", err)
  2080. }
  2081. })
  2082. }
  2083. // tests if rows are set in a proper state if some results were ignored before
  2084. // calling rows.NextResultSet.
  2085. func TestSkipResults(t *testing.T) {
  2086. runTests(t, dsn, func(dbt *DBTest) {
  2087. rows := dbt.mustQuery("SELECT 1, 2")
  2088. defer rows.Close()
  2089. if !rows.Next() {
  2090. dbt.Error("expected row")
  2091. }
  2092. if rows.NextResultSet() {
  2093. dbt.Error("unexpected next result set")
  2094. }
  2095. if err := rows.Err(); err != nil {
  2096. dbt.Error("expected nil; got ", err)
  2097. }
  2098. })
  2099. }
  2100. func TestPingContext(t *testing.T) {
  2101. runTests(t, dsn, func(dbt *DBTest) {
  2102. ctx, cancel := context.WithCancel(context.Background())
  2103. cancel()
  2104. if err := dbt.db.PingContext(ctx); err != context.Canceled {
  2105. dbt.Errorf("expected context.Canceled, got %v", err)
  2106. }
  2107. })
  2108. }
  2109. func TestContextCancelExec(t *testing.T) {
  2110. runTests(t, dsn, func(dbt *DBTest) {
  2111. dbt.mustExec("CREATE TABLE test (v INTEGER)")
  2112. ctx, cancel := context.WithCancel(context.Background())
  2113. // Delay execution for just a bit until db.ExecContext has begun.
  2114. defer time.AfterFunc(250*time.Millisecond, cancel).Stop()
  2115. // This query will be canceled.
  2116. startTime := time.Now()
  2117. if _, err := dbt.db.ExecContext(ctx, "INSERT INTO test VALUES (SLEEP(1))"); err != context.Canceled {
  2118. dbt.Errorf("expected context.Canceled, got %v", err)
  2119. }
  2120. if d := time.Since(startTime); d > 500*time.Millisecond {
  2121. dbt.Errorf("too long execution time: %s", d)
  2122. }
  2123. // Wait for the INSERT query to be done.
  2124. time.Sleep(time.Second)
  2125. // Check how many times the query is executed.
  2126. var v int
  2127. if err := dbt.db.QueryRow("SELECT COUNT(*) FROM test").Scan(&v); err != nil {
  2128. dbt.Fatalf("%s", err.Error())
  2129. }
  2130. if v != 1 { // TODO: need to kill the query, and v should be 0.
  2131. dbt.Skipf("[WARN] expected val to be 1, got %d", v)
  2132. }
  2133. // Context is already canceled, so error should come before execution.
  2134. if _, err := dbt.db.ExecContext(ctx, "INSERT INTO test VALUES (1)"); err == nil {
  2135. dbt.Error("expected error")
  2136. } else if err.Error() != "context canceled" {
  2137. dbt.Fatalf("unexpected error: %s", err)
  2138. }
  2139. // The second insert query will fail, so the table has no changes.
  2140. if err := dbt.db.QueryRow("SELECT COUNT(*) FROM test").Scan(&v); err != nil {
  2141. dbt.Fatalf("%s", err.Error())
  2142. }
  2143. if v != 1 {
  2144. dbt.Skipf("[WARN] expected val to be 1, got %d", v)
  2145. }
  2146. })
  2147. }
  2148. func TestContextCancelQuery(t *testing.T) {
  2149. runTests(t, dsn, func(dbt *DBTest) {
  2150. dbt.mustExec("CREATE TABLE test (v INTEGER)")
  2151. ctx, cancel := context.WithCancel(context.Background())
  2152. // Delay execution for just a bit until db.ExecContext has begun.
  2153. defer time.AfterFunc(250*time.Millisecond, cancel).Stop()
  2154. // This query will be canceled.
  2155. startTime := time.Now()
  2156. if _, err := dbt.db.QueryContext(ctx, "INSERT INTO test VALUES (SLEEP(1))"); err != context.Canceled {
  2157. dbt.Errorf("expected context.Canceled, got %v", err)
  2158. }
  2159. if d := time.Since(startTime); d > 500*time.Millisecond {
  2160. dbt.Errorf("too long execution time: %s", d)
  2161. }
  2162. // Wait for the INSERT query to be done.
  2163. time.Sleep(time.Second)
  2164. // Check how many times the query is executed.
  2165. var v int
  2166. if err := dbt.db.QueryRow("SELECT COUNT(*) FROM test").Scan(&v); err != nil {
  2167. dbt.Fatalf("%s", err.Error())
  2168. }
  2169. if v != 1 { // TODO: need to kill the query, and v should be 0.
  2170. dbt.Skipf("[WARN] expected val to be 1, got %d", v)
  2171. }
  2172. // Context is already canceled, so error should come before execution.
  2173. if _, err := dbt.db.QueryContext(ctx, "INSERT INTO test VALUES (1)"); err != context.Canceled {
  2174. dbt.Errorf("expected context.Canceled, got %v", err)
  2175. }
  2176. // The second insert query will fail, so the table has no changes.
  2177. if err := dbt.db.QueryRow("SELECT COUNT(*) FROM test").Scan(&v); err != nil {
  2178. dbt.Fatalf("%s", err.Error())
  2179. }
  2180. if v != 1 {
  2181. dbt.Skipf("[WARN] expected val to be 1, got %d", v)
  2182. }
  2183. })
  2184. }
  2185. func TestContextCancelQueryRow(t *testing.T) {
  2186. runTests(t, dsn, func(dbt *DBTest) {
  2187. dbt.mustExec("CREATE TABLE test (v INTEGER)")
  2188. dbt.mustExec("INSERT INTO test VALUES (1), (2), (3)")
  2189. ctx, cancel := context.WithCancel(context.Background())
  2190. rows, err := dbt.db.QueryContext(ctx, "SELECT v FROM test")
  2191. if err != nil {
  2192. dbt.Fatalf("%s", err.Error())
  2193. }
  2194. // the first row will be succeed.
  2195. var v int
  2196. if !rows.Next() {
  2197. dbt.Fatalf("unexpected end")
  2198. }
  2199. if err := rows.Scan(&v); err != nil {
  2200. dbt.Fatalf("%s", err.Error())
  2201. }
  2202. cancel()
  2203. // make sure the driver receives the cancel request.
  2204. time.Sleep(100 * time.Millisecond)
  2205. if rows.Next() {
  2206. dbt.Errorf("expected end, but not")
  2207. }
  2208. if err := rows.Err(); err != context.Canceled {
  2209. dbt.Errorf("expected context.Canceled, got %v", err)
  2210. }
  2211. })
  2212. }
  2213. func TestContextCancelPrepare(t *testing.T) {
  2214. runTests(t, dsn, func(dbt *DBTest) {
  2215. ctx, cancel := context.WithCancel(context.Background())
  2216. cancel()
  2217. if _, err := dbt.db.PrepareContext(ctx, "SELECT 1"); err != context.Canceled {
  2218. dbt.Errorf("expected context.Canceled, got %v", err)
  2219. }
  2220. })
  2221. }
  2222. func TestContextCancelStmtExec(t *testing.T) {
  2223. runTests(t, dsn, func(dbt *DBTest) {
  2224. dbt.mustExec("CREATE TABLE test (v INTEGER)")
  2225. ctx, cancel := context.WithCancel(context.Background())
  2226. stmt, err := dbt.db.PrepareContext(ctx, "INSERT INTO test VALUES (SLEEP(1))")
  2227. if err != nil {
  2228. dbt.Fatalf("unexpected error: %v", err)
  2229. }
  2230. // Delay execution for just a bit until db.ExecContext has begun.
  2231. defer time.AfterFunc(250*time.Millisecond, cancel).Stop()
  2232. // This query will be canceled.
  2233. startTime := time.Now()
  2234. if _, err := stmt.ExecContext(ctx); err != context.Canceled {
  2235. dbt.Errorf("expected context.Canceled, got %v", err)
  2236. }
  2237. if d := time.Since(startTime); d > 500*time.Millisecond {
  2238. dbt.Errorf("too long execution time: %s", d)
  2239. }
  2240. // Wait for the INSERT query to be done.
  2241. time.Sleep(time.Second)
  2242. // Check how many times the query is executed.
  2243. var v int
  2244. if err := dbt.db.QueryRow("SELECT COUNT(*) FROM test").Scan(&v); err != nil {
  2245. dbt.Fatalf("%s", err.Error())
  2246. }
  2247. if v != 1 { // TODO: need to kill the query, and v should be 0.
  2248. dbt.Skipf("[WARN] expected val to be 1, got %d", v)
  2249. }
  2250. })
  2251. }
  2252. func TestContextCancelStmtQuery(t *testing.T) {
  2253. runTests(t, dsn, func(dbt *DBTest) {
  2254. dbt.mustExec("CREATE TABLE test (v INTEGER)")
  2255. ctx, cancel := context.WithCancel(context.Background())
  2256. stmt, err := dbt.db.PrepareContext(ctx, "INSERT INTO test VALUES (SLEEP(1))")
  2257. if err != nil {
  2258. dbt.Fatalf("unexpected error: %v", err)
  2259. }
  2260. // Delay execution for just a bit until db.ExecContext has begun.
  2261. defer time.AfterFunc(250*time.Millisecond, cancel).Stop()
  2262. // This query will be canceled.
  2263. startTime := time.Now()
  2264. if _, err := stmt.QueryContext(ctx); err != context.Canceled {
  2265. dbt.Errorf("expected context.Canceled, got %v", err)
  2266. }
  2267. if d := time.Since(startTime); d > 500*time.Millisecond {
  2268. dbt.Errorf("too long execution time: %s", d)
  2269. }
  2270. // Wait for the INSERT query has done.
  2271. time.Sleep(time.Second)
  2272. // Check how many times the query is executed.
  2273. var v int
  2274. if err := dbt.db.QueryRow("SELECT COUNT(*) FROM test").Scan(&v); err != nil {
  2275. dbt.Fatalf("%s", err.Error())
  2276. }
  2277. if v != 1 { // TODO: need to kill the query, and v should be 0.
  2278. dbt.Skipf("[WARN] expected val to be 1, got %d", v)
  2279. }
  2280. })
  2281. }
  2282. func TestContextCancelBegin(t *testing.T) {
  2283. runTests(t, dsn, func(dbt *DBTest) {
  2284. dbt.mustExec("CREATE TABLE test (v INTEGER)")
  2285. ctx, cancel := context.WithCancel(context.Background())
  2286. tx, err := dbt.db.BeginTx(ctx, nil)
  2287. if err != nil {
  2288. dbt.Fatal(err)
  2289. }
  2290. // Delay execution for just a bit until db.ExecContext has begun.
  2291. defer time.AfterFunc(100*time.Millisecond, cancel).Stop()
  2292. // This query will be canceled.
  2293. startTime := time.Now()
  2294. if _, err := tx.ExecContext(ctx, "INSERT INTO test VALUES (SLEEP(1))"); err != context.Canceled {
  2295. dbt.Errorf("expected context.Canceled, got %v", err)
  2296. }
  2297. if d := time.Since(startTime); d > 500*time.Millisecond {
  2298. dbt.Errorf("too long execution time: %s", d)
  2299. }
  2300. // Transaction is canceled, so expect an error.
  2301. switch err := tx.Commit(); err {
  2302. case sql.ErrTxDone:
  2303. // because the transaction has already been rollbacked.
  2304. // the database/sql package watches ctx
  2305. // and rollbacks when ctx is canceled.
  2306. case context.Canceled:
  2307. // the database/sql package rollbacks on another goroutine,
  2308. // so the transaction may not be rollbacked depending on goroutine scheduling.
  2309. default:
  2310. dbt.Errorf("expected sql.ErrTxDone or context.Canceled, got %v", err)
  2311. }
  2312. // Context is canceled, so cannot begin a transaction.
  2313. if _, err := dbt.db.BeginTx(ctx, nil); err != context.Canceled {
  2314. dbt.Errorf("expected context.Canceled, got %v", err)
  2315. }
  2316. })
  2317. }
  2318. func TestContextBeginIsolationLevel(t *testing.T) {
  2319. runTests(t, dsn, func(dbt *DBTest) {
  2320. dbt.mustExec("CREATE TABLE test (v INTEGER)")
  2321. ctx, cancel := context.WithCancel(context.Background())
  2322. defer cancel()
  2323. tx1, err := dbt.db.BeginTx(ctx, &sql.TxOptions{
  2324. Isolation: sql.LevelRepeatableRead,
  2325. })
  2326. if err != nil {
  2327. dbt.Fatal(err)
  2328. }
  2329. tx2, err := dbt.db.BeginTx(ctx, &sql.TxOptions{
  2330. Isolation: sql.LevelReadCommitted,
  2331. })
  2332. if err != nil {
  2333. dbt.Fatal(err)
  2334. }
  2335. _, err = tx1.ExecContext(ctx, "INSERT INTO test VALUES (1)")
  2336. if err != nil {
  2337. dbt.Fatal(err)
  2338. }
  2339. var v int
  2340. row := tx2.QueryRowContext(ctx, "SELECT COUNT(*) FROM test")
  2341. if err := row.Scan(&v); err != nil {
  2342. dbt.Fatal(err)
  2343. }
  2344. // Because writer transaction wasn't commited yet, it should be available
  2345. if v != 0 {
  2346. dbt.Errorf("expected val to be 0, got %d", v)
  2347. }
  2348. err = tx1.Commit()
  2349. if err != nil {
  2350. dbt.Fatal(err)
  2351. }
  2352. row = tx2.QueryRowContext(ctx, "SELECT COUNT(*) FROM test")
  2353. if err := row.Scan(&v); err != nil {
  2354. dbt.Fatal(err)
  2355. }
  2356. // Data written by writer transaction is already commited, it should be selectable
  2357. if v != 1 {
  2358. dbt.Errorf("expected val to be 1, got %d", v)
  2359. }
  2360. tx2.Commit()
  2361. })
  2362. }
  2363. func TestContextBeginReadOnly(t *testing.T) {
  2364. runTests(t, dsn, func(dbt *DBTest) {
  2365. dbt.mustExec("CREATE TABLE test (v INTEGER)")
  2366. ctx, cancel := context.WithCancel(context.Background())
  2367. defer cancel()
  2368. tx, err := dbt.db.BeginTx(ctx, &sql.TxOptions{
  2369. ReadOnly: true,
  2370. })
  2371. if _, ok := err.(*MySQLError); ok {
  2372. dbt.Skip("It seems that your MySQL does not support READ ONLY transactions")
  2373. return
  2374. } else if err != nil {
  2375. dbt.Fatal(err)
  2376. }
  2377. // INSERT queries fail in a READ ONLY transaction.
  2378. _, err = tx.ExecContext(ctx, "INSERT INTO test VALUES (1)")
  2379. if _, ok := err.(*MySQLError); !ok {
  2380. dbt.Errorf("expected MySQLError, got %v", err)
  2381. }
  2382. // SELECT queries can be executed.
  2383. var v int
  2384. row := tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM test")
  2385. if err := row.Scan(&v); err != nil {
  2386. dbt.Fatal(err)
  2387. }
  2388. if v != 0 {
  2389. dbt.Errorf("expected val to be 0, got %d", v)
  2390. }
  2391. if err := tx.Commit(); err != nil {
  2392. dbt.Fatal(err)
  2393. }
  2394. })
  2395. }
  2396. func TestRowsColumnTypes(t *testing.T) {
  2397. niNULL := sql.NullInt64{Int64: 0, Valid: false}
  2398. ni0 := sql.NullInt64{Int64: 0, Valid: true}
  2399. ni1 := sql.NullInt64{Int64: 1, Valid: true}
  2400. ni42 := sql.NullInt64{Int64: 42, Valid: true}
  2401. nfNULL := sql.NullFloat64{Float64: 0.0, Valid: false}
  2402. nf0 := sql.NullFloat64{Float64: 0.0, Valid: true}
  2403. nf1337 := sql.NullFloat64{Float64: 13.37, Valid: true}
  2404. nt0 := NullTime{Time: time.Date(2006, 01, 02, 15, 04, 05, 0, time.UTC), Valid: true}
  2405. nt1 := NullTime{Time: time.Date(2006, 01, 02, 15, 04, 05, 100000000, time.UTC), Valid: true}
  2406. nt2 := NullTime{Time: time.Date(2006, 01, 02, 15, 04, 05, 110000000, time.UTC), Valid: true}
  2407. nt6 := NullTime{Time: time.Date(2006, 01, 02, 15, 04, 05, 111111000, time.UTC), Valid: true}
  2408. nd1 := NullTime{Time: time.Date(2006, 01, 02, 0, 0, 0, 0, time.UTC), Valid: true}
  2409. nd2 := NullTime{Time: time.Date(2006, 03, 04, 0, 0, 0, 0, time.UTC), Valid: true}
  2410. ndNULL := NullTime{Time: time.Time{}, Valid: false}
  2411. rbNULL := sql.RawBytes(nil)
  2412. rb0 := sql.RawBytes("0")
  2413. rb42 := sql.RawBytes("42")
  2414. rbTest := sql.RawBytes("Test")
  2415. rb0pad4 := sql.RawBytes("0\x00\x00\x00") // BINARY right-pads values with 0x00
  2416. rbx0 := sql.RawBytes("\x00")
  2417. rbx42 := sql.RawBytes("\x42")
  2418. var columns = []struct {
  2419. name string
  2420. fieldType string // type used when creating table schema
  2421. databaseTypeName string // actual type used by MySQL
  2422. scanType reflect.Type
  2423. nullable bool
  2424. precision int64 // 0 if not ok
  2425. scale int64
  2426. valuesIn [3]string
  2427. valuesOut [3]interface{}
  2428. }{
  2429. {"bit8null", "BIT(8)", "BIT", scanTypeRawBytes, true, 0, 0, [3]string{"0x0", "NULL", "0x42"}, [3]interface{}{rbx0, rbNULL, rbx42}},
  2430. {"boolnull", "BOOL", "TINYINT", scanTypeNullInt, true, 0, 0, [3]string{"NULL", "true", "0"}, [3]interface{}{niNULL, ni1, ni0}},
  2431. {"bool", "BOOL NOT NULL", "TINYINT", scanTypeInt8, false, 0, 0, [3]string{"1", "0", "FALSE"}, [3]interface{}{int8(1), int8(0), int8(0)}},
  2432. {"intnull", "INTEGER", "INT", scanTypeNullInt, true, 0, 0, [3]string{"0", "NULL", "42"}, [3]interface{}{ni0, niNULL, ni42}},
  2433. {"smallint", "SMALLINT NOT NULL", "SMALLINT", scanTypeInt16, false, 0, 0, [3]string{"0", "-32768", "32767"}, [3]interface{}{int16(0), int16(-32768), int16(32767)}},
  2434. {"smallintnull", "SMALLINT", "SMALLINT", scanTypeNullInt, true, 0, 0, [3]string{"0", "NULL", "42"}, [3]interface{}{ni0, niNULL, ni42}},
  2435. {"int3null", "INT(3)", "INT", scanTypeNullInt, true, 0, 0, [3]string{"0", "NULL", "42"}, [3]interface{}{ni0, niNULL, ni42}},
  2436. {"int7", "INT(7) NOT NULL", "INT", scanTypeInt32, false, 0, 0, [3]string{"0", "-1337", "42"}, [3]interface{}{int32(0), int32(-1337), int32(42)}},
  2437. {"mediumintnull", "MEDIUMINT", "MEDIUMINT", scanTypeNullInt, true, 0, 0, [3]string{"0", "42", "NULL"}, [3]interface{}{ni0, ni42, niNULL}},
  2438. {"bigint", "BIGINT NOT NULL", "BIGINT", scanTypeInt64, false, 0, 0, [3]string{"0", "65535", "-42"}, [3]interface{}{int64(0), int64(65535), int64(-42)}},
  2439. {"bigintnull", "BIGINT", "BIGINT", scanTypeNullInt, true, 0, 0, [3]string{"NULL", "1", "42"}, [3]interface{}{niNULL, ni1, ni42}},
  2440. {"tinyuint", "TINYINT UNSIGNED NOT NULL", "TINYINT", scanTypeUint8, false, 0, 0, [3]string{"0", "255", "42"}, [3]interface{}{uint8(0), uint8(255), uint8(42)}},
  2441. {"smalluint", "SMALLINT UNSIGNED NOT NULL", "SMALLINT", scanTypeUint16, false, 0, 0, [3]string{"0", "65535", "42"}, [3]interface{}{uint16(0), uint16(65535), uint16(42)}},
  2442. {"biguint", "BIGINT UNSIGNED NOT NULL", "BIGINT", scanTypeUint64, false, 0, 0, [3]string{"0", "65535", "42"}, [3]interface{}{uint64(0), uint64(65535), uint64(42)}},
  2443. {"uint13", "INT(13) UNSIGNED NOT NULL", "INT", scanTypeUint32, false, 0, 0, [3]string{"0", "1337", "42"}, [3]interface{}{uint32(0), uint32(1337), uint32(42)}},
  2444. {"float", "FLOAT NOT NULL", "FLOAT", scanTypeFloat32, false, math.MaxInt64, math.MaxInt64, [3]string{"0", "42", "13.37"}, [3]interface{}{float32(0), float32(42), float32(13.37)}},
  2445. {"floatnull", "FLOAT", "FLOAT", scanTypeNullFloat, true, math.MaxInt64, math.MaxInt64, [3]string{"0", "NULL", "13.37"}, [3]interface{}{nf0, nfNULL, nf1337}},
  2446. {"float74null", "FLOAT(7,4)", "FLOAT", scanTypeNullFloat, true, math.MaxInt64, 4, [3]string{"0", "NULL", "13.37"}, [3]interface{}{nf0, nfNULL, nf1337}},
  2447. {"double", "DOUBLE NOT NULL", "DOUBLE", scanTypeFloat64, false, math.MaxInt64, math.MaxInt64, [3]string{"0", "42", "13.37"}, [3]interface{}{float64(0), float64(42), float64(13.37)}},
  2448. {"doublenull", "DOUBLE", "DOUBLE", scanTypeNullFloat, true, math.MaxInt64, math.MaxInt64, [3]string{"0", "NULL", "13.37"}, [3]interface{}{nf0, nfNULL, nf1337}},
  2449. {"decimal1", "DECIMAL(10,6) NOT NULL", "DECIMAL", scanTypeRawBytes, false, 10, 6, [3]string{"0", "13.37", "1234.123456"}, [3]interface{}{sql.RawBytes("0.000000"), sql.RawBytes("13.370000"), sql.RawBytes("1234.123456")}},
  2450. {"decimal1null", "DECIMAL(10,6)", "DECIMAL", scanTypeRawBytes, true, 10, 6, [3]string{"0", "NULL", "1234.123456"}, [3]interface{}{sql.RawBytes("0.000000"), rbNULL, sql.RawBytes("1234.123456")}},
  2451. {"decimal2", "DECIMAL(8,4) NOT NULL", "DECIMAL", scanTypeRawBytes, false, 8, 4, [3]string{"0", "13.37", "1234.123456"}, [3]interface{}{sql.RawBytes("0.0000"), sql.RawBytes("13.3700"), sql.RawBytes("1234.1235")}},
  2452. {"decimal2null", "DECIMAL(8,4)", "DECIMAL", scanTypeRawBytes, true, 8, 4, [3]string{"0", "NULL", "1234.123456"}, [3]interface{}{sql.RawBytes("0.0000"), rbNULL, sql.RawBytes("1234.1235")}},
  2453. {"decimal3", "DECIMAL(5,0) NOT NULL", "DECIMAL", scanTypeRawBytes, false, 5, 0, [3]string{"0", "13.37", "-12345.123456"}, [3]interface{}{rb0, sql.RawBytes("13"), sql.RawBytes("-12345")}},
  2454. {"decimal3null", "DECIMAL(5,0)", "DECIMAL", scanTypeRawBytes, true, 5, 0, [3]string{"0", "NULL", "-12345.123456"}, [3]interface{}{rb0, rbNULL, sql.RawBytes("-12345")}},
  2455. {"char25null", "CHAR(25)", "CHAR", scanTypeRawBytes, true, 0, 0, [3]string{"0", "NULL", "'Test'"}, [3]interface{}{rb0, rbNULL, rbTest}},
  2456. {"varchar42", "VARCHAR(42) NOT NULL", "VARCHAR", scanTypeRawBytes, false, 0, 0, [3]string{"0", "'Test'", "42"}, [3]interface{}{rb0, rbTest, rb42}},
  2457. {"binary4null", "BINARY(4)", "BINARY", scanTypeRawBytes, true, 0, 0, [3]string{"0", "NULL", "'Test'"}, [3]interface{}{rb0pad4, rbNULL, rbTest}},
  2458. {"varbinary42", "VARBINARY(42) NOT NULL", "VARBINARY", scanTypeRawBytes, false, 0, 0, [3]string{"0", "'Test'", "42"}, [3]interface{}{rb0, rbTest, rb42}},
  2459. {"tinyblobnull", "TINYBLOB", "BLOB", scanTypeRawBytes, true, 0, 0, [3]string{"0", "NULL", "'Test'"}, [3]interface{}{rb0, rbNULL, rbTest}},
  2460. {"tinytextnull", "TINYTEXT", "TEXT", scanTypeRawBytes, true, 0, 0, [3]string{"0", "NULL", "'Test'"}, [3]interface{}{rb0, rbNULL, rbTest}},
  2461. {"blobnull", "BLOB", "BLOB", scanTypeRawBytes, true, 0, 0, [3]string{"0", "NULL", "'Test'"}, [3]interface{}{rb0, rbNULL, rbTest}},
  2462. {"textnull", "TEXT", "TEXT", scanTypeRawBytes, true, 0, 0, [3]string{"0", "NULL", "'Test'"}, [3]interface{}{rb0, rbNULL, rbTest}},
  2463. {"mediumblob", "MEDIUMBLOB NOT NULL", "BLOB", scanTypeRawBytes, false, 0, 0, [3]string{"0", "'Test'", "42"}, [3]interface{}{rb0, rbTest, rb42}},
  2464. {"mediumtext", "MEDIUMTEXT NOT NULL", "TEXT", scanTypeRawBytes, false, 0, 0, [3]string{"0", "'Test'", "42"}, [3]interface{}{rb0, rbTest, rb42}},
  2465. {"longblob", "LONGBLOB NOT NULL", "BLOB", scanTypeRawBytes, false, 0, 0, [3]string{"0", "'Test'", "42"}, [3]interface{}{rb0, rbTest, rb42}},
  2466. {"longtext", "LONGTEXT NOT NULL", "TEXT", scanTypeRawBytes, false, 0, 0, [3]string{"0", "'Test'", "42"}, [3]interface{}{rb0, rbTest, rb42}},
  2467. {"datetime", "DATETIME", "DATETIME", scanTypeNullTime, true, 0, 0, [3]string{"'2006-01-02 15:04:05'", "'2006-01-02 15:04:05.1'", "'2006-01-02 15:04:05.111111'"}, [3]interface{}{nt0, nt0, nt0}},
  2468. {"datetime2", "DATETIME(2)", "DATETIME", scanTypeNullTime, true, 2, 2, [3]string{"'2006-01-02 15:04:05'", "'2006-01-02 15:04:05.1'", "'2006-01-02 15:04:05.111111'"}, [3]interface{}{nt0, nt1, nt2}},
  2469. {"datetime6", "DATETIME(6)", "DATETIME", scanTypeNullTime, true, 6, 6, [3]string{"'2006-01-02 15:04:05'", "'2006-01-02 15:04:05.1'", "'2006-01-02 15:04:05.111111'"}, [3]interface{}{nt0, nt1, nt6}},
  2470. {"date", "DATE", "DATE", scanTypeNullTime, true, 0, 0, [3]string{"'2006-01-02'", "NULL", "'2006-03-04'"}, [3]interface{}{nd1, ndNULL, nd2}},
  2471. {"year", "YEAR NOT NULL", "YEAR", scanTypeUint16, false, 0, 0, [3]string{"2006", "2000", "1994"}, [3]interface{}{uint16(2006), uint16(2000), uint16(1994)}},
  2472. }
  2473. schema := ""
  2474. values1 := ""
  2475. values2 := ""
  2476. values3 := ""
  2477. for _, column := range columns {
  2478. schema += fmt.Sprintf("`%s` %s, ", column.name, column.fieldType)
  2479. values1 += column.valuesIn[0] + ", "
  2480. values2 += column.valuesIn[1] + ", "
  2481. values3 += column.valuesIn[2] + ", "
  2482. }
  2483. schema = schema[:len(schema)-2]
  2484. values1 = values1[:len(values1)-2]
  2485. values2 = values2[:len(values2)-2]
  2486. values3 = values3[:len(values3)-2]
  2487. dsns := []string{
  2488. dsn + "&parseTime=true",
  2489. dsn + "&parseTime=false",
  2490. }
  2491. for _, testdsn := range dsns {
  2492. runTests(t, testdsn, func(dbt *DBTest) {
  2493. dbt.mustExec("CREATE TABLE test (" + schema + ")")
  2494. dbt.mustExec("INSERT INTO test VALUES (" + values1 + "), (" + values2 + "), (" + values3 + ")")
  2495. rows, err := dbt.db.Query("SELECT * FROM test")
  2496. if err != nil {
  2497. t.Fatalf("Query: %v", err)
  2498. }
  2499. tt, err := rows.ColumnTypes()
  2500. if err != nil {
  2501. t.Fatalf("ColumnTypes: %v", err)
  2502. }
  2503. if len(tt) != len(columns) {
  2504. t.Fatalf("unexpected number of columns: expected %d, got %d", len(columns), len(tt))
  2505. }
  2506. types := make([]reflect.Type, len(tt))
  2507. for i, tp := range tt {
  2508. column := columns[i]
  2509. // Name
  2510. name := tp.Name()
  2511. if name != column.name {
  2512. t.Errorf("column name mismatch %s != %s", name, column.name)
  2513. continue
  2514. }
  2515. // DatabaseTypeName
  2516. databaseTypeName := tp.DatabaseTypeName()
  2517. if databaseTypeName != column.databaseTypeName {
  2518. t.Errorf("databasetypename name mismatch for column %q: %s != %s", name, databaseTypeName, column.databaseTypeName)
  2519. continue
  2520. }
  2521. // ScanType
  2522. scanType := tp.ScanType()
  2523. if scanType != column.scanType {
  2524. if scanType == nil {
  2525. t.Errorf("scantype is null for column %q", name)
  2526. } else {
  2527. t.Errorf("scantype mismatch for column %q: %s != %s", name, scanType.Name(), column.scanType.Name())
  2528. }
  2529. continue
  2530. }
  2531. types[i] = scanType
  2532. // Nullable
  2533. nullable, ok := tp.Nullable()
  2534. if !ok {
  2535. t.Errorf("nullable not ok %q", name)
  2536. continue
  2537. }
  2538. if nullable != column.nullable {
  2539. t.Errorf("nullable mismatch for column %q: %t != %t", name, nullable, column.nullable)
  2540. }
  2541. // Length
  2542. // length, ok := tp.Length()
  2543. // if length != column.length {
  2544. // if !ok {
  2545. // t.Errorf("length not ok for column %q", name)
  2546. // } else {
  2547. // t.Errorf("length mismatch for column %q: %d != %d", name, length, column.length)
  2548. // }
  2549. // continue
  2550. // }
  2551. // Precision and Scale
  2552. precision, scale, ok := tp.DecimalSize()
  2553. if precision != column.precision {
  2554. if !ok {
  2555. t.Errorf("precision not ok for column %q", name)
  2556. } else {
  2557. t.Errorf("precision mismatch for column %q: %d != %d", name, precision, column.precision)
  2558. }
  2559. continue
  2560. }
  2561. if scale != column.scale {
  2562. if !ok {
  2563. t.Errorf("scale not ok for column %q", name)
  2564. } else {
  2565. t.Errorf("scale mismatch for column %q: %d != %d", name, scale, column.scale)
  2566. }
  2567. continue
  2568. }
  2569. }
  2570. values := make([]interface{}, len(tt))
  2571. for i := range values {
  2572. values[i] = reflect.New(types[i]).Interface()
  2573. }
  2574. i := 0
  2575. for rows.Next() {
  2576. err = rows.Scan(values...)
  2577. if err != nil {
  2578. t.Fatalf("failed to scan values in %v", err)
  2579. }
  2580. for j := range values {
  2581. value := reflect.ValueOf(values[j]).Elem().Interface()
  2582. if !reflect.DeepEqual(value, columns[j].valuesOut[i]) {
  2583. if columns[j].scanType == scanTypeRawBytes {
  2584. t.Errorf("row %d, column %d: %v != %v", i, j, string(value.(sql.RawBytes)), string(columns[j].valuesOut[i].(sql.RawBytes)))
  2585. } else {
  2586. t.Errorf("row %d, column %d: %v != %v", i, j, value, columns[j].valuesOut[i])
  2587. }
  2588. }
  2589. }
  2590. i++
  2591. }
  2592. if i != 3 {
  2593. t.Errorf("expected 3 rows, got %d", i)
  2594. }
  2595. if err := rows.Close(); err != nil {
  2596. t.Errorf("error closing rows: %s", err)
  2597. }
  2598. })
  2599. }
  2600. }
  2601. func TestValuerWithValueReceiverGivenNilValue(t *testing.T) {
  2602. runTests(t, dsn, func(dbt *DBTest) {
  2603. dbt.mustExec("CREATE TABLE test (value VARCHAR(255))")
  2604. dbt.db.Exec("INSERT INTO test VALUES (?)", (*testValuer)(nil))
  2605. // This test will panic on the INSERT if ConvertValue() does not check for typed nil before calling Value()
  2606. })
  2607. }
  2608. // TestRawBytesAreNotModified checks for a race condition that arises when a query context
  2609. // is canceled while a user is calling rows.Scan. This is a more stringent test than the one
  2610. // proposed in https://github.com/golang/go/issues/23519. Here we're explicitly using
  2611. // `sql.RawBytes` to check the contents of our internal buffers are not modified after an implicit
  2612. // call to `Rows.Close`, so Context cancellation should **not** invalidate the backing buffers.
  2613. func TestRawBytesAreNotModified(t *testing.T) {
  2614. const blob = "abcdefghijklmnop"
  2615. const contextRaceIterations = 20
  2616. const blobSize = defaultBufSize * 3 / 4 // Second row overwrites first row.
  2617. const insertRows = 4
  2618. var sqlBlobs = [2]string{
  2619. strings.Repeat(blob, blobSize/len(blob)),
  2620. strings.Repeat(strings.ToUpper(blob), blobSize/len(blob)),
  2621. }
  2622. runTests(t, dsn, func(dbt *DBTest) {
  2623. dbt.mustExec("CREATE TABLE test (id int, value BLOB) CHARACTER SET utf8")
  2624. for i := 0; i < insertRows; i++ {
  2625. dbt.mustExec("INSERT INTO test VALUES (?, ?)", i+1, sqlBlobs[i&1])
  2626. }
  2627. for i := 0; i < contextRaceIterations; i++ {
  2628. func() {
  2629. ctx, cancel := context.WithCancel(context.Background())
  2630. defer cancel()
  2631. rows, err := dbt.db.QueryContext(ctx, `SELECT id, value FROM test`)
  2632. if err != nil {
  2633. t.Fatal(err)
  2634. }
  2635. var b int
  2636. var raw sql.RawBytes
  2637. for rows.Next() {
  2638. if err := rows.Scan(&b, &raw); err != nil {
  2639. t.Fatal(err)
  2640. }
  2641. before := string(raw)
  2642. // Ensure cancelling the query does not corrupt the contents of `raw`
  2643. cancel()
  2644. time.Sleep(time.Microsecond * 100)
  2645. after := string(raw)
  2646. if before != after {
  2647. t.Fatalf("the backing storage for sql.RawBytes has been modified (i=%v)", i)
  2648. }
  2649. }
  2650. rows.Close()
  2651. }()
  2652. }
  2653. })
  2654. }