gpt4 book ai didi

python - SQLAlchemy 在 PostgresQL 中创建 View

转载 作者:行者123 更新时间:2023-11-29 12:16:04 25 4
gpt4 key购买 nike

我正在尝试使用 SQLAlchemy 创建一个 View ,并将 Postgresql 作为基础数据库。创建 View 的单独选择查询运行良好并返回结果,但是当我在创建 View 中使用它时,出现错误 sqlalchemy.exc.NoSuchTableError: popular,这意味着未选择 View 。当我尝试从 View 中选择时出现错误。创建 View 不会引发任何错误,但不会创建 View 。这是我的代码:

from sqlalchemy import *
import sqlalchemy as db
from sqlalchemy import func
from sqlalchemy import desc
from sqlalchemy import Table
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.expression import Executable, ClauseElement

try:
engine = db.create_engine('postgresql://user:pass@localhost:5432/db_name')
connection = engine.connect()

except:
print('Error establishing DB connection')

# Import metadata
metadata = db.MetaData()

# Import articles, authors and log tables
art = db.Table('articles', metadata, autoload=True, autoload_with=engine)
aut = db.Table('authors', metadata, autoload=True, autoload_with=engine)
log = db.Table('log', metadata, autoload=True, autoload_with=engine)


class CreateView(Executable, ClauseElement):
def __init__(self, name, select):
self.name = name
self.select = select


@compiles(CreateView)
def visit_create_view(element, compiler, **kw):
return "CREATE VIEW %s AS %s" % (
element.name,
compiler.process(element.select, literal_binds=True)
)



# Method to create view with top three articles
def view_top_three():
top_three_view = CreateView('popular', db.select([art.columns.title, func.count(log.columns.path)]) \
.where(func.concat('/article/', art.columns.slug) == log.columns.path) \
.where(log.columns.path != "/") \
.group_by(log.columns.path, art.columns.title) \
.order_by(desc(func.count(log.columns.path))) \
.limit(3))

engine.execute(top_three_view)
v = Table('popular', metadata, autoload=True, autoload_with=engine)
for r in engine.execute(v.select()):
print(r)


# Call the method which creates view and selects from view
view_top_three()

任何帮助将不胜感激。

最佳答案

由于您的 CreateView 继承自 ExecutableClauseElement,因此它不被视为数据更改操作。也就是说

engine.execute(top_three_view)

执行 CREATE VIEW 语句,然后在连接返回池时隐式回滚。

相反,它应该是 DDLElement 的子类, 如 usage recipes wiki 所示.简单地更改基类将允许 SQLAlchemy autocommit才能正常工作。

关于python - SQLAlchemy 在 PostgresQL 中创建 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53498756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com