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.
 
 
 

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