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.

LongValueColumnImpl.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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.nio.ByteBuffer;
  16. import java.nio.ByteOrder;
  17. import java.util.Collection;
  18. import com.healthmarketscience.jackcess.InvalidValueException;
  19. /**
  20. * ColumnImpl subclass which is used for long value data types.
  21. *
  22. * @author James Ahlborn
  23. * @usage _advanced_class_
  24. */
  25. class LongValueColumnImpl extends ColumnImpl
  26. {
  27. /**
  28. * Long value (LVAL) type that indicates that the value is stored on the
  29. * same page
  30. */
  31. private static final byte LONG_VALUE_TYPE_THIS_PAGE = (byte) 0x80;
  32. /**
  33. * Long value (LVAL) type that indicates that the value is stored on another
  34. * page
  35. */
  36. private static final byte LONG_VALUE_TYPE_OTHER_PAGE = (byte) 0x40;
  37. /**
  38. * Long value (LVAL) type that indicates that the value is stored on
  39. * multiple other pages
  40. */
  41. private static final byte LONG_VALUE_TYPE_OTHER_PAGES = (byte) 0x00;
  42. /**
  43. * Mask to apply the long length in order to get the flag bits (only the
  44. * first 2 bits are type flags).
  45. */
  46. private static final int LONG_VALUE_TYPE_MASK = 0xC0000000;
  47. /** Holds additional info for writing long values */
  48. private LongValueBufferHolder _lvalBufferH;
  49. private int _maxLenInUnits = INVALID_LENGTH;
  50. LongValueColumnImpl(InitArgs args) throws IOException
  51. {
  52. super(args);
  53. }
  54. @Override
  55. public int getOwnedPageCount() {
  56. return ((_lvalBufferH == null) ? 0 : _lvalBufferH.getOwnedPageCount());
  57. }
  58. @Override
  59. void setUsageMaps(UsageMap ownedPages, UsageMap freeSpacePages) {
  60. _lvalBufferH = new UmapLongValueBufferHolder(ownedPages, freeSpacePages);
  61. }
  62. @Override
  63. void collectUsageMapPages(Collection<Integer> pages) {
  64. _lvalBufferH.collectUsageMapPages(pages);
  65. }
  66. @Override
  67. void postTableLoadInit() throws IOException {
  68. if(_lvalBufferH == null) {
  69. _lvalBufferH = new LegacyLongValueBufferHolder();
  70. }
  71. super.postTableLoadInit();
  72. }
  73. protected final int getMaxLengthInUnits() {
  74. if(_maxLenInUnits == INVALID_LENGTH) {
  75. _maxLenInUnits = calcMaxLengthInUnits();
  76. }
  77. return _maxLenInUnits;
  78. }
  79. protected int calcMaxLengthInUnits() {
  80. return getType().toUnitSize(getType().getMaxSize(), getFormat());
  81. }
  82. @Override
  83. public Object read(byte[] data, ByteOrder order) throws IOException {
  84. switch(getType()) {
  85. case OLE:
  86. if (data.length > 0) {
  87. return readLongValue(data);
  88. }
  89. return null;
  90. case MEMO:
  91. if (data.length > 0) {
  92. return readLongStringValue(data);
  93. }
  94. return null;
  95. default:
  96. throw new RuntimeException(withErrorContext(
  97. "unexpected var length, long value type: " + getType()));
  98. }
  99. }
  100. @Override
  101. protected ByteBuffer writeRealData(Object obj, int remainingRowLength,
  102. ByteOrder order)
  103. throws IOException
  104. {
  105. switch(getType()) {
  106. case OLE:
  107. // should already be "encoded"
  108. break;
  109. case MEMO:
  110. obj = encodeTextValue(obj, 0, getMaxLengthInUnits(), false).array();
  111. break;
  112. default:
  113. throw new RuntimeException(withErrorContext(
  114. "unexpected var length, long value type: " + getType()));
  115. }
  116. // create long value buffer
  117. return writeLongValue(toByteArray(obj), remainingRowLength);
  118. }
  119. /**
  120. * @param lvalDefinition Column value that points to an LVAL record
  121. * @return The LVAL data
  122. */
  123. protected byte[] readLongValue(byte[] lvalDefinition)
  124. throws IOException
  125. {
  126. ByteBuffer def = PageChannel.wrap(lvalDefinition);
  127. int lengthWithFlags = def.getInt();
  128. int length = lengthWithFlags & (~LONG_VALUE_TYPE_MASK);
  129. byte[] rtn = new byte[length];
  130. byte type = (byte)((lengthWithFlags & LONG_VALUE_TYPE_MASK) >>> 24);
  131. if(type == LONG_VALUE_TYPE_THIS_PAGE) {
  132. // inline long value
  133. def.getInt(); //Skip over lval_dp
  134. def.getInt(); //Skip over unknown
  135. int rowLen = def.remaining();
  136. if(rowLen < length) {
  137. // warn the caller, but return whatever we can
  138. LOG.warn(withErrorContext(
  139. "Value may be truncated: expected length " +
  140. length + " found " + rowLen));
  141. rtn = new byte[rowLen];
  142. }
  143. def.get(rtn);
  144. } else {
  145. // long value on other page(s)
  146. if (lvalDefinition.length != getFormat().SIZE_LONG_VALUE_DEF) {
  147. throw new IOException(withErrorContext(
  148. "Expected " + getFormat().SIZE_LONG_VALUE_DEF +
  149. " bytes in long value definition, but found " +
  150. lvalDefinition.length));
  151. }
  152. int rowNum = ByteUtil.getUnsignedByte(def);
  153. int pageNum = ByteUtil.get3ByteInt(def, def.position());
  154. ByteBuffer lvalPage = getPageChannel().createPageBuffer();
  155. switch (type) {
  156. case LONG_VALUE_TYPE_OTHER_PAGE:
  157. {
  158. getPageChannel().readPage(lvalPage, pageNum);
  159. short rowStart = TableImpl.findRowStart(lvalPage, rowNum, getFormat());
  160. short rowEnd = TableImpl.findRowEnd(lvalPage, rowNum, getFormat());
  161. int rowLen = rowEnd - rowStart;
  162. if(rowLen < length) {
  163. // warn the caller, but return whatever we can
  164. LOG.warn(withErrorContext(
  165. "Value may be truncated: expected length " +
  166. length + " found " + rowLen));
  167. rtn = new byte[rowLen];
  168. }
  169. lvalPage.position(rowStart);
  170. lvalPage.get(rtn);
  171. }
  172. break;
  173. case LONG_VALUE_TYPE_OTHER_PAGES:
  174. ByteBuffer rtnBuf = ByteBuffer.wrap(rtn);
  175. int remainingLen = length;
  176. while(remainingLen > 0) {
  177. lvalPage.clear();
  178. getPageChannel().readPage(lvalPage, pageNum);
  179. short rowStart = TableImpl.findRowStart(lvalPage, rowNum, getFormat());
  180. short rowEnd = TableImpl.findRowEnd(lvalPage, rowNum, getFormat());
  181. // read next page information
  182. lvalPage.position(rowStart);
  183. rowNum = ByteUtil.getUnsignedByte(lvalPage);
  184. pageNum = ByteUtil.get3ByteInt(lvalPage);
  185. // update rowEnd and remainingLen based on chunkLength
  186. int chunkLength = (rowEnd - rowStart) - 4;
  187. if(chunkLength > remainingLen) {
  188. rowEnd = (short)(rowEnd - (chunkLength - remainingLen));
  189. chunkLength = remainingLen;
  190. }
  191. remainingLen -= chunkLength;
  192. lvalPage.limit(rowEnd);
  193. rtnBuf.put(lvalPage);
  194. }
  195. break;
  196. default:
  197. throw new IOException(withErrorContext(
  198. "Unrecognized long value type: " + type));
  199. }
  200. }
  201. return rtn;
  202. }
  203. /**
  204. * @param lvalDefinition Column value that points to an LVAL record
  205. * @return The LVAL data
  206. */
  207. private String readLongStringValue(byte[] lvalDefinition)
  208. throws IOException
  209. {
  210. byte[] binData = readLongValue(lvalDefinition);
  211. if(binData == null) {
  212. return null;
  213. }
  214. if(binData.length == 0) {
  215. return "";
  216. }
  217. return decodeTextValue(binData);
  218. }
  219. /**
  220. * Write an LVAL column into a ByteBuffer inline if it fits, otherwise in
  221. * other data page(s).
  222. * @param value Value of the LVAL column
  223. * @return A buffer containing the LVAL definition and (possibly) the column
  224. * value (unless written to other pages)
  225. * @usage _advanced_method_
  226. */
  227. protected ByteBuffer writeLongValue(byte[] value, int remainingRowLength)
  228. throws IOException
  229. {
  230. if(value.length > getType().getMaxSize()) {
  231. throw new InvalidValueException(withErrorContext(
  232. "value too big for column, max " +
  233. getType().getMaxSize() + ", got " + value.length));
  234. }
  235. // determine which type to write
  236. byte type = 0;
  237. int lvalDefLen = getFormat().SIZE_LONG_VALUE_DEF;
  238. if(((getFormat().SIZE_LONG_VALUE_DEF + value.length) <= remainingRowLength)
  239. && (value.length <= getFormat().MAX_INLINE_LONG_VALUE_SIZE)) {
  240. type = LONG_VALUE_TYPE_THIS_PAGE;
  241. lvalDefLen += value.length;
  242. } else if(value.length <= getFormat().MAX_LONG_VALUE_ROW_SIZE) {
  243. type = LONG_VALUE_TYPE_OTHER_PAGE;
  244. } else {
  245. type = LONG_VALUE_TYPE_OTHER_PAGES;
  246. }
  247. ByteBuffer def = PageChannel.createBuffer(lvalDefLen);
  248. // take length and apply type to first byte
  249. int lengthWithFlags = value.length | (type << 24);
  250. def.putInt(lengthWithFlags);
  251. if(type == LONG_VALUE_TYPE_THIS_PAGE) {
  252. // write long value inline
  253. def.putInt(0);
  254. def.putInt(0); //Unknown
  255. def.put(value);
  256. } else {
  257. ByteBuffer lvalPage = null;
  258. int firstLvalPageNum = PageChannel.INVALID_PAGE_NUMBER;
  259. byte firstLvalRow = 0;
  260. // write other page(s)
  261. switch(type) {
  262. case LONG_VALUE_TYPE_OTHER_PAGE:
  263. lvalPage = _lvalBufferH.getLongValuePage(value.length);
  264. firstLvalPageNum = _lvalBufferH.getPageNumber();
  265. firstLvalRow = (byte)TableImpl.addDataPageRow(lvalPage, value.length,
  266. getFormat(), 0);
  267. lvalPage.put(value);
  268. getPageChannel().writePage(lvalPage, firstLvalPageNum);
  269. break;
  270. case LONG_VALUE_TYPE_OTHER_PAGES:
  271. ByteBuffer buffer = ByteBuffer.wrap(value);
  272. int remainingLen = buffer.remaining();
  273. buffer.limit(0);
  274. lvalPage = _lvalBufferH.getLongValuePage(remainingLen);
  275. firstLvalPageNum = _lvalBufferH.getPageNumber();
  276. firstLvalRow = (byte)TableImpl.getRowsOnDataPage(lvalPage, getFormat());
  277. int lvalPageNum = firstLvalPageNum;
  278. ByteBuffer nextLvalPage = null;
  279. int nextLvalPageNum = 0;
  280. int nextLvalRowNum = 0;
  281. while(remainingLen > 0) {
  282. lvalPage.clear();
  283. // figure out how much we will put in this page (we need 4 bytes for
  284. // the next page pointer)
  285. int chunkLength = Math.min(getFormat().MAX_LONG_VALUE_ROW_SIZE - 4,
  286. remainingLen);
  287. // figure out if we will need another page, and if so, allocate it
  288. if(chunkLength < remainingLen) {
  289. // force a new page to be allocated for the chunk after this
  290. _lvalBufferH.clear();
  291. nextLvalPage = _lvalBufferH.getLongValuePage(
  292. (remainingLen - chunkLength) + 4);
  293. nextLvalPageNum = _lvalBufferH.getPageNumber();
  294. nextLvalRowNum = TableImpl.getRowsOnDataPage(nextLvalPage,
  295. getFormat());
  296. } else {
  297. nextLvalPage = null;
  298. nextLvalPageNum = 0;
  299. nextLvalRowNum = 0;
  300. }
  301. // add row to this page
  302. TableImpl.addDataPageRow(lvalPage, chunkLength + 4, getFormat(), 0);
  303. // write next page info
  304. lvalPage.put((byte)nextLvalRowNum); // row number
  305. ByteUtil.put3ByteInt(lvalPage, nextLvalPageNum); // page number
  306. // write this page's chunk of data
  307. buffer.limit(buffer.limit() + chunkLength);
  308. lvalPage.put(buffer);
  309. remainingLen -= chunkLength;
  310. // write new page to database
  311. getPageChannel().writePage(lvalPage, lvalPageNum);
  312. // move to next page
  313. lvalPage = nextLvalPage;
  314. lvalPageNum = nextLvalPageNum;
  315. }
  316. break;
  317. default:
  318. throw new IOException(withErrorContext(
  319. "Unrecognized long value type: " + type));
  320. }
  321. // update def
  322. def.put(firstLvalRow);
  323. ByteUtil.put3ByteInt(def, firstLvalPageNum);
  324. def.putInt(0); //Unknown
  325. }
  326. def.flip();
  327. return def;
  328. }
  329. /**
  330. * Writes the header info for a long value page.
  331. */
  332. private void writeLongValueHeader(ByteBuffer lvalPage)
  333. {
  334. lvalPage.put(PageTypes.DATA); //Page type
  335. lvalPage.put((byte) 1); //Unknown
  336. lvalPage.putShort((short)getFormat().DATA_PAGE_INITIAL_FREE_SPACE); //Free space
  337. lvalPage.put((byte) 'L');
  338. lvalPage.put((byte) 'V');
  339. lvalPage.put((byte) 'A');
  340. lvalPage.put((byte) 'L');
  341. lvalPage.putInt(0); //unknown
  342. lvalPage.putShort((short)0); // num rows in page
  343. }
  344. /**
  345. * Manages secondary page buffers for long value writing.
  346. */
  347. private abstract class LongValueBufferHolder
  348. {
  349. /**
  350. * Returns a long value data page with space for data of the given length.
  351. */
  352. public ByteBuffer getLongValuePage(int dataLength) throws IOException {
  353. TempPageHolder lvalBufferH = getBufferHolder();
  354. dataLength = Math.min(dataLength, getFormat().MAX_LONG_VALUE_ROW_SIZE);
  355. ByteBuffer lvalPage = null;
  356. if(lvalBufferH.getPageNumber() != PageChannel.INVALID_PAGE_NUMBER) {
  357. lvalPage = lvalBufferH.getPage(getPageChannel());
  358. if(TableImpl.rowFitsOnDataPage(dataLength, lvalPage, getFormat())) {
  359. // the current page has space
  360. return lvalPage;
  361. }
  362. }
  363. // need new page
  364. return findNewPage(dataLength);
  365. }
  366. protected ByteBuffer findNewPage(int dataLength) throws IOException {
  367. ByteBuffer lvalPage = getBufferHolder().setNewPage(getPageChannel());
  368. writeLongValueHeader(lvalPage);
  369. return lvalPage;
  370. }
  371. public int getOwnedPageCount() {
  372. return 0;
  373. }
  374. /**
  375. * Returns the page number of the current long value data page.
  376. */
  377. public int getPageNumber() {
  378. return getBufferHolder().getPageNumber();
  379. }
  380. /**
  381. * Discards the current the current long value data page.
  382. */
  383. public void clear() throws IOException {
  384. getBufferHolder().clear();
  385. }
  386. public void collectUsageMapPages(Collection<Integer> pages) {
  387. // base does nothing
  388. }
  389. protected abstract TempPageHolder getBufferHolder();
  390. }
  391. /**
  392. * Manages a common, shared extra page for long values. This is legacy
  393. * behavior from before it was understood that there were additional usage
  394. * maps for each columns.
  395. */
  396. private final class LegacyLongValueBufferHolder extends LongValueBufferHolder
  397. {
  398. @Override
  399. protected TempPageHolder getBufferHolder() {
  400. return getTable().getLongValueBuffer();
  401. }
  402. }
  403. /**
  404. * Manages the column usage maps for long values.
  405. */
  406. private final class UmapLongValueBufferHolder extends LongValueBufferHolder
  407. {
  408. /** Usage map of pages that this column owns */
  409. private final UsageMap _ownedPages;
  410. /** Usage map of pages that this column owns with free space on them */
  411. private final UsageMap _freeSpacePages;
  412. /** page buffer used to write "long value" data */
  413. private final TempPageHolder _longValueBufferH =
  414. TempPageHolder.newHolder(TempBufferHolder.Type.SOFT);
  415. private UmapLongValueBufferHolder(UsageMap ownedPages,
  416. UsageMap freeSpacePages) {
  417. _ownedPages = ownedPages;
  418. _freeSpacePages = freeSpacePages;
  419. }
  420. @Override
  421. protected TempPageHolder getBufferHolder() {
  422. return _longValueBufferH;
  423. }
  424. @Override
  425. public int getOwnedPageCount() {
  426. return _ownedPages.getPageCount();
  427. }
  428. @Override
  429. protected ByteBuffer findNewPage(int dataLength) throws IOException {
  430. // grab last owned page and check for free space.
  431. ByteBuffer newPage = TableImpl.findFreeRowSpace(
  432. _ownedPages, _freeSpacePages, _longValueBufferH);
  433. if(newPage != null) {
  434. if(TableImpl.rowFitsOnDataPage(dataLength, newPage, getFormat())) {
  435. return newPage;
  436. }
  437. // discard this page and allocate a new one
  438. clear();
  439. }
  440. // nothing found on current pages, need new page
  441. newPage = super.findNewPage(dataLength);
  442. int pageNumber = getPageNumber();
  443. _ownedPages.addPageNumber(pageNumber);
  444. _freeSpacePages.addPageNumber(pageNumber);
  445. return newPage;
  446. }
  447. @Override
  448. public void clear() throws IOException {
  449. int pageNumber = getPageNumber();
  450. if(pageNumber != PageChannel.INVALID_PAGE_NUMBER) {
  451. _freeSpacePages.removePageNumber(pageNumber);
  452. }
  453. super.clear();
  454. }
  455. @Override
  456. public void collectUsageMapPages(Collection<Integer> pages) {
  457. pages.add(_ownedPages.getTablePageNumber());
  458. pages.add(_freeSpacePages.getTablePageNumber());
  459. }
  460. }
  461. }