~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/index.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2008-06-10 08:15:19 UTC
  • mfrom: (3489.1.2 integration)
  • Revision ID: pqm@pqm.ubuntu.com-20080610081519-95unlj6ayptlh2uv
(mbp) Bump version to 1.6b3

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""Indexing facilities."""
18
18
 
27
27
from bisect import bisect_right
28
28
from cStringIO import StringIO
29
29
import re
30
 
import sys
31
30
 
32
31
from bzrlib.lazy_import import lazy_import
33
32
lazy_import(globals(), """
53
52
_newline_null_re = re.compile('[\n\0]')
54
53
 
55
54
 
56
 
def _has_key_from_parent_map(self, key):
57
 
    """Check if this index has one key.
58
 
 
59
 
    If it's possible to check for multiple keys at once through
60
 
    calling get_parent_map that should be faster.
61
 
    """
62
 
    return (key in self.get_parent_map([key]))
63
 
 
64
 
 
65
 
def _missing_keys_from_parent_map(self, keys):
66
 
    return set(keys) - set(self.get_parent_map(keys))
67
 
 
68
 
 
69
55
class GraphIndexBuilder(object):
70
56
    """A builder that can build a GraphIndex.
71
 
 
 
57
    
72
58
    The resulting graph has the structure:
73
 
 
 
59
    
74
60
    _SIGNATURE OPTIONS NODES NEWLINE
75
61
    _SIGNATURE     := 'Bazaar Graph Index 1' NEWLINE
76
62
    OPTIONS        := 'node_ref_lists=' DIGITS NEWLINE
94
80
        """
95
81
        self.reference_lists = reference_lists
96
82
        self._keys = set()
97
 
        # A dict of {key: (absent, ref_lists, value)}
98
83
        self._nodes = {}
99
 
        self._nodes_by_key = None
 
84
        self._nodes_by_key = {}
100
85
        self._key_length = key_elements
101
 
        self._optimize_for_size = False
102
 
        self._combine_backing_indices = True
103
86
 
104
87
    def _check_key(self, key):
105
88
        """Raise BadIndexKey if key is not a valid key for this index."""
111
94
            if not element or _whitespace_re.search(element) is not None:
112
95
                raise errors.BadIndexKey(element)
113
96
 
114
 
    def _external_references(self):
115
 
        """Return references that are not present in this index.
116
 
        """
117
 
        keys = set()
118
 
        refs = set()
119
 
        # TODO: JAM 2008-11-21 This makes an assumption about how the reference
120
 
        #       lists are used. It is currently correct for pack-0.92 through
121
 
        #       1.9, which use the node references (3rd column) second
122
 
        #       reference list as the compression parent. Perhaps this should
123
 
        #       be moved into something higher up the stack, since it
124
 
        #       makes assumptions about how the index is used.
125
 
        if self.reference_lists > 1:
126
 
            for node in self.iter_all_entries():
127
 
                keys.add(node[1])
128
 
                refs.update(node[3][1])
129
 
            return refs - keys
130
 
        else:
131
 
            # If reference_lists == 0 there can be no external references, and
132
 
            # if reference_lists == 1, then there isn't a place to store the
133
 
            # compression parent
134
 
            return set()
135
 
 
136
 
    def _get_nodes_by_key(self):
137
 
        if self._nodes_by_key is None:
138
 
            nodes_by_key = {}
139
 
            if self.reference_lists:
140
 
                for key, (absent, references, value) in self._nodes.iteritems():
141
 
                    if absent:
142
 
                        continue
143
 
                    key_dict = nodes_by_key
144
 
                    for subkey in key[:-1]:
145
 
                        key_dict = key_dict.setdefault(subkey, {})
146
 
                    key_dict[key[-1]] = key, value, references
147
 
            else:
148
 
                for key, (absent, references, value) in self._nodes.iteritems():
149
 
                    if absent:
150
 
                        continue
151
 
                    key_dict = nodes_by_key
152
 
                    for subkey in key[:-1]:
153
 
                        key_dict = key_dict.setdefault(subkey, {})
154
 
                    key_dict[key[-1]] = key, value
155
 
            self._nodes_by_key = nodes_by_key
156
 
        return self._nodes_by_key
157
 
 
158
 
    def _update_nodes_by_key(self, key, value, node_refs):
