|
| 1 | +from itertools import chain, cycle, islice, repeat |
| 2 | +from mmap import mmap, ACCESS_READ |
| 3 | +from os import rename |
| 4 | +from os.path import getsize |
| 5 | + |
| 6 | +from .cdblib import Reader, Writer |
| 7 | + |
| 8 | + |
| 9 | +class error(IOError): |
| 10 | + pass |
| 11 | + |
| 12 | + |
| 13 | +class cdbmake: |
| 14 | + def __init__(self, cdb, tmp, encoding='utf-8'): |
| 15 | + """Create a new database to be stored at the path given by |
| 16 | + *cdb*. Records will be written to the file at the path given by |
| 17 | + *tmp*. After the ``finish()`` method is called, the file at *cdb* |
| 18 | + will be replaced by the one at *tmp*. |
| 19 | + If *encoding* is given, ``str`` keys and values will be converted |
| 20 | + to ``bytes`` with the given encoding. If *encoding* is ``None``, only |
| 21 | + ``bytes`` keys and values are accepted. |
| 22 | + """ |
| 23 | + self.fn = cdb |
| 24 | + self.fntmp = tmp |
| 25 | + self.encoding = encoding |
| 26 | + |
| 27 | + self._temp_obj = open(self.fntmp, 'wb') |
| 28 | + self._writer = Writer(self._temp_obj, strict=True) |
| 29 | + self.numentries = 0 |
| 30 | + self._finished = False |
| 31 | + |
| 32 | + def _cleanup(self): |
| 33 | + try: |
| 34 | + self._temp_obj.close() |
| 35 | + except Exception: |
| 36 | + pass |
| 37 | + |
| 38 | + def __del__(self): |
| 39 | + self._cleanup() |
| 40 | + |
| 41 | + def add(self, key, data): |
| 42 | + """Store a record in the database. |
| 43 | + """ |
| 44 | + if self._finished: |
| 45 | + raise error('cdbmake object already finished') |
| 46 | + |
| 47 | + args = [] |
| 48 | + for arg in (key, data): |
| 49 | + if isinstance(arg, bytes): |
| 50 | + args.append(arg) |
| 51 | + elif isinstance(arg, str) and self.encoding: |
| 52 | + args.append(arg.encode(self.encoding)) |
| 53 | + else: |
| 54 | + raise TypeError( |
| 55 | + 'add method only accepts bytes and str objects' |
| 56 | + ) |
| 57 | + |
| 58 | + self._writer.put(*args) |
| 59 | + self.numentries += 1 |
| 60 | + |
| 61 | + def addmany(self, items): |
| 62 | + """Store each of the records in *items* in the the database. |
| 63 | + *items* should be an iterable of ``(key, value)`` pairs. |
| 64 | + """ |
| 65 | + for key, value in items: |
| 66 | + self.add(key, value) |
| 67 | + |
| 68 | + @property |
| 69 | + def fd(self): |
| 70 | + return self._temp_obj.fileno() |
| 71 | + |
| 72 | + def finish(self): |
| 73 | + """Finalize the database being written to. Then move the temporary |
| 74 | + database to its final location. |
| 75 | + """ |
| 76 | + if self._finished: |
| 77 | + return |
| 78 | + |
| 79 | + self._writer.finalize() |
| 80 | + self._temp_obj.close() |
| 81 | + rename(self.fntmp, self.fn) |
| 82 | + self._finished = True |
| 83 | + |
| 84 | + |
| 85 | +class cdb: |
| 86 | + def __init__(self, f, encoding='utf-8'): |
| 87 | + self._file_path = f |
| 88 | + |
| 89 | + self.encoding = encoding |
| 90 | + strict = not bool(encoding) |
| 91 | + |
| 92 | + self._file_obj = open(self._file_path, mode='rb') |
| 93 | + self._mmap_obj = mmap(self._file_obj.fileno(), 0, access=ACCESS_READ) |
| 94 | + self._reader = Reader(self._mmap_obj, strict=strict) |
| 95 | + |
| 96 | + self._keys = self._get_key_iterator() |
| 97 | + self._items = cycle(chain(self._decoded_items(), [None])) |
| 98 | + |
| 99 | + def _cleanup(self): |
| 100 | + for f in (self._mmap_obj, self._file_obj): |
| 101 | + try: |
| 102 | + f.close() |
| 103 | + except Exception: |
| 104 | + pass |
| 105 | + |
| 106 | + def __del__(self): |
| 107 | + self._cleanup() |
| 108 | + |
| 109 | + def _unique_keys(self): |
| 110 | + all_keys = (k for k, v in self._decoded_items()) |
| 111 | + seen = set() |
| 112 | + seen_add = seen.add |
| 113 | + for k in all_keys: |
| 114 | + if k not in seen: |
| 115 | + seen_add(k) |
| 116 | + yield k |
| 117 | + |
| 118 | + def _decoded_items(self): |
| 119 | + for pair in self._reader.iteritems(): |
| 120 | + if not self.encoding: |
| 121 | + yield pair |
| 122 | + else: |
| 123 | + decoded_pair = [] |
| 124 | + for e in pair: |
| 125 | + try: |
| 126 | + e = e.decode(self.encoding) |
| 127 | + except UnicodeDecodeError: |
| 128 | + pass |
| 129 | + decoded_pair.append(e) |
| 130 | + |
| 131 | + yield tuple(decoded_pair) |
| 132 | + |
| 133 | + def _get_key_iterator(self): |
| 134 | + unique_keys = self._unique_keys() |
| 135 | + return cycle(chain(unique_keys, repeat(None))) |
| 136 | + |
| 137 | + def each(self): |
| 138 | + """Return successive ``(key, value)`` tuples from the database. |
| 139 | + After the last record is returned, the next call will return ``None``. |
| 140 | + The call after that will return the first record again. |
| 141 | + """ |
| 142 | + return next(self._items) |
| 143 | + |
| 144 | + @property |
| 145 | + def fd(self): |
| 146 | + return self._file_obj.fileno() |
| 147 | + |
| 148 | + def firstkey(self): |
| 149 | + """Return the first key in the database. |
| 150 | + If ``nextkey()`` is called after ``firstkey()``, the second key will |
| 151 | + returned. |
| 152 | + """ |
| 153 | + self._keys = self._get_key_iterator() |
| 154 | + return next(self._keys) |
| 155 | + |
| 156 | + def get(self, k, i=0): |
| 157 | + """Return the ``i``-th value stored under the key given by ``k``. |
| 158 | + If there are fewer than ``i`` items stored under key ``k``, return |
| 159 | + ``None``. |
| 160 | + """ |
| 161 | + value = next(islice(self._reader.gets(k), i, i + 1), None) |
| 162 | + if not self.encoding: |
| 163 | + return value |
| 164 | + |
| 165 | + try: |
| 166 | + return value.decode(self.encoding) |
| 167 | + except (AttributeError, UnicodeDecodeError): |
| 168 | + return value |
| 169 | + |
| 170 | + def __getitem__(self, key): |
| 171 | + value = self.get(key) |
| 172 | + if value is None: |
| 173 | + raise KeyError(key) |
| 174 | + |
| 175 | + return value |
| 176 | + |
| 177 | + def getall(self, k): |
| 178 | + """Return a list of the values stored under key ``k``. |
| 179 | + """ |
| 180 | + ret = [] |
| 181 | + ret_append = ret.append |
| 182 | + for value in self._reader.gets(k): |
| 183 | + try: |
| 184 | + value = value.decode(self.encoding) |
| 185 | + except (AttributeError, UnicodeDecodeError, TypeError): |
| 186 | + value = value |
| 187 | + ret_append(value) |
| 188 | + |
| 189 | + return ret |
| 190 | + |
| 191 | + def keys(self): |
| 192 | + """Return a list of the distinct keys stored in the database. |
| 193 | + """ |
| 194 | + unique_keys = self._unique_keys() |
| 195 | + return list(unique_keys) |
| 196 | + |
| 197 | + @property |
| 198 | + def name(self): |
| 199 | + return self._file_path |
| 200 | + |
| 201 | + def nextkey(self): |
| 202 | + """Return the next key in the datbase, or ``None`` if there are no more |
| 203 | + keys to retrieve. Call ``firstkey()`` to start from the beginning |
| 204 | + again. |
| 205 | + """ |
| 206 | + |
| 207 | + return next(self._keys) |
| 208 | + |
| 209 | + @property |
| 210 | + def size(self): |
| 211 | + return getsize(self._file_path) |
| 212 | + |
| 213 | + |
| 214 | +def init(f, encoding='utf-8'): |
| 215 | + """Return a ``cdb`` object based on the database stored at the file path |
| 216 | + given by *f*. |
| 217 | + If *encoding* is given, retrieved keys and values will be decoded using |
| 218 | + the given encoding (if possible). |
| 219 | + """ |
| 220 | + return cdb(f, encoding=encoding) |
0 commit comments