cassandra_test.go 28 KB

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