Beispiel #1
0
// Search all entities in the database
func (d *Default) Search(results interface{}, filter interface{}, sortParams *api.SortParameters, pagination *api.Pagination) error {
	term := r.Table(d.table)

	// Filter
	if filter != nil {
		term = term.Filter(filter)
	}

	// Get total
	if pagination != nil {
		total, err := d.WhereCount(filter)
		if err != nil {
			return api.NewDatabaseError(d, err, "")
		}
		pagination.SetTotal(uint(total))
	}

	// Sort
	if sortParams != nil {
		term = term.OrderBy(ConvertSortParameters(*sortParams)...)
	}

	// Slice result
	if pagination != nil {
		term = term.Slice(pagination.Offset(), pagination.Offset()+pagination.PerPage)
	}

	// Run the query
	cursor, err := term.Run(d.session)
	if err != nil {
		return api.NewDatabaseError(d, err, "")
	}

	// Fetch cursor
	err = cursor.All(results)
	if err != nil {
		if err == r.ErrEmptyResult {
			return api.ErrNoResult
		}
		return err
	}

	return nil
}
Beispiel #2
0
// Search all entities from the database
func (d *Default) Search(results interface{}, filter interface{}, sortParams *api.SortParameters, pagination *api.Pagination) error {
	session := d.session.Clone()
	defer session.Close()

	// Apply Filter
	if filter == nil {
		filter = bson.M{}
	}

	// Get total
	if pagination != nil {
		total, err := d.WhereCount(filter)
		if err != nil {
			return api.NewDatabaseError(d, err, "")
		}
		pagination.SetTotal(uint(total))
	}

	// Prepare the query
	query := session.DB(d.GetDBName()).C(d.GetTableName()).Find(filter)

	// Apply sorts
	if sortParams != nil {
		sort := ConvertSortParameters(*sortParams)
		if len(sort) > 0 {
			query = query.Sort(sort...)
		}
	}

	// Paginate
	if pagination != nil {
		query = query.Limit(int(pagination.PerPage)).Skip(int(pagination.Offset()))
	}

	err := query.All(results)
	if err != nil {
		return api.NewDatabaseError(d, err, "")
	}

	return err
}