compare.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2016 CoreOS, Inc.
  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 clientv3
  15. import (
  16. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  17. )
  18. type CompareTarget int
  19. type CompareResult int
  20. const (
  21. CompareVersion CompareTarget = iota
  22. CompareCreated
  23. CompareModified
  24. CompareValue
  25. )
  26. type Cmp pb.Compare
  27. func Compare(key string, t pb.Compare_CompareTarget, result string, v interface{}) Cmp {
  28. var r pb.Compare_CompareResult
  29. switch result {
  30. case "=":
  31. r = pb.Compare_EQUAL
  32. case ">":
  33. r = pb.Compare_GREATER
  34. case "<":
  35. r = pb.Compare_LESS
  36. default:
  37. panic("Unknown result op")
  38. }
  39. switch t {
  40. case pb.Compare_VALUE:
  41. val, ok := v.(string)
  42. if !ok {
  43. panic("bad compare value")
  44. }
  45. return Cmp{Key: []byte(key), Result: r, Target: t, TargetUnion: &pb.Compare_Value{Value: []byte(val)}}
  46. case pb.Compare_VERSION:
  47. return Cmp{Key: []byte(key), Result: r, Target: t, TargetUnion: &pb.Compare_Version{Version: mustInt64(v)}}
  48. case pb.Compare_CREATE:
  49. return Cmp{Key: []byte(key), Result: r, Target: t, TargetUnion: &pb.Compare_CreateRevision{CreateRevision: mustInt64(v)}}
  50. case pb.Compare_MOD:
  51. return Cmp{Key: []byte(key), Result: r, Target: t, TargetUnion: &pb.Compare_ModRevision{ModRevision: mustInt64(v)}}
  52. default:
  53. panic("Unknown compare type")
  54. }
  55. }
  56. func Value(key string) (string, pb.Compare_CompareTarget) {
  57. return key, pb.Compare_VALUE
  58. }
  59. func Version(key string) (string, pb.Compare_CompareTarget) {
  60. return key, pb.Compare_VERSION
  61. }
  62. func CreatedRevision(key string) (string, pb.Compare_CompareTarget) {
  63. return key, pb.Compare_CREATE
  64. }
  65. func ModifiedRevision(key string) (string, pb.Compare_CompareTarget) {
  66. return key, pb.Compare_MOD
  67. }
  68. func mustInt64(val interface{}) int64 {
  69. if v, ok := val.(int64); ok {
  70. return v
  71. }
  72. if v, ok := val.(int); ok {
  73. return int64(v)
  74. }
  75. panic("bad value")
  76. }