如何在Postgres的事务中使用Sqlalchemy创建表?

编程入门 行业动态 更新时间:2024-10-24 18:19:02
本文介绍了如何在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()。改用 table.create(sess.connection())。

更多推荐

如何在Postgres的事务中使用Sqlalchemy创建表?

本文发布于:2023-10-13 10:31:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1487705.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:事务   如何在   Postgres   Sqlalchemy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!