util.py 2.4 KB

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