|
| 1 | +"""Contains the MemoryDatabase implementation""" |
| 2 | +from loose import LooseObjectDB |
| 3 | +from base import ( |
| 4 | + ObjectDBR, |
| 5 | + ObjectDBW |
| 6 | + ) |
| 7 | + |
| 8 | +from gitdb.base import OStream |
| 9 | +from gitdb.util import to_bin_sha |
| 10 | +from gitdb.exc import ( |
| 11 | + BadObject, |
| 12 | + UnsupportedOperation |
| 13 | + ) |
| 14 | +from gitdb.stream import ( |
| 15 | + ZippedStoreShaWriter, |
| 16 | + DecompressMemMapReader, |
| 17 | + ) |
| 18 | + |
| 19 | +__all__ = ("MemoryDB", ) |
| 20 | + |
| 21 | +class MemoryDB(ObjectDBR, ObjectDBW): |
| 22 | + """A memory database stores everything to memory, providing fast IO and object |
| 23 | + retrieval. It should be used to buffer results and obtain SHAs before writing |
| 24 | + it to the actual physical storage, as it allows to query whether object already |
| 25 | + exists in the target storage before introducing actual IO |
| 26 | + |
| 27 | + :note: memory is currently not threadsafe, hence the async methods cannot be used |
| 28 | + for storing""" |
| 29 | + |
| 30 | + def __init__(self): |
| 31 | + super(MemoryDB, self).__init__() |
| 32 | + self._db = LooseObjectDB("path/doesnt/matter") |
| 33 | + |
| 34 | + # maps 20 byte shas to their OStream objects |
| 35 | + self._cache = dict() |
| 36 | + |
| 37 | + def set_ostream(self, stream): |
| 38 | + raise UnsupportedOperation("MemoryDB's always stream into memory") |
| 39 | + |
| 40 | + def store(self, istream): |
| 41 | + zstream = ZippedStoreShaWriter() |
| 42 | + self._db.set_ostream(zstream) |
| 43 | + |
| 44 | + istream = self._db.store(istream) |
| 45 | + zstream.close() # close to flush |
| 46 | + zstream.seek(0) |
| 47 | + |
| 48 | + # don't provide a size, the stream is written in object format, hence the |
| 49 | + # header needs decompression |
| 50 | + decomp_stream = DecompressMemMapReader(zstream.getvalue(), close_on_deletion=False) |
| 51 | + self._cache[istream.binsha] = OStream(istream.sha, istream.type, istream.size, decomp_stream) |
| 52 | + |
| 53 | + return istream |
| 54 | + |
| 55 | + def store_async(self, reader): |
| 56 | + raise UnsupportedOperation("MemoryDBs cannot currently be used for async write access") |
| 57 | + |
| 58 | + def has_object(self, sha): |
| 59 | + return to_bin_sha(sha) in self._cache |
| 60 | + |
| 61 | + def info(self, sha): |
| 62 | + # we always return streams, which are infos as well |
| 63 | + return self.stream(sha) |
| 64 | + |
| 65 | + def stream(self, sha): |
| 66 | + sha = to_bin_sha(sha) |
| 67 | + try: |
| 68 | + ostream = self._cache[sha] |
| 69 | + # rewind stream for the next one to read |
| 70 | + ostream.stream.seek(0) |
| 71 | + return ostream |
| 72 | + except KeyError: |
| 73 | + raise BadObject(sha) |
| 74 | + # END exception handling |
| 75 | + |
| 76 | + def size(self): |
| 77 | + return len(self._cache) |
| 78 | + |
| 79 | + def sha_iter(self): |
| 80 | + return self._cache.iterkeys() |
0 commit comments