登录
首页 >  Golang >  Go问答

Appengine 数据存储区查询在事务内返回不同的结果

来源:stackoverflow

时间:2024-04-21 09:06:35 445浏览 收藏

哈喽!今天心血来潮给大家带来了《Appengine 数据存储区查询在事务内返回不同的结果》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!

问题内容

希望有人能帮助指出我代码中的问题。

我在事务外部定义了一个查询,当执行该查询时,它会正确匹配数据库中的现有记录。

但是,当在事务内执行查询时,它无法匹配数据库中的现有记录,尽管它们确实存在。

这是代码,输出如下:

// query for url to see if any already exist
existingremoteurlquery := datastore.newquery("repostats").
    filter("repourl =", statstosave.repourl).
    keysonly().limit(1)

testkey, _ := existingremoteurlquery.getall(ctx, new(models.repostats))
if len(testkey) > 0 {
    log.infof(ctx, "test update existing record vice new key")
} else {
    log.infof(ctx, "test no existing key found, use new key")
}

// check if we already have a record with this remote url
var key *datastore.key

err := datastore.runintransaction(ctx, func(ctx context.context) error {
    // this function's argument ctx shadows the variable ctx from the surrounding function.

    // last parameter is ignored because it's a keys-only query
    existingkeys, err := existingremoteurlquery.getall(ctx, new(models.repostats))
    if len(existingkeys) > 0 {
        log.infof(ctx, "update existing record vice new key")
        // use existing key
        key = existingkeys[0]

    } else {
        log.infof(ctx, "no existing key found, use new key")
        key = datastore.newincompletekey(ctx, "repostats", nil)
    }

    return err
}, nil)

正如您在输出中看到的,事务外部的第一个查询与现有记录正确匹配。但在事务内部,它无法识别现有记录:

2018/08/28 11:50:47 info: test update existing record vice new key
2018/08/28 11:50:47 info: no existing key found, use new key

感谢您提前提供的帮助

已更新

dan 的评论导致打印出事务内查询的错误消息:

if err != nil {
        log.Errorf(ctx, "Issue running in transaction: %v", err)
    }

打印内容:

错误:事务中运行的问题:api 错误 1(datastore_v3:bad_request):事务内仅允许祖先查询。


解决方案


将评论转换为答案

事实证明,这是尝试在事务内执行非祖先查询时特定于 go 的行为(FWIW,在 python 中尝试这样做实际上会引发异常)。

祖先查询是事务内唯一允许的查询。来自 What can be done in a transaction(不是很明确,恕我直言,隐含的,因为查询可能返回不满足交易限制的实体):

事务中的所有 Cloud Datastore 操作都必须在 如果交易是单组,则同一实体组中的实体 交易,或最多二十五个实体组中的实体 如果交易是跨集团交易。这包括 按祖先查询实体,按键检索实体, 更新实体和删除实体。请注意,每个根实体 属于一个单独的实体组,因此单个交易不能 创建或操作多个根实体,除非它是一个 跨组交易。

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>