159
 
        """Update the _nodes_by_key dict with a new key.
160
 
 
161
 
        For a key of (foo, bar, baz) create
162
 
        _nodes_by_key[foo][bar][baz] = key_value
163
 
        """
164
 
        if self._nodes_by_key is None:
165
 
            return
166
 
        key_dict = self._nodes_by_key
167
 
        if self.reference_lists:
168
 
            key_value = key, value, node_refs
169
 
        else:
170
 
            key_value = key, value
171
 
        for subkey in key[:-1]:
172
 
            key_dict = key_dict.setdefault(subkey, {})
173
 
        key_dict[key[-1]] = key_value
174
 
 
175
 
    def _check_key_ref_value(self, key, references, value):
176
 
        """Check that 'key' and 'references' are all valid.
177
 
 
178
 
        :param key: A key tuple. Must conform to the key interface (be a tuple,
179
 
            be of the right length, not have any whitespace or nulls in any key
180
 
            element.)
181
 
        :param references: An iterable of reference lists. Something like
182
 
            [[(ref, key)], [(ref, key), (other, key)]]
183
 
        :param value: The value associate with this key. Must not contain
184
 
            newlines or null characters.
185
 
        :return: (node_refs, absent_references)
186
 
            node_refs   basically a packed form of 'references' where all
187
 
                        iterables are tuples
188
 
            absent_references   reference keys that are not in self._nodes.
189
 
                                This may contain duplicates if the same key is
190
 
                                referenced in multiple lists.
 
97
    def add_node(self, key, value, references=()):
 
98
        """Add a node to the index.
 
99
 
 
100
        :param key: The key. keys are non-empty tuples containing
 
101
            as many whitespace-free utf8 bytestrings as the key length
 
102
            defined for this index.
 
103
        :param references: An iterable of iterables of keys. Each is a
 
104
            reference to another key.
 
105
        :param value: The value to associate with the key. It may be any
 
106
            bytes as long as it does not contain \0 or \n.
191
107
        """
192
108
        self._check_key(key)
193
109
        if _newline_null_re.search(value) is not None:
195
111
        if len(references) != self.reference_lists:
196
112
            raise errors.BadIndexValue(references)
197
113
        node_refs = []
198
 
        absent_references = []
199
114
        for reference_list in references:
200
115
            for reference in reference_list:
201
 
                # If reference *is* in self._nodes, then we know it has already
202
 
                # been checked.
 
116
                self._check_key(reference)
203
117
                if reference not in self._nodes:
204
 
                    self._check_key(reference)
205
 
                    absent_references.append(reference)
 
118
                    self._nodes[reference] = ('a', (), '')
206
119
            node_refs.append(tuple(reference_list))
207
 
        return tuple(node_refs), absent_references
208
 
 
209
 
    def add_node(self, key, value, references=()):
210
 
        """Add a node to the index.
211
 
 
212
 
        :param key: The key. keys are non-empty tuples containing
213
 
            as many whitespace-free utf8 bytestrings as the key length
214
 
            defined for this index.
215
 
        :param references: An iterable of iterables of keys. Each is a
216
 
            reference to another key.
217
 
        :param value: The value to associate with the key. It may be any
218
 
            bytes as long as it does not contain \0 or \n.
