// getWorkItemsByFilterExpression retrieves Work Items, children and parents for a given expression and parameters
3597
func getWorkItemsByFilterExpression(ctx context.Context, db application.DB, filterExpression string, filterParentexists *bool, offset *int, limit *int) ([]workitem.WorkItem, link.WorkItemLinkList, link.AncestorList, error) {
	var result []workitem.WorkItem
	var childLinks link.WorkItemLinkList
	var parents link.AncestorList
	err := application.Transactional(db, func(appl application.Application) error {
		var err error
		// add tree option to query if not already present
		var reqMap map[string]interface{}
		err = json.Unmarshal([]byte(filterExpression), &reqMap)
		if err != nil {
			return errs.Errorf("error unmarshalling query expression for CSV filtering: %s", filterExpression)
		}
		if _, ok := reqMap["$OPTS"]; !ok {
			reqMap["$OPTS"] = make(map[string]interface{})
		}
		// Set "tree-view" to true. We always want tree-view to be enabled
		(reqMap["$OPTS"].(map[string]interface{}))["tree-view"] = true
		updatedFilterExpression, err := json.Marshal(reqMap)
		if err != nil {
			return errs.Errorf("error adding tree opt to query expression for CSV filtering: %s", filterExpression)
		}
		// execute query
		result, _, parents, childLinks, err = appl.SearchItems().Filter(ctx, string(updatedFilterExpression), filterParentexists, offset, limit)
		if err != nil {
			log.Error(ctx, map[string]interface{}{
				"err":               err,
				"filter_expression": filterExpression,
			}, "unable to list the work items")
			return errs.Wrapf(err, "error executing filter expression for CSV filtering: %s", filterExpression)
		}
		return nil
	})
	return result, childLinks, parents, err
}
467228
func (api *API) ValidateFilterExpression(expression string) error {
	uri := fmt.Sprintf("/filters/validate-expr")
	expressionPayload := FilterValidateExpression{Expression: expression}

	_, err := api.makeRequest("POST", uri, expressionPayload)
	if err != nil {
		var filterValidationResponse FilterValidateExpressionResponse

		jsonErr := json.Unmarshal([]byte(err.Error()), &filterValidationResponse)
		if jsonErr != nil {
			return errors.Wrap(jsonErr, errUnmarshalError)
		}

		if filterValidationResponse.Success != true {
			// Unsure why but the API returns `errors` as an array but it only
			// ever shows the issue with one problem at a time ¯\_(ツ)_/¯
			return errors.Errorf(filterValidationResponse.Errors[0].Message)
		}
	}

	return nil
}
1308125
func (s *FieldSort) NestedFilter(nestedFilter Query) *FieldSort {
	s.filter = nestedFilter
	return s
}
451037
func (r *GormWorkItemTypeRepository) loadChildTypeList(ctx context.Context, parentTypeID uuid.UUID) ([]uuid.UUID, error) {
	types := []ChildType{}
	db := r.db.Model(&types).Where("parent_work_item_type_id=?", parentTypeID).Order("position ASC").Find(&types)
	if db.RecordNotFound() {
		log.Error(ctx, map[string]interface{}{"wit_id": parentTypeID}, "work item type child types not found")
		return nil, errors.NewNotFoundError("work item type child types", parentTypeID.String())
	}
	if err := db.Error; err != nil {
		return nil, errors.NewInternalError(ctx, err)
	}
	res := make([]uuid.UUID, len(types))
	for i, childType := range types {
		res[i] = childType.ChildWorkItemTypeID
	}
	return res, nil
}
698143
func (s *Selection) ParentFiltered(selector string) *Selection {
	return filterAndPush(s, getParentNodes(s.Nodes), compileMatcher(selector))
}
280787
func (c *SearchController) enrichWorkItemList(ctx *app.ShowSearchContext, ancestors link.AncestorList, matchingIDs id.Slice, childLinks link.WorkItemLinkList, res *app.SearchWorkItemList, hasChildren WorkItemConvertFunc) error {
	parentIDs := id.Slice{}
	for _, wi := range res.Data {
		if wi.Relationships != nil && wi.Relationships.Parent != nil && wi.Relationships.Parent.Data != nil {
			parentIDs = append(parentIDs, wi.Relationships.Parent.Data.ID)
		}
	}

	// Also append the ancestors not already included in the parent list
	fetchInBatch := parentIDs
	fetchInBatch.Add(ancestors.GetDistinctAncestorIDs().Diff(parentIDs))

	// Append direct children of matching work items that have a child that is
	// also a match and are not yet in the list.
	nonMatchingChildItems := childLinks.GetDistinctListOfTargetIDs(link.SystemWorkItemLinkTypeParentChildID)
	fetchInBatch.Add(fetchInBatch.Diff(nonMatchingChildItems))

	// Eliminate work items already in the search
	fetchInBatch = fetchInBatch.Sub(matchingIDs)

	wis := []*workitem.WorkItem{}
	err := application.Transactional(c.db, func(appl application.Application) error {
		var err error
		wis, err = appl.WorkItems().LoadBatchByID(ctx, fetchInBatch)
		return err
	})
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"wis": wis,
			"err": err,
		}, "unable to load parent work items in batch: %s", fetchInBatch)
		return errs.Wrapf(err, "unable to load work item items in batch: %s", fetchInBatch)
	}

	for _, ele := range wis {
		wit, err := c.db.WorkItemTypes().Load(ctx.Context, ele.Type)
		if err != nil {
			return errs.Wrapf(err, "failed to load work item type: %s", ele.Type)
		}
		convertedWI, err := ConvertWorkItem(ctx.Request, *wit, *ele, hasChildren, includeParentWorkItem(ctx, ancestors, childLinks))
		if err != nil {
			return errs.WithStack(err)
		}
		res.Included = append(res.Included, *convertedWI)
	}
	return nil
}
500378
func (a *Client) GetWorkflowsLibraryInjectableName(params *GetWorkflowsLibraryInjectableNameParams, authInfo runtime.ClientAuthInfoWriter) (*GetWorkflowsLibraryInjectableNameOK, error) {
	// TODO: Validate the params before sending
	if params == nil {
		params = NewGetWorkflowsLibraryInjectableNameParams()
	}

	result, err := a.transport.Submit(&runtime.ClientOperation{
		ID:                 "GetWorkflowsLibraryInjectableName",
		Method:             "GET",
		PathPattern:        "/workflows/library/{injectableName}",
		ProducesMediaTypes: []string{"application/json", "application/x-gzip"},
		ConsumesMediaTypes: []string{"application/json"},
		Schemes:            []string{"http", "https"},
		Params:             params,
		Reader:             &GetWorkflowsLibraryInjectableNameReader{formats: a.formats},
		AuthInfo:           authInfo,
	})
	if err != nil {
		return nil, err
	}
	return result.(*GetWorkflowsLibraryInjectableNameOK), nil
}
753552
func (a *Client) GetWorkflowsTasks(params *GetWorkflowsTasksParams, authInfo runtime.ClientAuthInfoWriter) (*GetWorkflowsTasksOK, error) {
	// TODO: Validate the params before sending
	if params == nil {
		params = NewGetWorkflowsTasksParams()
	}

	result, err := a.transport.Submit(&runtime.ClientOperation{
		ID:                 "GetWorkflowsTasks",
		Method:             "GET",
		PathPattern:        "/workflows/tasks",
		ProducesMediaTypes: []string{"application/json", "application/x-gzip"},
		ConsumesMediaTypes: []string{"application/json"},
		Schemes:            []string{"http", "https"},
		Params:             params,
		Reader:             &GetWorkflowsTasksReader{formats: a.formats},
		AuthInfo:           authInfo,
	})
	if err != nil {
		return nil, err
	}
	return result.(*GetWorkflowsTasksOK), nil
}
776962
func (r *GormWorkItemLinkRepository) ListByWorkItem(ctx context.Context, wiID uuid.UUID) ([]WorkItemLink, error) {
	defer goa.MeasureSince([]string{"goa", "db", "workitemlink", "listByWorkItem"}, time.Now())
	var modelLinks []WorkItemLink
	wi, err := r.workItemRepo.LoadFromDB(ctx, wiID)
	if err != nil {
		return nil, errs.WithStack(err)
	}
	// Now fetch all links for that work item
	db := r.db.Model(modelLinks).Where("? IN (source_id, target_id)", wi.ID).Find(&modelLinks)
	if db.Error != nil {
		return nil, db.Error
	}
	return modelLinks, nil
}
141283
func (r *GormWorkItemRepository) LoadByIteration(ctx context.Context, iterationID uuid.UUID) ([]*WorkItem, error) {
	defer goa.MeasureSince([]string{"goa", "db", "workitem", "loadByIteration"}, time.Now())
	log.Info(nil, map[string]interface{}{
		"itr_id": iterationID,
	}, "Loading work items for iteration")

	res := []WorkItemStorage{}
	filter := fmt.Sprintf(`fields @> '{"%s":"%s"}'`, SystemIteration, iterationID)
	tx := r.db.Model(WorkItemStorage{}).Where(filter).Find(&res)
	if tx.Error != nil {
		return nil, errors.NewInternalError(ctx, tx.Error)
	}
	workitems := []*WorkItem{}
	for _, ele := range res {
		wiType, err := r.witr.Load(ctx, ele.Type)
		if err != nil {
			log.Error(nil, map[string]interface{}{
				"wit_id": ele.Type,
				"err":    err,
			}, "error in loading type from DB")
			return nil, errors.NewInternalError(ctx, err)
		}
		convertedWI, err := ConvertWorkItemStorageToModel(wiType, &ele)
		if err != nil {
			log.Error(nil, map[string]interface{}{
				"wi_id": ele.ID,
				"err":   err,
			}, "error in converting WI")
			return nil, errs.Wrap(err, "error when converting WI")
		}
		workitems = append(workitems, convertedWI)
	}
	return workitems, nil
}
258390
func getOperationsForItem(pathItem spec.PathItem) map[string]*spec.Operation {
	return map[string]*spec.Operation{
		"GET":    pathItem.Get,
		"DELETE": pathItem.Delete,
		"PATCH":  pathItem.Patch,
		"PUT":    pathItem.Put,
		"POST":   pathItem.Post,
		"HEAD":   pathItem.Head,
	}
}
356074
func zeroWorkItem(data []byte, workItemSize int) bool {
	if len(data)%workItemSize != 0 {
		data = data[:len(data)-(len(data)%workItemSize)]
	}
	dataLen := len(data)
	for i := 0; i < dataLen; i += workItemSize {
		j := 0
		for j < workItemSize && data[i+j] == 0 {
			j++
		}
		if j == workItemSize {
			return true
		}
	}
	return false
}
845718
func (s *SortGeoDistance) filterTermsByType(terms []string) []string {
	var termsWithShiftZero []string
	for _, term := range terms {
		valid, shift := numeric.ValidPrefixCodedTerm(term)
		if valid && shift == 0 {
			termsWithShiftZero = append(termsWithShiftZero, term)
		}
	}
	return termsWithShiftZero
}
837553
func ExtractTagFilters(opts ...interface{}) *opt.TagFiltersOption {
	for _, o := range opts {
		if v, ok := o.(*opt.TagFiltersOption); ok {
			return v
		}
	}
	return nil
}
1150501
func (s ReleaseImageSpec) selectWorkloads(rc ReleaseContext, results Result) ([]*WorkloadUpdate, error) {
	// Build list of filters
	prefilters, postfilters, err := s.filters(rc)
	if err != nil {
		return nil, err
	}
	// Find and filter workloads
	return rc.SelectWorkloads(results, prefilters, postfilters)
}
1201077
func (pattern *Pattern) GetFilter() Filter {
	ret := Filter(C.cairo_pattern_get_filter(pattern.Ptr))
	if err := pattern.status(); err != nil {
		panic(err)
	}
	return ret
}
868619
func ConvertWorkItems(request *http.Request, wits []workitem.WorkItemType, wis []workitem.WorkItem, additional ...WorkItemConvertFunc) ([]*app.WorkItem, error) {
	ops := []*app.WorkItem{}
	if len(wits) != len(wis) {
		return nil, errs.Errorf("length mismatch of work items (%d) and work item types (%d)", len(wis), len(wits))
	}
	for i := 0; i < len(wis); i++ {
		wi, err := ConvertWorkItem(request, wits[i], wis[i], additional...)
		if err != nil {
			return nil, errs.Wrapf(err, "failed to convert work item: %s", wis[i].ID)
		}
		ops = append(ops, wi)
	}
	return ops, nil
}