scan.go 12 KB

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