main.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. // Copyright (c) 2012 The gocql Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package main
  5. import (
  6. "log"
  7. "os"
  8. "reflect"
  9. "sort"
  10. "time"
  11. "tux21b.org/v1/gocql"
  12. "tux21b.org/v1/gocql/uuid"
  13. )
  14. var cluster *gocql.ClusterConfig
  15. var session *gocql.Session
  16. func init() {
  17. cluster = gocql.NewCluster("127.0.0.1")
  18. // uncomment the following two lines if you want to use Cassandra 1.2
  19. // cluster.ProtoVersion = 1
  20. // cluster.CQLVersion = "3.0.0"
  21. session, _ = cluster.CreateSession()
  22. }
  23. type Page struct {
  24. Title string
  25. RevId uuid.UUID
  26. Body string
  27. Views int64
  28. Protected bool
  29. Modified time.Time
  30. Tags []string
  31. Attachments map[string]Attachment
  32. }
  33. type Attachment []byte
  34. func initSchema() error {
  35. if err := session.Query("DROP KEYSPACE gocql_test").Exec(); err != nil {
  36. log.Println("drop keyspace", err)
  37. }
  38. if err := session.Query(`CREATE KEYSPACE gocql_test
  39. WITH replication = {
  40. 'class' : 'SimpleStrategy',
  41. 'replication_factor' : 1
  42. }`).Exec(); err != nil {
  43. return err
  44. }
  45. log.Println("Testing that the connections do not reconnect in an infinite loop.")
  46. session.Close()
  47. time.Sleep(15 * time.Second)
  48. log.Println("If there were error messages that an address cannot be assigned then the test failed.")
  49. cluster.Keyspace = "gocql_test"
  50. session, _ = cluster.CreateSession()
  51. if err := session.Query(`CREATE TABLE page (
  52. title varchar,
  53. revid timeuuid,
  54. body varchar,
  55. views bigint,
  56. protected boolean,
  57. modified timestamp,
  58. tags set<varchar>,
  59. attachments map<varchar, text>,
  60. PRIMARY KEY (title, revid)
  61. )`).Exec(); err != nil {
  62. return err
  63. }
  64. if err := session.Query(`CREATE TABLE page_stats (
  65. title varchar,
  66. views counter,
  67. PRIMARY KEY (title)
  68. )`).Exec(); err != nil {
  69. return err
  70. }
  71. return nil
  72. }
  73. var pageTestData = []*Page{
  74. &Page{
  75. Title: "Frontpage",
  76. RevId: uuid.TimeUUID(),
  77. Body: "Welcome to this wiki page!",
  78. Modified: time.Date(2013, time.August, 13, 9, 52, 3, 0, time.UTC),
  79. Tags: []string{"start", "important", "test"},
  80. Attachments: map[string]Attachment{
  81. "logo": Attachment("\x00company logo\x00"),
  82. "favicon": Attachment("favicon.ico"),
  83. },
  84. },
  85. &Page{
  86. Title: "Foobar",
  87. RevId: uuid.TimeUUID(),
  88. Body: "foo::Foo f = new foo::Foo(foo::Foo::INIT);",
  89. Modified: time.Date(2013, time.August, 13, 9, 52, 3, 0, time.UTC),
  90. },
  91. }
  92. func insertTestData() error {
  93. for _, page := range pageTestData {
  94. if err := session.Query(`INSERT INTO page
  95. (title, revid, body, views, protected, modified, tags, attachments)
  96. VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
  97. page.Title, page.RevId, page.Body, page.Views, page.Protected,
  98. page.Modified, page.Tags, page.Attachments).Exec(); err != nil {
  99. return err
  100. }
  101. }
  102. return nil
  103. }
  104. func insertBatch() error {
  105. batch := gocql.NewBatch(gocql.LoggedBatch)
  106. for _, page := range pageTestData {
  107. batch.Query(`INSERT INTO page
  108. (title, revid, body, views, protected, modified, tags, attachments)
  109. VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
  110. page.Title, page.RevId, page.Body, page.Views, page.Protected,
  111. page.Modified, page.Tags, page.Attachments)
  112. }
  113. if err := session.ExecuteBatch(batch); err != nil {
  114. return err
  115. }
  116. return nil
  117. }
  118. func getPage(title string, revid uuid.UUID) (*Page, error) {
  119. p := new(Page)
  120. err := session.Query(`SELECT title, revid, body, views, protected, modified,
  121. tags, attachments
  122. FROM page WHERE title = ? AND revid = ? LIMIT 1`, title, revid).Scan(
  123. &p.Title, &p.RevId, &p.Body, &p.Views, &p.Protected, &p.Modified,
  124. &p.Tags, &p.Attachments)
  125. return p, err
  126. }
  127. //This test checks to make sure a valid error and a nil reference to
  128. //a session are returned when an empty array of hosts are provided
  129. //to the cluster configuration
  130. func TestEmptyHosts() error {
  131. empty := make([]string, 0)
  132. cfg := gocql.NewCluster(empty...)
  133. _, err := cfg.CreateSession()
  134. return err
  135. }
  136. func main() {
  137. if err := TestEmptyHosts(); err == nil {
  138. log.Fatal("Failed to error when empty host list is provided.")
  139. }
  140. if err := initSchema(); err != nil {
  141. log.Fatal("initSchema: ", err)
  142. }
  143. if err := insertTestData(); err != nil {
  144. log.Fatal("insertTestData: ", err)
  145. }
  146. var count int
  147. if err := session.Query("SELECT COUNT(*) FROM page").Scan(&count); err != nil {
  148. log.Fatal("getCount: ", err)
  149. }
  150. if count != len(pageTestData) {
  151. log.Printf("count: expected %d, got %d", len(pageTestData), count)
  152. }
  153. for _, original := range pageTestData {
  154. page, err := getPage(original.Title, original.RevId)
  155. if err != nil {
  156. log.Print("getPage: ", err)
  157. continue
  158. }
  159. sort.Sort(sort.StringSlice(page.Tags))
  160. sort.Sort(sort.StringSlice(original.Tags))
  161. if !reflect.DeepEqual(page, original) {
  162. log.Printf("page: expected %#v, got %#v\n", original, page)
  163. }
  164. }
  165. // Query Tracing
  166. trace := gocql.NewTraceWriter(session, os.Stdout)
  167. if err := session.Query("SELECT COUNT(*) FROM page").Trace(trace).Scan(&count); err != nil {
  168. log.Fatal("trace: ", err)
  169. }
  170. if err := session.Query("CREATE TABLE large (id int primary key)").Exec(); err != nil {
  171. log.Fatal("create table: ", err)
  172. }
  173. for i := 0; i < 100; i++ {
  174. if err := session.Query("INSERT INTO large (id) VALUES (?)", i).Exec(); err != nil {
  175. log.Fatal("insert: ", err)
  176. }
  177. }
  178. if cluster.ProtoVersion >= 2 {
  179. // Result Paging
  180. iter := session.Query("SELECT id FROM large").PageSize(10).Iter()
  181. var id int
  182. count = 0
  183. for iter.Scan(&id) {
  184. count++
  185. }
  186. if err := iter.Close(); err != nil {
  187. log.Fatal("large iter:", err)
  188. }
  189. if count != 100 {
  190. log.Fatalf("expected %d, got %d", 100, count)
  191. }
  192. // Atomic Batches
  193. for _, original := range pageTestData {
  194. if err := session.Query("DELETE FROM page WHERE title = ? AND revid = ?",
  195. original.Title, original.RevId).Exec(); err != nil {
  196. log.Println("delete:", err)
  197. }
  198. }
  199. if err := session.Query("SELECT COUNT(*) FROM page").Scan(&count); err != nil {
  200. log.Fatal("getCount: ", err)
  201. }
  202. if count != 0 {
  203. log.Printf("count: expected %d, got %d", len(pageTestData), count)
  204. }
  205. if err := insertBatch(); err != nil {
  206. log.Fatal("insertBatch: ", err)
  207. }
  208. }
  209. }