簡體   English   中英

Appengine Datastore查詢在事務內返回不同的結果

[英]Appengine Datastore query returns different result inside transaction

希望有人可以在我的代碼中幫助指出問題。

我在事務外定義了一個查詢,當它被執行時,它正確匹配數據庫中的現有記錄。

但是,在事務內部執行查詢的那一刻,它無法匹配數據庫中的現有記錄,盡管它們存在。

這是代碼,輸出如下:

// 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):在事務內只允許祖先查詢。

將評論轉換為答案

事實證明,當嘗試在事務中執行非祖先查詢時,這是特定於行為的行為(FWIW,在python中嘗試這樣做實際上會引發異常)。

祖先查詢是事務內允許的唯一查詢。 事務中可以做什么 (不是非常明確的,因為查詢可以返回不符合事務限制的實體,因此IMHO隱含):

如果事務是單組事務,則事務中的所有Cloud Datastore操作必須對同一實體組中的實體進行操作;如果事務是跨組事務,則必須對最多25個實體組中的實體進行操作。 這包括由祖先查詢實體,按鍵檢索實體,更新實體和刪除實體。 請注意,每個根實體都屬於一個單獨的實體組,因此單個事務不能在多個根實體上創建或操作,除非它是跨組事務。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM