Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Atomic set only if not already set

Is there any way to do an atomic set only if not already set in Redis?

Specifically, I'm creating a user like "myapp:user:user_email" and want Redis to give me back an error if "user_email" is already taken, instead of silently replacing the old value. Something like declare, not replace.

like image 547
Aaron Yodaiken Avatar asked Apr 23 '13 00:04

Aaron Yodaiken


People also ask

Why can’t I use atomic() when autocommit is turned off?

This bug has two consequences: The low level APIs for savepoints are only usable inside a transaction i.e. inside an atomic () block. It’s impossible to use atomic () when autocommit is turned off. If you’re using MySQL, your tables may or may not support transactions; it depends on your MySQL version and the table types you’re using.

What is the difference between atomic_fcmpset () and atomic_fetchadd ()?

The atomic_cmpset() function returns the result of the compare operation. The atomic_fcmpset() function returns true if the operation succeeded. Otherwise it returns false and sets *old to the found value. The atomic_fetchadd() , atomic_load() , atomic_readandclear() , and atomic_swap() functions return the value at the specified address.

How to ensure the atomic block is always the outermost atomic block?

It is sometimes useful to ensure an atomic block is always the outermost atomic block, ensuring that any database changes are committed when the block is exited without errors. This is known as durability and can be achieved by setting durable=True. If the atomic block is nested within another it raises a RuntimeError.

Should I use atomic() or atomic()?

You’re strongly encouraged to use atomic () rather than the functions described below, but they’re still part of the public API, and there’s no plan to deprecate them. Each of these functions takes a using argument which should be the name of a database for which the behavior applies.


1 Answers

See SETNX

Set key to hold string value if key does not exist. In that case, it is equal to SET. When key already holds a value, no operation is performed. SETNX is short for "SET if N ot e X ists".

You can check the return value. If it is 0, the key was not set, implying it already existed.

like image 148
Sripathi Krishnan Avatar answered Oct 26 '22 19:10

Sripathi Krishnan