You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

522 lines
14 KiB

  1. // Copyright 2014 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package datastore
  15. import (
  16. "fmt"
  17. "reflect"
  18. "strings"
  19. "time"
  20. "cloud.google.com/go/internal/fields"
  21. pb "google.golang.org/genproto/googleapis/datastore/v1"
  22. )
  23. var (
  24. typeOfByteSlice = reflect.TypeOf([]byte(nil))
  25. typeOfTime = reflect.TypeOf(time.Time{})
  26. typeOfGeoPoint = reflect.TypeOf(GeoPoint{})
  27. typeOfKeyPtr = reflect.TypeOf(&Key{})
  28. )
  29. // typeMismatchReason returns a string explaining why the property p could not
  30. // be stored in an entity field of type v.Type().
  31. func typeMismatchReason(p Property, v reflect.Value) string {
  32. entityType := "empty"
  33. switch p.Value.(type) {
  34. case int64:
  35. entityType = "int"
  36. case bool:
  37. entityType = "bool"
  38. case string:
  39. entityType = "string"
  40. case float64:
  41. entityType = "float"
  42. case *Key:
  43. entityType = "*datastore.Key"
  44. case *Entity:
  45. entityType = "*datastore.Entity"
  46. case GeoPoint:
  47. entityType = "GeoPoint"
  48. case time.Time:
  49. entityType = "time.Time"
  50. case []byte:
  51. entityType = "[]byte"
  52. }
  53. return fmt.Sprintf("type mismatch: %s versus %v", entityType, v.Type())
  54. }
  55. func overflowReason(x interface{}, v reflect.Value) string {
  56. return fmt.Sprintf("value %v overflows struct field of type %v", x, v.Type())
  57. }
  58. type propertyLoader struct {
  59. // m holds the number of times a substruct field like "Foo.Bar.Baz" has
  60. // been seen so far. The map is constructed lazily.
  61. m map[string]int
  62. }
  63. func (l *propertyLoader) load(codec fields.List, structValue reflect.Value, p Property, prev map[string]struct{}) string {
  64. sl, ok := p.Value.([]interface{})
  65. if !ok {
  66. return l.loadOneElement(codec, structValue, p, prev)
  67. }
  68. for _, val := range sl {
  69. p.Value = val
  70. if errStr := l.loadOneElement(codec, structValue, p, prev); errStr != "" {
  71. return errStr
  72. }
  73. }
  74. return ""
  75. }
  76. // loadOneElement loads the value of Property p into structValue based on the provided
  77. // codec. codec is used to find the field in structValue into which p should be loaded.
  78. // prev is the set of property names already seen for structValue.
  79. func (l *propertyLoader) loadOneElement(codec fields.List, structValue reflect.Value, p Property, prev map[string]struct{}) string {
  80. var sliceOk bool
  81. var sliceIndex int
  82. var v reflect.Value
  83. name := p.Name
  84. fieldNames := strings.Split(name, ".")
  85. for len(fieldNames) > 0 {
  86. var field *fields.Field
  87. // Start by trying to find a field with name. If none found,
  88. // cut off the last field (delimited by ".") and find its parent
  89. // in the codec.
  90. // eg. for name "A.B.C.D", split off "A.B.C" and try to
  91. // find a field in the codec with this name.
  92. // Loop again with "A.B", etc.
  93. for i := len(fieldNames); i > 0; i-- {
  94. parent := strings.Join(fieldNames[:i], ".")
  95. field = codec.Match(parent)
  96. if field != nil {
  97. fieldNames = fieldNames[i:]
  98. break
  99. }
  100. }
  101. // If we never found a matching field in the codec, return
  102. // error message.
  103. if field == nil {
  104. return "no such struct field"
  105. }
  106. v = initField(structValue, field.Index)
  107. if !v.IsValid() {
  108. return "no such struct field"
  109. }
  110. if !v.CanSet() {
  111. return "cannot set struct field"
  112. }
  113. // If field implements PLS, we delegate loading to the PLS's Load early,
  114. // and stop iterating through fields.
  115. ok, err := plsFieldLoad(v, p, fieldNames)
  116. if err != nil {
  117. return err.Error()
  118. }
  119. if ok {
  120. return ""
  121. }
  122. if field.Type.Kind() == reflect.Ptr && field.Type.Elem().Kind() == reflect.Struct {
  123. codec, err = structCache.Fields(field.Type.Elem())
  124. if err != nil {
  125. return err.Error()
  126. }
  127. // Init value if its nil
  128. if v.IsNil() {
  129. v.Set(reflect.New(field.Type.Elem()))
  130. }
  131. structValue = v.Elem()
  132. }
  133. if field.Type.Kind() == reflect.Struct {
  134. codec, err = structCache.Fields(field.Type)
  135. if err != nil {
  136. return err.Error()
  137. }
  138. structValue = v
  139. }
  140. // If the element is a slice, we need to accommodate it.
  141. if v.Kind() == reflect.Slice && v.Type() != typeOfByteSlice {
  142. if l.m == nil {
  143. l.m = make(map[string]int)
  144. }
  145. sliceIndex = l.m[p.Name]
  146. l.m[p.Name] = sliceIndex + 1
  147. for v.Len() <= sliceIndex {
  148. v.Set(reflect.Append(v, reflect.New(v.Type().Elem()).Elem()))
  149. }
  150. structValue = v.Index(sliceIndex)
  151. // If structValue implements PLS, we delegate loading to the PLS's
  152. // Load early, and stop iterating through fields.
  153. ok, err := plsFieldLoad(structValue, p, fieldNames)
  154. if err != nil {
  155. return err.Error()
  156. }
  157. if ok {
  158. return ""
  159. }
  160. if structValue.Type().Kind() == reflect.Struct {
  161. codec, err = structCache.Fields(structValue.Type())
  162. if err != nil {
  163. return err.Error()
  164. }
  165. }
  166. sliceOk = true
  167. }
  168. }
  169. var slice reflect.Value
  170. if v.Kind() == reflect.Slice && v.Type().Elem().Kind() != reflect.Uint8 {
  171. slice = v
  172. v = reflect.New(v.Type().Elem()).Elem()
  173. } else if _, ok := prev[p.Name]; ok && !sliceOk {
  174. // Zero the field back out that was set previously, turns out
  175. // it's a slice and we don't know what to do with it
  176. v.Set(reflect.Zero(v.Type()))
  177. return "multiple-valued property requires a slice field type"
  178. }
  179. prev[p.Name] = struct{}{}
  180. if errReason := setVal(v, p); errReason != "" {
  181. // Set the slice back to its zero value.
  182. if slice.IsValid() {
  183. slice.Set(reflect.Zero(slice.Type()))
  184. }
  185. return errReason
  186. }
  187. if slice.IsValid() {
  188. slice.Index(sliceIndex).Set(v)
  189. }
  190. return ""
  191. }
  192. // plsFieldLoad first tries to converts v's value to a PLS, then v's addressed
  193. // value to a PLS. If neither succeeds, plsFieldLoad returns false for first return
  194. // value. Otherwise, the first return value will be true.
  195. // If v is successfully converted to a PLS, plsFieldLoad will then try to Load
  196. // the property p into v (by way of the PLS's Load method).
  197. //
  198. // If the field v has been flattened, the Property's name must be altered
  199. // before calling Load to reflect the field v.
  200. // For example, if our original field name was "A.B.C.D",
  201. // and at this point in iteration we had initialized the field
  202. // corresponding to "A" and have moved into the struct, so that now
  203. // v corresponds to the field named "B", then we want to let the
  204. // PLS handle this field (B)'s subfields ("C", "D"),
  205. // so we send the property to the PLS's Load, renamed to "C.D".
  206. //
  207. // If subfields are present, the field v has been flattened.
  208. func plsFieldLoad(v reflect.Value, p Property, subfields []string) (ok bool, err error) {
  209. vpls, err := plsForLoad(v)
  210. if err != nil {
  211. return false, err
  212. }
  213. if vpls == nil {
  214. return false, nil
  215. }
  216. // If Entity, load properties as well as key.
  217. if e, ok := p.Value.(*Entity); ok {
  218. err = loadEntity(vpls, e)
  219. return true, err
  220. }
  221. // If flattened, we must alter the property's name to reflect
  222. // the field v.
  223. if len(subfields) > 0 {
  224. p.Name = strings.Join(subfields, ".")
  225. }
  226. return true, vpls.Load([]Property{p})
  227. }
  228. // setVal sets 'v' to the value of the Property 'p'.
  229. func setVal(v reflect.Value, p Property) (s string) {
  230. pValue := p.Value
  231. switch v.Kind() {
  232. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  233. x, ok := pValue.(int64)
  234. if !ok && pValue != nil {
  235. return typeMismatchReason(p, v)
  236. }
  237. if v.OverflowInt(x) {
  238. return overflowReason(x, v)
  239. }
  240. v.SetInt(x)
  241. case reflect.Bool:
  242. x, ok := pValue.(bool)
  243. if !ok && pValue != nil {
  244. return typeMismatchReason(p, v)
  245. }
  246. v.SetBool(x)
  247. case reflect.String:
  248. x, ok := pValue.(string)
  249. if !ok && pValue != nil {
  250. return typeMismatchReason(p, v)
  251. }
  252. v.SetString(x)
  253. case reflect.Float32, reflect.Float64:
  254. x, ok := pValue.(float64)
  255. if !ok && pValue != nil {
  256. return typeMismatchReason(p, v)
  257. }
  258. if v.OverflowFloat(x) {
  259. return overflowReason(x, v)
  260. }
  261. v.SetFloat(x)
  262. case reflect.Ptr:
  263. // v must be a pointer to either a Key, an Entity, or one of the supported basic types.
  264. if v.Type() != typeOfKeyPtr && v.Type().Elem().Kind() != reflect.Struct && !isValidPointerType(v.Type().Elem()) {
  265. return typeMismatchReason(p, v)
  266. }
  267. if pValue == nil {
  268. // If v is populated already, set it to nil.
  269. if !v.IsNil() {
  270. v.Set(reflect.New(v.Type()).Elem())
  271. }
  272. return ""
  273. }
  274. if x, ok := p.Value.(*Key); ok {
  275. if _, ok := v.Interface().(*Key); !ok {
  276. return typeMismatchReason(p, v)
  277. }
  278. v.Set(reflect.ValueOf(x))
  279. return ""
  280. }
  281. if v.IsNil() {
  282. v.Set(reflect.New(v.Type().Elem()))
  283. }
  284. switch x := pValue.(type) {
  285. case *Entity:
  286. err := loadEntity(v.Interface(), x)
  287. if err != nil {
  288. return err.Error()
  289. }
  290. case int64:
  291. if v.Elem().OverflowInt(x) {
  292. return overflowReason(x, v.Elem())
  293. }
  294. v.Elem().SetInt(x)
  295. case float64:
  296. if v.Elem().OverflowFloat(x) {
  297. return overflowReason(x, v.Elem())
  298. }
  299. v.Elem().SetFloat(x)
  300. case bool:
  301. v.Elem().SetBool(x)
  302. case string:
  303. v.Elem().SetString(x)
  304. case GeoPoint, time.Time:
  305. v.Elem().Set(reflect.ValueOf(x))
  306. default:
  307. return typeMismatchReason(p, v)
  308. }
  309. case reflect.Struct:
  310. switch v.Type() {
  311. case typeOfTime:
  312. x, ok := pValue.(time.Time)
  313. if !ok && pValue != nil {
  314. return typeMismatchReason(p, v)
  315. }
  316. v.Set(reflect.ValueOf(x))
  317. case typeOfGeoPoint:
  318. x, ok := pValue.(GeoPoint)
  319. if !ok && pValue != nil {
  320. return typeMismatchReason(p, v)
  321. }
  322. v.Set(reflect.ValueOf(x))
  323. default:
  324. ent, ok := pValue.(*Entity)
  325. if !ok {
  326. return typeMismatchReason(p, v)
  327. }
  328. err := loadEntity(v.Addr().Interface(), ent)
  329. if err != nil {
  330. return err.Error()
  331. }
  332. }
  333. case reflect.Slice:
  334. x, ok := pValue.([]byte)
  335. if !ok && pValue != nil {
  336. return typeMismatchReason(p, v)
  337. }
  338. if v.Type().Elem().Kind() != reflect.Uint8 {
  339. return typeMismatchReason(p, v)
  340. }
  341. v.SetBytes(x)
  342. default:
  343. return typeMismatchReason(p, v)
  344. }
  345. return ""
  346. }
  347. // initField is similar to reflect's Value.FieldByIndex, in that it
  348. // returns the nested struct field corresponding to index, but it
  349. // initialises any nil pointers encountered when traversing the structure.
  350. func initField(val reflect.Value, index []int) reflect.Value {
  351. for _, i := range index[:len(index)-1] {
  352. val = val.Field(i)
  353. if val.Kind() == reflect.Ptr {
  354. if val.IsNil() {
  355. val.Set(reflect.New(val.Type().Elem()))
  356. }
  357. val = val.Elem()
  358. }
  359. }
  360. return val.Field(index[len(index)-1])
  361. }
  362. // loadEntityProto loads an EntityProto into PropertyLoadSaver or struct pointer.
  363. func loadEntityProto(dst interface{}, src *pb.Entity) error {
  364. ent, err := protoToEntity(src)
  365. if err != nil {
  366. return err
  367. }
  368. return loadEntity(dst, ent)
  369. }
  370. func loadEntity(dst interface{}, ent *Entity) error {
  371. if pls, ok := dst.(PropertyLoadSaver); ok {
  372. err := pls.Load(ent.Properties)
  373. if err != nil {
  374. return err
  375. }
  376. if e, ok := dst.(KeyLoader); ok {
  377. err = e.LoadKey(ent.Key)
  378. }
  379. return err
  380. }
  381. return loadEntityToStruct(dst, ent)
  382. }
  383. func loadEntityToStruct(dst interface{}, ent *Entity) error {
  384. pls, err := newStructPLS(dst)
  385. if err != nil {
  386. return err
  387. }
  388. // Try and load key.
  389. keyField := pls.codec.Match(keyFieldName)
  390. if keyField != nil && ent.Key != nil {
  391. pls.v.FieldByIndex(keyField.Index).Set(reflect.ValueOf(ent.Key))
  392. }
  393. // Load properties.
  394. return pls.Load(ent.Properties)
  395. }
  396. func (s structPLS) Load(props []Property) error {
  397. var fieldName, errReason string
  398. var l propertyLoader
  399. prev := make(map[string]struct{})
  400. for _, p := range props {
  401. if errStr := l.load(s.codec, s.v, p, prev); errStr != "" {
  402. // We don't return early, as we try to load as many properties as possible.
  403. // It is valid to load an entity into a struct that cannot fully represent it.
  404. // That case returns an error, but the caller is free to ignore it.
  405. fieldName, errReason = p.Name, errStr
  406. }
  407. }
  408. if errReason != "" {
  409. return &ErrFieldMismatch{
  410. StructType: s.v.Type(),
  411. FieldName: fieldName,
  412. Reason: errReason,
  413. }
  414. }
  415. return nil
  416. }
  417. func protoToEntity(src *pb.Entity) (*Entity, error) {
  418. props := make([]Property, 0, len(src.Properties))
  419. for name, val := range src.Properties {
  420. v, err := propToValue(val)
  421. if err != nil {
  422. return nil, err
  423. }
  424. props = append(props, Property{
  425. Name: name,
  426. Value: v,
  427. NoIndex: val.ExcludeFromIndexes,
  428. })
  429. }
  430. var key *Key
  431. if src.Key != nil {
  432. // Ignore any error, since nested entity values
  433. // are allowed to have an invalid key.
  434. key, _ = protoToKey(src.Key)
  435. }
  436. return &Entity{key, props}, nil
  437. }
  438. // propToValue returns a Go value that represents the PropertyValue. For
  439. // example, a TimestampValue becomes a time.Time.
  440. func propToValue(v *pb.Value) (interface{}, error) {
  441. switch v := v.ValueType.(type) {
  442. case *pb.Value_NullValue:
  443. return nil, nil
  444. case *pb.Value_BooleanValue:
  445. return v.BooleanValue, nil
  446. case *pb.Value_IntegerValue:
  447. return v.IntegerValue, nil
  448. case *pb.Value_DoubleValue:
  449. return v.DoubleValue, nil
  450. case *pb.Value_TimestampValue:
  451. return time.Unix(v.TimestampValue.Seconds, int64(v.TimestampValue.Nanos)), nil
  452. case *pb.Value_KeyValue:
  453. return protoToKey(v.KeyValue)
  454. case *pb.Value_StringValue:
  455. return v.StringValue, nil
  456. case *pb.Value_BlobValue:
  457. return []byte(v.BlobValue), nil
  458. case *pb.Value_GeoPointValue:
  459. return GeoPoint{Lat: v.GeoPointValue.Latitude, Lng: v.GeoPointValue.Longitude}, nil
  460. case *pb.Value_EntityValue:
  461. return protoToEntity(v.EntityValue)
  462. case *pb.Value_ArrayValue:
  463. arr := make([]interface{}, 0, len(v.ArrayValue.Values))
  464. for _, v := range v.ArrayValue.Values {
  465. vv, err := propToValue(v)
  466. if err != nil {
  467. return nil, err
  468. }
  469. arr = append(arr, vv)
  470. }
  471. return arr, nil
  472. default:
  473. return nil, nil
  474. }
  475. }