converters.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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 constants import FIELD_TYPE, FLAG
  24. from times import *
  25. import types
  26. import array
  27. try:
  28. set
  29. except NameError:
  30. from sets import Set as set
  31. def Bool2Str(s, d): return str(int(s))
  32. def Str2Set(s):
  33. return set([ i for i in s.split(',') if i ])
  34. def Set2Str(s, d):
  35. return string_literal(','.join(s), d)
  36. def Thing2Str(s, d):
  37. """Convert something into a string via str()."""
  38. return str(s)
  39. def Unicode2Str(s, d):
  40. """Convert a unicode object to a string using the default encoding.
  41. This is only used as a placeholder for the real function, which
  42. is connection-dependent."""
  43. return s.encode()
  44. Long2Int = Thing2Str
  45. def Float2Str(o, d):
  46. return '%.15g' % o
  47. def None2NULL(o, d):
  48. """Convert None to NULL."""
  49. return NULL # duh
  50. def Thing2Literal(o, d):
  51. """Convert something into a SQL string literal. If using
  52. MySQL-3.23 or newer, string_literal() is a method of the
  53. _mysql.MYSQL object, and this function will be overridden with
  54. that method when the connection is created."""
  55. return string_literal(o, d)
  56. def Instance2Str(o, d):
  57. """
  58. Convert an Instance to a string representation. If the __str__()
  59. method produces acceptable output, then you don't need to add the
  60. class to conversions; it will be handled by the default
  61. converter. If the exact class is not found in d, it will use the
  62. first class it can find for which o is an instance.
  63. """
  64. if d.has_key(o.__class__):
  65. return d[o.__class__](o, d)
  66. cl = filter(lambda x,o=o:
  67. type(x) is types.ClassType
  68. and isinstance(o, x), d.keys())
  69. if not cl and hasattr(types, 'ObjectType'):
  70. cl = filter(lambda x,o=o:
  71. type(x) is types.TypeType
  72. and isinstance(o, x)
  73. and d[x] is not Instance2Str,
  74. d.keys())
  75. if not cl:
  76. return d[types.StringType](o,d)
  77. d[o.__class__] = d[cl[0]]
  78. return d[cl[0]](o, d)
  79. def char_array(s):
  80. return array.array('c', s)
  81. def array2Str(o, d):
  82. return Thing2Literal(o.tostring(), d)
  83. conversions = {
  84. types.IntType: Thing2Str,
  85. types.LongType: Long2Int,
  86. types.FloatType: Float2Str,
  87. types.NoneType: None2NULL,
  88. types.TupleType: escape_sequence,
  89. types.ListType: escape_sequence,
  90. types.DictType: escape_dict,
  91. types.InstanceType: Instance2Str,
  92. array.ArrayType: array2Str,
  93. types.StringType: Thing2Literal, # default
  94. types.UnicodeType: Unicode2Str,
  95. types.ObjectType: Instance2Str,
  96. types.BooleanType: Bool2Str,
  97. DateTimeType: DateTime2literal,
  98. DateTimeDeltaType: DateTimeDelta2literal,
  99. set: Set2Str,
  100. FIELD_TYPE.TINY: int,
  101. FIELD_TYPE.SHORT: int,
  102. FIELD_TYPE.LONG: long,
  103. FIELD_TYPE.FLOAT: float,
  104. FIELD_TYPE.DOUBLE: float,
  105. FIELD_TYPE.DECIMAL: float,
  106. FIELD_TYPE.NEWDECIMAL: float,
  107. FIELD_TYPE.LONGLONG: long,
  108. FIELD_TYPE.INT24: int,
  109. FIELD_TYPE.YEAR: int,
  110. FIELD_TYPE.SET: Str2Set,
  111. FIELD_TYPE.TIMESTAMP: mysql_timestamp_converter,
  112. FIELD_TYPE.DATETIME: DateTime_or_None,
  113. FIELD_TYPE.TIME: TimeDelta_or_None,
  114. FIELD_TYPE.DATE: Date_or_None,
  115. FIELD_TYPE.BLOB: [
  116. (FLAG.BINARY, str),
  117. ],
  118. FIELD_TYPE.STRING: [
  119. (FLAG.BINARY, str),
  120. ],
  121. FIELD_TYPE.VAR_STRING: [
  122. (FLAG.BINARY, str),
  123. ],
  124. FIELD_TYPE.VARCHAR: [
  125. (FLAG.BINARY, str),
  126. ],
  127. }
  128. try:
  129. from decimal import Decimal
  130. conversions[FIELD_TYPE.DECIMAL] = Decimal
  131. conversions[FIELD_TYPE.NEWDECIMAL] = Decimal
  132. except ImportError:
  133. pass