forked from apache/flink
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CodeGenerator.scala
1531 lines (1337 loc) · 53.1 KB
/
CodeGenerator.scala
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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.flink.api.table.codegen
import java.math.{BigDecimal => JBigDecimal}
import org.apache.calcite.avatica.util.DateTimeUtils
import org.apache.calcite.rex._
import org.apache.calcite.sql.SqlOperator
import org.apache.calcite.sql.`type`.SqlTypeName._
import org.apache.calcite.sql.fun.SqlStdOperatorTable._
import org.apache.flink.api.common.functions.{FlatJoinFunction, FlatMapFunction, Function, MapFunction}
import org.apache.flink.api.common.io.GenericInputFormat
import org.apache.flink.api.common.typeinfo.{AtomicType, SqlTimeTypeInfo, TypeInformation}
import org.apache.flink.api.common.typeutils.CompositeType
import org.apache.flink.api.java.typeutils.{GenericTypeInfo, PojoTypeInfo, TupleTypeInfo}
import org.apache.flink.api.scala.typeutils.CaseClassTypeInfo
import org.apache.flink.api.table.codegen.CodeGenUtils._
import org.apache.flink.api.table.codegen.GeneratedExpression.{NEVER_NULL, NO_CODE}
import org.apache.flink.api.table.codegen.Indenter.toISC
import org.apache.flink.api.table.codegen.calls.FunctionGenerator
import org.apache.flink.api.table.codegen.calls.ScalarOperators._
import org.apache.flink.api.table.functions.UserDefinedFunction
import org.apache.flink.api.table.typeutils.{RowTypeInfo, TypeConverter}
import org.apache.flink.api.table.typeutils.TypeCheckUtils._
import org.apache.flink.api.table.{FlinkTypeFactory, TableConfig}
import scala.collection.JavaConversions._
import scala.collection.mutable
/**
* A code generator for generating Flink [[org.apache.flink.api.common.functions.Function]]s.
*
* @param config configuration that determines runtime behavior
* @param nullableInput input(s) can be null.
* @param input1 type information about the first input of the Function
* @param input2 type information about the second input if the Function is binary
* @param input1PojoFieldMapping additional mapping information if input1 is a POJO (POJO types
* have no deterministic field order).
* @param input2PojoFieldMapping additional mapping information if input2 is a POJO (POJO types
* have no deterministic field order).
*
*/
class CodeGenerator(
config: TableConfig,
nullableInput: Boolean,
input1: TypeInformation[Any],
input2: Option[TypeInformation[Any]] = None,
input1PojoFieldMapping: Option[Array[Int]] = None,
input2PojoFieldMapping: Option[Array[Int]] = None)
extends RexVisitor[GeneratedExpression] {
// check if nullCheck is enabled when inputs can be null
if (nullableInput && !config.getNullCheck) {
throw new CodeGenException("Null check must be enabled if entire rows can be null.")
}
// check for POJO input1 mapping
input1 match {
case pt: PojoTypeInfo[_] =>
input1PojoFieldMapping.getOrElse(
throw new CodeGenException("No input mapping is specified for input1 of type POJO."))
case _ => // ok
}
// check for POJO input2 mapping
input2 match {
case Some(pt: PojoTypeInfo[_]) =>
input2PojoFieldMapping.getOrElse(
throw new CodeGenException("No input mapping is specified for input2 of type POJO."))
case _ => // ok
}
/**
* A code generator for generating unary Flink
* [[org.apache.flink.api.common.functions.Function]]s with one input.
*
* @param config configuration that determines runtime behavior
* @param nullableInput input(s) can be null.
* @param input type information about the input of the Function
* @param inputPojoFieldMapping additional mapping information necessary if input is a
* POJO (POJO types have no deterministic field order).
*/
def this(
config: TableConfig,
nullableInput: Boolean,
input: TypeInformation[Any],
inputPojoFieldMapping: Array[Int]) =
this(config, nullableInput, input, None, Some(inputPojoFieldMapping))
/**
* A code generator for generating Flink input formats.
*
* @param config configuration that determines runtime behavior
*/
def this(config: TableConfig) =
this(config, false, TypeConverter.DEFAULT_ROW_TYPE, None, None)
// set of member statements that will be added only once
// we use a LinkedHashSet to keep the insertion order
private val reusableMemberStatements = mutable.LinkedHashSet[String]()
// set of constructor statements that will be added only once
// we use a LinkedHashSet to keep the insertion order
private val reusableInitStatements = mutable.LinkedHashSet[String]()
// set of statements that will be added only once per record
// we use a LinkedHashSet to keep the insertion order
private val reusablePerRecordStatements = mutable.LinkedHashSet[String]()
// map of initial input unboxing expressions that will be added only once
// (inputTerm, index) -> expr
private val reusableInputUnboxingExprs = mutable.Map[(String, Int), GeneratedExpression]()
/**
* @return code block of statements that need to be placed in the member area of the Function
* (e.g. member variables and their initialization)
*/
def reuseMemberCode(): String = {
reusableMemberStatements.mkString("", "\n", "\n")
}
/**
* @return code block of statements that need to be placed in the constructor of the Function
*/
def reuseInitCode(): String = {
reusableInitStatements.mkString("", "\n", "\n")
}
/**
* @return code block of statements that need to be placed in the SAM of the Function
*/
def reusePerRecordCode(): String = {
reusablePerRecordStatements.mkString("", "\n", "\n")
}
/**
* @return code block of statements that unbox input variables to a primitive variable
* and a corresponding null flag variable
*/
def reuseInputUnboxingCode(): String = {
reusableInputUnboxingExprs.values.map(_.code).mkString("", "\n", "\n")
}
/**
* @return term of the (casted and possibly boxed) first input
*/
var input1Term = "in1"
/**
* @return term of the (casted and possibly boxed) second input
*/
var input2Term = "in2"
/**
* @return term of the (casted) output collector
*/
var collectorTerm = "c"
/**
* @return term of the output record (possibly defined in the member area e.g. Row, Tuple)
*/
var outRecordTerm = "out"
/**
* @return returns if null checking is enabled
*/
def nullCheck: Boolean = config.getNullCheck
/**
* Generates an expression from a RexNode. If objects or variables can be reused, they will be
* added to reusable code sections internally.
*
* @param rex Calcite row expression
* @return instance of GeneratedExpression
*/
def generateExpression(rex: RexNode): GeneratedExpression = {
rex.accept(this)
}
/**
* Generates a [[org.apache.flink.api.common.functions.Function]] that can be passed to Java
* compiler.
*
* @param name Class name of the Function. Must not be unique but has to be a valid Java class
* identifier.
* @param clazz Flink Function to be generated.
* @param bodyCode code contents of the SAM (Single Abstract Method). Inputs, collector, or
* output record can be accessed via the given term methods.
* @param returnType expected return type
* @tparam T Flink Function to be generated.
* @return instance of GeneratedFunction
*/
def generateFunction[T <: Function](
name: String,
clazz: Class[T],
bodyCode: String,
returnType: TypeInformation[Any])
: GeneratedFunction[T] = {
val funcName = newName(name)
// Janino does not support generics, that's why we need
// manual casting here
val samHeader =
// FlatMapFunction
if (clazz == classOf[FlatMapFunction[_,_]]) {
val inputTypeTerm = boxedTypeTermForTypeInfo(input1)
(s"void flatMap(Object _in1, org.apache.flink.util.Collector $collectorTerm)",
List(s"$inputTypeTerm $input1Term = ($inputTypeTerm) _in1;"))
}
// MapFunction
else if (clazz == classOf[MapFunction[_,_]]) {
val inputTypeTerm = boxedTypeTermForTypeInfo(input1)
("Object map(Object _in1)",
List(s"$inputTypeTerm $input1Term = ($inputTypeTerm) _in1;"))
}
// FlatJoinFunction
else if (clazz == classOf[FlatJoinFunction[_,_,_]]) {
val inputTypeTerm1 = boxedTypeTermForTypeInfo(input1)
val inputTypeTerm2 = boxedTypeTermForTypeInfo(input2.getOrElse(
throw new CodeGenException("Input 2 for FlatJoinFunction should not be null")))
(s"void join(Object _in1, Object _in2, org.apache.flink.util.Collector $collectorTerm)",
List(s"$inputTypeTerm1 $input1Term = ($inputTypeTerm1) _in1;",
s"$inputTypeTerm2 $input2Term = ($inputTypeTerm2) _in2;"))
}
else {
// TODO more functions
throw new CodeGenException("Unsupported Function.")
}
val funcCode = j"""
public class $funcName
implements ${clazz.getCanonicalName} {
${reuseMemberCode()}
public $funcName() throws Exception {
${reuseInitCode()}
}
@Override
public ${samHeader._1} throws Exception {
${samHeader._2.mkString("\n")}
${reusePerRecordCode()}
${reuseInputUnboxingCode()}
$bodyCode
}
}
""".stripMargin
GeneratedFunction(funcName, returnType, funcCode)
}
/**
* Generates a values input format that can be passed to Java compiler.
*
* @param name Class name of the input format. Must not be unique but has to be a
* valid Java class identifier.
* @param records code for creating records
* @param returnType expected return type
* @tparam T Flink Function to be generated.
* @return instance of GeneratedFunction
*/
def generateValuesInputFormat[T](
name: String,
records: Seq[String],
returnType: TypeInformation[Any])
: GeneratedFunction[GenericInputFormat[T]] = {
val funcName = newName(name)
addReusableOutRecord(returnType)
val funcCode = j"""
public class $funcName extends ${classOf[GenericInputFormat[_]].getCanonicalName} {
private int nextIdx = 0;
${reuseMemberCode()}
public $funcName() throws Exception {
${reuseInitCode()}
}
@Override
public boolean reachedEnd() throws java.io.IOException {
return nextIdx >= ${records.length};
}
@Override
public Object nextRecord(Object reuse) {
switch (nextIdx) {
${records.zipWithIndex.map { case (r, i) =>
s"""
|case $i:
| $r
|break;
""".stripMargin
}.mkString("\n")}
}
nextIdx++;
return $outRecordTerm;
}
}
""".stripMargin
GeneratedFunction[GenericInputFormat[T]](funcName, returnType, funcCode)
}
/**
* Generates an expression that converts the first input (and second input) into the given type.
* If two inputs are converted, the second input is appended. If objects or variables can
* be reused, they will be added to reusable code sections internally. The evaluation result
* may be stored in the global result variable (see [[outRecordTerm]]).
*
* @param returnType conversion target type. Inputs and output must have the same arity.
* @param resultFieldNames result field names necessary for a mapping to POJO fields.
* @return instance of GeneratedExpression
*/
def generateConverterResultExpression(
returnType: TypeInformation[_ <: Any],
resultFieldNames: Seq[String])
: GeneratedExpression = {
val input1AccessExprs = for (i <- 0 until input1.getArity)
yield generateInputAccess(input1, input1Term, i, input1PojoFieldMapping)
val input2AccessExprs = input2 match {
case Some(ti) => for (i <- 0 until ti.getArity)
yield generateInputAccess(ti, input2Term, i, input2PojoFieldMapping)
case None => Seq() // add nothing
}
generateResultExpression(input1AccessExprs ++ input2AccessExprs, returnType, resultFieldNames)
}
/**
* Generates an expression from the left input and the right table function.
*/
def generateCorrelateAccessExprs: (Seq[GeneratedExpression], Seq[GeneratedExpression]) = {
val input1AccessExprs = for (i <- 0 until input1.getArity)
yield generateInputAccess(input1, input1Term, i, input1PojoFieldMapping)
val input2AccessExprs = input2 match {
case Some(ti) => for (i <- 0 until ti.getArity)
// use generateFieldAccess instead of generateInputAccess to avoid the generated table
// function's field access code is put on the top of function body rather than
// the while loop
yield generateFieldAccess(ti, input2Term, i, input2PojoFieldMapping)
case None => throw new CodeGenException("Type information of input2 must not be null.")
}
(input1AccessExprs, input2AccessExprs)
}
/**
* Generates an expression from a sequence of RexNode. If objects or variables can be reused,
* they will be added to reusable code sections internally. The evaluation result
* may be stored in the global result variable (see [[outRecordTerm]]).
*
* @param returnType conversion target type. Type must have the same arity than rexNodes.
* @param resultFieldNames result field names necessary for a mapping to POJO fields.
* @param rexNodes sequence of RexNode to be converted
* @return instance of GeneratedExpression
*/
def generateResultExpression(
returnType: TypeInformation[_ <: Any],
resultFieldNames: Seq[String],
rexNodes: Seq[RexNode])
: GeneratedExpression = {
val fieldExprs = rexNodes.map(generateExpression)
generateResultExpression(fieldExprs, returnType, resultFieldNames)
}
/**
* Generates an expression from a sequence of other expressions. If objects or variables can
* be reused, they will be added to reusable code sections internally. The evaluation result
* may be stored in the global result variable (see [[outRecordTerm]]).
*
* @param fieldExprs field expressions to be converted
* @param returnType conversion target type. Type must have the same arity than fieldExprs.
* @param resultFieldNames result field names necessary for a mapping to POJO fields.
* @return instance of GeneratedExpression
*/
def generateResultExpression(
fieldExprs: Seq[GeneratedExpression],
returnType: TypeInformation[_ <: Any],
resultFieldNames: Seq[String])
: GeneratedExpression = {
// initial type check
if (returnType.getArity != fieldExprs.length) {
throw new CodeGenException("Arity of result type does not match number of expressions.")
}
if (resultFieldNames.length != fieldExprs.length) {
throw new CodeGenException("Arity of result field names does not match number of " +
"expressions.")
}
// type check
returnType match {
case pt: PojoTypeInfo[_] =>
fieldExprs.zipWithIndex foreach {
case (fieldExpr, i) if fieldExpr.resultType != pt.getTypeAt(resultFieldNames(i)) =>
throw new CodeGenException("Incompatible types of expression and result type.")
case _ => // ok
}
case ct: CompositeType[_] =>
fieldExprs.zipWithIndex foreach {
case (fieldExpr, i) if fieldExpr.resultType != ct.getTypeAt(i) =>
throw new CodeGenException("Incompatible types of expression and result type.")
case _ => // ok
}
case at: AtomicType[_] if at != fieldExprs.head.resultType =>
throw new CodeGenException("Incompatible types of expression and result type.")
case _ => // ok
}
val returnTypeTerm = boxedTypeTermForTypeInfo(returnType)
val boxedFieldExprs = fieldExprs.map(generateOutputFieldBoxing)
// generate result expression
returnType match {
case ri: RowTypeInfo =>
addReusableOutRecord(ri)
val resultSetters: String = boxedFieldExprs.zipWithIndex map {
case (fieldExpr, i) =>
if (nullCheck) {
s"""
|${fieldExpr.code}
|if (${fieldExpr.nullTerm}) {
| $outRecordTerm.setField($i, null);
|}
|else {
| $outRecordTerm.setField($i, ${fieldExpr.resultTerm});
|}
|""".stripMargin
}
else {
s"""
|${fieldExpr.code}
|$outRecordTerm.setField($i, ${fieldExpr.resultTerm});
|""".stripMargin
}
} mkString "\n"
GeneratedExpression(outRecordTerm, "false", resultSetters, returnType)
case pt: PojoTypeInfo[_] =>
addReusableOutRecord(pt)
val resultSetters: String = boxedFieldExprs.zip(resultFieldNames) map {
case (fieldExpr, fieldName) =>
val accessor = getFieldAccessor(pt.getTypeClass, fieldName)
accessor match {
// Reflective access of primitives/Objects
case ObjectPrivateFieldAccessor(field) =>
val fieldTerm = addReusablePrivateFieldAccess(pt.getTypeClass, fieldName)
val defaultIfNull = if (isFieldPrimitive(field)) {
primitiveDefaultValue(fieldExpr.resultType)
} else {
"null"
}
if (nullCheck) {
s"""
|${fieldExpr.code}
|if (${fieldExpr.nullTerm}) {
| ${reflectiveFieldWriteAccess(
fieldTerm,
field,
outRecordTerm,
defaultIfNull)};
|}
|else {
| ${reflectiveFieldWriteAccess(
fieldTerm,
field,
outRecordTerm,
fieldExpr.resultTerm)};
|}
|""".stripMargin
}
else {
s"""
|${fieldExpr.code}
|${reflectiveFieldWriteAccess(
fieldTerm,
field,
outRecordTerm,
fieldExpr.resultTerm)};
|""".stripMargin
}
// primitive or Object field access (implicit boxing)
case _ =>
if (nullCheck) {
s"""
|${fieldExpr.code}
|if (${fieldExpr.nullTerm}) {
| $outRecordTerm.$fieldName = null;
|}
|else {
| $outRecordTerm.$fieldName = ${fieldExpr.resultTerm};
|}
|""".stripMargin
}
else {
s"""
|${fieldExpr.code}
|$outRecordTerm.$fieldName = ${fieldExpr.resultTerm};
|""".stripMargin
}
}
} mkString "\n"
GeneratedExpression(outRecordTerm, "false", resultSetters, returnType)
case tup: TupleTypeInfo[_] =>
addReusableOutRecord(tup)
val resultSetters: String = boxedFieldExprs.zipWithIndex map {
case (fieldExpr, i) =>
val fieldName = "f" + i
if (nullCheck) {
s"""
|${fieldExpr.code}
|if (${fieldExpr.nullTerm}) {
| throw new NullPointerException("Null result cannot be stored in a Tuple.");
|}
|else {
| $outRecordTerm.$fieldName = ${fieldExpr.resultTerm};
|}
|""".stripMargin
}
else {
s"""
|${fieldExpr.code}
|$outRecordTerm.$fieldName = ${fieldExpr.resultTerm};
|""".stripMargin
}
} mkString "\n"
GeneratedExpression(outRecordTerm, "false", resultSetters, returnType)
case cc: CaseClassTypeInfo[_] =>
val fieldCodes: String = boxedFieldExprs.map(_.code).mkString("\n")
val constructorParams: String = boxedFieldExprs.map(_.resultTerm).mkString(", ")
val resultTerm = newName(outRecordTerm)
val nullCheckCode = if (nullCheck) {
boxedFieldExprs map { (fieldExpr) =>
s"""
|if (${fieldExpr.nullTerm}) {
| throw new NullPointerException("Null result cannot be stored in a Case Class.");
|}
|""".stripMargin
} mkString "\n"
} else {
""
}
val resultCode =
s"""
|$fieldCodes
|$nullCheckCode
|$returnTypeTerm $resultTerm = new $returnTypeTerm($constructorParams);
|""".stripMargin
GeneratedExpression(resultTerm, "false", resultCode, returnType)
case a: AtomicType[_] =>
val fieldExpr = boxedFieldExprs.head
val nullCheckCode = if (nullCheck) {
s"""
|if (${fieldExpr.nullTerm}) {
| throw new NullPointerException("Null result cannot be used for atomic types.");
|}
|""".stripMargin
} else {
""
}
val resultCode =
s"""
|${fieldExpr.code}
|$nullCheckCode
|""".stripMargin
GeneratedExpression(fieldExpr.resultTerm, "false", resultCode, returnType)
case _ =>
throw new CodeGenException(s"Unsupported result type: $returnType")
}
}
// ----------------------------------------------------------------------------------------------
// RexVisitor methods
// ----------------------------------------------------------------------------------------------
override def visitInputRef(inputRef: RexInputRef): GeneratedExpression = {
// if inputRef index is within size of input1 we work with input1, input2 otherwise
val input = if (inputRef.getIndex < input1.getArity) {
(input1, input1Term, input1PojoFieldMapping)
} else {
(input2.getOrElse(throw new CodeGenException("Invalid input access.")),
input2Term,
input2PojoFieldMapping)
}
val index = if (input._2 == input1Term) {
inputRef.getIndex
} else {
inputRef.getIndex - input1.getArity
}
generateInputAccess(input._1, input._2, index, input._3)
}
override def visitFieldAccess(rexFieldAccess: RexFieldAccess): GeneratedExpression = {
val refExpr = rexFieldAccess.getReferenceExpr.accept(this)
val index = rexFieldAccess.getField.getIndex
val fieldAccessExpr = generateFieldAccess(
refExpr.resultType,
refExpr.resultTerm,
index,
input1PojoFieldMapping)
val resultTerm = newName("result")
val nullTerm = newName("isNull")
val resultTypeTerm = primitiveTypeTermForTypeInfo(fieldAccessExpr.resultType)
val defaultValue = primitiveDefaultValue(fieldAccessExpr.resultType)
val resultCode = if (nullCheck) {
s"""
|${refExpr.code}
|$resultTypeTerm $resultTerm;
|boolean $nullTerm;
|if (${refExpr.nullTerm}) {
| $resultTerm = $defaultValue;
| $nullTerm = true;
|}
|else {
| ${fieldAccessExpr.code}
| $resultTerm = ${fieldAccessExpr.resultTerm};
| $nullTerm = ${fieldAccessExpr.nullTerm};
|}
|""".stripMargin
} else {
s"""
|${refExpr.code}
|${fieldAccessExpr.code}
|$resultTypeTerm $resultTerm = ${fieldAccessExpr.resultTerm};
|""".stripMargin
}
GeneratedExpression(resultTerm, nullTerm, resultCode, fieldAccessExpr.resultType)
}
override def visitLiteral(literal: RexLiteral): GeneratedExpression = {
val resultType = FlinkTypeFactory.toTypeInfo(literal.getType)
val value = literal.getValue3
// null value with type
if (value == null) {
return generateNullLiteral(resultType)
}
// non-null values
literal.getType.getSqlTypeName match {
case BOOLEAN =>
generateNonNullLiteral(resultType, literal.getValue3.toString)
case TINYINT =>
val decimal = BigDecimal(value.asInstanceOf[JBigDecimal])
if (decimal.isValidByte) {
generateNonNullLiteral(resultType, decimal.byteValue().toString)
}
else {
throw new CodeGenException("Decimal can not be converted to byte.")
}
case SMALLINT =>
val decimal = BigDecimal(value.asInstanceOf[JBigDecimal])
if (decimal.isValidShort) {
generateNonNullLiteral(resultType, decimal.shortValue().toString)
}
else {
throw new CodeGenException("Decimal can not be converted to short.")
}
case INTEGER =>
val decimal = BigDecimal(value.asInstanceOf[JBigDecimal])
if (decimal.isValidInt) {
generateNonNullLiteral(resultType, decimal.intValue().toString)
}
else {
throw new CodeGenException("Decimal can not be converted to integer.")
}
case BIGINT =>
val decimal = BigDecimal(value.asInstanceOf[JBigDecimal])
if (decimal.isValidLong) {
generateNonNullLiteral(resultType, decimal.longValue().toString + "L")
}
else {
throw new CodeGenException("Decimal can not be converted to long.")
}
case FLOAT =>
val floatValue = value.asInstanceOf[JBigDecimal].floatValue()
floatValue match {
case Float.NaN => generateNonNullLiteral(resultType, "java.lang.Float.NaN")
case Float.NegativeInfinity =>
generateNonNullLiteral(resultType, "java.lang.Float.NEGATIVE_INFINITY")
case Float.PositiveInfinity =>
generateNonNullLiteral(resultType, "java.lang.Float.POSITIVE_INFINITY")
case _ => generateNonNullLiteral(resultType, floatValue.toString + "f")
}
case DOUBLE =>
val doubleValue = value.asInstanceOf[JBigDecimal].doubleValue()
doubleValue match {
case Double.NaN => generateNonNullLiteral(resultType, "java.lang.Double.NaN")
case Double.NegativeInfinity =>
generateNonNullLiteral(resultType, "java.lang.Double.NEGATIVE_INFINITY")
case Double.PositiveInfinity =>
generateNonNullLiteral(resultType, "java.lang.Double.POSITIVE_INFINITY")
case _ => generateNonNullLiteral(resultType, doubleValue.toString + "d")
}
case DECIMAL =>
val decimalField = addReusableDecimal(value.asInstanceOf[JBigDecimal])
generateNonNullLiteral(resultType, decimalField)
case VARCHAR | CHAR =>
generateNonNullLiteral(resultType, "\"" + value.toString + "\"")
case SYMBOL =>
generateSymbol(value.asInstanceOf[Enum[_]])
case DATE =>
generateNonNullLiteral(resultType, value.toString)
case TIME =>
generateNonNullLiteral(resultType, value.toString)
case TIMESTAMP =>
generateNonNullLiteral(resultType, value.toString + "L")
case typeName if YEAR_INTERVAL_TYPES.contains(typeName) =>
val decimal = BigDecimal(value.asInstanceOf[JBigDecimal])
if (decimal.isValidInt) {
generateNonNullLiteral(resultType, decimal.intValue().toString)
} else {
throw new CodeGenException("Decimal can not be converted to interval of months.")
}
case typeName if DAY_INTERVAL_TYPES.contains(typeName) =>
val decimal = BigDecimal(value.asInstanceOf[JBigDecimal])
if (decimal.isValidLong) {
generateNonNullLiteral(resultType, decimal.longValue().toString + "L")
} else {
throw new CodeGenException("Decimal can not be converted to interval of milliseconds.")
}
case t@_ =>
throw new CodeGenException(s"Type not supported: $t")
}
}
override def visitCorrelVariable(correlVariable: RexCorrelVariable): GeneratedExpression = {
GeneratedExpression(input1Term, NEVER_NULL, NO_CODE, input1)
}
override def visitLocalRef(localRef: RexLocalRef): GeneratedExpression =
throw new CodeGenException("Local variables are not supported yet.")
override def visitRangeRef(rangeRef: RexRangeRef): GeneratedExpression =
throw new CodeGenException("Range references are not supported yet.")
override def visitDynamicParam(dynamicParam: RexDynamicParam): GeneratedExpression =
throw new CodeGenException("Dynamic parameter references are not supported yet.")
override def visitCall(call: RexCall): GeneratedExpression = {
val operands = call.getOperands.map(_.accept(this))
val resultType = FlinkTypeFactory.toTypeInfo(call.getType)
call.getOperator match {
// arithmetic
case PLUS if isNumeric(resultType) =>
val left = operands.head
val right = operands(1)
requireNumeric(left)
requireNumeric(right)
generateArithmeticOperator("+", nullCheck, resultType, left, right)
case PLUS | DATETIME_PLUS if isTemporal(resultType) =>
val left = operands.head
val right = operands(1)
requireTemporal(left)
requireTemporal(right)
generateTemporalPlusMinus(plus = true, nullCheck, left, right)
case MINUS if isNumeric(resultType) =>
val left = operands.head
val right = operands(1)
requireNumeric(left)
requireNumeric(right)
generateArithmeticOperator("-", nullCheck, resultType, left, right)
case MINUS | MINUS_DATE if isTemporal(resultType) =>
val left = operands.head
val right = operands(1)
requireTemporal(left)
requireTemporal(right)
generateTemporalPlusMinus(plus = false, nullCheck, left, right)
case MULTIPLY if isNumeric(resultType) =>
val left = operands.head
val right = operands(1)
requireNumeric(left)
requireNumeric(right)
generateArithmeticOperator("*", nullCheck, resultType, left, right)
case DIVIDE | DIVIDE_INTEGER if isNumeric(resultType) =>
val left = operands.head
val right = operands(1)
requireNumeric(left)
requireNumeric(right)
generateArithmeticOperator("/", nullCheck, resultType, left, right)
case MOD if isNumeric(resultType) =>
val left = operands.head
val right = operands(1)
requireNumeric(left)
requireNumeric(right)
generateArithmeticOperator("%", nullCheck, resultType, left, right)
case UNARY_MINUS if isNumeric(resultType) =>
val operand = operands.head
requireNumeric(operand)
generateUnaryArithmeticOperator("-", nullCheck, resultType, operand)
case UNARY_MINUS if isTimeInterval(resultType) =>
val operand = operands.head
requireTimeInterval(operand)
generateUnaryIntervalPlusMinus(plus = false, nullCheck, operand)
case UNARY_PLUS if isNumeric(resultType) =>
val operand = operands.head
requireNumeric(operand)
generateUnaryArithmeticOperator("+", nullCheck, resultType, operand)
case UNARY_PLUS if isTimeInterval(resultType) =>
val operand = operands.head
requireTimeInterval(operand)
generateUnaryIntervalPlusMinus(plus = true, nullCheck, operand)
case IN =>
val left = operands.head
val right = operands.tail
val addReusableCodeCallback = (declaration: String, initialization: String) => {
reusableMemberStatements.add(declaration)
reusableInitStatements.add(initialization)
}
generateIn(nullCheck, left, right, addReusableCodeCallback)
// comparison
case EQUALS =>
val left = operands.head
val right = operands(1)
generateEquals(nullCheck, left, right)
case NOT_EQUALS =>
val left = operands.head
val right = operands(1)
generateNotEquals(nullCheck, left, right)
case GREATER_THAN =>
val left = operands.head
val right = operands(1)
requireComparable(left)
requireComparable(right)
generateComparison(">", nullCheck, left, right)
case GREATER_THAN_OR_EQUAL =>
val left = operands.head
val right = operands(1)
requireComparable(left)
requireComparable(right)
generateComparison(">=", nullCheck, left, right)
case LESS_THAN =>
val left = operands.head
val right = operands(1)
requireComparable(left)
requireComparable(right)
generateComparison("<", nullCheck, left, right)
case LESS_THAN_OR_EQUAL =>
val left = operands.head
val right = operands(1)
requireComparable(left)
requireComparable(right)
generateComparison("<=", nullCheck, left, right)
case IS_NULL =>
val operand = operands.head
generateIsNull(nullCheck, operand)
case IS_NOT_NULL =>
val operand = operands.head
generateIsNotNull(nullCheck, operand)
// logic
case AND =>
operands.reduceLeft { (left: GeneratedExpression, right: GeneratedExpression) =>
requireBoolean(left)
requireBoolean(right)
generateAnd(nullCheck, left, right)
}
case OR =>
operands.reduceLeft { (left: GeneratedExpression, right: GeneratedExpression) =>
requireBoolean(left)
requireBoolean(right)
generateOr(nullCheck, left, right)
}
case NOT =>
val operand = operands.head
requireBoolean(operand)
generateNot(nullCheck, operand)
case CASE =>
generateIfElse(nullCheck, operands, resultType)
case IS_TRUE =>
val operand = operands.head
requireBoolean(operand)
generateIsTrue(operand)
case IS_NOT_TRUE =>
val operand = operands.head
requireBoolean(operand)
generateIsNotTrue(operand)
case IS_FALSE =>
val operand = operands.head
requireBoolean(operand)
generateIsFalse(operand)
case IS_NOT_FALSE =>
val operand = operands.head
requireBoolean(operand)
generateIsNotFalse(operand)
// casting
case CAST | REINTERPRET =>
val operand = operands.head
generateCast(nullCheck, operand, resultType)
// as / renaming
case AS =>
operands.head
// string arithmetic
case CONCAT =>
val left = operands.head
val right = operands(1)
requireString(left)
generateArithmeticOperator("+", nullCheck, resultType, left, right)
// arrays
case ARRAY_VALUE_CONSTRUCTOR =>
generateArray(this, resultType, operands)
case ITEM =>
val array = operands.head
val index = operands(1)
requireArray(array)
requireInteger(index)
generateArrayElementAt(this, array, index)
case CARDINALITY =>