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.
 
 
 

431 lines
14 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. package spanner
  14. import (
  15. "reflect"
  16. proto3 "github.com/golang/protobuf/ptypes/struct"
  17. sppb "google.golang.org/genproto/googleapis/spanner/v1"
  18. "google.golang.org/grpc/codes"
  19. )
  20. // op is the mutation operation.
  21. type op int
  22. const (
  23. // opDelete removes a row from a table. Succeeds whether or not the
  24. // key was present.
  25. opDelete op = iota
  26. // opInsert inserts a row into a table. If the row already exists, the
  27. // write or transaction fails.
  28. opInsert
  29. // opInsertOrUpdate inserts a row into a table. If the row already
  30. // exists, it updates it instead. Any column values not explicitly
  31. // written are preserved.
  32. opInsertOrUpdate
  33. // opReplace inserts a row into a table, deleting any existing row.
  34. // Unlike InsertOrUpdate, this means any values not explicitly written
  35. // become NULL.
  36. opReplace
  37. // opUpdate updates a row in a table. If the row does not already
  38. // exist, the write or transaction fails.
  39. opUpdate
  40. )
  41. // A Mutation describes a modification to one or more Cloud Spanner rows. The
  42. // mutation represents an insert, update, delete, etc on a table.
  43. //
  44. // Many mutations can be applied in a single atomic commit. For purposes of
  45. // constraint checking (such as foreign key constraints), the operations can be
  46. // viewed as applying in the same order as the mutations are provided (so that, e.g.,
  47. // a row and its logical "child" can be inserted in the same commit).
  48. //
  49. // The Apply function applies series of mutations. For example,
  50. //
  51. // m := spanner.Insert("User",
  52. // []string{"user_id", "profile"},
  53. // []interface{}{UserID, profile})
  54. // _, err := client.Apply(ctx, []*spanner.Mutation{m})
  55. //
  56. // inserts a new row into the User table. The primary key
  57. // for the new row is UserID (presuming that "user_id" has been declared as the
  58. // primary key of the "User" table).
  59. //
  60. // To apply a series of mutations as part of an atomic read-modify-write operation,
  61. // use ReadWriteTransaction.
  62. //
  63. // Updating a row
  64. //
  65. // Changing the values of columns in an existing row is very similar to
  66. // inserting a new row:
  67. //
  68. // m := spanner.Update("User",
  69. // []string{"user_id", "profile"},
  70. // []interface{}{UserID, profile})
  71. // _, err := client.Apply(ctx, []*spanner.Mutation{m})
  72. //
  73. // Deleting a row
  74. //
  75. // To delete a row, use spanner.Delete:
  76. //
  77. // m := spanner.Delete("User", spanner.Key{UserId})
  78. // _, err := client.Apply(ctx, []*spanner.Mutation{m})
  79. //
  80. // spanner.Delete accepts a KeySet, so you can also pass in a KeyRange, or use the
  81. // spanner.KeySets function to build any combination of Keys and KeyRanges.
  82. //
  83. // Note that deleting a row in a table may also delete rows from other tables
  84. // if cascading deletes are specified in those tables' schemas. Delete does
  85. // nothing if the named row does not exist (does not yield an error).
  86. //
  87. // Deleting a field
  88. //
  89. // To delete/clear a field within a row, use spanner.Update with the value nil:
  90. //
  91. // m := spanner.Update("User",
  92. // []string{"user_id", "profile"},
  93. // []interface{}{UserID, nil})
  94. // _, err := client.Apply(ctx, []*spanner.Mutation{m})
  95. //
  96. // The valid Go types and their corresponding Cloud Spanner types that can be
  97. // used in the Insert/Update/InsertOrUpdate functions are:
  98. //
  99. // string, NullString - STRING
  100. // []string, []NullString - STRING ARRAY
  101. // []byte - BYTES
  102. // [][]byte - BYTES ARRAY
  103. // int, int64, NullInt64 - INT64
  104. // []int, []int64, []NullInt64 - INT64 ARRAY
  105. // bool, NullBool - BOOL
  106. // []bool, []NullBool - BOOL ARRAY
  107. // float64, NullFloat64 - FLOAT64
  108. // []float64, []NullFloat64 - FLOAT64 ARRAY
  109. // time.Time, NullTime - TIMESTAMP
  110. // []time.Time, []NullTime - TIMESTAMP ARRAY
  111. // Date, NullDate - DATE
  112. // []Date, []NullDate - DATE ARRAY
  113. //
  114. // To compare two Mutations for testing purposes, use reflect.DeepEqual.
  115. type Mutation struct {
  116. // op is the operation type of the mutation.
  117. // See documentation for spanner.op for more details.
  118. op op
  119. // Table is the name of the target table to be modified.
  120. table string
  121. // keySet is a set of primary keys that names the rows
  122. // in a delete operation.
  123. keySet KeySet
  124. // columns names the set of columns that are going to be
  125. // modified by Insert, InsertOrUpdate, Replace or Update
  126. // operations.
  127. columns []string
  128. // values specifies the new values for the target columns
  129. // named by Columns.
  130. values []interface{}
  131. }
  132. // mapToMutationParams converts Go map into mutation parameters.
  133. func mapToMutationParams(in map[string]interface{}) ([]string, []interface{}) {
  134. cols := []string{}
  135. vals := []interface{}{}
  136. for k, v := range in {
  137. cols = append(cols, k)
  138. vals = append(vals, v)
  139. }
  140. return cols, vals
  141. }
  142. // errNotStruct returns error for not getting a go struct type.
  143. func errNotStruct(in interface{}) error {
  144. return spannerErrorf(codes.InvalidArgument, "%T is not a go struct type", in)
  145. }
  146. // structToMutationParams converts Go struct into mutation parameters.
  147. // If the input is not a valid Go struct type, structToMutationParams
  148. // returns error.
  149. func structToMutationParams(in interface{}) ([]string, []interface{}, error) {
  150. if in == nil {
  151. return nil, nil, errNotStruct(in)
  152. }
  153. v := reflect.ValueOf(in)
  154. t := v.Type()
  155. if t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct {
  156. // t is a pointer to a struct.
  157. if v.IsNil() {
  158. // Return empty results.
  159. return nil, nil, nil
  160. }
  161. // Get the struct value that in points to.
  162. v = v.Elem()
  163. t = t.Elem()
  164. }
  165. if t.Kind() != reflect.Struct {
  166. return nil, nil, errNotStruct(in)
  167. }
  168. fields, err := fieldCache.Fields(t)
  169. if err != nil {
  170. return nil, nil, toSpannerError(err)
  171. }
  172. var cols []string
  173. var vals []interface{}
  174. for _, f := range fields {
  175. cols = append(cols, f.Name)
  176. vals = append(vals, v.FieldByIndex(f.Index).Interface())
  177. }
  178. return cols, vals, nil
  179. }
  180. // Insert returns a Mutation to insert a row into a table. If the row already
  181. // exists, the write or transaction fails.
  182. func Insert(table string, cols []string, vals []interface{}) *Mutation {
  183. return &Mutation{
  184. op: opInsert,
  185. table: table,
  186. columns: cols,
  187. values: vals,
  188. }
  189. }
  190. // InsertMap returns a Mutation to insert a row into a table, specified by
  191. // a map of column name to value. If the row already exists, the write or
  192. // transaction fails.
  193. func InsertMap(table string, in map[string]interface{}) *Mutation {
  194. cols, vals := mapToMutationParams(in)
  195. return Insert(table, cols, vals)
  196. }
  197. // InsertStruct returns a Mutation to insert a row into a table, specified by
  198. // a Go struct. If the row already exists, the write or transaction fails.
  199. //
  200. // The in argument must be a struct or a pointer to a struct. Its exported
  201. // fields specify the column names and values. Use a field tag like "spanner:name"
  202. // to provide an alternative column name, or use "spanner:-" to ignore the field.
  203. func InsertStruct(table string, in interface{}) (*Mutation, error) {
  204. cols, vals, err := structToMutationParams(in)
  205. if err != nil {
  206. return nil, err
  207. }
  208. return Insert(table, cols, vals), nil
  209. }
  210. // Update returns a Mutation to update a row in a table. If the row does not
  211. // already exist, the write or transaction fails.
  212. func Update(table string, cols []string, vals []interface{}) *Mutation {
  213. return &Mutation{
  214. op: opUpdate,
  215. table: table,
  216. columns: cols,
  217. values: vals,
  218. }
  219. }
  220. // UpdateMap returns a Mutation to update a row in a table, specified by
  221. // a map of column to value. If the row does not already exist, the write or
  222. // transaction fails.
  223. func UpdateMap(table string, in map[string]interface{}) *Mutation {
  224. cols, vals := mapToMutationParams(in)
  225. return Update(table, cols, vals)
  226. }
  227. // UpdateStruct returns a Mutation to update a row in a table, specified by a Go
  228. // struct. If the row does not already exist, the write or transaction fails.
  229. func UpdateStruct(table string, in interface{}) (*Mutation, error) {
  230. cols, vals, err := structToMutationParams(in)
  231. if err != nil {
  232. return nil, err
  233. }
  234. return Update(table, cols, vals), nil
  235. }
  236. // InsertOrUpdate returns a Mutation to insert a row into a table. If the row
  237. // already exists, it updates it instead. Any column values not explicitly
  238. // written are preserved.
  239. //
  240. // For a similar example, See Update.
  241. func InsertOrUpdate(table string, cols []string, vals []interface{}) *Mutation {
  242. return &Mutation{
  243. op: opInsertOrUpdate,
  244. table: table,
  245. columns: cols,
  246. values: vals,
  247. }
  248. }
  249. // InsertOrUpdateMap returns a Mutation to insert a row into a table,
  250. // specified by a map of column to value. If the row already exists, it
  251. // updates it instead. Any column values not explicitly written are preserved.
  252. //
  253. // For a similar example, See UpdateMap.
  254. func InsertOrUpdateMap(table string, in map[string]interface{}) *Mutation {
  255. cols, vals := mapToMutationParams(in)
  256. return InsertOrUpdate(table, cols, vals)
  257. }
  258. // InsertOrUpdateStruct returns a Mutation to insert a row into a table,
  259. // specified by a Go struct. If the row already exists, it updates it instead.
  260. // Any column values not explicitly written are preserved.
  261. //
  262. // The in argument must be a struct or a pointer to a struct. Its exported
  263. // fields specify the column names and values. Use a field tag like "spanner:name"
  264. // to provide an alternative column name, or use "spanner:-" to ignore the field.
  265. //
  266. // For a similar example, See UpdateStruct.
  267. func InsertOrUpdateStruct(table string, in interface{}) (*Mutation, error) {
  268. cols, vals, err := structToMutationParams(in)
  269. if err != nil {
  270. return nil, err
  271. }
  272. return InsertOrUpdate(table, cols, vals), nil
  273. }
  274. // Replace returns a Mutation to insert a row into a table, deleting any
  275. // existing row. Unlike InsertOrUpdate, this means any values not explicitly
  276. // written become NULL.
  277. //
  278. // For a similar example, See Update.
  279. func Replace(table string, cols []string, vals []interface{}) *Mutation {
  280. return &Mutation{
  281. op: opReplace,
  282. table: table,
  283. columns: cols,
  284. values: vals,
  285. }
  286. }
  287. // ReplaceMap returns a Mutation to insert a row into a table, deleting any
  288. // existing row. Unlike InsertOrUpdateMap, this means any values not explicitly
  289. // written become NULL. The row is specified by a map of column to value.
  290. //
  291. // For a similar example, See UpdateMap.
  292. func ReplaceMap(table string, in map[string]interface{}) *Mutation {
  293. cols, vals := mapToMutationParams(in)
  294. return Replace(table, cols, vals)
  295. }
  296. // ReplaceStruct returns a Mutation to insert a row into a table, deleting any
  297. // existing row. Unlike InsertOrUpdateMap, this means any values not explicitly
  298. // written become NULL. The row is specified by a Go struct.
  299. //
  300. // The in argument must be a struct or a pointer to a struct. Its exported
  301. // fields specify the column names and values. Use a field tag like "spanner:name"
  302. // to provide an alternative column name, or use "spanner:-" to ignore the field.
  303. //
  304. // For a similar example, See UpdateStruct.
  305. func ReplaceStruct(table string, in interface{}) (*Mutation, error) {
  306. cols, vals, err := structToMutationParams(in)
  307. if err != nil {
  308. return nil, err
  309. }
  310. return Replace(table, cols, vals), nil
  311. }
  312. // Delete removes the rows described by the KeySet from the table. It succeeds
  313. // whether or not the keys were present.
  314. func Delete(table string, ks KeySet) *Mutation {
  315. return &Mutation{
  316. op: opDelete,
  317. table: table,
  318. keySet: ks,
  319. }
  320. }
  321. // prepareWrite generates sppb.Mutation_Write from table name, column names
  322. // and new column values.
  323. func prepareWrite(table string, columns []string, vals []interface{}) (*sppb.Mutation_Write, error) {
  324. v, err := encodeValueArray(vals)
  325. if err != nil {
  326. return nil, err
  327. }
  328. return &sppb.Mutation_Write{
  329. Table: table,
  330. Columns: columns,
  331. Values: []*proto3.ListValue{v},
  332. }, nil
  333. }
  334. // errInvdMutationOp returns error for unrecognized mutation operation.
  335. func errInvdMutationOp(m Mutation) error {
  336. return spannerErrorf(codes.InvalidArgument, "Unknown op type: %d", m.op)
  337. }
  338. // proto converts spanner.Mutation to sppb.Mutation, in preparation to send
  339. // RPCs.
  340. func (m Mutation) proto() (*sppb.Mutation, error) {
  341. var pb *sppb.Mutation
  342. switch m.op {
  343. case opDelete:
  344. var kp *sppb.KeySet
  345. if m.keySet != nil {
  346. var err error
  347. kp, err = m.keySet.keySetProto()
  348. if err != nil {
  349. return nil, err
  350. }
  351. }
  352. pb = &sppb.Mutation{
  353. Operation: &sppb.Mutation_Delete_{
  354. Delete: &sppb.Mutation_Delete{
  355. Table: m.table,
  356. KeySet: kp,
  357. },
  358. },
  359. }
  360. case opInsert:
  361. w, err := prepareWrite(m.table, m.columns, m.values)
  362. if err != nil {
  363. return nil, err
  364. }
  365. pb = &sppb.Mutation{Operation: &sppb.Mutation_Insert{Insert: w}}
  366. case opInsertOrUpdate:
  367. w, err := prepareWrite(m.table, m.columns, m.values)
  368. if err != nil {
  369. return nil, err
  370. }
  371. pb = &sppb.Mutation{Operation: &sppb.Mutation_InsertOrUpdate{InsertOrUpdate: w}}
  372. case opReplace:
  373. w, err := prepareWrite(m.table, m.columns, m.values)
  374. if err != nil {
  375. return nil, err
  376. }
  377. pb = &sppb.Mutation{Operation: &sppb.Mutation_Replace{Replace: w}}
  378. case opUpdate:
  379. w, err := prepareWrite(m.table, m.columns, m.values)
  380. if err != nil {
  381. return nil, err
  382. }
  383. pb = &sppb.Mutation{Operation: &sppb.Mutation_Update{Update: w}}
  384. default:
  385. return nil, errInvdMutationOp(m)
  386. }
  387. return pb, nil
  388. }
  389. // mutationsProto turns a spanner.Mutation array into a sppb.Mutation array,
  390. // it is convenient for sending batch mutations to Cloud Spanner.
  391. func mutationsProto(ms []*Mutation) ([]*sppb.Mutation, error) {
  392. l := make([]*sppb.Mutation, 0, len(ms))
  393. for _, m := range ms {
  394. pb, err := m.proto()
  395. if err != nil {
  396. return nil, err
  397. }
  398. l = append(l, pb)
  399. }
  400. return l, nil
  401. }