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."""
19
__all__ = ['CombinedGraphIndex', 'GraphIndex', 'GraphIndexBuilder']
21
from cStringIO import StringIO
24
from bzrlib import errors
26
_OPTION_NODE_REFS = "node_ref_lists="
27
_SIGNATURE = "Bazaar Graph Index 1\n"
30
_whitespace_re = re.compile('[\t\n\x0b\x0c\r\x00 ]')
31
_newline_null_re = re.compile('[\n\0]')
34
class GraphIndexBuilder(object):
35
"""A builder that can build a GraphIndex.
37
The resulting graph has the structure:
39
_SIGNATURE OPTIONS NODES NEWLINE
40
_SIGNATURE := 'Bazaar Graph Index 1' NEWLINE
41
OPTIONS := 'node_ref_lists=' DIGITS NEWLINE
43
NODE := KEY NULL ABSENT? NULL REFERENCES NULL VALUE NEWLINE
44
KEY := Not-whitespace-utf8
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
50
VALUE := no-newline-no-null-bytes
53
def __init__(self, reference_lists=0):
54
"""Create a GraphIndex builder.
56
:param reference_lists: The number of node references lists for each
59
self.reference_lists = reference_lists
62
def add_node(self, key, references, value):
63
"""Add a node to the index.
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.
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)
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
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
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
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.
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
125
non_ref_bytes += len(ref_list) - 1
126
# how many digits are needed to represent the total byte count?
128
possible_total_bytes = non_ref_bytes + total_references*digits
129
while 10 ** digits < possible_total_bytes:
131
possible_total_bytes = non_ref_bytes + total_references*digits
132
# resolve 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.
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
151
# accrue reference separators
152
current_offset += len(ref_list) - 1
154
format_string = '%%0%sd' % digits
155
for key, (absent, references, value) in nodes:
156
flattened_references = []
157
for ref_list in references:
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))
165
return StringIO(''.join(lines))
168
class GraphIndex(object):
169
"""An index for data with embedded graphs.
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.
176
It is presumed that the index will not be mutated - it is static data.
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
184
def __init__(self, transport, name):
185
"""Open an index called name on transport.
187
:param transport: A bzrlib.transport.Transport.
188
:param name: A path to provide to transport API calls.
190
self._transport = transport
193
def iter_all_entries(self):
194
"""Iterate over all keys within the index.
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.
200
stream = self._transport.get(self._name)
201
self._read_prefix(stream)
203
self.keys_by_offset = {}
206
for line in stream.readlines():
210
key, absent, references, value = line[:-1].split('\0')
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
216
ref_lists = tuple(ref_lists)
217
self.keys_by_offset[pos] = (key, absent, ref_lists, value)
219
for key, absent, references, value in self.keys_by_offset.values():
222
# resolve references:
223
if self.node_ref_lists:
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)
230
yield (key, node_refs, value)
232
# there must be one line - the empty trailer line.
233
raise errors.BadIndexData(self)
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)
243
self.node_ref_lists = int(options_line[len(_OPTION_NODE_REFS):-1])
245
raise errors.BadIndexOptions(self)
247
def iter_entries(self, keys):
248
"""Iterate over keys within the index.
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.
256
for node in self.iter_all_entries():
260
def _signature(self):
261
"""The file signature for this index type."""
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():
271
class CombinedGraphIndex(object):
272
"""A GraphIndex made up from smaller GraphIndices.
274
The backing indices must implement GraphIndex, and are presumed to be
278
def __init__(self, indices):
279
"""Create a CombinedGraphIndex backed by indices.
281
:param indices: The indices to query for data.
283
self._indices = indices
285
def iter_all_entries(self):
286
"""Iterate over all keys within the index
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.
293
for index in self._indices:
294
for node in index.iter_all_entries():
295
if node[0] not in seen_keys:
297
seen_keys.add(node[0])
299
def iter_entries(self, keys):
300
"""Iterate over keys within the index.
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.
308
for node in self.iter_all_entries():
313
"""Validate that everything in the index can be accessed."""
314
for index in self._indices: