如何在Postgres的事务中使用Sqlalchemy创建表? [英] How do you create a table with Sqlalchemy within a transaction in Postgres?

查看:103
本文介绍了如何在Postgres的事务中使用Sqlalchemy创建表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在多租户Flask应用程序中使用Sqlalchemy,并且需要在添加新租户时动态创建表。我一直在使用Table.create在新的Postgres模式中创建单个表(以及对search_path的修改),并且效果很好。

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.

我发现的局限性是Table.create方法在当前事务中是否有任何未决状态时阻塞。我必须在.create调用之前提交事务,否则它将阻塞。它似乎没有在Sqlalchemy中被阻止,因为您无法Ctrl-C对其进行阻止。您必须终止该过程。因此,我假设它在Postgres中还有待进一步研究。

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.

我在其他答案中看到CREATE TABLE是事务性的并且可以回滚,所以我假设这应该工作。我尝试使用当前引擎启动新事务,并将其用于表创建(与当前Flask相比),但这也没有帮助。

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

这是Python 2.7,Postgres 9.1和Sqlalchemy 0.8.0b2。 / p>

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

推荐答案

(从评论中复制)

假设 sess 是会话,您可以执行 sess.execute(CreateTable(tenantX_tableY))

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

编辑: CreateTable 只是调用 table.create()<时要做的事情之一/ code>。改用 table.create(sess.connection())

这篇关于如何在Postgres的事务中使用Sqlalchemy创建表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