2011-07-04 91 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) 
    ) 

查詢:

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

....但沒有插入。任何想法我應該怎麼做?

+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

我等着你我的男人。謝謝 :)) –