@@ -571,30 +571,32 @@ def _put_item(
571571 composite_key = self ._construct_composite_key (namespace , key )
572572 current_time = datetime .now (timezone .utc ).isoformat ()
573573
574- # Check if item exists to preserve created_at
575- existing_item = None
576- try :
577- response = self .table .get_item (Key = {"PK" : composite_key [0 ], "SK" : composite_key [1 ]})
578- existing_item = response .get ("Item" )
579- except Exception :
580- pass
581-
582- item : dict [str , Any ] = {
583- "PK" : composite_key [0 ],
584- "SK" : composite_key [1 ],
585- "value" : value ,
586- "created_at" : existing_item ["created_at" ] if existing_item else current_time ,
587- "updated_at" : current_time ,
574+ # Build update expression to set created_at only if it doesn't exist
575+ update_expression = "SET #value = :value, updated_at = :updated_at"
576+ expression_attribute_names = {"#value" : "value" }
577+ expression_attribute_values = {
578+ ":value" : value ,
579+ ":updated_at" : current_time ,
580+ ":created_at" : current_time ,
588581 }
589582
583+ # Add created_at with if_not_exists to preserve existing value
584+ update_expression += ", created_at = if_not_exists(created_at, :created_at)"
585+
590586 # Add TTL if configured
591587 if ttl is not None :
592588 expires_at = self ._calculate_expiry (ttl )
593589 if expires_at :
594- item ["expires_at" ] = expires_at
590+ update_expression += ", expires_at = :expires_at"
591+ expression_attribute_values [":expires_at" ] = expires_at
595592
596593 try :
597- self .table .put_item (Item = item )
594+ self .table .update_item (
595+ Key = {"PK" : composite_key [0 ], "SK" : composite_key [1 ]},
596+ UpdateExpression = update_expression ,
597+ ExpressionAttributeNames = expression_attribute_names ,
598+ ExpressionAttributeValues = expression_attribute_values ,
599+ )
598600 except Exception as e :
599601 logger .error (f"Error putting item { namespace } /{ key } : { e } " )
600602 raise
0 commit comments