Repository navigation
Expand file tree
/
Copy pathsql_executor_context_test.go
More file actions
1223 lines (1133 loc) · 47.4 KB
/
Copy pathsql_executor_context_test.go
File metadata and controls
1223 lines (1133 loc) · 47.4 KB
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 2023 Matrix Origin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package compile
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"strings"
"testing"
"time"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
"github.com/matrixorigin/matrixone/pkg/catalog"
"github.com/matrixorigin/matrixone/pkg/common/moerr"
"github.com/matrixorigin/matrixone/pkg/common/mpool"
moruntime "github.com/matrixorigin/matrixone/pkg/common/runtime"
"github.com/matrixorigin/matrixone/pkg/container/types"
"github.com/matrixorigin/matrixone/pkg/defines"
pbplan "github.com/matrixorigin/matrixone/pkg/pb/plan"
pbstats "github.com/matrixorigin/matrixone/pkg/pb/statsinfo"
"github.com/matrixorigin/matrixone/pkg/pb/timestamp"
"github.com/matrixorigin/matrixone/pkg/pb/txn"
"github.com/matrixorigin/matrixone/pkg/sql/parsers"
"github.com/matrixorigin/matrixone/pkg/sql/parsers/dialect"
"github.com/matrixorigin/matrixone/pkg/testutil"
"github.com/matrixorigin/matrixone/pkg/txn/client"
"github.com/matrixorigin/matrixone/pkg/util/executor"
"github.com/matrixorigin/matrixone/pkg/vm/process"
mock_frontend "github.com/matrixorigin/matrixone/pkg/frontend/test"
"github.com/matrixorigin/matrixone/pkg/sql/plan"
"github.com/matrixorigin/matrixone/pkg/sql/plan/function"
"github.com/matrixorigin/matrixone/pkg/util/resource"
"github.com/matrixorigin/matrixone/pkg/util/trace/impl/motrace/statistic"
)
func TestInternalExecutorCommittedLogWaitHonorsCallerCancellation(t *testing.T) {
ctrl := gomock.NewController(t)
txnClient := mock_frontend.NewMockTxnClient(ctrl)
txnOperator := mock_frontend.NewMockTxnOperator(ctrl)
commitTS := timestamp.Timestamp{PhysicalTime: 42}
txnOperator.EXPECT().Txn().Return(txn.TxnMeta{CommitTS: commitTS})
waitStarted := make(chan struct{})
txnClient.EXPECT().WaitLogTailAppliedAt(gomock.Any(), commitTS).DoAndReturn(
func(ctx context.Context, _ timestamp.Timestamp) (timestamp.Timestamp, error) {
close(waitStarted)
<-ctx.Done()
return timestamp.Timestamp{}, ctx.Err()
},
)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
errC := make(chan error, 1)
go func() {
errC <- (&sqlExecutor{txnClient: txnClient}).maybeWaitCommittedLogApplied(
ctx,
executor.Options{}.
WithTxn(txnOperator).
WithWaitCommittedLogApplied(),
)
}()
select {
case <-waitStarted:
case <-time.After(time.Second):
t.Fatal("committed-log wait did not start")
}
cancel()
select {
case err := <-errC:
require.ErrorIs(t, err, context.Canceled)
case <-time.After(time.Second):
t.Fatal("caller cancellation did not release committed-log wait")
}
}
func TestInternalExecutorCommittedLogWaitContract(t *testing.T) {
waitErr := errors.New("logtail wait failed")
commitTS := timestamp.Timestamp{PhysicalTime: 42}
for _, tc := range []struct {
name string
wait bool
commitTS timestamp.Timestamp
wantErr error
wantCalls int
}{
{name: "disabled", commitTS: commitTS},
{name: "empty commit timestamp", wait: true},
{name: "success", wait: true, commitTS: commitTS, wantCalls: 1},
{name: "wait error", wait: true, commitTS: commitTS, wantErr: waitErr, wantCalls: 1},
} {
t.Run(tc.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
txnClient := mock_frontend.NewMockTxnClient(ctrl)
txnOperator := mock_frontend.NewMockTxnOperator(ctrl)
if tc.wait {
txnOperator.EXPECT().Txn().Return(txn.TxnMeta{CommitTS: tc.commitTS})
}
if tc.wantCalls == 1 {
txnClient.EXPECT().WaitLogTailAppliedAt(gomock.Any(), tc.commitTS).
Return(timestamp.Timestamp{}, tc.wantErr)
}
opts := executor.Options{}.WithTxn(txnOperator)
if tc.wait {
opts = opts.WithWaitCommittedLogApplied()
}
err := (&sqlExecutor{txnClient: txnClient}).maybeWaitCommittedLogApplied(
context.Background(), opts)
require.ErrorIs(t, err, tc.wantErr)
})
}
}
func TestNewInternalStatementContextPreservesRootAndClaimsStatsOnce(t *testing.T) {
root := resource.NewRoot(resource.ConnExternal)
parentStats := statistic.NewStatsInfo()
parent := resource.ContextWithRoot(
statistic.ContextWithStatsInfo(context.Background(), parentStats),
root)
child := newInternalStatementContext(parent)
childStats := statistic.StatsInfoFromContext(child)
childAgain := newInternalStatementContext(parent)
childAgainStats := statistic.StatsInfoFromContext(childAgain)
require.Same(t, root, resource.RootFromContext(child))
require.NotNil(t, childStats)
require.NotSame(t, parentStats, childStats)
require.NotSame(t, childStats, childAgainStats)
for _, stats := range []*statistic.StatsInfo{parentStats, childStats, childAgainStats} {
_, ok := stats.ClaimRootPhaseResource()
require.True(t, ok)
_, ok = stats.ClaimRootPhaseResource()
require.False(t, ok)
}
}
func TestInternalStatementContextSuppressesInheritedJSONMergeWarning(t *testing.T) {
parent := plan.WithJSONMergeWarningContext(
context.Background(), nil, plan.JSONMergeWarningUser)
internal := markInternalJSONMergeWarningContext(
newInternalStatementContext(parent))
origin, ok := plan.JSONMergeWarningOriginFromContext(internal)
require.True(t, ok)
require.Equal(t, plan.JSONMergeWarningInternalReprepare, origin)
}
func TestCompilerContextUnsupportedOperations(t *testing.T) {
r := func() {
err := recover()
require.Equal(t, "not supported in internal sql executor", err)
}
c := &compilerContext{}
meta, err := c.GetSubscriptionMeta("", nil)
require.NoError(t, err)
require.Nil(t, meta)
require.Error(t, c.CheckSubscriptionValid("", "", ""))
_, err = c.IsPublishing("")
require.Error(t, err)
c.SetQueryingSubscription(nil)
func() {
defer r()
_, _ = c.ResolveUdf("", nil)
}()
func() {
defer r()
_, _ = c.ResolveAccountIds(nil)
}()
// GetQueryResultMeta is a delegated operation since CTAS-from-result_scan
// support: without a delegate - including the nil-context case above - it
// must return a clean typed internal error and no metadata, never panic.
cols, path, qerr := c.GetQueryResultMeta("")
require.Error(t, qerr)
require.True(t, moerr.IsMoErrCode(qerr, moerr.ErrInternal),
"want typed internal error, got %v", qerr)
require.Nil(t, cols)
require.Empty(t, path)
}
type recordingSessionCompilerContext struct {
*plan.MockCompilerContext
snapshot *plan.Snapshot
subscription *plan.SubscriptionMeta
queryingSubscription *plan.SubscriptionMeta
checkedSubscription []string
resolvedDatabase string
resolvedTable string
resolvedTableDef *plan.TableDef
resolvedIndexRef *plan.ObjectRef
resolvedIndexSnapshot *plan.Snapshot
proc *process.Process
}
func (c *recordingSessionCompilerContext) GetProcess() *process.Process { return c.proc }
func (c *recordingSessionCompilerContext) ResolveSnapshotWithSnapshotName(name string) (*plan.Snapshot, error) {
if name != "daily" {
return nil, moerr.NewInternalErrorNoCtx("unexpected snapshot")
}
return c.snapshot, nil
}
func (c *recordingSessionCompilerContext) GetSubscriptionMeta(
dbName string,
snapshot *plan.Snapshot,
) (*plan.SubscriptionMeta, error) {
if dbName != "sub" || snapshot != c.snapshot {
return nil, moerr.NewInternalErrorNoCtx("unexpected subscription binding")
}
return c.subscription, nil
}
func (c *recordingSessionCompilerContext) CheckSubscriptionValid(subName, accountName, pubName string) error {
c.checkedSubscription = []string{subName, accountName, pubName}
return nil
}
func (c *recordingSessionCompilerContext) SetQueryingSubscription(meta *plan.SubscriptionMeta) {
c.queryingSubscription = meta
}
func (c *recordingSessionCompilerContext) GetQueryingSubscription() *plan.SubscriptionMeta {
return c.queryingSubscription
}
func (c *recordingSessionCompilerContext) Resolve(
databaseName string,
tableName string,
_ *plan.Snapshot, borrowOutput *plan.TableResolution,
) (*plan.ObjectRef, *plan.TableDef, error) {
borrowOutput.Reset()
c.resolvedDatabase = databaseName
c.resolvedTable = tableName
return &plan.ObjectRef{}, c.resolvedTableDef, nil
}
func (c *recordingSessionCompilerContext) ResolveIndexTableByRef(ref *plan.ObjectRef, tableName string, snapshot *plan.Snapshot, borrowOutput *plan.TableResolution) (*plan.ObjectRef, *plan.TableDef, error) {
borrowOutput.Reset()
c.resolvedIndexRef, c.resolvedIndexSnapshot = ref, snapshot
c.resolvedTable = tableName
return &plan.ObjectRef{NotLockMeta: ref.NotLockMeta}, c.resolvedTableDef, nil
}
func TestCompilerContextDelegatesSnapshotAndSubscriptionBinding(t *testing.T) {
snapshot := &plan.Snapshot{}
subscription := &plan.SubscriptionMeta{Name: "pub", SubName: "sub"}
delegate := &recordingSessionCompilerContext{
MockCompilerContext: plan.NewMockCompilerContext(false, nil),
snapshot: snapshot, subscription: subscription,
resolvedTableDef: &plan.TableDef{Name: "physical_source"},
}
proc := testutil.NewProcess(t)
c := &compilerContext{
ctx: attachInternalExecutorCompilerContext(context.Background(), delegate),
proc: proc,
}
actualSnapshot, err := c.ResolveSnapshotWithSnapshotName("daily")
require.NoError(t, err)
require.Same(t, snapshot, actualSnapshot)
actualSubscription, err := c.GetSubscriptionMeta("sub", snapshot)
require.NoError(t, err)
require.Same(t, subscription, actualSubscription)
require.NoError(t, c.CheckSubscriptionValid("sub", "publisher", "pub"))
require.Equal(t, []string{"sub", "publisher", "pub"}, delegate.checkedSubscription)
c.SetQueryingSubscription(subscription)
require.Same(t, subscription, c.GetQueryingSubscription())
_, resolved, err := c.Resolve("subscription_db", "source", snapshot, nil)
require.NoError(t, err)
require.Same(t, delegate.resolvedTableDef, resolved)
require.Equal(t, "subscription_db", delegate.resolvedDatabase)
require.Equal(t, "source", delegate.resolvedTable)
for _, skipMeta := range []bool{false, true} {
baseRef := &plan.ObjectRef{SchemaName: "db", NotLockMeta: skipMeta}
indexRef, _, err := c.ResolveIndexTableByRef(baseRef, "hidden_index", snapshot, nil)
require.NoError(t, err)
require.Equal(t, skipMeta, indexRef.NotLockMeta)
require.Equal(t, "hidden_index", delegate.resolvedTable)
require.Same(t, baseRef, delegate.resolvedIndexRef)
require.Same(t, snapshot, delegate.resolvedIndexSnapshot)
}
}
type isolatedViewTestDelegate struct {
*recordingSessionCompilerContext
child *recordingSessionCompilerContext
err error
}
func (d *isolatedViewTestDelegate) NewViewDescriptionCompilerContext(
_ context.Context,
) (plan.CompilerContext, func(), error) {
if d.err != nil {
return nil, nil, d.err
}
return d.child, func() {}, nil
}
func TestInternalExecutorViewChildDoesNotMutateParent(t *testing.T) {
proc := testutil.NewProcess(t)
original := proc.GetTopContext()
parentSubscription := &plan.SubscriptionMeta{Name: "parent"}
delegate := &isolatedViewTestDelegate{
recordingSessionCompilerContext: &recordingSessionCompilerContext{
MockCompilerContext: plan.NewMockCompilerContext(false, nil),
queryingSubscription: parentSubscription,
},
child: &recordingSessionCompilerContext{MockCompilerContext: plan.NewMockCompilerContext(false, nil)},
}
parent := &compilerContext{proc: proc, ctx: attachInternalExecutorCompilerContext(original, delegate)}
childContext := context.WithValue(original, struct{}{}, "child")
binding, cleanup, err := parent.NewViewDescriptionCompilerContext(childContext)
require.NoError(t, err)
defer cleanup()
child := binding.(*compilerContext)
require.NotSame(t, proc, child.GetProcess())
require.NotSame(t, proc.Base, child.GetProcess().Base)
require.Same(t, child, child.GetProcess().GetSessionInfo().CompilerContext)
child.SetContext(context.WithValue(child.GetContext(), struct{}{}, "nested"))
childSubscription := &plan.SubscriptionMeta{Name: "publisher"}
child.SetQueryingSubscription(childSubscription)
require.Same(t, childSubscription, child.GetQueryingSubscription())
require.Same(t, childSubscription, delegate.child.GetQueryingSubscription())
require.Same(t, parentSubscription, delegate.GetQueryingSubscription())
require.Same(t, original, proc.GetTopContext())
require.Same(t, child.GetContext(), child.GetProcess().GetTopContext())
child.SetQueryingSubscription(nil)
require.Same(t, parentSubscription, delegate.GetQueryingSubscription())
}
func TestInternalExecutorViewChildUsesDelegateProcess(t *testing.T) {
proc := testutil.NewProcess(t)
original := proc.GetTopContext()
separate := proc.NewViewBindingProcess(original)
defer separate.Free()
delegate := &isolatedViewTestDelegate{
recordingSessionCompilerContext: &recordingSessionCompilerContext{MockCompilerContext: plan.NewMockCompilerContext(false, nil)},
child: &recordingSessionCompilerContext{
MockCompilerContext: plan.NewMockCompilerContext(false, nil), proc: separate,
},
}
parent := &compilerContext{proc: proc, ctx: attachInternalExecutorCompilerContext(original, delegate)}
binding, cleanup, err := parent.NewViewDescriptionCompilerContext(original)
require.NoError(t, err)
defer cleanup()
child := binding.(*compilerContext)
require.Same(t, separate, child.GetProcess())
child.SetContext(context.WithValue(original, struct{}{}, "nested"))
require.Same(t, original, proc.GetTopContext())
require.Same(t, child.GetContext(), separate.GetTopContext())
}
func TestInternalExecutorViewChildPropagatesDelegateFailure(t *testing.T) {
proc := testutil.NewProcess(t)
original := proc.GetTopContext()
delegate := &isolatedViewTestDelegate{
recordingSessionCompilerContext: &recordingSessionCompilerContext{MockCompilerContext: plan.NewMockCompilerContext(false, nil)},
err: errors.New("cannot create child"),
}
parent := &compilerContext{proc: proc, ctx: attachInternalExecutorCompilerContext(original, delegate)}
binding, cleanup, err := parent.NewViewDescriptionCompilerContext(original)
require.ErrorContains(t, err, "cannot create child")
require.Nil(t, binding)
require.Nil(t, cleanup)
require.Same(t, original, proc.GetTopContext())
}
func TestInternalExecutorViewChildRejectsUnisolatedDelegate(t *testing.T) {
proc := testutil.NewProcess(t)
original := proc.GetTopContext()
delegate := &recordingSessionCompilerContext{MockCompilerContext: plan.NewMockCompilerContext(false, nil)}
parent := &compilerContext{proc: proc, ctx: attachInternalExecutorCompilerContext(original, delegate)}
binding, cleanup, err := parent.NewViewDescriptionCompilerContext(original)
require.ErrorContains(t, err, "cannot isolate view binding")
require.Nil(t, binding)
require.Nil(t, cleanup)
require.Same(t, original, proc.GetTopContext())
}
func TestInternalExecutorViewChildWithoutDelegateIsIsolated(t *testing.T) {
proc := testutil.NewProcess(t)
original := proc.GetTopContext()
parent := &compilerContext{proc: proc, ctx: original}
binding, cleanup, err := parent.NewViewDescriptionCompilerContext(original)
require.NoError(t, err)
defer cleanup()
child := binding.(*compilerContext)
require.NotSame(t, proc.Base, child.GetProcess().Base)
child.SetContext(context.WithValue(original, struct{}{}, "child"))
child.SetQueryingSubscription(&plan.SubscriptionMeta{Name: "publisher"})
require.Equal(t, "publisher", child.GetQueryingSubscription().Name)
require.Same(t, child.GetContext(), child.GetProcess().GetTopContext())
require.Same(t, child.GetContext(), child.GetProcess().Ctx)
require.Same(t, original, proc.GetTopContext())
require.Nil(t, parent.GetQueryingSubscription())
}
func TestInternalExecutorViewUdfCatalogBody(t *testing.T) {
const (
database = "app"
name = "f"
body = `select power($1,0.5) from "app"."source"`
sqlMode = "ANSI_QUOTES"
)
for _, tc := range []struct {
name, language, storedBody, decodedBody string
legacy bool
}{
{name: "marked SQL", language: "sql", storedBody: function.EncodeSQLUdfBody(body), decodedBody: body},
{name: "unmarked SQL", language: "sql", storedBody: body, decodedBody: body, legacy: true},
{
name: "opaque Python", language: "python",
storedBody: `{"handler":"f","import":false,"body":"def f(x): return x"}`,
decodedBody: `{"handler":"f","import":false,"body":"def f(x): return x"}`,
},
} {
t.Run(tc.name, func(t *testing.T) {
proc := testutil.NewProcess(t)
ctx := defines.AttachAccountId(proc.GetTopContext(), 0)
proc.ReplaceTopCtx(ctx)
proc.Ctx = ctx
exec := executor.NewMemExecutor(func(query string) (executor.Result, error) {
require.Contains(t, query, "from mo_catalog.mo_user_defined_function where name = 'f' and db = 'app'")
result := executor.NewMemResult([]types.Type{
types.T_json.ToType(), types.T_text.ToType(), types.T_varchar.ToType(),
types.T_varchar.ToType(), types.T_varchar.ToType(), types.T_varchar.ToType(), types.T_varchar.ToType(),
}, proc.Mp())
result.NewBatchWithRowCount(1)
args, err := types.ParseStringToByteJson(`[{"name":"x","type":"double"}]`)
require.NoError(t, err)
rawArgs, err := args.Marshal()
require.NoError(t, err)
require.NoError(t, executor.AppendBytesRows(result, 0, [][]byte{rawArgs}))
for i, value := range []string{tc.storedBody, tc.language, "double", database, "2026-11-27 10:00:00", sqlMode} {
require.NoError(t, executor.AppendStringRows(result, i+1, []string{value}))
}
return result.GetResult(), nil
})
rt := moruntime.ServiceRuntime(proc.GetService())
previous, hadPrevious := rt.GetGlobalVariables(moruntime.InternalSQLExecutor)
rt.SetGlobalVariables(moruntime.InternalSQLExecutor, exec)
t.Cleanup(func() {
if hadPrevious {
rt.SetGlobalVariables(moruntime.InternalSQLExecutor, previous)
} else {
rt.CompareAndDeleteGlobalVariables(moruntime.InternalSQLExecutor, exec)
}
})
compiler := &compilerContext{proc: proc, ctx: ctx, viewChild: true}
udf, err := compiler.ResolveViewUdf(name, []*plan.Expr{{Typ: plan.Type{Id: int32(types.T_float64)}}}, database)
require.NoError(t, err)
require.Equal(t, tc.decodedBody, udf.Body)
require.Equal(t, tc.legacy, udf.LegacyPower)
require.Equal(t, tc.language, udf.Language)
require.NotNil(t, udf.SQLMode)
require.Equal(t, sqlMode, *udf.SQLMode)
})
}
}
func TestInternalExecutorSubscriptionViewWithoutFrontendDelegate(t *testing.T) {
ctrl := gomock.NewController(t)
proc := testutil.NewProcessWithOwnedMPool(t, "", mpool.MustNewZero())
relation := mock_frontend.NewMockRelation(ctrl)
relation.EXPECT().GetTableDef(gomock.Any()).Return(&plan.TableDef{Name: "v"})
relation.EXPECT().GetTableID(gomock.Any()).Return(uint64(42))
database := mock_frontend.NewMockDatabase(ctrl)
database.EXPECT().Relation(gomock.Any(), "v", nil).Return(relation, nil)
eng := mock_frontend.NewMockEngine(ctrl)
eng.EXPECT().GetNameById(gomock.Any(), nil, uint64(42)).Return("db", "v", nil)
eng.EXPECT().Database(gomock.Any(), "db", nil).Return(database, nil)
parent := &compilerContext{proc: proc, engine: eng, ctx: proc.GetTopContext()}
binding, cleanup, err := parent.NewViewDescriptionCompilerContext(proc.GetTopContext())
require.NoError(t, err)
defer cleanup()
child := binding.(*compilerContext)
child.SetContext(defines.AttachAccountId(child.GetContext(), 23))
obj, def, err := child.ResolveSubscriptionTableById(42, &plan.SubscriptionMeta{AccountId: 23})
require.NoError(t, err)
require.Equal(t, "v", obj.ObjName)
require.Equal(t, "v", def.Name)
require.Nil(t, parent.GetQueryingSubscription())
}
func TestCompilerContext_Database(t *testing.T) {
ctrl := gomock.NewController(t)
database := mock_frontend.NewMockDatabase(ctrl)
database.EXPECT().GetDatabaseId(gomock.Any()).Return("1")
engine := mock_frontend.NewMockEngine(ctrl)
engine.EXPECT().Database(gomock.Any(), "", nil).Return(database, nil).Times(2)
c := &compilerContext{
proc: testutil.NewProcessWithOwnedMPool(t, "", mpool.MustNewZero()),
engine: engine,
}
exists := c.DatabaseExists("", &plan.Snapshot{})
require.Equal(t, exists, true)
_, err := c.GetDatabaseId("", &plan.Snapshot{})
require.Nil(t, err)
sql := c.GetRootSql()
require.Equal(t, sql, "")
}
func TestCompilerContextBuildTableDefByMoColumns(t *testing.T) {
ctrl := gomock.NewController(t)
proc := testutil.NewProcessWithOwnedMPool(t, "", mpool.MustNewZero())
tableDef := &plan.TableDef{
Name: "src",
Cols: []*plan.ColDef{
{Name: "a"},
{Name: "b"},
},
}
relation := mock_frontend.NewMockRelation(ctrl)
relation.EXPECT().GetTableDef(gomock.Any()).Return(tableDef)
relation.EXPECT().GetTableID(gomock.Any()).Return(uint64(42))
database := mock_frontend.NewMockDatabase(ctrl)
database.EXPECT().Relation(gomock.Any(), "src", nil).Return(relation, nil)
eng := mock_frontend.NewMockEngine(ctrl)
eng.EXPECT().Database(gomock.Any(), "db", gomock.Any()).Return(database, nil)
c := &compilerContext{
defaultDB: "db",
engine: eng,
proc: proc,
}
actual, err := c.BuildTableDefByMoColumns("db", "src")
require.NoError(t, err)
require.Equal(t, tableDef.Cols, actual.Cols)
require.NotSame(t, tableDef, actual)
}
func TestInternalResolverNormalizesPersistedDecimalCoercions(t *testing.T) {
data, err := os.ReadFile("../plan/testdata/legacy_decimal_catalog_63a964a82f.json")
require.NoError(t, err)
var fixtures map[string][]byte
require.NoError(t, json.Unmarshal(data, &fixtures))
catalogDef := new(plan.TableDef)
require.NoError(t, catalogDef.Unmarshal(fixtures["signed_compare"]))
wire, err := catalogDef.Marshal()
require.NoError(t, err)
ctrl := gomock.NewController(t)
proc := testutil.NewProcess(t)
requestCtx := proc.GetTopContext()
pipelineCtx, cancel := context.WithCancel(requestCtx)
cancel()
proc.Ctx = pipelineCtx
relation := mock_frontend.NewMockRelation(ctrl)
relation.EXPECT().GetTableDef(gomock.Any()).Return(catalogDef).Times(2)
relation.EXPECT().GetTableID(gomock.Any()).Return(uint64(42)).Times(2)
database := mock_frontend.NewMockDatabase(ctrl)
database.EXPECT().Relation(gomock.Any(), "legacy_cmp", nil).Return(relation, nil).Times(2)
eng := mock_frontend.NewMockEngine(ctrl)
eng.EXPECT().Database(gomock.Any(), "db", gomock.Any()).Return(database, nil).Times(2)
c := &compilerContext{ctx: requestCtx, defaultDB: "db", engine: eng, proc: proc}
for range 2 {
_, resolved, err := c.Resolve("db", "legacy_cmp", nil, nil)
require.NoError(t, err)
require.NotSame(t, catalogDef.Checks[0], resolved.Checks[0])
for _, arg := range resolved.Checks[0].Check.GetF().Args {
require.Equal(t, int32(types.T_decimal128), arg.Typ.Id)
require.Equal(t, int32(19), arg.Typ.Width)
}
}
after, err := catalogDef.Marshal()
require.NoError(t, err)
require.Equal(t, wire, after)
}
func TestCompilerContextBuildTableDefByMoColumnsPropagatesRelationError(t *testing.T) {
ctrl := gomock.NewController(t)
proc := testutil.NewProcessWithOwnedMPool(t, "", mpool.MustNewZero())
relationErr := moerr.NewInternalErrorNoCtx("relation failed")
database := mock_frontend.NewMockDatabase(ctrl)
database.EXPECT().Relation(gomock.Any(), "src", nil).Return(nil, relationErr)
eng := mock_frontend.NewMockEngine(ctrl)
eng.EXPECT().Database(gomock.Any(), "db", gomock.Any()).Return(database, nil)
c := &compilerContext{
defaultDB: "db",
engine: eng,
proc: proc,
}
actual, err := c.BuildTableDefByMoColumns("db", "src")
require.Nil(t, actual)
require.ErrorIs(t, err, relationErr)
}
func TestCompilerContextBuildTableDefByMoColumnsNoSuchTable(t *testing.T) {
ctrl := gomock.NewController(t)
proc := testutil.NewProcessWithOwnedMPool(t, "", mpool.MustNewZero())
database := mock_frontend.NewMockDatabase(ctrl)
database.EXPECT().Relation(gomock.Any(), "src", nil).Return(nil, nil)
eng := mock_frontend.NewMockEngine(ctrl)
eng.EXPECT().Database(gomock.Any(), "db", gomock.Any()).Return(database, nil)
c := &compilerContext{
defaultDB: "db",
engine: eng,
proc: proc,
}
actual, err := c.BuildTableDefByMoColumns("db", "src")
require.Nil(t, actual)
require.Error(t, err)
require.True(t, moerr.IsMoErrCode(err, moerr.ErrNoSuchTable))
}
func TestCompilerContextResolveDatabaseErrors(t *testing.T) {
for _, tc := range []struct {
name string
databaseErr error
wantMissing bool
}{
{
name: "ExpectedEOB is a missing database",
databaseErr: moerr.GetOkExpectedEOB(),
wantMissing: true,
},
{
name: "unexpected database error is preserved",
databaseErr: moerr.NewInternalErrorNoCtx("database lookup failed"),
},
} {
t.Run(tc.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
proc := testutil.NewProcessWithOwnedMPool(t, "", mpool.MustNewZero())
eng := mock_frontend.NewMockEngine(ctrl)
eng.EXPECT().Database(gomock.Any(), "db", gomock.Any()).Return(nil, tc.databaseErr)
c := &compilerContext{
defaultDB: "db",
engine: eng,
proc: proc,
}
obj, tableDef, err := c.Resolve("db", "missing", nil, nil)
if tc.wantMissing {
require.NoError(t, err)
require.Nil(t, obj)
require.Nil(t, tableDef)
return
}
require.ErrorIs(t, err, tc.databaseErr)
require.Nil(t, obj)
require.Nil(t, tableDef)
})
}
}
func TestInternalCompilerContextDropTableIfExistsExpectedEOBNoop(t *testing.T) {
ctrl := gomock.NewController(t)
proc := testutil.NewProcessWithOwnedMPool(t, "", mpool.MustNewZero())
eng := mock_frontend.NewMockEngine(ctrl)
eng.EXPECT().Database(gomock.Any(), "gone", gomock.Any()).
Return(nil, moerr.GetOkExpectedEOB())
c := &compilerContext{engine: eng, proc: proc}
stmt, err := parsers.ParseOne(t.Context(), dialect.MYSQL,
"drop table if exists gone.__mo_tmp_table", 1)
require.NoError(t, err)
defer stmt.Free()
p, err := plan.BuildPlan(c, stmt, false, nil)
require.NoError(t, err)
drop := p.GetDdl().GetDropTable()
require.Equal(t, "gone", drop.GetDatabase())
require.Equal(t, "__mo_tmp_table", drop.GetTable())
require.Nil(t, drop.GetTableDef())
}
// Internal SQL must inherit variables that shape the user's plan, whether it
// carries the frontend compiler context (CTAS) or its session resolver (ALTER).
func TestCompilerContextResolveVariableDelegatesToAttachedSession(t *testing.T) {
type resolved struct {
name string
isSystem, isGlobal bool
}
var seen []resolved
delegate := plan.NewMockCompilerContext(false, nil)
delegate.ResolveVariableFunc = func(name string, isSystemVar, isGlobalVar bool) (interface{}, error) {
seen = append(seen, resolved{name, isSystemVar, isGlobalVar})
if name == "sql_mode" {
return "ONLY_FULL_GROUP_BY,ENABLE_BOOL_SUMAVG", nil
}
return nil, moerr.NewInternalErrorNoCtx("unexpected variable")
}
delegate.ResolveVariableTypeFunc = func(name string, isSystemVar, isGlobalVar bool) (plan.Type, error) {
seen = append(seen, resolved{name, isSystemVar, isGlobalVar})
if name == "fraction" {
return plan.Type{Id: int32(types.T_float64)}, nil
}
return plan.Type{}, moerr.NewInternalErrorNoCtx("unexpected variable type")
}
attached := &compilerContext{
ctx: attachInternalExecutorCompilerContext(context.Background(), delegate),
proc: testutil.NewProcess(t),
}
value, err := attached.ResolveVariable("sql_mode", true, false)
require.NoError(t, err)
require.Equal(t, "ONLY_FULL_GROUP_BY,ENABLE_BOOL_SUMAVG", value)
require.Equal(t, []resolved{{"sql_mode", true, false}}, seen)
declared, err := attached.ResolveVariableType("fraction", false, false)
require.NoError(t, err)
require.Equal(t, int32(types.T_float64), declared.Id)
require.Equal(t, []resolved{{"sql_mode", true, false}, {"fraction", false, false}}, seen)
attached.proc.SetResolveVariableFunc(func(string, bool, bool) (interface{}, error) {
t.Fatal("frontend delegate should take precedence over process resolver")
return nil, nil
})
// An error from the session must reach the caller rather than being
// flattened into the nil default, which would silently compile the replay
// under different rules than the statement the user ran.
_, err = attached.ResolveVariable("other", true, false)
require.Error(t, err)
processOnly := &compilerContext{ctx: context.Background(), proc: testutil.NewProcess(t)}
var processSeen []resolved
processOnly.proc.SetResolveVariableFunc(func(name string, system, global bool) (interface{}, error) {
processSeen = append(processSeen, resolved{name, system, global})
if name == "div_precision_increment" {
return int64(10), nil
}
return nil, moerr.NewInternalErrorNoCtx("resolver failed")
})
value, err = processOnly.ResolveVariable("div_precision_increment", true, false)
require.NoError(t, err)
require.Equal(t, int64(10), value)
// Internal SQL callers can install a resolver for only a subset of
// session variables. Unrelated planner lookups retain their nil default.
value, err = processOnly.ResolveVariable("sql_mode", true, false)
require.NoError(t, err)
require.Nil(t, value)
value, err = processOnly.ResolveVariable("other", false, true)
require.NoError(t, err)
require.Nil(t, value)
require.Equal(t, []resolved{{"div_precision_increment", true, false}}, processSeen)
// An actual error resolving the required precision setting must propagate.
_, err = processOnly.ResolveVariable("div_precision_increment", false, true)
require.NoError(t, err)
processOnly.proc.SetResolveVariableFunc(func(string, bool, bool) (interface{}, error) {
return nil, moerr.NewInternalErrorNoCtx("precision resolver failed")
})
_, err = processOnly.ResolveVariable("div_precision_increment", true, false)
require.ErrorContains(t, err, "precision resolver failed")
detached := &compilerContext{ctx: context.Background(), proc: testutil.NewProcess(t)}
value, err = detached.ResolveVariable("sql_mode", true, false)
require.NoError(t, err)
require.Nil(t, value)
declared, err = detached.ResolveVariableType("fraction", false, false)
require.NoError(t, err)
require.Equal(t, plan.Type{}, declared)
// A context attaching the same compilerContext must not recurse.
selfAttached := &compilerContext{proc: testutil.NewProcess(t)}
selfAttached.ctx = attachInternalExecutorCompilerContext(context.Background(), selfAttached)
value, err = selfAttached.ResolveVariable("sql_mode", true, false)
require.NoError(t, err)
require.Nil(t, value)
declared, err = selfAttached.ResolveVariableType("fraction", false, false)
require.NoError(t, err)
require.Equal(t, plan.Type{}, declared)
}
func TestCompilerContextDelegatesRegexpNullHistory(t *testing.T) {
delegate := plan.NewMockCompilerContext(false, testutil.NewProcess(t))
delegate.ResolveVariableRegexpStringResultFunc = func(name string) (bool, error) {
if name == "history" {
return true, nil
}
return false, moerr.NewInternalErrorNoCtx("history resolver failed")
}
attached := &compilerContext{ctx: attachInternalExecutorCompilerContext(context.Background(), delegate)}
stringResult, err := attached.ResolveVariableRegexpStringResult("history")
require.NoError(t, err)
require.True(t, stringResult)
_, err = attached.ResolveVariableRegexpStringResult("other")
require.ErrorContains(t, err, "history resolver failed")
detached := &compilerContext{ctx: context.Background()}
stringResult, err = detached.ResolveVariableRegexpStringResult("history")
require.NoError(t, err)
require.False(t, stringResult)
detached.ctx = attachInternalExecutorCompilerContext(context.Background(), detached)
stringResult, err = detached.ResolveVariableRegexpStringResult("history")
require.NoError(t, err)
require.False(t, stringResult)
}
func TestInternalCompilerPlanConsumesScopedDOP(t *testing.T) {
ctx := defines.AttachAccountId(t.Context(), 0)
proc := testutil.NewProcess(t)
compiler := &compilerContext{ctx: ctx, proc: proc}
build := func(c plan.CompilerContext, sql string) *plan.Plan {
stmt, err := parsers.ParseOne(ctx, dialect.MYSQL, sql, 1)
require.NoError(t, err)
defer stmt.Free()
result, err := plan.BuildPlan(c, stmt, false, nil)
require.NoError(t, err)
return result
}
for _, tc := range []struct {
value interface{}
want int64
}{
{int64(1), 1}, {int64(3), 3}, {int64(0), 0}, {int(1), 0}, {nil, 0},
} {
if tc.value == nil {
proc.SetResolveVariableFunc(nil)
} else {
proc.SetResolveVariableFunc(func(name string, system, global bool) (interface{}, error) {
if system && !global && strings.EqualFold(name, "max_dop") {
return tc.value, nil
}
return nil, nil
})
}
require.Equal(t, tc.want, build(compiler, "select 1").GetQuery().MaxDop)
}
// Precision continues to shape real expression binding alongside DOP.
var seen []string
proc.SetResolveVariableFunc(func(name string, system, global bool) (interface{}, error) {
seen = append(seen, name)
if strings.EqualFold(name, "max_dop") {
return int64(1), nil
}
if strings.EqualFold(name, "div_precision_increment") {
return int64(10), nil
}
return nil, errors.New("unexpected variable")
})
query := build(compiler, "select cast(1.23 as decimal(10,2)) / cast(3.45 as decimal(10,2))").GetQuery()
require.Equal(t, int64(1), query.MaxDop)
require.Equal(t, int32(12), query.Nodes[query.Steps[0]].ProjectList[0].Typ.Scale)
for _, name := range []string{"MAX_DOP", "DIV_PRECISION_INCREMENT"} {
_, err := compiler.ResolveVariable(name, true, false)
require.NoError(t, err)
}
seen = nil
for _, tc := range []struct {
name string
system, global bool
}{
{"max_dop", false, false}, {"max_dop", true, true},
{"div_precision_increment", false, false}, {"div_precision_increment", true, true},
{"sql_mode", true, false},
} {
v, err := compiler.ResolveVariable(tc.name, tc.system, tc.global)
require.NoError(t, err)
require.Nil(t, v)
}
require.Empty(t, seen)
empty := &compilerContext{ctx: ctx}
v, err := empty.ResolveVariable("max_dop", true, false)
require.NoError(t, err)
require.Nil(t, v)
proc.SetResolveVariableFunc(func(string, bool, bool) (interface{}, error) { return nil, errors.New("resolver failed") })
_, err = compiler.ResolveVariable("max_dop", true, false)
require.ErrorContains(t, err, "resolver failed")
// An attached frontend delegate controls replay even when the process disagrees.
delegate := plan.NewMockCompilerContext(false, nil)
delegate.ResolveVariableFunc = func(name string, system, global bool) (interface{}, error) {
if name == "max_dop" {
return int64(2), nil
}
return nil, nil
}
compiler.ctx = attachInternalExecutorCompilerContext(ctx, delegate)
proc.SetResolveVariableFunc(func(string, bool, bool) (interface{}, error) {
t.Fatal("process resolver must not override frontend delegate")
return nil, nil
})
require.Equal(t, int64(2), build(compiler, "select 1").GetQuery().MaxDop)
delegate.ResolveVariableFunc = func(string, bool, bool) (interface{}, error) { return nil, nil }
require.Equal(t, int64(0), build(compiler, "select 1").GetQuery().MaxDop)
delegate.ResolveVariableFunc = func(string, bool, bool) (interface{}, error) { return nil, errors.New("delegate failed") }
_, err = compiler.ResolveVariable("max_dop", true, false)
require.ErrorContains(t, err, "delegate failed")
}
func TestInternalCompilerStatsCacheObservations(t *testing.T) {
ctrl := gomock.NewController(t)
proc := testutil.NewProcess(t)
op := mock_frontend.NewMockTxnOperator(ctrl)
proc.Base.TxnOperator = op
readonly := true
ws := mock_frontend.NewMockWorkspace(ctrl)
ws.EXPECT().Readonly().DoAndReturn(func() bool { return readonly }).AnyTimes()
op.EXPECT().GetWorkspace().Return(ws).AnyTimes()
op.EXPECT().Txn().Return(txn.TxnMeta{}).AnyTimes()
eng := mock_frontend.NewMockEngine(ctrl)
db := mock_frontend.NewMockDatabase(ctrl)
rel := mock_frontend.NewMockRelation(ctrl)
eng.EXPECT().Database(gomock.Any(), "d", op).Return(db, nil).AnyTimes()
db.EXPECT().Relation(gomock.Any(), "t", nil).Return(rel, nil).AnyTimes()
current := &pbstats.StatsInfo{TableName: "t", TableCnt: 5, NdvMap: map[string]float64{"v": 5}}
observed := current
calls := 0
rel.EXPECT().Stats(gomock.Any(), true).DoAndReturn(func(context.Context, bool) (*pbstats.StatsInfo, error) {
calls++
return observed, nil
}).AnyTimes()
ctx := &compilerContext{ctx: context.Background(), proc: proc, engine: eng, statsCache: plan.NewStatsCache()}
obj := &plan.ObjectRef{Obj: 42, SchemaName: "d", ObjName: "t"}
tableDef := &plan.TableDef{Version: 7}
got, err := ctx.StatsWithTableDef(obj, tableDef, nil)
require.NoError(t, err)
require.Same(t, current, got)
_, err = ctx.StatsWithTableDef(obj, tableDef, nil)
require.NoError(t, err)
require.Equal(t, 1, calls, "completed readonly observation is reused")
snapshot := &plan.Snapshot{TS: ×tamp.Timestamp{PhysicalTime: 1}}
for _, count := range []float64{2, 0} {
observed = &pbstats.StatsInfo{TableName: "t", TableCnt: count, NdvMap: map[string]float64{"v": count}}
got, err = ctx.StatsWithTableDef(obj, tableDef, snapshot)
require.NoError(t, err)
require.Same(t, observed, got)
wrapper := ctx.GetStatsCache().Get(42)
require.Equal(t, observed.NdvMap, wrapper.GetStats().NdvMap)
require.Empty(t, wrapper.GetStats().TableName)
require.Equal(t, "t", observed.TableName)
observed = current
before := calls
got, err = ctx.StatsWithTableDef(obj, tableDef, nil)
require.NoError(t, err)
require.Same(t, current, got)
require.Equal(t, before+1, calls, "historical maps cannot serve the current fast cache")
}
readonly = false
observed = &pbstats.StatsInfo{TableCnt: 10, AccurateObjectNumber: 1}
got, err = ctx.StatsWithTableDef(obj, tableDef, nil)
require.NoError(t, err)
require.Same(t, observed, got)
readonly = true
before := calls
_, err = ctx.StatsWithTableDef(obj, tableDef, nil)
require.NoError(t, err)
require.Equal(t, before+1, calls, "anonymous overlays cannot retain the 3s fast hit")
}
type failingStatementWorkspace struct {
Ws
err error
prepared int
}
func (w *failingStatementWorkspace) IncrStatementID(context.Context, bool) error {
w.prepared++
return w.err
}
type deferredRollbackTxn struct {
client.TxnOperator
sealed error
}
func (op *deferredRollbackTxn) RollbackAfterRunningSQL(err error) { op.sealed = err }
func (op *deferredRollbackTxn) TryEnterRunSqlWithTokenAndSQL(context.CancelFunc, string) (uint64, error) {
if op.sealed != nil {
return 0, moerr.NewTxnClosedNoCtx(nil)
}
return 1, nil
}