U
    W+d                     @   s   d dl Z d dlmZ d dlmZmZmZmZmZm	Z	m
Z
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mZ d dlmZ G d	d
 d
eZG dd deZdS )    N)
exceptions)HashKeyRangeKeyAllIndexKeysOnlyIndexIncludeIndexGlobalAllIndexGlobalKeysOnlyIndexGlobalIncludeIndex)Item)DynamoDBConnection)	ResultSetBatchGetResultSet)NonBooleanDynamizer	DynamizerFILTER_OPERATORSQUERY_OPERATORSSTRING)JSONResponseErrorc                	   @   sn  e Zd ZdZdZeeeeedee	e
eddZdLddZdd	 ZedMd
dZdNddZdd Zdd Zdd Zdd ZdOddZdd Zdd Zdd Zdd Zd d! ZdPd#d$Zd%d& Zd'd( Zd)d* ZdQd+d,Z dRd-d.Z!dSd/d0Z"dTd1d2Z#d3d4 Z$d5d6 Z%e&fd7d8Z'dUd9d:Z(dVd;d<Z)dWd>d?Z*dXd@dAZ+dYdBdCZ,dZdDdEZ-d[dFdGZ.d\dHdIZ/dJdK Z0dS )]Tablea  
    Interacts & models the behavior of a DynamoDB table.

    The ``Table`` object represents a set (or rough categorization) of
    records within DynamoDB. The important part is that all records within the
    table, while largely-schema-free, share the same schema & are essentially
    namespaced for use in your application. For example, you might have a
    ``users`` table or a ``forums`` table.
    d   )ALL	KEYS_ONLYINCLUDE)global_indexeslocal_indexesNc                 C   sV   || _ || _ddd| _|| _|| _|| _| jdkr<t | _|dk	rJ|| _t | _dS )a  
        Sets up a new in-memory ``Table``.

        This is useful if the table already exists within DynamoDB & you simply
        want to use it for additional interactions. The only required parameter
        is the ``table_name``. However, under the hood, the object will call
        ``describe_table`` to determine the schema/indexes/throughput. You
        can avoid this extra call by passing in ``schema`` & ``indexes``.

        **IMPORTANT** - If you're creating a new ``Table`` for the first time,
        you should use the ``Table.create`` method instead, as it will
        persist the table structure to DynamoDB.

        Requires a ``table_name`` parameter, which should be a simple string
        of the name of the table.

        Optionally accepts a ``schema`` parameter, which should be a list of
        ``BaseSchemaField`` subclasses representing the desired schema.

        Optionally accepts a ``throughput`` parameter, which should be a
        dictionary. If provided, it should specify a ``read`` & ``write`` key,
        both of which should have an integer value associated with them.

        Optionally accepts a ``indexes`` parameter, which should be a list of
        ``BaseIndexField`` subclasses representing the desired indexes.

        Optionally accepts a ``global_indexes`` parameter, which should be a
        list of ``GlobalBaseIndexField`` subclasses representing the desired
        indexes.

        Optionally accepts a ``connection`` parameter, which should be a
        ``DynamoDBConnection`` instance (or subclass). This is primarily useful
        for specifying alternate connection parameters.

        Example::

            # The simple, it-already-exists case.
            >>> conn = Table('users')

            # The full, minimum-extra-calls case.
            >>> from boto import dynamodb2
            >>> users = Table('users', schema=[
            ...     HashKey('username'),
            ...     RangeKey('date_joined', data_type=NUMBER)
            ... ], throughput={
            ...     'read':20,
            ...     'write': 10,
            ... }, indexes=[
            ...     KeysOnlyIndex('MostRecentlyJoined', parts=[
            ...         HashKey('username')
            ...         RangeKey('date_joined')
            ...     ]),
            ... ], global_indexes=[
            ...     GlobalAllIndex('UsersByZipcode', parts=[
            ...         HashKey('zipcode'),
            ...         RangeKey('username'),
            ...     ],
            ...     throughput={
            ...       'read':10,
            ...       'write':10,
            ...     }),
            ... ], connection=dynamodb2.connect_to_region('us-west-2',
            ...     aws_access_key_id='key',
            ...     aws_secret_access_key='key',
            ... ))

           )readwriteN)	
