session_iterate.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Copyright 2016 The Xorm Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package xorm
  5. import "reflect"
  6. // IterFunc only use by Iterate
  7. type IterFunc func(idx int, bean interface{}) error
  8. // Rows return sql.Rows compatible Rows obj, as a forward Iterator object for iterating record by record, bean's non-empty fields
  9. // are conditions.
  10. func (session *Session) Rows(bean interface{}) (*Rows, error) {
  11. return newRows(session, bean)
  12. }
  13. // Iterate record by record handle records from table, condiBeans's non-empty fields
  14. // are conditions. beans could be []Struct, []*Struct, map[int64]Struct
  15. // map[int64]*Struct
  16. func (session *Session) Iterate(bean interface{}, fun IterFunc) error {
  17. rows, err := session.Rows(bean)
  18. if err != nil {
  19. return err
  20. }
  21. defer rows.Close()
  22. i := 0
  23. for rows.Next() {
  24. b := reflect.New(rows.beanType).Interface()
  25. err = rows.Scan(b)
  26. if err != nil {
  27. return err
  28. }
  29. err = fun(i, b)
  30. if err != nil {
  31. return err
  32. }
  33. i++
  34. }
  35. return err
  36. }