cassandra_test.go 72 KB

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