processors.pyx 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # cyextension/processors.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
  7. import datetime
  8. from datetime import datetime as datetime_cls
  9. from datetime import time as time_cls
  10. from datetime import date as date_cls
  11. import re
  12. from cpython.object cimport PyObject_Str
  13. from cpython.unicode cimport PyUnicode_AsASCIIString, PyUnicode_Check, PyUnicode_Decode
  14. from libc.stdio cimport sscanf
  15. def int_to_boolean(value):
  16. if value is None:
  17. return None
  18. return True if value else False
  19. def to_str(value):
  20. return PyObject_Str(value) if value is not None else None
  21. def to_float(value):
  22. return float(value) if value is not None else None
  23. cdef inline bytes to_bytes(object value, str type_name):
  24. try:
  25. return PyUnicode_AsASCIIString(value)
  26. except Exception as e:
  27. raise ValueError(
  28. f"Couldn't parse {type_name} string '{value!r}' "
  29. "- value is not a string."
  30. ) from e
  31. def str_to_datetime(value):
  32. if value is not None:
  33. value = datetime_cls.fromisoformat(value)
  34. return value
  35. def str_to_time(value):
  36. if value is not None:
  37. value = time_cls.fromisoformat(value)
  38. return value
  39. def str_to_date(value):
  40. if value is not None:
  41. value = date_cls.fromisoformat(value)
  42. return value
  43. cdef class DecimalResultProcessor:
  44. cdef object type_
  45. cdef str format_
  46. def __cinit__(self, type_, format_):
  47. self.type_ = type_
  48. self.format_ = format_
  49. def process(self, object value):
  50. if value is None:
  51. return None
  52. else:
  53. return self.type_(self.format_ % value)