web/lib/django/db/backends/util.py
changeset 38 77b6da96e6f1
equal deleted inserted replaced
37:8d941af65caf 38:77b6da96e6f1
       
     1 import datetime
       
     2 import decimal
       
     3 from time import time
       
     4 
       
     5 from django.utils.hashcompat import md5_constructor
       
     6 
       
     7 class CursorDebugWrapper(object):
       
     8     def __init__(self, cursor, db):
       
     9         self.cursor = cursor
       
    10         self.db = db # Instance of a BaseDatabaseWrapper subclass
       
    11 
       
    12     def execute(self, sql, params=()):
       
    13         start = time()
       
    14         try:
       
    15             return self.cursor.execute(sql, params)
       
    16         finally:
       
    17             stop = time()
       
    18             sql = self.db.ops.last_executed_query(self.cursor, sql, params)
       
    19             self.db.queries.append({
       
    20                 'sql': sql,
       
    21                 'time': "%.3f" % (stop - start),
       
    22             })
       
    23 
       
    24     def executemany(self, sql, param_list):
       
    25         start = time()
       
    26         try:
       
    27             return self.cursor.executemany(sql, param_list)
       
    28         finally:
       
    29             stop = time()
       
    30             self.db.queries.append({
       
    31                 'sql': '%s times: %s' % (len(param_list), sql),
       
    32                 'time': "%.3f" % (stop - start),
       
    33             })
       
    34 
       
    35     def __getattr__(self, attr):
       
    36         if attr in self.__dict__:
       
    37             return self.__dict__[attr]
       
    38         else:
       
    39             return getattr(self.cursor, attr)
       
    40 
       
    41     def __iter__(self):
       
    42         return iter(self.cursor)
       
    43 
       
    44 ###############################################
       
    45 # Converters from database (string) to Python #
       
    46 ###############################################
       
    47 
       
    48 def typecast_date(s):
       
    49     return s and datetime.date(*map(int, s.split('-'))) or None # returns None if s is null
       
    50 
       
    51 def typecast_time(s): # does NOT store time zone information
       
    52     if not s: return None
       
    53     hour, minutes, seconds = s.split(':')
       
    54     if '.' in seconds: # check whether seconds have a fractional part
       
    55         seconds, microseconds = seconds.split('.')
       
    56     else:
       
    57         microseconds = '0'
       
    58     return datetime.time(int(hour), int(minutes), int(seconds), int(float('.'+microseconds) * 1000000))
       
    59 
       
    60 def typecast_timestamp(s): # does NOT store time zone information
       
    61     # "2005-07-29 15:48:00.590358-05"
       
    62     # "2005-07-29 09:56:00-05"
       
    63     if not s: return None
       
    64     if not ' ' in s: return typecast_date(s)
       
    65     d, t = s.split()
       
    66     # Extract timezone information, if it exists. Currently we just throw
       
    67     # it away, but in the future we may make use of it.
       
    68     if '-' in t:
       
    69         t, tz = t.split('-', 1)
       
    70         tz = '-' + tz
       
    71     elif '+' in t:
       
    72         t, tz = t.split('+', 1)
       
    73         tz = '+' + tz
       
    74     else:
       
    75         tz = ''
       
    76     dates = d.split('-')
       
    77     times = t.split(':')
       
    78     seconds = times[2]
       
    79     if '.' in seconds: # check whether seconds have a fractional part
       
    80         seconds, microseconds = seconds.split('.')
       
    81     else:
       
    82         microseconds = '0'
       
    83     return datetime.datetime(int(dates[0]), int(dates[1]), int(dates[2]),
       
    84         int(times[0]), int(times[1]), int(seconds), int(float('.'+microseconds) * 1000000))
       
    85 
       
    86 def typecast_boolean(s):
       
    87     if s is None: return None
       
    88     if not s: return False
       
    89     return str(s)[0].lower() == 't'
       
    90 
       
    91 def typecast_decimal(s):
       
    92     if s is None or s == '':
       
    93         return None
       
    94     return decimal.Decimal(s)
       
    95 
       
    96 ###############################################
       
    97 # Converters from Python to database (string) #
       
    98 ###############################################
       
    99 
       
   100 def rev_typecast_boolean(obj, d):
       
   101     return obj and '1' or '0'
       
   102 
       
   103 def rev_typecast_decimal(d):
       
   104     if d is None:
       
   105         return None
       
   106     return str(d)
       
   107 
       
   108 def truncate_name(name, length=None):
       
   109     """Shortens a string to a repeatable mangled version with the given length.
       
   110     """
       
   111     if length is None or len(name) <= length:
       
   112         return name
       
   113 
       
   114     hash = md5_constructor(name).hexdigest()[:4]
       
   115 
       
   116     return '%s%s' % (name[:length-4], hash)
       
   117 
       
   118 def format_number(value, max_digits, decimal_places):
       
   119     """
       
   120     Formats a number into a string with the requisite number of digits and
       
   121     decimal places.
       
   122     """
       
   123     if isinstance(value, decimal.Decimal):
       
   124         context = decimal.getcontext().copy()
       
   125         context.prec = max_digits
       
   126         return u'%s' % str(value.quantize(decimal.Decimal(".1") ** decimal_places, context=context))
       
   127     else:
       
   128         return u"%.*f" % (decimal_places, value)