Exemplo n.º 1
0
def Init():
    """
    Connect to DynamoDB Local. If you want to connect to the real DynamoDB set the 'local'
    variable below to Fals, but make sure either you have a .boto file or you
    pass both the aws_access_key_id and aws_secret_access_key parameters to the create
    (this code fetches them from settings.cfg).
    """
    local = True

    if local:
        # Connect to local DynamoDB server. Make sure you have that running first.
        conn = DynamoDBConnection(host='localhost',
                                  port=8001,
                                  aws_secret_access_key='anything',
                                  is_secure=False)
    else:
        # Connect to the real DynamoDB.
        config = ConfigParser.RawConfigParser()
        config.read("settings.cfg")
        id = config.get('DynamoDB', 'aws_access_key_id')
        key = config.get('DynamoDB', 'aws_secret_access_key')

        conn = boto.dynamodb2.connect_to_region('us-west-2',
                                                aws_access_key_id=id,
                                                aws_secret_access_key=key)

    # Get a list of all tables from DynamoDB.
    tables = conn.list_tables()
    #print "Tables:", tables
    """
    If there isn't an employees table then create it. The table has a primary key of the
    employee type and id, allowing you to query them. It has a secondary index on the 
    employee type and title, allowing you to query them as well.
    """

    if 'employees' not in tables['TableNames']:
        # Create table of employees
        print "Creating new table"
        employees = Table.create(
            'employees',
            schema=[HashKey('etype'), RangeKey('id')],
            indexes=[
                AllIndex('TitleIndex',
                         parts=[HashKey('etype'),
                                RangeKey('title')])
            ],
            connection=conn)
        # Wait for table to be created (DynamoDB has eventual consistency)
        while True:
            time.sleep(5)
            try:
                conn.describe_table('employees')
            except Exception, e:
                print e
            else:
                break
Exemplo n.º 2
0
def Init():
    """
    Connect to DynamoDB Local. If you want to connect to the real DynamoDB set the 'local'
    variable below to Fals, but make sure either you have a .boto file or you
    pass both the aws_access_key_id and aws_secret_access_key parameters to the create
    (this code fetches them from settings.cfg).
    """
    local = True

    if local:
        # Connect to local DynamoDB server. Make sure you have that running first.
        conn = DynamoDBConnection(
            host='localhost',
            port=8001,
            aws_secret_access_key='anything',
            is_secure=False)
    else:
        # Connect to the real DynamoDB.
        config = ConfigParser.RawConfigParser()
        config.read("settings.cfg")
        id = config.get('DynamoDB', 'aws_access_key_id')
        key = config.get('DynamoDB', 'aws_secret_access_key')

        conn = boto.dynamodb2.connect_to_region('us-west-2',
            aws_access_key_id = id, aws_secret_access_key = key)

    # Get a list of all tables from DynamoDB.
    tables = conn.list_tables()
    #print "Tables:", tables

    """
    If there isn't an employees table then create it. The table has a primary key of the
    employee type and id, allowing you to query them. It has a secondary index on the 
    employee type and title, allowing you to query them as well.
    """

    if 'employees' not in tables['TableNames']:
        # Create table of employees
        print "Creating new table"
        employees = Table.create('employees',
                                 schema = [HashKey('etype'), RangeKey('id')],
                                 indexes = [AllIndex('TitleIndex', parts = [
                                                HashKey('etype'),
                                                RangeKey('title')])],
                                 connection = conn)
        # Wait for table to be created (DynamoDB has eventual consistency)
        while True:
            time.sleep(5)
            try:
                conn.describe_table('employees')
            except Exception, e:
                print e
            else:
                break
Exemplo n.º 3
0
def main():
    if len(sys.argv) == 2 and sys.argv[1] == 'check':
        print "*** Checking the table in dynamoDB, create one if not exist..."
        try:
            ddbc = DynamoDBConnection()
            src = ddbc.describe_table(iperf_table_name)['Table']
            logs = Table(iperf_table_name, schema=[HashKey('path'),RangeKey('datetime'),])
            logs.describe()
            sys.exit(0)
        except JSONResponseError:
            logs = Table.create(iperf_table_name, schema=[HashKey('path'),RangeKey('datetime'),])
            while ddbc.describe_table(iperf_table_name)['Table']['TableStatus'] != 'ACTIVE':
                sleep(3)
            sys.exit(1)
    if len(sys.argv) != 4:
        print "usage: %s <iperf_client_name> <datetime> <iperf_server_name>" % sys.argv[0]
        sys.exit(2)

    # Store arg lists
    iperf_client_name = sys.argv[1]
    datetime = sys.argv[2]
    iperf_server_name = sys.argv[3]
    path = iperf_client_name + '-' + iperf_server_name

    # Retrieve dynamoDB object
    try:
        logs = Table(iperf_table_name, schema=[HashKey('path'),RangeKey('datetime'),])
        tmp = logs.describe()
    except JSONResponseError:
        print "The table %s doesn't exist!" % iperf_table_name
        sys.exit(1)

    # Parse iperf log
    iperf = {}
    iperf['path'] = path
    iperf['datetime'] = datetime
    line = open(os.path.dirname(os.path.abspath(__file__))+'/log/'+datetime+'.log','r').readlines()[6]
    m = re.search(r"sec\s+(\d+\s+\w+)\s+(\d+\s+[\w/]+)", line)
    transfer = m.group(1)
    bandwidth = m.group(2)
    iperf['transfer'] = transfer
    iperf['bandwidth'] = bandwidth

    # Put the log to the dynamoDB table
    try:
        logs.put_item(data=iperf, overwrite=True)
    except ValidationException:
        pprint(iperf)
    except JSONResponseError:
        pass
Exemplo n.º 4
0
    def createTable(self):
        provider = Provider('aws')
        connection = DynamoDBConnection(aws_access_key_id=provider.get_access_key(),
            aws_secret_access_key=provider.get_secret_key(), region=self.regionv2)
        self.blockTablev2 = Table.create(self.tableName + "Blocks",
            schema=[
                HashKey('blockId'),
                RangeKey('blockNum', data_type=NUMBER)
            ],
            throughput={'read': 30, 'write': 10},
            connection=connection
        )
        self.tablev2 = Table.create(self.tableName,
            schema=[
                HashKey('path'),
                RangeKey('name')
            ],
            throughput={'read': 30, 'write': 10},
            indexes=[
                KeysOnlyIndex("Links", parts=[
                    HashKey('path'),
                    RangeKey('link')
                ])
            ],
            connection=connection
        )

        description = connection.describe_table(self.tableName)
        iter = 0
        while description["Table"]["TableStatus"] != "ACTIVE":
            print "Waiting for %s to create %d..." % (self.tableName, iter)
            iter += 1
            sleep(1)
            description = connection.describe_table(self.tableName)
        self.table = self.conn.get_table(self.tableName)
        self.blockTable = self.conn.get_table(self.tableName + "Blocks")
Exemplo n.º 5
0
def getMessageTable():
    conn = None
    if os.environ.get('DEVELOPER_MODE'):
        host, port = 'localhost', 8000
        confirmDynamoDbLocalIsRunning(host, port)
        conn = DynamoDBConnection(host=host,
                                  port=port,
                                  aws_access_key_id='unit_test',
                                  aws_secret_access_key='unit_test',
                                  is_secure=False)
    else:
        conn = DynamoDBConnection()

    try:
        msg_table_desc = conn.describe_table(_message_table)
        msg_table = Table(_message_table, connection=conn)
    except JSONResponseError as e:
        # Only handle the ResourceNotFoundException here
        if e.error_code != 'ResourceNotFoundException':
            raise e

        msg_table = Table.create(
            _message_table,
            schema=[HashKey('date_string'),
                    RangeKey('date')],
            throughput={
                'read': 5,
                'write': 5
            },
            connection=conn)

    while not msg_table.describe()['Table']['TableStatus'] == "ACTIVE":
        from time import sleep
        sleep(1)

    return msg_table
