Skip to content

Instantly share code, notes, and snippets.

@jeanphix
Created October 23, 2012 15:28
Show Gist options
  • Save jeanphix/3939448 to your computer and use it in GitHub Desktop.
Save jeanphix/3939448 to your computer and use it in GitHub Desktop.
SQLAlchemy - INSERT INTO ... (SELECT ...)
from sqlalchemy.sql.expression import Executable, ClauseElement
class InsertFromSelect(Executable, ClauseElement):
_execution_options = \
Executable._execution_options.union({'autocommit': True})
def __init__(self, table, columns, select):
self.table = table
self.columns = columns
self.select = select
@compiles(InsertFromSelect)
def visit_insert_from_select(element, compiler, **kw):
return "INSERT INTO %s (%s) (%s)" % (
compiler.process(element.table, asfrom=True),
", ".join([col.name for col in element.columns]),
compiler.process(element.select)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment