doushao1087 2017-04-11 14:53
浏览 126
已采纳

如何推迟Postgres中的外键约束

I tried to set a foreign key constraint deferrable so that it won't be checked when I insert into a lookup/pivot table until end of transaction. However, it woks in psql shell but its just not working in the code. same as in the psql shell, I start a transaction with begin in code as well.

This is the sql:

create table campaign_r_company (
  campaign_id         uuid            not null references campaign(id) on delete cascade deferrable initially deferred,
  company_id          varchar(32)     not null,
  primary key (campaign_id, company_id)
);

Here's the code:

  tx, err := d.Begin()
  if err != nil {
    return err
  }


  err = h(tx) // there are two db queries will be called in this function

  if err == nil {
    err = tx.Commit()
  }

h(tx):

_, err := cxt.Exec(fmt.Sprintf(`INSERT INTO hp_campaign (%s) VALUES (%s)`, proplist("", campaignProps), arglist(1, len(campaignProps))),
    id, v.Name, created, v.Updated,
)
if err != nil {
    return err
}

v.Id = id
v.Created = created

if (opts & StoreOptionStoreRelated) == StoreOptionStoreRelated {
    err := d.attach("company", "campaign_r_company", v.Companies, v.Id)
    if err != nil {
        return err
    }

}

attach():

func (d *Database) attach(entityName string, tableName string, ids []string, campaignID string) error {

    for _, id := range ids {

        stmt := fmt.Sprintf(`INSERT INTO %s (%s) VALUES ($1, $2)`, tableName, fmt.Sprintf("campaign_id, %s_id", entityName))
        _, err := d.db.Exec(stmt, campaignID, id)

        if err != nil {
            return err
        }
    }
    return nil

}

Error:

insert or update on table "campaign_r_company" violates foreign key constraint "campaign_r_company_campaign_id_fkey"
  • 写回答

2条回答 默认 最新

  • douzhanbai9526 2017-04-11 18:55
    关注

    From the updated code, and subsequent comments, we know now that the issue was that the two queries were executed separately and not in a single transaction.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配