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

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