scan.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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. case nil:
  44. sname = "Redis nil"
  45. default:
  46. sname = reflect.TypeOf(s).String()
  47. }
  48. return fmt.Errorf("cannot convert from %s to %s", sname, d.Type())
  49. }
  50. func convertAssignNil(d reflect.Value) (err error) {
  51. switch d.Type().Kind() {
  52. case reflect.Slice, reflect.Interface:
  53. d.Set(reflect.Zero(d.Type()))
  54. default:
  55. err = cannotConvert(d, nil)
  56. }
  57. return err
  58. }
  59. func convertAssignError(d reflect.Value, s Error) (err error) {
  60. if d.Kind() == reflect.String {
  61. d.SetString(string(s))
  62. } else if d.Kind() == reflect.Slice && d.Type().Elem().Kind() == reflect.Uint8 {
  63. d.SetBytes([]byte(s))
  64. } else {
  65. err = cannotConvert(d, s)
  66. }
  67. return
  68. }
  69. func convertAssignString(d reflect.Value, s string) (err error) {
  70. switch d.Type().Kind() {
  71. case reflect.Float32, reflect.Float64:
  72. var x float64
  73. x, err = strconv.ParseFloat(s, d.Type().Bits())
  74. d.SetFloat(x)
  75. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  76. var x int64
  77. x, err = strconv.ParseInt(s, 10, d.Type().Bits())
  78. d.SetInt(x)
  79. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  80. var x uint64
  81. x, err = strconv.ParseUint(s, 10, d.Type().Bits())
  82. d.SetUint(x)
  83. case reflect.Bool:
  84. var x bool
  85. x, err = strconv.ParseBool(s)
  86. d.SetBool(x)
  87. case reflect.String:
  88. d.SetString(s)
  89. case reflect.Slice:
  90. if d.Type().Elem().Kind() == reflect.Uint8 {
  91. d.SetBytes([]byte(s))
  92. } else {
  93. err = cannotConvert(d, s)
  94. }
  95. default:
  96. err = cannotConvert(d, s)
  97. }
  98. return
  99. }
  100. func convertAssignBulkString(d reflect.Value, s []byte) (err error) {
  101. switch d.Type().Kind() {
  102. case reflect.Slice:
  103. // Handle []byte destination here to avoid unnecessary
  104. // []byte -> string -> []byte converion.
  105. if d.Type().Elem().Kind() == reflect.Uint8 {
  106. d.SetBytes(s)
  107. } else {
  108. err = cannotConvert(d, s)
  109. }
  110. default:
  111. err = convertAssignString(d, string(s))
  112. }
  113. return err
  114. }
  115. func convertAssignInt(d reflect.Value, s int64) (err error) {
  116. switch d.Type().Kind() {
  117. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  118. d.SetInt(s)
  119. if d.Int() != s {
  120. err = strconv.ErrRange
  121. d.SetInt(0)
  122. }
  123. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  124. if s < 0 {
  125. err = strconv.ErrRange
  126. } else {
  127. x := uint64(s)
  128. d.SetUint(x)
  129. if d.Uint() != x {
  130. err = strconv.ErrRange
  131. d.SetUint(0)
  132. }
  133. }
  134. case reflect.Bool:
  135. d.SetBool(s != 0)
  136. default:
  137. err = cannotConvert(d, s)
  138. }
  139. return
  140. }
  141. func convertAssignValue(d reflect.Value, s interface{}) (err error) {
  142. if d.Kind() != reflect.Ptr {
  143. if d.CanAddr() {
  144. d2 := d.Addr()
  145. if d2.CanInterface() {
  146. if scanner, ok := d2.Interface().(Scanner); ok {
  147. return scanner.RedisScan(s)
  148. }
  149. }
  150. }
  151. } else if d.CanInterface() {
  152. // Already a reflect.Ptr
  153. if d.IsNil() {
  154. d.Set(reflect.New(d.Type().Elem()))
  155. }
  156. if scanner, ok := d.Interface().(Scanner); ok {
  157. return scanner.RedisScan(s)
  158. }
  159. }
  160. switch s := s.(type) {
  161. case nil:
  162. err = convertAssignNil(d)
  163. case []byte:
  164. err = convertAssignBulkString(d, s)
  165. case int64:
  166. err = convertAssignInt(d, s)
  167. case string:
  168. err = convertAssignString(d, s)
  169. case Error:
  170. err = convertAssignError(d, s)
  171. default:
  172. err = cannotConvert(d, s)
  173. }
  174. return err
  175. }
  176. func convertAssignArray(d reflect.Value, s []interface{}) error {
  177. if d.Type().Kind() != reflect.Slice {
  178. return cannotConvert(d, s)
  179. }
  180. ensureLen(d, len(s))
  181. for i := 0; i < len(s); i++ {
  182. if err := convertAssignValue(d.Index(i), s[i]); err != nil {
  183. return err
  184. }
  185. }
  186. return nil
  187. }
  188. func convertAssign(d interface{}, s interface{}) (err error) {
  189. if scanner, ok := d.(Scanner); ok {
  190. return scanner.RedisScan(s)
  191. }
  192. // Handle the most common destination types using type switches and
  193. // fall back to reflection for all other types.
  194. switch s := s.(type) {
  195. case nil:
  196. // ignore
  197. case []byte:
  198. switch d := d.(type) {
  199. case *string:
  200. *d = string(s)
  201. case *int:
  202. *d, err = strconv.Atoi(string(s))
  203. case *bool:
  204. *d, err = strconv.ParseBool(string(s))
  205. case *[]byte:
  206. *d = s
  207. case *interface{}:
  208. *d = s
  209. case nil:
  210. // skip value
  211. default:
  212. if d := reflect.ValueOf(d); d.Type().Kind() != reflect.Ptr {
  213. err = cannotConvert(d, s)
  214. } else {
  215. err = convertAssignBulkString(d.Elem(), s)
  216. }
  217. }
  218. case int64:
  219. switch d := d.(type) {
  220. case *int:
  221. x := int(s)
  222. if int64(x) != s {
  223. err = strconv.ErrRange
  224. x = 0
  225. }
  226. *d = x
  227. case *bool:
  228. *d = s != 0
  229. case *interface{}:
  230. *d = s
  231. case nil:
  232. // skip value
  233. default:
  234. if d := reflect.ValueOf(d); d.Type().Kind() != reflect.Ptr {
  235. err = cannotConvert(d, s)
  236. } else {
  237. err = convertAssignInt(d.Elem(), s)
  238. }
  239. }
  240. case string:
  241. switch d := d.(type) {
  242. case *string:
  243. *d = s
  244. case *interface{}:
  245. *d = s
  246. case nil:
  247. // skip value
  248. default:
  249. err = cannotConvert(reflect.ValueOf(d), s)
  250. }
  251. case []interface{}:
  252. switch d := d.(type) {
  253. case *[]interface{}:
  254. *d = s
  255. case *interface{}:
  256. *d = s
  257. case nil:
  258. // skip value
  259. default:
  260. if d := reflect.ValueOf(d); d.Type().Kind() != reflect.Ptr {
  261. err = cannotConvert(d, s)
  262. } else {
  263. err = convertAssignArray(d.Elem(), s)
  264. }
  265. }
  266. case Error:
  267. err = s
  268. default:
  269. err = cannotConvert(reflect.ValueOf(d), s)
  270. }
  271. return
  272. }
  273. // Scan copies from src to the values pointed at by dest.
  274. //
  275. // Scan uses RedisScan if available otherwise:
  276. //
  277. // The values pointed at by dest must be an integer, float, boolean, string,
  278. // []byte, interface{} or slices of these types. Scan uses the standard strconv
  279. // package to convert bulk strings to numeric and boolean types.
  280. //
  281. // If a dest value is nil, then the corresponding src value is skipped.
  282. //
  283. // If a src element is nil, then the corresponding dest value is not modified.
  284. //
  285. // To enable easy use of Scan in a loop, Scan returns the slice of src
  286. // following the copied values.
  287. func Scan(src []interface{}, dest ...interface{}) ([]interface{}, error) {
  288. if len(src) < len(dest) {
  289. return nil, errors.New("redigo.Scan: array short")
  290. }
  291. var err error
  292. for i, d := range dest {
  293. err = convertAssign(d, src[i])
  294. if err != nil {
  295. err = fmt.Errorf("redigo.Scan: cannot assign to dest %d: %v", i, err)
  296. break
  297. }
  298. }
  299. return src[len(dest):], err
  300. }
  301. type fieldSpec struct {
  302. name string
  303. index []int
  304. omitEmpty bool
  305. }
  306. type structSpec struct {
  307. m map[string]*fieldSpec
  308. l []*fieldSpec
  309. }
  310. func (ss *structSpec) fieldSpec(name []byte) *fieldSpec {
  311. return ss.m[string(name)]
  312. }
  313. func compileStructSpec(t reflect.Type, depth map[string]int, index []int, ss *structSpec) {
  314. for i := 0; i < t.NumField(); i++ {
  315. f := t.Field(i)
  316. switch {
  317. case f.PkgPath != "" && !f.Anonymous:
  318. // Ignore unexported fields.
  319. case f.Anonymous:
  320. // TODO: Handle pointers. Requires change to decoder and
  321. // protection against infinite recursion.
  322. if f.Type.Kind() == reflect.Struct {
  323. compileStructSpec(f.Type, depth, append(index, i), ss)
  324. }
  325. default:
  326. fs := &fieldSpec{name: f.Name}
  327. tag := f.Tag.Get("redis")
  328. p := strings.Split(tag, ",")
  329. if len(p) > 0 {
  330. if p[0] == "-" {
  331. continue
  332. }
  333. if len(p[0]) > 0 {
  334. fs.name = p[0]
  335. }
  336. for _, s := range p[1:] {
  337. switch s {
  338. case "omitempty":
  339. fs.omitEmpty = true
  340. default:
  341. panic(fmt.Errorf("redigo: unknown field tag %s for type %s", s, t.Name()))
  342. }
  343. }
  344. }
  345. d, found := depth[fs.name]
  346. if !found {
  347. d = 1 << 30
  348. }
  349. switch {
  350. case len(index) == d:
  351. // At same depth, remove from result.
  352. delete(ss.m, fs.name)
  353. j := 0
  354. for i := 0; i < len(ss.l); i++ {
  355. if fs.name != ss.l[i].name {
  356. ss.l[j] = ss.l[i]
  357. j += 1
  358. }
  359. }
  360. ss.l = ss.l[:j]
  361. case len(index) < d:
  362. fs.index = make([]int, len(index)+1)
  363. copy(fs.index, index)
  364. fs.index[len(index)] = i
  365. depth[fs.name] = len(index)
  366. ss.m[fs.name] = fs
  367. ss.l = append(ss.l, fs)
  368. }
  369. }
  370. }
  371. }
  372. var (
  373. structSpecMutex sync.RWMutex
  374. structSpecCache = make(map[reflect.Type]*structSpec)
  375. defaultFieldSpec = &fieldSpec{}
  376. )
  377. func structSpecForType(t reflect.Type) *structSpec {
  378. structSpecMutex.RLock()
  379. ss, found := structSpecCache[t]
  380. structSpecMutex.RUnlock()
  381. if found {
  382. return ss
  383. }
  384. structSpecMutex.Lock()
  385. defer structSpecMutex.Unlock()
  386. ss, found = structSpecCache[t]
  387. if found {
  388. return ss
  389. }
  390. ss = &structSpec{m: make(map[string]*fieldSpec)}
  391. compileStructSpec(t, make(map[string]int), nil, ss)
  392. structSpecCache[t] = ss
  393. return ss
  394. }
  395. var errScanStructValue = errors.New("redigo.ScanStruct: value must be non-nil pointer to a struct")
  396. // ScanStruct scans alternating names and values from src to a struct. The
  397. // HGETALL and CONFIG GET commands return replies in this format.
  398. //
  399. // ScanStruct uses exported field names to match values in the response. Use
  400. // 'redis' field tag to override the name:
  401. //
  402. // Field int `redis:"myName"`
  403. //
  404. // Fields with the tag redis:"-" are ignored.
  405. //
  406. // Each field uses RedisScan if available otherwise:
  407. // Integer, float, boolean, string and []byte fields are supported. Scan uses the
  408. // standard strconv package to convert bulk string values to numeric and
  409. // boolean types.
  410. //
  411. // If a src element is nil, then the corresponding field is not modified.
  412. func ScanStruct(src []interface{}, dest interface{}) error {
  413. d := reflect.ValueOf(dest)
  414. if d.Kind() != reflect.Ptr || d.IsNil() {
  415. return errScanStructValue
  416. }
  417. d = d.Elem()
  418. if d.Kind() != reflect.Struct {
  419. return errScanStructValue
  420. }
  421. ss := structSpecForType(d.Type())
  422. if len(src)%2 != 0 {
  423. return errors.New("redigo.ScanStruct: number of values not a multiple of 2")
  424. }
  425. for i := 0; i < len(src); i += 2 {
  426. s := src[i+1]
  427. if s == nil {
  428. continue
  429. }
  430. name, ok := src[i].([]byte)
  431. if !ok {
  432. return fmt.Errorf("redigo.ScanStruct: key %d not a bulk string value", i)
  433. }
  434. fs := ss.fieldSpec(name)
  435. if fs == nil {
  436. continue
  437. }
  438. if err := convertAssignValue(d.FieldByIndex(fs.index), s); err != nil {
  439. return fmt.Errorf("redigo.ScanStruct: cannot assign field %s: %v", fs.name, err)
  440. }
  441. }
  442. return nil
  443. }
  444. var (
  445. errScanSliceValue = errors.New("redigo.ScanSlice: dest must be non-nil pointer to a struct")
  446. )
  447. // ScanSlice scans src to the slice pointed to by dest. The elements the dest
  448. // slice must be integer, float, boolean, string, struct or pointer to struct
  449. // values.
  450. //
  451. // Struct fields must be integer, float, boolean or string values. All struct
  452. // fields are used unless a subset is specified using fieldNames.
  453. func ScanSlice(src []interface{}, dest interface{}, fieldNames ...string) error {
  454. d := reflect.ValueOf(dest)
  455. if d.Kind() != reflect.Ptr || d.IsNil() {
  456. return errScanSliceValue
  457. }
  458. d = d.Elem()
  459. if d.Kind() != reflect.Slice {
  460. return errScanSliceValue
  461. }
  462. isPtr := false
  463. t := d.Type().Elem()
  464. if t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct {
  465. isPtr = true
  466. t = t.Elem()
  467. }
  468. if t.Kind() != reflect.Struct {
  469. ensureLen(d, len(src))
  470. for i, s := range src {
  471. if s == nil {
  472. continue
  473. }
  474. if err := convertAssignValue(d.Index(i), s); err != nil {
  475. return fmt.Errorf("redigo.ScanSlice: cannot assign element %d: %v", i, err)
  476. }
  477. }
  478. return nil
  479. }
  480. ss := structSpecForType(t)
  481. fss := ss.l
  482. if len(fieldNames) > 0 {
  483. fss = make([]*fieldSpec, len(fieldNames))
  484. for i, name := range fieldNames {
  485. fss[i] = ss.m[name]
  486. if fss[i] == nil {
  487. return fmt.Errorf("redigo.ScanSlice: ScanSlice bad field name %s", name)
  488. }
  489. }
  490. }
  491. if len(fss) == 0 {
  492. return errors.New("redigo.ScanSlice: no struct fields")
  493. }
  494. n := len(src) / len(fss)
  495. if n*len(fss) != len(src) {
  496. return errors.New("redigo.ScanSlice: length not a multiple of struct field count")
  497. }
  498. ensureLen(d, n)
  499. for i := 0; i < n; i++ {
  500. d := d.Index(i)
  501. if isPtr {
  502. if d.IsNil() {
  503. d.Set(reflect.New(t))
  504. }
  505. d = d.Elem()
  506. }
  507. for j, fs := range fss {
  508. s := src[i*len(fss)+j]
  509. if s == nil {
  510. continue
  511. }
  512. if err := convertAssignValue(d.FieldByIndex(fs.index), s); err != nil {
  513. return fmt.Errorf("redigo.ScanSlice: cannot assign element %d to field %s: %v", i*len(fss)+j, fs.name, err)
  514. }
  515. }
  516. }
  517. return nil
  518. }
  519. // Args is a helper for constructing command arguments from structured values.
  520. type Args []interface{}
  521. // Add returns the result of appending value to args.
  522. func (args Args) Add(value ...interface{}) Args {
  523. return append(args, value...)
  524. }
  525. // AddFlat returns the result of appending the flattened value of v to args.
  526. //
  527. // Maps are flattened by appending the alternating keys and map values to args.
  528. //
  529. // Slices are flattened by appending the slice elements to args.
  530. //
  531. // Structs are flattened by appending the alternating names and values of
  532. // exported fields to args. If v is a nil struct pointer, then nothing is
  533. // appended. The 'redis' field tag overrides struct field names. See ScanStruct
  534. // for more information on the use of the 'redis' field tag.
  535. //
  536. // Other types are appended to args as is.
  537. func (args Args) AddFlat(v interface{}) Args {
  538. rv := reflect.ValueOf(v)
  539. switch rv.Kind() {
  540. case reflect.Struct:
  541. args = flattenStruct(args, rv)
  542. case reflect.Slice:
  543. for i := 0; i < rv.Len(); i++ {
  544. args = append(args, rv.Index(i).Interface())
  545. }
  546. case reflect.Map:
  547. for _, k := range rv.MapKeys() {
  548. args = append(args, k.Interface(), rv.MapIndex(k).Interface())
  549. }
  550. case reflect.Ptr:
  551. if rv.Type().Elem().Kind() == reflect.Struct {
  552. if !rv.IsNil() {
  553. args = flattenStruct(args, rv.Elem())
  554. }
  555. } else {
  556. args = append(args, v)
  557. }
  558. default:
  559. args = append(args, v)
  560. }
  561. return args
  562. }
  563. func flattenStruct(args Args, v reflect.Value) Args {
  564. ss := structSpecForType(v.Type())
  565. for _, fs := range ss.l {
  566. fv := v.FieldByIndex(fs.index)
  567. if fs.omitEmpty {
  568. var empty = false
  569. switch fv.Kind() {
  570. case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
  571. empty = fv.Len() == 0
  572. case reflect.Bool:
  573. empty = !fv.Bool()
  574. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  575. empty = fv.Int() == 0
  576. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  577. empty = fv.Uint() == 0
  578. case reflect.Float32, reflect.Float64:
  579. empty = fv.Float() == 0
  580. case reflect.Interface, reflect.Ptr:
  581. empty = fv.IsNil()
  582. }
  583. if empty {
  584. continue
  585. }
  586. }
  587. args = append(args, fs.name, fv.Interface())
  588. }
  589. return args
  590. }