简体   繁体   English

Web2py-使用单独的SQL数据库进行归档时的密钥/约束问题

[英]Web2py - Key/constraint issue when using separate SQL database for archiving

In a web2py application, I've got a primary postgresql database (db1), and I've set up a separate postgresql database (db1_archive) used for archiving several of the tables from db1. 在一个web2py应用程序中,我有一个主要的postgresql数据库(db1),并且设置了一个单独的postgresql数据库(db1_archive),用于从db1归档多个表。 This functionality is implemented in a module with the following: 此功能在具有以下功能的模块中实现:

class db_archives():

    def __init__(self, request, response, db1_archive, db1, auth):

        ...

        auth.enable_record_versioning(
            archive_db = db1_archive,
            tables = [db1.auth_user, db1.table1, db1.table2, ...]
            archive_names='archive_%(tablename)s'
            )

When something is deleted from the relevant tables in db1, it should automatically be archived in db1_archive. 从db1的相关表中删除某些内容后,应将其自动归档到db1_archive中。 However, upon deletion, the following psycopg2.IntegrityError is produced instead: 但是,删除后,将产生以下psycopg2.IntegrityError:

insert or update on table "archive_table1" violates foreign key constraint "archive_table1_created_by_fkey" DETAIL: Key (created_by)=(9) is > not present in table "auth_user" 在表“ archive_table1”上进行插入或更新违反了外键约束“ archive_table1_created_by_fkey”详细信息:表(auth_user)中不存在键(created_by)=(9)

I guess what's happening is that the archive DB is not finding a user with an ID of 9. The 'created_by' field has the following constraint: 我猜发生了什么事,就是归档数据库找不到ID为9的用户。“ created_by”字段具有以下约束:

FOREIGN KEY (created_by) REFERENCES auth_user(id) ON DELETE CASCADE

I'd like to remove all constraints from the archive db. 我想从存档数据库中删除所有约束。 I think this can be done with web2py's [database_name].executesql() function. 我认为可以使用web2py的[database_name].executesql()函数完成此操作。 However, I've tried a few things such as db1_archive.executesql('SET FOREIGN_KEY_CHECKS=0;') , and only ended up with error messages. 但是,我尝试了一些事情,例如db1_archive.executesql('SET FOREIGN_KEY_CHECKS=0;') ,但最后只收到错误消息。 Can anyone advise me on some SQL or web2py codes I could try to fix the situation? 谁能在某些SQL或Web2py代码上为我提供建议,我可以尝试解决此问题? Thanks. 谢谢。

What you need to do is build a list of the constraint names and then walk through them in your code and: 您需要做的是建立一个约束名称列表,然后在代码中遍历它们,并:

alter table [tablename] drop constraint [fkeyname];

If you need to pull this info from the system catalogs, see the pg_constraint table. 如果您需要从系统目录中获取此信息,请参见pg_constraint表。

Please note that alter table cannot be parameterized so you will have to assemble the command as a string with proper escaping and run it. 请注意,不能对alter table进行参数化,因此您必须将命令汇编为带有适当转义符的字符串,然后运行它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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