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 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. import com.healthmarketscience.jackcess.InvalidValueException;
  19. /**
  20. * Utility code for dealing with calculated columns.
  21. * <p>
  22. * These are the currently possible calculated types: FLOAT, DOUBLE, INT,
  23. * LONG, BIG_INT, GUID, SHORT_DATE_TIME, MONEY, BOOLEAN, NUMERIC, TEXT, MEMO.
  24. *
  25. * @author James Ahlborn
  26. */
  27. class CalculatedColumnUtil
  28. {
  29. // offset to the int which specifies the length of the actual data
  30. private static final int CALC_DATA_LEN_OFFSET = 16;
  31. // offset to the actual data
  32. private static final int CALC_DATA_OFFSET = CALC_DATA_LEN_OFFSET + 4;
  33. // total amount of extra bytes added for calculated values
  34. static final int CALC_EXTRA_DATA_LEN = 23;
  35. // ms access seems to define all fixed-len calc fields as this length
  36. static final short CALC_FIXED_FIELD_LEN = 39;
  37. // fully encode calculated BOOLEAN "true" value
  38. private static final byte[] CALC_BOOL_TRUE = wrapCalculatedValue(
  39. new byte[]{(byte)0xFF});
  40. // fully encode calculated BOOLEAN "false" value
  41. private static final byte[] CALC_BOOL_FALSE = wrapCalculatedValue(
  42. new byte[]{0});
  43. /**
  44. * Creates the appropriate ColumnImpl class for a calculated column and
  45. * reads a column definition in from a buffer
  46. *
  47. * @param args column construction info
  48. * @usage _advanced_method_
  49. */
  50. static ColumnImpl create(ColumnImpl.InitArgs args) throws IOException
  51. {
  52. switch(args.type) {
  53. case BOOLEAN:
  54. return new CalcBooleanColImpl(args);
  55. case TEXT:
  56. return new CalcTextColImpl(args);
  57. case MEMO:
  58. return new CalcMemoColImpl(args);
  59. default:
  60. // fall through
  61. }
  62. if(args.type.getHasScalePrecision()) {
  63. return new CalcNumericColImpl(args);
  64. }
  65. return new CalcColImpl(args);
  66. }
  67. /**
  68. * Grabs the real data bytes from a calculated value.
  69. */
  70. private static byte[] unwrapCalculatedValue(byte[] data) {
  71. if(data.length < CALC_DATA_OFFSET) {
  72. return data;
  73. }
  74. ByteBuffer buffer = PageChannel.wrap(data);
  75. buffer.position(CALC_DATA_LEN_OFFSET);
  76. int dataLen = buffer.getInt();
  77. byte[] newData = new byte[Math.min(buffer.remaining(), dataLen)];
  78. buffer.get(newData);
  79. return newData;
  80. }
  81. /**
  82. * Wraps the given data bytes with the extra calculated value data and
  83. * returns a new ByteBuffer containing the final data.
  84. */
  85. private static ByteBuffer wrapCalculatedValue(ByteBuffer buffer) {
  86. ByteBuffer newBuf = prepareWrappedCalcValue(
  87. buffer.remaining(), buffer.order());
  88. newBuf.put(buffer);
  89. newBuf.rewind();
  90. return newBuf;
  91. }
  92. /**
  93. * Wraps the given data bytes with the extra calculated value data and
  94. * returns a new byte[] containing the final data.
  95. */
  96. private static byte[] wrapCalculatedValue(byte[] data) {
  97. int dataLen = data.length;
  98. data = ByteUtil.copyOf(data, 0, dataLen + CALC_EXTRA_DATA_LEN,
  99. CALC_DATA_OFFSET);
  100. PageChannel.wrap(data).putInt(CALC_DATA_LEN_OFFSET, dataLen);
  101. return data;
  102. }
  103. /**
  104. * Prepares a calculated value buffer for data of the given length.
  105. */
  106. private static ByteBuffer prepareWrappedCalcValue(int dataLen, ByteOrder order)
  107. {
  108. ByteBuffer buffer = ByteBuffer.allocate(
  109. dataLen + CALC_EXTRA_DATA_LEN).order(order);
  110. buffer.putInt(CALC_DATA_LEN_OFFSET, dataLen);
  111. buffer.position(CALC_DATA_OFFSET);
  112. return buffer;
  113. }
  114. /**
  115. * General calculated column implementation.
  116. */
  117. private static class CalcColImpl extends ColumnImpl
  118. {
  119. private CalcColEvalContext _calcCol;
  120. CalcColImpl(InitArgs args) throws IOException {
  121. super(args);
  122. }
  123. @Override
  124. protected CalcColEvalContext getCalculationContext() {
  125. return _calcCol;
  126. }
  127. @Override
  128. protected void setCalcColEvalContext(CalcColEvalContext calcCol) {
  129. _calcCol = calcCol;
  130. }
  131. @Override
  132. public Object read(byte[] data, ByteOrder order) throws IOException {
  133. data = unwrapCalculatedValue(data);
  134. if((data.length == 0) && !getType().isVariableLength()) {
  135. // apparently "null" values can be written as actual data
  136. return null;
  137. }
  138. return super.read(data, order);
  139. }
  140. @Override
  141. protected ByteBuffer writeRealData(Object obj, int remainingRowLength,
  142. ByteOrder order)
  143. throws IOException
  144. {
  145. // we should only be working with fixed length types
  146. ByteBuffer buffer = writeFixedLengthField(
  147. obj, prepareWrappedCalcValue(getType().getFixedSize(), order));
  148. buffer.rewind();
  149. return buffer;
  150. }
  151. }
  152. /**
  153. * Calculated BOOLEAN column implementation.
  154. */
  155. private static class CalcBooleanColImpl extends ColumnImpl
  156. {
  157. private CalcColEvalContext _calcCol;
  158. CalcBooleanColImpl(InitArgs args) throws IOException {
  159. super(args);
  160. }
  161. @Override
  162. protected CalcColEvalContext getCalculationContext() {
  163. return _calcCol;
  164. }
  165. @Override
  166. protected void setCalcColEvalContext(CalcColEvalContext calcCol) {
  167. _calcCol = calcCol;
  168. }
  169. @Override
  170. public boolean storeInNullMask() {
  171. // calculated booleans are _not_ stored in null mask
  172. return false;
  173. }
  174. @Override
  175. public Object read(byte[] data, ByteOrder order) throws IOException {
  176. data = unwrapCalculatedValue(data);
  177. if(data.length == 0) {
  178. return Boolean.FALSE;
  179. }
  180. return ((data[0] != 0) ? Boolean.TRUE : Boolean.FALSE);
  181. }
  182. @Override
  183. protected ByteBuffer writeRealData(Object obj, int remainingRowLength,
  184. ByteOrder order)
  185. throws IOException
  186. {
  187. return ByteBuffer.wrap(
  188. toBooleanValue(obj) ? CALC_BOOL_TRUE : CALC_BOOL_FALSE).order(order);
  189. }
  190. }
  191. /**
  192. * Calculated TEXT column implementation.
  193. */
  194. private static class CalcTextColImpl extends TextColumnImpl
  195. {
  196. private CalcColEvalContext _calcCol;
  197. CalcTextColImpl(InitArgs args) throws IOException {
  198. super(args);
  199. }
  200. @Override
  201. protected CalcColEvalContext getCalculationContext() {
  202. return _calcCol;
  203. }
  204. @Override
  205. protected void setCalcColEvalContext(CalcColEvalContext calcCol) {
  206. _calcCol = calcCol;
  207. }
  208. @Override
  209. protected int calcLengthInUnits() {
  210. // the byte "length" includes the calculated field overhead. remove
  211. // that to get the _actual_ data length (in units)
  212. return getType().toUnitSize(getLength() - CALC_EXTRA_DATA_LEN,
  213. getFormat());
  214. }
  215. @Override
  216. public Object read(byte[] data, ByteOrder order) throws IOException {
  217. return decodeTextValue(unwrapCalculatedValue(data));
  218. }
  219. @Override
  220. protected ByteBuffer writeRealData(Object obj, int remainingRowLength,
  221. ByteOrder order)
  222. throws IOException
  223. {
  224. return wrapCalculatedValue(super.writeRealData(
  225. obj, remainingRowLength, order));
  226. }
  227. }
  228. /**
  229. * Calculated MEMO column implementation.
  230. */
  231. private static class CalcMemoColImpl extends MemoColumnImpl
  232. {
  233. private CalcColEvalContext _calcCol;
  234. CalcMemoColImpl(InitArgs args) throws IOException {
  235. super(args);
  236. }
  237. @Override
  238. protected CalcColEvalContext getCalculationContext() {
  239. return _calcCol;
  240. }
  241. @Override
  242. protected void setCalcColEvalContext(CalcColEvalContext calcCol) {
  243. _calcCol = calcCol;
  244. }
  245. @Override
  246. protected int calcMaxLengthInUnits() {
  247. // the byte "length" includes the calculated field overhead. remove
  248. // that to get the _actual_ data length (in units)
  249. return getType().toUnitSize(getType().getMaxSize() - CALC_EXTRA_DATA_LEN,
  250. getFormat());
  251. }
  252. @Override
  253. protected byte[] readLongValue(byte[] lvalDefinition)
  254. throws IOException
  255. {
  256. return unwrapCalculatedValue(super.readLongValue(lvalDefinition));
  257. }
  258. @Override
  259. protected ByteBuffer writeLongValue(byte[] value, int remainingRowLength)
  260. throws IOException
  261. {
  262. return super.writeLongValue(
  263. wrapCalculatedValue(value), remainingRowLength);
  264. }
  265. }
  266. /**
  267. * Calculated NUMERIC column implementation.
  268. */
  269. private static class CalcNumericColImpl extends NumericColumnImpl
  270. {
  271. private CalcColEvalContext _calcCol;
  272. CalcNumericColImpl(InitArgs args) throws IOException {
  273. super(args);
  274. }
  275. @Override
  276. protected CalcColEvalContext getCalculationContext() {
  277. return _calcCol;
  278. }
  279. @Override
  280. protected void setCalcColEvalContext(CalcColEvalContext calcCol) {
  281. _calcCol = calcCol;
  282. }
  283. @Override
  284. public byte getPrecision() {
  285. return (byte)getType().getMaxPrecision();
  286. }
  287. @Override
  288. public Object read(byte[] data, ByteOrder order) throws IOException {
  289. data = unwrapCalculatedValue(data);
  290. if(data.length == 0) {
  291. // apparently "null" values can be written as actual data
  292. return null;
  293. }
  294. return readCalcNumericValue(ByteBuffer.wrap(data).order(order));
  295. }
  296. @Override
  297. protected ByteBuffer writeRealData(Object obj, int remainingRowLength,
  298. ByteOrder order)
  299. throws IOException
  300. {
  301. int totalDataLen = Math.min(CALC_EXTRA_DATA_LEN + 16 + 4, getLength());
  302. // data length must be multiple of 4
  303. int dataLen = toMul4(totalDataLen - CALC_EXTRA_DATA_LEN);
  304. ByteBuffer buffer = prepareWrappedCalcValue(dataLen, order);
  305. writeCalcNumericValue(buffer, obj, dataLen);
  306. buffer.rewind();
  307. return buffer;
  308. }
  309. private static BigDecimal readCalcNumericValue(ByteBuffer buffer)
  310. {
  311. short totalLen = buffer.getShort();
  312. // numeric bytes need to be a multiple of 4 and we currently handle at
  313. // most 16 bytes
  314. int numByteLen = ((totalLen > 0) ? totalLen : buffer.remaining()) - 2;
  315. numByteLen = Math.min(toMul4(numByteLen), 16);
  316. byte scale = buffer.get();
  317. boolean negate = (buffer.get() != 0);
  318. byte[] tmpArr = ByteUtil.getBytes(buffer, numByteLen);
  319. if(buffer.order() != ByteOrder.BIG_ENDIAN) {
  320. fixNumericByteOrder(tmpArr);
  321. }
  322. return toBigDecimal(tmpArr, negate, scale);
  323. }
  324. private void writeCalcNumericValue(ByteBuffer buffer, Object value,
  325. int dataLen)
  326. throws IOException
  327. {
  328. Object inValue = value;
  329. try {
  330. BigDecimal decVal = toBigDecimal(value);
  331. inValue = decVal;
  332. int signum = decVal.signum();
  333. if(signum < 0) {
  334. decVal = decVal.negate();
  335. }
  336. int maxScale = getType().getMaxScale();
  337. if(decVal.scale() > maxScale) {
  338. // adjust scale according to max (will cause the an
  339. // ArithmeticException if number has too many decimal places)
  340. decVal = decVal.setScale(maxScale);
  341. }
  342. int scale = decVal.scale();
  343. // check precision
  344. if(decVal.precision() > getType().getMaxPrecision()) {
  345. throw new InvalidValueException(withErrorContext(
  346. "Numeric value is too big for specified precision "
  347. + getType().getMaxPrecision() + ": " + decVal));
  348. }
  349. // convert to unscaled BigInteger, big-endian bytes
  350. byte[] intValBytes = toUnscaledByteArray(decVal, dataLen - 4);
  351. if(buffer.order() != ByteOrder.BIG_ENDIAN) {
  352. fixNumericByteOrder(intValBytes);
  353. }
  354. buffer.putShort((short)(dataLen - 2));
  355. buffer.put((byte)scale);
  356. // write sign byte
  357. buffer.put((signum < 0) ? NUMERIC_NEGATIVE_BYTE : 0);
  358. buffer.put(intValBytes);
  359. } catch(ArithmeticException e) {
  360. throw new IOException(
  361. withErrorContext("Numeric value '" + inValue + "' out of range"), e);
  362. }
  363. }
  364. private static void fixNumericByteOrder(byte[] bytes) {
  365. // this is a little weird. it looks like they decided to truncate
  366. // leading 0 bytes and _then_ swap endian, which ends up kind of odd.
  367. int pos = 0;
  368. if((bytes.length % 8) != 0) {
  369. // leading 4 bytes are swapped
  370. ByteUtil.swap4Bytes(bytes, 0);
  371. pos += 4;
  372. }
  373. // then fix endianness of each 8 byte segment
  374. for(; pos < bytes.length; pos+=8) {
  375. ByteUtil.swap8Bytes(bytes, pos);
  376. }
  377. }
  378. private static int toMul4(int val) {
  379. return ((val / 4) * 4);
  380. }
  381. }
  382. }