/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/index.py

  • Committer: Robert Collins
  • Date: 2007-07-13 16:35:54 UTC
  • mto: (2592.3.3 repository)
  • mto: This revision was merged to the branch mainline in revision 2624.
  • Revision ID: robertc@robertcollins.net-20070713163554-ok2qtnzv6rcbpt3z
Change the missing key interface in index operations to not raise, allowing callers to set policy.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2007 Canonical Ltd
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
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
 
16
 
 
17
"""Indexing facilities."""
 
18
 
 
19
__all__ = ['CombinedGraphIndex', 'GraphIndex', 'GraphIndexBuilder']
 
20
 
 
21
from cStringIO import StringIO
 
22
import re
 
23
 
 
24
from bzrlib import errors
 
25
 
 
26
_OPTION_NODE_REFS = "node_ref_lists="
 
27
_SIGNATURE = "Bazaar Graph Index 1\n"
 
28
 
 
29
 
 
30
_whitespace_re = re.compile('[\t\n\x0b\x0c\r\x00 ]')
 
31
_newline_null_re = re.compile('[\n\0]')
 
32
 
 
33
 
 
34
class GraphIndexBuilder(object):
 
35
    """A builder that can build a GraphIndex.
 
36
    
 
37
    The resulting graph has the structure:
 
38
    
 
39
    _SIGNATURE OPTIONS NODES NEWLINE
 
40
    _SIGNATURE     := 'Bazaar Graph Index 1' NEWLINE
 
41
    OPTIONS        := 'node_ref_lists=' DIGITS NEWLINE
 
42
    NODES          := NODE*
 
43
    NODE           := KEY NULL ABSENT? NULL REFERENCES NULL VALUE NEWLINE
 
44
    KEY            := Not-whitespace-utf8
 
45
    ABSENT         := 'a'
 
46
    REFERENCES     := REFERENCE_LIST (TAB REFERENCE_LIST){node_ref_lists - 1}
 
47
    REFERENCE_LIST := (REFERENCE (CR REFERENCE)*)?
 
48
    REFERENCE      := DIGITS  ; digits is the byte offset in the index of the
 
49
                              ; referenced key.
 
50
    VALUE          := no-newline-no-null-bytes
 
51
    """
 
52
 
 
53
    def __init__(self, reference_lists=0):
 
54
        """Create a GraphIndex builder.
 
55
 
 
56
        :param reference_lists: The number of node references lists for each
 
57
            entry.
 
58
        """
 
59
        self.reference_lists = reference_lists
 
60
        self._nodes = {}
 
61
 
 
62
    def add_node(self, key, references, value):
 
63
        """Add a node to the index.
 
64
 
 
65
        :param key: The key. keys must be whitespace free utf8.
 
66
        :param references: An iterable of iterables of keys. Each is a
 
67
            reference to another key.
 
68
        :param value: The value to associate with the key. It may be any
 
69
            bytes as long as it does not contain \0 or \n.
 
70
        """
 
71
        if not key or _whitespace_re.search(key) is not None:
 
72
            raise errors.BadIndexKey(key)
 
73
        if _newline_null_re.search(value) is not None:
 
74
            raise errors.BadIndexValue(value)
 
75
        if len(references) != self.reference_lists:
 
76
            raise errors.BadIndexValue(references)
 
77
        for reference_list in references:
 
78
            for reference in reference_list:
 
79
                if _whitespace_re.search(reference) is not None:
 
80
                    raise errors.BadIndexKey(reference)
 
81
                if reference not in self._nodes:
 
82
                    self._nodes[reference] = ('a', [], '')
 
83
        if key in self._nodes and self._nodes[key][0] == '':
 
84
            raise errors.BadIndexDuplicateKey(key, self)
 
85
        self._nodes[key] = ('', references, value)
 
86
 
 
87
    def finish(self):
 
88
        lines = [_SIGNATURE]
 
89
        lines.append(_OPTION_NODE_REFS + str(self.reference_lists) + '\n')
 
90
        prefix_length = len(lines[0]) + len(lines[1])
 
91
        # references are byte offsets. To avoid having to do nasty
 
92
        # polynomial work to resolve offsets (references to later in the 
 
93
        # file cannot be determined until all the inbetween references have
 
94
        # been calculated too) we pad the offsets with 0's to make them be
 
95
        # of consistent length. Using binary offsets would break the trivial
 
96
        # file parsing.
 
97
        # to calculate the width of zero's needed we do three passes:
 
98
        # one to gather all the non-reference data and the number of references.
 
99
        # one to pad all the data with reference-length and determine entry
 
100
        # addresses.
 
