-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
internal.go
1822 lines (1666 loc) · 62.6 KB
/
internal.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 2016 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 (
"context"
"math"
"strings"
"sync"
"time"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/concurrency/isolation"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catsessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descs"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/lease"
"github.com/cockroachdb/cockroach/pkg/sql/isql"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgwirebase"
"github.com/cockroachdb/cockroach/pkg/sql/regions"
"github.com/cockroachdb/cockroach/pkg/sql/sem/catconstants"
"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/sqlstats"
"github.com/cockroachdb/cockroach/pkg/sql/sqltelemetry"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/fsm"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"github.com/cockroachdb/cockroach/pkg/util/startup"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/logtags"
)
// NewInternalSessionData returns a session data for use in internal queries
// that are not run on behalf of a user session, such as those run during the
// steps of background jobs and schema changes. Each session variable is
// initialized using the correct default value.
func NewInternalSessionData(
ctx context.Context, settings *cluster.Settings, opName string,
) *sessiondata.SessionData {
appName := catconstants.InternalAppNamePrefix
if opName != "" {
appName = catconstants.InternalAppNamePrefix + "-" + opName
}
sd := &sessiondata.SessionData{}
sds := sessiondata.NewStack(sd)
defaults := SessionDefaults(map[string]string{
"application_name": appName,
})
sdMutIterator := makeSessionDataMutatorIterator(sds, defaults, settings)
sdMutIterator.applyOnEachMutator(func(m sessionDataMutator) {
for varName, v := range varGen {
if v.Set != nil {
hasDefault, defVal := getSessionVarDefaultString(varName, v, m.sessionDataMutatorBase)
if hasDefault {
if err := v.Set(ctx, m, defVal); err != nil {
log.Warningf(ctx, "error setting default for %s: %v", varName, err)
}
}
}
}
})
sd.UserProto = username.NodeUserName().EncodeProto()
sd.Internal = true
sd.SearchPath = sessiondata.DefaultSearchPathForUser(username.NodeUserName())
sd.SequenceState = sessiondata.NewSequenceState()
sd.Location = time.UTC
return sd
}
var _ isql.Executor = &InternalExecutor{}
// InternalExecutor can be used internally by code modules to execute SQL
// statements without needing to open a SQL connection.
//
// InternalExecutor can execute one statement at a time. As of 03/2018, it
// doesn't offer a session interface for maintaining session state or for
// running explicit SQL transactions. However, it supports running SQL
// statements inside a higher-lever (KV) txn and inheriting session variables
// from another session.
//
// Methods not otherwise specified are safe for concurrent execution.
type InternalExecutor struct {
s *Server
// mon is the monitor used by all queries executed through the
// InternalExecutor.
mon *mon.BytesMonitor
// memMetrics is the memory metrics that queries executed through the
// InternalExecutor will contribute to.
memMetrics MemoryMetrics
// sessionDataStack, if not nil, represents the session variable stack used by
// statements executed on this internalExecutor. Note that queries executed
// by the executor will run on copies of the top element of this data.
sessionDataStack *sessiondata.Stack
// syntheticDescriptors stores the synthetic descriptors to be injected into
// each query/statement's descs.Collection upon initialization.
//
// Warning: Not safe for concurrent use from multiple goroutines.
syntheticDescriptors []catalog.Descriptor
// extraTxnState is to store extra transaction state info that
// will be passed to an internal executor. It should only be set when the
// internal executor is used under a not-nil txn.
// TODO (janexing): we will deprecate this field with *connExecutor ASAP.
// An internal executor, if used with a not nil txn, should be always coupled
// with a single connExecutor which runs all passed sql statements.
extraTxnState *extraTxnState
}
// WithSyntheticDescriptors sets the synthetic descriptors before running the
// the provided closure and resets them afterward. Used for queries/statements
// that need to use in-memory synthetic descriptors different from descriptors
// written to disk. These descriptors override all other descriptors on the
// immutable resolution path.
//
// Warning: Not safe for concurrent use from multiple goroutines. This API is
// flawed in that the internal executor is meant to function as a stateless
// wrapper, and creates a new connExecutor and descs.Collection on each query/
// statement, so these descriptors should really be specified at a per-query/
// statement level. See #34304.
func (ie *InternalExecutor) WithSyntheticDescriptors(
descs []catalog.Descriptor, run func() error,
) error {
ie.syntheticDescriptors = descs
defer func() {
ie.syntheticDescriptors = nil
}()
return run()
}
// MakeInternalExecutor creates an InternalExecutor.
// TODO (janexing): usage of it should be deprecated with `DescsTxnWithExecutor()`
// or `Executor()`.
func MakeInternalExecutor(
s *Server, memMetrics MemoryMetrics, monitor *mon.BytesMonitor,
) InternalExecutor {
return InternalExecutor{
s: s,
mon: monitor,
memMetrics: memMetrics,
}
}
// MakeInternalExecutorMemMonitor creates and starts memory monitor for an
// InternalExecutor.
func MakeInternalExecutorMemMonitor(
memMetrics MemoryMetrics, settings *cluster.Settings,
) *mon.BytesMonitor {
return mon.NewMonitor(
"internal SQL executor",
mon.MemoryResource,
memMetrics.CurBytesCount,
memMetrics.MaxBytesHist,
-1, /* use default increment */
math.MaxInt64, /* noteworthy */
settings,
)
}
// SetSessionData binds the session variables that will be used by queries
// performed through this executor from now on. This creates a new session stack.
// It is recommended to use SetSessionDataStack.
//
// SetSessionData cannot be called concurrently with query execution.
func (ie *InternalExecutor) SetSessionData(sessionData *sessiondata.SessionData) {
if sessionData != nil {
populateMinimalSessionData(sessionData)
ie.sessionDataStack = sessiondata.NewStack(sessionData)
}
}
func (ie *InternalExecutor) runWithEx(
ctx context.Context,
txn *kv.Txn,
w ieResultWriter,
mode ieExecutionMode,
sd *sessiondata.SessionData,
stmtBuf *StmtBuf,
wg *sync.WaitGroup,
syncCallback func([]*streamingCommandResult),
errCallback func(error),
) error {
ex, err := ie.initConnEx(ctx, txn, w, mode, sd, stmtBuf, syncCallback)
if err != nil {
return err
}
wg.Add(1)
go func() {
if err := ex.run(ctx, ie.mon, &mon.BoundAccount{} /*reserved*/, nil /* cancel */); err != nil {
sqltelemetry.RecordError(ctx, err, &ex.server.cfg.Settings.SV)
errCallback(err)
}
w.finish()
closeMode := normalClose
if txn != nil {
closeMode = externalTxnClose
}
ex.close(ctx, closeMode)
wg.Done()
}()
return nil
}
// initConnEx creates a connExecutor and runs it on a separate goroutine. It
// takes in a StmtBuf into which commands can be pushed and a WaitGroup that
// will be signaled when connEx.run() returns.
//
// If txn is not nil, the statement will be executed in the respective txn.
//
// The ieResultWriter coordinates communicating results to the client. It may
// block execution when rows are being sent in order to prevent hazardous
// concurrency.
//
// sd will constitute the executor's session state.
func (ie *InternalExecutor) initConnEx(
ctx context.Context,
txn *kv.Txn,
w ieResultWriter,
mode ieExecutionMode,
sd *sessiondata.SessionData,
stmtBuf *StmtBuf,
syncCallback func([]*streamingCommandResult),
) (*connExecutor, error) {
clientComm := &internalClientComm{
w: w,
mode: mode,
sync: syncCallback,
resetRowsAffected: func() {
var zero int
_ = w.addResult(ctx, ieIteratorResult{rowsAffected: &zero})
},
}
applicationStats := ie.s.sqlStats.GetApplicationStats(sd.ApplicationName, true /* internal */)
sds := sessiondata.NewStack(sd)
defaults := SessionDefaults(map[string]string{
"application_name": sd.ApplicationName,
})
sdMutIterator := makeSessionDataMutatorIterator(sds, defaults, ie.s.cfg.Settings)
var ex *connExecutor
var err error
if txn == nil {
ex = ie.s.newConnExecutor(
ctx,
sdMutIterator,
stmtBuf,
clientComm,
ie.memMetrics,
&ie.s.InternalMetrics,
applicationStats,
nil, /* postSetupFn */
)
} else {
ex, err = ie.newConnExecutorWithTxn(
ctx,
txn,
sdMutIterator,
stmtBuf,
clientComm,
applicationStats,
)
if err != nil {
return nil, err
}
}
ex.executorType = executorTypeInternal
return ex, nil
}
// newConnExecutorWithTxn creates a connExecutor that will execute statements
// under a higher-level txn. This connExecutor runs with a different state
// machine, much reduced from the regular one. It cannot initiate or end
// transactions (so, no BEGIN, COMMIT, ROLLBACK, no auto-commit, no automatic
// retries). It may inherit the descriptor collection and txn state from the
// internal executor.
//
// If there is no error, this function also activate()s the returned
// executor, so the caller does not need to run the
// activation. However this means that run() or close() must be called
// to release resources.
// TODO (janexing): txn should be passed to ie.extraTxnState rather than
// as a parameter to this function.
func (ie *InternalExecutor) newConnExecutorWithTxn(
ctx context.Context,
txn *kv.Txn,
sdMutIterator *sessionDataMutatorIterator,
stmtBuf *StmtBuf,
clientComm ClientComm,
applicationStats sqlstats.ApplicationStats,
) (ex *connExecutor, _ error) {
// If the internal executor has injected synthetic descriptors, we will
// inject them into the descs.Collection below, and we'll note that
// fact so that the synthetic descriptors are reset when the statement
// finishes. This logic is in support of the legacy schema changer's
// execution of schema changes in a transaction. If the declarative
// schema changer is in use, the descs.Collection in the extraTxnState
// may have synthetic descriptors, but their lifecycle is controlled
// externally, and they should not be reset after executing a statement
// here.
shouldResetSyntheticDescriptors := len(ie.syntheticDescriptors) > 0
// If an internal executor is run with a not-nil txn, we may want to
// let it inherit the descriptor collection, schema change job records
// and job collections from the caller.
postSetupFn := func(ex *connExecutor) {
if ie.extraTxnState != nil {
ex.extraTxnState.descCollection = ie.extraTxnState.descCollection
ex.extraTxnState.fromOuterTxn = true
ex.extraTxnState.jobs = ie.extraTxnState.jobs
ex.extraTxnState.schemaChangerState = ie.extraTxnState.schemaChangerState
ex.extraTxnState.shouldResetSyntheticDescriptors = shouldResetSyntheticDescriptors
ex.initPlanner(ctx, &ex.planner)
}
}
ex = ie.s.newConnExecutor(
ctx,
sdMutIterator,
stmtBuf,
clientComm,
ie.memMetrics,
&ie.s.InternalMetrics,
applicationStats,
postSetupFn,
)
if txn.Type() == kv.LeafTxn {
// If the txn is a leaf txn it is not allowed to perform mutations. For
// sanity, set read only on the session.
ex.dataMutatorIterator.applyOnEachMutator(func(m sessionDataMutator) {
m.SetReadOnly(true)
})
}
// The new transaction stuff below requires active monitors and traces, so
// we need to activate the executor now.
ex.activate(ctx, ie.mon, &mon.BoundAccount{})
// Perform some surgery on the executor - replace its state machine and
// initialize the state, and its jobs and schema change job records if
// they are passed by the caller.
// The txn is always set as explicit, because when running in an outer txn,
// the conn executor inside an internal executor is generally not at liberty
// to commit the transaction.
// Thus, to disallow auto-commit and auto-retries, we make the txn
// here an explicit one.
ex.machine = fsm.MakeMachine(
BoundTxnStateTransitions,
stateOpen{ImplicitTxn: fsm.False, WasUpgraded: fsm.False},
&ex.state,
)
ex.state.resetForNewSQLTxn(
ctx,
explicitTxn,
txn.ReadTimestamp().GoTime(),
nil, /* historicalTimestamp */
roachpb.UnspecifiedUserPriority,
tree.ReadWrite,
txn,
ex.transitionCtx,
ex.QualityOfService(),
isolation.Serializable,
)
// Modify the Collection to match the parent executor's Collection.
// This allows the Executor to see schema changes made by the
// parent executor.
if shouldResetSyntheticDescriptors {
ex.extraTxnState.descCollection.SetSyntheticDescriptors(ie.syntheticDescriptors)
}
return ex, nil
}
type ieIteratorResult struct {
// Exactly one of these 4 fields will be set.
row tree.Datums
rowsAffected *int
cols colinfo.ResultColumns
err error
}
type rowsIterator struct {
r ieResultReader
rowsAffected int
resultCols colinfo.ResultColumns
mode ieExecutionMode
// first, if non-nil, is the first object read from r. We block the return
// of the created rowsIterator in execInternal() until the producer writes
// something into the corresponding ieResultWriter because this indicates
// that the query planning has been fully performed (we want to prohibit the
// concurrent usage of the transactions).
first *ieIteratorResult
lastRow tree.Datums
lastErr error
done bool
// errCallback is an optional callback that will be called exactly once
// before an error is returned by Next() or Close().
errCallback func(err error) error
// stmtBuf will be closed on Close(). This is necessary in order to tell
// the connExecutor's goroutine to exit when the iterator's user wants to
// short-circuit the iteration (i.e. before Next() returns false).
stmtBuf *StmtBuf
// wg can be used to wait for the connExecutor's goroutine to exit.
wg *sync.WaitGroup
// sp will finished on Close().
sp *tracing.Span
}
var _ isql.Rows = &rowsIterator{}
var _ eval.InternalRows = &rowsIterator{}
func (r *rowsIterator) Next(ctx context.Context) (_ bool, retErr error) {
// Due to recursive calls to Next() below, this deferred function might get
// executed multiple times, yet it is not a problem because Close() is
// idempotent and we're unsetting the error callback.
defer func() {
// If the iterator has just reached its terminal state, we'll close it
// automatically.
if r.done {
// We can ignore the returned error because Close() will update
// r.lastErr if necessary.
_ /* err */ = r.Close()
}
if r.errCallback != nil {
r.lastErr = r.errCallback(r.lastErr)
r.errCallback = nil
}
retErr = r.lastErr
}()
if r.done {
return false, r.lastErr
}
// handleDataObject processes a single object read from ieResultReader and
// returns the result to be returned by Next. It also might call Next
// recursively if the object is a piece of metadata.
handleDataObject := func(data ieIteratorResult) (bool, error) {
if data.row != nil {
r.rowsAffected++
// No need to make a copy because streamingCommandResult does that
// for us.
r.lastRow = data.row
return true, nil
}
if data.rowsAffected != nil {
r.rowsAffected = *data.rowsAffected
return r.Next(ctx)
}
if data.cols != nil {
if r.mode == rowsAffectedIEExecutionMode {
// In "rows affected" execution mode we simply ignore the column
// schema since we always return the number of rows affected
// (i.e. a single integer column).
return r.Next(ctx)
}
// At this point we don't expect to see the columns - we should only
// return the rowsIterator to the caller of execInternal after the
// columns have been determined.
data.err = errors.AssertionFailedf("unexpectedly received non-nil cols in Next: %v", data)
}
if data.err == nil {
data.err = errors.AssertionFailedf("unexpectedly empty ieIteratorResult object")
}
r.lastErr = data.err
r.done = true
return false, r.lastErr
}
if r.first != nil {
// This is the very first call to Next() and we have already buffered
// up the first piece of data before returning rowsIterator to the
// caller.
first := r.first
r.first = nil
return handleDataObject(*first)
}
var next ieIteratorResult
next, r.done, r.lastErr = r.r.nextResult(ctx)
if r.done || r.lastErr != nil {
return false, r.lastErr
}
return handleDataObject(next)
}
func (r *rowsIterator) Cur() tree.Datums {
return r.lastRow
}
func (r *rowsIterator) RowsAffected() int {
return r.rowsAffected
}
func (r *rowsIterator) Close() error {
// Closing the stmtBuf will tell the connExecutor to stop executing commands
// (if it hasn't exited yet).
r.stmtBuf.Close()
// We need to finish the span but only after the connExecutor goroutine is
// done.
defer func() {
if r.sp != nil {
r.wg.Wait()
r.sp.Finish()
r.sp = nil
}
}()
// Close the ieResultReader to tell the writer that we're done.
if err := r.r.close(); err != nil && r.lastErr == nil {
r.lastErr = err
}
return r.lastErr
}
func (r *rowsIterator) Types() colinfo.ResultColumns {
return r.resultCols
}
func (r *rowsIterator) HasResults() bool {
return r.first != nil && r.first.row != nil
}
// QueryBuffered executes the supplied SQL statement and returns the resulting
// rows (meaning all of them are buffered at once). If no user has been
// previously set through SetSessionData, the statement is executed as the root
// user.
//
// If txn is not nil, the statement will be executed in the respective txn.
//
// QueryBuffered is deprecated because it may transparently execute a query as
// root. Use QueryBufferedEx instead.
func (ie *InternalExecutor) QueryBuffered(
ctx context.Context, opName string, txn *kv.Txn, stmt string, qargs ...interface{},
) ([]tree.Datums, error) {
return ie.QueryBufferedEx(ctx, opName, txn, ie.maybeRootSessionDataOverride(opName), stmt, qargs...)
}
// QueryBufferedEx executes the supplied SQL statement and returns the resulting
// rows (meaning all of them are buffered at once).
//
// If txn is not nil, the statement will be executed in the respective txn.
//
// The fields set in session that are set override the respective fields if they
// have previously been set through SetSessionData().
func (ie *InternalExecutor) QueryBufferedEx(
ctx context.Context,
opName string,
txn *kv.Txn,
session sessiondata.InternalExecutorOverride,
stmt string,
qargs ...interface{},
) ([]tree.Datums, error) {
datums, _, err := ie.queryInternalBuffered(ctx, opName, txn, session, stmt, 0 /* limit */, qargs...)
return datums, err
}
// QueryBufferedExWithCols is like QueryBufferedEx, additionally returning the computed
// ResultColumns of the input query.
func (ie *InternalExecutor) QueryBufferedExWithCols(
ctx context.Context,
opName string,
txn *kv.Txn,
session sessiondata.InternalExecutorOverride,
stmt string,
qargs ...interface{},
) ([]tree.Datums, colinfo.ResultColumns, error) {
datums, cols, err := ie.queryInternalBuffered(ctx, opName, txn, session, stmt, 0 /* limit */, qargs...)
return datums, cols, err
}
func (ie *InternalExecutor) queryInternalBuffered(
ctx context.Context,
opName string,
txn *kv.Txn,
sessionDataOverride sessiondata.InternalExecutorOverride,
stmt string,
// Non-zero limit specifies the limit on the number of rows returned.
limit int,
qargs ...interface{},
) ([]tree.Datums, colinfo.ResultColumns, error) {
// We will run the query to completion, so we can use an async result
// channel.
rw := newAsyncIEResultChannel()
it, err := ie.execInternal(ctx, opName, rw, defaultIEExecutionMode, txn, sessionDataOverride, stmt, qargs...)
if err != nil {
return nil, nil, err
}
var rows []tree.Datums
var ok bool
for ok, err = it.Next(ctx); ok; ok, err = it.Next(ctx) {
rows = append(rows, it.Cur())
if limit != 0 && len(rows) == limit {
// We have accumulated the requested number of rows, so we can
// short-circuit the iteration.
err = it.Close()
break
}
}
if err != nil {
return nil, nil, err
}
return rows, it.Types(), nil
}
// QueryRow is like Query, except it returns a single row, or nil if not row is
// found, or an error if more that one row is returned.
//
// QueryRow is deprecated (like Query). Use QueryRowEx() instead.
func (ie *InternalExecutor) QueryRow(
ctx context.Context, opName string, txn *kv.Txn, stmt string, qargs ...interface{},
) (tree.Datums, error) {
return ie.QueryRowEx(ctx, opName, txn, ie.maybeRootSessionDataOverride(opName), stmt, qargs...)
}
// QueryRowEx is like QueryRow, but allows the caller to override some session data
// fields (e.g. the user).
//
// The fields set in session that are set override the respective fields if they
// have previously been set through SetSessionData().
func (ie *InternalExecutor) QueryRowEx(
ctx context.Context,
opName string,
txn *kv.Txn,
session sessiondata.InternalExecutorOverride,
stmt string,
qargs ...interface{},
) (tree.Datums, error) {
rows, _, err := ie.QueryRowExWithCols(ctx, opName, txn, session, stmt, qargs...)
return rows, err
}
// QueryRowExWithCols is like QueryRowEx, additionally returning the computed
// ResultColumns of the input query.
func (ie *InternalExecutor) QueryRowExWithCols(
ctx context.Context,
opName string,
txn *kv.Txn,
session sessiondata.InternalExecutorOverride,
stmt string,
qargs ...interface{},
) (tree.Datums, colinfo.ResultColumns, error) {
rows, cols, err := ie.queryInternalBuffered(ctx, opName, txn, session, stmt, 2 /* limit */, qargs...)
if err != nil {
return nil, nil, err
}
switch len(rows) {
case 0:
return nil, nil, nil
case 1:
return rows[0], cols, nil
default:
return nil, nil, &tree.MultipleResultsError{SQL: stmt}
}
}
// Exec executes the supplied SQL statement and returns the number of rows
// affected (not like the results; see Query()). If no user has been previously
// set through SetSessionData, the statement is executed as the root user.
//
// If txn is not nil, the statement will be executed in the respective txn.
//
// Exec is deprecated because it may transparently execute a query as root. Use
// ExecEx instead.
func (ie *InternalExecutor) Exec(
ctx context.Context, opName string, txn *kv.Txn, stmt string, qargs ...interface{},
) (int, error) {
return ie.ExecEx(ctx, opName, txn, ie.maybeRootSessionDataOverride(opName), stmt, qargs...)
}
// ExecEx is like Exec, but allows the caller to override some session data
// fields (e.g. the user).
//
// The fields set in session that are set override the respective fields if they
// have previously been set through SetSessionData().
func (ie *InternalExecutor) ExecEx(
ctx context.Context,
opName string,
txn *kv.Txn,
session sessiondata.InternalExecutorOverride,
stmt string,
qargs ...interface{},
) (int, error) {
// We will run the query to completion, so we can use an async result
// channel.
rw := newAsyncIEResultChannel()
// Since we only return the number of rows affected as given by the
// rowsIterator, we execute this stmt in "rows affected" mode allowing the
// internal executor to transparently retry.
const mode = rowsAffectedIEExecutionMode
it, err := ie.execInternal(ctx, opName, rw, mode, txn, session, stmt, qargs...)
if err != nil {
return 0, err
}
// We need to exhaust the iterator so that it can count the number of rows
// affected.
var ok bool
for ok, err = it.Next(ctx); ok; ok, err = it.Next(ctx) {
}
if err != nil {
return 0, err
}
return it.rowsAffected, nil
}
// QueryIterator executes the query, returning an iterator that can be used
// to get the results. If the call is successful, the returned iterator
// *must* be closed.
//
// QueryIterator is deprecated because it may transparently execute a query
// as root. Use QueryIteratorEx instead.
func (ie *InternalExecutor) QueryIterator(
ctx context.Context, opName string, txn *kv.Txn, stmt string, qargs ...interface{},
) (isql.Rows, error) {
return ie.QueryIteratorEx(ctx, opName, txn, ie.maybeRootSessionDataOverride(opName), stmt, qargs...)
}
// QueryIteratorEx executes the query, returning an iterator that can be used
// to get the results. If the call is successful, the returned iterator
// *must* be closed.
func (ie *InternalExecutor) QueryIteratorEx(
ctx context.Context,
opName string,
txn *kv.Txn,
session sessiondata.InternalExecutorOverride,
stmt string,
qargs ...interface{},
) (isql.Rows, error) {
return ie.execInternal(
ctx, opName, newSyncIEResultChannel(), defaultIEExecutionMode, txn, session, stmt, qargs...,
)
}
// applyInternalExecutorSessionExceptions overrides values from
// the session data that may have been set from a user-session but
// which don't make sense to use in the InternalExecutor.
func applyInternalExecutorSessionExceptions(sd *sessiondata.SessionData) {
// Even if session queries are told to error on non-home region accesses,
// internal queries spawned from the same context should never do so.
sd.LocalOnlySessionData.EnforceHomeRegion = false
// DisableBuffering is not supported by the InternalExecutor
// which uses streamingCommandResults.
sd.LocalOnlySessionData.AvoidBuffering = false
// At the moment, we disable the usage of the Streamer API in the internal
// executor to avoid possible concurrency with the "outer" query (which
// might be using the RootTxn).
sd.LocalOnlySessionData.StreamerEnabled = false
// If the internal executor creates a new transaction, then it runs in
// SERIALIZABLE. If it's used in an existing transaction, then it inherits the
// isolation level of the existing transaction.
sd.DefaultTxnIsolationLevel = int64(tree.SerializableIsolation)
}
// applyOverrides overrides the respective fields from sd for all the fields set on o.
func applyOverrides(o sessiondata.InternalExecutorOverride, sd *sessiondata.SessionData) {
if !o.User.Undefined() {
sd.UserProto = o.User.EncodeProto()
}
if o.Database != "" {
sd.Database = o.Database
}
if o.ApplicationName != "" {
sd.ApplicationName = o.ApplicationName
}
if o.SearchPath != nil {
sd.SearchPath = *o.SearchPath
}
if o.DatabaseIDToTempSchemaID != nil {
sd.DatabaseIDToTempSchemaID = o.DatabaseIDToTempSchemaID
}
if o.QualityOfService != nil {
sd.DefaultTxnQualityOfService = o.QualityOfService.ValidateInternal()
}
// We always override the injection knob based on the override struct.
sd.InjectRetryErrorsEnabled = o.InjectRetryErrorsEnabled
}
func (ie *InternalExecutor) maybeRootSessionDataOverride(
opName string,
) sessiondata.InternalExecutorOverride {
if ie.sessionDataStack == nil {
return sessiondata.InternalExecutorOverride{
User: username.RootUserName(),
ApplicationName: catconstants.InternalAppNamePrefix + "-" + opName,
}
}
o := sessiondata.NoSessionDataOverride
sd := ie.sessionDataStack.Top()
if sd.User().Undefined() {
o.User = username.RootUserName()
}
if sd.ApplicationName == "" {
o.ApplicationName = catconstants.InternalAppNamePrefix + "-" + opName
}
return o
}
var rowsAffectedResultColumns = colinfo.ResultColumns{
colinfo.ResultColumn{
Name: "rows_affected",
Typ: types.Int,
},
}
// execInternal is the main entry point for executing a statement via the
// InternalExecutor. From the high level it does the following:
// - parses the statement as well as its arguments
// - creates an "internal" connExecutor that runs in a separate goroutine
// - pushes a few commands onto the StmtBuf of the connExecutor to be evaluated
// - blocks until the first row of data is sent by the connExecutor
// - returns the rowsIterator that can consume the result of the statement.
//
// Only a single statement is supported. If there are no query arguments, then
// {ExecStmt, Sync} commands are pushed onto the StmtBuf, if there are some
// query arguments, then {PrepareStmt, BindStmt, ExecPortal, Sync} are pushed.
//
// The coordination between the rowsIterator and the connExecutor is managed by
// the internalClientComm as well as the ieResultChannel. The rowsIterator is
// the reader of the ieResultChannel while the connExecutor is the writer. The
// connExecutor goroutine exits (achieved by closing the StmtBuf) once the
// result for the Sync command evaluation is closed.
//
// execInternal defines two callbacks that are passed into the connExecutor
// machinery:
// - syncCallback is called when the result for the Sync command evaluation is
// closed. It is responsible for closing the StmtBuf (to allow the connExecutor
// to exit its 'run' loop) as well iterating over the results to see whether an
// error was encountered. Note that, unlike rows that are sent directly from the
// streamingCommandResult (the writer) to the rowsIterator (the reader), errors
// are buffered in the results - this is needed since the errors might be
// updated by the connExecutor after they have been generated (e.g. replacing
// context cancellation error with a nice "statement timed out" error).
// - errCallback is called when the connExecutor's 'run' returns an error in
// order to propagate the error to the rowsIterator.
//
// It's worth noting that rows as well some metadata (column schema as well as
// "rows affected" number) are sent directly from the streamingCommandResult to
// the rowsIterator, meaning that this communication doesn't go through the
// internalClientComm.
//
// The returned rowsIterator can be synchronized with the connExecutor goroutine
// if "synchronous" ieResultChannel is provided. In this case, only one
// goroutine (among the rowsIterator and the connExecutor) is active at any
// point in time since each read / write is blocked until the "send" / "receive"
// happens on the ieResultChannel.
//
// It's also worth noting that execInternal doesn't return until the
// connExecutor reaches the execution engine (i.e. until after the query
// planning has been performed). This blocking behavior is still respected in
// case a retry error occurs after the column schema is communicated, but before
// the stmt reaches the execution engine. This is needed in order to avoid
// concurrent access to the txn by the rowsIterator and the connExecutor
// goroutines. In particular, this blocking allows us to avoid invalid
// concurrent txn access when during the stmt evaluation the internal executor
// needs to run "nested" internally-executed stmt (see #62415 for an example).
//
// An additional responsibility of the internalClientComm is handling the retry
// errors. If a retry error is encountered with an implicit txn (i.e. nil txn
// is passed to execInternal), then we do our best to retry the execution
// transparently; however, we can **not** do so in all cases, so sometimes the
// retry error will be propagated to the user of the rowsIterator. In
// particular, here is the summary of how retries are handled:
// - If the retry error occurs after some rows have been sent from the
// streamingCommandResult to the rowsIterator, we have no choice but to return
// the retry error to the caller.
// - The only exception to this is when the stmt of "Rows" type was issued via
// ExecEx call. In such a scenario, we only need to report the number of
// "rows affected" that we obtain by counting all rows seen by the
// rowsIterator. With such a setup, we can transparently retry the execution
// of the corresponding command by simply resetting the counter when
// discarding the result of Sync command after the retry error occurs.
// - If the retry error occurs after the "rows affected" metadata was sent for
// stmts of "RowsAffected" type, then we will always retry transparently. This
// is achieved by overriding the "rows affected" number, stored in the
// rowsIterator, with the latest information. With such setup, even if the
// stmt execution before the retry communicated its incorrect "rows affected"
// information, that info is overridden accordingly after the connExecutor
// re-executes the corresponding command.
// - If the retry error occurs after the column schema is sent, then - similar
// to how we handle the "rows affected" metadata - we always transparently
// retry by keeping the latest information.
//
// Note that only implicit txns can be retried internally. If an explicit txn is
// passed to execInternal, then the retry error is propagated to the
// rowsIterator in the following manner (say we use {ExecStmt, Sync} commands):
// - ExecStmt evaluation encounters a retry error
// - the error is stored in internalClientComm.results[0] (since it's not
// propagated right away to the rowsIterator)
// - the connExecutor's state machine rolls back the stmt
// - the connExecutor then processes the Sync command, and when the
// corresponding result is closed, syncCallback is called
// - in the syncCallback we iterate over two results and find the error in the
// zeroth result - the error is sent on the ieResultChannel
// - the rowsIterator receives the error and returns it to the caller of
// execInternal.
// execInternal executes a statement.
//
// sessionDataOverride can be used to control select fields in the executor's
// session data. It overrides what has been previously set through
// SetSessionData(), if anything.
func (ie *InternalExecutor) execInternal(
ctx context.Context,
opName string,
rw *ieResultChannel,
mode ieExecutionMode,
txn *kv.Txn,
sessionDataOverride sessiondata.InternalExecutorOverride,
stmt string,
qargs ...interface{},
) (r *rowsIterator, retErr error) {
startup.AssertStartupRetry(ctx)
if err := ie.checkIfTxnIsConsistent(txn); err != nil {
return nil, err
}
ctx = logtags.AddTag(ctx, "intExec", opName)
var sd *sessiondata.SessionData
if ie.sessionDataStack != nil {
// TODO(andrei): Properly clone (deep copy) ie.sessionData.
sd = ie.sessionDataStack.Top().Clone()
} else {
sd = NewInternalSessionData(context.Background(), ie.s.cfg.Settings, "" /* opName */)
}
applyInternalExecutorSessionExceptions(sd)
applyOverrides(sessionDataOverride, sd)
sd.Internal = true
if sd.User().Undefined() {
return nil, errors.AssertionFailedf("no user specified for internal query")
}
// When the connEx is serving an internal executor, it can inherit the
// application name from an outer session. This happens e.g. during ::regproc
// casts and built-in functions that use SQL internally. In that case, we do
// not want to record statistics against the outer application name directly;
// instead we want to use a separate bucket. However we will still want to
// have separate buckets for different applications so that we can measure
// their respective "pressure" on internal queries. Hence the choice here to
// add the delegate prefix to the current app name.
if sd.ApplicationName == "" || sd.ApplicationName == catconstants.InternalAppNamePrefix {
sd.ApplicationName = catconstants.InternalAppNamePrefix + "-" + opName
} else if !strings.HasPrefix(sd.ApplicationName, catconstants.InternalAppNamePrefix) {
// If this is already an "internal app", don't put more prefix.
sd.ApplicationName = catconstants.DelegatedAppNamePrefix + sd.ApplicationName
}
// If the caller has injected a mapping to temp schemas, install it, and
// leave it installed for the rest of the transaction.
if ie.extraTxnState != nil && sd.DatabaseIDToTempSchemaID != nil {
p := catsessiondata.NewDescriptorSessionDataStackProvider(sessiondata.NewStack(sd))
ie.extraTxnState.descCollection.SetDescriptorSessionDataProvider(p)
}
// The returned span is finished by this function in all error paths, but if
// an iterator is returned, then we transfer the responsibility of closing
// the span to the iterator. This is necessary so that the connExecutor
// exits before the span is finished.
ctx, sp := tracing.EnsureChildSpan(ctx, ie.s.cfg.AmbientCtx.Tracer, opName)
stmtBuf := NewStmtBuf()
var wg sync.WaitGroup