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

爱⌒轻易说出口 提交于 2019-12-07 02:33:56

问题


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


回答1:


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



回答2:


Looks like you need an ACID transaction and Cassandra, simply put, is not ACID. You have absolutely no guarantee that in the interval you check if username exists it will not be created from someone else. Besides that, in CQL standard INSERT and UPDATE do the same thing. They both write a "new" record marking the old ones deleted. If there are old records or not is not important. IF you want to authenticate or create a new user on the fly, I suppose you can work on a composite key username + password, and to your query as update where username =datum AND password = datum. IN this way, if the user gives you a wrong password your query fails. If user is new, he cant give a "wrong" password, and so his account is created. You can now test for a field like "alreadysubscribed" which you only set after the first login, so in case of a "just created" user will be missing



来源:https://stackoverflow.com/questions/31390419/how-will-i-know-that-record-was-duplicate-or-it-was-inserted-successfully

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!