aboutsummaryrefslogtreecommitdiff
path: root/exec/java-exec/src/main/codegen/templates/Decimal/DecimalFunctions.java
blob: 059080e15fbc44c08cb8f52bf6b509f5c8777d58 (plain)
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
/*
 * 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.
 */
import org.apache.drill.exec.expr.annotations.Workspace;

<@pp.dropOutputFile />

<#-- TODO:  Refactor comparison code from here into ComparisonFunctions (to
     eliminate duplicate template code and so that ComparisonFunctions actually
     as all comparison functions. -->

<#macro compareNullsSubblock leftType rightType output breakTarget nullCompare nullComparesHigh>
  <#if nullCompare>
    <#if nullComparesHigh>
      <#assign leftNullResult = 1> <#-- if only L is null and nulls are high, then "L > R" (1) -->
      <#assign rightNullResult = -1>
    <#else>
      <#assign leftNullResult = -1> <#-- if only L is null and nulls are low, then "L < R" (-1) -->
      <#assign rightNullResult = 1>
    </#if>

    <#if leftType?starts_with("Nullable")>
      <#if rightType?starts_with("Nullable")>
        <#-- Both are nullable. -->
        if ( left.isSet == 0 ) {
          if ( right.isSet == 0 ) {
            <#-- Both are null--result is "L = R". -->
            ${output} = 0;
            break ${breakTarget};
          } else {
            <#-- Only left is null--result is "L < R" or "L > R" per null ordering. -->
            ${output} = ${leftNullResult};
            break ${breakTarget};
          }
        } else if ( right.isSet == 0 ) {
          <#-- Only right is null--result is "L > R" or "L < R" per null ordering. -->
          ${output} = ${rightNullResult};
          break ${breakTarget};
        }
      <#else>
        <#-- Left is nullable but right is not. -->
        if ( left.isSet == 0 ) {
          <#-- Only left is null--result is "L < R" or "L > R" per null ordering. -->
          ${output} = ${leftNullResult};
          break ${breakTarget};
        }
      </#if>
    <#elseif rightType?starts_with("Nullable")>
      <#-- Left is not nullable but right is. -->
      if ( right.isSet == 0 ) {
        <#-- Only right is null--result is "L > R" or "L < R" per null ordering. -->
        ${output} = ${rightNullResult};
        break ${breakTarget};
      }
    </#if>
  </#if>

</#macro>


<#macro compareBlock leftType rightType absCompare output nullCompare nullComparesHigh>
         outside:
          {
            <@compareNullsSubblock leftType=leftType rightType=rightType output=output breakTarget="outside" nullCompare=nullCompare nullComparesHigh=nullComparesHigh />

            ${output} = org.apache.drill.exec.util.DecimalUtility.compareSparseBytes(left.buffer, left.start, left.getSign(left.start, left.buffer),
                            left.scale, left.precision, right.buffer,
                            right.start, right.getSign(right.start, right.buffer), right.precision,
                            right.scale, left.WIDTH, left.nDecimalDigits, ${absCompare});

          } // outside
</#macro>

<#macro varCompareBlock leftType rightType absCompare output nullCompare nullComparesHigh>
      outside:
      {
        <@compareNullsSubblock leftType = leftType rightType=rightType output = output breakTarget = "outside" nullCompare = nullCompare nullComparesHigh=nullComparesHigh />

        ${output} = org.apache.drill.exec.util.DecimalUtility.compareVarLenBytes(left.buffer, left.start, left.end, left.scale, right.buffer, right.start, right.end, right.scale, ${absCompare});
      } // outside
</#macro>

<#-- For each DECIMAL... type (in DecimalTypes.tdd) ... -->
<#list comparisonTypesDecimal.decimalTypes as type>

<#if type.name.endsWith("VarDecimal")>

<@pp.changeOutputFile name="/org/apache/drill/exec/expr/fn/impl/${type.name}Functions.java" />

<#include "/@includes/license.ftl" />

package org.apache.drill.exec.expr.fn.impl;

<#include "/@includes/vv_imports.ftl" />