table_name
connection
throughputschemaindexesr   r   r   
_dynamizer)selfr   r"   r!   r#   r   r     r&   8/tmp/pip-unpacked-wheel-dlxw5sjy/boto/dynamodb2/table.py__init__'   s    E
zTable.__init__c                 C   s   t  | _d S N)r   r$   r%   r&   r&   r'   use_boolean~   s    zTable.use_booleanc                 C   s<  | ||d}||_ |dk	r ||_|dk	r.||_|dk	r<||_g }g }	t }
|j D ],}||   |
|j |	|  qPt	|jd t	|jd d}i }ddd}dD ]j}t
||}|rg }|D ]B}||   |jD ](}|j|
kr|
|j |	|  qq|||| < q|jjf |j|	||d	| |S )
a
  
        Creates a new table in DynamoDB & returns an in-memory ``Table`` object.

        This will setup a brand new table within DynamoDB. The ``table_name``
        must be unique for your AWS account. The ``schema`` is also required
        to define the key structure of the table.

        **IMPORTANT** - You should consider the usage pattern of your table
        up-front, as the schema can **NOT** be modified once the table is
        created, requiring the creation of a new table & migrating the data
        should you wish to revise it.

        **IMPORTANT** - If the table already exists in DynamoDB, additional
        calls to this method will result in an error. If you just need
        a ``Table`` object to interact with the existing table, you should
        just initialize a new ``Table`` object, which requires only the
        ``table_name``.

        Requires a ``table_name`` parameter, which should be a simple string
        of the name of the table.

        Requires a ``schema`` parameter, which should be a list of
        ``BaseSchemaField`` subclasses representing the desired schema.

        Optionally accepts a ``throughput`` parameter, which should be a
        dictionary. If provided, it should specify a ``read`` & ``write`` key,
        both of which should have an integer value associated with them.

        Optionally accepts a ``indexes`` parameter, which should be a list of
        ``BaseIndexField`` subclasses representing the desired indexes.

        Optionally accepts a ``global_indexes`` parameter, which should be a
        list of ``GlobalBaseIndexField`` subclasses representing the desired
        indexes.

        Optionally accepts a ``connection`` parameter, which should be a
        ``DynamoDBConnection`` instance (or subclass). This is primarily useful
        for specifying alternate connection parameters.

        Example::

            >>> users = Table.create('users', schema=[
            ...     HashKey('username'),
            ...     RangeKey('date_joined', data_type=NUMBER)
            ... ], throughput={
            ...     'read':20,
            ...     'write': 10,
            ... }, indexes=[
            ...     KeysOnlyIndex('MostRecentlyJoined', parts=[
            ...         HashKey('username'),
            ...         RangeKey('date_joined'),
            ... ]), global_indexes=[
            ...     GlobalAllIndex('UsersByZipcode', parts=[
            ...         HashKey('zipcode'),
            ...         RangeKey('username'),
            ...     ],
            ...     throughput={
            ...       'read':10,
            ...       'write':10,
            ...     }),
            ... ])

        )r   r    Nr   r   ReadCapacityUnitsWriteCapacityUnitsZlocal_secondary_indexesZglobal_secondary_indexes)r#   r   )r   attribute_definitionsZ
key_schemaprovisioned_throughput)r"   r!   r#   r   setappendaddname
definitionintgetattrpartsr    Zcreate_tabler   )clsr   r"   r!   r#   r   r    table
raw_schemaZ	attr_defsZ
seen_attrsfieldraw_throughputkwargsZ	kwarg_mapZ
index_attrZtable_indexesraw_indexesZindex_fieldr&   r&   r'   create   sT    B



zTable.createc                 C   s   g }i }|r&|D ]}|d ||d < q|D ]n}| |d t}|d dkrb|t|d |d q*|d dkr|t|d |d q*td|d  q*|S )z
        Given a raw schema structure back from a DynamoDB response, parse
        out & build the high-level Python objects that represent them.
        ZAttributeTypeZAttributeNameZKeyTypeHASH)	data_typeRANGEW%s was seen, but is unknown. Please report this at https://github.com/boto/boto/issues.)getr   r2   r   r   r   ZUnknownSchemaFieldError)r%   r;   raw_attributesr"   Zsane_attributesr<   rB   r&   r&   r'   _introspect_schema   s*    zTable._introspect_schemac                 C   s   g }|D ]}| d}dg i}|d d dkr:| d}n^|d d dkrV| d}nB|d d dkr| d}|d d |d< ntd	|d d  |d
 }| |d d|d< |||f| q|S )z
        Given a raw index/global index structure back from a DynamoDB response,
        parse out & build the high-level Python objects that represent them.
        r   r8   Z
ProjectionZProjectionTyper   r   ZNonKeyAttributesZincludesrD   	IndexName	KeySchemaN)rE   r   ZUnknownIndexFieldErrorrG   r2   )r%   r?   Zmap_indexes_projectionr#   r<   Zindex_klassr>   r4   r&   r&   r'   _introspect_all_indexes  s,    
 

zTable._introspect_all_indexesc                 C   s   |  || jdS )z
        Given a raw index structure back from a DynamoDB response, parse
        out & build the high-level Python objects that represent them.
        r   rJ   _PROJECTION_TYPE_TO_INDEXrE   )r%   r?   r&   r&   r'   _introspect_indexes<  s     
zTable._introspect_indexesc                 C   s   |  || jdS )z
        Given a raw global index structure back from a DynamoDB response, parse
        out & build the high-level Python objects that represent them.
        r   rK   )r%   raw_global_indexesr&   r&   r'   _introspect_global_indexesD  s    
z Table._introspect_global_indexesc                 C   s   | j | j}|d d }t|d | jd< t|d | jd< | jsr|d dg }|d dg }| ||| _| js|d d	g }| 	|| _|d d
g }| 
|| _|S )a  
        Describes the current structure of the table in DynamoDB.

        This information will be used to update the ``schema``, ``indexes``,
        ``global_indexes`` and ``throughput`` information on the ``Table``. Some
        calls, such as those involving creating keys or querying, will require
        this information to be populated.

        It also returns the full raw data structure from DynamoDB, in the
        event you'd like to parse out additional information (such as the
        ``ItemCount`` or usage information).

        Example::

            >>> users.describe()
            {
                # Lots of keys here...
            }
            >>> len(users.schema)
            2

        r   ProvisionedThroughputr-   r   r.   r   rI   ZAttributeDefinitionsZLocalSecondaryIndexesZGlobalSecondaryIndexes)r    Zdescribe_tabler   r6   r!   r"   rE   rG   r#   rM   rO   r   )r%   resultr=   r;   rF   r?   rN   r&   r&   r'   describeM  s    zTable.describec              	   C   s   d}|r,|| _ t| j d t| j d d}d}|rtg }| D ]2\}}|d|t|d t|d ddi q@|s||r| jj| j||d dS d	}tj	| d
