You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CalculatedColumnUtil.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. /*
  2. Copyright (c) 2014 James Ahlborn
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package com.healthmarketscience.jackcess.impl;
  14. import java.io.IOException;
  15. import java.math.BigDecimal;
  16. import java.nio.ByteBuffer;
  17. import java.nio.ByteOrder;
  18. /**
  19. * Utility code for dealing with calculated columns.
  20. * <p/>
  21. * These are the currently possible calculated types: FLOAT, DOUBLE, INT,
  22. * LONG, GUID, SHORT_DATE_TIME, MONEY, BOOLEAN, NUMERIC, TEXT, MEMO.
  23. *
  24. * @author James Ahlborn
  25. */
  26. class CalculatedColumnUtil
  27. {
  28. // offset to the int which specifies the length of the actual data
  29. private static final int CALC_DATA_LEN_OFFSET = 16;
  30. // offset to the actual data
  31. private static final int CALC_DATA_OFFSET = CALC_DATA_LEN_OFFSET + 4;
  32. // total amount of extra bytes added for calculated values
  33. static final int CALC_EXTRA_DATA_LEN = 23;
  34. // ms access seems to define all fixed-len calc fields as this length
  35. static final short CALC_FIXED_FIELD_LEN = 39;
  36. // fully encode calculated BOOLEAN "true" value
  37. private static final byte[] CALC_BOOL_TRUE = wrapCalculatedValue(
  38. new byte[]{(byte)0xFF});
  39. // fully encode calculated BOOLEAN "false" value
  40. private static final byte[] CALC_BOOL_FALSE = wrapCalculatedValue(
  41. new byte[]{0});
  42. /**
  43. * Creates the appropriate ColumnImpl class for a calculated column and
  44. * reads a column definition in from a buffer
  45. *
  46. * @param args column construction info
  47. * @usage _advanced_method_
  48. */
  49. static ColumnImpl create(ColumnImpl.InitArgs args) throws IOException
  50. {
  51. switch(args.type) {
  52. case BOOLEAN:
  53. return new CalcBooleanColImpl(args);
  54. case TEXT:
  55. return new CalcTextColImpl(args);
  56. case MEMO:
  57. return new CalcMemoColImpl(args);
  58. default:
  59. // fall through
  60. }
  61. if(args.type.getHasScalePrecision()) {
  62. return new CalcNumericColImpl(args);
  63. }
  64. return new CalcColImpl(args);
  65. }
  66. /**
  67. * Grabs the real data bytes from a calculated value.
  68. */
  69. private static byte[] unwrapCalculatedValue(byte[] data) {
  70. if(data.length < CALC_DATA_OFFSET) {
  71. return data;
  72. }
  73. ByteBuffer buffer = PageChannel.wrap(data);
  74. buffer.position(CALC_DATA_LEN_OFFSET);
  75. int dataLen = buffer.getInt();
  76. byte[] newData = new byte[Math.min(buffer.remaining(), dataLen)];
  77. buffer.get(newData);
  78. return newData;
  79. }
  80. /**
  81. * Wraps the given data bytes with the extra calculated value data and
  82. * returns a new ByteBuffer containing the final data.
  83. */
  84. private static ByteBuffer wrapCalculatedValue(ByteBuffer buffer) {
  85. ByteBuffer newBuf = prepareWrappedCalcValue(
  86. buffer.remaining(), buffer.order());
  87. newBuf.put(buffer);
  88. newBuf.rewind();
  89. return newBuf;
  90. }
  91. /**
  92. * Wraps the given data bytes with the extra calculated value data and
  93. * returns a new byte[] containing the final data.
  94. */
  95. private static byte[] wrapCalculatedValue(byte[] data) {
  96. int dataLen = data.length;
  97. data = ByteUtil.copyOf(data, 0, dataLen + CALC_EXTRA_DATA_LEN,
  98. CALC_DATA_OFFSET);
  99. PageChannel.wrap(data).putInt(CALC_DATA_LEN_OFFSET, dataLen);
  100. return data;
  101. }
  102. /**
  103. * Prepares a calculated value buffer for data of the given length.
  104. */
  105. private static ByteBuffer prepareWrappedCalcValue(int dataLen, ByteOrder order)
  106. {
  107. ByteBuffer buffer = ByteBuffer.allocate(
  108. dataLen + CALC_EXTRA_DATA_LEN).order(order);
  109. buffer.putInt(CALC_DATA_LEN_OFFSET, dataLen);
  110. buffer.position(CALC_DATA_OFFSET);
  111. return buffer;
  112. }
  113. /**
  114. * General calculated column implementation.
  115. */
  116. private static class CalcColImpl extends ColumnImpl
  117. {
  118. CalcColImpl(InitArgs args) throws IOException {
  119. super(args);
  120. }
  121. @Override
  122. public Object read(byte[] data, ByteOrder order) throws IOException {
  123. return super.read(unwrapCalculatedValue(data), order);
  124. }
  125. @Override
  126. protected ByteBuffer writeRealData(Object obj, int remainingRowLength,
  127. ByteOrder order)
  128. throws IOException
  129. {
  130. // we should only be working with fixed length types
  131. ByteBuffer buffer = writeFixedLengthField(
  132. obj, prepareWrappedCalcValue(getType().getFixedSize(), order));
  133. buffer.rewind();
  134. return buffer;
  135. }
  136. }
  137. /**
  138. * Calculated BOOLEAN column implementation.
  139. */
  140. private static class CalcBooleanColImpl extends ColumnImpl
  141. {
  142. CalcBooleanColImpl(InitArgs args) throws IOException {
  143. super(args);
  144. }
  145. @Override
  146. public boolean storeInNullMask() {
  147. // calculated booleans are _not_ stored in null mask
  148. return false;
  149. }
  150. @Override
  151. public Object read(byte[] data, ByteOrder order) throws IOException {
  152. data = unwrapCalculatedValue(data);
  153. return ((data[0] != 0) ? Boolean.TRUE : Boolean.FALSE);
  154. }
  155. @Override
  156. protected ByteBuffer writeRealData(Object obj, int remainingRowLength,
  157. ByteOrder order)
  158. throws IOException
  159. {
  160. return ByteBuffer.wrap(
  161. toBooleanValue(obj) ? CALC_BOOL_TRUE : CALC_BOOL_FALSE).order(order);
  162. }
  163. }
  164. /**
  165. * Calculated TEXT column implementation.
  166. */
  167. private static class CalcTextColImpl extends TextColumnImpl
  168. {
  169. CalcTextColImpl(InitArgs args) throws IOException {
  170. super(args);
  171. }
  172. @Override
  173. public short getLengthInUnits() {
  174. // the byte "length" includes the calculated field overhead. remove
  175. // that to get the _actual_ data length (in units)
  176. return (short)getType().toUnitSize(getLength() - CALC_EXTRA_DATA_LEN);
  177. }
  178. @Override
  179. public Object read(byte[] data, ByteOrder order) throws IOException {
  180. return decodeTextValue(unwrapCalculatedValue(data));
  181. }
  182. @Override
  183. protected ByteBuffer writeRealData(Object obj, int remainingRowLength,
  184. ByteOrder order)
  185. throws IOException
  186. {
  187. return wrapCalculatedValue(super.writeRealData(
  188. obj, remainingRowLength, order));
  189. }
  190. }
  191. /**
  192. * Calculated MEMO column implementation.
  193. */
  194. private static class CalcMemoColImpl extends MemoColumnImpl
  195. {
  196. CalcMemoColImpl(InitArgs args) throws IOException {
  197. super(args);
  198. }
  199. @Override
  200. protected int getMaxLengthInUnits() {
  201. // the byte "length" includes the calculated field overhead. remove
  202. // that to get the _actual_ data length (in units)
  203. return getType().toUnitSize(getType().getMaxSize() - CALC_EXTRA_DATA_LEN);
  204. }
  205. @Override
  206. protected byte[] readLongValue(byte[] lvalDefinition)
  207. throws IOException
  208. {
  209. return unwrapCalculatedValue(super.readLongValue(lvalDefinition));
  210. }
  211. @Override
  212. protected ByteBuffer writeLongValue(byte[] value, int remainingRowLength)
  213. throws IOException
  214. {
  215. return super.writeLongValue(
  216. wrapCalculatedValue(value), remainingRowLength);
  217. }
  218. }
  219. /**
  220. * Calculated NUMERIC column implementation.
  221. */
  222. private static class CalcNumericColImpl extends NumericColumnImpl
  223. {
  224. CalcNumericColImpl(InitArgs args) throws IOException {
  225. super(args);
  226. }
  227. @Override
  228. public byte getPrecision() {
  229. return (byte)getType().getMaxPrecision();
  230. }
  231. @Override
  232. public Object read(byte[] data, ByteOrder order) throws IOException {
  233. data = unwrapCalculatedValue(data);
  234. return readCalcNumericValue(ByteBuffer.wrap(data).order(order));
  235. }
  236. @Override
  237. protected ByteBuffer writeRealData(Object obj, int remainingRowLength,
  238. ByteOrder order)
  239. throws IOException
  240. {
  241. int totalDataLen = Math.min(CALC_EXTRA_DATA_LEN + 16 + 4, getLength());
  242. // data length must be multiple of 4
  243. int dataLen = toMul4(totalDataLen - CALC_EXTRA_DATA_LEN);
  244. ByteBuffer buffer = prepareWrappedCalcValue(dataLen, order);
  245. writeCalcNumericValue(buffer, obj, dataLen);
  246. buffer.rewind();
  247. return buffer;
  248. }
  249. private static BigDecimal readCalcNumericValue(ByteBuffer buffer)
  250. {
  251. short totalLen = buffer.getShort();
  252. // numeric bytes need to be a multiple of 4 and we currently handle at
  253. // most 16 bytes
  254. int numByteLen = ((totalLen > 0) ? totalLen : buffer.remaining()) - 2;
  255. numByteLen = Math.min(toMul4(numByteLen), 16);
  256. byte scale = buffer.get();
  257. boolean negate = (buffer.get() != 0);
  258. byte[] tmpArr = ByteUtil.getBytes(buffer, numByteLen);
  259. if(buffer.order() != ByteOrder.BIG_ENDIAN) {
  260. fixNumericByteOrder(tmpArr);
  261. }
  262. return toBigDecimal(tmpArr, negate, scale);
  263. }
  264. private void writeCalcNumericValue(ByteBuffer buffer, Object value,
  265. int dataLen)
  266. throws IOException
  267. {
  268. Object inValue = value;
  269. try {
  270. BigDecimal decVal = toBigDecimal(value);
  271. inValue = decVal;
  272. int signum = decVal.signum();
  273. if(signum < 0) {
  274. decVal = decVal.negate();
  275. }
  276. int maxScale = getType().getMaxScale();
  277. if(decVal.scale() > maxScale) {
  278. // adjust scale according to max (will cause the an
  279. // ArithmeticException if number has too many decimal places)
  280. decVal = decVal.setScale(maxScale);
  281. }
  282. int scale = decVal.scale();
  283. // check precision
  284. if(decVal.precision() > getType().getMaxPrecision()) {
  285. throw new IOException(withErrorContext(
  286. "Numeric value is too big for specified precision "
  287. + getType().getMaxPrecision() + ": " + decVal));
  288. }
  289. // convert to unscaled BigInteger, big-endian bytes
  290. byte[] intValBytes = toUnscaledByteArray(decVal, dataLen - 4);
  291. if(buffer.order() != ByteOrder.BIG_ENDIAN) {
  292. fixNumericByteOrder(intValBytes);
  293. }
  294. buffer.putShort((short)(dataLen - 2));
  295. buffer.put((byte)scale);
  296. // write sign byte
  297. buffer.put((signum < 0) ? NUMERIC_NEGATIVE_BYTE : 0);
  298. buffer.put(intValBytes);
  299. } catch(ArithmeticException e) {
  300. throw (IOException)
  301. new IOException(withErrorContext(
  302. "Numeric value '" + inValue + "' out of range"))
  303. .initCause(e);
  304. }
  305. }
  306. private static void fixNumericByteOrder(byte[] bytes) {
  307. // this is a little weird. it looks like they decided to truncate
  308. // leading 0 bytes and _then_ swap endian, which ends up kind of odd.
  309. int pos = 0;
  310. if((bytes.length % 8) != 0) {
  311. // leading 4 bytes are swapped
  312. ByteUtil.swap4Bytes(bytes, 0);
  313. pos += 4;
  314. }
  315. // then fix endianness of each 8 byte segment
  316. for(; pos < bytes.length; pos+=8) {
  317. ByteUtil.swap8Bytes(bytes, pos);
  318. }
  319. }
  320. private static int toMul4(int val) {
  321. return ((val / 4) * 4);
  322. }
  323. }
  324. }