How do you create a table with Sqlalchemy within a transaction in Postgres?

与世无争的帅哥 提交于 2019-12-12 03:03:19

问题


I'm using Sqlalchemy in a multitenant Flask application and need to create tables on the fly when a new tenant is added. I've been using Table.create to create individual tables within a new Postgres schema (along with search_path modifications) and this works quite well.

The limitation I've found is that the Table.create method blocks if there is anything pending in the current transaction. I have to commit the transaction right before the .create call or it will block. It doesn't appear to be blocked in Sqlalchemy because you can't Ctrl-C it. You have to kill the process. So, I'm assuming it's something further down in Postgres.

I've read in other answers that CREATE TABLE is transactional and can be rolled back, so I'm presuming this should be working. I've tried starting a new transaction with the current engine and using that for the table create (vs. the current Flask one) but that hasn't helped either.

Does anybody know how to get this to work without an early commit (and risking partial dangling data)?

This is Python 2.7, Postgres 9.1 and Sqlalchemy 0.8.0b2.


回答1:


(Copy from comment)

Assuming sess is the session, you can do sess.execute(CreateTable(tenantX_tableY)) instead.

EDIT: CreateTable is only one of the things being done when calling table.create(). Use table.create(sess.connection()) instead.



来源:https://stackoverflow.com/questions/15774899/how-do-you-create-a-table-with-sqlalchemy-within-a-transaction-in-postgres

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