Skip to content

Instantly share code, notes, and snippets.

@Stiivi
Created January 21, 2013 23:09
Show Gist options
  • Save Stiivi/4590386 to your computer and use it in GitHub Desktop.
Save Stiivi/4590386 to your computer and use it in GitHub Desktop.
Classes for "bulk append" operations in SQL such as CREATE TABLE and INSERT from SELECT.
from sqlalchemy.sql.expression import Executable, ClauseElement
from sqlalchemy.ext.compiler import compiles
class CreateTableAsSelect(Executable, ClauseElement):
def __init__(self, table, select):
self.table = table
self.select = select
@compiles(CreateTableAsSelect)
def visit_create_table_as_select(element, compiler, **kw):
return "CREATE TABLE %s AS (%s)" % (
element.table,
compiler.process(element.select)
)
class InsertFromSelect(Executable, ClauseElement):
_execution_options = \
Executable._execution_options.union({'autocommit': True})
def __init__(self, table, select):
self.table = table
self.select = select
@compiles(InsertFromSelect)
def visit_insert_from_select(element, compiler, **kw):
return "INSERT INTO %s (%s)" % (
compiler.process(element.table, asfrom=True),
compiler.process(element.select)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment