1 // Copyright 2011 Google Inc. All rights reserved.
2 // Use of this source code is governed by the Apache 2.0
3 // license that can be found in the LICENSE file.
14 "github.com/golang/protobuf/proto"
16 "google.golang.org/appengine"
17 pb "google.golang.org/appengine/internal/datastore"
20 func toUnixMicro(t time.Time) int64 {
21 // We cannot use t.UnixNano() / 1e3 because we want to handle times more than
22 // 2^63 nanoseconds (which is about 292 years) away from 1970, and those cannot
23 // be represented in the numerator of a single int64 divide.
24 return t.Unix()*1e6 + int64(t.Nanosecond()/1e3)
27 func fromUnixMicro(t int64) time.Time {
28 return time.Unix(t/1e6, (t%1e6)*1e3).UTC()
32 minTime = time.Unix(int64(math.MinInt64)/1e6, (int64(math.MinInt64)%1e6)*1e3)
33 maxTime = time.Unix(int64(math.MaxInt64)/1e6, (int64(math.MaxInt64)%1e6)*1e3)
36 // valueToProto converts a named value to a newly allocated Property.
37 // The returned error string is empty on success.
38 func valueToProto(defaultAppID, name string, v reflect.Value, multiple bool) (p *pb.Property, errStr string) {
46 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
47 pv.Int64Value = proto.Int64(v.Int())
49 pv.BooleanValue = proto.Bool(v.Bool())
51 pv.StringValue = proto.String(v.String())
52 case reflect.Float32, reflect.Float64:
53 pv.DoubleValue = proto.Float64(v.Float())
55 if k, ok := v.Interface().(*Key); ok {
57 pv.Referencevalue = keyToReferenceValue(defaultAppID, k)
63 switch t := v.Interface().(type) {
65 if t.Before(minTime) || t.After(maxTime) {
66 return nil, "time value out of range"
68 pv.Int64Value = proto.Int64(toUnixMicro(t))
69 case appengine.GeoPoint:
71 return nil, "invalid GeoPoint value"
73 // NOTE: Strangely, latitude maps to X, longitude to Y.
74 pv.Pointvalue = &pb.PropertyValue_PointValue{X: &t.Lat, Y: &t.Lng}
79 if b, ok := v.Interface().([]byte); ok {
80 pv.StringValue = proto.String(string(b))
82 // nvToProto should already catch slice values.
83 // If we get here, we have a slice of slice values.
90 return nil, "unsupported datastore value type: " + v.Type().String()
93 Name: proto.String(name),
95 Multiple: proto.Bool(multiple),
98 switch v.Interface().(type) {
100 p.Meaning = pb.Property_BLOB.Enum()
102 p.Meaning = pb.Property_BYTESTRING.Enum()
103 case appengine.BlobKey:
104 p.Meaning = pb.Property_BLOBKEY.Enum()
106 p.Meaning = pb.Property_GD_WHEN.Enum()
107 case appengine.GeoPoint:
108 p.Meaning = pb.Property_GEORSS_POINT.Enum()
114 type saveOpts struct {
120 // saveEntity saves an EntityProto into a PropertyLoadSaver or struct pointer.
121 func saveEntity(defaultAppID string, key *Key, src interface{}) (*pb.EntityProto, error) {
124 if e, ok := src.(PropertyLoadSaver); ok {
125 props, err = e.Save()
127 props, err = SaveStruct(src)
132 return propertiesToProto(defaultAppID, key, props)
135 func saveStructProperty(props *[]Property, name string, opts saveOpts, v reflect.Value) error {
136 if opts.omitEmpty && isEmptyValue(v) {
141 NoIndex: opts.noIndex,
142 Multiple: opts.multiple,
144 switch x := v.Interface().(type) {
149 case appengine.BlobKey:
151 case appengine.GeoPoint:
157 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
163 case reflect.Float32, reflect.Float64:
166 if v.Type().Elem().Kind() == reflect.Uint8 {
172 return fmt.Errorf("datastore: unsupported struct field: value is unaddressable")
174 sub, err := newStructPLS(v.Addr().Interface())
176 return fmt.Errorf("datastore: unsupported struct field: %v", err)
178 return sub.save(props, name+".", opts)
182 return fmt.Errorf("datastore: unsupported struct field type: %v", v.Type())
184 *props = append(*props, p)
188 func (s structPLS) Save() ([]Property, error) {
190 if err := s.save(&props, "", saveOpts{}); err != nil {
196 func (s structPLS) save(props *[]Property, prefix string, opts saveOpts) error {
197 for name, f := range s.codec.fields {
199 v := s.v.FieldByIndex(f.path)
200 if !v.IsValid() || !v.CanSet() {
204 opts1.noIndex = opts.noIndex || f.noIndex
205 opts1.multiple = opts.multiple
206 opts1.omitEmpty = f.omitEmpty // don't propagate
207 // For slice fields that aren't []byte, save each element.
208 if v.Kind() == reflect.Slice && v.Type().Elem().Kind() != reflect.Uint8 {
209 opts1.multiple = true
210 for j := 0; j < v.Len(); j++ {
211 if err := saveStructProperty(props, name, opts1, v.Index(j)); err != nil {
217 // Otherwise, save the field itself.
218 if err := saveStructProperty(props, name, opts1, v); err != nil {
225 func propertiesToProto(defaultAppID string, key *Key, props []Property) (*pb.EntityProto, error) {
226 e := &pb.EntityProto{
227 Key: keyToProto(defaultAppID, key),
229 if key.parent == nil {
230 e.EntityGroup = &pb.Path{}
232 e.EntityGroup = keyToProto(defaultAppID, key.root()).Path
234 prevMultiple := make(map[string]bool)
236 for _, p := range props {
237 if pm, ok := prevMultiple[p.Name]; ok {
238 if !pm || !p.Multiple {
239 return nil, fmt.Errorf("datastore: multiple Properties with Name %q, but Multiple is false", p.Name)
242 prevMultiple[p.Name] = p.Multiple
246 Name: proto.String(p.Name),
247 Value: new(pb.PropertyValue),
248 Multiple: proto.Bool(p.Multiple),
250 switch v := p.Value.(type) {
252 x.Value.Int64Value = proto.Int64(v)
254 x.Value.BooleanValue = proto.Bool(v)
256 x.Value.StringValue = proto.String(v)
258 x.Meaning = pb.Property_TEXT.Enum()
261 x.Value.DoubleValue = proto.Float64(v)
264 x.Value.Referencevalue = keyToReferenceValue(defaultAppID, v)
267 if v.Before(minTime) || v.After(maxTime) {
268 return nil, fmt.Errorf("datastore: time value out of range")
270 x.Value.Int64Value = proto.Int64(toUnixMicro(v))
271 x.Meaning = pb.Property_GD_WHEN.Enum()
272 case appengine.BlobKey:
273 x.Value.StringValue = proto.String(string(v))
274 x.Meaning = pb.Property_BLOBKEY.Enum()
275 case appengine.GeoPoint:
277 return nil, fmt.Errorf("datastore: invalid GeoPoint value")
279 // NOTE: Strangely, latitude maps to X, longitude to Y.
280 x.Value.Pointvalue = &pb.PropertyValue_PointValue{X: &v.Lat, Y: &v.Lng}
281 x.Meaning = pb.Property_GEORSS_POINT.Enum()
283 x.Value.StringValue = proto.String(string(v))
284 x.Meaning = pb.Property_BLOB.Enum()
286 return nil, fmt.Errorf("datastore: cannot index a []byte valued Property with Name %q", p.Name)
289 x.Value.StringValue = proto.String(string(v))
290 x.Meaning = pb.Property_BYTESTRING.Enum()
293 return nil, fmt.Errorf("datastore: invalid Value type for a Property with Name %q", p.Name)
298 e.RawProperty = append(e.RawProperty, x)
300 e.Property = append(e.Property, x)
301 if len(e.Property) > maxIndexedProperties {
302 return nil, errors.New("datastore: too many indexed properties")
309 // isEmptyValue is taken from the encoding/json package in the standard library.
310 func isEmptyValue(v reflect.Value) bool {
312 case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
313 // TODO(perfomance): Only reflect.String needed, other property types are not supported (copy/paste from json package)
317 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
319 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
320 // TODO(perfomance): Uint* are unsupported property types - should be removed (copy/paste from json package)
322 case reflect.Float32, reflect.Float64:
323 return v.Float() == 0
324 case reflect.Interface, reflect.Ptr:
327 switch x := v.Interface().(type) {