2011-07-04 15 views
0

私は、正確にその名前を言うカスタムInsertFromSelectクラスを持っています。出力クエリはまさに私が必要とするものですが、問題は私がそれを実行するように見えないことです。sqlalchemyコンパイラの質問

クラス:

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

問合せ:私はのparamsで(データベースに対して手動でクエリをテストしてみた

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

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)もちろん)私は必要なものを生成しますが、私はsqlalchemyで実行することはできません。

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

....しかし何も挿入されていません。どのように私はこれを行う必要がありますか?

+0

あなたがコミットしましたか? –

+0

私はここにコミットするものはないと思う。 http://www.sqlalchemy.org/docs/core/connections.html#dbengine-implicit –

答えて

1

トランザクションを使用していないことから、あなたの構造に "自動コミット" オプションを追加します。

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

+0

私はあなたに私の人を待っていました。ありがとう:)) –