converters.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. """MySQLdb type conversion module
  2. This module handles all the type conversions for MySQL. If the default
  3. type conversions aren't what you need, you can make your own. The
  4. dictionary conversions maps some kind of type to a conversion function
  5. which returns the corresponding value:
  6. Key: FIELD_TYPE.* (from MySQLdb.constants)
  7. Conversion function:
  8. Arguments: string
  9. Returns: Python object
  10. Key: Python type object (from types) or class
  11. Conversion function:
  12. Arguments: Python object of indicated type or class AND
  13. conversion dictionary
  14. Returns: SQL literal value
  15. Notes: Most conversion functions can ignore the dictionary, but
  16. it is a required parameter. It is necessary for converting
  17. things like sequences and instances.
  18. Don't modify conversions if you can avoid it. Instead, make copies
  19. (with the copy() method), modify the copies, and then pass them to
  20. MySQL.connect().
  21. """
  22. from _mysql import string_literal, escape_sequence, escape_dict, escape, NULL
  23. from MySQLdb.constants import FIELD_TYPE, FLAG
  24. from MySQLdb.times import *
  25. try:
  26. from types import IntType, LongType, FloatType, NoneType, TupleType, ListType, DictType, InstanceType, \
  27. StringType, UnicodeType, ObjectType, BooleanType, ClassType, TypeType
  28. except ImportError:
  29. # Python 3
  30. long = int
  31. IntType, LongType, FloatType, NoneType = int, long, float, type(None)
  32. TupleType, ListType, DictType, InstanceType = tuple, list, dict, None
  33. StringType, UnicodeType, ObjectType, BooleanType = bytes, str, object, bool
  34. import array
  35. try:
  36. ArrayType = array.ArrayType
  37. except AttributeError:
  38. ArrayType = array.array
  39. try:
  40. set
  41. except NameError:
  42. from sets import Set as set
  43. def Bool2Str(s, d): return str(int(s))
  44. def Str2Set(s):
  45. return set([ i for i in s.split(',') if i ])
  46. def Set2Str(s, d):
  47. return string_literal(','.join(s), d)
  48. def Thing2Str(s, d):
  49. """Convert something into a string via str()."""
  50. return str(s)
  51. def Unicode2Str(s, d):
  52. """Convert a unicode object to a string using the default encoding.
  53. This is only used as a placeholder for the real function, which
  54. is connection-dependent."""
  55. return s.encode()
  56. Long2Int = Thing2Str
  57. def Float2Str(o, d):
  58. return '%.15g' % o
  59. def None2NULL(o, d):
  60. """Convert None to NULL."""
  61. return NULL # duh
  62. def Thing2Literal(o, d):
  63. """Convert something into a SQL string literal. If using
  64. MySQL-3.23 or newer, string_literal() is a method of the
  65. _mysql.MYSQL object, and this function will be overridden with
  66. that method when the connection is created."""
  67. return string_literal(o, d)
  68. def Instance2Str(o, d):
  69. """
  70. Convert an Instance to a string representation. If the __str__()
  71. method produces acceptable output, then you don't need to add the
  72. class to conversions; it will be handled by the default
  73. converter. If the exact class is not found in d, it will use the
  74. first class it can find for which o is an instance.
  75. """
  76. if o.__class__ in d:
  77. return d[o.__class__](o, d)
  78. cl = filter(lambda x,o=o:
  79. type(x) is ClassType
  80. and isinstance(o, x), d.keys())
  81. if not cl:
  82. cl = filter(lambda x,o=o:
  83. type(x) is TypeType
  84. and isinstance(o, x)
  85. and d[x] is not Instance2Str,
  86. d.keys())
  87. if not cl:
  88. return d[StringType](o,d)
  89. d[o.__class__] = d[cl[0]]
  90. return d[cl[0]](o, d)
  91. def char_array(s):
  92. return array.array('c', s)
  93. def array2Str(o, d):
  94. return Thing2Literal(o.tostring(), d)
  95. def quote_tuple(t, d):
  96. return "(%s)" % (','.join(escape_sequence(t, d)))
  97. conversions = {
  98. IntType: Thing2Str,
  99. LongType: Long2Int,
  100. FloatType: Float2Str,
  101. NoneType: None2NULL,
  102. TupleType: quote_tuple,
  103. ListType: quote_tuple,
  104. DictType: escape_dict,
  105. InstanceType: Instance2Str,
  106. ArrayType: array2Str,
  107. StringType: Thing2Literal, # default
  108. UnicodeType: Unicode2Str,
  109. ObjectType: Instance2Str,
  110. BooleanType: Bool2Str,
  111. DateTimeType: DateTime2literal,
  112. DateTimeDeltaType: DateTimeDelta2literal,
  113. set: Set2Str,
  114. FIELD_TYPE.TINY: int,
  115. FIELD_TYPE.SHORT: int,
  116. FIELD_TYPE.LONG: long,
  117. FIELD_TYPE.FLOAT: float,
  118. FIELD_TYPE.DOUBLE: float,
  119. FIELD_TYPE.DECIMAL: float,
  120. FIELD_TYPE.NEWDECIMAL: float,
  121. FIELD_TYPE.LONGLONG: long,
  122. FIELD_TYPE.INT24: int,
  123. FIELD_TYPE.YEAR: int,
  124. FIELD_TYPE.SET: Str2Set,
  125. FIELD_TYPE.TIMESTAMP: mysql_timestamp_converter,
  126. FIELD_TYPE.DATETIME: DateTime_or_None,
  127. FIELD_TYPE.TIME: TimeDelta_or_None,
  128. FIELD_TYPE.DATE: Date_or_None,
  129. FIELD_TYPE.BLOB: [
  130. (FLAG.BINARY, str),
  131. ],
  132. FIELD_TYPE.STRING: [
  133. (FLAG.BINARY, str),
  134. ],
  135. FIELD_TYPE.VAR_STRING: [
  136. (FLAG.BINARY, str),
  137. ],
  138. FIELD_TYPE.VARCHAR: [
  139. (FLAG.BINARY, str),
  140. ],
  141. }
  142. try:
  143. from decimal import Decimal
  144. conversions[FIELD_TYPE.DECIMAL] = Decimal
  145. conversions[FIELD_TYPE.NEWDECIMAL] = Decimal
  146. except ImportError:
  147. pass