github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/pingcap/tidb/executor/executor.go (about)

     1  // Copyright 2015 PingCAP, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package executor
    15  
    16  import (
    17  	"sort"
    18  
    19  	"github.com/insionng/yougam/libraries/juju/errors"
    20  	"github.com/insionng/yougam/libraries/pingcap/tidb/ast"
    21  	"github.com/insionng/yougam/libraries/pingcap/tidb/column"
    22  	"github.com/insionng/yougam/libraries/pingcap/tidb/context"
    23  	"github.com/insionng/yougam/libraries/pingcap/tidb/evaluator"
    24  	"github.com/insionng/yougam/libraries/pingcap/tidb/inspectkv"
    25  	"github.com/insionng/yougam/libraries/pingcap/tidb/kv"
    26  	"github.com/insionng/yougam/libraries/pingcap/tidb/model"
    27  	"github.com/insionng/yougam/libraries/pingcap/tidb/optimizer/plan"
    28  	"github.com/insionng/yougam/libraries/pingcap/tidb/sessionctx"
    29  	"github.com/insionng/yougam/libraries/pingcap/tidb/sessionctx/db"
    30  	"github.com/insionng/yougam/libraries/pingcap/tidb/sessionctx/forupdate"
    31  	"github.com/insionng/yougam/libraries/pingcap/tidb/table"
    32  	"github.com/insionng/yougam/libraries/pingcap/tidb/terror"
    33  	"github.com/insionng/yougam/libraries/pingcap/tidb/util/codec"
    34  	"github.com/insionng/yougam/libraries/pingcap/tidb/util/distinct"
    35  	"github.com/insionng/yougam/libraries/pingcap/tidb/util/types"
    36  )
    37  
    38  var (
    39  	_ Executor = &AggregateExec{}
    40  	_ Executor = &CheckTableExec{}
    41  	_ Executor = &FilterExec{}
    42  	_ Executor = &IndexRangeExec{}
    43  	_ Executor = &IndexScanExec{}
    44  	_ Executor = &LimitExec{}
    45  	_ Executor = &SelectFieldsExec{}
    46  	_ Executor = &SelectLockExec{}
    47  	_ Executor = &ShowDDLExec{}
    48  	_ Executor = &SortExec{}
    49  	_ Executor = &TableDualExec{}
    50  	_ Executor = &TableScanExec{}
    51  )
    52  
    53  // Error instances.
    54  var (
    55  	ErrUnknownPlan     = terror.ClassExecutor.New(CodeUnknownPlan, "Unknown plan")
    56  	ErrPrepareMulti    = terror.ClassExecutor.New(CodePrepareMulti, "Can not prepare multiple statements")
    57  	ErrStmtNotFound    = terror.ClassExecutor.New(CodeStmtNotFound, "Prepared statement not found")
    58  	ErrSchemaChanged   = terror.ClassExecutor.New(CodeSchemaChanged, "Schema has changed")
    59  	ErrWrongParamCount = terror.ClassExecutor.New(CodeWrongParamCount, "Wrong parameter count")
    60  )
    61  
    62  // Error codes.
    63  const (
    64  	CodeUnknownPlan     terror.ErrCode = 1
    65  	CodePrepareMulti    terror.ErrCode = 2
    66  	CodeStmtNotFound    terror.ErrCode = 3
    67  	CodeSchemaChanged   terror.ErrCode = 4
    68  	CodeWrongParamCount terror.ErrCode = 5
    69  )
    70  
    71  // Row represents a record row.
    72  type Row struct {
    73  	// Data is the output record data for current Plan.
    74  	Data []types.Datum
    75  
    76  	RowKeys []*RowKeyEntry
    77  }
    78  
    79  // RowKeyEntry is designed for Delete statement in multi-table mode,
    80  // we should know which table this row comes from.
    81  type RowKeyEntry struct {
    82  	// The table which this row come from.
    83  	Tbl table.Table
    84  	// Row key.
    85  	Handle int64
    86  	// Table alias name.
    87  	TableAsName *model.CIStr
    88  }
    89  
    90  // Executor executes a query.
    91  type Executor interface {
    92  	Fields() []*ast.ResultField
    93  	Next() (*Row, error)
    94  	Close() error
    95  }
    96  
    97  // ShowDDLExec represents a show DDL executor.
    98  type ShowDDLExec struct {
    99  	fields []*ast.ResultField
   100  	ctx    context.Context
   101  	done   bool
   102  }
   103  
   104  // Fields implements Executor Fields interface.
   105  func (e *ShowDDLExec) Fields() []*ast.ResultField {
   106  	return e.fields
   107  }
   108  
   109  // Next implements Executor Next interface.
   110  func (e *ShowDDLExec) Next() (*Row, error) {
   111  	if e.done {
   112  		return nil, nil
   113  	}
   114  
   115  	txn, err := e.ctx.GetTxn(false)
   116  	if err != nil {
   117  		return nil, errors.Trace(err)
   118  	}
   119  
   120  	ddlInfo, err := inspectkv.GetDDLInfo(txn)
   121  	if err != nil {
   122  		return nil, errors.Trace(err)
   123  	}
   124  	bgInfo, err := inspectkv.GetBgDDLInfo(txn)
   125  	if err != nil {
   126  		return nil, errors.Trace(err)
   127  	}
   128  
   129  	var ddlOwner, ddlJob string
   130  	if ddlInfo.Owner != nil {
   131  		ddlOwner = ddlInfo.Owner.String()
   132  	}
   133  	if ddlInfo.Job != nil {
   134  		ddlJob = ddlInfo.Job.String()
   135  	}
   136  
   137  	var bgOwner, bgJob string
   138  	if bgInfo.Owner != nil {
   139  		bgOwner = bgInfo.Owner.String()
   140  	}
   141  	if bgInfo.Job != nil {
   142  		bgJob = bgInfo.Job.String()
   143  	}
   144  
   145  	row := &Row{}
   146  	row.Data = types.MakeDatums(
   147  		ddlInfo.SchemaVer,
   148  		ddlOwner,
   149  		ddlJob,
   150  		bgInfo.SchemaVer,
   151  		bgOwner,
   152  		bgJob,
   153  	)
   154  	for i, f := range e.fields {
   155  		f.Expr.SetValue(row.Data[i].GetValue())
   156  	}
   157  	e.done = true
   158  
   159  	return row, nil
   160  }
   161  
   162  // Close implements Executor Close interface.
   163  func (e *ShowDDLExec) Close() error {
   164  	return nil
   165  }
   166  
   167  // CheckTableExec represents a check table executor.
   168  type CheckTableExec struct {
   169  	tables []*ast.TableName
   170  	ctx    context.Context
   171  	done   bool
   172  }
   173  
   174  // Fields implements Executor Fields interface.
   175  func (e *CheckTableExec) Fields() []*ast.ResultField {
   176  	return nil
   177  }
   178  
   179  // Next implements Executor Next interface.
   180  func (e *CheckTableExec) Next() (*Row, error) {
   181  	if e.done {
   182  		return nil, nil
   183  	}
   184  
   185  	dbName := model.NewCIStr(db.GetCurrentSchema(e.ctx))
   186  	is := sessionctx.GetDomain(e.ctx).InfoSchema()
   187  
   188  	for _, t := range e.tables {
   189  		tb, err := is.TableByName(dbName, t.Name)
   190  		if err != nil {
   191  			return nil, errors.Trace(err)
   192  		}
   193  		for _, idx := range tb.Indices() {
   194  			txn, err := e.ctx.GetTxn(false)
   195  			if err != nil {
   196  				return nil, errors.Trace(err)
   197  			}
   198  			err = inspectkv.CompareIndexData(txn, tb, idx)
   199  			if err != nil {
   200  				return nil, errors.Errorf("%v err:%v", t.Name, err)
   201  			}
   202  		}
   203  	}
   204  	e.done = true
   205  
   206  	return nil, nil
   207  }
   208  
   209  // Close implements plan.Plan Close interface.
   210  func (e *CheckTableExec) Close() error {
   211  	return nil
   212  }
   213  
   214  // TableDualExec represents a dual table executor.
   215  type TableDualExec struct {
   216  	fields   []*ast.ResultField
   217  	executed bool
   218  }
   219  
   220  // Fields implements Executor Fields interface.
   221  func (e *TableDualExec) Fields() []*ast.ResultField {
   222  	return e.fields
   223  }
   224  
   225  // Next implements Executor Next interface.
   226  func (e *TableDualExec) Next() (*Row, error) {
   227  	if e.executed {
   228  		return nil, nil
   229  	}
   230  	e.executed = true
   231  	return &Row{}, nil
   232  }
   233  
   234  // Close implements plan.Plan Close interface.
   235  func (e *TableDualExec) Close() error {
   236  	return nil
   237  }
   238  
   239  // TableScanExec represents a table scan executor.
   240  type TableScanExec struct {
   241  	t           table.Table
   242  	tableAsName *model.CIStr
   243  	fields      []*ast.ResultField
   244  	iter        kv.Iterator
   245  	ctx         context.Context
   246  	ranges      []plan.TableRange // Disjoint close handle ranges.
   247  	seekHandle  int64             // The handle to seek, should be initialized to math.MinInt64.
   248  	cursor      int               // The range cursor, used to locate to current range.
   249  }
   250  
   251  // Fields implements Executor Fields interface.
   252  func (e *TableScanExec) Fields() []*ast.ResultField {
   253  	return e.fields
   254  }
   255  
   256  // Next implements Executor Next interface.
   257  func (e *TableScanExec) Next() (*Row, error) {
   258  	for {
   259  		if e.cursor >= len(e.ranges) {
   260  			return nil, nil
   261  		}
   262  		ran := e.ranges[e.cursor]
   263  		if e.seekHandle < ran.LowVal {
   264  			e.seekHandle = ran.LowVal
   265  		}
   266  		if e.seekHandle > ran.HighVal {
   267  			e.cursor++
   268  			continue
   269  		}
   270  		handle, found, err := e.t.Seek(e.ctx, e.seekHandle)
   271  		if err != nil {
   272  			return nil, errors.Trace(err)
   273  		}
   274  		if !found {
   275  			return nil, nil
   276  		}
   277  		if handle > ran.HighVal {
   278  			// The handle is out of the current range, but may be in following ranges.
   279  			// We seek to the range that may contains the handle, so we
   280  			// don't need to seek key again.
   281  			inRange := e.seekRange(handle)
   282  			if !inRange {
   283  				// The handle may be less than the current range low value, can not
   284  				// return directly.
   285  				continue
   286  			}
   287  		}
   288  		row, err := e.getRow(handle)
   289  		if err != nil {
   290  			return nil, errors.Trace(err)
   291  		}
   292  		e.seekHandle = handle + 1
   293  		return row, nil
   294  	}
   295  }
   296  
   297  // seekRange increments the range cursor to the range
   298  // with high value greater or equal to handle.
   299  func (e *TableScanExec) seekRange(handle int64) (inRange bool) {
   300  	for {
   301  		e.cursor++
   302  		if e.cursor >= len(e.ranges) {
   303  			return false
   304  		}
   305  		ran := e.ranges[e.cursor]
   306  		if handle < ran.LowVal {
   307  			return false
   308  		}
   309  		if handle > ran.HighVal {
   310  			continue
   311  		}
   312  		return true
   313  	}
   314  }
   315  
   316  func (e *TableScanExec) getRow(handle int64) (*Row, error) {
   317  	row := &Row{}
   318  	var err error
   319  
   320  	columns := make([]*column.Col, len(e.fields))
   321  	for i, v := range e.fields {
   322  		if v.Referenced {
   323  			columns[i] = e.t.Cols()[i]
   324  		}
   325  	}
   326  	row.Data, err = e.t.RowWithCols(e.ctx, handle, columns)
   327  	if err != nil {
   328  		return nil, errors.Trace(err)
   329  	}
   330  	// Set result fields value.
   331  	for i, v := range e.fields {
   332  		if v.Referenced {
   333  			v.Expr.SetValue(row.Data[i].GetValue())
   334  		}
   335  	}
   336  
   337  	// Put rowKey to the tail of record row
   338  	rke := &RowKeyEntry{
   339  		Tbl:         e.t,
   340  		Handle:      handle,
   341  		TableAsName: e.tableAsName,
   342  	}
   343  	row.RowKeys = append(row.RowKeys, rke)
   344  	return row, nil
   345  }
   346  
   347  // Close implements Executor Close interface.
   348  func (e *TableScanExec) Close() error {
   349  	if e.iter != nil {
   350  		e.iter.Close()
   351  		e.iter = nil
   352  	}
   353  	return nil
   354  }
   355  
   356  // IndexRangeExec represents an index range scan executor.
   357  type IndexRangeExec struct {
   358  	scan *IndexScanExec
   359  
   360  	// seekVal is different from lowVal, it is casted from lowVal and
   361  	// must be less than or equal to lowVal, used to seek the index.
   362  	lowVals     []types.Datum
   363  	lowExclude  bool
   364  	highVals    []types.Datum
   365  	highExclude bool
   366  
   367  	iter       kv.IndexIterator
   368  	skipLowCmp bool
   369  	finished   bool
   370  }
   371  
   372  // Fields implements Executor Fields interface.
   373  func (e *IndexRangeExec) Fields() []*ast.ResultField {
   374  	return e.scan.fields
   375  }
   376  
   377  // Next implements Executor Next interface.
   378  func (e *IndexRangeExec) Next() (*Row, error) {
   379  	if e.iter == nil {
   380  		seekVals := make([]types.Datum, len(e.scan.idx.Columns))
   381  		for i := 0; i < len(e.lowVals); i++ {
   382  			if e.lowVals[i].Kind() == types.KindMinNotNull {
   383  				seekVals[i].SetBytes([]byte{})
   384  			} else {
   385  				val, err := e.lowVals[i].ConvertTo(e.scan.valueTypes[i])
   386  				seekVals[i] = val
   387  				if err != nil {
   388  					return nil, errors.Trace(err)
   389  				}
   390  			}
   391  		}
   392  		txn, err := e.scan.ctx.GetTxn(false)
   393  		if err != nil {
   394  			return nil, errors.Trace(err)
   395  		}
   396  		e.iter, _, err = e.scan.idx.X.Seek(txn, seekVals)
   397  		if err != nil {
   398  			return nil, types.EOFAsNil(err)
   399  		}
   400  	}
   401  
   402  	for {
   403  		if e.finished {
   404  			return nil, nil
   405  		}
   406  		idxKey, h, err := e.iter.Next()
   407  		if err != nil {
   408  			return nil, types.EOFAsNil(err)
   409  		}
   410  		if !e.skipLowCmp {
   411  			var cmp int
   412  			cmp, err = indexCompare(idxKey, e.lowVals)
   413  			if err != nil {
   414  				return nil, errors.Trace(err)
   415  			}
   416  			if cmp < 0 || (cmp == 0 && e.lowExclude) {
   417  				continue
   418  			}
   419  			e.skipLowCmp = true
   420  		}
   421  		cmp, err := indexCompare(idxKey, e.highVals)
   422  		if err != nil {
   423  			return nil, errors.Trace(err)
   424  		}
   425  		if cmp > 0 || (cmp == 0 && e.highExclude) {
   426  			// This span has finished iteration.
   427  			e.finished = true
   428  			continue
   429  		}
   430  		var row *Row
   431  		row, err = e.lookupRow(h)
   432  		if err != nil {
   433  			return nil, errors.Trace(err)
   434  		}
   435  		return row, nil
   436  	}
   437  }
   438  
   439  // indexCompare compares multi column index.
   440  // The length of boundVals may be less than idxKey.
   441  func indexCompare(idxKey []types.Datum, boundVals []types.Datum) (int, error) {
   442  	for i := 0; i < len(boundVals); i++ {
   443  		cmp, err := idxKey[i].CompareDatum(boundVals[i])
   444  		if err != nil {
   445  			return -1, errors.Trace(err)
   446  		}
   447  		if cmp != 0 {
   448  			return cmp, nil
   449  		}
   450  	}
   451  	return 0, nil
   452  }
   453  
   454  func (e *IndexRangeExec) lookupRow(h int64) (*Row, error) {
   455  	row := &Row{}
   456  	var err error
   457  	columns := make([]*column.Col, len(e.scan.fields))
   458  	for i, v := range e.scan.fields {
   459  		if v.Referenced {
   460  			columns[i] = e.scan.tbl.Cols()[i]
   461  		}
   462  	}
   463  	row.Data, err = e.scan.tbl.RowWithCols(e.scan.ctx, h, columns)
   464  	if err != nil {
   465  		return nil, errors.Trace(err)
   466  	}
   467  	rowKey := &RowKeyEntry{
   468  		Tbl:    e.scan.tbl,
   469  		Handle: h,
   470  	}
   471  	row.RowKeys = append(row.RowKeys, rowKey)
   472  	return row, nil
   473  }
   474  
   475  // Close implements Executor Close interface.
   476  func (e *IndexRangeExec) Close() error {
   477  	if e.iter != nil {
   478  		e.iter.Close()
   479  		e.iter = nil
   480  	}
   481  	e.finished = false
   482  	e.skipLowCmp = false
   483  	return nil
   484  }
   485  
   486  // IndexScanExec represents an index scan executor.
   487  type IndexScanExec struct {
   488  	tbl         table.Table
   489  	tableAsName *model.CIStr
   490  	idx         *column.IndexedCol
   491  	fields      []*ast.ResultField
   492  	Ranges      []*IndexRangeExec
   493  	Desc        bool
   494  	rangeIdx    int
   495  	ctx         context.Context
   496  	valueTypes  []*types.FieldType
   497  }
   498  
   499  // Fields implements Executor Fields interface.
   500  func (e *IndexScanExec) Fields() []*ast.ResultField {
   501  	return e.fields
   502  }
   503  
   504  // Next implements Executor Next interface.
   505  func (e *IndexScanExec) Next() (*Row, error) {
   506  	for e.rangeIdx < len(e.Ranges) {
   507  		ran := e.Ranges[e.rangeIdx]
   508  		row, err := ran.Next()
   509  		if err != nil {
   510  			return nil, errors.Trace(err)
   511  		}
   512  		if row != nil {
   513  			for i, val := range row.Data {
   514  				e.fields[i].Expr.SetValue(val.GetValue())
   515  			}
   516  			for _, entry := range row.RowKeys {
   517  				entry.TableAsName = e.tableAsName
   518  			}
   519  			return row, nil
   520  		}
   521  		ran.Close()
   522  		e.rangeIdx++
   523  	}
   524  	return nil, nil
   525  }
   526  
   527  // Close implements Executor Close interface.
   528  func (e *IndexScanExec) Close() error {
   529  	for e.rangeIdx < len(e.Ranges) {
   530  		e.Ranges[e.rangeIdx].Close()
   531  		e.rangeIdx++
   532  	}
   533  	return nil
   534  }
   535  
   536  // JoinOuterExec represents an outer join executor.
   537  type JoinOuterExec struct {
   538  	OuterExec Executor
   539  	InnerPlan plan.Plan
   540  	innerExec Executor
   541  	fields    []*ast.ResultField
   542  	builder   *executorBuilder
   543  	gotRow    bool
   544  }
   545  
   546  // Fields implements Executor Fields interface.
   547  func (e *JoinOuterExec) Fields() []*ast.ResultField {
   548  	return e.fields
   549  }
   550  
   551  // Next implements Executor Next interface.
   552  // The data in the returned row is not used by caller.
   553  // If inner executor didn't get any row for an outer executor row,
   554  // a row with 0 len Data indicates there is no inner row matched for
   555  // an outer row.
   556  func (e *JoinOuterExec) Next() (*Row, error) {
   557  	var rowKeys []*RowKeyEntry
   558  	for {
   559  		if e.innerExec == nil {
   560  			e.gotRow = false
   561  			outerRow, err := e.OuterExec.Next()
   562  			if err != nil {
   563  				return nil, errors.Trace(err)
   564  			}
   565  			if outerRow == nil {
   566  				return nil, nil
   567  			}
   568  			rowKeys = outerRow.RowKeys
   569  			plan.Refine(e.InnerPlan)
   570  			e.innerExec = e.builder.build(e.InnerPlan)
   571  			if e.builder.err != nil {
   572  				return nil, errors.Trace(e.builder.err)
   573  			}
   574  		}
   575  		row, err := e.innerExec.Next()
   576  		if err != nil {
   577  			return nil, errors.Trace(err)
   578  		}
   579  		if row == nil {
   580  			e.innerExec.Close()
   581  			e.innerExec = nil
   582  			if e.gotRow {
   583  				continue
   584  			}
   585  			e.setInnerNull()
   586  			return &Row{RowKeys: rowKeys}, nil
   587  		}
   588  		if len(row.Data) != 0 {
   589  			e.gotRow = true
   590  			row.RowKeys = append(rowKeys, row.RowKeys...)
   591  			return row, nil
   592  		}
   593  	}
   594  }
   595  
   596  func (e *JoinOuterExec) setInnerNull() {
   597  	for _, rf := range e.InnerPlan.Fields() {
   598  		rf.Expr.SetValue(nil)
   599  	}
   600  }
   601  
   602  // Close implements Executor Close interface.
   603  func (e *JoinOuterExec) Close() error {
   604  	err := e.OuterExec.Close()
   605  	if e.innerExec != nil {
   606  		return errors.Trace(e.innerExec.Close())
   607  	}
   608  	return errors.Trace(err)
   609  }
   610  
   611  // JoinInnerExec represents an inner join executor.
   612  type JoinInnerExec struct {
   613  	InnerPlans []plan.Plan
   614  	innerExecs []Executor
   615  	Condition  ast.ExprNode
   616  	ctx        context.Context
   617  	fields     []*ast.ResultField
   618  	builder    *executorBuilder
   619  	done       bool
   620  	cursor     int
   621  }
   622  
   623  // Fields implements Executor Fields interface.
   624  func (e *JoinInnerExec) Fields() []*ast.ResultField {
   625  	return e.fields
   626  }
   627  
   628  // Next implements Executor Next interface.
   629  // The data in the returned row is not used by caller.
   630  func (e *JoinInnerExec) Next() (*Row, error) {
   631  	if e.done {
   632  		return nil, nil
   633  	}
   634  	rowKeysSlice := make([][]*RowKeyEntry, len(e.InnerPlans))
   635  	for {
   636  		exec := e.innerExecs[e.cursor]
   637  		if exec == nil {
   638  			innerPlan := e.InnerPlans[e.cursor]
   639  			plan.Refine(innerPlan)
   640  			exec = e.builder.build(innerPlan)
   641  			if e.builder.err != nil {
   642  				return nil, errors.Trace(e.builder.err)
   643  			}
   644  			e.innerExecs[e.cursor] = exec
   645  		}
   646  		row, err := exec.Next()
   647  		if err != nil {
   648  			return nil, errors.Trace(err)
   649  		}
   650  		if row == nil {
   651  			exec.Close()
   652  			e.innerExecs[e.cursor] = nil
   653  			if e.cursor == 0 {
   654  				e.done = true
   655  				return nil, nil
   656  			}
   657  			e.cursor--
   658  			continue
   659  		}
   660  		rowKeysSlice[e.cursor] = row.RowKeys
   661  		if e.cursor < len(e.innerExecs)-1 {
   662  			e.cursor++
   663  			continue
   664  		}
   665  
   666  		var match = true
   667  		if e.Condition != nil {
   668  			match, err = evaluator.EvalBool(e.ctx, e.Condition)
   669  			if err != nil {
   670  				return nil, errors.Trace(err)
   671  			}
   672  		}
   673  		if match {
   674  			row.RowKeys = joinRowKeys(rowKeysSlice)
   675  			return row, nil
   676  		}
   677  	}
   678  }
   679  
   680  func joinRowKeys(rowKeysSlice [][]*RowKeyEntry) []*RowKeyEntry {
   681  	count := 0
   682  	for _, rowKeys := range rowKeysSlice {
   683  		count += len(rowKeys)
   684  	}
   685  	joined := make([]*RowKeyEntry, count)
   686  	offset := 0
   687  	for _, rowKeys := range rowKeysSlice {
   688  		copy(joined[offset:], rowKeys)
   689  		offset += len(rowKeys)
   690  	}
   691  	return joined
   692  }
   693  
   694  // Close implements Executor Close interface.
   695  func (e *JoinInnerExec) Close() error {
   696  	var err error
   697  	for _, inExec := range e.innerExecs {
   698  		if inExec != nil {
   699  			e := inExec.Close()
   700  			if e != nil {
   701  				err = errors.Trace(e)
   702  			}
   703  		}
   704  	}
   705  	return err
   706  }
   707  
   708  // SelectFieldsExec represents a select fields executor.
   709  type SelectFieldsExec struct {
   710  	Src          Executor
   711  	ResultFields []*ast.ResultField
   712  	executed     bool
   713  	ctx          context.Context
   714  }
   715  
   716  // Fields implements Executor Fields interface.
   717  func (e *SelectFieldsExec) Fields() []*ast.ResultField {
   718  	return e.ResultFields
   719  }
   720  
   721  // Next implements Executor Next interface.
   722  func (e *SelectFieldsExec) Next() (*Row, error) {
   723  	var rowKeys []*RowKeyEntry
   724  	if e.Src != nil {
   725  		srcRow, err := e.Src.Next()
   726  		if err != nil {
   727  			return nil, errors.Trace(err)
   728  		}
   729  		if srcRow == nil {
   730  			return nil, nil
   731  		}
   732  		rowKeys = srcRow.RowKeys
   733  	} else {
   734  		// If Src is nil, only one row should be returned.
   735  		if e.executed {
   736  			return nil, nil
   737  		}
   738  	}
   739  	e.executed = true
   740  	row := &Row{
   741  		RowKeys: rowKeys,
   742  		Data:    make([]types.Datum, len(e.ResultFields)),
   743  	}
   744  	for i, field := range e.ResultFields {
   745  		val, err := evaluator.Eval(e.ctx, field.Expr)
   746  		if err != nil {
   747  			return nil, errors.Trace(err)
   748  		}
   749  		row.Data[i] = val
   750  	}
   751  	return row, nil
   752  }
   753  
   754  // Close implements Executor Close interface.
   755  func (e *SelectFieldsExec) Close() error {
   756  	if e.Src != nil {
   757  		return e.Src.Close()
   758  	}
   759  	return nil
   760  }
   761  
   762  // FilterExec represents a filter executor.
   763  type FilterExec struct {
   764  	Src       Executor
   765  	Condition ast.ExprNode
   766  	ctx       context.Context
   767  }
   768  
   769  // Fields implements Executor Fields interface.
   770  func (e *FilterExec) Fields() []*ast.ResultField {
   771  	return e.Src.Fields()
   772  }
   773  
   774  // Next implements Executor Next interface.
   775  func (e *FilterExec) Next() (*Row, error) {
   776  	for {
   777  		srcRow, err := e.Src.Next()
   778  		if err != nil {
   779  			return nil, errors.Trace(err)
   780  		}
   781  		if srcRow == nil {
   782  			return nil, nil
   783  		}
   784  		match, err := evaluator.EvalBool(e.ctx, e.Condition)
   785  		if err != nil {
   786  			return nil, errors.Trace(err)
   787  		}
   788  		if match {
   789  			return srcRow, nil
   790  		}
   791  	}
   792  }
   793  
   794  // Close implements Executor Close interface.
   795  func (e *FilterExec) Close() error {
   796  	return e.Src.Close()
   797  }
   798  
   799  // SelectLockExec represents a select lock executor.
   800  type SelectLockExec struct {
   801  	Src  Executor
   802  	Lock ast.SelectLockType
   803  	ctx  context.Context
   804  }
   805  
   806  // Fields implements Executor Fields interface.
   807  func (e *SelectLockExec) Fields() []*ast.ResultField {
   808  	return e.Src.Fields()
   809  }
   810  
   811  // Next implements Executor Next interface.
   812  func (e *SelectLockExec) Next() (*Row, error) {
   813  	row, err := e.Src.Next()
   814  	if err != nil {
   815  		return nil, errors.Trace(err)
   816  	}
   817  	if row == nil {
   818  		return nil, nil
   819  	}
   820  	if len(row.RowKeys) != 0 && e.Lock == ast.SelectLockForUpdate {
   821  		forupdate.SetForUpdate(e.ctx)
   822  		for _, k := range row.RowKeys {
   823  			err = k.Tbl.LockRow(e.ctx, k.Handle, true)
   824  			if err != nil {
   825  				return nil, errors.Trace(err)
   826  			}
   827  		}
   828  	}
   829  	return row, nil
   830  }
   831  
   832  // Close implements Executor Close interface.
   833  func (e *SelectLockExec) Close() error {
   834  	return e.Src.Close()
   835  }
   836  
   837  // LimitExec represents limit executor
   838  type LimitExec struct {
   839  	Src    Executor
   840  	Offset uint64
   841  	Count  uint64
   842  	Idx    uint64
   843  }
   844  
   845  // Fields implements Executor Fields interface.
   846  func (e *LimitExec) Fields() []*ast.ResultField {
   847  	return e.Src.Fields()
   848  }
   849  
   850  // Next implements Executor Next interface.
   851  func (e *LimitExec) Next() (*Row, error) {
   852  	for e.Idx < e.Offset {
   853  		srcRow, err := e.Src.Next()
   854  		if err != nil {
   855  			return nil, errors.Trace(err)
   856  		}
   857  		if srcRow == nil {
   858  			return nil, nil
   859  		}
   860  		e.Idx++
   861  	}
   862  	if e.Idx >= e.Count+e.Offset {
   863  		return nil, nil
   864  	}
   865  	srcRow, err := e.Src.Next()
   866  	if err != nil {
   867  		return nil, errors.Trace(err)
   868  	}
   869  	if srcRow == nil {
   870  		return nil, nil
   871  	}
   872  	e.Idx++
   873  	return srcRow, nil
   874  }
   875  
   876  // Close implements Executor Close interface.
   877  func (e *LimitExec) Close() error {
   878  	return e.Src.Close()
   879  }
   880  
   881  // orderByRow binds a row to its order values, so it can be sorted.
   882  type orderByRow struct {
   883  	key []types.Datum
   884  	row *Row
   885  }
   886  
   887  // SortExec represents sorting executor.
   888  type SortExec struct {
   889  	Src     Executor
   890  	ByItems []*ast.ByItem
   891  	Rows    []*orderByRow
   892  	ctx     context.Context
   893  	Limit   *plan.Limit
   894  	Idx     int
   895  	fetched bool
   896  	err     error
   897  }
   898  
   899  // Fields implements Executor Fields interface.
   900  func (e *SortExec) Fields() []*ast.ResultField {
   901  	return e.Src.Fields()
   902  }
   903  
   904  // Len returns the number of rows.
   905  func (e *SortExec) Len() int {
   906  	return len(e.Rows)
   907  }
   908  
   909  // Swap implements sort.Interface Swap interface.
   910  func (e *SortExec) Swap(i, j int) {
   911  	e.Rows[i], e.Rows[j] = e.Rows[j], e.Rows[i]
   912  }
   913  
   914  // Less implements sort.Interface Less interface.
   915  func (e *SortExec) Less(i, j int) bool {
   916  	for index, by := range e.ByItems {
   917  		v1 := e.Rows[i].key[index]
   918  		v2 := e.Rows[j].key[index]
   919  
   920  		ret, err := v1.CompareDatum(v2)
   921  		if err != nil {
   922  			e.err = err
   923  			return true
   924  		}
   925  
   926  		if by.Desc {
   927  			ret = -ret
   928  		}
   929  
   930  		if ret < 0 {
   931  			return true
   932  		} else if ret > 0 {
   933  			return false
   934  		}
   935  	}
   936  
   937  	return false
   938  }
   939  
   940  // SortBufferSize represents the total extra row count that sort can use.
   941  var SortBufferSize = 500
   942  
   943  // Next implements Executor Next interface.
   944  func (e *SortExec) Next() (*Row, error) {
   945  	if !e.fetched {
   946  		offset := -1
   947  		totalCount := -1
   948  		if e.Limit != nil {
   949  			offset = int(e.Limit.Offset)
   950  			totalCount = offset + int(e.Limit.Count)
   951  		}
   952  		for {
   953  			srcRow, err := e.Src.Next()
   954  			if err != nil {
   955  				return nil, errors.Trace(err)
   956  			}
   957  			if srcRow == nil {
   958  				break
   959  			}
   960  			orderRow := &orderByRow{
   961  				row: srcRow,
   962  				key: make([]types.Datum, len(e.ByItems)),
   963  			}
   964  			for i, byItem := range e.ByItems {
   965  				orderRow.key[i], err = evaluator.Eval(e.ctx, byItem.Expr)
   966  				if err != nil {
   967  					return nil, errors.Trace(err)
   968  				}
   969  			}
   970  			e.Rows = append(e.Rows, orderRow)
   971  			if totalCount != -1 && e.Len() >= totalCount+SortBufferSize {
   972  				sort.Sort(e)
   973  				e.Rows = e.Rows[:totalCount]
   974  			}
   975  		}
   976  		sort.Sort(e)
   977  		if offset >= 0 && offset < e.Len() {
   978  			if totalCount > e.Len() {
   979  				e.Rows = e.Rows[offset:]
   980  			} else {
   981  				e.Rows = e.Rows[offset:totalCount]
   982  			}
   983  		} else if offset != -1 {
   984  			e.Rows = e.Rows[:0]
   985  		}
   986  		e.fetched = true
   987  	}
   988  	if e.err != nil {
   989  		return nil, errors.Trace(e.err)
   990  	}
   991  	if e.Idx >= len(e.Rows) {
   992  		return nil, nil
   993  	}
   994  	row := e.Rows[e.Idx].row
   995  	e.Idx++
   996  	return row, nil
   997  }
   998  
   999  // Close implements Executor Close interface.
  1000  func (e *SortExec) Close() error {
  1001  	return e.Src.Close()
  1002  }
  1003  
  1004  // For select stmt with aggregate function but without groupby clasue,
  1005  // We consider there is a single group with key singleGroup.
  1006  const singleGroup = "SingleGroup"
  1007  
  1008  // AggregateExec deals with all the aggregate functions.
  1009  // It is built from Aggregate Plan. When Next() is called, it reads all the data from Src and updates all the items in AggFuncs.
  1010  // TODO: Support having.
  1011  type AggregateExec struct {
  1012  	Src               Executor
  1013  	ResultFields      []*ast.ResultField
  1014  	executed          bool
  1015  	ctx               context.Context
  1016  	finish            bool
  1017  	AggFuncs          []*ast.AggregateFuncExpr
  1018  	groupMap          map[string]bool
  1019  	groups            []string
  1020  	currentGroupIndex int
  1021  	GroupByItems      []*ast.ByItem
  1022  }
  1023  
  1024  // Fields implements Executor Fields interface.
  1025  func (e *AggregateExec) Fields() []*ast.ResultField {
  1026  	return e.ResultFields
  1027  }
  1028  
  1029  // Next implements Executor Next interface.
  1030  func (e *AggregateExec) Next() (*Row, error) {
  1031  	// In this stage we consider all data from src as a single group.
  1032  	if !e.executed {
  1033  		e.groupMap = make(map[string]bool)
  1034  		e.groups = []string{}
  1035  		for {
  1036  			hasMore, err := e.innerNext()
  1037  			if err != nil {
  1038  				return nil, errors.Trace(err)
  1039  			}
  1040  			if !hasMore {
  1041  				break
  1042  			}
  1043  		}
  1044  		e.executed = true
  1045  		if (len(e.groups) == 0) && (len(e.GroupByItems) == 0) {
  1046  			// If no groupby and no data, we should add an empty group.
  1047  			// For example:
  1048  			// "select count(c) from t;" should return one row [0]
  1049  			// "select count(c) from t group by c1;" should return empty result set.
  1050  			e.groups = append(e.groups, singleGroup)
  1051  		}
  1052  	}
  1053  	if e.currentGroupIndex >= len(e.groups) {
  1054  		return nil, nil
  1055  	}
  1056  	groupKey := e.groups[e.currentGroupIndex]
  1057  	for _, af := range e.AggFuncs {
  1058  		af.CurrentGroup = groupKey
  1059  	}
  1060  	e.currentGroupIndex++
  1061  	return &Row{}, nil
  1062  }
  1063  
  1064  func (e *AggregateExec) getGroupKey() (string, error) {
  1065  	if len(e.GroupByItems) == 0 {
  1066  		return singleGroup, nil
  1067  	}
  1068  	vals := make([]types.Datum, 0, len(e.GroupByItems))
  1069  	for _, item := range e.GroupByItems {
  1070  		v, err := evaluator.Eval(e.ctx, item.Expr)
  1071  		if err != nil {
  1072  			return "", errors.Trace(err)
  1073  		}
  1074  		vals = append(vals, v)
  1075  	}
  1076  	bs, err := codec.EncodeValue([]byte{}, vals...)
  1077  	if err != nil {
  1078  		return "", errors.Trace(err)
  1079  	}
  1080  	return string(bs), nil
  1081  }
  1082  
  1083  // Fetch a single row from src and update each aggregate function.
  1084  // If the first return value is false, it means there is no more data from src.
  1085  func (e *AggregateExec) innerNext() (bool, error) {
  1086  	if e.Src != nil {
  1087  		srcRow, err := e.Src.Next()
  1088  		if err != nil {
  1089  			return false, errors.Trace(err)
  1090  		}
  1091  		if srcRow == nil {
  1092  			return false, nil
  1093  		}
  1094  	} else {
  1095  		// If Src is nil, only one row should be returned.
  1096  		if e.executed {
  1097  			return false, nil
  1098  		}
  1099  	}
  1100  	e.executed = true
  1101  	groupKey, err := e.getGroupKey()
  1102  	if err != nil {
  1103  		return false, errors.Trace(err)
  1104  	}
  1105  	if _, ok := e.groupMap[groupKey]; !ok {
  1106  		e.groupMap[groupKey] = true
  1107  		e.groups = append(e.groups, groupKey)
  1108  	}
  1109  	for _, af := range e.AggFuncs {
  1110  		for _, arg := range af.Args {
  1111  			_, err := evaluator.Eval(e.ctx, arg)
  1112  			if err != nil {
  1113  				return false, errors.Trace(err)
  1114  			}
  1115  		}
  1116  		af.CurrentGroup = groupKey
  1117  		af.Update()
  1118  	}
  1119  	return true, nil
  1120  }
  1121  
  1122  // Close implements Executor Close interface.
  1123  func (e *AggregateExec) Close() error {
  1124  	for _, af := range e.AggFuncs {
  1125  		af.Clear()
  1126  	}
  1127  	if e.Src != nil {
  1128  		return e.Src.Close()
  1129  	}
  1130  	return nil
  1131  }
  1132  
  1133  // UnionExec represents union executor.
  1134  type UnionExec struct {
  1135  	fields []*ast.ResultField
  1136  	Sels   []Executor
  1137  	cursor int
  1138  }
  1139  
  1140  // Fields implements Executor Fields interface.
  1141  func (e *UnionExec) Fields() []*ast.ResultField {
  1142  	return e.fields
  1143  }
  1144  
  1145  // Next implements Executor Next interface.
  1146  func (e *UnionExec) Next() (*Row, error) {
  1147  	for {
  1148  		if e.cursor >= len(e.Sels) {
  1149  			return nil, nil
  1150  		}
  1151  		sel := e.Sels[e.cursor]
  1152  		row, err := sel.Next()
  1153  		if err != nil {
  1154  			return nil, errors.Trace(err)
  1155  		}
  1156  		if row == nil {
  1157  			e.cursor++
  1158  			continue
  1159  		}
  1160  		if e.cursor != 0 {
  1161  			for i := range row.Data {
  1162  				// The column value should be casted as the same type of the first select statement in corresponding position
  1163  				rf := e.fields[i]
  1164  				var val types.Datum
  1165  				val, err = row.Data[i].ConvertTo(&rf.Column.FieldType)
  1166  				if err != nil {
  1167  					return nil, errors.Trace(err)
  1168  				}
  1169  				row.Data[i] = val
  1170  			}
  1171  		}
  1172  		for i, v := range row.Data {
  1173  			e.fields[i].Expr.SetValue(v.GetValue())
  1174  		}
  1175  		return row, nil
  1176  	}
  1177  }
  1178  
  1179  // Close implements Executor Close interface.
  1180  func (e *UnionExec) Close() error {
  1181  	var err error
  1182  	for _, sel := range e.Sels {
  1183  		er := sel.Close()
  1184  		if er != nil {
  1185  			err = errors.Trace(er)
  1186  		}
  1187  	}
  1188  	return err
  1189  }
  1190  
  1191  // DistinctExec represents Distinct executor.
  1192  type DistinctExec struct {
  1193  	Src     Executor
  1194  	checker *distinct.Checker
  1195  }
  1196  
  1197  // Fields implements Executor Fields interface.
  1198  func (e *DistinctExec) Fields() []*ast.ResultField {
  1199  	return e.Src.Fields()
  1200  }
  1201  
  1202  // Next implements Executor Next interface.
  1203  func (e *DistinctExec) Next() (*Row, error) {
  1204  	if e.checker == nil {
  1205  		e.checker = distinct.CreateDistinctChecker()
  1206  	}
  1207  	for {
  1208  		row, err := e.Src.Next()
  1209  		if err != nil {
  1210  			return nil, errors.Trace(err)
  1211  		}
  1212  		if row == nil {
  1213  			return nil, nil
  1214  		}
  1215  		ok, err := e.checker.Check(types.DatumsToInterfaces(row.Data))
  1216  		if err != nil {
  1217  			return nil, errors.Trace(err)
  1218  		}
  1219  		if !ok {
  1220  			continue
  1221  		}
  1222  		return row, nil
  1223  	}
  1224  }
  1225  
  1226  // Close implements Executor Close interface.
  1227  func (e *DistinctExec) Close() error {
  1228  	return e.Src.Close()
  1229  }
  1230  
  1231  // ReverseExec produces reverse ordered result, it is used to wrap executors that do not support reverse scan.
  1232  type ReverseExec struct {
  1233  	Src    Executor
  1234  	rows   []*Row
  1235  	cursor int
  1236  	done   bool
  1237  }
  1238  
  1239  // Fields implements Executor Fields interface.
  1240  func (e *ReverseExec) Fields() []*ast.ResultField {
  1241  	return e.Src.Fields()
  1242  }
  1243  
  1244  // Next implements Executor Next interface.
  1245  func (e *ReverseExec) Next() (*Row, error) {
  1246  	if !e.done {
  1247  		for {
  1248  			row, err := e.Src.Next()
  1249  			if err != nil {
  1250  				return nil, errors.Trace(err)
  1251  			}
  1252  			if row == nil {
  1253  				break
  1254  			}
  1255  			e.rows = append(e.rows, row)
  1256  		}
  1257  		e.cursor = len(e.rows) - 1
  1258  		e.done = true
  1259  	}
  1260  	if e.cursor < 0 {
  1261  		return nil, nil
  1262  	}
  1263  	row := e.rows[e.cursor]
  1264  	e.cursor--
  1265  	for i, field := range e.Src.Fields() {
  1266  		field.Expr.SetDatum(row.Data[i])
  1267  	}
  1268  	return row, nil
  1269  }
  1270  
  1271  // Close implements Executor Close interface.
  1272  func (e *ReverseExec) Close() error {
  1273  	return e.Src.Close()
  1274  }