U
    ÓZjÚ(  ã                   @   s‚   d dl Z d dlZd dlmZ d dlmZ d dlmZ ddlm	Z	 ej
rnd dlmZmZ d dlmZ d d	lmZ G d
d„ deƒZdS )é    N)ÚResourceNotExistsError)ÚAbstractPersistenceAdapter)ÚPersistenceExceptioné   )Úuser_id_partition_keygen)ÚCallableÚDict)ÚRequestEnvelope)ÚServiceResourcec                   @   sJ   e Zd ZdZdddee d¡fdd„Zdd	„ Zd
d„ Z	dd„ Z
dd„ ZdS )ÚDynamoDbAdapteraü  Persistence Adapter implementation using Amazon DynamoDb.

    Amazon DynamoDb based persistence adapter implementation. This
    internally uses the AWS Python SDK (`boto3`) to process the
    dynamodb operations. The adapter tries to create the table if
    ``create_table`` is set, during initialization.

    :param table_name: Name of the table to be created or used
    :type table_name: str
    :param partition_key_name: Partition key name to be used.
        Defaulted to 'id'
    :type partition_key_name: str
    :param attribute_name: Attribute name for storing and
        retrieving attributes from dynamodb.
        Defaulted to 'attributes'
    :type attribute_name: str
    :param create_table: Should the adapter try to create the table
        if it doesn't exist. Defaulted to False
    :type create_table: bool
    :param partition_keygen: Callable function that takes a
        request envelope and provides a unique partition key value.
        Defaulted to user id keygen function
    :type partition_keygen: Callable[[RequestEnvelope], str]
    :param dynamodb_resource: Resource to be used, to perform
        dynamo operations. Defaulted to resource generated from
        boto3
    :type dynamodb_resource: boto3.resources.base.ServiceResource
    ÚidÚ
attributesFÚdynamodbc                 C   s0   || _ || _|| _|| _|| _|| _|  ¡  dS )a^  Persistence Adapter implementation using Amazon DynamoDb.

        Amazon DynamoDb based persistence adapter implementation. This
        internally uses the AWS Python SDK (`boto3`) to process the
        dynamodb operations. The adapter tries to create the table if
        `create_table` is set, during initialization.

        :param table_name: Name of the table to be created or used
        :type table_name: str
        :param partition_key_name: Partition key name to be used.
            Defaulted to 'id'
        :type partition_key_name: str
        :param attribute_name: Attribute name for storing and
            retrieving attributes from dynamodb.
            Defaulted to 'attributes'
        :type attribute_name: str
        :param create_table: Should the adapter try to create the table
            if it doesn't exist. Defaulted to False
        :type create_table: bool
        :param partition_keygen: Callable function that takes a
            request envelope and provides a unique partition key value.
            Defaulted to user id keygen function
        :type partition_keygen: Callable[[RequestEnvelope], str]
        :param dynamodb_resource: Resource to be used, to perform
            dynamo operations. Defaulted to resource generated from
            boto3
        :type dynamodb_resource: boto3.resources.base.ServiceResource
        N)Ú
table_nameÚpartition_key_nameÚattribute_nameÚcreate_tableÚpartition_keygenr   Ú,_DynamoDbAdapter__create_table_if_not_exists)Úselfr   r   r   r   r   Zdynamodb_resource© r   ú[/var/www/html/TRUCKING_PROJECT/venv/lib/python3.8/site-packages/ask_sdk_dynamodb/adapter.pyÚ__init__>   s    "zDynamoDbAdapter.__init__c              
   C   s²   zN| j  | j¡}|  |¡}|j| j|idd�}d|krF|d | j W S i W S W n^ tk
rr   td 	| j¡ƒ‚Y n< t
k
r¬ } ztd 	t|ƒjt|ƒ¡ƒ‚W 5 d}~X Y nX dS )a¼  Get attributes from table in Dynamodb resource.

        Retrieves the attributes from Dynamodb table. If the table
        doesn't exist, returns an empty dict if the
        ``create_table`` variable is set as True, else it raises
        PersistenceException. Raises PersistenceException if `get_item`
        fails on the table.

        :param request_envelope: Request Envelope passed during skill
            invocation
        :type request_envelope: ask_sdk_model.RequestEnvelope
        :return: Attributes stored under the partition keygen mapping
            in the table
        :rtype: Dict[str, object]
        :raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
        T)ÚKeyZConsistentReadÚItemzqDynamoDb table {} doesn't exist or in the process of being created. Failed to get attributes from DynamoDb table.zTFailed to retrieve attributes from DynamoDb table. Exception of type {} occurred: {}N)r   ÚTabler   r   Zget_itemr   r   r   r   ÚformatÚ	ExceptionÚtypeÚ__name__Ústr)r   Úrequest_envelopeÚtableÚpartition_key_valÚresponseÚer   r   r   Úget_attributesh   s.    
