U
    W+d                     @   s|   d dl mZ d dlmZ d dlmZ d dlmZ d dlm	Z	m
Z
 d dlmZmZmZmZ G dd deZG d	d
 d
eZdS )    )Layer1)Table)Schema)Item)	BatchListBatchWriteList)get_dynamodb_type	DynamizerLossyFloatDynamizerNonBooleanDynamizerc                   @   sX   e Zd ZdZdd Zedd Zedd Zedd	 Zed
d Z	dd Z
dd ZdS )TableGeneratora  
    This is an object that wraps up the table_generator function.
    The only real reason to have this is that we want to be able
    to accumulate and return the ConsumedCapacityUnits element that
    is part of each response.

    :ivar last_evaluated_key: A sequence representing the key(s)
        of the item last evaluated, or None if no additional
        results are available.

    :ivar remaining: The remaining quantity of results requested.

    :ivar table: The table to which the call was made.
    c                 C   sL   || _ || _|d krdn|| _|| _|| _d| _d | _d| _d| _d | _	d S )N        r   )
tablecallable	remaining
item_classkwargs_consumed_unitslast_evaluated_key_count_scanned_count	_response)selfr   r   r   r   r    r   8/tmp/pip-unpacked-wheel-dlxw5sjy/boto/dynamodb/layer2.py__init__0   s    zTableGenerator.__init__c                 C   s   | j  | jS )z
        The total number of items retrieved thus far.  This value changes with
        iteration and even when issuing a call with count=True, it is necessary
        to complete the iteration to assert an accurate count value.
        )responser   r   r   r   r   count<   s    zTableGenerator.countc                 C   s   | j  | jS )z
        As above, but representing the total number of items scanned by
        DynamoDB, without regard to any filters.
        )r   r   r   r   r   r   scanned_countF   s    zTableGenerator.scanned_countc                 C   s   | j  | jS )zU
        Returns a float representing the ConsumedCapacityUnits accumulated.
        )r   r   r   r   r   r   consumed_unitsO   s    zTableGenerator.consumed_unitsc                 C   s   | j dkr|  S | j S )zA
        The current response to the call from DynamoDB.
        N)r   next_responser   r   r   r   r   W   s    zTableGenerator.responsec                 C   s   | j d}| jdkr4|dks(|| jkr4| j| j d< | jf | j | _|| j d< |  j| jdd7  _|  j| jdd7  _|  j| jdd7  _d| jkr| jd }| jj	
|}|| j d	< |d
 f}d|kr||d f7 }|| _nd| _| jS )z
        Issue a call and return the result.  You can invoke this method
        while iterating over the TableGenerator in order to skip to the
        next "page" of results.
        limitr   NConsumedCapacityUnitsr   ZCountZScannedCountZLastEvaluatedKeyexclusive_start_keyHashKeyElementRangeKeyElement)r   getr   r   r   r   r   r   r   Zlayer2dynamize_last_evaluated_keyr   )r   r#   ZlekeskZlektupler   r   r   r"   ^   s$    




zTableGenerator.next_responsec                 c   s   | j dkr| j}|dg D ]@}|  j d8  _ | j| j|dV  | j dkrN qt|| jk	r qtq| jd k	r|   q q|| jk	rq qq d S )Nr   ZItems   )attrs)r   r   r(   r   r   r   r   r"   )r   r   itemr   r   r   __iter__{   s     




zTableGenerator.__iter__N)__name__
__module____qualname____doc__r   propertyr   r    r!   r   r"   r.   r   r   r   r   r       s   
	


r   c                   @   s>  e Zd ZddddddddddedfddZd;ddZd	d
 Zdd Zdd Zdd Z	dd Z