S dS )a0  
        Updates table attributes and global indexes in DynamoDB.

        Optionally accepts a ``throughput`` parameter, which should be a
        dictionary. If provided, it should specify a ``read`` & ``write`` key,
        both of which should have an integer value associated with them.

        Optionally accepts a ``global_indexes`` parameter, which should be a
        dictionary. If provided, it should specify the index name, which is also
        a dict containing a ``read`` & ``write`` key, both of which
        should have an integer value associated with them. If you are writing
        new code, please use ``Table.update_global_secondary_index``.

        Returns ``True`` on success.

        Example::

            # For a read-heavier application...
            >>> users.update(throughput={
            ...     'read': 20,
            ...     'write': 10,
            ... })
            True

            # To also update the global index(es) throughput.
            >>> users.update(throughput={
            ...     'read': 20,
            ...     'write': 10,
            ... },
            ... global_secondary_indexes={
            ...     'TheIndexNameHere': {
            ...         'read': 15,
            ...         'write': 5,
            ...     }
            ... })
            True
        Nr   r   r,   UpdaterH   rP   )r0   global_secondary_index_updatesTzPYou need to provide either the throughput or the global_indexes to update methodF)
r!   r6   itemsr2   r    update_tabler   botologerror)r%   r!   r   datagsi_datagsi_namegsi_throughputmsgr&   r&   r'   update~  s8    '


zTable.updatec                 C   sh   |rPg }g }| d| i |jD ]}| |  q$| jj| j||d dS d}tj	| dS dS )a  
        Creates a global index in DynamoDB after the table has been created.

        Requires a ``global_indexes`` parameter, which should be a
        ``GlobalBaseIndexField`` subclass representing the desired index.

        To update ``global_indexes`` information on the ``Table``, you'll need
        to call ``Table.describe``.

        Returns ``True`` on success.

        Example::

            # To create a global index
            >>> users.create_global_secondary_index(
            ...     global_index=GlobalAllIndex(
            ...         'TheIndexNameHere', parts=[
            ...             HashKey('requiredHashkey', data_type=STRING),
            ...             RangeKey('optionalRangeKey', data_type=STRING)
            ...         ],
            ...         throughput={
            ...             'read': 2,
            ...             'write': 1,
            ...         })
            ... )
            True

        ZCreate)rU   r/   TzLYou need to provide the global_index to create_global_secondary_index methodFN)
r2   r"   r8   r5   r    rW   r   rX   rY   rZ   )r%   Zglobal_indexr\   Zgsi_data_attr_defZattr_defr_   r&   r&   r'   create_global_secondary_index  s$     
z#Table.create_global_secondary_indexc                 C   s@   |r(dd|iig}| j j| j|d dS d}tj| dS dS )a  
        Deletes a global index in DynamoDB after the table has been created.

        Requires a ``global_index_name`` parameter, which should be a simple
        string of the name of the global secondary index.

        To update ``global_indexes`` information on the ``Table``, you'll need
        to call ``Table.describe``.

        Returns ``True`` on success.

        Example::

            # To delete a global index
            >>> users.delete_global_secondary_index('TheIndexNameHere')
            True

        ZDeleterH   rU   TzQYou need to provide the global index name to delete_global_secondary_index methodFN)r    rW   r   rX   rY   rZ   )r%   Zglobal_index_namer\   r_   r&   r&   r'   delete_global_secondary_index  s     z#Table.delete_global_secondary_indexc              	   C   sr   |rZg }|  D ]2\}}|d|t|d t|d ddi q| jj| j|d dS d}tj| d	S d
S )a5  
        Updates a global index(es) in DynamoDB after the table has been created.

        Requires a ``global_indexes`` parameter, which should be a
        dictionary. If provided, it should specify the index name, which is also
        a dict containing a ``read`` & ``write`` key, both of which
        should have an integer value associated with them.

        To update ``global_indexes`` information on the ``Table``, you'll need
        to call ``Table.describe``.

        Returns ``True`` on success.

        Example::

            # To update a global index
            >>> users.update_global_secondary_index(global_indexes={
            ...     'TheIndexNameHere': {
            ...         'read': 15,
            ...         'write': 5,
            ...     }
            ... })
            True

        rS   r   r   r,   rT   rb   TzNYou need to provide the global indexes to update_global_secondary_index methodFN)	rV   r2   r6   r    rW   r   rX   rY   rZ   )r%   r   r\   r]   r^   r_   r&   r&   r'   update_global_secondary_index.  s&    


