Ejemplo n.º 1
0
func QueryForPage(
	query *db.Query,
	criteria Criteria,
	target interface{},
	transformer func(in interface{}) interface{},
) (Page, error) {
	max := criteria.PageSize
	first := (criteria.Page - 1) * max
	// for the first page the offset is zero
	query.Skip(first)
	if max > 0 {
		query.Limit(max + 1)
	}

	var entities coll.Collection
	var err error
	var results []interface{}

	if reflect.TypeOf(target).Kind() == reflect.Func {
		results, err = query.ListInto(target)
	} else if _, ok := target.(tk.Hasher); ok {
		entities, err = query.ListFlatTreeOf(target)
	} else {
		entities, err = query.ListOf(target)
	}
	if err != nil {
		return Page{}, err
	}

	if results == nil {
		results = entities.Elements()
	}

	page := Page{}
	size := int64(len(results))
	if max > 0 && size > max {
		page.Last = false
		page.Results = results[:max]
	} else {
		page.Last = true
		page.Results = results
	}

	// transform results
	if transformer != nil {
		for k, v := range page.Results {
			page.Results[k] = transformer(v)
		}
	}

	// count records
	if criteria.CountRecords {
		DB := query.GetDb()
		cnt := DB.Query(query.GetTable())
		cnt.Copy(query)
		cnt.ColumnsReset()
		cnt.CountAll()
		cnt.OrdersReset()
		var recs int64
		_, err = cnt.SelectInto(&recs)
		if err != nil {
			return Page{}, err
		}
		page.Count = Int64(recs)
	}

	return page, nil
}