codekingpro/portable-devtools
115k
1# sql/_py_util.py
2# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3# <see AUTHORS file>
4#
5# This module is part of SQLAlchemy and is released under
6# the MIT License: https://www.opensource.org/licenses/mit-license.php
7
8from __future__ import annotations
9
10import typing
11from typing import Any
12from typing import Dict
13from typing import Tuple
14from typing import Union
15
16from ..util.typing import Literal
17
18if typing.TYPE_CHECKING:
19 from .cache_key import CacheConst
20
21
22class prefix_anon_map(Dict[str, str]):
23 """A map that creates new keys for missing key access.
24
25 Considers keys of the form "<ident> <name>" to produce
26 new symbols "<name>_<index>", where "index" is an incrementing integer
27 corresponding to <name>.
28
29 Inlines the approach taken by :class:`sqlalchemy.util.PopulateDict` which
30 is otherwise usually used for this type of operation.
31
32 """
33
34 def __missing__(self, key: str) -> str:
35 (ident, derived) = key.split(" ", 1)
36 anonymous_counter = self.get(derived, 1)
37 self[derived] = anonymous_counter + 1 # type: ignore
38 value = f"{derived}_{anonymous_counter}"
39 self[key] = value
40 return value
41
42
43class cache_anon_map(
44 Dict[Union[int, "Literal[CacheConst.NO_CACHE]"], Union[Literal[True], str]]
45):
46 """A map that creates new keys for missing key access.
47
48 Produces an incrementing sequence given a series of unique keys.
49
50 This is similar to the compiler prefix_anon_map class although simpler.
51
52 Inlines the approach taken by :class:`sqlalchemy.util.PopulateDict` which
53 is otherwise usually used for this type of operation.
54
55 """
56
57 _index = 0
58
59 def get_anon(self, object_: Any) -> Tuple[str, bool]:
60 idself = id(object_)
61 if idself in self:
62 s_val = self[idself]
63 assert s_val is not True
64 return s_val, True
65 else:
66 # inline of __missing__
67 self[idself] = id_ = str(self._index)
68 self._index += 1
69
70 return id_, False
71
72 def __missing__(self, key: int) -> str:
73 self[key] = val = str(self._index)
74 self._index += 1
75 return val
76 