I want to create two tables, er entities:
User { UserID: String, UserName: String }
UserSession { SessionID: String, UserID: String, LoginTime: Date }
Using the console dashboard in gae, I can't seem to be able to define the UserSession's UserID (a sort of secondary key) to represent the key in the first entity such as Key('User', 'UserID')
. The syntax fails.
Extra issue: I can't define the LoginTime as a date because it wants a default value. Why can't the property be set as blank when creating the entity?
UPDATE
Here is the code I am using. Can you please validate if this is the right way to get back user data by linking the entities with parenting?
package testapp
import (
"fmt"
"net/http"
"time"
"appengine"
"appengine/datastore"
)
type User struct {
Name string
FullName string `datastore:",noindex"`
Password string `datastore:",noindex"`
IsDisabled bool `datastore:",noindex"`
}
type Session struct {
LoginTime time.Time `datastore:",noindex"`
LastSeen time.Time `datastore:",noindex"`
}
func init() {
http.HandleFunc("/", handler)
}
func handler(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
u := User{
Name: "john",
FullName: "John Difool",
Password: "secret",
IsDisabled: false}
userId, err := datastore.Put(c, datastore.NewIncompleteKey(c, "user", nil), &u)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
s := Session{
LoginTime: time.Now(),
LastSeen: time.Now()}
key, err := datastore.Put(c, datastore.NewIncompleteKey(c, "session", userId), &s) // parent is user
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// store key and later on get it back
t := new(Session)
if err := datastore.Get(c, key, t); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// let's get back user's data using parent key
e := new(User)
if err := datastore.Get(c, key.Parent(), e); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprintf(w, "name=%q
password=%q
", e.Name, e.Password)
}