Reputation: 10138
I want to create some record with Cassandra now()
to keep unique identifiers (generation uuid is not good since can be duplicate).
How can I do it using object mapper.
I wrote such model:
class OwnerUnique(models.Model):
__keyspace__ = 'training'
__table_name__ = 'owner_unique'
name = columns.Text(primary_key=True)
owner_id = columns.UUID()
I try to use OwnerUnique.create(owner_id='now()')
and owner_id = columns.UUID(deafult='now()')
.
Finnally I gave up and wrote raw query code - whatever maybe it is not need to write this code. I think that setting UUID from now is normal practice so we do not need such flow. How to do it in object mapper?
@classmethod
def create_unique_async(cls, name: str) -> ResponseFuture:
query = '''
insert into training.owner_unique
(name, owner_id)
values (?, now())
if not exists'''
params = {
'name': name
}
current_connection: Connection = connection.get_connection('training')
session = current_connection.session
prepared_statement = cls._prepared_statements.get(query)
if prepared_statement is None:
prepared_statement: PreparedStatement = session.prepare(query)
cls._prepared_statements[query] = prepared_statement
response_future: ResponseFuture = session.execute_async(prepared_statement, params)
return response_future
@classmethod
def create_unique(cls, name: str) -> ResultSet:
response_future = cls.create_unique_async(name)
result_set = response_future.result()
return result_set
Upvotes: 0
Views: 33
Reputation: 261
As usual @erick-ramirez has it exactly right. As discussed in the docs for the Python driver the "uuid" CQL type is mapped to the uuid.UUID Python type. Anything which generates a UUID (including the uuid4() method referenced by Erick above) should do the trick.
Upvotes: 1
Reputation: 16373
The UUID
module does not have a now()
method unlike DateTime
which has datetime.now()
(returns the local date and time). Still, it is not the same as the CQL function NOW()
which generates a time UUID which contains the current timestamp.
Try using the uuid4()
method instead to generate a unique ID with default=uuid.uuid4()
. Cheers!
Upvotes: 0