1
# Copyright (C) 2007 Canonical Ltd
 
 
3
# This program is free software; you can redistribute it and/or modify
 
 
4
# it under the terms of the GNU General Public License as published by
 
 
5
# the Free Software Foundation; either version 2 of the License, or
 
 
6
# (at your option) any later version.
 
 
8
# This program is distributed in the hope that it will be useful,
 
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 
11
# GNU General Public License for more details.
 
 
13
# You should have received a copy of the GNU General Public License
 
 
14
# along with this program; if not, write to the Free Software
 
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
 
17
"""Indexing facilities."""
 
 
23
    'GraphIndexPrefixAdapter',
 
 
27
from cStringIO import StringIO
 
 
30
from bzrlib.lazy_import import lazy_import
 
 
31
lazy_import(globals(), """
 
 
32
from bzrlib.trace import mutter
 
 
34
from bzrlib import debug, errors
 
 
36
_OPTION_KEY_ELEMENTS = "key_elements="
 
 
38
_OPTION_NODE_REFS = "node_ref_lists="
 
 
39
_SIGNATURE = "Bazaar Graph Index 1\n"
 
 
42
_whitespace_re = re.compile('[\t\n\x0b\x0c\r\x00 ]')
 
 
43
_newline_null_re = re.compile('[\n\0]')
 
 
46
class GraphIndexBuilder(object):
 
 
47
    """A builder that can build a GraphIndex.
 
 
49
    The resulting graph has the structure:
 
 
51
    _SIGNATURE OPTIONS NODES NEWLINE
 
 
52
    _SIGNATURE     := 'Bazaar Graph Index 1' NEWLINE
 
 
53
    OPTIONS        := 'node_ref_lists=' DIGITS NEWLINE
 
 
55
    NODE           := KEY NULL ABSENT? NULL REFERENCES NULL VALUE NEWLINE
 
 
56
    KEY            := Not-whitespace-utf8
 
 
58
    REFERENCES     := REFERENCE_LIST (TAB REFERENCE_LIST){node_ref_lists - 1}
 
 
59
    REFERENCE_LIST := (REFERENCE (CR REFERENCE)*)?
 
 
60
    REFERENCE      := DIGITS  ; digits is the byte offset in the index of the
 
 
62
    VALUE          := no-newline-no-null-bytes
 
 
65
    def __init__(self, reference_lists=0, key_elements=1):
 
 
66
        """Create a GraphIndex builder.
 
 
68
        :param reference_lists: The number of node references lists for each
 
 
70
        :param key_elements: The number of bytestrings in each key.
 
 
72
        self.reference_lists = reference_lists
 
 
75
        self._nodes_by_key = {}
 
 
76
        self._key_length = key_elements
 
 
78
    def _check_key(self, key):
 
 
79
        """Raise BadIndexKey if key is not a valid key for this index."""
 
 
80
        if type(key) != tuple:
 
 
81
            raise errors.BadIndexKey(key)
 
 
82
        if self._key_length != len(key):
 
 
83
            raise errors.BadIndexKey(key)
 
 
85
            if not element or _whitespace_re.search(element) is not None:
 
 
86
                raise errors.BadIndexKey(element)
 
 
88
    def add_node(self, key, value, references=()):
 
 
89
        """Add a node to the index.
 
 
91
        :param key: The key. keys are non-empty tuples containing
 
 
92
            as many whitespace-free utf8 bytestrings as the key length
 
 
93
            defined for this index.
 
 
94
        :param references: An iterable of iterables of keys. Each is a
 
 
95
            reference to another key.
 
 
96
        :param value: The value to associate with the key. It may be any
 
 
97
            bytes as long as it does not contain \0 or \n.
 
 
100
        if _newline_null_re.search(value) is not None:
 
 
101
            raise errors.BadIndexValue(value)
 
 
102
        if len(references) != self.reference_lists:
 
 
103
            raise errors.BadIndexValue(references)
 
 
105
        for reference_list in references:
 
 
106
            for reference in reference_list:
 
 
107
                self._check_key(reference)
 
 
108
                if reference not in self._nodes:
 
 
109
                    self._nodes[reference] = ('a', (), '')
 
 
110
            node_refs.append(tuple(reference_list))
 
 
111
        if key in self._nodes and self._nodes[key][0] == '':
 
 
112
            raise errors.BadIndexDuplicateKey(key, self)
 
 
113
        self._nodes[key] = ('', tuple(node_refs), value)
 
 
115
        if self._key_length > 1:
 
 
116
            key_dict = self._nodes_by_key
 
 
117
            if self.reference_lists:
 
 
118
                key_value = key, value, tuple(node_refs)
 
 
120
                key_value = key, value
 
 
121
            # possibly should do this on-demand, but it seems likely it is 
 
 
123
            # For a key of (foo, bar, baz) create
 
 
124
            # _nodes_by_key[foo][bar][baz] = key_value
 
 
125
            for subkey in key[:-1]:
 
 
126
                key_dict = key_dict.setdefault(subkey, {})
 
 
127
            key_dict[key[-1]] = key_value
 
 
131
        lines.append(_OPTION_NODE_REFS + str(self.reference_lists) + '\n')
 
 
132
        lines.append(_OPTION_KEY_ELEMENTS + str(self._key_length) + '\n')
 
 
133
        lines.append(_OPTION_LEN + str(len(self._keys)) + '\n')
 
 
134
        prefix_length = sum(len(x) for x in lines)
 
 
135
        # references are byte offsets. To avoid having to do nasty
 
 
136
        # polynomial work to resolve offsets (references to later in the 
 
 
137
        # file cannot be determined until all the inbetween references have
 
 
138
        # been calculated too) we pad the offsets with 0's to make them be
 
 
139
        # of consistent length. Using binary offsets would break the trivial
 
 
141
        # to calculate the width of zero's needed we do three passes:
 
 
142
        # one to gather all the non-reference data and the number of references.
 
 
143
        # one to pad all the data with reference-length and determine entry
 
 
147
        # forward sorted by key. In future we may consider topological sorting,
 
 
148
        # at the cost of table scans for direct lookup, or a second index for
 
 
150
        nodes = sorted(self._nodes.items())
 
 
151
        # if we do not prepass, we don't know how long it will be up front.
 
 
152
        expected_bytes = None
 
 
153
        # we only need to pre-pass if we have reference lists at all.
 
 
154
        if self.reference_lists:
 
 
156
            non_ref_bytes = prefix_length
 
 
158
            # TODO use simple multiplication for the constants in this loop.
 
 
159
            for key, (absent, references, value) in nodes:
 
 
160
                # record the offset known *so far* for this key:
 
 
161
                # the non reference bytes to date, and the total references to
 
 
162
                # date - saves reaccumulating on the second pass
 
 
163
                key_offset_info.append((key, non_ref_bytes, total_references))
 
 
164
                # key is literal, value is literal, there are 3 null's, 1 NL
 
 
165
                # key is variable length tuple, \x00 between elements
 
 
166
                non_ref_bytes += sum(len(element) for element in key)
 
 
167
                if self._key_length > 1:
 
 
168
                    non_ref_bytes += self._key_length - 1
 
 
169
                # value is literal bytes, there are 3 null's, 1 NL.
 
 
170
                non_ref_bytes += len(value) + 3 + 1
 
 
171
                # one byte for absent if set.
 
 
174
                elif self.reference_lists:
 
 
175
                    # (ref_lists -1) tabs
 
 
176
                    non_ref_bytes += self.reference_lists - 1
 
 
177
                    # (ref-1 cr's per ref_list)
 
 
178
                    for ref_list in references:
 
 
179
                        # how many references across the whole file?
 
 
180
                        total_references += len(ref_list)
 
 
181
                        # accrue reference separators
 
 
183
                            non_ref_bytes += len(ref_list) - 1
 
 
184
            # how many digits are needed to represent the total byte count?
 
 
186
            possible_total_bytes = non_ref_bytes + total_references*digits
 
 
187
            while 10 ** digits < possible_total_bytes:
 
 
189
                possible_total_bytes = non_ref_bytes + total_references*digits
 
 
190
            expected_bytes = possible_total_bytes + 1 # terminating newline
 
 
191
            # resolve key addresses.
 
 
193
            for key, non_ref_bytes, total_references in key_offset_info:
 
 
194
                key_addresses[key] = non_ref_bytes + total_references*digits
 
 
196
            format_string = '%%0%sd' % digits
 
 
197
        for key, (absent, references, value) in nodes:
 
 
198
            flattened_references = []
 
 
199
            for ref_list in references:
 
 
201
                for reference in ref_list:
 
 
202
                    ref_addresses.append(format_string % key_addresses[reference])
 
 
203
                flattened_references.append('\r'.join(ref_addresses))
 
 
204
            string_key = '\x00'.join(key)
 
 
205
            lines.append("%s\x00%s\x00%s\x00%s\n" % (string_key, absent,
 
 
206
                '\t'.join(flattened_references), value))
 
 
208
        result = StringIO(''.join(lines))
 
 
209
        if expected_bytes and len(result.getvalue()) != expected_bytes:
 
 
210
            raise errors.BzrError('Failed index creation. Internal error:'
 
 
211
                ' mismatched output length and expected length: %d %d' %
 
 
212
                (len(result.getvalue()), expected_bytes))
 
 
213
        return StringIO(''.join(lines))
 
 
216
class GraphIndex(object):
 
 
217
    """An index for data with embedded graphs.
 
 
219
    The index maps keys to a list of key reference lists, and a value.
 
 
220
    Each node has the same number of key reference lists. Each key reference
 
 
221
    list can be empty or an arbitrary length. The value is an opaque NULL
 
 
222
    terminated string without any newlines. The storage of the index is 
 
 
223
    hidden in the interface: keys and key references are always tuples of
 
 
224
    bytestrings, never the internal representation (e.g. dictionary offsets).
 
 
226
    It is presumed that the index will not be mutated - it is static data.
 
 
228
    Successive iter_all_entries calls will read the entire index each time.
 
 
229
    Additionally, iter_entries calls will read the index linearly until the
 
 
230
    desired keys are found. XXX: This must be fixed before the index is
 
 
231
    suitable for production use. :XXX
 
 
234
    def __init__(self, transport, name):
 
 
235
        """Open an index called name on transport.
 
 
237
        :param transport: A bzrlib.transport.Transport.
 
 
238
        :param name: A path to provide to transport API calls.
 
 
240
        self._transport = transport
 
 
243
        self._key_count = None
 
 
244
        self._keys_by_offset = None
 
 
245
        self._nodes_by_key = None
 
 
247
    def _buffer_all(self):
 
 
248
        """Buffer all the index data.
 
 
250
        Mutates self._nodes and self.keys_by_offset.
 
 
252
        if 'index' in debug.debug_flags:
 
 
253
            mutter('Reading entire index %s', self._transport.abspath(self._name))
 
 
254
        stream = self._transport.get(self._name)
 
 
255
        self._read_prefix(stream)
 
 
256
        expected_elements = 3 + self._key_length
 
 
258
        # raw data keyed by offset
 
 
259
        self._keys_by_offset = {}
 
 
260
        # ready-to-return key:value or key:value, node_ref_lists
 
 
262
        self._nodes_by_key = {}
 
 
265
        for line in stream.readlines():
 
 
269
            elements = line.split('\0')
 
 
270
            if len(elements) != expected_elements:
 
 
271
                raise errors.BadIndexData(self)
 
 
273
            key = tuple(elements[:self._key_length])
 
 
274
            absent, references, value = elements[-3:]
 
 
275
            value = value[:-1] # remove the newline
 
 
277
            for ref_string in references.split('\t'):
 
 
278
                ref_lists.append(tuple([
 
 
279
                    int(ref) for ref in ref_string.split('\r') if ref
 
 
281
            ref_lists = tuple(ref_lists)
 
 
282
            self._keys_by_offset[pos] = (key, absent, ref_lists, value)
 
 
284
        for key, absent, references, value in self._keys_by_offset.itervalues():
 
 
287
            # resolve references:
 
 
288
            if self.node_ref_lists:
 
 
290
                for ref_list in references:
 
 
291
                    node_refs.append(tuple([self._keys_by_offset[ref][0] for ref in ref_list]))
 
 
292
                node_value = (value, tuple(node_refs))
 
 
295
            self._nodes[key] = node_value
 
 
296
            if self._key_length > 1:
 
 
297
                subkey = list(reversed(key[:-1]))
 
 
298
                key_dict = self._nodes_by_key
 
 
299
                if self.node_ref_lists:
 
 
300
                    key_value = key, node_value[0], node_value[1]
 
 
302
                    key_value = key, node_value
 
 
303
                # possibly should do this on-demand, but it seems likely it is 
 
 
305
                # For a key of (foo, bar, baz) create
 
 
306
                # _nodes_by_key[foo][bar][baz] = key_value
 
 
307
                for subkey in key[:-1]:
 
 
308
                    key_dict = key_dict.setdefault(subkey, {})
 
 
309
                key_dict[key[-1]] = key_value
 
 
310
        # cache the keys for quick set intersections
 
 
311
        self._keys = set(self._nodes)
 
 
313
            # there must be one line - the empty trailer line.
 
 
314
            raise errors.BadIndexData(self)
 
 
316
    def iter_all_entries(self):
 
 
317
        """Iterate over all keys within the index.
 
 
319
        :return: An iterable of (key, value) or (key, value, reference_lists).
 
 
320
            The former tuple is used when there are no reference lists in the
 
 
321
            index, making the API compatible with simple key:value index types.
 
 
322
            There is no defined order for the result iteration - it will be in
 
 
323
            the most efficient order for the index.
 
 
325
        if self._nodes is None:
 
 
327
        if self.node_ref_lists:
 
 
328
            for key, (value, node_ref_lists) in self._nodes.iteritems():
 
 
329
                yield self, key, value, node_ref_lists
 
 
331
            for key, value in self._nodes.iteritems():
 
 
332
                yield self, key, value
 
 
334
    def _read_prefix(self, stream):
 
 
335
        signature = stream.read(len(self._signature()))
 
 
336
        if not signature == self._signature():
 
 
337
            raise errors.BadIndexFormatSignature(self._name, GraphIndex)
 
 
338
        options_line = stream.readline()
 
 
339
        if not options_line.startswith(_OPTION_NODE_REFS):
 
 
340
            raise errors.BadIndexOptions(self)
 
 
342
            self.node_ref_lists = int(options_line[len(_OPTION_NODE_REFS):-1])
 
 
344
            raise errors.BadIndexOptions(self)
 
 
345
        options_line = stream.readline()
 
 
346
        if not options_line.startswith(_OPTION_KEY_ELEMENTS):
 
 
347
            raise errors.BadIndexOptions(self)
 
 
349
            self._key_length = int(options_line[len(_OPTION_KEY_ELEMENTS):-1])
 
 
351
            raise errors.BadIndexOptions(self)
 
 
352
        options_line = stream.readline()
 
 
353
        if not options_line.startswith(_OPTION_LEN):
 
 
354
            raise errors.BadIndexOptions(self)
 
 
356
            self._key_count = int(options_line[len(_OPTION_LEN):-1])
 
 
358
            raise errors.BadIndexOptions(self)
 
 
360
    def iter_entries(self, keys):
 
 
361
        """Iterate over keys within the index.
 
 
363
        :param keys: An iterable providing the keys to be retrieved.
 
 
364
        :return: An iterable as per iter_all_entries, but restricted to the
 
 
365
            keys supplied. No additional keys will be returned, and every
 
 
366
            key supplied that is in the index will be returned.
 
 
371
        if self._nodes is None:
 
 
373
        keys = keys.intersection(self._keys)
 
 
374
        if self.node_ref_lists:
 
 
376
                value, node_refs = self._nodes[key]
 
 
377
                yield self, key, value, node_refs
 
 
380
                yield self, key, self._nodes[key]
 
 
382
    def iter_entries_prefix(self, keys):
 
 
383
        """Iterate over keys within the index using prefix matching.
 
 
385
        Prefix matching is applied within the tuple of a key, not to within
 
 
386
        the bytestring of each key element. e.g. if you have the keys ('foo',
 
 
387
        'bar'), ('foobar', 'gam') and do a prefix search for ('foo', None) then
 
 
388
        only the former key is returned.
 
 
390
        :param keys: An iterable providing the key prefixes to be retrieved.
 
 
391
            Each key prefix takes the form of a tuple the length of a key, but
 
 
392
            with the last N elements 'None' rather than a regular bytestring.
 
 
393
            The first element cannot be 'None'.
 
 
394
        :return: An iterable as per iter_all_entries, but restricted to the
 
 
395
            keys with a matching prefix to those supplied. No additional keys
 
 
396
            will be returned, and every match that is in the index will be
 
 
402
        # load data - also finds key lengths
 
 
403
        if self._nodes is None:
 
 
405
        if self._key_length == 1:
 
 
409
                    raise errors.BadIndexKey(key)
 
 
410
                if len(key) != self._key_length:
 
 
411
                    raise errors.BadIndexKey(key)
 
 
412
                if self.node_ref_lists:
 
 
413
                    value, node_refs = self._nodes[key]
 
 
414
                    yield self, key, value, node_refs
 
 
416
                    yield self, key, self._nodes[key]
 
 
421
                raise errors.BadIndexKey(key)
 
 
422
            if len(key) != self._key_length:
 
 
423
                raise errors.BadIndexKey(key)
 
 
424
            # find what it refers to:
 
 
425
            key_dict = self._nodes_by_key
 
 
427
            # find the subdict whose contents should be returned.
 
 
429
                while len(elements) and elements[0] is not None:
 
 
430
                    key_dict = key_dict[elements[0]]
 
 
433
                # a non-existant lookup.
 
 
438
                    key_dict = dicts.pop(-1)
 
 
439
                    # can't be empty or would not exist
 
 
440
                    item, value = key_dict.iteritems().next()
 
 
441
                    if type(value) == dict:
 
 
443
                        dicts.extend(key_dict.itervalues())
 
 
446
                        for value in key_dict.itervalues():
 
 
447
                            # each value is the key:value:node refs tuple
 
 
449
                            yield (self, ) + value
 
 
451
                # the last thing looked up was a terminal element
 
 
452
                yield (self, ) + key_dict
 
 
455
        """Return an estimate of the number of keys in this index.
 
 
457
        For GraphIndex the estimate is exact.
 
 
459
        if self._key_count is None:
 
 
460
            # really this should just read the prefix
 
 
462
        return self._key_count
 
 
464
    def _signature(self):
 
 
465
        """The file signature for this index type."""
 
 
469
        """Validate that everything in the index can be accessed."""
 
 
470
        # iter_all validates completely at the moment, so just do that.
 
 
471
        for node in self.iter_all_entries():
 
 
475
class CombinedGraphIndex(object):
 
 
476
    """A GraphIndex made up from smaller GraphIndices.
 
 
478
    The backing indices must implement GraphIndex, and are presumed to be
 
 
481
    Queries against the combined index will be made against the first index,
 
 
482
    and then the second and so on. The order of index's can thus influence
 
 
483
    performance significantly. For example, if one index is on local disk and a
 
 
484
    second on a remote server, the local disk index should be before the other
 
 
488
    def __init__(self, indices):
 
 
489
        """Create a CombinedGraphIndex backed by indices.
 
 
491
        :param indices: An ordered list of indices to query for data.
 
 
493
        self._indices = indices
 
 
495
    def insert_index(self, pos, index):
 
 
496
        """Insert a new index in the list of indices to query.
 
 
498
        :param pos: The position to insert the index.
 
 
499
        :param index: The index to insert.
 
 
501
        self._indices.insert(pos, index)
 
 
503
    def iter_all_entries(self):
 
 
504
        """Iterate over all keys within the index
 
 
506
        Duplicate keys across child indices are presumed to have the same
 
 
507
        value and are only reported once.
 
 
509
        :return: An iterable of (key, reference_lists, value). There is no
 
 
510
            defined order for the result iteration - it will be in the most
 
 
511
            efficient order for the index.
 
 
514
        for index in self._indices:
 
 
515
            for node in index.iter_all_entries():
 
 
516
                if node[1] not in seen_keys:
 
 
518
                    seen_keys.add(node[1])
 
 
520
    def iter_entries(self, keys):
 
 
521
        """Iterate over keys within the index.
 
 
523
        Duplicate keys across child indices are presumed to have the same
 
 
524
        value and are only reported once.
 
 
526
        :param keys: An iterable providing the keys to be retrieved.
 
 
527
        :return: An iterable of (key, reference_lists, value). There is no
 
 
528
            defined order for the result iteration - it will be in the most
 
 
529
            efficient order for the index.
 
 
532
        for index in self._indices:
 
 
535
            for node in index.iter_entries(keys):
 
 
539
    def iter_entries_prefix(self, keys):
 
 
540
        """Iterate over keys within the index using prefix matching.
 
 
542
        Duplicate keys across child indices are presumed to have the same
 
 
543
        value and are only reported once.
 
 
545
        Prefix matching is applied within the tuple of a key, not to within
 
 
546
        the bytestring of each key element. e.g. if you have the keys ('foo',
 
 
547
        'bar'), ('foobar', 'gam') and do a prefix search for ('foo', None) then
 
 
548
        only the former key is returned.
 
 
550
        :param keys: An iterable providing the key prefixes to be retrieved.
 
 
551
            Each key prefix takes the form of a tuple the length of a key, but
 
 
552
            with the last N elements 'None' rather than a regular bytestring.
 
 
553
            The first element cannot be 'None'.
 
 
554
        :return: An iterable as per iter_all_entries, but restricted to the
 
 
555
            keys with a matching prefix to those supplied. No additional keys
 
 
556
            will be returned, and every match that is in the index will be
 
 
563
        for index in self._indices:
 
 
564
            for node in index.iter_entries_prefix(keys):
 
 
565
                if node[1] in seen_keys:
 
 
567
                seen_keys.add(node[1])
 
 
571
        """Return an estimate of the number of keys in this index.
 
 
573
        For CombinedGraphIndex this is approximated by the sum of the keys of
 
 
574
        the child indices. As child indices may have duplicate keys this can
 
 
575
        have a maximum error of the number of child indices * largest number of
 
 
578
        return sum((index.key_count() for index in self._indices), 0)
 
 
581
        """Validate that everything in the index can be accessed."""
 
 
582
        for index in self._indices:
 
 
586
class InMemoryGraphIndex(GraphIndexBuilder):
 
 
587
    """A GraphIndex which operates entirely out of memory and is mutable.
 
 
589
    This is designed to allow the accumulation of GraphIndex entries during a
 
 
590
    single write operation, where the accumulated entries need to be immediately
 
 
591
    available - for example via a CombinedGraphIndex.
 
 
594
    def add_nodes(self, nodes):
 
 
595
        """Add nodes to the index.
 
 
597
        :param nodes: An iterable of (key, node_refs, value) entries to add.
 
 
599
        if self.reference_lists:
 
 
600
            for (key, value, node_refs) in nodes:
 
 
601
                self.add_node(key, value, node_refs)
 
 
603
            for (key, value) in nodes:
 
 
604
                self.add_node(key, value)
 
 
606
    def iter_all_entries(self):
 
 
607
        """Iterate over all keys within the index
 
 
609
        :return: An iterable of (key, reference_lists, value). There is no
 
 
610
            defined order for the result iteration - it will be in the most
 
 
611
            efficient order for the index (in this case dictionary hash order).
 
 
613
        if self.reference_lists:
 
 
614
            for key, (absent, references, value) in self._nodes.iteritems():
 
 
616
                    yield self, key, value, references
 
 
618
            for key, (absent, references, value) in self._nodes.iteritems():
 
 
620
                    yield self, key, value
 
 
622
    def iter_entries(self, keys):
 
 
623
        """Iterate over keys within the index.
 
 
625
        :param keys: An iterable providing the keys to be retrieved.
 
 
626
        :return: An iterable of (key, reference_lists, value). There is no
 
 
627
            defined order for the result iteration - it will be in the most
 
 
628
            efficient order for the index (keys iteration order in this case).
 
 
631
        if self.reference_lists:
 
 
632
            for key in keys.intersection(self._keys):
 
 
633
                node = self._nodes[key]
 
 
635
                    yield self, key, node[2], node[1]
 
 
637
            for key in keys.intersection(self._keys):
 
 
638
                node = self._nodes[key]
 
 
640
                    yield self, key, node[2]
 
 
642
    def iter_entries_prefix(self, keys):
 
 
643
        """Iterate over keys within the index using prefix matching.
 
 
645
        Prefix matching is applied within the tuple of a key, not to within
 
 
646
        the bytestring of each key element. e.g. if you have the keys ('foo',
 
 
647
        'bar'), ('foobar', 'gam') and do a prefix search for ('foo', None) then
 
 
648
        only the former key is returned.
 
 
650
        :param keys: An iterable providing the key prefixes to be retrieved.
 
 
651
            Each key prefix takes the form of a tuple the length of a key, but
 
 
652
            with the last N elements 'None' rather than a regular bytestring.
 
 
653
            The first element cannot be 'None'.
 
 
654
        :return: An iterable as per iter_all_entries, but restricted to the
 
 
655
            keys with a matching prefix to those supplied. No additional keys
 
 
656
            will be returned, and every match that is in the index will be
 
 
659
        # XXX: To much duplication with the GraphIndex class; consider finding
 
 
660
        # a good place to pull out the actual common logic.
 
 
664
        if self._key_length == 1:
 
 
668
                    raise errors.BadIndexKey(key)
 
 
669
                if len(key) != self._key_length:
 
 
670
                    raise errors.BadIndexKey(key)
 
 
671
                node = self._nodes[key]
 
 
674
                if self.reference_lists:
 
 
675
                    yield self, key, node[2], node[1]
 
 
677
                    yield self, key, node[2]
 
 
682
                raise errors.BadIndexKey(key)
 
 
683
            if len(key) != self._key_length:
 
 
684
                raise errors.BadIndexKey(key)
 
 
685
            # find what it refers to:
 
 
686
            key_dict = self._nodes_by_key
 
 
688
            # find the subdict to return
 
 
690
                while len(elements) and elements[0] is not None:
 
 
691
                    key_dict = key_dict[elements[0]]
 
 
694
                # a non-existant lookup.
 
 
699
                    key_dict = dicts.pop(-1)
 
 
700
                    # can't be empty or would not exist
 
 
701
                    item, value = key_dict.iteritems().next()
 
 
702
                    if type(value) == dict:
 
 
704
                        dicts.extend(key_dict.itervalues())
 
 
707
                        for value in key_dict.itervalues():
 
 
708
                            yield (self, ) + value
 
 
710
                yield (self, ) + key_dict
 
 
713
        """Return an estimate of the number of keys in this index.
 
 
715
        For InMemoryGraphIndex the estimate is exact.
 
 
717
        return len(self._keys)
 
 
720
        """In memory index's have no known corruption at the moment."""
 
 
723
class GraphIndexPrefixAdapter(object):
 
 
724
    """An adapter between GraphIndex with different key lengths.
 
 
726
    Queries against this will emit queries against the adapted Graph with the
 
 
727
    prefix added, queries for all items use iter_entries_prefix. The returned
 
 
728
    nodes will have their keys and node references adjusted to remove the 
 
 
729
    prefix. Finally, an add_nodes_callback can be supplied - when called the
 
 
730
    nodes and references being added will have prefix prepended.
 
 
733
    def __init__(self, adapted, prefix, missing_key_length,
 
 
734
        add_nodes_callback=None):
 
 
735
        """Construct an adapter against adapted with prefix."""
 
 
736
        self.adapted = adapted
 
 
737
        self.prefix_key = prefix + (None,)*missing_key_length
 
 
739
        self.prefix_len = len(prefix)
 
 
740
        self.add_nodes_callback = add_nodes_callback
 
 
742
    def add_nodes(self, nodes):
 
 
743
        """Add nodes to the index.
 
 
745
        :param nodes: An iterable of (key, node_refs, value) entries to add.
 
 
747
        # save nodes in case its an iterator
 
 
749
        translated_nodes = []
 
 
751
            # Add prefix_key to each reference node_refs is a tuple of tuples,
 
 
752
            # so split it apart, and add prefix_key to the internal reference
 
 
753
            for (key, value, node_refs) in nodes:
 
 
754
                adjusted_references = (
 
 
755
                    tuple(tuple(self.prefix + ref_node for ref_node in ref_list)
 
 
756
                        for ref_list in node_refs))
 
 
757
                translated_nodes.append((self.prefix + key, value,
 
 
758
                    adjusted_references))
 
 
760
            # XXX: TODO add an explicit interface for getting the reference list
 
 
761
            # status, to handle this bit of user-friendliness in the API more 
 
 
763
            for (key, value) in nodes:
 
 
764
                translated_nodes.append((self.prefix + key, value))
 
 
765
        self.add_nodes_callback(translated_nodes)
 
 
767
    def add_node(self, key, value, references=()):
 
 
768
        """Add a node to the index.
 
 
770
        :param key: The key. keys are non-empty tuples containing
 
 
771
            as many whitespace-free utf8 bytestrings as the key length
 
 
772
            defined for this index.
 
 
773
        :param references: An iterable of iterables of keys. Each is a
 
 
774
            reference to another key.
 
 
775
        :param value: The value to associate with the key. It may be any
 
 
776
            bytes as long as it does not contain \0 or \n.
 
 
778
        self.add_nodes(((key, value, references), ))
 
 
780
    def _strip_prefix(self, an_iter):
 
 
781
        """Strip prefix data from nodes and return it."""
 
 
784
            if node[1][:self.prefix_len] != self.prefix:
 
 
785
                raise errors.BadIndexData(self)
 
 
786
            for ref_list in node[3]:
 
 
787
                for ref_node in ref_list:
 
 
788
                    if ref_node[:self.prefix_len] != self.prefix:
 
 
789
                        raise errors.BadIndexData(self)
 
 
790
            yield node[0], node[1][self.prefix_len:], node[2], (
 
 
791
                tuple(tuple(ref_node[self.prefix_len:] for ref_node in ref_list)
 
 
792
                for ref_list in node[3]))
 
 
794
    def iter_all_entries(self):
 
 
795
        """Iterate over all keys within the index
 
 
797
        iter_all_entries is implemented against the adapted index using
 
 
800
        :return: An iterable of (key, reference_lists, value). There is no
 
 
801
            defined order for the result iteration - it will be in the most
 
 
802
            efficient order for the index (in this case dictionary hash order).
 
 
804
        return self._strip_prefix(self.adapted.iter_entries_prefix([self.prefix_key]))
 
 
806
    def iter_entries(self, keys):
 
 
807
        """Iterate over keys within the index.
 
 
809
        :param keys: An iterable providing the keys to be retrieved.
 
 
810
        :return: An iterable of (key, reference_lists, value). There is no
 
 
811
            defined order for the result iteration - it will be in the most
 
 
812
            efficient order for the index (keys iteration order in this case).
 
 
814
        return self._strip_prefix(self.adapted.iter_entries(
 
 
815
            self.prefix + key for key in keys))
 
 
817
    def iter_entries_prefix(self, keys):
 
 
818
        """Iterate over keys within the index using prefix matching.
 
 
820
        Prefix matching is applied within the tuple of a key, not to within
 
 
821
        the bytestring of each key element. e.g. if you have the keys ('foo',
 
 
822
        'bar'), ('foobar', 'gam') and do a prefix search for ('foo', None) then
 
 
823
        only the former key is returned.
 
 
825
        :param keys: An iterable providing the key prefixes to be retrieved.
 
 
826
            Each key prefix takes the form of a tuple the length of a key, but
 
 
827
            with the last N elements 'None' rather than a regular bytestring.
 
 
828
            The first element cannot be 'None'.
 
 
829
        :return: An iterable as per iter_all_entries, but restricted to the
 
 
830
            keys with a matching prefix to those supplied. No additional keys
 
 
831
            will be returned, and every match that is in the index will be
 
 
834
        return self._strip_prefix(self.adapted.iter_entries_prefix(
 
 
835
            self.prefix + key for key in keys))
 
 
838
        """Return an estimate of the number of keys in this index.
 
 
840
        For GraphIndexPrefixAdapter this is relatively expensive - key
 
 
841
        iteration with the prefix is done.
 
 
843
        return len(list(self.iter_all_entries()))
 
 
846
        """Call the adapted's validate."""
 
 
847
        self.adapted.validate()