dd Zd<ddZdd Zdd Zd=ddZdd Zdd  Zd!d" ZeZd#d$ Zd%d& Zd'd( Zd>d)d*Zdddefd+d,Zd-d. Zd/d0 Zd?d1d2Zd@d3d4ZdAd5d6Zdddddddedf	d7d8Zdddddedfd9d:Z dS )BLayer2NTr   c                 C   s,   t |||||||||	|
|d| _| | _d S )N)validate_certsprofile_name)r   layer1	dynamizer)r   Zaws_access_key_idZaws_secret_access_keyZ	is_secureportproxyZ
proxy_portdebugZsecurity_tokenZregionr5   r8   r6   r   r   r   r      s         zLayer2.__init__Fc                 C   s   |r
t  nt | _dS )a  
        Use the ``decimal.Decimal`` type for encoding/decoding numeric types.

        By default, ints/floats are used to represent numeric types
        ('N', 'NS') received from DynamoDB.  Using the ``Decimal``
        type is recommended to prevent loss of precision.

        N)r	   r   r8   )r   Zuse_booleanr   r   r   use_decimals   s    
zLayer2.use_decimalsc                 C   sJ   i }|D ]<}|| \}}|dkr.d|i||< q|| j |d||< q|S )zf
        Convert a set of pending item updates into the structure
        required by Layer1.
        NAction)r=   Valuer8   encode)r   Zpending_updatesd	attr_nameactionvaluer   r   r   dynamize_attribute_updates   s    
z!Layer2.dynamize_attribute_updatesc                 C   s&   i }|D ]}| j || ||< q|S )Nr?   )r   r-   rA   rB   r   r   r   dynamize_item   s    zLayer2.dynamize_itemc                 C   s   |  S )zo
        Convert a layer2 range_key_condition parameter into the
        structure required by Layer1.
        to_dict)r   range_key_conditionr   r   r   dynamize_range_key_condition   s    z#Layer2.dynamize_range_key_conditionc                 C   s.   d}|r*i }|D ]}|| }|  ||< q|S )zg
        Convert a layer2 scan_filter parameter into the
        structure required by Layer1.
        NrG   )r   scan_filterrA   rB   	conditionr   r   r   dynamize_scan_filter   s    zLayer2.dynamize_scan_filterc                 C   sf   d}|rbi }|D ]P}|| }|dkr.ddi}n*|dkr@ddi}n| j || }d|i}|||< q|S )zj
        Convert an expected_value parameter into the data structure
        required for Layer1.
        NTZExistsFr>   r?   )r   expected_valuerA   rB   
attr_valuevalr   r   r   dynamize_expected_value   s    


zLayer2.dynamize_expected_valuec                 C   sD   d}|r@|d }d| j |i}d|kr@|d }| j ||d< |S )zm
        Convert a last_evaluated_key parameter into the data structure
        required for Layer1.
        Nr&   r'   r?   )r   r   rA   hash_key	range_keyr   r   r   r)      s    z"Layer2.dynamize_last_evaluated_keyc                 C   s   i }| j |}t| d |jkr8d|j }t|||d< |dk	r| j |}t| d |jkr|d|j }t|||d< |S )ax  
        Build a Key structure to be used for accessing items
        in Amazon DynamoDB.  This method takes the supplied hash_key
        and optional range_key and validates them against the
        schema.  If there is a mismatch, a TypeError is raised.
        Otherwise, a Python dict version of a Amazon DynamoDB Key
        data structure is returned.

        :type hash_key: int|float|str|unicode|Binary
        :param hash_key: The hash key of the item you are looking for.
            The type of the hash key should match the type defined in
            the schema.

        :type range_key: int|float|str|unicode|Binary
        :param range_key: The range key of the item your are looking for.
            This should be supplied only if the schema requires a
            range key.  The type of the range key should match the
            type defined in the schema.
        r   zHashkey must be of type: %sr&   NzRangeKey must be of type: %sr'   )r8   r@   listkeysZhash_key_type	TypeErrorZrange_key_type)r   schemarR   rS   Zdynamodb_keyZdynamodb_valuemsgr   r   r   build_key_from_values   s    

zLayer2.build_key_from_valuesc                 C   s   t | S )z\
        Return a new, empty :class:`boto.dynamodb.batch.BatchList`
        object.
        )r   r   r   r   r   new_batch_list  s    zLayer2.new_batch_listc                 C   s   t | S )za
        Return a new, empty :class:`boto.dynamodb.batch.BatchWriteList`
        object.
        )r   r   r   r   r   new_batch_write_list  s    zLayer2.new_batch_write_listc                 C   sp   g }d}|rt ||k rld}|r6|t | }t|d}| jj||d}||dg  |dd}|sqlq|S )z
        Return a list of the names of all tables associated with the
        current account and region.

        :type limit: int
        :param limit: The maximum number of tables to return.
        Nd   )r#   start_tableZ
