// RewriteSelect We are removing Column Aliases "user_id as uid"
// as well as functions - used when we are going to defer projection, aggs
434772
func RewriteSelect(m *SqlSelect) {
	originalCols := m.Columns
	m.Columns = make(Columns, 0, len(originalCols)+5)
	rewriteIntoProjection(m, originalCols)
	rewriteIntoProjection(m, m.GroupBy)
	if m.Where != nil {
		colsToAdd := expr.FindAllIdentityField(m.Where.Expr)
		addIntoProjection(m, colsToAdd)
	}
	rewriteIntoProjection(m, m.OrderBy)
}
668994
func (b *Bound) ToMysqlIntersectsCondition(column string) string {
	return fmt.Sprintf("INTERSECTS(%s, GEOMFROMTEXT('%s'))", column, b.String())
}
454242
func (l *labelIdentitySelector) updateSelections() {
	selections := make([]identity.NumericIdentity, len(l.cachedSelections))
	i := 0
	for nid := range l.cachedSelections {
		selections[i] = nid
		i++
	}
	// Sort the numeric identities so that the map iteration order
	// does not matter. This makes testing easier, but may help
	// identifying changes easier also otherwise.
	sort.Slice(selections, func(i, j int) bool {
		return selections[i] < selections[j]
	})
	l.setSelections(&selections)
}
1020791
func (s *SelectQuery) Select(cols ...string) *SelectQuery {
	s.selects = cols
	return s
}
982836
func (s *SelectStatement) rewriteWithoutTimeDimensions() string {
	n := RewriteFunc(s.Condition, func(n Node) Node {
		switch n := n.(type) {
		case *BinaryExpr:
			if n.LHS.String() == "time" {
				return &BooleanLiteral{Val: true}
			}
			return n
		case *Call:
			return &BooleanLiteral{Val: true}
		default:
			return n
		}
	})

	return n.String()
}
282955
func Rewrite(r Rewriter, node Node) Node {
	switch n := node.(type) {
	case *Query:
		n.Statements = Rewrite(r, n.Statements).(Statements)

	case Statements:
		for i, s := range n {
			n[i] = Rewrite(r, s).(Statement)
		}

	case *SelectStatement:
		n.Fields = Rewrite(r, n.Fields).(Fields)
		n.Dimensions = Rewrite(r, n.Dimensions).(Dimensions)
		n.Sources = Rewrite(r, n.Sources).(Sources)

		// Rewrite may return nil. Nil does not satisfy the Expr
		// interface. We only assert the rewritten result to be an
		// Expr if it is not nil:
		if cond := Rewrite(r, n.Condition); cond != nil {
			n.Condition = cond.(Expr)
		} else {
			n.Condition = nil
		}

	case *SubQuery:
		n.Statement = Rewrite(r, n.Statement).(*SelectStatement)

	case Fields:
		for i, f := range n {
			n[i] = Rewrite(r, f).(*Field)
		}

	case *Field:
		n.Expr = Rewrite(r, n.Expr).(Expr)

	case Dimensions:
		for i, d := range n {
			n[i] = Rewrite(r, d).(*Dimension)
		}

	case *Dimension:
		n.Expr = Rewrite(r, n.Expr).(Expr)

	case *BinaryExpr:
		n.LHS = Rewrite(r, n.LHS).(Expr)
		n.RHS = Rewrite(r, n.RHS).(Expr)

	case *ParenExpr:
		n.Expr = Rewrite(r, n.Expr).(Expr)

	case *Call:
		for i, expr := range n.Args {
			n.Args[i] = Rewrite(r, expr).(Expr)
		}
	}

	return r.Rewrite(node)
}
207560
func (rule *classRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result {
	if rule.fromClass > 0 && rule.toClass > 0 {
		if r.Question[0].Qclass == rule.fromClass {
			r.Question[0].Qclass = rule.toClass
			return RewriteDone
		}
	}
	return RewriteIgnored
}
1153156
func (c *DOM) QuerySelectorAll(nodeId int, selector string) ([]int, error) {
	var v DOMQuerySelectorAllParams
	v.NodeId = nodeId
	v.Selector = selector
	return c.QuerySelectorAllWithParams(&v)
}
141825
func (me *Dataset) selectSqlWriteTo(buf *SqlBuilder) error {
	if err := me.adapter.CommonTablesSql(buf, me.clauses.CommonTables); err != nil {
		return err
	}
	if me.clauses.SelectDistinct != nil {
		if err := me.adapter.SelectDistinctSql(buf, me.clauses.SelectDistinct); err != nil {
			return err
		}
	} else {
		if err := me.adapter.SelectSql(buf, me.clauses.Select); err != nil {
			return err
		}
	}
	if err := me.adapter.FromSql(buf, me.clauses.From); err != nil {
		return err
	}
	if err := me.adapter.JoinSql(buf, me.clauses.Joins); err != nil {
		return err
	}
	if err := me.adapter.WhereSql(buf, me.clauses.Where); err != nil {
		return err
	}
	if err := me.adapter.GroupBySql(buf, me.clauses.GroupBy); err != nil {
		return err
	}
	if err := me.adapter.HavingSql(buf, me.clauses.Having); err != nil {
		return err
	}
	if err := me.adapter.CompoundsSql(buf, me.clauses.Compounds); err != nil {
		return err
	}
	if err := me.adapter.OrderSql(buf, me.clauses.Order); err != nil {
		return err
	}
	if err := me.adapter.LimitSql(buf, me.clauses.Limit); err != nil {
		return err
	}
	return me.adapter.OffsetSql(buf, me.clauses.Offset)

}
997159
func (s *Selection) IndexSelector(selector string) int {
	if len(s.Nodes) > 0 {
		sel := s.document.Find(selector)
		return indexInSlice(sel.Nodes, s.Nodes[0])
	}
	return -1
}
81341
func (sess *Session) Select(column ...string) *SelectStmt {
	b := Select(prepareSelect(column)...)
	b.runner = sess
	b.EventReceiver = sess.EventReceiver
	b.Dialect = sess.Dialect
	return b
}
969332
func RewriteSimpleExprWithSchema(ctx sessionctx.Context, expr ast.ExprNode, schema *Schema) (Expression, error) {
	rewriter := &simpleRewriter{ctx: ctx, schema: schema}
	expr.Accept(rewriter)
	if rewriter.err != nil {
		return nil, rewriter.err
	}
	return rewriter.pop(), nil
}
213857
func (ps *pulloutSubquery) PushSelect(expr *sqlparser.AliasedExpr, origin builder) (rc *resultColumn, colnum int, err error) {
	return ps.underlying.PushSelect(expr, origin)
}
292604
func RewriteShowAsSelect(stmt *rel.SqlShow, ctx *Context) (*rel.SqlSelect, error) {

	raw := strings.ToLower(stmt.Raw)
	if ctx.Funcs == nil {
		ctx.Funcs = fr
	}

	showType := strings.ToLower(stmt.ShowType)
	u.Debugf("showType=%q create=%q from=%q rewrite: %s", showType, stmt.CreateWhat, stmt.From, raw)
	sqlStatement := ""
	from := "tables"
	if stmt.Db != "" {
		from = fmt.Sprintf("%s.%s", stmt.Db, expr.IdentityMaybeQuote('`', from))
	}
	switch showType {
	case "tables":
		if stmt.Full {
			// SHOW FULL TABLES;    = select name, table_type from tables;
			// TODO:  note the stupid "_in_mysql", assuming i don't have to implement
			/*
			   mysql> show full tables;
			   +---------------------------+------------+
			   | Tables_in_mysql           | Table_type |
			   +---------------------------+------------+
			   | columns_priv              | BASE TABLE |

			*/
			sqlStatement = "select Table, Table_Type from `schema`.`tables`;"
		} else {
			// show tables;
			sqlStatement = "select Table from `schema`.`tables`;"
		}
	case "create":
		// SHOW CREATE {TABLE | DATABASE | EVENT | VIEW }
		switch strings.ToLower(stmt.CreateWhat) {
		case "table":
			sqlStatement = fmt.Sprintf("select Table , mysql_create as `Create Table` FROM `schema`.`%s`", from)
			vn := expr.NewStringNode(stmt.Identity)
			lh := expr.NewIdentityNodeVal("Table")
			stmt.Where = expr.NewBinaryNode(lex.Token{T: lex.TokenEqual, V: "="}, lh, vn)
		default:
			return nil, fmt.Errorf("Unsupported show create %q", stmt.CreateWhat)
		}
	case "databases":
		// SHOW databases;  ->  select Database from databases;
		sqlStatement = "select Database from schema.databases;"
	case "columns":
		if stmt.Full {
			/*
				mysql> show full columns from user;
				+------------------------+-----------------------------------+-----------------+------+-----+-----------------------+-------+---------------------------------+---------+
				| Field                  | Type                              | Collation       | Null | Key | Default               | Extra | Privileges                      | Comment |

			*/
			sqlStatement = fmt.Sprintf("select Field, typewriter(Type) AS Type, Collation, `Null`, Key, Default, Extra, Privileges, Comment from `schema`.`%s`;", stmt.Identity)

		} else {
			/*
				mysql> show columns from user;
				+------------------------+-----------------------------------+------+-----+-----------------------+-------+
				| Field                  | Type                              | Null | Key | Default               | Extra |
				+------------------------+-----------------------------------+------+-----+-----------------------+-------+
			*/
			sqlStatement = fmt.Sprintf("select Field, typewriter(Type) AS Type, `Null`, Key, Default, Extra from `schema`.`%s`;", stmt.Identity)
		}
	case "keys", "indexes", "index":
		/*
			mysql> show keys from `user` from `mysql`;
			+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
			| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
			+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
			| user  |          0 | PRIMARY  |            1 | Host        | A         |        NULL |     NULL | NULL   |      | BTREE      |         |               |
			| user  |          0 | PRIMARY  |            2 | User        | A         |           3 |     NULL | NULL   |      | BTREE      |         |               |
			+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

			mysql> show indexes from `user` from `mysql`;
			+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
			| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
			+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
			| user  |          0 | PRIMARY  |            1 | Host        | A         |        NULL |     NULL | NULL   |      | BTREE      |         |               |
			| user  |          0 | PRIMARY  |            2 | User        | A         |           3 |     NULL | NULL   |      | BTREE      |         |               |
			+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

		*/
		sqlStatement = fmt.Sprintf("select Table, Non_unique, Key_name, Seq_in_index, Column_name, Collation, Cardinality, Sub_part, Packed, `Null`, Index_type, Index_comment from `schema`.`indexes`;")

	case "variables":
		// SHOW [GLOBAL | SESSION] VARIABLES [like_or_where]
		scope := stmt.Scope
		if scope == "" {
			scope = "session"
		} else {

		}
		sqlStatement = fmt.Sprintf("select Variable_name, Value from `context`.`%s_variables`;", scope)
		/*
		   mysql> show variables LIKE 'version';
		   +---------------+----------+
		   | Variable_name | Value    |
		   +---------------+----------+
		   | version       | 5.7.10-3 |
		   +---------------+----------+
		*/

	case "status":
		// Status is a subset of just some variables
		// http://dev.mysql.com/doc/refman/5.7/en/server-status-variables.html

		// SHOW [GLOBAL | SESSION | SLAVE ] STATUS [like_or_where]
		scope := stmt.Scope
		switch scope {
		case "session", "":
			scope = "session"
		}
		sqlStatement = fmt.Sprintf("select Variable_name, Value from `context`.`%s_variables`;", scope)
		/*
			mysql> show global status;
			+--------------------------------+-----------------+
			| Variable_name                  | Value
			+--------------------------------+------------------
			| Aborted_clients                | 0
			| Aborted_connects               | 0
			| Binlog_snapshot_file           |
			| Binlog_snapshot_position       | 0
		*/
	case "engines":
		sqlStatement = fmt.Sprintf("select Engine, Support, Comment, Transactions, XA, Savepoints from `context`.`engines`;")
		/*
			show engines;
			mysql> show engines;
			+--------------------+---------+----------------------------------------------------------------------------+--------------+------+------------+
			| Engine             | Support | Comment                                                                    | Transactions | XA   | Savepoints |
			+--------------------+---------+----------------------------------------------------------------------------+--------------+------+------------+
			| InnoDB             | DEFAULT | Percona-XtraDB, Supports transactions, row-level locking, and foreign keys | YES          | YES  | YES        |
			| CSV                | YES     | CSV storage engine                                                         | NO           | NO   | NO         |
			| MyISAM             | YES     | MyISAM storage engine                                                      | NO           | NO   | NO         |
			| BLACKHOLE          | YES     | /dev/null storage engine (anything you write to it disappears)             | NO           | NO   | NO         |
			| PERFORMANCE_SCHEMA | YES     | Performance Schema                                                         | NO           | NO   | NO         |
			| MEMORY             | YES     | Hash based, stored in memory, useful for temporary tables                  | NO           | NO   | NO         |
			| ARCHIVE            | YES     | Archive storage engine                                                     | NO           | NO   | NO         |
			| MRG_MYISAM         | YES     | Collection of identical MyISAM tables                                      | NO           | NO   | NO         |
			| FEDERATED          | NO      | Federated MySQL storage engine                                             | NULL         | NULL | NULL       |
			+--------------------+---------+----------------------------------------------------------------------------+--------------+------+------------+
		*/
	case "procedure", "function":
		/*
			show procuedure status;
			show function status;

				| Db  | Name | Type | Definer | Modified | Created | Security_type | Comment| character_set_client | collation_connection | Database Collation |
		*/
		sqlStatement = fmt.Sprintf("SELECT Db, Name, Type, Definer, Modified, Created, Security_type, Comment, character_set_client, `collation_connection`, `Database Collation` from `context`.`%ss`;", showType)

	default:
		u.Warnf("unhandled sql rewrite statement %s", raw)
		return nil, fmt.Errorf("Unrecognized:   %s", raw)
	}
	sel, err := rel.ParseSqlSelectResolver(sqlStatement, ctx.Funcs)
	if err != nil {
		u.Errorf("could not reparse %s  err=%v", sqlStatement, err)
		return nil, err
	}
	sel.SetSystemQry()
	if stmt.Like != nil {
		// We are going to ReWrite LIKE clause to WHERE clause
		sel.Where = &rel.SqlWhere{Expr: stmt.Like}
		bn, ok := stmt.Like.(*expr.BinaryNode)
		if ok {
			rhn, ok := bn.Args[1].(*expr.StringNode)
			// See if the Like Clause has wildcard matching, if so
			// our internal vm uses * not %
			if ok && rhn.Text == "%" {
				rhn.Text = strings.Replace(rhn.Text, "%", "*", -1)
			}
		}

	} else if stmt.Where != nil {
		//u.Debugf("add where: %s", stmt.Where)
		sel.Where = &rel.SqlWhere{Expr: stmt.Where}
	}
	if ctx.Schema == nil {
		u.Warnf("missing schema for %s", stmt.Raw)
		return nil, fmt.Errorf("Must have schema")
	}
	if ctx.Schema.InfoSchema == nil {
		u.Warnf("WAT?  Information Schema Nil?")
		return nil, fmt.Errorf("Must have Info schema")
	}

	ctx.Schema = ctx.Schema.InfoSchema
	u.Debugf("SHOW rewrite: %q  ==> %s", stmt.Raw, sel.String())
	return sel, nil
}
109578
func (rule *prefixTtlRule) Rewrite(ctx context.Context, state request.Request) Result {
	if strings.HasPrefix(state.Name(), rule.Prefix) {
		return RewriteDone
	}
	return RewriteIgnored
}
1185293
func (a *aggregationEliminateChecker) rewriteExpr(ctx sessionctx.Context, aggFunc *aggregation.AggFuncDesc) expression.Expression {
	switch aggFunc.Name {
	case ast.AggFuncCount:
		if aggFunc.Mode == aggregation.FinalMode {
			return a.wrapCastFunction(ctx, aggFunc.Args[0], aggFunc.RetTp)
		}
		return a.rewriteCount(ctx, aggFunc.Args, aggFunc.RetTp)
	case ast.AggFuncSum, ast.AggFuncAvg, ast.AggFuncFirstRow, ast.AggFuncMax, ast.AggFuncMin, ast.AggFuncGroupConcat:
		return a.wrapCastFunction(ctx, aggFunc.Args[0], aggFunc.RetTp)
	case ast.AggFuncBitAnd, ast.AggFuncBitOr, ast.AggFuncBitXor:
		return a.rewriteBitFunc(ctx, aggFunc.Name, aggFunc.Args[0], aggFunc.RetTp)
	default:
		panic("Unsupported function")
	}
}
242379
func (r ComplexRule) Rewrite(fs http.FileSystem, req *http.Request) (re Result) {
	replacer := newReplacer(req)

	// validate regexp if present
	if r.Regexp != nil {
		matches := regexpMatches(r.Regexp, r.Base, req.URL.Path)
		switch len(matches) {
		case 0:
			// no match
			return
		default:
			// set regexp match variables {1}, {2} ...

			// url escaped values of ? and #.
			q, f := url.QueryEscape("?"), url.QueryEscape("#")

			for i := 1; i < len(matches); i++ {
				// Special case of unescaped # and ? by stdlib regexp.
				// Reverse the unescape.
				if strings.ContainsAny(matches[i], "?#") {
					matches[i] = strings.NewReplacer("?", q, "#", f).Replace(matches[i])
				}

				replacer.Set(fmt.Sprint(i), matches[i])
			}
		}
	}

	// attempt rewrite
	return To(fs, req, r.To, replacer)
}