219
 
        """
220
 
        (node_refs,
221
 
         absent_references) = self._check_key_ref_value(key, references, value)
222
 
        if key in self._nodes and self._nodes[key][0] != 'a':
 
120
        if key in self._nodes and self._nodes[key][0] == '':
223
121
            raise errors.BadIndexDuplicateKey(key, self)
224
 
        for reference in absent_references:
225
 
            # There may be duplicates, but I don't think it is worth worrying
226
 
            # about
227
 
            self._nodes[reference] = ('a', (), '')
228
 
        self._nodes[key] = ('', node_refs, value)
 
122
        self._nodes[key] = ('', tuple(node_refs), value)
229
123
        self._keys.add(key)
230
 
        if self._nodes_by_key is not None and self._key_length > 1:
231
 
            self._update_nodes_by_key(key, value, node_refs)
 
124
        if self._key_length > 1:
 
125
            key_dict = self._nodes_by_key
 
126
            if self.reference_lists:
 
127
                key_value = key, value, tuple(node_refs)
 
128
            else:
 
129
                key_value = key, value
 
130
            # possibly should do this on-demand, but it seems likely it is 
 
131
            # always wanted
 
132
            # For a key of (foo, bar, baz) create
 
133
            # _nodes_by_key[foo][bar][baz] = key_value
 
134
            for subkey in key[:-1]:
 
135
                key_dict = key_dict.setdefault(subkey, {})
 
136
            key_dict[key[-1]] = key_value
232
137
 
233
138
    def finish(self):
234
139
        lines = [_SIGNATURE]
237
142
        lines.append(_OPTION_LEN + str(len(self._keys)) + '\n')
238
143
        prefix_length = sum(len(x) for x in lines)
239
144
        # references are byte offsets. To avoid having to do nasty
240
 
        # polynomial work to resolve offsets (references to later in the
 
145
        # polynomial work to resolve offsets (references to later in the 
241
146
        # file cannot be determined until all the inbetween references have
242
147
        # been calculated too) we pad the offsets with 0's to make them be
243
148
        # of consistent length. Using binary offsets would break the trivial
247
152
        # one to pad all the data with reference-length and determine entry
248
153
        # addresses.
249
154
        # One to serialise.
250
 
 
 
155
        
251
156
        # forward sorted by key. In future we may consider topological sorting,
252
157
        # at the cost of table scans for direct lookup, or a second index for
253
158
        # direct lookup
314
219
            raise errors.BzrError('Failed index creation. Internal error:'
315
220
                ' mismatched output length and expected length: %d %d' %
316
221
                (len(result.getvalue()), expected_bytes))
317
 
        return result
318
 
 
319
 
    def set_optimize(self, for_size=None, combine_backing_indices=None):
320
 
        """Change how the builder tries to optimize the result.
321
 
 
322
 
        :param for_size: Tell the builder to try and make the index as small as
323
 
            possible.
324
 
        :param combine_backing_indices: If the builder spills to disk to save
325
 
            memory, should the on-disk indices be combined. Set to True if you
326
 
            are going to be probing the index, but to False if you are not. (If
327
 
            you are not querying, then the time spent combining is wasted.)
328
 
        :return: None
329
 
        """
330
 
        # GraphIndexBuilder itself doesn't pay attention to the flag yet, but
331
 
        # other builders do.
332
 
        if for_size is not None:
333
 
            self._optimize_for_size = for_size
334
 
        if combine_backing_indices is not None:
335
 
            self._combine_backing_indices = combine_backing_indices
 
222
        return StringIO(''.join(lines))
336
223
 
337
224
 
338
225
class GraphIndex(object):
339
226
    """An index for data with embedded graphs.
340
 
 
 
227
 
341
228
    The index maps keys to a list of key reference lists, and a value.
342
229
    Each node has the same number of key reference lists. Each key reference
343
230
    list can be empty or an arbitrary length. The value is an opaque NULL
344
 
    terminated string without any newlines. The storage of the index is
 
231
    terminated string without any newlines. The storage of the index is 
345
232
    hidden in the interface: keys and key references are always tuples of
346
233
    bytestrings, never the internal representation (e.g. dictionary offsets).
347
234
 
385
272
        self._keys_by_offset = None
386
273
        self._nodes_by_key = None
387
274
        self._size = size
388
 
        # The number of bytes we've read so far in trying to process this file
389
 
        self._bytes_read = 0
390
275
 
391
276
    def __eq__(self, other):
392
277
        """Equal when self and other were created with the same parameters."""
399
284
    def __ne__(self, other):
400
285
        return not self.__eq__(other)
401
286
 
402
 
    def __repr__(self):
403
 
        return "%s(%r)" % (self.__class__.__name__,
404
 
            self._transport.abspath(self._name))
405
 
 
406
 
    def _buffer_all(self, stream=None):
 
287
    def _buffer_all(self):
407
288
        """Buffer all the index data.
408
289
 
409
290
        Mutates self._nodes and self.keys_by_offset.
410
291
        """
411
 
        if self._nodes is not None:
412
 
            # We already did this
413
 
            return
414
292
        if 'index' in debug.debug_flags:
415
293
            mutter('Reading entire index %s', self._transport.abspath(self._name))
416
 
        if stream is None:
417
 
            stream = self._transport.get(self._name)
 
294
        stream = self._transport.get(self._name)
418
295
        self._read_prefix(stream)
419
296
        self._expected_elements = 3 + self._key_length
420
297
        line_count = 0
