Example #1
0
func TestStructToMap(t *testing.T) {
	//Test that if the value is not a struct we return nil, false
	m, ok := StructToMap("str")
	if m != nil {
		t.Error("map is not nil when val is a string")
	}
	if ok {
		t.Error("ok result from StructToMap when the val is a string")

	}

	tweet := Tweet{
		"t",
		gocql.TimeUUID(),
		"ignored",
		"hello gocassa",
		nil,
	}

	m, ok = StructToMap(tweet)
	if !ok {
		t.Error("ok is false for a tweet")
	}

	if m["Timeline"] != tweet.Timeline {
		t.Errorf("Expected %s but got %s", tweet.Timeline, m["Timeline"])
	}

	if m["id"] != tweet.ID {
		t.Errorf("Expected %s but got %s", tweet.ID, m["id"])
	}
	if m["Text"] != tweet.Text {
		t.Errorf("Expected %s but got %s", tweet.Text, m["Text"])
	}
	if m["OriginalTweet"] != tweet.OriginalTweet {
		t.Errorf("Expected %v but got %s", tweet.OriginalTweet, m["OriginalTweet"])
	}
	if _, ok := m["Ignore"]; ok {
		t.Errorf("Igonred should be empty but got %s instead", m["Ignored"])
	}

	id := gocql.TimeUUID()
	tweet.OriginalTweet = &id
	m, _ = StructToMap(tweet)
	if m["OriginalTweet"] != tweet.OriginalTweet {
		t.Errorf("Expected nil but got %s", m["OriginalTweet"])
	}
}
Example #2
0
File: sensor.go Project: arkxu/cqlc
func main() {

	session := integration.TestSession("127.0.0.1", "cqlc")
	integration.Truncate(session, EVENTS)

	result := "FAILED"

	ctx := cqlc.NewContext()

	var sensorId int64 = 100

	ctx.Upsert(EVENTS).
		SetInt64(EVENTS.SENSOR, sensorId).
		SetTimeUUID(EVENTS.TIMESTAMP, gocql.TimeUUID()).
		SetFloat32(EVENTS.TEMPERATURE, 19.8).
		SetInt32(EVENTS.PRESSURE, 357).
		Exec(session)

	iter, err := ctx.Select().
		From(EVENTS).
		Where(
			EVENTS.SENSOR.Eq(sensorId),
			EVENTS.TIMESTAMP.Lt(gocql.TimeUUID())).
		Fetch(session)

	if err != nil {
		log.Fatalf("Could not execute query: %v", err)
		return
	}

	events, err := BindEvents(iter)
	if err != nil {
		log.Fatalf("Could not bind data: %v", err)
		return
	}

	err = iter.Close()
	if err != nil {
		log.Fatalf("Could not bind data: %v", err)
		return
	}

	if len(events) == 1 {
		result = "PASSED"
	}

	os.Stdout.WriteString(result)
}
Example #3
0
func TestFieldsAndValues(t *testing.T) {
	var emptyUUID gocql.UUID
	id := gocql.TimeUUID()
	var nilID *gocql.UUID
	var tests = []struct {
		tweet  Tweet
		fields []string
		values []interface{}
	}{
		{
			Tweet{},
			[]string{"Timeline", "id", "Text", "OriginalTweet"},
			[]interface{}{"", emptyUUID, "", nilID},
		},
		{
			Tweet{"timeline1", id, "ignored", "hello gocassa", &id},
			[]string{"Timeline", "id", "Text", "OriginalTweet"},
			[]interface{}{"timeline1", id, "hello gocassa", &id},
		},
	}
	for _, test := range tests {
		fields, values, _ := FieldsAndValues(test.tweet)
		assertFieldsEqual(t, test.fields, fields)
		assertValuesEqual(t, test.values, values)
	}
}
Example #4
0
func (asset *Asset) Save(session *gocql.Session) error {
	if asset.Id.Timestamp() == 0 {
		asset.Id = gocql.TimeUUID()
		if err := session.Query(`INSERT INTO assets (id, name, path, contenttype, createdat, binary) VALUES (?, ?, ?, ?, ?, ?)`,
			asset.Id, asset.Name, strings.Join(asset.Path, ","), asset.ContentType, asset.CreatedAt, asset.Binary).Exec(); err != nil {
			glog.Fatal(err)
			return err
		}

		if err := session.Query(`INSERT INTO assetbypaths (path, id, name) VALUES (?, ?, ?)`,
			strings.Join(asset.Path, ","), asset.Id, asset.Name).Exec(); err != nil {
			glog.Fatal(err)
			return err
		}
		return nil
	} else {
		if err := session.Query(`UPDATE assets SET name = ?, path = ?, contenttype = ? WHERE id = ?`,
			asset.Name, strings.Join(asset.Path, ","), asset.ContentType, asset.Id).Exec(); err != nil {
			glog.Fatal(err)
			return err
		}

		if err := session.Query(`UPDATE assetbypaths SET name = ?, path = ? WHERE id = ?`,
			asset.Name, strings.Join(asset.Path, ","), asset.Id).Exec(); err != nil {
			glog.Fatal(err)
			return err
		}
		return nil
	}
}
Example #5
0
func NewTweet(timeLine, text string) (tw *Tweet) {
	tw = new(Tweet)
	tw.Timeline = timeLine
	tw.Text = text
	tw.Id = gocql.TimeUUID()
	return
}
Example #6
0
func main() {

	session := integration.TestSession("127.0.0.1", "cqlc")
	session.SetPageSize(1000)
	integration.Truncate(session, EVENTS)

	result := "FAILED"

	ctx := cqlc.NewContext()
	batch := gocql.NewBatch(gocql.LoggedBatch)

	rounds := 10
	distinct := 10

	for i := 0; i < rounds; i++ {
		for j := 0; j < distinct; j++ {
			ctx.Upsert(EVENTS).
				SetInt64(EVENTS.SENSOR, int64(j)).
				SetTimeUUID(EVENTS.TIMESTAMP, gocql.TimeUUID()).
				SetFloat32(EVENTS.TEMPERATURE, 19.8).
				SetInt32(EVENTS.PRESSURE, 357).
				Batch(batch)
		}
	}

	err := session.ExecuteBatch(batch)

	if err != nil {
		log.Fatalf("Could not execute batch: %v", err)
		os.Exit(1)
	}

	iter, err := ctx.SelectDistinct(EVENTS.SENSOR).From(EVENTS).Fetch(session)
	if err != nil {
		log.Fatalf("Could not prepare query: %v", err)
		os.Exit(1)
	}

	count := 0

	MapEvents(iter, func(e Events) (bool, error) {
		count++
		return true, nil
	})

	if err := iter.Close(); err != nil {
		log.Fatalf("Could not close iterator: %v", err)
		os.Exit(1)
	}

	if count == distinct {
		result = "PASSED"
	} else {
		result = fmt.Sprintf("Expected %d distinct rows; got %d", distinct, count)
	}

	os.Stdout.WriteString(result)
}
Example #7
0
func (querier Querier) InsertCachedComment(id, htmlString string) error {
	if err := querier.Session.Query(`INSERT INTO caches (id, post_id, content) VALUES (?, ?, ?)`,
		gocql.TimeUUID(),
		id,
		htmlString).Exec(); err != nil {
		return err
	}
	return nil
}
Example #8
0
func TestHighLevelAPIOnly(t *testing.T) {

	type Message struct {
		Identifier gocql.UUID
		Epoch      int64
		User       string
		Payload    []byte
	}

	strat := map[string]string{
		"id":   "Identifier",
		"unix": "Epoch",
		"usr":  "******",
		"msg":  "Payload",
	}

	s := setup(t, "queue")

	msgs := 163

	for i := 0; i < msgs; i++ {
		msg := make([]byte, 64)
		_, err := rand.Read(msg)
		if err != nil {
			t.Fatal(err)
		}

		m := Message{
			Identifier: gocql.TimeUUID(),
			Epoch:      time.Now().Unix(),
			User:       "******",
			Payload:    msg,
		}

		if err := Bind(`INSERT INTO queue (id, unix, usr, msg) VALUES (?, ?, ?, ?)`, m).Map(strat).Exec(s); err != nil {
			t.Fatal(err)
		}
	}

	q := s.Query(`SELECT id, unix, usr, msg FROM queue`)

	b := BindQuery(q).Map(strat)

	count := 0
	var m Message

	for b.Scan(&m) {
		count++
		assert.Equal(t, "deamon", m.User)
	}

	err := b.Close()
	assert.Nil(t, err, "Could not close binding")
	assert.Equal(t, msgs, count)

}
Example #9
0
func (this *Tweet) Save() error {
	session, _ := db.cluster.CreateSession()
	defer session.Close()

	query := `INSERT INTO tweets (id, user, body) VALUES (?, ?, ?)`
	if err := session.Query(query, gocql.TimeUUID(), this.User, this.Body).Exec(); err != nil {
		return err
	}
	return nil
}
Example #10
0
// Report failure stats to cassandra.
func (stat ValkyrieCassandraStats) Failure(err error, clientId, serviceId string) error {
	hour := timestamp(HOUR)
	id := gocql.TimeUUID()
	insertStmt := "INSERT INTO request_errors (hour, client_id, service_id, id, reason) VALUES (?, ?, ?, ?, ?)"
	e := stat.session.Query(insertStmt, hour, clientId, serviceId, id, err.Error()).Exec()
	if e != nil {
		log.Println(e)
		return e
	}
	return nil
}
Example #11
0
// Report trace stats to cassandra.
func (stat ValkyrieCassandraStats) Trace(event string, start, end time.Time, duration time.Duration) error {
	hour := timestamp(HOUR)
	id := gocql.TimeUUID()
	insertStmt := "INSERT INTO traces (hour, event, start, end, duration, id) VALUES (?, ?, ?, ?, ?, ?)"
	err := stat.session.Query(insertStmt, hour, event, start, end, duration.Nanoseconds(), id).Exec()
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}
Example #12
0
File: sub.go Project: DrewWeth/eta
func (querier Querier) InsertSub(subName string) error {
	if err := querier.Session.Query(`INSERT INTO subs (id, name, subscribers, created_at, updated_at) VALUES (?, ?, ?, ?, ?)`,
		gocql.TimeUUID(),
		subName,
		0,
		time.Now(),
		time.Now()).Exec(); err != nil {
		return err
	}
	return nil
}
Example #13
0
// Report general failure stats to cassandra.
func (stat ValkyrieCassandraStats) GeneralFailure(err error) error {
	hour := timestamp(HOUR)
	id := gocql.TimeUUID()
	insertStmt := "INSERT INTO errors (hour, id, reason) VALUES (?, ?, ?)"
	e := stat.session.Query(insertStmt, hour, id, err.Error()).Exec()
	if e != nil {
		log.Println(e)
		return e
	}
	return nil
}
Example #14
0
func (suite *ExamplesSuite) SetupSuite() {
	suite.id = gocql.TimeUUID()
	suite.executeTemplate(upTemplate)

	cluster := gocql.NewCluster(cassandraConfig.Hosts...)
	cluster.Keyspace = cassandraConfig.Keyspace
	if session, sessionErr := cluster.CreateSession(); nil == sessionErr {
		suite.session = session
	} else {
		panic(sessionErr.Error())
	}
}
Example #15
0
//-----------------------------------------------------------------------------
// Test
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Insert
//-----------------------------------------------------------------------------
func TestInsert(t *testing.T) {
	db := GetCass()
	//INSERT
	sql := `INSERT INTO t_users
	(id, first_name, last_name, email, password, age, created_at, updated_at)
	VALUES
	(?, ?, ?, ?, ?, ?, ?, ?)`

	err := db.Session.Query(sql, gocql.TimeUUID(), "taro", "yamada", "*****@*****.**", "aaaa", 24, time.Now(), time.Now()).Exec()
	if err != nil {
		t.Errorf("INSERT error: %s", err)
	}
}
Example #16
0
func (suite *ExamplesSuite) TestInstanceMapper_InsertQuery() {
	exampleTable := &ExampleTable{
		Id:    gocql.TimeUUID(),
		Value: "NewValue",
	}

	mapper, _ := cqlmapper.Underscore.NewInstanceMapper(exampleTable)

	insertQuery := suite.session.Query(mapper.InsertQuery(), mapper.FieldValues()...)

	if execErr := insertQuery.Exec(); nil != execErr {
		panic(execErr.Error())
	}

}
Example #17
0
File: post.go Project: DrewWeth/eta
func (querier *Querier) InsertPost(subName, title, comment, link string) error {
	if err := querier.Session.Query(`INSERT INTO posts (id, sub_id, title, comment, link, upvotes, downvotes, comment_count, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
		gocql.TimeUUID(),
		subName,
		title,
		comment,
		link,
		0,
		0,
		0,
		time.Now(),
		time.Now(),
	).Exec(); err != nil {
		return err
	}
	return nil
}
Example #18
0
func (querier *Querier) InsertComment(postID, parentID, content string) error {
	if err := querier.Session.Query(`INSERT INTO comments (id, post_id, parent_id, content, upvotes, downvotes, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
		gocql.TimeUUID(),
		postID,
		parentID,
		content,
		0,
		0,
		time.Now(),
		time.Now()).Exec(); err != nil {
		return err
	}
	// err := querier.UpCommentCount(postID)
	// if err !=nil{
	// 	log.Println("UpCommentCount encountered error on id:", postID)
	// 	return err
	// }
	return nil
}
Example #19
0
// Create a new template record: a brand new template, a new template commit (version), or just a template release
func (t *Template) CreateTemplate() error {

	//flatten files
	files_str := ""
	if &t.Files != nil && len(t.Files) > 0 {
		var files []string
		for _, file := range t.Files {
			files = append(files, file.toString())
		}
		files_str = strings.Join(files, ",")
	}

	query_str := fmt.Sprintf(QUERY_STR_INSERT_TEMPLATE, gocql.TimeUUID(), t.Template_name, t.Template_hash, t.Commit_info.toString(), files_str, t.Release_info.toString())

	//DEDBUG
	fmt.Println(query_str)
	err := Conn.Query(query_str).Exec()

	return err

}
Example #20
0
//TestNoCaseColumns is a test case to verify case insensitive columns are mapped properly
func TestNoCaseColumns(t *testing.T) {

	type Tweet struct {
		TimeLine string
		Id       gocql.UUID
		Text     string
	}

	s := setup(t, "tweet")
	defer s.Close()

	tw := Tweet{
		TimeLine: "me",
		Id:       gocql.TimeUUID(),
		Text:     fmt.Sprintf("hello world %d", 1),
	}

	if err := Bind(`INSERT INTO tweet (timeline, Id, Text) VALUES (?, ?, ?)`, tw).Exec(s); err != nil {
		t.Fatal(err)
	}

}
Example #21
0
func (p *Player) Create() error {

	p.Exists = false

	for {
		p.UUID = gocql.TimeUUID()
		var row = map[string]interface{}{}

		var apply bool
		var err error

		if apply, err = CQLSession.Query(`insert into players (player_uuid,create_time) values (?,now()) if not exists`, p.UUID).MapScanCAS(row); err != nil {
			logger.Error(errors.New(err))
			return err
		}

		if apply {
			break
		}
	}

	return nil
}
Example #22
0
func main() {
	// NOTE: copied from gocql readme
	cluster := gocql.NewCluster("192.168.99.100")
	cluster.ProtoVersion = 4
	cluster.Keyspace = "example"
	cluster.Consistency = gocql.One // was ".Quorum"
	session, _ := cluster.CreateSession()
	defer session.Close()

	// insert a tweet
	if err := session.Query(`INSERT INTO tweet (timeline, id, text) VALUES (?, ?, ?)`,
		"me", gocql.TimeUUID(), "hello world").Exec(); err != nil {
		log.Fatal(err)
	}

	var id gocql.UUID
	var text string

	/* Search for a specific set of records whose 'timeline' column matches
	 * the value 'me'. The secondary index that we created earlier will be
	 * used for optimizing the search */
	if err := session.Query(`SELECT id, text FROM tweet WHERE timeline = ? LIMIT 1`,
		"me").Consistency(gocql.One).Scan(&id, &text); err != nil {
		log.Fatal(err)
	}
	fmt.Println("Tweet:", id, text)

	// list all tweets
	iter := session.Query(`SELECT id, text FROM tweet WHERE timeline = ?`, "me").Iter()
	for iter.Scan(&id, &text) {
		fmt.Println("Tweet:", id, text)
	}
	if err := iter.Close(); err != nil {
		log.Fatal(err)
	}
}
Example #23
0
//TestCasedColumns is a test case to verify case sensitive columns are mapped properly
func TestCasedColumns(t *testing.T) {

	type Tweet struct {
		TimeLine string `cql:"timeLine"`
		Timeline string
		Id       gocql.UUID
		Text     string
	}

	s := setup(t, "tweetcase")
	defer s.Close()

	tw := Tweet{
		TimeLine: "me",
		Timeline: "me2",
		Id:       gocql.TimeUUID(),
		Text:     fmt.Sprintf("hello world %d", 1),
	}

	if err := Bind(`INSERT INTO tweetcase ("timeLine", timeline, Id, Text) VALUES (?,?, ?, ?)`, tw).Exec(s); err != nil {
		t.Fatal(err)
	}

	q := s.Query(`SELECT "timeLine", timeline, Id, Text FROM tweetcase`)

	b := BindQuery(q)

	var twr Tweet

	for b.Scan(&twr) {
		assert.Equal(t, tw, twr)
	}

	err := b.Close()
	assert.Nil(t, err, "Could not close binding")
}
Example #24
0
func (s *Session) Create(remoteAddr string, userAgent string) {

	s.Exists = false

	for {
		s.UUID = gocql.TimeUUID()
		var row = model.Fields{}

		var apply bool
		var err error

		if apply, err = CQLSession.Query(`insert into auth_sessions (session_uuid,last_access,create_time, remote_addr, user_agent) values (?,now(),now(),?,?) if not exists`, s.UUID, remoteAddr, userAgent).MapScanCAS(row); err != nil {
			logger.Error(errors.New(err))
			return
		}

		if apply {
			break
		}
	}

	s.Load()

}
Example #25
0
func TestMapToStruct(t *testing.T) {

	m := make(map[string]interface{})
	assert := func() {
		tweet := Tweet{}
		if err := MapToStruct(m, &tweet); err != nil {
			t.Fatal(err.Error())
		}
		timeline, ok := m["Timeline"]
		if ok {
			if timeline != tweet.Timeline {
				t.Errorf("Expected timeline to be %s but got %s", timeline, tweet.Timeline)
			}
		} else {
			if "" != tweet.Timeline {
				t.Errorf("Expected timeline to be empty but got %s", tweet.Timeline)
			}
		}
		id, ok := m["id"]
		if ok {
			if id != tweet.ID {
				t.Errorf("Expected id to be %s but got %s", id, tweet.ID)
			}
		} else {
			var emptyID gocql.UUID
			if emptyID != tweet.ID {
				t.Errorf("Expected id to be empty but got %s", tweet.ID)
			}
		}
		text, ok := m["teXt"]
		if ok {
			if text != tweet.Text {
				t.Errorf("Expected text to be %s but got %s", text, tweet.Text)
			}
		} else {
			if "" != tweet.Text {
				t.Errorf("Expected text to be empty but got %s", tweet.Text)
			}
		}

		originalTweet, ok := m["OriginalTweet"]
		if ok {
			if originalTweet != tweet.OriginalTweet {
				t.Errorf("Expected original tweet to be %s but got %s",
					originalTweet, tweet.OriginalTweet)
			}
		} else {
			if nil != tweet.OriginalTweet {
				t.Errorf("Expected original tweet to be empty but got %s",
					tweet.OriginalTweet)
			}
		}
		//Ignored should be always empty
		if tweet.Ingored != "" {
			t.Errorf("Expected ignored to be empty but got %s",
				tweet.Ingored)
		}
	}

	assert()
	m["Timeline"] = "timeline"
	assert()
	m["id"] = gocql.TimeUUID()
	assert()
	m["text"] = "Hello gocassa"
	assert()
	id := gocql.TimeUUID()
	m["OriginalTweet"] = &id
	assert()
	m["Ignored"] = "ignored"
	assert()
}
Example #26
0
func (this *Tweet) GenerateId() {
	this.Id = gocql.TimeUUID()
}
Example #27
0
File: limit.go Project: arkxu/cqlc
func main() {

	session := integration.TestSession("127.0.0.1", "cqlc")
	integration.Truncate(session, EVENTS)

	result := "FAILED"

	ctx := cqlc.NewContext()
	batch := gocql.NewBatch(gocql.LoggedBatch)

	events := 100

	for i := 0; i < events; i++ {
		ctx.Upsert(EVENTS).
			SetInt64(EVENTS.SENSOR, int64(100)).
			SetTimeUUID(EVENTS.TIMESTAMP, gocql.TimeUUID()).
			SetFloat32(EVENTS.TEMPERATURE, 19.8).
			SetInt32(EVENTS.PRESSURE, 357).
			Batch(batch)
	}

	if err := session.ExecuteBatch(batch); err != nil {
		log.Fatalf("Could not execute batch: %v", err)
		os.Exit(1)
	}

	limit := 11

	iter, err := ctx.Select(EVENTS.SENSOR).
		From(EVENTS).
		Limit(limit).
		Fetch(session)

	if err != nil {
		log.Fatalf("Could not execute query: %v", err)
		os.Exit(1)
	}

	count := 0

	MapEvents(iter, func(e Events) (bool, error) {
		count++
		return true, nil
	})

	if count == limit {

		limit = 14

		iter, err = ctx.Select().
			From(EVENTS).
			Where(EVENTS.SENSOR.Eq(int64(100))).
			Limit(limit).
			Fetch(session)

		count := 0

		MapEvents(iter, func(e Events) (bool, error) {
			count++
			return true, nil
		})

		if count == limit {
			result = "PASSED"
		} else {
			result = fmt.Sprintf("Expected limit of %d; got %d rows", limit, count)
		}

	} else {
		result = fmt.Sprintf("Expected limit of %d; got %d rows", limit, count)
	}

	if err != nil {
		log.Fatalf("Could not execute query: %v", err)
		os.Exit(1)
	}

	os.Stdout.WriteString(result)
}
Example #28
0
func main() {

	session := integration.TestSession("127.0.0.1", "cqlc")
	integration.Truncate(session, EVENTS)

	result := "FAILED"

	ctx := cqlc.NewContext()
	batch := gocql.NewBatch(gocql.LoggedBatch)

	events := 50 * 1000
	batchSize := 1000

	for i := 0; i < events; i++ {
		ctx.Upsert(EVENTS).
			SetInt64(EVENTS.SENSOR, int64(i)).
			SetTimeUUID(EVENTS.TIMESTAMP, gocql.TimeUUID()).
			SetFloat32(EVENTS.TEMPERATURE, 19.8).
			SetInt32(EVENTS.PRESSURE, 357).
			Batch(batch)

		if i%batchSize == 0 {
			if err := session.ExecuteBatch(batch); err != nil {
				log.Fatalf("Could not execute batch: %v", err)
				os.Exit(1)
			}
			batch = gocql.NewBatch(gocql.LoggedBatch)
		}
	}

	err := session.ExecuteBatch(batch)

	if err != nil {
		log.Fatalf("Could not execute batch: %v", err)
		os.Exit(1)
	}

	query, err := ctx.Select().From(EVENTS).Prepare(session)
	if err != nil {
		log.Fatalf("Could not prepare query: %v", err)
		os.Exit(1)
	}

	query.PageSize(100)
	iter := query.Iter()
	count := 0

	MapEvents(iter, func(e Events) (bool, error) {
		count++
		return true, nil
	})

	if err := iter.Close(); err != nil {
		log.Fatalf("Could not close iterator: %v", err)
		os.Exit(1)
	}

	if count == events {
		result = "PASSED"
	}

	os.Stdout.WriteString(result)
}
Example #29
0
func main() {
	session := integration.TestSession("127.0.0.1", "cqlc")
	integration.Truncate(session, FIRST_TIMELINE)
	integration.Truncate(session, SECOND_TIMELINE)

	result := "FAILED"

	timestamp := gocql.TimeUUID()

	first := FirstTimeline{
		When: timestamp,
		Tag:  "foobar",
	}

	second := SecondTimeline{
		When:      timestamp,
		Latitude:  50.12,
		Longitude: 0.87,
	}

	ctx := cqlc.NewContext()
	err := ctx.Store(FIRST_TIMELINE.Bind(first)).Exec(session)
	err = ctx.Store(SECOND_TIMELINE.Bind(second)).Exec(session)

	if err != nil {
		log.Fatalf("Could not execute upsert: %v", err)
		os.Exit(1)
	}

	var tag string
	var latitude float32

	f1, err := fetchOne(ctx, session, FIRST_TIMELINE, timestamp, FIRST_TIMELINE.TAG.To(&tag))
	f2, err := fetchOne(ctx, session, SECOND_TIMELINE, timestamp, SECOND_TIMELINE.LATITUDE.To(&latitude))

	if err != nil {
		log.Fatalf("Could not execute select: %v", err)
		os.Exit(1)
	}

	if f1 && f2 && tag == "foobar" && math.Float32bits(latitude) == math.Float32bits(50.12) {

		// TODO Implement a FROM binding
		t := "bar"
		l := float32(72.34)

		err = upsert(ctx, session, FIRST_TIMELINE, timestamp, FIRST_TIMELINE.TAG.To(&t))
		err = upsert(ctx, session, SECOND_TIMELINE, timestamp, SECOND_TIMELINE.LATITUDE.To(&l))

		if err != nil {
			log.Fatalf("Could not execute upsert: %v", err)
			os.Exit(1)
		}

		f1, err = fetchOne(ctx, session, FIRST_TIMELINE, timestamp, FIRST_TIMELINE.TAG.To(&tag))
		f2, err = fetchOne(ctx, session, SECOND_TIMELINE, timestamp, SECOND_TIMELINE.LATITUDE.To(&latitude))

		if err != nil {
			log.Fatalf("Could not execute select: %v", err)
			os.Exit(1)
		}

		if f1 && f2 && tag == t && math.Float32bits(latitude) == math.Float32bits(l) {

			err = deleteByTimestamp(ctx, session, FIRST_TIMELINE, timestamp)
			err = deleteByTimestamp(ctx, session, SECOND_TIMELINE, timestamp)

			if err != nil {
				log.Fatalf("Could not execute delete: %v", err)
				os.Exit(1)
			}

			var tag string
			var latitude float32

			f1, err = fetchOne(ctx, session, FIRST_TIMELINE, timestamp, FIRST_TIMELINE.TAG.To(&tag))
			f2, err = fetchOne(ctx, session, SECOND_TIMELINE, timestamp, SECOND_TIMELINE.LATITUDE.To(&latitude))

			if err != nil {
				log.Fatalf("Could not execute select: %v", err)
				os.Exit(1)
			}

			if !f1 && !f2 && tag == "" && latitude == 0.0 {
				result = "PASSED"
			} else {
				result = fmt.Sprintf("After delete - Tag was: %s; Latitude was %f", tag, latitude)
			}
		} else {
			result = fmt.Sprintf("After upsert - Tag was: %s; Latitude was %f", tag, latitude)
		}

	} else {
		result = fmt.Sprintf("Before delete - Tag was: %s; Latitude was %f", tag, latitude)
	}

	os.Stdout.WriteString(result)
}
Example #30
0
func main() {

	session := integration.TestSession("127.0.0.1", "cqlc")
	integration.Truncate(session, BASIC)

	result := "FAILED"

	ctx := cqlc.NewContext()

	basic := Basic{
		Id:              "x",
		Int32Column:     999,
		Int64Column:     1 << 55,
		AsciiColumn:     "do-re-me",
		TimestampColumn: time.Date(1999, time.December, 31, 23, 59, 59, 59, time.UTC), // Keep it simple for reflect.DeepEqual
		BooleanColumn:   true,
		TextColumn:      "ipso",
		VarcharColumn:   "lorem",
		FloatColumn:     math.MaxFloat32,
		DoubleColumn:    math.MaxFloat64,
		DecimalColumn:   inf.NewDec(1, 9),
		TimeuuidColumn:  gocql.TimeUUID(),
		MapColumn:       map[string]string{"baz": "quux"},
		ArrayColumn:     []string{"baz", "quux"},
	}

	err := ctx.Store(BASIC.Bind(basic)).Exec(session)

	if err != nil {
		log.Fatalf("Could not bind data: %v", err)
		os.Exit(1)
	}

	var int32Column int32
	var decimalColumn *inf.Dec

	found, err := ctx.Select().
		From(BASIC).
		Where(BASIC.ID.Eq("x")).
		Bind(BASIC.INT32_COLUMN.To(&int32Column), BASIC.DECIMAL_COLUMN.To(&decimalColumn)).
		FetchOne(session)

	if err != nil {
		log.Fatalf("Could not bind data: %v", err)
		os.Exit(1)
	}

	if err != nil {
		log.Fatalf("Could not bind data: %v", err)
		os.Exit(1)
	}

	if int32Column == 999 && reflect.DeepEqual(decimalColumn, basic.DecimalColumn) && found {

		found, err := ctx.Select().
			From(BASIC).
			Where(BASIC.ID.Eq("y")).
			Bind(BASIC.INT32_COLUMN.To(&int32Column), BASIC.DECIMAL_COLUMN.To(&decimalColumn)).
			FetchOne(session)

		if err != nil {
			log.Fatalf("Could not bind data: %v", err)
			os.Exit(1)
		}

		if !found {
			result = "PASSED"
		}

	} else {
		result = fmt.Sprintf("int32Column: %d, decimalColumn %v", int32Column, decimalColumn)
	}

	os.Stdout.WriteString(result)

}