Hi/Lo algorithm
≈ 2 min read
Names in other languages
No names in other languages are held for this entry yet.
Article bodies are English and are not machine-translated. A name in another language is not a translation of the article.
Hi/Lo is an algorithm and a key generation strategy used for generating unique keys for use in a database as a primary key. It uses a sequence-based hi-lo pattern to generate values. Hi/Lo is used in scenarios where an application needs its entities to have an identity prior to persistence. It is a value generation strategy. An alternative to Hi/Lo would be for the application to generate keys as universally unique identifiers (UUID).
Hi/Lo is an algorithm and a key generation strategy used for generating unique keys for use in a database as a primary key. It uses a sequence-based hi-lo pattern to generate values. Hi/Lo is used in scenarios where an application needs its entities to have an identity prior to persistence. It is a value generation strategy. An alternative to Hi/Lo would be for the application to generate keys as universally unique identifiers (UUID). current_hi := get_next_hi() current_lo := 0 key := current_hi × max_lo + current_lo current_lo := current_lo + 1 return key class HiloKeyGenerator: """Key generator that uses a Hi/Lo algorithm. Args: get_next_hi: A callable function that retrieves a new high value. max_lo: The maximum low value. Defaults to 1000. Raises: ValueError: If the value of max_lo is not greater than zero. """ def __init__(self, get_next_hi: Callable[[], int], max_lo: int = 1000) -> None: if max_lo int: """Generate a new unique key.""" if self._current_lo >= self._max_lo: self._current_hi = self._get_next_hi() self._current_lo = 0 key = self._current_hi * self._max_lo + self._current_lo self._current_lo += 1 return key Output: >>> def get_next_hi(): ... return 2 # From database server. ... >>> generator = HiloKeyGenerator(get_next_hi) >>> generator.generate_key() 2000 >>> generator.generate_key() 2001 >>> generator.generate_key() 2002
Text derived from https://en.wikipedia.org/w/index.php?oldid=1331627826 under CC BY-SA 4.0; modifications have been made.