aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/com/healthmarketscience/jackcess/impl/CalculatedColumnUtil.java
blob: 0ded048239375d2317724ad0ea2a007fdaebc1ef (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
/*
Copyright (c) 2014 James Ahlborn

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 com.healthmarketscience.jackcess.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import com.healthmarketscience.jackcess.InvalidValueException;


/**
 * Utility code for dealing with calculated columns.
 * <p>
 * These are the currently possible calculated types: FLOAT, DOUBLE, INT,
 * LONG, BIG_INT, GUID, SHORT_DATE_TIME, MONEY, BOOLEAN, NUMERIC, TEXT, MEMO.
 *
 * @author James Ahlborn
 */
class CalculatedColumnUtil
{
  // offset to the int which specifies the length of the actual data
  private static final int CALC_DATA_LEN_OFFSET = 16;
  // offset to the actual data
  private static final int CALC_DATA_OFFSET = CALC_DATA_LEN_OFFSET + 4;
  // total amount of extra bytes added for calculated values
  static final int CALC_EXTRA_DATA_LEN = 23;
  // ms access seems to define all fixed-len calc fields as this length
  static final short CALC_FIXED_FIELD_LEN = 39;

  // fully encode calculated BOOLEAN "true" value
  private static final byte[] CALC_BOOL_TRUE = wrapCalculatedValue(
      new byte[]{(byte)0xFF});
  // fully encode calculated BOOLEAN "false" value
  private static final byte[] CALC_BOOL_FALSE = wrapCalculatedValue(
      new byte[]{0});

  /**
   * Creates the appropriate ColumnImpl class for a calculated column and
   * reads a column definition in from a buffer
   *
   * @param args column construction info
   * @usage _advanced_method_
   */
  static ColumnImpl create(ColumnImpl.InitArgs args) throws IOException
  {
    switch(args.type) {
    case BOOLEAN:
      return new CalcBooleanColImpl(args);
    case TEXT:
      return new CalcTextColImpl(args);
    case MEMO:
      return new CalcMemoColImpl(args);
    default:
      // fall through
    }

    if(args.type.getHasScalePrecision()) {
      return new CalcNumericColImpl(args);
    }

    return new CalcColImpl(args);
  }

  /**
   * Grabs the real data bytes from a calculated value.
   */
  private static byte[] unwrapCalculatedValue(byte[] data) {
    if(data.length < CALC_DATA_OFFSET) {
      return data;
    }

    ByteBuffer buffer = PageChannel.wrap(data);
    buffer.position(CALC_DATA_LEN_OFFSET);
    int dataLen = buffer.getInt();
    byte[] newData = new byte[Math.min(buffer.remaining(), dataLen)];
    buffer.get(newData);
    return newData;
  }

  /**
   * Wraps the given data bytes with the extra calculated value data and
   * returns a new ByteBuffer containing the final data.
   */
  private static ByteBuffer wrapCalculatedValue(ByteBuffer buffer) {
    ByteBuffer newBuf = prepareWrappedCalcValue(
        buffer.remaining(), buffer.order());
    newBuf.put(buffer);
    newBuf.rewind();
    return newBuf;
  }

  /**
   * Wraps the given data bytes with the extra calculated value data and
   * returns a new byte[] containing the final data.
   */
  private static byte[] wrapCalculatedValue(byte[] data) {
    int dataLen = data.length;
    data = ByteUtil.copyOf(data, 0, dataLen + CALC_EXTRA_DATA_LEN,
                           CALC_DATA_OFFSET);
    PageChannel.wrap(data).putInt(CALC_DATA_LEN_OFFSET, dataLen);
    return data;
  }

  /**
   * Prepares a calculated value buffer for data of the given length.
   */
  private static ByteBuffer prepareWrappedCalcValue(int dataLen, ByteOrder order)
  {
    ByteBuffer buffer = ByteBuffer.allocate(
        dataLen + CALC_EXTRA_DATA_LEN).order(order);
    buffer.putInt(CALC_DATA_LEN_OFFSET, dataLen);
    buffer.position(CALC_DATA_OFFSET);
    return buffer;
  }


  /**
   * General calculated column implementation.
   */
  private static class CalcColImpl extends ColumnImpl
  {
    private CalcColEvalContext _calcCol;

    CalcColImpl(InitArgs args) throws IOException {
      super(args);
    }

    @Override
    protected CalcColEvalContext getCalculationContext() {
      return _calcCol;
    }

    @Override
    protected void setCalcColEvalContext(CalcColEvalContext calcCol) {
      _calcCol = calcCol;
    }

    @Override
    public Object read(byte[] data, ByteOrder order) throws IOException {
      data = unwrapCalculatedValue(data);
      if((data.length == 0) && !getType().isVariableLength()) {
        // apparently "null" values can be written as actual data
        return null;
      }
      return super.read(data, order);
    }

    @Override
    protected ByteBuffer writeRealData(Object obj, int remainingRowLength,
                                       ByteOrder order)
      throws IOException
    {
      // we should only be working with fixed length types
      ByteBuffer buffer = writeFixedLengthField(
          obj, prepareWrappedCalcValue(getType().getFixedSize(), order));
      buffer.rewind();
      return buffer;
    }
  }

  /**
   * Calculated BOOLEAN column implementation.
   */
  private static class CalcBooleanColImpl extends ColumnImpl
  {
    private CalcColEvalContext _calcCol;

    CalcBooleanColImpl(InitArgs args) throws IOException {
      super(args);
    }

    @Override
    protected CalcColEvalContext getCalculationContext() {
      return _calcCol;
    }

    @Override
    protected void setCalcColEvalContext(CalcColEvalContext calcCol) {
      _calcCol = calcCol;
    }

    @Override
    public boolean storeInNullMask() {
      // calculated booleans are _not_ stored in null mask
      return false;
    }

    @Override
    public Object read(byte[] data, ByteOrder order) throws IOException {
      data = unwrapCalculatedValue(data);
      if(data.length == 0) {
        return Boolean.FALSE;
      }
      return ((data[0] != 0) ? Boolean.TRUE : Boolean.FALSE);
    }

    @Override
    protected ByteBuffer writeRealData(Object obj, int remainingRowLength,
                                       ByteOrder order)
      throws IOException
    {
      return ByteBuffer.wrap(
          toBooleanValue(obj) ? CALC_BOOL_TRUE : CALC_BOOL_FALSE).order(order);
    }
  }

  /**
   * Calculated TEXT column implementation.
   */
  private static class CalcTextColImpl extends TextColumnImpl
  {
    private CalcColEvalContext _calcCol;

    CalcTextColImpl(InitArgs args) throws IOException {
      super(args);
    }

    @Override
    protected CalcColEvalContext getCalculationContext() {
      return _calcCol;
    }

    @Override
    protected void setCalcColEvalContext(CalcColEvalContext calcCol) {
      _calcCol = calcCol;
    }

    @Override
    protected int calcLengthInUnits() {
      // the byte "length" includes the calculated field overhead.  remove
      // that to get the _actual_ data length (in units)
      return getType().toUnitSize(getLength() - CALC_EXTRA_DATA_LEN,
                                  getFormat());
    }

    @Override
    public Object read(byte[] data, ByteOrder order) throws IOException {
      return decodeTextValue(unwrapCalculatedValue(data));
    }

    @Override
    protected ByteBuffer writeRealData(Object obj, int remainingRowLength,
                                       ByteOrder order)
      throws IOException
    {
      return wrapCalculatedValue(super.writeRealData(
                                     obj, remainingRowLength, order));
    }
  }

  /**
   * Calculated MEMO column implementation.
   */
  private static class CalcMemoColImpl extends MemoColumnImpl
  {
    private CalcColEvalContext _calcCol;

    CalcMemoColImpl(InitArgs args) throws IOException {
      super(args);
    }

    @Override
    protected CalcColEvalContext getCalculationContext() {
      return _calcCol;
    }

    @Override
    protected void setCalcColEvalContext(CalcColEvalContext calcCol) {
      _calcCol = calcCol;
    }

    @Override
    protected int calcMaxLengthInUnits() {
      // the byte "length" includes the calculated field overhead.  remove
      // that to get the _actual_ data length (in units)
      return getType().toUnitSize(getType().getMaxSize() - CALC_EXTRA_DATA_LEN,
                                  getFormat());
    }

    @Override
    protected byte[] readLongValue(byte[] lvalDefinition)
      throws IOException
    {
      return unwrapCalculatedValue(super.readLongValue(lvalDefinition));
    }

    @Override
    protected ByteBuffer writeLongValue(byte[] value, int remainingRowLength)
      throws IOException
    {
      return super.writeLongValue(
          wrapCalculatedValue(value), remainingRowLength);
    }
  }

  /**
   * Calculated NUMERIC column implementation.
   */
  private static class CalcNumericColImpl extends NumericColumnImpl
  {
    private CalcColEvalContext _calcCol;

    CalcNumericColImpl(InitArgs args) throws IOException {
      super(args);
    }

    @Override
    protected CalcColEvalContext getCalculationContext() {
      return _calcCol;
    }

    @Override
    protected void setCalcColEvalContext(CalcColEvalContext calcCol) {
      _calcCol = calcCol;
    }

    @Override
    public byte getPrecision() {
      return (byte)getType().getMaxPrecision();
    }

    @Override
    public Object read(byte[] data, ByteOrder order) throws IOException {
      data = unwrapCalculatedValue(data);
      if(data.length == 0) {
        // apparently "null" values can be written as actual data
        return null;
      }
      return readCalcNumericValue(ByteBuffer.wrap(data).order(order));
    }

    @Override
    protected ByteBuffer writeRealData(Object obj, int remainingRowLength,
                                       ByteOrder order)
      throws IOException
    {
      int totalDataLen = Math.min(CALC_EXTRA_DATA_LEN + 16 + 4, getLength());
      // data length must be multiple of 4
      int dataLen = toMul4(totalDataLen - CALC_EXTRA_DATA_LEN);
      ByteBuffer buffer = prepareWrappedCalcValue(dataLen, order);

      writeCalcNumericValue(buffer, obj, dataLen);

      buffer.rewind();
      return buffer;
    }

    private static BigDecimal readCalcNumericValue(ByteBuffer buffer)
    {
      short totalLen = buffer.getShort();
      // numeric bytes need to be a multiple of 4 and we currently handle at
      // most 16 bytes
      int numByteLen = ((totalLen > 0) ? totalLen : buffer.remaining()) - 2;
      numByteLen = Math.min(toMul4(numByteLen), 16);

      byte scale = buffer.get();
      boolean negate = (buffer.get() != 0);
      byte[] tmpArr = ByteUtil.getBytes(buffer, numByteLen);

      if(buffer.order() != ByteOrder.BIG_ENDIAN) {
        fixNumericByteOrder(tmpArr);
      }

      return toBigDecimal(tmpArr, negate, scale);
    }

    private void writeCalcNumericValue(ByteBuffer buffer, Object value,
                                       int dataLen)
      throws IOException
    {
      Object inValue = value;
      try {
        BigDecimal decVal = toBigDecimal(value);
        inValue = decVal;

        int signum = decVal.signum();
        if(signum < 0) {
          decVal = decVal.negate();
        }

        int maxScale = getType().getMaxScale();
        if(decVal.scale() > maxScale) {
          // adjust scale according to max (will cause the an
          // ArithmeticException if number has too many decimal places)
          decVal = decVal.setScale(maxScale);
        }
        int scale = decVal.scale();

        // check precision
        if(decVal.precision() > getType().getMaxPrecision()) {
          throw new InvalidValueException(withErrorContext(
              "Numeric value is too big for specified precision "
              + getType().getMaxPrecision() + ": " + decVal));
        }

        // convert to unscaled BigInteger, big-endian bytes
        byte[] intValBytes = toUnscaledByteArray(decVal, dataLen - 4);

        if(buffer.order() != ByteOrder.BIG_ENDIAN) {
          fixNumericByteOrder(intValBytes);
        }

        buffer.putShort((short)(dataLen - 2));
        buffer.put((byte)scale);
        // write sign byte
        buffer.put((signum < 0) ? NUMERIC_NEGATIVE_BYTE : 0);
        buffer.put(intValBytes);

      } catch(ArithmeticException e) {
        throw new IOException(
            withErrorContext("Numeric value '" + inValue + "' out of range"), e);
      }
    }

    private static void fixNumericByteOrder(byte[] bytes) {

      // this is a little weird.  it looks like they decided to truncate
      // leading 0 bytes and _then_ swap endian, which ends up kind of odd.
      int pos = 0;
      if((bytes.length % 8) != 0) {
        // leading 4 bytes are swapped
        ByteUtil.swap4Bytes(bytes, 0);
        pos += 4;
      }

      // then fix endianness of each 8 byte segment
      for(; pos < bytes.length; pos+=8) {
        ByteUtil.swap8Bytes(bytes, pos);
      }
    }

    private static int toMul4(int val) {
      return ((val / 4) * 4);
    }
  }

}