1# engine/util.py
2# Copyright (C) 2005-2021 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: http://www.opensource.org/licenses/mit-license.php
7
8from .. import util
9
10
11def connection_memoize(key):
12 """Decorator, memoize a function in a connection.info stash.
13
14 Only applicable to functions which take no arguments other than a
15 connection. The memo will be stored in ``connection.info[key]``.
16 """
17
18 @util.decorator
19 def decorated(fn, self, connection):
20 connection = connection.connect()
21 try:
22 return connection.info[key]
23 except KeyError:
24 connection.info[key] = val = fn(self, connection)
25 return val
26
27 return decorated
28
29
30def py_fallback():
31 def _distill_params(multiparams, params): # noqa
32 r"""Given arguments from the calling form \*multiparams, \**params,
33 return a list of bind parameter structures, usually a list of
34 dictionaries.
35
36 In the case of 'raw' execution which accepts positional parameters,
37 it may be a list of tuples or lists.
38
39 """
40
41 if not multiparams:
42 if params:
43 return [params]
44 else:
45 return []
46 elif len(multiparams) == 1:
47 zero = multiparams[0]
48 if isinstance(zero, (list, tuple)):
49 if (
50 not zero
51 or hasattr(zero[0], "__iter__")
52 and not hasattr(zero[0], "strip")
53 ):
54 # execute(stmt, [{}, {}, {}, ...])
55 # execute(stmt, [(), (), (), ...])
56 return zero
57 else:
58 # execute(stmt, ("value", "value"))
59 return [zero]
60 elif hasattr(zero, "keys"):
61 # execute(stmt, {"key":"value"})
62 return [zero]
63 else:
64 # execute(stmt, "value")
65 return [[zero]]
66 else:
67 if hasattr(multiparams[0], "__iter__") and not hasattr(
68 multiparams[0], "strip"
69 ):
70 return multiparams
71 else:
72 return [multiparams]
73
74 return locals()
75
76
77try:
78 from sqlalchemy.cutils import _distill_params # noqa
79except ImportError:
80 globals().update(py_fallback())