import org.apache.drill.exec.expr.DrillSimpleFunc;
import org.apache.drill.exec.expr.annotations.FunctionTemplate;
import org.apache.drill.exec.expr.annotations.FunctionTemplate.NullHandling;
import org.apache.drill.exec.expr.annotations.Output;
import org.apache.drill.exec.expr.annotations.Param;
import org.apache.drill.exec.expr.annotations.Workspace;
import org.apache.drill.exec.expr.fn.FunctionGenerationHelper;
import org.apache.drill.exec.expr.holders.*;
import org.apache.drill.exec.record.RecordBatch;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.DrillBuf;

import java.nio.ByteBuffer;

@SuppressWarnings("unused")
public class ${type.name}Functions {

<#list ["Subtract", "Add", "Multiply", "Divide", "Mod"] as functionName>
  @FunctionTemplate(name = "${functionName?lower_case}",
                    scope = FunctionTemplate.FunctionScope.SIMPLE,
                  <#if functionName == "Subtract" || functionName == "Add">
                    returnType = FunctionTemplate.ReturnType.DECIMAL_ADD_SCALE,
                  <#elseif functionName == "Multiply">
                    returnType = FunctionTemplate.ReturnType.DECIMAL_SUM_SCALE,
                  <#elseif functionName == "Divide">
                    returnType = FunctionTemplate.ReturnType.DECIMAL_DIV_SCALE,
                  <#elseif functionName == "Mod">
                    returnType = FunctionTemplate.ReturnType.DECIMAL_MOD_SCALE,
                  </#if>
                    nulls = NullHandling.NULL_IF_NULL,
                    checkPrecisionRange = true)
  public static class ${type.name}${functionName}Function implements DrillSimpleFunc {
    @Param ${type.name}Holder left;
    @Param ${type.name}Holder right;
    @Inject DrillBuf buffer;
    @Output ${type.name}Holder result;

    public void setup() {
    }

