How do I know if a record was duplicated 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 java datastax 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); 

The problem here is that if I delete IF NOT EXIST , everything will work fine, but if you put it back in, just don't insert records into the table and not cause any errors.

So how do I know that I am inserting a duplicate userName ?

I am using cassandra 2.0.1

+5
source share
2 answers

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

 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 affects performance. See this article for more details.
  • There is only one statement in your example, you do not need a package
+10
source

It looks like you need an ACID transaction, and Cassandra, just delivered, is not an ACID. You have absolutely no guarantee that during that period of time when you check if the username exists, it will not be created by someone else. In addition, in the CQL standard, INSERT and UPDATE do the same. They both record a โ€œnewโ€ record marking old deleted ones. If there are old records or not, it does not matter. If you want to authenticate or create a new user on the fly, I suppose you can work on the composite keys of the user + password, and on your request, as an update, where username = IPD and password = IPD. Thus, if the user gives an incorrect password, your request is not executed. If the user is new, he cannot enter the "wrong" password, and therefore his account is created. Now you can test a field of type "alreadysubscribed", which you set only after the first login, so if there is no "newly created" user, there will be no

-4
source

All Articles