// SelectPlanFromPbBytes Create a sql plan from pb.
175828
func SelectPlanFromPbBytes(pb []byte, loader SchemaLoader) (*Select, error) {
	p := &PlanPb{}
	if err := proto.Unmarshal(pb, p); err != nil {
		u.Errorf("error reading protobuf select: %v  \n%s", err, pb)
		return nil, err
	}
	switch {
	case p.Select != nil:
		return SelectFromPB(p, loader)
	}
	return nil, ErrNotImplemented
}
1012390
func getPlanFromPath(path string) (*plans.Plan, error) {
	pr, err := planfile.Open(path)
	if err != nil {
		return nil, err
	}
	plan, err := pr.ReadPlan()
	if err != nil {
		return nil, err
	}
	return plan, nil
}
995115
func selectBuilderContainer(containers []corev1.Container) string {
	for _, c := range containers {
		for _, bcName := range buildstrategy.BuildContainerNames {
			if c.Name == bcName {
				return bcName
			}
		}
	}
	return ""
}
1289342
func SelectTaskFromTaskPb(pb *PlanPb, ctx *Context, sel *rel.SqlSelect) (Task, error) {
	switch {
	case pb.Source != nil:
		return SourceFromPB(pb, ctx)
	case pb.Where != nil:
		return WhereFromPB(pb), nil
	case pb.Having != nil:
		return HavingFromPB(pb), nil
	case pb.GroupBy != nil:
		return GroupByFromPB(pb), nil
	case pb.Order != nil:
		return OrderFromPB(pb), nil
	case pb.Projection != nil:
		return ProjectionFromPB(pb, sel), nil
	case pb.JoinMerge != nil:
		u.Warnf("JoinMerge not implemented: %T", pb)
	case pb.JoinKey != nil:
		u.Warnf("JoinKey not implemented: %T", pb)
	default:
		u.Warnf("not implemented: %#v", pb)
	}
	return nil, ErrNotImplemented
}
860537
func (b *Builder) SelectAllParam(selectAll bool) *Builder {
	if selectAll && (b.labelSelector != nil || b.fieldSelector != nil) {
		b.errs = append(b.errs, fmt.Errorf("setting 'all' parameter but found a non empty selector. "))
		return b
	}
	b.selectAll = selectAll
	return b
}
140561
func (b *PlanBuilder) coalesceCommonColumns(p *LogicalJoin, leftPlan, rightPlan LogicalPlan, rightJoin bool, filter map[string]bool) error {
	lsc := leftPlan.Schema().Clone()
	rsc := rightPlan.Schema().Clone()
	lColumns, rColumns := lsc.Columns, rsc.Columns
	if rightJoin {
		lColumns, rColumns = rsc.Columns, lsc.Columns
	}

	// Find out all the common columns and put them ahead.
	commonLen := 0
	for i, lCol := range lColumns {
		for j := commonLen; j < len(rColumns); j++ {
			if lCol.ColName.L != rColumns[j].ColName.L {
				continue
			}

			if len(filter) > 0 {
				if !filter[lCol.ColName.L] {
					break
				}
				// Mark this column exist.
				filter[lCol.ColName.L] = false
			}

			col := lColumns[i]
			copy(lColumns[commonLen+1:i+1], lColumns[commonLen:i])
			lColumns[commonLen] = col

			col = rColumns[j]
			copy(rColumns[commonLen+1:j+1], rColumns[commonLen:j])
			rColumns[commonLen] = col

			commonLen++
			break
		}
	}

	if len(filter) > 0 && len(filter) != commonLen {
		for col, notExist := range filter {
			if notExist {
				return ErrUnknownColumn.GenWithStackByArgs(col, "from clause")
			}
		}
	}

	schemaCols := make([]*expression.Column, len(lColumns)+len(rColumns)-commonLen)
	copy(schemaCols[:len(lColumns)], lColumns)
	copy(schemaCols[len(lColumns):], rColumns[commonLen:])

	conds := make([]expression.Expression, 0, commonLen)
	for i := 0; i < commonLen; i++ {
		lc, rc := lsc.Columns[i], rsc.Columns[i]
		cond, err := expression.NewFunction(b.ctx, ast.EQ, types.NewFieldType(mysql.TypeTiny), lc, rc)
		if err != nil {
			return err
		}
		conds = append(conds, cond)
	}

	p.SetSchema(expression.NewSchema(schemaCols...))
	p.redundantSchema = expression.MergeSchema(p.redundantSchema, expression.NewSchema(rColumns[:commonLen]...))
	p.OtherConditions = append(conds, p.OtherConditions...)

	return nil
}
904640
func (b *PlanBuilder) buildProjectionForWindow(p LogicalPlan, expr *ast.WindowFuncExpr, aggMap map[*ast.AggregateFuncExpr]int) (LogicalPlan, []property.Item, []property.Item, []expression.Expression, error) {
	b.optFlag |= flagEliminateProjection

	var items []*ast.ByItem
	if expr.Spec.Name.L != "" {
		ref, ok := b.windowSpecs[expr.Spec.Name.L]
		if !ok {
			return nil, nil, nil, nil, ErrWindowNoSuchWindow.GenWithStackByArgs(expr.Spec.Name.O)
		}
		expr.Spec = ref
	}
	spec := expr.Spec
	if spec.Ref.L != "" {
		ref, ok := b.windowSpecs[spec.Ref.L]
		if !ok {
			return nil, nil, nil, nil, ErrWindowNoSuchWindow.GenWithStackByArgs(spec.Ref.O)
		}
		err := mergeWindowSpec(&spec, &ref)
		if err != nil {
			return nil, nil, nil, nil, err
		}
	}

	lenPartition := 0
	if spec.PartitionBy != nil {
		items = append(items, spec.PartitionBy.Items...)
		lenPartition = len(spec.PartitionBy.Items)
	}
	if spec.OrderBy != nil {
		items = append(items, spec.OrderBy.Items...)
	}
	projLen := len(p.Schema().Columns) + len(items) + len(expr.Args)
	proj := LogicalProjection{Exprs: make([]expression.Expression, 0, projLen)}.Init(b.ctx)
	schema := expression.NewSchema(make([]*expression.Column, 0, projLen)...)
	for _, col := range p.Schema().Columns {
		proj.Exprs = append(proj.Exprs, col)
		schema.Append(col)
	}

	transformer := &itemTransformer{}
	propertyItems := make([]property.Item, 0, len(items))
	for _, item := range items {
		newExpr, _ := item.Expr.Accept(transformer)
		item.Expr = newExpr.(ast.ExprNode)
		it, np, err := b.rewrite(item.Expr, p, aggMap, true)
		if err != nil {
			return nil, nil, nil, nil, err
		}
		p = np
		if col, ok := it.(*expression.Column); ok {
			propertyItems = append(propertyItems, property.Item{Col: col, Desc: item.Desc})
			continue
		}
		proj.Exprs = append(proj.Exprs, it)
		col := &expression.Column{
			ColName:  model.NewCIStr(fmt.Sprintf("%d_proj_window_%d", p.ID(), schema.Len())),
			UniqueID: b.ctx.GetSessionVars().AllocPlanColumnID(),
			RetType:  it.GetType(),
		}
		schema.Append(col)
		propertyItems = append(propertyItems, property.Item{Col: col, Desc: item.Desc})
	}

	newArgList := make([]expression.Expression, 0, len(expr.Args))
	for _, arg := range expr.Args {
		newArg, np, err := b.rewrite(arg, p, aggMap, true)
		if err != nil {
			return nil, nil, nil, nil, err
		}
		p = np
		switch newArg.(type) {
		case *expression.Column, *expression.Constant:
			newArgList = append(newArgList, newArg)
			continue
		}
		proj.Exprs = append(proj.Exprs, newArg)
		col := &expression.Column{
			ColName:  model.NewCIStr(fmt.Sprintf("%d_proj_window_%d", p.ID(), schema.Len())),
			UniqueID: b.ctx.GetSessionVars().AllocPlanColumnID(),
			RetType:  newArg.GetType(),
		}
		schema.Append(col)
		newArgList = append(newArgList, col)
	}

	proj.SetSchema(schema)
	proj.SetChildren(p)
	return proj, propertyItems[:lenPartition], propertyItems[lenPartition:], newArgList, nil
}
870259
func BuildSqlJobPlanned(planner plan.Planner, executor Executor, ctx *plan.Context) (Task, error) {

	//u.Debugf("build: %q", ctx.Raw)
	if ctx.Raw == "" {
		return nil, fmt.Errorf("no sql provided")
	}
	stmt, err := rel.ParseSql(ctx.Raw)
	if err != nil {
		u.Debugf("could not parse sql : %v", err)
		return nil, err
	}
	if stmt == nil {
		return nil, fmt.Errorf("Not statement for parse? %v", ctx.Raw)
	}
	ctx.Stmt = stmt

	pln, err := plan.WalkStmt(ctx, stmt, planner)

	if err != nil {
		return nil, err
	}
	if pln == nil {
		u.Warnf("error, no plan task, should not be possible?  %v", err)
		return nil, fmt.Errorf("No plan root task found? %v", ctx.Raw)
	}

	execRoot, err := executor.WalkPlan(pln)

	if err != nil {
		return nil, err
	}
	if execRoot == nil {
		return nil, fmt.Errorf("No plan root task found? %v", ctx.Raw)
	}

	return execRoot, err
}
372146
func (p *propServerPlan) SetServerPlanByID(planID string) {
	if p.ServerPlan == nil {
		p.ServerPlan = &ProductServer{}
	}
	p.ServerPlan.Resource = NewResourceByStringID(planID)
}
281635
func (c *Client) ChangePlanOfServer(id string, planID int) error {
	values := url.Values{
		"SUBID":     {id},
		"VPSPLANID": {fmt.Sprintf("%v", planID)},
	}

	if err := c.post(`server/upgrade_plan`, values, nil); err != nil {
		return err
	}
	return nil
}
730605
func (qe *QueryEngine) GetStreamPlan(sql string) (*TabletPlan, error) {
	qe.mu.RLock()
	defer qe.mu.RUnlock()
	splan, err := planbuilder.BuildStreaming(sql, qe.tables)
	if err != nil {
		return nil, err
	}
	plan := &TabletPlan{Plan: splan}
	plan.Rules = qe.queryRuleSources.FilterByPlan(sql, plan.PlanID, plan.TableName().String())
	plan.buildAuthorized()
	return plan, nil
}
133971
func (plan *Plan) filter(values []sqltypes.Value) (bool, []sqltypes.Value, error) {
	result := make([]sqltypes.Value, len(plan.ColExprs))
	for i, colExpr := range plan.ColExprs {
		result[i] = values[colExpr.ColNum]
	}
	if plan.Vindex == nil {
		return true, result, nil
	}

	// Filter by Vindex.
	destinations, err := plan.Vindex.Map(nil, []sqltypes.Value{result[plan.VindexColumn]})
	if err != nil {
		return false, nil, err
	}
	if len(destinations) != 1 {
		return false, nil, fmt.Errorf("mapping row to keyspace id returned an invalid array of destinations: %v", key.DestinationsString(destinations))
	}
	ksid, ok := destinations[0].(key.DestinationKeyspaceID)
	if !ok || len(ksid) == 0 {
		return false, nil, fmt.Errorf("could not map %v to a keyspace id, got destination %v", result[plan.VindexColumn], destinations[0])
	}
	if !key.KeyRangeContains(plan.KeyRange, ksid) {
		return false, nil, nil
	}
	return true, result, nil
}
486886
func (c *IDClient) CreatePlanCost(ctx context.Context, id gomanifold.ID, planCostRequest *PlanCostRequest) (*Price, error) {
	idBytes, err := id.MarshalText()
	if err != nil {
		return nil, err
	}

	p := fmt.Sprintf("/id/plan/%s/cost", string(idBytes))

	req, err := c.backend.NewRequest(http.MethodPost, p, nil, planCostRequest)
	if err != nil {
		return nil, err
	}

	var resp Price
	_, err = c.backend.Do(ctx, req, &resp, func(code int) error {
		switch code {
		case 400, 404, 500:
			return &Error{}
		default:
			return nil
		}
	})
	if err != nil {
		return nil, err
	}

	return &resp, nil
}
309576
func IgnoreUnmappedCols(ignore bool) DBOption {
	return func(db *DB) error {
		db.IgnoreUnmappedCols = ignore
		return nil
	}
}
696563
func Plan(segments []Segment, o *MergePlanOptions) (*MergePlan, error) {
	return plan(segments, o)
}
323330
func (n NFSRemark) SetRemarkPlanID(planID int64) {
	if n.Plan == nil {
		n.Plan = &struct {
			ID json.Number `json:",omitempty"`
		}{}
	}
	n.Plan.ID = json.Number(planID)
}
980344
func (tx *Tx) SelectContext(ctx context.Context, dest interface{}, q interface{}, args ...interface{}) error {
	return selectObjects(ctx, tx.DB, tx, dest, q, args)
}