cassandra_test.go 31 KB

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