Exemplo n.º 6
0
class Table(object):
    """
    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.
    """
    max_batch_get = 100

    def __init__(self,
                 table_name,
                 schema=None,
                 throughput=None,
                 indexes=None,
                 connection=None):
        """
        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 ``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=[
            ...         RangeKey('date_joined')
            ...     ]),
            ... ],
            ... connection=dynamodb2.connect_to_region('us-west-2',
		    ...     aws_access_key_id='key',
		    ...     aws_secret_access_key='key',
	        ... ))

        """
        self.table_name = table_name
        self.connection = connection
        self.throughput = {
            'read': 5,
            'write': 5,
        }
        self.schema = schema
        self.indexes = indexes

        if self.connection is None:
            self.connection = DynamoDBConnection()

        if throughput is not None:
            self.throughput = throughput

        self._dynamizer = Dynamizer()

    @classmethod
    def create(cls,
               table_name,
               schema,
               throughput=None,
               indexes=None,
               connection=None):
        """
        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 & indexes 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 ``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=[
            ...         RangeKey('date_joined')
            ...     ]),
            ... ])

        """
        table = cls(table_name=table_name, connection=connection)
        table.schema = schema

        if throughput is not None:
            table.throughput = throughput

        if indexes is not None:
            table.indexes = indexes

        # Prep the schema.
        raw_schema = []
        attr_defs = []

        for field in table.schema:
            raw_schema.append(field.schema())
            # Build the attributes off what we know.
            attr_defs.append(field.definition())

        raw_throughput = {
            'ReadCapacityUnits': int(table.throughput['read']),
            'WriteCapacityUnits': int(table.throughput['write']),
        }
        kwargs = {}

        if table.indexes:
            # Prep the LSIs.
            raw_lsi = []

            for index_field in table.indexes:
                raw_lsi.append(index_field.schema())
                # Again, build the attributes off what we know.
                # HOWEVER, only add attributes *NOT* already seen.
                attr_define = index_field.definition()

                for part in attr_define:
                    attr_names = [attr['AttributeName'] for attr in attr_defs]

                    if not part['AttributeName'] in attr_names:
                        attr_defs.append(part)

            kwargs['local_secondary_indexes'] = raw_lsi

        table.connection.create_table(table_name=table.table_name,
                                      attribute_definitions=attr_defs,
                                      key_schema=raw_schema,
                                      provisioned_throughput=raw_throughput,
                                      **kwargs)
        return table

    def _introspect_schema(self, raw_schema):
        """
        Given a raw schema structure back from a DynamoDB response, parse
        out & build the high-level Python objects that represent them.
        """
        schema = []

        for field in raw_schema:
            if field['KeyType'] == 'HASH':
                schema.append(HashKey(field['AttributeName']))
            elif field['KeyType'] == 'RANGE':
                schema.append(RangeKey(field['AttributeName']))
            else:
                raise exceptions.UnknownSchemaFieldError(
                    "%s was seen, but is unknown. Please report this at "
                    "https://github.com/boto/boto/issues." % field['KeyType'])

        return schema

    def _introspect_indexes(self, raw_indexes):
        """
        Given a raw index structure back from a DynamoDB response, parse
        out & build the high-level Python objects that represent them.
        """
        indexes = []

        for field in raw_indexes:
            index_klass = AllIndex
            kwargs = {'parts': []}

            if field['Projection']['ProjectionType'] == 'ALL':
                index_klass = AllIndex
            elif field['Projection']['ProjectionType'] == 'KEYS_ONLY':
                index_klass = KeysOnlyIndex
            elif field['Projection']['ProjectionType'] == 'INCLUDE':
                index_klass = IncludeIndex
                kwargs['includes'] = field['Projection']['NonKeyAttributes']
            else:
                raise exceptions.UnknownIndexFieldError(
                    "%s was seen, but is unknown. Please report this at "
                    "https://github.com/boto/boto/issues." % \
                    field['Projection']['ProjectionType']
                )

            name = field['IndexName']
            kwargs['parts'] = self._introspect_schema(field['KeySchema'])
            indexes.append(index_klass(name, **kwargs))

        return indexes

    def describe(self):
        """
        Describes the current structure of the table in DynamoDB.

        This information will be used to update the ``schema``, ``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 datastructure 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

        """
        result = self.connection.describe_table(self.table_name)

        # Blindly update throughput, since what's on DynamoDB's end is likely
        # more correct.
        raw_throughput = result['Table']['ProvisionedThroughput']
        self.throughput['read'] = int(raw_throughput['ReadCapacityUnits'])
        self.throughput['write'] = int(raw_throughput['WriteCapacityUnits'])

        if not self.schema:
            # Since we have the data, build the schema.
            raw_schema = result['Table'].get('KeySchema', [])
            self.schema = self._introspect_schema(raw_schema)

        if not self.indexes:
            # Build the index information as well.
            raw_indexes = result['Table'].get('LocalSecondaryIndexes', [])
            self.indexes = self._introspect_indexes(raw_indexes)

        # This is leaky.
        return result

    def update(self, throughput):
        """
        Updates table attributes in DynamoDB.

        Currently, the only thing you can modify about a table after it has
        been created is the throughput.

        Requires 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.

        Returns ``True`` on success.

        Example::

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

        """
        self.throughput = throughput
        self.connection.update_table(
            self.table_name, {
                'ReadCapacityUnits': int(self.throughput['read']),
                'WriteCapacityUnits': int(self.throughput['write']),
            })
        return True

    def delete(self):
        """
        Deletes a table in DynamoDB.

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

        Returns ``True`` on success.

        Example::

            >>> users.delete()
            True

        """
        self.connection.delete_table(self.table_name)
        return True

    def _encode_keys(self, keys):
        """
        Given a flat Python dictionary of keys/values, converts it into the
        nested dictionary DynamoDB expects.

        Converts::

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

        ...to...::

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

        """
        raw_key = {}

        for key, value in keys.items():
            raw_key[key] = self._dynamizer.encode(value)

        return raw_key

    def get_item(self, consistent=False, **kwargs):
        """
        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``)

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

        Example::

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

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

            # A consistent read (assuming the data might have just changed).
            >>> john = users.get_item(username='******', 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'

        """
        raw_key = self._encode_keys(kwargs)
        item_data = self.connection.get_item(self.table_name,
                                             raw_key,
                                             consistent_read=consistent)
        item = Item(self)
        item.load(item_data)
        return item

    def lookup(self, *args, **kwargs):
        """
        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')

        """
        if not self.schema:
            self.describe()
        for x, arg in enumerate(args):
            kwargs[self.schema[x].name] = arg
        ret = self.get_item(**kwargs)
        if not ret.keys():
            return None
        return ret

    def new_item(self, *args):
        """
        Returns a new, blank item

        This is mostly for consistency with boto.dynamodb
        """
        if not self.schema:
            self.describe()
        data = {}
        for x, arg in enumerate(args):
            data[self.schema[x].name] = arg
        return Item(self, data=data)

    def put_item(self, data, overwrite=False):
        """
        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': '******',
            ...     'first_name': 'Jane',
            ...     'last_name': 'Doe',
            ...     'date_joined': 126478915,
            ... })
            True

        """
        item = Item(self, data=data)
        return item.save(overwrite=overwrite)

    def _put_item(self, item_data, expects=None):
        """
        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.
        """
        kwargs = {}

        if expects is not None:
            kwargs['expected'] = expects

        self.connection.put_item(self.table_name, item_data, **kwargs)
        return True

    def _update_item(self, key, item_data, expects=None):
        """
        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.
        """
        raw_key = self._encode_keys(key)
        kwargs = {}

        if expects is not None:
            kwargs['expected'] = expects

        self.connection.update_item(self.table_name, raw_key, item_data,
                                    **kwargs)
        return True

    def delete_item(self, **kwargs):
        """
        Deletes an item in DynamoDB.

        **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.

        Returns ``True`` on success.

        Example::

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

            # A complex hash+range key.
            >>> users.delete_item(username='******', 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

        """
        raw_key = self._encode_keys(kwargs)
        self.connection.delete_item(self.table_name, raw_key)
        return True

    def get_key_fields(self):
        """
        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']

        """
        if not self.schema:
            # We don't know the structure of the table. Get a description to
            # populate the schema.
            self.describe()

        return [field.name for field in self.schema]

    def batch_write(self):
        """
        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': '******',
            ...         'first_name': 'John',
            ...         'last_name': 'Doe',
            ...         'owner': 1,
            ...     })
            ...     # Nothing across the wire yet.
            ...     batch.delete_item(username='******')
            ...     # Still no requests sent.
            ...     batch.put_item(data={
            ...         'username': '******',
            ...         'first_name': 'Jane',
            ...         'last_name': 'Doe',
            ...         'date_joined': 127436192,
            ...     })
            ...     # Nothing yet, but once we leave the context, the
            ...     # put/deletes will be sent.

        """
        # PHENOMENAL COSMIC DOCS!!! itty-bitty code.
        return BatchTable(self)

    def _build_filters(self, filter_kwargs, using=QUERY_OPERATORS):
        """
        An internal method for taking query/scan-style ``**kwargs`` & turning
        them into the raw structure DynamoDB expects for filtering.
        """
        filters = {}

        for field_and_op, value in filter_kwargs.items():
            field_bits = field_and_op.split('__')
            fieldname = '__'.join(field_bits[:-1])

            try:
                op = using[field_bits[-1]]
            except KeyError:
                raise exceptions.UnknownFilterTypeError(
                    "Operator '%s' from '%s' is not recognized." %
                    (field_bits[-1], field_and_op))

            lookup = {
                'AttributeValueList': [],
                'ComparisonOperator': op,
            }

            # Special-case the ``NULL/NOT_NULL`` case.
            if field_bits[-1] == 'null':
                del lookup['AttributeValueList']

                if value is False:
                    lookup['ComparisonOperator'] = 'NOT_NULL'
                else:
                    lookup['ComparisonOperator'] = 'NULL'
            # Special-case the ``BETWEEN`` case.
            elif field_bits[-1] == 'between':
                if len(value) == 2 and isinstance(value, (list, tuple)):
                    lookup['AttributeValueList'].append(
                        self._dynamizer.encode(value[0]))
                    lookup['AttributeValueList'].append(
                        self._dynamizer.encode(value[1]))
            else:
                # Fix up the value for encoding, because it was built to only work
                # with ``set``s.
                if isinstance(value, (list, tuple)):
                    value = set(value)
                lookup['AttributeValueList'].append(
                    self._dynamizer.encode(value))

            # Finally, insert it into the filters.
            filters[fieldname] = lookup

        return filters

    def query(self,
              limit=None,
              index=None,
              reverse=False,
              consistent=False,
              attributes=None,
              **filter_kwargs):
        """
        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.

        **Note** - You can not query against arbitrary fields within the data
        stored in DynamoDB.

        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 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: ``None`` - 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.

        Returns a ``ResultSet``, 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'

        """
        if self.schema:
            if len(self.schema) == 1 and len(filter_kwargs) <= 1:
                raise exceptions.QueryError(
                    "You must specify more than one key to filter on.")

        if attributes is not None:
            select = 'SPECIFIC_ATTRIBUTES'
        else:
            select = None

        results = ResultSet()
        kwargs = filter_kwargs.copy()
        kwargs.update({
            'limit': limit,
            'index': index,
            'reverse': reverse,
            'consistent': consistent,
            'select': select,
            'attributes_to_get': attributes
        })
        results.to_call(self._query, **kwargs)
        return results

    def query_count(self, index=None, consistent=False, **filter_kwargs):
        """
        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.

        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 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)

        Returns an integer which represents the exact amount of matched
        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

        """
        key_conditions = self._build_filters(filter_kwargs,
                                             using=QUERY_OPERATORS)

        raw_results = self.connection.query(
            self.table_name,
            index_name=index,
            consistent_read=consistent,
            select='COUNT',
            key_conditions=key_conditions,
        )
        return int(raw_results.get('Count', 0))

    def _query(self,
               limit=None,
               index=None,
               reverse=False,
               consistent=False,
               exclusive_start_key=None,
               select=None,
               attributes_to_get=None,
               **filter_kwargs):
        """
        The internal method that performs the actual queries. Used extensively
        by ``ResultSet`` to perform each (paginated) request.
        """
        kwargs = {
            'limit': limit,
            'index_name': index,
            'scan_index_forward': reverse,
            'consistent_read': consistent,
            'select': select,
            'attributes_to_get': attributes_to_get
        }

        if exclusive_start_key:
            kwargs['exclusive_start_key'] = {}

            for key, value in exclusive_start_key.items():
                kwargs['exclusive_start_key'][key] = \
                    self._dynamizer.encode(value)

        # Convert the filters into something we can actually use.
        kwargs['key_conditions'] = self._build_filters(filter_kwargs,
                                                       using=QUERY_OPERATORS)

        raw_results = self.connection.query(self.table_name, **kwargs)
        results = []
        last_key = None

        for raw_item in raw_results.get('Items', []):
            item = Item(self)
            item.load({
                'Item': raw_item,
            })
            results.append(item)

        if raw_results.get('LastEvaluatedKey', None):
            last_key = {}

            for key, value in raw_results['LastEvaluatedKey'].items():
                last_key[key] = self._dynamizer.decode(value)

        return {
            'results': results,
            'last_key': last_key,
        }

    def scan(self,
             limit=None,
             segment=None,
             total_segments=None,
             **filter_kwargs):
        """
        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.

        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)

        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'

        """
        results = ResultSet()
        kwargs = filter_kwargs.copy()
        kwargs.update({
            'limit': limit,
            'segment': segment,
            'total_segments': total_segments,
        })
        results.to_call(self._scan, **kwargs)
        return results

    def _scan(self,
              limit=None,
              exclusive_start_key=None,
              segment=None,
              total_segments=None,
              **filter_kwargs):
        """
        The internal method that performs the actual scan. Used extensively
        by ``ResultSet`` to perform each (paginated) request.
        """
        kwargs = {
            'limit': limit,
            'segment': segment,
            'total_segments': total_segments,
        }

        if exclusive_start_key:
            kwargs['exclusive_start_key'] = {}

            for key, value in exclusive_start_key.items():
                kwargs['exclusive_start_key'][key] = \
                    self._dynamizer.encode(value)

        # Convert the filters into something we can actually use.
        kwargs['scan_filter'] = self._build_filters(filter_kwargs,
                                                    using=FILTER_OPERATORS)

        raw_results = self.connection.scan(self.table_name, **kwargs)
        results = []
        last_key = None

        for raw_item in raw_results.get('Items', []):
            item = Item(self)
            item.load({
                'Item': raw_item,
            })
            results.append(item)

        if raw_results.get('LastEvaluatedKey', None):
            last_key = {}

            for key, value in raw_results['LastEvaluatedKey'].items():
                last_key[key] = self._dynamizer.decode(value)

        return {
            'results': results,
            'last_key': last_key,
        }

    def batch_get(self, keys, consistent=False):
        """
        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)

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

        Example::

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

        """
        # We pass the keys to the constructor instead, so it can maintain it's
        # own internal state as to what keys have been processed.
        results = BatchGetResultSet(keys=keys,
                                    max_batch_get=self.max_batch_get)
        results.to_call(self._batch_get, consistent=False)
        return results

    def _batch_get(self, keys, consistent=False):
        """
        The internal method that performs the actual batch get. Used extensively
        by ``BatchGetResultSet`` to perform each (paginated) request.
        """
        items = {
            self.table_name: {
                'Keys': [],
            },
        }

        if consistent:
            items[self.table_name]['ConsistentRead'] = True

        for key_data in keys:
            raw_key = {}

            for key, value in key_data.items():
                raw_key[key] = self._dynamizer.encode(value)

            items[self.table_name]['Keys'].append(raw_key)

        raw_results = self.connection.batch_get_item(request_items=items)
        results = []
        unprocessed_keys = []

        for raw_item in raw_results['Responses'].get(self.table_name, []):
            item = Item(self)
            item.load({
                'Item': raw_item,
            })
            results.append(item)

        raw_unproccessed = raw_results.get('UnprocessedKeys', {})

        for raw_key in raw_unproccessed.get('Keys', []):
            py_key = {}

            for key, value in raw_key.items():
                py_key[key] = self._dynamizer.decode(value)

            unprocessed_keys.append(py_key)

        return {
            'results': results,
            # NEVER return a ``last_key``. Just in-case any part of
            # ``ResultSet`` peeks through, since much of the
            # original underlying implementation is based on this key.
            'last_key': None,
            'unprocessed_keys': unprocessed_keys,
        }

    def count(self):
        """
        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

        """
        info = self.describe()
        return info['Table'].get('ItemCount', 0)
