Cug*_*uga 4 google-app-engine go google-cloud-datastore
希望有人可以在我的代码中帮助指出问题.
我在事务外定义了一个查询,当它被执行时,它正确匹配数据库中的现有记录.
但是,在事务内部执行查询的那一刻,它无法匹配数据库中的现有记录,尽管它们存在.
这是代码,输出如下:
// 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)
Run Code Online (Sandbox Code Playgroud)
正如您在输出中看到的,事务外部的第一个查询正确匹配现有记录.但在交易中,它无法识别现有记录:
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
Run Code Online (Sandbox Code Playgroud)
在此先感谢您的帮助
更新
Dan的评论导致在事务内的查询上打印出错误消息:
if err != nil {
log.Errorf(ctx, "Issue running in transaction: %v", err)
}
Run Code Online (Sandbox Code Playgroud)
哪个印刷品:
错误:在事务中运行的问题:API错误1(datastore_v3:BAD_REQUEST):在事务内只允许祖先查询.
将评论转换为答案
事实证明,当尝试在事务中执行非祖先查询时,这是特定于行为的行为(FWIW,在python中尝试这样做实际上会引发异常).
祖先查询是事务内允许的唯一查询.从事务中可以做什么(不是非常明确的,因为查询可以返回不符合事务限制的实体,因此IMHO隐含):
如果事务是单组事务,则事务中的所有Cloud Datastore操作必须对同一实体组中的实体进行操作;如果事务是跨组事务,则必须对最多25个实体组中的实体进行操作.这包括由祖先查询实体,按键检索实体,更新实体和删除实体.请注意,每个根实体都属于一个单独的实体组,因此单个事务不能在多个根实体上创建或操作,除非它是跨组事务.