cassandra_test.go 71 KB

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