    public void eval() {
      result.start = 0;

      java.math.BigDecimal leftInput =
          org.apache.drill.exec.util.DecimalUtility
              .getBigDecimalFromDrillBuf(left.buffer, left.start, left.end - left.start, left.scale);
      java.math.BigDecimal rightInput =
          org.apache.drill.exec.util.DecimalUtility
              .getBigDecimalFromDrillBuf(right.buffer, right.start, right.end - right.start, right.scale);
      org.apache.drill.exec.planner.types.decimal.DrillBaseComputeScalePrecision typeInference =
      <#if functionName == "Subtract" || functionName == "Add">
          new org.apache.drill.exec.planner.types.decimal.DecimalScalePrecisionAddFunction(
      <#elseif functionName == "Multiply">
          new org.apache.drill.exec.planner.types.decimal.DecimalScalePrecisionMulFunction(
      <#elseif functionName == "Divide">
          new org.apache.drill.exec.planner.types.decimal.DecimalScalePrecisionDivideFunction(
      <#elseif functionName == "Mod">
          new org.apache.drill.exec.planner.types.decimal.DecimalScalePrecisionModFunction(
      </#if>
              left.precision, left.scale,
              right.precision, right.scale);

      result.scale = typeInference.getOutputScale();
      result.precision = typeInference.getOutputPrecision();

      java.math.BigDecimal opResult =
      <#if functionName == "Subtract" || functionName == "Add"
          || functionName == "Multiply"|| functionName == "Divide">
          leftInput.${functionName?lower_case}(rightInput,
      <#elseif functionName == "Mod">
        leftInput.remainder(rightInput,
      </#if>
              new java.math.MathContext(result.precision, java.math.RoundingMode.HALF_UP))
            .setScale(result.scale, java.math.BigDecimal.ROUND_HALF_UP);

      byte[] bytes = opResult.unscaledValue().toByteArray();
      int len = bytes.length;
      result.buffer = buffer.reallocIfNeeded(len);
      result.buffer.setBytes(0, bytes);
      result.end = len;
    }
  }

</#list>

<#list ["Abs", "Ceil", "Floor", "Trunc", "Round"] as functionName>
  <#if functionName == "Ceil">
  @FunctionTemplate(names = {"ceil", "ceiling"},
  <#elseif functionName == "Trunc">
  @FunctionTemplate(names = {"trunc", "truncate"},
  <#else>
  @FunctionTemplate(name = "${functionName?lower_case}",
  </#if>
                    scope = FunctionTemplate.FunctionScope.SIMPLE,
                  <#if functionName == "Abs">
                    returnType = FunctionTemplate.ReturnType.DECIMAL_MAX_SCALE,
                  <#elseif functionName == "Ceil" || functionName == "Floor"
                      || functionName == "Trunc" || functionName == "Round">
                    returnType = FunctionTemplate.ReturnType.DECIMAL_ZERO_SCALE,
                  </#if>
                    nulls = NullHandling.NULL_IF_NULL)
  public static class ${type.name}${functionName}Function implements DrillSimpleFunc {
    @Param  ${type.name}Holder in;
    @Output ${type.name}Holder result;
    @Inject DrillBuf buffer;

    public void setup() {
    }

    public void eval() {
      result.start = 0;
      result.precision = in.precision;

      java.math.BigDecimal opResult =
          org.apache.drill.exec.util.DecimalUtility
              .getBigDecimalFromDrillBuf(in.buffer, in.start, in.end - in.start, in.scale)
          <#if functionName == "Abs">
                  .abs();
      result.scale = in.scale;
          <#elseif functionName == "Ceil">
                  .setScale(0, java.math.BigDecimal.ROUND_CEILING);
          <#elseif functionName == "Floor">
                  .setScale(0, java.math.BigDecimal.ROUND_FLOOR);
          <#elseif functionName == "Trunc">
                  .setScale(0, java.math.BigDecimal.ROUND_DOWN);
          <#elseif functionName == "Round">
                  .setScale(0, java.math.BigDecimal.ROUND_HALF_UP);
          </#if>

      byte[] bytes = opResult.unscaledValue().toByteArray();
      int len = bytes.length;
      result.buffer = buffer.reallocIfNeeded(len);
      result.buffer.setBytes(0, bytes);
      result.end = len;
    }
  }

</#list>
  @FunctionTemplate(name = "sign",
                    scope = FunctionTemplate.FunctionScope.SIMPLE,
                    nulls = NullHandling.NULL_IF_NULL)
  public static class ${type.name}SignFunction implements DrillSimpleFunc {
    @Param ${type.name}Holder in;
    @Output IntHolder out;

    public void setup() {}

    public void eval() {
      // TODO: optimize to get only bytes that corresponds to sign.
      // Should be taken into account case when leading zero bytes are stored in buff.
      java.math.BigDecimal bd =
          org.apache.drill.exec.util.DecimalUtility
              .getBigDecimalFromDrillBuf(in.buffer, in.start, in.end - in.start, in.scale);
      out.value = bd.signum();
    }
  }

  @FunctionTemplate(names = {"trunc", "truncate"},
                    scope = FunctionTemplate.FunctionScope.SIMPLE,
                    returnType = FunctionTemplate.ReturnType.DECIMAL_SET_SCALE,
                    nulls = NullHandling.NULL_IF_NULL)
  public static class ${type.name}TruncateScaleFunction implements DrillSimpleFunc {
    @Param  ${type.name}Holder left;
    @Param  IntHolder right;
    @Output ${type.name}Holder result;
    @Inject DrillBuf buffer;

    public void setup() {
    }

    public void eval() {
      result.start = 0;
      result.scale = right.value;
      result.precision = left.precision;
      java.math.BigDecimal opResult =
          org.apache.drill.exec.util.DecimalUtility
              .getBigDecimalFromDrillBuf(left.buffer, left.start, left.end - left.start, left.scale)
                  .setScale(result.scale, java.math.BigDecimal.ROUND_DOWN);
      byte[] bytes = opResult.unscaledValue().toByteArray();
      int len = bytes.length;
      result.buffer = buffer.reallocIfNeeded(len);
      result.buffer.setBytes(0, bytes);
      result.end = len;
    }
  }

  @FunctionTemplate(name = "round",
                    scope = FunctionTemplate.FunctionScope.SIMPLE,
                    returnType = FunctionTemplate.ReturnType.DECIMAL_SET_SCALE,
                    nulls = NullHandling.NULL_IF_NULL)
  public static class ${type.name}RoundScaleFunction implements DrillSimpleFunc {
    @Param  ${type.name}Holder left;
    @Param  IntHolder right;
    @Output ${type.name}Holder result;
    @Inject DrillBuf buffer;

    public void setup() {
    }

    public void eval() {
      result.scale = right.value;
      result.precision = left.precision;
      result.start = 0;
      java.math.BigDecimal bd =
          org.apache.drill.exec.util.DecimalUtility
              .getBigDecimalFromDrillBuf(left.buffer, left.start, left.end - left.start, left.scale)
                  .setScale(result.scale, java.math.BigDecimal.ROUND_HALF_UP);
      byte[] bytes = bd.unscaledValue().toByteArray();
      int len = bytes.length;
      result.buffer = buffer.reallocIfNeeded(len);
      result.buffer.setBytes(0, bytes);
      result.end = len;
    }
  }

  <#-- Handle 2 x 2 combinations of nullable and non-nullable arguments. -->
  <#list ["Nullable${type.name}", "${type.name}"] as leftType >
  <#list ["Nullable${type.name}", "${type.name}"] as rightType >

  <#-- Comparison function for sorting and grouping relational operators
       (not for comparison expression operators (=, <, etc.)). -->
  @FunctionTemplate(name = FunctionGenerationHelper.COMPARE_TO_NULLS_HIGH,
                    scope = FunctionTemplate.FunctionScope.SIMPLE,
                    returnType = FunctionTemplate.ReturnType.DECIMAL_MAX_SCALE,
                    nulls = NullHandling.INTERNAL)
  public static class GCompare${leftType}Vs${rightType}NullHigh implements DrillSimpleFunc {

    @Param ${leftType}Holder left;
    @Param ${rightType}Holder right;
    @Output IntHolder out;

    public void setup() {}

    public void eval() {
      <@varCompareBlock leftType = leftType rightType = rightType absCompare="false" output = "out.value" nullCompare = true nullComparesHigh = true />
    }
  }



  <#-- Comparison function for sorting and grouping relational operators
        (not for comparison expression operators (=, <, etc.)). -->
  @FunctionTemplate(name = FunctionGenerationHelper.COMPARE_TO_NULLS_LOW,
                    scope = FunctionTemplate.FunctionScope.SIMPLE,
                    returnType = FunctionTemplate.ReturnType.DECIMAL_MAX_SCALE,
                    nulls = NullHandling.INTERNAL)
  public static class GCompare${leftType}Vs${rightType}NullLow implements DrillSimpleFunc {

    @Param ${leftType}Holder left;
    @Param ${rightType}Holder right;
    @Output IntHolder out;

    public void setup() {}

    public void eval() {
      <@varCompareBlock leftType = leftType rightType = rightType absCompare = "false" output = "out.value" nullCompare = true nullComparesHigh = false />
    }
  }

  </#list>
  </#list>

  <#-- Comparison function for comparison expression operator (=, &lt;, etc.),
         not for sorting and grouping relational operators.) -->
  @FunctionTemplate(name = FunctionGenerationHelper.LT,
                    scope = FunctionTemplate.FunctionScope.SIMPLE,
                    nulls = NullHandling.NULL_IF_NULL)
  public static class ${type.name}LessThan implements DrillSimpleFunc {

    @Param ${type.name}Holder left;
    @Param ${type.name}Holder right;
    @Output BitHolder out;
    public void setup() {}

    public void eval() {
      int cmp;
      <@varCompareBlock leftType = "leftType" rightType = "rightType" absCompare = "false" output = "cmp" nullCompare = false nullComparesHigh = false />
      out.value = cmp == -1 ? 1 : 0;
    }
  }

  <#-- Comparison function for comparison expression operator (=, &lt;, etc.),
         not for sorting and grouping relational operators.) -->
  @FunctionTemplate(name = FunctionGenerationHelper.LE,
                    scope = FunctionTemplate.FunctionScope.SIMPLE,
                    nulls = NullHandling.NULL_IF_NULL)
  public static class ${type.name}LessThanEq implements DrillSimpleFunc {

    @Param ${type.name}Holder left;
    @Param ${type.name}Holder right;
    @Output BitHolder out;

    public void setup() {}

    public void eval() {
      int cmp;
      <@varCompareBlock leftType = "leftType" rightType = "rightType" absCompare = "false" output = "cmp" nullCompare = false nullComparesHigh = false />
      out.value = cmp < 1 ? 1 : 0;
    }
  }

  <#-- Comparison function for comparison expression operator (=, &lt;, etc.),
         not for sorting and grouping relational operators.) -->
  @FunctionTemplate(name = FunctionGenerationHelper.GT,
                    scope = FunctionTemplate.FunctionScope.SIMPLE,
                    nulls = NullHandling.NULL_IF_NULL)
  public static class ${type.name}GreaterThan implements DrillSimpleFunc {

    @Param ${type.name}Holder left;
    @Param ${type.name}Holder right;
    @Output BitHolder out;

    public void setup() {}

    public void eval() {
      int cmp;
      <@varCompareBlock leftType = "leftType" rightType = "rightType" absCompare = "false" output = "cmp" nullCompare = false nullComparesHigh = false />
      out.value = cmp == 1 ? 1 : 0;
    }
  }

  <#-- Comparison function for comparison expression operator (=, &lt;, etc.),
         not for sorting and grouping relational operators.) -->
  @FunctionTemplate(name = FunctionGenerationHelper.GE,
                    scope = FunctionTemplate.FunctionScope.SIMPLE,
                    nulls = NullHandling.NULL_IF_NULL)
  public static class ${type.name}GreaterThanEq implements DrillSimpleFunc {

    @Param ${type.name}Holder left;
    @Param ${type.name}Holder right;
    @Output BitHolder out;

    public void setup() {}

    public void eval() {
      int cmp;
      <@varCompareBlock leftType = "leftType" rightType = "rightType" absCompare = "false" output = "cmp" nullCompare = false nullComparesHigh = false />
      out.value = cmp > -1 ? 1 : 0;
    }
  }

  <#-- Comparison function for comparison expression operator (=, &lt;, etc.),
         not for sorting and grouping relational operators.) -->
  @FunctionTemplate(name = FunctionGenerationHelper.EQ,
                    scope = FunctionTemplate.FunctionScope.SIMPLE,
                    nulls = NullHandling.NULL_IF_NULL)
  public static class ${type.name}Equal implements DrillSimpleFunc {

    @Param ${type.name}Holder left;
    @Param ${type.name}Holder right;
    @Output BitHolder out;

    public void setup() {}

    public void eval() {
      int cmp;
      <@varCompareBlock leftType = "leftType" rightType = "rightType" absCompare = "false" output = "cmp" nullCompare = false nullComparesHigh = false />
      out.value = cmp == 0 ? 1 : 0;
    }
  }

  <#-- Comparison function for comparison expression operator (=, &lt;, etc.),
         not for sorting and grouping relational operators.) -->
  @FunctionTemplate(name = FunctionGenerationHelper.NE,
                    scope = FunctionTemplate.FunctionScope.SIMPLE,
                    nulls = NullHandling.NULL_IF_NULL)
  public static class ${type.name}NotEqual implements DrillSimpleFunc {

    @Param ${type.name}Holder left;
    @Param ${type.name}Holder right;
    @Output BitHolder out;

    public void setup() {}

    public void eval() {
      int cmp;
      <@varCompareBlock leftType = "leftType" rightType = "rightType" absCompare = "false" output = "cmp" nullCompare = false nullComparesHigh = false />
      out.value = cmp != 0 ? 1 : 0;
    }
  }
}
</#if>

</#list>