Why is SQLAlchemy execute Update not working

人走茶凉 提交于 2019-12-12 09:14:12

问题


I have the following:

@periodic_task(run_every=crontab(minute="*/1"))
def PeriodicUpdateAgentLastRica():
    query = """update agents
            inner join
               (select sims.consignment_agents_id as agents_id,
                MAX(sims.rica_current_stamp) 
            as last_rica_stamp
            from sims
            where sims.rica_current_stamp > DATE_SUB(now(), INTERVAL 3 MONTH) and sims.consignment_agents_id is not NULL
            group by sims.consignment_agents_id) as dt on dt.agents_id = agents.id
            set agents.last_rica_stamp = dt.last_rica_stamp"""
    res = Session.execute(query)
    print res
    if res.rowcount:
        log.info("Updated %s agents" % res.rowcount)
    #transaction.commit()

When I run celery worker -B This is what is returned:

[2014-02-12 09:15:00,012: INFO/MainProcess] Received task: prepaid.models.Prepaid.PeriodicUpdateAgentLastRica[9ca091c8-595f-4163-8ddf-2742e573b90c]
[2014-02-12 09:15:01,812: WARNING/Worker-7] <sqlalchemy.engine.result.ResultProxy object at 0x776f310>
[2014-02-12 09:15:01,813: INFO/Worker-7] Updated 2923 agents 
[2014-02-12 09:15:01,816: INFO/MainProcess] Task prepaid.models.Prepaid.PeriodicUpdateAgentLastRica[9ca091c8-595f-4163-8ddf-2742e573b90c] succeeded in 1.798980095s: None

Even though it says that it updated: Updated 2923 agents, when I check the DB, no record is changed.

There is nothing wrong with the query, as when I run it in mySQL Workbench it works.

The same happens when I try forcing AutoCommit, i.e.

res = Session.execute(text(query).execution_options(autocommit=True))

So it committing, but still the Update is not affecting the DB. Why is it not affecting the database? Why is it not working?

UPDATE

I have also tried doing:

with transaction.manager:
    #Rest of code

But it still does not change anything in the DB


回答1:


This looks like you are using zodb transaction manager in pyramid.

You have to mark the session as changed

http://www.upfrontsystems.co.za/Members/izak/sysadman/how-to-commit-a-transaction-even-when-sqlalchemy-thinks-the-session-is-clean

You should do something like

from zope.sqlalchemy import mark_changed
mark_changed(Session)

if that does not work try

from zope.sqlalchemy import ZopeTransactionExtension
Session.configure(extension=ZopeTransactionExtension('changed'))


来源:https://stackoverflow.com/questions/21721545/why-is-sqlalchemy-execute-update-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!