driver_test.go 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001
  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. "crypto/tls"
  12. "database/sql"
  13. "database/sql/driver"
  14. "fmt"
  15. "io"
  16. "io/ioutil"
  17. "log"
  18. "net"
  19. "net/url"
  20. "os"
  21. "strings"
  22. "sync"
  23. "sync/atomic"
  24. "testing"
  25. "time"
  26. )
  27. var (
  28. user string
  29. pass string
  30. prot string
  31. addr string
  32. dbname string
  33. dsn string
  34. netAddr string
  35. available bool
  36. )
  37. var (
  38. tDate = time.Date(2012, 6, 14, 0, 0, 0, 0, time.UTC)
  39. sDate = "2012-06-14"
  40. tDateTime = time.Date(2011, 11, 20, 21, 27, 37, 0, time.UTC)
  41. sDateTime = "2011-11-20 21:27:37"
  42. tDate0 = time.Time{}
  43. sDate0 = "0000-00-00"
  44. sDateTime0 = "0000-00-00 00:00:00"
  45. )
  46. // See https://github.com/go-sql-driver/mysql/wiki/Testing
  47. func init() {
  48. // get environment variables
  49. env := func(key, defaultValue string) string {
  50. if value := os.Getenv(key); value != "" {
  51. return value
  52. }
  53. return defaultValue
  54. }
  55. user = env("MYSQL_TEST_USER", "root")
  56. pass = env("MYSQL_TEST_PASS", "")
  57. prot = env("MYSQL_TEST_PROT", "tcp")
  58. addr = env("MYSQL_TEST_ADDR", "localhost:3306")
  59. dbname = env("MYSQL_TEST_DBNAME", "gotest")
  60. netAddr = fmt.Sprintf("%s(%s)", prot, addr)
  61. dsn = fmt.Sprintf("%s:%s@%s/%s?timeout=30s&strict=true", user, pass, netAddr, dbname)
  62. c, err := net.Dial(prot, addr)
  63. if err == nil {
  64. available = true
  65. c.Close()
  66. }
  67. }
  68. type DBTest struct {
  69. *testing.T
  70. db *sql.DB
  71. }
  72. func runTestsWithMultiStatement(t *testing.T, dsn string, tests ...func(dbt *DBTest)) {
  73. if !available {
  74. t.Skipf("MySQL server not running on %s", netAddr)
  75. }
  76. dsn += "&multiStatements=true"
  77. var db *sql.DB
  78. if _, err := ParseDSN(dsn); err != errInvalidDSNUnsafeCollation {
  79. db, err = sql.Open("mysql", dsn)
  80. if err != nil {
  81. t.Fatalf("error connecting: %s", err.Error())
  82. }
  83. defer db.Close()
  84. }
  85. dbt := &DBTest{t, db}
  86. for _, test := range tests {
  87. test(dbt)
  88. dbt.db.Exec("DROP TABLE IF EXISTS test")
  89. }
  90. }
  91. func runTests(t *testing.T, dsn string, tests ...func(dbt *DBTest)) {
  92. if !available {
  93. t.Skipf("MySQL server not running on %s", netAddr)
  94. }
  95. db, err := sql.Open("mysql", dsn)
  96. if err != nil {
  97. t.Fatalf("error connecting: %s", err.Error())
  98. }
  99. defer db.Close()
  100. db.Exec("DROP TABLE IF EXISTS test")
  101. dsn2 := dsn + "&interpolateParams=true"
  102. var db2 *sql.DB
  103. if _, err := ParseDSN(dsn2); err != errInvalidDSNUnsafeCollation {
  104. db2, err = sql.Open("mysql", dsn2)
  105. if err != nil {
  106. t.Fatalf("error connecting: %s", err.Error())
  107. }
  108. defer db2.Close()
  109. }
  110. dsn3 := dsn + "&multiStatements=true"
  111. var db3 *sql.DB
  112. if _, err := ParseDSN(dsn3); err != errInvalidDSNUnsafeCollation {
  113. db3, err = sql.Open("mysql", dsn3)
  114. if err != nil {
  115. t.Fatalf("error connecting: %s", err.Error())
  116. }
  117. defer db3.Close()
  118. }
  119. dbt := &DBTest{t, db}
  120. dbt2 := &DBTest{t, db2}
  121. dbt3 := &DBTest{t, db3}
  122. for _, test := range tests {
  123. test(dbt)
  124. dbt.db.Exec("DROP TABLE IF EXISTS test")
  125. if db2 != nil {
  126. test(dbt2)
  127. dbt2.db.Exec("DROP TABLE IF EXISTS test")
  128. }
  129. if db3 != nil {
  130. test(dbt3)
  131. dbt3.db.Exec("DROP TABLE IF EXISTS test")
  132. }
  133. }
  134. }
  135. func (dbt *DBTest) fail(method, query string, err error) {
  136. if len(query) > 300 {
  137. query = "[query too large to print]"
  138. }
  139. dbt.Fatalf("error on %s %s: %s", method, query, err.Error())
  140. }
  141. func (dbt *DBTest) mustExec(query string, args ...interface{}) (res sql.Result) {
  142. res, err := dbt.db.Exec(query, args...)
  143. if err != nil {
  144. dbt.fail("exec", query, err)
  145. }
  146. return res
  147. }
  148. func (dbt *DBTest) mustQuery(query string, args ...interface{}) (rows *sql.Rows) {
  149. rows, err := dbt.db.Query(query, args...)
  150. if err != nil {
  151. dbt.fail("query", query, err)
  152. }
  153. return rows
  154. }
  155. func maybeSkip(t *testing.T, err error, skipErrno uint16) {
  156. mySQLErr, ok := err.(*MySQLError)
  157. if !ok {
  158. return
  159. }
  160. if mySQLErr.Number == skipErrno {
  161. t.Skipf("skipping test for error: %v", err)
  162. }
  163. }
  164. func TestEmptyQuery(t *testing.T) {
  165. runTests(t, dsn, func(dbt *DBTest) {
  166. // just a comment, no query
  167. rows := dbt.mustQuery("--")
  168. // will hang before #255
  169. if rows.Next() {
  170. dbt.Errorf("next on rows must be false")
  171. }
  172. })
  173. }
  174. func TestCRUD(t *testing.T) {
  175. runTests(t, dsn, func(dbt *DBTest) {
  176. // Create Table
  177. dbt.mustExec("CREATE TABLE test (value BOOL)")
  178. // Test for unexpected data
  179. var out bool
  180. rows := dbt.mustQuery("SELECT * FROM test")
  181. if rows.Next() {
  182. dbt.Error("unexpected data in empty table")
  183. }
  184. // Create Data
  185. res := dbt.mustExec("INSERT INTO test VALUES (1)")
  186. count, err := res.RowsAffected()
  187. if err != nil {
  188. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  189. }
  190. if count != 1 {
  191. dbt.Fatalf("expected 1 affected row, got %d", count)
  192. }
  193. id, err := res.LastInsertId()
  194. if err != nil {
  195. dbt.Fatalf("res.LastInsertId() returned error: %s", err.Error())
  196. }
  197. if id != 0 {
  198. dbt.Fatalf("expected InsertId 0, got %d", id)
  199. }
  200. // Read
  201. rows = dbt.mustQuery("SELECT value FROM test")
  202. if rows.Next() {
  203. rows.Scan(&out)
  204. if true != out {
  205. dbt.Errorf("true != %t", out)
  206. }
  207. if rows.Next() {
  208. dbt.Error("unexpected data")
  209. }
  210. } else {
  211. dbt.Error("no data")
  212. }
  213. // Update
  214. res = dbt.mustExec("UPDATE test SET value = ? WHERE value = ?", false, true)
  215. count, err = res.RowsAffected()
  216. if err != nil {
  217. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  218. }
  219. if count != 1 {
  220. dbt.Fatalf("expected 1 affected row, got %d", count)
  221. }
  222. // Check Update
  223. rows = dbt.mustQuery("SELECT value FROM test")
  224. if rows.Next() {
  225. rows.Scan(&out)
  226. if false != out {
  227. dbt.Errorf("false != %t", out)
  228. }
  229. if rows.Next() {
  230. dbt.Error("unexpected data")
  231. }
  232. } else {
  233. dbt.Error("no data")
  234. }
  235. // Delete
  236. res = dbt.mustExec("DELETE FROM test WHERE value = ?", false)
  237. count, err = res.RowsAffected()
  238. if err != nil {
  239. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  240. }
  241. if count != 1 {
  242. dbt.Fatalf("expected 1 affected row, got %d", count)
  243. }
  244. // Check for unexpected rows
  245. res = dbt.mustExec("DELETE FROM test")
  246. count, err = res.RowsAffected()
  247. if err != nil {
  248. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  249. }
  250. if count != 0 {
  251. dbt.Fatalf("expected 0 affected row, got %d", count)
  252. }
  253. })
  254. }
  255. func TestMultiQuery(t *testing.T) {
  256. runTestsWithMultiStatement(t, dsn, func(dbt *DBTest) {
  257. // Create Table
  258. dbt.mustExec("CREATE TABLE `test` (`id` int(11) NOT NULL, `value` int(11) NOT NULL) ")
  259. // Create Data
  260. res := dbt.mustExec("INSERT INTO test VALUES (1, 1)")
  261. count, err := res.RowsAffected()
  262. if err != nil {
  263. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  264. }
  265. if count != 1 {
  266. dbt.Fatalf("expected 1 affected row, got %d", count)
  267. }
  268. // Update
  269. 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;")
  270. count, err = res.RowsAffected()
  271. if err != nil {
  272. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  273. }
  274. if count != 1 {
  275. dbt.Fatalf("expected 1 affected row, got %d", count)
  276. }
  277. // Read
  278. var out int
  279. rows := dbt.mustQuery("SELECT value FROM test WHERE id=1;")
  280. if rows.Next() {
  281. rows.Scan(&out)
  282. if 5 != out {
  283. dbt.Errorf("5 != %d", out)
  284. }
  285. if rows.Next() {
  286. dbt.Error("unexpected data")
  287. }
  288. } else {
  289. dbt.Error("no data")
  290. }
  291. })
  292. }
  293. func TestInt(t *testing.T) {
  294. runTests(t, dsn, func(dbt *DBTest) {
  295. types := [5]string{"TINYINT", "SMALLINT", "MEDIUMINT", "INT", "BIGINT"}
  296. in := int64(42)
  297. var out int64
  298. var rows *sql.Rows
  299. // SIGNED
  300. for _, v := range types {
  301. dbt.mustExec("CREATE TABLE test (value " + v + ")")
  302. dbt.mustExec("INSERT INTO test VALUES (?)", in)
  303. rows = dbt.mustQuery("SELECT value FROM test")
  304. if rows.Next() {
  305. rows.Scan(&out)
  306. if in != out {
  307. dbt.Errorf("%s: %d != %d", v, in, out)
  308. }
  309. } else {
  310. dbt.Errorf("%s: no data", v)
  311. }
  312. dbt.mustExec("DROP TABLE IF EXISTS test")
  313. }
  314. // UNSIGNED ZEROFILL
  315. for _, v := range types {
  316. dbt.mustExec("CREATE TABLE test (value " + v + " ZEROFILL)")
  317. dbt.mustExec("INSERT INTO test VALUES (?)", in)
  318. rows = dbt.mustQuery("SELECT value FROM test")
  319. if rows.Next() {
  320. rows.Scan(&out)
  321. if in != out {
  322. dbt.Errorf("%s ZEROFILL: %d != %d", v, in, out)
  323. }
  324. } else {
  325. dbt.Errorf("%s ZEROFILL: no data", v)
  326. }
  327. dbt.mustExec("DROP TABLE IF EXISTS test")
  328. }
  329. })
  330. }
  331. func TestFloat32(t *testing.T) {
  332. runTests(t, dsn, func(dbt *DBTest) {
  333. types := [2]string{"FLOAT", "DOUBLE"}
  334. in := float32(42.23)
  335. var out float32
  336. var rows *sql.Rows
  337. for _, v := range types {
  338. dbt.mustExec("CREATE TABLE test (value " + v + ")")
  339. dbt.mustExec("INSERT INTO test VALUES (?)", in)
  340. rows = dbt.mustQuery("SELECT value FROM test")
  341. if rows.Next() {
  342. rows.Scan(&out)
  343. if in != out {
  344. dbt.Errorf("%s: %g != %g", v, in, out)
  345. }
  346. } else {
  347. dbt.Errorf("%s: no data", v)
  348. }
  349. dbt.mustExec("DROP TABLE IF EXISTS test")
  350. }
  351. })
  352. }
  353. func TestFloat64(t *testing.T) {
  354. runTests(t, dsn, func(dbt *DBTest) {
  355. types := [2]string{"FLOAT", "DOUBLE"}
  356. var expected float64 = 42.23
  357. var out float64
  358. var rows *sql.Rows
  359. for _, v := range types {
  360. dbt.mustExec("CREATE TABLE test (value " + v + ")")
  361. dbt.mustExec("INSERT INTO test VALUES (42.23)")
  362. rows = dbt.mustQuery("SELECT value FROM test")
  363. if rows.Next() {
  364. rows.Scan(&out)
  365. if expected != out {
  366. dbt.Errorf("%s: %g != %g", v, expected, out)
  367. }
  368. } else {
  369. dbt.Errorf("%s: no data", v)
  370. }
  371. dbt.mustExec("DROP TABLE IF EXISTS test")
  372. }
  373. })
  374. }
  375. func TestFloat64Placeholder(t *testing.T) {
  376. runTests(t, dsn, func(dbt *DBTest) {
  377. types := [2]string{"FLOAT", "DOUBLE"}
  378. var expected float64 = 42.23
  379. var out float64
  380. var rows *sql.Rows
  381. for _, v := range types {
  382. dbt.mustExec("CREATE TABLE test (id int, value " + v + ")")
  383. dbt.mustExec("INSERT INTO test VALUES (1, 42.23)")
  384. rows = dbt.mustQuery("SELECT value FROM test WHERE id = ?", 1)
  385. if rows.Next() {
  386. rows.Scan(&out)
  387. if expected != out {
  388. dbt.Errorf("%s: %g != %g", v, expected, out)
  389. }
  390. } else {
  391. dbt.Errorf("%s: no data", v)
  392. }
  393. dbt.mustExec("DROP TABLE IF EXISTS test")
  394. }
  395. })
  396. }
  397. func TestString(t *testing.T) {
  398. runTests(t, dsn, func(dbt *DBTest) {
  399. types := [6]string{"CHAR(255)", "VARCHAR(255)", "TINYTEXT", "TEXT", "MEDIUMTEXT", "LONGTEXT"}
  400. in := "κόσμε üöäßñóùéàâÿœ'îë Árvíztűrő いろはにほへとちりぬるを イロハニホヘト דג סקרן чащах น่าฟังเอย"
  401. var out string
  402. var rows *sql.Rows
  403. for _, v := range types {
  404. dbt.mustExec("CREATE TABLE test (value " + v + ") CHARACTER SET utf8")
  405. dbt.mustExec("INSERT INTO test VALUES (?)", in)
  406. rows = dbt.mustQuery("SELECT value FROM test")
  407. if rows.Next() {
  408. rows.Scan(&out)
  409. if in != out {
  410. dbt.Errorf("%s: %s != %s", v, in, out)
  411. }
  412. } else {
  413. dbt.Errorf("%s: no data", v)
  414. }
  415. dbt.mustExec("DROP TABLE IF EXISTS test")
  416. }
  417. // BLOB
  418. dbt.mustExec("CREATE TABLE test (id int, value BLOB) CHARACTER SET utf8")
  419. id := 2
  420. in = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, " +
  421. "sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, " +
  422. "sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. " +
  423. "Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. " +
  424. "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, " +
  425. "sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, " +
  426. "sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. " +
  427. "Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."
  428. dbt.mustExec("INSERT INTO test VALUES (?, ?)", id, in)
  429. err := dbt.db.QueryRow("SELECT value FROM test WHERE id = ?", id).Scan(&out)
  430. if err != nil {
  431. dbt.Fatalf("Error on BLOB-Query: %s", err.Error())
  432. } else if out != in {
  433. dbt.Errorf("BLOB: %s != %s", in, out)
  434. }
  435. })
  436. }
  437. type timeTests struct {
  438. dbtype string
  439. tlayout string
  440. tests []timeTest
  441. }
  442. type timeTest struct {
  443. s string // leading "!": do not use t as value in queries
  444. t time.Time
  445. }
  446. type timeMode byte
  447. func (t timeMode) String() string {
  448. switch t {
  449. case binaryString:
  450. return "binary:string"
  451. case binaryTime:
  452. return "binary:time.Time"
  453. case textString:
  454. return "text:string"
  455. }
  456. panic("unsupported timeMode")
  457. }
  458. func (t timeMode) Binary() bool {
  459. switch t {
  460. case binaryString, binaryTime:
  461. return true
  462. }
  463. return false
  464. }
  465. const (
  466. binaryString timeMode = iota
  467. binaryTime
  468. textString
  469. )
  470. func (t timeTest) genQuery(dbtype string, mode timeMode) string {
  471. var inner string
  472. if mode.Binary() {
  473. inner = "?"
  474. } else {
  475. inner = `"%s"`
  476. }
  477. return `SELECT cast(` + inner + ` as ` + dbtype + `)`
  478. }
  479. func (t timeTest) run(dbt *DBTest, dbtype, tlayout string, mode timeMode) {
  480. var rows *sql.Rows
  481. query := t.genQuery(dbtype, mode)
  482. switch mode {
  483. case binaryString:
  484. rows = dbt.mustQuery(query, t.s)
  485. case binaryTime:
  486. rows = dbt.mustQuery(query, t.t)
  487. case textString:
  488. query = fmt.Sprintf(query, t.s)
  489. rows = dbt.mustQuery(query)
  490. default:
  491. panic("unsupported mode")
  492. }
  493. defer rows.Close()
  494. var err error
  495. if !rows.Next() {
  496. err = rows.Err()
  497. if err == nil {
  498. err = fmt.Errorf("no data")
  499. }
  500. dbt.Errorf("%s [%s]: %s", dbtype, mode, err)
  501. return
  502. }
  503. var dst interface{}
  504. err = rows.Scan(&dst)
  505. if err != nil {
  506. dbt.Errorf("%s [%s]: %s", dbtype, mode, err)
  507. return
  508. }
  509. switch val := dst.(type) {
  510. case []uint8:
  511. str := string(val)
  512. if str == t.s {
  513. return
  514. }
  515. if mode.Binary() && dbtype == "DATETIME" && len(str) == 26 && str[:19] == t.s {
  516. // a fix mainly for TravisCI:
  517. // accept full microsecond resolution in result for DATETIME columns
  518. // where the binary protocol was used
  519. return
  520. }
  521. dbt.Errorf("%s [%s] to string: expected %q, got %q",
  522. dbtype, mode,
  523. t.s, str,
  524. )
  525. case time.Time:
  526. if val == t.t {
  527. return
  528. }
  529. dbt.Errorf("%s [%s] to string: expected %q, got %q",
  530. dbtype, mode,
  531. t.s, val.Format(tlayout),
  532. )
  533. default:
  534. fmt.Printf("%#v\n", []interface{}{dbtype, tlayout, mode, t.s, t.t})
  535. dbt.Errorf("%s [%s]: unhandled type %T (is '%v')",
  536. dbtype, mode,
  537. val, val,
  538. )
  539. }
  540. }
  541. func TestDateTime(t *testing.T) {
  542. afterTime := func(t time.Time, d string) time.Time {
  543. dur, err := time.ParseDuration(d)
  544. if err != nil {
  545. panic(err)
  546. }
  547. return t.Add(dur)
  548. }
  549. // NOTE: MySQL rounds DATETIME(x) up - but that's not included in the tests
  550. format := "2006-01-02 15:04:05.999999"
  551. t0 := time.Time{}
  552. tstr0 := "0000-00-00 00:00:00.000000"
  553. testcases := []timeTests{
  554. {"DATE", format[:10], []timeTest{
  555. {t: time.Date(2011, 11, 20, 0, 0, 0, 0, time.UTC)},
  556. {t: t0, s: tstr0[:10]},
  557. }},
  558. {"DATETIME", format[:19], []timeTest{
  559. {t: time.Date(2011, 11, 20, 21, 27, 37, 0, time.UTC)},
  560. {t: t0, s: tstr0[:19]},
  561. }},
  562. {"DATETIME(0)", format[:21], []timeTest{
  563. {t: time.Date(2011, 11, 20, 21, 27, 37, 0, time.UTC)},
  564. {t: t0, s: tstr0[:19]},
  565. }},
  566. {"DATETIME(1)", format[:21], []timeTest{
  567. {t: time.Date(2011, 11, 20, 21, 27, 37, 100000000, time.UTC)},
  568. {t: t0, s: tstr0[:21]},
  569. }},
  570. {"DATETIME(6)", format, []timeTest{
  571. {t: time.Date(2011, 11, 20, 21, 27, 37, 123456000, time.UTC)},
  572. {t: t0, s: tstr0},
  573. }},
  574. {"TIME", format[11:19], []timeTest{
  575. {t: afterTime(t0, "12345s")},
  576. {s: "!-12:34:56"},
  577. {s: "!-838:59:59"},
  578. {s: "!838:59:59"},
  579. {t: t0, s: tstr0[11:19]},
  580. }},
  581. {"TIME(0)", format[11:19], []timeTest{
  582. {t: afterTime(t0, "12345s")},
  583. {s: "!-12:34:56"},
  584. {s: "!-838:59:59"},
  585. {s: "!838:59:59"},
  586. {t: t0, s: tstr0[11:19]},
  587. }},
  588. {"TIME(1)", format[11:21], []timeTest{
  589. {t: afterTime(t0, "12345600ms")},
  590. {s: "!-12:34:56.7"},
  591. {s: "!-838:59:58.9"},
  592. {s: "!838:59:58.9"},
  593. {t: t0, s: tstr0[11:21]},
  594. }},
  595. {"TIME(6)", format[11:], []timeTest{
  596. {t: afterTime(t0, "1234567890123000ns")},
  597. {s: "!-12:34:56.789012"},
  598. {s: "!-838:59:58.999999"},
  599. {s: "!838:59:58.999999"},
  600. {t: t0, s: tstr0[11:]},
  601. }},
  602. }
  603. dsns := []string{
  604. dsn + "&parseTime=true",
  605. dsn + "&parseTime=false",
  606. }
  607. for _, testdsn := range dsns {
  608. runTests(t, testdsn, func(dbt *DBTest) {
  609. microsecsSupported := false
  610. zeroDateSupported := false
  611. var rows *sql.Rows
  612. var err error
  613. rows, err = dbt.db.Query(`SELECT cast("00:00:00.1" as TIME(1)) = "00:00:00.1"`)
  614. if err == nil {
  615. rows.Scan(&microsecsSupported)
  616. rows.Close()
  617. }
  618. rows, err = dbt.db.Query(`SELECT cast("0000-00-00" as DATE) = "0000-00-00"`)
  619. if err == nil {
  620. rows.Scan(&zeroDateSupported)
  621. rows.Close()
  622. }
  623. for _, setups := range testcases {
  624. if t := setups.dbtype; !microsecsSupported && t[len(t)-1:] == ")" {
  625. // skip fractional second tests if unsupported by server
  626. continue
  627. }
  628. for _, setup := range setups.tests {
  629. allowBinTime := true
  630. if setup.s == "" {
  631. // fill time string wherever Go can reliable produce it
  632. setup.s = setup.t.Format(setups.tlayout)
  633. } else if setup.s[0] == '!' {
  634. // skip tests using setup.t as source in queries
  635. allowBinTime = false
  636. // fix setup.s - remove the "!"
  637. setup.s = setup.s[1:]
  638. }
  639. if !zeroDateSupported && setup.s == tstr0[:len(setup.s)] {
  640. // skip disallowed 0000-00-00 date
  641. continue
  642. }
  643. setup.run(dbt, setups.dbtype, setups.tlayout, textString)
  644. setup.run(dbt, setups.dbtype, setups.tlayout, binaryString)
  645. if allowBinTime {
  646. setup.run(dbt, setups.dbtype, setups.tlayout, binaryTime)
  647. }
  648. }
  649. }
  650. })
  651. }
  652. }
  653. func TestTimestampMicros(t *testing.T) {
  654. format := "2006-01-02 15:04:05.999999"
  655. f0 := format[:19]
  656. f1 := format[:21]
  657. f6 := format[:26]
  658. runTests(t, dsn, func(dbt *DBTest) {
  659. // check if microseconds are supported.
  660. // Do not use timestamp(x) for that check - before 5.5.6, x would mean display width
  661. // and not precision.
  662. // Se last paragraph at http://dev.mysql.com/doc/refman/5.6/en/fractional-seconds.html
  663. microsecsSupported := false
  664. if rows, err := dbt.db.Query(`SELECT cast("00:00:00.1" as TIME(1)) = "00:00:00.1"`); err == nil {
  665. rows.Scan(&microsecsSupported)
  666. rows.Close()
  667. }
  668. if !microsecsSupported {
  669. // skip test
  670. return
  671. }
  672. _, err := dbt.db.Exec(`
  673. CREATE TABLE test (
  674. value0 TIMESTAMP NOT NULL DEFAULT '` + f0 + `',
  675. value1 TIMESTAMP(1) NOT NULL DEFAULT '` + f1 + `',
  676. value6 TIMESTAMP(6) NOT NULL DEFAULT '` + f6 + `'
  677. )`,
  678. )
  679. if err != nil {
  680. dbt.Error(err)
  681. }
  682. defer dbt.mustExec("DROP TABLE IF EXISTS test")
  683. dbt.mustExec("INSERT INTO test SET value0=?, value1=?, value6=?", f0, f1, f6)
  684. var res0, res1, res6 string
  685. rows := dbt.mustQuery("SELECT * FROM test")
  686. if !rows.Next() {
  687. dbt.Errorf("test contained no selectable values")
  688. }
  689. err = rows.Scan(&res0, &res1, &res6)
  690. if err != nil {
  691. dbt.Error(err)
  692. }
  693. if res0 != f0 {
  694. dbt.Errorf("expected %q, got %q", f0, res0)
  695. }
  696. if res1 != f1 {
  697. dbt.Errorf("expected %q, got %q", f1, res1)
  698. }
  699. if res6 != f6 {
  700. dbt.Errorf("expected %q, got %q", f6, res6)
  701. }
  702. })
  703. }
  704. func TestNULL(t *testing.T) {
  705. runTests(t, dsn, func(dbt *DBTest) {
  706. nullStmt, err := dbt.db.Prepare("SELECT NULL")
  707. if err != nil {
  708. dbt.Fatal(err)
  709. }
  710. defer nullStmt.Close()
  711. nonNullStmt, err := dbt.db.Prepare("SELECT 1")
  712. if err != nil {
  713. dbt.Fatal(err)
  714. }
  715. defer nonNullStmt.Close()
  716. // NullBool
  717. var nb sql.NullBool
  718. // Invalid
  719. if err = nullStmt.QueryRow().Scan(&nb); err != nil {
  720. dbt.Fatal(err)
  721. }
  722. if nb.Valid {
  723. dbt.Error("valid NullBool which should be invalid")
  724. }
  725. // Valid
  726. if err = nonNullStmt.QueryRow().Scan(&nb); err != nil {
  727. dbt.Fatal(err)
  728. }
  729. if !nb.Valid {
  730. dbt.Error("invalid NullBool which should be valid")
  731. } else if nb.Bool != true {
  732. dbt.Errorf("Unexpected NullBool value: %t (should be true)", nb.Bool)
  733. }
  734. // NullFloat64
  735. var nf sql.NullFloat64
  736. // Invalid
  737. if err = nullStmt.QueryRow().Scan(&nf); err != nil {
  738. dbt.Fatal(err)
  739. }
  740. if nf.Valid {
  741. dbt.Error("valid NullFloat64 which should be invalid")
  742. }
  743. // Valid
  744. if err = nonNullStmt.QueryRow().Scan(&nf); err != nil {
  745. dbt.Fatal(err)
  746. }
  747. if !nf.Valid {
  748. dbt.Error("invalid NullFloat64 which should be valid")
  749. } else if nf.Float64 != float64(1) {
  750. dbt.Errorf("unexpected NullFloat64 value: %f (should be 1.0)", nf.Float64)
  751. }
  752. // NullInt64
  753. var ni sql.NullInt64
  754. // Invalid
  755. if err = nullStmt.QueryRow().Scan(&ni); err != nil {
  756. dbt.Fatal(err)
  757. }
  758. if ni.Valid {
  759. dbt.Error("valid NullInt64 which should be invalid")
  760. }
  761. // Valid
  762. if err = nonNullStmt.QueryRow().Scan(&ni); err != nil {
  763. dbt.Fatal(err)
  764. }
  765. if !ni.Valid {
  766. dbt.Error("invalid NullInt64 which should be valid")
  767. } else if ni.Int64 != int64(1) {
  768. dbt.Errorf("unexpected NullInt64 value: %d (should be 1)", ni.Int64)
  769. }
  770. // NullString
  771. var ns sql.NullString
  772. // Invalid
  773. if err = nullStmt.QueryRow().Scan(&ns); err != nil {
  774. dbt.Fatal(err)
  775. }
  776. if ns.Valid {
  777. dbt.Error("valid NullString which should be invalid")
  778. }
  779. // Valid
  780. if err = nonNullStmt.QueryRow().Scan(&ns); err != nil {
  781. dbt.Fatal(err)
  782. }
  783. if !ns.Valid {
  784. dbt.Error("invalid NullString which should be valid")
  785. } else if ns.String != `1` {
  786. dbt.Error("unexpected NullString value:" + ns.String + " (should be `1`)")
  787. }
  788. // nil-bytes
  789. var b []byte
  790. // Read nil
  791. if err = nullStmt.QueryRow().Scan(&b); err != nil {
  792. dbt.Fatal(err)
  793. }
  794. if b != nil {
  795. dbt.Error("non-nil []byte which should be nil")
  796. }
  797. // Read non-nil
  798. if err = nonNullStmt.QueryRow().Scan(&b); err != nil {
  799. dbt.Fatal(err)
  800. }
  801. if b == nil {
  802. dbt.Error("nil []byte which should be non-nil")
  803. }
  804. // Insert nil
  805. b = nil
  806. success := false
  807. if err = dbt.db.QueryRow("SELECT ? IS NULL", b).Scan(&success); err != nil {
  808. dbt.Fatal(err)
  809. }
  810. if !success {
  811. dbt.Error("inserting []byte(nil) as NULL failed")
  812. }
  813. // Check input==output with input==nil
  814. b = nil
  815. if err = dbt.db.QueryRow("SELECT ?", b).Scan(&b); err != nil {
  816. dbt.Fatal(err)
  817. }
  818. if b != nil {
  819. dbt.Error("non-nil echo from nil input")
  820. }
  821. // Check input==output with input!=nil
  822. b = []byte("")
  823. if err = dbt.db.QueryRow("SELECT ?", b).Scan(&b); err != nil {
  824. dbt.Fatal(err)
  825. }
  826. if b == nil {
  827. dbt.Error("nil echo from non-nil input")
  828. }
  829. // Insert NULL
  830. dbt.mustExec("CREATE TABLE test (dummmy1 int, value int, dummy2 int)")
  831. dbt.mustExec("INSERT INTO test VALUES (?, ?, ?)", 1, nil, 2)
  832. var out interface{}
  833. rows := dbt.mustQuery("SELECT * FROM test")
  834. if rows.Next() {
  835. rows.Scan(&out)
  836. if out != nil {
  837. dbt.Errorf("%v != nil", out)
  838. }
  839. } else {
  840. dbt.Error("no data")
  841. }
  842. })
  843. }
  844. func TestUint64(t *testing.T) {
  845. const (
  846. u0 = uint64(0)
  847. uall = ^u0
  848. uhigh = uall >> 1
  849. utop = ^uhigh
  850. s0 = int64(0)
  851. sall = ^s0
  852. shigh = int64(uhigh)
  853. stop = ^shigh
  854. )
  855. runTests(t, dsn, func(dbt *DBTest) {
  856. stmt, err := dbt.db.Prepare(`SELECT ?, ?, ? ,?, ?, ?, ?, ?`)
  857. if err != nil {
  858. dbt.Fatal(err)
  859. }
  860. defer stmt.Close()
  861. row := stmt.QueryRow(
  862. u0, uhigh, utop, uall,
  863. s0, shigh, stop, sall,
  864. )
  865. var ua, ub, uc, ud uint64
  866. var sa, sb, sc, sd int64
  867. err = row.Scan(&ua, &ub, &uc, &ud, &sa, &sb, &sc, &sd)
  868. if err != nil {
  869. dbt.Fatal(err)
  870. }
  871. switch {
  872. case ua != u0,
  873. ub != uhigh,
  874. uc != utop,
  875. ud != uall,
  876. sa != s0,
  877. sb != shigh,
  878. sc != stop,
  879. sd != sall:
  880. dbt.Fatal("unexpected result value")
  881. }
  882. })
  883. }
  884. func TestLongData(t *testing.T) {
  885. runTests(t, dsn, func(dbt *DBTest) {
  886. var maxAllowedPacketSize int
  887. err := dbt.db.QueryRow("select @@max_allowed_packet").Scan(&maxAllowedPacketSize)
  888. if err != nil {
  889. dbt.Fatal(err)
  890. }
  891. maxAllowedPacketSize--
  892. // don't get too ambitious
  893. if maxAllowedPacketSize > 1<<25 {
  894. maxAllowedPacketSize = 1 << 25
  895. }
  896. dbt.mustExec("CREATE TABLE test (value LONGBLOB)")
  897. in := strings.Repeat(`a`, maxAllowedPacketSize+1)
  898. var out string
  899. var rows *sql.Rows
  900. // Long text data
  901. const nonDataQueryLen = 28 // length query w/o value
  902. inS := in[:maxAllowedPacketSize-nonDataQueryLen]
  903. dbt.mustExec("INSERT INTO test VALUES('" + inS + "')")
  904. rows = dbt.mustQuery("SELECT value FROM test")
  905. if rows.Next() {
  906. rows.Scan(&out)
  907. if inS != out {
  908. dbt.Fatalf("LONGBLOB: length in: %d, length out: %d", len(inS), len(out))
  909. }
  910. if rows.Next() {
  911. dbt.Error("LONGBLOB: unexpexted row")
  912. }
  913. } else {
  914. dbt.Fatalf("LONGBLOB: no data")
  915. }
  916. // Empty table
  917. dbt.mustExec("TRUNCATE TABLE test")
  918. // Long binary data
  919. dbt.mustExec("INSERT INTO test VALUES(?)", in)
  920. rows = dbt.mustQuery("SELECT value FROM test WHERE 1=?", 1)
  921. if rows.Next() {
  922. rows.Scan(&out)
  923. if in != out {
  924. dbt.Fatalf("LONGBLOB: length in: %d, length out: %d", len(in), len(out))
  925. }
  926. if rows.Next() {
  927. dbt.Error("LONGBLOB: unexpexted row")
  928. }
  929. } else {
  930. if err = rows.Err(); err != nil {
  931. dbt.Fatalf("LONGBLOB: no data (err: %s)", err.Error())
  932. } else {
  933. dbt.Fatal("LONGBLOB: no data (err: <nil>)")
  934. }
  935. }
  936. })
  937. }
  938. func TestLoadData(t *testing.T) {
  939. runTests(t, dsn, func(dbt *DBTest) {
  940. verifyLoadDataResult := func() {
  941. rows, err := dbt.db.Query("SELECT * FROM test")
  942. if err != nil {
  943. dbt.Fatal(err.Error())
  944. }
  945. i := 0
  946. values := [4]string{
  947. "a string",
  948. "a string containing a \t",
  949. "a string containing a \n",
  950. "a string containing both \t\n",
  951. }
  952. var id int
  953. var value string
  954. for rows.Next() {
  955. i++
  956. err = rows.Scan(&id, &value)
  957. if err != nil {
  958. dbt.Fatal(err.Error())
  959. }
  960. if i != id {
  961. dbt.Fatalf("%d != %d", i, id)
  962. }
  963. if values[i-1] != value {
  964. dbt.Fatalf("%q != %q", values[i-1], value)
  965. }
  966. }
  967. err = rows.Err()
  968. if err != nil {
  969. dbt.Fatal(err.Error())
  970. }
  971. if i != 4 {
  972. dbt.Fatalf("rows count mismatch. Got %d, want 4", i)
  973. }
  974. }
  975. dbt.db.Exec("DROP TABLE IF EXISTS test")
  976. dbt.mustExec("CREATE TABLE test (id INT NOT NULL PRIMARY KEY, value TEXT NOT NULL) CHARACTER SET utf8")
  977. // Local File
  978. file, err := ioutil.TempFile("", "gotest")
  979. defer os.Remove(file.Name())
  980. if err != nil {
  981. dbt.Fatal(err)
  982. }
  983. RegisterLocalFile(file.Name())
  984. // Try first with empty file
  985. dbt.mustExec(fmt.Sprintf("LOAD DATA LOCAL INFILE %q INTO TABLE test", file.Name()))
  986. var count int
  987. err = dbt.db.QueryRow("SELECT COUNT(*) FROM test").Scan(&count)
  988. if err != nil {
  989. dbt.Fatal(err.Error())
  990. }
  991. if count != 0 {
  992. dbt.Fatalf("unexpected row count: got %d, want 0", count)
  993. }
  994. // Then fille File with data and try to load it
  995. 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")
  996. file.Close()
  997. dbt.mustExec(fmt.Sprintf("LOAD DATA LOCAL INFILE %q INTO TABLE test", file.Name()))
  998. verifyLoadDataResult()
  999. // Try with non-existing file
  1000. _, err = dbt.db.Exec("LOAD DATA LOCAL INFILE 'doesnotexist' INTO TABLE test")
  1001. if err == nil {
  1002. dbt.Fatal("load non-existent file didn't fail")
  1003. } else if err.Error() != "local file 'doesnotexist' is not registered" {
  1004. dbt.Fatal(err.Error())
  1005. }
  1006. // Empty table
  1007. dbt.mustExec("TRUNCATE TABLE test")
  1008. // Reader
  1009. RegisterReaderHandler("test", func() io.Reader {
  1010. file, err = os.Open(file.Name())
  1011. if err != nil {
  1012. dbt.Fatal(err)
  1013. }
  1014. return file
  1015. })
  1016. dbt.mustExec("LOAD DATA LOCAL INFILE 'Reader::test' INTO TABLE test")
  1017. verifyLoadDataResult()
  1018. // negative test
  1019. _, err = dbt.db.Exec("LOAD DATA LOCAL INFILE 'Reader::doesnotexist' INTO TABLE test")
  1020. if err == nil {
  1021. dbt.Fatal("load non-existent Reader didn't fail")
  1022. } else if err.Error() != "Reader 'doesnotexist' is not registered" {
  1023. dbt.Fatal(err.Error())
  1024. }
  1025. })
  1026. }
  1027. func TestFoundRows(t *testing.T) {
  1028. runTests(t, dsn, func(dbt *DBTest) {
  1029. dbt.mustExec("CREATE TABLE test (id INT NOT NULL ,data INT NOT NULL)")
  1030. dbt.mustExec("INSERT INTO test (id, data) VALUES (0, 0),(0, 0),(1, 0),(1, 0),(1, 1)")
  1031. res := dbt.mustExec("UPDATE test SET data = 1 WHERE id = 0")
  1032. count, err := res.RowsAffected()
  1033. if err != nil {
  1034. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  1035. }
  1036. if count != 2 {
  1037. dbt.Fatalf("Expected 2 affected rows, got %d", count)
  1038. }
  1039. res = dbt.mustExec("UPDATE test SET data = 1 WHERE id = 1")
  1040. count, err = res.RowsAffected()
  1041. if err != nil {
  1042. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  1043. }
  1044. if count != 2 {
  1045. dbt.Fatalf("Expected 2 affected rows, got %d", count)
  1046. }
  1047. })
  1048. runTests(t, dsn+"&clientFoundRows=true", func(dbt *DBTest) {
  1049. dbt.mustExec("CREATE TABLE test (id INT NOT NULL ,data INT NOT NULL)")
  1050. dbt.mustExec("INSERT INTO test (id, data) VALUES (0, 0),(0, 0),(1, 0),(1, 0),(1, 1)")
  1051. res := dbt.mustExec("UPDATE test SET data = 1 WHERE id = 0")
  1052. count, err := res.RowsAffected()
  1053. if err != nil {
  1054. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  1055. }
  1056. if count != 2 {
  1057. dbt.Fatalf("Expected 2 matched rows, got %d", count)
  1058. }
  1059. res = dbt.mustExec("UPDATE test SET data = 1 WHERE id = 1")
  1060. count, err = res.RowsAffected()
  1061. if err != nil {
  1062. dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
  1063. }
  1064. if count != 3 {
  1065. dbt.Fatalf("Expected 3 matched rows, got %d", count)
  1066. }
  1067. })
  1068. }
  1069. func TestStrict(t *testing.T) {
  1070. // ALLOW_INVALID_DATES to get rid of stricter modes - we want to test for warnings, not errors
  1071. relaxedDsn := dsn + "&sql_mode='ALLOW_INVALID_DATES,NO_AUTO_CREATE_USER'"
  1072. // make sure the MySQL version is recent enough with a separate connection
  1073. // before running the test
  1074. conn, err := MySQLDriver{}.Open(relaxedDsn)
  1075. if conn != nil {
  1076. conn.Close()
  1077. }
  1078. // Error 1231: Variable 'sql_mode' can't be set to the value of
  1079. // 'ALLOW_INVALID_DATES' => skip test, MySQL server version is too old
  1080. maybeSkip(t, err, 1231)
  1081. runTests(t, relaxedDsn, func(dbt *DBTest) {
  1082. dbt.mustExec("CREATE TABLE test (a TINYINT NOT NULL, b CHAR(4))")
  1083. var queries = [...]struct {
  1084. in string
  1085. codes []string
  1086. }{
  1087. {"DROP TABLE IF EXISTS no_such_table", []string{"1051"}},
  1088. {"INSERT INTO test VALUES(10,'mysql'),(NULL,'test'),(300,'Open Source')", []string{"1265", "1048", "1264", "1265"}},
  1089. }
  1090. var err error
  1091. var checkWarnings = func(err error, mode string, idx int) {
  1092. if err == nil {
  1093. dbt.Errorf("expected STRICT error on query [%s] %s", mode, queries[idx].in)
  1094. }
  1095. if warnings, ok := err.(MySQLWarnings); ok {
  1096. var codes = make([]string, len(warnings))
  1097. for i := range warnings {
  1098. codes[i] = warnings[i].Code
  1099. }
  1100. if len(codes) != len(queries[idx].codes) {
  1101. dbt.Errorf("unexpected STRICT error count on query [%s] %s: Wanted %v, Got %v", mode, queries[idx].in, queries[idx].codes, codes)
  1102. }
  1103. for i := range warnings {
  1104. if codes[i] != queries[idx].codes[i] {
  1105. dbt.Errorf("unexpected STRICT error codes on query [%s] %s: Wanted %v, Got %v", mode, queries[idx].in, queries[idx].codes, codes)
  1106. return
  1107. }
  1108. }
  1109. } else {
  1110. dbt.Errorf("unexpected error on query [%s] %s: %s", mode, queries[idx].in, err.Error())
  1111. }
  1112. }
  1113. // text protocol
  1114. for i := range queries {
  1115. _, err = dbt.db.Exec(queries[i].in)
  1116. checkWarnings(err, "text", i)
  1117. }
  1118. var stmt *sql.Stmt
  1119. // binary protocol
  1120. for i := range queries {
  1121. stmt, err = dbt.db.Prepare(queries[i].in)
  1122. if err != nil {
  1123. dbt.Errorf("error on preparing query %s: %s", queries[i].in, err.Error())
  1124. }
  1125. _, err = stmt.Exec()
  1126. checkWarnings(err, "binary", i)
  1127. err = stmt.Close()
  1128. if err != nil {
  1129. dbt.Errorf("error on closing stmt for query %s: %s", queries[i].in, err.Error())
  1130. }
  1131. }
  1132. })
  1133. }
  1134. func TestTLS(t *testing.T) {
  1135. tlsTest := func(dbt *DBTest) {
  1136. if err := dbt.db.Ping(); err != nil {
  1137. if err == ErrNoTLS {
  1138. dbt.Skip("server does not support TLS")
  1139. } else {
  1140. dbt.Fatalf("error on Ping: %s", err.Error())
  1141. }
  1142. }
  1143. rows := dbt.mustQuery("SHOW STATUS LIKE 'Ssl_cipher'")
  1144. var variable, value *sql.RawBytes
  1145. for rows.Next() {
  1146. if err := rows.Scan(&variable, &value); err != nil {
  1147. dbt.Fatal(err.Error())
  1148. }
  1149. if value == nil {
  1150. dbt.Fatal("no Cipher")
  1151. }
  1152. }
  1153. }
  1154. runTests(t, dsn+"&tls=skip-verify", tlsTest)
  1155. // Verify that registering / using a custom cfg works
  1156. RegisterTLSConfig("custom-skip-verify", &tls.Config{
  1157. InsecureSkipVerify: true,
  1158. })
  1159. runTests(t, dsn+"&tls=custom-skip-verify", tlsTest)
  1160. }
  1161. func TestReuseClosedConnection(t *testing.T) {
  1162. // this test does not use sql.database, it uses the driver directly
  1163. if !available {
  1164. t.Skipf("MySQL server not running on %s", netAddr)
  1165. }
  1166. md := &MySQLDriver{}
  1167. conn, err := md.Open(dsn)
  1168. if err != nil {
  1169. t.Fatalf("error connecting: %s", err.Error())
  1170. }
  1171. stmt, err := conn.Prepare("DO 1")
  1172. if err != nil {
  1173. t.Fatalf("error preparing statement: %s", err.Error())
  1174. }
  1175. _, err = stmt.Exec(nil)
  1176. if err != nil {
  1177. t.Fatalf("error executing statement: %s", err.Error())
  1178. }
  1179. err = conn.Close()
  1180. if err != nil {
  1181. t.Fatalf("error closing connection: %s", err.Error())
  1182. }
  1183. defer func() {
  1184. if err := recover(); err != nil {
  1185. t.Errorf("panic after reusing a closed connection: %v", err)
  1186. }
  1187. }()
  1188. _, err = stmt.Exec(nil)
  1189. if err != nil && err != driver.ErrBadConn {
  1190. t.Errorf("unexpected error '%s', expected '%s'",
  1191. err.Error(), driver.ErrBadConn.Error())
  1192. }
  1193. }
  1194. func TestCharset(t *testing.T) {
  1195. if !available {
  1196. t.Skipf("MySQL server not running on %s", netAddr)
  1197. }
  1198. mustSetCharset := func(charsetParam, expected string) {
  1199. runTests(t, dsn+"&"+charsetParam, func(dbt *DBTest) {
  1200. rows := dbt.mustQuery("SELECT @@character_set_connection")
  1201. defer rows.Close()
  1202. if !rows.Next() {
  1203. dbt.Fatalf("error getting connection charset: %s", rows.Err())
  1204. }
  1205. var got string
  1206. rows.Scan(&got)
  1207. if got != expected {
  1208. dbt.Fatalf("expected connection charset %s but got %s", expected, got)
  1209. }
  1210. })
  1211. }
  1212. // non utf8 test
  1213. mustSetCharset("charset=ascii", "ascii")
  1214. // when the first charset is invalid, use the second
  1215. mustSetCharset("charset=none,utf8", "utf8")
  1216. // when the first charset is valid, use it
  1217. mustSetCharset("charset=ascii,utf8", "ascii")
  1218. mustSetCharset("charset=utf8,ascii", "utf8")
  1219. }
  1220. func TestFailingCharset(t *testing.T) {
  1221. runTests(t, dsn+"&charset=none", func(dbt *DBTest) {
  1222. // run query to really establish connection...
  1223. _, err := dbt.db.Exec("SELECT 1")
  1224. if err == nil {
  1225. dbt.db.Close()
  1226. t.Fatalf("connection must not succeed without a valid charset")
  1227. }
  1228. })
  1229. }
  1230. func TestCollation(t *testing.T) {
  1231. if !available {
  1232. t.Skipf("MySQL server not running on %s", netAddr)
  1233. }
  1234. defaultCollation := "utf8_general_ci"
  1235. testCollations := []string{
  1236. "", // do not set
  1237. defaultCollation, // driver default
  1238. "latin1_general_ci",
  1239. "binary",
  1240. "utf8_unicode_ci",
  1241. "cp1257_bin",
  1242. }
  1243. for _, collation := range testCollations {
  1244. var expected, tdsn string
  1245. if collation != "" {
  1246. tdsn = dsn + "&collation=" + collation
  1247. expected = collation
  1248. } else {
  1249. tdsn = dsn
  1250. expected = defaultCollation
  1251. }
  1252. runTests(t, tdsn, func(dbt *DBTest) {
  1253. var got string
  1254. if err := dbt.db.QueryRow("SELECT @@collation_connection").Scan(&got); err != nil {
  1255. dbt.Fatal(err)
  1256. }
  1257. if got != expected {
  1258. dbt.Fatalf("expected connection collation %s but got %s", expected, got)
  1259. }
  1260. })
  1261. }
  1262. }
  1263. func TestColumnsWithAlias(t *testing.T) {
  1264. runTests(t, dsn+"&columnsWithAlias=true", func(dbt *DBTest) {
  1265. rows := dbt.mustQuery("SELECT 1 AS A")
  1266. defer rows.Close()
  1267. cols, _ := rows.Columns()
  1268. if len(cols) != 1 {
  1269. t.Fatalf("expected 1 column, got %d", len(cols))
  1270. }
  1271. if cols[0] != "A" {
  1272. t.Fatalf("expected column name \"A\", got \"%s\"", cols[0])
  1273. }
  1274. rows.Close()
  1275. rows = dbt.mustQuery("SELECT * FROM (SELECT 1 AS one) AS A")
  1276. cols, _ = rows.Columns()
  1277. if len(cols) != 1 {
  1278. t.Fatalf("expected 1 column, got %d", len(cols))
  1279. }
  1280. if cols[0] != "A.one" {
  1281. t.Fatalf("expected column name \"A.one\", got \"%s\"", cols[0])
  1282. }
  1283. })
  1284. }
  1285. func TestRawBytesResultExceedsBuffer(t *testing.T) {
  1286. runTests(t, dsn, func(dbt *DBTest) {
  1287. // defaultBufSize from buffer.go
  1288. expected := strings.Repeat("abc", defaultBufSize)
  1289. rows := dbt.mustQuery("SELECT '" + expected + "'")
  1290. defer rows.Close()
  1291. if !rows.Next() {
  1292. dbt.Error("expected result, got none")
  1293. }
  1294. var result sql.RawBytes
  1295. rows.Scan(&result)
  1296. if expected != string(result) {
  1297. dbt.Error("result did not match expected value")
  1298. }
  1299. })
  1300. }
  1301. func TestTimezoneConversion(t *testing.T) {
  1302. zones := []string{"UTC", "US/Central", "US/Pacific", "Local"}
  1303. // Regression test for timezone handling
  1304. tzTest := func(dbt *DBTest) {
  1305. // Create table
  1306. dbt.mustExec("CREATE TABLE test (ts TIMESTAMP)")
  1307. // Insert local time into database (should be converted)
  1308. usCentral, _ := time.LoadLocation("US/Central")
  1309. reftime := time.Date(2014, 05, 30, 18, 03, 17, 0, time.UTC).In(usCentral)
  1310. dbt.mustExec("INSERT INTO test VALUE (?)", reftime)
  1311. // Retrieve time from DB
  1312. rows := dbt.mustQuery("SELECT ts FROM test")
  1313. if !rows.Next() {
  1314. dbt.Fatal("did not get any rows out")
  1315. }
  1316. var dbTime time.Time
  1317. err := rows.Scan(&dbTime)
  1318. if err != nil {
  1319. dbt.Fatal("Err", err)
  1320. }
  1321. // Check that dates match
  1322. if reftime.Unix() != dbTime.Unix() {
  1323. dbt.Errorf("times do not match.\n")
  1324. dbt.Errorf(" Now(%v)=%v\n", usCentral, reftime)
  1325. dbt.Errorf(" Now(UTC)=%v\n", dbTime)
  1326. }
  1327. }
  1328. for _, tz := range zones {
  1329. runTests(t, dsn+"&parseTime=true&loc="+url.QueryEscape(tz), tzTest)
  1330. }
  1331. }
  1332. // Special cases
  1333. func TestRowsClose(t *testing.T) {
  1334. runTests(t, dsn, func(dbt *DBTest) {
  1335. rows, err := dbt.db.Query("SELECT 1")
  1336. if err != nil {
  1337. dbt.Fatal(err)
  1338. }
  1339. err = rows.Close()
  1340. if err != nil {
  1341. dbt.Fatal(err)
  1342. }
  1343. if rows.Next() {
  1344. dbt.Fatal("unexpected row after rows.Close()")
  1345. }
  1346. err = rows.Err()
  1347. if err != nil {
  1348. dbt.Fatal(err)
  1349. }
  1350. })
  1351. }
  1352. // dangling statements
  1353. // http://code.google.com/p/go/issues/detail?id=3865
  1354. func TestCloseStmtBeforeRows(t *testing.T) {
  1355. runTests(t, dsn, func(dbt *DBTest) {
  1356. stmt, err := dbt.db.Prepare("SELECT 1")
  1357. if err != nil {
  1358. dbt.Fatal(err)
  1359. }
  1360. rows, err := stmt.Query()
  1361. if err != nil {
  1362. stmt.Close()
  1363. dbt.Fatal(err)
  1364. }
  1365. defer rows.Close()
  1366. err = stmt.Close()
  1367. if err != nil {
  1368. dbt.Fatal(err)
  1369. }
  1370. if !rows.Next() {
  1371. dbt.Fatal("getting row failed")
  1372. } else {
  1373. err = rows.Err()
  1374. if err != nil {
  1375. dbt.Fatal(err)
  1376. }
  1377. var out bool
  1378. err = rows.Scan(&out)
  1379. if err != nil {
  1380. dbt.Fatalf("error on rows.Scan(): %s", err.Error())
  1381. }
  1382. if out != true {
  1383. dbt.Errorf("true != %t", out)
  1384. }
  1385. }
  1386. })
  1387. }
  1388. // It is valid to have multiple Rows for the same Stmt
  1389. // http://code.google.com/p/go/issues/detail?id=3734
  1390. func TestStmtMultiRows(t *testing.T) {
  1391. runTests(t, dsn, func(dbt *DBTest) {
  1392. stmt, err := dbt.db.Prepare("SELECT 1 UNION SELECT 0")
  1393. if err != nil {
  1394. dbt.Fatal(err)
  1395. }
  1396. rows1, err := stmt.Query()
  1397. if err != nil {
  1398. stmt.Close()
  1399. dbt.Fatal(err)
  1400. }
  1401. defer rows1.Close()
  1402. rows2, err := stmt.Query()
  1403. if err != nil {
  1404. stmt.Close()
  1405. dbt.Fatal(err)
  1406. }
  1407. defer rows2.Close()
  1408. var out bool
  1409. // 1
  1410. if !rows1.Next() {
  1411. dbt.Fatal("first rows1.Next failed")
  1412. } else {
  1413. err = rows1.Err()
  1414. if err != nil {
  1415. dbt.Fatal(err)
  1416. }
  1417. err = rows1.Scan(&out)
  1418. if err != nil {
  1419. dbt.Fatalf("error on rows.Scan(): %s", err.Error())
  1420. }
  1421. if out != true {
  1422. dbt.Errorf("true != %t", out)
  1423. }
  1424. }
  1425. if !rows2.Next() {
  1426. dbt.Fatal("first rows2.Next failed")
  1427. } else {
  1428. err = rows2.Err()
  1429. if err != nil {
  1430. dbt.Fatal(err)
  1431. }
  1432. err = rows2.Scan(&out)
  1433. if err != nil {
  1434. dbt.Fatalf("error on rows.Scan(): %s", err.Error())
  1435. }
  1436. if out != true {
  1437. dbt.Errorf("true != %t", out)
  1438. }
  1439. }
  1440. // 2
  1441. if !rows1.Next() {
  1442. dbt.Fatal("second rows1.Next failed")
  1443. } else {
  1444. err = rows1.Err()
  1445. if err != nil {
  1446. dbt.Fatal(err)
  1447. }
  1448. err = rows1.Scan(&out)
  1449. if err != nil {
  1450. dbt.Fatalf("error on rows.Scan(): %s", err.Error())
  1451. }
  1452. if out != false {
  1453. dbt.Errorf("false != %t", out)
  1454. }
  1455. if rows1.Next() {
  1456. dbt.Fatal("unexpected row on rows1")
  1457. }
  1458. err = rows1.Close()
  1459. if err != nil {
  1460. dbt.Fatal(err)
  1461. }
  1462. }
  1463. if !rows2.Next() {
  1464. dbt.Fatal("second rows2.Next failed")
  1465. } else {
  1466. err = rows2.Err()
  1467. if err != nil {
  1468. dbt.Fatal(err)
  1469. }
  1470. err = rows2.Scan(&out)
  1471. if err != nil {
  1472. dbt.Fatalf("error on rows.Scan(): %s", err.Error())
  1473. }
  1474. if out != false {
  1475. dbt.Errorf("false != %t", out)
  1476. }
  1477. if rows2.Next() {
  1478. dbt.Fatal("unexpected row on rows2")
  1479. }
  1480. err = rows2.Close()
  1481. if err != nil {
  1482. dbt.Fatal(err)
  1483. }
  1484. }
  1485. })
  1486. }
  1487. // Regression test for
  1488. // * more than 32 NULL parameters (issue 209)
  1489. // * more parameters than fit into the buffer (issue 201)
  1490. func TestPreparedManyCols(t *testing.T) {
  1491. const numParams = defaultBufSize
  1492. runTests(t, dsn, func(dbt *DBTest) {
  1493. query := "SELECT ?" + strings.Repeat(",?", numParams-1)
  1494. stmt, err := dbt.db.Prepare(query)
  1495. if err != nil {
  1496. dbt.Fatal(err)
  1497. }
  1498. defer stmt.Close()
  1499. // create more parameters than fit into the buffer
  1500. // which will take nil-values
  1501. params := make([]interface{}, numParams)
  1502. rows, err := stmt.Query(params...)
  1503. if err != nil {
  1504. stmt.Close()
  1505. dbt.Fatal(err)
  1506. }
  1507. defer rows.Close()
  1508. })
  1509. }
  1510. func TestConcurrent(t *testing.T) {
  1511. if enabled, _ := readBool(os.Getenv("MYSQL_TEST_CONCURRENT")); !enabled {
  1512. t.Skip("MYSQL_TEST_CONCURRENT env var not set")
  1513. }
  1514. runTests(t, dsn, func(dbt *DBTest) {
  1515. var max int
  1516. err := dbt.db.QueryRow("SELECT @@max_connections").Scan(&max)
  1517. if err != nil {
  1518. dbt.Fatalf("%s", err.Error())
  1519. }
  1520. dbt.Logf("testing up to %d concurrent connections \r\n", max)
  1521. var remaining, succeeded int32 = int32(max), 0
  1522. var wg sync.WaitGroup
  1523. wg.Add(max)
  1524. var fatalError string
  1525. var once sync.Once
  1526. fatalf := func(s string, vals ...interface{}) {
  1527. once.Do(func() {
  1528. fatalError = fmt.Sprintf(s, vals...)
  1529. })
  1530. }
  1531. for i := 0; i < max; i++ {
  1532. go func(id int) {
  1533. defer wg.Done()
  1534. tx, err := dbt.db.Begin()
  1535. atomic.AddInt32(&remaining, -1)
  1536. if err != nil {
  1537. if err.Error() != "Error 1040: Too many connections" {
  1538. fatalf("error on conn %d: %s", id, err.Error())
  1539. }
  1540. return
  1541. }
  1542. // keep the connection busy until all connections are open
  1543. for remaining > 0 {
  1544. if _, err = tx.Exec("DO 1"); err != nil {
  1545. fatalf("error on conn %d: %s", id, err.Error())
  1546. return
  1547. }
  1548. }
  1549. if err = tx.Commit(); err != nil {
  1550. fatalf("error on conn %d: %s", id, err.Error())
  1551. return
  1552. }
  1553. // everything went fine with this connection
  1554. atomic.AddInt32(&succeeded, 1)
  1555. }(i)
  1556. }
  1557. // wait until all conections are open
  1558. wg.Wait()
  1559. if fatalError != "" {
  1560. dbt.Fatal(fatalError)
  1561. }
  1562. dbt.Logf("reached %d concurrent connections\r\n", succeeded)
  1563. })
  1564. }
  1565. // Tests custom dial functions
  1566. func TestCustomDial(t *testing.T) {
  1567. if !available {
  1568. t.Skipf("MySQL server not running on %s", netAddr)
  1569. }
  1570. // our custom dial function which justs wraps net.Dial here
  1571. RegisterDial("mydial", func(addr string) (net.Conn, error) {
  1572. return net.Dial(prot, addr)
  1573. })
  1574. db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@mydial(%s)/%s?timeout=30s&strict=true", user, pass, addr, dbname))
  1575. if err != nil {
  1576. t.Fatalf("error connecting: %s", err.Error())
  1577. }
  1578. defer db.Close()
  1579. if _, err = db.Exec("DO 1"); err != nil {
  1580. t.Fatalf("connection failed: %s", err.Error())
  1581. }
  1582. }
  1583. func TestSQLInjection(t *testing.T) {
  1584. createTest := func(arg string) func(dbt *DBTest) {
  1585. return func(dbt *DBTest) {
  1586. dbt.mustExec("CREATE TABLE test (v INTEGER)")
  1587. dbt.mustExec("INSERT INTO test VALUES (?)", 1)
  1588. var v int
  1589. // NULL can't be equal to anything, the idea here is to inject query so it returns row
  1590. // This test verifies that escapeQuotes and escapeBackslash are working properly
  1591. err := dbt.db.QueryRow("SELECT v FROM test WHERE NULL = ?", arg).Scan(&v)
  1592. if err == sql.ErrNoRows {
  1593. return // success, sql injection failed
  1594. } else if err == nil {
  1595. dbt.Errorf("sql injection successful with arg: %s", arg)
  1596. } else {
  1597. dbt.Errorf("error running query with arg: %s; err: %s", arg, err.Error())
  1598. }
  1599. }
  1600. }
  1601. dsns := []string{
  1602. dsn,
  1603. dsn + "&sql_mode='NO_BACKSLASH_ESCAPES,NO_AUTO_CREATE_USER'",
  1604. }
  1605. for _, testdsn := range dsns {
  1606. runTests(t, testdsn, createTest("1 OR 1=1"))
  1607. runTests(t, testdsn, createTest("' OR '1'='1"))
  1608. }
  1609. }
  1610. // Test if inserted data is correctly retrieved after being escaped
  1611. func TestInsertRetrieveEscapedData(t *testing.T) {
  1612. testData := func(dbt *DBTest) {
  1613. dbt.mustExec("CREATE TABLE test (v VARCHAR(255))")
  1614. // All sequences that are escaped by escapeQuotes and escapeBackslash
  1615. v := "foo \x00\n\r\x1a\"'\\"
  1616. dbt.mustExec("INSERT INTO test VALUES (?)", v)
  1617. var out string
  1618. err := dbt.db.QueryRow("SELECT v FROM test").Scan(&out)
  1619. if err != nil {
  1620. dbt.Fatalf("%s", err.Error())
  1621. }
  1622. if out != v {
  1623. dbt.Errorf("%q != %q", out, v)
  1624. }
  1625. }
  1626. dsns := []string{
  1627. dsn,
  1628. dsn + "&sql_mode='NO_BACKSLASH_ESCAPES,NO_AUTO_CREATE_USER'",
  1629. }
  1630. for _, testdsn := range dsns {
  1631. runTests(t, testdsn, testData)
  1632. }
  1633. }
  1634. func TestUnixSocketAuthFail(t *testing.T) {
  1635. runTests(t, dsn, func(dbt *DBTest) {
  1636. // Save the current logger so we can restore it.
  1637. oldLogger := errLog
  1638. // Set a new logger so we can capture its output.
  1639. buffer := bytes.NewBuffer(make([]byte, 0, 64))
  1640. newLogger := log.New(buffer, "prefix: ", 0)
  1641. SetLogger(newLogger)
  1642. // Restore the logger.
  1643. defer SetLogger(oldLogger)
  1644. // Make a new DSN that uses the MySQL socket file and a bad password, which
  1645. // we can make by simply appending any character to the real password.
  1646. badPass := pass + "x"
  1647. socket := ""
  1648. if prot == "unix" {
  1649. socket = addr
  1650. } else {
  1651. // Get socket file from MySQL.
  1652. err := dbt.db.QueryRow("SELECT @@socket").Scan(&socket)
  1653. if err != nil {
  1654. t.Fatalf("error on SELECT @@socket: %s", err.Error())
  1655. }
  1656. }
  1657. t.Logf("socket: %s", socket)
  1658. badDSN := fmt.Sprintf("%s:%s@unix(%s)/%s?timeout=30s&strict=true", user, badPass, socket, dbname)
  1659. db, err := sql.Open("mysql", badDSN)
  1660. if err != nil {
  1661. t.Fatalf("error connecting: %s", err.Error())
  1662. }
  1663. defer db.Close()
  1664. // Connect to MySQL for real. This will cause an auth failure.
  1665. err = db.Ping()
  1666. if err == nil {
  1667. t.Error("expected Ping() to return an error")
  1668. }
  1669. // The driver should not log anything.
  1670. if actual := buffer.String(); actual != "" {
  1671. t.Errorf("expected no output, got %q", actual)
  1672. }
  1673. })
  1674. }
  1675. // See Issue #422
  1676. func TestInterruptBySignal(t *testing.T) {
  1677. runTestsWithMultiStatement(t, dsn, func(dbt *DBTest) {
  1678. dbt.mustExec(`
  1679. DROP PROCEDURE IF EXISTS test_signal;
  1680. CREATE PROCEDURE test_signal(ret INT)
  1681. BEGIN
  1682. SELECT ret;
  1683. SIGNAL SQLSTATE
  1684. '45001'
  1685. SET
  1686. MESSAGE_TEXT = "an error",
  1687. MYSQL_ERRNO = 45001;
  1688. END
  1689. `)
  1690. defer dbt.mustExec("DROP PROCEDURE test_signal")
  1691. var val int
  1692. // text protocol
  1693. rows, err := dbt.db.Query("CALL test_signal(42)")
  1694. if err != nil {
  1695. dbt.Fatalf("error on text query: %s", err.Error())
  1696. }
  1697. for rows.Next() {
  1698. if err := rows.Scan(&val); err != nil {
  1699. dbt.Error(err)
  1700. } else if val != 42 {
  1701. dbt.Errorf("expected val to be 42")
  1702. }
  1703. }
  1704. // binary protocol
  1705. rows, err = dbt.db.Query("CALL test_signal(?)", 42)
  1706. if err != nil {
  1707. dbt.Fatalf("error on binary query: %s", err.Error())
  1708. }
  1709. for rows.Next() {
  1710. if err := rows.Scan(&val); err != nil {
  1711. dbt.Error(err)
  1712. } else if val != 42 {
  1713. dbt.Errorf("expected val to be 42")
  1714. }
  1715. }
  1716. })
  1717. }
  1718. func TestColumnsReusesSlice(t *testing.T) {
  1719. rows := mysqlRows{
  1720. rs: resultSet{
  1721. columns: []mysqlField{
  1722. {
  1723. tableName: "test",
  1724. name: "A",
  1725. },
  1726. {
  1727. tableName: "test",
  1728. name: "B",
  1729. },
  1730. },
  1731. },
  1732. }
  1733. allocs := testing.AllocsPerRun(1, func() {
  1734. cols := rows.Columns()
  1735. if len(cols) != 2 {
  1736. t.Fatalf("expected 2 columns, got %d", len(cols))
  1737. }
  1738. })
  1739. if allocs != 0 {
  1740. t.Fatalf("expected 0 allocations, got %d", int(allocs))
  1741. }
  1742. if rows.rs.columnNames == nil {
  1743. t.Fatalf("expected columnNames to be set, got nil")
  1744. }
  1745. }
  1746. func TestRejectReadOnly(t *testing.T) {
  1747. runTests(t, dsn, func(dbt *DBTest) {
  1748. // Create Table
  1749. dbt.mustExec("CREATE TABLE test (value BOOL)")
  1750. // Set the session to read-only. We didn't set the `rejectReadOnly`
  1751. // option, so any writes after this should fail.
  1752. _, err := dbt.db.Exec("SET SESSION TRANSACTION READ ONLY")
  1753. // Error 1193: Unknown system variable 'TRANSACTION' => skip test,
  1754. // MySQL server version is too old
  1755. maybeSkip(t, err, 1193)
  1756. if _, err := dbt.db.Exec("DROP TABLE test"); err == nil {
  1757. t.Fatalf("writing to DB in read-only session without " +
  1758. "rejectReadOnly did not error")
  1759. }
  1760. // Set the session back to read-write so runTests() can properly clean
  1761. // up the table `test`.
  1762. dbt.mustExec("SET SESSION TRANSACTION READ WRITE")
  1763. })
  1764. // Enable the `rejectReadOnly` option.
  1765. runTests(t, dsn+"&rejectReadOnly=true", func(dbt *DBTest) {
  1766. // Create Table
  1767. dbt.mustExec("CREATE TABLE test (value BOOL)")
  1768. // Set the session to read only. Any writes after this should error on
  1769. // a driver.ErrBadConn, and cause `database/sql` to initiate a new
  1770. // connection.
  1771. dbt.mustExec("SET SESSION TRANSACTION READ ONLY")
  1772. // This would error, but `database/sql` should automatically retry on a
  1773. // new connection which is not read-only, and eventually succeed.
  1774. dbt.mustExec("DROP TABLE test")
  1775. })
  1776. }
  1777. func TestPing(t *testing.T) {
  1778. runTests(t, dsn, func(dbt *DBTest) {
  1779. if err := dbt.db.Ping(); err != nil {
  1780. dbt.fail("Ping", "Ping", err)
  1781. }
  1782. })
  1783. }