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.
 
 
 

316 lines
9.7 KiB

  1. /*
  2. Copyright 2017 Google LLC
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. /*
  14. Package spanner provides a client for reading and writing to Cloud Spanner
  15. databases. See the packages under admin for clients that operate on databases
  16. and instances.
  17. Note: This package is in beta. Some backwards-incompatible changes may occur.
  18. See https://cloud.google.com/spanner/docs/getting-started/go/ for an introduction
  19. to Cloud Spanner and additional help on using this API.
  20. See https://godoc.org/cloud.google.com/go for authentication, timeouts,
  21. connection pooling and similar aspects of this package.
  22. Creating a Client
  23. To start working with this package, create a client that refers to the database
  24. of interest:
  25. ctx := context.Background()
  26. client, err := spanner.NewClient(ctx, "projects/P/instances/I/databases/D")
  27. if err != nil {
  28. // TODO: Handle error.
  29. }
  30. defer client.Close()
  31. Remember to close the client after use to free up the sessions in the session
  32. pool.
  33. Simple Reads and Writes
  34. Two Client methods, Apply and Single, work well for simple reads and writes. As
  35. a quick introduction, here we write a new row to the database and read it back:
  36. _, err := client.Apply(ctx, []*spanner.Mutation{
  37. spanner.Insert("Users",
  38. []string{"name", "email"},
  39. []interface{}{"alice", "a@example.com"})})
  40. if err != nil {
  41. // TODO: Handle error.
  42. }
  43. row, err := client.Single().ReadRow(ctx, "Users",
  44. spanner.Key{"alice"}, []string{"email"})
  45. if err != nil {
  46. // TODO: Handle error.
  47. }
  48. All the methods used above are discussed in more detail below.
  49. Keys
  50. Every Cloud Spanner row has a unique key, composed of one or more columns.
  51. Construct keys with a literal of type Key:
  52. key1 := spanner.Key{"alice"}
  53. KeyRanges
  54. The keys of a Cloud Spanner table are ordered. You can specify ranges of keys
  55. using the KeyRange type:
  56. kr1 := spanner.KeyRange{Start: key1, End: key2}
  57. By default, a KeyRange includes its start key but not its end key. Use
  58. the Kind field to specify other boundary conditions:
  59. // include both keys
  60. kr2 := spanner.KeyRange{Start: key1, End: key2, Kind: spanner.ClosedClosed}
  61. KeySets
  62. A KeySet represents a set of keys. A single Key or KeyRange can act as a KeySet. Use
  63. the KeySets function to build the union of several KeySets:
  64. ks1 := spanner.KeySets(key1, key2, kr1, kr2)
  65. AllKeys returns a KeySet that refers to all the keys in a table:
  66. ks2 := spanner.AllKeys()
  67. Transactions
  68. All Cloud Spanner reads and writes occur inside transactions. There are two
  69. types of transactions, read-only and read-write. Read-only transactions cannot
  70. change the database, do not acquire locks, and may access either the current
  71. database state or states in the past. Read-write transactions can read the
  72. database before writing to it, and always apply to the most recent database
  73. state.
  74. Single Reads
  75. The simplest and fastest transaction is a ReadOnlyTransaction that supports a
  76. single read operation. Use Client.Single to create such a transaction. You can
  77. chain the call to Single with a call to a Read method.
  78. When you only want one row whose key you know, use ReadRow. Provide the table
  79. name, key, and the columns you want to read:
  80. row, err := client.Single().ReadRow(ctx, "Accounts", spanner.Key{"alice"}, []string{"balance"})
  81. Read multiple rows with the Read method. It takes a table name, KeySet, and list
  82. of columns:
  83. iter := client.Single().Read(ctx, "Accounts", keyset1, columns)
  84. Read returns a RowIterator. You can call the Do method on the iterator and pass
  85. a callback:
  86. err := iter.Do(func(row *Row) error {
  87. // TODO: use row
  88. return nil
  89. })
  90. RowIterator also follows the standard pattern for the Google
  91. Cloud Client Libraries:
  92. defer iter.Stop()
  93. for {
  94. row, err := iter.Next()
  95. if err == iterator.Done {
  96. break
  97. }
  98. if err != nil {
  99. // TODO: Handle error.
  100. }
  101. // TODO: use row
  102. }
  103. Always call Stop when you finish using an iterator this way, whether or not you
  104. iterate to the end. (Failing to call Stop could lead you to exhaust the
  105. database's session quota.)
  106. To read rows with an index, use ReadUsingIndex.
  107. Statements
  108. The most general form of reading uses SQL statements. Construct a Statement
  109. with NewStatement, setting any parameters using the Statement's Params map:
  110. stmt := spanner.NewStatement("SELECT First, Last FROM SINGERS WHERE Last >= @start")
  111. stmt.Params["start"] = "Dylan"
  112. You can also construct a Statement directly with a struct literal, providing
  113. your own map of parameters.
  114. Use the Query method to run the statement and obtain an iterator:
  115. iter := client.Single().Query(ctx, stmt)
  116. Rows
  117. Once you have a Row, via an iterator or a call to ReadRow, you can extract
  118. column values in several ways. Pass in a pointer to a Go variable of the
  119. appropriate type when you extract a value.
  120. You can extract by column position or name:
  121. err := row.Column(0, &name)
  122. err = row.ColumnByName("balance", &balance)
  123. You can extract all the columns at once:
  124. err = row.Columns(&name, &balance)
  125. Or you can define a Go struct that corresponds to your columns, and extract
  126. into that:
  127. var s struct { Name string; Balance int64 }
  128. err = row.ToStruct(&s)
  129. For Cloud Spanner columns that may contain NULL, use one of the NullXXX types,
  130. like NullString:
  131. var ns spanner.NullString
  132. if err := row.Column(0, &ns); err != nil {
  133. // TODO: Handle error.
  134. }
  135. if ns.Valid {
  136. fmt.Println(ns.StringVal)
  137. } else {
  138. fmt.Println("column is NULL")
  139. }
  140. Multiple Reads
  141. To perform more than one read in a transaction, use ReadOnlyTransaction:
  142. txn := client.ReadOnlyTransaction()
  143. defer txn.Close()
  144. iter := txn.Query(ctx, stmt1)
  145. // ...
  146. iter = txn.Query(ctx, stmt2)
  147. // ...
  148. You must call Close when you are done with the transaction.
  149. Timestamps and Timestamp Bounds
  150. Cloud Spanner read-only transactions conceptually perform all their reads at a
  151. single moment in time, called the transaction's read timestamp. Once a read has
  152. started, you can call ReadOnlyTransaction's Timestamp method to obtain the read
  153. timestamp.
  154. By default, a transaction will pick the most recent time (a time where all
  155. previously committed transactions are visible) for its reads. This provides the
  156. freshest data, but may involve some delay. You can often get a quicker response
  157. if you are willing to tolerate "stale" data. You can control the read timestamp
  158. selected by a transaction by calling the WithTimestampBound method on the
  159. transaction before using it. For example, to perform a query on data that is at
  160. most one minute stale, use
  161. client.Single().
  162. WithTimestampBound(spanner.MaxStaleness(1*time.Minute)).
  163. Query(ctx, stmt)
  164. See the documentation of TimestampBound for more details.
  165. Mutations
  166. To write values to a Cloud Spanner database, construct a Mutation. The spanner
  167. package has functions for inserting, updating and deleting rows. Except for the
  168. Delete methods, which take a Key or KeyRange, each mutation-building function
  169. comes in three varieties.
  170. One takes lists of columns and values along with the table name:
  171. m1 := spanner.Insert("Users",
  172. []string{"name", "email"},
  173. []interface{}{"alice", "a@example.com"})
  174. One takes a map from column names to values:
  175. m2 := spanner.InsertMap("Users", map[string]interface{}{
  176. "name": "alice",
  177. "email": "a@example.com",
  178. })
  179. And the third accepts a struct value, and determines the columns from the
  180. struct field names:
  181. type User struct { Name, Email string }
  182. u := User{Name: "alice", Email: "a@example.com"}
  183. m3, err := spanner.InsertStruct("Users", u)
  184. Writes
  185. To apply a list of mutations to the database, use Apply:
  186. _, err := client.Apply(ctx, []*spanner.Mutation{m1, m2, m3})
  187. If you need to read before writing in a single transaction, use a
  188. ReadWriteTransaction. ReadWriteTransactions may abort and need to be retried.
  189. You pass in a function to ReadWriteTransaction, and the client will handle the
  190. retries automatically. Use the transaction's BufferWrite method to buffer
  191. mutations, which will all be executed at the end of the transaction:
  192. _, err := client.ReadWriteTransaction(ctx, func(ctx context.Context, txn *spanner.ReadWriteTransaction) error {
  193. var balance int64
  194. row, err := txn.ReadRow(ctx, "Accounts", spanner.Key{"alice"}, []string{"balance"})
  195. if err != nil {
  196. // This function will be called again if this is an IsAborted error.
  197. return err
  198. }
  199. if err := row.Column(0, &balance); err != nil {
  200. return err
  201. }
  202. if balance <= 10 {
  203. return errors.New("insufficient funds in account")
  204. }
  205. balance -= 10
  206. m := spanner.Update("Accounts", []string{"user", "balance"}, []interface{}{"alice", balance})
  207. txn.BufferWrite([]*spanner.Mutation{m})
  208. // The buffered mutation will be committed. If the commit
  209. // fails with an IsAborted error, this function will be called
  210. // again.
  211. return nil
  212. })
  213. Tracing
  214. This client has been instrumented to use OpenCensus tracing (http://opencensus.io).
  215. To enable tracing, see "Enabling Tracing for a Program" at
  216. https://godoc.org/go.opencensus.io/trace. OpenCensus tracing requires Go 1.8 or higher.
  217. */
  218. package spanner // import "cloud.google.com/go/spanner"