scan.go 15 KB

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