// ColumnSubstitute substitutes the columns in filter to expressions in select fields.
// e.g. select * from (select b as a from t) k where a < 10 => select * from (select b as a from t where b < 10) k.
963354
func ColumnSubstitute(expr Expression, schema Schema, newExprs []Expression) Expression {
	switch v := expr.(type) {
	case *Column:
		id := schema.GetColumnIndex(v)
		if id == -1 {
			return v
		}
		return newExprs[id].Clone()
	case *ScalarFunction:
		if v.FuncName.L == ast.Cast {
			newFunc := v.Clone().(*ScalarFunction)
			newFunc.GetArgs()[0] = ColumnSubstitute(newFunc.GetArgs()[0], schema, newExprs)
			return newFunc
		}
		newArgs := make([]Expression, 0, len(v.GetArgs()))
		for _, arg := range v.GetArgs() {
			newArgs = append(newArgs, ColumnSubstitute(arg, schema, newExprs))
		}
		fun, _ := NewFunction(v.GetCtx(), v.FuncName.L, v.RetType, newArgs...)
		return fun
	}
	return expr
}
1365518
func (h *SMTPAPIHeader) AddSubstitutions(key string, subs []string) {
	for i := 0; i < len(subs); i++ {
		h.AddSubstitution(key, subs[i])
	}
}
735794
func columnOutput(list []string, c *columnize.Config) string {
	if len(list) == 0 {
		return ""
	}

	if c == nil {
		c = &columnize.Config{}
	}
	if c.Glue == "" {
		c.Glue = "    "
	}
	if c.Empty == "" {
		c.Empty = "n/a"
	}

	return columnize.Format(list, c)
}
242401
func (s *Schema) ColumnIndex(col *Column) int {
	for i, c := range s.Columns {
		if c.UniqueID == col.UniqueID {
			return i
		}
	}
	return -1
}
406069
func (d *Database) ColumnsQuoted(src interface{}, includePk bool) (string, error) {
	unquoted, err := d.Columns(src, includePk)
	if err != nil {
		return "", err
	}

	var parts []string
	for _, elt := range unquoted {
		parts = append(parts, d.quoted(elt))
	}

	return strings.Join(parts, ","), nil
}
109476
func SqTableColumns(db models.XODB, schema string, table string) ([]*models.Column, error) {
	var err error

	// grab
	rows, err := models.SqTableColumns(db, table)
	if err != nil {
		return nil, err
	}

	// fix columns
	var cols []*models.Column
	for _, row := range rows {
		cols = append(cols, &models.Column{
			FieldOrdinal: row.FieldOrdinal,
			ColumnName:   row.ColumnName,
			DataType:     row.DataType,
			NotNull:      row.NotNull,
			DefaultValue: row.DefaultValue,
			IsPrimaryKey: row.PkColIndex != 0,
		})
	}

	return cols, nil
}
1091220
func Sub(a, b *T) T {
	return T{a[0] - b[0], a[1] - b[1], a[2] - b[2]}
}
577960
func (s *BaiduMessage) SetSubstitutions(v map[string][]*string) *BaiduMessage {
	s.Substitutions = v
	return s
}
994057
func (b *InsertBuilder) Values(columnValues ...interface{}) *InsertBuilder {
	b.lock.Lock()
	sqlValue := "("
	if b.prepared {
		for k, columnValue := range columnValues {
			switch v := columnValue.(type) {
			case string:
				sqlValue = fmt.Sprintf("%s'%s'", sqlValue, strings.Replace(v, "'", "''", -1))
			default:
				sqlValue = fmt.Sprintf("%s%v", sqlValue, v)
			}
			if k < len(columnValues)-1 {
				sqlValue = fmt.Sprintf("%s, ", sqlValue)
			}
		}
	} else {
		for k := range columnValues {
			sqlValue = fmt.Sprintf("%s?", sqlValue)
			if k < len(columnValues)-1 {
				sqlValue = fmt.Sprintf("%s, ", sqlValue)
			}
		}
	}
	b.sqlValues = append(b.sqlValues, fmt.Sprintf(`%s)`, sqlValue))

	b.lock.Unlock()

	return b
}
286433
func Columns(src interface{}, includePk bool) ([]string, error) {
	return Default.Columns(src, includePk)
}
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
}
1134350
func (m *SqlSource) ColumnPositions() map[string]int {
	if len(m.colIndex) > 0 {
		return m.colIndex
	}
	if m.Source == nil {
		return nil
	}
	cols := make(map[string]int)
	for idx, col := range m.Source.Columns {
		left, right, ok := col.LeftRight()
		//u.Debugf("aliasing: l:%v r:%v ok?%v", left, right, ok)
		if ok {
			cols[right] = idx
		} else {
			cols[left] = idx
		}
	}
	m.colIndex = cols
	return m.colIndex
}
231922
func (b *InsertBuilder) Columns(columns ...string) *InsertBuilder {
	for _, c := range columns {
		b.columns = append(b.columns, initializer{
			column: c,
			value:  param(c),
		})
	}
	return b
}
659076
func SELECT(entity interface{}, afterKeyword Expression, binding ...interface{}) Expression {
	return &PrefixedExp{"SELECT", []Expression{FROM(entity, afterKeyword)}, "", binding}
}
45110
func (qb *TiDBQueryBuilder) Subquery(sub string, alias string) string {
	return fmt.Sprintf("(%s) AS %s", sub, alias)
}
336232
func replaceColsInPropBySchema(prop *requiredProperty, schema expression.Schema) *requiredProperty {
	newProps := make([]*columnProp, 0, len(prop.props))
	for _, p := range prop.props {
		idx := schema.GetColumnIndex(p.col)
		if idx == -1 {
			log.Printf("Can't find column %s in schema", p.col)
		}
		newProps = append(newProps, &columnProp{col: schema.Columns[idx], desc: p.desc})
	}
	return &requiredProperty{
		props:      newProps,
		sortKeyLen: prop.sortKeyLen,
		limit:      prop.limit,
	}
}
917741
func newSubquery(alias sqlparser.TableIdent, bldr builder) (*subquery, *symtab, error) {
	sq := &subquery{
		order:     bldr.Order() + 1,
		input:     bldr,
		esubquery: &engine.Subquery{},
	}

	// Create a 'table' that represents the subquery.
	t := &table{
		alias:  sqlparser.TableName{Name: alias},
		origin: sq,
	}

	// Create column symbols based on the result column names.
	for _, rc := range bldr.ResultColumns() {
		if _, ok := t.columns[rc.alias.Lowered()]; ok {
			return nil, nil, fmt.Errorf("duplicate column names in subquery: %s", sqlparser.String(rc.alias))
		}
		t.addColumn(rc.alias, &column{origin: sq})
	}
	t.isAuthoritative = true
	st := newSymtab()
	// AddTable will not fail because symtab is empty.
	_ = st.AddTable(t)
	return sq, st, nil
}