简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM