// Load a datastore value into a model and add the key func GetModel(ctx appengine.Context, key *datastore.Key, model models.Model) error { err := datastore.Get(ctx, key, model) if err == nil { model.SetKey(key) } return err }
func DeleteModel(ctx appengine.Context, model models.Model) error { key, err := model.Key() if err != nil { return err } return datastore.Delete(ctx, key) }
// If the key has already been added to the model, we can just generate // the key argument from the model. func GetModelWithKey(ctx appengine.Context, model models.Model) error { key, err := model.Key() if err != nil { return err } return GetModel(ctx, key, model) }
// Call the parent Next and set the model's key func (iterator *ModelIterator) Next(destModel models.Model) (*datastore.Key, error) { modelKey, err := iterator.Iterator.Next(destModel) if err == nil { destModel.SetKey(modelKey) } return modelKey, err }
// Load multiple datastore values into a slice of models func GetModels(ctx appengine.Context, keys []*datastore.Key, modelSlice []models.Model) error { err := datastore.GetMulti(ctx, keys, modelSlice) var ( index int model models.Model ) for index, model = range modelSlice { model.SetKey(keys[index]) } return err }
func (suite *datastoreTestSuite) TestModelIterator() { loadTestData(suite.GAEContext) query := NewModelQuery(kindForTest()) count, err := query.Count(suite.GAEContext) assert.Nil(suite.T, err, "Query should be countable.") assert.NotEqual(suite.T, count, 0, "Data should exist in the database by now.") iterator := query.Run(suite.GAEContext) var ( entry models.Model = new(testModel) key *datastore.Key ) for _, err := iterator.Next(entry); err != datastore.Done; _, err = iterator.Next(entry) { if err != nil { panic(err) } key, err = entry.Key() assert.NotNil(suite.T, key, "Query iterators should populate entry keys.") } }
// Store a Model, and call SetKey after generating its key (if it doesn't // have one already). func PutModel(ctx appengine.Context, model models.Model) error { modelKey, err := model.Key() if err == models.NoKeyLoaded { modelKey = datastore.NewIncompleteKey(ctx, model.Kind(), nil) } else if err != nil { panic(err) } key, err := datastore.Put(ctx, modelKey, model) if err == nil { model.SetKey(key) } return err }