101
        # One to serialise.
 
102
        nodes = sorted(self._nodes.items(),reverse=True)
 
103
        # we only need to pre-pass if we have reference lists at all.
 
104
        if self.reference_lists:
 
105
            non_ref_bytes = prefix_length
 
106
            total_references = 0
 
107
            # TODO use simple multiplication for the constants in this loop.
 
108
            # TODO: factor out the node length calculations so this loop 
 
109
            #       and the next have less (no!) duplicate code.
 
110
            for key, (absent, references, value) in nodes:
 
111
                # key is literal, value is literal, there are 3 null's, 1 NL
 
112
                non_ref_bytes += len(key) + len(value) + 3 + 1
 
113
                # one byte for absent if set.
 
114
                if absent:
 
115
                    non_ref_bytes += 1
 
116
                if self.reference_lists:
 
117
                    # (ref_lists -1) tabs
 
118
                    non_ref_bytes += self.reference_lists - 1
 
119
                    # (ref-1 cr's per ref_list)
 
120
                    for ref_list in references:
 
121
                        # how many references across the whole file?
 
122
                        total_references += len(ref_list)
 
123
                        # accrue reference separators
 
124
                        if ref_list:
 
125
                            non_ref_bytes += len(ref_list) - 1
 
126
            # how many digits are needed to represent the total byte count?
 
127
            digits = 1
 
128
            possible_total_bytes = non_ref_bytes + total_references*digits
 
129
            while 10 ** digits < possible_total_bytes:
 
130
                digits += 1
 
131
                possible_total_bytes = non_ref_bytes + total_references*digits
 
132
            # resolve key addresses.
 
133
            key_addresses = {}
 
134
            current_offset = prefix_length
 
135
            for key, (absent, references, value) in nodes:
 
136
                key_addresses[key] = current_offset
 
137
                # key is literal, value is literal, there are 3 null's, 1 NL
 
138
                current_offset += len(key) + len(value) + 3 + 1
 
139
                # one byte for absent if set.
 
140
                if absent:
 
141
                    current_offset+= 1
 
142
                if self.reference_lists:
 
143
                    # (ref_lists -1) tabs
 
144
                    current_offset += self.reference_lists - 1
 
145
                    # (ref-1 cr's per ref_list)
 
146
                    for ref_list in references:
 
147
                        # accrue reference bytes
 
148
                        current_offset += digits * len(ref_list)
 
149
                        # accrue reference separators
 
150
                        if ref_list:
 
151
                            # accrue reference separators
 
152
                            current_offset += len(ref_list) - 1
 
153
            # serialise
 
154
            format_string = '%%0%sd' % digits
 
155
        for key, (absent, references, value) in nodes:
 
156
            flattened_references = []
 
157
            for ref_list in references:
 
158
                ref_addresses = []
 
159
                for reference in ref_list:
 
160
                    ref_addresses.append(format_string % key_addresses[reference])
 
161
                flattened_references.append('\r'.join(ref_addresses))
 
162
            lines.append("%s\0%s\0%s\0%s\n" % (key, absent,
 
163
                '\t'.join(flattened_references), value))
 
164
        lines.append('\n')
 
165
        return StringIO(''.join(lines))
 
166
 
 
167
 
 
168
class GraphIndex(object):
 
169
    """An index for data with embedded graphs.
 
170
 
 
171
    The index maps keys to a list of key reference lists, and a value.
 
172
    Each node has the same number of key reference lists. Each key reference
 
173
    list can be empty or an arbitrary length. The value is an opaque NULL
 
174
    terminated string without any newlines.
 
175
 
 
176
    It is presumed that the index will not be mutated - it is static data.
 
177
 
 
178
    Currently successive iter_entries/iter_all_entries calls will read the
 
179
    entire index each time. Additionally iter_entries calls will read the
 
180
    entire index always. XXX: This must be fixed before the index is 
 
181
    suitable for production use. :XXX
 
182
    """
 
183
 
 
184
    def __init__(self, transport, name):
 
185
        """Open an index called name on transport.
 
186
 
 
187
        :param transport: A bzrlib.transport.Transport.
 
188
        :param name: A path to provide to transport API calls.
 
189
        """
 
190
        self._transport = transport
 
191
        self._name = name
 
192
 
 
193
    def iter_all_entries(self):
 
194
        """Iterate over all keys within the index.
 
195
 
 
196
        :return: An iterable of (key, reference_lists, value). There is no
 
197
            defined order for the result iteration - it will be in the most
 
198
            efficient order for the index.
 
199
        """
 
200
        stream = self._transport.get(self._name)
 