z#Table.update_global_secondary_indexc                 C   s   | j | j dS )z
        Deletes a table in DynamoDB.

        **IMPORTANT** - Be careful when using this method, there is no undo.

        Returns ``True`` on success.

        Example::

            >>> users.delete()
            True

        T)r    Zdelete_tabler   r*   r&   r&   r'   deletec  s    zTable.deletec                 C   s*   i }|  D ]\}}| j|||< q|S )a  
        Given a flat Python dictionary of keys/values, converts it into the
        nested dictionary DynamoDB expects.

        Converts::

            {
                'username': 'john',
                'tags': [1, 2, 5],
            }

        ...to...::

            {
                'username': {'S': 'john'},
                'tags': {'NS': ['1', '2', '5']},
            }

        )rV   r$   encode)r%   keysraw_keykeyvaluer&   r&   r'   _encode_keyst  s    zTable._encode_keysFc                 K   sL   |  |}| jj| j|||d}d|kr6td| t| }|| |S )a/  
        Fetches an item (record) from a table in DynamoDB.

        To specify the key of the item you'd like to get, you can specify the
        key attributes as kwargs.

        Optionally accepts a ``consistent`` parameter, which should be a
        boolean. If you provide ``True``, it will perform
        a consistent (but more expensive) read from DynamoDB.
        (Default: ``False``)

        Optionally accepts an ``attributes`` parameter, which should be a
        list of fieldname to fetch. (Default: ``None``, which means all fields
        should be fetched)

        Returns an ``Item`` instance containing all the data for that record.

        Raises an ``ItemNotFound`` exception if the item is not found.

        Example::

            # A simple hash key.
            >>> john = users.get_item(username='johndoe')
            >>> john['first_name']
            'John'

            # A complex hash+range key.
            >>> john = users.get_item(username='johndoe', last_name='Doe')
            >>> john['first_name']
            'John'

            # A consistent read (assuming the data might have just changed).
            >>> john = users.get_item(username='johndoe', consistent=True)
            >>> john['first_name']
            'Johann'

            # With a key that is an invalid variable name in Python.
            # Also, assumes a different schema than previous examples.
            >>> john = users.get_item(**{
            ...     'date-joined': 127549192,
            ... })
            >>> john['first_name']
            'John'

        )attributes_to_getconsistent_readr   zItem %s couldn't be found.)rk   r    get_itemr   r   ItemNotFoundr   load)r%   
consistent
attributesr>   rh   	item_dataitemr&   r&   r'   rn     s    .

zTable.get_itemc              	   K   s2   z| j f | W n ttjfk
r,   Y dS X dS )a  
        Return whether an item (record) exists within a table in DynamoDB.

        To specify the key of the item you'd like to get, you can specify the
        key attributes as kwargs.

        Optionally accepts a ``consistent`` parameter, which should be a
        boolean. If you provide ``True``, it will perform
        a consistent (but more expensive) read from DynamoDB.
        (Default: ``False``)

        Optionally accepts an ``attributes`` parameter, which should be a
        list of fieldnames to fetch. (Default: ``None``, which means all fields
        should be fetched)

        Returns ``True`` if an ``Item`` is present, ``False`` if not.

        Example::

            # Simple, just hash-key schema.
            >>> users.has_item(username='johndoe')
            True

            # Complex schema, item not present.
            >>> users.has_item(
            ...     username='johndoe',
            ...     date_joined='2014-01-07'
            ... )
            False

        FT)rn   r   r   ro   r%   r>   r&   r&   r'   has_item  s
     zTable.has_itemc                 O   sL   | j s|   t|D ]\}}||| j | j< q| jf |}| sHdS |S )ai  
        Look up an entry in DynamoDB. This is mostly backwards compatible
        with boto.dynamodb. Unlike get_item, it takes hash_key and range_key first,
        although you may still specify keyword arguments instead.

        Also unlike the get_item command, if the returned item has no keys
        (i.e., it does not exist in DynamoDB), a None result is returned, instead
        of an empty key object.

        Example::
            >>> user = users.lookup(username)
            >>> user = users.lookup(username, consistent=True)
            >>> app = apps.lookup('my_customer_id', 'my_app_id')

        N)r"   rR   	enumerater4   rn   rg   )r%   argsr>   xargretr&   r&   r'   lookup  s    zTable.lookupc                 G   s@   | j s|   i }t|D ]\}}||| j | j< qt| |dS )zf
        Returns a new, blank item

        This is mostly for consistency with boto.dynamodb
        r[   )r"   rR   rw   r4   r   )r%   rx   r[   ry   rz   r&   r&   r'   new_item
  s    zTable.new_itemc                 C   s   t | |d}|j|dS )a  
        Saves an entire item to DynamoDB.

        By default, if any part of the ``Item``'s original data doesn't match
        what's currently in DynamoDB, this request will fail. This prevents
        other processes from updating the data in between when you read the
        item & when your request to update the item's data is processed, which
        would typically result in some data loss.

        Requires a ``data`` parameter, which should be a dictionary of the data
        you'd like to store in DynamoDB.

        Optionally accepts an ``overwrite`` parameter, which should be a
        boolean. If you provide ``True``, this will tell DynamoDB to blindly
        overwrite whatever data is present, if any.

        Returns ``True`` on success.

        Example::

            >>> users.put_item(data={
            ...     'username': 'jane',
            ...     'first_name': 'Jane',
            ...     'last_name': 'Doe',
            ...     'date_joined': 126478915,
            ... })
            True

        r}   )	overwrite)r   save)r%   r[   r   rt   r&   r&   r'   put_item  s    zTable.put_itemc                 C   s,   i }|dk	r||d< | j j| j|f| dS )a  
        The internal variant of ``put_item`` (full data). This is used by the
        ``Item`` objects, since that operation is represented at the
        table-level by the API, but conceptually maps better to telling an
        individual ``Item`` to save itself.
        NexpectedT)r    r   r   )r%   rs   expectsr>   r&   r&   r'   	_put_item8  s
    zTable._put_itemc                 C   s8   |  |}i }|dk	r||d< | jj| j||f| dS )a  
        The internal variant of ``put_item`` (partial data). This is used by the
        ``Item`` objects, since that operation is represented at the
        table-level by the API, but conceptually maps better to telling an
        individual ``Item`` to save itself.
        Nr   T)rk   r    Zupdate_itemr   )r%   ri   rs   r   rh   r>   r&   r&   r'   _update_itemG  s    
