codekingpro/portable-devtools
114k
1# cyextension/util.pyx
2# Copyright (C) 2005-2024 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
7from collections.abc import Mapping
8
9from sqlalchemy import exc
10
11cdef tuple _Empty_Tuple = ()
12
13cdef inline bint _is_mapping_or_tuple(object value):
14 return isinstance(value, dict) or isinstance(value, tuple) or isinstance(value, Mapping)
15
16
17cdef inline bint _is_mapping(object value):
18 return isinstance(value, dict) or isinstance(value, Mapping)
19
20
21def _distill_params_20(object params):
22 if params is None:
23 return _Empty_Tuple
24 elif isinstance(params, list) or isinstance(params, tuple):
25 if params and not _is_mapping(params[0]):
26 raise exc.ArgumentError(
27 "List argument must consist only of dictionaries"
28 )
29 return params
30 elif _is_mapping(params):
31 return [params]
32 else:
33 raise exc.ArgumentError("mapping or list expected for parameters")
34
35
36def _distill_raw_params(object params):
37 if params is None:
38 return _Empty_Tuple
39 elif isinstance(params, list):
40 if params and not _is_mapping_or_tuple(params[0]):
41 raise exc.ArgumentError(
42 "List argument must consist only of tuples or dictionaries"
43 )
44 return params
45 elif _is_mapping_or_tuple(params):
46 return [params]
47 else:
48 raise exc.ArgumentError("mapping or sequence expected for parameters")
49
50cdef class prefix_anon_map(dict):
51 def __missing__(self, str key):
52 cdef str derived
53 cdef int anonymous_counter
54 cdef dict self_dict = self
55
56 derived = key.split(" ", 1)[1]
57
58 anonymous_counter = self_dict.get(derived, 1)
59 self_dict[derived] = anonymous_counter + 1
60 value = f"{derived}_{anonymous_counter}"
61 self_dict[key] = value
62 return value
63
64
65cdef class cache_anon_map(dict):
66 cdef int _index
67
68 def __init__(self):
69 self._index = 0
70
71 def get_anon(self, obj):
72 cdef long long idself
73 cdef str id_
74 cdef dict self_dict = self
75
76 idself = id(obj)
77 if idself in self_dict:
78 return self_dict[idself], True
79 else:
80 id_ = self.__missing__(idself)
81 return id_, False
82
83 def __missing__(self, key):
84 cdef str val
85 cdef dict self_dict = self
86
87 self_dict[key] = val = str(self._index)
88 self._index += 1
89 return val
90
91 