cassandra_test.go 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297
  1. // +build all integration
  2. package gocql
  3. import (
  4. "bytes"
  5. "io"
  6. "math"
  7. "math/big"
  8. "net"
  9. "reflect"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "testing"
  14. "time"
  15. "unicode"
  16. "gopkg.in/inf.v0"
  17. )
  18. // TestAuthentication verifies that gocql will work with a host configured to only accept authenticated connections
  19. func TestAuthentication(t *testing.T) {
  20. if *flagProto < 2 {
  21. t.Skip("Authentication is not supported with protocol < 2")
  22. }
  23. if !*flagRunAuthTest {
  24. t.Skip("Authentication is not configured in the target cluster")
  25. }
  26. cluster := createCluster()
  27. cluster.Authenticator = PasswordAuthenticator{
  28. Username: "cassandra",
  29. Password: "cassandra",
  30. }
  31. session, err := cluster.CreateSession()
  32. if err != nil {
  33. t.Fatalf("Authentication error: %s", err)
  34. }
  35. session.Close()
  36. }
  37. //TestRingDiscovery makes sure that you can autodiscover other cluster members when you seed a cluster config with just one node
  38. func TestRingDiscovery(t *testing.T) {
  39. cluster := createCluster()
  40. cluster.Hosts = clusterHosts[:1]
  41. session := createSessionFromCluster(cluster, t)
  42. defer session.Close()
  43. if *clusterSize > 1 {
  44. // wait for autodiscovery to update the pool with the list of known hosts
  45. time.Sleep(*flagAutoWait)
  46. }
  47. session.pool.mu.RLock()
  48. size := len(session.pool.hostConnPools)
  49. session.pool.mu.RUnlock()
  50. if *clusterSize != size {
  51. t.Fatalf("Expected a cluster size of %d, but actual size was %d", *clusterSize, size)
  52. }
  53. }
  54. func TestEmptyHosts(t *testing.T) {
  55. cluster := createCluster()
  56. cluster.Hosts = nil
  57. if session, err := cluster.CreateSession(); err == nil {
  58. session.Close()
  59. t.Error("expected err, got nil")
  60. }
  61. }
  62. //TestUseStatementError checks to make sure the correct error is returned when the user tries to execute a use statement.
  63. func TestUseStatementError(t *testing.T) {
  64. session := createSession(t)
  65. defer session.Close()
  66. if err := session.Query("USE gocql_test").Exec(); err != nil {
  67. if err != ErrUseStmt {
  68. t.Fatalf("expected ErrUseStmt, got " + err.Error())
  69. }
  70. } else {
  71. t.Fatal("expected err, got nil.")
  72. }
  73. }
  74. //TestInvalidKeyspace checks that an invalid keyspace will return promptly and without a flood of connections
  75. func TestInvalidKeyspace(t *testing.T) {
  76. cluster := createCluster()
  77. cluster.Keyspace = "invalidKeyspace"
  78. session, err := cluster.CreateSession()
  79. if err != nil {
  80. if err != ErrNoConnectionsStarted {
  81. t.Fatalf("Expected ErrNoConnections but got %v", err)
  82. }
  83. } else {
  84. session.Close() //Clean up the session
  85. t.Fatal("expected err, got nil.")
  86. }
  87. }
  88. func TestTracing(t *testing.T) {
  89. session := createSession(t)
  90. defer session.Close()
  91. if err := createTable(session, `CREATE TABLE gocql_test.trace (id int primary key)`); err != nil {
  92. t.Fatal("create:", err)
  93. }
  94. buf := &bytes.Buffer{}
  95. trace := NewTraceWriter(session, buf)
  96. if err := session.Query(`INSERT INTO trace (id) VALUES (?)`, 42).Trace(trace).Exec(); err != nil {
  97. t.Fatal("insert:", err)
  98. } else if buf.Len() == 0 {
  99. t.Fatal("insert: failed to obtain any tracing")
  100. }
  101. buf.Reset()
  102. var value int
  103. if err := session.Query(`SELECT id FROM trace WHERE id = ?`, 42).Trace(trace).Scan(&value); err != nil {
  104. t.Fatal("select:", err)
  105. } else if value != 42 {
  106. t.Fatalf("value: expected %d, got %d", 42, value)
  107. } else if buf.Len() == 0 {
  108. t.Fatal("select: failed to obtain any tracing")
  109. }
  110. }
  111. func TestPaging(t *testing.T) {
  112. if *flagProto == 1 {
  113. t.Skip("Paging not supported. Please use Cassandra >= 2.0")
  114. }
  115. session := createSession(t)
  116. defer session.Close()
  117. if err := createTable(session, "CREATE TABLE gocql_test.paging (id int primary key)"); err != nil {
  118. t.Fatal("create table:", err)
  119. }
  120. for i := 0; i < 100; i++ {
  121. if err := session.Query("INSERT INTO paging (id) VALUES (?)", i).Exec(); err != nil {
  122. t.Fatal("insert:", err)
  123. }
  124. }
  125. iter := session.Query("SELECT id FROM paging").PageSize(10).Iter()
  126. var id int
  127. count := 0
  128. for iter.Scan(&id) {
  129. count++
  130. }
  131. if err := iter.Close(); err != nil {
  132. t.Fatal("close:", err)
  133. }
  134. if count != 100 {
  135. t.Fatalf("expected %d, got %d", 100, count)
  136. }
  137. }
  138. func TestCAS(t *testing.T) {
  139. if *flagProto == 1 {
  140. t.Skip("lightweight transactions not supported. Please use Cassandra >= 2.0")
  141. }
  142. session := createSession(t)
  143. defer session.Close()
  144. session.cfg.SerialConsistency = LocalSerial
  145. if err := createTable(session, `CREATE TABLE gocql_test.cas_table (
  146. title varchar,
  147. revid timeuuid,
  148. last_modified timestamp,
  149. PRIMARY KEY (title, revid)
  150. )`); err != nil {
  151. t.Fatal("create:", err)
  152. }
  153. title, revid, modified := "baz", TimeUUID(), time.Now()
  154. var titleCAS string
  155. var revidCAS UUID
  156. var modifiedCAS time.Time
  157. if applied, err := session.Query(`INSERT INTO cas_table (title, revid, last_modified)
  158. VALUES (?, ?, ?) IF NOT EXISTS`,
  159. title, revid, modified).ScanCAS(&titleCAS, &revidCAS, &modifiedCAS); err != nil {
  160. t.Fatal("insert:", err)
  161. } else if !applied {
  162. t.Fatal("insert should have been applied")
  163. }
  164. if applied, err := session.Query(`INSERT INTO cas_table (title, revid, last_modified)
  165. VALUES (?, ?, ?) IF NOT EXISTS`,
  166. title, revid, modified).ScanCAS(&titleCAS, &revidCAS, &modifiedCAS); err != nil {
  167. t.Fatal("insert:", err)
  168. } else if applied {
  169. t.Fatal("insert should not have been applied")
  170. } else if title != titleCAS || revid != revidCAS {
  171. t.Fatalf("expected %s/%v/%v but got %s/%v/%v", title, revid, modified, titleCAS, revidCAS, modifiedCAS)
  172. }
  173. tenSecondsLater := modified.Add(10 * time.Second)
  174. if applied, err := session.Query(`DELETE FROM cas_table WHERE title = ? and revid = ? IF last_modified = ?`,
  175. title, revid, tenSecondsLater).ScanCAS(&modifiedCAS); err != nil {
  176. t.Fatal("delete:", err)
  177. } else if applied {
  178. t.Fatal("delete should have not been applied")
  179. }
  180. if modifiedCAS.Unix() != tenSecondsLater.Add(-10*time.Second).Unix() {
  181. t.Fatalf("Was expecting modified CAS to be %v; but was one second later", modifiedCAS.UTC())
  182. }
  183. if _, err := session.Query(`DELETE FROM cas_table WHERE title = ? and revid = ? IF last_modified = ?`,
  184. title, revid, tenSecondsLater).ScanCAS(); err.Error() != "count mismatch" {
  185. t.Fatalf("delete: was expecting count mismatch error but got %s", err)
  186. }
  187. if applied, err := session.Query(`DELETE FROM cas_table WHERE title = ? and revid = ? IF last_modified = ?`,
  188. title, revid, modified).ScanCAS(&modifiedCAS); err != nil {
  189. t.Fatal("delete:", err)
  190. } else if !applied {
  191. t.Fatal("delete should have been applied")
  192. }
  193. if err := session.Query(`TRUNCATE cas_table`).Exec(); err != nil {
  194. t.Fatal("truncate:", err)
  195. }
  196. successBatch := session.NewBatch(LoggedBatch)
  197. successBatch.Query("INSERT INTO cas_table (title, revid, last_modified) VALUES (?, ?, ?) IF NOT EXISTS", title, revid, modified)
  198. if applied, _, err := session.ExecuteBatchCAS(successBatch, &titleCAS, &revidCAS, &modifiedCAS); err != nil {
  199. t.Fatal("insert:", err)
  200. } else if !applied {
  201. t.Fatalf("insert should have been applied: title=%v revID=%v modified=%v", titleCAS, revidCAS, modifiedCAS)
  202. }
  203. successBatch = session.NewBatch(LoggedBatch)
  204. successBatch.Query("INSERT INTO cas_table (title, revid, last_modified) VALUES (?, ?, ?) IF NOT EXISTS", title+"_foo", revid, modified)
  205. casMap := make(map[string]interface{})
  206. if applied, _, err := session.MapExecuteBatchCAS(successBatch, casMap); err != nil {
  207. t.Fatal("insert:", err)
  208. } else if !applied {
  209. t.Fatal("insert should have been applied")
  210. }
  211. failBatch := session.NewBatch(LoggedBatch)
  212. failBatch.Query("INSERT INTO cas_table (title, revid, last_modified) VALUES (?, ?, ?) IF NOT EXISTS", title, revid, modified)
  213. if applied, _, err := session.ExecuteBatchCAS(successBatch, &titleCAS, &revidCAS, &modifiedCAS); err != nil {
  214. t.Fatal("insert:", err)
  215. } else if applied {
  216. t.Fatalf("insert should have been applied: title=%v revID=%v modified=%v", titleCAS, revidCAS, modifiedCAS)
  217. }
  218. insertBatch := session.NewBatch(LoggedBatch)
  219. insertBatch.Query("INSERT INTO cas_table (title, revid, last_modified) VALUES ('_foo', 2c3af400-73a4-11e5-9381-29463d90c3f0, DATEOF(NOW()))")
  220. insertBatch.Query("INSERT INTO cas_table (title, revid, last_modified) VALUES ('_foo', 3e4ad2f1-73a4-11e5-9381-29463d90c3f0, DATEOF(NOW()))")
  221. if err := session.ExecuteBatch(insertBatch); err != nil {
  222. t.Fatal("insert:", err)
  223. }
  224. failBatch = session.NewBatch(LoggedBatch)
  225. failBatch.Query("UPDATE cas_table SET last_modified = DATEOF(NOW()) WHERE title='_foo' AND revid=2c3af400-73a4-11e5-9381-29463d90c3f0 IF last_modified=DATEOF(NOW());")
  226. failBatch.Query("UPDATE cas_table SET last_modified = DATEOF(NOW()) WHERE title='_foo' AND revid=3e4ad2f1-73a4-11e5-9381-29463d90c3f0 IF last_modified=DATEOF(NOW());")
  227. if applied, iter, err := session.ExecuteBatchCAS(failBatch, &titleCAS, &revidCAS, &modifiedCAS); err != nil {
  228. t.Fatal("insert:", err)
  229. } else if applied {
  230. t.Fatalf("insert should have been applied: title=%v revID=%v modified=%v", titleCAS, revidCAS, modifiedCAS)
  231. } else {
  232. if scan := iter.Scan(&applied, &titleCAS, &revidCAS, &modifiedCAS); scan && applied {
  233. t.Fatalf("insert should have been applied: title=%v revID=%v modified=%v", titleCAS, revidCAS, modifiedCAS)
  234. } else if !scan {
  235. t.Fatal("should have scanned another row")
  236. }
  237. if err := iter.Close(); err != nil {
  238. t.Fatal("scan:", err)
  239. }
  240. }
  241. }
  242. func TestMapScanCAS(t *testing.T) {
  243. if *flagProto == 1 {
  244. t.Skip("lightweight transactions not supported. Please use Cassandra >= 2.0")
  245. }
  246. session := createSession(t)
  247. defer session.Close()
  248. if err := createTable(session, `CREATE TABLE gocql_test.cas_table2 (
  249. title varchar,
  250. revid timeuuid,
  251. last_modified timestamp,
  252. deleted boolean,
  253. PRIMARY KEY (title, revid)
  254. )`); err != nil {
  255. t.Fatal("create:", err)
  256. }
  257. title, revid, modified, deleted := "baz", TimeUUID(), time.Now(), false
  258. mapCAS := map[string]interface{}{}
  259. if applied, err := session.Query(`INSERT INTO cas_table2 (title, revid, last_modified, deleted)
  260. VALUES (?, ?, ?, ?) IF NOT EXISTS`,
  261. title, revid, modified, deleted).MapScanCAS(mapCAS); err != nil {
  262. t.Fatal("insert:", err)
  263. } else if !applied {
  264. t.Fatalf("insert should have been applied: title=%v revID=%v modified=%v", title, revid, modified)
  265. }
  266. mapCAS = map[string]interface{}{}
  267. if applied, err := session.Query(`INSERT INTO cas_table2 (title, revid, last_modified, deleted)
  268. VALUES (?, ?, ?, ?) IF NOT EXISTS`,
  269. title, revid, modified, deleted).MapScanCAS(mapCAS); err != nil {
  270. t.Fatal("insert:", err)
  271. } else if applied {
  272. t.Fatalf("insert should have been applied: title=%v revID=%v modified=%v", title, revid, modified)
  273. } else if title != mapCAS["title"] || revid != mapCAS["revid"] || deleted != mapCAS["deleted"] {
  274. 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"])
  275. }
  276. }
  277. func TestBatch(t *testing.T) {
  278. if *flagProto == 1 {
  279. t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
  280. }
  281. session := createSession(t)
  282. defer session.Close()
  283. if err := createTable(session, `CREATE TABLE gocql_test.batch_table (id int primary key)`); err != nil {
  284. t.Fatal("create table:", err)
  285. }
  286. batch := NewBatch(LoggedBatch)
  287. for i := 0; i < 100; i++ {
  288. batch.Query(`INSERT INTO batch_table (id) VALUES (?)`, i)
  289. }
  290. if err := session.ExecuteBatch(batch); err != nil {
  291. t.Fatal("execute batch:", err)
  292. }
  293. count := 0
  294. if err := session.Query(`SELECT COUNT(*) FROM batch_table`).Scan(&count); err != nil {
  295. t.Fatal("select count:", err)
  296. } else if count != 100 {
  297. t.Fatalf("count: expected %d, got %d\n", 100, count)
  298. }
  299. }
  300. func TestUnpreparedBatch(t *testing.T) {
  301. if *flagProto == 1 {
  302. t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
  303. }
  304. session := createSession(t)
  305. defer session.Close()
  306. if err := createTable(session, `CREATE TABLE gocql_test.batch_unprepared (id int primary key, c counter)`); err != nil {
  307. t.Fatal("create table:", err)
  308. }
  309. var batch *Batch
  310. if *flagProto == 2 {
  311. batch = NewBatch(CounterBatch)
  312. } else {
  313. batch = NewBatch(UnloggedBatch)
  314. }
  315. for i := 0; i < 100; i++ {
  316. batch.Query(`UPDATE batch_unprepared SET c = c + 1 WHERE id = 1`)
  317. }
  318. if err := session.ExecuteBatch(batch); err != nil {
  319. t.Fatal("execute batch:", err)
  320. }
  321. count := 0
  322. if err := session.Query(`SELECT COUNT(*) FROM batch_unprepared`).Scan(&count); err != nil {
  323. t.Fatal("select count:", err)
  324. } else if count != 1 {
  325. t.Fatalf("count: expected %d, got %d\n", 100, count)
  326. }
  327. if err := session.Query(`SELECT c FROM batch_unprepared`).Scan(&count); err != nil {
  328. t.Fatal("select count:", err)
  329. } else if count != 100 {
  330. t.Fatalf("count: expected %d, got %d\n", 100, count)
  331. }
  332. }
  333. // TestBatchLimit tests gocql to make sure batch operations larger than the maximum
  334. // statement limit are not submitted to a cassandra node.
  335. func TestBatchLimit(t *testing.T) {
  336. if *flagProto == 1 {
  337. t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
  338. }
  339. session := createSession(t)
  340. defer session.Close()
  341. if err := createTable(session, `CREATE TABLE gocql_test.batch_table2 (id int primary key)`); err != nil {
  342. t.Fatal("create table:", err)
  343. }
  344. batch := NewBatch(LoggedBatch)
  345. for i := 0; i < 65537; i++ {
  346. batch.Query(`INSERT INTO batch_table2 (id) VALUES (?)`, i)
  347. }
  348. if err := session.ExecuteBatch(batch); err != ErrTooManyStmts {
  349. t.Fatal("gocql attempted to execute a batch larger than the support limit of statements.")
  350. }
  351. }
  352. func TestWhereIn(t *testing.T) {
  353. session := createSession(t)
  354. defer session.Close()
  355. if err := createTable(session, `CREATE TABLE gocql_test.where_in_table (id int, cluster int, primary key (id,cluster))`); err != nil {
  356. t.Fatal("create table:", err)
  357. }
  358. if err := session.Query("INSERT INTO where_in_table (id, cluster) VALUES (?,?)", 100, 200).Exec(); err != nil {
  359. t.Fatal("insert:", err)
  360. }
  361. iter := session.Query("SELECT * FROM where_in_table WHERE id = ? AND cluster IN (?)", 100, 200).Iter()
  362. var id, cluster int
  363. count := 0
  364. for iter.Scan(&id, &cluster) {
  365. count++
  366. }
  367. if id != 100 || cluster != 200 {
  368. t.Fatalf("Was expecting id and cluster to be (100,200) but were (%d,%d)", id, cluster)
  369. }
  370. }
  371. // TestTooManyQueryArgs tests to make sure the library correctly handles the application level bug
  372. // whereby too many query arguments are passed to a query
  373. func TestTooManyQueryArgs(t *testing.T) {
  374. if *flagProto == 1 {
  375. t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
  376. }
  377. session := createSession(t)
  378. defer session.Close()
  379. if err := createTable(session, `CREATE TABLE gocql_test.too_many_query_args (id int primary key, value int)`); err != nil {
  380. t.Fatal("create table:", err)
  381. }
  382. _, err := session.Query(`SELECT * FROM too_many_query_args WHERE id = ?`, 1, 2).Iter().SliceMap()
  383. if err == nil {
  384. t.Fatal("'`SELECT * FROM too_many_query_args WHERE id = ?`, 1, 2' should return an ErrQueryArgLength")
  385. }
  386. if err != ErrQueryArgLength {
  387. t.Fatalf("'`SELECT * FROM too_many_query_args WHERE id = ?`, 1, 2' should return an ErrQueryArgLength, but returned: %s", err)
  388. }
  389. batch := session.NewBatch(UnloggedBatch)
  390. batch.Query("INSERT INTO too_many_query_args (id, value) VALUES (?, ?)", 1, 2, 3)
  391. err = session.ExecuteBatch(batch)
  392. if err == nil {
  393. t.Fatal("'`INSERT INTO too_many_query_args (id, value) VALUES (?, ?)`, 1, 2, 3' should return an ErrQueryArgLength")
  394. }
  395. if err != ErrQueryArgLength {
  396. t.Fatalf("'INSERT INTO too_many_query_args (id, value) VALUES (?, ?)`, 1, 2, 3' should return an ErrQueryArgLength, but returned: %s", err)
  397. }
  398. }
  399. // TestNotEnoughQueryArgs tests to make sure the library correctly handles the application level bug
  400. // whereby not enough query arguments are passed to a query
  401. func TestNotEnoughQueryArgs(t *testing.T) {
  402. if *flagProto == 1 {
  403. t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
  404. }
  405. session := createSession(t)
  406. defer session.Close()
  407. if err := createTable(session, `CREATE TABLE gocql_test.not_enough_query_args (id int, cluster int, value int, primary key (id, cluster))`); err != nil {
  408. t.Fatal("create table:", err)
  409. }
  410. _, err := session.Query(`SELECT * FROM not_enough_query_args WHERE id = ? and cluster = ?`, 1).Iter().SliceMap()
  411. if err == nil {
  412. t.Fatal("'`SELECT * FROM not_enough_query_args WHERE id = ? and cluster = ?`, 1' should return an ErrQueryArgLength")
  413. }
  414. if err != ErrQueryArgLength {
  415. t.Fatalf("'`SELECT * FROM too_few_query_args WHERE id = ? and cluster = ?`, 1' should return an ErrQueryArgLength, but returned: %s", err)
  416. }
  417. batch := session.NewBatch(UnloggedBatch)
  418. batch.Query("INSERT INTO not_enough_query_args (id, cluster, value) VALUES (?, ?, ?)", 1, 2)
  419. err = session.ExecuteBatch(batch)
  420. if err == nil {
  421. t.Fatal("'`INSERT INTO not_enough_query_args (id, cluster, value) VALUES (?, ?, ?)`, 1, 2' should return an ErrQueryArgLength")
  422. }
  423. if err != ErrQueryArgLength {
  424. t.Fatalf("'INSERT INTO not_enough_query_args (id, cluster, value) VALUES (?, ?, ?)`, 1, 2' should return an ErrQueryArgLength, but returned: %s", err)
  425. }
  426. }
  427. // TestCreateSessionTimeout tests to make sure the CreateSession function timeouts out correctly
  428. // and prevents an infinite loop of connection retries.
  429. func TestCreateSessionTimeout(t *testing.T) {
  430. go func() {
  431. <-time.After(2 * time.Second)
  432. t.Error("no startup timeout")
  433. }()
  434. cluster := createCluster()
  435. cluster.Hosts = []string{"127.0.0.1:1"}
  436. session, err := cluster.CreateSession()
  437. if err == nil {
  438. session.Close()
  439. t.Fatal("expected ErrNoConnectionsStarted, but no error was returned.")
  440. }
  441. }
  442. type FullName struct {
  443. FirstName string
  444. LastName string
  445. }
  446. func (n FullName) MarshalCQL(info TypeInfo) ([]byte, error) {
  447. return []byte(n.FirstName + " " + n.LastName), nil
  448. }
  449. func (n *FullName) UnmarshalCQL(info TypeInfo, data []byte) error {
  450. t := strings.SplitN(string(data), " ", 2)
  451. n.FirstName, n.LastName = t[0], t[1]
  452. return nil
  453. }
  454. func TestMapScanWithRefMap(t *testing.T) {
  455. session := createSession(t)
  456. defer session.Close()
  457. if err := createTable(session, `CREATE TABLE gocql_test.scan_map_ref_table (
  458. testtext text PRIMARY KEY,
  459. testfullname text,
  460. testint int,
  461. )`); err != nil {
  462. t.Fatal("create table:", err)
  463. }
  464. m := make(map[string]interface{})
  465. m["testtext"] = "testtext"
  466. m["testfullname"] = FullName{"John", "Doe"}
  467. m["testint"] = 100
  468. if err := session.Query(`INSERT INTO scan_map_ref_table (testtext, testfullname, testint) values (?,?,?)`, m["testtext"], m["testfullname"], m["testint"]).Exec(); err != nil {
  469. t.Fatal("insert:", err)
  470. }
  471. var testText string
  472. var testFullName FullName
  473. ret := map[string]interface{}{
  474. "testtext": &testText,
  475. "testfullname": &testFullName,
  476. // testint is not set here.
  477. }
  478. iter := session.Query(`SELECT * FROM scan_map_ref_table`).Iter()
  479. if ok := iter.MapScan(ret); !ok {
  480. t.Fatal("select:", iter.Close())
  481. } else {
  482. if ret["testtext"] != "testtext" {
  483. t.Fatal("returned testtext did not match")
  484. }
  485. f := ret["testfullname"].(FullName)
  486. if f.FirstName != "John" || f.LastName != "Doe" {
  487. t.Fatal("returned testfullname did not match")
  488. }
  489. if ret["testint"] != 100 {
  490. t.Fatal("returned testinit did not match")
  491. }
  492. }
  493. }
  494. func TestSliceMap(t *testing.T) {
  495. session := createSession(t)
  496. defer session.Close()
  497. if err := createTable(session, `CREATE TABLE gocql_test.slice_map_table (
  498. testuuid timeuuid PRIMARY KEY,
  499. testtimestamp timestamp,
  500. testvarchar varchar,
  501. testbigint bigint,
  502. testblob blob,
  503. testbool boolean,
  504. testfloat float,
  505. testdouble double,
  506. testint int,
  507. testdecimal decimal,
  508. testlist list<text>,
  509. testset set<int>,
  510. testmap map<varchar, varchar>,
  511. testvarint varint,
  512. testinet inet
  513. )`); err != nil {
  514. t.Fatal("create table:", err)
  515. }
  516. m := make(map[string]interface{})
  517. bigInt := new(big.Int)
  518. if _, ok := bigInt.SetString("830169365738487321165427203929228", 10); !ok {
  519. t.Fatal("Failed setting bigint by string")
  520. }
  521. m["testuuid"] = TimeUUID()
  522. m["testvarchar"] = "Test VarChar"
  523. m["testbigint"] = time.Now().Unix()
  524. m["testtimestamp"] = time.Now().Truncate(time.Millisecond).UTC()
  525. m["testblob"] = []byte("test blob")
  526. m["testbool"] = true
  527. m["testfloat"] = float32(4.564)
  528. m["testdouble"] = float64(4.815162342)
  529. m["testint"] = 2343
  530. m["testdecimal"] = inf.NewDec(100, 0)
  531. m["testlist"] = []string{"quux", "foo", "bar", "baz", "quux"}
  532. m["testset"] = []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
  533. m["testmap"] = map[string]string{"field1": "val1", "field2": "val2", "field3": "val3"}
  534. m["testvarint"] = bigInt
  535. m["testinet"] = "213.212.2.19"
  536. sliceMap := []map[string]interface{}{m}
  537. 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
  538. 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 {
  539. t.Fatal("insert:", err)
  540. }
  541. if returned, retErr := session.Query(`SELECT * FROM slice_map_table`).Iter().SliceMap(); retErr != nil {
  542. t.Fatal("select:", retErr)
  543. } else {
  544. matchSliceMap(t, sliceMap, returned[0])
  545. }
  546. // Test for Iter.MapScan()
  547. {
  548. testMap := make(map[string]interface{})
  549. if !session.Query(`SELECT * FROM slice_map_table`).Iter().MapScan(testMap) {
  550. t.Fatal("MapScan failed to work with one row")
  551. }
  552. matchSliceMap(t, sliceMap, testMap)
  553. }
  554. // Test for Query.MapScan()
  555. {
  556. testMap := make(map[string]interface{})
  557. if session.Query(`SELECT * FROM slice_map_table`).MapScan(testMap) != nil {
  558. t.Fatal("MapScan failed to work with one row")
  559. }
  560. matchSliceMap(t, sliceMap, testMap)
  561. }
  562. }
  563. func matchSliceMap(t *testing.T, sliceMap []map[string]interface{}, testMap map[string]interface{}) {
  564. if sliceMap[0]["testuuid"] != testMap["testuuid"] {
  565. t.Fatal("returned testuuid did not match")
  566. }
  567. if sliceMap[0]["testtimestamp"] != testMap["testtimestamp"] {
  568. t.Fatal("returned testtimestamp did not match")
  569. }
  570. if sliceMap[0]["testvarchar"] != testMap["testvarchar"] {
  571. t.Fatal("returned testvarchar did not match")
  572. }
  573. if sliceMap[0]["testbigint"] != testMap["testbigint"] {
  574. t.Fatal("returned testbigint did not match")
  575. }
  576. if !reflect.DeepEqual(sliceMap[0]["testblob"], testMap["testblob"]) {
  577. t.Fatal("returned testblob did not match")
  578. }
  579. if sliceMap[0]["testbool"] != testMap["testbool"] {
  580. t.Fatal("returned testbool did not match")
  581. }
  582. if sliceMap[0]["testfloat"] != testMap["testfloat"] {
  583. t.Fatal("returned testfloat did not match")
  584. }
  585. if sliceMap[0]["testdouble"] != testMap["testdouble"] {
  586. t.Fatal("returned testdouble did not match")
  587. }
  588. if sliceMap[0]["testinet"] != testMap["testinet"] {
  589. t.Fatal("returned testinet did not match")
  590. }
  591. expectedDecimal := sliceMap[0]["testdecimal"].(*inf.Dec)
  592. returnedDecimal := testMap["testdecimal"].(*inf.Dec)
  593. if expectedDecimal.Cmp(returnedDecimal) != 0 {
  594. t.Fatal("returned testdecimal did not match")
  595. }
  596. if !reflect.DeepEqual(sliceMap[0]["testlist"], testMap["testlist"]) {
  597. t.Fatal("returned testlist did not match")
  598. }
  599. if !reflect.DeepEqual(sliceMap[0]["testset"], testMap["testset"]) {
  600. t.Fatal("returned testset did not match")
  601. }
  602. if !reflect.DeepEqual(sliceMap[0]["testmap"], testMap["testmap"]) {
  603. t.Fatal("returned testmap did not match")
  604. }
  605. if sliceMap[0]["testint"] != testMap["testint"] {
  606. t.Fatal("returned testint did not match")
  607. }
  608. }
  609. func TestScanWithNilArguments(t *testing.T) {
  610. session := createSession(t)
  611. defer session.Close()
  612. if err := createTable(session, `CREATE TABLE gocql_test.scan_with_nil_arguments (
  613. foo varchar,
  614. bar int,
  615. PRIMARY KEY (foo, bar)
  616. )`); err != nil {
  617. t.Fatal("create:", err)
  618. }
  619. for i := 1; i <= 20; i++ {
  620. if err := session.Query("INSERT INTO scan_with_nil_arguments (foo, bar) VALUES (?, ?)",
  621. "squares", i*i).Exec(); err != nil {
  622. t.Fatal("insert:", err)
  623. }
  624. }
  625. iter := session.Query("SELECT * FROM scan_with_nil_arguments WHERE foo = ?", "squares").Iter()
  626. var n int
  627. count := 0
  628. for iter.Scan(nil, &n) {
  629. count += n
  630. }
  631. if err := iter.Close(); err != nil {
  632. t.Fatal("close:", err)
  633. }
  634. if count != 2870 {
  635. t.Fatalf("expected %d, got %d", 2870, count)
  636. }
  637. }
  638. func TestScanCASWithNilArguments(t *testing.T) {
  639. if *flagProto == 1 {
  640. t.Skip("lightweight transactions not supported. Please use Cassandra >= 2.0")
  641. }
  642. session := createSession(t)
  643. defer session.Close()
  644. if err := createTable(session, `CREATE TABLE gocql_test.scan_cas_with_nil_arguments (
  645. foo varchar,
  646. bar varchar,
  647. PRIMARY KEY (foo, bar)
  648. )`); err != nil {
  649. t.Fatal("create:", err)
  650. }
  651. foo := "baz"
  652. var cas string
  653. if applied, err := session.Query(`INSERT INTO scan_cas_with_nil_arguments (foo, bar)
  654. VALUES (?, ?) IF NOT EXISTS`,
  655. foo, foo).ScanCAS(nil, nil); err != nil {
  656. t.Fatal("insert:", err)
  657. } else if !applied {
  658. t.Fatal("insert should have been applied")
  659. }
  660. if applied, err := session.Query(`INSERT INTO scan_cas_with_nil_arguments (foo, bar)
  661. VALUES (?, ?) IF NOT EXISTS`,
  662. foo, foo).ScanCAS(&cas, nil); err != nil {
  663. t.Fatal("insert:", err)
  664. } else if applied {
  665. t.Fatal("insert should not have been applied")
  666. } else if foo != cas {
  667. t.Fatalf("expected %v but got %v", foo, cas)
  668. }
  669. if applied, err := session.Query(`INSERT INTO scan_cas_with_nil_arguments (foo, bar)
  670. VALUES (?, ?) IF NOT EXISTS`,
  671. foo, foo).ScanCAS(nil, &cas); err != nil {
  672. t.Fatal("insert:", err)
  673. } else if applied {
  674. t.Fatal("insert should not have been applied")
  675. } else if foo != cas {
  676. t.Fatalf("expected %v but got %v", foo, cas)
  677. }
  678. }
  679. func TestRebindQueryInfo(t *testing.T) {
  680. session := createSession(t)
  681. defer session.Close()
  682. if err := createTable(session, "CREATE TABLE gocql_test.rebind_query (id int, value text, PRIMARY KEY (id))"); err != nil {
  683. t.Fatalf("failed to create table with error '%v'", err)
  684. }
  685. if err := session.Query("INSERT INTO rebind_query (id, value) VALUES (?, ?)", 23, "quux").Exec(); err != nil {
  686. t.Fatalf("insert into rebind_query failed, err '%v'", err)
  687. }
  688. if err := session.Query("INSERT INTO rebind_query (id, value) VALUES (?, ?)", 24, "w00t").Exec(); err != nil {
  689. t.Fatalf("insert into rebind_query failed, err '%v'", err)
  690. }
  691. q := session.Query("SELECT value FROM rebind_query WHERE ID = ?")
  692. q.Bind(23)
  693. iter := q.Iter()
  694. var value string
  695. for iter.Scan(&value) {
  696. }
  697. if value != "quux" {
  698. t.Fatalf("expected %v but got %v", "quux", value)
  699. }
  700. q.Bind(24)
  701. iter = q.Iter()
  702. for iter.Scan(&value) {
  703. }
  704. if value != "w00t" {
  705. t.Fatalf("expected %v but got %v", "quux", value)
  706. }
  707. }
  708. //TestStaticQueryInfo makes sure that the application can manually bind query parameters using the simplest possible static binding strategy
  709. func TestStaticQueryInfo(t *testing.T) {
  710. session := createSession(t)
  711. defer session.Close()
  712. if err := createTable(session, "CREATE TABLE gocql_test.static_query_info (id int, value text, PRIMARY KEY (id))"); err != nil {
  713. t.Fatalf("failed to create table with error '%v'", err)
  714. }
  715. if err := session.Query("INSERT INTO static_query_info (id, value) VALUES (?, ?)", 113, "foo").Exec(); err != nil {
  716. t.Fatalf("insert into static_query_info failed, err '%v'", err)
  717. }
  718. autobinder := func(q *QueryInfo) ([]interface{}, error) {
  719. values := make([]interface{}, 1)
  720. values[0] = 113
  721. return values, nil
  722. }
  723. qry := session.Bind("SELECT id, value FROM static_query_info WHERE id = ?", autobinder)
  724. if err := qry.Exec(); err != nil {
  725. t.Fatalf("expose query info failed, error '%v'", err)
  726. }
  727. iter := qry.Iter()
  728. var id int
  729. var value string
  730. iter.Scan(&id, &value)
  731. if err := iter.Close(); err != nil {
  732. t.Fatalf("query with exposed info failed, err '%v'", err)
  733. }
  734. if value != "foo" {
  735. t.Fatalf("Expected value %s, but got %s", "foo", value)
  736. }
  737. }
  738. type ClusteredKeyValue struct {
  739. Id int
  740. Cluster int
  741. Value string
  742. }
  743. func (kv *ClusteredKeyValue) Bind(q *QueryInfo) ([]interface{}, error) {
  744. values := make([]interface{}, len(q.Args))
  745. for i, info := range q.Args {
  746. fieldName := upcaseInitial(info.Name)
  747. value := reflect.ValueOf(kv)
  748. field := reflect.Indirect(value).FieldByName(fieldName)
  749. values[i] = field.Addr().Interface()
  750. }
  751. return values, nil
  752. }
  753. func upcaseInitial(str string) string {
  754. for i, v := range str {
  755. return string(unicode.ToUpper(v)) + str[i+1:]
  756. }
  757. return ""
  758. }
  759. //TestBoundQueryInfo makes sure that the application can manually bind query parameters using the query meta data supplied at runtime
  760. func TestBoundQueryInfo(t *testing.T) {
  761. session := createSession(t)
  762. defer session.Close()
  763. if err := createTable(session, "CREATE TABLE gocql_test.clustered_query_info (id int, cluster int, value text, PRIMARY KEY (id, cluster))"); err != nil {
  764. t.Fatalf("failed to create table with error '%v'", err)
  765. }
  766. write := &ClusteredKeyValue{Id: 200, Cluster: 300, Value: "baz"}
  767. insert := session.Bind("INSERT INTO clustered_query_info (id, cluster, value) VALUES (?, ?,?)", write.Bind)
  768. if err := insert.Exec(); err != nil {
  769. t.Fatalf("insert into clustered_query_info failed, err '%v'", err)
  770. }
  771. read := &ClusteredKeyValue{Id: 200, Cluster: 300}
  772. qry := session.Bind("SELECT id, cluster, value FROM clustered_query_info WHERE id = ? and cluster = ?", read.Bind)
  773. iter := qry.Iter()
  774. var id, cluster int
  775. var value string
  776. iter.Scan(&id, &cluster, &value)
  777. if err := iter.Close(); err != nil {
  778. t.Fatalf("query with clustered_query_info info failed, err '%v'", err)
  779. }
  780. if value != "baz" {
  781. t.Fatalf("Expected value %s, but got %s", "baz", value)
  782. }
  783. }
  784. //TestBatchQueryInfo makes sure that the application can manually bind query parameters when executing in a batch
  785. func TestBatchQueryInfo(t *testing.T) {
  786. if *flagProto == 1 {
  787. t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
  788. }
  789. session := createSession(t)
  790. defer session.Close()
  791. if err := createTable(session, "CREATE TABLE gocql_test.batch_query_info (id int, cluster int, value text, PRIMARY KEY (id, cluster))"); err != nil {
  792. t.Fatalf("failed to create table with error '%v'", err)
  793. }
  794. write := func(q *QueryInfo) ([]interface{}, error) {
  795. values := make([]interface{}, 3)
  796. values[0] = 4000
  797. values[1] = 5000
  798. values[2] = "bar"
  799. return values, nil
  800. }
  801. batch := session.NewBatch(LoggedBatch)
  802. batch.Bind("INSERT INTO batch_query_info (id, cluster, value) VALUES (?, ?,?)", write)
  803. if err := session.ExecuteBatch(batch); err != nil {
  804. t.Fatalf("batch insert into batch_query_info failed, err '%v'", err)
  805. }
  806. read := func(q *QueryInfo) ([]interface{}, error) {
  807. values := make([]interface{}, 2)
  808. values[0] = 4000
  809. values[1] = 5000
  810. return values, nil
  811. }
  812. qry := session.Bind("SELECT id, cluster, value FROM batch_query_info WHERE id = ? and cluster = ?", read)
  813. iter := qry.Iter()
  814. var id, cluster int
  815. var value string
  816. iter.Scan(&id, &cluster, &value)
  817. if err := iter.Close(); err != nil {
  818. t.Fatalf("query with batch_query_info info failed, err '%v'", err)
  819. }
  820. if value != "bar" {
  821. t.Fatalf("Expected value %s, but got %s", "bar", value)
  822. }
  823. }
  824. func injectInvalidPreparedStatement(t *testing.T, session *Session, table string) (string, *Conn) {
  825. if err := createTable(session, `CREATE TABLE gocql_test.`+table+` (
  826. foo varchar,
  827. bar int,
  828. PRIMARY KEY (foo, bar)
  829. )`); err != nil {
  830. t.Fatal("create:", err)
  831. }
  832. stmt := "INSERT INTO " + table + " (foo, bar) VALUES (?, 7)"
  833. _, conn := session.pool.Pick(nil)
  834. flight := new(inflightPrepare)
  835. stmtsLRU.Lock()
  836. stmtsLRU.lru.Add(conn.addr+stmt, flight)
  837. stmtsLRU.Unlock()
  838. flight.info = QueryInfo{
  839. Id: []byte{'f', 'o', 'o', 'b', 'a', 'r'},
  840. Args: []ColumnInfo{
  841. {
  842. Keyspace: "gocql_test",
  843. Table: table,
  844. Name: "foo",
  845. TypeInfo: NativeType{
  846. typ: TypeVarchar,
  847. },
  848. },
  849. },
  850. }
  851. return stmt, conn
  852. }
  853. func TestMissingSchemaPrepare(t *testing.T) {
  854. s := createSession(t)
  855. _, conn := s.pool.Pick(nil)
  856. defer s.Close()
  857. insertQry := &Query{stmt: "INSERT INTO invalidschemaprep (val) VALUES (?)", values: []interface{}{5}, cons: s.cons,
  858. session: s, pageSize: s.pageSize, trace: s.trace,
  859. prefetch: s.prefetch, rt: s.cfg.RetryPolicy}
  860. if err := conn.executeQuery(insertQry).err; err == nil {
  861. t.Fatal("expected error, but got nil.")
  862. }
  863. if err := createTable(s, "CREATE TABLE gocql_test.invalidschemaprep (val int, PRIMARY KEY (val))"); err != nil {
  864. t.Fatal("create table:", err)
  865. }
  866. if err := conn.executeQuery(insertQry).err; err != nil {
  867. t.Fatal(err) // unconfigured columnfamily
  868. }
  869. }
  870. func TestReprepareStatement(t *testing.T) {
  871. session := createSession(t)
  872. defer session.Close()
  873. stmt, conn := injectInvalidPreparedStatement(t, session, "test_reprepare_statement")
  874. query := session.Query(stmt, "bar")
  875. if err := conn.executeQuery(query).Close(); err != nil {
  876. t.Fatalf("Failed to execute query for reprepare statement: %v", err)
  877. }
  878. }
  879. func TestReprepareBatch(t *testing.T) {
  880. if *flagProto == 1 {
  881. t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
  882. }
  883. session := createSession(t)
  884. defer session.Close()
  885. stmt, conn := injectInvalidPreparedStatement(t, session, "test_reprepare_statement_batch")
  886. batch := session.NewBatch(UnloggedBatch)
  887. batch.Query(stmt, "bar")
  888. if _, err := conn.executeBatch(batch); err != nil {
  889. t.Fatalf("Failed to execute query for reprepare statement: %v", err)
  890. }
  891. }
  892. func TestQueryInfo(t *testing.T) {
  893. session := createSession(t)
  894. defer session.Close()
  895. _, conn := session.pool.Pick(nil)
  896. info, err := conn.prepareStatement("SELECT release_version, host_id FROM system.local WHERE key = ?", nil)
  897. if err != nil {
  898. t.Fatalf("Failed to execute query for preparing statement: %v", err)
  899. }
  900. if x := len(info.Args); x != 1 {
  901. t.Fatalf("Was not expecting meta data for %d query arguments, but got %d\n", 1, x)
  902. }
  903. if *flagProto > 1 {
  904. if x := len(info.Rval); x != 2 {
  905. t.Fatalf("Was not expecting meta data for %d result columns, but got %d\n", 2, x)
  906. }
  907. }
  908. }
  909. //TestPreparedCacheEviction will make sure that the cache size is maintained
  910. func TestPreparedCacheEviction(t *testing.T) {
  911. session := createSession(t)
  912. defer session.Close()
  913. stmtsLRU.Lock()
  914. stmtsLRU.Max(4)
  915. stmtsLRU.Unlock()
  916. if err := createTable(session, "CREATE TABLE gocql_test.prepcachetest (id int,mod int,PRIMARY KEY (id))"); err != nil {
  917. t.Fatalf("failed to create table with error '%v'", err)
  918. }
  919. //Fill the table
  920. for i := 0; i < 2; i++ {
  921. if err := session.Query("INSERT INTO prepcachetest (id,mod) VALUES (?, ?)", i, 10000%(i+1)).Exec(); err != nil {
  922. t.Fatalf("insert into prepcachetest failed, err '%v'", err)
  923. }
  924. }
  925. //Populate the prepared statement cache with select statements
  926. var id, mod int
  927. for i := 0; i < 2; i++ {
  928. err := session.Query("SELECT id,mod FROM prepcachetest WHERE id = "+strconv.FormatInt(int64(i), 10)).Scan(&id, &mod)
  929. if err != nil {
  930. t.Fatalf("select from prepcachetest failed, error '%v'", err)
  931. }
  932. }
  933. //generate an update statement to test they are prepared
  934. err := session.Query("UPDATE prepcachetest SET mod = ? WHERE id = ?", 1, 11).Exec()
  935. if err != nil {
  936. t.Fatalf("update prepcachetest failed, error '%v'", err)
  937. }
  938. //generate a delete statement to test they are prepared
  939. err = session.Query("DELETE FROM prepcachetest WHERE id = ?", 1).Exec()
  940. if err != nil {
  941. t.Fatalf("delete from prepcachetest failed, error '%v'", err)
  942. }
  943. //generate an insert statement to test they are prepared
  944. err = session.Query("INSERT INTO prepcachetest (id,mod) VALUES (?, ?)", 3, 11).Exec()
  945. if err != nil {
  946. t.Fatalf("insert into prepcachetest failed, error '%v'", err)
  947. }
  948. stmtsLRU.Lock()
  949. //Make sure the cache size is maintained
  950. if stmtsLRU.lru.Len() != stmtsLRU.lru.MaxEntries {
  951. t.Fatalf("expected cache size of %v, got %v", stmtsLRU.lru.MaxEntries, stmtsLRU.lru.Len())
  952. }
  953. //Walk through all the configured hosts and test cache retention and eviction
  954. var selFound, insFound, updFound, delFound, selEvict bool
  955. for i := range session.cfg.Hosts {
  956. _, ok := stmtsLRU.lru.Get(session.cfg.Hosts[i] + ":9042gocql_testSELECT id,mod FROM prepcachetest WHERE id = 1")
  957. selFound = selFound || ok
  958. _, ok = stmtsLRU.lru.Get(session.cfg.Hosts[i] + ":9042gocql_testINSERT INTO prepcachetest (id,mod) VALUES (?, ?)")
  959. insFound = insFound || ok
  960. _, ok = stmtsLRU.lru.Get(session.cfg.Hosts[i] + ":9042gocql_testUPDATE prepcachetest SET mod = ? WHERE id = ?")
  961. updFound = updFound || ok
  962. _, ok = stmtsLRU.lru.Get(session.cfg.Hosts[i] + ":9042gocql_testDELETE FROM prepcachetest WHERE id = ?")
  963. delFound = delFound || ok
  964. _, ok = stmtsLRU.lru.Get(session.cfg.Hosts[i] + ":9042gocql_testSELECT id,mod FROM prepcachetest WHERE id = 0")
  965. selEvict = selEvict || !ok
  966. }
  967. stmtsLRU.Unlock()
  968. if !selEvict {
  969. t.Fatalf("expected first select statement to be purged, but statement was found in the cache.")
  970. }
  971. if !selFound {
  972. t.Fatalf("expected second select statement to be cached, but statement was purged or not prepared.")
  973. }
  974. if !insFound {
  975. t.Fatalf("expected insert statement to be cached, but statement was purged or not prepared.")
  976. }
  977. if !updFound {
  978. t.Fatalf("expected update statement to be cached, but statement was purged or not prepared.")
  979. }
  980. if !delFound {
  981. t.Error("expected delete statement to be cached, but statement was purged or not prepared.")
  982. }
  983. }
  984. func TestPreparedCacheKey(t *testing.T) {
  985. session := createSession(t)
  986. defer session.Close()
  987. // create a second keyspace
  988. cluster2 := createCluster()
  989. createKeyspace(t, cluster2, "gocql_test2")
  990. cluster2.Keyspace = "gocql_test2"
  991. session2, err := cluster2.CreateSession()
  992. if err != nil {
  993. t.Fatal("create session:", err)
  994. }
  995. defer session2.Close()
  996. // both keyspaces have a table named "test_stmt_cache_key"
  997. if err := createTable(session, "CREATE TABLE gocql_test.test_stmt_cache_key (id varchar primary key, field varchar)"); err != nil {
  998. t.Fatal("create table:", err)
  999. }
  1000. if err := createTable(session2, "CREATE TABLE gocql_test2.test_stmt_cache_key (id varchar primary key, field varchar)"); err != nil {
  1001. t.Fatal("create table:", err)
  1002. }
  1003. // both tables have a single row with the same partition key but different column value
  1004. if err = session.Query(`INSERT INTO test_stmt_cache_key (id, field) VALUES (?, ?)`, "key", "one").Exec(); err != nil {
  1005. t.Fatal("insert:", err)
  1006. }
  1007. if err = session2.Query(`INSERT INTO test_stmt_cache_key (id, field) VALUES (?, ?)`, "key", "two").Exec(); err != nil {
  1008. t.Fatal("insert:", err)
  1009. }
  1010. // should be able to see different values in each keyspace
  1011. var value string
  1012. if err = session.Query("SELECT field FROM test_stmt_cache_key WHERE id = ?", "key").Scan(&value); err != nil {
  1013. t.Fatal("select:", err)
  1014. }
  1015. if value != "one" {
  1016. t.Errorf("Expected one, got %s", value)
  1017. }
  1018. if err = session2.Query("SELECT field FROM test_stmt_cache_key WHERE id = ?", "key").Scan(&value); err != nil {
  1019. t.Fatal("select:", err)
  1020. }
  1021. if value != "two" {
  1022. t.Errorf("Expected two, got %s", value)
  1023. }
  1024. }
  1025. //TestMarshalFloat64Ptr tests to see that a pointer to a float64 is marshalled correctly.
  1026. func TestMarshalFloat64Ptr(t *testing.T) {
  1027. session := createSession(t)
  1028. defer session.Close()
  1029. if err := createTable(session, "CREATE TABLE gocql_test.float_test (id double, test double, primary key (id))"); err != nil {
  1030. t.Fatal("create table:", err)
  1031. }
  1032. testNum := float64(7500)
  1033. if err := session.Query(`INSERT INTO float_test (id,test) VALUES (?,?)`, float64(7500.00), &testNum).Exec(); err != nil {
  1034. t.Fatal("insert float64:", err)
  1035. }
  1036. }
  1037. //TestMarshalInet tests to see that a pointer to a float64 is marshalled correctly.
  1038. func TestMarshalInet(t *testing.T) {
  1039. session := createSession(t)
  1040. defer session.Close()
  1041. if err := createTable(session, "CREATE TABLE gocql_test.inet_test (ip inet, name text, primary key (ip))"); err != nil {
  1042. t.Fatal("create table:", err)
  1043. }
  1044. stringIp := "123.34.45.56"
  1045. if err := session.Query(`INSERT INTO inet_test (ip,name) VALUES (?,?)`, stringIp, "Test IP 1").Exec(); err != nil {
  1046. t.Fatal("insert string inet:", err)
  1047. }
  1048. var stringResult string
  1049. if err := session.Query("SELECT ip FROM inet_test").Scan(&stringResult); err != nil {
  1050. t.Fatalf("select for string from inet_test 1 failed: %v", err)
  1051. }
  1052. if stringResult != stringIp {
  1053. t.Errorf("Expected %s, was %s", stringIp, stringResult)
  1054. }
  1055. var ipResult net.IP
  1056. if err := session.Query("SELECT ip FROM inet_test").Scan(&ipResult); err != nil {
  1057. t.Fatalf("select for net.IP from inet_test 1 failed: %v", err)
  1058. }
  1059. if ipResult.String() != stringIp {
  1060. t.Errorf("Expected %s, was %s", stringIp, ipResult.String())
  1061. }
  1062. if err := session.Query(`DELETE FROM inet_test WHERE ip = ?`, stringIp).Exec(); err != nil {
  1063. t.Fatal("delete inet table:", err)
  1064. }
  1065. netIp := net.ParseIP("222.43.54.65")
  1066. if err := session.Query(`INSERT INTO inet_test (ip,name) VALUES (?,?)`, netIp, "Test IP 2").Exec(); err != nil {
  1067. t.Fatal("insert netIp inet:", err)
  1068. }
  1069. if err := session.Query("SELECT ip FROM inet_test").Scan(&stringResult); err != nil {
  1070. t.Fatalf("select for string from inet_test 2 failed: %v", err)
  1071. }
  1072. if stringResult != netIp.String() {
  1073. t.Errorf("Expected %s, was %s", netIp.String(), stringResult)
  1074. }
  1075. if err := session.Query("SELECT ip FROM inet_test").Scan(&ipResult); err != nil {
  1076. t.Fatalf("select for net.IP from inet_test 2 failed: %v", err)
  1077. }
  1078. if ipResult.String() != netIp.String() {
  1079. t.Errorf("Expected %s, was %s", netIp.String(), ipResult.String())
  1080. }
  1081. }
  1082. func TestVarint(t *testing.T) {
  1083. session := createSession(t)
  1084. defer session.Close()
  1085. if err := createTable(session, "CREATE TABLE gocql_test.varint_test (id varchar, test varint, test2 varint, primary key (id))"); err != nil {
  1086. t.Fatalf("failed to create table with error '%v'", err)
  1087. }
  1088. if err := session.Query(`INSERT INTO varint_test (id, test) VALUES (?, ?)`, "id", 0).Exec(); err != nil {
  1089. t.Fatalf("insert varint: %v", err)
  1090. }
  1091. var result int
  1092. if err := session.Query("SELECT test FROM varint_test").Scan(&result); err != nil {
  1093. t.Fatalf("select from varint_test failed: %v", err)
  1094. }
  1095. if result != 0 {
  1096. t.Errorf("Expected 0, was %d", result)
  1097. }
  1098. if err := session.Query(`INSERT INTO varint_test (id, test) VALUES (?, ?)`, "id", -1).Exec(); err != nil {
  1099. t.Fatalf("insert varint: %v", err)
  1100. }
  1101. if err := session.Query("SELECT test FROM varint_test").Scan(&result); err != nil {
  1102. t.Fatalf("select from varint_test failed: %v", err)
  1103. }
  1104. if result != -1 {
  1105. t.Errorf("Expected -1, was %d", result)
  1106. }
  1107. if err := session.Query(`INSERT INTO varint_test (id, test) VALUES (?, ?)`, "id", int64(math.MaxInt32)+1).Exec(); err != nil {
  1108. t.Fatalf("insert varint: %v", err)
  1109. }
  1110. var result64 int64
  1111. if err := session.Query("SELECT test FROM varint_test").Scan(&result64); err != nil {
  1112. t.Fatalf("select from varint_test failed: %v", err)
  1113. }
  1114. if result64 != int64(math.MaxInt32)+1 {
  1115. t.Errorf("Expected %d, was %d", int64(math.MaxInt32)+1, result64)
  1116. }
  1117. biggie := new(big.Int)
  1118. biggie.SetString("36893488147419103232", 10) // > 2**64
  1119. if err := session.Query(`INSERT INTO varint_test (id, test) VALUES (?, ?)`, "id", biggie).Exec(); err != nil {
  1120. t.Fatalf("insert varint: %v", err)
  1121. }
  1122. resultBig := new(big.Int)
  1123. if err := session.Query("SELECT test FROM varint_test").Scan(resultBig); err != nil {
  1124. t.Fatalf("select from varint_test failed: %v", err)
  1125. }
  1126. if resultBig.String() != biggie.String() {
  1127. t.Errorf("Expected %s, was %s", biggie.String(), resultBig.String())
  1128. }
  1129. err := session.Query("SELECT test FROM varint_test").Scan(&result64)
  1130. if err == nil || strings.Index(err.Error(), "out of range") == -1 {
  1131. t.Errorf("expected out of range error since value is too big for int64")
  1132. }
  1133. // value not set in cassandra, leave bind variable empty
  1134. resultBig = new(big.Int)
  1135. if err := session.Query("SELECT test2 FROM varint_test").Scan(resultBig); err != nil {
  1136. t.Fatalf("select from varint_test failed: %v", err)
  1137. }
  1138. if resultBig.Int64() != 0 {
  1139. t.Errorf("Expected %s, was %s", biggie.String(), resultBig.String())
  1140. }
  1141. // can use double pointer to explicitly detect value is not set in cassandra
  1142. if err := session.Query("SELECT test2 FROM varint_test").Scan(&resultBig); err != nil {
  1143. t.Fatalf("select from varint_test failed: %v", err)
  1144. }
  1145. if resultBig != nil {
  1146. t.Errorf("Expected %v, was %v", nil, *resultBig)
  1147. }
  1148. }
  1149. //TestQueryStats confirms that the stats are returning valid data. Accuracy may be questionable.
  1150. func TestQueryStats(t *testing.T) {
  1151. session := createSession(t)
  1152. defer session.Close()
  1153. qry := session.Query("SELECT * FROM system.peers")
  1154. if err := qry.Exec(); err != nil {
  1155. t.Fatalf("query failed. %v", err)
  1156. } else {
  1157. if qry.Attempts() < 1 {
  1158. t.Fatal("expected at least 1 attempt, but got 0")
  1159. }
  1160. if qry.Latency() <= 0 {
  1161. t.Fatalf("expected latency to be greater than 0, but got %v instead.", qry.Latency())
  1162. }
  1163. }
  1164. }
  1165. //TestBatchStats confirms that the stats are returning valid data. Accuracy may be questionable.
  1166. func TestBatchStats(t *testing.T) {
  1167. if *flagProto == 1 {
  1168. t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
  1169. }
  1170. session := createSession(t)
  1171. defer session.Close()
  1172. if err := createTable(session, "CREATE TABLE gocql_test.batchStats (id int, PRIMARY KEY (id))"); err != nil {
  1173. t.Fatalf("failed to create table with error '%v'", err)
  1174. }
  1175. b := session.NewBatch(LoggedBatch)
  1176. b.Query("INSERT INTO batchStats (id) VALUES (?)", 1)
  1177. b.Query("INSERT INTO batchStats (id) VALUES (?)", 2)
  1178. if err := session.ExecuteBatch(b); err != nil {
  1179. t.Fatalf("query failed. %v", err)
  1180. } else {
  1181. if b.Attempts() < 1 {
  1182. t.Fatal("expected at least 1 attempt, but got 0")
  1183. }
  1184. if b.Latency() <= 0 {
  1185. t.Fatalf("expected latency to be greater than 0, but got %v instead.", b.Latency())
  1186. }
  1187. }
  1188. }
  1189. //TestNilInQuery tests to see that a nil value passed to a query is handled by Cassandra
  1190. //TODO validate the nil value by reading back the nil. Need to fix Unmarshalling.
  1191. func TestNilInQuery(t *testing.T) {
  1192. session := createSession(t)
  1193. defer session.Close()
  1194. if err := createTable(session, "CREATE TABLE gocql_test.testNilInsert (id int, count int, PRIMARY KEY (id))"); err != nil {
  1195. t.Fatalf("failed to create table with error '%v'", err)
  1196. }
  1197. if err := session.Query("INSERT INTO testNilInsert (id,count) VALUES (?,?)", 1, nil).Exec(); err != nil {
  1198. t.Fatalf("failed to insert with err: %v", err)
  1199. }
  1200. var id int
  1201. if err := session.Query("SELECT id FROM testNilInsert").Scan(&id); err != nil {
  1202. t.Fatalf("failed to select with err: %v", err)
  1203. } else if id != 1 {
  1204. t.Fatalf("expected id to be 1, got %v", id)
  1205. }
  1206. }
  1207. // Don't initialize time.Time bind variable if cassandra timestamp column is empty
  1208. func TestEmptyTimestamp(t *testing.T) {
  1209. session := createSession(t)
  1210. defer session.Close()
  1211. if err := createTable(session, "CREATE TABLE gocql_test.test_empty_timestamp (id int, time timestamp, num int, PRIMARY KEY (id))"); err != nil {
  1212. t.Fatalf("failed to create table with error '%v'", err)
  1213. }
  1214. if err := session.Query("INSERT INTO test_empty_timestamp (id, num) VALUES (?,?)", 1, 561).Exec(); err != nil {
  1215. t.Fatalf("failed to insert with err: %v", err)
  1216. }
  1217. var timeVal time.Time
  1218. if err := session.Query("SELECT time FROM test_empty_timestamp where id = ?", 1).Scan(&timeVal); err != nil {
  1219. t.Fatalf("failed to select with err: %v", err)
  1220. }
  1221. if !timeVal.IsZero() {
  1222. t.Errorf("time.Time bind variable should still be empty (was %s)", timeVal)
  1223. }
  1224. }
  1225. // Integration test of just querying for data from the system.schema_keyspace table
  1226. func TestGetKeyspaceMetadata(t *testing.T) {
  1227. session := createSession(t)
  1228. defer session.Close()
  1229. keyspaceMetadata, err := getKeyspaceMetadata(session, "gocql_test")
  1230. if err != nil {
  1231. t.Fatalf("failed to query the keyspace metadata with err: %v", err)
  1232. }
  1233. if keyspaceMetadata == nil {
  1234. t.Fatal("failed to query the keyspace metadata, nil returned")
  1235. }
  1236. if keyspaceMetadata.Name != "gocql_test" {
  1237. t.Errorf("Expected keyspace name to be 'gocql' but was '%s'", keyspaceMetadata.Name)
  1238. }
  1239. if keyspaceMetadata.StrategyClass != "org.apache.cassandra.locator.SimpleStrategy" {
  1240. t.Errorf("Expected replication strategy class to be 'org.apache.cassandra.locator.SimpleStrategy' but was '%s'", keyspaceMetadata.StrategyClass)
  1241. }
  1242. if keyspaceMetadata.StrategyOptions == nil {
  1243. t.Error("Expected replication strategy options map but was nil")
  1244. }
  1245. rfStr, ok := keyspaceMetadata.StrategyOptions["replication_factor"]
  1246. if !ok {
  1247. t.Fatalf("Expected strategy option 'replication_factor' but was not found in %v", keyspaceMetadata.StrategyOptions)
  1248. }
  1249. rfInt, err := strconv.Atoi(rfStr.(string))
  1250. if err != nil {
  1251. t.Fatalf("Error converting string to int with err: %v", err)
  1252. }
  1253. if rfInt != *flagRF {
  1254. t.Errorf("Expected replication factor to be %d but was %d", *flagRF, rfInt)
  1255. }
  1256. }
  1257. // Integration test of just querying for data from the system.schema_columnfamilies table
  1258. func TestGetTableMetadata(t *testing.T) {
  1259. session := createSession(t)
  1260. defer session.Close()
  1261. if err := createTable(session, "CREATE TABLE gocql_test.test_table_metadata (first_id int, second_id int, third_id int, PRIMARY KEY (first_id, second_id))"); err != nil {
  1262. t.Fatalf("failed to create table with error '%v'", err)
  1263. }
  1264. tables, err := getTableMetadata(session, "gocql_test")
  1265. if err != nil {
  1266. t.Fatalf("failed to query the table metadata with err: %v", err)
  1267. }
  1268. if tables == nil {
  1269. t.Fatal("failed to query the table metadata, nil returned")
  1270. }
  1271. var testTable *TableMetadata
  1272. // verify all tables have minimum expected data
  1273. for i := range tables {
  1274. table := &tables[i]
  1275. if table.Name == "" {
  1276. t.Errorf("Expected table name to be set, but it was empty: index=%d metadata=%+v", i, table)
  1277. }
  1278. if table.Keyspace != "gocql_test" {
  1279. t.Errorf("Expected keyspace for '%d' table metadata to be 'gocql_test' but was '%s'", table.Name, table.Keyspace)
  1280. }
  1281. if table.KeyValidator == "" {
  1282. t.Errorf("Expected key validator to be set for table %s", table.Name)
  1283. }
  1284. if table.Comparator == "" {
  1285. t.Errorf("Expected comparator to be set for table %s", table.Name)
  1286. }
  1287. if table.DefaultValidator == "" {
  1288. t.Errorf("Expected default validator to be set for table %s", table.Name)
  1289. }
  1290. // these fields are not set until the metadata is compiled
  1291. if table.PartitionKey != nil {
  1292. t.Errorf("Did not expect partition key for table %s", table.Name)
  1293. }
  1294. if table.ClusteringColumns != nil {
  1295. t.Errorf("Did not expect clustering columns for table %s", table.Name)
  1296. }
  1297. if table.Columns != nil {
  1298. t.Errorf("Did not expect columns for table %s", table.Name)
  1299. }
  1300. // for the next part of the test after this loop, find the metadata for the test table
  1301. if table.Name == "test_table_metadata" {
  1302. testTable = table
  1303. }
  1304. }
  1305. // verify actual values on the test tables
  1306. if testTable == nil {
  1307. t.Fatal("Expected table metadata for name 'test_table_metadata'")
  1308. }
  1309. if testTable.KeyValidator != "org.apache.cassandra.db.marshal.Int32Type" {
  1310. t.Errorf("Expected test_table_metadata key validator to be 'org.apache.cassandra.db.marshal.Int32Type' but was '%s'", testTable.KeyValidator)
  1311. }
  1312. if testTable.Comparator != "org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.Int32Type,org.apache.cassandra.db.marshal.UTF8Type)" {
  1313. 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)
  1314. }
  1315. if testTable.DefaultValidator != "org.apache.cassandra.db.marshal.BytesType" {
  1316. t.Errorf("Expected test_table_metadata key validator to be 'org.apache.cassandra.db.marshal.BytesType' but was '%s'", testTable.DefaultValidator)
  1317. }
  1318. if *flagProto < protoVersion4 {
  1319. expectedKeyAliases := []string{"first_id"}
  1320. if !reflect.DeepEqual(testTable.KeyAliases, expectedKeyAliases) {
  1321. t.Errorf("Expected key aliases %v but was %v", expectedKeyAliases, testTable.KeyAliases)
  1322. }
  1323. expectedColumnAliases := []string{"second_id"}
  1324. if !reflect.DeepEqual(testTable.ColumnAliases, expectedColumnAliases) {
  1325. t.Errorf("Expected key aliases %v but was %v", expectedColumnAliases, testTable.ColumnAliases)
  1326. }
  1327. }
  1328. if testTable.ValueAlias != "" {
  1329. t.Errorf("Expected value alias '' but was '%s'", testTable.ValueAlias)
  1330. }
  1331. }
  1332. // Integration test of just querying for data from the system.schema_columns table
  1333. func TestGetColumnMetadata(t *testing.T) {
  1334. session := createSession(t)
  1335. defer session.Close()
  1336. if err := createTable(session, "CREATE TABLE gocql_test.test_column_metadata (first_id int, second_id int, third_id int, PRIMARY KEY (first_id, second_id))"); err != nil {
  1337. t.Fatalf("failed to create table with error '%v'", err)
  1338. }
  1339. if err := session.Query("CREATE INDEX index_column_metadata ON test_column_metadata ( third_id )").Exec(); err != nil {
  1340. t.Fatalf("failed to create index with err: %v", err)
  1341. }
  1342. columns, err := getColumnMetadata(session, "gocql_test")
  1343. if err != nil {
  1344. t.Fatalf("failed to query column metadata with err: %v", err)
  1345. }
  1346. if columns == nil {
  1347. t.Fatal("failed to query column metadata, nil returned")
  1348. }
  1349. testColumns := map[string]*ColumnMetadata{}
  1350. // verify actual values on the test columns
  1351. for i := range columns {
  1352. column := &columns[i]
  1353. if column.Name == "" {
  1354. t.Errorf("Expected column name to be set, but it was empty: index=%d metadata=%+v", i, column)
  1355. }
  1356. if column.Table == "" {
  1357. t.Errorf("Expected column %s table name to be set, but it was empty", column.Name)
  1358. }
  1359. if column.Keyspace != "gocql_test" {
  1360. t.Errorf("Expected column %s keyspace name to be 'gocql_test', but it was '%s'", column.Name, column.Keyspace)
  1361. }
  1362. if column.Kind == "" {
  1363. t.Errorf("Expected column %s kind to be set, but it was empty", column.Name)
  1364. }
  1365. if session.cfg.ProtoVersion == 1 && column.Kind != "regular" {
  1366. t.Errorf("Expected column %s kind to be set to 'regular' for proto V1 but it was '%s'", column.Name, column.Kind)
  1367. }
  1368. if column.Validator == "" {
  1369. t.Errorf("Expected column %s validator to be set, but it was empty", column.Name)
  1370. }
  1371. // find the test table columns for the next step after this loop
  1372. if column.Table == "test_column_metadata" {
  1373. testColumns[column.Name] = column
  1374. }
  1375. }
  1376. if *flagProto == 1 {
  1377. // V1 proto only returns "regular columns"
  1378. if len(testColumns) != 1 {
  1379. t.Errorf("Expected 1 test columns but there were %d", len(testColumns))
  1380. }
  1381. thirdID, found := testColumns["third_id"]
  1382. if !found {
  1383. t.Fatalf("Expected to find column 'third_id' metadata but there was only %v", testColumns)
  1384. }
  1385. if thirdID.Kind != REGULAR {
  1386. t.Errorf("Expected %s column kind to be '%s' but it was '%s'", thirdID.Name, REGULAR, thirdID.Kind)
  1387. }
  1388. if thirdID.Index.Name != "index_column_metadata" {
  1389. t.Errorf("Expected %s column index name to be 'index_column_metadata' but it was '%s'", thirdID.Name, thirdID.Index.Name)
  1390. }
  1391. } else {
  1392. if len(testColumns) != 3 {
  1393. t.Errorf("Expected 3 test columns but there were %d", len(testColumns))
  1394. }
  1395. firstID, found := testColumns["first_id"]
  1396. if !found {
  1397. t.Fatalf("Expected to find column 'first_id' metadata but there was only %v", testColumns)
  1398. }
  1399. secondID, found := testColumns["second_id"]
  1400. if !found {
  1401. t.Fatalf("Expected to find column 'second_id' metadata but there was only %v", testColumns)
  1402. }
  1403. thirdID, found := testColumns["third_id"]
  1404. if !found {
  1405. t.Fatalf("Expected to find column 'third_id' metadata but there was only %v", testColumns)
  1406. }
  1407. if firstID.Kind != PARTITION_KEY {
  1408. t.Errorf("Expected %s column kind to be '%s' but it was '%s'", firstID.Name, PARTITION_KEY, firstID.Kind)
  1409. }
  1410. if secondID.Kind != CLUSTERING_KEY {
  1411. t.Errorf("Expected %s column kind to be '%s' but it was '%s'", secondID.Name, CLUSTERING_KEY, secondID.Kind)
  1412. }
  1413. if thirdID.Kind != REGULAR {
  1414. t.Errorf("Expected %s column kind to be '%s' but it was '%s'", thirdID.Name, REGULAR, thirdID.Kind)
  1415. }
  1416. if thirdID.Index.Name != "index_column_metadata" {
  1417. t.Errorf("Expected %s column index name to be 'index_column_metadata' but it was '%s'", thirdID.Name, thirdID.Index.Name)
  1418. }
  1419. }
  1420. }
  1421. // Integration test of querying and composition the keyspace metadata
  1422. func TestKeyspaceMetadata(t *testing.T) {
  1423. session := createSession(t)
  1424. defer session.Close()
  1425. if err := createTable(session, "CREATE TABLE gocql_test.test_metadata (first_id int, second_id int, third_id int, PRIMARY KEY (first_id, second_id))"); err != nil {
  1426. t.Fatalf("failed to create table with error '%v'", err)
  1427. }
  1428. if err := session.Query("CREATE INDEX index_metadata ON test_metadata ( third_id )").Exec(); err != nil {
  1429. t.Fatalf("failed to create index with err: %v", err)
  1430. }
  1431. keyspaceMetadata, err := session.KeyspaceMetadata("gocql_test")
  1432. if err != nil {
  1433. t.Fatalf("failed to query keyspace metadata with err: %v", err)
  1434. }
  1435. if keyspaceMetadata == nil {
  1436. t.Fatal("expected the keyspace metadata to not be nil, but it was nil")
  1437. }
  1438. if keyspaceMetadata.Name != session.cfg.Keyspace {
  1439. t.Fatalf("Expected the keyspace name to be %s but was %s", session.cfg.Keyspace, keyspaceMetadata.Name)
  1440. }
  1441. if len(keyspaceMetadata.Tables) == 0 {
  1442. t.Errorf("Expected tables but there were none")
  1443. }
  1444. tableMetadata, found := keyspaceMetadata.Tables["test_metadata"]
  1445. if !found {
  1446. t.Fatalf("failed to find the test_metadata table metadata")
  1447. }
  1448. if len(tableMetadata.PartitionKey) != 1 {
  1449. t.Errorf("expected partition key length of 1, but was %d", len(tableMetadata.PartitionKey))
  1450. }
  1451. for i, column := range tableMetadata.PartitionKey {
  1452. if column == nil {
  1453. t.Errorf("partition key column metadata at index %d was nil", i)
  1454. }
  1455. }
  1456. if tableMetadata.PartitionKey[0].Name != "first_id" {
  1457. t.Errorf("Expected the first partition key column to be 'first_id' but was '%s'", tableMetadata.PartitionKey[0].Name)
  1458. }
  1459. if len(tableMetadata.ClusteringColumns) != 1 {
  1460. t.Fatalf("expected clustering columns length of 1, but was %d", len(tableMetadata.ClusteringColumns))
  1461. }
  1462. for i, column := range tableMetadata.ClusteringColumns {
  1463. if column == nil {
  1464. t.Fatalf("clustering column metadata at index %d was nil", i)
  1465. }
  1466. }
  1467. if tableMetadata.ClusteringColumns[0].Name != "second_id" {
  1468. t.Errorf("Expected the first clustering column to be 'second_id' but was '%s'", tableMetadata.ClusteringColumns[0].Name)
  1469. }
  1470. thirdColumn, found := tableMetadata.Columns["third_id"]
  1471. if !found {
  1472. t.Fatalf("Expected a column definition for 'third_id'")
  1473. }
  1474. if thirdColumn.Index.Name != "index_metadata" {
  1475. t.Errorf("Expected column index named 'index_metadata' but was '%s'", thirdColumn.Index.Name)
  1476. }
  1477. }
  1478. // Integration test of the routing key calculation
  1479. func TestRoutingKey(t *testing.T) {
  1480. session := createSession(t)
  1481. defer session.Close()
  1482. if err := createTable(session, "CREATE TABLE gocql_test.test_single_routing_key (first_id int, second_id int, PRIMARY KEY (first_id, second_id))"); err != nil {
  1483. t.Fatalf("failed to create table with error '%v'", err)
  1484. }
  1485. if err := createTable(session, "CREATE TABLE gocql_test.test_composite_routing_key (first_id int, second_id int, PRIMARY KEY ((first_id, second_id)))"); err != nil {
  1486. t.Fatalf("failed to create table with error '%v'", err)
  1487. }
  1488. routingKeyInfo, err := session.routingKeyInfo("SELECT * FROM test_single_routing_key WHERE second_id=? AND first_id=?")
  1489. if err != nil {
  1490. t.Fatalf("failed to get routing key info due to error: %v", err)
  1491. }
  1492. if routingKeyInfo == nil {
  1493. t.Fatal("Expected routing key info, but was nil")
  1494. }
  1495. if len(routingKeyInfo.indexes) != 1 {
  1496. t.Fatalf("Expected routing key indexes length to be 1 but was %d", len(routingKeyInfo.indexes))
  1497. }
  1498. if routingKeyInfo.indexes[0] != 1 {
  1499. t.Errorf("Expected routing key index[0] to be 1 but was %d", routingKeyInfo.indexes[0])
  1500. }
  1501. if len(routingKeyInfo.types) != 1 {
  1502. t.Fatalf("Expected routing key types length to be 1 but was %d", len(routingKeyInfo.types))
  1503. }
  1504. if routingKeyInfo.types[0] == nil {
  1505. t.Fatal("Expected routing key types[0] to be non-nil")
  1506. }
  1507. if routingKeyInfo.types[0].Type() != TypeInt {
  1508. t.Fatalf("Expected routing key types[0].Type to be %v but was %v", TypeInt, routingKeyInfo.types[0].Type())
  1509. }
  1510. // verify the cache is working
  1511. routingKeyInfo, err = session.routingKeyInfo("SELECT * FROM test_single_routing_key WHERE second_id=? AND first_id=?")
  1512. if err != nil {
  1513. t.Fatalf("failed to get routing key info due to error: %v", err)
  1514. }
  1515. if len(routingKeyInfo.indexes) != 1 {
  1516. t.Fatalf("Expected routing key indexes length to be 1 but was %d", len(routingKeyInfo.indexes))
  1517. }
  1518. if routingKeyInfo.indexes[0] != 1 {
  1519. t.Errorf("Expected routing key index[0] to be 1 but was %d", routingKeyInfo.indexes[0])
  1520. }
  1521. if len(routingKeyInfo.types) != 1 {
  1522. t.Fatalf("Expected routing key types length to be 1 but was %d", len(routingKeyInfo.types))
  1523. }
  1524. if routingKeyInfo.types[0] == nil {
  1525. t.Fatal("Expected routing key types[0] to be non-nil")
  1526. }
  1527. if routingKeyInfo.types[0].Type() != TypeInt {
  1528. t.Fatalf("Expected routing key types[0] to be %v but was %v", TypeInt, routingKeyInfo.types[0].Type())
  1529. }
  1530. cacheSize := session.routingKeyInfoCache.lru.Len()
  1531. if cacheSize != 1 {
  1532. t.Errorf("Expected cache size to be 1 but was %d", cacheSize)
  1533. }
  1534. query := session.Query("SELECT * FROM test_single_routing_key WHERE second_id=? AND first_id=?", 1, 2)
  1535. routingKey, err := query.GetRoutingKey()
  1536. if err != nil {
  1537. t.Fatalf("Failed to get routing key due to error: %v", err)
  1538. }
  1539. expectedRoutingKey := []byte{0, 0, 0, 2}
  1540. if !reflect.DeepEqual(expectedRoutingKey, routingKey) {
  1541. t.Errorf("Expected routing key %v but was %v", expectedRoutingKey, routingKey)
  1542. }
  1543. routingKeyInfo, err = session.routingKeyInfo("SELECT * FROM test_composite_routing_key WHERE second_id=? AND first_id=?")
  1544. if err != nil {
  1545. t.Fatalf("failed to get routing key info due to error: %v", err)
  1546. }
  1547. if routingKeyInfo == nil {
  1548. t.Fatal("Expected routing key info, but was nil")
  1549. }
  1550. if len(routingKeyInfo.indexes) != 2 {
  1551. t.Fatalf("Expected routing key indexes length to be 2 but was %d", len(routingKeyInfo.indexes))
  1552. }
  1553. if routingKeyInfo.indexes[0] != 1 {
  1554. t.Errorf("Expected routing key index[0] to be 1 but was %d", routingKeyInfo.indexes[0])
  1555. }
  1556. if routingKeyInfo.indexes[1] != 0 {
  1557. t.Errorf("Expected routing key index[1] to be 0 but was %d", routingKeyInfo.indexes[1])
  1558. }
  1559. if len(routingKeyInfo.types) != 2 {
  1560. t.Fatalf("Expected routing key types length to be 1 but was %d", len(routingKeyInfo.types))
  1561. }
  1562. if routingKeyInfo.types[0] == nil {
  1563. t.Fatal("Expected routing key types[0] to be non-nil")
  1564. }
  1565. if routingKeyInfo.types[0].Type() != TypeInt {
  1566. t.Fatalf("Expected routing key types[0] to be %v but was %v", TypeInt, routingKeyInfo.types[0].Type())
  1567. }
  1568. if routingKeyInfo.types[1] == nil {
  1569. t.Fatal("Expected routing key types[1] to be non-nil")
  1570. }
  1571. if routingKeyInfo.types[1].Type() != TypeInt {
  1572. t.Fatalf("Expected routing key types[0] to be %v but was %v", TypeInt, routingKeyInfo.types[1].Type())
  1573. }
  1574. query = session.Query("SELECT * FROM test_composite_routing_key WHERE second_id=? AND first_id=?", 1, 2)
  1575. routingKey, err = query.GetRoutingKey()
  1576. if err != nil {
  1577. t.Fatalf("Failed to get routing key due to error: %v", err)
  1578. }
  1579. expectedRoutingKey = []byte{0, 4, 0, 0, 0, 2, 0, 0, 4, 0, 0, 0, 1, 0}
  1580. if !reflect.DeepEqual(expectedRoutingKey, routingKey) {
  1581. t.Errorf("Expected routing key %v but was %v", expectedRoutingKey, routingKey)
  1582. }
  1583. // verify the cache is working
  1584. cacheSize = session.routingKeyInfoCache.lru.Len()
  1585. if cacheSize != 2 {
  1586. t.Errorf("Expected cache size to be 2 but was %d", cacheSize)
  1587. }
  1588. }
  1589. // Integration test of the token-aware policy-based connection pool
  1590. func TestTokenAwareConnPool(t *testing.T) {
  1591. cluster := createCluster()
  1592. cluster.PoolConfig.HostSelectionPolicy = TokenAwareHostPolicy(RoundRobinHostPolicy())
  1593. session := createSessionFromCluster(cluster, t)
  1594. defer session.Close()
  1595. if expected := cluster.NumConns * len(session.ring.allHosts()); session.pool.Size() != expected {
  1596. t.Errorf("Expected pool size %d but was %d", expected, session.pool.Size())
  1597. }
  1598. if err := createTable(session, "CREATE TABLE gocql_test.test_token_aware (id int, data text, PRIMARY KEY (id))"); err != nil {
  1599. t.Fatalf("failed to create test_token_aware table with err: %v", err)
  1600. }
  1601. query := session.Query("INSERT INTO test_token_aware (id, data) VALUES (?,?)", 42, "8 * 6 =")
  1602. if err := query.Exec(); err != nil {
  1603. t.Fatalf("failed to insert with err: %v", err)
  1604. }
  1605. query = session.Query("SELECT data FROM test_token_aware where id = ?", 42).Consistency(One)
  1606. var data string
  1607. if err := query.Scan(&data); err != nil {
  1608. t.Error(err)
  1609. }
  1610. // TODO add verification that the query went to the correct host
  1611. }
  1612. type frameWriterFunc func(framer *framer, streamID int) error
  1613. func (f frameWriterFunc) writeFrame(framer *framer, streamID int) error {
  1614. return f(framer, streamID)
  1615. }
  1616. func TestStream0(t *testing.T) {
  1617. session := createSession(t)
  1618. defer session.Close()
  1619. var conn *Conn
  1620. for i := 0; i < 5; i++ {
  1621. if conn != nil {
  1622. break
  1623. }
  1624. _, conn = session.pool.Pick(nil)
  1625. }
  1626. if conn == nil {
  1627. t.Fatal("no connections available in the pool")
  1628. }
  1629. writer := frameWriterFunc(func(f *framer, streamID int) error {
  1630. if streamID == 0 {
  1631. t.Fatal("should not use stream 0 for requests")
  1632. }
  1633. f.writeHeader(0, opError, streamID)
  1634. f.writeString("i am a bad frame")
  1635. f.wbuf[0] = 0xFF
  1636. return f.finishWrite()
  1637. })
  1638. const expErr = "gocql: error on stream 0:"
  1639. // need to write out an invalid frame, which we need a connection to do
  1640. frame, err := conn.exec(writer, nil)
  1641. if err == nil {
  1642. t.Fatal("expected to get an error on stream 0")
  1643. } else if !strings.HasPrefix(err.Error(), expErr) {
  1644. t.Fatalf("expected to get error prefix %q got %q", expErr, err.Error())
  1645. } else if frame != nil {
  1646. t.Fatalf("expected to get nil frame got %+v", frame)
  1647. }
  1648. }
  1649. func TestNegativeStream(t *testing.T) {
  1650. session := createSession(t)
  1651. defer session.Close()
  1652. var conn *Conn
  1653. for i := 0; i < 5; i++ {
  1654. if conn != nil {
  1655. break
  1656. }
  1657. _, conn = session.pool.Pick(nil)
  1658. }
  1659. if conn == nil {
  1660. t.Fatal("no connections available in the pool")
  1661. }
  1662. const stream = -50
  1663. writer := frameWriterFunc(func(f *framer, streamID int) error {
  1664. f.writeHeader(0, opOptions, stream)
  1665. return f.finishWrite()
  1666. })
  1667. frame, err := conn.exec(writer, nil)
  1668. if err == nil {
  1669. t.Fatalf("expected to get an error on stream %d", stream)
  1670. } else if frame != nil {
  1671. t.Fatalf("expected to get nil frame got %+v", frame)
  1672. }
  1673. }
  1674. func TestManualQueryPaging(t *testing.T) {
  1675. const rowsToInsert = 5
  1676. session := createSession(t)
  1677. defer session.Close()
  1678. if err := createTable(session, "CREATE TABLE gocql_test.testManualPaging (id int, count int, PRIMARY KEY (id))"); err != nil {
  1679. t.Fatal(err)
  1680. }
  1681. for i := 0; i < rowsToInsert; i++ {
  1682. err := session.Query("INSERT INTO testManualPaging(id, count) VALUES(?, ?)", i, i*i).Exec()
  1683. if err != nil {
  1684. t.Fatal(err)
  1685. }
  1686. }
  1687. // disable auto paging, 1 page per iteration
  1688. query := session.Query("SELECT id, count FROM testManualPaging").PageState(nil).PageSize(2)
  1689. var id, count, fetched int
  1690. iter := query.Iter()
  1691. // NOTE: this isnt very indicitive of how it should be used, the idea is that
  1692. // the page state is returned to some client who will send it back to manually
  1693. // page through the results.
  1694. for {
  1695. for iter.Scan(&id, &count) {
  1696. if count != (id * id) {
  1697. t.Fatalf("got wrong value from iteration: got %d expected %d", count, id*id)
  1698. }
  1699. fetched++
  1700. }
  1701. if len(iter.PageState()) > 0 {
  1702. // more pages
  1703. iter = query.PageState(iter.PageState()).Iter()
  1704. } else {
  1705. break
  1706. }
  1707. }
  1708. if err := iter.Close(); err != nil {
  1709. t.Fatal(err)
  1710. }
  1711. if fetched != rowsToInsert {
  1712. t.Fatalf("expected to fetch %d rows got %d", fetched, rowsToInsert)
  1713. }
  1714. }
  1715. func TestLexicalUUIDType(t *testing.T) {
  1716. session := createSession(t)
  1717. defer session.Close()
  1718. if err := createTable(session, `CREATE TABLE gocql_test.test_lexical_uuid (
  1719. key varchar,
  1720. column1 'org.apache.cassandra.db.marshal.LexicalUUIDType',
  1721. value int,
  1722. PRIMARY KEY (key, column1)
  1723. )`); err != nil {
  1724. t.Fatal("create:", err)
  1725. }
  1726. key := TimeUUID().String()
  1727. column1 := TimeUUID()
  1728. err := session.Query("INSERT INTO test_lexical_uuid(key, column1, value) VALUES(?, ?, ?)", key, column1, 55).Exec()
  1729. if err != nil {
  1730. t.Fatal(err)
  1731. }
  1732. var gotUUID UUID
  1733. if err := session.Query("SELECT column1 from test_lexical_uuid where key = ? AND column1 = ?", key, column1).Scan(&gotUUID); err != nil {
  1734. t.Fatal(err)
  1735. }
  1736. if gotUUID != column1 {
  1737. t.Errorf("got %s, expected %s", gotUUID, column1)
  1738. }
  1739. }
  1740. // Issue 475
  1741. func TestSessionBindRoutingKey(t *testing.T) {
  1742. cluster := createCluster()
  1743. cluster.PoolConfig.HostSelectionPolicy = TokenAwareHostPolicy(RoundRobinHostPolicy())
  1744. session := createSessionFromCluster(cluster, t)
  1745. defer session.Close()
  1746. if err := createTable(session, `CREATE TABLE gocql_test.test_bind_routing_key (
  1747. key varchar,
  1748. value int,
  1749. PRIMARY KEY (key)
  1750. )`); err != nil {
  1751. t.Fatal(err)
  1752. }
  1753. const (
  1754. key = "routing-key"
  1755. value = 5
  1756. )
  1757. fn := func(info *QueryInfo) ([]interface{}, error) {
  1758. return []interface{}{key, value}, nil
  1759. }
  1760. q := session.Bind("INSERT INTO test_bind_routing_key(key, value) VALUES(?, ?)", fn)
  1761. if err := q.Exec(); err != nil {
  1762. t.Fatal(err)
  1763. }
  1764. }
  1765. func TestJSONSupport(t *testing.T) {
  1766. if *flagProto < 4 {
  1767. t.Skip("skipping JSON support on proto < 4")
  1768. }
  1769. session := createSession(t)
  1770. defer session.Close()
  1771. if err := createTable(session, `CREATE TABLE gocql_test.test_json (
  1772. id text PRIMARY KEY,
  1773. age int,
  1774. state text
  1775. )`); err != nil {
  1776. t.Fatal(err)
  1777. }
  1778. err := session.Query("INSERT INTO test_json JSON ?", `{"id": "user123", "age": 42, "state": "TX"}`).Exec()
  1779. if err != nil {
  1780. t.Fatal(err)
  1781. }
  1782. var (
  1783. id string
  1784. age int
  1785. state string
  1786. )
  1787. err = session.Query("SELECT id, age, state FROM test_json WHERE id = ?", "user123").Scan(&id, &age, &state)
  1788. if err != nil {
  1789. t.Fatal(err)
  1790. }
  1791. if id != "user123" {
  1792. t.Errorf("got id %q expected %q", id, "user123")
  1793. }
  1794. if age != 42 {
  1795. t.Errorf("got age %d expected %d", age, 42)
  1796. }
  1797. if state != "TX" {
  1798. t.Errorf("got state %q expected %q", state, "TX")
  1799. }
  1800. }
  1801. func TestUDF(t *testing.T) {
  1802. if *flagProto < 4 {
  1803. t.Skip("skipping UDF support on proto < 4")
  1804. }
  1805. session := createSession(t)
  1806. defer session.Close()
  1807. const query = `CREATE OR REPLACE FUNCTION uniq(state set<text>, val text)
  1808. CALLED ON NULL INPUT RETURNS set<text> LANGUAGE java
  1809. AS 'state.add(val); return state;'`
  1810. err := session.Query(query).Exec()
  1811. if err != nil {
  1812. t.Fatal(err)
  1813. }
  1814. }
  1815. func TestDiscoverViaProxy(t *testing.T) {
  1816. // This (complicated) test tests that when the driver is given an initial host
  1817. // that is infact a proxy it discovers the rest of the ring behind the proxy
  1818. // and does not store the proxies address as a host in its connection pool.
  1819. // See https://github.com/gocql/gocql/issues/481
  1820. proxy, err := net.Listen("tcp", "localhost:0")
  1821. if err != nil {
  1822. t.Fatalf("unable to create proxy listener: %v", err)
  1823. }
  1824. var (
  1825. wg sync.WaitGroup
  1826. mu sync.Mutex
  1827. proxyConns []net.Conn
  1828. closed bool
  1829. )
  1830. go func(wg *sync.WaitGroup) {
  1831. cassandraAddr := JoinHostPort(clusterHosts[0], 9042)
  1832. cassandra := func() (net.Conn, error) {
  1833. return net.Dial("tcp", cassandraAddr)
  1834. }
  1835. proxyFn := func(wg *sync.WaitGroup, from, to net.Conn) {
  1836. defer wg.Done()
  1837. _, err := io.Copy(to, from)
  1838. if err != nil {
  1839. mu.Lock()
  1840. if !closed {
  1841. t.Error(err)
  1842. }
  1843. mu.Unlock()
  1844. }
  1845. }
  1846. // handle dials cassandra and then proxies requests and reponsess. It waits
  1847. // for both the read and write side of the TCP connection to close before
  1848. // returning.
  1849. handle := func(conn net.Conn) error {
  1850. defer conn.Close()
  1851. cass, err := cassandra()
  1852. if err != nil {
  1853. return err
  1854. }
  1855. mu.Lock()
  1856. proxyConns = append(proxyConns, cass)
  1857. mu.Unlock()
  1858. defer cass.Close()
  1859. var wg sync.WaitGroup
  1860. wg.Add(1)
  1861. go proxyFn(&wg, conn, cass)
  1862. wg.Add(1)
  1863. go proxyFn(&wg, cass, conn)
  1864. wg.Wait()
  1865. return nil
  1866. }
  1867. for {
  1868. // proxy just accepts connections and then proxies them to cassandra,
  1869. // it runs until it is closed.
  1870. conn, err := proxy.Accept()
  1871. if err != nil {
  1872. mu.Lock()
  1873. if !closed {
  1874. t.Error(err)
  1875. }
  1876. mu.Unlock()
  1877. return
  1878. }
  1879. mu.Lock()
  1880. proxyConns = append(proxyConns, conn)
  1881. mu.Unlock()
  1882. wg.Add(1)
  1883. go func(conn net.Conn) {
  1884. defer wg.Done()
  1885. if err := handle(conn); err != nil {
  1886. t.Error(err)
  1887. return
  1888. }
  1889. }(conn)
  1890. }
  1891. }(&wg)
  1892. defer wg.Wait()
  1893. proxyAddr := proxy.Addr().String()
  1894. cluster := createCluster()
  1895. cluster.NumConns = 1
  1896. // initial host is the proxy address
  1897. cluster.Hosts = []string{proxyAddr}
  1898. session := createSessionFromCluster(cluster, t)
  1899. defer session.Close()
  1900. if !session.hostSource.localHasRpcAddr {
  1901. t.Skip("Target cluster does not have rpc_address in system.local.")
  1902. goto close
  1903. }
  1904. // we shouldnt need this but to be safe
  1905. time.Sleep(1 * time.Second)
  1906. session.pool.mu.RLock()
  1907. for _, host := range clusterHosts {
  1908. if _, ok := session.pool.hostConnPools[host]; !ok {
  1909. t.Errorf("missing host in pool after discovery: %q", host)
  1910. }
  1911. }
  1912. session.pool.mu.RUnlock()
  1913. close:
  1914. if err := proxy.Close(); err != nil {
  1915. t.Log(err)
  1916. }
  1917. mu.Lock()
  1918. closed = true
  1919. for _, conn := range proxyConns {
  1920. if err := conn.Close(); err != nil {
  1921. t.Log(err)
  1922. }
  1923. }
  1924. mu.Unlock()
  1925. }