2009-12-04 15 views

Respuesta

34

SQLalchemy no crea esta construcción para usted. Puede usar la consulta desde el texto.

session.execute('INSERT INTO t1 (SELECT * FROM t2)') 

EDIT:

Más de un año después, pero ahora en sqlalchemy 0.6+ you can create it:

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

class InsertFromSelect(Executable, ClauseElement): 
    def __init__(self, table, select): 
     self.table = table 
     self.select = select 

@compiler.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) 
    ) 

insert = InsertFromSelect(t1, select([t1]).where(t1.c.x>5)) 
print insert 

Produce:

"INSERT INTO mytable (SELECT mytable.x, mytable.y, mytable.z FROM mytable WHERE mytable.x > :x_1)" 

Otro EDITAR:

Ahora, 4 años después, la sintaxis se incorpora en SQLAlchemy 0.9 y se transfiere a 0.8.3; Usted puede crear cualquier select() y luego utilizar el nuevo método de from_select()Insert objetos:

>>> from sqlalchemy.sql import table, column 
>>> t1 = table('t1', column('a'), column('b')) 
>>> t2 = table('t2', column('x'), column('y')) 
>>> print(t1.insert().from_select(['a', 'b'], t2.select().where(t2.c.y == 5))) 
INSERT INTO t1 (a, b) SELECT t2.x, t2.y 
FROM t2 
WHERE t2.y = :y_1 

More information in the docs.

+0

¿Sugeriría session.execute ('INSERT INTO t1 (% s)'% str (sqlalchemy_select_expression))? – joeforker

+0

Claro, ¿por qué no? No necesita el 'str()', ya que '% s' ya lo hace. – nosklo

+0

¿Todavía no se puede hacer ahora? – Hadrien

0

Como Noslko señaló en el comentario, ahora puede deshacerse de SQL prima: http://www.sqlalchemy.org/docs/core/compiler.html#compiling-sub-elements-of-a-custom-expression-construct

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

class InsertFromSelect(Executable, ClauseElement): 
    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) 
    ) 

insert = InsertFromSelect(t1, select([t1]).where(t1.c.x>5)) 
print insert 

Produce:

INSERT INTO mytable (SELECT mytable.x, mytable.y, mytable.z FROM mytable WHERE mytable.x > :x_1) 
+1

Ahora no tiene que crear su propio ClauseElement. ¡Puedes usar el nuevo método 'Insert.from_select'! Ver mi respuesta – nosklo

13

A partir de 0,8. 3, ahora puede hacer esto directamente en sqlalchemy: Insert.from_select:

sel = select([table1.c.a, table1.c.b]).where(table1.c.c > 5) 
ins = table2.insert().from_select(['a', 'b'], sel) 
+1

Gracias. Añadiré eso en la respuesta original. – nosklo

Cuestiones relacionadas