-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
internal.go
2115 lines (1943 loc) · 72.3 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 CockroachDB Software License
// included in the /LICENSE file.
package sql
import (
"context"
"strings"
"sync"
"time"
"github.com/cockroachdb/cockroach/pkg/keys"
"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"
"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/parser/statements"
"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/growstack"
"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/stop"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/logtags"
"github.com/cockroachdb/redact"
)
// 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 varName == "optimizer_use_histograms" {
// Do not use histograms when optimizing internal executor
// queries. This causes a significant performance regression.
// TODO(#102954): Diagnose and fix this.
continue
}
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
sd.StmtTimeout = 0
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(mon.Options{
Name: "internal SQL executor",
CurCount: memMetrics.CurBytesCount,
MaxHist: memMetrics.MaxBytesHist,
Settings: settings,
LongLiving: true,
})
}
// 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)
}
}
var ieRowsAffectedRetryLimit = settings.RegisterIntSetting(
settings.ApplicationLevel,
"sql.internal_executor.rows_affected_retry_limit",
"limit on the number of retries that can be transparently performed "+
"by the InternalExecutor's Exec{Ex} methods",
5,
settings.NonNegativeInt,
)
func (ie *InternalExecutor) runWithEx(
ctx context.Context,
opName redact.RedactableString,
txn *kv.Txn,
w ieResultWriter,
mode ieExecutionMode,
sd *sessiondata.SessionData,
stmtBuf *StmtBuf,
wg *sync.WaitGroup,
syncCallback func([]*streamingCommandResult),
errCallback func(error),
attributeToUser bool,
growStackSize bool,
) error {
ex, err := ie.initConnEx(ctx, txn, w, mode, sd, stmtBuf, syncCallback, attributeToUser)
if err != nil {
return err
}
wg.Add(1)
cleanup := func(ctx context.Context) {
closeMode := normalClose
if txn != nil {
closeMode = externalTxnClose
}
ex.close(ctx, closeMode)
wg.Done()
}
if err = ie.s.cfg.Stopper.RunAsyncTaskEx(
ctx,
stop.TaskOpts{
TaskName: opName.StripMarkers(),
SpanOpt: stop.ChildSpan,
},
func(ctx context.Context) {
defer cleanup(ctx)
// TODO(yuzefovich): benchmark whether we should be growing the
// stack size unconditionally.
if growStackSize {
growstack.Grow()
}
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()
},
); err != nil {
// The goroutine wasn't started, so we need to perform the cleanup
// ourselves.
cleanup(ctx)
return err
}
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),
attributeToUser bool,
) (*connExecutor, error) {
clientComm := &internalClientComm{
w: w,
mode: mode,
sync: syncCallback,
}
clientComm.results = clientComm.resultsScratch[:0]
clientComm.rowsAffectedState.rewind = func() {
var zero int
_ = w.addResult(ctx, ieIteratorResult{rowsAffected: &zero})
}
clientComm.rowsAffectedState.numRewindsLimit = ieRowsAffectedRetryLimit.Get(&ie.s.cfg.Settings.SV)
applicationStats := ie.s.sqlStats.GetApplicationStats(sd.ApplicationName)
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 {
var postSetupFn func(*connExecutor)
// Inject any synthetic descriptors into the internal executor after
// it's created.
if ie.syntheticDescriptors != nil {
postSetupFn = func(ex *connExecutor) {
// Note that we don't need to set shouldResetSyntheticDescriptors
// since ReleaseAll will be called on the descs.Collection which
// will also release synthetic descriptors.
ex.extraTxnState.descCollection.SetSyntheticDescriptors(ie.syntheticDescriptors)
}
}
srvMetrics := &ie.s.InternalMetrics
if attributeToUser {
srvMetrics = &ie.s.Metrics
}
ex = ie.s.newConnExecutor(
ctx,
executorTypeInternal,
sdMutIterator,
stmtBuf,
clientComm,
// memMetrics is only about attributing memory monitoring to the
// right metric, so we choose to ignore the 'attributeToUser'
// boolean and use "internal memory metrics" unconditionally. (We
// will be using the internal sql executor as the parent during
// query execution, using different metrics here could lead to
// confusion.)
ie.memMetrics,
srvMetrics,
applicationStats,
ie.s.cfg.GenerateID(),
false, /* underOuterTxn */
postSetupFn,
)
} else {
ex, err = ie.newConnExecutorWithTxn(
ctx,
txn,
sdMutIterator,
stmtBuf,
clientComm,
applicationStats,
attributeToUser,
)
if err != nil {
return nil, err
}
}
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,
attributeToUser bool,
) (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
var postSetupFn func(*connExecutor)
// If an internal executor is run with a not-nil txn and has some extra txn
// state already set up, we may want to let it inherit the descriptor
// collection, schema change job records and job collections from the
// caller.
if ie.extraTxnState != nil {
postSetupFn = func(ex *connExecutor) {
ex.extraTxnState.skipResettingSchemaObjects = true
ex.extraTxnState.descCollection = ie.extraTxnState.descCollection
ex.extraTxnState.jobs = ie.extraTxnState.jobs
ex.extraTxnState.schemaChangerState = ie.extraTxnState.schemaChangerState
ex.extraTxnState.shouldResetSyntheticDescriptors = shouldResetSyntheticDescriptors
}
}
srvMetrics := &ie.s.InternalMetrics
if attributeToUser {
srvMetrics = &ie.s.Metrics
}
ex = ie.s.newConnExecutor(
ctx,
executorTypeInternal,
sdMutIterator,
stmtBuf,
clientComm,
// memMetrics is only about attributing memory monitoring to the right
// metric, so we choose to ignore the 'attributeToUser' boolean and use
// "internal memory metrics" unconditionally. (We will be using the
// internal sql executor as the parent during query execution, using
// different metrics here could lead to confusion.)
ie.memMetrics,
srvMetrics,
applicationStats,
ie.s.cfg.GenerateID(),
true, /* underOuterTxn */
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.
if err := ex.dataMutatorIterator.applyOnEachMutatorError(func(m sessionDataMutator) error {
return m.SetReadOnly(true)
}); err != nil {
return nil, err
}
}
// 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,
txn.GetOmitInRangefeeds(),
)
// 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
}
var _ isql.Rows = &rowsIterator{}
var _ eval.InternalRows = &rowsIterator{}
func (r *rowsIterator) Next(ctx context.Context) (bool, error) {
for !r.done && r.lastErr == nil {
var data ieIteratorResult
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.
data = *r.first
r.first = nil
} else {
nextItem, done, err := r.r.nextResult(ctx)
if err != nil || done {
r.lastErr = err
break
}
data = nextItem
}
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
continue
}
// 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).
if r.mode == rowsAffectedIEExecutionMode && data.cols != nil {
continue
}
if data.cols != nil {
r.lastErr = errors.AssertionFailedf("unexpectedly received non-nil cols in Next: %v", data)
} else if data.err == nil {
r.lastErr = errors.AssertionFailedf("unexpectedly empty ieIteratorResult object")
} else {
r.lastErr = data.err
}
}
r.done = true
// r.Close() is idempotent, so it's okay to call multiple times.
_ = r.Close()
return false, r.lastErr
}
func (r *rowsIterator) Cur() tree.Datums {
return r.lastRow
}
func (r *rowsIterator) RowsAffected() int {
return r.rowsAffected
}
func (r *rowsIterator) Close() error {
// Ensure that we wait for the connExecutor goroutine to exit.
defer r.wg.Wait()
// Closing the stmtBuf will tell the connExecutor to stop executing commands
// (if it hasn't exited yet).
r.stmtBuf.Close()
// Close the ieResultReader to tell the writer that we're done.
if err := r.r.close(); err != nil && r.lastErr == nil {
r.lastErr = err
}
if r.lastErr != nil && r.errCallback != nil {
r.lastErr = r.errCallback(r.lastErr)
r.errCallback = nil
}
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 redact.RedactableString,
txn *kv.Txn,
stmt string,
qargs ...interface{},
) ([]tree.Datums, error) {
return ie.QueryBufferedEx(ctx, opName, txn, ie.maybeNodeSessionDataOverride(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 redact.RedactableString,
txn *kv.Txn,
session sessiondata.InternalExecutorOverride,
stmt string,
qargs ...interface{},
) ([]tree.Datums, error) {
datums, _, err := ie.queryInternalBuffered(ctx, opName, txn, session, ieStmt{stmt: 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 redact.RedactableString,
txn *kv.Txn,
session sessiondata.InternalExecutorOverride,
stmt string,
qargs ...interface{},
) ([]tree.Datums, colinfo.ResultColumns, error) {
datums, cols, err := ie.queryInternalBuffered(ctx, opName, txn, session, ieStmt{stmt: stmt}, 0 /* limit */, qargs...)
return datums, cols, err
}
func (ie *InternalExecutor) queryInternalBuffered(
ctx context.Context,
opName redact.RedactableString,
txn *kv.Txn,
sessionDataOverride sessiondata.InternalExecutorOverride,
stmt ieStmt,
// 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 redact.RedactableString,
txn *kv.Txn,
stmt string,
qargs ...interface{},
) (tree.Datums, error) {
return ie.QueryRowEx(ctx, opName, txn, ie.maybeNodeSessionDataOverride(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 redact.RedactableString,
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
}
// QueryRowExParsed is like QueryRowEx, but takes a parsed statement.
func (ie *InternalExecutor) QueryRowExParsed(
ctx context.Context,
opName redact.RedactableString,
txn *kv.Txn,
session sessiondata.InternalExecutorOverride,
parsedStmt statements.Statement[tree.Statement],
qargs ...interface{},
) (tree.Datums, error) {
rows, _, err := ie.queryRowExWithCols(ctx, opName, txn, session, ieStmt{parsed: parsedStmt}, 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 redact.RedactableString,
txn *kv.Txn,
session sessiondata.InternalExecutorOverride,
stmt string,
qargs ...interface{},
) (tree.Datums, colinfo.ResultColumns, error) {
return ie.queryRowExWithCols(ctx, opName, txn, session, ieStmt{stmt: stmt}, qargs...)
}
// QueryRowExWithCols is like QueryRowEx, additionally returning the computed
// ResultColumns of the input query.
func (ie *InternalExecutor) queryRowExWithCols(
ctx context.Context,
opName redact.RedactableString,
txn *kv.Txn,
session sessiondata.InternalExecutorOverride,
stmt ieStmt,
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.SQL()}
}
}
// 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 redact.RedactableString,
txn *kv.Txn,
stmt string,
qargs ...interface{},
) (int, error) {
return ie.ExecEx(ctx, opName, txn, ie.maybeNodeSessionDataOverride(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 redact.RedactableString,
txn *kv.Txn,
session sessiondata.InternalExecutorOverride,
stmt string,
qargs ...interface{},
) (int, error) {
return ie.execIEStmt(ctx, opName, txn, session, ieStmt{stmt: stmt}, qargs...)
}
// ExecParsed is like Exec but allows the caller to provide an already parsed
// statement.
func (ie *InternalExecutor) ExecParsed(
ctx context.Context,
opName redact.RedactableString,
txn *kv.Txn,
o sessiondata.InternalExecutorOverride,
parsedStmt statements.Statement[tree.Statement],
qargs ...interface{},
) (int, error) {
return ie.execIEStmt(ctx, opName, txn, o, ieStmt{parsed: parsedStmt}, qargs...)
}
type ieStmt struct {
// Only one should be set.
stmt string
parsed statements.Statement[tree.Statement]
}
func (s *ieStmt) SQL() string {
if s.stmt != "" {
return s.stmt
}
return s.parsed.SQL
}
// execIEStmt extracts the shared logic between ExecEx and ExecParsed.
func (ie *InternalExecutor) execIEStmt(
ctx context.Context,
opName redact.RedactableString,
txn *kv.Txn,
session sessiondata.InternalExecutorOverride,
stmt ieStmt,
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 redact.RedactableString,
txn *kv.Txn,
stmt string,
qargs ...interface{},
) (isql.Rows, error) {
return ie.QueryIteratorEx(ctx, opName, txn, ie.maybeNodeSessionDataOverride(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 redact.RedactableString,
txn *kv.Txn,
session sessiondata.InternalExecutorOverride,
stmt string,
qargs ...interface{},
) (isql.Rows, error) {
return ie.execInternal(
ctx, opName, newSyncIEResultChannel(), defaultIEExecutionMode, txn, session, ieStmt{stmt: 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
// 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
if o.OptimizerUseHistograms {
sd.OptimizerUseHistograms = true
}
if o.OriginIDForLogicalDataReplication != 0 {
sd.OriginIDForLogicalDataReplication = o.OriginIDForLogicalDataReplication
}
if o.OriginTimestampForLogicalDataReplication.IsSet() {
sd.OriginTimestampForLogicalDataReplication = o.OriginTimestampForLogicalDataReplication
}
if o.PlanCacheMode != nil {
sd.PlanCacheMode = *o.PlanCacheMode
}
if o.DisablePlanGists {
sd.DisablePlanGists = true
}
if o.MultiOverride != "" {
overrides := strings.Split(o.MultiOverride, ",")
for _, override := range overrides {
parts := strings.Split(override, "=")
if len(parts) == 2 {
sd.Update(parts[0], parts[1])
}
}
}
// Add any new overrides above the MultiOverride.
}
var ieMultiOverride = settings.RegisterStringSetting(
settings.ApplicationLevel,
"sql.internal_executor.session_overrides",
"comma-separated list of 'variable=value' pairs that change the corresponding "+
"session variables used by the InternalExecutor (performed on a best-effort basis)",
"",
settings.WithValidateString(func(_ *settings.Values, val string) error {
if val == "" {
return nil
}
overrides := strings.Split(val, ",")
for _, override := range overrides {
parts := strings.Split(override, "=")
if len(parts) != 2 {
return errors.Newf("invalid override format: expected 'variable=value', found %q", override)
}
}
return nil
}),
)
func (ie *InternalExecutor) maybeNodeSessionDataOverride(
opName redact.RedactableString,
) sessiondata.InternalExecutorOverride {
if ie.sessionDataStack == nil {
return sessiondata.InternalExecutorOverride{
User: username.NodeUserName(),