scan.go 13 KB

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