// SubstituteCorCol2Constant will substitute correlated column to constant value which it contains.
// If the args of one scalar function are all constant, we will substitute it to constant.
492723
func SubstituteCorCol2Constant(expr Expression) (Expression, error) {
	switch x := expr.(type) {
	case *ScalarFunction:
		allConstant := true
		newArgs := make([]Expression, 0, len(x.GetArgs()))
		for _, arg := range x.GetArgs() {
			newArg, err := SubstituteCorCol2Constant(arg)
			if err != nil {
				return nil, err
			}
			_, ok := newArg.(*Constant)
			newArgs = append(newArgs, newArg)
			allConstant = allConstant && ok
		}
		if allConstant {
			val, err := x.Eval(chunk.Row{})
			if err != nil {
				return nil, err
			}
			return &Constant{Value: val, RetType: x.GetType()}, nil
		}
		var newSf Expression
		if x.FuncName.L == ast.Cast {
			newSf = BuildCastFunction(x.GetCtx(), newArgs[0], x.RetType)
		} else {
			newSf = NewFunctionInternal(x.GetCtx(), x.FuncName.L, x.GetType(), newArgs...)
		}
		return newSf, nil
	case *CorrelatedColumn:
		return &Constant{Value: *x.Data, RetType: x.GetType()}, nil
	case *Constant:
		if x.DeferredExpr != nil {
			newExpr := FoldConstant(x)
			return &Constant{Value: newExpr.(*Constant).Value, RetType: x.GetType()}, nil
		}
	}
	return expr, nil
}
601784
func EqFunc(column string, fn *Func) Cmp {
	return Cmp{
		op:     eq,
		column: column,
		value:  fn,
	}
}
306179
func DatumToConstant(d types.Datum, tp byte) *Constant {
	return &Constant{Value: d, RetType: types.NewFieldType(tp)}
}
554828
func (me *DefaultAdapter) InsertColumnsSql(buf *SqlBuilder, cols ColumnList) error {
	buf.WriteRune(space_rune)
	buf.WriteRune(left_paren_rune)
	if err := me.Literal(buf, cols); err != nil {
		return err
	}
	buf.WriteRune(right_paren_rune)
	return nil
}
441842
func (oa *orderedAggregate) SupplyCol(col *sqlparser.ColName) (rc *resultColumn, colnum int) {
	panic("BUG: nothing should depend on orderedAggregate")
}
129489
func GetStringFromConstant(ctx sessionctx.Context, value Expression) (string, bool, error) {
	con, ok := value.(*Constant)
	if !ok {
		err := errors.Errorf("Not a Constant expression %+v", value)
		return "", true, err
	}
	str, isNull, err := con.EvalString(ctx, chunk.Row{})
	if err != nil || isNull {
		return "", true, err
	}
	return str, false, nil
}
952900
func (p *Apply) SetCorrelated() {
	corCols := p.GetChildren()[1].extractCorrelatedCols()
	p.correlated = p.GetChildren()[0].IsCorrelated()
	for _, corCol := range corCols {
		// If the outer column can't be resolved from this outer schema, it should be resolved by outer schema.
		if idx := p.GetChildren()[0].GetSchema().GetColumnIndex(&corCol.Column); idx == -1 {
			p.correlated = true
			break
		}
	}
}
1354724
func ColumnClauseFromColumn(c ColumnElem) ColumnClause {
	return ColumnClause{table: c.table, name: c.name}
}
153308
func substituteParams(tmpl *wfv1.Template, globalParams, localParams map[string]string) (*wfv1.Template, error) {
	tmplBytes, err := json.Marshal(tmpl)
	if err != nil {
		return nil, errors.InternalWrapError(err)
	}
	// First replace globals & locals, then replace inputs because globals could be referenced in the inputs
	replaceMap := make(map[string]string)
	for k, v := range globalParams {
		replaceMap[k] = v
	}
	for k, v := range localParams {
		replaceMap[k] = v
	}
	fstTmpl := fasttemplate.New(string(tmplBytes), "{{", "}}")
	globalReplacedTmplStr, err := Replace(fstTmpl, replaceMap, true)
	if err != nil {
		return nil, err
	}
	var globalReplacedTmpl wfv1.Template
	err = json.Unmarshal([]byte(globalReplacedTmplStr), &globalReplacedTmpl)
	if err != nil {
		return nil, errors.InternalWrapError(err)
	}
	// Now replace the rest of substitutions (the ones that can be made) in the template
	replaceMap = make(map[string]string)
	for _, inParam := range globalReplacedTmpl.Inputs.Parameters {
		if inParam.Value == nil {
			return nil, errors.InternalErrorf("inputs.parameters.%s had no value", inParam.Name)
		}
		replaceMap["inputs.parameters."+inParam.Name] = *inParam.Value
	}
	for _, inArt := range globalReplacedTmpl.Inputs.Artifacts {
		if inArt.Path != "" {
			replaceMap["inputs.artifacts."+inArt.Name+".path"] = inArt.Path
		}
	}
	for _, outArt := range globalReplacedTmpl.Outputs.Artifacts {
		if outArt.Path != "" {
			replaceMap["outputs.artifacts."+outArt.Name+".path"] = outArt.Path
		}
	}
	for _, param := range globalReplacedTmpl.Outputs.Parameters {
		if param.ValueFrom != nil && param.ValueFrom.Path != "" {
			replaceMap["outputs.parameters."+param.Name+".path"] = param.ValueFrom.Path
		}
	}

	fstTmpl = fasttemplate.New(globalReplacedTmplStr, "{{", "}}")
	s, err := Replace(fstTmpl, replaceMap, true)
	if err != nil {
		return nil, err
	}
	var newTmpl wfv1.Template
	err = json.Unmarshal([]byte(s), &newTmpl)
	if err != nil {
		return nil, errors.InternalWrapError(err)
	}
	return &newTmpl, nil
}
726703
func (d *Dataset) InsertConstrainedColumn(index int, header string,
	constraint ColumnConstraint, cols []interface{}) error {
	err := d.InsertColumn(index, header, cols)
	if err != nil {
		return err
	}

	d.constraints[index] = constraint
	return nil
}
1107033
func ReplaceStringSecret(val string, secretValues map[string]string) string {
	if val == "" || !strings.HasPrefix(val, "$") {
		return val
	}
	secretKey := val[1:]
	secretVal, ok := secretValues[secretKey]
	if !ok {
		log.Warnf("config referenced '%s', but key does not exist in secret", val)
		return val
	}
	return secretVal
}
1282304
func NormalizeConditions(columnConditions map[string][]*Condition) []*ColumnCondition {
	var cc []*ColumnCondition

	for column, conds := range columnConditions {
		for _, cond := range conds {
			cc = append(cc, &ColumnCondition{
				Name:      column,
				Condition: cond})
		}
	}

	sort.Sort(sortedColumnCondition(cc))
	return cc
}
724999
func substituteEnvVars(data map[string]interface{}) (map[string]interface{}, error) {
	envErrors := []string{}
	getEnvOrErr := func(key string) string {
		// Performance optimization: slice sub-sequence is faster than regex.FindStringSubmatch
		key = key[2 : len(key)-1]

		val := os.Getenv(key)
		if val == "" {
			envErrors = append(envErrors, fmt.Sprintf("\tEnvironment variable '%s' not set", key))
		}
		return val
	}

	subs := substitute(data, envvarTokens, getEnvOrErr)
	if len(envErrors) > 0 {
		return nil, errors.New(strings.Join(envErrors, "\n"))
	}

	return subs, nil
}
1183523
func indexCol2Col(cols []*Column, col *model.IndexColumn) *Column {
	for _, c := range cols {
		if c.ColName.L == col.Name.L {
			return c
		}
	}
	return nil
}
1099013
func (p *PhysicalApply) SetCorrelated() {
	corColumns := p.GetChildren()[1].extractCorrelatedCols()
	p.correlated = p.GetChildren()[0].IsCorrelated()
	for _, corCol := range corColumns {
		if idx := p.GetChildren()[0].GetSchema().GetColumnIndex(&corCol.Column); idx == -1 {
			p.correlated = true
			break
		}
	}
}
609924
func (p *Processor) SubstituteParameters(params map[string]templateapi.Parameter, item runtime.Object) (runtime.Object, error) {
	stringreplace.VisitObjectStrings(item, func(in string) (string, bool) {
		return p.EvaluateParameterSubstitution(params, in)
	})
	return item, nil
}
356551
func colFunc(name string, col interface{}) SqlFunctionExpression {
	if s, ok := col.(string); ok {
		col = I(s)
	}
	return Func(name, col)
}