load.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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.
  4. package datastore
  5. import (
  6. "fmt"
  7. "reflect"
  8. "strings"
  9. "time"
  10. "github.com/golang/protobuf/proto"
  11. "google.golang.org/appengine"
  12. pb "google.golang.org/appengine/internal/datastore"
  13. )
  14. var (
  15. typeOfBlobKey = reflect.TypeOf(appengine.BlobKey(""))
  16. typeOfByteSlice = reflect.TypeOf([]byte(nil))
  17. typeOfByteString = reflect.TypeOf(ByteString(nil))
  18. typeOfGeoPoint = reflect.TypeOf(appengine.GeoPoint{})
  19. typeOfTime = reflect.TypeOf(time.Time{})
  20. typeOfKeyPtr = reflect.TypeOf(&Key{})
  21. typeOfEntityPtr = reflect.TypeOf(&Entity{})
  22. )
  23. // typeMismatchReason returns a string explaining why the property p could not
  24. // be stored in an entity field of type v.Type().
  25. func typeMismatchReason(pValue interface{}, v reflect.Value) string {
  26. entityType := "empty"
  27. switch pValue.(type) {
  28. case int64:
  29. entityType = "int"
  30. case bool:
  31. entityType = "bool"
  32. case string:
  33. entityType = "string"
  34. case float64:
  35. entityType = "float"
  36. case *Key:
  37. entityType = "*datastore.Key"
  38. case time.Time:
  39. entityType = "time.Time"
  40. case appengine.BlobKey:
  41. entityType = "appengine.BlobKey"
  42. case appengine.GeoPoint:
  43. entityType = "appengine.GeoPoint"
  44. case ByteString:
  45. entityType = "datastore.ByteString"
  46. case []byte:
  47. entityType = "[]byte"
  48. }
  49. return fmt.Sprintf("type mismatch: %s versus %v", entityType, v.Type())
  50. }
  51. type propertyLoader struct {
  52. // m holds the number of times a substruct field like "Foo.Bar.Baz" has
  53. // been seen so far. The map is constructed lazily.
  54. m map[string]int
  55. }
  56. func (l *propertyLoader) load(codec *structCodec, structValue reflect.Value, p Property, requireSlice bool) string {
  57. var v reflect.Value
  58. var sliceIndex int
  59. name := p.Name
  60. // If name ends with a '.', the last field is anonymous.
  61. // In this case, strings.Split will give us "" as the
  62. // last element of our fields slice, which will match the ""
  63. // field name in the substruct codec.
  64. fields := strings.Split(name, ".")
  65. for len(fields) > 0 {
  66. var decoder fieldCodec
  67. var ok bool
  68. // Cut off the last field (delimited by ".") and find its parent
  69. // in the codec.
  70. // eg. for name "A.B.C.D", split off "A.B.C" and try to
  71. // find a field in the codec with this name.
  72. // Loop again with "A.B", etc.
  73. for i := len(fields); i > 0; i-- {
  74. parent := strings.Join(fields[:i], ".")
  75. decoder, ok = codec.fields[parent]
  76. if ok {
  77. fields = fields[i:]
  78. break
  79. }
  80. }
  81. // If we never found a matching field in the codec, return
  82. // error message.
  83. if !ok {
  84. return "no such struct field"
  85. }
  86. v = initField(structValue, decoder.path)
  87. if !v.IsValid() {
  88. return "no such struct field"
  89. }
  90. if !v.CanSet() {
  91. return "cannot set struct field"
  92. }
  93. if decoder.structCodec != nil {
  94. codec = decoder.structCodec
  95. structValue = v
  96. }
  97. if v.Kind() == reflect.Slice && v.Type() != typeOfByteSlice {
  98. if l.m == nil {
  99. l.m = make(map[string]int)
  100. }
  101. sliceIndex = l.m[p.Name]
  102. l.m[p.Name] = sliceIndex + 1
  103. for v.Len() <= sliceIndex {
  104. v.Set(reflect.Append(v, reflect.New(v.Type().Elem()).Elem()))
  105. }
  106. structValue = v.Index(sliceIndex)
  107. requireSlice = false
  108. }
  109. }
  110. var slice reflect.Value
  111. if v.Kind() == reflect.Slice && v.Type().Elem().Kind() != reflect.Uint8 {
  112. slice = v
  113. v = reflect.New(v.Type().Elem()).Elem()
  114. } else if requireSlice {
  115. return "multiple-valued property requires a slice field type"
  116. }
  117. // Convert indexValues to a Go value with a meaning derived from the
  118. // destination type.
  119. pValue := p.Value
  120. if iv, ok := pValue.(indexValue); ok {
  121. meaning := pb.Property_NO_MEANING
  122. switch v.Type() {
  123. case typeOfBlobKey:
  124. meaning = pb.Property_BLOBKEY
  125. case typeOfByteSlice:
  126. meaning = pb.Property_BLOB
  127. case typeOfByteString:
  128. meaning = pb.Property_BYTESTRING
  129. case typeOfGeoPoint:
  130. meaning = pb.Property_GEORSS_POINT
  131. case typeOfTime:
  132. meaning = pb.Property_GD_WHEN
  133. case typeOfEntityPtr:
  134. meaning = pb.Property_ENTITY_PROTO
  135. }
  136. var err error
  137. pValue, err = propValue(iv.value, meaning)
  138. if err != nil {
  139. return err.Error()
  140. }
  141. }
  142. if errReason := setVal(v, pValue); errReason != "" {
  143. // Set the slice back to its zero value.
  144. if slice.IsValid() {
  145. slice.Set(reflect.Zero(slice.Type()))
  146. }
  147. return errReason
  148. }
  149. if slice.IsValid() {
  150. slice.Index(sliceIndex).Set(v)
  151. }
  152. return ""
  153. }
  154. // setVal sets v to the value pValue.
  155. func setVal(v reflect.Value, pValue interface{}) string {
  156. switch v.Kind() {
  157. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  158. x, ok := pValue.(int64)
  159. if !ok && pValue != nil {
  160. return typeMismatchReason(pValue, v)
  161. }
  162. if v.OverflowInt(x) {
  163. return fmt.Sprintf("value %v overflows struct field of type %v", x, v.Type())
  164. }
  165. v.SetInt(x)
  166. case reflect.Bool:
  167. x, ok := pValue.(bool)
  168. if !ok && pValue != nil {
  169. return typeMismatchReason(pValue, v)
  170. }
  171. v.SetBool(x)
  172. case reflect.String:
  173. switch x := pValue.(type) {
  174. case appengine.BlobKey:
  175. v.SetString(string(x))
  176. case ByteString:
  177. v.SetString(string(x))
  178. case string:
  179. v.SetString(x)
  180. default:
  181. if pValue != nil {
  182. return typeMismatchReason(pValue, v)
  183. }
  184. }
  185. case reflect.Float32, reflect.Float64:
  186. x, ok := pValue.(float64)
  187. if !ok && pValue != nil {
  188. return typeMismatchReason(pValue, v)
  189. }
  190. if v.OverflowFloat(x) {
  191. return fmt.Sprintf("value %v overflows struct field of type %v", x, v.Type())
  192. }
  193. v.SetFloat(x)
  194. case reflect.Ptr:
  195. x, ok := pValue.(*Key)
  196. if !ok && pValue != nil {
  197. return typeMismatchReason(pValue, v)
  198. }
  199. if _, ok := v.Interface().(*Key); !ok {
  200. return typeMismatchReason(pValue, v)
  201. }
  202. v.Set(reflect.ValueOf(x))
  203. case reflect.Struct:
  204. switch v.Type() {
  205. case typeOfTime:
  206. x, ok := pValue.(time.Time)
  207. if !ok && pValue != nil {
  208. return typeMismatchReason(pValue, v)
  209. }
  210. v.Set(reflect.ValueOf(x))
  211. case typeOfGeoPoint:
  212. x, ok := pValue.(appengine.GeoPoint)
  213. if !ok && pValue != nil {
  214. return typeMismatchReason(pValue, v)
  215. }
  216. v.Set(reflect.ValueOf(x))
  217. default:
  218. ent, ok := pValue.(*Entity)
  219. if !ok {
  220. return typeMismatchReason(pValue, v)
  221. }
  222. // Recursively load nested struct
  223. pls, err := newStructPLS(v.Addr().Interface())
  224. if err != nil {
  225. return err.Error()
  226. }
  227. // if ent has a Key value and our struct has a Key field,
  228. // load the Entity's Key value into the Key field on the struct.
  229. if ent.Key != nil && pls.codec.keyField != -1 {
  230. pls.v.Field(pls.codec.keyField).Set(reflect.ValueOf(ent.Key))
  231. }
  232. err = pls.Load(ent.Properties)
  233. if err != nil {
  234. return err.Error()
  235. }
  236. }
  237. case reflect.Slice:
  238. x, ok := pValue.([]byte)
  239. if !ok {
  240. if y, yok := pValue.(ByteString); yok {
  241. x, ok = []byte(y), true
  242. }
  243. }
  244. if !ok && pValue != nil {
  245. return typeMismatchReason(pValue, v)
  246. }
  247. if v.Type().Elem().Kind() != reflect.Uint8 {
  248. return typeMismatchReason(pValue, v)
  249. }
  250. v.SetBytes(x)
  251. default:
  252. return typeMismatchReason(pValue, v)
  253. }
  254. return ""
  255. }
  256. // initField is similar to reflect's Value.FieldByIndex, in that it
  257. // returns the nested struct field corresponding to index, but it
  258. // initialises any nil pointers encountered when traversing the structure.
  259. func initField(val reflect.Value, index []int) reflect.Value {
  260. for _, i := range index[:len(index)-1] {
  261. val = val.Field(i)
  262. if val.Kind() == reflect.Ptr {
  263. if val.IsNil() {
  264. val.Set(reflect.New(val.Type().Elem()))
  265. }
  266. val = val.Elem()
  267. }
  268. }
  269. return val.Field(index[len(index)-1])
  270. }
  271. // loadEntity loads an EntityProto into PropertyLoadSaver or struct pointer.
  272. func loadEntity(dst interface{}, src *pb.EntityProto) (err error) {
  273. ent, err := protoToEntity(src)
  274. if err != nil {
  275. return err
  276. }
  277. if e, ok := dst.(PropertyLoadSaver); ok {
  278. return e.Load(ent.Properties)
  279. }
  280. return LoadStruct(dst, ent.Properties)
  281. }
  282. func (s structPLS) Load(props []Property) error {
  283. var fieldName, reason string
  284. var l propertyLoader
  285. for _, p := range props {
  286. if errStr := l.load(s.codec, s.v, p, p.Multiple); errStr != "" {
  287. // We don't return early, as we try to load as many properties as possible.
  288. // It is valid to load an entity into a struct that cannot fully represent it.
  289. // That case returns an error, but the caller is free to ignore it.
  290. fieldName, reason = p.Name, errStr
  291. }
  292. }
  293. if reason != "" {
  294. return &ErrFieldMismatch{
  295. StructType: s.v.Type(),
  296. FieldName: fieldName,
  297. Reason: reason,
  298. }
  299. }
  300. return nil
  301. }
  302. func protoToEntity(src *pb.EntityProto) (*Entity, error) {
  303. props, rawProps := src.Property, src.RawProperty
  304. outProps := make([]Property, 0, len(props)+len(rawProps))
  305. for {
  306. var (
  307. x *pb.Property
  308. noIndex bool
  309. )
  310. if len(props) > 0 {
  311. x, props = props[0], props[1:]
  312. } else if len(rawProps) > 0 {
  313. x, rawProps = rawProps[0], rawProps[1:]
  314. noIndex = true
  315. } else {
  316. break
  317. }
  318. var value interface{}
  319. if x.Meaning != nil && *x.Meaning == pb.Property_INDEX_VALUE {
  320. value = indexValue{x.Value}
  321. } else {
  322. var err error
  323. value, err = propValue(x.Value, x.GetMeaning())
  324. if err != nil {
  325. return nil, err
  326. }
  327. }
  328. outProps = append(outProps, Property{
  329. Name: x.GetName(),
  330. Value: value,
  331. NoIndex: noIndex,
  332. Multiple: x.GetMultiple(),
  333. })
  334. }
  335. var key *Key
  336. if src.Key != nil {
  337. // Ignore any error, since nested entity values
  338. // are allowed to have an invalid key.
  339. key, _ = protoToKey(src.Key)
  340. }
  341. return &Entity{key, outProps}, nil
  342. }
  343. // propValue returns a Go value that combines the raw PropertyValue with a
  344. // meaning. For example, an Int64Value with GD_WHEN becomes a time.Time.
  345. func propValue(v *pb.PropertyValue, m pb.Property_Meaning) (interface{}, error) {
  346. switch {
  347. case v.Int64Value != nil:
  348. if m == pb.Property_GD_WHEN {
  349. return fromUnixMicro(*v.Int64Value), nil
  350. } else {
  351. return *v.Int64Value, nil
  352. }
  353. case v.BooleanValue != nil:
  354. return *v.BooleanValue, nil
  355. case v.StringValue != nil:
  356. if m == pb.Property_BLOB {
  357. return []byte(*v.StringValue), nil
  358. } else if m == pb.Property_BLOBKEY {
  359. return appengine.BlobKey(*v.StringValue), nil
  360. } else if m == pb.Property_BYTESTRING {
  361. return ByteString(*v.StringValue), nil
  362. } else if m == pb.Property_ENTITY_PROTO {
  363. var ent pb.EntityProto
  364. err := proto.Unmarshal([]byte(*v.StringValue), &ent)
  365. if err != nil {
  366. return nil, err
  367. }
  368. return protoToEntity(&ent)
  369. } else {
  370. return *v.StringValue, nil
  371. }
  372. case v.DoubleValue != nil:
  373. return *v.DoubleValue, nil
  374. case v.Referencevalue != nil:
  375. key, err := referenceValueToKey(v.Referencevalue)
  376. if err != nil {
  377. return nil, err
  378. }
  379. return key, nil
  380. case v.Pointvalue != nil:
  381. // NOTE: Strangely, latitude maps to X, longitude to Y.
  382. return appengine.GeoPoint{Lat: v.Pointvalue.GetX(), Lng: v.Pointvalue.GetY()}, nil
  383. }
  384. return nil, nil
  385. }
  386. // indexValue is a Property value that is created when entities are loaded from
  387. // an index, such as from a projection query.
  388. //
  389. // Such Property values do not contain all of the metadata required to be
  390. // faithfully represented as a Go value, and are instead represented as an
  391. // opaque indexValue. Load the properties into a concrete struct type (e.g. by
  392. // passing a struct pointer to Iterator.Next) to reconstruct actual Go values
  393. // of type int, string, time.Time, etc.
  394. type indexValue struct {
  395. value *pb.PropertyValue
  396. }