/
context.go
1551 lines (1329 loc) · 38.6 KB
/
context.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 2014-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.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/APL2.txt.
package execution
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"regexp"
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/couchbase/cbauth"
"github.com/couchbase/query/algebra"
"github.com/couchbase/query/auth"
"github.com/couchbase/query/datastore"
"github.com/couchbase/query/errors"
"github.com/couchbase/query/expression"
"github.com/couchbase/query/logging"
"github.com/couchbase/query/logging/event"
"github.com/couchbase/query/memory"
"github.com/couchbase/query/plan"
"github.com/couchbase/query/planner"
"github.com/couchbase/query/system"
"github.com/couchbase/query/tenant"
"github.com/couchbase/query/timestamp"
"github.com/couchbase/query/transactions"
"github.com/couchbase/query/util"
"github.com/couchbase/query/value"
)
type Phases int
const (
// Execution layer
AUTHORIZE = Phases(iota)
FETCH
INDEX_SCAN
PRIMARY_SCAN
JOIN
INDEX_JOIN
NL_JOIN
HASH_JOIN
NEST
INDEX_NEST
NL_NEST
HASH_NEST
COUNT
INDEX_COUNT
FILTER
SORT
PROJECT
STREAM
INSERT
DELETE
UPDATE
UPSERT
MERGE
INFER
FTS_SEARCH
UPDATE_STAT
// Expression layer
ADVISOR
// Server layer
INSTANTIATE
PARSE
PLAN
REPREPARE
RUN
PHASES // Sizer
)
func (phase Phases) String() string {
return _PHASE_NAMES[phase]
}
var _PHASE_NAMES = []string{
AUTHORIZE: "authorize",
FETCH: "fetch",
INDEX_SCAN: "indexScan",
PRIMARY_SCAN: "primaryScan",
JOIN: "join",
INDEX_JOIN: "indexJoin",
NL_JOIN: "nestedLoopJoin",
HASH_JOIN: "hashJoin",
NEST: "nest",
INDEX_NEST: "indexNest",
NL_NEST: "nestedLoopNest",
HASH_NEST: "hashNest",
COUNT: "count",
INDEX_COUNT: "indexCount",
SORT: "sort",
FILTER: "filter",
PROJECT: "project",
STREAM: "stream",
INSERT: "insert",
DELETE: "delete",
UPDATE: "update",
UPSERT: "upsert",
MERGE: "merge",
INFER: "inferKeySpace",
FTS_SEARCH: "ftsSearch",
UPDATE_STAT: "updateStatistics",
ADVISOR: "advisor",
INSTANTIATE: "instantiate",
PARSE: "parse",
PLAN: "plan",
REPREPARE: "reprepare",
RUN: "run",
}
const _PHASE_UPDATE_COUNT uint64 = 100
type Output interface {
SetUp() // Any action necessary before processing results
Result(item value.AnnotatedValue) bool // Process individual items
CloseResults() // Signal that results are through
Abort(err errors.Error)
Fatal(err errors.Error)
Error(err errors.Error)
Warning(wrn errors.Error)
AddMutationCount(uint64)
MutationCount() uint64
SortCount() uint64
SetSortCount(i uint64)
AddPhaseOperator(p Phases)
AddPhaseCount(p Phases, c uint64)
FmtPhaseCounts() map[string]interface{}
FmtPhaseOperators() map[string]interface{}
AddPhaseTime(phase Phases, duration time.Duration)
FmtPhaseTimes() map[string]interface{}
FmtOptimizerEstimates(op Operator) map[string]interface{}
AddCpuTime(duration time.Duration)
AddTenantUnits(s tenant.Service, cu tenant.Unit)
TrackMemory(size uint64)
SetTransactionStartTime(t time.Time)
}
// context flags
const (
CONTEXT_IS_ADVISOR = 1 << iota // Advisor() function
)
type Context struct {
requestId string
datastore datastore.Datastore
systemstore datastore.Systemstore
namespace string
indexApiVersion int
featureControls uint64
queryContext string
useFts bool
useCBO bool
useReplica bool
optimizer planner.Optimizer
readonly bool
maxParallelism int
scanCap int64
pipelineCap int64
pipelineBatch int
isPrepared bool
reqDeadline time.Time
now time.Time
namedArgs map[string]value.Value
positionalArgs value.Values
credentials *auth.Credentials
consistency datastore.ScanConsistency
originalConsistency datastore.ScanConsistency
scanVectorSource timestamp.ScanVectorSource
output Output
prepared *plan.Prepared
subExecTrees *subqueryArrayMap
subplans *subqueryMap
subresults *subqueryMap
httpRequest *http.Request
mutex sync.RWMutex
allowlist map[string]interface{}
inlistHashMap map[*expression.In]*expression.InlistHash
inlistHashLock sync.RWMutex
memoryQuota uint64
reqTimeout time.Duration
deltaKeyspaces map[string]bool
durabilityLevel datastore.DurabilityLevel
durabilityTimeout time.Duration
txContext *transactions.TranContext
txTimeout time.Duration
txImplicit bool
txData []byte
txDataVal value.Value
atrCollection string
numAtrs int
kvTimeout time.Duration
preserveExpiry bool
flags uint32
recursionCount int32
result func(context *Context, item value.AnnotatedValue) bool
likeRegexMap map[*expression.Like]*expression.LikeRegex
udfValueMap *sync.Map
udfHandleMap map[*executionHandle]bool
tracked bool
bitFilterMap map[string]*BitFilterTerm
bitFilterLock sync.RWMutex
tenantCtx tenant.Context
memorySession memory.MemorySession
keysToSkip *sync.Map
keysToSkipLength int32
planPreparedTime time.Time // time the plan was created
}
func NewContext(requestId string, datastore datastore.Datastore, systemstore datastore.Systemstore,
namespace string, readonly bool, maxParallelism int, scanCap, pipelineCap int64,
pipelineBatch int, namedArgs map[string]value.Value, positionalArgs value.Values,
credentials *auth.Credentials, consistency datastore.ScanConsistency,
scanVectorSource timestamp.ScanVectorSource, output Output,
prepared *plan.Prepared, indexApiVersion int, featureControls uint64, queryContext string,
useFts, useCBO bool, optimizer planner.Optimizer, kvTimeout, reqTimeout time.Duration) *Context {
rv := &Context{
requestId: requestId,
datastore: datastore,
systemstore: systemstore,
namespace: namespace,
readonly: readonly,
maxParallelism: maxParallelism,
scanCap: scanCap,
pipelineCap: pipelineCap,
pipelineBatch: pipelineBatch,
now: time.Now(),
namedArgs: namedArgs,
positionalArgs: positionalArgs,
credentials: credentials,
consistency: consistency,
scanVectorSource: scanVectorSource,
output: output,
subplans: nil,
subresults: nil,
prepared: prepared,
indexApiVersion: indexApiVersion,
featureControls: featureControls,
useReplica: false,
queryContext: queryContext,
useFts: useFts,
useCBO: useCBO,
optimizer: optimizer,
inlistHashMap: nil,
kvTimeout: kvTimeout,
result: setup,
likeRegexMap: nil,
reqTimeout: reqTimeout,
udfValueMap: &sync.Map{},
keysToSkip: &sync.Map{},
}
if rv.maxParallelism <= 0 || rv.maxParallelism > util.NumCPU() {
rv.maxParallelism = util.NumCPU()
}
return rv
}
func (this *Context) Copy() *Context {
rv := &Context{
requestId: this.requestId,
datastore: this.datastore,
systemstore: this.systemstore,
namespace: this.namespace,
readonly: this.readonly,
maxParallelism: this.maxParallelism,
scanCap: this.scanCap,
pipelineCap: this.pipelineCap,
pipelineBatch: this.pipelineBatch,
now: this.now,
credentials: this.credentials,
consistency: this.consistency,
originalConsistency: this.originalConsistency,
scanVectorSource: this.scanVectorSource,
output: this.output,
result: this.result,
httpRequest: this.httpRequest,
indexApiVersion: this.indexApiVersion,
featureControls: this.featureControls,
useReplica: this.useReplica,
queryContext: this.queryContext,
useFts: this.useFts,
useCBO: this.useCBO,
optimizer: this.optimizer,
deltaKeyspaces: this.deltaKeyspaces,
txTimeout: this.txTimeout,
txImplicit: this.txImplicit,
txContext: this.txContext,
txData: this.txData,
txDataVal: this.txDataVal,
kvTimeout: this.kvTimeout,
atrCollection: this.atrCollection,
numAtrs: this.numAtrs,
preserveExpiry: this.preserveExpiry,
flags: this.flags,
reqTimeout: this.reqTimeout,
memoryQuota: this.memoryQuota,
allowlist: this.allowlist,
udfValueMap: this.udfValueMap,
recursionCount: this.recursionCount,
tenantCtx: this.tenantCtx,
memorySession: this.memorySession,
keysToSkip: this.keysToSkip,
keysToSkipLength: this.keysToSkipLength,
planPreparedTime: this.planPreparedTime,
}
rv.SetDurability(this.DurabilityLevel(), this.DurabilityTimeout())
return rv
}
func (this *Context) NewQueryContext(queryContext string, readonly bool) interface{} {
rv := this.Copy()
rv.queryContext = queryContext
rv.readonly = readonly
return rv
}
func (this *Context) QueryContext() string {
return this.queryContext
}
func (this *Context) RequestId() string {
return this.requestId
}
func (this *Context) Type() string {
if this.prepared != nil {
return this.prepared.Type()
}
return ""
}
func (this *Context) Datastore() datastore.Datastore {
return this.datastore
}
func (this *Context) SetNamedArgs(namedArgs map[string]value.Value) {
this.namedArgs = namedArgs
}
func (this *Context) SetPositionalArgs(positionalArgs value.Values) {
this.positionalArgs = positionalArgs
}
func (this *Context) SetPrepared(prepared *plan.Prepared) {
this.prepared = prepared
}
func (this *Context) SetAllowlist(val map[string]interface{}) {
this.allowlist = val
}
func (this *Context) GetAllowlist() map[string]interface{} {
return this.allowlist
}
func (this *Context) Optimizer() planner.Optimizer {
return this.optimizer
}
func (this *Context) DatastoreVersion() string {
return this.datastore.Info().Version()
}
func (this *Context) Systemstore() datastore.Systemstore {
return this.systemstore
}
func (this *Context) Namespace() string {
return this.namespace
}
func (this *Context) Readonly() bool {
return this.readonly
}
func (this *Context) MaxParallelism() int {
return this.maxParallelism
}
func (this *Context) Now() time.Time {
return this.now
}
func (this *Context) NamedArg(name string) (value.Value, bool) {
val, ok := this.namedArgs[name]
return val, ok
}
// The position is 1-based (i.e. 1 is the first position)
func (this *Context) PositionalArg(position int) (value.Value, bool) {
position--
if position >= 0 && position < len(this.positionalArgs) {
return this.positionalArgs[position], true
} else {
return nil, false
}
}
func (this *Context) GetTimeout() time.Duration {
return this.reqTimeout
}
func (this *Context) GetTxContext() interface{} {
return this.txContext
}
func (this *Context) TxContext() *transactions.TranContext {
return this.txContext
}
func (this *Context) TxDataVal() value.Value {
return this.txDataVal
}
func (this *Context) SetTxContext(tc interface{}) {
this.txContext, _ = tc.(*transactions.TranContext)
}
func (this *Context) AdjustTimeout(timeout time.Duration, stmtType string, isPrepare bool) time.Duration {
if this.txContext != nil {
if !isPrepare && (stmtType == "COMMIT" || stmtType == "ROLLBACK") {
// Don't start timer for the commit and rollback
return 0
}
timeout = this.txContext.TxTimeRemaining()
// At least keep 10ms so that executor can lanunch before timer kicks in.
if timeout <= 10*time.Millisecond {
timeout = 10 * time.Millisecond
}
}
return timeout
}
func (this *Context) Credentials() *auth.Credentials {
return this.credentials
}
func (this *Context) UrlCredentials(urlS string) *auth.Credentials {
// For the cases where the request doesnt have credentials but uses an auth
// token or x509 certs, we need to derive the credentials to be able to query
// the fts index.
if urlS == "" {
dUrl, _ := url.Parse(this.DatastoreURL())
urlS = dUrl.Hostname() + ":" + dUrl.Port()
}
authenticator := cbauth.Default
u, p, _ := authenticator.GetHTTPServiceAuth(urlS)
return &auth.Credentials{map[string]string{u: p}, nil, nil, nil}
}
func (this *Context) UseReplica() bool {
return this.useReplica
}
func (this *Context) SetUseReplica(r bool) {
this.useReplica = r
}
func (this *Context) ScanConsistency() datastore.ScanConsistency {
return this.consistency
}
func (this *Context) SetScanConsistency(consistency, originalConsistency datastore.ScanConsistency) {
this.consistency = consistency
this.originalConsistency = originalConsistency
}
func (this *Context) ScanVectorSource() timestamp.ScanVectorSource {
return this.scanVectorSource
}
func (this *Context) GetScanCap() int64 {
if this.scanCap > 0 {
return this.scanCap
} else {
return datastore.GetScanCap()
}
}
func (this *Context) ScanCap() int64 {
return this.scanCap
}
func (this *Context) SetScanCap(scanCap int64) {
this.scanCap = scanCap
}
func (this *Context) GetReqDeadline() time.Time {
return this.reqDeadline
}
func (this *Context) SetReqDeadline(reqDeadline time.Time) {
this.reqDeadline = reqDeadline
}
func (this *Context) SetMemoryQuota(memoryQuota uint64) {
this.memoryQuota = memoryQuota * util.MiB
}
func (this *Context) SetMemorySession(m memory.MemorySession) {
if m != nil {
this.memorySession = m
}
}
func (this *Context) GetPipelineCap() int64 {
if this.pipelineCap > 0 {
return this.pipelineCap
} else {
return GetPipelineCap()
}
}
func (this *Context) PipelineCap() int64 {
return this.pipelineCap
}
func (this *Context) SetPipelineCap(pipelineCap int64) {
this.pipelineCap = pipelineCap
}
func (this *Context) GetPipelineBatch() int {
if this.pipelineBatch > 0 {
return this.pipelineBatch
} else {
return PipelineBatchSize()
}
}
func (this *Context) PipelineBatch() int {
return this.pipelineBatch
}
func (this *Context) SetPipelineBatch(pipelineBatch int) {
this.pipelineBatch = pipelineBatch
}
func (this *Context) IsPrepared() bool {
return this.isPrepared
}
func (this *Context) SetIsPrepared(isPrepared bool) {
this.isPrepared = isPrepared
}
func (this *Context) AddMutationCount(i uint64) {
this.output.AddMutationCount(i)
}
func (this *Context) MutationCount() uint64 {
return this.output.MutationCount()
}
func (this *Context) SetSortCount(i uint64) {
this.output.SetSortCount(i)
}
func (this *Context) SortCount() uint64 {
return this.output.SortCount()
}
func (this *Context) AddPhaseOperator(p Phases) {
this.output.AddPhaseOperator(p)
}
func (this *Context) AddPhaseCount(p Phases, c uint64) {
this.output.AddPhaseCount(p, c)
}
func (this *Context) AddPhaseTime(phase Phases, duration time.Duration) {
this.output.AddPhaseTime(phase, duration)
}
func (this *Context) queryCU(duration time.Duration) {
}
func setup(context *Context, item value.AnnotatedValue) bool {
context.output.SetUp()
context.result = result
return context.output.Result(item)
}
func result(context *Context, item value.AnnotatedValue) bool {
return context.output.Result(item)
}
func (this *Context) Result(item value.AnnotatedValue) bool {
return this.result(this, item)
}
func (this *Context) CloseResults() {
this.output.CloseResults()
}
func (this *Context) RecursionCount() int {
return int(this.recursionCount)
}
func (this *Context) IncRecursionCount(inc int) int {
return int(atomic.AddInt32(&this.recursionCount, int32(inc)))
}
type eventError struct {
t event.EventType
l event.EventLevel
}
var eventErrors = map[errors.ErrorCode]eventError{
errors.E_MEMORY_QUOTA_EXCEEDED: {event.QUOTA_EXCEEDED, event.INFO},
}
func (this *Context) Error(err errors.Error) {
if evt, ok := eventErrors[err.Code()]; ok {
event.Report(evt.t, evt.l, "request-id", this.RequestId())
}
this.output.Error(err)
}
func (this *Context) Errors(errs errors.Errors) {
for _, err := range errs {
this.output.Error(err)
}
}
func (this *Context) Abort(err errors.Error) {
this.output.Abort(err)
}
func (this *Context) Fatal(err errors.Error) {
this.output.Fatal(err)
}
func (this *Context) Warning(wrn errors.Error) {
this.output.Warning(wrn)
}
// memory quota
func (this *Context) UseRequestQuota() bool {
return this.memorySession != nil
}
func (this *Context) MemoryQuota() uint64 {
return this.memoryQuota
}
func (this *Context) ProducerThrottleQuota() uint64 {
return this.memoryQuota / 10
}
func (this *Context) TrackValueSize(size uint64) errors.Error {
sz, _, err := this.memorySession.Track(size)
this.output.TrackMemory(sz)
if this.memoryQuota > 0 && sz > this.memoryQuota {
return errors.NewMemoryQuotaExceededError()
}
return err
}
func (this *Context) ReleaseValueSize(size uint64) {
this.memorySession.Track(^(size - 1))
}
func (this *Context) Release() {
if this.memorySession != nil {
this.memorySession.Release()
}
}
func (this *Context) CurrentQuotaUsage() float64 {
if this.memorySession == nil || this.memoryQuota == 0 {
return 0.0
}
sz := this.memorySession.InUseMemory()
if sz <= 0 {
return 0.0
}
return float64(sz) / float64(this.memoryQuota)
}
func (this *Context) AvailableMemory() uint64 {
if this.memorySession != nil {
return this.memorySession.AvailableMemory()
}
return system.GetMemFree()
}
// UDF memory storage
func (this *Context) StoreValue(key string, val interface{}) {
this.udfValueMap.Store(key, val)
}
func (this *Context) RetrieveValue(key string) interface{} {
res, _ := this.udfValueMap.Load(key)
return res
}
func (this *Context) ReleaseValue(key string) {
this.udfValueMap.Delete(key)
}
func (this *Context) SetDeltaKeyspaces(d map[string]bool) {
this.deltaKeyspaces = d
}
func (this *Context) DeltaKeyspaces() map[string]bool {
return this.deltaKeyspaces
}
func (this *Context) SetDurability(l datastore.DurabilityLevel, d time.Duration) {
this.durabilityLevel = l
this.durabilityTimeout = d
}
func (this *Context) DurabilityLevel() datastore.DurabilityLevel {
return this.durabilityLevel
}
func (this *Context) DurabilityTimeout() time.Duration {
return this.durabilityTimeout
}
func (this *Context) KvTimeout() time.Duration {
return this.kvTimeout
}
func (this *Context) SetPreserveExpiry(preserve bool) {
this.preserveExpiry = preserve
}
func (this *Context) PreserveExpiry() bool {
return this.preserveExpiry
}
func (this *Context) ResetTxContext() {
if this.txContext != nil {
this.txContext = nil
}
}
func (this *Context) SetTxTimeout(txTimeout time.Duration) {
this.txTimeout = txTimeout
}
func (this *Context) SetTransactionInfo(txId string, txStmtNum int64) (err errors.Error) {
txContext := transactions.GetTransContext(txId)
if txContext == nil {
return errors.NewTransactionContextError(fmt.Errorf("transaction (%s) is not present", txId))
} else if err := txContext.TxValid(); err != nil {
return err
}
this.txTimeout = txContext.TxTimeout()
if this.originalConsistency == datastore.NOT_SET {
this.consistency = txContext.TxScanConsistency()
} else if this.originalConsistency == datastore.AT_PLUS {
this.consistency = datastore.SCAN_PLUS
}
this.SetDurability(txContext.TxDurabilityLevel(), txContext.TxDurabilityTimeout())
this.atrCollection = txContext.AtrCollection()
this.numAtrs = txContext.NumAtrs()
this.txImplicit = false
if txStmtNum > 0 {
lastStmtNum := txContext.TxLastStmtNum()
if lastStmtNum >= txStmtNum {
return errors.NewTranStatementOutOfOrderError(lastStmtNum, txStmtNum)
}
txContext.SetTxLastStmtNum(txStmtNum)
}
this.txContext = txContext
return nil
}
func (this *Context) SetTransactionContext(stmtType string, txImplicit bool, rTxTimeout, sTxTimeout time.Duration,
atrCollection string, numAtrs int, txData []byte) (err errors.Error) {
if this.txContext != nil || stmtType == "START_TRANSACTION" || (txImplicit && stmtType != "EXECUTE_FUNCTION") {
this.txData = txData
if len(txData) > 0 {
this.txDataVal = value.NewValue(txData)
}
if this.txContext == nil {
// start transaction or implicit transaction
if sTxTimeout > 0 && sTxTimeout < rTxTimeout {
rTxTimeout = sTxTimeout
}
this.txTimeout = rTxTimeout
this.atrCollection = atrCollection
this.numAtrs = numAtrs
if stmtType != "START_TRANSACTION" {
// start implicit transaction
this.txImplicit = txImplicit
txId, _, err := this.ExecuteTranStatement("START", !txImplicit)
if err != nil {
return err
}
this.txContext = transactions.GetTransContext(txId)
if this.txContext == nil {
return errors.NewTransactionContextError(fmt.Errorf("transaction (%s) is not present", txId))
}
if this.txImplicit {
this.SetDeltaKeyspaces(make(map[string]bool, 1))
}
}
} else {
switch stmtType {
case "START_TRANSACTION", "COMMIT", "ROLLBACK":
case "ROLLBACK_SAVEPOINT", "SAVEPOINT", "SET_TRANSACTION_ISOLATION":
default:
// setup atomicity
_, dks, err := this.ExecuteTranStatement("START", true)
if err != nil {
return err
}
this.SetDeltaKeyspaces(dks)
}
}
} else if stmtType == "EXECUTE_FUNCTION" {
// set up transaction timeout in case the function starts a transaction
if sTxTimeout > 0 && sTxTimeout < rTxTimeout {
rTxTimeout = sTxTimeout
}
this.txTimeout = rTxTimeout
}
return nil
}
func (this *Context) SetAtrCollection(atrCollection string, numAtrs int) {
this.atrCollection = atrCollection
this.numAtrs = numAtrs
}
func (this *Context) AtrCollection() (string, int) {
return this.atrCollection, this.numAtrs
}
func (this *Context) TxExpired() bool {
return this.txContext != nil && this.txContext.TxExpired()
}
// Serverless management
func (this *Context) recordCU(d time.Duration) {
this.output.AddCpuTime(d)
}
// Serverless cost from other services
// TODO TENANT placeholder: jsevaluator is undefined as of yet
func (this *Context) RecordJsCU(d time.Duration, m uint64) {
if tenant.IsServerless() {
units := tenant.RecordJsCU(this.tenantCtx, d, m)
this.output.AddTenantUnits(tenant.JS_CU, units)
}
}
// Serverless cost from other services
// TODO TENANT Gsi and Fts are undefined as of yet
func (this *Context) RecordFtsRU(ru tenant.Unit) {
if tenant.IsServerless() {
this.output.AddTenantUnits(tenant.FTS_RU, ru)
}
}
func (this *Context) RecordGsiRU(ru tenant.Unit) {
if tenant.IsServerless() {
this.output.AddTenantUnits(tenant.GSI_RU, ru)
}
}
// Kv returns actual RUs and WUs
func (this *Context) RecordKvRU(ru tenant.Unit) {
if tenant.IsServerless() {
this.output.AddTenantUnits(tenant.KV_RU, ru)
}
}
func (this *Context) RecordKvWU(wu tenant.Unit) {
if tenant.IsServerless() {
this.output.AddTenantUnits(tenant.KV_WU, wu)
}
}
// subquery evaluation
func (this *Context) EvaluateSubquery(query *algebra.Select, parent value.Value) (value.Value, error) {
var qp *plan.QueryPlan
var subplan, subplanIsks interface{}
planFound := false
useCache := useSubqCachedResult(query)
if useCache {
subresults := this.getSubresults()
subresult, _, ok := subresults.get(query)
if ok {
return subresult.(value.Value), nil
}
}
subplans := this.getSubplans()
subplan, subplanIsks, planFound = subplans.get(query)
// MB-34749 make subquery plans a property of the prepared statement
if !planFound && this.IsPrepared() {
this.prepared.RLock()
subplan, subplanIsks, planFound = this.prepared.GetSubqueryPlan(query)
this.prepared.RUnlock()
if !planFound {
var err error
this.prepared.Lock()
// check again, just in case somebody has done it while we were waiting
subplan, subplanIsks, planFound = this.prepared.GetSubqueryPlan(query)
if !planFound {
// MB-32140: do not replace named/positional arguments with its value for prepared statements
var prepContext planner.PrepareContext
planner.NewPrepareContext(&prepContext, this.requestId, this.queryContext, nil, nil,
this.indexApiVersion, this.featureControls, this.useFts, this.useCBO, this.optimizer,
nil, this, false)
qp, subplanIsks, err = planner.Build(query, this.datastore, this.systemstore, this.namespace,
true, false, &prepContext)
if err != nil {
this.prepared.Unlock()
// Generate our own error for this subquery, in addition to whatever the query above is doing.
err1 := errors.NewSubqueryBuildError(err)
this.Error(err1)
return nil, err1
}
subplan = qp.PlanOp()
// Cache plan
this.prepared.SetSubqueryPlan(query, subplan, subplanIsks)
planFound = true
}
this.prepared.Unlock()
}
for ks, _ := range subplanIsks.(map[string]bool) {
if _, ok := this.deltaKeyspaces[ks]; ok {
planFound = false
break
}
}
}
if !planFound {
var err error
var prepContext planner.PrepareContext
planner.NewPrepareContext(&prepContext, this.requestId, this.queryContext, this.namedArgs,
this.positionalArgs, this.indexApiVersion, this.featureControls, this.useFts, this.useCBO, this.optimizer,
this.deltaKeyspaces, this, false)
qp, subplanIsks, err = planner.Build(query, this.datastore, this.systemstore,
this.namespace, true, false, &prepContext)
if err != nil {
// Generate our own error for this subquery, in addition to whatever the query above is doing.
err1 := errors.NewSubqueryBuildError(err)
this.Error(err1)
return nil, err1
}
subplan = qp.PlanOp()
// Cache plan