用于使用 Pandas 导入 .csv to_sql 的 Python 脚本失败,除非我 DROP TRIGGER 更新物化 View

标签 python postgresql triggers materialized-views

我有一个 Postgres 数据库,其中有一个带有物化 View 的表,每次通过以下用户定义的函数和触发器对表进行更改时,该 View 都会自动更新:

create function refresh_matview_dohscrapemat()
returns trigger language plpgsql
as $$
begin
    refresh materialized view dohscrape;
    return null;
end $$;
create trigger refresh_matview_dohscrapemat
after insert or update or delete or truncate
on dohscrape for each statement
execute procedure refresh_matview_dohscrapemat();

我有一个 python 脚本,它使用 pandas 自动将 .csv 文件导入到这个表中,只有当我在运行它之前删除 TRIGGER 以更新实体化 View 时它才有效。

如果我尝试在不删除触发器的情况下运行脚本,我会收到以下错误:

sqlalchemy.exc.NotSupportedError: (psycopg2.NotSupportedError) "dohscrape" is not a materialized view CONTEXT: SQL statement "refresh materialized view dohscrape" PL/pgSQL function refresh_matview_dohscrapemat() line 3 at SQL statement [SQL: 'INSERT INTO dohscrape (filename, content) VALUES (%(filename)s, %(content)s)'] [parameters: ({'filename':...(Background on this error at: http://sqlalche.me/e/tw8g)

它说“dohscrape”不是物化 View ,这是正确的,因为那是表的名称而不是物化 View 。实体化 View 被命名为“dohscrapemat”。

错误消息中的链接指向以下信息:

NotSupportedError Exception raised in case a method or database API was used which is not supported by the database, e.g. requesting a .rollback() on a connection that does not support transaction or has transactions turned off.

This error is a DBAPI Error and originates from the database driver (DBAPI), not SQLAlchemy itself.

但我看不出这与由更新物化 View 的触发器引起/相关的错误有何关系,我认为这是根本问题,因为删除它可以解决错误。

一旦我让脚本上传到表并重新创建触发器,一切正常,但我希望能够运行此脚本而不必删除并重新创建触发器。

为什么刷新实体化 View 的触发器会导致导入错误?为什么 pandas/sqlalchemy/psycopg2 将我的表与其物化 View 混淆了?

上传到数据库的 python 脚本中的代码片段是:

for files in source:
    if files.endswith(".csv"):
        df = pd.read_csv(os.path.join(sourcepath,files))
        df.to_sql(name='dohscrape',con=dbconn,if_exists='append',index=False)

我正在使用 Python 3.7 和 Postgres 11。

最佳答案

It says "dohscrape" is not a materialized view, which is correct because that's the name of the table not the materialized view. The materialized view is named "dohscrapemat".

所以你的触发函数显然是错误的。替换

    refresh materialized view dohscrape; -- error

    refresh materialized view dohscrapemat;

关于用于使用 Pandas 导入 .csv to_sql 的 Python 脚本失败,除非我 DROP TRIGGER 更新物化 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54452003/

相关文章:

swift - 为 UNNotificationRequest 检索下一个请求日期和关联的 ID

python - Pandas:带有两个条形图和两个 y 轴的条形图

python - 扩展列表理解(以更好地理解它)?

javascript - 在选择更改时打开下一个选择元素

Postgresql 将单行拆分为多行

sql - PostgreSQL 不在多个通配符中

sql-server - TSql 触发器只需要在值已更改的列上触发

python - 多处理中共享项目是否有内存限制?

python - 创建一个 matplotlib 散点图例大小相关

sql - Postgres 创建 View 而不是 View