TableNamesZLastEvaluatedTableName)lenminr7   list_tablesextendr(   )r   r#   Ztablesr]   Zthis_round_limitresultr   r   r   r`   %  s    
zLayer2.list_tablesc                 C   s   | j |S )z
        Retrieve information about an existing table.

        :type name: str
        :param name: The name of the desired table.

        )r7   describe_table)r   namer   r   r   rc   ;  s    zLayer2.describe_tablec                 C   s   t | ||S )a  
        Create a Table object from a schema.

        This method will create a Table object without
        making any API calls.  If you know the name and schema
        of the table, you can use this method instead of
        ``get_table``.

        Example usage::

            table = layer2.table_from_schema(
                'tablename',
                Schema.create(hash_key=('foo', 'N')))

        :type name: str
        :param name: The name of the table.

        :type schema: :class:`boto.dynamodb.schema.Schema`
        :param schema: The schema associated with the table.

        :rtype: :class:`boto.dynamodb.table.Table`
        :return: A Table object representing the table.

        )r   Zcreate_from_schema)r   rd   rW   r   r   r   table_from_schemaE  s    zLayer2.table_from_schemac                 C   s   | j |}t| |S )z
        Retrieve the Table object for an existing table.

        :type name: str
        :param name: The name of the desired table.

        :rtype: :class:`boto.dynamodb.table.Table`
        :return: A Table object representing the table.
        )r7   rc   r   )r   rd   r   r   r   r   	get_table`  s    
zLayer2.get_tablec                 C   s"   | j ||j||d}t| |S )aX  
        Create a new Amazon DynamoDB table.

        :type name: str
        :param name: The name of the desired table.

        :type schema: :class:`boto.dynamodb.schema.Schema`
        :param schema: The Schema object that defines the schema used
            by this table.

        :type read_units: int
        :param read_units: The value for ReadCapacityUnits.

        :type write_units: int
        :param write_units: The value for WriteCapacityUnits.

        :rtype: :class:`boto.dynamodb.table.Table`
        :return: A Table object representing the new Amazon DynamoDB table.
        ZReadCapacityUnitsZWriteCapacityUnits)r7   create_tabledictr   )r   rd   rW   
read_unitswrite_unitsr   r   r   r   rh   o  s    zLayer2.create_tablec                 C   s$   | j |j||d}|| dS )a  
        Update the ProvisionedThroughput for the Amazon DynamoDB Table.

        :type table: :class:`boto.dynamodb.table.Table`
        :param table: The Table object whose throughput is being updated.

        :type read_units: int
        :param read_units: The new value for ReadCapacityUnits.

        :type write_units: int
        :param write_units: The new value for WriteCapacityUnits.
        rg   N)r7   Zupdate_tablerd   update_from_response)r   r   rj   rk   r   r   r   r   update_throughput  s    
zLayer2.update_throughputc                 C   s   | j |j}|| dS )a	  
        Delete this table and all items in it.  After calling this
        the Table objects status attribute will be set to 'DELETING'.

        :type table: :class:`boto.dynamodb.table.Table`
        :param table: The Table object that is being deleted.
        N)r7   delete_tablerd   rl   )r   r   r   r   r   r   rn     s    zLayer2.delete_tablec                 C   s6   |t |f}|r&|dk	r&|t |f}nd}t||S )a  
        Create a Schema object used when creating a Table.

        :type hash_key_name: str
        :param hash_key_name: The name of the HashKey for the schema.

        :type hash_key_proto_value: int|long|float|str|unicode|Binary
        :param hash_key_proto_value: A sample or prototype of the type
            of value you want to use for the HashKey.  Alternatively,
            you can also just pass in the Python type (e.g. int, float, etc.).

        :type range_key_name: str
        :param range_key_name: The name of the RangeKey for the schema.
            This parameter is optional.

        :type range_key_proto_value: int|long|float|str|unicode|Binary
        :param range_key_proto_value: A sample or prototype of the type
            of value you want to use for the RangeKey.  Alternatively,
            you can also pass in the Python type (e.g. int, float, etc.)
            This parameter is optional.
        N)r   r   create)r   Zhash_key_nameZhash_key_proto_valueZrange_key_nameZrange_key_proto_valuerR   rS   r   r   r   create_schema  s    zLayer2.create_schemac           
      C   sT   |  |j||}| jj|j|||| jjd}|||||d }	d|krP|d |	_|	S )a  
        Retrieve an existing item from the table.

        :type table: :class:`boto.dynamodb.table.Table`
        :param table: The Table object from which the item is retrieved.

        :type hash_key: int|long|float|str|unicode|Binary
        :param hash_key: The HashKey of the requested item.  The
            type of the value must match the type defined in the
            schema for the table.

        :type range_key: int|long|float|str|unicode|Binary
        :param range_key: The optional RangeKey of the requested item.
            The type of the value must match the type defined in the
            schema for the table.

        :type attributes_to_get: list
        :param attributes_to_get: A list of attribute names.
            If supplied, only the specified attribute names will
            be returned.  Otherwise, all attributes will be returned.

        :type consistent_read: bool
        :param consistent_read: If True, a consistent read
            request is issued.  Otherwise, an eventually consistent
            request is issued.

        :type item_class: Class
        :param item_class: Allows you to override the class used
            to generate the items. This should be a subclass of
            :class:`boto.dynamodb.item.Item`
        object_hookr   r$   )rY   rW   r7   get_itemrd   r8   decoder!   )
r   r   rR   rS   attributes_to_getconsistent_readr   keyr   r-   r   r   r   rs     s    " 
zLayer2.get_itemc                 C   s   |  }| jj|| jjdS )a  
        Return a set of attributes for a multiple items in
        multiple tables using their primary keys.

        :type batch_list: :class:`boto.dynamodb.batch.BatchList`
        :param batch_list: A BatchList object which consists of a
            list of :class:`boto.dynamoddb.batch.Batch` objects.
            Each Batch object contains the information about one
            batch of objects that you wish to retrieve in this
            request.
        rq   )rH   r7   batch_get_itemr8   rt   r   Z
batch_listZrequest_itemsr   r   r   rx     s    zLayer2.batch_get_itemc                 C   s   |  }| jj|| jjdS )a  
        Performs multiple Puts and Deletes in one batch.

        :type batch_list: :class:`boto.dynamodb.batch.BatchWriteList`
        :param batch_list: A BatchWriteList object which consists of a
            list of :class:`boto.dynamoddb.batch.BatchWrite` objects.
            Each Batch object contains the information about one
            batch of objects that you wish to put or delete.
        rq   )rH   r7   batch_write_itemr8   rt   ry   r   r   r   rz     s    
zLayer2.batch_write_itemc                 C   sD   |  |}| jj|jj| |||| jjd}d|kr@|d |_|S )a  
        Store a new item or completely replace an existing item
        in Amazon DynamoDB.

        :type item: :class:`boto.dynamodb.item.Item`
        :param item: The Item to write to Amazon DynamoDB.

        :type expected_value: dict
        :param expected_value: A dictionary of name/value pairs that you expect.
            This dictionary should have name/value pairs where the name
            is the name of the attribute and the value is either the value
            you are expecting or False if you expect the attribute not to
            exist.

        :type return_values: str
        :param return_values: Controls the return of attribute
            name-value pairs before then were changed.  Possible
            values are: None or 'ALL_OLD'. If 'ALL_OLD' is
            specified and the item is overwritten, the content
            of the old item is returned.
        rq   r$   )	rQ   r7   put_itemr   rd   rF   r8   rt   r!   )r   r-   rN   return_valuesr   r   r   r   r{     s    
 
zLayer2.put_itemc                 C   sl   |  |}| |jj|j|j}| |j}| jj	|jj
||||| jjd}|j  d|krh|d |_|S )aS  
        Commit pending item updates to Amazon DynamoDB.

        :type item: :class:`boto.dynamodb.item.Item`
        :param item: The Item to update in Amazon DynamoDB.  It is expected
            that you would have called the add_attribute, put_attribute
            and/or delete_attribute methods on this Item prior to calling
            this method.  Those queued changes are what will be updated.

        :type expected_value: dict
        :param expected_value: A dictionary of name/value pairs that you
            expect.  This dictionary should have name/value pairs where the
            name is the name of the attribute and the value is either the
            value you are expecting or False if you expect the attribute
            not to exist.

        :type return_values: str
        :param return_values: Controls the return of attribute name/value pairs
            before they were updated. Possible values are: None, 'ALL_OLD',
            'UPDATED_OLD', 'ALL_NEW' or 'UPDATED_NEW'. If 'ALL_OLD' is
            specified and the item is overwritten, the content of the old item
            is returned. If 'ALL_NEW' is specified, then all the attributes of
            the new version of the item are returned. If 'UPDATED_NEW' is
            specified, the new versions of only the updated attributes are
            returned.

        rq   r$   )rQ   rY   r   rW   rR   rS   rE   Z_updatesr7   update_itemrd   r8   rt   clearr!   )r   r-   rN   r|   rw   Zattr_updatesr   r   r   r   r}   ,  s     

  

zLayer2.update_itemc                 C   s>   |  |}| |jj|j|j}| jj|jj|||| j	j
dS )aU  
        Delete the item from Amazon DynamoDB.

        :type item: :class:`boto.dynamodb.item.Item`
        :param item: The Item to delete from Amazon DynamoDB.

        :type expected_value: dict
        :param expected_value: A dictionary of name/value pairs that you expect.
            This dictionary should have name/value pairs where the name
            is the name of the attribute and the value is either the value
            you are expecting or False if you expect the attribute not to
            exist.

        :type return_values: str
        :param return_values: Controls the return of attribute
            name-value pairs before then were changed.  Possible
            values are: None or 'ALL_OLD'. If 'ALL_OLD' is
            specified and the item is overwritten, the content
            of the old item is returned.
        )expectedr|   rr   )rQ   rY   r   rW   rR   rS   r7   delete_itemrd   r8   rt   )r   r-   rN   r|   rw   r   r   r   r   V  s    

 zLayer2.delete_itemc                 C   sl   |r|  |}nd}|	r,| j|jf|	 }nd}|j| j||||||||| jjd
}t|| jj	||
|S )a5  
        Perform a query on the table.

        :type table: :class:`boto.dynamodb.table.Table`
        :param table: The Table object that is being queried.

        :type hash_key: int|long|float|str|unicode|Binary
        :param hash_key: The HashKey of the requested item.  The
            type of the value must match the type defined in the
            schema for the table.

        :type range_key_condition: :class:`boto.dynamodb.condition.Condition`
        :param range_key_condition: A Condition object.
            Condition object can be one of the following types:

            EQ|LE|LT|GE|GT|BEGINS_WITH|BETWEEN

            The only condition which expects or will accept two
            values is 'BETWEEN', otherwise a single value should
            be passed to the Condition constructor.

        :type attributes_to_get: list
        :param attributes_to_get: A list of attribute names.
            If supplied, only the specified attribute names will
            be returned.  Otherwise, all attributes will be returned.

        :type request_limit: int
        :param request_limit: The maximum number of items to retrieve
            from Amazon DynamoDB on each request.  You may want to set
            a specific request_limit based on the provisioned throughput
            of your table.  The default behavior is to retrieve as many
            results as possible per request.

        :type max_results: int
        :param max_results: The maximum number of results that will
            be retrieved from Amazon DynamoDB in total.  For example,
            if you only wanted to see the first 100 results from the
            query, regardless of how many were actually available, you
            could set max_results to 100 and the generator returned
            from the query method will only yeild 100 results max.

        :type consistent_read: bool
        :param consistent_read: If True, a consistent read
            request is issued.  Otherwise, an eventually consistent
            request is issued.

        :type scan_index_forward: bool
        :param scan_index_forward: Specified forward or backward
            traversal of the index.  Default is forward (True).

        :type count: bool
        :param count: If True, Amazon DynamoDB returns a total
            number of items for the Query operation, even if the
            operation has no matching items for the assigned filter.
            If count is True, the actual items are not returned and
            the count is accessible as the ``count`` attribute of
            the returned object.

        :type exclusive_start_key: list or tuple
        :param exclusive_start_key: Primary key of the item from
            which to continue an earlier query.  This would be
            provided as the LastEvaluatedKey in that query.

        :type item_class: Class
        :param item_class: Allows you to override the class used
            to generate the items. This should be a subclass of
            :class:`boto.dynamodb.item.Item`

        :rtype: :class:`boto.dynamodb.layer2.TableGenerator`
        N)

table_nameZhash_key_valueZrange_key_conditionsru   r#   r   rv   scan_index_forwardr%   rr   )
rJ   rY   rW   rd   r8   r@   rt   r   r7   query)r   r   rR   rI   ru   request_limitmax_resultsrv   r   r%   r   r   Zrkcr*   r   r   r   r   r   s  s0    K



  zLayer2.queryc	                 C   sP   |r| j |jf| }	nd}	|j| |||||	| jjd}
t|| jj|||
S )a  
        Perform a scan of DynamoDB.

        :type table: :class:`boto.dynamodb.table.Table`
        :param table: The Table object that is being scanned.

        :type scan_filter: A dict
        :param scan_filter: A dictionary where the key is the
            attribute name and the value is a
            :class:`boto.dynamodb.condition.Condition` object.
            Valid Condition objects include:

             * EQ - equal (1)
             * NE - not equal (1)
             * LE - less than or equal (1)
             * LT - less than (1)
             * GE - greater than or equal (1)
             * GT - greater than (1)
             * NOT_NULL - attribute exists (0, use None)
             * NULL - attribute does not exist (0, use None)
             * CONTAINS - substring or value in list (1)
             * NOT_CONTAINS - absence of substring or value in list (1)
             * BEGINS_WITH - substring prefix (1)
             * IN - exact match in list (N)
             * BETWEEN - >= first value, <= second value (2)

        :type attributes_to_get: list
        :param attributes_to_get: A list of attribute names.
            If supplied, only the specified attribute names will
            be returned.  Otherwise, all attributes will be returned.

        :type request_limit: int
        :param request_limit: The maximum number of items to retrieve
            from Amazon DynamoDB on each request.  You may want to set
            a specific request_limit based on the provisioned throughput
            of your table.  The default behavior is to retrieve as many
            results as possible per request.

        :type max_results: int
        :param max_results: The maximum number of results that will
            be retrieved from Amazon DynamoDB in total.  For example,
            if you only wanted to see the first 100 results from the
            query, regardless of how many were actually available, you
            could set max_results to 100 and the generator returned
            from the query method will only yeild 100 results max.

        :type count: bool
        :param count: If True, Amazon DynamoDB returns a total
            number of items for the Scan operation, even if the
            operation has no matching items for the assigned filter.
            If count is True, the actual items are not returned and
            the count is accessible as the ``count`` attribute of
            the returned object.

        :type exclusive_start_key: list or tuple
        :param exclusive_start_key: Primary key of the item from
            which to continue an earlier query.  This would be
            provided as the LastEvaluatedKey in that query.

        :type item_class: Class
        :param item_class: Allows you to override the class used
            to generate the items. This should be a subclass of
            :class:`boto.dynamodb.item.Item`

        :rtype: :class:`boto.dynamodb.layer2.TableGenerator`
        N)r   rK   ru   r#   r   r%   rr   )	rY   rW   rd   rM   r8   rt   r   r7   scan)r   r   rK   ru   r   r   r%   r   r   r*   r   r   r   r   r     s$    E

  zLayer2.scan)F)N)N)NN)NN)NN)NN)!r/   r0   r1   r
   r   r<   rE   rF   rJ   rM   rQ   r)   rY   rZ   r[   r`   rc   re   rf   lookuprh   rm   rn   rp   r   rs   rx   rz   r{   r}   r   r   r   r   r   r   r   r4      sz         


"

   
 
+

*
    
a    r4   N)Zboto.dynamodb.layer1r   Zboto.dynamodb.tabler   Zboto.dynamodb.schemar   Zboto.dynamodb.itemr   Zboto.dynamodb.batchr   r   Zboto.dynamodb.typesr   r	   r
   r   objectr   r4   r   r   r   r   <module>   s   o