MCPcopy Create free account
hub / github.com/MagicStack/asyncpg / _StatementCache

Class _StatementCache

asyncpg/connection.py:2535–2673  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

2533
2534
2535class _StatementCache:
2536
2537 __slots__ = ('_loop', '_entries', '_max_size', '_on_remove',
2538 '_max_lifetime')
2539
2540 def __init__(self, *, loop, max_size, on_remove, max_lifetime):
2541 self._loop = loop
2542 self._max_size = max_size
2543 self._on_remove = on_remove
2544 self._max_lifetime = max_lifetime
2545
2546 # We use an OrderedDict for LRU implementation. Operations:
2547 #
2548 # * We use a simple `__setitem__` to push a new entry:
2549 # `entries[key] = new_entry`
2550 # That will push `new_entry` to the *end* of the entries dict.
2551 #
2552 # * When we have a cache hit, we call
2553 # `entries.move_to_end(key, last=True)`
2554 # to move the entry to the *end* of the entries dict.
2555 #
2556 # * When we need to remove entries to maintain `max_size`, we call
2557 # `entries.popitem(last=False)`
2558 # to remove an entry from the *beginning* of the entries dict.
2559 #
2560 # So new entries and hits are always promoted to the end of the
2561 # entries dict, whereas the unused one will group in the
2562 # beginning of it.
2563 self._entries = collections.OrderedDict()
2564
2565 def __len__(self):
2566 return len(self._entries)
2567
2568 def get_max_size(self):
2569 return self._max_size
2570
2571 def set_max_size(self, new_size):
2572 assert new_size >= 0
2573 self._max_size = new_size
2574 self._maybe_cleanup()
2575
2576 def get_max_lifetime(self):
2577 return self._max_lifetime
2578
2579 def set_max_lifetime(self, new_lifetime):
2580 assert new_lifetime >= 0
2581 self._max_lifetime = new_lifetime
2582 for entry in self._entries.values():
2583 # For every entry cancel the existing callback
2584 # and setup a new one if necessary.
2585 self._set_entry_timeout(entry)
2586
2587 def get(self, query, *, promote=True):
2588 if not self._max_size:
2589 # The cache is disabled.
2590 return
2591
2592 entry = self._entries.get(query) # type: _StatementCacheEntry

Callers 1

__init__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected