Wiki

Clone wiki

sqlalchemy / UsageRecipes / SelectIntoOutfile

Custom compilation to generate queries like:

SELECT * FROM t1 INTO OUTFILE 'file';

from sqlalchemy import *
from sqlalchemy.sql.expression import Executable, ClauseElement
from sqlalchemy.ext import compiler

class SelectIntoOutfile(Executable, ClauseElement):
    def __init__(self, select, file):
        self.select = select
        self.file = file


@compiler.compiles(SelectIntoOutfile)
def compile(element, compiler, **kw):
    return "%s INTO OUTFILE '%s'" % (
        compiler.process(element.select), element.file
    )


e = SelectIntoOutfile(select([s.dim_date_table]).where(s.dim_date_table.c.Year==2009), '/tmp/test.txt')
print e
eng.execute(e)

Updated