mysql.conversion.input

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

# Source Code for Module mysql.conversion.input

      1  # $Header: /home/cvs2/mysql/mysql/conversion/input.py,v 1.5 2006/08/26 22:30:06 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  """Input Conversion converts Python data types to be made appropriate for MySQL
     30  parameters.
     31
     32  The main function of these conversions for simple data types is to escape them
     33  (such as escaping quotes in strings).  It also handles converting more
     34  elaborate data structures, such as `datetime` objects, to strings that MySQL
     35  can parse.
     36
     37  The base class `Input_Conversion` defines the API for converting values.
     38
     39  The class `Basic_Conversion` is the default conversion used if you do not specify
     40  a conversion instance.
     41  """
     42
     43  __version__ = '$Revision: 1.5 $'
     44
     45  import datetime
     46  import decimal
     47  import sets
     48  import types
     49
     50  import mysql.util.string
     51
     52 -class Input_Conversion:
     53
     54      """Base class for the input conversion API.
     55
     56      The basic requirement is to implement the `convert` method which takes the
     57      values and must return a tuple of strings.
     58      """
     59
     60 -    def convert(self, *values):
     61          """Convert Python values to strings suitable for MySQL.
     62
     63          This method takes a sequence of Python values to convert. It must
     64          return a tuple of strings suitable for MySQL, with all appropriate
     65          escaping done.
     66
     67          :Parameters:
     68              - `values`: A tuple of Python values to convert.
     69
     70          :Return:
     71              Returns a tuple of strings.
     72          """
     73          raise NotImplementedError
     74
     75
     76 -class Basic_Conversion(Input_Conversion):
     77
     78      """The default conversion class used if none is specified.
     79
     80      It can handle the following Python types:
     81
     82      - ``int``: Returned as-is.
     83      - ``long``: Returned as-is.
     84      - ``float``: Returned as-is.
     85      - ``None``: Converts to "NULL".
     86      - ``str``: Escaped string.
     87      - ``bool``: Converted to 1 or 0.
     88      - ``decimal.Decimal``: Returned as a string.
     89      - ``dict``: Comma seperated list of escaped values. (Useful for sets.)
     90      - ``list``: Comma seperated list of escaped values.
     91      - ``tuple``: Comma seperated list of escaped values.
     92      - ``sets.Set``: Comma seperated list of escaped values.
     93      - ``datetime.datetime``: ``%Y-%m-%d %H:%M:%S``
     94      - ``datetime.time``: ``%H:%M:%S``
     95      - ``datetime.timedelta``: ``%H:%M:%S`` possibly negative.
     96      - ``datetime.date``: ``%Y-%m-%d``
     97
     98      For MySQL "BIT" fields, you may use integers, or binary strings (such as
     99      '\x10\x04' which has bits 13 and 3 set).
    100
    101      If the type is not known, the default behavior is to first call ``str`` on
    102      the object, and then escape it.
    103      """
    104
    105 -    def __init__(self):
    106          self._type_map = {int:      self._number,
    107                            long:     self._number,
    108                            float:    self._number,
    109                            types.NoneType: self._none,
    110                            str:      mysql.util.string.escape,
    111                            decimal.Decimal: str,
    112                            dict: self._dict,
    113                            list: self._sequence,
    114                            tuple: self._sequence,
    115                            sets.Set: self._sequence,
    116                            datetime.datetime: self._datetime,
    117                            datetime.time: self._time,
    118                            datetime.timedelta: self._timedelta,
    119                            datetime.date: self._date,
    120                            bool: self._bool,
    121                           }
    122
    123 -    def convert(self, *values):
    124          return tuple([ self._type_map.get(type(value), self._escape)(value) for value in values ])
    125
    126 -    def _number(self, value):
    127          return value
    128
    129 -    def _bool(self, value):
    130          return int(value)
    131
    132 -    def _none(self, value):
    133          return 'NULL'
    134
    135 -    def _escape(self, value):
    136          return mysql.util.string.escape(str(value))
    137
    138 -    def _dict(self, value):
    139          return self._sequence(value.keys())
    140
    141 -    def _sequence(self, value):
    142          return mysql.util.string.escape(
    143              ','.join([ v for v in value ])
    144          )
    145
    146 -    def _datetime(self, value):
    147          return value.strftime('\'%Y-%m-%d %H:%M:%S\'')
    148
    149 -    def _time(self, value):
    150          return value.strftime('\'%H:%M:%S\'')
    151
    152 -    def _timedelta(self, value):
    153          # Denormalize.
    154          if value.days < 0:
    155              value = -value
    156              neg = '-'
    157          else:
    158              neg = ''
    159
    160          hours = value.days*24 + value.seconds/3600
    161
    162          if hours > 838:
    163              raise OverflowError('Time value is too large.')
    164          minutes = (value.seconds % 3600) / 60
    165          seconds = value.seconds % 60
    166
    167          return '\'%s%i:%i:%i\'' % (neg, hours, minutes, seconds)
    168
    169 -    def _date(self, value):
    170          return value.strftime('\'%Y-%m-%d\'')
    171