422
299
        self._keys_by_offset = {}
423
300
        # ready-to-return key:value or key:value, node_ref_lists
424
301
        self._nodes = {}
425
 
        self._nodes_by_key = None
 
302
        self._nodes_by_key = {}
426
303
        trailers = 0
427
304
        pos = stream.tell()
428
305
        lines = stream.read().split('\n')
437
314
            else:
438
315
                node_value = value
439
316
            self._nodes[key] = node_value
 
317
            if self._key_length > 1:
 
318
                subkey = list(reversed(key[:-1]))
 
319
                key_dict = self._nodes_by_key
 
320
                if self.node_ref_lists:
 
321
                    key_value = key, node_value[0], node_value[1]
 
322
                else:
 
323
                    key_value = key, node_value
 
324
                # possibly should do this on-demand, but it seems likely it is 
 
325
                # always wanted
 
326
                # For a key of (foo, bar, baz) create
 
327
                # _nodes_by_key[foo][bar][baz] = key_value
 
328
                for subkey in key[:-1]:
 
329
                    key_dict = key_dict.setdefault(subkey, {})
 
330
                key_dict[key[-1]] = key_value
440
331
        # cache the keys for quick set intersections
441
332
        self._keys = set(self._nodes)
442
333
        if trailers != 1:
443
334
            # there must be one line - the empty trailer line.
444
335
            raise errors.BadIndexData(self)
445
336
 
446
 
    def external_references(self, ref_list_num):
447
 
        """Return references that are not present in this index.
448
 
        """
449
 
        self._buffer_all()
450
 
        if ref_list_num + 1 > self.node_ref_lists:
451
 
            raise ValueError('No ref list %d, index has %d ref lists'
452
 
                % (ref_list_num, self.node_ref_lists))
453
 
        refs = set()
454
 
        for key, (value, ref_lists) in self._nodes.iteritems():
455
 
            ref_list = ref_lists[ref_list_num]
456
 
            refs.update(ref_list)
457
 
        return refs - self._keys
458
 
 
459
 
    def _get_nodes_by_key(self):
460
 
        if self._nodes_by_key is None:
461
 
            nodes_by_key = {}
462
 
            if self.node_ref_lists:
463
 
                for key, (value, references) in self._nodes.iteritems():
464
 
                    key_dict = nodes_by_key
465
 
                    for subkey in key[:-1]:
466
 
                        key_dict = key_dict.setdefault(subkey, {})
467
 
                    key_dict[key[-1]] = key, value, references
468
 
            else:
469
 
                for key, value in self._nodes.iteritems():
470
 
                    key_dict = nodes_by_key
471
 
                    for subkey in key[:-1]:
472
 
                        key_dict = key_dict.setdefault(subkey, {})
473
 
                    key_dict[key[-1]] = key, value
474
 
            self._nodes_by_key = nodes_by_key
475
 
        return self._nodes_by_key
476
 
 
477
337
    def iter_all_entries(self):
478
338
        """Iterate over all keys within the index.
479
339
 
523
383
 
524
384
    def _resolve_references(self, references):
525
385
        """Return the resolved key references for references.
526
 
 
 
386
        
527
387
        References are resolved by looking up the location of the key in the
528
388
        _keys_by_offset map and substituting the key name, preserving ordering.
529
389
 
530
 
        :param references: An iterable of iterables of key locations. e.g.
 
390
        :param references: An iterable of iterables of key locations. e.g. 
531
391
            [[123, 456], [123]]
532
392
        :return: A tuple of tuples of keys.
533
393
        """
604
464
            keys supplied. No additional keys will be returned, and every
605
465
            key supplied that is in the index will be returned.
606
466
        """
 
467
        # PERFORMANCE TODO: parse and bisect all remaining data at some
 
468
        # threshold of total-index processing/get calling layers that expect to
 
469
        # read the entire index to use the iter_all_entries  method instead.
607
470
        keys = set(keys)
608
471
        if not keys:
609
472
            return []
610
473
        if self._size is None and self._nodes is None:
611
474
            self._buffer_all()
612
 
 
613
 
        # We fit about 20 keys per minimum-read (4K), so if we are looking for
614
 
        # more than 1/20th of the index its likely (assuming homogenous key
615
 
        # spread) that we'll read the entire index. If we're going to do that,
616
 
        # buffer the whole thing. A better analysis might take key spread into
