diff --git a/pkg/sql/conn_executor_exec.go b/pkg/sql/conn_executor_exec.go index 9e6e4b02a1b2..af5da5a4dcca 100644 --- a/pkg/sql/conn_executor_exec.go +++ b/pkg/sql/conn_executor_exec.go @@ -279,9 +279,6 @@ func (ex *connExecutor) execStmtInOpenState( ast := parserStmt.AST ctx = withStatement(ctx, ast) - var cancelQuery context.CancelFunc - ctx, cancelQuery = contextutil.WithCancel(ctx) - makeErrEvent := func(err error) (fsm.Event, fsm.EventPayload, error) { ev, payload := ex.makeErrEvent(err, ast) return ev, payload, nil @@ -327,10 +324,9 @@ func (ex *connExecutor) execStmtInOpenState( ex.planner.EvalContext().Placeholders = pinfo } + var cancelQuery context.CancelFunc + ctx, cancelQuery = contextutil.WithCancel(ctx) ex.addActiveQuery(ast, formatWithPlaceholders(ast, ex.planner.EvalContext()), queryID, cancelQuery) - if ex.executorType != executorTypeInternal { - ex.metrics.EngineMetrics.SQLActiveStatements.Inc(1) - } // Make sure that we always unregister the query. It also deals with // overwriting res.Error to a more user-friendly message in case of query @@ -343,10 +339,6 @@ func (ex *connExecutor) execStmtInOpenState( <-doneAfterFunc } } - ex.removeActiveQuery(queryID, ast) - if ex.executorType != executorTypeInternal { - ex.metrics.EngineMetrics.SQLActiveStatements.Dec(1) - } // Detect context cancelation and overwrite whatever error might have been // set on the result before. The idea is that once the query's context is @@ -365,6 +357,12 @@ func (ex *connExecutor) execStmtInOpenState( retPayload = eventNonRetriableErrPayload{err: cancelchecker.QueryCanceledError} } + ex.removeActiveQuery(queryID, ast) + cancelQuery() + if ex.executorType != executorTypeInternal { + ex.metrics.EngineMetrics.SQLActiveStatements.Dec(1) + } + // If the query timed out, we intercept the error, payload, and event here // for the same reasons we intercept them for canceled queries above. // Overriding queries with a QueryTimedOut error needs to happen after @@ -386,6 +384,10 @@ func (ex *connExecutor) execStmtInOpenState( } }(ctx, res) + if ex.executorType != executorTypeInternal { + ex.metrics.EngineMetrics.SQLActiveStatements.Inc(1) + } + p := &ex.planner stmtTS := ex.server.cfg.Clock.PhysicalTime() ex.statsCollector.Reset(ex.applicationStats, ex.phaseTimes) @@ -505,7 +507,7 @@ func (ex *connExecutor) execStmtInOpenState( timeoutTicker = time.AfterFunc( timerDuration, func() { - ex.cancelQuery(queryID) + cancelQuery() queryTimedOut = true doneAfterFunc <- struct{}{} })