PYTHON   31

utils.py

Guest on 3rd June 2021 05:57:21 AM

  1. import datetime
  2. import decimal
  3. import functools
  4. import hashlib
  5. import logging
  6. import time
  7. from contextlib import contextmanager
  8.  
  9. from django.conf import settings
  10. from django.db.utils import NotSupportedError
  11. from django.utils.timezone import utc
  12.  
  13. logger = logging.getLogger('django.db.backends')
  14.  
  15.  
  16. class CursorWrapper:
  17.     def __init__(self, cursor, db):
  18.         self.cursor = cursor
  19.         self.db = db
  20.  
  21.     WRAP_ERROR_ATTRS = frozenset(['fetchone', 'fetchmany', 'fetchall', 'nextset'])
  22.  
  23.     def __getattr__(self, attr):
  24.         cursor_attr = getattr(self.cursor, attr)
  25.         if attr in CursorWrapper.WRAP_ERROR_ATTRS:
  26.             return self.db.wrap_database_errors(cursor_attr)
  27.         else:
  28.             return cursor_attr
  29.  
  30.     def __iter__(self):
  31.         with self.db.wrap_database_errors:
  32.             yield from self.cursor
  33.  
  34.     def __enter__(self):
  35.         return self
  36.  
  37.     def __exit__(self, type, value, traceback):
  38.         # Close instead of passing through to avoid backend-specific behavior
  39.         # (#17671). Catch errors liberally because errors in cleanup code
  40.         # aren't useful.
  41.         try:
  42.             self.close()
  43.         except self.db.Database.Error:
  44.             pass
  45.  
  46.     # The following methods cannot be implemented in __getattr__, because the
  47.     # code must run when the method is invoked, not just when it is accessed.
  48.  
  49.     def callproc(self, procname, params=None, kparams=None):
  50.         # Keyword parameters for callproc aren't supported in PEP 249, but the
  51.         # database driver may support them (e.g. cx_Oracle).
  52.         if kparams is not None and not self.db.features.supports_callproc_kwargs:
  53.             raise NotSupportedError(
  54.                 'Keyword parameters for callproc are not supported on this '
  55.                 'database backend.'
  56.             )
  57.         self.db.validate_no_broken_transaction()
  58.         with self.db.wrap_database_errors:
  59.             if params is None and kparams is None:
  60.                 return self.cursor.callproc(procname)
  61.             elif kparams is None:
  62.                 return self.cursor.callproc(procname, params)
  63.             else:
  64.                 params = params or ()
  65.                 return self.cursor.callproc(procname, params, kparams)
  66.  
  67.     def execute(self, sql, params=None):
  68.         return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  69.  
  70.     def executemany(self, sql, param_list):
  71.         return self._execute_with_wrappers(sql, param_list, many=True, executor=self._executemany)
  72.  
  73.     def _execute_with_wrappers(self, sql, params, many, executor):
  74.         context = {'connection': self.db, 'cursor': self}
  75.         for wrapper in reversed(self.db.execute_wrappers):
  76.             executor = functools.partial(wrapper, executor)
  77.         return executor(sql, params, many, context)
  78.  
  79.     def _execute(self, sql, params, *ignored_wrapper_args):
  80.         self.db.validate_no_broken_transaction()
  81.         with self.db.wrap_database_errors:
  82.             if params is None:
  83.                 # params default might be backend specific.
  84.                 return self.cursor.execute(sql)
  85.             else:
  86.                 return self.cursor.execute(sql, params)
  87.  
  88.     def _executemany(self, sql, param_list, *ignored_wrapper_args):
  89.         self.db.validate_no_broken_transaction()
  90.         with self.db.wrap_database_errors:
  91.             return self.cursor.executemany(sql, param_list)
  92.  
  93.  
  94. class CursorDebugWrapper(CursorWrapper):
  95.  
  96.     # XXX callproc isn't instrumented at this time.
  97.  
  98.     def execute(self, sql, params=None):
  99.         with self.debug_sql(sql, params, use_last_executed_query=True):
  100.             return super().execute(sql, params)
  101.  
  102.     def executemany(self, sql, param_list):
  103.         with self.debug_sql(sql, param_list, many=True):
  104.             return super().executemany(sql, param_list)
  105.  
  106.     @contextmanager
  107.     def debug_sql(self, sql=None, params=None, use_last_executed_query=False, many=False):
  108.         start = time.monotonic()
  109.         try:
  110.             yield
  111.         finally:
  112.             stop = time.monotonic()
  113.             duration = stop - start
  114.             if use_last_executed_query:
  115.                 sql = self.db.ops.last_executed_query(self.cursor, sql, params)
  116.             try:
  117.                 times = len(params) if many else ''
  118.             except TypeError:
  119.                 # params could be an iterator.
  120.                 times = '?'
  121.             self.db.queries_log.append({
  122.                 'sql': '%s times: %s' % (times, sql) if many else sql,
  123.                 'time': '%.3f' % duration,
  124.             })
  125.             logger.debug(
  126.                 '(%.3f) %s; args=%s',
  127.                 duration,
  128.                 sql,
  129.                 params,
  130.                 extra={'duration': duration, 'sql': sql, 'params': params},
  131.             )
  132.  
  133.  
  134. ###############################################
  135. # Converters from database (string) to Python #
  136. ###############################################
  137.  
  138. def typecast_date(s):
  139.     return datetime.date(*map(int, s.split('-'))) if s else None  # return None if s is null
  140.  
  141.  
  142. def typecast_time(s):  # does NOT store time zone information
  143.     if not s:
  144.         return None
  145.     hour, minutes, seconds = s.split(':')
  146.     if '.' in seconds:  # check whether seconds have a fractional part
  147.         seconds, microseconds = seconds.split('.')
  148.     else:
  149.         microseconds = '0'
  150.     return datetime.time(int(hour), int(minutes), int(seconds), int((microseconds + '000000')[:6]))
  151.  
  152.  
  153. def typecast_timestamp(s):  # does NOT store time zone information
  154.     # "2005-07-29 15:48:00.590358-05"
  155.     # "2005-07-29 09:56:00-05"
  156.     if not s:
  157.         return None
  158.     if ' ' not in s:
  159.         return typecast_date(s)
  160.     d, t = s.split()
  161.     # Remove timezone information.
  162.     if '-' in t:
  163.         t, _ = t.split('-', 1)
  164.     elif '+' in t:
  165.         t, _ = t.split('+', 1)
  166.     dates = d.split('-')
  167.     times = t.split(':')
  168.     seconds = times[2]
  169.     if '.' in seconds:  # check whether seconds have a fractional part
  170.         seconds, microseconds = seconds.split('.')
  171.     else:
  172.         microseconds = '0'
  173.     tzinfo = utc if settings.USE_TZ else None
  174.     return datetime.datetime(
  175.         int(dates[0]), int(dates[1]), int(dates[2]),
  176.         int(times[0]), int(times[1]), int(seconds),
  177.         int((microseconds + '000000')[:6]), tzinfo
  178.     )
  179.  
  180.  
  181. ###############################################
  182. # Converters from Python to database (string) #
  183. ###############################################
  184.  
  185. def split_identifier(identifier):
  186.     """
  187.    Split a SQL identifier into a two element tuple of (namespace, name).
  188.  
  189.    The identifier could be a table, column, or sequence name might be prefixed
  190.    by a namespace.
  191.    """
  192.     try:
  193.         namespace, name = identifier.split('"."')
  194.     except ValueError:
  195.         namespace, name = '', identifier
  196.     return namespace.strip('"'), name.strip('"')
  197.  
  198.  
  199. def truncate_name(identifier, length=None, hash_len=4):
  200.     """
  201.    Shorten a SQL identifier to a repeatable mangled version with the given
  202.    length.
  203.  
  204.    If a quote stripped name contains a namespace, e.g. USERNAME"."TABLE,
  205.    truncate the table portion only.
  206.    """
  207.     namespace, name = split_identifier(identifier)
  208.  
  209.     if length is None or len(name) <= length:
  210.         return identifier
  211.  
  212.     digest = names_digest(name, length=hash_len)
  213.     return '%s%s%s' % ('%s"."' % namespace if namespace else '', name[:length - hash_len], digest)
  214.  
  215.  
  216. def names_digest(*args, length):
  217.     """
  218.    Generate a 32-bit digest of a set of arguments that can be used to shorten
  219.    identifying names.
  220.    """
  221.     h = hashlib.md5()
  222.     for arg in args:
  223.         h.update(arg.encode())
  224.     return h.hexdigest()[:length]
  225.  
  226.  
  227. def format_number(value, max_digits, decimal_places):
  228.     """
  229.    Format a number into a string with the requisite number of digits and
  230.    decimal places.
  231.    """
  232.     if value is None:
  233.         return None
  234.     context = decimal.getcontext().copy()
  235.     if max_digits is not None:
  236.         context.prec = max_digits
  237.     if decimal_places is not None:
  238.         value = value.quantize(decimal.Decimal(1).scaleb(-decimal_places), context=context)
  239.     else:
  240.         context.traps[decimal.Rounded] = 1
  241.         value = context.create_decimal(value)
  242.     return "{:f}".format(value)
  243.  
  244.  
  245. def strip_quotes(table_name):
  246.     """
  247.    Strip quotes off of quoted table names to make them safe for use in index
  248.    names, sequence names, etc. For example '"USER"."TABLE"' (an Oracle naming
  249.    scheme) becomes 'USER"."TABLE'.
  250.    """
  251.     has_quotes = table_name.startswith('"') and table_name.endswith('"')
  252.     return table_name[1:-1] if has_quotes else table_name

Raw Paste


Login or Register to edit or fork this paste. It's free.