// Run the explain analysis on the given queries
354557
func Run(sql string) ([]*Explain, error) {
	explains := make([]*Explain, 0, 16)

	var (
		rem string
		err error
	)

	for {
		// Need to strip comments in a loop to handle multiple comments
		// in a row.
		for {
			s := sqlparser.StripLeadingComments(sql)
			if s == sql {
				break
			}
			sql = s
		}

		sql, rem, err = sqlparser.SplitStatement(sql)
		if err != nil {
			return nil, err
		}

		if sql != "" {
			// Reset the global time simulator unless there's an open transaction
			// in the session from the previous staement.
			if vtgateSession == nil || !vtgateSession.GetInTransaction() {
				batchTime = sync2.NewBatcher(*batchInterval)
			}
			log.V(100).Infof("explain %s", sql)
			e, err := explain(sql)
			if err != nil {
				return nil, err
			}
			explains = append(explains, e)
		}

		sql = rem
		if sql == "" {
			break
		}
	}

	return explains, nil
}
1172784
func ExtractQuery(opts ...interface{}) *opt.QueryOption {
	for _, o := range opts {
		if v, ok := o.(*opt.QueryOption); ok {
			return v
		}
	}
	return nil
}
475535
func Queries(queries []string) func(*sql.Tx) error {
	return func(tx *sql.Tx) error {
		for _, query := range queries {
			if _, err := tx.Exec(query); err != nil {
				return err
			}
		}

		return nil
	}
}
1193235
func (s *ClusterRerouteService) Explain(explain bool) *ClusterRerouteService {
	s.explain = &explain
	return s
}
755874
func (s *SearchService) Explain(explain bool) *SearchService {
	s.searchSource = s.searchSource.Explain(explain)
	return s
}
66882
func (interview *Interview) Run() (map[string]interface{}, error) {
	answers := make(map[string]interface{}, len(interview.Questions))
	for index, question := range interview.Questions {
		// If they haven't set the answer type, set it to String
		if question.AnswerKind == reflect.Invalid {
			question.AnswerKind = reflect.String
		}

		// If they haven't set a key, return an error
		if question.Key == "" {
			return nil, fmt.Errorf("Question %d has no key", index)
		}

		// If they haven't set the text for a question, return an error
		if question.Text == "" {
			return nil, fmt.Errorf("Question %d has no text", index)
		}

		answer, err := interview.getAnswer(&question)
		if err == nil {
			answers[question.Key] = answer
		} else {
			return answers, err
		}
	}
	return answers, nil
}
788910
func Run(db *sql.DB, migrationsFolder string) error {
	postgres := NewPostgresDatabase(db)
	return ApplyMigrations(postgres, migrationsFolder)
}
1123248
func (t Term) Run(s QueryExecutor, optArgs ...RunOpts) (*Cursor, error) {
	opts := map[string]interface{}{}
	var ctx context.Context = nil // if it's nil connection will form context from connection opts
	if len(optArgs) >= 1 {
		opts = optArgs[0].toMap()
		ctx = optArgs[0].Context
	}

	if s == nil || !s.IsConnected() {
		return nil, ErrConnectionClosed
	}

	q, err := s.newQuery(t, opts)
	if err != nil {
		return nil, err
	}

	return s.Query(ctx, q)
}
431590
func (d *commandSQLAll) Run() error {
	sqls, indexes := getDbCreateSQL(d.al)
	var all []string
	for i, mi := range modelCache.allOrdered() {
		queries := []string{sqls[i]}
		for _, idx := range indexes[mi.table] {
			queries = append(queries, idx.SQL)
		}
		sql := strings.Join(queries, "\n")
		all = append(all, sql)
	}
	fmt.Println(strings.Join(all, "\n\n"))

	return nil
}
55691
func (r *SearchRequest) Explain(explain bool) *SearchRequest {
	r.searchSource = r.searchSource.Explain(explain)
	return r
}
59575
func (s *Script) Run(c scripter, keys []string, args ...interface{}) *Cmd {
	r := s.EvalSha(c, keys, args...)
	if err := r.Err(); err != nil && strings.HasPrefix(err.Error(), "NOSCRIPT ") {
		return s.Eval(c, keys, args...)
	}
	return r
}
966902
func ExplainsAsText(explains []*Explain) string {
	var b bytes.Buffer
	for _, explain := range explains {
		fmt.Fprintf(&b, "----------------------------------------------------------------------\n")
		fmt.Fprintf(&b, "%s\n\n", explain.SQL)

		queries := make([]outputQuery, 0, 4)
		for tablet, actions := range explain.TabletActions {
			for _, q := range actions.MysqlQueries {
				queries = append(queries, outputQuery{
					tablet: tablet,
					Time:   q.Time,
					sql:    q.SQL,
				})
			}
		}

		// Make sure to sort first by the batch time and then by the
		// shard to avoid flakiness in the tests for parallel queries
		sort.SliceStable(queries, func(i, j int) bool {
			if queries[i].Time == queries[j].Time {
				return queries[i].tablet < queries[j].tablet
			}
			return queries[i].Time < queries[j].Time
		})

		for _, q := range queries {
			fmt.Fprintf(&b, "%d %s: %s\n", q.Time, q.tablet, q.sql)
		}
		fmt.Fprintf(&b, "\n")
	}
	fmt.Fprintf(&b, "----------------------------------------------------------------------\n")
	return b.String()
}
669690
func (m *DbMap) Exec(query string, args ...interface{}) (sql.Result, error) {
	m.trace(query, args)
	//stmt, err := m.Db.Prepare(query)
	//if err != nil {
	//	return nil, err
	//}
	//fmt.Println("Exec", query, args)
	return m.Db.Exec(query, args...)
}
962362
func (f *PlatformFilter) Explain(nodes int) string {
	if nodes == 1 {
		return "unsupported platform on 1 node"
	}
	return fmt.Sprintf("unsupported platform on %d nodes", nodes)
}
1017349
func (d *Datastore) Query(q dsq.Query) (dsq.Results, error) {
	nq, cq := d.prepareQuery(q)

	cqr, err := d.child.Query(cq)
	if err != nil {
		return nil, err
	}

	qr := dsq.ResultsFromIterator(q, dsq.Iterator{
		Next: func() (dsq.Result, bool) {
			r, ok := cqr.NextSync()
			if !ok {
				return r, false
			}
			if r.Error == nil {
				r.Entry.Key = d.InvertKey(ds.RawKey(r.Entry.Key)).String()
			}
			return r, true
		},
		Close: func() error {
			return cqr.Close()
		},
	})
	return dsq.NaiveQueryApply(nq, qr), nil
}
98854
func (p Plan) Run(input map[Req][]models.Series) ([]models.Series, error) {
	var out []models.Series
	p.data = input
	for _, fn := range p.funcs {
		series, err := fn.Exec(p.data)
		if err != nil {
			return nil, err
		}
		out = append(out, series...)
	}
	for i, o := range out {
		if p.MaxDataPoints != 0 && len(o.Datapoints) > int(p.MaxDataPoints) {
			// series may have been created by a function that didn't know which consolidation function to default to.
			// in the future maybe we can do more clever things here. e.g. perSecond maybe consolidate by max.
			if o.Consolidator == 0 {
				o.Consolidator = consolidation.Avg
			}
			out[i].Datapoints, out[i].Interval = consolidation.ConsolidateStable(o.Datapoints, o.Interval, p.MaxDataPoints, o.Consolidator)
		}
	}
	return out, nil
}
371764
func (t *explainTablet) HandleQuery(c *mysql.Conn, query string, callback func(*sqltypes.Result) error) error {
	t.mu.Lock()
	defer t.mu.Unlock()

	if !strings.Contains(query, "1 != 1") {
		t.mysqlQueries = append(t.mysqlQueries, &MysqlQuery{
			Time: t.currentTime,
			SQL:  query,
		})
	}

	// return the pre-computed results for any schema introspection queries
	result, ok := schemaQueries[query]
	if ok {
		return callback(result)
	}

	switch sqlparser.Preview(query) {
	case sqlparser.StmtSelect:
		// Parse the select statement to figure out the table and columns
		// that were referenced so that the synthetic response has the
		// expected field names and types.
		stmt, err := sqlparser.Parse(query)
		if err != nil {
			return err
		}

		selStmt := stmt.(*sqlparser.Select)

		if len(selStmt.From) != 1 {
			return fmt.Errorf("unsupported select with multiple from clauses")
		}

		var table sqlparser.TableIdent
		switch node := selStmt.From[0].(type) {
		case *sqlparser.AliasedTableExpr:
			table = sqlparser.GetTableName(node.Expr)
		}

		// For complex select queries just return an empty result
		// since it's too hard to figure out the real columns
		if table.IsEmpty() {
			log.V(100).Infof("query %s result {}\n", query)
			return callback(&sqltypes.Result{})
		}

		tableName := sqlparser.String(table)
		colTypeMap := tableColumns[tableName]
		if colTypeMap == nil && tableName != "dual" {
			return fmt.Errorf("unable to resolve table name %s", tableName)
		}

		colNames := make([]string, 0, 4)
		colTypes := make([]querypb.Type, 0, 4)
		for _, node := range selStmt.SelectExprs {
			switch node := node.(type) {
			case *sqlparser.AliasedExpr:
				switch node := node.Expr.(type) {
				case *sqlparser.ColName:
					col := strings.ToLower(node.Name.String())
					colType := colTypeMap[col]
					if colType == querypb.Type_NULL_TYPE {
						return fmt.Errorf("invalid column %s", col)
					}
					colNames = append(colNames, col)
					colTypes = append(colTypes, colType)
				case *sqlparser.FuncExpr:
					// As a shortcut, functions are integral types
					colNames = append(colNames, sqlparser.String(node))
					colTypes = append(colTypes, querypb.Type_INT32)
				case *sqlparser.SQLVal:
					colNames = append(colNames, sqlparser.String(node))
					switch node.Type {
					case sqlparser.IntVal:
						fallthrough
					case sqlparser.HexNum:
						fallthrough
					case sqlparser.HexVal:
						fallthrough
					case sqlparser.BitVal:
						colTypes = append(colTypes, querypb.Type_INT32)
					case sqlparser.StrVal:
						colTypes = append(colTypes, querypb.Type_VARCHAR)
					case sqlparser.FloatVal:
						colTypes = append(colTypes, querypb.Type_FLOAT64)
					default:
						return fmt.Errorf("unsupported sql value %s", sqlparser.String(node))
					}
				default:
					return fmt.Errorf("unsupported select expression %s", sqlparser.String(node))
				}
			case *sqlparser.StarExpr:
				for col, colType := range colTypeMap {
					colNames = append(colNames, col)
					colTypes = append(colTypes, colType)
				}
			}
		}

		fields := make([]*querypb.Field, len(colNames))
		values := make([]sqltypes.Value, len(colNames))
		for i, col := range colNames {
			colType := colTypes[i]
			fields[i] = &querypb.Field{
				Name: col,
				Type: colType,
			}

			// Generate a fake value for the given column. For numeric types,
			// use the column index. For all other types, just shortcut to using
			// a string type that encodes the column name + index.
			if sqltypes.IsIntegral(colType) {
				values[i] = sqltypes.NewInt32(int32(i + 1))
			} else if sqltypes.IsFloat(colType) {
				values[i] = sqltypes.NewFloat64(1.0 + float64(i))
			} else {
				values[i] = sqltypes.NewVarChar(fmt.Sprintf("%s_val_%d", col, i+1))
			}
		}
		result = &sqltypes.Result{
			Fields:       fields,
			RowsAffected: 1,
			InsertID:     0,
			Rows:         [][]sqltypes.Value{values},
		}

		resultJSON, _ := json.MarshalIndent(result, "", "    ")
		log.V(100).Infof("query %s result %s\n", query, string(resultJSON))

	case sqlparser.StmtBegin, sqlparser.StmtCommit, sqlparser.StmtSet, sqlparser.StmtShow:
		result = &sqltypes.Result{}
	case sqlparser.StmtInsert, sqlparser.StmtReplace, sqlparser.StmtUpdate, sqlparser.StmtDelete:
		result = &sqltypes.Result{
			RowsAffected: 1,
		}
	default:
		return fmt.Errorf("unsupported query %s", query)
	}

	return callback(result)
}