zTable._update_itemc                 K   sP   | j |td}| |}z| jj| j|||d W n tjk
rJ   Y dS X dS )a  
        Deletes a single item. You can perform a conditional delete operation
        that deletes the item if it exists, or if it has an expected attribute
        value.

        Conditional deletes are useful for only deleting items if specific
        conditions are met. If those conditions are met, DynamoDB performs
        the delete. Otherwise, the item is not deleted.

        To specify the expected attribute values of the item, you can pass a
        dictionary of conditions to ``expected``. Each condition should follow
        the pattern ``<attributename>__<comparison_operator>=<value_to_expect>``.

        **IMPORTANT** - Be careful when using this method, there is no undo.

        To specify the key of the item you'd like to get, you can specify the
        key attributes as kwargs.

        Optionally accepts an ``expected`` parameter which is a dictionary of
        expected attribute value conditions.

        Optionally accepts a ``conditional_operator`` which applies to the
        expected attribute value conditions:

        + `AND` - If all of the conditions evaluate to true (default)
        + `OR` - True if at least one condition evaluates to true

        Returns ``True`` on success, ``False`` on failed conditional delete.

        Example::

            # A simple hash key.
            >>> users.delete_item(username='johndoe')
            True

            # A complex hash+range key.
            >>> users.delete_item(username='jane', last_name='Doe')
            True

            # With a key that is an invalid variable name in Python.
            # Also, assumes a different schema than previous examples.
            >>> users.delete_item(**{
            ...     'date-joined': 127549192,
            ... })
            True

            # Conditional delete
            >>> users.delete_item(username='johndoe',
            ...                   expected={'balance__eq': 0})
            True
        using)r   conditional_operatorFT)_build_filtersr   rk   r    delete_itemr   r   ZConditionalCheckFailedException)r%   r   r   r>   rh   r&   r&   r'   r   W  s    4

zTable.delete_itemc                 C   s   | j s|   dd | j D S )a  
        Returns the fields necessary to make a key for a table.

        If the ``Table`` does not already have a populated ``schema``,
        this will request it via a ``Table.describe`` call.

        Returns a list of fieldnames (strings).

        Example::

            # A simple hash key.
            >>> users.get_key_fields()
            ['username']

            # A complex hash+range key.
            >>> users.get_key_fields()
            ['username', 'last_name']

        c                 S   s   g | ]
}|j qS r&   )r4   ).0r<   r&   r&   r'   
<listcomp>  s     z(Table.get_key_fields.<locals>.<listcomp>)r"   rR   r*   r&   r&   r'   get_key_fields  s    zTable.get_key_fieldsc                 C   s   t | S )a  
        Allows the batching of writes to DynamoDB.

        Since each write/delete call to DynamoDB has a cost associated with it,
        when loading lots of data, it makes sense to batch them, creating as
        few calls as possible.

        This returns a context manager that will transparently handle creating
        these batches. The object you get back lightly-resembles a ``Table``
        object, sharing just the ``put_item`` & ``delete_item`` methods
        (which are all that DynamoDB can batch in terms of writing data).

        DynamoDB's maximum batch size is 25 items per request. If you attempt
        to put/delete more than that, the context manager will batch as many
        as it can up to that number, then flush them to DynamoDB & continue
        batching as more calls come in.

        Example::

            # Assuming a table with one record...
            >>> with users.batch_write() as batch:
            ...     batch.put_item(data={
            ...         'username': 'johndoe',
            ...         'first_name': 'John',
            ...         'last_name': 'Doe',
            ...         'owner': 1,
            ...     })
            ...     # Nothing across the wire yet.
            ...     batch.delete_item(username='bob')
            ...     # Still no requests sent.
            ...     batch.put_item(data={
            ...         'username': 'jane',
            ...         'first_name': 'Jane',
            ...         'last_name': 'Doe',
            ...         'date_joined': 127436192,
            ...     })
            ...     # Nothing yet, but once we leave the context, the
            ...     # put/deletes will be sent.

        )
