sqlite3_test.go 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032
  1. // Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>.
  2. //
  3. // Use of this source code is governed by an MIT-style
  4. // license that can be found in the LICENSE file.
  5. package sqlite3
  6. import (
  7. "bytes"
  8. "database/sql"
  9. "database/sql/driver"
  10. "errors"
  11. "fmt"
  12. "io/ioutil"
  13. "math/rand"
  14. "net/url"
  15. "os"
  16. "reflect"
  17. "regexp"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "testing"
  22. "time"
  23. )
  24. func TempFilename(t *testing.T) string {
  25. f, err := ioutil.TempFile("", "go-sqlite3-test-")
  26. if err != nil {
  27. t.Fatal(err)
  28. }
  29. f.Close()
  30. return f.Name()
  31. }
  32. func doTestOpen(t *testing.T, option string) (string, error) {
  33. var url string
  34. tempFilename := TempFilename(t)
  35. defer os.Remove(tempFilename)
  36. if option != "" {
  37. url = tempFilename + option
  38. } else {
  39. url = tempFilename
  40. }
  41. db, err := sql.Open("sqlite3", url)
  42. if err != nil {
  43. return "Failed to open database:", err
  44. }
  45. defer os.Remove(tempFilename)
  46. defer db.Close()
  47. _, err = db.Exec("drop table foo")
  48. _, err = db.Exec("create table foo (id integer)")
  49. if err != nil {
  50. return "Failed to create table:", err
  51. }
  52. if stat, err := os.Stat(tempFilename); err != nil || stat.IsDir() {
  53. return "Failed to create ./foo.db", nil
  54. }
  55. return "", nil
  56. }
  57. func TestOpen(t *testing.T) {
  58. cases := map[string]bool{
  59. "": true,
  60. "?_txlock=immediate": true,
  61. "?_txlock=deferred": true,
  62. "?_txlock=exclusive": true,
  63. "?_txlock=bogus": false,
  64. }
  65. for option, expectedPass := range cases {
  66. result, err := doTestOpen(t, option)
  67. if result == "" {
  68. if !expectedPass {
  69. errmsg := fmt.Sprintf("_txlock error not caught at dbOpen with option: %s", option)
  70. t.Fatal(errmsg)
  71. }
  72. } else if expectedPass {
  73. if err == nil {
  74. t.Fatal(result)
  75. } else {
  76. t.Fatal(result, err)
  77. }
  78. }
  79. }
  80. }
  81. func TestReadonly(t *testing.T) {
  82. tempFilename := TempFilename(t)
  83. defer os.Remove(tempFilename)
  84. db1, err := sql.Open("sqlite3", "file:"+tempFilename)
  85. if err != nil {
  86. t.Fatal(err)
  87. }
  88. db1.Exec("CREATE TABLE test (x int, y float)")
  89. db2, err := sql.Open("sqlite3", "file:"+tempFilename+"?mode=ro")
  90. if err != nil {
  91. t.Fatal(err)
  92. }
  93. _ = db2
  94. _, err = db2.Exec("INSERT INTO test VALUES (1, 3.14)")
  95. if err == nil {
  96. t.Fatal("didn't expect INSERT into read-only database to work")
  97. }
  98. }
  99. func TestForeignKeys(t *testing.T) {
  100. cases := map[string]bool{
  101. "?_foreign_keys=1": true,
  102. "?_foreign_keys=0": false,
  103. }
  104. for option, want := range cases {
  105. fname := TempFilename(t)
  106. uri := "file:" + fname + option
  107. db, err := sql.Open("sqlite3", uri)
  108. if err != nil {
  109. os.Remove(fname)
  110. t.Errorf("sql.Open(\"sqlite3\", %q): %v", uri, err)
  111. continue
  112. }
  113. var enabled bool
  114. err = db.QueryRow("PRAGMA foreign_keys;").Scan(&enabled)
  115. db.Close()
  116. os.Remove(fname)
  117. if err != nil {
  118. t.Errorf("query foreign_keys for %s: %v", uri, err)
  119. continue
  120. }
  121. if enabled != want {
  122. t.Errorf("\"PRAGMA foreign_keys;\" for %q = %t; want %t", uri, enabled, want)
  123. continue
  124. }
  125. }
  126. }
  127. func TestRecursiveTriggers(t *testing.T) {
  128. cases := map[string]bool{
  129. "?_recursive_triggers=1": true,
  130. "?_recursive_triggers=0": false,
  131. }
  132. for option, want := range cases {
  133. fname := TempFilename(t)
  134. uri := "file:" + fname + option
  135. db, err := sql.Open("sqlite3", uri)
  136. if err != nil {
  137. os.Remove(fname)
  138. t.Errorf("sql.Open(\"sqlite3\", %q): %v", uri, err)
  139. continue
  140. }
  141. var enabled bool
  142. err = db.QueryRow("PRAGMA recursive_triggers;").Scan(&enabled)
  143. db.Close()
  144. os.Remove(fname)
  145. if err != nil {
  146. t.Errorf("query recursive_triggers for %s: %v", uri, err)
  147. continue
  148. }
  149. if enabled != want {
  150. t.Errorf("\"PRAGMA recursive_triggers;\" for %q = %t; want %t", uri, enabled, want)
  151. continue
  152. }
  153. }
  154. }
  155. func TestClose(t *testing.T) {
  156. tempFilename := TempFilename(t)
  157. defer os.Remove(tempFilename)
  158. db, err := sql.Open("sqlite3", tempFilename)
  159. if err != nil {
  160. t.Fatal("Failed to open database:", err)
  161. }
  162. _, err = db.Exec("drop table foo")
  163. _, err = db.Exec("create table foo (id integer)")
  164. if err != nil {
  165. t.Fatal("Failed to create table:", err)
  166. }
  167. stmt, err := db.Prepare("select id from foo where id = ?")
  168. if err != nil {
  169. t.Fatal("Failed to select records:", err)
  170. }
  171. db.Close()
  172. _, err = stmt.Exec(1)
  173. if err == nil {
  174. t.Fatal("Failed to operate closed statement")
  175. }
  176. }
  177. func TestInsert(t *testing.T) {
  178. tempFilename := TempFilename(t)
  179. defer os.Remove(tempFilename)
  180. db, err := sql.Open("sqlite3", tempFilename)
  181. if err != nil {
  182. t.Fatal("Failed to open database:", err)
  183. }
  184. defer db.Close()
  185. _, err = db.Exec("drop table foo")
  186. _, err = db.Exec("create table foo (id integer)")
  187. if err != nil {
  188. t.Fatal("Failed to create table:", err)
  189. }
  190. res, err := db.Exec("insert into foo(id) values(123)")
  191. if err != nil {
  192. t.Fatal("Failed to insert record:", err)
  193. }
  194. affected, _ := res.RowsAffected()
  195. if affected != 1 {
  196. t.Fatalf("Expected %d for affected rows, but %d:", 1, affected)
  197. }
  198. rows, err := db.Query("select id from foo")
  199. if err != nil {
  200. t.Fatal("Failed to select records:", err)
  201. }
  202. defer rows.Close()
  203. rows.Next()
  204. var result int
  205. rows.Scan(&result)
  206. if result != 123 {
  207. t.Errorf("Expected %d for fetched result, but %d:", 123, result)
  208. }
  209. }
  210. func TestUpdate(t *testing.T) {
  211. tempFilename := TempFilename(t)
  212. defer os.Remove(tempFilename)
  213. db, err := sql.Open("sqlite3", tempFilename)
  214. if err != nil {
  215. t.Fatal("Failed to open database:", err)
  216. }
  217. defer db.Close()
  218. _, err = db.Exec("drop table foo")
  219. _, err = db.Exec("create table foo (id integer)")
  220. if err != nil {
  221. t.Fatal("Failed to create table:", err)
  222. }
  223. res, err := db.Exec("insert into foo(id) values(123)")
  224. if err != nil {
  225. t.Fatal("Failed to insert record:", err)
  226. }
  227. expected, err := res.LastInsertId()
  228. if err != nil {
  229. t.Fatal("Failed to get LastInsertId:", err)
  230. }
  231. affected, _ := res.RowsAffected()
  232. if err != nil {
  233. t.Fatal("Failed to get RowsAffected:", err)
  234. }
  235. if affected != 1 {
  236. t.Fatalf("Expected %d for affected rows, but %d:", 1, affected)
  237. }
  238. res, err = db.Exec("update foo set id = 234")
  239. if err != nil {
  240. t.Fatal("Failed to update record:", err)
  241. }
  242. lastID, err := res.LastInsertId()
  243. if err != nil {
  244. t.Fatal("Failed to get LastInsertId:", err)
  245. }
  246. if expected != lastID {
  247. t.Errorf("Expected %q for last Id, but %q:", expected, lastID)
  248. }
  249. affected, _ = res.RowsAffected()
  250. if err != nil {
  251. t.Fatal("Failed to get RowsAffected:", err)
  252. }
  253. if affected != 1 {
  254. t.Fatalf("Expected %d for affected rows, but %d:", 1, affected)
  255. }
  256. rows, err := db.Query("select id from foo")
  257. if err != nil {
  258. t.Fatal("Failed to select records:", err)
  259. }
  260. defer rows.Close()
  261. rows.Next()
  262. var result int
  263. rows.Scan(&result)
  264. if result != 234 {
  265. t.Errorf("Expected %d for fetched result, but %d:", 234, result)
  266. }
  267. }
  268. func TestDelete(t *testing.T) {
  269. tempFilename := TempFilename(t)
  270. defer os.Remove(tempFilename)
  271. db, err := sql.Open("sqlite3", tempFilename)
  272. if err != nil {
  273. t.Fatal("Failed to open database:", err)
  274. }
  275. defer db.Close()
  276. _, err = db.Exec("drop table foo")
  277. _, err = db.Exec("create table foo (id integer)")
  278. if err != nil {
  279. t.Fatal("Failed to create table:", err)
  280. }
  281. res, err := db.Exec("insert into foo(id) values(123)")
  282. if err != nil {
  283. t.Fatal("Failed to insert record:", err)
  284. }
  285. expected, err := res.LastInsertId()
  286. if err != nil {
  287. t.Fatal("Failed to get LastInsertId:", err)
  288. }
  289. affected, err := res.RowsAffected()
  290. if err != nil {
  291. t.Fatal("Failed to get RowsAffected:", err)
  292. }
  293. if affected != 1 {
  294. t.Errorf("Expected %d for cout of affected rows, but %q:", 1, affected)
  295. }
  296. res, err = db.Exec("delete from foo where id = 123")
  297. if err != nil {
  298. t.Fatal("Failed to delete record:", err)
  299. }
  300. lastID, err := res.LastInsertId()
  301. if err != nil {
  302. t.Fatal("Failed to get LastInsertId:", err)
  303. }
  304. if expected != lastID {
  305. t.Errorf("Expected %q for last Id, but %q:", expected, lastID)
  306. }
  307. affected, err = res.RowsAffected()
  308. if err != nil {
  309. t.Fatal("Failed to get RowsAffected:", err)
  310. }
  311. if affected != 1 {
  312. t.Errorf("Expected %d for cout of affected rows, but %q:", 1, affected)
  313. }
  314. rows, err := db.Query("select id from foo")
  315. if err != nil {
  316. t.Fatal("Failed to select records:", err)
  317. }
  318. defer rows.Close()
  319. if rows.Next() {
  320. t.Error("Fetched row but expected not rows")
  321. }
  322. }
  323. func TestBooleanRoundtrip(t *testing.T) {
  324. tempFilename := TempFilename(t)
  325. defer os.Remove(tempFilename)
  326. db, err := sql.Open("sqlite3", tempFilename)
  327. if err != nil {
  328. t.Fatal("Failed to open database:", err)
  329. }
  330. defer db.Close()
  331. _, err = db.Exec("DROP TABLE foo")
  332. _, err = db.Exec("CREATE TABLE foo(id INTEGER, value BOOL)")
  333. if err != nil {
  334. t.Fatal("Failed to create table:", err)
  335. }
  336. _, err = db.Exec("INSERT INTO foo(id, value) VALUES(1, ?)", true)
  337. if err != nil {
  338. t.Fatal("Failed to insert true value:", err)
  339. }
  340. _, err = db.Exec("INSERT INTO foo(id, value) VALUES(2, ?)", false)
  341. if err != nil {
  342. t.Fatal("Failed to insert false value:", err)
  343. }
  344. rows, err := db.Query("SELECT id, value FROM foo")
  345. if err != nil {
  346. t.Fatal("Unable to query foo table:", err)
  347. }
  348. defer rows.Close()
  349. for rows.Next() {
  350. var id int
  351. var value bool
  352. if err := rows.Scan(&id, &value); err != nil {
  353. t.Error("Unable to scan results:", err)
  354. continue
  355. }
  356. if id == 1 && !value {
  357. t.Error("Value for id 1 should be true, not false")
  358. } else if id == 2 && value {
  359. t.Error("Value for id 2 should be false, not true")
  360. }
  361. }
  362. }
  363. func timezone(t time.Time) string { return t.Format("-07:00") }
  364. func TestTimestamp(t *testing.T) {
  365. tempFilename := TempFilename(t)
  366. defer os.Remove(tempFilename)
  367. db, err := sql.Open("sqlite3", tempFilename)
  368. if err != nil {
  369. t.Fatal("Failed to open database:", err)
  370. }
  371. defer db.Close()
  372. _, err = db.Exec("DROP TABLE foo")
  373. _, err = db.Exec("CREATE TABLE foo(id INTEGER, ts timeSTAMP, dt DATETIME)")
  374. if err != nil {
  375. t.Fatal("Failed to create table:", err)
  376. }
  377. timestamp1 := time.Date(2012, time.April, 6, 22, 50, 0, 0, time.UTC)
  378. timestamp2 := time.Date(2006, time.January, 2, 15, 4, 5, 123456789, time.UTC)
  379. timestamp3 := time.Date(2012, time.November, 4, 0, 0, 0, 0, time.UTC)
  380. tzTest := time.FixedZone("TEST", -9*3600-13*60)
  381. tests := []struct {
  382. value interface{}
  383. expected time.Time
  384. }{
  385. {"nonsense", time.Time{}},
  386. {"0000-00-00 00:00:00", time.Time{}},
  387. {time.Time{}.Unix(), time.Time{}},
  388. {timestamp1, timestamp1},
  389. {timestamp2.Unix(), timestamp2.Truncate(time.Second)},
  390. {timestamp2.UnixNano() / int64(time.Millisecond), timestamp2.Truncate(time.Millisecond)},
  391. {timestamp1.In(tzTest), timestamp1.In(tzTest)},
  392. {timestamp1.Format("2006-01-02 15:04:05.000"), timestamp1},
  393. {timestamp1.Format("2006-01-02T15:04:05.000"), timestamp1},
  394. {timestamp1.Format("2006-01-02 15:04:05"), timestamp1},
  395. {timestamp1.Format("2006-01-02T15:04:05"), timestamp1},
  396. {timestamp2, timestamp2},
  397. {"2006-01-02 15:04:05.123456789", timestamp2},
  398. {"2006-01-02T15:04:05.123456789", timestamp2},
  399. {"2006-01-02T05:51:05.123456789-09:13", timestamp2.In(tzTest)},
  400. {"2012-11-04", timestamp3},
  401. {"2012-11-04 00:00", timestamp3},
  402. {"2012-11-04 00:00:00", timestamp3},
  403. {"2012-11-04 00:00:00.000", timestamp3},
  404. {"2012-11-04T00:00", timestamp3},
  405. {"2012-11-04T00:00:00", timestamp3},
  406. {"2012-11-04T00:00:00.000", timestamp3},
  407. {"2006-01-02T15:04:05.123456789Z", timestamp2},
  408. {"2012-11-04Z", timestamp3},
  409. {"2012-11-04 00:00Z", timestamp3},
  410. {"2012-11-04 00:00:00Z", timestamp3},
  411. {"2012-11-04 00:00:00.000Z", timestamp3},
  412. {"2012-11-04T00:00Z", timestamp3},
  413. {"2012-11-04T00:00:00Z", timestamp3},
  414. {"2012-11-04T00:00:00.000Z", timestamp3},
  415. }
  416. for i := range tests {
  417. _, err = db.Exec("INSERT INTO foo(id, ts, dt) VALUES(?, ?, ?)", i, tests[i].value, tests[i].value)
  418. if err != nil {
  419. t.Fatal("Failed to insert timestamp:", err)
  420. }
  421. }
  422. rows, err := db.Query("SELECT id, ts, dt FROM foo ORDER BY id ASC")
  423. if err != nil {
  424. t.Fatal("Unable to query foo table:", err)
  425. }
  426. defer rows.Close()
  427. seen := 0
  428. for rows.Next() {
  429. var id int
  430. var ts, dt time.Time
  431. if err := rows.Scan(&id, &ts, &dt); err != nil {
  432. t.Error("Unable to scan results:", err)
  433. continue
  434. }
  435. if id < 0 || id >= len(tests) {
  436. t.Error("Bad row id: ", id)
  437. continue
  438. }
  439. seen++
  440. if !tests[id].expected.Equal(ts) {
  441. t.Errorf("Timestamp value for id %v (%v) should be %v, not %v", id, tests[id].value, tests[id].expected, dt)
  442. }
  443. if !tests[id].expected.Equal(dt) {
  444. t.Errorf("Datetime value for id %v (%v) should be %v, not %v", id, tests[id].value, tests[id].expected, dt)
  445. }
  446. if timezone(tests[id].expected) != timezone(ts) {
  447. t.Errorf("Timezone for id %v (%v) should be %v, not %v", id, tests[id].value,
  448. timezone(tests[id].expected), timezone(ts))
  449. }
  450. if timezone(tests[id].expected) != timezone(dt) {
  451. t.Errorf("Timezone for id %v (%v) should be %v, not %v", id, tests[id].value,
  452. timezone(tests[id].expected), timezone(dt))
  453. }
  454. }
  455. if seen != len(tests) {
  456. t.Errorf("Expected to see %d rows", len(tests))
  457. }
  458. }
  459. func TestBoolean(t *testing.T) {
  460. tempFilename := TempFilename(t)
  461. defer os.Remove(tempFilename)
  462. db, err := sql.Open("sqlite3", tempFilename)
  463. if err != nil {
  464. t.Fatal("Failed to open database:", err)
  465. }
  466. defer db.Close()
  467. _, err = db.Exec("CREATE TABLE foo(id INTEGER, fbool BOOLEAN)")
  468. if err != nil {
  469. t.Fatal("Failed to create table:", err)
  470. }
  471. bool1 := true
  472. _, err = db.Exec("INSERT INTO foo(id, fbool) VALUES(1, ?)", bool1)
  473. if err != nil {
  474. t.Fatal("Failed to insert boolean:", err)
  475. }
  476. bool2 := false
  477. _, err = db.Exec("INSERT INTO foo(id, fbool) VALUES(2, ?)", bool2)
  478. if err != nil {
  479. t.Fatal("Failed to insert boolean:", err)
  480. }
  481. bool3 := "nonsense"
  482. _, err = db.Exec("INSERT INTO foo(id, fbool) VALUES(3, ?)", bool3)
  483. if err != nil {
  484. t.Fatal("Failed to insert nonsense:", err)
  485. }
  486. rows, err := db.Query("SELECT id, fbool FROM foo where fbool = ?", bool1)
  487. if err != nil {
  488. t.Fatal("Unable to query foo table:", err)
  489. }
  490. counter := 0
  491. var id int
  492. var fbool bool
  493. for rows.Next() {
  494. if err := rows.Scan(&id, &fbool); err != nil {
  495. t.Fatal("Unable to scan results:", err)
  496. }
  497. counter++
  498. }
  499. if counter != 1 {
  500. t.Fatalf("Expected 1 row but %v", counter)
  501. }
  502. if id != 1 && !fbool {
  503. t.Fatalf("Value for id 1 should be %v, not %v", bool1, fbool)
  504. }
  505. rows, err = db.Query("SELECT id, fbool FROM foo where fbool = ?", bool2)
  506. if err != nil {
  507. t.Fatal("Unable to query foo table:", err)
  508. }
  509. counter = 0
  510. for rows.Next() {
  511. if err := rows.Scan(&id, &fbool); err != nil {
  512. t.Fatal("Unable to scan results:", err)
  513. }
  514. counter++
  515. }
  516. if counter != 1 {
  517. t.Fatalf("Expected 1 row but %v", counter)
  518. }
  519. if id != 2 && fbool {
  520. t.Fatalf("Value for id 2 should be %v, not %v", bool2, fbool)
  521. }
  522. // make sure "nonsense" triggered an error
  523. rows, err = db.Query("SELECT id, fbool FROM foo where id=?;", 3)
  524. if err != nil {
  525. t.Fatal("Unable to query foo table:", err)
  526. }
  527. rows.Next()
  528. err = rows.Scan(&id, &fbool)
  529. if err == nil {
  530. t.Error("Expected error from \"nonsense\" bool")
  531. }
  532. }
  533. func TestFloat32(t *testing.T) {
  534. tempFilename := TempFilename(t)
  535. defer os.Remove(tempFilename)
  536. db, err := sql.Open("sqlite3", tempFilename)
  537. if err != nil {
  538. t.Fatal("Failed to open database:", err)
  539. }
  540. defer db.Close()
  541. _, err = db.Exec("CREATE TABLE foo(id INTEGER)")
  542. if err != nil {
  543. t.Fatal("Failed to create table:", err)
  544. }
  545. _, err = db.Exec("INSERT INTO foo(id) VALUES(null)")
  546. if err != nil {
  547. t.Fatal("Failed to insert null:", err)
  548. }
  549. rows, err := db.Query("SELECT id FROM foo")
  550. if err != nil {
  551. t.Fatal("Unable to query foo table:", err)
  552. }
  553. if !rows.Next() {
  554. t.Fatal("Unable to query results:", err)
  555. }
  556. var id interface{}
  557. if err := rows.Scan(&id); err != nil {
  558. t.Fatal("Unable to scan results:", err)
  559. }
  560. if id != nil {
  561. t.Error("Expected nil but not")
  562. }
  563. }
  564. func TestNull(t *testing.T) {
  565. tempFilename := TempFilename(t)
  566. defer os.Remove(tempFilename)
  567. db, err := sql.Open("sqlite3", tempFilename)
  568. if err != nil {
  569. t.Fatal("Failed to open database:", err)
  570. }
  571. defer db.Close()
  572. rows, err := db.Query("SELECT 3.141592")
  573. if err != nil {
  574. t.Fatal("Unable to query foo table:", err)
  575. }
  576. if !rows.Next() {
  577. t.Fatal("Unable to query results:", err)
  578. }
  579. var v interface{}
  580. if err := rows.Scan(&v); err != nil {
  581. t.Fatal("Unable to scan results:", err)
  582. }
  583. f, ok := v.(float64)
  584. if !ok {
  585. t.Error("Expected float but not")
  586. }
  587. if f != 3.141592 {
  588. t.Error("Expected 3.141592 but not")
  589. }
  590. }
  591. func TestTransaction(t *testing.T) {
  592. tempFilename := TempFilename(t)
  593. defer os.Remove(tempFilename)
  594. db, err := sql.Open("sqlite3", tempFilename)
  595. if err != nil {
  596. t.Fatal("Failed to open database:", err)
  597. }
  598. defer db.Close()
  599. _, err = db.Exec("CREATE TABLE foo(id INTEGER)")
  600. if err != nil {
  601. t.Fatal("Failed to create table:", err)
  602. }
  603. tx, err := db.Begin()
  604. if err != nil {
  605. t.Fatal("Failed to begin transaction:", err)
  606. }
  607. _, err = tx.Exec("INSERT INTO foo(id) VALUES(1)")
  608. if err != nil {
  609. t.Fatal("Failed to insert null:", err)
  610. }
  611. rows, err := tx.Query("SELECT id from foo")
  612. if err != nil {
  613. t.Fatal("Unable to query foo table:", err)
  614. }
  615. err = tx.Rollback()
  616. if err != nil {
  617. t.Fatal("Failed to rollback transaction:", err)
  618. }
  619. if rows.Next() {
  620. t.Fatal("Unable to query results:", err)
  621. }
  622. tx, err = db.Begin()
  623. if err != nil {
  624. t.Fatal("Failed to begin transaction:", err)
  625. }
  626. _, err = tx.Exec("INSERT INTO foo(id) VALUES(1)")
  627. if err != nil {
  628. t.Fatal("Failed to insert null:", err)
  629. }
  630. err = tx.Commit()
  631. if err != nil {
  632. t.Fatal("Failed to commit transaction:", err)
  633. }
  634. rows, err = tx.Query("SELECT id from foo")
  635. if err == nil {
  636. t.Fatal("Expected failure to query")
  637. }
  638. }
  639. func TestWAL(t *testing.T) {
  640. tempFilename := TempFilename(t)
  641. defer os.Remove(tempFilename)
  642. db, err := sql.Open("sqlite3", tempFilename)
  643. if err != nil {
  644. t.Fatal("Failed to open database:", err)
  645. }
  646. defer db.Close()
  647. if _, err = db.Exec("PRAGMA journal_mode=WAL;"); err != nil {
  648. t.Fatal("Failed to Exec PRAGMA journal_mode:", err)
  649. }
  650. if _, err = db.Exec("PRAGMA locking_mode=EXCLUSIVE;"); err != nil {
  651. t.Fatal("Failed to Exec PRAGMA locking_mode:", err)
  652. }
  653. if _, err = db.Exec("CREATE TABLE test (id SERIAL, user TEXT NOT NULL, name TEXT NOT NULL);"); err != nil {
  654. t.Fatal("Failed to Exec CREATE TABLE:", err)
  655. }
  656. if _, err = db.Exec("INSERT INTO test (user, name) VALUES ('user','name');"); err != nil {
  657. t.Fatal("Failed to Exec INSERT:", err)
  658. }
  659. trans, err := db.Begin()
  660. if err != nil {
  661. t.Fatal("Failed to Begin:", err)
  662. }
  663. s, err := trans.Prepare("INSERT INTO test (user, name) VALUES (?, ?);")
  664. if err != nil {
  665. t.Fatal("Failed to Prepare:", err)
  666. }
  667. var count int
  668. if err = trans.QueryRow("SELECT count(user) FROM test;").Scan(&count); err != nil {
  669. t.Fatal("Failed to QueryRow:", err)
  670. }
  671. if _, err = s.Exec("bbbb", "aaaa"); err != nil {
  672. t.Fatal("Failed to Exec prepared statement:", err)
  673. }
  674. if err = s.Close(); err != nil {
  675. t.Fatal("Failed to Close prepared statement:", err)
  676. }
  677. if err = trans.Commit(); err != nil {
  678. t.Fatal("Failed to Commit:", err)
  679. }
  680. }
  681. func TestTimezoneConversion(t *testing.T) {
  682. zones := []string{"UTC", "US/Central", "US/Pacific", "Local"}
  683. for _, tz := range zones {
  684. tempFilename := TempFilename(t)
  685. defer os.Remove(tempFilename)
  686. db, err := sql.Open("sqlite3", tempFilename+"?_loc="+url.QueryEscape(tz))
  687. if err != nil {
  688. t.Fatal("Failed to open database:", err)
  689. }
  690. defer db.Close()
  691. _, err = db.Exec("DROP TABLE foo")
  692. _, err = db.Exec("CREATE TABLE foo(id INTEGER, ts TIMESTAMP, dt DATETIME)")
  693. if err != nil {
  694. t.Fatal("Failed to create table:", err)
  695. }
  696. loc, err := time.LoadLocation(tz)
  697. if err != nil {
  698. t.Fatal("Failed to load location:", err)
  699. }
  700. timestamp1 := time.Date(2012, time.April, 6, 22, 50, 0, 0, time.UTC)
  701. timestamp2 := time.Date(2006, time.January, 2, 15, 4, 5, 123456789, time.UTC)
  702. timestamp3 := time.Date(2012, time.November, 4, 0, 0, 0, 0, time.UTC)
  703. tests := []struct {
  704. value interface{}
  705. expected time.Time
  706. }{
  707. {"nonsense", time.Time{}.In(loc)},
  708. {"0000-00-00 00:00:00", time.Time{}.In(loc)},
  709. {timestamp1, timestamp1.In(loc)},
  710. {timestamp1.Unix(), timestamp1.In(loc)},
  711. {timestamp1.In(time.FixedZone("TEST", -7*3600)), timestamp1.In(loc)},
  712. {timestamp1.Format("2006-01-02 15:04:05.000"), timestamp1.In(loc)},
  713. {timestamp1.Format("2006-01-02T15:04:05.000"), timestamp1.In(loc)},
  714. {timestamp1.Format("2006-01-02 15:04:05"), timestamp1.In(loc)},
  715. {timestamp1.Format("2006-01-02T15:04:05"), timestamp1.In(loc)},
  716. {timestamp2, timestamp2.In(loc)},
  717. {"2006-01-02 15:04:05.123456789", timestamp2.In(loc)},
  718. {"2006-01-02T15:04:05.123456789", timestamp2.In(loc)},
  719. {"2012-11-04", timestamp3.In(loc)},
  720. {"2012-11-04 00:00", timestamp3.In(loc)},
  721. {"2012-11-04 00:00:00", timestamp3.In(loc)},
  722. {"2012-11-04 00:00:00.000", timestamp3.In(loc)},
  723. {"2012-11-04T00:00", timestamp3.In(loc)},
  724. {"2012-11-04T00:00:00", timestamp3.In(loc)},
  725. {"2012-11-04T00:00:00.000", timestamp3.In(loc)},
  726. }
  727. for i := range tests {
  728. _, err = db.Exec("INSERT INTO foo(id, ts, dt) VALUES(?, ?, ?)", i, tests[i].value, tests[i].value)
  729. if err != nil {
  730. t.Fatal("Failed to insert timestamp:", err)
  731. }
  732. }
  733. rows, err := db.Query("SELECT id, ts, dt FROM foo ORDER BY id ASC")
  734. if err != nil {
  735. t.Fatal("Unable to query foo table:", err)
  736. }
  737. defer rows.Close()
  738. seen := 0
  739. for rows.Next() {
  740. var id int
  741. var ts, dt time.Time
  742. if err := rows.Scan(&id, &ts, &dt); err != nil {
  743. t.Error("Unable to scan results:", err)
  744. continue
  745. }
  746. if id < 0 || id >= len(tests) {
  747. t.Error("Bad row id: ", id)
  748. continue
  749. }
  750. seen++
  751. if !tests[id].expected.Equal(ts) {
  752. t.Errorf("Timestamp value for id %v (%v) should be %v, not %v", id, tests[id].value, tests[id].expected, ts)
  753. }
  754. if !tests[id].expected.Equal(dt) {
  755. t.Errorf("Datetime value for id %v (%v) should be %v, not %v", id, tests[id].value, tests[id].expected, dt)
  756. }
  757. if tests[id].expected.Location().String() != ts.Location().String() {
  758. t.Errorf("Location for id %v (%v) should be %v, not %v", id, tests[id].value, tests[id].expected.Location().String(), ts.Location().String())
  759. }
  760. if tests[id].expected.Location().String() != dt.Location().String() {
  761. t.Errorf("Location for id %v (%v) should be %v, not %v", id, tests[id].value, tests[id].expected.Location().String(), dt.Location().String())
  762. }
  763. }
  764. if seen != len(tests) {
  765. t.Errorf("Expected to see %d rows", len(tests))
  766. }
  767. }
  768. }
  769. // TODO: Execer & Queryer currently disabled
  770. // https://github.com/mattn/go-sqlite3/issues/82
  771. func TestExecer(t *testing.T) {
  772. tempFilename := TempFilename(t)
  773. defer os.Remove(tempFilename)
  774. db, err := sql.Open("sqlite3", tempFilename)
  775. if err != nil {
  776. t.Fatal("Failed to open database:", err)
  777. }
  778. defer db.Close()
  779. _, err = db.Exec(`
  780. create table foo (id integer); -- one comment
  781. insert into foo(id) values(?);
  782. insert into foo(id) values(?);
  783. insert into foo(id) values(?); -- another comment
  784. `, 1, 2, 3)
  785. if err != nil {
  786. t.Error("Failed to call db.Exec:", err)
  787. }
  788. }
  789. func TestQueryer(t *testing.T) {
  790. tempFilename := TempFilename(t)
  791. defer os.Remove(tempFilename)
  792. db, err := sql.Open("sqlite3", tempFilename)
  793. if err != nil {
  794. t.Fatal("Failed to open database:", err)
  795. }
  796. defer db.Close()
  797. _, err = db.Exec(`
  798. create table foo (id integer);
  799. `)
  800. if err != nil {
  801. t.Error("Failed to call db.Query:", err)
  802. }
  803. rows, err := db.Query(`
  804. insert into foo(id) values(?);
  805. insert into foo(id) values(?);
  806. insert into foo(id) values(?);
  807. select id from foo order by id;
  808. `, 3, 2, 1)
  809. if err != nil {
  810. t.Error("Failed to call db.Query:", err)
  811. }
  812. defer rows.Close()
  813. n := 1
  814. if rows != nil {
  815. for rows.Next() {
  816. var id int
  817. err = rows.Scan(&id)
  818. if err != nil {
  819. t.Error("Failed to db.Query:", err)
  820. }
  821. if id != n {
  822. t.Error("Failed to db.Query: not matched results")
  823. }
  824. }
  825. }
  826. }
  827. func TestStress(t *testing.T) {
  828. tempFilename := TempFilename(t)
  829. defer os.Remove(tempFilename)
  830. db, err := sql.Open("sqlite3", tempFilename)
  831. if err != nil {
  832. t.Fatal("Failed to open database:", err)
  833. }
  834. db.Exec("CREATE TABLE foo (id int);")
  835. db.Exec("INSERT INTO foo VALUES(1);")
  836. db.Exec("INSERT INTO foo VALUES(2);")
  837. db.Close()
  838. for i := 0; i < 10000; i++ {
  839. db, err := sql.Open("sqlite3", tempFilename)
  840. if err != nil {
  841. t.Fatal("Failed to open database:", err)
  842. }
  843. for j := 0; j < 3; j++ {
  844. rows, err := db.Query("select * from foo where id=1;")
  845. if err != nil {
  846. t.Error("Failed to call db.Query:", err)
  847. }
  848. for rows.Next() {
  849. var i int
  850. if err := rows.Scan(&i); err != nil {
  851. t.Errorf("Scan failed: %v\n", err)
  852. }
  853. }
  854. if err := rows.Err(); err != nil {
  855. t.Errorf("Post-scan failed: %v\n", err)
  856. }
  857. rows.Close()
  858. }
  859. db.Close()
  860. }
  861. }
  862. func TestDateTimeLocal(t *testing.T) {
  863. zone := "Asia/Tokyo"
  864. tempFilename := TempFilename(t)
  865. defer os.Remove(tempFilename)
  866. db, err := sql.Open("sqlite3", tempFilename+"?_loc="+zone)
  867. if err != nil {
  868. t.Fatal("Failed to open database:", err)
  869. }
  870. db.Exec("CREATE TABLE foo (dt datetime);")
  871. db.Exec("INSERT INTO foo VALUES('2015-03-05 15:16:17');")
  872. row := db.QueryRow("select * from foo")
  873. var d time.Time
  874. err = row.Scan(&d)
  875. if err != nil {
  876. t.Fatal("Failed to scan datetime:", err)
  877. }
  878. if d.Hour() == 15 || !strings.Contains(d.String(), "JST") {
  879. t.Fatal("Result should have timezone", d)
  880. }
  881. db.Close()
  882. db, err = sql.Open("sqlite3", tempFilename)
  883. if err != nil {
  884. t.Fatal("Failed to open database:", err)
  885. }
  886. row = db.QueryRow("select * from foo")
  887. err = row.Scan(&d)
  888. if err != nil {
  889. t.Fatal("Failed to scan datetime:", err)
  890. }
  891. if d.UTC().Hour() != 15 || !strings.Contains(d.String(), "UTC") {
  892. t.Fatalf("Result should not have timezone %v %v", zone, d.String())
  893. }
  894. _, err = db.Exec("DELETE FROM foo")
  895. if err != nil {
  896. t.Fatal("Failed to delete table:", err)
  897. }
  898. dt, err := time.Parse("2006/1/2 15/4/5 -0700 MST", "2015/3/5 15/16/17 +0900 JST")
  899. if err != nil {
  900. t.Fatal("Failed to parse datetime:", err)
  901. }
  902. db.Exec("INSERT INTO foo VALUES(?);", dt)
  903. db.Close()
  904. db, err = sql.Open("sqlite3", tempFilename+"?_loc="+zone)
  905. if err != nil {
  906. t.Fatal("Failed to open database:", err)
  907. }
  908. row = db.QueryRow("select * from foo")
  909. err = row.Scan(&d)
  910. if err != nil {
  911. t.Fatal("Failed to scan datetime:", err)
  912. }
  913. if d.Hour() != 15 || !strings.Contains(d.String(), "JST") {
  914. t.Fatalf("Result should have timezone %v %v", zone, d.String())
  915. }
  916. }
  917. func TestVersion(t *testing.T) {
  918. s, n, id := Version()
  919. if s == "" || n == 0 || id == "" {
  920. t.Errorf("Version failed %q, %d, %q\n", s, n, id)
  921. }
  922. }
  923. func TestStringContainingZero(t *testing.T) {
  924. tempFilename := TempFilename(t)
  925. defer os.Remove(tempFilename)
  926. db, err := sql.Open("sqlite3", tempFilename)
  927. if err != nil {
  928. t.Fatal("Failed to open database:", err)
  929. }
  930. defer db.Close()
  931. _, err = db.Exec(`
  932. create table foo (id integer, name, extra text);
  933. `)
  934. if err != nil {
  935. t.Error("Failed to call db.Query:", err)
  936. }
  937. const text = "foo\x00bar"
  938. _, err = db.Exec(`insert into foo(id, name, extra) values($1, $2, $2)`, 1, text)
  939. if err != nil {
  940. t.Error("Failed to call db.Exec:", err)
  941. }
  942. row := db.QueryRow(`select id, extra from foo where id = $1 and extra = $2`, 1, text)
  943. if row == nil {
  944. t.Error("Failed to call db.QueryRow")
  945. }
  946. var id int
  947. var extra string
  948. err = row.Scan(&id, &extra)
  949. if err != nil {
  950. t.Error("Failed to db.Scan:", err)
  951. }
  952. if id != 1 || extra != text {
  953. t.Error("Failed to db.QueryRow: not matched results")
  954. }
  955. }
  956. const CurrentTimeStamp = "2006-01-02 15:04:05"
  957. type TimeStamp struct{ *time.Time }
  958. func (t TimeStamp) Scan(value interface{}) error {
  959. var err error
  960. switch v := value.(type) {
  961. case string:
  962. *t.Time, err = time.Parse(CurrentTimeStamp, v)
  963. case []byte:
  964. *t.Time, err = time.Parse(CurrentTimeStamp, string(v))
  965. default:
  966. err = errors.New("invalid type for current_timestamp")
  967. }
  968. return err
  969. }
  970. func (t TimeStamp) Value() (driver.Value, error) {
  971. return t.Time.Format(CurrentTimeStamp), nil
  972. }
  973. func TestDateTimeNow(t *testing.T) {
  974. tempFilename := TempFilename(t)
  975. defer os.Remove(tempFilename)
  976. db, err := sql.Open("sqlite3", tempFilename)
  977. if err != nil {
  978. t.Fatal("Failed to open database:", err)
  979. }
  980. defer db.Close()
  981. var d time.Time
  982. err = db.QueryRow("SELECT datetime('now')").Scan(TimeStamp{&d})
  983. if err != nil {
  984. t.Fatal("Failed to scan datetime:", err)
  985. }
  986. }
  987. func TestFunctionRegistration(t *testing.T) {
  988. addi8_16_32 := func(a int8, b int16) int32 { return int32(a) + int32(b) }
  989. addi64 := func(a, b int64) int64 { return a + b }
  990. addu8_16_32 := func(a uint8, b uint16) uint32 { return uint32(a) + uint32(b) }
  991. addu64 := func(a, b uint64) uint64 { return a + b }
  992. addiu := func(a int, b uint) int64 { return int64(a) + int64(b) }
  993. addf32_64 := func(a float32, b float64) float64 { return float64(a) + b }
  994. not := func(a bool) bool { return !a }
  995. regex := func(re, s string) (bool, error) {
  996. return regexp.MatchString(re, s)
  997. }
  998. generic := func(a interface{}) int64 {
  999. switch a.(type) {
  1000. case int64:
  1001. return 1
  1002. case float64:
  1003. return 2
  1004. case []byte:
  1005. return 3
  1006. case string:
  1007. return 4
  1008. default:
  1009. panic("unreachable")
  1010. }
  1011. }
  1012. variadic := func(a, b int64, c ...int64) int64 {
  1013. ret := a + b
  1014. for _, d := range c {
  1015. ret += d
  1016. }
  1017. return ret
  1018. }
  1019. variadicGeneric := func(a ...interface{}) int64 {
  1020. return int64(len(a))
  1021. }
  1022. sql.Register("sqlite3_FunctionRegistration", &SQLiteDriver{
  1023. ConnectHook: func(conn *SQLiteConn) error {
  1024. if err := conn.RegisterFunc("addi8_16_32", addi8_16_32, true); err != nil {
  1025. return err
  1026. }
  1027. if err := conn.RegisterFunc("addi64", addi64, true); err != nil {
  1028. return err
  1029. }
  1030. if err := conn.RegisterFunc("addu8_16_32", addu8_16_32, true); err != nil {
  1031. return err
  1032. }
  1033. if err := conn.RegisterFunc("addu64", addu64, true); err != nil {
  1034. return err
  1035. }
  1036. if err := conn.RegisterFunc("addiu", addiu, true); err != nil {
  1037. return err
  1038. }
  1039. if err := conn.RegisterFunc("addf32_64", addf32_64, true); err != nil {
  1040. return err
  1041. }
  1042. if err := conn.RegisterFunc("not", not, true); err != nil {
  1043. return err
  1044. }
  1045. if err := conn.RegisterFunc("regex", regex, true); err != nil {
  1046. return err
  1047. }
  1048. if err := conn.RegisterFunc("generic", generic, true); err != nil {
  1049. return err
  1050. }
  1051. if err := conn.RegisterFunc("variadic", variadic, true); err != nil {
  1052. return err
  1053. }
  1054. if err := conn.RegisterFunc("variadicGeneric", variadicGeneric, true); err != nil {
  1055. return err
  1056. }
  1057. return nil
  1058. },
  1059. })
  1060. db, err := sql.Open("sqlite3_FunctionRegistration", ":memory:")
  1061. if err != nil {
  1062. t.Fatal("Failed to open database:", err)
  1063. }
  1064. defer db.Close()
  1065. ops := []struct {
  1066. query string
  1067. expected interface{}
  1068. }{
  1069. {"SELECT addi8_16_32(1,2)", int32(3)},
  1070. {"SELECT addi64(1,2)", int64(3)},
  1071. {"SELECT addu8_16_32(1,2)", uint32(3)},
  1072. {"SELECT addu64(1,2)", uint64(3)},
  1073. {"SELECT addiu(1,2)", int64(3)},
  1074. {"SELECT addf32_64(1.5,1.5)", float64(3)},
  1075. {"SELECT not(1)", false},
  1076. {"SELECT not(0)", true},
  1077. {`SELECT regex("^foo.*", "foobar")`, true},
  1078. {`SELECT regex("^foo.*", "barfoobar")`, false},
  1079. {"SELECT generic(1)", int64(1)},
  1080. {"SELECT generic(1.1)", int64(2)},
  1081. {`SELECT generic(NULL)`, int64(3)},
  1082. {`SELECT generic("foo")`, int64(4)},
  1083. {"SELECT variadic(1,2)", int64(3)},
  1084. {"SELECT variadic(1,2,3,4)", int64(10)},
  1085. {"SELECT variadic(1,1,1,1,1,1,1,1,1,1)", int64(10)},
  1086. {`SELECT variadicGeneric(1,"foo",2.3, NULL)`, int64(4)},
  1087. }
  1088. for _, op := range ops {
  1089. ret := reflect.New(reflect.TypeOf(op.expected))
  1090. err = db.QueryRow(op.query).Scan(ret.Interface())
  1091. if err != nil {
  1092. t.Errorf("Query %q failed: %s", op.query, err)
  1093. } else if !reflect.DeepEqual(ret.Elem().Interface(), op.expected) {
  1094. t.Errorf("Query %q returned wrong value: got %v (%T), want %v (%T)", op.query, ret.Elem().Interface(), ret.Elem().Interface(), op.expected, op.expected)
  1095. }
  1096. }
  1097. }
  1098. type sumAggregator int64
  1099. func (s *sumAggregator) Step(x int64) {
  1100. *s += sumAggregator(x)
  1101. }
  1102. func (s *sumAggregator) Done() int64 {
  1103. return int64(*s)
  1104. }
  1105. func TestAggregatorRegistration(t *testing.T) {
  1106. customSum := func() *sumAggregator {
  1107. var ret sumAggregator
  1108. return &ret
  1109. }
  1110. sql.Register("sqlite3_AggregatorRegistration", &SQLiteDriver{
  1111. ConnectHook: func(conn *SQLiteConn) error {
  1112. if err := conn.RegisterAggregator("customSum", customSum, true); err != nil {
  1113. return err
  1114. }
  1115. return nil
  1116. },
  1117. })
  1118. db, err := sql.Open("sqlite3_AggregatorRegistration", ":memory:")
  1119. if err != nil {
  1120. t.Fatal("Failed to open database:", err)
  1121. }
  1122. defer db.Close()
  1123. _, err = db.Exec("create table foo (department integer, profits integer)")
  1124. if err != nil {
  1125. // trace feature is not implemented
  1126. t.Skip("Failed to create table:", err)
  1127. }
  1128. _, err = db.Exec("insert into foo values (1, 10), (1, 20), (2, 42)")
  1129. if err != nil {
  1130. t.Fatal("Failed to insert records:", err)
  1131. }
  1132. tests := []struct {
  1133. dept, sum int64
  1134. }{
  1135. {1, 30},
  1136. {2, 42},
  1137. }
  1138. for _, test := range tests {
  1139. var ret int64
  1140. err = db.QueryRow("select customSum(profits) from foo where department = $1 group by department", test.dept).Scan(&ret)
  1141. if err != nil {
  1142. t.Fatal("Query failed:", err)
  1143. }
  1144. if ret != test.sum {
  1145. t.Fatalf("Custom sum returned wrong value, got %d, want %d", ret, test.sum)
  1146. }
  1147. }
  1148. }
  1149. func rot13(r rune) rune {
  1150. switch {
  1151. case r >= 'A' && r <= 'Z':
  1152. return 'A' + (r-'A'+13)%26
  1153. case r >= 'a' && r <= 'z':
  1154. return 'a' + (r-'a'+13)%26
  1155. }
  1156. return r
  1157. }
  1158. func TestCollationRegistration(t *testing.T) {
  1159. collateRot13 := func(a, b string) int {
  1160. ra, rb := strings.Map(rot13, a), strings.Map(rot13, b)
  1161. return strings.Compare(ra, rb)
  1162. }
  1163. collateRot13Reverse := func(a, b string) int {
  1164. return collateRot13(b, a)
  1165. }
  1166. sql.Register("sqlite3_CollationRegistration", &SQLiteDriver{
  1167. ConnectHook: func(conn *SQLiteConn) error {
  1168. if err := conn.RegisterCollation("rot13", collateRot13); err != nil {
  1169. return err
  1170. }
  1171. if err := conn.RegisterCollation("rot13reverse", collateRot13Reverse); err != nil {
  1172. return err
  1173. }
  1174. return nil
  1175. },
  1176. })
  1177. db, err := sql.Open("sqlite3_CollationRegistration", ":memory:")
  1178. if err != nil {
  1179. t.Fatal("Failed to open database:", err)
  1180. }
  1181. defer db.Close()
  1182. populate := []string{
  1183. `CREATE TABLE test (s TEXT)`,
  1184. `INSERT INTO test VALUES ("aaaa")`,
  1185. `INSERT INTO test VALUES ("ffff")`,
  1186. `INSERT INTO test VALUES ("qqqq")`,
  1187. `INSERT INTO test VALUES ("tttt")`,
  1188. `INSERT INTO test VALUES ("zzzz")`,
  1189. }
  1190. for _, stmt := range populate {
  1191. if _, err := db.Exec(stmt); err != nil {
  1192. t.Fatal("Failed to populate test DB:", err)
  1193. }
  1194. }
  1195. ops := []struct {
  1196. query string
  1197. want []string
  1198. }{
  1199. {
  1200. "SELECT * FROM test ORDER BY s COLLATE rot13 ASC",
  1201. []string{
  1202. "qqqq",
  1203. "tttt",
  1204. "zzzz",
  1205. "aaaa",
  1206. "ffff",
  1207. },
  1208. },
  1209. {
  1210. "SELECT * FROM test ORDER BY s COLLATE rot13 DESC",
  1211. []string{
  1212. "ffff",
  1213. "aaaa",
  1214. "zzzz",
  1215. "tttt",
  1216. "qqqq",
  1217. },
  1218. },
  1219. {
  1220. "SELECT * FROM test ORDER BY s COLLATE rot13reverse ASC",
  1221. []string{
  1222. "ffff",
  1223. "aaaa",
  1224. "zzzz",
  1225. "tttt",
  1226. "qqqq",
  1227. },
  1228. },
  1229. {
  1230. "SELECT * FROM test ORDER BY s COLLATE rot13reverse DESC",
  1231. []string{
  1232. "qqqq",
  1233. "tttt",
  1234. "zzzz",
  1235. "aaaa",
  1236. "ffff",
  1237. },
  1238. },
  1239. }
  1240. for _, op := range ops {
  1241. rows, err := db.Query(op.query)
  1242. if err != nil {
  1243. t.Fatalf("Query %q failed: %s", op.query, err)
  1244. }
  1245. got := []string{}
  1246. defer rows.Close()
  1247. for rows.Next() {
  1248. var s string
  1249. if err = rows.Scan(&s); err != nil {
  1250. t.Fatalf("Reading row for %q: %s", op.query, err)
  1251. }
  1252. got = append(got, s)
  1253. }
  1254. if err = rows.Err(); err != nil {
  1255. t.Fatalf("Reading rows for %q: %s", op.query, err)
  1256. }
  1257. if !reflect.DeepEqual(got, op.want) {
  1258. t.Fatalf("Unexpected output from %q\ngot:\n%s\n\nwant:\n%s", op.query, strings.Join(got, "\n"), strings.Join(op.want, "\n"))
  1259. }
  1260. }
  1261. }
  1262. func TestDeclTypes(t *testing.T) {
  1263. d := SQLiteDriver{}
  1264. conn, err := d.Open(":memory:")
  1265. if err != nil {
  1266. t.Fatal("Failed to begin transaction:", err)
  1267. }
  1268. defer conn.Close()
  1269. sqlite3conn := conn.(*SQLiteConn)
  1270. _, err = sqlite3conn.Exec("create table foo (id integer not null primary key, name text)", nil)
  1271. if err != nil {
  1272. t.Fatal("Failed to create table:", err)
  1273. }
  1274. _, err = sqlite3conn.Exec("insert into foo(name) values(\"bar\")", nil)
  1275. if err != nil {
  1276. t.Fatal("Failed to insert:", err)
  1277. }
  1278. rs, err := sqlite3conn.Query("select * from foo", nil)
  1279. if err != nil {
  1280. t.Fatal("Failed to select:", err)
  1281. }
  1282. defer rs.Close()
  1283. declTypes := rs.(*SQLiteRows).DeclTypes()
  1284. if !reflect.DeepEqual(declTypes, []string{"integer", "text"}) {
  1285. t.Fatal("Unexpected declTypes:", declTypes)
  1286. }
  1287. }
  1288. func TestPinger(t *testing.T) {
  1289. db, err := sql.Open("sqlite3", ":memory:")
  1290. if err != nil {
  1291. t.Fatal(err)
  1292. }
  1293. err = db.Ping()
  1294. if err != nil {
  1295. t.Fatal(err)
  1296. }
  1297. db.Close()
  1298. err = db.Ping()
  1299. if err == nil {
  1300. t.Fatal("Should be closed")
  1301. }
  1302. }
  1303. func TestUpdateAndTransactionHooks(t *testing.T) {
  1304. var events []string
  1305. var commitHookReturn = 0
  1306. sql.Register("sqlite3_UpdateHook", &SQLiteDriver{
  1307. ConnectHook: func(conn *SQLiteConn) error {
  1308. conn.RegisterCommitHook(func() int {
  1309. events = append(events, "commit")
  1310. return commitHookReturn
  1311. })
  1312. conn.RegisterRollbackHook(func() {
  1313. events = append(events, "rollback")
  1314. })
  1315. conn.RegisterUpdateHook(func(op int, db string, table string, rowid int64) {
  1316. events = append(events, fmt.Sprintf("update(op=%v db=%v table=%v rowid=%v)", op, db, table, rowid))
  1317. })
  1318. return nil
  1319. },
  1320. })
  1321. db, err := sql.Open("sqlite3_UpdateHook", ":memory:")
  1322. if err != nil {
  1323. t.Fatal("Failed to open database:", err)
  1324. }
  1325. defer db.Close()
  1326. statements := []string{
  1327. "create table foo (id integer primary key)",
  1328. "insert into foo values (9)",
  1329. "update foo set id = 99 where id = 9",
  1330. "delete from foo where id = 99",
  1331. }
  1332. for _, statement := range statements {
  1333. _, err = db.Exec(statement)
  1334. if err != nil {
  1335. t.Fatalf("Unable to prepare test data [%v]: %v", statement, err)
  1336. }
  1337. }
  1338. commitHookReturn = 1
  1339. _, err = db.Exec("insert into foo values (5)")
  1340. if err == nil {
  1341. t.Error("Commit hook failed to rollback transaction")
  1342. }
  1343. var expected = []string{
  1344. "commit",
  1345. fmt.Sprintf("update(op=%v db=main table=foo rowid=9)", SQLITE_INSERT),
  1346. "commit",
  1347. fmt.Sprintf("update(op=%v db=main table=foo rowid=99)", SQLITE_UPDATE),
  1348. "commit",
  1349. fmt.Sprintf("update(op=%v db=main table=foo rowid=99)", SQLITE_DELETE),
  1350. "commit",
  1351. fmt.Sprintf("update(op=%v db=main table=foo rowid=5)", SQLITE_INSERT),
  1352. "commit",
  1353. "rollback",
  1354. }
  1355. if !reflect.DeepEqual(events, expected) {
  1356. t.Errorf("Expected notifications %v but got %v", expected, events)
  1357. }
  1358. }
  1359. func TestNilAndEmptyBytes(t *testing.T) {
  1360. db, err := sql.Open("sqlite3", ":memory:")
  1361. if err != nil {
  1362. t.Fatal(err)
  1363. }
  1364. defer db.Close()
  1365. actualNil := []byte("use this to use an actual nil not a reference to nil")
  1366. emptyBytes := []byte{}
  1367. for tsti, tst := range []struct {
  1368. name string
  1369. columnType string
  1370. insertBytes []byte
  1371. expectedBytes []byte
  1372. }{
  1373. {"actual nil blob", "blob", actualNil, nil},
  1374. {"referenced nil blob", "blob", nil, nil},
  1375. {"empty blob", "blob", emptyBytes, emptyBytes},
  1376. {"actual nil text", "text", actualNil, nil},
  1377. {"referenced nil text", "text", nil, nil},
  1378. {"empty text", "text", emptyBytes, emptyBytes},
  1379. } {
  1380. if _, err = db.Exec(fmt.Sprintf("create table tbl%d (txt %s)", tsti, tst.columnType)); err != nil {
  1381. t.Fatal(tst.name, err)
  1382. }
  1383. if bytes.Equal(tst.insertBytes, actualNil) {
  1384. if _, err = db.Exec(fmt.Sprintf("insert into tbl%d (txt) values (?)", tsti), nil); err != nil {
  1385. t.Fatal(tst.name, err)
  1386. }
  1387. } else {
  1388. if _, err = db.Exec(fmt.Sprintf("insert into tbl%d (txt) values (?)", tsti), &tst.insertBytes); err != nil {
  1389. t.Fatal(tst.name, err)
  1390. }
  1391. }
  1392. rows, err := db.Query(fmt.Sprintf("select txt from tbl%d", tsti))
  1393. if err != nil {
  1394. t.Fatal(tst.name, err)
  1395. }
  1396. if !rows.Next() {
  1397. t.Fatal(tst.name, "no rows")
  1398. }
  1399. var scanBytes []byte
  1400. if err = rows.Scan(&scanBytes); err != nil {
  1401. t.Fatal(tst.name, err)
  1402. }
  1403. if err = rows.Err(); err != nil {
  1404. t.Fatal(tst.name, err)
  1405. }
  1406. if tst.expectedBytes == nil && scanBytes != nil {
  1407. t.Errorf("%s: %#v != %#v", tst.name, scanBytes, tst.expectedBytes)
  1408. } else if !bytes.Equal(scanBytes, tst.expectedBytes) {
  1409. t.Errorf("%s: %#v != %#v", tst.name, scanBytes, tst.expectedBytes)
  1410. }
  1411. }
  1412. }
  1413. var customFunctionOnce sync.Once
  1414. func BenchmarkCustomFunctions(b *testing.B) {
  1415. customFunctionOnce.Do(func() {
  1416. customAdd := func(a, b int64) int64 {
  1417. return a + b
  1418. }
  1419. sql.Register("sqlite3_BenchmarkCustomFunctions", &SQLiteDriver{
  1420. ConnectHook: func(conn *SQLiteConn) error {
  1421. // Impure function to force sqlite to reexecute it each time.
  1422. return conn.RegisterFunc("custom_add", customAdd, false)
  1423. },
  1424. })
  1425. })
  1426. db, err := sql.Open("sqlite3_BenchmarkCustomFunctions", ":memory:")
  1427. if err != nil {
  1428. b.Fatal("Failed to open database:", err)
  1429. }
  1430. defer db.Close()
  1431. b.ResetTimer()
  1432. for i := 0; i < b.N; i++ {
  1433. var i int64
  1434. err = db.QueryRow("SELECT custom_add(1,2)").Scan(&i)
  1435. if err != nil {
  1436. b.Fatal("Failed to run custom add:", err)
  1437. }
  1438. }
  1439. }
  1440. func TestSuite(t *testing.T) {
  1441. tempFilename := TempFilename(t)
  1442. defer os.Remove(tempFilename)
  1443. d, err := sql.Open("sqlite3", tempFilename+"?_busy_timeout=99999")
  1444. if err != nil {
  1445. t.Fatal(err)
  1446. }
  1447. defer d.Close()
  1448. db = &TestDB{t, d, SQLITE, sync.Once{}}
  1449. testing.RunTests(func(string, string) (bool, error) { return true, nil }, tests)
  1450. if !testing.Short() {
  1451. for _, b := range benchmarks {
  1452. fmt.Printf("%-20s", b.Name)
  1453. r := testing.Benchmark(b.F)
  1454. fmt.Printf("%10d %10.0f req/s\n", r.N, float64(r.N)/r.T.Seconds())
  1455. }
  1456. }
  1457. db.tearDown()
  1458. }
  1459. // Dialect is a type of dialect of databases.
  1460. type Dialect int
  1461. // Dialects for databases.
  1462. const (
  1463. SQLITE Dialect = iota // SQLITE mean SQLite3 dialect
  1464. POSTGRESQL // POSTGRESQL mean PostgreSQL dialect
  1465. MYSQL // MYSQL mean MySQL dialect
  1466. )
  1467. // DB provide context for the tests
  1468. type TestDB struct {
  1469. *testing.T
  1470. *sql.DB
  1471. dialect Dialect
  1472. once sync.Once
  1473. }
  1474. var db *TestDB
  1475. // the following tables will be created and dropped during the test
  1476. var testTables = []string{"foo", "bar", "t", "bench"}
  1477. var tests = []testing.InternalTest{
  1478. {Name: "TestResult", F: testResult},
  1479. {Name: "TestBlobs", F: testBlobs},
  1480. {Name: "TestManyQueryRow", F: testManyQueryRow},
  1481. {Name: "TestTxQuery", F: testTxQuery},
  1482. {Name: "TestPreparedStmt", F: testPreparedStmt},
  1483. }
  1484. var benchmarks = []testing.InternalBenchmark{
  1485. {Name: "BenchmarkExec", F: benchmarkExec},
  1486. {Name: "BenchmarkQuery", F: benchmarkQuery},
  1487. {Name: "BenchmarkParams", F: benchmarkParams},
  1488. {Name: "BenchmarkStmt", F: benchmarkStmt},
  1489. {Name: "BenchmarkRows", F: benchmarkRows},
  1490. {Name: "BenchmarkStmtRows", F: benchmarkStmtRows},
  1491. }
  1492. func (db *TestDB) mustExec(sql string, args ...interface{}) sql.Result {
  1493. res, err := db.Exec(sql, args...)
  1494. if err != nil {
  1495. db.Fatalf("Error running %q: %v", sql, err)
  1496. }
  1497. return res
  1498. }
  1499. func (db *TestDB) tearDown() {
  1500. for _, tbl := range testTables {
  1501. switch db.dialect {
  1502. case SQLITE:
  1503. db.mustExec("drop table if exists " + tbl)
  1504. case MYSQL, POSTGRESQL:
  1505. db.mustExec("drop table if exists " + tbl)
  1506. default:
  1507. db.Fatal("unknown dialect")
  1508. }
  1509. }
  1510. }
  1511. // q replaces ? parameters if needed
  1512. func (db *TestDB) q(sql string) string {
  1513. switch db.dialect {
  1514. case POSTGRESQL: // replace with $1, $2, ..
  1515. qrx := regexp.MustCompile(`\?`)
  1516. n := 0
  1517. return qrx.ReplaceAllStringFunc(sql, func(string) string {
  1518. n++
  1519. return "$" + strconv.Itoa(n)
  1520. })
  1521. }
  1522. return sql
  1523. }
  1524. func (db *TestDB) blobType(size int) string {
  1525. switch db.dialect {
  1526. case SQLITE:
  1527. return fmt.Sprintf("blob[%d]", size)
  1528. case POSTGRESQL:
  1529. return "bytea"
  1530. case MYSQL:
  1531. return fmt.Sprintf("VARBINARY(%d)", size)
  1532. }
  1533. panic("unknown dialect")
  1534. }
  1535. func (db *TestDB) serialPK() string {
  1536. switch db.dialect {
  1537. case SQLITE:
  1538. return "integer primary key autoincrement"
  1539. case POSTGRESQL:
  1540. return "serial primary key"
  1541. case MYSQL:
  1542. return "integer primary key auto_increment"
  1543. }
  1544. panic("unknown dialect")
  1545. }
  1546. func (db *TestDB) now() string {
  1547. switch db.dialect {
  1548. case SQLITE:
  1549. return "datetime('now')"
  1550. case POSTGRESQL:
  1551. return "now()"
  1552. case MYSQL:
  1553. return "now()"
  1554. }
  1555. panic("unknown dialect")
  1556. }
  1557. func makeBench() {
  1558. if _, err := db.Exec("create table bench (n varchar(32), i integer, d double, s varchar(32), t datetime)"); err != nil {
  1559. panic(err)
  1560. }
  1561. st, err := db.Prepare("insert into bench values (?, ?, ?, ?, ?)")
  1562. if err != nil {
  1563. panic(err)
  1564. }
  1565. defer st.Close()
  1566. for i := 0; i < 100; i++ {
  1567. if _, err = st.Exec(nil, i, float64(i), fmt.Sprintf("%d", i), time.Now()); err != nil {
  1568. panic(err)
  1569. }
  1570. }
  1571. }
  1572. // testResult is test for result
  1573. func testResult(t *testing.T) {
  1574. db.tearDown()
  1575. db.mustExec("create temporary table test (id " + db.serialPK() + ", name varchar(10))")
  1576. for i := 1; i < 3; i++ {
  1577. r := db.mustExec(db.q("insert into test (name) values (?)"), fmt.Sprintf("row %d", i))
  1578. n, err := r.RowsAffected()
  1579. if err != nil {
  1580. t.Fatal(err)
  1581. }
  1582. if n != 1 {
  1583. t.Errorf("got %v, want %v", n, 1)
  1584. }
  1585. n, err = r.LastInsertId()
  1586. if err != nil {
  1587. t.Fatal(err)
  1588. }
  1589. if n != int64(i) {
  1590. t.Errorf("got %v, want %v", n, i)
  1591. }
  1592. }
  1593. if _, err := db.Exec("error!"); err == nil {
  1594. t.Fatalf("expected error")
  1595. }
  1596. }
  1597. // testBlobs is test for blobs
  1598. func testBlobs(t *testing.T) {
  1599. db.tearDown()
  1600. var blob = []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
  1601. db.mustExec("create table foo (id integer primary key, bar " + db.blobType(16) + ")")
  1602. db.mustExec(db.q("insert into foo (id, bar) values(?,?)"), 0, blob)
  1603. want := fmt.Sprintf("%x", blob)
  1604. b := make([]byte, 16)
  1605. err := db.QueryRow(db.q("select bar from foo where id = ?"), 0).Scan(&b)
  1606. got := fmt.Sprintf("%x", b)
  1607. if err != nil {
  1608. t.Errorf("[]byte scan: %v", err)
  1609. } else if got != want {
  1610. t.Errorf("for []byte, got %q; want %q", got, want)
  1611. }
  1612. err = db.QueryRow(db.q("select bar from foo where id = ?"), 0).Scan(&got)
  1613. want = string(blob)
  1614. if err != nil {
  1615. t.Errorf("string scan: %v", err)
  1616. } else if got != want {
  1617. t.Errorf("for string, got %q; want %q", got, want)
  1618. }
  1619. }
  1620. // testManyQueryRow is test for many query row
  1621. func testManyQueryRow(t *testing.T) {
  1622. if testing.Short() {
  1623. t.Log("skipping in short mode")
  1624. return
  1625. }
  1626. db.tearDown()
  1627. db.mustExec("create table foo (id integer primary key, name varchar(50))")
  1628. db.mustExec(db.q("insert into foo (id, name) values(?,?)"), 1, "bob")
  1629. var name string
  1630. for i := 0; i < 10000; i++ {
  1631. err := db.QueryRow(db.q("select name from foo where id = ?"), 1).Scan(&name)
  1632. if err != nil || name != "bob" {
  1633. t.Fatalf("on query %d: err=%v, name=%q", i, err, name)
  1634. }
  1635. }
  1636. }
  1637. // testTxQuery is test for transactional query
  1638. func testTxQuery(t *testing.T) {
  1639. db.tearDown()
  1640. tx, err := db.Begin()
  1641. if err != nil {
  1642. t.Fatal(err)
  1643. }
  1644. defer tx.Rollback()
  1645. _, err = tx.Exec("create table foo (id integer primary key, name varchar(50))")
  1646. if err != nil {
  1647. t.Fatal(err)
  1648. }
  1649. _, err = tx.Exec(db.q("insert into foo (id, name) values(?,?)"), 1, "bob")
  1650. if err != nil {
  1651. t.Fatal(err)
  1652. }
  1653. r, err := tx.Query(db.q("select name from foo where id = ?"), 1)
  1654. if err != nil {
  1655. t.Fatal(err)
  1656. }
  1657. defer r.Close()
  1658. if !r.Next() {
  1659. if r.Err() != nil {
  1660. t.Fatal(err)
  1661. }
  1662. t.Fatal("expected one rows")
  1663. }
  1664. var name string
  1665. err = r.Scan(&name)
  1666. if err != nil {
  1667. t.Fatal(err)
  1668. }
  1669. }
  1670. // testPreparedStmt is test for prepared statement
  1671. func testPreparedStmt(t *testing.T) {
  1672. db.tearDown()
  1673. db.mustExec("CREATE TABLE t (count INT)")
  1674. sel, err := db.Prepare("SELECT count FROM t ORDER BY count DESC")
  1675. if err != nil {
  1676. t.Fatalf("prepare 1: %v", err)
  1677. }
  1678. ins, err := db.Prepare(db.q("INSERT INTO t (count) VALUES (?)"))
  1679. if err != nil {
  1680. t.Fatalf("prepare 2: %v", err)
  1681. }
  1682. for n := 1; n <= 3; n++ {
  1683. if _, err := ins.Exec(n); err != nil {
  1684. t.Fatalf("insert(%d) = %v", n, err)
  1685. }
  1686. }
  1687. const nRuns = 10
  1688. var wg sync.WaitGroup
  1689. for i := 0; i < nRuns; i++ {
  1690. wg.Add(1)
  1691. go func() {
  1692. defer wg.Done()
  1693. for j := 0; j < 10; j++ {
  1694. count := 0
  1695. if err := sel.QueryRow().Scan(&count); err != nil && err != sql.ErrNoRows {
  1696. t.Errorf("Query: %v", err)
  1697. return
  1698. }
  1699. if _, err := ins.Exec(rand.Intn(100)); err != nil {
  1700. t.Errorf("Insert: %v", err)
  1701. return
  1702. }
  1703. }
  1704. }()
  1705. }
  1706. wg.Wait()
  1707. }
  1708. // Benchmarks need to use panic() since b.Error errors are lost when
  1709. // running via testing.Benchmark() I would like to run these via go
  1710. // test -bench but calling Benchmark() from a benchmark test
  1711. // currently hangs go.
  1712. // benchmarkExec is benchmark for exec
  1713. func benchmarkExec(b *testing.B) {
  1714. for i := 0; i < b.N; i++ {
  1715. if _, err := db.Exec("select 1"); err != nil {
  1716. panic(err)
  1717. }
  1718. }
  1719. }
  1720. // benchmarkQuery is benchmark for query
  1721. func benchmarkQuery(b *testing.B) {
  1722. for i := 0; i < b.N; i++ {
  1723. var n sql.NullString
  1724. var i int
  1725. var f float64
  1726. var s string
  1727. // var t time.Time
  1728. if err := db.QueryRow("select null, 1, 1.1, 'foo'").Scan(&n, &i, &f, &s); err != nil {
  1729. panic(err)
  1730. }
  1731. }
  1732. }
  1733. // benchmarkParams is benchmark for params
  1734. func benchmarkParams(b *testing.B) {
  1735. for i := 0; i < b.N; i++ {
  1736. var n sql.NullString
  1737. var i int
  1738. var f float64
  1739. var s string
  1740. // var t time.Time
  1741. if err := db.QueryRow("select ?, ?, ?, ?", nil, 1, 1.1, "foo").Scan(&n, &i, &f, &s); err != nil {
  1742. panic(err)
  1743. }
  1744. }
  1745. }
  1746. // benchmarkStmt is benchmark for statement
  1747. func benchmarkStmt(b *testing.B) {
  1748. st, err := db.Prepare("select ?, ?, ?, ?")
  1749. if err != nil {
  1750. panic(err)
  1751. }
  1752. defer st.Close()
  1753. for n := 0; n < b.N; n++ {
  1754. var n sql.NullString
  1755. var i int
  1756. var f float64
  1757. var s string
  1758. // var t time.Time
  1759. if err := st.QueryRow(nil, 1, 1.1, "foo").Scan(&n, &i, &f, &s); err != nil {
  1760. panic(err)
  1761. }
  1762. }
  1763. }
  1764. // benchmarkRows is benchmark for rows
  1765. func benchmarkRows(b *testing.B) {
  1766. db.once.Do(makeBench)
  1767. for n := 0; n < b.N; n++ {
  1768. var n sql.NullString
  1769. var i int
  1770. var f float64
  1771. var s string
  1772. var t time.Time
  1773. r, err := db.Query("select * from bench")
  1774. if err != nil {
  1775. panic(err)
  1776. }
  1777. for r.Next() {
  1778. if err = r.Scan(&n, &i, &f, &s, &t); err != nil {
  1779. panic(err)
  1780. }
  1781. }
  1782. if err = r.Err(); err != nil {
  1783. panic(err)
  1784. }
  1785. }
  1786. }
  1787. // benchmarkStmtRows is benchmark for statement rows
  1788. func benchmarkStmtRows(b *testing.B) {
  1789. db.once.Do(makeBench)
  1790. st, err := db.Prepare("select * from bench")
  1791. if err != nil {
  1792. panic(err)
  1793. }
  1794. defer st.Close()
  1795. for n := 0; n < b.N; n++ {
  1796. var n sql.NullString
  1797. var i int
  1798. var f float64
  1799. var s string
  1800. var t time.Time
  1801. r, err := st.Query()
  1802. if err != nil {
  1803. panic(err)
  1804. }
  1805. for r.Next() {
  1806. if err = r.Scan(&n, &i, &f, &s, &t); err != nil {
  1807. panic(err)
  1808. }
  1809. }
  1810. if err = r.Err(); err != nil {
  1811. panic(err)
  1812. }
  1813. }
  1814. }