Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How will i know that record was duplicate or it was inserted successfully?

Here is my CQL table:

CREATE TABLE user_login (
    userName varchar PRIMARY KEY,
    userId uuid,
    fullName varchar,
    password text,
    blocked boolean
);

I have this datastax java driver code

PreparedStatement prepareStmt= instances.getCqlSession().prepare("INSERT INTO "+ AppConstants.KEYSPACE+".user_info(userId, userName, fullName, bizzCateg, userType, blocked) VALUES(?, ?, ?, ?, ?, ?);");

batch.add(prepareStmt.bind(userId, userData.getEmail(), userData.getName(), userData.getBizzCategory(), userData.getUserType(), false));


PreparedStatement pstmtUserLogin = instances.getCqlSession().prepare("INSERT INTO "+ AppConstants.KEYSPACE+".user_login(userName, userId, fullName, password, blocked) VALUES(?, ?, ?, ?, ?) IF NOT EXIST");

batch.add(pstmtUserLogin.bind(userData.getEmail(), userId, userData.getName(), passwordEncoder.encode(userData.getPwd()), false));
            instances.getCqlSession().executeAsync(batch);

Here the problem is that if I remove IF NOT EXIST all work fine but if put it back it simply do not insert records in table nor throw any error.

So how will i know that i am inserting duplicate userName ?

I am using cassandra 2.0.1

like image 987
Manish Kumar Avatar asked Jul 13 '15 18:07

Manish Kumar


1 Answers

Use INSERT... IF NOT EXISTS, then you can use ResultSet#wasApplied() to check the outcome:

ResultSet rs = session.execute("insert into user (name) values ('foo') if not exists");
System.out.println(rs.wasApplied());

Notes:

  • this CQL query is a lightweight transaction, that carries performance implications. See this article for more information.
  • your example only has one statement, you don't need a batch
like image 186
Olivier Michallat Avatar answered Nov 15 '22 09:11

Olivier Michallat