617
 
        # account - but B+Tree indices are better anyway.
618
 
        # We could look at all data read, and use a threshold there, which will
619
 
        # trigger on ancestry walks, but that is not yet fully mapped out.
620
 
        if self._nodes is None and len(keys) * 20 > self.key_count():
621
 
            self._buffer_all()
622
475
        if self._nodes is not None:
623
476
            return self._iter_entries_from_total_buffer(keys)
624
477
        else:
666
519
                else:
667
520
                    yield self, key, self._nodes[key]
668
521
            return
669
 
        nodes_by_key = self._get_nodes_by_key()
670
522
        for key in keys:
671
523
            # sanity check
672
524
            if key[0] is None:
674
526
            if len(key) != self._key_length:
675
527
                raise errors.BadIndexKey(key)
676
528
            # find what it refers to:
677
 
            key_dict = nodes_by_key
 
529
            key_dict = self._nodes_by_key
678
530
            elements = list(key)
679
531
            # find the subdict whose contents should be returned.
680
532
            try:
691
543
                    # can't be empty or would not exist
692
544
                    item, value = key_dict.iteritems().next()
693
545
                    if type(value) == dict:
694
 
                        # push keys
 
546
                        # push keys 
695
547
                        dicts.extend(key_dict.itervalues())
696
548
                    else:
697
549
                        # yield keys
705
557
 
706
558
    def key_count(self):
707
559
        """Return an estimate of the number of keys in this index.
708
 
 
 
560
        
709
561
        For GraphIndex the estimate is exact.
710
562
        """
711
563
        if self._key_count is None:
727
579
        # Possible improvements:
728
580
        #  - only bisect lookup each key once
729
581
        #  - sort the keys first, and use that to reduce the bisection window
730
 
        # -----
 
582
        # ----- 
731
583
        # this progresses in three parts:
732
584
        # read data
733
585
        # parse it
742
594
                # We have the key parsed.
743
595
                continue
744
596
            index = self._parsed_key_index(key)