Exemplo n.º 7
0
class Table(object):
    """
    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.
    """

    max_batch_get = 100

    def __init__(self, table_name, schema=None, throughput=None, indexes=None, connection=None):
        """
        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 ``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=[
            ...         RangeKey('date_joined')
            ...     ]),
            ... ],
            ... connection=dynamodb2.connect_to_region('us-west-2',
		    ...     aws_access_key_id='key',
		    ...     aws_secret_access_key='key',
	        ... ))

        """
        self.table_name = table_name
        self.connection = connection
        self.throughput = {"read": 5, "write": 5}
        self.schema = schema
        self.indexes = indexes

        if self.connection is None:
            self.connection = DynamoDBConnection()

        if throughput is not None:
            self.throughput = throughput

        self._dynamizer = Dynamizer()

    @classmethod
    def create(cls, table_name, schema, throughput=None, indexes=None, connection=None):
        """
        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 & indexes 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 ``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=[
            ...         RangeKey('date_joined')
            ...     ]),
            ... ])

        """
        table = cls(table_name=table_name, connection=connection)
        table.schema = schema

        if throughput is not None:
            table.throughput = throughput

        if indexes is not None:
            table.indexes = indexes

        # Prep the schema.
        raw_schema = []
        attr_defs = []

        for field in table.schema:
            raw_schema.append(field.schema())
            # Build the attributes off what we know.
            attr_defs.append(field.definition())

        raw_throughput = {
            "ReadCapacityUnits": int(table.throughput["read"]),
            "WriteCapacityUnits": int(table.throughput["write"]),
        }
        kwargs = {}

        if table.indexes:
            # Prep the LSIs.
            raw_lsi = []

            for index_field in table.indexes:
                raw_lsi.append(index_field.schema())
                # Again, build the attributes off what we know.
                # HOWEVER, only add attributes *NOT* already seen.
                attr_define = index_field.definition()

                for part in attr_define:
                    attr_names = [attr["AttributeName"] for attr in attr_defs]

                    if not part["AttributeName"] in attr_names:
                        attr_defs.append(part)

            kwargs["local_secondary_indexes"] = raw_lsi

        table.connection.create_table(
            table_name=table.table_name,
            attribute_definitions=attr_defs,
            key_schema=raw_schema,
            provisioned_throughput=raw_throughput,
            **kwargs
        )
        return table

    def _introspect_schema(self, raw_schema):
        """
        Given a raw schema structure back from a DynamoDB response, parse
        out & build the high-level Python objects that represent them.
        """
        schema = []

        for field in raw_schema:
            if field["KeyType"] == "HASH":
                schema.append(HashKey(field["AttributeName"]))
            elif field["KeyType"] == "RANGE":
                schema.append(RangeKey(field["AttributeName"]))
            else:
                raise exceptions.UnknownSchemaFieldError(
                    "%s was seen, but is unknown. Please report this at "
                    "https://github.com/boto/boto/issues." % field["KeyType"]
                )

        return schema

    def _introspect_indexes(self, raw_indexes):
        """
        Given a raw index structure back from a DynamoDB response, parse
        out & build the high-level Python objects that represent them.
        """
        indexes = []

        for field in raw_indexes:
            index_klass = AllIndex
            kwargs = {"parts": []}

            if field["Projection"]["ProjectionType"] == "ALL":
                index_klass = AllIndex
            elif field["Projection"]["ProjectionType"] == "KEYS_ONLY":
                index_klass = KeysOnlyIndex
            elif field["Projection"]["ProjectionType"] == "INCLUDE":
                index_klass = IncludeIndex
                kwargs["includes"] = field["Projection"]["NonKeyAttributes"]
            else:
                raise exceptions.UnknownIndexFieldError(
                    "%s was seen, but is unknown. Please report this at "
                    "https://github.com/boto/boto/issues." % field["Projection"]["ProjectionType"]
                )

            name = field["IndexName"]
            kwargs["parts"] = self._introspect_schema(field["KeySchema"])
            indexes.append(index_klass(name, **kwargs))

        return indexes

    def describe(self):
        """
        Describes the current structure of the table in DynamoDB.

        This information will be used to update the ``schema``, ``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 datastructure 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

        """
        result = self.connection.describe_table(self.table_name)

        # Blindly update throughput, since what's on DynamoDB's end is likely
        # more correct.
        raw_throughput = result["Table"]["ProvisionedThroughput"]
        self.throughput["read"] = int(raw_throughput["ReadCapacityUnits"])
        self.throughput["write"] = int(raw_throughput["WriteCapacityUnits"])

        if not self.schema:
            # Since we have the data, build the schema.
            raw_schema = result["Table"].get("KeySchema", [])
            self.schema = self._introspect_schema(raw_schema)

        if not self.indexes:
            # Build the index information as well.
            raw_indexes = result["Table"].get("LocalSecondaryIndexes", [])
            self.indexes = self._introspect_indexes(raw_indexes)

        # This is leaky.
        return result

    def update(self, throughput):
        """
        Updates table attributes in DynamoDB.

        Currently, the only thing you can modify about a table after it has
        been created is the throughput.

        Requires 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.

        Returns ``True`` on success.

        Example::

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

        """
        self.throughput = throughput
        self.connection.update_table(
            self.table_name,
            {"ReadCapacityUnits": int(self.throughput["read"]), "WriteCapacityUnits": int(self.throughput["write"])},
        )
        return True

    def delete(self):
        """
        Deletes a table in DynamoDB.

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

        Returns ``True`` on success.

        Example::

            >>> users.delete()
            True

        """
        self.connection.delete_table(self.table_name)
        return True

    def _encode_keys(self, keys):
        """
        Given a flat Python dictionary of keys/values, converts it into the
        nested dictionary DynamoDB expects.

        Converts::

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

        ...to...::

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

        """
        raw_key = {}

        for key, value in keys.items():
            raw_key[key] = self._dynamizer.encode(value)

        return raw_key

    def get_item(self, consistent=False, **kwargs):
        """
        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``)

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

        Example::

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

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

            # A consistent read (assuming the data might have just changed).
            >>> john = users.get_item(username='******', 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'

        """
        raw_key = self._encode_keys(kwargs)
        item_data = self.connection.get_item(self.table_name, raw_key, consistent_read=consistent)
        item = Item(self)
        item.load(item_data)
        return item

    def put_item(self, data, overwrite=False):
        """
        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': '******',
            ...     'first_name': 'Jane',
            ...     'last_name': 'Doe',
            ...     'date_joined': 126478915,
            ... })
            True

        """
        item = Item(self, data=data)
        return item.save(overwrite=overwrite)

    def _put_item(self, item_data, expects=None):
        """
        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.
        """
        kwargs = {}

        if expects is not None:
            kwargs["expected"] = expects

        self.connection.put_item(self.table_name, item_data, **kwargs)
        return True

    def _update_item(self, key, item_data, expects=None):
        """
        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.
        """
        raw_key = self._encode_keys(key)
        kwargs = {}

        if expects is not None:
            kwargs["expected"] = expects

        self.connection.update_item(self.table_name, raw_key, item_data, **kwargs)
        return True

    def delete_item(self, **kwargs):
        """
        Deletes an item in DynamoDB.

        **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.

        Returns ``True`` on success.

        Example::

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

            # A complex hash+range key.
            >>> users.delete_item(username='******', 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

        """
        raw_key = self._encode_keys(kwargs)
        self.connection.delete_item(self.table_name, raw_key)
        return True

    def get_key_fields(self):
        """
        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']

        """
        if not self.schema:
            # We don't know the structure of the table. Get a description to
            # populate the schema.
            self.describe()

        return [field.name for field in self.schema]

    def batch_write(self):
        """
        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': '******',
            ...         'first_name': 'John',
            ...         'last_name': 'Doe',
            ...         'owner': 1,
            ...     })
            ...     # Nothing across the wire yet.
            ...     batch.delete_item(username='******')
            ...     # Still no requests sent.
            ...     batch.put_item(data={
            ...         'username': '******',
            ...         'first_name': 'Jane',
            ...         'last_name': 'Doe',
            ...         'date_joined': 127436192,
            ...     })
            ...     # Nothing yet, but once we leave the context, the
            ...     # put/deletes will be sent.

        """
        # PHENOMENAL COSMIC DOCS!!! itty-bitty code.
        return BatchTable(self)

    def _build_filters(self, filter_kwargs, using=QUERY_OPERATORS):
        """
        An internal method for taking query/scan-style ``**kwargs`` & turning
        them into the raw structure DynamoDB expects for filtering.
        """
        filters = {}

        for field_and_op, value in filter_kwargs.items():
            field_bits = field_and_op.split("__")
            fieldname = "__".join(field_bits[:-1])

            try:
                op = using[field_bits[-1]]
            except KeyError:
                raise exceptions.UnknownFilterTypeError(
                    "Operator '%s' from '%s' is not recognized." % (field_bits[-1], field_and_op)
                )

            lookup = {"AttributeValueList": [], "ComparisonOperator": op}

            # Special-case the ``NULL/NOT_NULL`` case.
            if field_bits[-1] == "null":
                del lookup["AttributeValueList"]

                if value is False:
                    lookup["ComparisonOperator"] = "NOT_NULL"
                else:
                    lookup["ComparisonOperator"] = "NULL"
            # Special-case the ``BETWEEN`` case.
            elif field_bits[-1] == "between":
                if len(value) == 2 and isinstance(value, (list, tuple)):
                    lookup["AttributeValueList"].append(self._dynamizer.encode(value[0]))
                    lookup["AttributeValueList"].append(self._dynamizer.encode(value[1]))
            else:
                # Fix up the value for encoding, because it was built to only work
                # with ``set``s.
                if isinstance(value, (list, tuple)):
                    value = set(value)
                lookup["AttributeValueList"].append(self._dynamizer.encode(value))

            # Finally, insert it into the filters.
            filters[fieldname] = lookup

        return filters

    def query(self, limit=None, index=None, reverse=False, consistent=False, attributes=None, **filter_kwargs):
        """
        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.

        **Note** - You can not query against arbitrary fields within the data
        stored in DynamoDB.

        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 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: ``None`` - 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.

        Returns a ``ResultSet``, 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'

        """
        if self.schema:
            if len(self.schema) == 1 and len(filter_kwargs) <= 1:
                raise exceptions.QueryError("You must specify more than one key to filter on.")

        if attributes is not None:
            select = "SPECIFIC_ATTRIBUTES"
        else:
            select = None

        results = ResultSet()
        kwargs = filter_kwargs.copy()
        kwargs.update(
            {
                "limit": limit,
                "index": index,
                "reverse": reverse,
                "consistent": consistent,
                "select": select,
                "attributes_to_get": attributes,
            }
        )
        results.to_call(self._query, **kwargs)
        return results

    def query_count(self, index=None, consistent=False, **filter_kwargs):
        """
        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.

        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 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)

        Returns an integer which represents the exact amount of matched
        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

        """
        key_conditions = self._build_filters(filter_kwargs, using=QUERY_OPERATORS)

        raw_results = self.connection.query(
            self.table_name, index_name=index, consistent_read=consistent, select="COUNT", key_conditions=key_conditions
        )
        return int(raw_results.get("Count", 0))

    def _query(
        self,
        limit=None,
        index=None,
        reverse=False,
        consistent=False,
        exclusive_start_key=None,
        select=None,
        attributes_to_get=None,
        **filter_kwargs
    ):
        """
        The internal method that performs the actual queries. Used extensively
        by ``ResultSet`` to perform each (paginated) request.
        """
        kwargs = {
            "limit": limit,
            "index_name": index,
            "scan_index_forward": reverse,
            "consistent_read": consistent,
            "select": select,
            "attributes_to_get": attributes_to_get,
        }

        if exclusive_start_key:
            kwargs["exclusive_start_key"] = {}

            for key, value in exclusive_start_key.items():
                kwargs["exclusive_start_key"][key] = self._dynamizer.encode(value)

        # Convert the filters into something we can actually use.
        kwargs["key_conditions"] = self._build_filters(filter_kwargs, using=QUERY_OPERATORS)

        raw_results = self.connection.query(self.table_name, **kwargs)
        results = []
        last_key = None

        for raw_item in raw_results.get("Items", []):
            item = Item(self)
            item.load({"Item": raw_item})
            results.append(item)

        if raw_results.get("LastEvaluatedKey", None):
            last_key = {}

            for key, value in raw_results["LastEvaluatedKey"].items():
                last_key[key] = self._dynamizer.decode(value)

        return {"results": results, "last_key": last_key}

    def scan(self, limit=None, segment=None, total_segments=None, **filter_kwargs):
        """
        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.

        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)

        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'

        """
        results = ResultSet()
        kwargs = filter_kwargs.copy()
        kwargs.update({"limit": limit, "segment": segment, "total_segments": total_segments})
        results.to_call(self._scan, **kwargs)
        return results

    def _scan(self, limit=None, exclusive_start_key=None, segment=None, total_segments=None, **filter_kwargs):
        """
        The internal method that performs the actual scan. Used extensively
        by ``ResultSet`` to perform each (paginated) request.
        """
        kwargs = {"limit": limit, "segment": segment, "total_segments": total_segments}

        if exclusive_start_key:
            kwargs["exclusive_start_key"] = {}

            for key, value in exclusive_start_key.items():
                kwargs["exclusive_start_key"][key] = self._dynamizer.encode(value)

        # Convert the filters into something we can actually use.
        kwargs["scan_filter"] = self._build_filters(filter_kwargs, using=FILTER_OPERATORS)

        raw_results = self.connection.scan(self.table_name, **kwargs)
        results = []
        last_key = None

        for raw_item in raw_results.get("Items", []):
            item = Item(self)
            item.load({"Item": raw_item})
            results.append(item)

        if raw_results.get("LastEvaluatedKey", None):
            last_key = {}

            for key, value in raw_results["LastEvaluatedKey"].items():
                last_key[key] = self._dynamizer.decode(value)

        return {"results": results, "last_key": last_key}

    def batch_get(self, keys, consistent=False):
        """
        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)

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

        Example::

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

        """
        # We pass the keys to the constructor instead, so it can maintain it's
        # own internal state as to what keys have been processed.
        results = BatchGetResultSet(keys=keys, max_batch_get=self.max_batch_get)
        results.to_call(self._batch_get, consistent=False)
        return results

    def _batch_get(self, keys, consistent=False):
        """
        The internal method that performs the actual batch get. Used extensively
        by ``BatchGetResultSet`` to perform each (paginated) request.
        """
        items = {self.table_name: {"Keys": []}}

        if consistent:
            items[self.table_name]["ConsistentRead"] = True

        for key_data in keys:
            raw_key = {}

            for key, value in key_data.items():
                raw_key[key] = self._dynamizer.encode(value)

            items[self.table_name]["Keys"].append(raw_key)

        raw_results = self.connection.batch_get_item(request_items=items)
        results = []
        unprocessed_keys = []

        for raw_item in raw_results["Responses"].get(self.table_name, []):
            item = Item(self)
            item.load({"Item": raw_item})
            results.append(item)

        raw_unproccessed = raw_results.get("UnprocessedKeys", {})

        for raw_key in raw_unproccessed.get("Keys", []):
            py_key = {}

            for key, value in raw_key.items():
                py_key[key] = self._dynamizer.decode(value)

            unprocessed_keys.append(py_key)

        return {
            "results": results,
            # NEVER return a ``last_key``. Just in-case any part of
            # ``ResultSet`` peeks through, since much of the
            # original underlying implementation is based on this key.
            "last_key": None,
            "unprocessed_keys": unprocessed_keys,
        }

    def count(self):
        """
        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

        """
        info = self.describe()
        return info["Table"].get("ItemCount", 0)
