scan.go 15 KB

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