scan.go 12 KB

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