# host = 'dynamodb.%s.amazonaws.com' % region
# ddbc = DynamoDBConnection(is_secure=False, region=region, host=host)
DynamoDBConnection.DefaultRegionName = region
ddbc = DynamoDBConnection()

# 1. Read and copy the target table to be copied
table_struct = None
try:
    logs = Table(src_table, connection=ddbc)
    table_struct = logs.describe()
except JSONResponseError:
    print "Table %s does not exist" % src_table
    sys.exit(1)

print '*** Reading key schema from %s table' % src_table
src = ddbc.describe_table(src_table)['Table']
hash_key = ''
range_key = ''
for schema in src['KeySchema']:
    attr_name = schema['AttributeName']
    key_type = schema['KeyType']
    if key_type == 'HASH':
        hash_key = attr_name
    elif key_type == 'RANGE':
        range_key = attr_name

# 2. Create the new table
table_struct = None
try:
    new_logs = Table(dst_table,
                     connection=ddbc,
Exemplo n.º 9
0
source_hostname = 'dynamodb.{}.amazonaws.com'.format(src_region)
destination_hostname = 'dynamodb.{}.amazonaws.com'.format(dst_region)
source_ddbc = DynamoDBConnection(is_secure=False, region=src_region, host=source_hostname)
destination_ddbc = DynamoDBConnection(is_secure=False, region=dst_region, host=destination_hostname)

# 1. Try to connect to the source table
try:
    src_logs = Table(src_table, connection=source_ddbc)
    print "Connected to source table %s in region %s" % (src_table, src_region)
except JSONResponseError:
    print "Source table %s in region %s does not exist" % (src_table, src_region)
    sys.exit(1)(src_table, src_region)

print 'Reading source key schema from %s in %s' % (src_table, src_region)
src_table_describe = source_ddbc.describe_table(src_table)['Table']
src_hash_key = ''
src_range_key = ''
for schema in src_table_describe['KeySchema']:
    attr_name = schema['AttributeName']
    key_type = schema['KeyType']
    if key_type == 'HASH':
        src_hash_key = attr_name
    elif key_type == 'RANGE':
        src_range_key = attr_name
print 'Found hash_key = %s, and range_key = %s' % (src_hash_key, src_range_key or 'None')

# 2. Try to connect to the destination table
try:
    dst_logs = Table(dst_table, connection=destination_ddbc)
    print "Connected to destination table %s in region %s" % (dst_table, dst_region)
# host = 'dynamodb.%s.amazonaws.com' % region
# ddbc = DynamoDBConnection(is_secure=False, region=region, host=host)
DynamoDBConnection.DefaultRegionName = region
ddbc = DynamoDBConnection()

# 1. Read and copy the target table to be copied
table_struct = None
try:
    logs = Table(src_table, connection=ddbc)
    table_struct = logs.describe()
except JSONResponseError:
    print "Table %s does not exist" % src_table
    sys.exit(1)

print '*** Reading key schema from %s table' % src_table
src = ddbc.describe_table(src_table)['Table']
hash_key = ''
range_key = ''
for schema in src['KeySchema']:
    attr_name = schema['AttributeName']
    key_type = schema['KeyType']
    if key_type == 'HASH':
        hash_key = attr_name
    elif key_type == 'RANGE':
        range_key = attr_name

# 2. Create the new table
table_struct = None
try:
    new_logs = Table(dst_table,
                     connection=ddbc,
Exemplo n.º 11
0
region = os.getenv("AWS_DEFAULT_REGION", "ap-northeast-2")

DynamoDBConnection.DefaultRegionName = region
ddbc = DynamoDBConnection()

# source table
try:
    src_logs = Table(src_name, connection=ddbc)
    src_logs.describe()
except JSONResponseError:
    print("Table [%s] does not exist." % src_name)
    sys.exit(1)

print("# Read from [%s]." % src_name)
src_table = ddbc.describe_table(src_name)["Table"]

hash_key = ""
range_key = ""
for schema in src_table["KeySchema"]:
    attr_name = schema["AttributeName"]
    key_type = schema["KeyType"]
    if key_type == "HASH":
        hash_key = attr_name
    elif key_type == "RANGE":
        range_key = attr_name

# destnation table
try:
    dst_logs = Table(dst_name,
                     connection=ddbc,
Exemplo n.º 12
0
                                 host=source_hostname)
destination_ddbc = DynamoDBConnection(is_secure=False,
                                      region=dst_region,
                                      host=destination_hostname)

# 1. Try to connect to the source table
try:
    src_logs = Table(src_table, connection=source_ddbc)
    print "Connected to source table %s in region %s" % (src_table, src_region)
except JSONResponseError:
    print "Source table %s in region %s does not exist" % (src_table,
                                                           src_region)
    sys.exit(1)(src_table, src_region)

print 'Reading source key schema from %s in %s' % (src_table, src_region)
src_table_describe = source_ddbc.describe_table(src_table)['Table']
src_hash_key = ''
src_range_key = ''
for schema in src_table_describe['KeySchema']:
    attr_name = schema['AttributeName']
    key_type = schema['KeyType']
    if key_type == 'HASH':
        src_hash_key = attr_name
    elif key_type == 'RANGE':
        src_range_key = attr_name
print 'Found hash_key = %s, and range_key = %s' % (src_hash_key, src_range_key
                                                   or 'None')

# 2. Try to connect to the destination table
try:
    dst_logs = Table(dst_table, connection=destination_ddbc)
Exemplo n.º 13
0
class ClariDynamo(object):
    def __init__(self,
                 aws_access_key,
                 aws_secret_access_key,
                 is_secure,
                 is_remote=False,
                 host=None,
                 port=None,
                 in_memory=False,
                 auth_func=None):
        if auth_func and not auth_func():
            raise self.AuthException()

        self.host = host
        self.port = port
        self.is_secure = is_secure
        self.is_remote = is_remote
        self.in_memory = in_memory
        kwargs = {
            'aws_access_key_id': aws_access_key,
            'aws_secret_access_key': aws_secret_access_key,
            'is_secure': is_secure
        }
        if not is_remote:
            kwargs['host'] = host
            kwargs['port'] = port
            self.local_db = LocalDb(port, in_memory)

        self.connection = DynamoDBConnection(**kwargs)

    @item_op
    def query(self, table_name, purpose, tenant_id, **query):
        boto_table = self.get_table(table_name)
        # TODO: Implement paging by serializing underlying page data and
        # storing it for subsequent request.
        return boto_table.query_2(**query)

    @item_op
    def get_item(self,
                 table_name,
                 tenant_id,
                 purpose,
                 attributes=None,
                 **id_query):
        boto_table = self.get_table(table_name)
        if attributes is None:
            _attributes = None
        else:
            assert len(attributes) > 0, 'attributes should be a list'
            _attributes = attributes[:]

        self._add_mandatory_attributes(_attributes)
        item = self._get_with_retries(boto_table,
                                      table_name,
                                      id_query,
                                      _attributes,
                                      retry=0)
        self._check_tenant_id(item, tenant_id)
        self._check_for_meta(item._data, boto_table, operation='get')
        self._hide_mandatory_attributes(item, attributes)
        self._hide_internal_fields(item)
        return item

    @item_op
    def put_item(self,
                 table_name,
                 item,
                 tenant_id,
                 purpose,
                 overwrite=False,
                 condition=None,
                 vars=None):
        """
        Puts item into DynamoDB
        :param table_name:
        :param item:
        :param tenant_id: i.e. a user / customer id used for maintaining
                          data access boundaries between db tenants
        :param purpose:
        :param condition: DynamoDB condition # https://goo.gl/VRx8ST

        :return: Empty object on success: {}
        """
        boto_table = self.get_table(table_name)
        assert type(item) == dict
        assert isinstance(tenant_id, str)
        item['tenant_id'] = tenant_id
        item['encrypted_tenant_id'] = CRYPTO.encrypt(bytes(tenant_id, 'UTF-8'))
        item['created_at'] = item['updated_at'] = (str(datetime.now()))
        self._check_for_meta(item, boto_table, operation='put')

        # TODO: Get Boto/Dynamo to return new object
        return self._put_with_retries(boto_table,
                                      self._get_table_name(table_name),
                                      item,
                                      overwrite,
                                      condition,
                                      vars,
                                      retry=0)

    @item_op
    def delete_item(self, table_name, item, tenant_id, purpose):
        boto_table = self.get_table(table_name)
        data = item._data
        assert type(data) == dict
        self._check_for_meta(data, boto_table, operation='delete')
        item.delete()

    def wait_for_table_to_become_active(self, boto_table, table_name):
        while self.get_table_status(boto_table) != 'ACTIVE':
            logging.info('Waiting for table to finish creating')
            sleep(1)

    @table_op
    def create_table(self, table_name, **kwargs):
        """
        N.B. This is a synchronous operation. Not to be called from a
        web request. Use migrations framework instead for creating tables.
        """
        ret = BotoTable.create(self._get_table_name(table_name),
                               connection=self.connection,
                               **kwargs)

        self.wait_for_table_to_become_active(ret, table_name)

        return ret

    @table_op
    def get_table_status(self, boto_table):
        description = boto_table.describe()
        status = description['Table']['TableStatus']
        return status

    @table_op
    def drop_table(self, table_name):
        return self.connection.delete_table(self._get_table_name(table_name))

    def get_table(self, table_name, **kwargs):
        ret = BotoTable(self._get_table_name(table_name),
                        connection=self.connection,
                        **kwargs)
        # ret.clari_description = ret.describe() # Arg, props not correct unless you call this
        return ret

    @table_op
    def _change_throughput(self, new_throughput, boto_table, table_name):
        try:
            logging.warn('Attempting to increase throughput of ' + table_name)
            self.connection.update_table(table_name,
                                         provisioned_throughput=new_throughput)
        except Exception as e:
            # TODO: Fail gracefully here on Validation Exception.
            # TODO: Don't refresh table info after getting throughput exceeded
            exc_info = sys.exc_info()
            logging.error(
                'Could not increase table throughput will continue '
                'retrying. Error was: %s %s %s', exc_info[0], exc_info[1],
                exc_info[2])
        else:
            logging.info('Successfully increased throughput of ' + table_name)

    @table_op
    def list_tables(self):
        table_names = self.connection.list_tables()['TableNames']
        table_data = {}
        for table_name in table_names:
            try:
                description = self.connection.describe_table(
                    table_name)['Table']
            except Exception as e:
                if e.error_code.find('ResourceNotFoundException') >= 0:
                    logging.warn('Table ' + table_name +
                                 ' was just deleted, cannot describe.')
                else:
                    raise e
            else:
                table_data[table_name] = description
        return table_data

    @table_op
    def has_table(self, table_name):
        full_table_name = self._get_table_name(table_name)
        return full_table_name in self.list_tables()

    def _get_table_name(self, name):
        return 'clari_dynamo_' + ENV_NAME + '_' + name

    def _stop_local(self):
        if not self.is_remote:
            self.local_db.stop()

    def _check_tenant_id(self, item, tenant_id):
        assert item['tenant_id'] == tenant_id
        assert item['tenant_id'] == CRYPTO.decrypt(
            bytes(item['encrypted_tenant_id'], 'UTF-8'))

    def _handle_s3_backed_item(self, table, operation, parent, key, value):
        if operation == 'get':
            parent[key] = s3_kms.get(value["$s3_key"])
        elif operation == 'put':
            s3_key = s3_kms.put(table.table_name, key, value['$data'])
            value['$s3_key'] = s3_key.key
            del value['$data']
        elif operation == 'delete':
            s3_kms.delete(value["$s3_key"])

    def _handle_base64_item(self, operation, parent, key, value):
        if operation == 'get':
            pass
        elif operation == 'put':
            binary_data = Binary('')

            #  base64 comes in from API, so set directly (minor hack)
            binary_data.value = value['$data']

            assert len(value) == 2, \
                'only $data and $base64 should be set on binary item'

            parent[key] = binary_data

        elif operation == 'delete':
            pass

    def _check_for_meta(self, item, boto_table, operation):
        for key, value in item.iteritems():
            if type(value) == dict:
                # Read meta info
                if value.get("$s3"):
                    self._handle_s3_backed_item(boto_table, operation, item,
                                                key, value)
                if value.get('$base64'):
                    self._handle_base64_item(operation, item, key, value)
                if value.get('$data'):
                    item[key] = value.get('$data')
            if type(value) in (dict, list):
                self._check_for_meta(value, boto_table, operation)

    def _put_with_retries(self, boto_table, table_name, data, overwrite,
                          condition, vars, retry):
        boto_item = BotoItem(boto_table, data)

        # Use internal boto method to access to full AWS Dynamo capabilities
        final_data = boto_item.prepare_full()

        def try_function():
            expected = boto_item.build_expects(
            ) if overwrite is False else None
            return boto_table.connection.put_item(
                table_name,
                final_data,
                expected=expected,  # Don't overwrite
                condition_expression=condition,
                expression_attribute_values=vars)

        try:
            ret = self._attempt_throttled_operation(
                try_function,
                retry,
                boto_table,
                increased_throughput=get_double_writes(boto_table))
        except ConditionalCheckFailedException as e:
            raise self.ClariDynamoConditionCheckFailedException(
                str(e) + ' - ' + 'This could be due to a duplicate insertion.')
        return ret

    def _get_with_retries(self, boto_table, table_name, id_query, attributes,
                          retry):
        try_function = lambda: (boto_table.get_item(attributes=attributes,
                                                    **id_query))
        ret = self._attempt_throttled_operation(
            try_function,
            retry,
            boto_table,
            increased_throughput=get_double_reads(boto_table))
        return ret

    def _attempt_throttled_operation(self, try_function, retry_number,
                                     boto_table, increased_throughput):
        try:
            ret = try_function()
        except ProvisionedThroughputExceededException as e:
            if RETRY_ON_THROUGHPUT_EXCEEDED and retry_number < MAX_RETRY_COUNT:
                self._handle_throughput_exceeded(increased_throughput,
                                                 retry_number, boto_table)
                ret = self._attempt_throttled_operation(
                    try_function, retry_number + 1, boto_table,
                    increased_throughput)
            else:
                exc_info = sys.exc_info()
                raise exc_info[0], exc_info[1], exc_info[2]
        return ret

    def _get_secs_since_increase(self, boto_table):
        default_timestamp = 0.0
        description = boto_table.describe()
        timestamp = (description['Table']['ProvisionedThroughput'].get(
            'LastIncreaseDateTime', default_timestamp))
        if timestamp == default_timestamp:
            logging.warn('Unable to determine LastIncreaseDateTime for table')

        last_modified = datetime.fromtimestamp(timestamp)
        secs_since_increase = (datetime.now() - last_modified).total_seconds()
        return secs_since_increase

    def _handle_throughput_exceeded(self, new_throughput, retry, boto_table):
        logging.warn('ProvisionedThroughputExceededException retrying: ' +
                     str(retry))
        if retry == 0:
            # Only increase throughput on first retry for this request.
            # assert False
            # TODO: Create our own last_increase_time in meta unless AWS fixes
            # their ProvisionedThroughputDescription response.
            # TODO: See if throughput increased.
            secs_since_increase = self._get_secs_since_increase(boto_table)
            if secs_since_increase > 5:
                if self.get_table_status(boto_table) != 'UPDATING':
                    # Avoid piling on throughput from several requests
                    self._change_throughput(new_throughput, boto_table,
                                            boto_table.table_name)

        self._exponential_splay(retry)

    def _exponential_splay(self, retry):
        if IS_TEST:
            sleep_coeff = 0
        else:
            sleep_coeff = 1

        # random => ! herd
        # Max: 2 ** 4 = 16 seconds
        time_to_sleep = sleep_coeff * 2**retry * random.random()
        logging.info('sleeping for %f seconds' % time_to_sleep)
        time.sleep(time_to_sleep)

    def _add_mandatory_attributes(self, attributes):
        if not attributes:
            return
        for attr in MANDATORY_ATTRIBUTES:
            if attr not in attributes:
                attributes.append(attr)

    def _hide_mandatory_attributes(self, item, orig_attributes):
        if not orig_attributes:
            return
        for attr in MANDATORY_ATTRIBUTES:
            if attr in item and attr not in orig_attributes:
                del item[attr]

    def _hide_internal_fields(self, item):
        if ENCRYPTED_TENANT_ID_NAME in item:
            del item[ENCRYPTED_TENANT_ID_NAME]

    class AuthException(Exception):
        pass

    class ClariDynamoConditionCheckFailedException(Exception):
        pass
# host = 'dynamodb.%s.amazonaws.com' % region
# ddbc = DynamoDBConnection(is_secure=False, region=region, host=host)
DynamoDBConnection.DefaultRegionName = region
ddbc = DynamoDBConnection()

# 1. Read and copy the target table to be copied
table_struct = None
try:
    logs = Table(src_table, connection=ddbc)
    table_struct = logs.describe()
except JSONResponseError:
    print "Table %s does not exist" % src_table
    sys.exit(1)

print '*** Reading key schema from %s table' % src_table
src = ddbc.describe_table(src_table)['Table']
hash_key = ''
range_key = ''
for schema in src['KeySchema']:
    attr_name = schema['AttributeName']
    key_type = schema['KeyType']
    if key_type == 'HASH':
        hash_key = attr_name
    elif key_type == 'RANGE':
        range_key = attr_name

# 2. Create the new table
table_struct = None
try:
    new_logs = Table(dst_table,
                     connection=ddbc,
Exemplo n.º 15
0
class DynamoDBv2Layer1Test(unittest.TestCase):
    dynamodb = True

    def setUp(self):
        self.dynamodb = DynamoDBConnection()
        self.table_name = 'test-%d' % int(time.time())
        self.hash_key_name = 'username'
        self.hash_key_type = 'S'
        self.range_key_name = 'date_joined'
        self.range_key_type = 'N'
        self.read_units = 5
        self.write_units = 5
        self.attributes = [
            {
                'AttributeName': self.hash_key_name,
                'AttributeType': self.hash_key_type,
            },
            {
                'AttributeName': self.range_key_name,
                'AttributeType': self.range_key_type,
            }
        ]
        self.schema = [
            {
                'AttributeName': self.hash_key_name,
                'KeyType': 'HASH',
            },
            {
                'AttributeName': self.range_key_name,
                'KeyType': 'RANGE',
            },
        ]
        self.provisioned_throughput = {
            'ReadCapacityUnits': self.read_units,
            'WriteCapacityUnits': self.write_units,
        }
        self.lsi = [
            {
                'IndexName': 'MostRecentIndex',
                'KeySchema': [
                    {
                        'AttributeName': self.hash_key_name,
                        'KeyType': 'HASH',
                    },
                    {
                        'AttributeName': self.range_key_name,
                        'KeyType': 'RANGE',
                    },
                ],
                'Projection': {
                    'ProjectionType': 'KEYS_ONLY',
                }
            }
        ]

    def create_table(self, table_name, attributes, schema,
                     provisioned_throughput, lsi=None, wait=True):
        # Note: This is a slightly different ordering that makes less sense.
        result = self.dynamodb.create_table(
            attributes,
            table_name,
            schema,
            provisioned_throughput,
            local_secondary_indexes=lsi
        )
        self.addCleanup(self.dynamodb.delete_table, table_name)
        if wait:
            while True:
                description = self.dynamodb.describe_table(table_name)
                if description['Table']['TableStatus'].lower() == 'active':
                    return result
                else:
                    time.sleep(5)
        else:
            return result

    def test_integrated(self):
        result = self.create_table(
            self.table_name,
            self.attributes,
            self.schema,
            self.provisioned_throughput,
            self.lsi
        )
        self.assertEqual(
            result['TableDescription']['TableName'],
            self.table_name
        )

        description = self.dynamodb.describe_table(self.table_name)
        self.assertEqual(description['Table']['ItemCount'], 0)

        # Create some records.
        record_1_data = {
            'username': {'S': 'johndoe'},
            'first_name': {'S': 'John'},
            'last_name': {'S': 'Doe'},
            'date_joined': {'N': '1366056668'},
            'friend_count': {'N': '3'},
            'friends': {'SS': ['alice', 'bob', 'jane']},
        }
        r1_result = self.dynamodb.put_item(self.table_name, record_1_data)

        # Get the data.
        record_1 = self.dynamodb.get_item(self.table_name, key={
            'username': {'S': 'johndoe'},
            'date_joined': {'N': '1366056668'},
        }, consistent_read=True)
        self.assertEqual(record_1['Item']['username']['S'], 'johndoe')
        self.assertEqual(record_1['Item']['first_name']['S'], 'John')
        self.assertEqual(record_1['Item']['friends']['SS'], [
            'alice', 'bob', 'jane'
        ])

        # Now in a batch.
        self.dynamodb.batch_write_item({
            self.table_name: [
                {
                    'PutRequest': {
                        'Item': {
                            'username': {'S': 'jane'},
                            'first_name': {'S': 'Jane'},
                            'last_name': {'S': 'Doe'},
                            'date_joined': {'N': '1366056789'},
                            'friend_count': {'N': '1'},
                            'friends': {'SS': ['johndoe']},
                        },
                    },
                },
            ]
        })

        # Now a query.
        lsi_results = self.dynamodb.query(
            self.table_name,
            index_name='MostRecentIndex',
            key_conditions={
                'username': {
                    'AttributeValueList': [
                        {'S': 'johndoe'},
                    ],
                    'ComparisonOperator': 'EQ',
                },
            },
            consistent_read=True
        )
        self.assertEqual(lsi_results['Count'], 1)

        results = self.dynamodb.query(self.table_name, key_conditions={
            'username': {
                'AttributeValueList': [
                    {'S': 'jane'},
                ],
                'ComparisonOperator': 'EQ',
            },
            'date_joined': {
                'AttributeValueList': [
                    {'N': '1366050000'}
                ],
                'ComparisonOperator': 'GT',
            }
        }, consistent_read=True)
        self.assertEqual(results['Count'], 1)

        # Now a scan.
        results = self.dynamodb.scan(self.table_name)
        self.assertEqual(results['Count'], 2)
        s_items = sorted([res['username']['S'] for res in results['Items']])
        self.assertEqual(s_items, ['jane', 'johndoe'])

        self.dynamodb.delete_item(self.table_name, key={
            'username': {'S': 'johndoe'},
            'date_joined': {'N': '1366056668'},
        })

        results = self.dynamodb.scan(self.table_name)
        self.assertEqual(results['Count'], 1)

        # Parallel scan (minus client-side threading).
        self.dynamodb.batch_write_item({
            self.table_name: [
                {
                    'PutRequest': {
                        'Item': {
                            'username': {'S': 'johndoe'},
                            'first_name': {'S': 'Johann'},
                            'last_name': {'S': 'Does'},
                            'date_joined': {'N': '1366058000'},
                            'friend_count': {'N': '1'},
                            'friends': {'SS': ['jane']},
                        },
                    },
                    'PutRequest': {
                        'Item': {
                            'username': {'S': 'alice'},
                            'first_name': {'S': 'Alice'},
                            'last_name': {'S': 'Expert'},
                            'date_joined': {'N': '1366056800'},
                            'friend_count': {'N': '2'},
                            'friends': {'SS': ['johndoe', 'jane']},
                        },
                    },
                },
            ]
        })
        time.sleep(20)
        results = self.dynamodb.scan(self.table_name, segment=0, total_segments=2)
        self.assertTrue(results['Count'] in [1, 2])
        results = self.dynamodb.scan(self.table_name, segment=1, total_segments=2)
        self.assertTrue(results['Count'] in [1, 2])

    def test_without_range_key(self):
        result = self.create_table(
            self.table_name,
            [
                {
                    'AttributeName': self.hash_key_name,
                    'AttributeType': self.hash_key_type,
                },
            ],
            [
                {
                    'AttributeName': self.hash_key_name,
                    'KeyType': 'HASH',
                },
            ],
            self.provisioned_throughput
        )
        self.assertEqual(
            result['TableDescription']['TableName'],
            self.table_name
        )

        description = self.dynamodb.describe_table(self.table_name)
        self.assertEqual(description['Table']['ItemCount'], 0)

        # Create some records.
        record_1_data = {
            'username': {'S': 'johndoe'},
            'first_name': {'S': 'John'},
            'last_name': {'S': 'Doe'},
            'date_joined': {'N': '1366056668'},
            'friend_count': {'N': '3'},
            'friends': {'SS': ['alice', 'bob', 'jane']},
        }
        r1_result = self.dynamodb.put_item(self.table_name, record_1_data)

        # Now try a range-less get.
        johndoe = self.dynamodb.get_item(self.table_name, key={
            'username': {'S': 'johndoe'},
        }, consistent_read=True)
        self.assertEqual(johndoe['Item']['username']['S'], 'johndoe')
        self.assertEqual(johndoe['Item']['first_name']['S'], 'John')
        self.assertEqual(johndoe['Item']['friends']['SS'], [
            'alice', 'bob', 'jane'
        ])

    def test_throughput_exceeded_regression(self):
        tiny_tablename = 'TinyThroughput'
        tiny = self.create_table(
            tiny_tablename,
            self.attributes,
            self.schema,
            {
                'ReadCapacityUnits': 1,
                'WriteCapacityUnits': 1,
            }
        )

        self.dynamodb.put_item(tiny_tablename, {
            'username': {'S': 'johndoe'},
            'first_name': {'S': 'John'},
            'last_name': {'S': 'Doe'},
            'date_joined': {'N': '1366056668'},
        })
        self.dynamodb.put_item(tiny_tablename, {
            'username': {'S': 'jane'},
            'first_name': {'S': 'Jane'},
            'last_name': {'S': 'Doe'},
            'date_joined': {'N': '1366056669'},
        })
        self.dynamodb.put_item(tiny_tablename, {
            'username': {'S': 'alice'},
            'first_name': {'S': 'Alice'},
            'last_name': {'S': 'Expert'},
            'date_joined': {'N': '1366057000'},
        })
        time.sleep(20)

        for i in range(100):
            # This would cause an exception due to a non-existant instance variable.
            self.dynamodb.scan(tiny_tablename)
Exemplo n.º 16
0
# Author Balbir Singh <*****@*****.**>
# Date 13th February 2015

import simplejson
from boto.dynamodb2.layer1 import DynamoDBConnection


# Connect to Dynamo DB, by default it will connect us-east-1 as mentioned in .boto config
ddb2_conn = DynamoDBConnection(profile_name="dhap-test")

# Getting the list of the table
table = ddb2_conn.list_tables()

# Going over each and every table in loop
for t in table['TableNames']:
    table_data_json = ddb2_conn.describe_table(t)
    table_data_json_dumps = simplejson.dumps(table_data_json)
    print table_data_json_dumps
    print "="*90
Exemplo n.º 17
0
class DynamoDBv2Layer1Test(unittest.TestCase):
    dynamodb = True

    def setUp(self):
        self.dynamodb = DynamoDBConnection()
        self.table_name = 'test-%d' % int(time.time())
        self.hash_key_name = 'username'
        self.hash_key_type = 'S'
        self.range_key_name = 'date_joined'
        self.range_key_type = 'N'
        self.read_units = 5
        self.write_units = 5
        self.attributes = [
            {
                'AttributeName': self.hash_key_name,
                'AttributeType': self.hash_key_type,
            },
            {
                'AttributeName': self.range_key_name,
                'AttributeType': self.range_key_type,
            }
        ]
        self.schema = [
            {
                'AttributeName': self.hash_key_name,
                'KeyType': 'HASH',
            },
            {
                'AttributeName': self.range_key_name,
                'KeyType': 'RANGE',
            },
        ]
        self.provisioned_throughput = {
            'ReadCapacityUnits': self.read_units,
            'WriteCapacityUnits': self.write_units,
        }
        self.lsi = [
            {
                'IndexName': 'MostRecentIndex',
                'KeySchema': [
                    {
                        'AttributeName': self.hash_key_name,
                        'KeyType': 'HASH',
                    },
                    {
                        'AttributeName': self.range_key_name,
                        'KeyType': 'RANGE',
                    },
                ],
                'Projection': {
                    'ProjectionType': 'KEYS_ONLY',
                }
            }
        ]

    def create_table(self, table_name, attributes, schema,
                     provisioned_throughput, lsi=None, wait=True):
        # Note: This is a slightly different ordering that makes less sense.
        result = self.dynamodb.create_table(
            attributes,
            table_name,
            schema,
            provisioned_throughput,
            local_secondary_indexes=lsi
        )
        self.addCleanup(self.dynamodb.delete_table, table_name)
        if wait:
            while True:
                description = self.dynamodb.describe_table(table_name)
                if description['Table']['TableStatus'].lower() == 'active':
                    return result
                else:
                    time.sleep(5)
        else:
            return result

    def test_integrated(self):
        result = self.create_table(
            self.table_name,
            self.attributes,
            self.schema,
            self.provisioned_throughput,
            self.lsi
        )
        self.assertEqual(
            result['TableDescription']['TableName'],
            self.table_name
        )

        description = self.dynamodb.describe_table(self.table_name)
        self.assertEqual(description['Table']['ItemCount'], 0)

        # Create some records.
        record_1_data = {
            'username': {'S': 'johndoe'},
            'first_name': {'S': 'John'},
            'last_name': {'S': 'Doe'},
            'date_joined': {'N': '1366056668'},
            'friend_count': {'N': '3'},
            'friends': {'SS': ['alice', 'bob', 'jane']},
        }
        r1_result = self.dynamodb.put_item(self.table_name, record_1_data)

        # Get the data.
        record_1 = self.dynamodb.get_item(self.table_name, key={
            'username': {'S': 'johndoe'},
            'date_joined': {'N': '1366056668'},
        }, consistent_read=True)
        self.assertEqual(record_1['Item']['username']['S'], 'johndoe')
        self.assertEqual(record_1['Item']['first_name']['S'], 'John')
        self.assertEqual(record_1['Item']['friends']['SS'], [
            'alice', 'bob', 'jane'
        ])

        # Now in a batch.
        self.dynamodb.batch_write_item({
            self.table_name: [
                {
                    'PutRequest': {
                        'Item': {
                            'username': {'S': 'jane'},
                            'first_name': {'S': 'Jane'},
                            'last_name': {'S': 'Doe'},
                            'date_joined': {'N': '1366056789'},
                            'friend_count': {'N': '1'},
                            'friends': {'SS': ['johndoe']},
                        },
                    },
                },
            ]
        })

        # Now a query.
        lsi_results = self.dynamodb.query(
            self.table_name,
            index_name='MostRecentIndex',
            key_conditions={
                'username': {
                    'AttributeValueList': [
                        {'S': 'johndoe'},
                    ],
                    'ComparisonOperator': 'EQ',
                },
            },
            consistent_read=True
        )
        self.assertEqual(lsi_results['Count'], 1)

        results = self.dynamodb.query(self.table_name, key_conditions={
            'username': {
                'AttributeValueList': [
                    {'S': 'jane'},
                ],
                'ComparisonOperator': 'EQ',
            },
            'date_joined': {
                'AttributeValueList': [
                    {'N': '1366050000'}
                ],
                'ComparisonOperator': 'GT',
            }
        }, consistent_read=True)
        self.assertEqual(results['Count'], 1)

        # Now a scan.
        results = self.dynamodb.scan(self.table_name)
        self.assertEqual(results['Count'], 2)
        s_items = sorted([res['username']['S'] for res in results['Items']])
        self.assertEqual(s_items, ['jane', 'johndoe'])

        self.dynamodb.delete_item(self.table_name, key={
            'username': {'S': 'johndoe'},
            'date_joined': {'N': '1366056668'},
        })

        results = self.dynamodb.scan(self.table_name)
        self.assertEqual(results['Count'], 1)

        # Parallel scan (minus client-side threading).
        self.dynamodb.batch_write_item({
            self.table_name: [
                {
                    'PutRequest': {
                        'Item': {
                            'username': {'S': 'johndoe'},
                            'first_name': {'S': 'Johann'},
                            'last_name': {'S': 'Does'},
                            'date_joined': {'N': '1366058000'},
                            'friend_count': {'N': '1'},
                            'friends': {'SS': ['jane']},
                        },
                    },
                    'PutRequest': {
                        'Item': {
                            'username': {'S': 'alice'},
                            'first_name': {'S': 'Alice'},
                            'last_name': {'S': 'Expert'},
                            'date_joined': {'N': '1366056800'},
                            'friend_count': {'N': '2'},
                            'friends': {'SS': ['johndoe', 'jane']},
                        },
                    },
                },
            ]
        })
        time.sleep(20)
        results = self.dynamodb.scan(self.table_name, segment=0, total_segments=2)
        self.assertTrue(results['Count'] in [1, 2])
        results = self.dynamodb.scan(self.table_name, segment=1, total_segments=2)
        self.assertTrue(results['Count'] in [1, 2])

    def test_without_range_key(self):
        result = self.create_table(
            self.table_name,
            [
                {
                    'AttributeName': self.hash_key_name,
                    'AttributeType': self.hash_key_type,
                },
            ],
            [
                {
                    'AttributeName': self.hash_key_name,
                    'KeyType': 'HASH',
                },
            ],
            self.provisioned_throughput
        )
        self.assertEqual(
            result['TableDescription']['TableName'],
            self.table_name
        )

        description = self.dynamodb.describe_table(self.table_name)
        self.assertEqual(description['Table']['ItemCount'], 0)

        # Create some records.
        record_1_data = {
            'username': {'S': 'johndoe'},
            'first_name': {'S': 'John'},
            'last_name': {'S': 'Doe'},
            'date_joined': {'N': '1366056668'},
            'friend_count': {'N': '3'},
            'friends': {'SS': ['alice', 'bob', 'jane']},
        }
        r1_result = self.dynamodb.put_item(self.table_name, record_1_data)

        # Now try a range-less get.
        johndoe = self.dynamodb.get_item(self.table_name, key={
            'username': {'S': 'johndoe'},
        }, consistent_read=True)
        self.assertEqual(johndoe['Item']['username']['S'], 'johndoe')
        self.assertEqual(johndoe['Item']['first_name']['S'], 'John')
        self.assertEqual(johndoe['Item']['friends']['SS'], [
            'alice', 'bob', 'jane'
        ])

    def test_throughput_exceeded_regression(self):
        tiny_tablename = 'TinyThroughput'
        tiny = self.create_table(
            tiny_tablename,
            self.attributes,
            self.schema,
            {
                'ReadCapacityUnits': 1,
                'WriteCapacityUnits': 1,
            }
        )

        self.dynamodb.put_item(tiny_tablename, {
            'username': {'S': 'johndoe'},
            'first_name': {'S': 'John'},
            'last_name': {'S': 'Doe'},
            'date_joined': {'N': '1366056668'},
        })
        self.dynamodb.put_item(tiny_tablename, {
            'username': {'S': 'jane'},
            'first_name': {'S': 'Jane'},
            'last_name': {'S': 'Doe'},
            'date_joined': {'N': '1366056669'},
        })
        self.dynamodb.put_item(tiny_tablename, {
            'username': {'S': 'alice'},
            'first_name': {'S': 'Alice'},
            'last_name': {'S': 'Expert'},
            'date_joined': {'N': '1366057000'},
        })
        time.sleep(20)

        for i in range(100):
            # This would cause an exception due to a non-existant instance variable.
            self.dynamodb.scan(tiny_tablename)

    def test_recursive(self):
        result = self.create_table(
            self.table_name,
            self.attributes,
            self.schema,
            self.provisioned_throughput,
            self.lsi
        )
        self.assertEqual(
            result['TableDescription']['TableName'],
            self.table_name
        )

        description = self.dynamodb.describe_table(self.table_name)
        self.assertEqual(description['Table']['ItemCount'], 0)

        # Create some records with one being a recursive shape.
        record_1_data = {
            'username': {'S': 'johndoe'},
            'first_name': {'S': 'John'},
            'last_name': {'S': 'Doe'},
            'date_joined': {'N': '1366056668'},
            'friend_count': {'N': '3'},
            'friend_data': {'M': {'username': {'S': 'alice'},
                                  'friend_count': {'N': '4'}}}
        }
        r1_result = self.dynamodb.put_item(self.table_name, record_1_data)

        # Get the data.
        record_1 = self.dynamodb.get_item(self.table_name, key={
            'username': {'S': 'johndoe'},
            'date_joined': {'N': '1366056668'},
        }, consistent_read=True)
        self.assertEqual(record_1['Item']['username']['S'], 'johndoe')
        self.assertEqual(record_1['Item']['first_name']['S'], 'John')
        recursive_data = record_1['Item']['friend_data']['M']
        self.assertEqual(recursive_data['username']['S'], 'alice')
        self.assertEqual(recursive_data['friend_count']['N'], '4')
Exemplo n.º 18
0
class Table(object):
    """
    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.
    """
    max_batch_get = 100

    def __init__(self, table_name, schema=None, throughput=None, indexes=None,
                 global_indexes=None, connection=None):
        """
        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',
            ... ))

        """
        self.table_name = table_name
        self.connection = connection
        self.throughput = {
            'read': 5,
            'write': 5,
        }
        self.schema = schema
        self.indexes = indexes
        self.global_indexes = global_indexes

        if self.connection is None:
            self.connection = DynamoDBConnection()

        if throughput is not None:
            self.throughput = throughput

        self._dynamizer = Dynamizer()

    @classmethod
    def create(cls, table_name, schema, throughput=None, indexes=None,
               global_indexes=None, connection=None):
        """
        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 & indexes 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=[
            ...         RangeKey('date_joined')
            ... ]), global_indexes=[
            ...     GlobalAllIndex('UsersByZipcode', parts=[
            ...         HashKey('zipcode'),
            ...         RangeKey('username'),
            ...     ],
            ...     throughput={
            ...       'read':10,
            ...       'write':10,
            ...     }),
            ... ])

        """
        table = cls(table_name=table_name, connection=connection)
        table.schema = schema

        if throughput is not None:
            table.throughput = throughput

        if indexes is not None:
            table.indexes = indexes

        if global_indexes is not None:
            table.global_indexes = global_indexes

        # Prep the schema.
        raw_schema = []
        attr_defs = []
        seen_attrs = set()

        for field in table.schema:
            raw_schema.append(field.schema())
            # Build the attributes off what we know.
            seen_attrs.add(field.name)
            attr_defs.append(field.definition())

        raw_throughput = {
            'ReadCapacityUnits': int(table.throughput['read']),
            'WriteCapacityUnits': int(table.throughput['write']),
        }
        kwargs = {}

        kwarg_map = {
            'indexes': 'local_secondary_indexes',
            'global_indexes': 'global_secondary_indexes',
        }
        for index_attr in ('indexes', 'global_indexes'):
            table_indexes = getattr(table, index_attr)
            if table_indexes:
                raw_indexes = []
                for index_field in table_indexes:
                    raw_indexes.append(index_field.schema())
                    # Make sure all attributes specified in the indexes are
                    # added to the definition
                    for field in index_field.parts:
                        if field.name not in seen_attrs:
                            seen_attrs.add(field.name)
                            attr_defs.append(field.definition())

                kwargs[kwarg_map[index_attr]] = raw_indexes

        table.connection.create_table(
            table_name=table.table_name,
            attribute_definitions=attr_defs,
            key_schema=raw_schema,
            provisioned_throughput=raw_throughput,
            **kwargs
        )
        return table

    def _introspect_schema(self, raw_schema, raw_attributes=None):
        """
        Given a raw schema structure back from a DynamoDB response, parse
        out & build the high-level Python objects that represent them.
        """
        schema = []
        sane_attributes = {}

        if raw_attributes:
            for field in raw_attributes:
                sane_attributes[field['AttributeName']] = field['AttributeType']

        for field in raw_schema:
            data_type = sane_attributes.get(field['AttributeName'], STRING)

            if field['KeyType'] == 'HASH':
                schema.append(
                    HashKey(field['AttributeName'], data_type=data_type)
                )
            elif field['KeyType'] == 'RANGE':
                schema.append(
                    RangeKey(field['AttributeName'], data_type=data_type)
                )
            else:
                raise exceptions.UnknownSchemaFieldError(
                    "%s was seen, but is unknown. Please report this at "
                    "https://github.com/boto/boto/issues." % field['KeyType']
                )

        return schema

    def _introspect_indexes(self, raw_indexes):
        """
        Given a raw index structure back from a DynamoDB response, parse
        out & build the high-level Python objects that represent them.
        """
        indexes = []

        for field in raw_indexes:
            index_klass = AllIndex
            kwargs = {
                'parts': []
            }

            if field['Projection']['ProjectionType'] == 'ALL':
                index_klass = AllIndex
            elif field['Projection']['ProjectionType'] == 'KEYS_ONLY':
                index_klass = KeysOnlyIndex
            elif field['Projection']['ProjectionType'] == 'INCLUDE':
                index_klass = IncludeIndex
                kwargs['includes'] = field['Projection']['NonKeyAttributes']
            else:
                raise exceptions.UnknownIndexFieldError(
                    "%s was seen, but is unknown. Please report this at "
                    "https://github.com/boto/boto/issues." % \
                    field['Projection']['ProjectionType']
                )

            name = field['IndexName']
            kwargs['parts'] = self._introspect_schema(field['KeySchema'], None)
            indexes.append(index_klass(name, **kwargs))

        return indexes

    def describe(self):
        """
        Describes the current structure of the table in DynamoDB.

        This information will be used to update the ``schema``, ``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 datastructure 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

        """
        result = self.connection.describe_table(self.table_name)

        # Blindly update throughput, since what's on DynamoDB's end is likely
        # more correct.
        raw_throughput = result['Table']['ProvisionedThroughput']
        self.throughput['read'] = int(raw_throughput['ReadCapacityUnits'])
        self.throughput['write'] = int(raw_throughput['WriteCapacityUnits'])

        if not self.schema:
            # Since we have the data, build the schema.
            raw_schema = result['Table'].get('KeySchema', [])
            raw_attributes = result['Table'].get('AttributeDefinitions', [])
            self.schema = self._introspect_schema(raw_schema, raw_attributes)

        if not self.indexes:
            # Build the index information as well.
            raw_indexes = result['Table'].get('LocalSecondaryIndexes', [])
            self.indexes = self._introspect_indexes(raw_indexes)

        # This is leaky.
        return result

    def update(self, throughput, global_indexes=None):
        """
        Updates table attributes in DynamoDB.

        Currently, the only thing you can modify about a table after it has
        been created is the throughput.

        Requires 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.

        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

        """
        self.throughput = throughput
        data = {
            'ReadCapacityUnits': int(self.throughput['read']),
            'WriteCapacityUnits': int(self.throughput['write']),
        }
        gsi_data = None

        if global_indexes:
            gsi_data = []

            for gsi_name, gsi_throughput in global_indexes.items():
                gsi_data.append({
                    "Update": {
                        "IndexName": gsi_name,
                        "ProvisionedThroughput": {
                            "ReadCapacityUnits": int(gsi_throughput['read']),
                            "WriteCapacityUnits": int(gsi_throughput['write']),
                        },
                    },
                })

        self.connection.update_table(
            self.table_name,
            provisioned_throughput=data,
            global_secondary_index_updates=gsi_data
        )
        return True

    def delete(self):
        """
        Deletes a table in DynamoDB.

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

        Returns ``True`` on success.

        Example::

            >>> users.delete()
            True

        """
        self.connection.delete_table(self.table_name)
        return True

    def _encode_keys(self, keys):
        """
        Given a flat Python dictionary of keys/values, converts it into the
        nested dictionary DynamoDB expects.

        Converts::

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

        ...to...::

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

        """
        raw_key = {}

        for key, value in keys.items():
            raw_key[key] = self._dynamizer.encode(value)

        return raw_key

    def get_item(self, consistent=False, attributes=None, **kwargs):
        """
        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.

        Example::

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

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

            # A consistent read (assuming the data might have just changed).
            >>> john = users.get_item(username='******', 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'

        """
        raw_key = self._encode_keys(kwargs)
        item_data = self.connection.get_item(
            self.table_name,
            raw_key,
            attributes_to_get=attributes,
            consistent_read=consistent
        )
        if 'Item' not in item_data:
            raise exceptions.ItemNotFound("Item %s couldn't be found." % kwargs)
        item = Item(self)
        item.load(item_data)
        return item

    def has_item(self, **kwargs):
        """
        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='******')
            True

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

        """
        try:
            self.get_item(**kwargs)
        except (JSONResponseError, exceptions.ItemNotFound):
            return False

        return True

    def lookup(self, *args, **kwargs):
        """
        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')

        """
        if not self.schema:
            self.describe()
        for x, arg in enumerate(args):
            kwargs[self.schema[x].name] = arg
        ret = self.get_item(**kwargs)
        if not ret.keys():
            return None
        return ret

    def new_item(self, *args):
        """
        Returns a new, blank item

        This is mostly for consistency with boto.dynamodb
        """
        if not self.schema:
            self.describe()
        data = {}
        for x, arg in enumerate(args):
            data[self.schema[x].name] = arg
        return Item(self, data=data)

    def put_item(self, data, overwrite=False):
        """
        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': '******',
            ...     'first_name': 'Jane',
            ...     'last_name': 'Doe',
            ...     'date_joined': 126478915,
            ... })
            True

        """
        item = Item(self, data=data)
        return item.save(overwrite=overwrite)

    def _put_item(self, item_data, expects=None):
        """
        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.
        """
        kwargs = {}

        if expects is not None:
            kwargs['expected'] = expects

        self.connection.put_item(self.table_name, item_data, **kwargs)
        return True

    def _update_item(self, key, item_data, expects=None):
        """
        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.
        """
        raw_key = self._encode_keys(key)
        kwargs = {}

        if expects is not None:
            kwargs['expected'] = expects

        self.connection.update_item(self.table_name, raw_key, item_data, **kwargs)
        return True

    def delete_item(self, **kwargs):
        """
        Deletes an item in DynamoDB.

        **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.

        Returns ``True`` on success.

        Example::

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

            # A complex hash+range key.
            >>> users.delete_item(username='******', 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

        """
        raw_key = self._encode_keys(kwargs)
        self.connection.delete_item(self.table_name, raw_key)
        return True

    def get_key_fields(self):
        """
        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']

        """
        if not self.schema:
            # We don't know the structure of the table. Get a description to
            # populate the schema.
            self.describe()

        return [field.name for field in self.schema]

    def batch_write(self):
        """
        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': '******',
            ...         'first_name': 'John',
            ...         'last_name': 'Doe',
            ...         'owner': 1,
            ...     })
            ...     # Nothing across the wire yet.
            ...     batch.delete_item(username='******')
            ...     # Still no requests sent.
            ...     batch.put_item(data={
            ...         'username': '******',
            ...         'first_name': 'Jane',
            ...         'last_name': 'Doe',
            ...         'date_joined': 127436192,
            ...     })
            ...     # Nothing yet, but once we leave the context, the
            ...     # put/deletes will be sent.

        """
        # PHENOMENAL COSMIC DOCS!!! itty-bitty code.
        return BatchTable(self)

    def _build_filters(self, filter_kwargs, using=QUERY_OPERATORS):
        """
        An internal method for taking query/scan-style ``**kwargs`` & turning
        them into the raw structure DynamoDB expects for filtering.
        """
        filters = {}

        for field_and_op, value in filter_kwargs.items():
            field_bits = field_and_op.split('__')
            fieldname = '__'.join(field_bits[:-1])

            try:
                op = using[field_bits[-1]]
            except KeyError:
                raise exceptions.UnknownFilterTypeError(
                    "Operator '%s' from '%s' is not recognized." % (
                        field_bits[-1],
                        field_and_op
                    )
                )

            lookup = {
                'AttributeValueList': [],
                'ComparisonOperator': op,
            }

            # Special-case the ``NULL/NOT_NULL`` case.
            if field_bits[-1] == 'null':
                del lookup['AttributeValueList']

                if value is False:
                    lookup['ComparisonOperator'] = 'NOT_NULL'
                else:
                    lookup['ComparisonOperator'] = 'NULL'
            # Special-case the ``BETWEEN`` case.
            elif field_bits[-1] == 'between':
                if len(value) == 2 and isinstance(value, (list, tuple)):
                    lookup['AttributeValueList'].append(
                        self._dynamizer.encode(value[0])
                    )
                    lookup['AttributeValueList'].append(
                        self._dynamizer.encode(value[1])
                    )
            # Special-case the ``IN`` case
            elif field_bits[-1] == 'in':
                for val in value:
                    lookup['AttributeValueList'].append(self._dynamizer.encode(val))
            else:
                # Fix up the value for encoding, because it was built to only work
                # with ``set``s.
                if isinstance(value, (list, tuple)):
                    value = set(value)
                lookup['AttributeValueList'].append(
                    self._dynamizer.encode(value)
                )

            # Finally, insert it into the filters.
            filters[fieldname] = lookup

        return filters

    def query(self, limit=None, index=None, reverse=False, consistent=False,
              attributes=None, max_page_size=None, **filter_kwargs):
        """
        **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``.
        """
        reverse = not reverse
        return self.query_2(limit=limit, index=index, reverse=reverse,
                            consistent=consistent, attributes=attributes,
                            max_page_size=max_page_size, **filter_kwargs)

    def query_2(self, limit=None, index=None, reverse=False,
                consistent=False, attributes=None, max_page_size=None,
                **filter_kwargs):
        """
        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.

        **Note** - You can not query against arbitrary fields within the data
        stored in DynamoDB.

        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 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)

        Returns a ``ResultSet``, 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'

        """
        if self.schema:
            if len(self.schema) == 1:
                if len(filter_kwargs) <= 1:
                    if not self.global_indexes or not len(self.global_indexes):
                        # If the schema only has one field, there's <= 1 filter
                        # param & no Global Secondary Indexes, this is user
                        # error. Bail early.
                        raise exceptions.QueryError(
                            "You must specify more than one key to filter on."
                        )

        if attributes is not None:
            select = 'SPECIFIC_ATTRIBUTES'
        else:
            select = None

        results = ResultSet(
            max_page_size=max_page_size
        )
        kwargs = filter_kwargs.copy()
        kwargs.update({
            'limit': limit,
            'index': index,
            'reverse': reverse,
            'consistent': consistent,
            'select': select,
            'attributes_to_get': attributes,
        })
        results.to_call(self._query, **kwargs)
        return results

    def query_count(self, index=None, consistent=False, **filter_kwargs):
        """
        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.

        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 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)

        Returns an integer which represents the exact amount of matched
        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

        """
        key_conditions = self._build_filters(
            filter_kwargs,
            using=QUERY_OPERATORS
        )

        raw_results = self.connection.query(
            self.table_name,
            index_name=index,
            consistent_read=consistent,
            select='COUNT',
            key_conditions=key_conditions,
        )
        return int(raw_results.get('Count', 0))

    def _query(self, limit=None, index=None, reverse=False, consistent=False,
               exclusive_start_key=None, select=None, attributes_to_get=None,
               **filter_kwargs):
        """
        The internal method that performs the actual queries. Used extensively
        by ``ResultSet`` to perform each (paginated) request.
        """
        kwargs = {
            'limit': limit,
            'index_name': index,
            'consistent_read': consistent,
            'select': select,
            'attributes_to_get': attributes_to_get,
        }

        if reverse:
            kwargs['scan_index_forward'] = False

        if exclusive_start_key:
            kwargs['exclusive_start_key'] = {}

            for key, value in exclusive_start_key.items():
                kwargs['exclusive_start_key'][key] = \
                    self._dynamizer.encode(value)

        # Convert the filters into something we can actually use.
        kwargs['key_conditions'] = self._build_filters(
            filter_kwargs,
            using=QUERY_OPERATORS
        )

        raw_results = self.connection.query(
            self.table_name,
            **kwargs
        )
        results = []
        last_key = None

        for raw_item in raw_results.get('Items', []):
            item = Item(self)
            item.load({
                'Item': raw_item,
            })
            results.append(item)

        if raw_results.get('LastEvaluatedKey', None):
            last_key = {}

            for key, value in raw_results['LastEvaluatedKey'].items():
                last_key[key] = self._dynamizer.decode(value)

        return {
            'results': results,
            'last_key': last_key,
        }

    def scan(self, limit=None, segment=None, total_segments=None,
             max_page_size=None, attributes=None, **filter_kwargs):
        """
        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.

        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'

        """
        results = ResultSet(
            max_page_size=max_page_size
        )
        kwargs = filter_kwargs.copy()
        kwargs.update({
            'limit': limit,
            'segment': segment,
            'total_segments': total_segments,
            'attributes': attributes,
        })
        results.to_call(self._scan, **kwargs)
        return results

    def _scan(self, limit=None, exclusive_start_key=None, segment=None,
              total_segments=None, attributes=None, **filter_kwargs):
        """
        The internal method that performs the actual scan. Used extensively
        by ``ResultSet`` to perform each (paginated) request.
        """
        kwargs = {
            'limit': limit,
            'segment': segment,
            'total_segments': total_segments,
            'attributes_to_get': attributes,
        }

        if exclusive_start_key:
            kwargs['exclusive_start_key'] = {}

            for key, value in exclusive_start_key.items():
                kwargs['exclusive_start_key'][key] = \
                    self._dynamizer.encode(value)

        # Convert the filters into something we can actually use.
        kwargs['scan_filter'] = self._build_filters(
            filter_kwargs,
            using=FILTER_OPERATORS
        )

        raw_results = self.connection.scan(
            self.table_name,
            **kwargs
        )
        results = []
        last_key = None

        for raw_item in raw_results.get('Items', []):
            item = Item(self)
            item.load({
                'Item': raw_item,
            })
            results.append(item)

        if raw_results.get('LastEvaluatedKey', None):
            last_key = {}

            for key, value in raw_results['LastEvaluatedKey'].items():
                last_key[key] = self._dynamizer.decode(value)

        return {
            'results': results,
            'last_key': last_key,
        }

    def batch_get(self, keys, consistent=False):
        """
        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)

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

        Example::

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

        """
        # We pass the keys to the constructor instead, so it can maintain it's
        # own internal state as to what keys have been processed.
        results = BatchGetResultSet(keys=keys, max_batch_get=self.max_batch_get)
        results.to_call(self._batch_get, consistent=False)
        return results

    def _batch_get(self, keys, consistent=False):
        """
        The internal method that performs the actual batch get. Used extensively
        by ``BatchGetResultSet`` to perform each (paginated) request.
        """
        items = {
            self.table_name: {
                'Keys': [],
            },
        }

        if consistent:
            items[self.table_name]['ConsistentRead'] = True

        for key_data in keys:
            raw_key = {}

            for key, value in key_data.items():
                raw_key[key] = self._dynamizer.encode(value)

            items[self.table_name]['Keys'].append(raw_key)

        raw_results = self.connection.batch_get_item(request_items=items)
        results = []
        unprocessed_keys = []

        for raw_item in raw_results['Responses'].get(self.table_name, []):
            item = Item(self)
            item.load({
                'Item': raw_item,
            })
            results.append(item)

        raw_unproccessed = raw_results.get('UnprocessedKeys', {})

        for raw_key in raw_unproccessed.get('Keys', []):
            py_key = {}

            for key, value in raw_key.items():
                py_key[key] = self._dynamizer.decode(value)

            unprocessed_keys.append(py_key)

        return {
            'results': results,
            # NEVER return a ``last_key``. Just in-case any part of
            # ``ResultSet`` peeks through, since much of the
            # original underlying implementation is based on this key.
            'last_key': None,
            'unprocessed_keys': unprocessed_keys,
        }

    def count(self):
        """
        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

        """
        info = self.describe()
        return info['Table'].get('ItemCount', 0)