Joni Atif
Joni Atif

Reputation: 61

How to do INSERT IF NOT EXIST in gocql

I've been reading http://godoc.org/github.com/gocql/gocql Yet I don't understand how to do INSERT -- IF NOT EXIST with gocql.
It stated that

func (*Query) ScanCAS

func (q *Query) ScanCAS(dest ...interface{}) (applied bool, err error)

ScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT statement containing an IF clause). If the transaction fails because the existing values did not match, the previous values will be stored in dest.

When I run

cluster := gocql.NewCluster("127.0.0.1")
cluster.Keyspace = "example"
cluster.Consistency = gocql.Quorum
session, _ := cluster.CreateSession()
defer session.Close()

var mapQ map[string]interface{}
var inserted bool
var id gocql.UUID
var timeline, text string
// insert a tweet
isTrue, err := session.Query(`INSERT INTO tweet (timeline, id, text) VALUES (?, ?, ?) IF NOT EXIST`,
    "hermano", gocql.TimeUUID(), "good night").
    ScanCAS(); if err != nil {
    log.Println(err)
}
fmt.Println(timeline, id, text)
fmt.Printf("%+v\n", isTrue)
fmt.Printf("%+v\n", inserted)
fmt.Printf("%+v\n", mapQ)

I get:
Failed parsing statement: [INSERT INTO tweet (timeline, id, text) VALUES (?, ?, ?) IF NOT EXIST] reason: ArrayIndexOutOfBoundsException -1

So my question is:
1. How to actually do INSERT IF NOT EXIST in gocql? Can you guys give me any example?
2. How to do proper ScanCAS?
3. What makes MapScanCAS and ScanCAS different? I don't understand what column mismatching are the author is talking about
4. Are there any good page that explains gocql beside its godoc page?

Upvotes: 1

Views: 3234

Answers (2)

Ertai Duo
Ertai Duo

Reputation: 11

My understanding:

How to actually do INSERT IF NOT EXIST in gocql? Can you guys give me any example?

Since the LWT you are executing needs to read data from Cassandra first and decide if the value should be inserted/updated, ScanCAS will return 1) whether the change of this LWT is applied, 2) if not applied, ScanCAS will return the existing value(s) in Cassandra. So in ScanCAS you should try to read the same type of data you are inserting.

How to do proper ScanCAS?

Similar to question 1.

What makes MapScanCAS and ScanCAS different? I don't understand what column mismatching are the author is talking about

I think the author means that it is easy to mess up the order of scanning the returned values/columns, so you could use MapScanCAS to avoid this issue

Upvotes: 1

user3562417
user3562417

Reputation: 256

looks like a typo, you should use "IF NOT EXISTS"

Upvotes: 0

Related Questions