0

我试图设置一个可延迟的外键约束,以便在事务结束之前插入查找/数据透视表时不会对其进行检查。但是,它可以在 psql shell 中工作,但它不能在代码中工作。与在 psql shell 中一样,我也使用beginin 代码启动事务。

这是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)
);

这是代码:

  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
    }

}

附():

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

}

错误:

insert or update on table "campaign_r_company" violates foreign key constraint "campaign_r_company_campaign_id_fkey"
4

2 回答 2

0

如果您不使用手动事务管理,Go+PG 会为您执行此操作。在这种情况下,任何语句都是单个事务,并且在每个语句结束时都会检查约束。所以引发了异常。

于 2017-04-11T18:19:43.767 回答
0

从更新的代码和随后的注释中,我们现在知道问题在于这两个查询是分开执行的,而不是在一个事务中。

于 2017-04-11T18:55:33.840 回答