1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| package main
import ( "fmt" "log" "time"
"github.com/gocql/gocql" "github.com/kristoiv/gocqltable" )
func main() {
c := gocql.NewCluster("10.112.68.186", "10.112.68.192") s, err := c.CreateSession() if err != nil { log.Fatalln("Unable to open up a session with the Cassandra database (err=" + err.Error() + ")") }
gocqltable.SetDefaultSession(s) fmt.Println("Gocql session setup complete")
keyspace := gocqltable.NewKeyspace("gocqltable_test")
err = keyspace.Create(map[string]interface{}{ "class": "SimpleStrategy", "replication_factor": 1, }, true) if err != nil { log.Fatalln(err) } fmt.Println("Keyspace created")
type User struct { Email string Password string Active bool Created time.Time }
userTable := struct { gocqltable.Table }{ keyspace.NewTable( "users", []string{"email"}, nil, User{}, ), }
err = userTable.Create() if err != nil { log.Fatalln(err) } fmt.Println("") fmt.Println("Table created: users")
err = userTable.Query("INSERT INTO gocqltable_test.users (email, password, active, created) VALUES (?, ?, ?, ?)", "1@example.com", "123456", true, time.Now().UTC()).Exec() if err != nil { log.Fatalln(err) } fmt.Println("User inserted: 1@example.com")
err = userTable.Query("INSERT INTO gocqltable_test.users (email, password, active, created) VALUES (?, ?, ?, ?)", "2@example.com", "123456", true, time.Now().UTC()).Exec() if err != nil { log.Fatalln(err) } fmt.Println("User inserted: 2@example.com")
err = userTable.Query("INSERT INTO gocqltable_test.users (email, password, active, created) VALUES (?, ?, ?, ?)", "3@example.com", "123456", true, time.Now().UTC()).Exec() if err != nil { log.Fatalln(err) } fmt.Println("User inserted: 3@example.com")
iter := userTable.Query("SELECT * FROM gocqltable_test.users").Fetch() fmt.Println("") fmt.Println("Fetched all from users:") for row := range iter.Range() { user := row.(*User) fmt.Println("User:", user) } if err := iter.Close(); err != nil { log.Fatalln(err) }
row, err := userTable.Query(`SELECT * FROM gocqltable_test.users WHERE email = ? LIMIT 1`, "2@example.com").FetchRow() if err != nil { log.Fatalln(err) } user := row.(*User) fmt.Println("") fmt.Println("Fetched single row by email: ", user)
keyspace.Drop() fmt.Println("") fmt.Println("Keyspace dropped") }
|