首页 > 解决方案 > 我收到错误:在 else 语句中查询已释放或丢失的连接

问题描述

这是代码,我正在尝试检查插入语句的结果。如果它为null(如果标签标题已经存在),它必须执行else语句。但它在 else 语句中失败,抛出丢失的连接错误。

 return this.store.tx('create-tags', async (transaction: any) => {
    tagDetails.forEach((tag: any) => {
     transaction
      .oneOrNone(
      `INSERT INTO tag(title)
         VALUES ($1)
         ON CONFLICT DO NOTHING
         RETURNING tag_id, title`,
        [tag.title],
      )
        .then((result: any) => {
            console.log('the tag details are', result);
           if (result !== null) {
              this.createTags(collectionId, tag.item_id, result.tag_id);
            } else {
           transaction.oneOrNone(
           `
           SELECT tag_id
           FROM tag
           WHERE title = $1
           `,
           [tag.title],
              ).then((tagId: string) => {
               console.log('the tagid in else statement is', tagId);
              if (tagId) {
                this.createTags(collectionId, tag.item_id, tagId);
               }
             })
             .catch(err => {
               console.log('the error in else statement is', err);
             });
       }
      });
  });

标签: javascriptpostgresqlpg-promise

解决方案


您的代码显示了许多问题。

主要的,也是您收到错误的原因,是因为您未能将查询结果链接到事务结果中。您最终会尝试在事务上下文之外执行多个查询,因此会出现错误。这是一个修改后的版本,可以解决这个问题:

return this.store.tx('create-tags', t => {
    const res = tagDetails.map((tag: any) => {
        return t.oneOrNone(`INSERT INTO tag(title) VALUES ($1) ON CONFLICT DO NOTHING RETURNING tag_id, title`,
            [tag.title],
        )
            .then((result: any) => {
                console.log('the tag details are', result);
                if (result !== null) {
                    return this.createTags(collectionId, tag.item_id, result.tag_id);
                } else {
                    return t.oneOrNone(`SELECT tag_id FROM tag WHERE title = $1`, [tag.title])
                        .then((tagId: string) => {
                            console.log('the tagid in else statement is', tagId);
                            if (tagId) {
                                return this.createTags(collectionId, tag.item_id, tagId);
                            }
                        })
                        .catch(err => {
                            console.log('the error in else statement is', err);
                        });
                }
            });
    });
    return t.batch(res);
});

但是,这并不是特别好,原因如下:

  • 您应该使用完整的async代码重写它
  • 您应该在事务之外进行错误处理
  • 您的整个代码看起来可以只用一个查询替换。
  • 我们不知道是什么createTags,因此无法对此发表评论

推荐阅读