-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
conn_executor_exec.go
2934 lines (2715 loc) · 107 KB
/
conn_executor_exec.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package sql
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"runtime/pprof"
"strings"
"time"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/multitenant"
"github.com/cockroachdb/cockroach/pkg/multitenant/multitenantcpu"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/appstatspb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descs"
"github.com/cockroachdb/cockroach/pkg/sql/clusterunique"
"github.com/cockroachdb/cockroach/pkg/sql/contentionpb"
"github.com/cockroachdb/cockroach/pkg/sql/execinfra"
"github.com/cockroachdb/cockroach/pkg/sql/execstats"
"github.com/cockroachdb/cockroach/pkg/sql/isql"
"github.com/cockroachdb/cockroach/pkg/sql/opt/exec/explain"
"github.com/cockroachdb/cockroach/pkg/sql/paramparse"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/physicalplan"
"github.com/cockroachdb/cockroach/pkg/sql/sem/asof"
"github.com/cockroachdb/cockroach/pkg/sql/sem/eval"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondatapb"
"github.com/cockroachdb/cockroach/pkg/sql/sessionphase"
"github.com/cockroachdb/cockroach/pkg/sql/sqlerrors"
"github.com/cockroachdb/cockroach/pkg/sql/sqlstats"
"github.com/cockroachdb/cockroach/pkg/sql/sqltelemetry"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/buildutil"
"github.com/cockroachdb/cockroach/pkg/util/cancelchecker"
"github.com/cockroachdb/cockroach/pkg/util/contextutil"
"github.com/cockroachdb/cockroach/pkg/util/duration"
"github.com/cockroachdb/cockroach/pkg/util/fsm"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/log/eventpb"
"github.com/cockroachdb/cockroach/pkg/util/log/logpb"
"github.com/cockroachdb/cockroach/pkg/util/metric"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/cockroach/pkg/util/tracing/tracingpb"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/redact"
"github.com/lib/pq/oid"
"go.opentelemetry.io/otel/attribute"
)
// numTxnRetryErrors is the number of times an error will be injected if
// the transaction is retried using SAVEPOINTs.
const numTxnRetryErrors = 3
// execStmt executes one statement by dispatching according to the current
// state. Returns an Event to be passed to the state machine, or nil if no
// transition is needed. If nil is returned, then the cursor is supposed to
// advance to the next statement.
//
// If an error is returned, the session is supposed to be considered done. Query
// execution errors are not returned explicitly and they're also not
// communicated to the client. Instead they're incorporated in the returned
// event (the returned payload will implement payloadWithError). It is the
// caller's responsibility to deliver execution errors to the client.
//
// Args:
// stmt: The statement to execute.
// res: Used to produce query results.
// pinfo: The values to use for the statement's placeholders. If nil is passed,
//
// then the statement cannot have any placeholder.
func (ex *connExecutor) execStmt(
ctx context.Context,
parserStmt parser.Statement,
portal *PreparedPortal,
pinfo *tree.PlaceholderInfo,
res RestrictedCommandResult,
canAutoCommit bool,
) (fsm.Event, fsm.EventPayload, error) {
ast := parserStmt.AST
if log.V(2) || logStatementsExecuteEnabled.Get(&ex.server.cfg.Settings.SV) ||
log.HasSpanOrEvent(ctx) {
log.VEventf(ctx, 2, "executing: %s in state: %s", ast, ex.machine.CurState())
}
// Stop the session idle timeout when a new statement is executed.
ex.mu.IdleInSessionTimeout.Stop()
ex.mu.IdleInTransactionSessionTimeout.Stop()
// Run observer statements in a separate code path; their execution does not
// depend on the current transaction state.
if _, ok := ast.(tree.ObserverStatement); ok {
ex.statsCollector.Reset(ex.applicationStats, ex.phaseTimes)
err := ex.runObserverStatement(ctx, ast, res)
// Note that regardless of res.Err(), these observer statements don't
// generate error events; transactions are always allowed to continue.
return nil, nil, err
}
// Dispatch the statement for execution based on the current state.
var ev fsm.Event
var payload fsm.EventPayload
var err error
switch ex.machine.CurState().(type) {
case stateNoTxn:
// Note: when not using explicit transactions, we go through this transition
// for every statement. It is important to minimize the amount of work and
// allocations performed up to this point.
ev, payload = ex.execStmtInNoTxnState(ctx, ast, res)
case stateOpen:
var preparedStmt *PreparedStatement
if portal != nil {
preparedStmt = portal.Stmt
}
err = ex.execWithProfiling(ctx, ast, preparedStmt, func(ctx context.Context) error {
ev, payload, err = ex.execStmtInOpenState(ctx, parserStmt, portal, pinfo, res, canAutoCommit)
return err
})
switch ev.(type) {
case eventNonRetriableErr:
ex.recordFailure()
}
case stateAborted:
ev, payload = ex.execStmtInAbortedState(ctx, ast, res)
case stateCommitWait:
ev, payload = ex.execStmtInCommitWaitState(ctx, ast, res)
default:
panic(errors.AssertionFailedf("unexpected txn state: %#v", ex.machine.CurState()))
}
if ex.sessionData().IdleInSessionTimeout > 0 {
// Cancel the session if the idle time exceeds the idle in session timeout.
ex.mu.IdleInSessionTimeout = timeout{time.AfterFunc(
ex.sessionData().IdleInSessionTimeout,
ex.CancelSession,
)}
}
if ex.sessionData().IdleInTransactionSessionTimeout > 0 {
startIdleInTransactionSessionTimeout := func() {
switch ast.(type) {
case *tree.CommitTransaction, *tree.RollbackTransaction:
// Do nothing, the transaction is completed, we do not want to start
// an idle timer.
default:
ex.mu.IdleInTransactionSessionTimeout = timeout{time.AfterFunc(
ex.sessionData().IdleInTransactionSessionTimeout,
ex.CancelSession,
)}
}
}
switch ex.machine.CurState().(type) {
case stateAborted, stateCommitWait:
startIdleInTransactionSessionTimeout()
case stateOpen:
// Only start timeout if the statement is executed in an
// explicit transaction.
if !ex.implicitTxn() {
startIdleInTransactionSessionTimeout()
}
}
}
return ev, payload, err
}
func (ex *connExecutor) recordFailure() {
ex.metrics.EngineMetrics.FailureCount.Inc(1)
}
// execPortal executes a prepared statement. It is a "wrapper" around execStmt
// method that is performing additional work to track portal's state.
func (ex *connExecutor) execPortal(
ctx context.Context,
portal PreparedPortal,
portalName string,
stmtRes CommandResult,
pinfo *tree.PlaceholderInfo,
canAutoCommit bool,
) (ev fsm.Event, payload fsm.EventPayload, err error) {
defer func() {
if portal.isPausable() {
if !portal.pauseInfo.exhaustPortal.isComplete {
portal.pauseInfo.exhaustPortal.appendFunc(namedFunc{fName: "exhaust portal", f: func() {
ex.exhaustPortal(portalName)
}})
portal.pauseInfo.exhaustPortal.isComplete = true
}
// If we encountered an error when executing a pausable portal, clean up
// the retained resources.
if err != nil {
portal.pauseInfo.cleanupAll()
}
}
}()
switch ex.machine.CurState().(type) {
case stateOpen:
// We're about to execute the statement in an open state which
// could trigger the dispatch to the execution engine. However, it
// is possible that we're trying to execute an already exhausted
// portal - in such a scenario we should return no rows, but the
// execution engine is not aware of that and would run the
// statement as if it was running it for the first time. In order
// to prevent such behavior, we check whether the portal has been
// exhausted and execute the statement only if it hasn't. If it has
// been exhausted, then we do not dispatch the query for execution,
// but connExecutor will still perform necessary state transitions
// which will emit CommandComplete messages and alike (in a sense,
// by not calling execStmt we "execute" the portal in such a way
// that it returns 0 rows).
// Note that here we deviate from Postgres which returns an error
// when attempting to execute an exhausted portal which has a
// StatementReturnType() different from "Rows".
if portal.exhausted {
return nil, nil, nil
}
ev, payload, err = ex.execStmt(ctx, portal.Stmt.Statement, &portal, pinfo, stmtRes, canAutoCommit)
// For a non-pausable portal, it is considered exhausted regardless of the
// fact whether an error occurred or not - if it did, we still don't want
// to re-execute the portal from scratch.
// The current statement may have just closed and deleted the portal,
// so only exhaust it if it still exists.
if _, ok := ex.extraTxnState.prepStmtsNamespace.portals[portalName]; ok && !portal.isPausable() {
defer ex.exhaustPortal(portalName)
}
return ev, payload, err
default:
return ex.execStmt(ctx, portal.Stmt.Statement, &portal, pinfo, stmtRes, canAutoCommit)
}
}
// execStmtInOpenState executes one statement in the context of the session's
// current transaction.
// It handles statements that affect the transaction state (BEGIN, COMMIT)
// directly and delegates everything else to the execution engines.
// Results and query execution errors are written to res.
//
// This method also handles "auto commit" - committing of implicit transactions.
//
// If an error is returned, the connection is supposed to be consider done.
// Query execution errors are not returned explicitly; they're incorporated in
// the returned Event.
//
// The returned event can be nil if no state transition is required.
func (ex *connExecutor) execStmtInOpenState(
ctx context.Context,
parserStmt parser.Statement,
portal *PreparedPortal,
pinfo *tree.PlaceholderInfo,
res RestrictedCommandResult,
canAutoCommit bool,
) (retEv fsm.Event, retPayload fsm.EventPayload, retErr error) {
isPausablePortal := portal != nil && portal.isPausable()
// For pausable portals, we delay the clean-up until closing the portal by
// adding the function to the execStmtInOpenStateCleanup.
// Otherwise, perform the clean-up step within every execution.
processCleanupFunc := func(fName string, f func()) {
if !isPausablePortal {
f()
} else if !portal.pauseInfo.execStmtInOpenStateCleanup.isComplete {
portal.pauseInfo.execStmtInOpenStateCleanup.appendFunc(namedFunc{
fName: fName,
f: f,
})
}
}
defer func() {
// This is the first defer, so it will always be called after any cleanup
// func being added to the stack from the defers below.
if isPausablePortal && !portal.pauseInfo.execStmtInOpenStateCleanup.isComplete {
portal.pauseInfo.execStmtInOpenStateCleanup.isComplete = true
}
// If there's any error, do the cleanup right here.
if (retErr != nil || payloadHasError(retPayload)) && isPausablePortal {
portal.pauseInfo.flowCleanup.run()
portal.pauseInfo.dispatchToExecEngCleanup.run()
portal.pauseInfo.execStmtInOpenStateCleanup.run()
}
}()
ast := parserStmt.AST
var sp *tracing.Span
if !isPausablePortal || !portal.pauseInfo.execStmtInOpenStateCleanup.isComplete {
ctx, sp = tracing.EnsureChildSpan(ctx, ex.server.cfg.AmbientCtx.Tracer, "sql query")
// TODO(andrei): Consider adding the placeholders as tags too.
sp.SetTag("statement", attribute.StringValue(parserStmt.SQL))
ctx = withStatement(ctx, ast)
if isPausablePortal {
portal.pauseInfo.sp = sp
portal.pauseInfo.spCtx = ctx
}
defer func() {
spToFinish := sp
// For pausable portals, we need to persist the span as it shares the ctx
// with the underlying flow. If it gets cleaned up before we close the
// flow, we will hit `span used after finished` whenever we log an event
// when cleaning up the flow.
if isPausablePortal {
spToFinish = portal.pauseInfo.sp
}
processCleanupFunc("cleanup span", spToFinish.Finish)
}()
} else {
ctx = portal.pauseInfo.spCtx
}
makeErrEvent := func(err error) (fsm.Event, fsm.EventPayload, error) {
ev, payload := ex.makeErrEvent(err, ast)
return ev, payload, nil
}
var stmt Statement
var queryID clusterunique.ID
if isPausablePortal {
if !portal.pauseInfo.isQueryIDSet() {
portal.pauseInfo.queryID = ex.generateID()
}
queryID = portal.pauseInfo.queryID
} else {
queryID = ex.generateID()
}
// Update the deadline on the transaction based on the collections.
err := ex.extraTxnState.descCollection.MaybeUpdateDeadline(ctx, ex.state.mu.txn)
if err != nil {
return makeErrEvent(err)
}
os := ex.machine.CurState().(stateOpen)
isExtendedProtocol := portal != nil && portal.Stmt != nil
if isExtendedProtocol {
stmt = makeStatementFromPrepared(portal.Stmt, queryID)
} else {
stmt = makeStatement(parserStmt, queryID)
}
var queryTimeoutTicker *time.Timer
var txnTimeoutTicker *time.Timer
queryTimedOut := false
txnTimedOut := false
// queryDoneAfterFunc and txnDoneAfterFunc will be allocated only when
// queryTimeoutTicker or txnTimeoutTicker is non-nil.
var queryDoneAfterFunc chan struct{}
var txnDoneAfterFunc chan struct{}
var cancelQuery context.CancelFunc
addActiveQuery := func() {
ctx, cancelQuery = contextutil.WithCancel(ctx)
ex.incrementStartedStmtCounter(ast)
func(st *txnState) {
st.mu.Lock()
defer st.mu.Unlock()
st.mu.stmtCount++
}(&ex.state)
ex.addActiveQuery(parserStmt, pinfo, queryID, cancelQuery)
}
// For pausable portal, the active query needs to be set up only when
// the portal is executed for the first time.
if !isPausablePortal || !portal.pauseInfo.execStmtInOpenStateCleanup.isComplete {
addActiveQuery()
if isPausablePortal {
portal.pauseInfo.cancelQueryFunc = cancelQuery
portal.pauseInfo.cancelQueryCtx = ctx
}
defer func() {
processCleanupFunc(
"increment executed stmt cnt",
func() {
if retErr == nil && !payloadHasError(retPayload) {
ex.incrementExecutedStmtCounter(ast)
}
},
)
}()
} else {
ctx = portal.pauseInfo.cancelQueryCtx
}
// 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
// cancellation.
defer func(ctx context.Context, res RestrictedCommandResult) {
if queryTimeoutTicker != nil {
if !queryTimeoutTicker.Stop() {
// Wait for the timer callback to complete to avoid a data race on
// queryTimedOut.
<-queryDoneAfterFunc
}
}
if txnTimeoutTicker != nil {
if !txnTimeoutTicker.Stop() {
// Wait for the timer callback to complete to avoid a data race on
// txnTimedOut.
<-txnDoneAfterFunc
}
}
processCleanupFunc("cancel query", func() {
cancelQueryCtx := ctx
cancelQueryFunc := cancelQuery
if isPausablePortal {
cancelQueryCtx = portal.pauseInfo.cancelQueryCtx
cancelQueryFunc = portal.pauseInfo.cancelQueryFunc
}
// 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
// canceled, all sorts of actors can detect the cancelation and set all
// sorts of errors on the result. Rather than trying to impose discipline
// in that jungle, we just overwrite them all here with an error that's
// nicer to look at for the client.
// Explaining why we need to check if the result has been released:
// If we're checking for a portal, it can happen after all executions have
// finished, the result has been released, and we're simply closing the
// connExecutor. We should allow this case, so don't want to return an
// assertion error in resToPushErr.Err() when the result is released.
if res != nil && cancelQueryCtx.Err() != nil && !res.IsReleased() && res.Err() != nil {
// Even in the cases where the error is a retryable error, we want to
// intercept the event and payload returned here to ensure that the query
// is not retried.
retEv = eventNonRetriableErr{
IsCommit: fsm.FromBool(isCommit(ast)),
}
errToPush := cancelchecker.QueryCanceledError
// For pausable portal, we can arrive this after encountering a timeout
// error and then perform a query-cleanup step. In this case, we don't
// want to override the original timeout error with the query-cancelled
// error.
if isPausablePortal && (errors.Is(res.Err(), sqlerrors.QueryTimeoutError) || errors.Is(res.Err(), sqlerrors.TxnTimeoutError)) {
errToPush = res.Err()
}
res.SetError(errToPush)
retPayload = eventNonRetriableErrPayload{err: errToPush}
}
ex.removeActiveQuery(queryID, ast)
cancelQueryFunc()
})
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
// we've checked for canceled queries as some queries may be canceled
// because of a timeout, in which case the appropriate error to return to
// the client is one that indicates the timeout, rather than the more general
// query canceled error. It's important to note that a timed out query may
// not have been canceled (eg. We never even start executing a query
// because the timeout has already expired), and therefore this check needs
// to happen outside the canceled query check above.
if queryTimedOut {
// A timed out query should never produce retryable errors/events/payloads
// so we intercept and overwrite them all here.
retEv = eventNonRetriableErr{
IsCommit: fsm.FromBool(isCommit(ast)),
}
res.SetError(sqlerrors.QueryTimeoutError)
retPayload = eventNonRetriableErrPayload{err: sqlerrors.QueryTimeoutError}
} else if txnTimedOut {
retEv = eventNonRetriableErr{
IsCommit: fsm.FromBool(isCommit(ast)),
}
res.SetError(sqlerrors.TxnTimeoutError)
retPayload = eventNonRetriableErrPayload{err: sqlerrors.TxnTimeoutError}
}
}(ctx, res)
if ex.executorType != executorTypeInternal {
ex.metrics.EngineMetrics.SQLActiveStatements.Inc(1)
}
// TODO(sql-sessions): persist the planner for a pausable portal, and reuse
// it for each re-execution.
// https://github.com/cockroachdb/cockroach/issues/99625
p := &ex.planner
stmtTS := ex.server.cfg.Clock.PhysicalTime()
ex.statsCollector.Reset(ex.applicationStats, ex.phaseTimes)
ex.resetPlanner(ctx, p, ex.state.mu.txn, stmtTS)
p.sessionDataMutatorIterator.paramStatusUpdater = res
p.noticeSender = res
ih := &p.instrumentation
// Special top-level handling for EXPLAIN ANALYZE.
if e, ok := ast.(*tree.ExplainAnalyze); ok {
switch e.Mode {
case tree.ExplainDebug:
telemetry.Inc(sqltelemetry.ExplainAnalyzeDebugUseCounter)
flags := explain.MakeFlags(&e.ExplainOptions)
flags.Verbose = true
flags.ShowTypes = true
if ex.server.cfg.TestingKnobs.DeterministicExplain {
flags.Deflake = explain.DeflakeAll
}
ih.SetOutputMode(explainAnalyzeDebugOutput, flags)
case tree.ExplainPlan:
telemetry.Inc(sqltelemetry.ExplainAnalyzeUseCounter)
flags := explain.MakeFlags(&e.ExplainOptions)
if ex.server.cfg.TestingKnobs.DeterministicExplain {
flags.Deflake = explain.DeflakeAll
}
ih.SetOutputMode(explainAnalyzePlanOutput, flags)
case tree.ExplainDistSQL:
telemetry.Inc(sqltelemetry.ExplainAnalyzeDistSQLUseCounter)
flags := explain.MakeFlags(&e.ExplainOptions)
if ex.server.cfg.TestingKnobs.DeterministicExplain {
flags.Deflake = explain.DeflakeAll
}
ih.SetOutputMode(explainAnalyzeDistSQLOutput, flags)
default:
return makeErrEvent(errors.AssertionFailedf("unsupported EXPLAIN ANALYZE mode %s", e.Mode))
}
// Strip off the explain node to execute the inner statement.
stmt.AST = e.Statement
ast = e.Statement
// TODO(radu): should we trim the "EXPLAIN ANALYZE (DEBUG)" part from
// stmt.SQL?
// Clear any ExpectedTypes we set if we prepared this statement (they
// reflect the column types of the EXPLAIN itself and not those of the inner
// statement).
stmt.ExpectedTypes = nil
}
// Special top-level handling for EXECUTE. This must happen after the handling
// for EXPLAIN ANALYZE (in order to support EXPLAIN ANALYZE EXECUTE) but
// before setting up the instrumentation helper.
if e, ok := ast.(*tree.Execute); ok {
// Replace the `EXECUTE foo` statement with the prepared statement, and
// continue execution.
name := e.Name.String()
ps, ok := ex.extraTxnState.prepStmtsNamespace.prepStmts[name]
if !ok {
return makeErrEvent(newPreparedStmtDNEError(ex.sessionData(), name))
}
ex.extraTxnState.prepStmtsNamespace.touchLRUEntry(name)
var err error
pinfo, err = ex.planner.fillInPlaceholders(ctx, ps, name, e.Params)
if err != nil {
return makeErrEvent(err)
}
// TODO(radu): what about .SQL, .NumAnnotations, .NumPlaceholders?
stmt.Statement = ps.Statement
stmt.Prepared = ps
stmt.ExpectedTypes = ps.Columns
stmt.StmtNoConstants = ps.StatementNoConstants
stmt.StmtSummary = ps.StatementSummary
res.ResetStmtType(ps.AST)
if e.DiscardRows {
ih.SetDiscardRows()
}
ast = stmt.Statement.AST
}
var needFinish bool
// For pausable portal, the instrumentation helper needs to be set up only when
// the portal is executed for the first time.
if !isPausablePortal || portal.pauseInfo.ihWrapper == nil {
ctx, needFinish = ih.Setup(
ctx, ex.server.cfg, ex.statsCollector, p, ex.stmtDiagnosticsRecorder,
stmt.StmtNoConstants, os.ImplicitTxn.Get(), ex.extraTxnState.shouldCollectTxnExecutionStats,
)
} else {
ctx = portal.pauseInfo.ihWrapper.ctx
}
// For pausable portals, we need to persist the instrumentationHelper as it
// shares the ctx with the underlying flow. If it got cleaned up before we
// clean up the flow, we will hit `span used after finished` whenever we log
// an event when cleaning up the flow.
// We need this seemingly weird wrapper here because we set the planner's ih
// with its pointer. However, for pausable portal, we'd like to persist the
// ih and reuse it for all re-executions. So the planner's ih and the portal's
// ih should never have the same address, otherwise changing the former will
// change the latter, and we will never be able to persist it.
if isPausablePortal {
if portal.pauseInfo.ihWrapper == nil {
portal.pauseInfo.ihWrapper = &instrumentationHelperWrapper{
ctx: ctx,
ih: *ih,
}
} else {
p.instrumentation = portal.pauseInfo.ihWrapper.ih
}
}
if needFinish {
sql := stmt.SQL
defer func() {
processCleanupFunc("finish instrumentation helper", func() {
// We need this weird thing because we need to make sure we're closing
// the correct instrumentation helper for the paused portal.
ihToFinish := ih
if isPausablePortal && portal.pauseInfo.ihWrapper != nil {
ihToFinish = &portal.pauseInfo.ihWrapper.ih
}
retErr = ihToFinish.Finish(
ex.server.cfg,
ex.statsCollector,
&ex.extraTxnState.accumulatedStats,
ihToFinish.collectExecStats,
p,
ast,
sql,
res,
retPayload,
retErr,
)
})
}()
}
if ex.sessionData().TransactionTimeout > 0 && !ex.implicitTxn() && ex.executorType != executorTypeInternal {
timerDuration :=
ex.sessionData().TransactionTimeout - timeutil.Since(ex.phaseTimes.GetSessionPhaseTime(sessionphase.SessionTransactionStarted))
// If the timer already expired, but the transaction is not yet aborted,
// we should error immediately without executing. If the timer
// expired but the transaction already is aborted, then we should still
// proceed with executing the statement in order to get a
// TransactionAbortedError.
_, txnAborted := ex.machine.CurState().(stateAborted)
if timerDuration < 0 && !txnAborted {
txnTimedOut = true
return makeErrEvent(sqlerrors.TxnTimeoutError)
}
if timerDuration > 0 {
txnDoneAfterFunc = make(chan struct{}, 1)
txnTimeoutTicker = time.AfterFunc(
timerDuration,
func() {
cancelQuery()
txnTimedOut = true
txnDoneAfterFunc <- struct{}{}
})
}
}
// We exempt `SET` statements from the statement timeout, particularly so as
// not to block the `SET statement_timeout` command itself.
if ex.sessionData().StmtTimeout > 0 && ast.StatementTag() != "SET" {
timerDuration :=
ex.sessionData().StmtTimeout - timeutil.Since(ex.phaseTimes.GetSessionPhaseTime(sessionphase.SessionQueryReceived))
// There's no need to proceed with execution if the timer has already expired.
if timerDuration < 0 {
queryTimedOut = true
return makeErrEvent(sqlerrors.QueryTimeoutError)
}
queryDoneAfterFunc = make(chan struct{}, 1)
queryTimeoutTicker = time.AfterFunc(
timerDuration,
func() {
if isPausablePortal {
portal.pauseInfo.cancelQueryFunc()
} else {
cancelQuery()
}
queryTimedOut = true
queryDoneAfterFunc <- struct{}{}
})
}
defer func(ctx context.Context) {
if filter := ex.server.cfg.TestingKnobs.StatementFilter; retErr == nil && filter != nil {
var execErr error
if perr, ok := retPayload.(payloadWithError); ok {
execErr = perr.errorCause()
}
filter(ctx, ex.sessionData(), stmt.AST.String(), execErr)
}
// Do the auto-commit, if necessary. In the extended protocol, the
// auto-commit happens when the Sync message is handled.
if retEv != nil || retErr != nil {
return
}
// As portals are from extended protocol, we don't auto commit for them.
if canAutoCommit && !isExtendedProtocol {
retEv, retPayload = ex.handleAutoCommit(ctx, ast)
}
}(ctx)
switch s := ast.(type) {
case *tree.BeginTransaction:
// BEGIN is only allowed if we are in an implicit txn.
if os.ImplicitTxn.Get() {
// When executing the BEGIN, we also need to set any transaction modes
// that were specified on the BEGIN statement.
if _, err := ex.planner.SetTransaction(ctx, &tree.SetTransaction{Modes: s.Modes}); err != nil {
return makeErrEvent(err)
}
ex.sessionDataStack.PushTopClone()
return eventTxnUpgradeToExplicit{}, nil, nil
}
return makeErrEvent(errTransactionInProgress)
case *tree.CommitTransaction:
// CommitTransaction is executed fully here; there's no plan for it.
ev, payload := ex.commitSQLTransaction(ctx, ast, ex.commitSQLTransactionInternal)
return ev, payload, nil
case *tree.RollbackTransaction:
// RollbackTransaction is executed fully here; there's no plan for it.
ev, payload := ex.rollbackSQLTransaction(ctx, s)
return ev, payload, nil
case *tree.Savepoint:
return ex.execSavepointInOpenState(ctx, s, res)
case *tree.ReleaseSavepoint:
ev, payload := ex.execRelease(ctx, s, res)
return ev, payload, nil
case *tree.RollbackToSavepoint:
ev, payload := ex.execRollbackToSavepointInOpenState(ctx, s, res)
return ev, payload, nil
case *tree.ShowCommitTimestamp:
ev, payload := ex.execShowCommitTimestampInOpenState(ctx, s, res, canAutoCommit)
return ev, payload, nil
case *tree.Prepare:
// This is handling the SQL statement "PREPARE". See execPrepare for
// handling of the protocol-level command for preparing statements.
name := s.Name.String()
if _, ok := ex.extraTxnState.prepStmtsNamespace.prepStmts[name]; ok {
err := pgerror.Newf(
pgcode.DuplicatePreparedStatement,
"prepared statement %q already exists", name,
)
return makeErrEvent(err)
}
var typeHints tree.PlaceholderTypes
// We take max(len(s.Types), stmt.NumPlaceHolders) as the length of types.
numParams := len(s.Types)
if stmt.NumPlaceholders > numParams {
numParams = stmt.NumPlaceholders
}
if len(s.Types) > 0 {
typeHints = make(tree.PlaceholderTypes, numParams)
for i, t := range s.Types {
resolved, err := tree.ResolveType(ctx, t, ex.planner.semaCtx.GetTypeResolver())
if err != nil {
return makeErrEvent(err)
}
typeHints[i] = resolved
}
}
prepStmt := makeStatement(
parser.Statement{
// We need the SQL string just for the part that comes after
// "PREPARE ... AS",
// TODO(radu): it would be nice if the parser would figure out this
// string and store it in tree.Prepare.
SQL: tree.AsStringWithFlags(s.Statement, tree.FmtParsable),
AST: s.Statement,
NumPlaceholders: stmt.NumPlaceholders,
NumAnnotations: stmt.NumAnnotations,
},
ex.generateID(),
)
var rawTypeHints []oid.Oid
if _, err := ex.addPreparedStmt(
ctx, name, prepStmt, typeHints, rawTypeHints, PreparedStatementOriginSQL,
); err != nil {
return makeErrEvent(err)
}
return nil, nil, nil
}
p.semaCtx.Annotations = tree.MakeAnnotations(stmt.NumAnnotations)
// For regular statements (the ones that get to this point), we
// don't return any event unless an error happens.
// For a portal (prepared stmt), since handleAOST() is called when preparing
// the statement, and this function is idempotent, we don't need to
// call it again during execution.
if portal == nil {
if err := ex.handleAOST(ctx, ast); err != nil {
return makeErrEvent(err)
}
}
// The first order of business is to ensure proper sequencing
// semantics. As per PostgreSQL's dialect specs, the "read" part of
// statements always see the data as per a snapshot of the database
// taken the instant the statement begins to run. In particular a
// mutation does not see its own writes. If a query contains
// multiple mutations using CTEs (WITH) or a read part following a
// mutation, all still operate on the same read snapshot.
//
// (To communicate data between CTEs and a main query, the result
// set / RETURNING can be used instead. However this is not relevant
// here.)
// We first ensure stepping mode is enabled.
//
// This ought to be done just once when a txn gets initialized;
// unfortunately, there are too many places where the txn object
// is re-configured, re-set etc without using NewTxnWithSteppingEnabled().
//
// Manually hunting them down and calling ConfigureStepping() each
// time would be error prone (and increase the chance that a future
// change would forget to add the call).
//
// TODO(andrei): really the code should be rearchitected to ensure
// that all uses of SQL execution initialize the client.Txn using a
// single/common function. That would be where the stepping mode
// gets enabled once for all SQL statements executed "underneath".
prevSteppingMode := ex.state.mu.txn.ConfigureStepping(ctx, kv.SteppingEnabled)
defer func() { _ = ex.state.mu.txn.ConfigureStepping(ctx, prevSteppingMode) }()
// Then we create a sequencing point.
//
// This is not the only place where a sequencing point is
// placed. There are also sequencing point after every stage of
// constraint checks and cascading actions at the _end_ of a
// statement's execution.
if err := ex.state.mu.txn.Step(ctx); err != nil {
return makeErrEvent(err)
}
if err := p.semaCtx.Placeholders.Assign(pinfo, stmt.NumPlaceholders); err != nil {
return makeErrEvent(err)
}
p.extendedEvalCtx.Placeholders = &p.semaCtx.Placeholders
p.extendedEvalCtx.Annotations = &p.semaCtx.Annotations
p.stmt = stmt
if isPausablePortal {
p.pausablePortal = portal
} else {
p.cancelChecker.Reset(ctx)
}
// Auto-commit is disallowed during statement execution if we previously
// executed any DDL. This is because may potentially create jobs and do other
// operations rather than a KV commit.
// This prevents commit during statement execution, but the conn_executor
// will still commit this transaction after this statement executes.
p.autoCommit = canAutoCommit &&
!ex.server.cfg.TestingKnobs.DisableAutoCommitDuringExec && ex.extraTxnState.numDDL == 0
p.extendedEvalCtx.TxnIsSingleStmt = canAutoCommit && !ex.extraTxnState.firstStmtExecuted
ex.extraTxnState.firstStmtExecuted = true
var stmtThresholdSpan *tracing.Span
alreadyRecording := ex.transitionCtx.sessionTracing.Enabled()
// TODO(sql-sessions): fix the stmtTraceThreshold for pausable portals, so
// that it records all executions.
// https://github.com/cockroachdb/cockroach/issues/99404
stmtTraceThreshold := TraceStmtThreshold.Get(&ex.planner.execCfg.Settings.SV)
var stmtCtx context.Context
// TODO(andrei): I think we should do this even if alreadyRecording == true.
if !alreadyRecording && stmtTraceThreshold > 0 {
stmtCtx, stmtThresholdSpan = tracing.EnsureChildSpan(ctx, ex.server.cfg.AmbientCtx.Tracer, "trace-stmt-threshold", tracing.WithRecording(tracingpb.RecordingVerbose))
} else {
stmtCtx = ctx
}
var rollbackSP *tree.RollbackToSavepoint
var r *tree.ReleaseSavepoint
enforceHomeRegion := p.EnforceHomeRegion()
_, isSelectStmt := stmt.AST.(*tree.Select)
// TODO(sql-sessions): ensure this is not broken for pausable portals.
// https://github.com/cockroachdb/cockroach/issues/99408
if enforceHomeRegion && ex.state.mu.txn.IsOpen() && isSelectStmt {
// Create a savepoint at a point before which rows were read so that we can
// roll back to it, which will allow the txn to be modified with a
// historical timestamp (so that the locality-optimized ops used for error
// reporting can run locally and not incur latency). This is currently only
// supported for SELECT statements.
var b strings.Builder
b.WriteString("enforce_home_region_sp")
// Add some unprintable ASCII characters to the name of the savepoint to
// decrease the likelihood of collision with a user-created savepoint.
b.WriteRune(rune(0x11))
b.WriteRune(rune(0x12))
b.WriteRune(rune(0x13))
enforceHomeRegionSavepointName := tree.Name(b.String())
s := &tree.Savepoint{Name: enforceHomeRegionSavepointName}
var event fsm.Event
var eventPayload fsm.EventPayload
if event, eventPayload, err = ex.execSavepointInOpenState(ctx, s, res); err != nil {
return event, eventPayload, err
}
r = &tree.ReleaseSavepoint{Savepoint: enforceHomeRegionSavepointName}
rollbackSP = &tree.RollbackToSavepoint{Savepoint: enforceHomeRegionSavepointName}
defer func() {
// The default case is to roll back the internally-generated savepoint
// after every request. We only need it if a retryable "query has no home
// region" error occurs.
ex.execRelease(ctx, r, res)
}()
}
if err = ex.dispatchToExecutionEngine(stmtCtx, p, res); err != nil {
stmtThresholdSpan.Finish()
return nil, nil, err
}
if stmtThresholdSpan != nil {
stmtDur := timeutil.Since(ex.phaseTimes.GetSessionPhaseTime(sessionphase.SessionQueryReceived))
needRecording := stmtTraceThreshold < stmtDur
if needRecording {
rec := stmtThresholdSpan.FinishAndGetRecording(tracingpb.RecordingVerbose)
// NB: This recording does not include the commit for implicit
// transactions if the statement didn't auto-commit.
logTraceAboveThreshold(
ctx,
rec,
fmt.Sprintf("SQL stmt %s", stmt.AST.String()),
stmtTraceThreshold,
stmtDur,
)
} else {
stmtThresholdSpan.Finish()
}
}
if err = res.Err(); err != nil {
setErrorAndRestoreLocality := func(err error) {
res.SetError(err)
// We won't be faking the gateway region any more. Restore the original
// locality.
p.EvalContext().Locality = p.EvalContext().OriginalLocality
}
if execinfra.IsDynamicQueryHasNoHomeRegionError(err) {
if rollbackSP != nil {
// A retryable "query has no home region" error has occurred.
// Roll back to the internal savepoint in preparation for the next
// planning and execution of this query with a different gateway region
// (as considered by the optimizer).
p.StmtNoConstantsWithHomeRegionEnforced = p.stmt.StmtNoConstants
event, eventPayload := ex.execRollbackToSavepointInOpenState(
ctx, rollbackSP, res,
)
_, isTxnRestart := event.(eventTxnRestart)
rollbackToSavepointFailed := !isTxnRestart || eventPayload != nil
if ex.implicitTxn() && rollbackToSavepointFailed {
err = errors.AssertionFailedf(
"unable to roll back to internal savepoint for enforce_home_region",
)
setErrorAndRestoreLocality(err)
} else if rollbackToSavepointFailed || int(ex.state.mu.autoRetryCounter) == len(ex.planner.EvalContext().RemoteRegions) {
// If rollback to savepoint in the transaction failed (perhaps because
// the txn was aborted) and we're in an explicit transaction, or we
// have retried the statement using each remote region as a fake
// gateway region, then give up and return the generic "query has no
// home region" error message.
err = execinfra.MaybeGetNonRetryableDynamicQueryHasNoHomeRegionError(err)
setErrorAndRestoreLocality(err)
}
} else {
err = execinfra.MaybeGetNonRetryableDynamicQueryHasNoHomeRegionError(err)
setErrorAndRestoreLocality(err)
}
} else if execinfra.IsDynamicQueryHasNoHomeRegionError(ex.state.mu.autoRetryReason) {
// If we are retrying a dynamic "query has no home region" error and
// we get a different error message when executing with locality-optimized
// ops using a different local region (for example, relation does not
// exist, due to the AOST read), return the original error message in