-
Notifications
You must be signed in to change notification settings - Fork 264
/
func_builtin.go
2282 lines (2110 loc) · 63.1 KB
/
func_builtin.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 2021 - 2022 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 function
import (
"bytes"
"context"
"encoding/json"
"fmt"
"math"
"math/rand"
"strings"
"time"
"unsafe"
"github.com/matrixorigin/matrixone/pkg/common/hashmap"
"github.com/matrixorigin/matrixone/pkg/common/moerr"
"github.com/matrixorigin/matrixone/pkg/common/runtime"
"github.com/matrixorigin/matrixone/pkg/common/util"
"github.com/matrixorigin/matrixone/pkg/config"
"github.com/matrixorigin/matrixone/pkg/container/hashtable"
"github.com/matrixorigin/matrixone/pkg/container/nulls"
"github.com/matrixorigin/matrixone/pkg/container/types"
"github.com/matrixorigin/matrixone/pkg/container/vector"
"github.com/matrixorigin/matrixone/pkg/pb/plan"
"github.com/matrixorigin/matrixone/pkg/sql/plan/function/functionUtil"
"github.com/matrixorigin/matrixone/pkg/util/executor"
"github.com/matrixorigin/matrixone/pkg/util/export/table"
"github.com/matrixorigin/matrixone/pkg/util/trace/impl/motrace"
"github.com/matrixorigin/matrixone/pkg/util/trace/impl/motrace/statistic"
"github.com/matrixorigin/matrixone/pkg/vectorize/moarray"
"github.com/matrixorigin/matrixone/pkg/vectorize/momath"
"github.com/matrixorigin/matrixone/pkg/vm/process"
"github.com/google/uuid"
)
func builtInDateDiff(parameters []*vector.Vector, result vector.FunctionResultWrapper, _ *process.Process, length int) error {
p1 := vector.GenerateFunctionFixedTypeParameter[types.Date](parameters[0])
p2 := vector.GenerateFunctionFixedTypeParameter[types.Date](parameters[1])
rs := vector.MustFunctionResult[int64](result)
for i := uint64(0); i < uint64(length); i++ {
v1, null1 := p1.GetValue(i)
v2, null2 := p2.GetValue(i)
if null1 || null2 {
if err := rs.Append(0, true); err != nil {
return err
}
} else {
if err := rs.Append(int64(v1-v2), false); err != nil {
return err
}
}
}
return nil
}
func builtInCurrentTimestamp(ivecs []*vector.Vector, result vector.FunctionResultWrapper, proc *process.Process, length int) error {
rs := vector.MustFunctionResult[types.Timestamp](result)
// TODO: not a good way to solve this problem. and will be fixed by file `specialRule.go`
scale := int32(6)
if len(ivecs) == 1 && !ivecs[0].IsConstNull() {
scale = int32(vector.MustFixedCol[int64](ivecs[0])[0])
}
rs.TempSetType(types.New(types.T_timestamp, 0, scale))
resultValue := types.UnixNanoToTimestamp(proc.UnixTime)
for i := uint64(0); i < uint64(length); i++ {
if err := rs.Append(resultValue, false); err != nil {
return err
}
}
return nil
}
func builtInSysdate(ivecs []*vector.Vector, result vector.FunctionResultWrapper, _ *process.Process, length int) error {
rs := vector.MustFunctionResult[types.Timestamp](result)
scale := int32(6)
if len(ivecs) == 1 && !ivecs[0].IsConstNull() {
scale = int32(vector.MustFixedCol[int64](ivecs[0])[0])
}
rs.TempSetType(types.New(types.T_timestamp, 0, scale))
resultValue := types.UnixNanoToTimestamp(time.Now().UnixNano())
for i := uint64(0); i < uint64(length); i++ {
if err := rs.Append(resultValue, false); err != nil {
return err
}
}
return nil
}
const (
onUpdateExpr = iota
defaultExpr
typNormal
typWithLen
)
func builtInMoShowVisibleBin(parameters []*vector.Vector, result vector.FunctionResultWrapper, proc *process.Process, length int) error {
p1 := vector.GenerateFunctionStrParameter(parameters[0])
p2 := vector.GenerateFunctionFixedTypeParameter[uint8](parameters[1])
tp, null := p2.GetValue(0)
if null {
return moerr.NewNotSupported(proc.Ctx, "show visible bin, the second argument must be in [0, 3], but got NULL")
}
if tp > 3 {
return moerr.NewNotSupported(proc.Ctx, fmt.Sprintf("show visible bin, the second argument must be in [0, 3], but got %d", tp))
}
var f func(s []byte) ([]byte, error)
rs := vector.MustFunctionResult[types.Varlena](result)
switch tp {
case onUpdateExpr:
f = func(s []byte) ([]byte, error) {
update := new(plan.OnUpdate)
err := types.Decode(s, update)
if err != nil {
return nil, err
}
return functionUtil.QuickStrToBytes(update.OriginString), nil
}
case defaultExpr:
f = func(s []byte) ([]byte, error) {
def := new(plan.Default)
err := types.Decode(s, def)
if err != nil {
return nil, err
}
return functionUtil.QuickStrToBytes(def.OriginString), nil
}
case typNormal:
f = func(s []byte) ([]byte, error) {
typ := new(types.Type)
err := types.Decode(s, typ)
if err != nil {
return nil, err
}
return functionUtil.QuickStrToBytes(typ.String()), nil
}
case typWithLen:
f = func(s []byte) ([]byte, error) {
typ := new(types.Type)
err := types.Decode(s, typ)
if err != nil {
return nil, err
}
ret := fmt.Sprintf("%s(%d)", typ.String(), typ.Width)
return functionUtil.QuickStrToBytes(ret), nil
}
}
for i := uint64(0); i < uint64(length); i++ {
v1, null1 := p1.GetStrValue(i)
if null1 || len(v1) == 0 {
if err := rs.AppendBytes(nil, true); err != nil {
return err
}
} else {
b, err := f(v1)
if err != nil {
return err
}
if b == nil {
if err := rs.AppendBytes(nil, true); err != nil {
return err
}
} else {
if err = rs.AppendBytes(b, false); err != nil {
return err
}
}
}
}
return nil
}
func builtInMoShowVisibleBinEnum(parameters []*vector.Vector, result vector.FunctionResultWrapper, proc *process.Process, length int) error {
p1 := vector.GenerateFunctionStrParameter(parameters[0])
enumVal := vector.GenerateFunctionStrParameter(parameters[1])
var f func([]byte, string) ([]byte, error)
rs := vector.MustFunctionResult[types.Varlena](result)
f = func(s []byte, enumStr string) ([]byte, error) {
typ := new(types.Type)
err := types.Decode(s, typ)
if err != nil {
return nil, err
}
if typ.Oid != types.T_enum {
return nil, moerr.NewNotSupported(proc.Ctx, "show visible bin enum, the type must be enum, but got %s", typ.String())
}
// get enum values
enums := strings.Split(enumStr, ",")
enumVal := ""
for i, e := range enums {
enumVal += fmt.Sprintf("'%s'", e)
if i < len(enums)-1 {
enumVal += ","
}
}
ret := fmt.Sprintf("%s(%s)", typ.String(), enumVal)
return functionUtil.QuickStrToBytes(ret), nil
}
for i := uint64(0); i < uint64(length); i++ {
v1, null1 := p1.GetStrValue(i)
enumStr, null2 := enumVal.GetStrValue(i)
if null1 || null2 || len(v1) == 0 || len(enumStr) == 0 {
if err := rs.AppendBytes(nil, true); err != nil {
return err
}
} else {
enumString := functionUtil.QuickBytesToStr(enumStr)
b, err := f(v1, enumString)
if err != nil {
return err
}
if b == nil {
if err := rs.AppendBytes(nil, true); err != nil {
return err
}
} else {
if err = rs.AppendBytes(b, false); err != nil {
return err
}
}
}
}
return nil
}
func builtInInternalCharLength(parameters []*vector.Vector, result vector.FunctionResultWrapper, _ *process.Process, length int) error {
p1 := vector.GenerateFunctionStrParameter(parameters[0])
rs := vector.MustFunctionResult[int64](result)
for i := uint64(0); i < uint64(length); i++ {
v, null := p1.GetStrValue(i)
if !null {
typ := types.Type{}
if err := types.Decode(v, &typ); err != nil {
return err
}
if typ.Oid.IsMySQLString() {
if err := rs.Append(int64(typ.Width), false); err != nil {
return err
}
continue
}
}
if err := rs.Append(0, true); err != nil {
return err
}
}
return nil
}
func builtInInternalCharSize(parameters []*vector.Vector, result vector.FunctionResultWrapper, _ *process.Process, length int) error {
p1 := vector.GenerateFunctionStrParameter(parameters[0])
rs := vector.MustFunctionResult[int64](result)
for i := uint64(0); i < uint64(length); i++ {
v, null := p1.GetStrValue(i)
if !null {
typ := types.Type{}
if err := types.Decode(v, &typ); err != nil {
return err
}
if typ.Oid.IsMySQLString() {
if err := rs.Append(int64(typ.GetSize()*typ.Width), false); err != nil {
return err
}
continue
}
}
if err := rs.Append(0, true); err != nil {
return err
}
}
return nil
}
func builtInInternalNumericPrecision(parameters []*vector.Vector, result vector.FunctionResultWrapper, _ *process.Process, length int) error {
p1 := vector.GenerateFunctionStrParameter(parameters[0])
rs := vector.MustFunctionResult[int64](result)
for i := uint64(0); i < uint64(length); i++ {
v, null := p1.GetStrValue(i)
if !null {
typ := types.Type{}
if err := types.Decode(v, &typ); err != nil {
return err
}
if typ.Oid.IsDecimal() {
if err := rs.Append(int64(typ.Width), false); err != nil {
return err
}
continue
}
}
if err := rs.Append(0, true); err != nil {
return err
}
}
return nil
}
func builtInInternalNumericScale(parameters []*vector.Vector, result vector.FunctionResultWrapper, _ *process.Process, length int) error {
p1 := vector.GenerateFunctionStrParameter(parameters[0])
rs := vector.MustFunctionResult[int64](result)
for i := uint64(0); i < uint64(length); i++ {
v, null := p1.GetStrValue(i)
if !null {
typ := types.Type{}
if err := types.Decode(v, &typ); err != nil {
return err
}
if typ.Oid.IsDecimal() {
if err := rs.Append(int64(typ.Scale), false); err != nil {
return err
}
continue
}
}
if err := rs.Append(0, true); err != nil {
return err
}
}
return nil
}
func builtInInternalDatetimeScale(parameters []*vector.Vector, result vector.FunctionResultWrapper, _ *process.Process, length int) error {
p1 := vector.GenerateFunctionStrParameter(parameters[0])
rs := vector.MustFunctionResult[int64](result)
for i := uint64(0); i < uint64(length); i++ {
v, null := p1.GetStrValue(i)
if !null {
typ := types.Type{}
if err := types.Decode(v, &typ); err != nil {
return err
}
if typ.Oid == types.T_datetime {
if err := rs.Append(int64(typ.Scale), false); err != nil {
return err
}
continue
}
}
if err := rs.Append(0, true); err != nil {
return err
}
}
return nil
}
func builtInInternalCharacterSet(parameters []*vector.Vector, result vector.FunctionResultWrapper, _ *process.Process, length int) error {
p1 := vector.GenerateFunctionStrParameter(parameters[0])
rs := vector.MustFunctionResult[int64](result)
for i := uint64(0); i < uint64(length); i++ {
v, null := p1.GetStrValue(i)
if !null {
typ := types.Type{}
if err := types.Decode(v, &typ); err != nil {
return err
}
if typ.Oid == types.T_varchar || typ.Oid == types.T_char ||
typ.Oid == types.T_blob || typ.Oid == types.T_text {
if err := rs.Append(int64(typ.Scale), false); err != nil {
return err
}
continue
}
}
if err := rs.Append(0, true); err != nil {
return err
}
}
return nil
}
func builtInConcatCheck(_ []overload, inputs []types.Type) checkResult {
if len(inputs) > 1 {
shouldCast := false
ret := make([]types.Type, len(inputs))
for i, source := range inputs {
if !source.Oid.IsMySQLString() {
c, _ := tryToMatch([]types.Type{source}, []types.T{types.T_varchar})
if c == matchFailed {
return newCheckResultWithFailure(failedFunctionParametersWrong)
}
if c == matchByCast {
shouldCast = true
ret[i] = types.T_varchar.ToType()
}
} else {
ret[i] = source
}
}
if shouldCast {
return newCheckResultWithCast(0, ret)
}
return newCheckResultWithSuccess(0)
}
return newCheckResultWithFailure(failedFunctionParametersWrong)
}
func builtInConcat(parameters []*vector.Vector, result vector.FunctionResultWrapper, _ *process.Process, length int) error {
rs := vector.MustFunctionResult[types.Varlena](result)
ps := make([]vector.FunctionParameterWrapper[types.Varlena], len(parameters))
for i := range ps {
ps[i] = vector.GenerateFunctionStrParameter(parameters[i])
}
for i := uint64(0); i < uint64(length); i++ {
var vs string
apv := true
for _, p := range ps {
v, null := p.GetStrValue(i)
if null {
if err := rs.AppendBytes(nil, true); err != nil {
return err
}
apv = false
break
} else {
vs += string(v)
}
}
if apv {
if err := rs.AppendBytes([]byte(vs), false); err != nil {
return err
}
}
}
return nil
}
const (
formatMask = "%Y/%m/%d"
regexpMask = `\d{1,4}/\d{1,2}/\d{1,2}`
)
// MOLogDate parse 'YYYY/MM/DD' date from input string.
// return '0001-01-01' if input string not container 'YYYY/MM/DD' substr, until DateParse Function support return NULL for invalid date string.
func builtInMoLogDate(parameters []*vector.Vector, result vector.FunctionResultWrapper, proc *process.Process, length int) error {
rs := vector.MustFunctionResult[types.Date](result)
p1 := vector.GenerateFunctionStrParameter(parameters[0])
op := newOpBuiltInRegexp()
generalTime := NewGeneralTime()
for i := uint64(0); i < uint64(length); i++ {
v, null := p1.GetStrValue(i)
if null {
if err := rs.Append(0, true); err != nil {
return err
}
} else {
expr := functionUtil.QuickBytesToStr(v)
match, parsedInput, err := op.regMap.regularSubstr(regexpMask, expr, 1, 1)
if err != nil {
return err
}
if !match {
if err = rs.Append(0, true); err != nil {
return err
}
} else {
generalTime.ResetTime()
success := coreStrToDate(proc.Ctx, generalTime, parsedInput, formatMask)
if success && types.ValidDate(int32(generalTime.year), generalTime.month, generalTime.day) {
val := types.DateFromCalendar(int32(generalTime.year), generalTime.month, generalTime.day)
if err = rs.Append(val, false); err != nil {
return err
}
} else {
if err = rs.Append(0, true); err != nil {
return err
}
}
}
}
}
return nil
}
// builtInPurgeLog act like `select mo_purge_log('rawlog,statement_info,metric', '2023-06-27')`
func builtInPurgeLog(parameters []*vector.Vector, result vector.FunctionResultWrapper, proc *process.Process, length int) error {
rs := vector.MustFunctionResult[uint8](result)
p1 := vector.GenerateFunctionStrParameter(parameters[0])
p2 := vector.GenerateFunctionFixedTypeParameter[types.Date](parameters[1])
if proc.SessionInfo.AccountId != sysAccountID {
return moerr.NewNotSupported(proc.Ctx, "only support sys account")
}
for i := uint64(0); i < uint64(length); i++ {
v1, null1 := p1.GetStrValue(i)
v2, null2 := p2.GetValue(i)
// fixme: should we need to support null date?
if null1 || null2 {
rs.Append(uint8(1), true)
continue
}
v, ok := runtime.ProcessLevelRuntime().GetGlobalVariables(runtime.InternalSQLExecutor)
if !ok {
return moerr.NewNotSupported(proc.Ctx, "no implement sqlExecutor")
}
exec := v.(executor.SQLExecutor)
tables := table.GetAllTables()
tableNames := strings.Split(util.UnsafeBytesToString(v1), ",")
for _, tblName := range tableNames {
found := false
for _, tbl := range tables {
if tbl.TimestampColumn != nil && strings.TrimSpace(tblName) == tbl.Table {
found = true
break
}
}
if !found {
return moerr.NewNotSupported(proc.Ctx, "purge '%s'", tblName)
}
}
for _, tblName := range tableNames {
for _, tbl := range tables {
if strings.TrimSpace(tblName) == tbl.Table {
sql := fmt.Sprintf("delete from `%s`.`%s` where `%s` < %q",
tbl.Database, tbl.Table, tbl.TimestampColumn.Name, v2.String())
opts := executor.Options{}.WithDatabase(tbl.Database).
WithTxn(proc.TxnOperator).
WithTimeZone(proc.SessionInfo.TimeZone)
if proc.TxnOperator != nil {
opts = opts.WithDisableIncrStatement() // this option always with WithTxn()
}
res, err := exec.Exec(proc.Ctx, sql, opts)
if err != nil {
return err
}
res.Close()
}
}
}
rs.Append(uint8(0), false)
}
return nil
}
func builtInDatabase(_ []*vector.Vector, result vector.FunctionResultWrapper, proc *process.Process, length int) error {
rs := vector.MustFunctionResult[types.Varlena](result)
for i := uint64(0); i < uint64(length); i++ {
db := proc.SessionInfo.GetDatabase()
if err := rs.AppendBytes(functionUtil.QuickStrToBytes(db), false); err != nil {
return err
}
}
return nil
}
func builtInCurrentRole(_ []*vector.Vector, result vector.FunctionResultWrapper, proc *process.Process, length int) error {
rs := vector.MustFunctionResult[types.Varlena](result)
for i := uint64(0); i < uint64(length); i++ {
if err := rs.AppendBytes([]byte(proc.SessionInfo.GetRole()), false); err != nil {
return err
}
}
return nil
}
func builtInCurrentAccountID(_ []*vector.Vector, result vector.FunctionResultWrapper, proc *process.Process, length int) error {
rs := vector.MustFunctionResult[uint32](result)
for i := uint64(0); i < uint64(length); i++ {
if err := rs.Append(proc.SessionInfo.AccountId, false); err != nil {
return err
}
}
return nil
}
func builtInCurrentAccountName(_ []*vector.Vector, result vector.FunctionResultWrapper, proc *process.Process, length int) error {
rs := vector.MustFunctionResult[types.Varlena](result)
for i := uint64(0); i < uint64(length); i++ {
if err := rs.AppendBytes([]byte(proc.SessionInfo.Account), false); err != nil {
return err
}
}
return nil
}
func builtInCurrentRoleID(_ []*vector.Vector, result vector.FunctionResultWrapper, proc *process.Process, length int) error {
rs := vector.MustFunctionResult[uint32](result)
for i := uint64(0); i < uint64(length); i++ {
if err := rs.Append(proc.SessionInfo.RoleId, false); err != nil {
return err
}
}
return nil
}
func builtInCurrentRoleName(_ []*vector.Vector, result vector.FunctionResultWrapper, proc *process.Process, length int) error {
rs := vector.MustFunctionResult[types.Varlena](result)
for i := uint64(0); i < uint64(length); i++ {
if err := rs.AppendBytes([]byte(proc.SessionInfo.Role), false); err != nil {
return err
}
}
return nil
}
func builtInCurrentUserID(_ []*vector.Vector, result vector.FunctionResultWrapper, proc *process.Process, length int) error {
rs := vector.MustFunctionResult[uint32](result)
for i := uint64(0); i < uint64(length); i++ {
if err := rs.Append(proc.SessionInfo.UserId, false); err != nil {
return err
}
}
return nil
}
func builtInCurrentUserName(_ []*vector.Vector, result vector.FunctionResultWrapper, proc *process.Process, length int) error {
rs := vector.MustFunctionResult[types.Varlena](result)
for i := uint64(0); i < uint64(length); i++ {
if err := rs.AppendBytes([]byte(proc.SessionInfo.User), false); err != nil {
return err
}
}
return nil
}
const MaxTgtLen = int64(16 * 1024 * 1024)
func doLpad(src string, tgtLen int64, pad string) (string, bool) {
srcRune, padRune := []rune(src), []rune(pad)
srcLen, padLen := len(srcRune), len(padRune)
if tgtLen < 0 || tgtLen > MaxTgtLen {
return "", true
} else if int(tgtLen) < srcLen {
return string(srcRune[:tgtLen]), false
} else if int(tgtLen) == srcLen {
return src, false
} else if padLen == 0 {
return "", false
} else {
r := int(tgtLen) - srcLen
p, m := r/padLen, r%padLen
return strings.Repeat(pad, p) + string(padRune[:m]) + src, false
}
}
func doRpad(src string, tgtLen int64, pad string) (string, bool) {
srcRune, padRune := []rune(src), []rune(pad)
srcLen, padLen := len(srcRune), len(padRune)
if tgtLen < 0 || tgtLen > MaxTgtLen {
return "", true
} else if int(tgtLen) < srcLen {
return string(srcRune[:tgtLen]), false
} else if int(tgtLen) == srcLen {
return src, false
} else if padLen == 0 {
return "", false
} else {
r := int(tgtLen) - srcLen
p, m := r/padLen, r%padLen
return src + strings.Repeat(pad, p) + string(padRune[:m]), false
}
}
func builtInRepeat(parameters []*vector.Vector, result vector.FunctionResultWrapper, proc *process.Process, length int) error {
// repeat the string n times.
repeatNTimes := func(base string, n int64) (r string, null bool) {
if n <= 0 {
return "", false
}
// return null if result is too long.
// I'm not sure if this is the right thing to do, MySql can repeat string with the result length at least 1,000,000.
// and there is no documentation about the limit of the result length.
sourceLen := int64(len(base))
if sourceLen*n > MaxTgtLen {
return "", true
}
return strings.Repeat(base, int(n)), false
}
p1 := vector.GenerateFunctionStrParameter(parameters[0])
p2 := vector.GenerateFunctionFixedTypeParameter[int64](parameters[1])
rs := vector.MustFunctionResult[types.Varlena](result)
var err error
rowCount := uint64(length)
for i := uint64(0); i < rowCount; i++ {
v1, null1 := p1.GetStrValue(i)
v2, null2 := p2.GetValue(i)
if null1 || null2 {
err = rs.AppendMustNullForBytesResult()
} else {
r, null := repeatNTimes(functionUtil.QuickBytesToStr(v1), v2)
if null {
err = rs.AppendMustNullForBytesResult()
} else {
err = rs.AppendBytes([]byte(r), false)
}
}
if err != nil {
return err
}
}
return nil
}
func builtInLpad(parameters []*vector.Vector, result vector.FunctionResultWrapper, _ *process.Process, length int) error {
p1 := vector.GenerateFunctionStrParameter(parameters[0])
p2 := vector.GenerateFunctionFixedTypeParameter[int64](parameters[1])
p3 := vector.GenerateFunctionStrParameter(parameters[2])
rs := vector.MustFunctionResult[types.Varlena](result)
for i := uint64(0); i < uint64(length); i++ {
v1, null1 := p1.GetStrValue(i)
v2, null2 := p2.GetValue(i)
v3, null3 := p3.GetStrValue(i)
if !(null1 || null2 || null3) {
rval, shouldNull := doLpad(string(v1), v2, string(v3))
if !shouldNull {
if err := rs.AppendBytes([]byte(rval), false); err != nil {
return err
}
continue
}
}
if err := rs.AppendBytes(nil, true); err != nil {
return err
}
}
return nil
}
func builtInRpad(parameters []*vector.Vector, result vector.FunctionResultWrapper, _ *process.Process, length int) error {
p1 := vector.GenerateFunctionStrParameter(parameters[0])
p2 := vector.GenerateFunctionFixedTypeParameter[int64](parameters[1])
p3 := vector.GenerateFunctionStrParameter(parameters[2])
rs := vector.MustFunctionResult[types.Varlena](result)
for i := uint64(0); i < uint64(length); i++ {
v1, null1 := p1.GetStrValue(i)
v2, null2 := p2.GetValue(i)
v3, null3 := p3.GetStrValue(i)
if !(null1 || null2 || null3) {
rval, shouldNull := doRpad(string(v1), v2, string(v3))
if !shouldNull {
if err := rs.AppendBytes([]byte(rval), false); err != nil {
return err
}
continue
}
}
if err := rs.AppendBytes(nil, true); err != nil {
return err
}
}
return nil
}
func builtInUUID(_ []*vector.Vector, result vector.FunctionResultWrapper, proc *process.Process, length int) error {
rs := vector.MustFunctionResult[types.Uuid](result)
for i := uint64(0); i < uint64(length); i++ {
val, err := uuid.NewV7()
if err != nil {
return moerr.NewInternalError(proc.Ctx, "newuuid failed")
}
if err = rs.Append(types.Uuid(val), false); err != nil {
return err
}
}
return nil
}
func builtInUnixTimestamp(parameters []*vector.Vector, result vector.FunctionResultWrapper, _ *process.Process, length int) error {
rs := vector.MustFunctionResult[int64](result)
if len(parameters) == 0 {
val := types.CurrentTimestamp().Unix()
for i := uint64(0); i < uint64(length); i++ {
if err := rs.Append(val, false); err != nil {
return nil
}
}
return nil
}
p1 := vector.GenerateFunctionFixedTypeParameter[types.Timestamp](parameters[0])
for i := uint64(0); i < uint64(length); i++ {
v1, null1 := p1.GetValue(i)
val := v1.Unix()
if val < 0 || null1 {
// XXX v1 < 0 need to raise error here.
if err := rs.Append(0, true); err != nil {
return err
}
} else {
if err := rs.Append(val, false); err != nil {
return err
}
}
}
return nil
}
func mustTimestamp(loc *time.Location, s string) types.Timestamp {
ts, err := types.ParseTimestamp(loc, s, 6)
if err != nil {
ts = 0
}
return ts
}
func builtInUnixTimestampVarcharToInt64(parameters []*vector.Vector, result vector.FunctionResultWrapper, proc *process.Process, length int) error {
p1 := vector.GenerateFunctionStrParameter(parameters[0])
rs := vector.MustFunctionResult[int64](result)
for i := uint64(0); i < uint64(length); i++ {
v1, null1 := p1.GetStrValue(i)
if null1 {
if err := rs.Append(0, true); err != nil {
return err
}
} else {
val := mustTimestamp(proc.SessionInfo.TimeZone, string(v1)).Unix()
if val < 0 {
if err := rs.Append(0, true); err != nil {
return err
}
continue
}
if err := rs.Append(val, false); err != nil {
return err
}
}
}
return nil
}
var _ = builtInUnixTimestampVarcharToFloat64
func builtInUnixTimestampVarcharToFloat64(parameters []*vector.Vector, result vector.FunctionResultWrapper, proc *process.Process, length int) error {
p1 := vector.GenerateFunctionStrParameter(parameters[0])
rs := vector.MustFunctionResult[float64](result)
for i := uint64(0); i < uint64(length); i++ {
v1, null1 := p1.GetStrValue(i)
if null1 {
if err := rs.Append(0, true); err != nil {
return err
}
} else {
val := mustTimestamp(proc.SessionInfo.TimeZone, string(v1))
if err := rs.Append(val.UnixToFloat(), false); err != nil {
return err
}
}
}
return nil
}
func builtInUnixTimestampVarcharToDecimal128(parameters []*vector.Vector, result vector.FunctionResultWrapper, proc *process.Process, length int) error {
p1 := vector.GenerateFunctionStrParameter(parameters[0])
rs := vector.MustFunctionResult[types.Decimal128](result)
var d types.Decimal128
for i := uint64(0); i < uint64(length); i++ {
v1, null1 := p1.GetStrValue(i)
if null1 {
if err := rs.Append(d, true); err != nil {
return err
}
} else {
val, err := mustTimestamp(proc.SessionInfo.TimeZone, string(v1)).UnixToDecimal128()
if err != nil {
return err
}
if val.Compare(types.Decimal128{B0_63: 0, B64_127: 0}) <= 0 {
if err := rs.Append(d, true); err != nil {
return err
}
}
if err = rs.Append(val, false); err != nil {
return err
}
}
}
return nil
}
// XXX I just copy this function.
func builtInHash(parameters []*vector.Vector, result vector.FunctionResultWrapper, proc *process.Process, length int) error {
fillStringGroupStr := func(keys [][]byte, vec *vector.Vector, n int, start int) {
area := vec.GetArea()
vs := vector.MustFixedCol[types.Varlena](vec)
if !vec.GetNulls().Any() {
for i := 0; i < n; i++ {
keys[i] = append(keys[i], byte(0))
keys[i] = append(keys[i], vs[i+start].GetByteSlice(area)...)
}
} else {
nsp := vec.GetNulls()
for i := 0; i < n; i++ {
hasNull := nsp.Contains(uint64(i + start))
if hasNull {
keys[i] = append(keys[i], byte(1))
} else {
keys[i] = append(keys[i], byte(0))
keys[i] = append(keys[i], vs[i+start].GetByteSlice(area)...)
}
}
}
}
fillGroupStr := func(keys [][]byte, vec *vector.Vector, n int, sz int, start int) {
data := unsafe.Slice(vector.GetPtrAt[byte](vec, 0), (n+start)*sz)
if !vec.GetNulls().Any() {
for i := 0; i < n; i++ {
keys[i] = append(keys[i], byte(0))
keys[i] = append(keys[i], data[(i+start)*sz:(i+start+1)*sz]...)
}
} else {
nsp := vec.GetNulls()
for i := 0; i < n; i++ {
isNull := nsp.Contains(uint64(i + start))
if isNull {
keys[i] = append(keys[i], byte(1))
} else {
keys[i] = append(keys[i], byte(0))
keys[i] = append(keys[i], data[(i+start)*sz:(i+start+1)*sz]...)
}
}
}
}
encodeHashKeys := func(keys [][]byte, vecs []*vector.Vector, start, count int) {
for _, vec := range vecs {
if vec.GetType().IsFixedLen() {
fillGroupStr(keys, vec, count, vec.GetType().TypeSize(), start)
} else {
fillStringGroupStr(keys, vec, count, start)
}
}
for i := 0; i < count; i++ {
if l := len(keys[i]); l < 16 {
keys[i] = append(keys[i], hashtable.StrKeyPadding[l:]...)
}
}
}
rs := vector.MustFunctionResult[int64](result)
keys := make([][]byte, hashmap.UnitLimit)
states := make([][3]uint64, hashmap.UnitLimit)
for i := 0; i < length; i += hashmap.UnitLimit {
n := length - i
if n > hashmap.UnitLimit {
n = hashmap.UnitLimit
}
for j := 0; j < n; j++ {
keys[j] = keys[j][:0]
}
encodeHashKeys(keys, parameters, i, n)
hashtable.BytesBatchGenHashStates(&keys[0], &states[0], n)
for j := 0; j < n; j++ {
rs.AppendMustValue(int64(states[j][0]))
}
}
return nil
}
// BuiltInSerial have a similar function named SerialWithCompacted in the index_util