The Google App Engine Datastore provides a powerful data storage solution for web applications, offering flexibility and scalability. Sometimes, there's a need to store data with dynamic properties, meaning properties that are not declared ahead of time. This can be achieved in Go by leveraging Google App Engine's PropertyLoadSaver interface.
The PropertyLoadSaver interface allows you to define how an entity's properties should be loaded and saved to the datastore. By implementing this interface, you gain control over the dynamic property handling.
The Go App Engine platform provides a PropertyList type that implements the PropertyLoadSaver interface. PropertyList is essentially a slice of properties, allowing you to add and remove properties dynamically.
To create an entity with dynamic properties using PropertyList, follow these steps:
import "google.golang.org/appengine/datastore" // Create a PropertyList to hold the dynamic properties. props := datastore.PropertyList{ datastore.Property{Name: "time", Value: time.Now()}, datastore.Property{Name: "email", Value: "[email protected]"}, } // Create an incomplete key for the new entity. k := datastore.NewIncompleteKey(ctx, "DynEntity", nil) // Save the entity using the PropertyList. key, err := datastore.Put(ctx, k, &props)
This code snippet creates an entity with the "DynEntity" kind and two dynamic properties: "time" and "email." The PropertyList is saved as the value for the entity.
You can also implement your own PropertyLoadSaver if required. Here's an example using a custom type called "DynEnt":
import "google.golang.org/appengine/datastore" type DynEnt map[string]interface{} func (d *DynEnt) Load(props []datastore.Property) error { for _, p := range props { (*d)[p.Name] = p.Value } return nil } func (d *DynEnt) Save(props []datastore.Property, err error) error { for k, v := range *d { props = append(props, datastore.Property{Name: k, Value: v}) } return err }
This DynEnt type can then be used to store entities with dynamic properties, as shown below:
import "google.golang.org/appengine/datastore" // Create a DynEnt with dynamic properties. d := DynEnt{"email": "[email protected]", "time": time.Now()} // Create an incomplete key for the new entity. k := datastore.NewIncompleteKey(ctx, "DynEntity", nil) // Save the entity using the DynEnt. key, err := datastore.Put(ctx, k, &d)
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3