Search code examples
flaskcassandracassandra-3.0cqlengine

CqlEngine model primary_key not raising Unique Error


I am using CassandraDB in a flask project

I have created a User Model which has email as the primary_key.

class User(Model):
    __table_name__ = 'user'

    user_id = UUID(primary_key=True)
    email = Text(max_length=120, primary_key=True)
    first_name = Text()
    last_name = Text()

python code:

user_data = {'email': 'john@example.com', "first_name":'John', "last_name":'Doe'}
user = User(**user_data)
user.save()

the Above code correctly creates the user as required

user_data = {'email': 'john@example.com', "first_name":'Johnny', "last_name":'Daves'}
user = User(**user_data)
user.save()

Now the above code updates the existing User 'john doe' to 'johnny daves'. what I was expecting to get was an error raised by cqlengine stating "user with email john@example.com already exists"

Why did it not raise the error? Am I doing something wrong?


Solution

  • I manage to figure out the answer, after going through the code I was able to notice that Model class has an property called _if_not_exists = False which if set will raise LWTException indicating that the object already exists in the database and you cannot create it.

    class User(Model):
        __table_name__ = 'user'
        _if_not_exists = True  
    
        user_id = UUID(primary_key=True)
        email = Text(max_length=120, primary_key=True)
        first_name = Text()
        last_name = Text()
    

    as shown above setting _if_not_exists = True in the model solved my problem :)