BatchTabler*   r&   r&   r'   batch_write  s    *zTable.batch_writec              	   C   s  |dkrdS i }|  D ]b\}}|d}d|dd }z||d  }W n* tk
rx   td|d |f Y nX g |d}	|d dkr|	d= |dkrd	|	d
< nd|	d
< n|d dkrt|dkrtt|tt	frt|	d 
| j|d  |	d 
| j|d  n`|d dkrF|D ]}
|	d 
| j|
 q&n.t|tt	fr^t|}|	d 
| j| |	||< q|S )z
        An internal method for taking query/scan-style ``**kwargs`` & turning
        them into the raw structure DynamoDB expects for filtering.
        N__z*Operator '%s' from '%s' is not recognized.)AttributeValueListComparisonOperatornullr   FZNOT_NULLr   ZNULLZbetween   r      in)rV   splitjoinKeyErrorr   ZUnknownFilterTypeErrorlen
isinstancelisttupler2   r$   rf   r1   )r%   filter_kwargsr   filtersZfield_and_oprj   Z
field_bits	fieldnameopr|   valr&   r&   r'   r     sR    





zTable._build_filtersc              	   K   s$   | }| j f ||||||d|S )z
        **WARNING:** This method is provided **strictly** for
        backward-compatibility. It returns results in an incorrect order.

        If you are writing new code, please use ``Table.query_2``.
        )limitindexreverserq   rr   max_page_size)query_2)r%   r   r   r   rq   rr   r   r   r&   r&   r'   query  s     zTable.queryc	                 K   s   | j r:t| j dkr:t|	dkr:| jr0t| js:td|dk	rHd}
nd}
t|d}|	 }||||||
|||d |j| j	f| |S )a  
        Queries for a set of matching items in a DynamoDB table.

        Queries can be performed against a hash key, a hash+range key or
        against any data stored in your local secondary indexes. Query filters
        can be used to filter on arbitrary fields.

        **Note** - You can not query against arbitrary fields within the data
        stored in DynamoDB unless you specify ``query_filter`` values.

        To specify the filters of the items you'd like to get, you can specify
        the filters as kwargs. Each filter kwarg should follow the pattern
        ``<fieldname>__<filter_operation>=<value_to_look_for>``. Query filters
        are specified in the same way.

        Optionally accepts a ``limit`` parameter, which should be an integer
        count of the total number of items to return. (Default: ``None`` -
        all results)

        Optionally accepts an ``index`` parameter, which should be a string of
        name of the local secondary index you want to query against.
        (Default: ``None``)

        Optionally accepts a ``reverse`` parameter, which will present the
        results in reverse order. (Default: ``False`` - normal order)

        Optionally accepts a ``consistent`` parameter, which should be a
        boolean. If you provide ``True``, it will force a consistent read of
        the data (more expensive). (Default: ``False`` - use eventually
        consistent reads)

        Optionally accepts a ``attributes`` parameter, which should be a
        tuple. If you provide any attributes only these will be fetched
        from DynamoDB. This uses the ``AttributesToGet`` and set's
        ``Select`` to ``SPECIFIC_ATTRIBUTES`` API.

        Optionally accepts a ``max_page_size`` parameter, which should be an
        integer count of the maximum number of items to retrieve
        **per-request**. This is useful in making faster requests & prevent
        the scan from drowning out other queries. (Default: ``None`` -
        fetch as many as DynamoDB will return)

        Optionally accepts a ``query_filter`` which is a dictionary of filter
        conditions against any arbitrary field in the returned data.

        Optionally accepts a ``conditional_operator`` which applies to the
        query filter conditions:

        + `AND` - True if all filter conditions evaluate to true (default)
        + `OR` - True if at least one filter condition evaluates to true

        Returns a ``ResultSet`` containing ``Item``s, which transparently handles the pagination of
        results you get back.

        Example::

            # Look for last names equal to "Doe".
            >>> results = users.query(last_name__eq='Doe')
            >>> for res in results:
            ...     print res['first_name']
            'John'
            'Jane'

            # Look for last names beginning with "D", in reverse order, limit 3.
            >>> results = users.query(
            ...     last_name__beginswith='D',
            ...     reverse=True,
            ...     limit=3
            ... )
            >>> for res in results:
            ...     print res['first_name']
            'Alice'
            'Jane'
            'John'

            # Use an LSI & a consistent read.
            >>> results = users.query(
            ...     date_joined__gte=1236451000,
            ...     owner__eq=1,
            ...     index='DateJoinedIndex',
            ...     consistent=True
            ... )
            >>> for res in results:
            ...     print res['first_name']
            'Alice'
            'Bob'
            'John'
            'Fred'

            # Filter by non-indexed field(s)
            >>> results = users.query(
            ...     last_name__eq='Doe',
            ...     reverse=True,
            ...     query_filter={
            ...         'first_name__beginswith': 'A'
            ...     }
            ... )
            >>> for res in results:
            ...     print res['first_name'] + ' ' + res['last_name']
            'Alice Doe'

        r   z0You must specify more than one key to filter on.NZSPECIFIC_ATTRIBUTESr   )r   r   r   rq   selectrl   query_filterr   )
r"   r   r   r   Z
QueryErrorr   copyr`   to_call_query)r%   r   r   r   rq   rr   r   r   r   r   r   resultsr>   r&   r&   r'   r   +  s4    j
zTable.query_2Tc                 K   sx   | j |td}	| j |td}
d}|}| jj| j||d|	|
||||d
}|t|dd7 }|d}|rt|dk r$qtq$|S )a)  
        Queries the exact count of matching items in a DynamoDB table.

        Queries can be performed against a hash key, a hash+range key or
        against any data stored in your local secondary indexes. Query filters
        can be used to filter on arbitrary fields.

        To specify the filters of the items you'd like to get, you can specify
        the filters as kwargs. Each filter kwarg should follow the pattern
        ``<fieldname>__<filter_operation>=<value_to_look_for>``. Query filters
        are specified in the same way.

        Optionally accepts an ``index`` parameter, which should be a string of
        name of the local secondary index you want to query against.
        (Default: ``None``)

        Optionally accepts a ``consistent`` parameter, which should be a
        boolean. If you provide ``True``, it will force a consistent read of
        the data (more expensive). (Default: ``False`` - use eventually
        consistent reads)

        Optionally accepts a ``query_filter`` which is a dictionary of filter
        conditions against any arbitrary field in the returned data.

        Optionally accepts a ``conditional_operator`` which applies to the
        query filter conditions:

        + `AND` - True if all filter conditions evaluate to true (default)
        + `OR` - True if at least one filter condition evaluates to true

        Optionally accept a ``exclusive_start_key`` which is used to get
        the remaining items when a query cannot return the complete count.

        Returns an integer which represents the exact amount of matched
        items.

        :type scan_index_forward: boolean
        :param scan_index_forward: Specifies ascending (true) or descending
            (false) traversal of the index. DynamoDB returns results reflecting
            the requested order determined by the range key. If the data type
            is Number, the results are returned in numeric order. For String,
            the results are returned in order of ASCII character code values.
            For Binary, DynamoDB treats each byte of the binary data as
            unsigned when it compares binary values.

        If ScanIndexForward is not specified, the results are returned in
            ascending order.

        :type limit: integer
        :param limit: The maximum number of items to evaluate (not necessarily
            the number of matching items).

        Example::

            # Look for last names equal to "Doe".
            >>> users.query_count(last_name__eq='Doe')
            5

            # Use an LSI & a consistent read.
            >>> users.query_count(
            ...     date_joined__gte=1236451000,
            ...     owner__eq=1,
            ...     index='DateJoinedIndex',
            ...     consistent=True
            ... )
            2

        r   r   ZCOUNT)	
