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
package edu.caltech.nanodb.expressions;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.temporal.TemporalAmount;
import edu.caltech.nanodb.relations.ColumnInfo;
import edu.caltech.nanodb.relations.ColumnType;
import edu.caltech.nanodb.relations.SQLDataType;
import edu.caltech.nanodb.relations.Schema;
import edu.caltech.nanodb.relations.SchemaNameException;
import edu.caltech.nanodb.util.Pair;
/**
* This class implements simple binary arithmetic operations. The supported
* operations are:
* <ul>
* <li>addition, <tt>+</tt></li>
* <li>subtraction, <tt>-</tt></li>
* <li>multiplication, <tt>*</tt></li>
* <li>division, <tt>/</tt></li>
* <li>remainder, <tt>%</tt></li>
* <li>exponentiation, <tt>^</tt></li>
* </ul>
*/
public class ArithmeticOperator extends Expression {
/**
* This enum specifies the arithmetic operations that this class can provide.
* Each arithmetic operation also holds its string representation, which is
* used when converting an arithmetic expression into a string for display.
*/
public enum Type {
ADD("+"),
SUBTRACT("-"),
MULTIPLY("*"),
DIVIDE("/"),
REMAINDER("%"),
POWER("^");
/** The string representation for each operator. Used for printing. */
private final String stringRep;
/**
* Construct a Type enum with the specified string representation.
*
* @param rep the string representation of the arithmetic operation
*/
Type(String rep) {
stringRep = rep;
}
/**
* Accessor for the operator type's string representation.
*
* @return the string representation of the arithmetic operation
*/
public String stringRep() {
return stringRep;
}
/**
* Given a string representation of an arithmetic operator, this
* method returns the corresponding {@code Type} value.
*
* @param stringRep the string representation of the arithmetic
* operator
*
* @return the operator's corresponding type, or {@code null} if the
* type cannot be found
*/
public static Type find(String stringRep) {
for (Type t : values()) {
if (t.stringRep.equals(stringRep))
return t;
}
// Couldn't find the corresponding operator type.
return null;
}
}
/** The kind of comparison, such as "subtract" or "multiply." */
private Type type;
/** The left expression in the comparison. */
private Expression leftExpr;
/** The right expression in the comparison. */
private Expression rightExpr;
public ArithmeticOperator(Type type, Expression lhs, Expression rhs) {
if (type == null || lhs == null || rhs == null)
throw new NullPointerException();
leftExpr = lhs;
rightExpr = rhs;
this.type = type;
}
@Override
public ColumnInfo getColumnInfo(Schema schema) throws SchemaNameException {
ColumnInfo ltColInfo = leftExpr.getColumnInfo(schema);
ColumnInfo rtColInfo = rightExpr.getColumnInfo(schema);
SQLDataType resultSQLType = getSQLResultType(
ltColInfo.getType().getBaseType(), rtColInfo.getType().getBaseType());
ColumnType colType = new ColumnType(resultSQLType);
return new ColumnInfo(toString(), colType);
}
private SQLDataType getSQLResultType(SQLDataType lType, SQLDataType rType) {
// This array specifies the type-conversion sequence. If at least one of
// the arguments is type typeOrder[i], then both arguments are coerced to
// that type. (This is not entirely accurate at the moment, but is
// sufficient for our needs.)
SQLDataType[] typeOrder = {
SQLDataType.NUMERIC, SQLDataType.DOUBLE, SQLDataType.FLOAT,
SQLDataType.BIGINT, SQLDataType.INTEGER, SQLDataType.SMALLINT,
SQLDataType.TINYINT
};
for (SQLDataType aTypeOrder : typeOrder) {
if (lType == aTypeOrder || rType == aTypeOrder)
return aTypeOrder;
}
// Just guess INTEGER. Works for C...
return SQLDataType.INTEGER;
}
public Object evaluate(Environment env) throws ExpressionException {
// Evaluate the left and right subexpressions.
Object lhsValue = leftExpr.evaluate(env);
Object rhsValue = rightExpr.evaluate(env);
// If either the LHS value or RHS value is NULL (represented by Java
// null value) then the entire expression evaluates to NULL.
if (lhsValue == null || rhsValue == null)
return null;
return evalObjects(type, lhsValue, rhsValue);
}
/**
* This static helper method can be used to compute basic arithmetic
* operations between two arguments. It is of course used to evaluate
* <tt>ArithmeticOperator</tt> objects, but it can also be used to evaluate
* specific arithmetic operations within other components of the database
* system.
*
* @param type the arithmetic operation to perform
* @param aObj the first operand value for the operation
* @param bObj the second operand value for the operation
*
* @return the result of the arithmetic operation
*
* @throws ExpressionException if the operand type is unrecognized
*/
public static Object evalObjects(Type type, Object aObj, Object bObj) {
// Coerce the values to both have the same numeric type.
Pair coerced = TypeConverter.coerceArithmetic(aObj, bObj);
Object result;
if (coerced.value1 instanceof BigInteger) {
result = evalBigIntegers(type, (BigInteger) coerced.value1,
(BigInteger) coerced.value2);
}
else if (coerced.value1 instanceof BigDecimal) {
result = evalBigDecimals(type, (BigDecimal) coerced.value1,
(BigDecimal) coerced.value2);
}
else if (coerced.value1 instanceof Double) {
result = evalDoubles(type, (Double) coerced.value1,
(Double) coerced.value2);
}
else if (coerced.value1 instanceof Float) {
result = evalFloats(type, (Float) coerced.value1,
(Float) coerced.value2);
}
else if (coerced.value1 instanceof Long) {
result = evalLongs(type, (Long) coerced.value1,
(Long) coerced.value2);
}
else if (coerced.value1 instanceof Integer) {
result = evalIntegers(type, (Integer) coerced.value1,
(Integer) coerced.value2);
}
else if (coerced.value1 instanceof LocalDate &&
coerced.value2 instanceof LocalDate) {
result = evalDates(type, (LocalDate) coerced.value1,
(LocalDate) coerced.value2);
}
else if (coerced.value1 instanceof LocalTime &&
coerced.value2 instanceof LocalTime) {
result = evalTimes(type, (LocalTime) coerced.value1,
(LocalTime) coerced.value2);
}
else if (coerced.value1 instanceof LocalDateTime &&
coerced.value2 instanceof LocalDateTime) {
result = evalDateTimes(type, (LocalDateTime) coerced.value1,
(LocalDateTime) coerced.value2);
}
else if (coerced.value1 instanceof LocalDate &&
coerced.value2 instanceof TemporalAmount) {
result = evalDateInterval(type, (LocalDate) coerced.value1,
(TemporalAmount) coerced.value2);
}
else if (coerced.value1 instanceof LocalTime &&
coerced.value2 instanceof TemporalAmount) {
result = evalTimeInterval(type, (LocalTime) coerced.value1,
(TemporalAmount) coerced.value2);
}
else if (coerced.value1 instanceof LocalDateTime &&
coerced.value2 instanceof TemporalAmount) {
result = evalDateTimeInterval(type, (LocalDateTime) coerced.value1,
(TemporalAmount) coerced.value2);
}
else if (coerced.value1 instanceof TemporalAmount &&
coerced.value2 instanceof LocalDate) {
result = evalIntervalDate(type, (TemporalAmount) coerced.value1,
(LocalDate) coerced.value2);
}
else if (coerced.value1 instanceof TemporalAmount &&
coerced.value2 instanceof LocalTime) {
result = evalIntervalTime(type, (TemporalAmount) coerced.value1,
(LocalTime) coerced.value2);
}
else if (coerced.value1 instanceof TemporalAmount &&
coerced.value2 instanceof LocalDateTime) {
result = evalIntervalDateTime(type, (TemporalAmount) coerced.value1,
(LocalDateTime) coerced.value2);
}
else {
throw new IllegalArgumentException("Cannot perform arithmetic on " +
coerced.value1.getClass() + " and " + coerced.value2.getClass());
}
return result;
}
private static BigDecimal evalBigDecimals(Type type, BigDecimal a, BigDecimal b) {
BigDecimal result;
switch (type) {
case ADD:
result = a.add(b);
break;
case SUBTRACT:
result = a.subtract(b);
break;
case MULTIPLY:
result = a.multiply(b);
break;
case DIVIDE:
if (b.equals(BigDecimal.ZERO))
throw new DivideByZeroException();
int scale = 10; // TODO: Scale?
result = a.divide(b, scale, RoundingMode.HALF_UP);
break;
case REMAINDER:
if (b.equals(BigDecimal.ZERO))
throw new DivideByZeroException();
result = a.remainder(b);
break;
case POWER:
throw new ExpressionException("POWER is unsupported for BigDecimal");
default:
throw new ExpressionException("Unrecognized arithmetic type " + type);
}
return result;
}
private static BigInteger evalBigIntegers(Type type, BigInteger a, BigInteger b) {
BigInteger result;
switch (type) {
case ADD:
result = a.add(b);
break;
case SUBTRACT:
result = a.subtract(b);
break;
case MULTIPLY:
result = a.multiply(b);
break;
case DIVIDE:
if (b.equals(BigInteger.ZERO))
throw new DivideByZeroException();
result = a.divide(b);
break;
case REMAINDER:
if (b.equals(BigInteger.ZERO))
throw new DivideByZeroException();
result = a.remainder(b);
break;
case POWER:
throw new ExpressionException("POWER is unsupported for BigInteger");
default:
throw new ExpressionException("Unrecognized arithmetic type " + type);
}
return result;
}
/**
* This helper implements the arithmetic operations for <tt>Double</tt>
* values. Note that division of two <tt>Double</tt>s will produce a
* <tt>Double</tt>.
*
* @param type the arithmetic operation to perform
* @param a the first operand value for the operation
* @param b the second operand value for the operation
*
* @return the result of the arithmetic operation
*
* @throws ExpressionException if the operand type is unrecognized
*/
private static Double evalDoubles(Type type, Double a, Double b) {
double result;
switch (type) {
case ADD:
result = a + b;
break;
case SUBTRACT:
result = a - b;
break;
case MULTIPLY:
result = a * b;
break;
case DIVIDE:
if (b == 0)
throw new DivideByZeroException();
result = a / b;
break;
case REMAINDER:
if (b == 0)
throw new DivideByZeroException();
result = a % b;
break;
case POWER:
if (a == 0 && b == 0)
throw new ExpressionException("0**0 is undefined");
result = Math.pow(a, b);
break;
default:
throw new ExpressionException("Unrecognized arithmetic type " + type);
}
return result;
}
/**
* This helper implements the arithmetic operations for <tt>Float</tt>
* values. Note that division of two <tt>Float</tt>s will produce a
* <tt>Float</tt>.
*
* @param type the arithmetic operation to perform
* @param a the first operand value for the operation
* @param b the second operand value for the operation
*
* @return the result of the arithmetic operation
*
* @throws ExpressionException if the operand type is unrecognized
*/
private static Float evalFloats(Type type, Float a, Float b) {
float result;
switch (type) {
case ADD:
result = a + b;
break;
case SUBTRACT:
result = a - b;
break;
case MULTIPLY:
result = a * b;
break;
case DIVIDE:
if (b == 0)
throw new DivideByZeroException();
result = a / b;
break;
case REMAINDER:
if (b == 0)
throw new DivideByZeroException();
result = a % b;
break;
case POWER:
if (a == 0 && b == 0)
throw new ExpressionException("0**0 is undefined");
result = (float) Math.pow(a, b);
break;
default:
throw new ExpressionException("Unrecognized arithmetic type " + type);
}
return result; // Rely on boxing
}
/**
* This helper implements the arithmetic operations for <tt>Long</tt>
* values. Note that division of two <tt>Long</tt>s will produce a
* <tt>Double</tt>, not a <tt>Long</tt>.
*
* @param type the arithmetic operation to perform
* @param a the first operand value for the operation
* @param b the second operand value for the operation
*
* @return the result of the arithmetic operation
*
* @throws ExpressionException if the operand type is unrecognized
*/
private static Object evalLongs(Type type, Long a, Long b) {
long result;
switch (type) {
case ADD:
result = a + b;
break;
case SUBTRACT:
result = a - b;
break;
case MULTIPLY:
result = a * b;
break;
case DIVIDE:
if (b == 0)
throw new DivideByZeroException();
result = a / b;
break;
case REMAINDER:
if (b == 0)
throw new DivideByZeroException();
result = a % b;
break;
case POWER:
if (a == 0 && b == 0)
throw new ExpressionException("0**0 is undefined");
result = (long) Math.pow(a, b);
break;
default:
throw new ExpressionException("Unrecognized arithmetic type " + type);
}
return result; // Rely on boxing
}
/**
* This helper implements the arithmetic operations for <tt>Integer</tt>
* values. Note that division of two <tt>Integer</tt>s will produce a
* <tt>Double</tt>, not an <tt>Integer</tt>.
*
* @param type the arithmetic operation to perform
* @param a the first operand value for the operation
* @param b the second operand value for the operation
*
* @return the result of the arithmetic operation
*
* @throws ExpressionException if the operand type is unrecognized
*/
private static Object evalIntegers(Type type, Integer a, Integer b) {
int result;
switch (type) {
case ADD:
result = a + b;
break;
case SUBTRACT:
result = a - b;
break;
case MULTIPLY:
result = a * b;
break;
case DIVIDE:
if (b == 0)
throw new DivideByZeroException();
result = a / b;
break;
case REMAINDER:
if (b == 0)
throw new DivideByZeroException();
result = a % b;
break;
case POWER:
if (a == 0 && b == 0)
throw new ExpressionException("0**0 is undefined");
result = (int) Math.pow(a, b);
break;
default:
throw new ExpressionException("Unrecognized arithmetic type " + type);
}
return result; // Rely on boxing
}
private static Object evalDateTimes(Type type, LocalDateTime a, LocalDateTime b) {
if (a == null || b == null)
return null;
if (type == Type.SUBTRACT) {
return Duration.between(b, a);
}
else {
throw new IllegalArgumentException(
"Cannot perform requested operation " + type +
" on LocalDateTime objects");
}
}
private static Object evalDates(Type type, LocalDate a, LocalDate b) {
if (a == null || b == null)
return null;
if (type == Type.SUBTRACT) {
return Period.between(b, a);
}
else {
throw new IllegalArgumentException(
"Cannot perform requested operation " + type +
" on LocalDate objects");
}
}
private static Object evalTimes(Type type, LocalTime a, LocalTime b) {
if (a == null || b == null)
return null;
if (type == Type.SUBTRACT) {
return Duration.between(b, a);
}
else {
throw new IllegalArgumentException(
"Cannot perform requested operation " + type +
" on LocalTime objects");
}
}
private static Object evalDateInterval(Type type, LocalDate a, TemporalAmount b) {
if (a == null || b == null)
return null;
if (type == Type.ADD) {
return a.plus(b);
}
else if (type == Type.SUBTRACT) {
return a.minus(b);
}
else {
throw new IllegalArgumentException(
"Cannot perform requested operation " + type +
" on LocalDate and TemporalAmount objects");
}
}
private static Object evalTimeInterval(Type type, LocalTime a,
TemporalAmount b) {
if (a == null || b == null)
return null;
if (type == Type.ADD) {
return a.plus(b);
}
else if (type == Type.SUBTRACT) {
return a.minus(b);
}
else {
throw new IllegalArgumentException(
"Cannot perform requested operation " + type +
" on LocalTime and TemporalAmount objects");
}
}
private static Object evalDateTimeInterval(Type type, LocalDateTime a,
TemporalAmount b) {
if (a == null || b == null)
return null;
if (type == Type.ADD) {
return a.plus(b);
}
else if (type == Type.SUBTRACT) {
return a.minus(b);
}
else {
throw new IllegalArgumentException(
"Cannot perform requested operation " + type +
" on LocalDateTime and TemporalAmount objects");
}
}
private static Object evalIntervalDate(Type type, TemporalAmount a,
LocalDate b) {
if (a == null || b == null)
return null;
if (type == Type.ADD) {
return b.plus(a);
}
else {
throw new IllegalArgumentException(
"Cannot perform requested operation " + type +
" on TemporalAmount and LocalDate objects");
}
}
private static Object evalIntervalTime(Type type, TemporalAmount a,
LocalTime b) {
if (a == null || b == null)
return null;
if (type == Type.ADD) {
return b.plus(a);
}
else {
throw new IllegalArgumentException(
"Cannot perform requested operation " + type +
" on TemporalAmount and LocalTime objects");
}
}
private static Object evalIntervalDateTime(Type type, TemporalAmount a,
LocalDateTime b) {
if (a == null || b == null)
return null;
if (type == Type.ADD) {
return b.plus(a);
}
else {
throw new IllegalArgumentException(
"Cannot perform requested operation " + type +
" on TemporalAmount and LocalDateTime objects");
}
}
@Override
public Expression traverse(ExpressionProcessor p) {
p.enter(this);
leftExpr = leftExpr.traverse(p);
rightExpr = rightExpr.traverse(p);
return p.leave(this);
}
/**
* Returns a string representation of this arithmetic expression and its
* subexpressions, including parentheses where necessary to specify
* precedence.
*/
@Override
public String toString() {
// Convert all of the components into string representations.
String leftStr = leftExpr.toString();
String rightStr = rightExpr.toString();
String opStr = " " + type.stringRep() + " ";
// Figure out if I need parentheses around the subexpressions.
if (type == Type.MULTIPLY || type == Type.DIVIDE || type == Type.REMAINDER) {
if (leftExpr instanceof ArithmeticOperator) {
ArithmeticOperator leftOp = (ArithmeticOperator) leftExpr;
if (leftOp.type == Type.ADD || leftOp.type == Type.SUBTRACT)
leftStr = "(" + leftStr + ")";
}
if (rightExpr instanceof ArithmeticOperator) {
ArithmeticOperator rightOp = (ArithmeticOperator) rightExpr;
if (rightOp.type == Type.ADD || rightOp.type == Type.SUBTRACT)
rightStr = "(" + rightStr + ")";
}
}
return leftStr + opStr + rightStr;
}
/**
* Simplifies an arithmetic expression, computing as much of the expression
* as possible.
*/
@Override
public Expression simplify() {
leftExpr = leftExpr.simplify();
rightExpr = rightExpr.simplify();
if (!leftExpr.hasSymbols())
leftExpr = new LiteralValue(leftExpr.evaluate());
if (!rightExpr.hasSymbols())
rightExpr = new LiteralValue(rightExpr.evaluate());
if (!hasSymbols())
return new LiteralValue(evaluate());
return this;
}
/**
* Checks if the argument is an expression with the same structure, but not
* necesarily the same references.
*
* @param obj the object to which we are comparing
*/
@Override
public boolean equals(Object obj) {
if (obj instanceof ArithmeticOperator) {
ArithmeticOperator other = (ArithmeticOperator) obj;
return (type.equals(other.type) &&
leftExpr.equals(other.leftExpr) &&
rightExpr.equals(other.rightExpr));
}
return false;
}
/**
* Computes the hashcode of an Expression. This method is used to see if
* two expressions CAN be equal.
*/
@Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + type.hashCode();
hash = 31 * hash + leftExpr.hashCode();
hash = 31 * hash + rightExpr.hashCode();
return hash;
}
/** Creates a copy of expression. */
@Override
protected Object clone() throws CloneNotSupportedException {
ArithmeticOperator expr = (ArithmeticOperator)super.clone();
// Type is immutable, copy it.
expr.type = this.type;
// Clone the subexpressions
expr.leftExpr = (Expression) leftExpr.clone();
expr.rightExpr = (Expression) rightExpr.clone();
return expr;
}
}