745
 
            if (len(self._parsed_key_map) and
 
597
            if (len(self._parsed_key_map) and 
746
598
                self._parsed_key_map[index][0] <= key and
747
599
                (self._parsed_key_map[index][1] >= key or
748
600
                 # end of the file has been parsed
752
604
                continue
753
605
            # - if we have examined this part of the file already - yes
754
606
            index = self._parsed_byte_index(location)
755
 
            if (len(self._parsed_byte_map) and
 
607
            if (len(self._parsed_byte_map) and 
756
608
                self._parsed_byte_map[index][0] <= location and
757
609
                self._parsed_byte_map[index][1] > location):
758
610
                # the byte region has been parsed, so no read is needed.
767
619
        if self._bisect_nodes is None:
768
620
            readv_ranges.append(_HEADER_READV)
769
621
        self._read_and_parse(readv_ranges)
770
 
        result = []
771
 
        if self._nodes is not None:
772
 
            # _read_and_parse triggered a _buffer_all because we requested the
773
 
            # whole data range
774
 
            for location, key in location_keys:
775
 
                if key not in self._nodes: # not present
776
 
                    result.append(((location, key), False))
777
 
                elif self.node_ref_lists:
778
 
                    value, refs = self._nodes[key]
779
 
                    result.append(((location, key),
780
 
                        (self, key, value, refs)))
781
 
                else:
782
 
                    result.append(((location, key),
783
 
                        (self, key, self._nodes[key])))
784
 
            return result
785
622
        # generate results:
786
623
        #  - figure out <, >, missing, present
787
624
        #  - result present references so we can return them.
 
625
        result = []
788
626
        # keys that we cannot answer until we resolve references
789
627
        pending_references = []
790
628
        pending_locations = set()
840
678
            if length > 0:
841
679
                readv_ranges.append((location, length))
842
680
        self._read_and_parse(readv_ranges)
843
 
        if self._nodes is not None:
844
 
            # The _read_and_parse triggered a _buffer_all, grab the data and
845
 
            # return it
846
 
            for location, key in pending_references:
847
 
                value, refs = self._nodes[key]
848
 
                result.append(((location, key), (self, key, value, refs)))
849
 
            return result
850
681
        for location, key in pending_references:
851
682
            # answer key references we had to look-up-late.
 
683
            index = self._parsed_key_index(key)
852
684
            value, refs = self._bisect_nodes[key]
853
685
            result.append(((location, key), (self, key,
854
686
                value, self._resolve_references(refs))))
1013
845
        # adjust offset and data to the parseable data.
1014
846
        trimmed_data = data[trim_start:trim_end]
1015
847
        if not (trimmed_data):
1016
 
            raise AssertionError('read unneeded data [%d:%d] from [%d:%d]'
 
848
            raise AssertionError('read unneeded data [%d:%d] from [%d:%d]' 
1017
849
                % (trim_start, trim_end, offset, offset + len(data)))
1018
850
        if trim_start:
1019
851
            offset += trim_start
1045
877
            elements = line.split('\0')
1046
878
            if len(elements) != self._expected_elements:
1047
879
                raise errors.BadIndexData(self)
1048
 
            # keys are tuples. Each element is a string that may occur many
1049
 
            # times, so we intern them to save space. AB, RC, 200807
1050
 
            key = tuple([intern(element) for element in elements[:self._key_length]])
 
880
            # keys are tuples
 
881
            key = tuple(elements[:self._key_length])
1051
882
            if first_key is None:
1052
883
                first_key = key
1053
884
            absent, references, value = elements[-3:]
1124
955
 
1125
956
        :param readv_ranges: A prepared readv range list.
1126
957
        """
1127
 
        if not readv_ranges:
1128
 
            return
1129
 
        if self._nodes is None and self._bytes_read * 2 >= self._size:
1130
 
            # We've already read more than 50% of the file and we are about to
1131
 
            # request more data, just _buffer_all() and be done
1132
 
            self._buffer_all()
1133
 
            return
1134
 
 
1135
 
        readv_data = self._transport.readv(self._name, readv_ranges, True,
1136
 
            self._size)
1137
 
        # parse
1138
 
        for offset, data in readv_data:
1139
 
            self._bytes_read += len(data)
1140
 
            if offset == 0 and len(data) == self._size:
1141
 
                # We read the whole range, most likely because the
1142
 
                # Transport upcast our readv ranges into one long request
1143
 
                # for enough total data to grab the whole index.
1144
 
                self._buffer_all(StringIO(data))
1145
 
                return
1146
 
            if self._bisect_nodes is None:
1147
 
                # this must be the start
1148
 
                if not (offset == 0):
1149
 
                    raise AssertionError()
1150
 
                offset, data = self._parse_header_from_bytes(data)
1151
 
            # print readv_ranges, "[%d:%d]" % (offset, offset + len(data))
1152
 
            self._parse_region(offset, data)
 
958
        if readv_ranges:
 
959
            readv_data = self._transport.readv(self._name, readv_ranges, True,
 
960
                self._size)
 
961
            # parse
 
962
            for offset, data in readv_data:
 
963
                if self._bisect_nodes is None:
 
964
                    # this must be the start
 
965
                    if not (offset == 0):
 
966
                        raise AssertionError()
 
967
                    offset, data = self._parse_header_from_bytes(data)
 
968
                # print readv_ranges, "[%d:%d]" % (offset, offset + len(data))
 
969
                self._parse_region(offset, data)
1153
970
 
1154
971
    def _signature(self):
1155
972
        """The file signature for this index type."""
1164
981
 
1165
982
class CombinedGraphIndex(object):
1166
983
    """A GraphIndex made up from smaller GraphIndices.
1167
 
 
 
984
    
1168
985
    The backing indices must implement GraphIndex, and are presumed to be
1169
986
    static data.
1170
987
 
1175
992
    in the index list.
1176
993
    """
1177
994
 
1178
 
    def __init__(self, indices, reload_func=None):
 
995
    def __init__(self, indices):
1179
996
        """Create a CombinedGraphIndex backed by indices.
1180
997
 
1181
998
        :param indices: An ordered list of indices to query for data.
1182
 
        :param reload_func: A function to call if we find we are missing an
1183
 
            index. Should have the form reload_func() => True/False to indicate
1184
 
            if reloading actually changed anything.
1185
999
        """
1186
1000
        self._indices = indices
1187
 
        self._reload_func = reload_func
1188
1001
 
1189
1002
    def __repr__(self):
1190
1003
        return "%s(%s)" % (
1191
1004
                self.__class__.__name__,
1192
1005
                ', '.join(map(repr, self._indices)))
1193
1006
 
 
1007
    @symbol_versioning.deprecated_method(symbol_versioning.one_one)
 
1008
    def get_parents(self, revision_ids):
 
1009
        """See graph._StackedParentsProvider.get_parents.
 
1010
        
 
1011
        This implementation thunks the graph.Graph.get_parents api across to
 
1012
        GraphIndex.
 
1013
 
 
1014
        :param revision_ids: An iterable of graph keys for this graph.
 
1015
        :return: A list of parent details for each key in revision_ids.
 
1016
            Each parent details will be one of:
 
1017
             * None when the key was missing
 
1018
             * (NULL_REVISION,) when the key has no parents.
 
1019
             * (parent_key, parent_key...) otherwise.
 
1020
        """
 
1021
        parent_map = self.get_parent_map(revision_ids)
 
1022
        return [parent_map.get(r, None) for r in revision_ids]
 
1023
 
1194
1024
    def get_parent_map(self, keys):
1195
1025
        """See graph._StackedParentsProvider.get_parent_map"""
1196
1026
        search_keys = set(keys)
1206
1036
            found_parents[key] = parents
1207
1037
        return found_parents
1208
1038
 
1209
 
    has_key = _has_key_from_parent_map
1210
 
 
1211
1039
    def insert_index(self, pos, index):
1212
1040
        """Insert a new index in the list of indices to query.
1213
1041
 
1227
1055
            the most efficient order for the index.
1228
1056
        """
1229
1057
        seen_keys = set()
1230
 
        while True:
1231
 
            try:
1232
 
                for index in self._indices:
1233
 
                    for node in index.iter_all_entries():
1234
 
                        if node[1] not in seen_keys:
1235
 
                            yield node
1236
 
                            seen_keys.add(node[1])
1237
 
                return
1238
 
            except errors.NoSuchFile:
1239
 
                self._reload_or_raise()
 
1058
        for index in self._indices:
 
1059
            for node in index.iter_all_entries():
 
1060
                if node[1] not in seen_keys:
 
1061
                    yield node
 
1062
                    seen_keys.add(node[1])
1240
1063
 
1241
1064
    def iter_entries(self, keys):
1242
1065
        """Iterate over keys within the index.
1250
1073
            efficient order for the index.
1251
1074
        """
1252
1075
        keys = set(keys)
1253
 
        while True:
1254
 
            try:
1255
 
                for index in self._indices:
1256
 
                    if not keys:
1257
 
                        return
1258
 
                    for node in index.iter_entries(keys):
1259
 
                        keys.remove(node[1])
1260
 
                        yield node
 
1076
        for index in self._indices:
 
1077
            if not keys:
1261
1078
                return
1262
 
            except errors.NoSuchFile:
1263
 
                self._reload_or_raise()
 
1079
            for node in index.iter_entries(keys):
 
1080
                keys.remove(node[1])
 
1081
                yield node
1264
1082
 
1265
1083
    def iter_entries_prefix(self, keys):
1266
1084
        """Iterate over keys within the index using prefix matching.
1286
1104
        if not keys:
1287
1105
            return
1288
1106
        seen_keys = set()
1289
 
        while True:
1290
 
            try:
1291
 
                for index in self._indices:
1292
 
                    for node in index.iter_entries_prefix(keys):
1293
 
                        if node[1] in seen_keys:
1294
 
                            continue
1295
 
                        seen_keys.add(node[1])
1296
 
                        yield node
1297
 
                return
1298
 
            except errors.NoSuchFile:
1299
 
                self._reload_or_raise()
 
1107
        for index in self._indices:
 
1108
            for node in index.iter_entries_prefix(keys):
 
1109
                if node[1] in seen_keys:
 
1110
                    continue
 
1111
                seen_keys.add(node[1])
 
1112
                yield node
1300
1113
 
1301
1114
    def key_count(self):
1302
1115
        """Return an estimate of the number of keys in this index.
1303
 
 
 
1116
        
1304
1117
        For CombinedGraphIndex this is approximated by the sum of the keys of
1305
1118
        the child indices. As child indices may have duplicate keys this can
1306
1119
        have a maximum error of the number of child indices * largest number of
1307
1120
        keys in any index.
1308
1121
        """
1309
 
        while True:
1310
 
            try:
1311
 
                return sum((index.key_count() for index in self._indices), 0)
1312
 
            except errors.NoSuchFile:
1313
 
                self._reload_or_raise()
1314
 
 
1315
 
    missing_keys = _missing_keys_from_parent_map
1316
 
 
1317
 
    def _reload_or_raise(self):
1318
 
        """We just got a NoSuchFile exception.
1319
 
 
1320
 
        Try to reload the indices, if it fails, just raise the current
1321
 
        exception.
1322
 
        """
1323
 
        if self._reload_func is None:
1324
 
            raise
1325
 
        exc_type, exc_value, exc_traceback = sys.exc_info()
1326
 
        trace.mutter('Trying to reload after getting exception: %s',
1327
 
                     exc_value)
1328
 
        if not self._reload_func():
1329
 
            # We tried to reload, but nothing changed, so we fail anyway
1330
 
            trace.mutter('_reload_func indicated nothing has changed.'
1331
 
                         ' Raising original exception.')
1332
 
            raise exc_type, exc_value, exc_traceback
 
1122
        return sum((index.key_count() for index in self._indices), 0)
1333
1123
 
1334
1124
    def validate(self):
1335
1125
        """Validate that everything in the index can be accessed."""
1336
 
        while True:
1337
 
            try:
1338
 
                for index in self._indices:
1339
 
                    index.validate()
1340
 
                return
1341
 
            except errors.NoSuchFile:
1342
 
                self._reload_or_raise()
 
1126
        for index in self._indices:
 
1127
            index.validate()
1343
1128
 
1344
1129
 
1345
1130
class InMemoryGraphIndex(GraphIndexBuilder):
1432
1217
                    raise errors.BadIndexKey(key)
1433
1218
                node = self._nodes[key]
1434
1219
                if node[0]:
1435
 
                    continue
 
1220
                    continue 
1436
1221
                if self.reference_lists:
1437
1222
                    yield self, key, node[2], node[1]
1438
1223
                else:
1439
1224
                    yield self, key, node[2]
1440
1225
            return
1441
 
        nodes_by_key = self._get_nodes_by_key()
1442
1226
        for key in keys:
1443
1227
            # sanity check
1444
1228
            if key[0] is None:
1446
1230
            if len(key) != self._key_length:
1447
1231
                raise errors.BadIndexKey(key)
1448
1232
            # find what it refers to:
1449
 
            key_dict = nodes_by_key
 
1233
            key_dict = self._nodes_by_key
1450
1234
            elements = list(key)
1451
1235
            # find the subdict to return
1452
1236
            try:
1463
1247
                    # can't be empty or would not exist
1464
1248
                    item, value = key_dict.iteritems().next()
1465
1249
                    if type(value) == dict:
1466
 
                        # push keys
 
1250
                        # push keys 
1467
1251
                        dicts.extend(key_dict.itervalues())
1468
1252
                    else:
1469
1253
                        # yield keys
1474
1258
 
1475
1259
    def key_count(self):
1476
1260
        """Return an estimate of the number of keys in this index.
1477
 
 
 
1261
        
1478
1262
        For InMemoryGraphIndex the estimate is exact.
1479
1263
        """
1480
1264
        return len(self._keys)
1488
1272
 
1489
1273
    Queries against this will emit queries against the adapted Graph with the
1490
1274
    prefix added, queries for all items use iter_entries_prefix. The returned
1491
 
    nodes will have their keys and node references adjusted to remove the
 
1275
    nodes will have their keys and node references adjusted to remove the 
1492
1276
    prefix. Finally, an add_nodes_callback can be supplied - when called the
1493
1277
    nodes and references being added will have prefix prepended.
1494
1278
    """
1521
1305
                    adjusted_references))
1522
1306
        except ValueError:
1523
1307
            # XXX: TODO add an explicit interface for getting the reference list
1524
 
            # status, to handle this bit of user-friendliness in the API more
 
1308
            # status, to handle this bit of user-friendliness in the API more 
1525
1309
            # explicitly.
1526
1310
            for (key, value) in nodes:
1527
1311
                translated_nodes.append((self.prefix + key, value))
1599
1383
 
1600
1384
    def key_count(self):
1601
1385
        """Return an estimate of the number of keys in this index.
1602
 
 
 
1386
        
1603
1387
        For GraphIndexPrefixAdapter this is relatively expensive - key
1604
1388
        iteration with the prefix is done.
1605
1389
        """