mysql.conversion.output

Package mysql :: Package conversion :: Module output |
[hide private]
[frames] | no frames]

# Source Code for Module mysql.conversion.output

      1  # $Header: /home/cvs2/mysql/mysql/conversion/output.py,v 1.4 2006/08/26 21:30:47 ehuss Exp $
      2  # Copyright (c) 2006, Eric Huss
      3  # All rights reserved.
      4  #
      5  # Redistribution and use in source and binary forms, with or without
      6  # modification, are permitted provided that the following conditions are met:
      7  #
      8  # 1. Redistributions of source code must retain the above copyright notice,
      9  #    this list of conditions and the following disclaimer.
     10  # 2. Redistributions in binary form must reproduce the above copyright notice,
     11  #    this list of conditions and the following disclaimer in the documentation
     12  #    and/or other materials provided with the distribution.
     13  # 3. Neither the name of Eric Huss nor the names of any contributors may be
     14  #    used to endorse or promote products derived from this software without
     15  #    specific prior written permission.
     16  #
     17  # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
     18  # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     19  # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     20  # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
     21  # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     22  # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     23  # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     24  # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     25  # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     26  # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     27  # POSSIBILITY OF SUCH DAMAGE.
     28
     29  """Output Conversion converts values from MySQL (which are always strings) to Python data types.
     30
     31  The base class `Output_Conversion` defines the API for converting values.
     32
     33  The class `Basic_Conversion` is the default conversion used if you do not
     34  specify a conversion instance.
     35
     36  The class `No_Conversion` may be used if you do not want any values converted.
     37
     38  NULL values are always converted to None, and are not passed into the
     39  ``convert`` method.
     40  """
     41
     42  __version__ = '$Revision: 1.4 $'
     43
     44  import datetime
     45  import decimal
     46  import time
     47  from mysql.util.misc import big_str_to_host_int
     48  from mysql.constants import field_types
     49
     50 -class Output_Conversion:
     51
     52      """Base class for the output conversion API.
     53
     54      The basic requirement is to implement the `convert` method which takes the
     55      value and returns a Python value.
     56      """
     57
     58 -    def convert(self, mysql_type, value):
     59          """Convert a MySQL value to a Python object.
     60
     61          :Parameters:
     62              - `mysql_type`: The type from `mysql.constants.field_types`.
     63              - `value`: The value from MySQL as a string.
     64
     65          :Return:
     66              Returns the Python object.
     67          """
     68          raise NotImplementedError
     69
     70
     71 -class No_Conversion(Output_Conversion):
     72
     73      """Does no conversion, all values are returned as strings.
     74
     75      NULL columns are returned as the string 'NULL'.
     76      """
     77
     78 -    def convert(self, mysql_type, value):
     79          return value
     80
     81
     82 -class Basic_Conversion(Output_Conversion):
     83
     84      """The default conversion class used if none is specified.
     85
     86      It will convert the following MySQL data types:
     87
     88      - Integers (TINYINT, SMALLINT, INTEGER, MEDIUMINT, BIGINT): Integers or
     89        Longs.
     90      - DECIMAL: ``decimal.Decimal``.
     91      - FLOAT and DOUBLE: Floating point number.
     92      - BIT: Integer or Long.
     93      - TIMESTAMP: ``datetime.datetime``.
     94      - DATE: ``datetime.date``.
     95      - TIME: ``datetime.timedelta``.
     96      - DATETIME: ``datetime.datetime``.
     97      - YEAR: Integer.
     98      - SET: List of strings.
     99      - ENUM: String.
    100
    101      All other types are returned as strings.  NULL values are returned as None.
    102      """
    103
    104 -    def __init__(self):
    105          self._type_map = {field_types.TINYINT:  self._integer,
    106                            field_types.SMALLINT: self._integer,
    107                            field_types.INTEGER: self._integer,
    108                            field_types.MEDIUMINT: self._integer,
    109                            field_types.BIGINT: self._integer,
    110                            field_types.FLOAT: self._float,
    111                            field_types.DOUBLE: self._float,
    112                            field_types.DECIMAL: self._decimal,
    113                            field_types.NEWDECIMAL: self._decimal,
    114                            field_types.BIT: self._bit,
    115                            field_types.TIMESTAMP: self._datetime,
    116                            field_types.DATE: self._date,
    117                            field_types.TIME: self._time,
    118                            field_types.DATETIME: self._datetime,
    119                            field_types.YEAR: self._integer,
    120                            field_types.SET: self._set,
    121                           }
    122
    123 -    def convert(self, mysql_type, value):
    124          return self._type_map.get(mysql_type, self._string)(value)
    125
    126 -    def _integer(self, value):
    127          return int(value)
    128
    129 -    def _float(self, value):
    130          return float(value)
    131
    132 -    def _string(self, value):
    133          return value
    134
    135 -    def _decimal(self, value):
    136          return decimal.Decimal(value)
    137
    138 -    def _bit(self, value):
    139          return big_str_to_host_int(value)
    140
    141 -    def _datetime(self, value):
    142          st = time.strptime(value, '%Y-%m-%d %H:%M:%S')
    143          return datetime.datetime(st.tm_year, st.tm_mon, st.tm_mday, st.tm_hour, st.tm_min, st.tm_sec)
    144
    145 -    def _date(self, value):
    146          st = time.strptime(value, '%Y-%m-%d')
    147          return datetime.date(st.tm_year, st.tm_mon, st.tm_mday)
    148
    149 -    def _time(self, value):
    150          if value.startswith('-'):
    151              negative = -1
    152              value = value[1:]
    153          else:
    154              negative = 1
    155          parts = value.split(':')
    156          return datetime.timedelta(
    157              seconds= negative*(int(parts[0])*3600 + int(parts[1])*60 + int(parts[2]))
    158          )
    159
    160 -    def _set(self, value):
    161          return value.split(',')
    162