我正在尝试向现有表添加外键约束。我之所以不只是在初始查询(创建表的查询)中添加外键,是因为我将有多个不同的引用(即,某些表将比其他表有更多的引用),并且在处理不确定性时,使用ALTER 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文档的规定这样做
Psycopg2抱怨是对的。我认为生成的SQL即使通过psql或其他客户端提交也无法工作
架构和表引用不应包括。分离器。让它生成以下内容:
您的问题似乎与缺少
"
有关请尝试修改此行:
为此:
相关问题 更多 >
编程相关推荐