index_namerm   r   key_conditionsr   r   r   scan_index_forwardexclusive_start_keyZCountLastEvaluatedKeyr   )r   r   r   r    r   r   r6   rE   )r%   r   rq   r   r   r   r   r   r   r   Zbuilt_query_filterZcount_bufferZlast_evaluated_keyraw_resultsr&   r&   r'   query_count  s6    G
zTable.query_countc
                 K   s   ||||||	d}|rd|d< |rPi |d< |  D ]\}}| j||d |< q2| j|
td|d< | j|td|d< | jj| jf|}g }d}|	d	g D ]$}t
| }|d
|i || q|	ddri }|d   D ]\}}| j|||< q||dS )z
        The internal method that performs the actual queries. Used extensively
        by ``ResultSet`` to perform each (paginated) request.
        )r   r   rm   r   rl   r   Fr   r   r   r   r   NItemsr   r   r   last_key)rV   r$   rf   r   r   r   r    r   r   rE   r   rp   r2   decode)r%   r   r   r   rq   r   r   rl   r   r   r   r>   ri   rj   r   r   r   raw_itemrt   r&   r&   r'   r     sV    	


 zTable._queryc           
      K   s<   t |d}| }	|	|||||d |j| jf|	 |S )a	  
        Scans across all items within a DynamoDB table.

        Scans can be performed against a hash key or a hash+range key. You can
        additionally filter the results after the table has been read but
        before the response is returned by using query filters.

        To specify the filters of the items you'd like to get, you can specify
        the filters as kwargs. Each filter kwarg should follow the pattern
        ``<fieldname>__<filter_operation>=<value_to_look_for>``.

        Optionally accepts a ``limit`` parameter, which should be an integer
        count of the total number of items to return. (Default: ``None`` -
        all results)

        Optionally accepts a ``segment`` parameter, which should be an integer
        of the segment to retrieve on. Please see the documentation about
        Parallel Scans (Default: ``None`` - no segments)

        Optionally accepts a ``total_segments`` parameter, which should be an
        integer count of number of segments to divide the table into.
        Please see the documentation about Parallel Scans (Default: ``None`` -
        no segments)

        Optionally accepts a ``max_page_size`` parameter, which should be an
        integer count of the maximum number of items to retrieve
        **per-request**. This is useful in making faster requests & prevent
        the scan from drowning out other queries. (Default: ``None`` -
        fetch as many as DynamoDB will return)

        Optionally accepts an ``attributes`` parameter, which should be a
        tuple. If you provide any attributes only these will be fetched
        from DynamoDB. This uses the ``AttributesToGet`` and set's
        ``Select`` to ``SPECIFIC_ATTRIBUTES`` API.

        Returns a ``ResultSet``, which transparently handles the pagination of
        results you get back.

        Example::

            # All results.
            >>> everything = users.scan()

            # Look for last names beginning with "D".
            >>> results = users.scan(last_name__beginswith='D')
            >>> for res in results:
            ...     print res['first_name']
            'Alice'
            'John'
            'Jane'

            # Use an ``IN`` filter & limit.
            >>> results = users.scan(
            ...     age__in=[25, 26, 27, 28, 29],
            ...     limit=1
            ... )
            >>> for res in results:
            ...     print res['first_name']
            'Alice'

        r   )r   segmenttotal_segmentsrr   r   )r   r   r`   r   _scan)
r%   r   r   r   r   rr   r   r   r   r>   r&   r&   r'   scan]  s    @z
Table.scanc                 K   s   |||||d}|rBi |d< |  D ]\}	}
| j|
|d |	< q$| j|td|d< | jj| jf|}g }d}|dg D ]$}t	| }|
d|i || qz|ddri }|d   D ]\}	}
| j|
||	< q||d	S )
z
        The internal method that performs the actual scan. Used extensively
        by ``ResultSet`` to perform each (paginated) request.
        )r   r   r   rl   r   r   r   Zscan_filterNr   r   r   r   )rV   r$   rf   r   r   r    r   r   rE   r   rp   r2   r   )r%   r   r   r   r   rr   r   r   r>   ri   rj   r   r   r   r   rt   r&   r&   r'   r     sH    

 zTable._scanc                 C   s$   t || jd}|j| j||d |S )a  
        Fetches many specific items in batch from a table.

        Requires a ``keys`` parameter, which should be a list of dictionaries.
        Each dictionary should consist of the keys values to specify.

        Optionally accepts a ``consistent`` parameter, which should be a
        boolean. If you provide ``True``, a strongly consistent read will be
        used. (Default: False)

        Optionally accepts an ``attributes`` parameter, which should be a
        tuple. If you provide any attributes only these will be fetched
        from DynamoDB.

        Returns a ``ResultSet``, which transparently handles the pagination of
        results you get back.

        Example::

            >>> results = users.batch_get(keys=[
            ...     {
            ...         'username': 'johndoe',
            ...     },
            ...     {
            ...         'username': 'jane',
            ...     },
            ...     {
            ...         'username': 'fred',
            ...     },
            ... ])
            >>> for res in results:
            ...     print res['first_name']
            'John'
            'Jane'
            'Fred'

        )rg   max_batch_get)rq   rr   )r   r   r   
_batch_get)r%   rg   rq   rr   r   r&   r&   r'   	batch_get  s    (zTable.batch_getc                 C   s,  | j dg ii}|r d|| j  d< |dk	r6||| j  d< |D ]>}i }| D ]\}}| j|||< qJ|| j  d | q:| jj|d}	g }
g }|	d | j g D ]$}t| }|	d|i |
| q|	d	i | j i }|dg D ]4}i }| D ]\}}| j
|||< q|| q|
d|d
S )z
        The internal method that performs the actual batch get. Used extensively
        by ``BatchGetResultSet`` to perform each (paginated) request.
        ZKeysTZConsistentReadNZAttributesToGet)Zrequest_itemsZ	Responsesr   ZUnprocessedKeys)r   r   unprocessed_keys)r   rV   r$   rf   r2   r    Zbatch_get_itemrE   r   rp   r   )r%   rg   rq   rr   rV   Zkey_datarh   ri   rj   r   r   r   r   rt   Zraw_unprocessedZpy_keyr&   r&   r'   r     sD      zTable._batch_getc                 C   s   |   }|d ddS )z
        Returns a (very) eventually consistent count of the number of items
        in a table.

        Lag time is about 6 hours, so don't expect a high degree of accuracy.

        Example::

            >>> users.count()
            6

        r   Z	ItemCountr   )rR   rE   )r%   infor&   r&   r'   countC  s    zTable.count)NNNNN)NNNN)N)NN)FN)F)N)N)NN)NNFFNN)NNFFNNNN)NFNNTNN)	NNFFNNNNN)NNNNNN)NNNNNN)FN)FN)1__name__
__module____qualname____doc__r   dictr   r	   r
   r   r   r   rL   r(   r+   classmethodr@   rG   rJ   rM   rO   rR   r`   ra   rc   rd   re   rk   rn   rv   r|   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r&   r&   r&   r'   r      s   	    
