cassandra_test.go 20 KB

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