scan.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. // Copyright 2012 Gary Burd
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // 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, WITHOUT
  11. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. // License for the specific language governing permissions and limitations
  13. // under the License.
  14. package redis
  15. import (
  16. "errors"
  17. "fmt"
  18. "reflect"
  19. "strconv"
  20. "strings"
  21. "sync"
  22. )
  23. func ensureLen(d reflect.Value, n int) {
  24. if n > d.Cap() {
  25. d.Set(reflect.MakeSlice(d.Type(), n, n))
  26. } else {
  27. d.SetLen(n)
  28. }
  29. }
  30. func cannotConvert(d reflect.Value, s interface{}) error {
  31. var sname string
  32. switch s.(type) {
  33. case string:
  34. sname = "Redis simple string"
  35. case Error:
  36. sname = "Redis error"
  37. case int64:
  38. sname = "Redis integer"
  39. case []byte:
  40. sname = "Redis bulk string"
  41. case []interface{}:
  42. sname = "Redis array"
  43. default:
  44. sname = reflect.TypeOf(s).String()
  45. }
  46. return fmt.Errorf("cannot convert from %s to %s", sname, d.Type())
  47. }
  48. func convertAssignBulkString(d reflect.Value, s []byte) (err error) {
  49. switch d.Type().Kind() {
  50. case reflect.Float32, reflect.Float64:
  51. var x float64
  52. x, err = strconv.ParseFloat(string(s), d.Type().Bits())
  53. d.SetFloat(x)
  54. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  55. var x int64
  56. x, err = strconv.ParseInt(string(s), 10, d.Type().Bits())
  57. d.SetInt(x)
  58. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  59. var x uint64
  60. x, err = strconv.ParseUint(string(s), 10, d.Type().Bits())
  61. d.SetUint(x)
  62. case reflect.Bool:
  63. var x bool
  64. x, err = strconv.ParseBool(string(s))
  65. d.SetBool(x)
  66. case reflect.String:
  67. d.SetString(string(s))
  68. case reflect.Slice:
  69. if d.Type().Elem().Kind() != reflect.Uint8 {
  70. err = cannotConvert(d, s)
  71. } else {
  72. d.SetBytes(s)
  73. }
  74. default:
  75. err = cannotConvert(d, s)
  76. }
  77. return
  78. }
  79. func convertAssignInt(d reflect.Value, s int64) (err error) {
  80. switch d.Type().Kind() {
  81. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  82. d.SetInt(s)
  83. if d.Int() != s {
  84. err = strconv.ErrRange
  85. d.SetInt(0)
  86. }
  87. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  88. if s < 0 {
  89. err = strconv.ErrRange
  90. } else {
  91. x := uint64(s)
  92. d.SetUint(x)
  93. if d.Uint() != x {
  94. err = strconv.ErrRange
  95. d.SetUint(0)
  96. }
  97. }
  98. case reflect.Bool:
  99. d.SetBool(s != 0)
  100. default:
  101. err = cannotConvert(d, s)
  102. }
  103. return
  104. }
  105. func convertAssignValue(d reflect.Value, s interface{}) (err error) {
  106. switch s := s.(type) {
  107. case []byte:
  108. err = convertAssignBulkString(d, s)
  109. case int64:
  110. err = convertAssignInt(d, s)
  111. default:
  112. err = cannotConvert(d, s)
  113. }
  114. return err
  115. }
  116. func convertAssignArray(d reflect.Value, s []interface{}) error {
  117. if d.Type().Kind() != reflect.Slice {
  118. return cannotConvert(d, s)
  119. }
  120. ensureLen(d, len(s))
  121. for i := 0; i < len(s); i++ {
  122. if err := convertAssignValue(d.Index(i), s[i]); err != nil {
  123. return err
  124. }
  125. }
  126. return nil
  127. }
  128. func convertAssign(d interface{}, s interface{}) (err error) {
  129. // Handle the most common destination types using type switches and
  130. // fall back to reflection for all other types.
  131. switch s := s.(type) {
  132. case nil:
  133. // ingore
  134. case []byte:
  135. switch d := d.(type) {
  136. case *string:
  137. *d = string(s)
  138. case *int:
  139. *d, err = strconv.Atoi(string(s))
  140. case *bool:
  141. *d, err = strconv.ParseBool(string(s))
  142. case *[]byte:
  143. *d = s
  144. case *interface{}:
  145. *d = s
  146. case nil:
  147. // skip value
  148. default:
  149. if d := reflect.ValueOf(d); d.Type().Kind() != reflect.Ptr {
  150. err = cannotConvert(d, s)
  151. } else {
  152. err = convertAssignBulkString(d.Elem(), s)
  153. }
  154. }
  155. case int64:
  156. switch d := d.(type) {
  157. case *int:
  158. x := int(s)
  159. if int64(x) != s {
  160. err = strconv.ErrRange
  161. x = 0
  162. }
  163. *d = x
  164. case *bool:
  165. *d = s != 0
  166. case *interface{}:
  167. *d = s
  168. case nil:
  169. // skip value
  170. default:
  171. if d := reflect.ValueOf(d); d.Type().Kind() != reflect.Ptr {
  172. err = cannotConvert(d, s)
  173. } else {
  174. err = convertAssignInt(d.Elem(), s)
  175. }
  176. }
  177. case []interface{}:
  178. switch d := d.(type) {
  179. case *[]interface{}:
  180. *d = s
  181. case *interface{}:
  182. *d = s
  183. case nil:
  184. // skip value
  185. default:
  186. if d := reflect.ValueOf(d); d.Type().Kind() != reflect.Ptr {
  187. err = cannotConvert(d, s)
  188. } else {
  189. err = convertAssignArray(d.Elem(), s)
  190. }
  191. }
  192. case Error:
  193. err = s
  194. default:
  195. err = cannotConvert(reflect.ValueOf(d), s)
  196. }
  197. return
  198. }
  199. // Scan copies from src to the values pointed at by dest.
  200. //
  201. // The values pointed at by dest must be an integer, float, boolean, string,
  202. // []byte, interface{} or slices of these types. Scan uses the standard strconv
  203. // package to convert bulk strings to numeric and boolean types.
  204. //
  205. // If a dest value is nil, then the corresponding src value is skipped.
  206. //
  207. // If a src element is nil, then the corresponding dest value is not modified.
  208. //
  209. // To enable easy use of Scan in a loop, Scan returns the slice of src
  210. // following the copied values.
  211. func Scan(src []interface{}, dest ...interface{}) ([]interface{}, error) {
  212. if len(src) < len(dest) {
  213. return nil, errors.New("redigo.Scan: array short")
  214. }
  215. var err error
  216. for i, d := range dest {
  217. err = convertAssign(d, src[i])
  218. if err != nil {
  219. err = fmt.Errorf("redigo.Scan: cannot assign to dest %d: %v", i, err)
  220. break
  221. }
  222. }
  223. return src[len(dest):], err
  224. }
  225. type fieldSpec struct {
  226. name string
  227. index []int
  228. //omitEmpty bool
  229. }
  230. type structSpec struct {
  231. m map[string]*fieldSpec
  232. l []*fieldSpec
  233. }
  234. func (ss *structSpec) fieldSpec(name []byte) *fieldSpec {
  235. return ss.m[string(name)]
  236. }
  237. func compileStructSpec(t reflect.Type, depth map[string]int, index []int, ss *structSpec) {
  238. for i := 0; i < t.NumField(); i++ {
  239. f := t.Field(i)
  240. switch {
  241. case f.PkgPath != "":
  242. // Ignore unexported fields.
  243. case f.Anonymous:
  244. // TODO: Handle pointers. Requires change to decoder and
  245. // protection against infinite recursion.
  246. if f.Type.Kind() == reflect.Struct {
  247. compileStructSpec(f.Type, depth, append(index, i), ss)
  248. }
  249. default:
  250. fs := &fieldSpec{name: f.Name}
  251. tag := f.Tag.Get("redis")
  252. p := strings.Split(tag, ",")
  253. if len(p) > 0 {
  254. if p[0] == "-" {
  255. continue
  256. }
  257. if len(p[0]) > 0 {
  258. fs.name = p[0]
  259. }
  260. for _, s := range p[1:] {
  261. switch s {
  262. //case "omitempty":
  263. // fs.omitempty = true
  264. default:
  265. panic(fmt.Errorf("redigo: unknown field tag %s for type %s", s, t.Name()))
  266. }
  267. }
  268. }
  269. d, found := depth[fs.name]
  270. if !found {
  271. d = 1 << 30
  272. }
  273. switch {
  274. case len(index) == d:
  275. // At same depth, remove from result.
  276. delete(ss.m, fs.name)
  277. j := 0
  278. for i := 0; i < len(ss.l); i++ {
  279. if fs.name != ss.l[i].name {
  280. ss.l[j] = ss.l[i]
  281. j += 1
  282. }
  283. }
  284. ss.l = ss.l[:j]
  285. case len(index) < d:
  286. fs.index = make([]int, len(index)+1)
  287. copy(fs.index, index)
  288. fs.index[len(index)] = i
  289. depth[fs.name] = len(index)
  290. ss.m[fs.name] = fs
  291. ss.l = append(ss.l, fs)
  292. }
  293. }
  294. }
  295. }
  296. var (
  297. structSpecMutex sync.RWMutex
  298. structSpecCache = make(map[reflect.Type]*structSpec)
  299. defaultFieldSpec = &fieldSpec{}
  300. )
  301. func structSpecForType(t reflect.Type) *structSpec {
  302. structSpecMutex.RLock()
  303. ss, found := structSpecCache[t]
  304. structSpecMutex.RUnlock()
  305. if found {
  306. return ss
  307. }
  308. structSpecMutex.Lock()
  309. defer structSpecMutex.Unlock()
  310. ss, found = structSpecCache[t]
  311. if found {
  312. return ss
  313. }
  314. ss = &structSpec{m: make(map[string]*fieldSpec)}
  315. compileStructSpec(t, make(map[string]int), nil, ss)
  316. structSpecCache[t] = ss
  317. return ss
  318. }
  319. var errScanStructValue = errors.New("redigo.ScanStruct: value must be non-nil pointer to a struct")
  320. // ScanStruct scans alternating names and values from src to a struct. The
  321. // HGETALL and CONFIG GET commands return replies in this format.
  322. //
  323. // ScanStruct uses exported field names to match values in the response. Use
  324. // 'redis' field tag to override the name:
  325. //
  326. // Field int `redis:"myName"`
  327. //
  328. // Fields with the tag redis:"-" are ignored.
  329. //
  330. // Integer, float, boolean, string and []byte fields are supported. Scan uses the
  331. // standard strconv package to convert bulk string values to numeric and
  332. // boolean types.
  333. //
  334. // If a src element is nil, then the corresponding field is not modified.
  335. func ScanStruct(src []interface{}, dest interface{}) error {
  336. d := reflect.ValueOf(dest)
  337. if d.Kind() != reflect.Ptr || d.IsNil() {
  338. return errScanStructValue
  339. }
  340. d = d.Elem()
  341. if d.Kind() != reflect.Struct {
  342. return errScanStructValue
  343. }
  344. ss := structSpecForType(d.Type())
  345. if len(src)%2 != 0 {
  346. return errors.New("redigo.ScanStruct: number of values not a multiple of 2")
  347. }
  348. for i := 0; i < len(src); i += 2 {
  349. s := src[i+1]
  350. if s == nil {
  351. continue
  352. }
  353. name, ok := src[i].([]byte)
  354. if !ok {
  355. return fmt.Errorf("redigo.ScanStruct: key %d not a bulk string value", i)
  356. }
  357. fs := ss.fieldSpec(name)
  358. if fs == nil {
  359. continue
  360. }
  361. if err := convertAssignValue(d.FieldByIndex(fs.index), s); err != nil {
  362. return fmt.Errorf("redigo.ScanStruct: cannot assign field %s: %v", fs.name, err)
  363. }
  364. }
  365. return nil
  366. }
  367. var (
  368. errScanSliceValue = errors.New("redigo.ScanSlice: dest must be non-nil pointer to a struct")
  369. )
  370. // ScanSlice scans src to the slice pointed to by dest. The elements the dest
  371. // slice must be integer, float, boolean, string, struct or pointer to struct
  372. // values.
  373. //
  374. // Struct fields must be integer, float, boolean or string values. All struct
  375. // fields are used unless a subset is specified using fieldNames.
  376. func ScanSlice(src []interface{}, dest interface{}, fieldNames ...string) error {
  377. d := reflect.ValueOf(dest)
  378. if d.Kind() != reflect.Ptr || d.IsNil() {
  379. return errScanSliceValue
  380. }
  381. d = d.Elem()
  382. if d.Kind() != reflect.Slice {
  383. return errScanSliceValue
  384. }
  385. isPtr := false
  386. t := d.Type().Elem()
  387. if t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct {
  388. isPtr = true
  389. t = t.Elem()
  390. }
  391. if t.Kind() != reflect.Struct {
  392. ensureLen(d, len(src))
  393. for i, s := range src {
  394. if s == nil {
  395. continue
  396. }
  397. if err := convertAssignValue(d.Index(i), s); err != nil {
  398. return fmt.Errorf("redigo.ScanSlice: cannot assign element %d: %v", i, err)
  399. }
  400. }
  401. return nil
  402. }
  403. ss := structSpecForType(t)
  404. fss := ss.l
  405. if len(fieldNames) > 0 {
  406. fss = make([]*fieldSpec, len(fieldNames))
  407. for i, name := range fieldNames {
  408. fss[i] = ss.m[name]
  409. if fss[i] == nil {
  410. return fmt.Errorf("redigo.ScanSlice: ScanSlice bad field name %s", name)
  411. }
  412. }
  413. }
  414. if len(fss) == 0 {
  415. return errors.New("redigo.ScanSlice: no struct fields")
  416. }
  417. n := len(src) / len(fss)
  418. if n*len(fss) != len(src) {
  419. return errors.New("redigo.ScanSlice: length not a multiple of struct field count")
  420. }
  421. ensureLen(d, n)
  422. for i := 0; i < n; i++ {
  423. d := d.Index(i)
  424. if isPtr {
  425. if d.IsNil() {
  426. d.Set(reflect.New(t))
  427. }
  428. d = d.Elem()
  429. }
  430. for j, fs := range fss {
  431. s := src[i*len(fss)+j]
  432. if s == nil {
  433. continue
  434. }
  435. if err := convertAssignValue(d.FieldByIndex(fs.index), s); err != nil {
  436. return fmt.Errorf("redigo.ScanSlice: cannot assign element %d to field %s: %v", i*len(fss)+j, fs.name, err)
  437. }
  438. }
  439. }
  440. return nil
  441. }
  442. // Args is a helper for constructing command arguments from structured values.
  443. type Args []interface{}
  444. // Add returns the result of appending value to args.
  445. func (args Args) Add(value ...interface{}) Args {
  446. return append(args, value...)
  447. }
  448. // AddFlat returns the result of appending the flattened value of v to args.
  449. //
  450. // Maps are flattened by appending the alternating keys and map values to args.
  451. //
  452. // Slices are flattened by appending the slice elements to args.
  453. //
  454. // Structs are flattened by appending the alternating names and values of
  455. // exported fields to args. If v is a nil struct pointer, then nothing is
  456. // appended. The 'redis' field tag overrides struct field names. See ScanStruct
  457. // for more information on the use of the 'redis' field tag.
  458. //
  459. // Other types are appended to args as is.
  460. func (args Args) AddFlat(v interface{}) Args {
  461. rv := reflect.ValueOf(v)
  462. switch rv.Kind() {
  463. case reflect.Struct:
  464. args = flattenStruct(args, rv)
  465. case reflect.Slice:
  466. for i := 0; i < rv.Len(); i++ {
  467. args = append(args, rv.Index(i).Interface())
  468. }
  469. case reflect.Map:
  470. for _, k := range rv.MapKeys() {
  471. args = append(args, k.Interface(), rv.MapIndex(k).Interface())
  472. }
  473. case reflect.Ptr:
  474. if rv.Type().Elem().Kind() == reflect.Struct {
  475. if !rv.IsNil() {
  476. args = flattenStruct(args, rv.Elem())
  477. }
  478. } else {
  479. args = append(args, v)
  480. }
  481. default:
  482. args = append(args, v)
  483. }
  484. return args
  485. }
  486. func flattenStruct(args Args, v reflect.Value) Args {
  487. ss := structSpecForType(v.Type())
  488. for _, fs := range ss.l {
  489. fv := v.FieldByIndex(fs.index)
  490. args = append(args, fs.name, fv.Interface())
  491. }
  492. return args
  493. }