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.
 
 
 

302 lines
9.1 KiB

  1. // Copyright 2017 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 firestore
  15. import (
  16. "errors"
  17. "fmt"
  18. "reflect"
  19. "time"
  20. pb "google.golang.org/genproto/googleapis/firestore/v1beta1"
  21. "google.golang.org/grpc/codes"
  22. "google.golang.org/grpc/status"
  23. "github.com/golang/protobuf/ptypes"
  24. tspb "github.com/golang/protobuf/ptypes/timestamp"
  25. )
  26. // A DocumentSnapshot contains document data and metadata.
  27. type DocumentSnapshot struct {
  28. // The DocumentRef for this document.
  29. Ref *DocumentRef
  30. // Read-only. The time at which the document was created.
  31. // Increases monotonically when a document is deleted then
  32. // recreated. It can also be compared to values from other documents and
  33. // the read time of a query.
  34. CreateTime time.Time
  35. // Read-only. The time at which the document was last changed. This value
  36. // is initially set to CreateTime then increases monotonically with each
  37. // change to the document. It can also be compared to values from other
  38. // documents and the read time of a query.
  39. UpdateTime time.Time
  40. // Read-only. The time at which the document was read.
  41. ReadTime time.Time
  42. c *Client
  43. proto *pb.Document
  44. }
  45. // Exists reports whether the DocumentSnapshot represents an existing document.
  46. // Even if Exists returns false, the Ref and ReadTime fields of the DocumentSnapshot
  47. // are valid.
  48. func (d *DocumentSnapshot) Exists() bool {
  49. return d.proto != nil
  50. }
  51. // Data returns the DocumentSnapshot's fields as a map.
  52. // It is equivalent to
  53. // var m map[string]interface{}
  54. // d.DataTo(&m)
  55. // except that it returns nil if the document does not exist.
  56. func (d *DocumentSnapshot) Data() map[string]interface{} {
  57. if !d.Exists() {
  58. return nil
  59. }
  60. m, err := createMapFromValueMap(d.proto.Fields, d.c)
  61. // Any error here is a bug in the client.
  62. if err != nil {
  63. panic(fmt.Sprintf("firestore: %v", err))
  64. }
  65. return m
  66. }
  67. // DataTo uses the document's fields to populate p, which can be a pointer to a
  68. // map[string]interface{} or a pointer to a struct.
  69. //
  70. // Firestore field values are converted to Go values as follows:
  71. // - Null converts to nil.
  72. // - Bool converts to bool.
  73. // - String converts to string.
  74. // - Integer converts int64. When setting a struct field, any signed or unsigned
  75. // integer type is permitted except uint64. Overflow is detected and results in
  76. // an error.
  77. // - Double converts to float64. When setting a struct field, float32 is permitted.
  78. // Overflow is detected and results in an error.
  79. // - Bytes is converted to []byte.
  80. // - Timestamp converts to time.Time.
  81. // - GeoPoint converts to latlng.LatLng, where latlng is the package
  82. // "google.golang.org/genproto/googleapis/type/latlng".
  83. // - Arrays convert to []interface{}. When setting a struct field, the field
  84. // may be a slice or array of any type and is populated recursively.
  85. // Slices are resized to the incoming value's size, while arrays that are too
  86. // long have excess elements filled with zero values. If the array is too short,
  87. // excess incoming values will be dropped.
  88. // - Maps convert to map[string]interface{}. When setting a struct field,
  89. // maps of key type string and any value type are permitted, and are populated
  90. // recursively.
  91. // - References are converted to DocumentRefs.
  92. //
  93. // Field names given by struct field tags are observed, as described in
  94. // DocumentRef.Create.
  95. //
  96. // If the document does not exist, DataTo returns a NotFound error.
  97. func (d *DocumentSnapshot) DataTo(p interface{}) error {
  98. if !d.Exists() {
  99. return status.Errorf(codes.NotFound, "document %s does not exist", d.Ref.Path)
  100. }
  101. return setFromProtoValue(p, &pb.Value{ValueType: &pb.Value_MapValue{&pb.MapValue{Fields: d.proto.Fields}}}, d.c)
  102. }
  103. // DataAt returns the data value denoted by path.
  104. //
  105. // The path argument can be a single field or a dot-separated sequence of
  106. // fields, and must not contain any of the runes "˜*/[]". Use DataAtPath instead for
  107. // such a path.
  108. //
  109. // See DocumentSnapshot.DataTo for how Firestore values are converted to Go values.
  110. //
  111. // If the document does not exist, DataAt returns a NotFound error.
  112. func (d *DocumentSnapshot) DataAt(path string) (interface{}, error) {
  113. if !d.Exists() {
  114. return nil, status.Errorf(codes.NotFound, "document %s does not exist", d.Ref.Path)
  115. }
  116. fp, err := parseDotSeparatedString(path)
  117. if err != nil {
  118. return nil, err
  119. }
  120. return d.DataAtPath(fp)
  121. }
  122. // DataAtPath returns the data value denoted by the FieldPath fp.
  123. // If the document does not exist, DataAtPath returns a NotFound error.
  124. func (d *DocumentSnapshot) DataAtPath(fp FieldPath) (interface{}, error) {
  125. if !d.Exists() {
  126. return nil, status.Errorf(codes.NotFound, "document %s does not exist", d.Ref.Path)
  127. }
  128. v, err := valueAtPath(fp, d.proto.Fields)
  129. if err != nil {
  130. return nil, err
  131. }
  132. return createFromProtoValue(v, d.c)
  133. }
  134. // valueAtPath returns the value of m referred to by fp.
  135. func valueAtPath(fp FieldPath, m map[string]*pb.Value) (*pb.Value, error) {
  136. for _, k := range fp[:len(fp)-1] {
  137. v := m[k]
  138. if v == nil {
  139. return nil, fmt.Errorf("firestore: no field %q", k)
  140. }
  141. mv := v.GetMapValue()
  142. if mv == nil {
  143. return nil, fmt.Errorf("firestore: value for field %q is not a map", k)
  144. }
  145. m = mv.Fields
  146. }
  147. k := fp[len(fp)-1]
  148. v := m[k]
  149. if v == nil {
  150. return nil, fmt.Errorf("firestore: no field %q", k)
  151. }
  152. return v, nil
  153. }
  154. // toProtoDocument converts a Go value to a Document proto.
  155. // Valid values are: map[string]T, struct, or pointer to a valid value.
  156. // It also returns a list of field paths for DocumentTransform (server timestamp).
  157. func toProtoDocument(x interface{}) (*pb.Document, []FieldPath, error) {
  158. if x == nil {
  159. return nil, nil, errors.New("firestore: nil document contents")
  160. }
  161. v := reflect.ValueOf(x)
  162. pv, sawTransform, err := toProtoValue(v)
  163. if err != nil {
  164. return nil, nil, err
  165. }
  166. var fieldPaths []FieldPath
  167. if sawTransform {
  168. fieldPaths, err = extractTransformPaths(v, nil)
  169. if err != nil {
  170. return nil, nil, err
  171. }
  172. }
  173. var fields map[string]*pb.Value
  174. if pv != nil {
  175. m := pv.GetMapValue()
  176. if m == nil {
  177. return nil, nil, fmt.Errorf("firestore: cannot convert value of type %T into a map", x)
  178. }
  179. fields = m.Fields
  180. }
  181. return &pb.Document{Fields: fields}, fieldPaths, nil
  182. }
  183. func extractTransformPaths(v reflect.Value, prefix FieldPath) ([]FieldPath, error) {
  184. switch v.Kind() {
  185. case reflect.Map:
  186. return extractTransformPathsFromMap(v, prefix)
  187. case reflect.Struct:
  188. return extractTransformPathsFromStruct(v, prefix)
  189. case reflect.Ptr:
  190. if v.IsNil() {
  191. return nil, nil
  192. }
  193. return extractTransformPaths(v.Elem(), prefix)
  194. case reflect.Interface:
  195. if v.NumMethod() == 0 { // empty interface: recurse on its contents
  196. return extractTransformPaths(v.Elem(), prefix)
  197. }
  198. return nil, nil
  199. default:
  200. return nil, nil
  201. }
  202. }
  203. func extractTransformPathsFromMap(v reflect.Value, prefix FieldPath) ([]FieldPath, error) {
  204. var paths []FieldPath
  205. for _, k := range v.MapKeys() {
  206. sk := k.Interface().(string) // assume keys are strings; checked in toProtoValue
  207. path := prefix.with(sk)
  208. mi := v.MapIndex(k)
  209. if mi.Interface() == ServerTimestamp {
  210. paths = append(paths, path)
  211. } else {
  212. ps, err := extractTransformPaths(mi, path)
  213. if err != nil {
  214. return nil, err
  215. }
  216. paths = append(paths, ps...)
  217. }
  218. }
  219. return paths, nil
  220. }
  221. func extractTransformPathsFromStruct(v reflect.Value, prefix FieldPath) ([]FieldPath, error) {
  222. var paths []FieldPath
  223. fields, err := fieldCache.Fields(v.Type())
  224. if err != nil {
  225. return nil, err
  226. }
  227. for _, f := range fields {
  228. fv := v.FieldByIndex(f.Index)
  229. path := prefix.with(f.Name)
  230. opts := f.ParsedTag.(tagOptions)
  231. if opts.serverTimestamp {
  232. var isZero bool
  233. switch f.Type {
  234. case typeOfGoTime:
  235. isZero = fv.Interface().(time.Time).IsZero()
  236. case reflect.PtrTo(typeOfGoTime):
  237. isZero = fv.IsNil() || fv.Elem().Interface().(time.Time).IsZero()
  238. default:
  239. return nil, fmt.Errorf("firestore: field %s of struct %s with serverTimestamp tag must be of type time.Time or *time.Time",
  240. f.Name, v.Type())
  241. }
  242. if isZero {
  243. paths = append(paths, path)
  244. }
  245. } else {
  246. ps, err := extractTransformPaths(fv, path)
  247. if err != nil {
  248. return nil, err
  249. }
  250. paths = append(paths, ps...)
  251. }
  252. }
  253. return paths, nil
  254. }
  255. func newDocumentSnapshot(ref *DocumentRef, proto *pb.Document, c *Client, readTime *tspb.Timestamp) (*DocumentSnapshot, error) {
  256. d := &DocumentSnapshot{
  257. Ref: ref,
  258. c: c,
  259. proto: proto,
  260. }
  261. if proto != nil {
  262. ts, err := ptypes.Timestamp(proto.CreateTime)
  263. if err != nil {
  264. return nil, err
  265. }
  266. d.CreateTime = ts
  267. ts, err = ptypes.Timestamp(proto.UpdateTime)
  268. if err != nil {
  269. return nil, err
  270. }
  271. d.UpdateTime = ts
  272. }
  273. if readTime != nil {
  274. ts, err := ptypes.Timestamp(readTime)
  275. if err != nil {
  276. return nil, err
  277. }
  278. d.ReadTime = ts
  279. }
  280. return d, nil
  281. }