cassandra_test.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. // Copyright (c) 2012 The gocql Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package gocql
  5. import (
  6. "bytes"
  7. "flag"
  8. "reflect"
  9. "sort"
  10. "speter.net/go/exp/math/dec/inf"
  11. "strings"
  12. "sync"
  13. "testing"
  14. "time"
  15. )
  16. var (
  17. flagCluster = flag.String("cluster", "127.0.0.1", "a comma-separated list of host:port tuples")
  18. flagProto = flag.Int("proto", 2, "protcol version")
  19. flagCQL = flag.String("cql", "3.0.0", "CQL version")
  20. )
  21. var initOnce sync.Once
  22. func createSession(t *testing.T) *Session {
  23. cluster := NewCluster(strings.Split(*flagCluster, ",")...)
  24. cluster.ProtoVersion = *flagProto
  25. cluster.CQLVersion = *flagCQL
  26. cluster.Authenticator = PasswordAuthenticator{
  27. Username: "cassandra",
  28. Password: "cassandra",
  29. }
  30. initOnce.Do(func() {
  31. session, err := cluster.CreateSession()
  32. if err != nil {
  33. t.Fatal("createSession:", err)
  34. }
  35. // Drop and re-create the keyspace once. Different tests should use their own
  36. // individual tables, but can assume that the table does not exist before.
  37. if err := session.Query(`DROP KEYSPACE gocql_test`).Exec(); err != nil {
  38. t.Log("drop keyspace:", err)
  39. }
  40. if err := session.Query(`CREATE KEYSPACE gocql_test
  41. WITH replication = {
  42. 'class' : 'SimpleStrategy',
  43. 'replication_factor' : 1
  44. }`).Exec(); err != nil {
  45. t.Fatal("create keyspace:", err)
  46. }
  47. session.Close()
  48. })
  49. cluster.Keyspace = "gocql_test"
  50. session, err := cluster.CreateSession()
  51. if err != nil {
  52. t.Fatal("createSession:", err)
  53. }
  54. return session
  55. }
  56. func TestEmptyHosts(t *testing.T) {
  57. cluster := NewCluster()
  58. if session, err := cluster.CreateSession(); err == nil {
  59. session.Close()
  60. t.Error("expected err, got nil")
  61. }
  62. }
  63. //TestUseStatementError checks to make sure the correct error is returned when the user tries to execute a use statement.
  64. func TestUseStatementError(t *testing.T) {
  65. session := createSession(t)
  66. defer session.Close()
  67. if err := session.Query("USE gocql_test").Exec(); err != nil {
  68. if err != ErrUseStmt {
  69. t.Error("expected ErrUseStmt, got " + err.Error())
  70. }
  71. } else {
  72. t.Error("expected err, got nil.")
  73. }
  74. }
  75. //TestInvalidKeyspace checks that an invalid keyspace will return promptly and without a flood of connections
  76. func TestInvalidKeyspace(t *testing.T) {
  77. cluster := NewCluster(strings.Split(*flagCluster, ",")...)
  78. cluster.ProtoVersion = *flagProto
  79. cluster.CQLVersion = *flagCQL
  80. cluster.Keyspace = "invalidKeyspace"
  81. session, err := cluster.CreateSession()
  82. if err != nil {
  83. if err != ErrNoConnectionsStarted {
  84. t.Errorf("Expected ErrNoConnections but got %v", err)
  85. }
  86. } else {
  87. session.Close() //Clean up the session
  88. t.Error("expected err, got nil.")
  89. }
  90. }
  91. func TestCRUD(t *testing.T) {
  92. session := createSession(t)
  93. defer session.Close()
  94. if err := session.Query(`CREATE TABLE page (
  95. title varchar,
  96. revid timeuuid,
  97. body varchar,
  98. views bigint,
  99. protected boolean,
  100. modified timestamp,
  101. rating decimal,
  102. tags set<varchar>,
  103. attachments map<varchar, text>,
  104. PRIMARY KEY (title, revid)
  105. )`).Exec(); err != nil {
  106. t.Fatal("create table:", err)
  107. }
  108. for _, page := range pageTestData {
  109. if err := session.Query(`INSERT INTO page
  110. (title, revid, body, views, protected, modified, rating, tags, attachments)
  111. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
  112. page.Title, page.RevId, page.Body, page.Views, page.Protected,
  113. page.Modified, page.Rating, page.Tags, page.Attachments).Exec(); err != nil {
  114. t.Fatal("insert:", err)
  115. }
  116. }
  117. var count int
  118. if err := session.Query("SELECT COUNT(*) FROM page").Scan(&count); err != nil {
  119. t.Error("select count:", err)
  120. }
  121. if count != len(pageTestData) {
  122. t.Errorf("count: expected %d, got %d\n", len(pageTestData), count)
  123. }
  124. for _, original := range pageTestData {
  125. page := new(Page)
  126. err := session.Query(`SELECT title, revid, body, views, protected, modified,
  127. tags, attachments, rating
  128. FROM page WHERE title = ? AND revid = ? LIMIT 1`,
  129. original.Title, original.RevId).Scan(&page.Title, &page.RevId,
  130. &page.Body, &page.Views, &page.Protected, &page.Modified, &page.Tags,
  131. &page.Attachments, &page.Rating)
  132. if err != nil {
  133. t.Error("select page:", err)
  134. continue
  135. }
  136. sort.Sort(sort.StringSlice(page.Tags))
  137. sort.Sort(sort.StringSlice(original.Tags))
  138. if !reflect.DeepEqual(page, original) {
  139. t.Errorf("page: expected %#v, got %#v\n", original, page)
  140. }
  141. }
  142. }
  143. func TestTracing(t *testing.T) {
  144. session := createSession(t)
  145. defer session.Close()
  146. if err := session.Query(`CREATE TABLE trace (id int primary key)`).Exec(); err != nil {
  147. t.Fatal("create:", err)
  148. }
  149. buf := &bytes.Buffer{}
  150. trace := NewTraceWriter(session, buf)
  151. if err := session.Query(`INSERT INTO trace (id) VALUES (?)`, 42).Trace(trace).Exec(); err != nil {
  152. t.Error("insert:", err)
  153. } else if buf.Len() == 0 {
  154. t.Error("insert: failed to obtain any tracing")
  155. }
  156. buf.Reset()
  157. var value int
  158. if err := session.Query(`SELECT id FROM trace WHERE id = ?`, 42).Trace(trace).Scan(&value); err != nil {
  159. t.Error("select:", err)
  160. } else if value != 42 {
  161. t.Errorf("value: expected %d, got %d", 42, value)
  162. } else if buf.Len() == 0 {
  163. t.Error("select: failed to obtain any tracing")
  164. }
  165. }
  166. func TestPaging(t *testing.T) {
  167. if *flagProto == 1 {
  168. t.Skip("Paging not supported. Please use Cassandra >= 2.0")
  169. }
  170. session := createSession(t)
  171. defer session.Close()
  172. if err := session.Query("CREATE TABLE paging (id int primary key)").Exec(); err != nil {
  173. t.Fatal("create table:", err)
  174. }
  175. for i := 0; i < 100; i++ {
  176. if err := session.Query("INSERT INTO paging (id) VALUES (?)", i).Exec(); err != nil {
  177. t.Fatal("insert:", err)
  178. }
  179. }
  180. iter := session.Query("SELECT id FROM paging").PageSize(10).Iter()
  181. var id int
  182. count := 0
  183. for iter.Scan(&id) {
  184. count++
  185. }
  186. if err := iter.Close(); err != nil {
  187. t.Fatal("close:", err)
  188. }
  189. if count != 100 {
  190. t.Fatalf("expected %d, got %d", 100, count)
  191. }
  192. }
  193. func TestCAS(t *testing.T) {
  194. if *flagProto == 1 {
  195. t.Skip("lightweight transactions not supported. Please use Cassandra >= 2.0")
  196. }
  197. session := createSession(t)
  198. defer session.Close()
  199. if err := session.Query(`CREATE TABLE cas_table (
  200. title varchar,
  201. revid timeuuid,
  202. PRIMARY KEY (title, revid)
  203. )`).Exec(); err != nil {
  204. t.Fatal("create:", err)
  205. }
  206. title, revid := "baz", TimeUUID()
  207. var titleCAS string
  208. var revidCAS UUID
  209. if applied, err := session.Query(`INSERT INTO cas_table (title, revid)
  210. VALUES (?, ?) IF NOT EXISTS`,
  211. title, revid).ScanCAS(&titleCAS, &revidCAS); err != nil {
  212. t.Fatal("insert:", err)
  213. } else if !applied {
  214. t.Fatal("insert should have been applied")
  215. }
  216. if applied, err := session.Query(`INSERT INTO cas_table (title, revid)
  217. VALUES (?, ?) IF NOT EXISTS`,
  218. title, revid).ScanCAS(&titleCAS, &revidCAS); err != nil {
  219. t.Fatal("insert:", err)
  220. } else if applied {
  221. t.Fatal("insert should not have been applied")
  222. } else if title != titleCAS || revid != revidCAS {
  223. t.Fatalf("expected %s/%v but got %s/%v", title, revid, titleCAS, revidCAS)
  224. }
  225. }
  226. func TestBatch(t *testing.T) {
  227. if *flagProto == 1 {
  228. t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
  229. }
  230. session := createSession(t)
  231. defer session.Close()
  232. if err := session.Query(`CREATE TABLE batch_table (id int primary key)`).Exec(); err != nil {
  233. t.Fatal("create table:", err)
  234. }
  235. batch := NewBatch(LoggedBatch)
  236. for i := 0; i < 100; i++ {
  237. batch.Query(`INSERT INTO batch_table (id) VALUES (?)`, i)
  238. }
  239. if err := session.ExecuteBatch(batch); err != nil {
  240. t.Fatal("execute batch:", err)
  241. }
  242. count := 0
  243. if err := session.Query(`SELECT COUNT(*) FROM batch_table`).Scan(&count); err != nil {
  244. t.Fatal("select count:", err)
  245. } else if count != 100 {
  246. t.Fatalf("count: expected %d, got %d\n", 100, count)
  247. }
  248. }
  249. // TestBatchLimit tests gocql to make sure batch operations larger than the maximum
  250. // statement limit are not submitted to a cassandra node.
  251. func TestBatchLimit(t *testing.T) {
  252. if *flagProto == 1 {
  253. t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
  254. }
  255. session := createSession(t)
  256. defer session.Close()
  257. if err := session.Query(`CREATE TABLE batch_table2 (id int primary key)`).Exec(); err != nil {
  258. t.Fatal("create table:", err)
  259. }
  260. batch := NewBatch(LoggedBatch)
  261. for i := 0; i < 65537; i++ {
  262. batch.Query(`INSERT INTO batch_table2 (id) VALUES (?)`, i)
  263. }
  264. if err := session.ExecuteBatch(batch); err != ErrTooManyStmts {
  265. t.Fatal("gocql attempted to execute a batch larger than the support limit of statements.")
  266. }
  267. }
  268. // TestWrongQueryArgsLength tests to make sure the library correctly handles the application level bug
  269. // whereby the wrong number of query arguments are passed to a query
  270. func TestWrongQueryArgsLength(t *testing.T) {
  271. session := createSession(t)
  272. defer session.Close()
  273. if err := session.Query(`CREATE TABLE query_args_length (id int primary key, value int)`).Exec(); err != nil {
  274. t.Fatal("create table:", err)
  275. }
  276. _, err := session.Query(`SELECT * FROM query_args_length WHERE id = ?`, 1, 2).Iter().SliceMap()
  277. if err == nil || err != ErrQueryArgLength {
  278. t.Fatal("'`SELECT * FROM query_args_length WHERE id = ?`, 1, 2' should return an ErrQueryArgLength")
  279. }
  280. }
  281. // TestCreateSessionTimeout tests to make sure the CreateSession function timeouts out correctly
  282. // and prevents an infinite loop of connection retries.
  283. func TestCreateSessionTimeout(t *testing.T) {
  284. go func() {
  285. <-time.After(2 * time.Second)
  286. t.Fatal("no startup timeout")
  287. }()
  288. c := NewCluster("127.0.0.1:1")
  289. _, err := c.CreateSession()
  290. if err == nil {
  291. t.Fatal("expected ErrNoConnectionsStarted, but no error was returned.")
  292. }
  293. if err != ErrNoConnectionsStarted {
  294. t.Fatalf("expected ErrNoConnectionsStarted, but received %v", err)
  295. }
  296. }
  297. type Page struct {
  298. Title string
  299. RevId UUID
  300. Body string
  301. Views int64
  302. Protected bool
  303. Modified time.Time
  304. Rating *inf.Dec
  305. Tags []string
  306. Attachments map[string]Attachment
  307. }
  308. type Attachment []byte
  309. var rating, _ = inf.NewDec(0, 0).SetString("0.131")
  310. var pageTestData = []*Page{
  311. &Page{
  312. Title: "Frontpage",
  313. RevId: TimeUUID(),
  314. Body: "Welcome to this wiki page!",
  315. Rating: rating,
  316. Modified: time.Date(2013, time.August, 13, 9, 52, 3, 0, time.UTC),
  317. Tags: []string{"start", "important", "test"},
  318. Attachments: map[string]Attachment{
  319. "logo": Attachment("\x00company logo\x00"),
  320. "favicon": Attachment("favicon.ico"),
  321. },
  322. },
  323. &Page{
  324. Title: "Foobar",
  325. RevId: TimeUUID(),
  326. Body: "foo::Foo f = new foo::Foo(foo::Foo::INIT);",
  327. Modified: time.Date(2013, time.August, 13, 9, 52, 3, 0, time.UTC),
  328. },
  329. }
  330. func TestSliceMap(t *testing.T) {
  331. session := createSession(t)
  332. defer session.Close()
  333. if err := session.Query(`CREATE TABLE slice_map_table (
  334. testuuid timeuuid PRIMARY KEY,
  335. testtimestamp timestamp,
  336. testvarchar varchar,
  337. testbigint bigint,
  338. testblob blob,
  339. testbool boolean,
  340. testfloat float,
  341. testdouble double,
  342. testint int,
  343. testdecimal decimal,
  344. testset set<int>,
  345. testmap map<varchar, varchar>
  346. )`).Exec(); err != nil {
  347. t.Fatal("create table:", err)
  348. }
  349. m := make(map[string]interface{})
  350. m["testuuid"] = TimeUUID()
  351. m["testvarchar"] = "Test VarChar"
  352. m["testbigint"] = time.Now().Unix()
  353. m["testtimestamp"] = time.Now().Truncate(time.Millisecond).UTC()
  354. m["testblob"] = []byte("test blob")
  355. m["testbool"] = true
  356. m["testfloat"] = float32(4.564)
  357. m["testdouble"] = float64(4.815162342)
  358. m["testint"] = 2343
  359. m["testdecimal"] = inf.NewDec(100, 0)
  360. m["testset"] = []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
  361. m["testmap"] = map[string]string{"field1": "val1", "field2": "val2", "field3": "val3"}
  362. sliceMap := []map[string]interface{}{m}
  363. if err := session.Query(`INSERT INTO slice_map_table (testuuid, testtimestamp, testvarchar, testbigint, testblob, testbool, testfloat, testdouble, testint, testdecimal, testset, testmap) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
  364. m["testuuid"], m["testtimestamp"], m["testvarchar"], m["testbigint"], m["testblob"], m["testbool"], m["testfloat"], m["testdouble"], m["testint"], m["testdecimal"], m["testset"], m["testmap"]).Exec(); err != nil {
  365. t.Fatal("insert:", err)
  366. }
  367. if returned, retErr := session.Query(`SELECT * FROM slice_map_table`).Iter().SliceMap(); retErr != nil {
  368. t.Fatal("select:", retErr)
  369. } else {
  370. if sliceMap[0]["testuuid"] != returned[0]["testuuid"] {
  371. t.Fatal("returned testuuid did not match")
  372. }
  373. if sliceMap[0]["testtimestamp"] != returned[0]["testtimestamp"] {
  374. t.Fatalf("returned testtimestamp did not match: %v %v", sliceMap[0]["testtimestamp"], returned[0]["testtimestamp"])
  375. }
  376. if sliceMap[0]["testvarchar"] != returned[0]["testvarchar"] {
  377. t.Fatal("returned testvarchar did not match")
  378. }
  379. if sliceMap[0]["testbigint"] != returned[0]["testbigint"] {
  380. t.Fatal("returned testbigint did not match")
  381. }
  382. if !reflect.DeepEqual(sliceMap[0]["testblob"], returned[0]["testblob"]) {
  383. t.Fatal("returned testblob did not match")
  384. }
  385. if sliceMap[0]["testbool"] != returned[0]["testbool"] {
  386. t.Fatal("returned testbool did not match")
  387. }
  388. if sliceMap[0]["testfloat"] != returned[0]["testfloat"] {
  389. t.Fatal("returned testfloat did not match")
  390. }
  391. if sliceMap[0]["testdouble"] != returned[0]["testdouble"] {
  392. t.Fatal("returned testdouble did not match")
  393. }
  394. if sliceMap[0]["testint"] != returned[0]["testint"] {
  395. t.Fatal("returned testint did not match")
  396. }
  397. expectedDecimal := sliceMap[0]["testdecimal"].(*inf.Dec)
  398. returnedDecimal := returned[0]["testdecimal"].(*inf.Dec)
  399. if expectedDecimal.Cmp(returnedDecimal) != 0 {
  400. t.Fatal("returned testdecimal did not match")
  401. }
  402. if !reflect.DeepEqual(sliceMap[0]["testset"], returned[0]["testset"]) {
  403. t.Fatal("returned testset did not match")
  404. }
  405. if !reflect.DeepEqual(sliceMap[0]["testmap"], returned[0]["testmap"]) {
  406. t.Fatal("returned testmap did not match")
  407. }
  408. }
  409. // Test for MapScan()
  410. testMap := make(map[string]interface{})
  411. if !session.Query(`SELECT * FROM slice_map_table`).Iter().MapScan(testMap) {
  412. t.Fatal("MapScan failed to work with one row")
  413. }
  414. if sliceMap[0]["testuuid"] != testMap["testuuid"] {
  415. t.Fatal("returned testuuid did not match")
  416. }
  417. if sliceMap[0]["testtimestamp"] != testMap["testtimestamp"] {
  418. t.Fatal("returned testtimestamp did not match")
  419. }
  420. if sliceMap[0]["testvarchar"] != testMap["testvarchar"] {
  421. t.Fatal("returned testvarchar did not match")
  422. }
  423. if sliceMap[0]["testbigint"] != testMap["testbigint"] {
  424. t.Fatal("returned testbigint did not match")
  425. }
  426. if !reflect.DeepEqual(sliceMap[0]["testblob"], testMap["testblob"]) {
  427. t.Fatal("returned testblob did not match")
  428. }
  429. if sliceMap[0]["testbool"] != testMap["testbool"] {
  430. t.Fatal("returned testbool did not match")
  431. }
  432. if sliceMap[0]["testfloat"] != testMap["testfloat"] {
  433. t.Fatal("returned testfloat did not match")
  434. }
  435. if sliceMap[0]["testdouble"] != testMap["testdouble"] {
  436. t.Fatal("returned testdouble did not match")
  437. }
  438. if sliceMap[0]["testint"] != testMap["testint"] {
  439. t.Fatal("returned testint did not match")
  440. }
  441. expectedDecimal := sliceMap[0]["testdecimal"].(*inf.Dec)
  442. returnedDecimal := testMap["testdecimal"].(*inf.Dec)
  443. if expectedDecimal.Cmp(returnedDecimal) != 0 {
  444. t.Fatal("returned testdecimal did not match")
  445. }
  446. if !reflect.DeepEqual(sliceMap[0]["testset"], testMap["testset"]) {
  447. t.Fatal("returned testset did not match")
  448. }
  449. if !reflect.DeepEqual(sliceMap[0]["testmap"], testMap["testmap"]) {
  450. t.Fatal("returned testmap did not match")
  451. }
  452. }
  453. func TestScanWithNilArguments(t *testing.T) {
  454. session := createSession(t)
  455. defer session.Close()
  456. if err := session.Query(`CREATE TABLE scan_with_nil_arguments (
  457. foo varchar,
  458. bar int,
  459. PRIMARY KEY (foo, bar)
  460. )`).Exec(); err != nil {
  461. t.Fatal("create:", err)
  462. }
  463. for i := 1; i <= 20; i++ {
  464. if err := session.Query("INSERT INTO scan_with_nil_arguments (foo, bar) VALUES (?, ?)",
  465. "squares", i*i).Exec(); err != nil {
  466. t.Fatal("insert:", err)
  467. }
  468. }
  469. iter := session.Query("SELECT * FROM scan_with_nil_arguments WHERE foo = ?", "squares").Iter()
  470. var n int
  471. count := 0
  472. for iter.Scan(nil, &n) {
  473. count += n
  474. }
  475. if err := iter.Close(); err != nil {
  476. t.Fatal("close:", err)
  477. }
  478. if count != 2870 {
  479. t.Fatalf("expected %d, got %d", 2870, count)
  480. }
  481. }
  482. func TestScanCASWithNilArguments(t *testing.T) {
  483. if *flagProto == 1 {
  484. t.Skip("lightweight transactions not supported. Please use Cassandra >= 2.0")
  485. }
  486. session := createSession(t)
  487. defer session.Close()
  488. if err := session.Query(`CREATE TABLE scan_cas_with_nil_arguments (
  489. foo varchar,
  490. bar varchar,
  491. PRIMARY KEY (foo, bar)
  492. )`).Exec(); err != nil {
  493. t.Fatal("create:", err)
  494. }
  495. foo := "baz"
  496. var cas string
  497. if applied, err := session.Query(`INSERT INTO scan_cas_with_nil_arguments (foo, bar)
  498. VALUES (?, ?) IF NOT EXISTS`,
  499. foo, foo).ScanCAS(nil, nil); err != nil {
  500. t.Fatal("insert:", err)
  501. } else if !applied {
  502. t.Fatal("insert should have been applied")
  503. }
  504. if applied, err := session.Query(`INSERT INTO scan_cas_with_nil_arguments (foo, bar)
  505. VALUES (?, ?) IF NOT EXISTS`,
  506. foo, foo).ScanCAS(&cas, nil); err != nil {
  507. t.Fatal("insert:", err)
  508. } else if applied {
  509. t.Fatal("insert should not have been applied")
  510. } else if foo != cas {
  511. t.Fatalf("expected %v but got %v", foo, cas)
  512. }
  513. if applied, err := session.Query(`INSERT INTO scan_cas_with_nil_arguments (foo, bar)
  514. VALUES (?, ?) IF NOT EXISTS`,
  515. foo, foo).ScanCAS(nil, &cas); err != nil {
  516. t.Fatal("insert:", err)
  517. } else if applied {
  518. t.Fatal("insert should not have been applied")
  519. } else if foo != cas {
  520. t.Fatalf("expected %v but got %v", foo, cas)
  521. }
  522. }
  523. func injectInvalidPreparedStatement(t *testing.T, session *Session, table string) (string, *Conn) {
  524. if err := session.Query(`CREATE TABLE ` + table + ` (
  525. foo varchar,
  526. bar int,
  527. PRIMARY KEY (foo, bar)
  528. )`).Exec(); err != nil {
  529. t.Fatal("create:", err)
  530. }
  531. stmt := "INSERT INTO " + table + " (foo, bar) VALUES (?, 7)"
  532. conn := session.Pool.Pick(nil)
  533. conn.prepMu.Lock()
  534. flight := new(inflightPrepare)
  535. conn.prep[stmt] = flight
  536. flight.info = &queryInfo{
  537. id: []byte{'f', 'o', 'o', 'b', 'a', 'r'},
  538. args: []ColumnInfo{ColumnInfo{
  539. Keyspace: "gocql_test",
  540. Table: table,
  541. Name: "foo",
  542. TypeInfo: &TypeInfo{
  543. Type: TypeVarchar,
  544. },
  545. }},
  546. }
  547. conn.prepMu.Unlock()
  548. return stmt, conn
  549. }
  550. func TestReprepareStatement(t *testing.T) {
  551. session := createSession(t)
  552. defer session.Close()
  553. stmt, conn := injectInvalidPreparedStatement(t, session, "test_reprepare_statement")
  554. query := session.Query(stmt, "bar")
  555. if err := conn.executeQuery(query).Close(); err != nil {
  556. t.Fatalf("Failed to execute query for reprepare statement: %v", err)
  557. }
  558. }
  559. func TestReprepareBatch(t *testing.T) {
  560. session := createSession(t)
  561. defer session.Close()
  562. stmt, conn := injectInvalidPreparedStatement(t, session, "test_reprepare_statement_batch")
  563. batch := session.NewBatch(UnloggedBatch)
  564. batch.Query(stmt, "bar")
  565. if err := conn.executeBatch(batch); err != nil {
  566. t.Fatalf("Failed to execute query for reprepare statement: %v", err)
  567. }
  568. }