scan.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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 string:
  178. switch d := d.(type) {
  179. case *string:
  180. *d = s
  181. case *interface{}:
  182. *d = s
  183. case nil:
  184. // skip value
  185. default:
  186. err = cannotConvert(reflect.ValueOf(d), s)
  187. }
  188. case []interface{}:
  189. switch d := d.(type) {
  190. case *[]interface{}:
  191. *d = s
  192. case *interface{}:
  193. *d = s
  194. case nil:
  195. // skip value
  196. default:
  197. if d := reflect.ValueOf(d); d.Type().Kind() != reflect.Ptr {
  198. err = cannotConvert(d, s)
  199. } else {
  200. err = convertAssignArray(d.Elem(), s)
  201. }
  202. }
  203. case Error:
  204. err = s
  205. default:
  206. err = cannotConvert(reflect.ValueOf(d), s)
  207. }
  208. return
  209. }
  210. // Scan copies from src to the values pointed at by dest.
  211. //
  212. // The values pointed at by dest must be an integer, float, boolean, string,
  213. // []byte, interface{} or slices of these types. Scan uses the standard strconv
  214. // package to convert bulk strings to numeric and boolean types.
  215. //
  216. // If a dest value is nil, then the corresponding src value is skipped.
  217. //
  218. // If a src element is nil, then the corresponding dest value is not modified.
  219. //
  220. // To enable easy use of Scan in a loop, Scan returns the slice of src
  221. // following the copied values.
  222. func Scan(src []interface{}, dest ...interface{}) ([]interface{}, error) {
  223. if len(src) < len(dest) {
  224. return nil, errors.New("redigo.Scan: array short")
  225. }
  226. var err error
  227. for i, d := range dest {
  228. err = convertAssign(d, src[i])
  229. if err != nil {
  230. err = fmt.Errorf("redigo.Scan: cannot assign to dest %d: %v", i, err)
  231. break
  232. }
  233. }
  234. return src[len(dest):], err
  235. }
  236. type fieldSpec struct {
  237. name string
  238. index []int
  239. omitEmpty bool
  240. }
  241. type structSpec struct {
  242. m map[string]*fieldSpec
  243. l []*fieldSpec
  244. }
  245. func (ss *structSpec) fieldSpec(name []byte) *fieldSpec {
  246. return ss.m[string(name)]
  247. }
  248. func compileStructSpec(t reflect.Type, depth map[string]int, index []int, ss *structSpec) {
  249. for i := 0; i < t.NumField(); i++ {
  250. f := t.Field(i)
  251. switch {
  252. case f.PkgPath != "" && !f.Anonymous:
  253. // Ignore unexported fields.
  254. case f.Anonymous:
  255. // TODO: Handle pointers. Requires change to decoder and
  256. // protection against infinite recursion.
  257. if f.Type.Kind() == reflect.Struct {
  258. compileStructSpec(f.Type, depth, append(index, i), ss)
  259. }
  260. default:
  261. fs := &fieldSpec{name: f.Name}
  262. tag := f.Tag.Get("redis")
  263. p := strings.Split(tag, ",")
  264. if len(p) > 0 {
  265. if p[0] == "-" {
  266. continue
  267. }
  268. if len(p[0]) > 0 {
  269. fs.name = p[0]
  270. }
  271. for _, s := range p[1:] {
  272. switch s {
  273. case "omitempty":
  274. fs.omitEmpty = true
  275. default:
  276. panic(fmt.Errorf("redigo: unknown field tag %s for type %s", s, t.Name()))
  277. }
  278. }
  279. }
  280. d, found := depth[fs.name]
  281. if !found {
  282. d = 1 << 30
  283. }
  284. switch {
  285. case len(index) == d:
  286. // At same depth, remove from result.
  287. delete(ss.m, fs.name)
  288. j := 0
  289. for i := 0; i < len(ss.l); i++ {
  290. if fs.name != ss.l[i].name {
  291. ss.l[j] = ss.l[i]
  292. j += 1
  293. }
  294. }
  295. ss.l = ss.l[:j]
  296. case len(index) < d:
  297. fs.index = make([]int, len(index)+1)
  298. copy(fs.index, index)
  299. fs.index[len(index)] = i
  300. depth[fs.name] = len(index)
  301. ss.m[fs.name] = fs
  302. ss.l = append(ss.l, fs)
  303. }
  304. }
  305. }
  306. }
  307. var (
  308. structSpecMutex sync.RWMutex
  309. structSpecCache = make(map[reflect.Type]*structSpec)
  310. defaultFieldSpec = &fieldSpec{}
  311. )
  312. func structSpecForType(t reflect.Type) *structSpec {
  313. structSpecMutex.RLock()
  314. ss, found := structSpecCache[t]
  315. structSpecMutex.RUnlock()
  316. if found {
  317. return ss
  318. }
  319. structSpecMutex.Lock()
  320. defer structSpecMutex.Unlock()
  321. ss, found = structSpecCache[t]
  322. if found {
  323. return ss
  324. }
  325. ss = &structSpec{m: make(map[string]*fieldSpec)}
  326. compileStructSpec(t, make(map[string]int), nil, ss)
  327. structSpecCache[t] = ss
  328. return ss
  329. }
  330. var errScanStructValue = errors.New("redigo.ScanStruct: value must be non-nil pointer to a struct")
  331. // ScanStruct scans alternating names and values from src to a struct. The
  332. // HGETALL and CONFIG GET commands return replies in this format.
  333. //
  334. // ScanStruct uses exported field names to match values in the response. Use
  335. // 'redis' field tag to override the name:
  336. //
  337. // Field int `redis:"myName"`
  338. //
  339. // Fields with the tag redis:"-" are ignored.
  340. //
  341. // Integer, float, boolean, string and []byte fields are supported. Scan uses the
  342. // standard strconv package to convert bulk string values to numeric and
  343. // boolean types.
  344. //
  345. // If a src element is nil, then the corresponding field is not modified.
  346. func ScanStruct(src []interface{}, dest interface{}) error {
  347. d := reflect.ValueOf(dest)
  348. if d.Kind() != reflect.Ptr || d.IsNil() {
  349. return errScanStructValue
  350. }
  351. d = d.Elem()
  352. if d.Kind() != reflect.Struct {
  353. return errScanStructValue
  354. }
  355. ss := structSpecForType(d.Type())
  356. if len(src)%2 != 0 {
  357. return errors.New("redigo.ScanStruct: number of values not a multiple of 2")
  358. }
  359. for i := 0; i < len(src); i += 2 {
  360. s := src[i+1]
  361. if s == nil {
  362. continue
  363. }
  364. name, ok := src[i].([]byte)
  365. if !ok {
  366. return fmt.Errorf("redigo.ScanStruct: key %d not a bulk string value", i)
  367. }
  368. fs := ss.fieldSpec(name)
  369. if fs == nil {
  370. continue
  371. }
  372. if err := convertAssignValue(d.FieldByIndex(fs.index), s); err != nil {
  373. return fmt.Errorf("redigo.ScanStruct: cannot assign field %s: %v", fs.name, err)
  374. }
  375. }
  376. return nil
  377. }
  378. var (
  379. errScanSliceValue = errors.New("redigo.ScanSlice: dest must be non-nil pointer to a struct")
  380. )
  381. // ScanSlice scans src to the slice pointed to by dest. The elements the dest
  382. // slice must be integer, float, boolean, string, struct or pointer to struct
  383. // values.
  384. //
  385. // Struct fields must be integer, float, boolean or string values. All struct
  386. // fields are used unless a subset is specified using fieldNames.
  387. func ScanSlice(src []interface{}, dest interface{}, fieldNames ...string) error {
  388. d := reflect.ValueOf(dest)
  389. if d.Kind() != reflect.Ptr || d.IsNil() {
  390. return errScanSliceValue
  391. }
  392. d = d.Elem()
  393. if d.Kind() != reflect.Slice {
  394. return errScanSliceValue
  395. }
  396. isPtr := false
  397. t := d.Type().Elem()
  398. if t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct {
  399. isPtr = true
  400. t = t.Elem()
  401. }
  402. if t.Kind() != reflect.Struct {
  403. ensureLen(d, len(src))
  404. for i, s := range src {
  405. if s == nil {
  406. continue
  407. }
  408. if err := convertAssignValue(d.Index(i), s); err != nil {
  409. return fmt.Errorf("redigo.ScanSlice: cannot assign element %d: %v", i, err)
  410. }
  411. }
  412. return nil
  413. }
  414. ss := structSpecForType(t)
  415. fss := ss.l
  416. if len(fieldNames) > 0 {
  417. fss = make([]*fieldSpec, len(fieldNames))
  418. for i, name := range fieldNames {
  419. fss[i] = ss.m[name]
  420. if fss[i] == nil {
  421. return fmt.Errorf("redigo.ScanSlice: ScanSlice bad field name %s", name)
  422. }
  423. }
  424. }
  425. if len(fss) == 0 {
  426. return errors.New("redigo.ScanSlice: no struct fields")
  427. }
  428. n := len(src) / len(fss)
  429. if n*len(fss) != len(src) {
  430. return errors.New("redigo.ScanSlice: length not a multiple of struct field count")
  431. }
  432. ensureLen(d, n)
  433. for i := 0; i < n; i++ {
  434. d := d.Index(i)
  435. if isPtr {
  436. if d.IsNil() {
  437. d.Set(reflect.New(t))
  438. }
  439. d = d.Elem()
  440. }
  441. for j, fs := range fss {
  442. s := src[i*len(fss)+j]
  443. if s == nil {
  444. continue
  445. }
  446. if err := convertAssignValue(d.FieldByIndex(fs.index), s); err != nil {
  447. return fmt.Errorf("redigo.ScanSlice: cannot assign element %d to field %s: %v", i*len(fss)+j, fs.name, err)
  448. }
  449. }
  450. }
  451. return nil
  452. }
  453. // Args is a helper for constructing command arguments from structured values.
  454. type Args []interface{}
  455. // Add returns the result of appending value to args.
  456. func (args Args) Add(value ...interface{}) Args {
  457. return append(args, value...)
  458. }
  459. // AddFlat returns the result of appending the flattened value of v to args.
  460. //
  461. // Maps are flattened by appending the alternating keys and map values to args.
  462. //
  463. // Slices are flattened by appending the slice elements to args.
  464. //
  465. // Structs are flattened by appending the alternating names and values of
  466. // exported fields to args. If v is a nil struct pointer, then nothing is
  467. // appended. The 'redis' field tag overrides struct field names. See ScanStruct
  468. // for more information on the use of the 'redis' field tag.
  469. //
  470. // Other types are appended to args as is.
  471. func (args Args) AddFlat(v interface{}) Args {
  472. rv := reflect.ValueOf(v)
  473. switch rv.Kind() {
  474. case reflect.Struct:
  475. args = flattenStruct(args, rv)
  476. case reflect.Slice:
  477. for i := 0; i < rv.Len(); i++ {
  478. args = append(args, rv.Index(i).Interface())
  479. }
  480. case reflect.Map:
  481. for _, k := range rv.MapKeys() {
  482. args = append(args, k.Interface(), rv.MapIndex(k).Interface())
  483. }
  484. case reflect.Ptr:
  485. if rv.Type().Elem().Kind() == reflect.Struct {
  486. if !rv.IsNil() {
  487. args = flattenStruct(args, rv.Elem())
  488. }
  489. } else {
  490. args = append(args, v)
  491. }
  492. default:
  493. args = append(args, v)
  494. }
  495. return args
  496. }
  497. func flattenStruct(args Args, v reflect.Value) Args {
  498. ss := structSpecForType(v.Type())
  499. for _, fs := range ss.l {
  500. fv := v.FieldByIndex(fs.index)
  501. if fs.omitEmpty {
  502. var empty = false
  503. switch fv.Kind() {
  504. case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
  505. empty = fv.Len() == 0
  506. case reflect.Bool:
  507. empty = !fv.Bool()
  508. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  509. empty = fv.Int() == 0
  510. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  511. empty = fv.Uint() == 0
  512. case reflect.Float32, reflect.Float64:
  513. empty = fv.Float() == 0
  514. case reflect.Interface, reflect.Ptr:
  515. empty = fv.IsNil()
  516. }
  517. if empty {
  518. continue
  519. }
  520. }
  521. args = append(args, fs.name, fv.Interface())
  522. }
  523. return args
  524. }