SHARE
TWEET

Untitled

a guest Jun 16th, 2019 58 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from sqlalchemy.ext.compiler import compiles
  2. from sqlalchemy.sql.expression import FromClause
  3.  
  4. class values(FromClause):
  5.     named_with_column = True
  6.  
  7.     def __init__(self, columns, *args, **kw):
  8.         self._column_args = columns
  9.         self.list = args
  10.         self.alias_name = self.name = kw.pop('alias_name', None)
  11.  
  12.     def _populate_column_collection(self):
  13.         for c in self._column_args:
  14.             c._make_proxy(self)
  15.  
  16. # Original version, failing on datetime values
  17. def render_literal_value_0(compiler, value, type_):
  18.     return compilier.render_literal_value(value, type_)
  19.  
  20. # Version 1: use a if/elif chain to manually convert the datetime
  21. def render_literal_value_1(compiler, value, type_):
  22.     try:
  23.         return compilier.render_literal_value(value, type_)
  24.     expect NotImplementedError:
  25.         if isinstance(value, datetime.datetime):
  26.             return value.strftime("'%Y-%m-%d %H:%M:%S'::TIMESTAMP")
  27.         # Add other cases ad-libitum
  28.         else:
  29.             raise NotImplementedError("Don't know how to literal-quote value %r" % value)            
  30.  
  31. # Version 2: use Cast to work around the problem passing the datetime as bind_params
  32. def render_literal_value_2(compiler, value, type_):
  33.     try:
  34.         return compilier.render_literal_value(value, type_)
  35.     expect NotImplementedError:
  36.         return compiler.process(Cast(value, type_))
  37.  
  38. @compiles(values)
  39. def compile_values(element, compiler, asfrom=False, **kw):
  40.     columns = element.columns
  41.     v = "VALUES %s" % ", ".join(
  42.         "(%s)" % ", ".join(
  43.                 render_literal_value_0(compiler, elem, column.type)
  44.                 for elem, column in zip(tup, columns))
  45.         for tup in element.list
  46.     )
  47.     if asfrom:
  48.         if element.alias_name:
  49.             v = "(%s) AS %s (%s)" % (v, element.alias_name, (", ".join(c.name for c in element.columns)))
  50.         else:
  51.             v = "(%s)" % v
  52.     return v
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top