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()
....但沒有插入。任何想法我應該怎麼做?
您是否犯過? –
我不認爲這裏有任何提交。 http://www.sqlalchemy.org/docs/core/connections.html#dbengine-implicit –