cassandra_test.go 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858
  1. // +build all integration
  2. package gocql
  3. import (
  4. "bytes"
  5. "flag"
  6. "fmt"
  7. "log"
  8. "math"
  9. "math/big"
  10. "net"
  11. "reflect"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "testing"
  16. "time"
  17. "unicode"
  18. "speter.net/go/exp/math/dec/inf"
  19. )
  20. var (
  21. flagCluster = flag.String("cluster", "127.0.0.1", "a comma-separated list of host:port tuples")
  22. flagProto = flag.Int("proto", 2, "protcol version")
  23. flagCQL = flag.String("cql", "3.0.0", "CQL version")
  24. flagRF = flag.Int("rf", 1, "replication factor for test keyspace")
  25. clusterSize = flag.Int("clusterSize", 1, "the expected size of the cluster")
  26. flagRetry = flag.Int("retries", 5, "number of times to retry queries")
  27. flagAutoWait = flag.Duration("autowait", 1000*time.Millisecond, "time to wait for autodiscovery to fill the hosts poll")
  28. flagRunSslTest = flag.Bool("runssl", false, "Set to true to run ssl test")
  29. flagRunAuthTest = flag.Bool("runauth", false, "Set to true to run authentication test")
  30. flagCompressTest = flag.String("compressor", "", "compressor to use")
  31. clusterHosts []string
  32. )
  33. func init() {
  34. flag.Parse()
  35. clusterHosts = strings.Split(*flagCluster, ",")
  36. log.SetFlags(log.Lshortfile | log.LstdFlags)
  37. }
  38. func addSslOptions(cluster *ClusterConfig) *ClusterConfig {
  39. if *flagRunSslTest {
  40. cluster.SslOpts = &SslOptions{
  41. CertPath: "testdata/pki/gocql.crt",
  42. KeyPath: "testdata/pki/gocql.key",
  43. CaPath: "testdata/pki/ca.crt",
  44. EnableHostVerification: false,
  45. }
  46. }
  47. return cluster
  48. }
  49. var initOnce sync.Once
  50. func createTable(s *Session, table string) error {
  51. err := s.Query(table).Consistency(All).Exec()
  52. if *clusterSize > 1 {
  53. // wait for table definition to propogate
  54. time.Sleep(1 * time.Second)
  55. }
  56. return err
  57. }
  58. func createCluster() *ClusterConfig {
  59. cluster := NewCluster(clusterHosts...)
  60. cluster.ProtoVersion = *flagProto
  61. cluster.CQLVersion = *flagCQL
  62. cluster.Timeout = 5 * time.Second
  63. cluster.Consistency = Quorum
  64. if *flagRetry > 0 {
  65. cluster.RetryPolicy = &SimpleRetryPolicy{NumRetries: *flagRetry}
  66. }
  67. switch *flagCompressTest {
  68. case "snappy":
  69. cluster.Compressor = &SnappyCompressor{}
  70. case "":
  71. default:
  72. panic("invalid compressor: " + *flagCompressTest)
  73. }
  74. cluster = addSslOptions(cluster)
  75. return cluster
  76. }
  77. func createKeyspace(tb testing.TB, cluster *ClusterConfig, keyspace string) {
  78. session, err := cluster.CreateSession()
  79. if err != nil {
  80. tb.Fatal("createSession:", err)
  81. }
  82. defer session.Close()
  83. if err = session.Query(`DROP KEYSPACE IF EXISTS ` + keyspace).Exec(); err != nil {
  84. tb.Log("drop keyspace:", err)
  85. }
  86. if err := session.Query(fmt.Sprintf(`CREATE KEYSPACE %s
  87. WITH replication = {
  88. 'class' : 'SimpleStrategy',
  89. 'replication_factor' : %d
  90. }`, keyspace, *flagRF)).Consistency(All).Exec(); err != nil {
  91. tb.Fatalf("error creating keyspace %s: %v", keyspace, err)
  92. }
  93. tb.Logf("Created keyspace %s", keyspace)
  94. }
  95. func createSession(tb testing.TB) *Session {
  96. cluster := createCluster()
  97. // Drop and re-create the keyspace once. Different tests should use their own
  98. // individual tables, but can assume that the table does not exist before.
  99. initOnce.Do(func() {
  100. createKeyspace(tb, cluster, "gocql_test")
  101. })
  102. cluster.Keyspace = "gocql_test"
  103. session, err := cluster.CreateSession()
  104. if err != nil {
  105. tb.Fatal("createSession:", err)
  106. }
  107. return session
  108. }
  109. // TestAuthentication verifies that gocql will work with a host configured to only accept authenticated connections
  110. func TestAuthentication(t *testing.T) {
  111. if *flagProto < 2 {
  112. t.Skip("Authentication is not supported with protocol < 2")
  113. }
  114. if !*flagRunAuthTest {
  115. t.Skip("Authentication is not configured in the target cluster")
  116. }
  117. cluster := createCluster()
  118. cluster.Authenticator = PasswordAuthenticator{
  119. Username: "cassandra",
  120. Password: "cassandra",
  121. }
  122. session, err := cluster.CreateSession()
  123. if err != nil {
  124. t.Fatalf("Authentication error: %s", err)
  125. }
  126. session.Close()
  127. }
  128. //TestRingDiscovery makes sure that you can autodiscover other cluster members when you seed a cluster config with just one node
  129. func TestRingDiscovery(t *testing.T) {
  130. cluster := createCluster()
  131. cluster.Hosts = clusterHosts[:1]
  132. cluster.DiscoverHosts = true
  133. session, err := cluster.CreateSession()
  134. if err != nil {
  135. t.Fatalf("got error connecting to the cluster %v", err)
  136. }
  137. if *clusterSize > 1 {
  138. // wait for autodiscovery to update the pool with the list of known hosts
  139. time.Sleep(*flagAutoWait)
  140. }
  141. size := len(session.Pool.(*SimplePool).connPool)
  142. if *clusterSize != size {
  143. t.Logf("WARN: Expected a cluster size of %d, but actual size was %d", *clusterSize, size)
  144. }
  145. session.Close()
  146. }
  147. func TestEmptyHosts(t *testing.T) {
  148. cluster := createCluster()
  149. cluster.Hosts = nil
  150. if session, err := cluster.CreateSession(); err == nil {
  151. session.Close()
  152. t.Error("expected err, got nil")
  153. }
  154. }
  155. //TestUseStatementError checks to make sure the correct error is returned when the user tries to execute a use statement.
  156. func TestUseStatementError(t *testing.T) {
  157. session := createSession(t)
  158. defer session.Close()
  159. if err := session.Query("USE gocql_test").Exec(); err != nil {
  160. if err != ErrUseStmt {
  161. t.Error("expected ErrUseStmt, got " + err.Error())
  162. }
  163. } else {
  164. t.Error("expected err, got nil.")
  165. }
  166. }
  167. //TestInvalidKeyspace checks that an invalid keyspace will return promptly and without a flood of connections
  168. func TestInvalidKeyspace(t *testing.T) {
  169. cluster := createCluster()
  170. cluster.Keyspace = "invalidKeyspace"
  171. session, err := cluster.CreateSession()
  172. if err != nil {
  173. if err != ErrNoConnectionsStarted {
  174. t.Errorf("Expected ErrNoConnections but got %v", err)
  175. }
  176. } else {
  177. session.Close() //Clean up the session
  178. t.Error("expected err, got nil.")
  179. }
  180. }
  181. func TestTracing(t *testing.T) {
  182. session := createSession(t)
  183. defer session.Close()
  184. if err := createTable(session, `CREATE TABLE trace (id int primary key)`); err != nil {
  185. t.Fatal("create:", err)
  186. }
  187. buf := &bytes.Buffer{}
  188. trace := NewTraceWriter(session, buf)
  189. if err := session.Query(`INSERT INTO trace (id) VALUES (?)`, 42).Trace(trace).Exec(); err != nil {
  190. t.Error("insert:", err)
  191. } else if buf.Len() == 0 {
  192. t.Error("insert: failed to obtain any tracing")
  193. }
  194. buf.Reset()
  195. var value int
  196. if err := session.Query(`SELECT id FROM trace WHERE id = ?`, 42).Trace(trace).Scan(&value); err != nil {
  197. t.Error("select:", err)
  198. } else if value != 42 {
  199. t.Errorf("value: expected %d, got %d", 42, value)
  200. } else if buf.Len() == 0 {
  201. t.Error("select: failed to obtain any tracing")
  202. }
  203. }
  204. func TestPaging(t *testing.T) {
  205. if *flagProto == 1 {
  206. t.Skip("Paging not supported. Please use Cassandra >= 2.0")
  207. }
  208. session := createSession(t)
  209. defer session.Close()
  210. if err := createTable(session, "CREATE TABLE paging (id int primary key)"); err != nil {
  211. t.Fatal("create table:", err)
  212. }
  213. for i := 0; i < 100; i++ {
  214. if err := session.Query("INSERT INTO paging (id) VALUES (?)", i).Exec(); err != nil {
  215. t.Fatal("insert:", err)
  216. }
  217. }
  218. iter := session.Query("SELECT id FROM paging").PageSize(10).Iter()
  219. var id int
  220. count := 0
  221. for iter.Scan(&id) {
  222. count++
  223. }
  224. if err := iter.Close(); err != nil {
  225. t.Fatal("close:", err)
  226. }
  227. if count != 100 {
  228. t.Fatalf("expected %d, got %d", 100, count)
  229. }
  230. }
  231. func TestCAS(t *testing.T) {
  232. if *flagProto == 1 {
  233. t.Skip("lightweight transactions not supported. Please use Cassandra >= 2.0")
  234. }
  235. session := createSession(t)
  236. defer session.Close()
  237. if err := createTable(session, `CREATE TABLE cas_table (
  238. title varchar,
  239. revid timeuuid,
  240. last_modified timestamp,
  241. PRIMARY KEY (title, revid)
  242. )`); err != nil {
  243. t.Fatal("create:", err)
  244. }
  245. title, revid, modified := "baz", TimeUUID(), time.Now()
  246. var titleCAS string
  247. var revidCAS UUID
  248. var modifiedCAS time.Time
  249. if applied, err := session.Query(`INSERT INTO cas_table (title, revid, last_modified)
  250. VALUES (?, ?, ?) IF NOT EXISTS`,
  251. title, revid, modified).ScanCAS(&titleCAS, &revidCAS, &modifiedCAS); err != nil {
  252. t.Fatal("insert:", err)
  253. } else if !applied {
  254. t.Fatal("insert should have been applied")
  255. }
  256. if applied, err := session.Query(`INSERT INTO cas_table (title, revid, last_modified)
  257. VALUES (?, ?, ?) IF NOT EXISTS`,
  258. title, revid, modified).ScanCAS(&titleCAS, &revidCAS, &modifiedCAS); err != nil {
  259. t.Fatal("insert:", err)
  260. } else if applied {
  261. t.Fatal("insert should not have been applied")
  262. } else if title != titleCAS || revid != revidCAS {
  263. t.Fatalf("expected %s/%v/%v but got %s/%v/%v", title, revid, modified, titleCAS, revidCAS, modifiedCAS)
  264. }
  265. tenSecondsLater := modified.Add(10 * time.Second)
  266. if applied, err := session.Query(`DELETE FROM cas_table WHERE title = ? and revid = ? IF last_modified = ?`,
  267. title, revid, tenSecondsLater).ScanCAS(&modifiedCAS); err != nil {
  268. t.Fatal("delete:", err)
  269. } else if applied {
  270. t.Fatal("delete should have not been applied")
  271. }
  272. if modifiedCAS.Unix() != tenSecondsLater.Add(-10*time.Second).Unix() {
  273. t.Fatalf("Was expecting modified CAS to be %v; but was one second later", modifiedCAS.UTC())
  274. }
  275. if _, err := session.Query(`DELETE FROM cas_table WHERE title = ? and revid = ? IF last_modified = ?`,
  276. title, revid, tenSecondsLater).ScanCAS(); err.Error() != "count mismatch" {
  277. t.Fatalf("delete: was expecting count mismatch error but got %s", err)
  278. }
  279. if applied, err := session.Query(`DELETE FROM cas_table WHERE title = ? and revid = ? IF last_modified = ?`,
  280. title, revid, modified).ScanCAS(&modifiedCAS); err != nil {
  281. t.Fatal("delete:", err)
  282. } else if !applied {
  283. t.Fatal("delete should have been applied")
  284. }
  285. }
  286. func TestMapScanCAS(t *testing.T) {
  287. if *flagProto == 1 {
  288. t.Skip("lightweight transactions not supported. Please use Cassandra >= 2.0")
  289. }
  290. session := createSession(t)
  291. defer session.Close()
  292. if err := createTable(session, `CREATE TABLE cas_table2 (
  293. title varchar,
  294. revid timeuuid,
  295. last_modified timestamp,
  296. deleted boolean,
  297. PRIMARY KEY (title, revid)
  298. )`); err != nil {
  299. t.Fatal("create:", err)
  300. }
  301. title, revid, modified, deleted := "baz", TimeUUID(), time.Now(), false
  302. mapCAS := map[string]interface{}{}
  303. if applied, err := session.Query(`INSERT INTO cas_table2 (title, revid, last_modified, deleted)
  304. VALUES (?, ?, ?, ?) IF NOT EXISTS`,
  305. title, revid, modified, deleted).MapScanCAS(mapCAS); err != nil {
  306. t.Fatal("insert:", err)
  307. } else if !applied {
  308. t.Fatal("insert should have been applied")
  309. }
  310. mapCAS = map[string]interface{}{}
  311. if applied, err := session.Query(`INSERT INTO cas_table2 (title, revid, last_modified, deleted)
  312. VALUES (?, ?, ?, ?) IF NOT EXISTS`,
  313. title, revid, modified, deleted).MapScanCAS(mapCAS); err != nil {
  314. t.Fatal("insert:", err)
  315. } else if applied {
  316. t.Fatal("insert should not have been applied")
  317. } else if title != mapCAS["title"] || revid != mapCAS["revid"] || deleted != mapCAS["deleted"] {
  318. t.Fatalf("expected %s/%v/%v/%v but got %s/%v/%v%v", title, revid, modified, false, mapCAS["title"], mapCAS["revid"], mapCAS["last_modified"], mapCAS["deleted"])
  319. }
  320. }
  321. func TestBatch(t *testing.T) {
  322. if *flagProto == 1 {
  323. t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
  324. }
  325. session := createSession(t)
  326. defer session.Close()
  327. if err := createTable(session, `CREATE TABLE batch_table (id int primary key)`); err != nil {
  328. t.Fatal("create table:", err)
  329. }
  330. batch := NewBatch(LoggedBatch)
  331. for i := 0; i < 100; i++ {
  332. batch.Query(`INSERT INTO batch_table (id) VALUES (?)`, i)
  333. }
  334. if err := session.ExecuteBatch(batch); err != nil {
  335. t.Fatal("execute batch:", err)
  336. }
  337. count := 0
  338. if err := session.Query(`SELECT COUNT(*) FROM batch_table`).Scan(&count); err != nil {
  339. t.Fatal("select count:", err)
  340. } else if count != 100 {
  341. t.Fatalf("count: expected %d, got %d\n", 100, count)
  342. }
  343. }
  344. // TestBatchLimit tests gocql to make sure batch operations larger than the maximum
  345. // statement limit are not submitted to a cassandra node.
  346. func TestBatchLimit(t *testing.T) {
  347. if *flagProto == 1 {
  348. t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
  349. }
  350. session := createSession(t)
  351. defer session.Close()
  352. if err := createTable(session, `CREATE TABLE batch_table2 (id int primary key)`); err != nil {
  353. t.Fatal("create table:", err)
  354. }
  355. batch := NewBatch(LoggedBatch)
  356. for i := 0; i < 65537; i++ {
  357. batch.Query(`INSERT INTO batch_table2 (id) VALUES (?)`, i)
  358. }
  359. if err := session.ExecuteBatch(batch); err != ErrTooManyStmts {
  360. t.Fatal("gocql attempted to execute a batch larger than the support limit of statements.")
  361. }
  362. }
  363. // TestTooManyQueryArgs tests to make sure the library correctly handles the application level bug
  364. // whereby too many query arguments are passed to a query
  365. func TestTooManyQueryArgs(t *testing.T) {
  366. if *flagProto == 1 {
  367. t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
  368. }
  369. session := createSession(t)
  370. defer session.Close()
  371. if err := createTable(session, `CREATE TABLE too_many_query_args (id int primary key, value int)`); err != nil {
  372. t.Fatal("create table:", err)
  373. }
  374. _, err := session.Query(`SELECT * FROM too_many_query_args WHERE id = ?`, 1, 2).Iter().SliceMap()
  375. if err == nil {
  376. t.Fatal("'`SELECT * FROM too_many_query_args WHERE id = ?`, 1, 2' should return an ErrQueryArgLength")
  377. }
  378. if err != ErrQueryArgLength {
  379. t.Fatalf("'`SELECT * FROM too_many_query_args WHERE id = ?`, 1, 2' should return an ErrQueryArgLength, but returned: %s", err)
  380. }
  381. batch := session.NewBatch(UnloggedBatch)
  382. batch.Query("INSERT INTO too_many_query_args (id, value) VALUES (?, ?)", 1, 2, 3)
  383. err = session.ExecuteBatch(batch)
  384. if err == nil {
  385. t.Fatal("'`INSERT INTO too_many_query_args (id, value) VALUES (?, ?)`, 1, 2, 3' should return an ErrQueryArgLength")
  386. }
  387. if err != ErrQueryArgLength {
  388. t.Fatalf("'INSERT INTO too_many_query_args (id, value) VALUES (?, ?)`, 1, 2, 3' should return an ErrQueryArgLength, but returned: %s", err)
  389. }
  390. }
  391. // TestNotEnoughQueryArgs tests to make sure the library correctly handles the application level bug
  392. // whereby not enough query arguments are passed to a query
  393. func TestNotEnoughQueryArgs(t *testing.T) {
  394. if *flagProto == 1 {
  395. t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
  396. }
  397. session := createSession(t)
  398. defer session.Close()
  399. if err := createTable(session, `CREATE TABLE not_enough_query_args (id int, cluster int, value int, primary key (id, cluster))`); err != nil {
  400. t.Fatal("create table:", err)
  401. }
  402. _, err := session.Query(`SELECT * FROM not_enough_query_args WHERE id = ? and cluster = ?`, 1).Iter().SliceMap()
  403. if err == nil {
  404. t.Fatal("'`SELECT * FROM not_enough_query_args WHERE id = ? and cluster = ?`, 1' should return an ErrQueryArgLength")
  405. }
  406. if err != ErrQueryArgLength {
  407. t.Fatalf("'`SELECT * FROM too_few_query_args WHERE id = ? and cluster = ?`, 1' should return an ErrQueryArgLength, but returned: %s", err)
  408. }
  409. batch := session.NewBatch(UnloggedBatch)
  410. batch.Query("INSERT INTO not_enough_query_args (id, cluster, value) VALUES (?, ?, ?)", 1, 2)
  411. err = session.ExecuteBatch(batch)
  412. if err == nil {
  413. t.Fatal("'`INSERT INTO not_enough_query_args (id, cluster, value) VALUES (?, ?, ?)`, 1, 2' should return an ErrQueryArgLength")
  414. }
  415. if err != ErrQueryArgLength {
  416. t.Fatalf("'INSERT INTO not_enough_query_args (id, cluster, value) VALUES (?, ?, ?)`, 1, 2' should return an ErrQueryArgLength, but returned: %s", err)
  417. }
  418. }
  419. // TestCreateSessionTimeout tests to make sure the CreateSession function timeouts out correctly
  420. // and prevents an infinite loop of connection retries.
  421. func TestCreateSessionTimeout(t *testing.T) {
  422. go func() {
  423. <-time.After(2 * time.Second)
  424. t.Error("no startup timeout")
  425. }()
  426. cluster := createCluster()
  427. cluster.Hosts = []string{"127.0.0.1:1"}
  428. session, err := cluster.CreateSession()
  429. if err == nil {
  430. session.Close()
  431. t.Fatal("expected ErrNoConnectionsStarted, but no error was returned.")
  432. }
  433. if err != ErrNoConnectionsStarted {
  434. t.Fatalf("expected ErrNoConnectionsStarted, but received %v", err)
  435. }
  436. }
  437. type FullName struct {
  438. FirstName string
  439. LastName string
  440. }
  441. func (n FullName) MarshalCQL(info *TypeInfo) ([]byte, error) {
  442. return []byte(n.FirstName + " " + n.LastName), nil
  443. }
  444. func (n *FullName) UnmarshalCQL(info *TypeInfo, data []byte) error {
  445. t := strings.SplitN(string(data), " ", 2)
  446. n.FirstName, n.LastName = t[0], t[1]
  447. return nil
  448. }
  449. func TestMapScanWithRefMap(t *testing.T) {
  450. session := createSession(t)
  451. defer session.Close()
  452. if err := createTable(session, `CREATE TABLE scan_map_ref_table (
  453. testtext text PRIMARY KEY,
  454. testfullname text,
  455. testint int,
  456. )`); err != nil {
  457. t.Fatal("create table:", err)
  458. }
  459. m := make(map[string]interface{})
  460. m["testtext"] = "testtext"
  461. m["testfullname"] = FullName{"John", "Doe"}
  462. m["testint"] = 100
  463. if err := session.Query(`INSERT INTO scan_map_ref_table (testtext, testfullname, testint) values (?,?,?)`, m["testtext"], m["testfullname"], m["testint"]).Exec(); err != nil {
  464. t.Fatal("insert:", err)
  465. }
  466. var testText string
  467. var testFullName FullName
  468. ret := map[string]interface{}{
  469. "testtext": &testText,
  470. "testfullname": &testFullName,
  471. // testint is not set here.
  472. }
  473. iter := session.Query(`SELECT * FROM scan_map_ref_table`).Iter()
  474. if ok := iter.MapScan(ret); !ok {
  475. t.Fatal("select:", iter.Close())
  476. } else {
  477. if ret["testtext"] != "testtext" {
  478. t.Fatal("returned testtext did not match")
  479. }
  480. f := ret["testfullname"].(FullName)
  481. if f.FirstName != "John" || f.LastName != "Doe" {
  482. t.Fatal("returned testfullname did not match")
  483. }
  484. if ret["testint"] != 100 {
  485. t.Fatal("returned testinit did not match")
  486. }
  487. }
  488. }
  489. func TestSliceMap(t *testing.T) {
  490. session := createSession(t)
  491. defer session.Close()
  492. if err := createTable(session, `CREATE TABLE slice_map_table (
  493. testuuid timeuuid PRIMARY KEY,
  494. testtimestamp timestamp,
  495. testvarchar varchar,
  496. testbigint bigint,
  497. testblob blob,
  498. testbool boolean,
  499. testfloat float,
  500. testdouble double,
  501. testint int,
  502. testdecimal decimal,
  503. testlist list<text>,
  504. testset set<int>,
  505. testmap map<varchar, varchar>,
  506. testvarint varint,
  507. testinet inet
  508. )`); err != nil {
  509. t.Fatal("create table:", err)
  510. }
  511. m := make(map[string]interface{})
  512. bigInt := new(big.Int)
  513. if _, ok := bigInt.SetString("830169365738487321165427203929228", 10); !ok {
  514. t.Fatal("Failed setting bigint by string")
  515. }
  516. m["testuuid"] = TimeUUID()
  517. m["testvarchar"] = "Test VarChar"
  518. m["testbigint"] = time.Now().Unix()
  519. m["testtimestamp"] = time.Now().Truncate(time.Millisecond).UTC()
  520. m["testblob"] = []byte("test blob")
  521. m["testbool"] = true
  522. m["testfloat"] = float32(4.564)
  523. m["testdouble"] = float64(4.815162342)
  524. m["testint"] = 2343
  525. m["testdecimal"] = inf.NewDec(100, 0)
  526. m["testlist"] = []string{"quux", "foo", "bar", "baz", "quux"}
  527. m["testset"] = []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
  528. m["testmap"] = map[string]string{"field1": "val1", "field2": "val2", "field3": "val3"}
  529. m["testvarint"] = bigInt
  530. m["testinet"] = "213.212.2.19"
  531. sliceMap := []map[string]interface{}{m}
  532. if err := session.Query(`INSERT INTO slice_map_table (testuuid, testtimestamp, testvarchar, testbigint, testblob, testbool, testfloat, testdouble, testint, testdecimal, testlist, testset, testmap, testvarint, testinet) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
  533. m["testuuid"], m["testtimestamp"], m["testvarchar"], m["testbigint"], m["testblob"], m["testbool"], m["testfloat"], m["testdouble"], m["testint"], m["testdecimal"], m["testlist"], m["testset"], m["testmap"], m["testvarint"], m["testinet"]).Exec(); err != nil {
  534. t.Fatal("insert:", err)
  535. }
  536. if returned, retErr := session.Query(`SELECT * FROM slice_map_table`).Iter().SliceMap(); retErr != nil {
  537. t.Fatal("select:", retErr)
  538. } else {
  539. matchSliceMap(t, sliceMap, returned[0])
  540. }
  541. // Test for Iter.MapScan()
  542. {
  543. testMap := make(map[string]interface{})
  544. if !session.Query(`SELECT * FROM slice_map_table`).Iter().MapScan(testMap) {
  545. t.Fatal("MapScan failed to work with one row")
  546. }
  547. matchSliceMap(t, sliceMap, testMap)
  548. }
  549. // Test for Query.MapScan()
  550. {
  551. testMap := make(map[string]interface{})
  552. if session.Query(`SELECT * FROM slice_map_table`).MapScan(testMap) != nil {
  553. t.Fatal("MapScan failed to work with one row")
  554. }
  555. matchSliceMap(t, sliceMap, testMap)
  556. }
  557. }
  558. func matchSliceMap(t *testing.T, sliceMap []map[string]interface{}, testMap map[string]interface{}) {
  559. if sliceMap[0]["testuuid"] != testMap["testuuid"] {
  560. t.Fatal("returned testuuid did not match")
  561. }
  562. if sliceMap[0]["testtimestamp"] != testMap["testtimestamp"] {
  563. t.Fatal("returned testtimestamp did not match")
  564. }
  565. if sliceMap[0]["testvarchar"] != testMap["testvarchar"] {
  566. t.Fatal("returned testvarchar did not match")
  567. }
  568. if sliceMap[0]["testbigint"] != testMap["testbigint"] {
  569. t.Fatal("returned testbigint did not match")
  570. }
  571. if !reflect.DeepEqual(sliceMap[0]["testblob"], testMap["testblob"]) {
  572. t.Fatal("returned testblob did not match")
  573. }
  574. if sliceMap[0]["testbool"] != testMap["testbool"] {
  575. t.Fatal("returned testbool did not match")
  576. }
  577. if sliceMap[0]["testfloat"] != testMap["testfloat"] {
  578. t.Fatal("returned testfloat did not match")
  579. }
  580. if sliceMap[0]["testdouble"] != testMap["testdouble"] {
  581. t.Fatal("returned testdouble did not match")
  582. }
  583. if sliceMap[0]["testinet"] != testMap["testinet"] {
  584. t.Fatal("returned testinet did not match")
  585. }
  586. expectedDecimal := sliceMap[0]["testdecimal"].(*inf.Dec)
  587. returnedDecimal := testMap["testdecimal"].(*inf.Dec)
  588. if expectedDecimal.Cmp(returnedDecimal) != 0 {
  589. t.Fatal("returned testdecimal did not match")
  590. }
  591. if !reflect.DeepEqual(sliceMap[0]["testlist"], testMap["testlist"]) {
  592. t.Fatal("returned testlist did not match")
  593. }
  594. if !reflect.DeepEqual(sliceMap[0]["testset"], testMap["testset"]) {
  595. t.Fatal("returned testset did not match")
  596. }
  597. if !reflect.DeepEqual(sliceMap[0]["testmap"], testMap["testmap"]) {
  598. t.Fatal("returned testmap did not match")
  599. }
  600. if sliceMap[0]["testint"] != testMap["testint"] {
  601. t.Fatal("returned testint did not match")
  602. }
  603. }
  604. func TestScanWithNilArguments(t *testing.T) {
  605. session := createSession(t)
  606. defer session.Close()
  607. if err := createTable(session, `CREATE TABLE scan_with_nil_arguments (
  608. foo varchar,
  609. bar int,
  610. PRIMARY KEY (foo, bar)
  611. )`); err != nil {
  612. t.Fatal("create:", err)
  613. }
  614. for i := 1; i <= 20; i++ {
  615. if err := session.Query("INSERT INTO scan_with_nil_arguments (foo, bar) VALUES (?, ?)",
  616. "squares", i*i).Exec(); err != nil {
  617. t.Fatal("insert:", err)
  618. }
  619. }
  620. iter := session.Query("SELECT * FROM scan_with_nil_arguments WHERE foo = ?", "squares").Iter()
  621. var n int
  622. count := 0
  623. for iter.Scan(nil, &n) {
  624. count += n
  625. }
  626. if err := iter.Close(); err != nil {
  627. t.Fatal("close:", err)
  628. }
  629. if count != 2870 {
  630. t.Fatalf("expected %d, got %d", 2870, count)
  631. }
  632. }
  633. func TestScanCASWithNilArguments(t *testing.T) {
  634. if *flagProto == 1 {
  635. t.Skip("lightweight transactions not supported. Please use Cassandra >= 2.0")
  636. }
  637. session := createSession(t)
  638. defer session.Close()
  639. if err := createTable(session, `CREATE TABLE scan_cas_with_nil_arguments (
  640. foo varchar,
  641. bar varchar,
  642. PRIMARY KEY (foo, bar)
  643. )`); err != nil {
  644. t.Fatal("create:", err)
  645. }
  646. foo := "baz"
  647. var cas string
  648. if applied, err := session.Query(`INSERT INTO scan_cas_with_nil_arguments (foo, bar)
  649. VALUES (?, ?) IF NOT EXISTS`,
  650. foo, foo).ScanCAS(nil, nil); err != nil {
  651. t.Fatal("insert:", err)
  652. } else if !applied {
  653. t.Fatal("insert should have been applied")
  654. }
  655. if applied, err := session.Query(`INSERT INTO scan_cas_with_nil_arguments (foo, bar)
  656. VALUES (?, ?) IF NOT EXISTS`,
  657. foo, foo).ScanCAS(&cas, nil); err != nil {
  658. t.Fatal("insert:", err)
  659. } else if applied {
  660. t.Fatal("insert should not have been applied")
  661. } else if foo != cas {
  662. t.Fatalf("expected %v but got %v", foo, cas)
  663. }
  664. if applied, err := session.Query(`INSERT INTO scan_cas_with_nil_arguments (foo, bar)
  665. VALUES (?, ?) IF NOT EXISTS`,
  666. foo, foo).ScanCAS(nil, &cas); err != nil {
  667. t.Fatal("insert:", err)
  668. } else if applied {
  669. t.Fatal("insert should not have been applied")
  670. } else if foo != cas {
  671. t.Fatalf("expected %v but got %v", foo, cas)
  672. }
  673. }
  674. func TestRebindQueryInfo(t *testing.T) {
  675. session := createSession(t)
  676. defer session.Close()
  677. if err := createTable(session, "CREATE TABLE rebind_query (id int, value text, PRIMARY KEY (id))"); err != nil {
  678. t.Fatalf("failed to create table with error '%v'", err)
  679. }
  680. if err := session.Query("INSERT INTO rebind_query (id, value) VALUES (?, ?)", 23, "quux").Exec(); err != nil {
  681. t.Fatalf("insert into rebind_query failed, err '%v'", err)
  682. }
  683. if err := session.Query("INSERT INTO rebind_query (id, value) VALUES (?, ?)", 24, "w00t").Exec(); err != nil {
  684. t.Fatalf("insert into rebind_query failed, err '%v'", err)
  685. }
  686. q := session.Query("SELECT value FROM rebind_query WHERE ID = ?")
  687. q.Bind(23)
  688. iter := q.Iter()
  689. var value string
  690. for iter.Scan(&value) {
  691. }
  692. if value != "quux" {
  693. t.Fatalf("expected %v but got %v", "quux", value)
  694. }
  695. q.Bind(24)
  696. iter = q.Iter()
  697. for iter.Scan(&value) {
  698. }
  699. if value != "w00t" {
  700. t.Fatalf("expected %v but got %v", "quux", value)
  701. }
  702. }
  703. //TestStaticQueryInfo makes sure that the application can manually bind query parameters using the simplest possible static binding strategy
  704. func TestStaticQueryInfo(t *testing.T) {
  705. session := createSession(t)
  706. defer session.Close()
  707. if err := createTable(session, "CREATE TABLE static_query_info (id int, value text, PRIMARY KEY (id))"); err != nil {
  708. t.Fatalf("failed to create table with error '%v'", err)
  709. }
  710. if err := session.Query("INSERT INTO static_query_info (id, value) VALUES (?, ?)", 113, "foo").Exec(); err != nil {
  711. t.Fatalf("insert into static_query_info failed, err '%v'", err)
  712. }
  713. autobinder := func(q *QueryInfo) ([]interface{}, error) {
  714. values := make([]interface{}, 1)
  715. values[0] = 113
  716. return values, nil
  717. }
  718. qry := session.Bind("SELECT id, value FROM static_query_info WHERE id = ?", autobinder)
  719. if err := qry.Exec(); err != nil {
  720. t.Fatalf("expose query info failed, error '%v'", err)
  721. }
  722. iter := qry.Iter()
  723. var id int
  724. var value string
  725. iter.Scan(&id, &value)
  726. if err := iter.Close(); err != nil {
  727. t.Fatalf("query with exposed info failed, err '%v'", err)
  728. }
  729. if value != "foo" {
  730. t.Fatalf("Expected value %s, but got %s", "foo", value)
  731. }
  732. }
  733. type ClusteredKeyValue struct {
  734. Id int
  735. Cluster int
  736. Value string
  737. }
  738. func (kv *ClusteredKeyValue) Bind(q *QueryInfo) ([]interface{}, error) {
  739. values := make([]interface{}, len(q.Args))
  740. for i, info := range q.Args {
  741. fieldName := upcaseInitial(info.Name)
  742. value := reflect.ValueOf(kv)
  743. field := reflect.Indirect(value).FieldByName(fieldName)
  744. values[i] = field.Addr().Interface()
  745. }
  746. return values, nil
  747. }
  748. func upcaseInitial(str string) string {
  749. for i, v := range str {
  750. return string(unicode.ToUpper(v)) + str[i+1:]
  751. }
  752. return ""
  753. }
  754. //TestBoundQueryInfo makes sure that the application can manually bind query parameters using the query meta data supplied at runtime
  755. func TestBoundQueryInfo(t *testing.T) {
  756. session := createSession(t)
  757. defer session.Close()
  758. if err := createTable(session, "CREATE TABLE clustered_query_info (id int, cluster int, value text, PRIMARY KEY (id, cluster))"); err != nil {
  759. t.Fatalf("failed to create table with error '%v'", err)
  760. }
  761. write := &ClusteredKeyValue{Id: 200, Cluster: 300, Value: "baz"}
  762. insert := session.Bind("INSERT INTO clustered_query_info (id, cluster, value) VALUES (?, ?,?)", write.Bind)
  763. if err := insert.Exec(); err != nil {
  764. t.Fatalf("insert into clustered_query_info failed, err '%v'", err)
  765. }
  766. read := &ClusteredKeyValue{Id: 200, Cluster: 300}
  767. qry := session.Bind("SELECT id, cluster, value FROM clustered_query_info WHERE id = ? and cluster = ?", read.Bind)
  768. iter := qry.Iter()
  769. var id, cluster int
  770. var value string
  771. iter.Scan(&id, &cluster, &value)
  772. if err := iter.Close(); err != nil {
  773. t.Fatalf("query with clustered_query_info info failed, err '%v'", err)
  774. }
  775. if value != "baz" {
  776. t.Fatalf("Expected value %s, but got %s", "baz", value)
  777. }
  778. }
  779. //TestBatchQueryInfo makes sure that the application can manually bind query parameters when executing in a batch
  780. func TestBatchQueryInfo(t *testing.T) {
  781. if *flagProto == 1 {
  782. t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
  783. }
  784. session := createSession(t)
  785. defer session.Close()
  786. if err := createTable(session, "CREATE TABLE batch_query_info (id int, cluster int, value text, PRIMARY KEY (id, cluster))"); err != nil {
  787. t.Fatalf("failed to create table with error '%v'", err)
  788. }
  789. write := func(q *QueryInfo) ([]interface{}, error) {
  790. values := make([]interface{}, 3)
  791. values[0] = 4000
  792. values[1] = 5000
  793. values[2] = "bar"
  794. return values, nil
  795. }
  796. batch := session.NewBatch(LoggedBatch)
  797. batch.Bind("INSERT INTO batch_query_info (id, cluster, value) VALUES (?, ?,?)", write)
  798. if err := session.ExecuteBatch(batch); err != nil {
  799. t.Fatalf("batch insert into batch_query_info failed, err '%v'", err)
  800. }
  801. read := func(q *QueryInfo) ([]interface{}, error) {
  802. values := make([]interface{}, 2)
  803. values[0] = 4000
  804. values[1] = 5000
  805. return values, nil
  806. }
  807. qry := session.Bind("SELECT id, cluster, value FROM batch_query_info WHERE id = ? and cluster = ?", read)
  808. iter := qry.Iter()
  809. var id, cluster int
  810. var value string
  811. iter.Scan(&id, &cluster, &value)
  812. if err := iter.Close(); err != nil {
  813. t.Fatalf("query with batch_query_info info failed, err '%v'", err)
  814. }
  815. if value != "bar" {
  816. t.Fatalf("Expected value %s, but got %s", "bar", value)
  817. }
  818. }
  819. func injectInvalidPreparedStatement(t *testing.T, session *Session, table string) (string, *Conn) {
  820. if err := createTable(session, `CREATE TABLE `+table+` (
  821. foo varchar,
  822. bar int,
  823. PRIMARY KEY (foo, bar)
  824. )`); err != nil {
  825. t.Fatal("create:", err)
  826. }
  827. stmt := "INSERT INTO " + table + " (foo, bar) VALUES (?, 7)"
  828. conn := session.Pool.Pick(nil)
  829. flight := new(inflightPrepare)
  830. stmtsLRU.Lock()
  831. stmtsLRU.lru.Add(conn.addr+stmt, flight)
  832. stmtsLRU.Unlock()
  833. flight.info = &resultPreparedFrame{
  834. preparedID: []byte{'f', 'o', 'o', 'b', 'a', 'r'},
  835. reqMeta: resultMetadata{
  836. columns: []ColumnInfo{
  837. {
  838. Keyspace: "gocql_test",
  839. Table: table,
  840. Name: "foo",
  841. TypeInfo: &TypeInfo{
  842. Type: TypeVarchar,
  843. },
  844. },
  845. }},
  846. }
  847. return stmt, conn
  848. }
  849. func TestMissingSchemaPrepare(t *testing.T) {
  850. s := createSession(t)
  851. conn := s.Pool.Pick(nil)
  852. defer s.Close()
  853. insertQry := &Query{stmt: "INSERT INTO invalidschemaprep (val) VALUES (?)", values: []interface{}{5}, cons: s.cons,
  854. session: s, pageSize: s.pageSize, trace: s.trace,
  855. prefetch: s.prefetch, rt: s.cfg.RetryPolicy}
  856. if err := conn.executeQuery(insertQry).err; err == nil {
  857. t.Fatal("expected error, but got nil.")
  858. }
  859. if err := createTable(s, "CREATE TABLE invalidschemaprep (val int, PRIMARY KEY (val))"); err != nil {
  860. t.Fatal("create table:", err)
  861. }
  862. if err := conn.executeQuery(insertQry).err; err != nil {
  863. t.Fatal(err) // unconfigured columnfamily
  864. }
  865. }
  866. func TestReprepareStatement(t *testing.T) {
  867. session := createSession(t)
  868. defer session.Close()
  869. stmt, conn := injectInvalidPreparedStatement(t, session, "test_reprepare_statement")
  870. query := session.Query(stmt, "bar")
  871. if err := conn.executeQuery(query).Close(); err != nil {
  872. t.Fatalf("Failed to execute query for reprepare statement: %v", err)
  873. }
  874. }
  875. func TestReprepareBatch(t *testing.T) {
  876. if *flagProto == 1 {
  877. t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
  878. }
  879. session := createSession(t)
  880. defer session.Close()
  881. stmt, conn := injectInvalidPreparedStatement(t, session, "test_reprepare_statement_batch")
  882. batch := session.NewBatch(UnloggedBatch)
  883. batch.Query(stmt, "bar")
  884. if err := conn.executeBatch(batch); err != nil {
  885. t.Fatalf("Failed to execute query for reprepare statement: %v", err)
  886. }
  887. }
  888. func TestQueryInfo(t *testing.T) {
  889. session := createSession(t)
  890. defer session.Close()
  891. conn := session.Pool.Pick(nil)
  892. info, err := conn.prepareStatement("SELECT release_version, host_id FROM system.local WHERE key = ?", nil)
  893. if err != nil {
  894. t.Fatalf("Failed to execute query for preparing statement: %v", err)
  895. }
  896. if len(info.reqMeta.columns) != 1 {
  897. t.Fatalf("Was not expecting meta data for %d query arguments, but got %d\n", 1, len(info.reqMeta.columns))
  898. }
  899. if *flagProto > 1 {
  900. if len(info.respMeta.columns) != 2 {
  901. t.Fatalf("Was not expecting meta data for %d result columns, but got %d\n", 2, len(info.respMeta.columns))
  902. }
  903. }
  904. }
  905. //TestPreparedCacheEviction will make sure that the cache size is maintained
  906. func TestPreparedCacheEviction(t *testing.T) {
  907. session := createSession(t)
  908. defer session.Close()
  909. stmtsLRU.Lock()
  910. stmtsLRU.Max(4)
  911. stmtsLRU.Unlock()
  912. if err := createTable(session, "CREATE TABLE prepcachetest (id int,mod int,PRIMARY KEY (id))"); err != nil {
  913. t.Fatalf("failed to create table with error '%v'", err)
  914. }
  915. //Fill the table
  916. for i := 0; i < 2; i++ {
  917. if err := session.Query("INSERT INTO prepcachetest (id,mod) VALUES (?, ?)", i, 10000%(i+1)).Exec(); err != nil {
  918. t.Fatalf("insert into prepcachetest failed, err '%v'", err)
  919. }
  920. }
  921. //Populate the prepared statement cache with select statements
  922. var id, mod int
  923. for i := 0; i < 2; i++ {
  924. err := session.Query("SELECT id,mod FROM prepcachetest WHERE id = "+strconv.FormatInt(int64(i), 10)).Scan(&id, &mod)
  925. if err != nil {
  926. t.Fatalf("select from prepcachetest failed, error '%v'", err)
  927. }
  928. }
  929. //generate an update statement to test they are prepared
  930. err := session.Query("UPDATE prepcachetest SET mod = ? WHERE id = ?", 1, 11).Exec()
  931. if err != nil {
  932. t.Fatalf("update prepcachetest failed, error '%v'", err)
  933. }
  934. //generate a delete statement to test they are prepared
  935. err = session.Query("DELETE FROM prepcachetest WHERE id = ?", 1).Exec()
  936. if err != nil {
  937. t.Fatalf("delete from prepcachetest failed, error '%v'", err)
  938. }
  939. //generate an insert statement to test they are prepared
  940. err = session.Query("INSERT INTO prepcachetest (id,mod) VALUES (?, ?)", 3, 11).Exec()
  941. if err != nil {
  942. t.Fatalf("insert into prepcachetest failed, error '%v'", err)
  943. }
  944. //Make sure the cache size is maintained
  945. if stmtsLRU.lru.Len() != stmtsLRU.lru.MaxEntries {
  946. t.Fatalf("expected cache size of %v, got %v", stmtsLRU.lru.MaxEntries, stmtsLRU.lru.Len())
  947. }
  948. //Walk through all the configured hosts and test cache retention and eviction
  949. var selFound, insFound, updFound, delFound, selEvict bool
  950. for i := range session.cfg.Hosts {
  951. _, ok := stmtsLRU.lru.Get(session.cfg.Hosts[i] + ":9042gocql_testSELECT id,mod FROM prepcachetest WHERE id = 1")
  952. selFound = selFound || ok
  953. _, ok = stmtsLRU.lru.Get(session.cfg.Hosts[i] + ":9042gocql_testINSERT INTO prepcachetest (id,mod) VALUES (?, ?)")
  954. insFound = insFound || ok
  955. _, ok = stmtsLRU.lru.Get(session.cfg.Hosts[i] + ":9042gocql_testUPDATE prepcachetest SET mod = ? WHERE id = ?")
  956. updFound = updFound || ok
  957. _, ok = stmtsLRU.lru.Get(session.cfg.Hosts[i] + ":9042gocql_testDELETE FROM prepcachetest WHERE id = ?")
  958. delFound = delFound || ok
  959. _, ok = stmtsLRU.lru.Get(session.cfg.Hosts[i] + ":9042gocql_testSELECT id,mod FROM prepcachetest WHERE id = 0")
  960. selEvict = selEvict || !ok
  961. }
  962. if !selEvict {
  963. t.Fatalf("expected first select statement to be purged, but statement was found in the cache.")
  964. }
  965. if !selFound {
  966. t.Fatalf("expected second select statement to be cached, but statement was purged or not prepared.")
  967. }
  968. if !insFound {
  969. t.Fatalf("expected insert statement to be cached, but statement was purged or not prepared.")
  970. }
  971. if !updFound {
  972. t.Fatalf("expected update statement to be cached, but statement was purged or not prepared.")
  973. }
  974. if !delFound {
  975. t.Error("expected delete statement to be cached, but statement was purged or not prepared.")
  976. }
  977. }
  978. func TestPreparedCacheKey(t *testing.T) {
  979. session := createSession(t)
  980. defer session.Close()
  981. // create a second keyspace
  982. cluster2 := createCluster()
  983. createKeyspace(t, cluster2, "gocql_test2")
  984. cluster2.Keyspace = "gocql_test2"
  985. session2, err := cluster2.CreateSession()
  986. if err != nil {
  987. t.Fatal("create session:", err)
  988. }
  989. defer session2.Close()
  990. // both keyspaces have a table named "test_stmt_cache_key"
  991. if err := createTable(session, "CREATE TABLE test_stmt_cache_key (id varchar primary key, field varchar)"); err != nil {
  992. t.Fatal("create table:", err)
  993. }
  994. if err := createTable(session2, "CREATE TABLE test_stmt_cache_key (id varchar primary key, field varchar)"); err != nil {
  995. t.Fatal("create table:", err)
  996. }
  997. // both tables have a single row with the same partition key but different column value
  998. if err = session.Query(`INSERT INTO test_stmt_cache_key (id, field) VALUES (?, ?)`, "key", "one").Exec(); err != nil {
  999. t.Fatal("insert:", err)
  1000. }
  1001. if err = session2.Query(`INSERT INTO test_stmt_cache_key (id, field) VALUES (?, ?)`, "key", "two").Exec(); err != nil {
  1002. t.Fatal("insert:", err)
  1003. }
  1004. // should be able to see different values in each keyspace
  1005. var value string
  1006. if err = session.Query("SELECT field FROM test_stmt_cache_key WHERE id = ?", "key").Scan(&value); err != nil {
  1007. t.Fatal("select:", err)
  1008. }
  1009. if value != "one" {
  1010. t.Errorf("Expected one, got %s", value)
  1011. }
  1012. if err = session2.Query("SELECT field FROM test_stmt_cache_key WHERE id = ?", "key").Scan(&value); err != nil {
  1013. t.Fatal("select:", err)
  1014. }
  1015. if value != "two" {
  1016. t.Errorf("Expected two, got %s", value)
  1017. }
  1018. }
  1019. //TestMarshalFloat64Ptr tests to see that a pointer to a float64 is marshalled correctly.
  1020. func TestMarshalFloat64Ptr(t *testing.T) {
  1021. session := createSession(t)
  1022. defer session.Close()
  1023. if err := createTable(session, "CREATE TABLE float_test (id double, test double, primary key (id))"); err != nil {
  1024. t.Fatal("create table:", err)
  1025. }
  1026. testNum := float64(7500)
  1027. if err := session.Query(`INSERT INTO float_test (id,test) VALUES (?,?)`, float64(7500.00), &testNum).Exec(); err != nil {
  1028. t.Fatal("insert float64:", err)
  1029. }
  1030. }
  1031. //TestMarshalInet tests to see that a pointer to a float64 is marshalled correctly.
  1032. func TestMarshalInet(t *testing.T) {
  1033. session := createSession(t)
  1034. defer session.Close()
  1035. if err := createTable(session, "CREATE TABLE inet_test (ip inet, name text, primary key (ip))"); err != nil {
  1036. t.Fatal("create table:", err)
  1037. }
  1038. stringIp := "123.34.45.56"
  1039. if err := session.Query(`INSERT INTO inet_test (ip,name) VALUES (?,?)`, stringIp, "Test IP 1").Exec(); err != nil {
  1040. t.Fatal("insert string inet:", err)
  1041. }
  1042. var stringResult string
  1043. if err := session.Query("SELECT ip FROM inet_test").Scan(&stringResult); err != nil {
  1044. t.Fatalf("select for string from inet_test 1 failed: %v", err)
  1045. }
  1046. if stringResult != stringIp {
  1047. t.Errorf("Expected %s, was %s", stringIp, stringResult)
  1048. }
  1049. var ipResult net.IP
  1050. if err := session.Query("SELECT ip FROM inet_test").Scan(&ipResult); err != nil {
  1051. t.Fatalf("select for net.IP from inet_test 1 failed: %v", err)
  1052. }
  1053. if ipResult.String() != stringIp {
  1054. t.Errorf("Expected %s, was %s", stringIp, ipResult.String())
  1055. }
  1056. if err := session.Query(`DELETE FROM inet_test WHERE ip = ?`, stringIp).Exec(); err != nil {
  1057. t.Fatal("delete inet table:", err)
  1058. }
  1059. netIp := net.ParseIP("222.43.54.65")
  1060. if err := session.Query(`INSERT INTO inet_test (ip,name) VALUES (?,?)`, netIp, "Test IP 2").Exec(); err != nil {
  1061. t.Fatal("insert netIp inet:", err)
  1062. }
  1063. if err := session.Query("SELECT ip FROM inet_test").Scan(&stringResult); err != nil {
  1064. t.Fatalf("select for string from inet_test 2 failed: %v", err)
  1065. }
  1066. if stringResult != netIp.String() {
  1067. t.Errorf("Expected %s, was %s", netIp.String(), stringResult)
  1068. }
  1069. if err := session.Query("SELECT ip FROM inet_test").Scan(&ipResult); err != nil {
  1070. t.Fatalf("select for net.IP from inet_test 2 failed: %v", err)
  1071. }
  1072. if ipResult.String() != netIp.String() {
  1073. t.Errorf("Expected %s, was %s", netIp.String(), ipResult.String())
  1074. }
  1075. }
  1076. func TestVarint(t *testing.T) {
  1077. session := createSession(t)
  1078. defer session.Close()
  1079. if err := createTable(session, "CREATE TABLE varint_test (id varchar, test varint, test2 varint, primary key (id))"); err != nil {
  1080. t.Fatalf("failed to create table with error '%v'", err)
  1081. }
  1082. if err := session.Query(`INSERT INTO varint_test (id, test) VALUES (?, ?)`, "id", 0).Exec(); err != nil {
  1083. t.Fatalf("insert varint: %v", err)
  1084. }
  1085. var result int
  1086. if err := session.Query("SELECT test FROM varint_test").Scan(&result); err != nil {
  1087. t.Fatalf("select from varint_test failed: %v", err)
  1088. }
  1089. if result != 0 {
  1090. t.Errorf("Expected 0, was %d", result)
  1091. }
  1092. if err := session.Query(`INSERT INTO varint_test (id, test) VALUES (?, ?)`, "id", -1).Exec(); err != nil {
  1093. t.Fatalf("insert varint: %v", err)
  1094. }
  1095. if err := session.Query("SELECT test FROM varint_test").Scan(&result); err != nil {
  1096. t.Fatalf("select from varint_test failed: %v", err)
  1097. }
  1098. if result != -1 {
  1099. t.Errorf("Expected -1, was %d", result)
  1100. }
  1101. if err := session.Query(`INSERT INTO varint_test (id, test) VALUES (?, ?)`, "id", int64(math.MaxInt32)+1).Exec(); err != nil {
  1102. t.Fatalf("insert varint: %v", err)
  1103. }
  1104. var result64 int64
  1105. if err := session.Query("SELECT test FROM varint_test").Scan(&result64); err != nil {
  1106. t.Fatalf("select from varint_test failed: %v", err)
  1107. }
  1108. if result64 != int64(math.MaxInt32)+1 {
  1109. t.Errorf("Expected %d, was %d", int64(math.MaxInt32)+1, result64)
  1110. }
  1111. biggie := new(big.Int)
  1112. biggie.SetString("36893488147419103232", 10) // > 2**64
  1113. if err := session.Query(`INSERT INTO varint_test (id, test) VALUES (?, ?)`, "id", biggie).Exec(); err != nil {
  1114. t.Fatalf("insert varint: %v", err)
  1115. }
  1116. resultBig := new(big.Int)
  1117. if err := session.Query("SELECT test FROM varint_test").Scan(resultBig); err != nil {
  1118. t.Fatalf("select from varint_test failed: %v", err)
  1119. }
  1120. if resultBig.String() != biggie.String() {
  1121. t.Errorf("Expected %s, was %s", biggie.String(), resultBig.String())
  1122. }
  1123. err := session.Query("SELECT test FROM varint_test").Scan(&result64)
  1124. if err == nil || strings.Index(err.Error(), "out of range") == -1 {
  1125. t.Errorf("expected out of range error since value is too big for int64")
  1126. }
  1127. // value not set in cassandra, leave bind variable empty
  1128. resultBig = new(big.Int)
  1129. if err := session.Query("SELECT test2 FROM varint_test").Scan(resultBig); err != nil {
  1130. t.Fatalf("select from varint_test failed: %v", err)
  1131. }
  1132. if resultBig.Int64() != 0 {
  1133. t.Errorf("Expected %s, was %s", biggie.String(), resultBig.String())
  1134. }
  1135. // can use double pointer to explicitly detect value is not set in cassandra
  1136. if err := session.Query("SELECT test2 FROM varint_test").Scan(&resultBig); err != nil {
  1137. t.Fatalf("select from varint_test failed: %v", err)
  1138. }
  1139. if resultBig != nil {
  1140. t.Errorf("Expected %v, was %v", nil, *resultBig)
  1141. }
  1142. }
  1143. //TestQueryStats confirms that the stats are returning valid data. Accuracy may be questionable.
  1144. func TestQueryStats(t *testing.T) {
  1145. session := createSession(t)
  1146. defer session.Close()
  1147. qry := session.Query("SELECT * FROM system.peers")
  1148. if err := qry.Exec(); err != nil {
  1149. t.Fatalf("query failed. %v", err)
  1150. } else {
  1151. if qry.Attempts() < 1 {
  1152. t.Fatal("expected at least 1 attempt, but got 0")
  1153. }
  1154. if qry.Latency() <= 0 {
  1155. t.Fatalf("expected latency to be greater than 0, but got %v instead.", qry.Latency())
  1156. }
  1157. }
  1158. }
  1159. //TestBatchStats confirms that the stats are returning valid data. Accuracy may be questionable.
  1160. func TestBatchStats(t *testing.T) {
  1161. if *flagProto == 1 {
  1162. t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
  1163. }
  1164. session := createSession(t)
  1165. defer session.Close()
  1166. if err := createTable(session, "CREATE TABLE batchStats (id int, PRIMARY KEY (id))"); err != nil {
  1167. t.Fatalf("failed to create table with error '%v'", err)
  1168. }
  1169. b := session.NewBatch(LoggedBatch)
  1170. b.Query("INSERT INTO batchStats (id) VALUES (?)", 1)
  1171. b.Query("INSERT INTO batchStats (id) VALUES (?)", 2)
  1172. if err := session.ExecuteBatch(b); err != nil {
  1173. t.Fatalf("query failed. %v", err)
  1174. } else {
  1175. if b.Attempts() < 1 {
  1176. t.Fatal("expected at least 1 attempt, but got 0")
  1177. }
  1178. if b.Latency() <= 0 {
  1179. t.Fatalf("expected latency to be greater than 0, but got %v instead.", b.Latency())
  1180. }
  1181. }
  1182. }
  1183. //TestNilInQuery tests to see that a nil value passed to a query is handled by Cassandra
  1184. //TODO validate the nil value by reading back the nil. Need to fix Unmarshalling.
  1185. func TestNilInQuery(t *testing.T) {
  1186. session := createSession(t)
  1187. defer session.Close()
  1188. if err := createTable(session, "CREATE TABLE testNilInsert (id int, count int, PRIMARY KEY (id))"); err != nil {
  1189. t.Fatalf("failed to create table with error '%v'", err)
  1190. }
  1191. if err := session.Query("INSERT INTO testNilInsert (id,count) VALUES (?,?)", 1, nil).Exec(); err != nil {
  1192. t.Fatalf("failed to insert with err: %v", err)
  1193. }
  1194. var id int
  1195. if err := session.Query("SELECT id FROM testNilInsert").Scan(&id); err != nil {
  1196. t.Fatalf("failed to select with err: %v", err)
  1197. } else if id != 1 {
  1198. t.Fatalf("expected id to be 1, got %v", id)
  1199. }
  1200. }
  1201. // Don't initialize time.Time bind variable if cassandra timestamp column is empty
  1202. func TestEmptyTimestamp(t *testing.T) {
  1203. session := createSession(t)
  1204. defer session.Close()
  1205. if err := createTable(session, "CREATE TABLE test_empty_timestamp (id int, time timestamp, num int, PRIMARY KEY (id))"); err != nil {
  1206. t.Fatalf("failed to create table with error '%v'", err)
  1207. }
  1208. if err := session.Query("INSERT INTO test_empty_timestamp (id, num) VALUES (?,?)", 1, 561).Exec(); err != nil {
  1209. t.Fatalf("failed to insert with err: %v", err)
  1210. }
  1211. var timeVal time.Time
  1212. if err := session.Query("SELECT time FROM test_empty_timestamp where id = ?", 1).Scan(&timeVal); err != nil {
  1213. t.Fatalf("failed to select with err: %v", err)
  1214. }
  1215. if !timeVal.IsZero() {
  1216. t.Errorf("time.Time bind variable should still be empty (was %s)", timeVal)
  1217. }
  1218. }
  1219. func TestGetKeyspaceMetadata(t *testing.T) {
  1220. session := createSession(t)
  1221. defer session.Close()
  1222. keyspaceMetadata, err := getKeyspaceMetadata(session, "gocql_test")
  1223. if err != nil {
  1224. t.Fatalf("failed to query the keyspace metadata with err: %v", err)
  1225. }
  1226. if keyspaceMetadata == nil {
  1227. t.Fatal("failed to query the keyspace metadata, nil returned")
  1228. }
  1229. if keyspaceMetadata.Name != "gocql_test" {
  1230. t.Errorf("Expected keyspace name to be 'gocql' but was '%s'", keyspaceMetadata.Name)
  1231. }
  1232. if keyspaceMetadata.StrategyClass != "org.apache.cassandra.locator.SimpleStrategy" {
  1233. t.Errorf("Expected replication strategy class to be 'org.apache.cassandra.locator.SimpleStrategy' but was '%s'", keyspaceMetadata.StrategyClass)
  1234. }
  1235. if keyspaceMetadata.StrategyOptions == nil {
  1236. t.Error("Expected replication strategy options map but was nil")
  1237. }
  1238. rfStr, ok := keyspaceMetadata.StrategyOptions["replication_factor"]
  1239. if !ok {
  1240. t.Fatalf("Expected strategy option 'replication_factor' but was not found in %v", keyspaceMetadata.StrategyOptions)
  1241. }
  1242. rfInt, err := strconv.Atoi(rfStr.(string))
  1243. if err != nil {
  1244. t.Fatalf("Error converting string to int with err: %v", err)
  1245. }
  1246. if rfInt != *flagRF {
  1247. t.Errorf("Expected replication factor to be %d but was %d", *flagRF, rfInt)
  1248. }
  1249. }
  1250. func TestGetTableMetadata(t *testing.T) {
  1251. session := createSession(t)
  1252. defer session.Close()
  1253. if err := createTable(session, "CREATE TABLE test_table_metadata (first_id int, second_id int, third_id int, PRIMARY KEY (first_id, second_id))"); err != nil {
  1254. t.Fatalf("failed to create table with error '%v'", err)
  1255. }
  1256. tables, err := getTableMetadata(session, "gocql_test")
  1257. if err != nil {
  1258. t.Fatalf("failed to query the table metadata with err: %v", err)
  1259. }
  1260. if tables == nil {
  1261. t.Fatal("failed to query the table metadata, nil returned")
  1262. }
  1263. var testTable *TableMetadata
  1264. // verify all tables have minimum expected data
  1265. for i := range tables {
  1266. table := &tables[i]
  1267. if table.Name == "" {
  1268. t.Errorf("Expected table name to be set, but it was empty: index=%d metadata=%+v", i, table)
  1269. }
  1270. if table.Keyspace != "gocql_test" {
  1271. t.Errorf("Expected keyspace for '%d' table metadata to be 'gocql_test' but was '%s'", table.Name, table.Keyspace)
  1272. }
  1273. if table.KeyValidator == "" {
  1274. t.Errorf("Expected key validator to be set for table %s", table.Name)
  1275. }
  1276. if table.Comparator == "" {
  1277. t.Errorf("Expected comparator to be set for table %s", table.Name)
  1278. }
  1279. if table.DefaultValidator == "" {
  1280. t.Errorf("Expected default validator to be set for table %s", table.Name)
  1281. }
  1282. // these fields are not set until the metadata is compiled
  1283. if table.PartitionKey != nil {
  1284. t.Errorf("Did not expect partition key for table %s", table.Name)
  1285. }
  1286. if table.ClusteringColumns != nil {
  1287. t.Errorf("Did not expect clustering columns for table %s", table.Name)
  1288. }
  1289. if table.Columns != nil {
  1290. t.Errorf("Did not expect columns for table %s", table.Name)
  1291. }
  1292. // for the next part of the test after this loop, find the metadata for the test table
  1293. if table.Name == "test_table_metadata" {
  1294. testTable = table
  1295. }
  1296. }
  1297. // verify actual values on the test tables
  1298. if testTable == nil {
  1299. t.Fatal("Expected table metadata for name 'test_table_metadata'")
  1300. }
  1301. if testTable.KeyValidator != "org.apache.cassandra.db.marshal.Int32Type" {
  1302. t.Errorf("Expected test_table_metadata key validator to be 'org.apache.cassandra.db.marshal.Int32Type' but was '%s'", testTable.KeyValidator)
  1303. }
  1304. if testTable.Comparator != "org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.Int32Type,org.apache.cassandra.db.marshal.UTF8Type)" {
  1305. t.Errorf("Expected test_table_metadata key validator to be 'org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.Int32Type,org.apache.cassandra.db.marshal.UTF8Type)' but was '%s'", testTable.Comparator)
  1306. }
  1307. if testTable.DefaultValidator != "org.apache.cassandra.db.marshal.BytesType" {
  1308. t.Errorf("Expected test_table_metadata key validator to be 'org.apache.cassandra.db.marshal.BytesType' but was '%s'", testTable.DefaultValidator)
  1309. }
  1310. expectedKeyAliases := []string{"first_id"}
  1311. if !reflect.DeepEqual(testTable.KeyAliases, expectedKeyAliases) {
  1312. t.Errorf("Expected key aliases %v but was %v", expectedKeyAliases, testTable.KeyAliases)
  1313. }
  1314. expectedColumnAliases := []string{"second_id"}
  1315. if !reflect.DeepEqual(testTable.ColumnAliases, expectedColumnAliases) {
  1316. t.Errorf("Expected key aliases %v but was %v", expectedColumnAliases, testTable.ColumnAliases)
  1317. }
  1318. if testTable.ValueAlias != "" {
  1319. t.Errorf("Expected value alias '' but was '%s'", testTable.ValueAlias)
  1320. }
  1321. }
  1322. func TestGetColumnMetadata(t *testing.T) {
  1323. session := createSession(t)
  1324. defer session.Close()
  1325. if err := createTable(session, "CREATE TABLE test_column_metadata (first_id int, second_id int, third_id int, PRIMARY KEY (first_id, second_id))"); err != nil {
  1326. t.Fatalf("failed to create table with error '%v'", err)
  1327. }
  1328. if err := session.Query("CREATE INDEX index_column_metadata ON test_column_metadata ( third_id )").Exec(); err != nil {
  1329. t.Fatalf("failed to create index with err: %v", err)
  1330. }
  1331. columns, err := getColumnMetadata(session, "gocql_test")
  1332. if err != nil {
  1333. t.Fatalf("failed to query column metadata with err: %v", err)
  1334. }
  1335. if columns == nil {
  1336. t.Fatal("failed to query column metadata, nil returned")
  1337. }
  1338. testColumns := map[string]*ColumnMetadata{}
  1339. // verify actual values on the test columns
  1340. for i := range columns {
  1341. column := &columns[i]
  1342. if column.Name == "" {
  1343. t.Errorf("Expected column name to be set, but it was empty: index=%d metadata=%+v", i, column)
  1344. }
  1345. if column.Table == "" {
  1346. t.Errorf("Expected column %s table name to be set, but it was empty", column.Name)
  1347. }
  1348. if column.Keyspace != "gocql_test" {
  1349. t.Errorf("Expected column %s keyspace name to be 'gocql_test', but it was '%s'", column.Name, column.Keyspace)
  1350. }
  1351. if column.Kind == "" {
  1352. t.Errorf("Expected column %s kind to be set, but it was empty", column.Name)
  1353. }
  1354. if session.cfg.ProtoVersion == 1 && column.Kind != "regular" {
  1355. t.Errorf("Expected column %s kind to be set to 'regular' for proto V1 but it was '%s'", column.Name, column.Kind)
  1356. }
  1357. if column.Validator == "" {
  1358. t.Errorf("Expected column %s validator to be set, but it was empty", column.Name)
  1359. }
  1360. // find the test table columns for the next step after this loop
  1361. if column.Table == "test_column_metadata" {
  1362. testColumns[column.Name] = column
  1363. }
  1364. }
  1365. if *flagProto == 1 {
  1366. // V1 proto only returns "regular columns"
  1367. if len(testColumns) != 1 {
  1368. t.Errorf("Expected 1 test columns but there were %d", len(testColumns))
  1369. }
  1370. thirdID, found := testColumns["third_id"]
  1371. if !found {
  1372. t.Fatalf("Expected to find column 'third_id' metadata but there was only %v", testColumns)
  1373. }
  1374. if thirdID.Kind != REGULAR {
  1375. t.Errorf("Expected %s column kind to be '%s' but it was '%s'", thirdID.Name, REGULAR, thirdID.Kind)
  1376. }
  1377. if thirdID.Index.Name != "index_column_metadata" {
  1378. t.Errorf("Expected %s column index name to be 'index_column_metadata' but it was '%s'", thirdID.Name, thirdID.Index.Name)
  1379. }
  1380. } else {
  1381. if len(testColumns) != 3 {
  1382. t.Errorf("Expected 3 test columns but there were %d", len(testColumns))
  1383. }
  1384. firstID, found := testColumns["first_id"]
  1385. if !found {
  1386. t.Fatalf("Expected to find column 'first_id' metadata but there was only %v", testColumns)
  1387. }
  1388. secondID, found := testColumns["second_id"]
  1389. if !found {
  1390. t.Fatalf("Expected to find column 'second_id' metadata but there was only %v", testColumns)
  1391. }
  1392. thirdID, found := testColumns["third_id"]
  1393. if !found {
  1394. t.Fatalf("Expected to find column 'third_id' metadata but there was only %v", testColumns)
  1395. }
  1396. if firstID.Kind != PARTITION_KEY {
  1397. t.Errorf("Expected %s column kind to be '%s' but it was '%s'", firstID.Name, PARTITION_KEY, firstID.Kind)
  1398. }
  1399. if secondID.Kind != CLUSTERING_KEY {
  1400. t.Errorf("Expected %s column kind to be '%s' but it was '%s'", secondID.Name, CLUSTERING_KEY, secondID.Kind)
  1401. }
  1402. if thirdID.Kind != REGULAR {
  1403. t.Errorf("Expected %s column kind to be '%s' but it was '%s'", thirdID.Name, REGULAR, thirdID.Kind)
  1404. }
  1405. if thirdID.Index.Name != "index_column_metadata" {
  1406. t.Errorf("Expected %s column index name to be 'index_column_metadata' but it was '%s'", thirdID.Name, thirdID.Index.Name)
  1407. }
  1408. }
  1409. }
  1410. func TestKeyspaceMetadata(t *testing.T) {
  1411. session := createSession(t)
  1412. defer session.Close()
  1413. if err := createTable(session, "CREATE TABLE test_metadata (first_id int, second_id int, third_id int, PRIMARY KEY (first_id, second_id))"); err != nil {
  1414. t.Fatalf("failed to create table with error '%v'", err)
  1415. }
  1416. if err := session.Query("CREATE INDEX index_metadata ON test_metadata ( third_id )").Exec(); err != nil {
  1417. t.Fatalf("failed to create index with err: %v", err)
  1418. }
  1419. keyspaceMetadata, err := session.KeyspaceMetadata("gocql_test")
  1420. if err != nil {
  1421. t.Fatalf("failed to query keyspace metadata with err: %v", err)
  1422. }
  1423. if keyspaceMetadata == nil {
  1424. t.Fatal("expected the keyspace metadata to not be nil, but it was nil")
  1425. }
  1426. if keyspaceMetadata.Name != session.cfg.Keyspace {
  1427. t.Fatalf("Expected the keyspace name to be %s but was %s", session.cfg.Keyspace, keyspaceMetadata.Name)
  1428. }
  1429. if len(keyspaceMetadata.Tables) == 0 {
  1430. t.Errorf("Expected tables but there were none")
  1431. }
  1432. tableMetadata, found := keyspaceMetadata.Tables["test_metadata"]
  1433. if !found {
  1434. t.Fatalf("failed to find the test_metadata table metadata")
  1435. }
  1436. if len(tableMetadata.PartitionKey) != 1 {
  1437. t.Errorf("expected partition key length of 1, but was %d", len(tableMetadata.PartitionKey))
  1438. }
  1439. for i, column := range tableMetadata.PartitionKey {
  1440. if column == nil {
  1441. t.Errorf("partition key column metadata at index %d was nil", i)
  1442. }
  1443. }
  1444. if tableMetadata.PartitionKey[0].Name != "first_id" {
  1445. t.Errorf("Expected the first partition key column to be 'first_id' but was '%s'", tableMetadata.PartitionKey[0].Name)
  1446. }
  1447. if len(tableMetadata.ClusteringColumns) != 1 {
  1448. t.Fatalf("expected clustering columns length of 1, but was %d", len(tableMetadata.ClusteringColumns))
  1449. }
  1450. for i, column := range tableMetadata.ClusteringColumns {
  1451. if column == nil {
  1452. t.Fatalf("clustering column metadata at index %d was nil", i)
  1453. }
  1454. }
  1455. if tableMetadata.ClusteringColumns[0].Name != "second_id" {
  1456. t.Errorf("Expected the first clustering column to be 'second_id' but was '%s'", tableMetadata.ClusteringColumns[0].Name)
  1457. }
  1458. thirdColumn, found := tableMetadata.Columns["third_id"]
  1459. if !found {
  1460. t.Fatalf("Expected a column definition for 'third_id'")
  1461. }
  1462. if thirdColumn.Index.Name != "index_metadata" {
  1463. t.Errorf("Expected column index named 'index_metadata' but was '%s'", thirdColumn.Index.Name)
  1464. }
  1465. }
  1466. func TestRoutingKey(t *testing.T) {
  1467. session := createSession(t)
  1468. defer session.Close()
  1469. if err := createTable(session, "CREATE TABLE test_single_routing_key (first_id int, second_id int, PRIMARY KEY (first_id, second_id))"); err != nil {
  1470. t.Fatalf("failed to create table with error '%v'", err)
  1471. }
  1472. if err := createTable(session, "CREATE TABLE test_composite_routing_key (first_id int, second_id int, PRIMARY KEY ((first_id, second_id)))"); err != nil {
  1473. t.Fatalf("failed to create table with error '%v'", err)
  1474. }
  1475. routingKeyInfo, err := session.routingKeyInfo("SELECT * FROM test_single_routing_key WHERE second_id=? AND first_id=?")
  1476. if err != nil {
  1477. t.Fatalf("failed to get routing key info due to error: %v", err)
  1478. }
  1479. if routingKeyInfo == nil {
  1480. t.Fatal("Expected routing key info, but was nil")
  1481. }
  1482. if len(routingKeyInfo.indexes) != 1 {
  1483. t.Fatalf("Expected routing key indexes length to be 1 but was %d", len(routingKeyInfo.indexes))
  1484. }
  1485. if routingKeyInfo.indexes[0] != 1 {
  1486. t.Errorf("Expected routing key index[0] to be 1 but was %d", routingKeyInfo.indexes[0])
  1487. }
  1488. if len(routingKeyInfo.types) != 1 {
  1489. t.Fatalf("Expected routing key types length to be 1 but was %d", len(routingKeyInfo.types))
  1490. }
  1491. if routingKeyInfo.types[0] == nil {
  1492. t.Fatal("Expected routing key types[0] to be non-nil")
  1493. }
  1494. if routingKeyInfo.types[0].Type != TypeInt {
  1495. t.Fatalf("Expected routing key types[0].Type to be %v but was %v", TypeInt, routingKeyInfo.types[0])
  1496. }
  1497. // verify the cache is working
  1498. routingKeyInfo, err = session.routingKeyInfo("SELECT * FROM test_single_routing_key WHERE second_id=? AND first_id=?")
  1499. if err != nil {
  1500. t.Fatalf("failed to get routing key info due to error: %v", err)
  1501. }
  1502. if len(routingKeyInfo.indexes) != 1 {
  1503. t.Fatalf("Expected routing key indexes length to be 1 but was %d", len(routingKeyInfo.indexes))
  1504. }
  1505. if routingKeyInfo.indexes[0] != 1 {
  1506. t.Errorf("Expected routing key index[0] to be 1 but was %d", routingKeyInfo.indexes[0])
  1507. }
  1508. if len(routingKeyInfo.types) != 1 {
  1509. t.Fatalf("Expected routing key types length to be 1 but was %d", len(routingKeyInfo.types))
  1510. }
  1511. if routingKeyInfo.types[0] == nil {
  1512. t.Fatal("Expected routing key types[0] to be non-nil")
  1513. }
  1514. if routingKeyInfo.types[0].Type != TypeInt {
  1515. t.Fatalf("Expected routing key types[0] to be %v but was %v", TypeInt, routingKeyInfo.types[0])
  1516. }
  1517. cacheSize := session.routingKeyInfoCache.lru.Len()
  1518. if cacheSize != 1 {
  1519. t.Errorf("Expected cache size to be 1 but was %d", cacheSize)
  1520. }
  1521. query := session.Query("SELECT * FROM test_single_routing_key WHERE second_id=? AND first_id=?", 1, 2)
  1522. routingKey, err := query.GetRoutingKey()
  1523. if err != nil {
  1524. t.Fatalf("Failed to get routing key due to error: %v", err)
  1525. }
  1526. expectedRoutingKey := []byte{0, 0, 0, 2}
  1527. if !reflect.DeepEqual(expectedRoutingKey, routingKey) {
  1528. t.Errorf("Expected routing key %v but was %v", expectedRoutingKey, routingKey)
  1529. }
  1530. routingKeyInfo, err = session.routingKeyInfo("SELECT * FROM test_composite_routing_key WHERE second_id=? AND first_id=?")
  1531. if err != nil {
  1532. t.Fatalf("failed to get routing key info due to error: %v", err)
  1533. }
  1534. if routingKeyInfo == nil {
  1535. t.Fatal("Expected routing key info, but was nil")
  1536. }
  1537. if len(routingKeyInfo.indexes) != 2 {
  1538. t.Fatalf("Expected routing key indexes length to be 2 but was %d", len(routingKeyInfo.indexes))
  1539. }
  1540. if routingKeyInfo.indexes[0] != 1 {
  1541. t.Errorf("Expected routing key index[0] to be 1 but was %d", routingKeyInfo.indexes[0])
  1542. }
  1543. if routingKeyInfo.indexes[1] != 0 {
  1544. t.Errorf("Expected routing key index[1] to be 0 but was %d", routingKeyInfo.indexes[1])
  1545. }
  1546. if len(routingKeyInfo.types) != 2 {
  1547. t.Fatalf("Expected routing key types length to be 1 but was %d", len(routingKeyInfo.types))
  1548. }
  1549. if routingKeyInfo.types[0] == nil {
  1550. t.Fatal("Expected routing key types[0] to be non-nil")
  1551. }
  1552. if routingKeyInfo.types[0].Type != TypeInt {
  1553. t.Fatalf("Expected routing key types[0] to be %v but was %v", TypeInt, routingKeyInfo.types[0])
  1554. }
  1555. if routingKeyInfo.types[1] == nil {
  1556. t.Fatal("Expected routing key types[1] to be non-nil")
  1557. }
  1558. if routingKeyInfo.types[1].Type != TypeInt {
  1559. t.Fatalf("Expected routing key types[0] to be %v but was %v", TypeInt, routingKeyInfo.types[1])
  1560. }
  1561. query = session.Query("SELECT * FROM test_composite_routing_key WHERE second_id=? AND first_id=?", 1, 2)
  1562. routingKey, err = query.GetRoutingKey()
  1563. if err != nil {
  1564. t.Fatalf("Failed to get routing key due to error: %v", err)
  1565. }
  1566. expectedRoutingKey = []byte{0, 4, 0, 0, 0, 2, 0, 0, 4, 0, 0, 0, 1, 0}
  1567. if !reflect.DeepEqual(expectedRoutingKey, routingKey) {
  1568. t.Errorf("Expected routing key %v but was %v", expectedRoutingKey, routingKey)
  1569. }
  1570. // verify the cache is working
  1571. cacheSize = session.routingKeyInfoCache.lru.Len()
  1572. if cacheSize != 2 {
  1573. t.Errorf("Expected cache size to be 2 but was %d", cacheSize)
  1574. }
  1575. }