| 1 |
// Copyright 2019 The Go Cloud Development Kit Authors |
| 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 |
// https://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 |
|
| 15 |
// Package docstore provides a portable way of interacting with a document store. |
| 16 |
// Subpackages contain driver implementations of docstore for supported |
| 17 |
// services. |
| 18 |
// |
| 19 |
// See https://gocloud.dev/howto/docstore/ for a detailed how-to guide. |
| 20 |
// |
| 21 |
// # Collections |
| 22 |
// |
| 23 |
// In docstore, documents are grouped into collections, and each document has a key |
| 24 |
// that is unique in its collection. You can add, retrieve, modify and delete |
| 25 |
// documents by key, and you can query a collection to retrieve documents that match |
| 26 |
// certain criteria. |
| 27 |
// |
| 28 |
// # Representing Documents |
| 29 |
// |
| 30 |
// A document is a set of named fields, each with a value. A field's value can be a scalar, |
| 31 |
// a list, or a nested document. |
| 32 |
// |
| 33 |
// Docstore allows you to represent documents as either map[string]interface{} or |
| 34 |
// struct pointers. When you represent a document as a map, the fields are map keys |
| 35 |
// and the values are map values. Lists are represented with slices. For example, |
| 36 |
// here is a document about a book described as a map: |
| 37 |
// |
| 38 |
// doc := map[string]interface{}{ |
| 39 |
// "Title": "The Master and Margarita", |
| 40 |
// "Author": map[string]interface{}{ |
| 41 |
// "First": "Mikhail", |
| 42 |
// "Last": "Bulgakov", |
| 43 |
// }, |
| 44 |
// "PublicationYears": []int{1967, 1973}, |
| 45 |
// } |
| 46 |
// |
| 47 |
// Note that the value of "PublicationYears" is a list, and the value of "Author" is |
| 48 |
// itself a document. |
| 49 |
// |
| 50 |
// Here is the same document represented with structs: |
| 51 |
// |
| 52 |
// type Book struct { |
| 53 |
// Title string |
| 54 |
// Author Name |
| 55 |
// PublicationYears []int |
| 56 |
// } |
| 57 |
// |
| 58 |
// type Name struct { |
| 59 |
// First, Last string |
| 60 |
// } |
| 61 |
// |
| 62 |
// doc := &Book{ |
| 63 |
// Title: "The Master and Margarita", |
| 64 |
// Author: Name{ |
| 65 |
// First: "Mikhail", |
| 66 |
// Last: "Bulgakov", |
| 67 |
// }, |
| 68 |
// PublicationYears: []int{1967, 1973}, |
| 69 |
// } |
| 70 |
// |
| 71 |
// You must use a pointer to a struct to represent a document, although structs |
| 72 |
// nested inside a document, like the Name struct above, need not be pointers. |
| 73 |
// |
| 74 |
// Maps are best for applications where you don't know the structure of the |
| 75 |
// documents. Using structs is preferred because it enforces some structure on your |
| 76 |
// data. |
| 77 |
// |
| 78 |
// By default, Docstore treats a struct's exported fields as the fields of the |
| 79 |
// document. You can alter this default mapping by using a struct tag beginning |
| 80 |
// with "docstore:". Docstore struct tags support renaming, omitting fields |
| 81 |
// unconditionally, or omitting them only when they are empty, exactly like |
| 82 |
// encoding/json. For example, this is the Book struct with different field |
| 83 |
// names: |
| 84 |
// |
| 85 |
// type Book struct { |
| 86 |
// Title string `docstore:"title"` |
| 87 |
// Author Name `docstore:"author"` |
| 88 |
// PublicationYears []int `docstore:"pub_years,omitempty"` |
| 89 |
// NumPublications int `docstore:"-"` |
| 90 |
// } |
| 91 |
// |
| 92 |
// This struct describes a document with field names "title", "author" and |
| 93 |
// "pub_years". The pub_years field is omitted from the stored document if it has |
| 94 |
// length zero. The NumPublications field is never stored because it can easily be |
| 95 |
// computed from the PublicationYears field. |
| 96 |
// |
| 97 |
// Given a document field "Foo" and a struct type document, Docstore's decoder |
| 98 |
// will look through the destination struct's field to find (in order of |
| 99 |
// preference): |
| 100 |
// - An exported field with a tag of "Foo"; |
| 101 |
// - An exported field named "Foo". |
| 102 |
// |
| 103 |
// Note that unlike encoding/json, Docstore does case-sensitive matching during |
| 104 |
// decoding to match the behavior of decoders in most docstore services. |
| 105 |
// |
| 106 |
// # Representing Data |
| 107 |
// |
| 108 |
// Values stored in document fields can be any of a wide range of types. All |
| 109 |
// primitive types except for complex numbers are supported, as well as slices and |
| 110 |
// maps (the map key type must be a string, an integer, or a type that implements |
| 111 |
// encoding.TextMarshaler). In addition, any type that implements |
| 112 |
// encoding.BinaryMarshaler or encoding.TextMarshaler is permitted. This set of types |
| 113 |
// closely matches the encoding/json package (see https://golang.org/pkg/encoding/json). |
| 114 |
// |
| 115 |
// Times deserve special mention. Docstore can store and retrieve values of type |
| 116 |
// time.Time, with two caveats. First, the timezone will not be preserved. Second, |
| 117 |
// Docstore guarantees only that time.Time values are represented to millisecond |
| 118 |
// precision. Many services will do better, but if you need to be sure that times |
| 119 |
// are stored with nanosecond precision, convert the time.Time to another type before |
| 120 |
// storing and re-create when you retrieve it. For instance, if you store Unix |
| 121 |
// time in nanoseconds using time's UnixNano method, you can get the original |
| 122 |
// time back (in the local timezone) with the time.Unix function. |
| 123 |
// |
| 124 |
// # Representing Keys |
| 125 |
// |
| 126 |
// The key of a docstore document is its unique identifier, usually a field. |
| 127 |
// Keys never appear alone in the docstore API, only as part of a document. For |
| 128 |
// instance, to retrieve a document by key, you pass the Collection.Get method |
| 129 |
// a document as a struct pointer or map with the key field populated, and docstore |
| 130 |
// populates the rest of that argument with the stored contents. Docstore |
| 131 |
// doesn't take zero-value key. |
| 132 |
// |
| 133 |
// When you open a collection using an OpenCollection method of the |
| 134 |
// service-specific driver or a URL, you specify how to extract the key from a |
| 135 |
// document. |
| 136 |
// Usually, you provide the name of the key field, as in the example below: |
| 137 |
// |
| 138 |
// coll, err := memdocstore.OpenCollection("SSN", nil) |
| 139 |
// |
| 140 |
// Here, the "SSN" field of the document is used as the key. Some drivers let you |
| 141 |
// supply a function to extract the key from the document, which can be useful if the |
| 142 |
// key is composed of more than one field. |
| 143 |
// |
| 144 |
// # Actions |
| 145 |
// |
| 146 |
// Docstore supports six actions on documents as methods on the Collection type: |
| 147 |
// - Get retrieves a document. |
| 148 |
// - Create creates a new document. |
| 149 |
// - Replace replaces an existing document. |
| 150 |
// - Put puts a document into a collection, replacing it if it is already present. |
| 151 |
// - Update applies a set of modifications to a document. |
| 152 |
// - Delete deletes a document. |
| 153 |
// |
| 154 |
// Each action acts atomically on a single document. You can execute actions |
| 155 |
// individually or you can group them into an action list, like so: |
| 156 |
// |
| 157 |
// err := coll.Actions().Put(doc1).Replace(doc2).Get(doc3).Do(ctx) |
| 158 |
// |
| 159 |
// When you use an action list, docstore will try to optimize the execution of the |
| 160 |
// actions. For example, multiple Get actions may be combined into a single "batch |
| 161 |
// get" RPC. For the most part, actions in a list execute in an undefined order |
| 162 |
// (perhaps concurrently) and independently, but read and write operations on the same |
| 163 |
// document are executed in the user-specified order. See the documentation of |
| 164 |
// ActionList for details. |
| 165 |
// |
| 166 |
// # Revisions |
| 167 |
// |
| 168 |
// Docstore supports document revisions to distinguish different versions of a |
| 169 |
// document and enable optimistic locking. By default, Docstore stores the |
| 170 |
// revision in the field named "DocstoreRevision" (stored in the constant |
| 171 |
// DefaultRevisionField). Providers give you the option of changing that field |
| 172 |
// name. |
| 173 |
// |
| 174 |
// When you pass a document with a revision field to a write action, Docstore |
| 175 |
// will give it a revision at creation time or update the revision value when |
| 176 |
// modifying the document. If you don't want Docstore to handle any revision |
| 177 |
// logic, simply do not have the revision field in your document. |
| 178 |
// |
| 179 |
// When you pass a document with a non-nil revision to Put, Replace, Update or |
| 180 |
// Delete, Docstore will also compare the revision of the stored document to |
| 181 |
// that of the given document before making the change. It returns an error with |
| 182 |
// code FailedPrecondition on mismatch. (See https://gocloud.dev/gcerrors for |
| 183 |
// information about error codes.) If modification methods are called on a |
| 184 |
// document struct or map a nil revision field, then no revision checks are |
| 185 |
// performed, and changes are forced blindly, but a new revision will still be |
| 186 |
// given for the document. For example, if you call Get to retrieve a document |
| 187 |
// with a revision, then later perform a write action with that same document, |
| 188 |
// it will fail if the document was changed since the Get. |
| 189 |
// |
| 190 |
// Since different services use different types for revisions, revision fields |
| 191 |
// of unspecified type must be handled. When defining a document struct, |
| 192 |
// define the field to be of type interface{}. For example, |
| 193 |
// |
| 194 |
// type User { |
| 195 |
// Name string |
| 196 |
// DocstoreRevision interface{} |
| 197 |
// } |
| 198 |
// |
| 199 |
// # Queries |
| 200 |
// |
| 201 |
// Docstore supports querying within a collection. Call the Query method on |
| 202 |
// Collection to obtain a Query value, then build your query by calling Query methods |
| 203 |
// like Where, Limit and so on. Finally, call the Get method on the query to execute it. |
| 204 |
// The result is an iterator, whose use is described below. |
| 205 |
// |
| 206 |
// iter := coll.Query().Where("size", ">", 10).Limit(5).Get(ctx) |
| 207 |
// |
| 208 |
// The Where method defines a filter condition, much like a WHERE clause in SQL. |
| 209 |
// Conditions are of the form "field op value", where field is any document field |
| 210 |
// path (including dot-separated paths), op is one of "=", ">", "<", ">=" or "<=", |
| 211 |
// and value can be any value. |
| 212 |
// |
| 213 |
// iter := coll.Query().Where("Author.Last", "=", "Bulgakov").Limit(3).Get(ctx) |
| 214 |
// |
| 215 |
// Dot-separated paths work as you'd expect for nested structs and maps, addressing |
| 216 |
// the nested struct field or map key. For nested slices, some providers (notably |
| 217 |
// MongoDB) treat s.f, where s is a sequence, as the slice of e.f for each e in s. |
| 218 |
// However, others do not support field selectors inside slices, so docstore does |
| 219 |
// not support them -- while you may find that they work with some providers, you |
| 220 |
// cannot rely on that if you need fully portable code. |
| 221 |
// |
| 222 |
// You can make multiple Where calls. In some cases, parts of a Where clause may be |
| 223 |
// processed in the driver rather than natively by the backing service, which may have |
| 224 |
// performance implications for large result sets. See the driver package |
| 225 |
// documentation for details. |
| 226 |
// |
| 227 |
// Use the DocumentIterator returned from Query.Get by repeatedly calling its Next |
| 228 |
// method until it returns io.EOF. Always call Stop when you are finished with an |
| 229 |
// iterator. It is wise to use a defer statement for this. |
| 230 |
// |
| 231 |
// iter := coll.Query().Where("size", ">", 10).Limit(5).Get(ctx) |
| 232 |
// defer iter.Stop() |
| 233 |
// for { |
| 234 |
// m := map[string]interface{}{} |
| 235 |
// err := iter.Next(ctx, m) |
| 236 |
// if err == io.EOF { |
| 237 |
// break |
| 238 |
// } |
| 239 |
// if err != nil { |
| 240 |
// return err |
| 241 |
// } |
| 242 |
// fmt.Println(m) |
| 243 |
// } |
| 244 |
// |
| 245 |
// # Errors |
| 246 |
// |
| 247 |
// The errors returned from this package can be inspected in several ways: |
| 248 |
// |
| 249 |
// The Code function from https://gocloud.dev/gcerrors will return an error code, also |
| 250 |
// defined in that package, when invoked on an error. |
| 251 |
// |
| 252 |
// The Collection.ErrorAs method can retrieve the underlying driver error from |
| 253 |
// the returned error. See the specific driver's package doc for the supported |
| 254 |
// types. |
| 255 |
// |
| 256 |
// # OpenTelemetry Integration |
| 257 |
// |
| 258 |
// OpenTelemetry supports tracing, metrics, and logs collection for multiple languages and |
| 259 |
// backend providers. See https://opentelemetry.io. |
| 260 |
// |
| 261 |
// This API collects OpenTelemetry traces and metrics for the following methods: |
| 262 |
// - ActionList.Do |
| 263 |
// - Query.Get (for the first query only; drivers may make additional calls while iterating over results) |
| 264 |
// |
| 265 |
// All trace and metric names begin with the package import path. |
| 266 |
// The traces add the method name. |
| 267 |
// For example, "gocloud.dev/docstore/ActionList.Do". |
| 268 |
// The metrics are "completed_calls", a count of completed method calls by driver, |
| 269 |
// method and status (error code); and "latency", a distribution of method latency |
| 270 |
// by driver and method. |
| 271 |
// For example, "gocloud.dev/docstore/latency". |
| 272 |
// |
| 273 |
// To enable trace collection in your application, see the documentation at |
| 274 |
// https://opentelemetry.io/docs/instrumentation/go/getting-started/. |
| 275 |
// To enable metric collection in your application, see the documentation at |
| 276 |
// https://opentelemetry.io/docs/instrumentation/go/manual/. |
| 277 |
// |
| 278 |
// # GORM-like Code Generation |
| 279 |
// |
| 280 |
// You may find https://github.com/bartventer/docstore-gen useful. |
| 281 |
package docstore // import "gocloud.dev/docstore" |