þ
þÿ þÿzDynamoDbAdapter.get_attributesc              
   C   s˜   z4| j  | j¡}|  |¡}|j| j|| j|id� W n^ tk
rX   td 	| j¡ƒ‚Y n< t
k
r’ } ztd 	t|ƒjt|ƒ¡ƒ‚W 5 d}~X Y nX dS )ab  Saves attributes to table in Dynamodb resource.

        Saves the attributes into Dynamodb table. Raises
        PersistenceException if table doesn't exist or ``put_item`` fails
        on the table.

        :param request_envelope: Request Envelope passed during skill
            invocation
        :type request_envelope: ask_sdk_model.RequestEnvelope
        :param attributes: Attributes stored under the partition keygen
            mapping in the table
        :type attributes: Dict[str, object]
        :rtype: None
        :raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
        )r   zMDynamoDb table {} doesn't exist. Failed to save attributes to DynamoDb table.zNFailed to save attributes to DynamoDb table. Exception of type {} occurred: {}N)r   r   r   r   Zput_itemr   r   r   r   r   r   r   r   r    )r   r!   r   r"   r#   r%   r   r   r   Úsave_attributes�   s,    
 ÿÿ
þÿ þÿzDynamoDbAdapter.save_attributesc              
   C   s’   z.| j  | j¡}|  |¡}|j| j|id� W n^ tk
rR   td | j¡ƒ‚Y n< t	k
rŒ } ztd t
|ƒjt|ƒ¡ƒ‚W 5 d}~X Y nX dS )aÖ  Deletes attributes from table in Dynamodb resource.

        Deletes the attributes from Dynamodb table. Raises
        PersistenceException if table doesn't exist or ``delete_item`` fails
        on the table.

        :param request_envelope: Request Envelope passed during skill
            invocation
        :type request_envelope: ask_sdk_model.RequestEnvelope
        :rtype: None
        :raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
        )r   zQDynamoDb table {} doesn't exist. Failed to delete attributes from DynamoDb table.zPFailed to delete attributes in DynamoDb table. Exception of type {} occurred: {}N)r   r   r   r   Zdelete_itemr   r   r   r   r   r   r   r    )r   r!   r"   r#   r%   r   r   r   Údelete_attributes±   s&    
ÿ
þÿ þÿz!DynamoDbAdapter.delete_attributesc              
   C   sˆ   | j r„z4| jj | j| jddœg| jddœgdddœd� W nH tk
r‚ } z*|jjdkrrtd	 t	|ƒjt
|ƒ¡ƒ‚W 5 d
}~X Y nX d
S )záCreates table in Dynamodb resource if it doesn't exist and
        create_table is set as True.

        :rtype: None
        :raises: PersistenceException: When `create_table` fails on
            dynamodb resource.
        ÚHASH)ÚAttributeNameZKeyTypeÚS)r*   ZAttributeTypeé   )ZReadCapacityUnitsZWriteCapacityUnits)Z	TableNameZ	KeySchemaZAttributeDefinitionsZProvisionedThroughputZResourceInUseExceptionzLCreate table if not exists request failed: Exception of type {} occurred: {}N)r   r   r   r   r   Ú	__class__r   r   r   r   r    )r   r%   r   r   r   Z__create_table_if_not_existsÏ   s0    	þÿþÿþñ
 ýÿz,DynamoDbAdapter.__create_table_if_not_existsN)r   Ú
__module__Ú__qualname__Ú__doc__r   Úboto3Úresourcer   r&   r'   r(   r   r   r   r   r   r       s    ü
*'"r   )r1   ÚtypingZboto3.sessionr   Zask_sdk_core.attributes_managerr   Zask_sdk_core.exceptionsr   r   r   ÚTYPE_CHECKINGr   r   Zask_sdk_modelr	   Zboto3.resources.baser
   r   r   r   r   r   Ú<module>   s   