W    z
!	1
O7*5
;'
!


@,@    
         
        
i         
>      
N      
5
,
7r   c                   @   sZ   e Zd ZdZdd Zdd Zdd Zdd	d
Zdd Zdd Z	dd Z
dd Zdd ZdS )r   z
    Used by ``Table`` as the context manager for batch writes.

    You likely don't want to try to use this object directly.
    c                 C   s   || _ g | _g | _g | _d S r)   )r:   _to_put
_to_delete_unprocessed)r%   r:   r&   r&   r'   r(   Z  s    zBatchTable.__init__c                 C   s   | S r)   r&   r*   r&   r&   r'   	__enter__`  s    zBatchTable.__enter__c                 C   s&   | j s| jr|   | jr"|   d S r)   )r   r   flushr   resend_unprocessed)r%   typerj   	tracebackr&   r&   r'   __exit__c  s    zBatchTable.__exit__Fc                 C   s    | j | |  r|   d S r)   )r   r2   should_flushr   )r%   r[   r   r&   r&   r'   r   l  s    zBatchTable.put_itemc                 K   s    | j | |  r|   d S r)   )r   r2   r   r   ru   r&   r&   r'   r   r  s    zBatchTable.delete_itemc                 C   s    t | jt | j dkrdS dS )N   TF)r   r   r   r*   r&   r&   r'   r   x  s    zBatchTable.should_flushc                 C   s   | j jg i}| jD ]0}t| j |d}|| j j dd| ii q| jD ]&}|| j j dd| j |ii qJ| j j	|}| 
| g | _g | _dS )Nr}   Z
PutRequestr   ZDeleteRequestZKeyT)r:   r   r   r   r2   Zprepare_fullr   rk   r    batch_write_itemhandle_unprocessed)r%   
batch_dataputrt   re   respr&   r&   r'   r   ~  s.     
 
 

zBatchTable.flushc                 C   sP   t |dg rL| jj}|d |g }d}tj|t |  | j| d S )NZUnprocessedItemsz-%s items were unprocessed. Storing for later.)	r   rE   r:   r   rX   rY   r   r   extend)r%   r   r   Zunprocessedr_   r&   r&   r'   r     s    zBatchTable.handle_unprocessedc                 C   s   t jdt| j  t| jr| jd d }| jdd  | _| jj|i}t jdt|  | jj|}| 	| t jdt| j  qd S )Nz Re-sending %s unprocessed items.r   zSending %s itemsz%s unprocessed items left)
rX   rY   r   r   r   r:   r   r    r   r   )r%   Z	to_resendr   r   r&   r&   r'   r     s    
 
zBatchTable.resend_unprocessedN)F)r   r   r   r   r(   r   r   r   r   r   r   r   r   r&   r&   r&   r'   r   T  s   	
r   )rX   Zboto.dynamodb2r   Zboto.dynamodb2.fieldsr   r   r   r   r   r   r	   r
   Zboto.dynamodb2.itemsr   Zboto.dynamodb2.layer1r   Zboto.dynamodb2.resultsr   r   Zboto.dynamodb2.typesr   r   r   r   r   Zboto.exceptionr   objectr   r   r&   r&   r&   r'   <module>   s*   (            Q