使用 psycopg2 添加外键约束时出现问题

Problems when adding Foreign Key Constraints w/ psycopg2

我正在尝试向现有 table 添加外键约束。我不只是在初始查询(创建 table 的查询)中添加外键的原因是因为我将有多个不同的引用(即,一些 tables 将有比其他人更多的参考),并且使用 ALTER TABLE 似乎是处理不确定性的唯一选择。

现在,我遇到了以下问题:我尝试添加一个外键,它应该指向同一模式中的另一个 table。这是代码:

alter_query = """
                ALTER TABLE {schema}.{table}
                ADD CONSTRAINT {fk} FOREIGN KEY ({hashKey})
                REFERENCES {reference} ({hub_hash});
                """

#Note, that i = "company" in this example.

final_alter_query = sql.SQL(alter_query).format(
                                             schema=sql.Identifier(clientID),
                                             table=sql.Identifier(tableName),
                                             fk=sql.Identifier(tableName+"_"+i+"_hash_key_fk"),
                                             hashKey=sql.Identifier(i+"_hash_key"),
                                             reference=sql.Identifier(clientID+".hub_"+i),
                                             hub_hash=sql.Identifier(i+"_hash_key")
                                             )

为了更清楚一点,实际生成的SQL是:

    ALTER TABLE "c0001000_business_vault"."lnk_company_registration"
    ADD CONSTRAINT "lnk_company_registration_company_hash_key_fk" FOREIGN KEY ("company_hash_key")
    REFERENCES "c0001000_business_vault.hub_company" ("company_hash_key");

它给出了以下错误:(是的,关系确实存在)

cur2.execute(final_alter)
psycopg2.errors.UndefinedTable: relation "c0001000_business_vault.hub_company" does not exist

我不明白为什么它突然给我错误,因为当我使用没有 sql.Identifier 的格式时它可以工作,但我必须根据 psycopg2 文档这样做。

您的问题似乎与缺少 ".

有关

尝试修改这一行:

reference=sql.Identifier(clientID+".hub_"+i),

为此:

reference=sql.Identifier(clientID+"\".\"hub_"+i),

Psycopg2 的抱怨是对的。我认为即使通过 psql 或其他客户端提交,生成的 SQL 也不会起作用。

架构和 table 引用不应包含 .分隔器。让它生成这个:

 ALTER TABLE "c0001000_business_vault"."lnk_company_registration"
    ADD CONSTRAINT "lnk_company_registration_company_hash_key_fk" FOREIGN KEY ("company_hash_key")
    REFERENCES "c0001000_business_vault"."hub_company" ("company_hash_key");