Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 

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