sqlalchemy编译问题

时间:2011-07-04 17:15:14

标签: python sqlalchemy

我有一个自定义的InsertFromSelect类,它正如它的名字所说的那样。输出查询正是我需要的,问题是我似乎无法执行它。

类别:

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)
    )

查询:

import proxy.lib.sqlalchemy.compilers.insertFromSelect as ifs
from sqlalchemy import not_, literal_column, String, text
from proxy.database import engine

ifsTest = ifs.InsertFromSelect(
    user_ip_table,
    select(
        [
            user.id,
            ips_table.c.id, literal_column( "'inactive'", String ),
            literal_column( "'"+service_type+"'", String )
        ]
    ).where(
        not_( ips_table.c.id.in_(
            select(
                [user_ip_table.c.ip_id]
            )
        ) )
    ).where(
        ips_table.c.ip_address.in_( validIps )
    )
)

查询输出(打印ifsTest):

INSERT INTO user_ip (SELECT 5144, ip.id, 'inactive', 'proxy' 
FROM ip 
WHERE ip.id NOT IN (SELECT user_ip.ip_id 
FROM user_ip) AND ip.ip_address IN (:ip_address_1, :ip_address_2, :ip_address_3, :ip_address_4, :ip_address_5, :ip_address_6))

我已经针对数据库手动测试了查询(当然还有params),它产生了我需要的东西,但我似乎无法使用sqlalchemy执行它。

I've tried:
connection = engine.connect()
res = connection.execute( ifsTest )
connection.close()

....但没有插入任何内容。知道我该怎么办?

1 个答案:

答案 0 :(得分:1)

因为您没有使用事务,所以在构造中添加“autocommit”选项:

class InsertFromSelect( Executable, ClauseElement ):
    _execution_options = \
        Executable._execution_options.union({'autocommit': True})
    def __init__( self, table, select ):
        self.table = table
        self.select = select

或者明确地称之为:

connection.execution_options(autocommit=True).execute(mystatement)

或使用交易:

trans = connection.begin()
connection.execute(...)
trans.commit()

背景:

http://www.sqlalchemy.org/docs/core/connections.html#understanding-autocommit