cassandra_test.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  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. "speter.net/go/exp/math/dec/inf"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "testing"
  14. "time"
  15. "unicode"
  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(tb testing.TB) *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. tb.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. tb.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. tb.Fatal("create keyspace:", err)
  47. }
  48. session.Close()
  49. })
  50. cluster.Keyspace = "gocql_test"
  51. session, err := cluster.CreateSession()
  52. if err != nil {
  53. tb.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 TestTracing(t *testing.T) {
  93. session := createSession(t)
  94. defer session.Close()
  95. if err := session.Query(`CREATE TABLE trace (id int primary key)`).Exec(); err != nil {
  96. t.Fatal("create:", err)
  97. }
  98. buf := &bytes.Buffer{}
  99. trace := NewTraceWriter(session, buf)
  100. if err := session.Query(`INSERT INTO trace (id) VALUES (?)`, 42).Trace(trace).Exec(); err != nil {
  101. t.Error("insert:", err)
  102. } else if buf.Len() == 0 {
  103. t.Error("insert: failed to obtain any tracing")
  104. }
  105. buf.Reset()
  106. var value int
  107. if err := session.Query(`SELECT id FROM trace WHERE id = ?`, 42).Trace(trace).Scan(&value); err != nil {
  108. t.Error("select:", err)
  109. } else if value != 42 {
  110. t.Errorf("value: expected %d, got %d", 42, value)
  111. } else if buf.Len() == 0 {
  112. t.Error("select: failed to obtain any tracing")
  113. }
  114. }
  115. func TestPaging(t *testing.T) {
  116. if *flagProto == 1 {
  117. t.Skip("Paging not supported. Please use Cassandra >= 2.0")
  118. }
  119. session := createSession(t)
  120. defer session.Close()
  121. if err := session.Query("CREATE TABLE paging (id int primary key)").Exec(); err != nil {
  122. t.Fatal("create table:", err)
  123. }
  124. for i := 0; i < 100; i++ {
  125. if err := session.Query("INSERT INTO paging (id) VALUES (?)", i).Exec(); err != nil {
  126. t.Fatal("insert:", err)
  127. }
  128. }
  129. iter := session.Query("SELECT id FROM paging").PageSize(10).Iter()
  130. var id int
  131. count := 0
  132. for iter.Scan(&id) {
  133. count++
  134. }
  135. if err := iter.Close(); err != nil {
  136. t.Fatal("close:", err)
  137. }
  138. if count != 100 {
  139. t.Fatalf("expected %d, got %d", 100, count)
  140. }
  141. }
  142. func TestCAS(t *testing.T) {
  143. if *flagProto == 1 {
  144. t.Skip("lightweight transactions not supported. Please use Cassandra >= 2.0")
  145. }
  146. session := createSession(t)
  147. defer session.Close()
  148. if err := session.Query(`CREATE TABLE cas_table (
  149. title varchar,
  150. revid timeuuid,
  151. PRIMARY KEY (title, revid)
  152. )`).Exec(); err != nil {
  153. t.Fatal("create:", err)
  154. }
  155. title, revid := "baz", TimeUUID()
  156. var titleCAS string
  157. var revidCAS UUID
  158. if applied, err := session.Query(`INSERT INTO cas_table (title, revid)
  159. VALUES (?, ?) IF NOT EXISTS`,
  160. title, revid).ScanCAS(&titleCAS, &revidCAS); err != nil {
  161. t.Fatal("insert:", err)
  162. } else if !applied {
  163. t.Fatal("insert should have been applied")
  164. }
  165. if applied, err := session.Query(`INSERT INTO cas_table (title, revid)
  166. VALUES (?, ?) IF NOT EXISTS`,
  167. title, revid).ScanCAS(&titleCAS, &revidCAS); err != nil {
  168. t.Fatal("insert:", err)
  169. } else if applied {
  170. t.Fatal("insert should not have been applied")
  171. } else if title != titleCAS || revid != revidCAS {
  172. t.Fatalf("expected %s/%v but got %s/%v", title, revid, titleCAS, revidCAS)
  173. }
  174. }
  175. func TestBatch(t *testing.T) {
  176. if *flagProto == 1 {
  177. t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
  178. }
  179. session := createSession(t)
  180. defer session.Close()
  181. if err := session.Query(`CREATE TABLE batch_table (id int primary key)`).Exec(); err != nil {
  182. t.Fatal("create table:", err)
  183. }
  184. batch := NewBatch(LoggedBatch)
  185. for i := 0; i < 100; i++ {
  186. batch.Query(`INSERT INTO batch_table (id) VALUES (?)`, i)
  187. }
  188. if err := session.ExecuteBatch(batch); err != nil {
  189. t.Fatal("execute batch:", err)
  190. }
  191. count := 0
  192. if err := session.Query(`SELECT COUNT(*) FROM batch_table`).Scan(&count); err != nil {
  193. t.Fatal("select count:", err)
  194. } else if count != 100 {
  195. t.Fatalf("count: expected %d, got %d\n", 100, count)
  196. }
  197. }
  198. // TestBatchLimit tests gocql to make sure batch operations larger than the maximum
  199. // statement limit are not submitted to a cassandra node.
  200. func TestBatchLimit(t *testing.T) {
  201. if *flagProto == 1 {
  202. t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
  203. }
  204. session := createSession(t)
  205. defer session.Close()
  206. if err := session.Query(`CREATE TABLE batch_table2 (id int primary key)`).Exec(); err != nil {
  207. t.Fatal("create table:", err)
  208. }
  209. batch := NewBatch(LoggedBatch)
  210. for i := 0; i < 65537; i++ {
  211. batch.Query(`INSERT INTO batch_table2 (id) VALUES (?)`, i)
  212. }
  213. if err := session.ExecuteBatch(batch); err != ErrTooManyStmts {
  214. t.Fatal("gocql attempted to execute a batch larger than the support limit of statements.")
  215. }
  216. }
  217. // TestTooManyQueryArgs tests to make sure the library correctly handles the application level bug
  218. // whereby too many query arguments are passed to a query
  219. func TestTooManyQueryArgs(t *testing.T) {
  220. if *flagProto == 1 {
  221. t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
  222. }
  223. session := createSession(t)
  224. defer session.Close()
  225. if err := session.Query(`CREATE TABLE too_many_query_args (id int primary key, value int)`).Exec(); err != nil {
  226. t.Fatal("create table:", err)
  227. }
  228. _, err := session.Query(`SELECT * FROM too_many_query_args WHERE id = ?`, 1, 2).Iter().SliceMap()
  229. if err == nil {
  230. t.Fatal("'`SELECT * FROM too_many_query_args WHERE id = ?`, 1, 2' should return an ErrQueryArgLength")
  231. }
  232. if err != ErrQueryArgLength {
  233. t.Fatalf("'`SELECT * FROM too_many_query_args WHERE id = ?`, 1, 2' should return an ErrQueryArgLength, but returned: %s", err)
  234. }
  235. batch := session.NewBatch(UnloggedBatch)
  236. batch.Query("INSERT INTO too_many_query_args (id, value) VALUES (?, ?)", 1, 2, 3)
  237. err = session.ExecuteBatch(batch)
  238. if err == nil {
  239. t.Fatal("'`INSERT INTO too_many_query_args (id, value) VALUES (?, ?)`, 1, 2, 3' should return an ErrQueryArgLength")
  240. }
  241. if err != ErrQueryArgLength {
  242. t.Fatalf("'INSERT INTO too_many_query_args (id, value) VALUES (?, ?)`, 1, 2, 3' should return an ErrQueryArgLength, but returned: %s", err)
  243. }
  244. }
  245. // TestNotEnoughQueryArgs tests to make sure the library correctly handles the application level bug
  246. // whereby not enough query arguments are passed to a query
  247. func TestNotEnoughQueryArgs(t *testing.T) {
  248. if *flagProto == 1 {
  249. t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
  250. }
  251. session := createSession(t)
  252. defer session.Close()
  253. if err := session.Query(`CREATE TABLE not_enough_query_args (id int, cluster int, value int, primary key (id, cluster))`).Exec(); err != nil {
  254. t.Fatal("create table:", err)
  255. }
  256. _, err := session.Query(`SELECT * FROM not_enough_query_args WHERE id = ? and cluster = ?`, 1).Iter().SliceMap()
  257. if err == nil {
  258. t.Fatal("'`SELECT * FROM not_enough_query_args WHERE id = ? and cluster = ?`, 1' should return an ErrQueryArgLength")
  259. }
  260. if err != ErrQueryArgLength {
  261. t.Fatalf("'`SELECT * FROM too_few_query_args WHERE id = ? and cluster = ?`, 1' should return an ErrQueryArgLength, but returned: %s", err)
  262. }
  263. batch := session.NewBatch(UnloggedBatch)
  264. batch.Query("INSERT INTO not_enough_query_args (id, cluster, value) VALUES (?, ?, ?)", 1, 2)
  265. err = session.ExecuteBatch(batch)
  266. if err == nil {
  267. t.Fatal("'`INSERT INTO not_enough_query_args (id, cluster, value) VALUES (?, ?, ?)`, 1, 2' should return an ErrQueryArgLength")
  268. }
  269. if err != ErrQueryArgLength {
  270. t.Fatalf("'INSERT INTO not_enough_query_args (id, cluster, value) VALUES (?, ?, ?)`, 1, 2' should return an ErrQueryArgLength, but returned: %s", err)
  271. }
  272. }
  273. // TestCreateSessionTimeout tests to make sure the CreateSession function timeouts out correctly
  274. // and prevents an infinite loop of connection retries.
  275. func TestCreateSessionTimeout(t *testing.T) {
  276. go func() {
  277. <-time.After(2 * time.Second)
  278. t.Fatal("no startup timeout")
  279. }()
  280. c := NewCluster("127.0.0.1:1")
  281. _, err := c.CreateSession()
  282. if err == nil {
  283. t.Fatal("expected ErrNoConnectionsStarted, but no error was returned.")
  284. }
  285. if err != ErrNoConnectionsStarted {
  286. t.Fatalf("expected ErrNoConnectionsStarted, but received %v", err)
  287. }
  288. }
  289. func TestSliceMap(t *testing.T) {
  290. session := createSession(t)
  291. defer session.Close()
  292. if err := session.Query(`CREATE TABLE slice_map_table (
  293. testuuid timeuuid PRIMARY KEY,
  294. testtimestamp timestamp,
  295. testvarchar varchar,
  296. testbigint bigint,
  297. testblob blob,
  298. testbool boolean,
  299. testfloat float,
  300. testdouble double,
  301. testint int,
  302. testdecimal decimal,
  303. testset set<int>,
  304. testmap map<varchar, varchar>
  305. )`).Exec(); err != nil {
  306. t.Fatal("create table:", err)
  307. }
  308. m := make(map[string]interface{})
  309. m["testuuid"] = TimeUUID()
  310. m["testvarchar"] = "Test VarChar"
  311. m["testbigint"] = time.Now().Unix()
  312. m["testtimestamp"] = time.Now().Truncate(time.Millisecond).UTC()
  313. m["testblob"] = []byte("test blob")
  314. m["testbool"] = true
  315. m["testfloat"] = float32(4.564)
  316. m["testdouble"] = float64(4.815162342)
  317. m["testint"] = 2343
  318. m["testdecimal"] = inf.NewDec(100, 0)
  319. m["testset"] = []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
  320. m["testmap"] = map[string]string{"field1": "val1", "field2": "val2", "field3": "val3"}
  321. sliceMap := []map[string]interface{}{m}
  322. if err := session.Query(`INSERT INTO slice_map_table (testuuid, testtimestamp, testvarchar, testbigint, testblob, testbool, testfloat, testdouble, testint, testdecimal, testset, testmap) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
  323. 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 {
  324. t.Fatal("insert:", err)
  325. }
  326. if returned, retErr := session.Query(`SELECT * FROM slice_map_table`).Iter().SliceMap(); retErr != nil {
  327. t.Fatal("select:", retErr)
  328. } else {
  329. if sliceMap[0]["testuuid"] != returned[0]["testuuid"] {
  330. t.Fatal("returned testuuid did not match")
  331. }
  332. if sliceMap[0]["testtimestamp"] != returned[0]["testtimestamp"] {
  333. t.Fatalf("returned testtimestamp did not match: %v %v", sliceMap[0]["testtimestamp"], returned[0]["testtimestamp"])
  334. }
  335. if sliceMap[0]["testvarchar"] != returned[0]["testvarchar"] {
  336. t.Fatal("returned testvarchar did not match")
  337. }
  338. if sliceMap[0]["testbigint"] != returned[0]["testbigint"] {
  339. t.Fatal("returned testbigint did not match")
  340. }
  341. if !reflect.DeepEqual(sliceMap[0]["testblob"], returned[0]["testblob"]) {
  342. t.Fatal("returned testblob did not match")
  343. }
  344. if sliceMap[0]["testbool"] != returned[0]["testbool"] {
  345. t.Fatal("returned testbool did not match")
  346. }
  347. if sliceMap[0]["testfloat"] != returned[0]["testfloat"] {
  348. t.Fatal("returned testfloat did not match")
  349. }
  350. if sliceMap[0]["testdouble"] != returned[0]["testdouble"] {
  351. t.Fatal("returned testdouble did not match")
  352. }
  353. if sliceMap[0]["testint"] != returned[0]["testint"] {
  354. t.Fatal("returned testint did not match")
  355. }
  356. expectedDecimal := sliceMap[0]["testdecimal"].(*inf.Dec)
  357. returnedDecimal := returned[0]["testdecimal"].(*inf.Dec)
  358. if expectedDecimal.Cmp(returnedDecimal) != 0 {
  359. t.Fatal("returned testdecimal did not match")
  360. }
  361. if !reflect.DeepEqual(sliceMap[0]["testset"], returned[0]["testset"]) {
  362. t.Fatal("returned testset did not match")
  363. }
  364. if !reflect.DeepEqual(sliceMap[0]["testmap"], returned[0]["testmap"]) {
  365. t.Fatal("returned testmap did not match")
  366. }
  367. }
  368. // Test for MapScan()
  369. testMap := make(map[string]interface{})
  370. if !session.Query(`SELECT * FROM slice_map_table`).Iter().MapScan(testMap) {
  371. t.Fatal("MapScan failed to work with one row")
  372. }
  373. if sliceMap[0]["testuuid"] != testMap["testuuid"] {
  374. t.Fatal("returned testuuid did not match")
  375. }
  376. if sliceMap[0]["testtimestamp"] != testMap["testtimestamp"] {
  377. t.Fatal("returned testtimestamp did not match")
  378. }
  379. if sliceMap[0]["testvarchar"] != testMap["testvarchar"] {
  380. t.Fatal("returned testvarchar did not match")
  381. }
  382. if sliceMap[0]["testbigint"] != testMap["testbigint"] {
  383. t.Fatal("returned testbigint did not match")
  384. }
  385. if !reflect.DeepEqual(sliceMap[0]["testblob"], testMap["testblob"]) {
  386. t.Fatal("returned testblob did not match")
  387. }
  388. if sliceMap[0]["testbool"] != testMap["testbool"] {
  389. t.Fatal("returned testbool did not match")
  390. }
  391. if sliceMap[0]["testfloat"] != testMap["testfloat"] {
  392. t.Fatal("returned testfloat did not match")
  393. }
  394. if sliceMap[0]["testdouble"] != testMap["testdouble"] {
  395. t.Fatal("returned testdouble did not match")
  396. }
  397. if sliceMap[0]["testint"] != testMap["testint"] {
  398. t.Fatal("returned testint did not match")
  399. }
  400. expectedDecimal := sliceMap[0]["testdecimal"].(*inf.Dec)
  401. returnedDecimal := testMap["testdecimal"].(*inf.Dec)
  402. if expectedDecimal.Cmp(returnedDecimal) != 0 {
  403. t.Fatal("returned testdecimal did not match")
  404. }
  405. if !reflect.DeepEqual(sliceMap[0]["testset"], testMap["testset"]) {
  406. t.Fatal("returned testset did not match")
  407. }
  408. if !reflect.DeepEqual(sliceMap[0]["testmap"], testMap["testmap"]) {
  409. t.Fatal("returned testmap did not match")
  410. }
  411. }
  412. func TestScanWithNilArguments(t *testing.T) {
  413. session := createSession(t)
  414. defer session.Close()
  415. if err := session.Query(`CREATE TABLE scan_with_nil_arguments (
  416. foo varchar,
  417. bar int,
  418. PRIMARY KEY (foo, bar)
  419. )`).Exec(); err != nil {
  420. t.Fatal("create:", err)
  421. }
  422. for i := 1; i <= 20; i++ {
  423. if err := session.Query("INSERT INTO scan_with_nil_arguments (foo, bar) VALUES (?, ?)",
  424. "squares", i*i).Exec(); err != nil {
  425. t.Fatal("insert:", err)
  426. }
  427. }
  428. iter := session.Query("SELECT * FROM scan_with_nil_arguments WHERE foo = ?", "squares").Iter()
  429. var n int
  430. count := 0
  431. for iter.Scan(nil, &n) {
  432. count += n
  433. }
  434. if err := iter.Close(); err != nil {
  435. t.Fatal("close:", err)
  436. }
  437. if count != 2870 {
  438. t.Fatalf("expected %d, got %d", 2870, count)
  439. }
  440. }
  441. func TestScanCASWithNilArguments(t *testing.T) {
  442. if *flagProto == 1 {
  443. t.Skip("lightweight transactions not supported. Please use Cassandra >= 2.0")
  444. }
  445. session := createSession(t)
  446. defer session.Close()
  447. if err := session.Query(`CREATE TABLE scan_cas_with_nil_arguments (
  448. foo varchar,
  449. bar varchar,
  450. PRIMARY KEY (foo, bar)
  451. )`).Exec(); err != nil {
  452. t.Fatal("create:", err)
  453. }
  454. foo := "baz"
  455. var cas string
  456. if applied, err := session.Query(`INSERT INTO scan_cas_with_nil_arguments (foo, bar)
  457. VALUES (?, ?) IF NOT EXISTS`,
  458. foo, foo).ScanCAS(nil, nil); err != nil {
  459. t.Fatal("insert:", err)
  460. } else if !applied {
  461. t.Fatal("insert should have been applied")
  462. }
  463. if applied, err := session.Query(`INSERT INTO scan_cas_with_nil_arguments (foo, bar)
  464. VALUES (?, ?) IF NOT EXISTS`,
  465. foo, foo).ScanCAS(&cas, nil); err != nil {
  466. t.Fatal("insert:", err)
  467. } else if applied {
  468. t.Fatal("insert should not have been applied")
  469. } else if foo != cas {
  470. t.Fatalf("expected %v but got %v", foo, cas)
  471. }
  472. if applied, err := session.Query(`INSERT INTO scan_cas_with_nil_arguments (foo, bar)
  473. VALUES (?, ?) IF NOT EXISTS`,
  474. foo, foo).ScanCAS(nil, &cas); err != nil {
  475. t.Fatal("insert:", err)
  476. } else if applied {
  477. t.Fatal("insert should not have been applied")
  478. } else if foo != cas {
  479. t.Fatalf("expected %v but got %v", foo, cas)
  480. }
  481. }
  482. //TestStaticQueryInfo makes sure that the application can manually bind query parameters using the simplest possible static binding strategy
  483. func TestStaticQueryInfo(t *testing.T) {
  484. session := createSession(t)
  485. defer session.Close()
  486. if err := session.Query("CREATE TABLE static_query_info (id int, value text, PRIMARY KEY (id))").Exec(); err != nil {
  487. t.Fatalf("failed to create table with error '%v'", err)
  488. }
  489. if err := session.Query("INSERT INTO static_query_info (id, value) VALUES (?, ?)", 113, "foo").Exec(); err != nil {
  490. t.Fatalf("insert into static_query_info failed, err '%v'", err)
  491. }
  492. autobinder := func(q *QueryInfo) ([]interface{}, error) {
  493. values := make([]interface{}, 1)
  494. values[0] = 113
  495. return values, nil
  496. }
  497. qry := session.Bind("SELECT id, value FROM static_query_info WHERE id = ?", autobinder)
  498. if err := qry.Exec(); err != nil {
  499. t.Fatalf("expose query info failed, error '%v'", err)
  500. }
  501. iter := qry.Iter()
  502. var id int
  503. var value string
  504. iter.Scan(&id, &value)
  505. if err := iter.Close(); err != nil {
  506. t.Fatalf("query with exposed info failed, err '%v'", err)
  507. }
  508. if value != "foo" {
  509. t.Fatalf("Expected value %s, but got %s", "foo", value)
  510. }
  511. }
  512. type ClusteredKeyValue struct {
  513. Id int
  514. Cluster int
  515. Value string
  516. }
  517. func (kv *ClusteredKeyValue) Bind(q *QueryInfo) ([]interface{}, error) {
  518. values := make([]interface{}, len(q.args))
  519. for i, info := range q.args {
  520. fieldName := upcaseInitial(info.Name)
  521. value := reflect.ValueOf(kv)
  522. field := reflect.Indirect(value).FieldByName(fieldName)
  523. values[i] = field.Addr().Interface()
  524. }
  525. return values, nil
  526. }
  527. func upcaseInitial(str string) string {
  528. for i, v := range str {
  529. return string(unicode.ToUpper(v)) + str[i+1:]
  530. }
  531. return ""
  532. }
  533. //TestBoundQueryInfo makes sure that the application can manually bind query parameters using the query meta data supplied at runtime
  534. func TestBoundQueryInfo(t *testing.T) {
  535. session := createSession(t)
  536. defer session.Close()
  537. if err := session.Query("CREATE TABLE clustered_query_info (id int, cluster int, value text, PRIMARY KEY (id, cluster))").Exec(); err != nil {
  538. t.Fatalf("failed to create table with error '%v'", err)
  539. }
  540. write := &ClusteredKeyValue{Id: 200, Cluster: 300, Value: "baz"}
  541. insert := session.Bind("INSERT INTO clustered_query_info (id, cluster, value) VALUES (?, ?,?)", write.Bind)
  542. if err := insert.Exec(); err != nil {
  543. t.Fatalf("insert into clustered_query_info failed, err '%v'", err)
  544. }
  545. read := &ClusteredKeyValue{Id: 200, Cluster: 300}
  546. qry := session.Bind("SELECT id, cluster, value FROM clustered_query_info WHERE id = ? and cluster = ?", read.Bind)
  547. iter := qry.Iter()
  548. var id, cluster int
  549. var value string
  550. iter.Scan(&id, &cluster, &value)
  551. if err := iter.Close(); err != nil {
  552. t.Fatalf("query with clustered_query_info info failed, err '%v'", err)
  553. }
  554. if value != "baz" {
  555. t.Fatalf("Expected value %s, but got %s", "baz", value)
  556. }
  557. }
  558. //TestBatchQueryInfo makes sure that the application can manually bind query parameters when executing in a batch
  559. func TestBatchQueryInfo(t *testing.T) {
  560. if *flagProto == 1 {
  561. t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
  562. }
  563. session := createSession(t)
  564. defer session.Close()
  565. if err := session.Query("CREATE TABLE batch_query_info (id int, cluster int, value text, PRIMARY KEY (id, cluster))").Exec(); err != nil {
  566. t.Fatalf("failed to create table with error '%v'", err)
  567. }
  568. write := func(q *QueryInfo) ([]interface{}, error) {
  569. values := make([]interface{}, 3)
  570. values[0] = 4000
  571. values[1] = 5000
  572. values[2] = "bar"
  573. return values, nil
  574. }
  575. batch := session.NewBatch(LoggedBatch)
  576. batch.Bind("INSERT INTO batch_query_info (id, cluster, value) VALUES (?, ?,?)", write)
  577. if err := session.ExecuteBatch(batch); err != nil {
  578. t.Fatalf("batch insert into batch_query_info failed, err '%v'", err)
  579. }
  580. read := func(q *QueryInfo) ([]interface{}, error) {
  581. values := make([]interface{}, 2)
  582. values[0] = 4000
  583. values[1] = 5000
  584. return values, nil
  585. }
  586. qry := session.Bind("SELECT id, cluster, value FROM batch_query_info WHERE id = ? and cluster = ?", read)
  587. iter := qry.Iter()
  588. var id, cluster int
  589. var value string
  590. iter.Scan(&id, &cluster, &value)
  591. if err := iter.Close(); err != nil {
  592. t.Fatalf("query with batch_query_info info failed, err '%v'", err)
  593. }
  594. if value != "bar" {
  595. t.Fatalf("Expected value %s, but got %s", "bar", value)
  596. }
  597. }
  598. func injectInvalidPreparedStatement(t *testing.T, session *Session, table string) (string, *Conn) {
  599. if err := session.Query(`CREATE TABLE ` + table + ` (
  600. foo varchar,
  601. bar int,
  602. PRIMARY KEY (foo, bar)
  603. )`).Exec(); err != nil {
  604. t.Fatal("create:", err)
  605. }
  606. stmt := "INSERT INTO " + table + " (foo, bar) VALUES (?, 7)"
  607. conn := session.Pool.Pick(nil)
  608. flight := new(inflightPrepare)
  609. stmtsLRU.mu.Lock()
  610. stmtsLRU.lru.Add(conn.addr+stmt, flight)
  611. stmtsLRU.mu.Unlock()
  612. flight.info = &QueryInfo{
  613. id: []byte{'f', 'o', 'o', 'b', 'a', 'r'},
  614. args: []ColumnInfo{ColumnInfo{
  615. Keyspace: "gocql_test",
  616. Table: table,
  617. Name: "foo",
  618. TypeInfo: &TypeInfo{
  619. Type: TypeVarchar,
  620. },
  621. }},
  622. }
  623. return stmt, conn
  624. }
  625. func TestReprepareStatement(t *testing.T) {
  626. session := createSession(t)
  627. defer session.Close()
  628. stmt, conn := injectInvalidPreparedStatement(t, session, "test_reprepare_statement")
  629. query := session.Query(stmt, "bar")
  630. if err := conn.executeQuery(query).Close(); err != nil {
  631. t.Fatalf("Failed to execute query for reprepare statement: %v", err)
  632. }
  633. }
  634. func TestReprepareBatch(t *testing.T) {
  635. if *flagProto == 1 {
  636. t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
  637. }
  638. session := createSession(t)
  639. defer session.Close()
  640. stmt, conn := injectInvalidPreparedStatement(t, session, "test_reprepare_statement_batch")
  641. batch := session.NewBatch(UnloggedBatch)
  642. batch.Query(stmt, "bar")
  643. if err := conn.executeBatch(batch); err != nil {
  644. t.Fatalf("Failed to execute query for reprepare statement: %v", err)
  645. }
  646. }
  647. func TestQueryInfo(t *testing.T) {
  648. session := createSession(t)
  649. defer session.Close()
  650. conn := session.Pool.Pick(nil)
  651. info, err := conn.prepareStatement("SELECT release_version, host_id FROM system.local WHERE key = ?", nil)
  652. if err != nil {
  653. t.Fatalf("Failed to execute query for preparing statement: %v", err)
  654. }
  655. if len(info.args) != 1 {
  656. t.Fatalf("Was not expecting meta data for %d query arguments, but got %d\n", 1, len(info.args))
  657. }
  658. if *flagProto > 1 {
  659. if len(info.rval) != 2 {
  660. t.Fatalf("Was not expecting meta data for %d result columns, but got %d\n", 2, len(info.rval))
  661. }
  662. }
  663. }
  664. //TestPreparedCacheEviction will make sure that the cache size is maintained
  665. func TestPreparedCacheEviction(t *testing.T) {
  666. session := createSession(t)
  667. defer session.Close()
  668. stmtsLRU.mu.Lock()
  669. stmtsLRU.Max(4)
  670. stmtsLRU.mu.Unlock()
  671. if err := session.Query("CREATE TABLE prepcachetest (id int,mod int,PRIMARY KEY (id))").Exec(); err != nil {
  672. t.Fatalf("failed to create table with error '%v'", err)
  673. }
  674. //Fill the table
  675. for i := 0; i < 2; i++ {
  676. if err := session.Query("INSERT INTO prepcachetest (id,mod) VALUES (?, ?)", i, 10000%(i+1)).Exec(); err != nil {
  677. t.Fatalf("insert into prepcachetest failed, err '%v'", err)
  678. }
  679. }
  680. //Populate the prepared statement cache with select statements
  681. var id, mod int
  682. for i := 0; i < 2; i++ {
  683. err := session.Query("SELECT id,mod FROM prepcachetest WHERE id = "+strconv.FormatInt(int64(i), 10)).Scan(&id, &mod)
  684. if err != nil {
  685. t.Fatalf("select from prepcachetest failed, error '%v'", err)
  686. }
  687. }
  688. //generate an update statement to test they are prepared
  689. err := session.Query("UPDATE prepcachetest SET mod = ? WHERE id = ?", 1, 11).Exec()
  690. if err != nil {
  691. t.Fatalf("update prepcachetest failed, error '%v'", err)
  692. }
  693. //generate a delete statement to test they are prepared
  694. err = session.Query("DELETE FROM prepcachetest WHERE id = ?", 1).Exec()
  695. if err != nil {
  696. t.Fatalf("delete from prepcachetest failed, error '%v'", err)
  697. }
  698. //generate an insert statement to test they are prepared
  699. err = session.Query("INSERT INTO prepcachetest (id,mod) VALUES (?, ?)", 3, 11).Exec()
  700. if err != nil {
  701. t.Fatalf("insert into prepcachetest failed, error '%v'", err)
  702. }
  703. //Make sure the cache size is maintained
  704. if stmtsLRU.lru.Len() != stmtsLRU.lru.MaxEntries {
  705. t.Fatalf("expected cache size of %v, got %v", stmtsLRU.lru.MaxEntries, stmtsLRU.lru.Len())
  706. }
  707. //Walk through all the configured hosts and test cache retention and eviction
  708. var selFound, insFound, updFound, delFound, selEvict bool
  709. for i := range session.cfg.Hosts {
  710. _, ok := stmtsLRU.lru.Get(session.cfg.Hosts[i] + ":9042SELECT id,mod FROM prepcachetest WHERE id = 1")
  711. selFound = selFound || ok
  712. _, ok = stmtsLRU.lru.Get(session.cfg.Hosts[i] + ":9042INSERT INTO prepcachetest (id,mod) VALUES (?, ?)")
  713. insFound = insFound || ok
  714. _, ok = stmtsLRU.lru.Get(session.cfg.Hosts[i] + ":9042UPDATE prepcachetest SET mod = ? WHERE id = ?")
  715. updFound = updFound || ok
  716. _, ok = stmtsLRU.lru.Get(session.cfg.Hosts[i] + ":9042DELETE FROM prepcachetest WHERE id = ?")
  717. delFound = delFound || ok
  718. _, ok = stmtsLRU.lru.Get(session.cfg.Hosts[i] + ":9042SELECT id,mod FROM prepcachetest WHERE id = 0")
  719. selEvict = selEvict || !ok
  720. }
  721. if !selEvict {
  722. t.Fatalf("expected first select statement to be purged, but statement was found in the cache.")
  723. }
  724. if !selFound {
  725. t.Fatalf("expected second select statement to be cached, but statement was purged or not prepared.")
  726. }
  727. if !insFound {
  728. t.Fatalf("expected insert statement to be cached, but statement was purged or not prepared.")
  729. }
  730. if !updFound {
  731. t.Fatalf("expected update statement to be cached, but statement was purged or not prepared.")
  732. }
  733. if !delFound {
  734. t.Error("expected delete statement to be cached, but statement was purged or not prepared.")
  735. }
  736. }