201
        self._read_prefix(stream)
 
202
        line_count = 0
 
203
        self.keys_by_offset = {}
 
204
        trailers = 0
 
205
        pos = stream.tell()
 
206
        for line in stream.readlines():
 
207
            if line == '\n':
 
208
                trailers += 1
 
209
                continue
 
210
            key, absent, references, value = line[:-1].split('\0')
 
211
            ref_lists = []
 
212
            for ref_string in references.split('\t'):
 
213
                ref_lists.append(tuple([
 
214
                    int(ref) for ref in ref_string.split('\r') if ref
 
215
                    ]))
 
216
            ref_lists = tuple(ref_lists)
 
217
            self.keys_by_offset[pos] = (key, absent, ref_lists, value)
 
218
            pos += len(line)
 
219
        for key, absent, references, value in self.keys_by_offset.values():
 
220
            if absent:
 
221
                continue
 
222
            # resolve references:
 
223
            if self.node_ref_lists:
 
224
                node_refs = []
 
225
                for ref_list in references:
 
226
                    node_refs.append(tuple([self.keys_by_offset[ref][0] for ref in ref_list]))
 
227
                node_refs = tuple(node_refs)
 
228
            else:
 
229
                node_refs = ()
 
230
            yield (key, node_refs, value)
 
231
        if trailers != 1:
 
232
            # there must be one line - the empty trailer line.
 
233
            raise errors.BadIndexData(self)
 
234
 
 
235
    def _read_prefix(self, stream):
 
236
        signature = stream.read(len(self._signature()))
 
237
        if not signature == self._signature():
 
238
            raise errors.BadIndexFormatSignature(self._name, GraphIndex)
 
239
        options_line = stream.readline()
 
240
        if not options_line.startswith(_OPTION_NODE_REFS):
 
241
            raise errors.BadIndexOptions(self)
 
242
        try:
 
243
            self.node_ref_lists = int(options_line[len(_OPTION_NODE_REFS):-1])
 
244
        except ValueError:
 
245
            raise errors.BadIndexOptions(self)
 
246
 
 
247
    def iter_entries(self, keys):
 
248
        """Iterate over keys within the index.
 
249
 
 
250
        :param keys: An iterable providing the keys to be retrieved.
 
251
        :return: An iterable of (key, reference_lists, value). There is no
 
252
            defined order for the result iteration - it will be in the most
 
253
            efficient order for the index.
 
254
        """
 
255
        keys = set(keys)
 
256
        for node in self.iter_all_entries():
 
257
            if node[0] in keys:
 
258
                yield node
 
259
 
 
260
    def _signature(self):
 
261
        """The file signature for this index type."""
 
262
        return _SIGNATURE
 
263
 
 
264
    def validate(self):
 
265
        """Validate that everything in the index can be accessed."""
 
266
        # iter_all validates completely at the moment, so just do that.
 
267
        for node in self.iter_all_entries():
 
268
            pass
 
269
 
 
270
 
 
271
class CombinedGraphIndex(object):
 
272
    """A GraphIndex made up from smaller GraphIndices.
 
273
    
 
274
    The backing indices must implement GraphIndex, and are presumed to be
 
275
    static data.
 
276
    """
 
277
 
 
278
    def __init__(self, indices):
 
279
        """Create a CombinedGraphIndex backed by indices.
 
280
 
 
281
        :param indices: The indices to query for data.
 
282
        """
 
283
        self._indices = indices
 
284
        
 
285
    def iter_all_entries(self):
 
286
        """Iterate over all keys within the index
 
287
 
 
288
        :return: An iterable of (key, reference_lists, value). There is no
 
289
            defined order for the result iteration - it will be in the most
 
290
            efficient order for the index.
 
291
        """
 
292
        seen_keys = set()
 
293
        for index in self._indices:
 
294
            for node in index.iter_all_entries():
 
295
                if node[0] not in seen_keys:
 
296
                    yield node
 
297
                    seen_keys.add(node[0])
 
298
 
 
299
    def iter_entries(self, keys):
 
300
        """Iterate over keys within the index.
 
301
 
 
302
        :param keys: An iterable providing the keys to be retrieved.
 
303
        :return: An iterable of (key, reference_lists, value). There is no
 
304
            defined order for the result iteration - it will be in the most
 
305
            efficient order for the index.
 
306
        """
 
307
        keys = set(keys)
 
308
        for node in self.iter_all_entries():
 
309
            if node[0] in keys:
 
310
                yield node
 
311
 
 
312
    def validate(self):
 
313
        """Validate that everything in the index can be accessed."""
 
314
        for index in self._indices:
 
315
            index.validate()